Debian Codegraph @

src/com/google/javascript/jscomp/JSModuleGraph.java

raw symbols SCIP
1 /*
2 * Copyright 2008 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;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Throwables;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.Iterables;
23 import com.google.common.collect.LinkedHashMultimap;
24 import com.google.common.collect.LinkedListMultimap;
25 import com.google.common.collect.ListMultimap;
26 import com.google.common.collect.Lists;
27 import com.google.common.collect.Maps;
28 import com.google.common.collect.Multimap;
29 import com.google.common.collect.Sets;
30 import com.google.javascript.jscomp.deps.SortedDependencies;
31 import com.google.javascript.jscomp.deps.SortedDependencies.CircularDependencyException;
32 import com.google.javascript.jscomp.deps.SortedDependencies.MissingProvideException;
33 import com.google.javascript.jscomp.graph.LinkedDirectedGraph;
34
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Comparator;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Set;
42 import java.util.TreeSet;
43
44 import org.json.JSONArray;
45 import org.json.JSONException;
46 import org.json.JSONObject;
47
48 /**
49 * A {@link JSModule} dependency graph that assigns a depth to each module and
50 * can answer depth-related queries about them. For the purposes of this class,
51 * a module's depth is defined as the number of hops in the longest path from
52 * the module to a module with no dependencies.
53 *
54 */
55 public class JSModuleGraph {
56
57 private List<JSModule> modules;
58
59 /**
60 * Lists of modules at each depth. <code>modulesByDepth.get(3)</code> is a
61 * list of the modules at depth 3, for example.
62 */
63 private List<List<JSModule>> modulesByDepth;
64
65 /**
66 * dependencyMap is a cache of dependencies that makes the dependsOn
67 * function faster. Each map entry associates a starting
68 * JSModule with the set of JSModules that are transitively dependent on the
69 * starting module.
70 *
71 * If the cache returns null, then the entry hasn't been filled in for that
72 * module.
73 *
74 * dependencyMap should be filled from leaf to root so that
75 * getTransitiveDepsDeepestFirst can use its results directly.
76 */
77 private Map<JSModule, Set<JSModule>> dependencyMap = Maps.newHashMap();
78
79 /**
80 * Creates a module graph from a list of modules in dependency order.
81 */
82 public JSModuleGraph(JSModule[] modulesInDepOrder) {
83 this(ImmutableList.copyOf(modulesInDepOrder));
84 }
85
86 /**
87 * Creates a module graph from a list of modules in dependency order.
88 */
89 public JSModuleGraph(List<JSModule> modulesInDepOrder) {
90 Preconditions.checkState(
91 modulesInDepOrder.size() == Sets.newHashSet(modulesInDepOrder).size(),
92 "Found duplicate modules");
93 modules = ImmutableList.copyOf(modulesInDepOrder);
94 modulesByDepth = Lists.newArrayList();
95
96 for (JSModule module : modulesInDepOrder) {
97 int depth = 0;
98 for (JSModule dep : module.getDependencies()) {
99 int depDepth = dep.getDepth();
100 if (depDepth < 0) {
101 throw new ModuleDependenceException(String.format(
102 "Modules not in dependency order: %s preceded %s",
103 module.getName(), dep.getName()),
104 module, dep);
105 }
106 depth = Math.max(depth, depDepth + 1);
107 }
108
109 module.setDepth(depth);
110 if (depth == modulesByDepth.size()) {
111 modulesByDepth.add(new ArrayList<JSModule>());
112 }
113 modulesByDepth.get(depth).add(module);
114 }
115 }
116
117 /**
118 * Gets an iterable over all modules in dependency order.
119 */
120 Iterable<JSModule> getAllModules() {
121 return modules;
122 }
123
124 /**
125 * Gets all modules indexed by name.
126 */
127 Map<String, JSModule> getModulesByName() {
128 Map<String, JSModule> result = Maps.newHashMap();
129 for (JSModule m : modules) {
130 result.put(m.getName(), m);
131 }
132 return result;
133 }
134
135 /**
136 * Gets the total number of modules.
137 */
138 int getModuleCount() {
139 return modules.size();
140 }
141
142 /**
143 * Gets the root module.
144 */
145 JSModule getRootModule() {
146 return Iterables.getOnlyElement(modulesByDepth.get(0));
147 }
148
149 /**
150 * Returns a JSON representation of the JSModuleGraph. Specifically a
151 * JSONArray of "Modules" where each module has a
152 * - "name"
153 * - "dependencies" (list of module names)
154 * - "transitive-dependencies" (list of module names, deepest first)
155 * - "inputs" (list of file names)
156 * @return List of module JSONObjects.
157 */
158 JSONArray toJson() {
159 JSONArray modules = new JSONArray();
160 for (JSModule module : getAllModules()) {
161 JSONObject node = new JSONObject();
162 try {
163 node.put("name", module.getName());
164 JSONArray deps = new JSONArray();
165 node.put("dependencies", deps);
166 for (JSModule m : module.getDependencies()) {
167 deps.put(m.getName());
168 }
169 JSONArray transitiveDeps = new JSONArray();
170 node.put("transitive-dependencies", transitiveDeps);
171 for (JSModule m : getTransitiveDepsDeepestFirst(module)) {
172 transitiveDeps.put(m.getName());
173 }
174 JSONArray inputs = new JSONArray();
175 node.put("inputs", inputs);
176 for (CompilerInput input : module.getInputs()) {
177 inputs.put(input.getSourceFile().getOriginalPath());
178 }
179 modules.put(node);
180 } catch (JSONException e) {
181 Throwables.propagate(e);
182 }
183 }
184 return modules;
185 }
186
187 /**
188 * Determines whether this module depends on a given module. Note that a
189 * module never depends on itself, as that dependency would be cyclic.
190 */
191 public boolean dependsOn(JSModule src, JSModule m) {
192 Set<JSModule> deps = dependencyMap.get(src);
193 if (deps == null) {
194 deps = getTransitiveDepsDeepestFirst(src);
195 dependencyMap.put(src, deps);
196 }
197
198 return deps.contains(m);
199 }
200
201 /**
202 * Finds the deepest common dependency of two modules, not including the two
203 * modules themselves.
204 *
205 * @param m1 A module in this graph
206 * @param m2 A module in this graph
207 * @return The deepest common dep of {@code m1} and {@code m2}, or null if
208 * they have no common dependencies
209 */
210 JSModule getDeepestCommonDependency(JSModule m1, JSModule m2) {
211 int m1Depth = m1.getDepth();
212 int m2Depth = m2.getDepth();
213 // According our definition of depth, the result must have a strictly
214 // smaller depth than either m1 or m2.
215 for (int depth = Math.min(m1Depth, m2Depth) - 1; depth >= 0; depth--) {
216 List<JSModule> modulesAtDepth = modulesByDepth.get(depth);
217 // Look at the modules at this depth in reverse order, so that we use the
218 // original ordering of the modules to break ties (later meaning deeper).
219 for (int i = modulesAtDepth.size() - 1; i >= 0; i--) {
220 JSModule m = modulesAtDepth.get(i);
221 if (dependsOn(m1, m) && dependsOn(m2, m)) {
222 return m;
223 }
224 }
225 }
226 return null;
227 }
228
229 /**
230 * Finds the deepest common dependency of two modules, including the
231 * modules themselves.
232 *
233 * @param m1 A module in this graph
234 * @param m2 A module in this graph
235 * @return The deepest common dep of {@code m1} and {@code m2}, or null if
236 * they have no common dependencies
237 */
238 public JSModule getDeepestCommonDependencyInclusive(
239 JSModule m1, JSModule m2) {
240 if (m2 == m1 || dependsOn(m2, m1)) {
241 return m1;
242 } else if (dependsOn(m1, m2)) {
243 return m2;
244 }
245
246 return getDeepestCommonDependency(m1, m2);
247 }
248
249 /** Returns the deepest common dependency of the given modules. */
250 public JSModule getDeepestCommonDependencyInclusive(
251 Collection<JSModule> modules) {
252 Iterator<JSModule> iter = modules.iterator();
253 JSModule dep = iter.next();
254 while (iter.hasNext()) {
255 dep = getDeepestCommonDependencyInclusive(dep, iter.next());
256 }
257 return dep;
258 }
259
260 /**
261 * Creates an iterable over the transitive dependencies of module {@code m}
262 * in a non-increasing depth ordering. The result does not include the module
263 * {@code m}.
264 *
265 * @param m A module in this graph
266 * @return The transitive dependencies of module {@code m}
267 */
268 Set<JSModule> getTransitiveDepsDeepestFirst(JSModule m) {
269 Set<JSModule> deps = dependencyMap.get(m);
270 if (deps != null) {
271 return deps;
272 }
273 deps = new TreeSet<JSModule>(new InverseDepthComparator());
274 addDeps(deps, m);
275 dependencyMap.put(m, deps);
276 return deps;
277 }
278
279 /**
280 * Adds a module's transitive dependencies to a set.
281 */
282 private void addDeps(Set<JSModule> deps, JSModule m) {
283 for (JSModule dep : m.getDependencies()) {
284 deps.add(dep);
285 addDeps(deps, dep);
286 }
287 }
288
289 /**
290 * Replaces any files that are found multiple times with a single instance in
291 * the closest parent module that is common to all modules where it appears.
292 *
293 * JSCompiler normally errors if you attempt to compile modules containing the
294 * same file. This method can be used to remove duplicates before compiling
295 * to avoid such an error.
296 */
297 public void coalesceDuplicateFiles() {
298 Multimap<String, JSModule> fileRefs = LinkedHashMultimap.create();
299 for (JSModule module : modules) {
300 for (CompilerInput jsFile : module.getInputs()) {
301 fileRefs.put(jsFile.getName(), module);
302 }
303 }
304
305 for (String path : fileRefs.keySet()) {
306 Collection<JSModule> refModules = fileRefs.get(path);
307 if (refModules.size() > 1) {
308 JSModule depModule = getDeepestCommonDependencyInclusive(refModules);
309 CompilerInput file = refModules.iterator().next().getByName(path);
310 for (JSModule module : refModules) {
311 if (module != depModule) {
312 module.removeByName(path);
313 }
314 }
315 if (!refModules.contains(depModule)) {
316 depModule.add(file);
317 }
318 }
319 }
320 }
321
322 /**
323 * Applies a DependencyOptions in "dependency sorting" and "dependency pruning"
324 * mode to the given list of inputs. Returns a new list with the files sorted
325 * and removed. This module graph will be updated to reflect the new list.
326 *
327 * If you need more fine-grained dependency management, you should create your
328 * own DependencyOptions and call
329 * {@code manageDependencies(DependencyOptions, List<CompilerInput>)}.
330 *
331 * @param entryPoints The entry points into the program.
332 * Expressed as JS symbols.
333 * @param inputs The original list of sources. Used to ensure that the sort
334 * is stable.
335 * @throws CircularDependencyException if there is a circular dependency
336 * between the provides and requires.
337 * @throws MissingProvideException if an entry point was not provided
338 * by any of the inputs.
339 * @see DependencyOptions for more info on how this works.
340 */
341 public List<CompilerInput> manageDependencies(
342 List<String> entryPoints,
343 List<CompilerInput> inputs)
344 throws CircularDependencyException,
345 MissingModuleException,
346 MissingProvideException {
347 DependencyOptions depOptions = new DependencyOptions();
348 depOptions.setDependencySorting(true);
349 depOptions.setDependencyPruning(true);
350 depOptions.setEntryPoints(entryPoints);
351 return manageDependencies(depOptions, inputs);
352 }
353
354 /**
355 * Apply the dependency options to the list of sources, returning a new
356 * source list re-ordering and dropping files as necessary.
357 * This module graph will be updated to reflect the new list.
358 *
359 * @param inputs The original list of sources. Used to ensure that the sort
360 * is stable.
361 * @throws CircularDependencyException if there is a circular dependency
362 * between the provides and requires.
363 * @throws MissingProvideException if an entry point was not provided
364 * by any of the inputs.
365 * @see DependencyOptions for more info on how this works.
366 */
367 public List<CompilerInput> manageDependencies(
368 DependencyOptions depOptions,
369 List<CompilerInput> inputs)
370 throws CircularDependencyException, MissingProvideException,
371 MissingModuleException {
372
373 SortedDependencies<CompilerInput> sorter =
374 new SortedDependencies<CompilerInput>(inputs);
375 Iterable<CompilerInput> entryPointInputs = createEntryPointInputs(
376 depOptions, inputs, sorter);
377
378 // The order of inputs, sorted independently of modules.
379 List<CompilerInput> absoluteOrder =
380 sorter.getDependenciesOf(inputs, depOptions.shouldSortDependencies());
381
382 // Figure out which sources *must* be in each module.
383 ListMultimap<JSModule, CompilerInput> entryPointInputsPerModule =
384 LinkedListMultimap.create();
385 for (CompilerInput input : entryPointInputs) {
386 JSModule module = input.getModule();
387 Preconditions.checkNotNull(module);
388 entryPointInputsPerModule.put(module, input);
389 }
390
391 // Clear the modules of their inputs. This also nulls out
392 // the input's reference to its module.
393 for (JSModule module : getAllModules()) {
394 module.removeAll();
395 }
396
397 // Figure out which sources *must* be in each module, or in one
398 // of that module's dependencies.
399 for (JSModule module : entryPointInputsPerModule.keySet()) {
400 List<CompilerInput> transitiveClosure =
401 sorter.getDependenciesOf(
402 entryPointInputsPerModule.get(module),
403 depOptions.shouldSortDependencies());
404 for (CompilerInput input : transitiveClosure) {
405 JSModule oldModule = input.getModule();
406 if (oldModule == null) {
407 input.setModule(module);
408 } else {
409 input.setModule(null);
410 input.setModule(
411 getDeepestCommonDependencyInclusive(oldModule, module));
412 }
413 }
414 }
415
416 // All the inputs are pointing to the modules that own them. Yeah!
417 // Update the modules to reflect this.
418 for (CompilerInput input : absoluteOrder) {
419 JSModule module = input.getModule();
420 if (module != null) {
421 module.add(input);
422 }
423 }
424
425 // Now, generate the sorted result.
426 List<CompilerInput> result = Lists.newArrayList();
427 for (JSModule module : getAllModules()) {
428 result.addAll(module.getInputs());
429 }
430
431 return result;
432 }
433
434 private Collection<CompilerInput> createEntryPointInputs(
435 DependencyOptions depOptions,
436 List<CompilerInput> inputs,
437 SortedDependencies<CompilerInput> sorter)
438 throws MissingModuleException, MissingProvideException {
439 Set<CompilerInput> entryPointInputs = Sets.newLinkedHashSet();
440 Map<String, JSModule> modulesByName = getModulesByName();
441
442 if (depOptions.shouldPruneDependencies()) {
443 if (!depOptions.shouldDropMoochers()) {
444 entryPointInputs.addAll(sorter.getInputsWithoutProvides());
445 }
446
447 for (String entryPoint : depOptions.getEntryPoints()) {
448 // An entry point is either formatted as:
449 // 'foo.bar' - peg foo.bar to its current module
450 // 'modC:foo.bar' - peg foo.bar to modC
451 String inputName = entryPoint;
452 int splitPoint = entryPoint.indexOf(':');
453 CompilerInput entryPointInput = null;
454 if (splitPoint != -1) {
455 String moduleName = entryPoint.substring(0, splitPoint);
456 inputName = entryPoint.substring(
457 Math.min(splitPoint + 1, entryPoint.length() - 1));
458 JSModule module = modulesByName.get(moduleName);
459 if (module == null) {
460 throw new MissingModuleException(moduleName);
461 } else {
462 entryPointInput = sorter.getInputProviding(inputName);
463 entryPointInput.overrideModule(module);
464 }
465 } else {
466 entryPointInput = sorter.getInputProviding(inputName);
467 }
468
469 entryPointInputs.add(entryPointInput);
470 }
471
472 CompilerInput baseJs = sorter.maybeGetInputProviding("goog");
473 if (baseJs != null) {
474 entryPointInputs.add(baseJs);
475 }
476 } else {
477 entryPointInputs.addAll(inputs);
478 }
479 return entryPointInputs;
480 }
481
482 LinkedDirectedGraph<JSModule, String> toGraphvizGraph() {
483 LinkedDirectedGraph<JSModule, String> graphViz =
484 LinkedDirectedGraph.create();
485 for (JSModule module : getAllModules()) {
486 graphViz.createNode(module);
487 for (JSModule dep : module.getDependencies()) {
488 graphViz.createNode(dep);
489 graphViz.connect(module, "->", dep);
490 }
491 }
492 return graphViz;
493 }
494
495 /**
496 * A module depth comparator that considers a deeper module to be "less than"
497 * a shallower module. Uses module names to consistently break ties.
498 */
499 private class InverseDepthComparator implements Comparator<JSModule> {
500 @Override
501 public int compare(JSModule m1, JSModule m2) {
502 return depthCompare(m2, m1);
503 }
504 }
505
506 private int depthCompare(JSModule m1, JSModule m2) {
507 if (m1 == m2) {
508 return 0;
509 }
510 int d1 = m1.getDepth();
511 int d2 = m2.getDepth();
512 return d1 < d2 ? -1 : d2 == d1 ? m1.getName().compareTo(m2.getName()) : 1;
513 }
514
515 /*
516 * Exception class for declaring when the modules being fed into a
517 * JSModuleGraph as input aren't in dependence order, and so can't be
518 * processed for caching of various dependency-related queries.
519 */
520
521 protected static class ModuleDependenceException
522 extends IllegalArgumentException {
523 private static final long serialVersionUID = 1;
524
525 private final JSModule module;
526 private final JSModule dependentModule;
527
528 protected ModuleDependenceException(String message,
529 JSModule module, JSModule dependentModule) {
530 super(message);
531 this.module = module;
532 this.dependentModule = dependentModule;
533 }
534
535 public JSModule getModule() {
536 return module;
537 }
538
539 public JSModule getDependentModule() {
540 return dependentModule;
541 }
542 }
543
544 public static class MissingModuleException extends Exception {
545 MissingModuleException(String moduleName) {
546 super(moduleName);
547 }
548 }
549
550 }