Debian Codegraph @

src/com/google/javascript/jscomp/deps/DepsGenerator.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.deps;
18
19 import com.google.common.base.Function;
20 import com.google.common.base.Joiner;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Multimap;
24 import com.google.common.collect.Multimaps;
25 import com.google.common.collect.Sets;
26 import com.google.javascript.jscomp.CheckLevel;
27 import com.google.javascript.jscomp.DiagnosticType;
28 import com.google.javascript.jscomp.ErrorManager;
29 import com.google.javascript.jscomp.JSError;
30 import com.google.javascript.jscomp.SourceFile;
31
32 import java.io.ByteArrayOutputStream;
33 import java.io.File;
34 import java.io.IOException;
35 import java.io.PrintStream;
36 import java.util.Arrays;
37 import java.util.Collection;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Set;
41 import java.util.logging.Logger;
42
43 /**
44 * Generates deps.js files by scanning JavaScript files for
45 * calls to goog.provide(), goog.require() and goog.addDependency().
46 *
47 * @author [email protected] (Andrew Grieve)
48 */
49 public class DepsGenerator {
50
51 public static enum InclusionStrategy {
52 ALWAYS,
53 WHEN_IN_SRCS,
54 DO_NOT_DUPLICATE
55 }
56
57 private static Logger logger =
58 Logger.getLogger(DepsGenerator.class.getName());
59
60 // See the Flags in MakeJsDeps for descriptions of these.
61 private final Collection<SourceFile> srcs;
62 private final Collection<SourceFile> deps;
63 private final String closurePathAbs;
64 private final InclusionStrategy mergeStrategy;
65 final ErrorManager errorManager;
66
67 static final DiagnosticType SAME_FILE_WARNING = DiagnosticType.warning(
68 "DEPS_SAME_FILE",
69 "Namespace \"{0}\" is both required and provided in the same file.");
70
71 static final DiagnosticType NEVER_PROVIDED_ERROR = DiagnosticType.error(
72 "DEPS_NEVER_PROVIDED",
73 "Namespace \"{0}\" is required but never provided.");
74
75 static final DiagnosticType DUPE_PROVIDES_WARNING = DiagnosticType.warning(
76 "DEPS_DUPE_PROVIDES",
77 "Multiple calls to goog.provide(\"{0}\")");
78
79 static final DiagnosticType MULTIPLE_PROVIDES_ERROR = DiagnosticType.error(
80 "DEPS_DUPE_PROVIDES",
81 "Namespace \"{0}\" is already provided in other file {1}");
82
83 static final DiagnosticType DUPE_REQUIRE_WARNING = DiagnosticType.warning(
84 "DEPS_DUPE_REQUIRES",
85 "Namespace \"{0}\" is required multiple times");
86
87 static final DiagnosticType NO_DEPS_WARNING = DiagnosticType.warning(
88 "DEPS_NO_DEPS",
89 "No dependencies found in file");
90
91 /**
92 * Creates a new DepsGenerator.
93 */
94 public DepsGenerator(
95 Collection<SourceFile> deps,
96 Collection<SourceFile> srcs,
97 InclusionStrategy mergeStrategy,
98 String closurePathAbs,
99 ErrorManager errorManager) {
100 this.deps = deps;
101 this.srcs = srcs;
102 this.mergeStrategy = mergeStrategy;
103 this.closurePathAbs = closurePathAbs;
104 this.errorManager = errorManager;
105 }
106
107 /**
108 * Performs the parsing inputs and writing of outputs.
109 * @throws IOException Occurs upon an IO error.
110 * @return Returns a String of goog.addDependency calls that will build
111 * the dependency graph. Returns null if there was an error.
112 */
113 public String computeDependencyCalls() throws IOException {
114 // Build a map of closure-relative path -> DepInfo.
115 Map<String, DependencyInfo> depsFiles = parseDepsFiles();
116 logger.fine("preparsedFiles: " + depsFiles);
117
118 // Find all goog.provides & goog.requires in src files
119 Map<String, DependencyInfo> jsFiles = parseSources(depsFiles.keySet());
120
121 // Check if there were any parse errors.
122 if (errorManager.getErrorCount() > 0) {
123 return null;
124 }
125
126 cleanUpDuplicatedFiles(depsFiles, jsFiles);
127
128 // Check for missing provides or other semantic inconsistencies.
129 validateDependencies(depsFiles.values(), jsFiles.values());
130
131 if (errorManager.getErrorCount() > 0) {
132 return null;
133 }
134
135 ByteArrayOutputStream output = new ByteArrayOutputStream();
136 writeDepsContent(depsFiles, jsFiles, new PrintStream(output));
137 return new String(output.toByteArray());
138 }
139
140 /**
141 * Removes duplicated depsInfo from jsFiles if this info already present in
142 * some of the parsed deps.js
143 *
144 * @param depsFiles DepsInfo from deps.js dependencies
145 * @param jsFiles DepsInfo from some of jsSources
146 */
147 protected void cleanUpDuplicatedFiles(Map<String, DependencyInfo> depsFiles,
148 Map<String, DependencyInfo> jsFiles) {
149 Set<String> depsPathsCopy = Sets.newHashSet(depsFiles.keySet());
150 for (String path : depsPathsCopy) {
151 if (mergeStrategy != InclusionStrategy.WHEN_IN_SRCS) {
152 jsFiles.remove(path);
153 }
154 }
155
156 for (String path : jsFiles.keySet()) {
157 // If a generated file appears in both the jsFiles and in depsFiles, then
158 // remove it from depsFiles in order to get the full path the generated
159 // file.
160 depsFiles.remove(path);
161 }
162 }
163
164 /**
165 * Reports if there are any dependency problems with the given dependency
166 * information. Reported problems include:
167 * - A namespace being provided more than once
168 * - A namespace being required multiple times from within one file
169 * - A namespace being provided and required in the same file
170 * - A namespace being required that is never provided
171 * @param preparsedFileDepedencies Dependency information from existing
172 * deps.js files.
173 * @param parsedFileDependencies Dependency information from parsed .js files.
174 */
175 private void validateDependencies(Iterable<DependencyInfo> preparsedFileDepedencies,
176 Iterable<DependencyInfo> parsedFileDependencies) {
177 // Create a map of namespace -> file providing it.
178 // Also report any duplicate provides.
179 Map<String, DependencyInfo> providesMap = Maps.newHashMap();
180 addToProvideMap(preparsedFileDepedencies, providesMap);
181 addToProvideMap(parsedFileDependencies, providesMap);
182 // For each require in the parsed sources:
183 for (DependencyInfo depInfo : parsedFileDependencies) {
184 List<String> requires = Lists.newArrayList(depInfo.getRequires());
185 for (int i = 0, l = requires.size(); i < l; ++i) {
186 String namespace = requires.get(i);
187 // Check for multiple requires.
188 if (requires.subList(i + 1, l).contains(namespace)) {
189 reportDuplicateRequire(namespace, depInfo);
190 }
191 // Check for missing provides.
192 DependencyInfo provider = providesMap.get(namespace);
193 if (provider == null) {
194 reportUndefinedNamespace(namespace, depInfo);
195 } else if (provider == depInfo) {
196 reportSameFile(namespace, depInfo);
197 }
198 }
199 }
200 }
201
202 private void reportSameFile(String namespace, DependencyInfo depInfo) {
203 errorManager.report(CheckLevel.WARNING,
204 JSError.make(depInfo.getName(), -1, -1,
205 SAME_FILE_WARNING, namespace));
206 }
207
208 private void reportUndefinedNamespace(
209 String namespace, DependencyInfo depInfo) {
210 errorManager.report(CheckLevel.ERROR,
211 JSError.make(depInfo.getName(), -1, -1,
212 NEVER_PROVIDED_ERROR, namespace));
213 }
214
215 private void reportDuplicateProvide(String namespace, DependencyInfo firstDep,
216 DependencyInfo secondDep) {
217 if (firstDep == secondDep) {
218 errorManager.report(CheckLevel.WARNING,
219 JSError.make(firstDep.getName(), -1, -1,
220 DUPE_PROVIDES_WARNING, namespace));
221 } else {
222 errorManager.report(CheckLevel.ERROR,
223 JSError.make(secondDep.getName(), -1, -1,
224 MULTIPLE_PROVIDES_ERROR, namespace, firstDep.getName()));
225 }
226 }
227
228 private void reportDuplicateRequire(
229 String namespace, DependencyInfo depInfo) {
230 errorManager.report(CheckLevel.WARNING,
231 JSError.make(depInfo.getName(), -1, -1,
232 DUPE_REQUIRE_WARNING, namespace));
233 }
234
235 private void reportNoDepsInDepsFile(String filePath) {
236 errorManager.report(CheckLevel.WARNING,
237 JSError.make(filePath, -1, -1, NO_DEPS_WARNING));
238 }
239
240 /**
241 * Adds the given DependencyInfos to the given providesMap. Also checks for
242 * and reports duplicate provides.
243 */
244 private void addToProvideMap(Iterable<DependencyInfo> depInfos,
245 Map<String, DependencyInfo> providesMap) {
246 for (DependencyInfo depInfo : depInfos) {
247 for (String provide : depInfo.getProvides()) {
248 DependencyInfo prevValue = providesMap.put(provide, depInfo);
249 // Check for duplicate provides.
250 if (prevValue != null) {
251 reportDuplicateProvide(provide, prevValue, depInfo);
252 }
253 }
254 }
255 }
256
257 protected DepsFileParser createDepsFileParser() {
258 DepsFileParser depsParser = new DepsFileParser(errorManager);
259 depsParser.setShortcutMode(true);
260 return depsParser;
261 }
262
263 /**
264 * Returns whether we should ignore dependency info in the given deps file.
265 */
266 protected boolean shouldSkipDepsFile(SourceFile file) {
267 return false;
268 }
269
270 /**
271 * Parses all deps.js files in the deps list and creates a map of
272 * closure-relative path -> DependencyInfo.
273 */
274 private Map<String, DependencyInfo> parseDepsFiles() throws IOException {
275 DepsFileParser depsParser = createDepsFileParser();
276 Map<String, DependencyInfo> depsFiles = Maps.newHashMap();
277 for (SourceFile file : deps) {
278 if (!shouldSkipDepsFile(file)) {
279 List<DependencyInfo>
280 depInfos = depsParser.parseFileReader(
281 file.getName(), file.getCodeReader());
282 if (depInfos.isEmpty()) {
283 reportNoDepsInDepsFile(file.getName());
284 } else {
285 for (DependencyInfo info : depInfos) {
286 depsFiles.put(info.getPathRelativeToClosureBase(), info);
287 }
288 }
289 }
290 }
291
292 // If a deps file also appears in srcs, our build tools will move it
293 // into srcs. So we need to scan all the src files for addDependency
294 // calls as well.
295 for (SourceFile src : srcs) {
296 if ((new File(src.getName())).exists() &&
297 !shouldSkipDepsFile(src)) {
298 List<DependencyInfo> srcInfos =
299 depsParser.parseFileReader(src.getName(), src.getCodeReader());
300 for (DependencyInfo info : srcInfos) {
301 depsFiles.put(info.getPathRelativeToClosureBase(), info);
302 }
303 }
304 }
305
306 return depsFiles;
307 }
308
309 /**
310 * Parses all source files for dependency information.
311 * @param preparsedFiles A set of closure-relative paths.
312 * Files in this set are not parsed if they are encountered in srcs.
313 * @return Returns a map of closure-relative paths -> DependencyInfo for the
314 * newly parsed files.
315 * @throws IOException Occurs upon an IO error.
316 */
317 private Map<String, DependencyInfo> parseSources(
318 Set<String> preparsedFiles) throws IOException {
319 Map<String, DependencyInfo> parsedFiles = Maps.newHashMap();
320 JsFileParser jsParser = new JsFileParser(errorManager);
321
322 for (SourceFile file : srcs) {
323 String closureRelativePath =
324 PathUtil.makeRelative(
325 closurePathAbs, PathUtil.makeAbsolute(file.getName()));
326 logger.fine("Closure-relative path: " + closureRelativePath);
327
328 if (InclusionStrategy.WHEN_IN_SRCS == mergeStrategy ||
329 !preparsedFiles.contains(closureRelativePath)) {
330 DependencyInfo depInfo =
331 jsParser.parseFile(
332 file.getName(), closureRelativePath,
333 file.getCode());
334
335 // Kick the source out of memory.
336 file.clearCachedSource();
337 parsedFiles.put(closureRelativePath, depInfo);
338 }
339 }
340
341 return parsedFiles;
342 }
343
344 /**
345 * Creates the content to put into the output deps.js file. If mergeDeps is
346 * true, then all of the dependency information in the providedDeps will be
347 * included in the output.
348 * @throws IOException Occurs upon an IO error.
349 */
350 private void writeDepsContent(Map<String, DependencyInfo> depsFiles,
351 Map<String, DependencyInfo> jsFiles, PrintStream out)
352 throws IOException {
353 // Print all dependencies extracted from srcs.
354 writeDepInfos(out, jsFiles.values());
355
356 // Print all dependencies extracted from deps.
357 if (mergeStrategy == InclusionStrategy.ALWAYS) {
358 // This multimap is just for splitting DepsInfo objects by
359 // it's definition deps.js file
360 Multimap<String, DependencyInfo> infosIndex = Multimaps.index(
361 depsFiles.values(),
362 new Function<DependencyInfo, String>() {
363 @Override
364 public String apply(DependencyInfo from) {
365 return from.getName();
366 }
367 });
368
369 for (String depsPath : infosIndex.keySet()) {
370 String path = formatPathToDepsFile(depsPath);
371 out.println("\n// Included from: " + path);
372 writeDepInfos(out, infosIndex.get(depsPath));
373 }
374 }
375 }
376
377 /**
378 * Format the deps file path so that it can be included in the output file.
379 */
380 protected String formatPathToDepsFile(String path) {
381 return path;
382 }
383
384 /**
385 * Writes goog.addDependency() lines for each DependencyInfo in depInfos.
386 * @throws IOException Occurs upon an IO error.
387 */
388 private void writeDepInfos(PrintStream out,
389 Collection<DependencyInfo> depInfos
390 ) throws IOException {
391 // Print dependencies.
392 // Lines look like this:
393 // goog.addDependency('../../path/to/file.js', ['goog.Delay'],
394 // ['goog.Disposable', 'goog.Timer']);
395 for (DependencyInfo depInfo : depInfos) {
396 Collection<String> provides = depInfo.getProvides();
397 Collection<String> requires = depInfo.getRequires();
398
399 out.print("goog.addDependency('" +
400 depInfo.getPathRelativeToClosureBase() + "', ");
401 writeJsArray(out, provides);
402 out.print(", ");
403 writeJsArray(out, requires);
404 out.println(");");
405 }
406 }
407
408 /**
409 * Prints a list of strings formatted as a JavaScript array of string
410 * literals.
411 */
412 private static void writeJsArray(PrintStream out, Collection<String> values) {
413 if (values.isEmpty()) {
414 out.print("[]");
415 } else {
416 out.print("['");
417 out.print(Joiner.on("', '").join(values));
418 out.print("']");
419 }
420 }
421
422 static List<SourceFile> createSourceFilesFromPaths(
423 Collection<String> paths) {
424 List<SourceFile> files = Lists.newArrayList();
425 for (String path : paths) {
426 files.add(SourceFile.fromFile(path));
427 }
428 return files;
429 }
430
431 static List<SourceFile> createSourceFilesFromPaths(
432 String ... paths) {
433 return createSourceFilesFromPaths(Arrays.asList(paths));
434 }
435 }