1/*
2 * Copyright (C) 2015 Google, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package dagger.internal.codegen;
17
18import com.google.common.collect.ImmutableList;
19import java.util.ArrayDeque;
20import java.util.Deque;
21
22/**
23 * Utility code that looks for bindings matching a key in all subcomponents in a binding graph so
24 * that a user is advised that a binding exists elsewhere when it is not found in the current
25 * subgraph. If a binding matching a key exists in a sub- or sibling component, that is often what
26 * the user actually wants to use.
27 */
28class MissingBindingSuggestions {
29  /**
30   * Searches the entire binding graph from the top-level graph for a binding matching
31   * {@code key}.
32   */
33  static ImmutableList<String> forKey(BindingGraph topLevelGraph, BindingKey key) {
34    ImmutableList.Builder<String> resolutions = new ImmutableList.Builder<>();
35    Deque<BindingGraph> graphsToTry = new ArrayDeque<>();
36
37    graphsToTry.add(topLevelGraph);
38    do {
39      BindingGraph graph = graphsToTry.removeLast();
40      ResolvedBindings bindings = graph.resolvedBindings().get(key);
41      if ((bindings == null) || bindings.bindings().isEmpty()) {
42        graphsToTry.addAll(graph.subgraphs().values());
43      } else {
44        resolutions.add("A binding with matching key exists in component: "
45            + graph.componentDescriptor().componentDefinitionType().getQualifiedName());
46      }
47    } while (!graphsToTry.isEmpty());
48
49    return resolutions.build();
50  }
51
52  private MissingBindingSuggestions() {}
53}
54