Debian Codegraph @

src/com/google/javascript/jscomp/deps/SortedDependencies.java

raw symbols SCIP
1 /*
2 * Copyright 2010 The Closure Compiler Authors.
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 */
16
17 package com.google.javascript.jscomp.deps;
18
19 import com.google.common.base.Joiner;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.ArrayListMultimap;
22 import com.google.common.collect.HashMultimap;
23 import com.google.common.collect.HashMultiset;
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.collect.Lists;
26 import com.google.common.collect.Maps;
27 import com.google.common.collect.Multimap;
28 import com.google.common.collect.Multimaps;
29 import com.google.common.collect.Multiset;
30 import com.google.common.collect.Sets;
31
32 import java.util.ArrayDeque;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.Comparator;
36 import java.util.Deque;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.PriorityQueue;
40 import java.util.Set;
41
42 /**
43 * A sorted list of inputs with dependency information. Uses a stable
44 * topological sort to make sure that an input always comes after its
45 * dependencies.
46 *
47 * Also exposes other information about the inputs, like which inputs
48 * do not provide symbols.
49 *
50 * @author [email protected] (Nick Santos)
51 */
52 public class SortedDependencies<INPUT extends DependencyInfo> {
53
54 private final List<INPUT> inputs;
55
56 // A topologically sorted list of the inputs.
57 private final List<INPUT> sortedList;
58
59 // A list of all the inputs that do not have provides.
60 private final List<INPUT> noProvides;
61
62 private final Map<String, INPUT> provideMap = Maps.newHashMap();
63
64 public SortedDependencies(List<INPUT> inputs)
65 throws CircularDependencyException {
66 this.inputs = Lists.newArrayList(inputs);
67 noProvides = Lists.newArrayList();
68
69 // Collect all symbols provided in these files.
70 for (INPUT input : inputs) {
71 Collection<String> currentProvides = input.getProvides();
72 if (currentProvides.isEmpty()) {
73 noProvides.add(input);
74 }
75
76 for (String provide : currentProvides) {
77 provideMap.put(provide, input);
78 }
79 }
80
81 // Get the direct dependencies.
82 final Multimap<INPUT, INPUT> deps = HashMultimap.create();
83 for (INPUT input : inputs) {
84 for (String req : input.getRequires()) {
85 INPUT dep = provideMap.get(req);
86 if (dep != null && dep != input) {
87 deps.put(input, dep);
88 }
89 }
90 }
91
92 // Sort the inputs by sucking in 0-in-degree nodes until we're done.
93 sortedList = topologicalStableSort(inputs, deps);
94
95 // The dependency graph of inputs has a cycle iff sortedList is a proper
96 // subset of inputs. Also, it has a cycle iff the subgraph
97 // (inputs - sortedList) has a cycle. It's fairly easy to prove this
98 // by the lemma that a graph has a cycle iff it has a subgraph where
99 // no nodes have out-degree 0. I'll leave the proof of this as an exercise
100 // to the reader.
101 if (sortedList.size() < inputs.size()) {
102 List<INPUT> subGraph = Lists.newArrayList(inputs);
103 subGraph.removeAll(sortedList);
104
105 throw new CircularDependencyException(
106 cycleToString(findCycle(subGraph, deps)));
107 }
108 }
109
110 /**
111 * Return the input that gives us the given symbol.
112 * @throws MissingProvideException An exception if there is no
113 * input for this symbol.
114 */
115 public INPUT getInputProviding(String symbol)
116 throws MissingProvideException {
117 if (provideMap.containsKey(symbol)) {
118 return provideMap.get(symbol);
119 }
120 throw new MissingProvideException(symbol);
121 }
122
123 /**
124 * Return the input that gives us the given symbol, or null.
125 */
126 public INPUT maybeGetInputProviding(String symbol) {
127 return provideMap.get(symbol);
128 }
129
130 /**
131 * Returns the first circular dependency found. Expressed as a list of
132 * items in reverse dependency order (the second element depends on the
133 * first, etc.).
134 */
135 private List<INPUT> findCycle(
136 List<INPUT> subGraph, Multimap<INPUT, INPUT> deps) {
137 return findCycle(subGraph.get(0), Sets.<INPUT>newHashSet(subGraph),
138 deps, Sets.<INPUT>newHashSet());
139 }
140
141 private List<INPUT> findCycle(
142 INPUT current, Set<INPUT> subGraph, Multimap<INPUT, INPUT> deps,
143 Set<INPUT> covered) {
144 if (covered.add(current)) {
145 List<INPUT> cycle = findCycle(
146 findRequireInSubGraphOrFail(current, subGraph),
147 subGraph, deps, covered);
148
149 // Don't add the input to the list if the cycle has closed already.
150 if (cycle.get(0) != cycle.get(cycle.size() - 1)) {
151 cycle.add(current);
152 }
153
154 return cycle;
155 } else {
156 // Explicitly use the add() method, to prevent a generics constructor
157 // warning that is dumb. The condition it's protecting is
158 // obscure, and I think people have proposed that it be removed.
159 List<INPUT> cycle = Lists.<INPUT>newArrayList();
160 cycle.add(current);
161 return cycle;
162 }
163 }
164
165 private INPUT findRequireInSubGraphOrFail(INPUT input, Set<INPUT> subGraph) {
166 for (String symbol : input.getRequires()) {
167 INPUT candidate = provideMap.get(symbol);
168 if (subGraph.contains(candidate)) {
169 return candidate;
170 }
171 }
172 throw new IllegalStateException("no require found in subgraph");
173 }
174
175 /**
176 * @param cycle A cycle in reverse-dependency order.
177 */
178 private String cycleToString(List<INPUT> cycle) {
179 List<String> symbols = Lists.newArrayList();
180 for (int i = cycle.size() - 1; i >= 0; i--) {
181 symbols.add(cycle.get(i).getProvides().iterator().next());
182 }
183 symbols.add(symbols.get(0));
184 return Joiner.on(" -> ").join(symbols);
185 }
186
187 public List<INPUT> getSortedList() {
188 return Collections.<INPUT>unmodifiableList(sortedList);
189 }
190
191 /**
192 * Gets all the dependencies of the given roots. The inputs must be returned
193 * in a stable order. In other words, if A comes before B, and A does not
194 * transitively depend on B, then A must also come before B in the returned
195 * list.
196 */
197 public List<INPUT> getSortedDependenciesOf(List<INPUT> roots) {
198 return getDependenciesOf(roots, true);
199 }
200
201 /**
202 * Gets all the dependencies of the given roots. The inputs must be returned
203 * in a stable order. In other words, if A comes before B, and A does not
204 * transitively depend on B, then A must also come before B in the returned
205 * list.
206 *
207 * @param sorted If true, get them in topologically sorted order. If false,
208 * get them in the original order they were passed to the compiler.
209 */
210 public List<INPUT> getDependenciesOf(List<INPUT> roots, boolean sorted) {
211 Preconditions.checkArgument(inputs.containsAll(roots));
212 Set<INPUT> included = Sets.newHashSet();
213 Deque<INPUT> worklist = new ArrayDeque<INPUT>(roots);
214 while (!worklist.isEmpty()) {
215 INPUT current = worklist.pop();
216 if (included.add(current)) {
217 for (String req : current.getRequires()) {
218 INPUT dep = provideMap.get(req);
219 if (dep != null) {
220 worklist.add(dep);
221 }
222 }
223 }
224 }
225
226 ImmutableList.Builder<INPUT> builder = ImmutableList.builder();
227 for (INPUT current : (sorted ? sortedList : inputs)) {
228 if (included.contains(current)) {
229 builder.add(current);
230 }
231 }
232 return builder.build();
233 }
234
235 public List<INPUT> getInputsWithoutProvides() {
236 return Collections.<INPUT>unmodifiableList(noProvides);
237 }
238
239 private static <T> List<T> topologicalStableSort(
240 List<T> items, Multimap<T, T> deps) {
241 if (items.size() == 0) {
242 // Priority queue blows up if we give it a size of 0. Since we need
243 // to special case this either way, just bail out.
244 return Lists.newArrayList();
245 }
246
247 final Map<T, Integer> originalIndex = Maps.newHashMap();
248 for (int i = 0; i < items.size(); i++) {
249 originalIndex.put(items.get(i), i);
250 }
251
252 PriorityQueue<T> inDegreeZero = new PriorityQueue<T>(items.size(),
253 new Comparator<T>() {
254 @Override
255 public int compare(T a, T b) {
256 return originalIndex.get(a).intValue() -
257 originalIndex.get(b).intValue();
258 }
259 });
260 List<T> result = Lists.newArrayList();
261
262 Multiset<T> inDegree = HashMultiset.create();
263 Multimap<T, T> reverseDeps = ArrayListMultimap.create();
264 Multimaps.invertFrom(deps, reverseDeps);
265
266 // First, add all the inputs with in-degree 0.
267 for (T item : items) {
268 Collection<T> itemDeps = deps.get(item);
269 inDegree.add(item, itemDeps.size());
270 if (itemDeps.isEmpty()) {
271 inDegreeZero.add(item);
272 }
273 }
274
275 // Then, iterate to a fixed point over the reverse dependency graph.
276 while (!inDegreeZero.isEmpty()) {
277 T item = inDegreeZero.remove();
278 result.add(item);
279 for (T inWaiting : reverseDeps.get(item)) {
280 inDegree.remove(inWaiting, 1);
281 if (inDegree.count(inWaiting) == 0) {
282 inDegreeZero.add(inWaiting);
283 }
284 }
285 }
286
287 return result;
288 }
289
290 public static class CircularDependencyException extends Exception {
291 CircularDependencyException(String message) {
292 super(message);
293 }
294 }
295
296 public static class MissingProvideException extends Exception {
297 MissingProvideException(String provide) {
298 super(provide);
299 }
300 }
301 }