diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java index 40c07891227..6acb2bddafe 100644 --- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java +++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java @@ -186,7 +186,7 @@ public abstract class AbstractCommandLineRunner> inputsSupplierForTesting = null; @GwtIncompatible("Unnecessary") - private @Nullable Supplier> modulesSupplierForTesting = null; + private @Nullable Supplier> chunksSupplierForTesting = null; @GwtIncompatible("Unnecessary") private Function exitCodeReceiver = SystemExitCodeReceiver.INSTANCE; @@ -233,8 +233,8 @@ public abstract class AbstractCommandLineRunner> externsSupplier, Supplier> inputsSupplier, - Supplier> modulesSupplier, + Supplier> chunksSupplier, Function exitCodeReceiver) { - checkArgument(inputsSupplier == null != (modulesSupplier == null)); + checkArgument(inputsSupplier == null != (chunksSupplier == null)); testMode = true; this.externsSupplierForTesting = externsSupplier; this.inputsSupplierForTesting = inputsSupplier; - this.modulesSupplierForTesting = modulesSupplier; + this.chunksSupplierForTesting = chunksSupplier; this.exitCodeReceiver = exitCodeReceiver; } @@ -839,30 +839,30 @@ private List createExternInputs(List files) throws IOExcepti } /** - * Creates module objects from a list of chunk specifications. + * Creates chunk objects from a list of chunk specifications. * * @param specs A list of chunk specifications, not null or empty. * @param inputs A list of JS file paths, not null * @return An array of module objects */ - public static List createJsModules(List specs, List inputs) { + public static List createJsChunks(List specs, List inputs) { checkState(specs != null); checkState(!specs.isEmpty()); checkState(inputs != null); - List moduleNames = new ArrayList<>(specs.size()); - Map modulesByName = new LinkedHashMap<>(); + List chunkNames = new ArrayList<>(specs.size()); + Map chunksByName = new LinkedHashMap<>(); Map modulesFileCountMap = new LinkedHashMap<>(); int numJsFilesExpected = 0; int minJsFilesRequired = 0; for (JsChunkSpec spec : specs) { - if (modulesByName.containsKey(spec.name)) { + if (chunksByName.containsKey(spec.name)) { throw new FlagUsageException("Duplicate module name: " + spec.name); } - JSChunk module = new JSChunk(spec.name); + JSChunk chunk = new JSChunk(spec.name); for (String dep : spec.deps) { - JSChunk other = modulesByName.get(dep); + JSChunk other = chunksByName.get(dep); if (other == null) { throw new FlagUsageException( "Module '" @@ -871,7 +871,7 @@ public static List createJsModules(List specs, List createJsModules(List specs, List createJsModules(List specs, List moduleFiles = inputs.subList(numJsFilesLeft - numJsFiles, numJsFilesLeft); for (CompilerInput input : moduleFiles) { - module.add(input); + chunk.add(input); } numJsFilesLeft -= numJsFiles; moduleIndex++; } - return new ArrayList<>(modulesByName.values()); + return new ArrayList<>(chunksByName.values()); } /** @@ -1033,7 +1033,7 @@ private static ImmutableMap parseModuleOutputFiles(List */ @GwtIncompatible("Unnecessary") @VisibleForTesting - String getModuleOutputFileName(JSChunk m) { + String getChunkOutputFileName(JSChunk m) { if (parsedModuleOutputFiles == null) { parsedModuleOutputFiles = parseModuleOutputFiles(config.moduleOutputFiles); } @@ -1051,7 +1051,7 @@ void writeModuleOutput(String fileName, Appendable out, LicenseTracker lt, JSChu if (parsedModuleWrappers == null) { parsedModuleWrappers = parseModuleWrappers( - config.moduleWrapper, ImmutableList.copyOf(compiler.getModuleGraph().getAllChunks())); + config.moduleWrapper, ImmutableList.copyOf(compiler.getChunkGraph().getAllChunks())); } if (!isOutputInJson()) { @@ -1073,14 +1073,14 @@ void writeModuleOutput(String fileName, Appendable out, LicenseTracker lt, JSChu * Writes code to an output stream, optionally wrapping it in an arbitrary wrapper that contains a * placeholder where the code should be inserted. * - * @param module Which module to write. If this is null, write the entire AST. + * @param chunk Which chunk to write. If this is null, write the entire AST. */ @GwtIncompatible("Unnecessary") void writeOutput( Appendable out, Compiler compiler, LicenseTracker licenseTracker, - @Nullable JSChunk module, + @Nullable JSChunk chunk, String wrapper, String codePlaceholder, @Nullable Function escaper, @@ -1092,7 +1092,7 @@ void writeOutput( } checkState(compiler.getOptions().outputJs == OutputJs.NORMAL); - String code = module == null ? compiler.toSource() : compiler.toSource(licenseTracker, module); + String code = chunk == null ? compiler.toSource() : compiler.toSource(licenseTracker, chunk); writeOutput(out, compiler, code, wrapper, codePlaceholder, escaper, filename); } @@ -1197,7 +1197,7 @@ protected int doRun() throws IOException { @Nullable String typedAstListInputFilename = config.typedAstListInputFilename; List externs = createExterns(options); - List modules = null; + List chunks = null; rootRelativePathsMap = constructRootRelativePathsMap(); @@ -1261,7 +1261,7 @@ protected int doRun() throws IOException { if (!jsChunkSpecs.isEmpty()) { if (isInTestMode()) { - modules = modulesSupplierForTesting.get(); + chunks = chunksSupplierForTesting.get(); } else { if (JsonStreamMode.IN.equals(config.jsonStreamMode) || JsonStreamMode.NONE.equals(config.jsonStreamMode)) { @@ -1273,17 +1273,16 @@ protected int doRun() throws IOException { for (SourceFile source : sources) { inputs.add(new CompilerInput(source, /* isExtern= */ false)); } - modules = createJsModules(jsChunkSpecs, inputs.build()); + chunks = createJsChunks(jsChunkSpecs, inputs.build()); } - for (JSChunk m : modules) { - outputFileNames.add(getModuleOutputFileName(m)); + for (JSChunk m : chunks) { + outputFileNames.add(getChunkOutputFileName(m)); } if (typedAstListInputFilename != null) { - this.initModulesWithTypedAstFilesystem( - externs, modules, options, typedAstListInputFilename); + this.initChunksWithTypedAstFilesystem(externs, chunks, options, typedAstListInputFilename); } else { - compiler.initModules(externs, modules, options); + compiler.initChunks(externs, chunks, options); } } else { if (typedAstListInputFilename != null) { @@ -1305,12 +1304,12 @@ protected int doRun() throws IOException { boolean shouldProcessResults = true; if (config.skipNormalOutputs) { metricsRecorder.recordActionName("skip normal outputs"); - // TODO(bradfordcsmith): Should we be ignoring possible init/initModules() errors here? + // TODO(bradfordcsmith): Should we be ignoring possible init/initChunks() errors here? compiler.orderInputsWithLargeStack(); result = null; } else if (compiler.hasErrors()) { metricsRecorder.recordActionName("initialization errors occurred"); - // init() or initModules() encountered an error. + // init() or initChunks() encountered an error. compiler.generateReport(); result = compiler.getResult(); } else if (options.getInstrumentForCoverageOnly()) { @@ -1339,14 +1338,14 @@ protected int doRun() throws IOException { result = restoreAndPerformStages2and3( config.getContinueSavedCompilationFileName(), metricsRecorder); - if (modules != null) { - modules = ImmutableList.copyOf(compiler.getModules()); + if (chunks != null) { + chunks = ImmutableList.copyOf(compiler.getChunks()); } } else if (config.shouldRestoreAndPerformStage3()) { result = restoreAndPerformStage3(config.getContinueSavedCompilationFileName(), metricsRecorder); - if (modules != null) { - modules = ImmutableList.copyOf(compiler.getModules()); + if (chunks != null) { + chunks = ImmutableList.copyOf(compiler.getChunks()); } } else { result = performFullCompilation(metricsRecorder); @@ -1354,9 +1353,9 @@ protected int doRun() throws IOException { if (createCommonJsModules) { // For Commonchunks construct modules from actual inputs. - modules = ImmutableList.copyOf(compiler.getModules()); - for (JSChunk m : modules) { - outputFileNames.add(getModuleOutputFileName(m)); + chunks = ImmutableList.copyOf(compiler.getChunks()); + for (JSChunk c : chunks) { + outputFileNames.add(getChunkOutputFileName(c)); } } @@ -1369,7 +1368,7 @@ protected int doRun() throws IOException { int exitStatus = shouldProcessResults - ? processResults(result, modules, options) + ? processResults(result, chunks, options) : getExitStatusForResult(result); metricsRecorder.recordResultMetrics(compiler, result); return exitStatus; @@ -1423,11 +1422,11 @@ private void initWithTypedAstFilesystem( } @GwtIncompatible("Unnecessary") - private void initModulesWithTypedAstFilesystem( + private void initChunksWithTypedAstFilesystem( List externs, List chunks, CompilerOptions options, String filename) { try (GZIPInputStream typedAstListStream = new GZIPInputStream(new FileInputStream(filename), GZIPPED_TYPEDAST_BUFFER_SIZE)) { - compiler.initModulesWithTypedAstFilesystem(externs, chunks, options, typedAstListStream); + compiler.initChunksWithTypedAstFilesystem(externs, chunks, options, typedAstListStream); } catch (IOException e) { compiler.report(JSError.make(COULD_NOT_DESERIALIZE_AST, filename)); } @@ -1604,7 +1603,7 @@ private Result instrumentForCoverage(CompileMetricsRecorderInterface metricsReco /** Processes the results of the compile job, and returns an error code. */ @GwtIncompatible("Unnecessary") - int processResults(Result result, List modules, B options) throws IOException { + int processResults(Result result, List chunks, B options) throws IOException { if (config.printAst) { if (compiler.getRoot() == null) { return 1; @@ -1647,11 +1646,11 @@ int processResults(Result result, List modules, B options) throws IOExc // Output the manifest and bundle files if requested. outputManifest(); outputBundle(); - outputModuleGraphJson(); + outputChunkGraphJson(); return 0; } else if (options.outputJs != OutputJs.NONE && result.success) { - outputModuleGraphJson(); - if (modules == null) { + outputChunkGraphJson(); + if (chunks == null) { outputSingleBinary(options); // Output the source map if requested. @@ -1661,7 +1660,7 @@ int processResults(Result result, List modules, B options) throws IOExc outputSourceMap(options, config.jsOutputFile); } } else { - DiagnosticType error = outputModuleBinaryAndSourceMaps(compiler.getModuleGraph(), options); + DiagnosticType error = outputModuleBinaryAndSourceMaps(compiler.getChunkGraph(), options); if (error != null) { compiler.report(JSError.make(error)); return 1; @@ -1781,8 +1780,8 @@ void outputJsonStream() throws IOException { @GwtIncompatible("Unnecessary") private @Nullable DiagnosticType outputModuleBinaryAndSourceMaps( - JSChunkGraph moduleGraph, B options) throws IOException { - Iterable modules = moduleGraph.getAllChunks(); + JSChunkGraph chunkGraph, B options) throws IOException { + Iterable modules = chunkGraph.getAllChunks(); parsedModuleWrappers = parseModuleWrappers(config.moduleWrapper, modules); if (!isOutputInJson()) { // make sure the method generates all dirs up to the latest / @@ -1817,7 +1816,7 @@ void outputJsonStream() throws IOException { mapFileOut = fileNameToOutputWriter2(expandSourceMapPath(options, m)); } - String moduleFilename = getModuleOutputFileName(m); + String moduleFilename = getChunkOutputFileName(m); maybeCreateDirsForPath(moduleFilename); try (Writer writer = fileNameToLegacyOutputWriter(moduleFilename)) { if (options.shouldGatherSourceMapInfo()) { @@ -1845,18 +1844,18 @@ void outputJsonStream() throws IOException { /** Given an output module, convert it to a JSONFileSpec with associated sourcemap */ @GwtIncompatible("Unnecessary") - private JsonFileSpec createJsonFileFromModule(JSChunk module) throws IOException { + private JsonFileSpec createJsonFileFromModule(JSChunk chunk) throws IOException { compiler.resetAndIntitializeSourceMap(); - String filename = getModuleOutputFileName(module); + String filename = getChunkOutputFileName(chunk); StringBuilder output = new StringBuilder(); - writeModuleOutput(filename, output, new ScriptNodeLicensesOnlyTracker(compiler), module); + writeModuleOutput(filename, output, new ScriptNodeLicensesOnlyTracker(compiler), chunk); JsonFileSpec jsonFile = new JsonFileSpec(output.toString(), filename); StringBuilder moduleSourceMap = new StringBuilder(); - compiler.getSourceMap().appendTo(moduleSourceMap, getModuleOutputFileName(module)); + compiler.getSourceMap().appendTo(moduleSourceMap, getChunkOutputFileName(chunk)); jsonFile.setSourceMap(moduleSourceMap.toString()); @@ -1971,10 +1970,10 @@ protected boolean shouldGenerateMapPerModule(B options) { * strategy #1 or #2 based on the current output mode. */ @GwtIncompatible("Unnecessary") - private String expandCommandLinePath(String path, @Nullable JSChunk forModule) { + private String expandCommandLinePath(String path, @Nullable JSChunk forChunk) { String sub; - if (forModule != null) { - sub = getModuleOutputFileName(forModule); + if (forChunk != null) { + sub = getChunkOutputFileName(forChunk); } else if (!config.module.isEmpty()) { sub = config.moduleOutputPathPrefix; } else { @@ -1986,11 +1985,11 @@ private String expandCommandLinePath(String path, @Nullable JSChunk forModule) { /** Expansion function for source map. */ @VisibleForTesting @GwtIncompatible("Unnecessary") - @Nullable String expandSourceMapPath(B options, @Nullable JSChunk forModule) { + @Nullable String expandSourceMapPath(B options, @Nullable JSChunk forChunk) { if (!options.shouldGatherSourceMapInfo()) { return null; } - return expandCommandLinePath(options.getSourceMapOutputPath(), forModule); + return expandCommandLinePath(options.getSourceMapOutputPath(), forChunk); } /** @@ -2261,7 +2260,7 @@ private void outputBundle() throws IOException { @GwtIncompatible("Unnecessary") private void outputInstrumentationMapping() throws IOException { if (!Strings.isNullOrEmpty(config.instrumentationMappingFile)) { - String path = expandCommandLinePath(config.instrumentationMappingFile, /* forModule= */ null); + String path = expandCommandLinePath(config.instrumentationMappingFile, /* forChunk= */ null); compiler.getInstrumentationMapping().save(path); } } @@ -2284,13 +2283,13 @@ private void outputManifestOrBundle(List outputFiles, boolean isManifest if (shouldGenerateOutputPerModule(output)) { // Generate per-module manifests or bundles. - Iterable modules = compiler.getModuleGraph().getAllChunks(); - for (JSChunk module : modules) { - try (Writer out = fileNameToOutputWriter2(expandCommandLinePath(output, module))) { + Iterable chunks = compiler.getChunkGraph().getAllChunks(); + for (JSChunk chunk : chunks) { + try (Writer out = fileNameToOutputWriter2(expandCommandLinePath(output, chunk))) { if (isManifest) { - printManifestTo(module, out); + printManifestTo(chunk, out); } else { - printBundleTo(module, out); + printBundleTo(chunk, out); } } } @@ -2300,15 +2299,15 @@ private void outputManifestOrBundle(List outputFiles, boolean isManifest if (config.module.isEmpty()) { // For a single-module compilation, generate a single headerless manifest or bundle // containing only the strong files. - JSChunk module = compiler.getModuleGraph().getChunkByName(JSChunk.STRONG_CHUNK_NAME); + JSChunk chunk = compiler.getChunkGraph().getChunkByName(JSChunk.STRONG_CHUNK_NAME); if (isManifest) { - printManifestTo(module, out); + printManifestTo(chunk, out); } else { - printBundleTo(module, out); + printBundleTo(chunk, out); } } else { // For a multi-module compilation, generate a single manifest file with module headers. - printModuleGraphManifestOrBundleTo(compiler.getModuleGraph(), out, isManifest); + printChunkGraphManifestOrBundleTo(compiler.getChunkGraph(), out, isManifest); } } } @@ -2317,10 +2316,10 @@ private void outputManifestOrBundle(List outputFiles, boolean isManifest /** Creates a file containing the current module graph in JSON serialization. */ @GwtIncompatible("Unnecessary") - private void outputModuleGraphJson() throws IOException { + private void outputChunkGraphJson() throws IOException { if (config.outputModuleDependencies != null && config.outputModuleDependencies.length() != 0) { try (Writer out = fileNameToOutputWriter2(config.outputModuleDependencies)) { - printModuleGraphJsonTo(out); + printChunkGraphJsonTo(out); } } } @@ -2328,19 +2327,19 @@ private void outputModuleGraphJson() throws IOException { /** Prints the current module graph as JSON. */ @VisibleForTesting @GwtIncompatible("Unnecessary") - void printModuleGraphJsonTo(Appendable out) throws IOException { - out.append(compiler.getModuleGraph().toJson().toString()); + void printChunkGraphJsonTo(Appendable out) throws IOException { + out.append(compiler.getChunkGraph().toJson().toString()); } /** Prints a set of modules to the manifest or bundle file. */ @VisibleForTesting @GwtIncompatible("Unnecessary") - void printModuleGraphManifestOrBundleTo(JSChunkGraph graph, Appendable out, boolean isManifest) + void printChunkGraphManifestOrBundleTo(JSChunkGraph graph, Appendable out, boolean isManifest) throws IOException { Joiner commas = Joiner.on(","); boolean requiresNewline = false; - for (JSChunk module : graph.getAllChunks()) { - if (!isManifest && module.isWeak()) { + for (JSChunk chunk : graph.getAllChunks()) { + if (!isManifest && chunk.isWeak()) { // Skip the weak module on a multi-module bundle, but not a multi-module manifest. continue; } @@ -2352,13 +2351,13 @@ void printModuleGraphManifestOrBundleTo(JSChunkGraph graph, Appendable out, bool if (isManifest) { // See CommandLineRunnerTest to see what the format of this // manifest looks like. - String dependencies = commas.join(module.getSortedDependencyNames()); + String dependencies = commas.join(chunk.getSortedDependencyNames()); out.append( String.format( - "{%s%s}\n", module.getName(), dependencies.isEmpty() ? "" : ":" + dependencies)); - printManifestTo(module, out); + "{%s%s}\n", chunk.getName(), dependencies.isEmpty() ? "" : ":" + dependencies)); + printManifestTo(chunk, out); } else { - printBundleTo(module, out); + printBundleTo(chunk, out); } requiresNewline = true; } @@ -2370,8 +2369,8 @@ void printModuleGraphManifestOrBundleTo(JSChunkGraph graph, Appendable out, bool */ @VisibleForTesting @GwtIncompatible("Unnecessary") - void printManifestTo(JSChunk module, Appendable out) throws IOException { - for (CompilerInput input : module.getInputs()) { + void printManifestTo(JSChunk chunk, Appendable out) throws IOException { + for (CompilerInput input : chunk.getInputs()) { String name = input.getName(); // Ignore fill files created by the compiler to facilitate cross-module code motion. @@ -2392,8 +2391,8 @@ void printManifestTo(JSChunk module, Appendable out) throws IOException { */ @VisibleForTesting @GwtIncompatible("Unnecessary") - void printBundleTo(JSChunk module, Appendable out) throws IOException { - ImmutableList inputs = module.getInputs(); + void printBundleTo(JSChunk chunk, Appendable out) throws IOException { + ImmutableList inputs = chunk.getInputs(); // Prebuild ASTs before they're needed in getLoadFlags, for performance and because // StackOverflowErrors can be hit if not prebuilt. if (compiler.getOptions().numParallelThreads > 1) { diff --git a/src/com/google/javascript/jscomp/AbstractCompiler.java b/src/com/google/javascript/jscomp/AbstractCompiler.java index 1b690a2671c..5a828eaacb5 100644 --- a/src/com/google/javascript/jscomp/AbstractCompiler.java +++ b/src/com/google/javascript/jscomp/AbstractCompiler.java @@ -92,7 +92,7 @@ void afterPass(String passName) {} public abstract @Nullable Node getScriptNode(String filename); /** Gets the module graph. */ - abstract @Nullable JSChunkGraph getModuleGraph(); + abstract @Nullable JSChunkGraph getChunkGraph(); /** * Gets the inputs in the order in which they are being processed. Only for use by {@code @@ -245,7 +245,7 @@ void afterPass(String passName) {} * @param module A module. If null, will return the first SCRIPT node of all modules. * @return A SCRIPT node (never null). */ - abstract Node getNodeForCodeInsertion(@Nullable JSChunk module); + abstract Node getNodeForCodeInsertion(@Nullable JSChunk chunk); abstract TypeValidator getTypeValidator(); diff --git a/src/com/google/javascript/jscomp/AliasStrings.java b/src/com/google/javascript/jscomp/AliasStrings.java index 0be35234e3e..ef76e1255b1 100644 --- a/src/com/google/javascript/jscomp/AliasStrings.java +++ b/src/com/google/javascript/jscomp/AliasStrings.java @@ -55,7 +55,7 @@ class AliasStrings implements CompilerPass, NodeTraversal.Callback { private final AbstractCompiler compiler; - private final JSChunkGraph moduleGraph; + private final JSChunkGraph chunkGraph; private final boolean outputStringUsage; @@ -69,10 +69,10 @@ class AliasStrings implements CompilerPass, NodeTraversal.Callback { private static final int ALIAS_LARGE_STRINGS_LENGTH = 100; /** - * Map from module to the node in that module that should parent any string variable declarations - * that have to be moved into that module + * Map from chunk to the node in that chunk that should parent any string variable declarations + * that have to be moved into that chunk */ - private final Map moduleVarParentMap = new HashMap<>(); + private final Map chunkVarParentMap = new HashMap<>(); /** package private. This value is AND-ed with the hash function to allow * unit tests to reduce the range of hash values to test collision cases */ @@ -82,18 +82,18 @@ class AliasStrings implements CompilerPass, NodeTraversal.Callback { * Creates an instance. * * @param compiler The compiler - * @param moduleGraph The module graph, or null if there are no modules + * @param chunkGraph The module graph, or null if there are no modules * @param outputStringUsage Outputs all strings and the number of times they were used in the * application to the server log. * @param aliasStringsMode The alias strings policy set to either ALL or LARGE */ AliasStrings( AbstractCompiler compiler, - JSChunkGraph moduleGraph, + JSChunkGraph chunkGraph, boolean outputStringUsage, AliasStringsMode aliasStringsMode) { this.compiler = compiler; - this.moduleGraph = moduleGraph; + this.chunkGraph = chunkGraph; this.outputStringUsage = outputStringUsage; this.aliasStringsMode = aliasStringsMode; } @@ -154,26 +154,22 @@ public void visit(NodeTraversal t, Node n, Node parent) { info.occurrences.add(occurrence); - // The current module. - JSChunk module = t.getChunk(); + // The current chunk. + JSChunk chunk = t.getChunk(); if (info.occurrences.size() != 1) { // Check whether the current module depends on the module containing // the declaration. - if (module != null - && info.moduleToContainDecl != null - && module != info.moduleToContainDecl) { + if (chunk != null && info.chunkToContainDecl != null && chunk != info.chunkToContainDecl) { // We need to declare this string in the deepest module in the // module dependency graph that both of these modules depend on. - module = - moduleGraph.getDeepestCommonDependencyInclusive(module, info.moduleToContainDecl); + chunk = chunkGraph.getDeepestCommonDependencyInclusive(chunk, info.chunkToContainDecl); } else { // use the previously saved insertion location. return; } } - Node varParent = - moduleVarParentMap.computeIfAbsent(module, compiler::getNodeForCodeInsertion); - info.moduleToContainDecl = module; + Node varParent = chunkVarParentMap.computeIfAbsent(chunk, compiler::getNodeForCodeInsertion); + info.chunkToContainDecl = chunk; info.parentForNewVarDecl = varParent; info.siblingToInsertVarDeclBefore = varParent.getFirstChild(); } @@ -302,7 +298,7 @@ private final class StringInfo { final ArrayList occurrences = new ArrayList<>(); - JSChunk moduleToContainDecl; + JSChunk chunkToContainDecl; Node parentForNewVarDecl; Node siblingToInsertVarDeclBefore; diff --git a/src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java b/src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java index b4816a1372e..8026c82b41a 100644 --- a/src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java +++ b/src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java @@ -53,7 +53,7 @@ class AnalyzePrototypeProperties implements CompilerPass { private final boolean anchorUnusedVars; private final boolean rootScopeUsesAreGlobal; - private final JSChunkGraph moduleGraph; + private final JSChunkGraph chunkGraph; private final @Nullable JSChunk firstModule; // Properties that are implicitly used as part of the JS language. @@ -100,7 +100,7 @@ class AnalyzePrototypeProperties implements CompilerPass { * Creates a new pass for analyzing prototype properties. * * @param compiler The compiler. - * @param moduleGraph The graph for resolving module dependencies. + * @param chunkGraph The graph for resolving module dependencies. * @param canModifyExterns If true, then we can move prototype properties that are declared in the * externs file. * @param anchorUnusedVars If true, then we must mark all vars as referenced, even if they are @@ -110,18 +110,18 @@ class AnalyzePrototypeProperties implements CompilerPass { */ AnalyzePrototypeProperties( AbstractCompiler compiler, - JSChunkGraph moduleGraph, + JSChunkGraph chunkGraph, boolean canModifyExterns, boolean anchorUnusedVars, boolean rootScopeUsesAreGlobal) { this.compiler = compiler; - this.moduleGraph = moduleGraph; + this.chunkGraph = chunkGraph; this.canModifyExterns = canModifyExterns; this.anchorUnusedVars = anchorUnusedVars; this.rootScopeUsesAreGlobal = rootScopeUsesAreGlobal; - if (moduleGraph.getChunkCount() > 1) { - firstModule = moduleGraph.getRootChunk(); + if (chunkGraph.getChunkCount() > 1) { + firstModule = chunkGraph.getRootChunk(); } else { firstModule = null; } @@ -133,11 +133,11 @@ class AnalyzePrototypeProperties implements CompilerPass { for (String property : IMPLICITLY_USED_PROPERTIES) { NameInfo nameInfo = getNameInfoForName(property, PROPERTY); - if (moduleGraph == null) { + if (chunkGraph == null) { symbolGraph.connect(externNode, null, nameInfo); } else { - for (JSChunk module : moduleGraph.getAllChunks()) { - symbolGraph.connect(externNode, module, nameInfo); + for (JSChunk chunk : chunkGraph.getAllChunks()) { + symbolGraph.connect(externNode, chunk, nameInfo); } } } @@ -402,7 +402,7 @@ public void visit(NodeTraversal t, Node n, Node parent) { } } - private void addSymbolUse(String name, JSChunk module, SymbolType type) { + private void addSymbolUse(String name, JSChunk chunk, SymbolType type) { NameInfo info = getNameInfoForName(name, type); NameInfo def = null; // Skip all anonymous nodes. We care only about symbols with names. @@ -413,7 +413,7 @@ private void addSymbolUse(String name, JSChunk module, SymbolType type) { } } if (!def.equals(info)) { - symbolGraph.connect(def, module, info); + symbolGraph.connect(def, chunk, info); } } @@ -583,8 +583,8 @@ private void processMemberDef(NodeTraversal t, Node n) { return maybeName.isName() ? t.getScope().getVar(maybeName.getString()) : null; } - private void addGlobalUseOfSymbol(String name, JSChunk module, SymbolType type) { - symbolGraph.connect(globalNode, module, getNameInfoForName(name, type)); + private void addGlobalUseOfSymbol(String name, JSChunk chunk, SymbolType type) { + symbolGraph.connect(globalNode, chunk, getNameInfoForName(name, type)); } } @@ -623,7 +623,7 @@ private class PropagateReferences implements EdgeCallback { public boolean traverseEdge(NameInfo start, JSChunk edge, NameInfo dest) { if (start.isReferenced()) { JSChunk startModule = start.getDeepestCommonModuleRef(); - if (startModule != null && moduleGraph.dependsOn(startModule, edge)) { + if (startModule != null && chunkGraph.dependsOn(startModule, edge)) { return dest.markReference(startModule); } else { return dest.markReference(edge); @@ -639,7 +639,7 @@ interface Symbol { Var getRootVar(); /** Returns the module where this appears. */ - JSChunk getModule(); + JSChunk getChunk(); } private enum SymbolType { @@ -653,15 +653,15 @@ private enum SymbolType { */ static class GlobalFunction implements Symbol { private final Var var; - private final JSChunk module; + private final JSChunk chunk; - GlobalFunction(Node nameNode, Var var, JSChunk module) { + GlobalFunction(Node nameNode, Var var, JSChunk chunk) { Node parent = nameNode.getParent(); checkState( (NodeUtil.isNameDeclaration(parent) && var.isGlobal()) || NodeUtil.isFunctionDeclaration(parent)); this.var = var; - this.module = module; + this.chunk = chunk; } @Override @@ -670,8 +670,8 @@ public Var getRootVar() { } @Override - public JSChunk getModule() { - return module; + public JSChunk getChunk() { + return chunk; } } @@ -684,14 +684,14 @@ interface Property extends Symbol {} static class ClassMemberFunction implements Property { private final Node node; private final Var var; - private final JSChunk module; + private final JSChunk chunk; - ClassMemberFunction(Node node, Var var, JSChunk module) { + ClassMemberFunction(Node node, Var var, JSChunk chunk) { checkState(node.getParent().isClassMembers()); checkState(node.isMemberFunctionDef() || node.isSetterDef() || node.isGetterDef()); this.node = node; this.var = var; - this.module = module; + this.chunk = chunk; } @Override @@ -700,8 +700,8 @@ public Var getRootVar() { } @Override - public JSChunk getModule() { - return module; + public JSChunk getChunk() { + return chunk; } /** Returns the function node within the definition. */ @@ -751,13 +751,15 @@ interface PrototypeProperty extends Property { static class AssignmentPrototypeProperty implements PrototypeProperty { private final Node exprNode; private final Var rootVar; - private final JSChunk module; + private final JSChunk chunk; - /** @param node An EXPR node. */ - AssignmentPrototypeProperty(Node node, Var rootVar, JSChunk module) { + /** + * @param node An EXPR node. + */ + AssignmentPrototypeProperty(Node node, Var rootVar, JSChunk chunk) { this.exprNode = node; this.rootVar = rootVar; - this.module = module; + this.chunk = chunk; } @Override @@ -780,8 +782,8 @@ private Node getAssignNode() { } @Override - public JSChunk getModule() { - return module; + public JSChunk getChunk() { + return chunk; } } @@ -795,13 +797,13 @@ static class LiteralPrototypeProperty implements PrototypeProperty { private final Node value; private final Node assign; private final Var rootVar; - private final JSChunk module; + private final JSChunk chunk; - LiteralPrototypeProperty(Node value, Node assign, Var rootVar, JSChunk module) { + LiteralPrototypeProperty(Node value, Node assign, Var rootVar, JSChunk chunk) { this.value = value; this.assign = assign; this.rootVar = rootVar; - this.module = module; + this.chunk = chunk; } @Override @@ -820,8 +822,8 @@ public Node getValue() { } @Override - public JSChunk getModule() { - return module; + public JSChunk getChunk() { + return chunk; } } @@ -849,7 +851,7 @@ class NameInfo { private boolean referenced = false; private final Deque declarations = new ArrayDeque<>(); - private @Nullable JSChunk deepestCommonModuleRef = null; + private @Nullable JSChunk deepestCommonChunkRef = null; // True if this property is a function that reads a variable from an // outer scope which isn't the global scope. @@ -896,23 +898,23 @@ boolean referencesSuper() { * @param module The module where it was referenced. * @return Whether the name info has changed. */ - boolean markReference(@Nullable JSChunk module) { + boolean markReference(@Nullable JSChunk chunk) { boolean hasChanged = false; if (!referenced) { referenced = true; hasChanged = true; } - JSChunk originalDeepestCommon = deepestCommonModuleRef; + JSChunk originalDeepestCommon = deepestCommonChunkRef; - if (deepestCommonModuleRef == null) { - deepestCommonModuleRef = module; + if (deepestCommonChunkRef == null) { + deepestCommonChunkRef = chunk; } else { - deepestCommonModuleRef = - moduleGraph.getDeepestCommonDependencyInclusive(deepestCommonModuleRef, module); + deepestCommonChunkRef = + chunkGraph.getDeepestCommonDependencyInclusive(deepestCommonChunkRef, chunk); } - if (originalDeepestCommon != deepestCommonModuleRef) { + if (originalDeepestCommon != deepestCommonChunkRef) { hasChanged = true; } @@ -921,7 +923,7 @@ boolean markReference(@Nullable JSChunk module) { /** Returns the deepest common module of all the references to this property. */ JSChunk getDeepestCommonModuleRef() { - return deepestCommonModuleRef; + return deepestCommonChunkRef; } /** diff --git a/src/com/google/javascript/jscomp/CheckClosureImports.java b/src/com/google/javascript/jscomp/CheckClosureImports.java index 27d24e1c5c1..d1ed8675511 100644 --- a/src/com/google/javascript/jscomp/CheckClosureImports.java +++ b/src/com/google/javascript/jscomp/CheckClosureImports.java @@ -221,7 +221,7 @@ String callName() { this.compiler = compiler; this.checker = new Checker(compiler, moduleMetadataMap); this.namespacesSeen = new HashSet<>(); - this.chunkGraph = compiler.getModuleGraph(); + this.chunkGraph = compiler.getChunkGraph(); } @Override diff --git a/src/com/google/javascript/jscomp/Compiler.java b/src/com/google/javascript/jscomp/Compiler.java index 97f2ce3dad2..ce55046f4ec 100644 --- a/src/com/google/javascript/jscomp/Compiler.java +++ b/src/com/google/javascript/jscomp/Compiler.java @@ -161,7 +161,7 @@ public class Compiler extends AbstractCompiler implements ErrorHandler, SourceFi private final ArrayList externs = new ArrayList<>(); // The source module graph, denoting dependencies between chunks. - private JSChunkGraph moduleGraph; + private JSChunkGraph chunkGraph; // The module loader for resolving paths into module URIs. private ModuleLoader moduleLoader; @@ -472,11 +472,11 @@ public void printConfig() { logToFile("externs.log", externs::toString); // To get a pretty-printed JSON module graph, change the string generation expression to // - // new GsonBuilder().setPrettyPrinting().create().toJson(moduleGraph.toJson()) + // new GsonBuilder().setPrettyPrinting().create().toJson(chunkGraph.toJson()) // // TODO(bradfordcsmith): Come up with a JSON-printing version that will work when this code is // compiled with J2CL, so we can permanently improve this. - logToFile("inputs.json", () -> Iterables.toString(moduleGraph.getAllInputs())); + logToFile("inputs.json", () -> Iterables.toString(chunkGraph.getAllInputs())); logToFile("options.log", () -> options.toString()); logToFile("warningsGuard.log", () -> warningsGuard.toString()); } else { @@ -488,11 +488,11 @@ public void printConfig() { // To get a pretty-printed JSON module graph, change this line to // // err.println( - // new GsonBuilder().setPrettyPrinting().create().toJson(moduleGraph.toJson())); + // new GsonBuilder().setPrettyPrinting().create().toJson(chunkGraph.toJson())); // // TODO(bradfordcsmith): Come up with a JSON-printing version that will work when this code is // compiled with J2CL, so we can permanently improve this. - err.println(Iterables.toString(moduleGraph.getAllInputs())); + err.println(Iterables.toString(chunkGraph.getAllInputs())); err.println("==== CompilerOptions ===="); err.println(options); err.println("==== WarningsGuard ===="); @@ -608,15 +608,15 @@ public final void initWithTypedAstFilesystem( * @param typedAstListStream a gzipped, binary-serialized TypedAst.List proto */ @GwtIncompatible - public void initModulesWithTypedAstFilesystem( + public void initChunksWithTypedAstFilesystem( List externs, - List modules, + List chunks, CompilerOptions options, InputStream typedAstListStream) { ImmutableSet.Builder filesBuilder = ImmutableSet.builder(); filesBuilder.addAll(externs); - for (JSChunk chunk : modules) { + for (JSChunk chunk : chunks) { for (CompilerInput input : chunk.getInputs()) { filesBuilder.add(input.getSourceFile()); } @@ -626,7 +626,7 @@ public void initModulesWithTypedAstFilesystem( options.setMergedPrecompiledLibraries(true); this.initOptions(options); - this.initModules(externs, modules, options); + this.initChunks(externs, chunks, options); this.mergeAndDeserializeTypedAsts(files, typedAstListStream, options); } @@ -708,32 +708,31 @@ public void initRuntimeLibraryTypedAsts(Optional colorPoolBui /** Initializes the instance state needed for a compile job. */ public final void init( List externs, List sources, CompilerOptions options) { - JSChunk module = new JSChunk(JSChunk.STRONG_CHUNK_NAME); + JSChunk chunk = new JSChunk(JSChunk.STRONG_CHUNK_NAME); for (SourceFile source : sources) { - module.add(new CompilerInput(source, /* isExtern= */ false)); + chunk.add(new CompilerInput(source, /* isExtern= */ false)); } - List modules = new ArrayList<>(1); - modules.add(module); - initModules(externs, modules, options); + List chunks = new ArrayList<>(1); + chunks.add(chunk); + initChunks(externs, chunks, options); addFilesToSourceMap(sources); } /** Initializes the instance state needed for a compile job if the sources are in modules. */ - public void initModules( - List externs, List modules, CompilerOptions options) { + public void initChunks(List externs, List chunks, CompilerOptions options) { initOptions(options); - checkFirstModule(modules); + checkFirstModule(chunks); this.externs.clear(); for (SourceFile file : externs) { this.externs.add(new CompilerInput(file, /* isExtern= */ true)); } - // Generate the module graph, and report any errors in the module specification as errors. + // Generate the chunk graph, and report any errors in the chunk specification as errors. try { - this.moduleGraph = new JSChunkGraph(modules); + this.chunkGraph = new JSChunkGraph(chunks); } catch (ChunkDependenceException e) { // problems with the module format. Report as an error. The // message gives all details. @@ -744,9 +743,9 @@ public void initModules( } // Creating the module graph can move weak source around, and end up with empty modules. - fillEmptyModules(getModules()); + fillEmptyModules(getChunks()); - this.commentsPerFile = new ConcurrentHashMap<>(moduleGraph.getInputCount()); + this.commentsPerFile = new ConcurrentHashMap<>(chunkGraph.getInputCount()); initBasedOnOptions(); initInputsByIdMap(); @@ -755,7 +754,7 @@ public void initModules( if (isDebugLoggingEnabled() || options.printConfig) { // Always print configuration logs when debug logging is enabled. - // NOTE: initModules() is called by every execution path through the compiler code that + // NOTE: initChunks() is called by every execution path through the compiler code that // actually performs a compilation action. That's what makes this a good place to put this // logging. printConfig(); @@ -765,8 +764,8 @@ public void initModules( // This graph is often too big to reasonably render. // Using gvpr(1) is recommended to extract the parts of the graph that are of interest. // `dot -Tpng graph_file.dot > graph_file.png` will render an image. - try (LogFile moduleGraphLog = createOrReopenLog(this.getClass(), "chunk_graph.dot")) { - moduleGraphLog.log(DotFormatter.toDot(moduleGraph.toGraphvizGraph())); + try (LogFile chunkGraphLog = createOrReopenLog(this.getClass(), "chunk_graph.dot")) { + chunkGraphLog.log(DotFormatter.toDot(chunkGraph.toGraphvizGraph())); } } @@ -797,15 +796,15 @@ public void initBasedOnOptions() { "Root module ''{0}'' must contain at least one source code input"); /** - * Verifies that at least one module has been provided and that the first one has at least one + * Verifies that at least one chunk has been provided and that the first one has at least one * source code input. */ - private void checkFirstModule(List modules) { - if (modules.isEmpty()) { + private void checkFirstModule(List chunks) { + if (chunks.isEmpty()) { report(JSError.make(EMPTY_MODULE_LIST_ERROR)); - } else if (modules.get(0).getInputs().isEmpty() && modules.size() > 1) { + } else if (chunks.get(0).getInputs().isEmpty() && chunks.size() > 1) { // The root module may only be empty if there is exactly 1 module. - report(JSError.make(EMPTY_ROOT_MODULE_ERROR, modules.get(0).getName())); + report(JSError.make(EMPTY_ROOT_MODULE_ERROR, chunks.get(0).getName())); } } @@ -814,21 +813,21 @@ public static String joinPathParts(String... pathParts) { return pathJoiner.join(pathParts); } - /** Fill any empty modules with a place holder file. It makes any cross module motion easier. */ - private void fillEmptyModules(Iterable modules) { - for (JSChunk module : modules) { - if (!module.getName().equals(JSChunk.WEAK_CHUNK_NAME) && module.getInputs().isEmpty()) { + /** Fill any empty chunks with a place holder file. It makes any cross chunk motion easier. */ + private void fillEmptyModules(Iterable chunks) { + for (JSChunk chunk : chunks) { + if (!chunk.getName().equals(JSChunk.WEAK_CHUNK_NAME) && chunk.getInputs().isEmpty()) { CompilerInput input = - new CompilerInput(SourceFile.fromCode(createFillFileName(module.getName()), "")); + new CompilerInput(SourceFile.fromCode(createFillFileName(chunk.getName()), "")); input.setCompiler(this); - module.add(input); + chunk.add(input); } } } /** * Rebuilds the internal input map by iterating over all modules. This is necessary if inputs have - * been added to or removed from a module after an {@link #init} or {@link #initModules} call. + * been added to or removed from a module after an {@link #init} or {@link #initChunks} call. */ public void rebuildInputsFromModules() { initInputsByIdMap(); @@ -849,7 +848,7 @@ void initInputsByIdMap() { } } boolean hasZone = false; - for (CompilerInput input : moduleGraph.getAllInputs()) { + for (CompilerInput input : chunkGraph.getAllInputs()) { if (input.getName().endsWith("packages/zone.js/lib/zone.closure.js")) { hasZone = true; } @@ -936,7 +935,7 @@ public void generateReport() { } /** - * Compiles a list of modules. + * Compiles a list of chunks. * *

This is a convenience method to wrap up all the work of compilation, including generating * the error and warning report. @@ -944,13 +943,13 @@ public void generateReport() { *

NOTE: All methods called here must be public, because client code must be able to replicate * and customize this. */ - public Result compileModules( - List externs, List modules, CompilerOptions options) { + public Result compileChunks( + List externs, List chunks, CompilerOptions options) { // The compile method should only be called once. checkState(jsRoot == null); try { - initModules(externs, modules, options); + initChunks(externs, chunks, options); if (!hasErrors()) { parseForCompilation(); } @@ -987,7 +986,7 @@ public Result compileModules( * warnings and errors to stderr. See the invocation in {@link #compile} for a good example. */ public void stage1Passes() { - checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); + checkState(chunkGraph != null, "No inputs. Did you call init() or initChunks()?"); checkState(!hasErrors()); checkState(!options.getInstrumentForCoverageOnly()); runInCompilerThread( @@ -1008,12 +1007,12 @@ public void stage1Passes() { * warnings and errors to stderr. See the invocation in {@link #compile} for a good example. */ public void stage2Passes() { - checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); + checkState(chunkGraph != null, "No inputs. Did you call init() or initChunks()?"); checkState(!hasErrors()); checkState(!options.getInstrumentForCoverageOnly()); - JSChunk weakModule = moduleGraph.getChunkByName(JSChunk.WEAK_CHUNK_NAME); + JSChunk weakModule = chunkGraph.getChunkByName(JSChunk.WEAK_CHUNK_NAME); if (weakModule != null) { - for (CompilerInput i : moduleGraph.getAllInputs()) { + for (CompilerInput i : chunkGraph.getAllInputs()) { if (i.getSourceFile().isWeak()) { checkState( i.getChunk() == weakModule, "Expected all weak files to be in the weak module."); @@ -1040,7 +1039,7 @@ public void stage2Passes() { * warnings and errors to stderr. See the invocation in {@link #compile} for a good example. */ public void stage3Passes() { - checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); + checkState(chunkGraph != null, "No inputs. Did you call init() or initChunks()?"); checkState(!hasErrors()); checkState(!options.getInstrumentForCoverageOnly()); runInCompilerThread( @@ -1135,7 +1134,7 @@ private void performPostCompilationTasksInternal() { * two methods or this one, but not both. */ public void instrumentForCoverage() { - checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); + checkState(chunkGraph != null, "No inputs. Did you call init() or initChunks()?"); checkState(!hasErrors()); runInCompilerThread( () -> { @@ -1162,8 +1161,8 @@ private void instrumentForCoverageInternal(InstrumentOption instrumentForCoverag /** * Parses input files in preparation for compilation. * - *

Either {@code init()} or {@code initModules()} must be called first to set up the input - * files to be read. + *

Either {@code init()} or {@code initChunks()} must be called first to set up the input files + * to be read. * *

TODO(bradfordcsmith): Rename this to parse() */ @@ -1180,8 +1179,8 @@ public void parseForCompilation() { /** * Parses input files in preparation for compilation. * - *

Either {@code init()} or {@code initModules()} must be called first to set up the input - * files to be read. + *

Either {@code init()} or {@code initChunks()} must be called first to set up the input files + * to be read. * *

TODO(bradfordcsmith): Rename this to parse() */ @@ -1194,8 +1193,8 @@ private void parseForCompilationInternal() { /** * Parses input files without doing progress tracking that is part of a full compile. * - *

Either {@code init()} or {@code initModules()} must be called first to set up the input - * files to be read. + *

Either {@code init()} or {@code initChunks()} must be called first to set up the input files + * to be read. * *

TODO(bradfordcsmith): Rename this to parseIndependentOfCompilation() or similar. */ @@ -1413,7 +1412,7 @@ final String getCurrentJsSource() { } } if (!chunkNameRegexList.isEmpty()) { - final Iterable chunks = checkNotNull(getModules()); + final Iterable chunks = checkNotNull(getChunks()); final List unmatchedChunkNames = new ArrayList<>(); // As we are emitting all chunks at once in dependency order, we can be smarter about // deciding which licenses to emit where in the source. @@ -1649,22 +1648,22 @@ private CompilerInput putCompilerInput(CompilerInput input) { /** * Gets the graph of JS source modules. * - *

Returns null if {@code #init} or {@code #initModules} hasn't been called yet. Otherwise, the + *

Returns null if {@code #init} or {@code #initChunks} hasn't been called yet. Otherwise, the * result is always a module graph, even in the degenerate case where there's only one module. */ @Override - @Nullable JSChunkGraph getModuleGraph() { - return moduleGraph; + @Nullable JSChunkGraph getChunkGraph() { + return chunkGraph; } /** * Gets the JS source modules in dependency order. * - *

Returns null if {@code #init} or {@code #initModules} hasn't been called yet. Otherwise, the + *

Returns null if {@code #init} or {@code #initChunks} hasn't been called yet. Otherwise, the * result is always non-empty, even in the degenerate case where there's only one module. */ - public @Nullable Iterable getModules() { - return moduleGraph != null ? moduleGraph.getAllChunks() : null; + public @Nullable Iterable getChunks() { + return chunkGraph != null ? chunkGraph.getAllChunks() : null; } @Override @@ -1878,7 +1877,7 @@ void initializeModuleLoader() { // processJsonInputs requires a module loader to already be defined // so we redefine it afterwards with the package.json inputs moduleResolverFactory = - new NodeModuleResolver.Factory(processJsonInputs(moduleGraph.getAllInputs())); + new NodeModuleResolver.Factory(processJsonInputs(chunkGraph.getAllInputs())); break; case WEBPACK: moduleResolverFactory = new WebpackModuleResolver.Factory(inputPathByWebpackId); @@ -1893,7 +1892,7 @@ void initializeModuleLoader() { this.moduleLoader = ModuleLoader.builder() .setModuleRoots(options.moduleRoots) - .setInputs(moduleGraph.getAllInputs()) + .setInputs(chunkGraph.getAllInputs()) .setFactory(moduleResolverFactory) .setPathResolver(PathResolver.RELATIVE) .setPathEscaper(options.getPathEscaper()) @@ -1951,13 +1950,13 @@ Node parseInputs() { } else if (options.needsTranspilationFrom(FeatureSet.ES2015_MODULES) || options.getProcessCommonJSModules()) { if (options.getLanguageIn().toFeatureSet().has(Feature.MODULES)) { - parsePotentialModules(moduleGraph.getAllInputs()); + parsePotentialModules(chunkGraph.getAllInputs()); } // Build a map of module identifiers for any input which provides no namespace. // These files could be imported modules which have no exports, but do have side effects. Map inputModuleIdentifiers = new LinkedHashMap<>(); - for (CompilerInput input : moduleGraph.getAllInputs()) { + for (CompilerInput input : chunkGraph.getAllInputs()) { if (input.getKnownProvides().isEmpty()) { ModulePath modPath = moduleLoader.resolve(input.getSourceFile().getName()); inputModuleIdentifiers.put(modPath.toModuleName(), input); @@ -1967,7 +1966,7 @@ Node parseInputs() { // Find out if any input attempted to import a module that had no exports. // In this case we must force module rewriting to occur on the imported file Map inputsToRewrite = new LinkedHashMap<>(); - for (CompilerInput input : moduleGraph.getAllInputs()) { + for (CompilerInput input : chunkGraph.getAllInputs()) { for (String require : input.getKnownRequiredSymbols()) { if (inputModuleIdentifiers.containsKey(require) && !inputsToRewrite.containsKey(require)) { @@ -1994,10 +1993,10 @@ Node parseInputs() { // Build the AST. if (options.numParallelThreads > 1) { - new PrebuildAst(this, options.numParallelThreads).prebuild(moduleGraph.getAllInputs()); + new PrebuildAst(this, options.numParallelThreads).prebuild(chunkGraph.getAllInputs()); } - for (CompilerInput input : moduleGraph.getAllInputs()) { + for (CompilerInput input : chunkGraph.getAllInputs()) { Node n = checkNotNull(input.getAstRoot(this)); if (devMode) { runValidityCheck(); @@ -2089,7 +2088,7 @@ void orderInputs() { maybeDoThreadedParsing(); // Before dependency pruning, save a copy of the original inputs to use for externs hoisting. - ImmutableList originalInputs = ImmutableList.copyOf(moduleGraph.getAllInputs()); + ImmutableList originalInputs = ImmutableList.copyOf(chunkGraph.getAllInputs()); // Externs must be marked before dependency management since it needs to know what is an extern. markExterns(originalInputs); @@ -2098,7 +2097,7 @@ void orderInputs() { boolean staleInputs = false; if (options.getDependencyOptions().needsManagement()) { try { - moduleGraph.manageDependencies(this, options.getDependencyOptions()); + chunkGraph.manageDependencies(this, options.getDependencyOptions()); staleInputs = true; } catch (MissingProvideException e) { report(JSError.make(MISSING_ENTRY_ERROR, e.getMessage())); @@ -2109,7 +2108,7 @@ void orderInputs() { hoistExterns(originalInputs); // Manage dependencies may move weak sources around, and end up with empty modules. - fillEmptyModules(getModules()); + fillEmptyModules(getChunks()); hoistNoCompileFiles(); if (staleInputs) { @@ -2133,7 +2132,7 @@ private void findModulesFromEntryPoints( List entryPoints = new ArrayList<>(); Map inputsByProvide = new LinkedHashMap<>(); Map inputsByIdentifier = new LinkedHashMap<>(); - for (CompilerInput input : moduleGraph.getAllInputs()) { + for (CompilerInput input : chunkGraph.getAllInputs()) { Iterable provides = Iterables.filter(input.getProvides(), p -> !p.startsWith("module$")); if (!options.getDependencyOptions().shouldDropMoochers() && Iterables.isEmpty(provides)) { @@ -2156,7 +2155,7 @@ private void findModulesFromEntryPoints( } Set workingInputSet = new LinkedHashSet<>(); - for (CompilerInput input : moduleGraph.getAllInputs()) { + for (CompilerInput input : chunkGraph.getAllInputs()) { workingInputSet.add(input); } for (CompilerInput entryPoint : entryPoints) { @@ -2254,9 +2253,9 @@ private boolean hoistIfExtern(CompilerInput input) { externsRoot.addChildToBack(root); scriptNodeByFilename.put(input.getSourceFile().getName(), root); - JSChunk module = input.getChunk(); - if (module != null) { - module.remove(input); + JSChunk chunk = input.getChunk(); + if (chunk != null) { + chunk.remove(input); } externs.add(input); @@ -2283,7 +2282,7 @@ void hoistNoCompileFiles() { boolean staleInputs = false; maybeDoThreadedParsing(); // Iterate a copy because hoisting modifies what we're iterating over. - for (CompilerInput input : ImmutableList.copyOf(moduleGraph.getAllInputs())) { + for (CompilerInput input : ImmutableList.copyOf(chunkGraph.getAllInputs())) { if (input.getHasNoCompileAnnotation()) { input.getChunk().remove(input); staleInputs = true; @@ -2297,12 +2296,12 @@ void hoistNoCompileFiles() { private void maybeDoThreadedParsing() { if (options.numParallelThreads > 1) { - new PrebuildDependencyInfo(options.numParallelThreads).prebuild(moduleGraph.getAllInputs()); + new PrebuildDependencyInfo(options.numParallelThreads).prebuild(chunkGraph.getAllInputs()); } } private void repartitionInputs() { - fillEmptyModules(getModules()); + fillEmptyModules(getChunks()); rebuildInputsFromModules(); } @@ -2459,30 +2458,30 @@ public String toSource() { } /** - * Converts the parse tree for a module back to JS code. + * Converts the parse tree for a chunk back to JS code. * *

Consider using toSource(JSChunk, LicenseTracker) for better license handling. This call will - * emit all license text attached to all direct inputs to the module, which can be very + * emit all license text attached to all direct inputs to the chunk, which can be very * inefficient. */ - public String toSource(final JSChunk module) { + public String toSource(final JSChunk chunk) { return toSource( // Backwards-compatible implementation of license tracking. - new ScriptNodeLicensesOnlyTracker(this), module); + new ScriptNodeLicensesOnlyTracker(this), chunk); } /** - * Converts the parse tree for a module back to JS code, using the given License Tracker to + * Converts the parse tree for a chunk back to JS code, using the given License Tracker to * determine which licenses should be emitted before the source code. * * @param licenseTracker The license tracker implementation to use. {@link * ChunkGraphAwareLicenseTracker} is a suitable implementation when this method is being - * called on each module in the chunk graph in dependency order. + * called on each chunk in the chunk graph in dependency order. */ - public String toSource(final LicenseTracker licenseTracker, final JSChunk module) { + public String toSource(final LicenseTracker licenseTracker, final JSChunk chunk) { return runInCompilerThread( () -> { - ImmutableList inputs = module.getInputs(); + ImmutableList inputs = chunk.getInputs(); int numInputs = inputs.size(); if (numInputs == 0) { return ""; @@ -2491,7 +2490,7 @@ public String toSource(final LicenseTracker licenseTracker, final JSChunk module for (int i = 0; i < numInputs; i++) { Node scriptNode = inputs.get(i).getAstRoot(Compiler.this); if (scriptNode == null) { - throw new IllegalArgumentException("Bad module: " + module.getName()); + throw new IllegalArgumentException("Bad module: " + chunk.getName()); } toSource(cb, licenseTracker, i, scriptNode); } @@ -2857,10 +2856,10 @@ private CodePrinter.SourceAndMappings toSourceAndMappings( * use it correctly. * @param module the chunk being converted to source. */ - public String[] toSourceArray(LicenseTracker licenseTracker, final JSChunk module) { + public String[] toSourceArray(LicenseTracker licenseTracker, final JSChunk chunk) { return runInCompilerThread( () -> { - ImmutableList inputs = module.getInputs(); + ImmutableList inputs = chunk.getInputs(); int numInputs = inputs.size(); if (numInputs == 0) { return new String[0]; @@ -3493,19 +3492,19 @@ private synchronized void addSourceMapSourceFiles(SourceMapInput inputSourceMap) // ------------------------------------------------------------------------ @Override - protected Node getNodeForCodeInsertion(@Nullable JSChunk module) { + protected Node getNodeForCodeInsertion(@Nullable JSChunk chunk) { if (this.inputsById.containsKey(SYNTHETIC_CODE_INPUT_ID)) { return this.inputsById.get(SYNTHETIC_CODE_INPUT_ID).getAstRoot(this); } - if (module == null) { - if (moduleGraph == null || Iterables.isEmpty(moduleGraph.getAllInputs())) { + if (chunk == null) { + if (chunkGraph == null || Iterables.isEmpty(chunkGraph.getAllInputs())) { throw new IllegalStateException("No inputs"); } - CompilerInput firstInput = Iterables.getFirst(moduleGraph.getAllInputs(), null); + CompilerInput firstInput = Iterables.getFirst(chunkGraph.getAllInputs(), null); return checkNotModule(firstInput.getAstRoot(this), "Cannot insert code into a module"); } - ImmutableList moduleInputs = module.getInputs(); + ImmutableList moduleInputs = chunk.getInputs(); if (!moduleInputs.isEmpty()) { return checkNotModule( moduleInputs.get(0).getAstRoot(this), "Cannot insert code into a module"); @@ -3654,7 +3653,7 @@ public ErrorManager getErrorManager() { @Override Iterable getInputsInOrder() { - return moduleGraph.getAllInputs(); + return chunkGraph.getAllInputs(); } @Override @@ -3663,7 +3662,7 @@ int getNumberOfInputs() { // The intended use of this method is to allow passes to estimate how much memory they will // need for data structures, so it's not necessary that the returned value be exactly right // in the corner cases where inputs ends up being null. - return (moduleGraph != null) ? moduleGraph.getInputCount() : 1; + return (chunkGraph != null) ? chunkGraph.getInputCount() : 1; } /** Returns an unmodifiable view of the compiler inputs indexed by id. */ @@ -3678,7 +3677,7 @@ List getExternsInOrder() { @VisibleForTesting @Nullable List getInputsForTesting() { - return moduleGraph != null ? ImmutableList.copyOf(moduleGraph.getAllInputs()) : null; + return chunkGraph != null ? ImmutableList.copyOf(chunkGraph.getAllInputs()) : null; } @VisibleForTesting @@ -3742,11 +3741,11 @@ void initializeSyntheticCodeInput() { CompilerInput input = new CompilerInput(ast, false); jsRoot.addChildToFront(checkNotNull(ast.getAstRoot(this))); - JSChunk firstModule = Iterables.getFirst(getModules(), null); - if (firstModule.getName().equals(JSChunk.STRONG_CHUNK_NAME)) { - firstModule.add(input); + JSChunk firstChunk = Iterables.getFirst(getChunks(), null); + if (firstChunk.getName().equals(JSChunk.STRONG_CHUNK_NAME)) { + firstChunk.add(input); } - input.setModule(firstModule); + input.setChunk(firstChunk); putCompilerInput(input); commentsPerFile.put(SYNTHETIC_CODE_INPUT_ID.getIdName(), ImmutableList.of()); @@ -3966,7 +3965,7 @@ protected static class CompilerState implements Serializable { private final boolean hasRegExpGlobalReferences; private final LifeCycleStage lifeCycleStage; private final boolean mergedPrecompiledLibraries; - private final JSChunkGraph moduleGraph; + private final JSChunkGraph chunkGraph; private final int uniqueNameId; private final UniqueIdSupplier uniqueIdSupplier; private final LinkedHashSet exportedNames; @@ -3989,7 +3988,7 @@ protected static class CompilerState implements Serializable { this.hasRegExpGlobalReferences = compiler.hasRegExpGlobalReferences; this.lifeCycleStage = compiler.getLifeCycleStage(); this.mergedPrecompiledLibraries = compiler.options.getMergedPrecompiledLibraries(); - this.moduleGraph = compiler.moduleGraph; + this.chunkGraph = compiler.chunkGraph; this.uniqueNameId = compiler.uniqueNameId; this.uniqueIdSupplier = compiler.uniqueIdSupplier; this.exportedNames = compiler.exportedNames; @@ -4000,7 +3999,7 @@ protected static class CompilerState implements Serializable { this.runJ2clPasses = compiler.runJ2clPasses; this.externs = compiler.externs.stream().map(CompilerInput::getInputId).collect(toImmutableList()); - this.moduleToInputList = mapJSModulesToInputIds(compiler.moduleGraph.getAllChunks()); + this.moduleToInputList = mapJSModulesToInputIds(compiler.chunkGraph.getAllChunks()); this.injectedLibraries = compiler.injectedLibraries; this.lastInjectedLibraryIndexInFirstScript = compiler.lastInjectedLibrary != null @@ -4028,7 +4027,7 @@ protected void restoreFromState(CompilerState compilerState) { : compilerState.lifeCycleStage; setLifeCycleStage(stage); getOptions().setMergedPrecompiledLibraries(compilerState.mergedPrecompiledLibraries); - moduleGraph = compilerState.moduleGraph; + chunkGraph = compilerState.chunkGraph; uniqueNameId = compilerState.uniqueNameId; uniqueIdSupplier = compilerState.uniqueIdSupplier; exportedNames.clear(); @@ -4125,11 +4124,11 @@ private void deserializeCompilerState(InputStream inputStream) CompilerState compilerState = (CompilerState) new ObjectInputStream(inputStream).readObject(); checkNotNull( - this.moduleGraph, "Did you forget to call .init or .initModules before restoreState?"); + this.chunkGraph, "Did you forget to call .init or .initChunks before restoreState?"); ImmutableMap.Builder externFilesBuilder = ImmutableMap.builder(); ImmutableMap.Builder codeFilesBuilder = ImmutableMap.builder(); ImmutableSet.Builder allInputFiles = ImmutableSet.builder(); - for (CompilerInput input : this.moduleGraph.getAllInputs()) { + for (CompilerInput input : this.chunkGraph.getAllInputs()) { allInputFiles.add(input.getSourceFile()); codeFilesBuilder.put(input.getInputId().getIdName(), input.getSourceFile()); } @@ -4187,7 +4186,7 @@ private void deserializeCompilerState(InputStream inputStream) this.externs.add(input); } - for (JSChunk deserializedModule : getModules()) { + for (JSChunk deserializedModule : getChunks()) { for (InputId inputId : compilerState.moduleToInputList.get(deserializedModule)) { SourceFile src = codeFiles.get(inputId.getIdName()); if (src == null) { @@ -4304,11 +4303,11 @@ public void resetAndIntitializeSourceMap() { } // Add all the compilation sources to the source map as potential sources - Iterable allModules = getModules(); + Iterable allModules = getChunks(); if (allModules != null) { List sourceFiles = new ArrayList<>(); - for (JSChunk module : allModules) { - for (CompilerInput input : module.getInputs()) { + for (JSChunk chunk : allModules) { + for (CompilerInput input : chunk.getInputs()) { sourceFiles.add(input.getSourceFile()); } } diff --git a/src/com/google/javascript/jscomp/CompilerInput.java b/src/com/google/javascript/jscomp/CompilerInput.java index e50d812e456..53bf36ec6b2 100644 --- a/src/com/google/javascript/jscomp/CompilerInput.java +++ b/src/com/google/javascript/jscomp/CompilerInput.java @@ -52,7 +52,7 @@ public class CompilerInput implements DependencyInfo { private static final long serialVersionUID = 2L; // Info about where the file lives. - private JSChunk module; + private JSChunk chunk; private final InputId id; // The AST. @@ -555,21 +555,21 @@ public String getCode() throws IOException { return getSourceFile().getCode(); } - /** Returns the module to which the input belongs. */ + /** Returns the chunk to which the input belongs. */ public JSChunk getChunk() { - return module; + return chunk; } - /** Sets the module to which the input belongs. */ - public void setModule(JSChunk module) { + /** Sets the chunk to which the input belongs. */ + public void setChunk(JSChunk chunk) { // An input may only belong to one module. - checkArgument(module == null || this.module == null || this.module == module); - this.module = module; + checkArgument(chunk == null || this.chunk == null || this.chunk == chunk); + this.chunk = chunk; } /** Overrides the module to which the input belongs. */ - void overrideModule(JSChunk module) { - this.module = module; + void overrideModule(JSChunk chunk) { + this.chunk = chunk; } public boolean isExtern() { diff --git a/src/com/google/javascript/jscomp/ConvertChunksToESModules.java b/src/com/google/javascript/jscomp/ConvertChunksToESModules.java index 499707b98c9..875f447c1c3 100644 --- a/src/com/google/javascript/jscomp/ConvertChunksToESModules.java +++ b/src/com/google/javascript/jscomp/ConvertChunksToESModules.java @@ -110,7 +110,7 @@ public void process(Node externs, Node root) { // Force every output chunk to parse as an ES Module. If a chunk has no imports and // no exports, add an empty export list to generate an empty export statement: // example: export {}; - for (JSChunk chunk : compiler.getModuleGraph().getAllChunks()) { + for (JSChunk chunk : compiler.getChunkGraph().getAllChunks()) { if (!crossChunkExports.containsKey(chunk) && !crossChunkImports.containsKey(chunk) && !chunk.getInputs().isEmpty()) { @@ -131,7 +131,7 @@ public void process(Node externs, Node root) { * compilation, all input files should be scripts. */ private void convertChunkSourcesToModules() { - for (JSChunk chunk : compiler.getModuleGraph().getAllChunks()) { + for (JSChunk chunk : compiler.getChunkGraph().getAllChunks()) { if (chunk.getInputs().isEmpty()) { continue; } diff --git a/src/com/google/javascript/jscomp/CrossChunkCodeMotion.java b/src/com/google/javascript/jscomp/CrossChunkCodeMotion.java index c61a9d51b66..8a8f55b8223 100644 --- a/src/com/google/javascript/jscomp/CrossChunkCodeMotion.java +++ b/src/com/google/javascript/jscomp/CrossChunkCodeMotion.java @@ -122,7 +122,7 @@ public void process(Node externs, Node root) { private void addInstanceofGuards(Collection globalSymbols) { for (GlobalSymbol globalSymbol : globalSymbols) { for (InstanceofReference instanceofReference : globalSymbol.instanceofReferencesToGuard) { - if (!globalSymbol.declarationsCoverModule(instanceofReference.getModule())) { + if (!globalSymbol.declarationsCoverModule(instanceofReference.getChunk())) { addGuardToInstanceofReference(instanceofReference.getReference().getNode()); } } @@ -154,11 +154,11 @@ Collection collectGlobalSymbols(CrossChunkReferenceCollector refer private void processImmovableStatement(TopLevelStatement statement) { for (Reference ref : statement.getNonDeclarationReferences()) { - processImmovableReference(ref, statement.getModule()); + processImmovableReference(ref, statement.getChunk()); } } - private void processImmovableReference(Reference ref, JSChunk module) { + private void processImmovableReference(Reference ref, JSChunk chunk) { GlobalSymbol globalSymbol = getGlobalSymbol(ref.getSymbol()); if (parentModuleCanSeeSymbolsDeclaredInChildren) { // It is possible to move the declaration of `Foo` after @@ -169,13 +169,13 @@ private void processImmovableReference(Reference ref, JSChunk module) { return; } else if (isUnguardedInstanceofReference(n)) { ImmovableInstanceofReference instanceofReference = - new ImmovableInstanceofReference(module, ref); + new ImmovableInstanceofReference(chunk, ref); globalSymbol.instanceofReferencesToGuard.push(instanceofReference); return; } } - globalSymbol.addImmovableReference(module); + globalSymbol.addImmovableReference(chunk); } private void processDeclarationStatement(TopLevelStatement statement) { @@ -272,24 +272,24 @@ public String toString() { return var.getName(); } - void addImmovableReference(JSChunk module) { - modulesWithImmovableReferences.set(module.getIndex()); + void addImmovableReference(JSChunk chunk) { + modulesWithImmovableReferences.set(chunk.getIndex()); } /** Adds the statement to the appropriate DeclarationStatementGroup and returns it. */ DeclarationStatementGroup addDeclarationStatement(TopLevelStatement statement) { - JSChunk module = statement.getModule(); + JSChunk chunk = statement.getChunk(); DeclarationStatementGroup lastDsg = dsgStack.peek(); if (lastDsg == null) { - lastDsg = new DeclarationStatementGroup(this, module); + lastDsg = new DeclarationStatementGroup(this, chunk); dsgStack.push(lastDsg); } DeclarationStatementGroup statementDsg; - if (module.equals(lastDsg.currentModule)) { + if (chunk.equals(lastDsg.currentChunk)) { statementDsg = lastDsg; } else { // new chunk requires a new DSG - statementDsg = new DeclarationStatementGroup(this, module); + statementDsg = new DeclarationStatementGroup(this, chunk); dsgStack.push(statementDsg); } statementDsg.statementStack.push(statement); @@ -304,9 +304,9 @@ void addReferringGlobalSymbol(GlobalSymbol declaredSymbol) { * Does the chunk depend on at least one of the chunks containing declaration statements for * this symbol? */ - boolean declarationsCoverModule(JSChunk module) { + boolean declarationsCoverModule(JSChunk chunk) { for (DeclarationStatementGroup dsg : dsgStack) { - if (module.equals(dsg.currentModule) || graph.dependsOn(module, dsg.currentModule)) { + if (chunk.equals(dsg.currentChunk) || graph.dependsOn(chunk, dsg.currentChunk)) { return true; } } @@ -336,7 +336,7 @@ void moveDeclarationStatements() { for (GlobalSymbol symbol : symbols) { modulesWithImmovableReferences.or(symbol.modulesWithImmovableReferences); } - dsgCycle.moveToPreferredModule(modulesWithImmovableReferences); + dsgCycle.moveToPreferredChunk(modulesWithImmovableReferences); } for (GlobalSymbol symbol : symbols) { symbol.isMoveDeclarationStatementsDone = true; @@ -348,8 +348,8 @@ List getDsgCyclesLatestFirst() { Deque dsgsLatestFirst = getDsgsLatestFirst(); DeclarationStatementGroupCycle cycle = null; for (DeclarationStatementGroup dsg : dsgsLatestFirst) { - if (cycle == null || !cycle.currentModule.equals(dsg.currentModule)) { - cycle = new DeclarationStatementGroupCycle(this, dsg.currentModule); + if (cycle == null || !cycle.currentChunk.equals(dsg.currentChunk)) { + cycle = new DeclarationStatementGroupCycle(this, dsg.currentChunk); cyclesLatestFirst.add(cycle); } cycle.dsgs.add(dsg); @@ -373,17 +373,17 @@ private Deque getDsgsLatestFirst() { } else { DeclarationStatementGroup dsg1 = stack1.peek(); DeclarationStatementGroup dsg2 = stack2.peek(); - if (dsg1.currentModule.getIndex() > dsg2.currentModule.getIndex()) { + if (dsg1.currentChunk.getIndex() > dsg2.currentChunk.getIndex()) { resultStack.add(stack1.pop()); checkState( stack1.isEmpty() - || stack1.peek().currentModule.getIndex() <= dsg1.currentModule.getIndex(), + || stack1.peek().currentChunk.getIndex() <= dsg1.currentChunk.getIndex(), "DSG stacks are out of order."); } else { resultStack.add(stack2.pop()); checkState( stack2.isEmpty() - || stack2.peek().currentModule.getIndex() <= dsg2.currentModule.getIndex(), + || stack2.peek().currentChunk.getIndex() <= dsg2.currentChunk.getIndex(), "DSG stacks are out of order."); } } @@ -423,14 +423,16 @@ private static class DeclarationStatementGroup { final GlobalSymbol declaredGlobalSymbol; final Set referencedGlobalSymbols = new HashSet<>(); + /** chunk containing the statements */ - JSChunk currentModule; + JSChunk currentChunk; + /** statements in the group, latest first */ final Deque statementStack = new ArrayDeque<>(); - DeclarationStatementGroup(GlobalSymbol declaredGlobalSymbol, JSChunk currentModule) { + DeclarationStatementGroup(GlobalSymbol declaredGlobalSymbol, JSChunk currentChunk) { this.declaredGlobalSymbol = declaredGlobalSymbol; - this.currentModule = currentModule; + this.currentChunk = currentChunk; } boolean allStatementsCanMove() { @@ -447,14 +449,14 @@ void addReferenceToGlobalSymbol(GlobalSymbol refSymbol) { } void makeReferencesImmovable() { - declaredGlobalSymbol.addImmovableReference(currentModule); + declaredGlobalSymbol.addImmovableReference(currentChunk); for (GlobalSymbol symbol : referencedGlobalSymbols) { checkState( !symbol.isMoveDeclarationStatementsDone, "symbol %s moved before referring symbol %s", symbol, declaredGlobalSymbol); - symbol.addImmovableReference(currentModule); + symbol.addImmovableReference(currentChunk); } } } @@ -554,17 +556,17 @@ void processGlobalSymbol(GlobalSymbol symbol) { * symbols refer to each other. */ private class DeclarationStatementGroupCycle { - final JSChunk currentModule; + final JSChunk currentChunk; final Deque dsgs; - DeclarationStatementGroupCycle(GlobalSymbolCycle globalSymbolCycle, JSChunk currentModule) { - this.currentModule = currentModule; + DeclarationStatementGroupCycle(GlobalSymbolCycle globalSymbolCycle, JSChunk currentChunk) { + this.currentChunk = currentChunk; this.dsgs = new ArrayDeque<>(); } - void moveToPreferredModule(BitSet modulesWithImmovableReferences) { - JSChunk preferredModule = getPreferredModule(modulesWithImmovableReferences); - if (!preferredModule.equals(currentModule)) { + void moveToPreferredChunk(BitSet modulesWithImmovableReferences) { + JSChunk preferredChunk = getPreferredChunk(modulesWithImmovableReferences); + if (!preferredChunk.equals(currentChunk)) { if (cccmLog.isLogging()) { // Write a separate log for each global symbol, because this is easier to work // with when analyzing the log. @@ -575,15 +577,15 @@ void moveToPreferredModule(BitSet modulesWithImmovableReferences) { () -> SimpleFormat.format( "Moving DSG for %s from chunk %s to chunk %s", - globalSymbolName, currentModule, preferredModule)); + globalSymbolName, currentChunk, preferredChunk)); } } - moveStatementsToModule(preferredModule); + moveStatementsToModule(preferredChunk); } // Now that all the statements have been moved, update the current chunk for all the DSGs // and treat all the references they contain as now immovable. for (DeclarationStatementGroup dsg : dsgs) { - dsg.currentModule = preferredModule; + dsg.currentChunk = preferredChunk; dsg.makeReferencesImmovable(); } } @@ -596,10 +598,10 @@ private ImmutableList getGlobalSymbolNames() { return builder.build(); } - private void moveStatementsToModule(JSChunk preferredModule) { + private void moveStatementsToModule(JSChunk preferredChunk) { Node destParent = moduleInsertionPointMap.computeIfAbsent( - preferredModule, compiler::getNodeForCodeInsertion); + preferredChunk, compiler::getNodeForCodeInsertion); Deque statementsLastFirst = getStatementsLastFirst(); for (TopLevelStatement statement : statementsLastFirst) { Node statementNode = statement.getStatementNode(); @@ -652,13 +654,13 @@ private Deque getStatementsLastFirst() { return result; } - private JSChunk getPreferredModule(BitSet modulesWithImmovableReferences) { + private JSChunk getPreferredChunk(BitSet modulesWithImmovableReferences) { if (modulesWithImmovableReferences.isEmpty()) { - return currentModule; + return currentChunk; } else if (!allStatementsCanMove()) { - return currentModule; + return currentChunk; } else { - return graph.getSmallestCoveringSubtree(currentModule, modulesWithImmovableReferences); + return graph.getSmallestCoveringSubtree(currentChunk, modulesWithImmovableReferences); } } @@ -673,23 +675,23 @@ boolean allStatementsCanMove() { } interface InstanceofReference { - JSChunk getModule(); + JSChunk getChunk(); Reference getReference(); } private static class ImmovableInstanceofReference implements InstanceofReference { - final JSChunk module; + final JSChunk chunk; final Reference reference; - ImmovableInstanceofReference(JSChunk module, Reference reference) { - this.module = module; + ImmovableInstanceofReference(JSChunk chunk, Reference reference) { + this.chunk = chunk; this.reference = reference; } @Override - public JSChunk getModule() { - return module; + public JSChunk getChunk() { + return chunk; } @Override @@ -708,8 +710,8 @@ private static class MovableInstanceofReference implements InstanceofReference { } @Override - public JSChunk getModule() { - return containingDsg.currentModule; + public JSChunk getChunk() { + return containingDsg.currentChunk; } @Override diff --git a/src/com/google/javascript/jscomp/CrossChunkMethodMotion.java b/src/com/google/javascript/jscomp/CrossChunkMethodMotion.java index 270361abcaa..c90bad9cde1 100644 --- a/src/com/google/javascript/jscomp/CrossChunkMethodMotion.java +++ b/src/com/google/javascript/jscomp/CrossChunkMethodMotion.java @@ -35,14 +35,13 @@ public class CrossChunkMethodMotion implements CompilerPass { // Internal errors - static final DiagnosticType NULL_COMMON_MODULE_ERROR = DiagnosticType.error( - "JSC_INTERNAL_ERROR_MODULE_DEPEND", - "null deepest common module"); + static final DiagnosticType NULL_COMMON_MODULE_ERROR = + DiagnosticType.error("JSC_INTERNAL_ERROR_MODULE_DEPEND", "null deepest common module"); private final AbstractCompiler compiler; private final IdGenerator idGenerator; private final AnalyzePrototypeProperties analyzer; - private final JSChunkGraph moduleGraph; + private final JSChunkGraph chunkGraph; private final boolean noStubFunctions; private final AstFactory astFactory; @@ -71,8 +70,7 @@ public class CrossChunkMethodMotion implements CompilerPass { * @param idGenerator An id generator for method stubs. * @param canModifyExterns If true, then we can move prototype properties that are declared in the * externs file. - * @param noStubFunctions if true, we can move methods without stub functions in the parent - * chunk. + * @param noStubFunctions if true, we can move methods without stub functions in the parent chunk. */ CrossChunkMethodMotion( AbstractCompiler compiler, @@ -81,14 +79,10 @@ public class CrossChunkMethodMotion implements CompilerPass { boolean noStubFunctions) { this.compiler = compiler; this.idGenerator = idGenerator; - this.moduleGraph = compiler.getModuleGraph(); + this.chunkGraph = compiler.getChunkGraph(); this.analyzer = new AnalyzePrototypeProperties( - compiler, - moduleGraph, - canModifyExterns, - /* anchorUnusedVars= */ false, - noStubFunctions); + compiler, chunkGraph, canModifyExterns, /* anchorUnusedVars= */ false, noStubFunctions); this.noStubFunctions = noStubFunctions; this.astFactory = compiler.createAstFactory(); } @@ -97,15 +91,13 @@ public class CrossChunkMethodMotion implements CompilerPass { public void process(Node externRoot, Node root) { // If there are < 2 chunks, then we will never move anything, // so we're done. - if (moduleGraph.getChunkCount() > 1) { + if (chunkGraph.getChunkCount() > 1) { analyzer.process(externRoot, root); moveMethods(analyzer.getAllNameInfo()); } } - /** - * Move methods deeper in the chunk graph when possible. - */ + /** Move methods deeper in the chunk graph when possible. */ private void moveMethods(Collection allNameInfo) { boolean hasStubDeclaration = idGenerator.hasGeneratedAnyIds(); for (NameInfo nameInfo : allNameInfo) { @@ -126,8 +118,7 @@ private void moveMethods(Collection allNameInfo) { continue; } - Iterator declarations = - nameInfo.getDeclarations().descendingIterator(); + Iterator declarations = nameInfo.getDeclarations().descendingIterator(); while (declarations.hasNext()) { Symbol symbol = declarations.next(); if (symbol instanceof PrototypeProperty) { @@ -138,8 +129,7 @@ private void moveMethods(Collection allNameInfo) { } } - if (!noStubFunctions && !hasStubDeclaration && idGenerator - .hasGeneratedAnyIds()) { + if (!noStubFunctions && !hasStubDeclaration && idGenerator.hasGeneratedAnyIds()) { // Declare stub functions in the top-most chunk. Node declarations = compiler.parseSyntheticCode("chunk_method_stubbing", STUB_DECLARATIONS); NodeUtil.markNewScopesChanged(declarations, compiler); @@ -190,7 +180,7 @@ private void tryToMovePrototypeMethod( return; } - if (moduleGraph.dependsOn(deepestCommonModuleRef, prop.getModule())) { + if (chunkGraph.dependsOn(deepestCommonModuleRef, prop.getChunk())) { if (hasUnmovableRedeclaration(nameInfo, prop)) { // If it has been redeclared on the same object, skip it. return; @@ -466,7 +456,7 @@ private void tryToMoveMemberFunction( return; } - if (moduleGraph.dependsOn(deepestCommonModuleRef, classMemberFunction.getModule())) { + if (chunkGraph.dependsOn(deepestCommonModuleRef, classMemberFunction.getChunk())) { if (hasUnmovableRedeclaration(nameInfo, classMemberFunction)) { // If it has been redeclared on the same object, skip it. return; @@ -571,7 +561,7 @@ static boolean hasUnmovableRedeclaration(NameInfo nameInfo, Property prop) { // worth the effort to check. if (prop != otherProp && prop.getRootVar() == otherProp.getRootVar() - && prop.getModule() != otherProp.getModule()) { + && prop.getChunk() != otherProp.getChunk()) { return true; } } diff --git a/src/com/google/javascript/jscomp/CrossChunkReferenceCollector.java b/src/com/google/javascript/jscomp/CrossChunkReferenceCollector.java index e2311de3470..533d079a97d 100644 --- a/src/com/google/javascript/jscomp/CrossChunkReferenceCollector.java +++ b/src/com/google/javascript/jscomp/CrossChunkReferenceCollector.java @@ -169,9 +169,9 @@ public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { return true; } - private TopLevelStatementDraft initializeDraftStatement(JSChunk module, Node statementNode) { + private TopLevelStatementDraft initializeDraftStatement(JSChunk chunk, Node statementNode) { TopLevelStatementDraft draft = - new TopLevelStatementDraft(statementCounter++, module, statementNode); + new TopLevelStatementDraft(statementCounter++, chunk, statementNode); // Determine whether this statement declares a name or not. // If so, save its name node and value node, if any. if (NodeUtil.isNameDeclaration(statementNode)) { @@ -452,7 +452,7 @@ final class TopLevelStatement { /** 0-based index indicating original order of this statement in the source. */ private final int originalOrder; - private final JSChunk module; + private final JSChunk chunk; private final Node statementNode; private final List nonDeclarationReferences; private final Reference declaredNameReference; @@ -460,7 +460,7 @@ final class TopLevelStatement { TopLevelStatement(TopLevelStatementDraft draft) { this.originalOrder = draft.originalOrder; - this.module = draft.module; + this.chunk = draft.chunk; this.statementNode = draft.statementNode; this.nonDeclarationReferences = Collections.unmodifiableList(draft.nonDeclarationReferences); this.declaredNameReference = draft.declaredNameReference; @@ -471,8 +471,8 @@ int getOriginalOrder() { return originalOrder; } - JSChunk getModule() { - return module; + JSChunk getChunk() { + return chunk; } Node getStatementNode() { @@ -508,16 +508,16 @@ private static final class TopLevelStatementDraft { /** 0-based index indicating original order of this statement in the source. */ final int originalOrder; - final JSChunk module; + final JSChunk chunk; final Node statementNode; final List nonDeclarationReferences = new ArrayList<>(); @Nullable Node declaredValueNode = null; @Nullable Node declaredNameNode = null; @Nullable Reference declaredNameReference = null; - TopLevelStatementDraft(int originalOrder, JSChunk module, Node statementNode) { + TopLevelStatementDraft(int originalOrder, JSChunk chunk, Node statementNode) { this.originalOrder = originalOrder; - this.module = module; + this.chunk = chunk; this.statementNode = statementNode; } } diff --git a/src/com/google/javascript/jscomp/DefaultPassConfig.java b/src/com/google/javascript/jscomp/DefaultPassConfig.java index 5219ebf83a7..63d5af27305 100644 --- a/src/com/google/javascript/jscomp/DefaultPassConfig.java +++ b/src/com/google/javascript/jscomp/DefaultPassConfig.java @@ -2376,7 +2376,7 @@ public void process(Node externs, Node root) { (compiler) -> new CrossChunkCodeMotion( compiler, - compiler.getModuleGraph(), + compiler.getChunkGraph(), options.parentChunkCanSeeSymbolsDeclaredInChildren)) .build(); @@ -2483,7 +2483,7 @@ compiler, PassNames.EXPLOIT_ASSIGN, new ExploitAssigns())) (compiler) -> new AliasStrings( compiler, - compiler.getModuleGraph(), + compiler.getChunkGraph(), options.outputJsStringUsage, options.getAliasStringsMode())) .build(); diff --git a/src/com/google/javascript/jscomp/DevirtualizeMethods.java b/src/com/google/javascript/jscomp/DevirtualizeMethods.java index 6680c55facb..9c336f76af7 100644 --- a/src/com/google/javascript/jscomp/DevirtualizeMethods.java +++ b/src/com/google/javascript/jscomp/DevirtualizeMethods.java @@ -360,14 +360,14 @@ private boolean isEligibleCallSite(Node access, Node definitionSite) { // - Rewriting all call-sites in a way that preserves exact ordering (e.g. using // `ExpressionDecomposer`) has a significant code-size impact (circa 2018-11-19). - JSChunkGraph moduleGraph = compiler.getModuleGraph(); - @Nullable JSChunk definitionModule = moduleForNode(definitionSite); - @Nullable JSChunk callModule = moduleForNode(access); + JSChunkGraph chunkGraph = compiler.getChunkGraph(); + @Nullable JSChunk definitionModule = chunkForNode(definitionSite); + @Nullable JSChunk callModule = chunkForNode(access); if (definitionModule == callModule) { // Do nothing. } else if (callModule == null) { return false; - } else if (!moduleGraph.dependsOn(callModule, definitionModule)) { + } else if (!chunkGraph.dependsOn(callModule, definitionModule)) { return false; } @@ -508,7 +508,7 @@ private void replaceReferencesToThis(Node node, String name) { } } - private @Nullable JSChunk moduleForNode(Node node) { + private @Nullable JSChunk chunkForNode(Node node) { Node script = NodeUtil.getEnclosingScript(node); CompilerInput input = compiler.getInput(script.getInputId()); return input.getChunk(); diff --git a/src/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarations.java b/src/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarations.java index 45c27c8c716..16b32333689 100644 --- a/src/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarations.java +++ b/src/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarations.java @@ -178,13 +178,13 @@ private void maybeDoExtraction(GatherExtractionInfo info) { compiler.reportChangeToEnclosingScope(var); } // Go through all extraction instances and extract each of them. - for (Map.Entry entry : info.instancesByModule.entrySet()) { + for (Map.Entry entry : info.instancesByChunk.entrySet()) { String alias = PROTOTYPE_ALIAS; if (pattern == Pattern.USE_CHUNK_TEMP) { // Rather than a truly global variable, use a unique variable per output chunk. // This prevents RescopeGlobalSymbolNames from converting these references to // namespace properties which reduces the benefit of the alias. - if (info.shouldExtractModule(entry.getKey())) { + if (info.shouldExtractChunk(entry.getKey())) { Node injectionPoint = compiler.getNodeForCodeInsertion(entry.getKey()); alias = PROTOTYPE_ALIAS + entry.getKey().getIndex(); Node var = NodeUtil.newVarNode(alias, null).srcrefTreeIfMissing(injectionPoint); @@ -276,7 +276,7 @@ private static class ExtractionInstanceInfo { /** Collects all the possible extraction instances in a node traversal. */ private class GatherExtractionInfo extends AbstractShallowCallback { - private final Map instancesByModule = new HashMap<>(); + private final Map instancesByChunk = new HashMap<>(); @Override public void visit(NodeTraversal t, Node n, Node parent) { @@ -299,9 +299,9 @@ public void visit(NodeTraversal t, Node n, Node parent) { // Only add it to our work list if the extraction at this instance makes the code smaller. if (instance.isFavorable()) { - instancesByModule.computeIfAbsent( + instancesByChunk.computeIfAbsent( t.getChunk(), (JSChunk k) -> new ExtractionInstanceInfo()); - ExtractionInstanceInfo instanceInfo = instancesByModule.get(t.getChunk()); + ExtractionInstanceInfo instanceInfo = instancesByChunk.get(t.getChunk()); instanceInfo.instances.add(instance); instanceInfo.totalDelta += instance.delta; } @@ -314,7 +314,7 @@ public void visit(NodeTraversal t, Node n, Node parent) { */ private boolean shouldExtractGlobal() { int allModulesDelta = 0; - for (ExtractionInstanceInfo instanceInfo : instancesByModule.values()) { + for (ExtractionInstanceInfo instanceInfo : instancesByChunk.values()) { allModulesDelta += instanceInfo.totalDelta; } return allModulesDelta + pattern.globalOverhead < 0; @@ -324,8 +324,8 @@ private boolean shouldExtractGlobal() { * @return {@code true} if the sum of all the extraction instance gain outweighs the overhead of * the temp variable declaration. */ - private boolean shouldExtractModule(JSChunk module) { - ExtractionInstanceInfo instanceInfo = instancesByModule.get(module); + private boolean shouldExtractChunk(JSChunk chunk) { + ExtractionInstanceInfo instanceInfo = instancesByChunk.get(chunk); if (instanceInfo == null) { return false; } diff --git a/src/com/google/javascript/jscomp/FunctionInjector.java b/src/com/google/javascript/jscomp/FunctionInjector.java index d93cd465f39..3f9f1b99e68 100644 --- a/src/com/google/javascript/jscomp/FunctionInjector.java +++ b/src/com/google/javascript/jscomp/FunctionInjector.java @@ -169,13 +169,13 @@ enum InliningMode { static class Reference { final Node callNode; final Scope scope; - final JSChunk module; + final JSChunk chunk; final InliningMode mode; - Reference(Node callNode, Scope scope, JSChunk module, InliningMode mode) { + Reference(Node callNode, Scope scope, JSChunk chunk, InliningMode mode) { this.callNode = callNode; this.scope = scope; - this.module = module; + this.chunk = chunk; this.mode = mode; } @@ -901,7 +901,7 @@ private CanInlineResult canInlineReferenceDirectly( /** Determine if inlining the function is likely to reduce the code size. */ boolean inliningLowersCost( - JSChunk fnModule, + JSChunk fnChunk, Node fnNode, Collection refs, Set namesToAlias, @@ -914,8 +914,8 @@ boolean inliningLowersCost( int referencesUsingBlockInlining = 0; - boolean checkModules = isRemovable && fnModule != null; - JSChunkGraph moduleGraph = compiler.getModuleGraph(); + boolean checkModules = isRemovable && fnChunk != null; + JSChunkGraph chunkGraph = compiler.getChunkGraph(); for (Reference ref : refs) { if (ref.mode == InliningMode.BLOCK) { @@ -923,8 +923,8 @@ boolean inliningLowersCost( } // Check if any of the references cross the module boundaries. - if (checkModules && ref.module != null) { - if (ref.module != fnModule && !moduleGraph.dependsOn(ref.module, fnModule)) { + if (checkModules && ref.chunk != null) { + if (ref.chunk != fnChunk && !chunkGraph.dependsOn(ref.chunk, fnChunk)) { // Calculate the cost as if the function were non-removable, // if it still lowers the cost inline it. isRemovable = false; diff --git a/src/com/google/javascript/jscomp/InlineFunctions.java b/src/com/google/javascript/jscomp/InlineFunctions.java index 4a78f2b6f96..3da939aefb7 100644 --- a/src/com/google/javascript/jscomp/InlineFunctions.java +++ b/src/com/google/javascript/jscomp/InlineFunctions.java @@ -259,7 +259,7 @@ public void findFunctionExpressions(NodeTraversal t, Node n) { * Updates the FunctionState object for the given function. Checks if the given function matches * the criteria for an inlinable function. */ - void maybeAddFunction(Function fn, JSChunk module) { + void maybeAddFunction(Function fn, JSChunk chunk) { String name = fn.getName(); FunctionState functionState = getOrCreateFunctionState(name); @@ -306,7 +306,7 @@ void maybeAddFunction(Function fn, JSChunk module) { // Set the module and gather names that need temporaries. if (functionState.canInline()) { - functionState.setModule(module); + functionState.setChunk(chunk); Set namesToAlias = functionArgumentInjector.findModifiedParameters(fnNode); if (!namesToAlias.isEmpty()) { @@ -513,19 +513,19 @@ public void visitCallSite(NodeTraversal t, Node callNode, FunctionState function } void maybeAddReference( - NodeTraversal t, FunctionState functionState, Node callNode, JSChunk module) { + NodeTraversal t, FunctionState functionState, Node callNode, JSChunk chunk) { if (!functionState.canInline()) { return; } InliningMode mode = functionState.canInlineDirectly() ? InliningMode.DIRECT : InliningMode.BLOCK; - boolean referenceAdded = maybeAddReferenceUsingMode(t, functionState, callNode, module, mode); + boolean referenceAdded = maybeAddReferenceUsingMode(t, functionState, callNode, chunk, mode); if (!referenceAdded && mode == InliningMode.DIRECT) { // This reference can not be directly inlined, see if // block replacement inlining is possible. mode = InliningMode.BLOCK; - referenceAdded = maybeAddReferenceUsingMode(t, functionState, callNode, module, mode); + referenceAdded = maybeAddReferenceUsingMode(t, functionState, callNode, chunk, mode); } if (!referenceAdded) { @@ -539,7 +539,7 @@ private boolean maybeAddReferenceUsingMode( NodeTraversal t, FunctionState functionState, Node callNode, - JSChunk module, + JSChunk chunk, InliningMode mode) { // If many functions are inlined into the same function F in the same @@ -552,7 +552,7 @@ private boolean maybeAddReferenceUsingMode( return false; } - Reference candidate = new Reference(callNode, t.getScope(), module, mode); + Reference candidate = new Reference(callNode, t.getScope(), chunk, mode); CanInlineResult result = injector.canInlineReferenceToFunction( candidate, @@ -698,7 +698,7 @@ private boolean minimizeCost(FunctionState functionState) { */ private boolean inliningLowersCost(FunctionState functionState) { return injector.inliningLowersCost( - functionState.getModule(), + functionState.getChunk(), functionState.getFn().getFunctionNode(), functionState.getReferences(), functionState.getNamesToAlias(), @@ -848,7 +848,7 @@ private static class FunctionState { private boolean referencesThis = false; private boolean hasInnerFunctions = false; private @Nullable Map references = null; - private @Nullable JSChunk module = null; + private @Nullable JSChunk chunk = null; private @Nullable Set namesToAlias = null; boolean hasExistingFunctionDefinition() { @@ -973,12 +973,12 @@ public void setNamesToAlias(Set names) { namesToAlias = names; } - public void setModule(JSChunk module) { - this.module = module; + public void setChunk(JSChunk chunk) { + this.chunk = chunk; } - public JSChunk getModule() { - return module; + public JSChunk getChunk() { + return chunk; } } @@ -1115,8 +1115,8 @@ static class Reference extends FunctionInjector.Reference { boolean requiresDecomposition = false; boolean inlined = false; - Reference(Node callNode, Scope scope, JSChunk module, InliningMode mode) { - super(callNode, scope, module, mode); + Reference(Node callNode, Scope scope, JSChunk chunk, InliningMode mode) { + super(callNode, scope, chunk, mode); } void setRequiresDecomposition(boolean newVal) { diff --git a/src/com/google/javascript/jscomp/JSChunk.java b/src/com/google/javascript/jscomp/JSChunk.java index be25c3fc123..84a263bab13 100644 --- a/src/com/google/javascript/jscomp/JSChunk.java +++ b/src/com/google/javascript/jscomp/JSChunk.java @@ -152,7 +152,7 @@ public void add(CompilerInput input) { checkArgument( !inputs.containsKey(inputName), "%s already exist in chunk %s", inputName, this.getName()); inputs.put(inputName, input); - input.setModule(this); + input.setChunk(this); } /** @@ -176,14 +176,14 @@ public void addDependency(JSChunk dep) { /** Removes an input from this chunk. */ public void remove(CompilerInput input) { - input.setModule(null); + input.setChunk(null); inputs.remove(input.getName()); } /** Removes all of the inputs from this chunk. */ public void removeAll() { for (CompilerInput input : inputs.values()) { - input.setModule(null); + input.setChunk(null); } inputs.clear(); } diff --git a/src/com/google/javascript/jscomp/JSChunkGraph.java b/src/com/google/javascript/jscomp/JSChunkGraph.java index a5072ec14ee..5f78ce438ea 100644 --- a/src/com/google/javascript/jscomp/JSChunkGraph.java +++ b/src/com/google/javascript/jscomp/JSChunkGraph.java @@ -613,10 +613,10 @@ public ImmutableList manageDependencies( } JSChunk oldChunk = input.getChunk(); if (oldChunk == null) { - input.setModule(chunk); + input.setChunk(chunk); } else { - input.setModule(null); - input.setModule(getDeepestCommonDependencyInclusive(oldChunk, chunk)); + input.setChunk(null); + input.setChunk(getDeepestCommonDependencyInclusive(oldChunk, chunk)); } } } @@ -635,7 +635,7 @@ public ImmutableList manageDependencies( // in command line flag order. checkState(i.getChunk() == null); i.getSourceFile().setKind(SourceKind.WEAK); - i.setModule(weakChunk); + i.setChunk(weakChunk); weakChunk.add(i); } } else { diff --git a/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java b/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java index 759007c0ac7..c767a917b4b 100644 --- a/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java +++ b/src/com/google/javascript/jscomp/ProcessClosureProvidesAndRequires.java @@ -75,7 +75,7 @@ class ProcessClosureProvidesAndRequires implements CompilerPass { AbstractCompiler compiler, boolean preserveGoogProvidesAndRequires) { this.compiler = compiler; - this.chunkGraph = compiler.getModuleGraph(); + this.chunkGraph = compiler.getChunkGraph(); this.preserveGoogProvidesAndRequires = preserveGoogProvidesAndRequires; this.astFactory = compiler.createAstFactory(); } @@ -401,20 +401,20 @@ private boolean verifyOnlyArgumentIsString(Node call) { * @param node The EXPR of the provide call. * @param module The current module. */ - private void registerAnyProvidedPrefixes(String ns, Node node, JSChunk module) { + private void registerAnyProvidedPrefixes(String ns, Node node, JSChunk chunk) { int pos = ns.indexOf('.'); while (pos != -1) { String prefixNs = ns.substring(0, pos); pos = ns.indexOf('.', pos + 1); if (providedNames.containsKey(prefixNs)) { - providedNames.get(prefixNs).addProvide(node, module, /* explicit= */ false, chunkGraph); + providedNames.get(prefixNs).addProvide(node, chunk, /* explicit= */ false, chunkGraph); } else { providedNames.put( prefixNs, new ProvidedNameBuilder() .setNamespace(prefixNs) .setNode(node) - .setChunk(module) + .setChunk(chunk) .setExplicit(false) .build()); } @@ -632,7 +632,7 @@ String getNamespace() { *

This pass gives preference to declarations. If no declaration exists, records a reference * to an assignment so it can be repurposed later into a declaration. */ - private void addDefinition(Node node, JSChunk module, JSChunkGraph chunkGraph) { + private void addDefinition(Node node, JSChunk chunk, JSChunkGraph chunkGraph) { Preconditions.checkArgument( node.isExprResult() // assign || node.isFunction() @@ -640,7 +640,7 @@ private void addDefinition(Node node, JSChunk module, JSChunkGraph chunkGraph) { checkArgument(explicitNode != node); if ((candidateDefinition == null) || !node.isExprResult()) { candidateDefinition = node; - updateMinimumChunk(module, chunkGraph); + updateMinimumChunk(chunk, chunkGraph); } } diff --git a/src/com/google/javascript/jscomp/RescopeGlobalSymbols.java b/src/com/google/javascript/jscomp/RescopeGlobalSymbols.java index 08eb4e9090b..48e47ff225d 100644 --- a/src/com/google/javascript/jscomp/RescopeGlobalSymbols.java +++ b/src/com/google/javascript/jscomp/RescopeGlobalSymbols.java @@ -39,13 +39,13 @@ * *

 NS.a = 1; NS.b = function b() { return NS.a }
* - * This allows splitting code into modules that depend on each other's global symbols, without using + * This allows splitting code into chunks that depend on each other's global symbols, without using * polluting JavaScript's global scope with those symbols. You typically define just a single global - * symbol, wrap each module in a function wrapper, and pass the global symbol around, eg, + * symbol, wrap each chunk in a function wrapper, and pass the global symbol around, eg, * *
 var uniqueNs = uniqueNs || {}; 
* - *
 (function (NS) { ...your module code here... })(uniqueNs); 
+ *
 (function (NS) { ...your chunk code here... })(uniqueNs); 
* *

This compile step requires rewriteGlobalDeclarationsForTryCatchWrapping to be turned on to * guarantee semantics. @@ -60,8 +60,9 @@ final class RescopeGlobalSymbols implements CompilerPass { private final AbstractCompiler compiler; private final String globalSymbolNamespace; private final boolean addExtern; - private final boolean assumeCrossModuleNames; - private final Set crossModuleNames = new HashSet<>(); + private final boolean assumeCrossChunkNames; + private final Set crossChunkNames = new HashSet<>(); + /** Global identifiers that may be a non-arrow function referencing "this" */ private final Set maybeReferencesThis = new HashSet<>(); @@ -71,44 +72,38 @@ final class RescopeGlobalSymbols implements CompilerPass { * Constructor for the RescopeGlobalSymbols compiler pass. * * @param compiler The JSCompiler, for reporting code changes. - * @param globalSymbolNamespace Name of namespace into which all global - * symbols are transferred. - * @param assumeCrossModuleNames If true, all global symbols will be assumed - * cross module boundaries and thus require renaming. + * @param globalSymbolNamespace Name of namespace into which all global symbols are transferred. + * @param assumeCrossChunkNames If true, all global symbols will be assumed cross chunk boundaries + * and thus require renaming. */ RescopeGlobalSymbols( - AbstractCompiler compiler, - String globalSymbolNamespace, - boolean assumeCrossModuleNames) { - this(compiler, globalSymbolNamespace, true, assumeCrossModuleNames); + AbstractCompiler compiler, String globalSymbolNamespace, boolean assumeCrossChunkNames) { + this(compiler, globalSymbolNamespace, true, assumeCrossChunkNames); } /** * Constructor for the RescopeGlobalSymbols compiler pass for use in testing. * * @param compiler The JSCompiler, for reporting code changes. - * @param globalSymbolNamespace Name of namespace into which all global - * symbols are transferred. - * @param addExtern If true, the compiler will consider the - * globalSymbolNamespace an extern name. - * @param assumeCrossModuleNames If true, all global symbols will be assumed - * cross module boundaries and thus require renaming. - * VisibleForTesting + * @param globalSymbolNamespace Name of namespace into which all global symbols are transferred. + * @param addExtern If true, the compiler will consider the globalSymbolNamespace an extern name. + * @param assumeCrossChunkNames If true, all global symbols will be assumed cross chunk boundaries + * and thus require renaming. VisibleForTesting */ RescopeGlobalSymbols( AbstractCompiler compiler, String globalSymbolNamespace, boolean addExtern, - boolean assumeCrossModuleNames) { + boolean assumeCrossChunkNames) { this.compiler = compiler; this.globalSymbolNamespace = globalSymbolNamespace; this.addExtern = addExtern; - this.assumeCrossModuleNames = assumeCrossModuleNames; + this.assumeCrossChunkNames = assumeCrossChunkNames; } - private boolean isCrossModuleName(String name) { - return assumeCrossModuleNames - || crossModuleNames.contains(name) + private boolean isCrossChunkName(String name) { + return assumeCrossChunkNames + || crossChunkNames.contains(name) || compiler.getCodingConvention().isExported(name, /* local= */ false); } @@ -145,10 +140,10 @@ public void process(Node externs, Node root) { NodeTraversal.traverse( compiler, root, new RewriteGlobalClassFunctionDeclarationsToVarAssignmentsCallback()); - // Find global names that are used in more than one module. Those that + // Find global names that are used in more than one chunk. Those that // are have to be rewritten. List nonMutatingPasses = new ArrayList<>(); - nonMutatingPasses.add(new FindCrossModuleNamesCallback()); + nonMutatingPasses.add(new FindCrossChunkNamesCallback()); // And find names that may refer to functions that reference this. nonMutatingPasses.add(new FindNamesReferencingThis()); @@ -161,7 +156,7 @@ public void process(Node externs, Node root) { // Remove the var from statements in global scope if the declared names have been rewritten // in the previous pass. NodeTraversal.traverse(compiler, root, new RemoveGlobalVarCallback()); - rewriteScope.declareModuleGlobals(); + rewriteScope.declareChunkGlobals(); } /** @@ -223,16 +218,15 @@ public void visit(NodeTraversal t, Node n, Node parent) { } /** - * Find all global names that are used in more than one module. The following - * compiler transformations can ignore the globals that are not. + * Find all global names that are used in more than one chunk. The following compiler + * transformations can ignore the globals that are not. */ - private class FindCrossModuleNamesCallback extends - AbstractPostOrderCallback { + private class FindCrossChunkNamesCallback extends AbstractPostOrderCallback { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName()) { String name = n.getString(); - if ("".equals(name) || crossModuleNames.contains(name)) { + if ("".equals(name) || crossChunkNames.contains(name)) { return; } Scope s = t.getScope(); @@ -242,28 +236,26 @@ public void visit(NodeTraversal t, Node n, Node parent) { } CompilerInput input = v.getInput(); if (input == null) { - // We know nothing. Assume name is used across modules. - crossModuleNames.add(name); + // We know nothing. Assume name is used across chunks. + crossChunkNames.add(name); return; } - // Compare the module where the variable is declared to the current - // module. If they are different, the variable is used across modules. - JSChunk module = input.getChunk(); - if (module != t.getChunk()) { - crossModuleNames.add(name); + // Compare the chunk where the variable is declared to the current + // chunk. If they are different, the variable is used across chunks. + JSChunk chunk = input.getChunk(); + if (chunk != t.getChunk()) { + crossChunkNames.add(name); } } } } /** - * Builds the maybeReferencesThis set of names that may reference a function - * that references this. If the function a name references does not reference - * this it can be called as a method call where the this value is not the - * same as in a normal function call. + * Builds the maybeReferencesThis set of names that may reference a function that references this. + * If the function a name references does not reference this it can be called as a method call + * where the this value is not the same as in a normal function call. */ - private class FindNamesReferencingThis extends - AbstractPostOrderCallback { + private class FindNamesReferencingThis extends AbstractPostOrderCallback { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName()) { @@ -341,7 +333,7 @@ public void visit(NodeTraversal t, Node n, Node parent) { * (This is invalid syntax, but the VAR token is removed later). */ private class RewriteScopeCallback implements NodeTraversal.Callback { - final List preDeclarations = new ArrayList<>(); + final List preDeclarations = new ArrayList<>(); @Override public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { @@ -367,10 +359,10 @@ private void visitNameDeclaration(NodeTraversal t, Node declaration) { boolean hasImportantName = false; boolean isGlobalDeclaration = t.getScope().getVar(allLhsNodes.get(0).getString()).isGlobal(); - // Check if any names are in the externs or are global and cross module. + // Check if any names are in the externs or are global and cross chunk. for (Node lhs : allLhsNodes) { checkState(lhs.isName(), "Unexpected lhs node %s, expected NAME", lhs); - if ((isGlobalDeclaration && isCrossModuleName(lhs.getString())) + if ((isGlobalDeclaration && isCrossChunkName(lhs.getString())) || isExternVar(lhs.getString(), t)) { hasImportantName = true; break; @@ -385,7 +377,7 @@ private void visitNameDeclaration(NodeTraversal t, Node declaration) { /** * Partially rewrites a declaration as an assignment. * - *

In the post traversal, all global, cross-module names and extern name references will + *

In the post traversal, all global, cross-chunk names and extern name references will * become property accesses. They will then be invalid as the lhs of a declaration, so we need * to convert them to assignments. We also convert any other names or destructuring patterns in * the same declaration to assignments and add an earlier declaration. @@ -393,13 +385,13 @@ private void visitNameDeclaration(NodeTraversal t, Node declaration) { private void rewriteNameDeclaration( NodeTraversal t, Node declaration, List allLhsNodes, boolean isGlobalDeclaration) { - // Add predeclarations for variables that are neither global/cross-module names nor externs. + // Add predeclarations for variables that are neither global/cross-chunk names nor externs. CompilerInput input = t.getInput(); for (Node lhs : allLhsNodes) { String name = lhs.getString(); - if (!(isGlobalDeclaration && isCrossModuleName(name)) && !isExternVar(name, t)) { + if (!(isGlobalDeclaration && isCrossChunkName(name)) && !isExternVar(name, t)) { preDeclarations.add( - new ModuleGlobal(input.getAstRoot(compiler), IR.name(name).srcref(lhs))); + new ChunkGlobal(input.getAstRoot(compiler), IR.name(name).srcref(lhs))); } } @@ -458,13 +450,13 @@ private void visitName(NodeTraversal t, Node n, Node parent) { compiler.reportChangeToEnclosingScope(n); } // We only care about global vars. - if (!(var.isGlobal() && isCrossModuleName(name))) { + if (!(var.isGlobal() && isCrossChunkName(name))) { return; } replaceSymbol(n, name); } - /** Replaces a global cross-module name with an access on the global namespace symbol */ + /** Replaces a global cross-chunk name with an access on the global namespace symbol */ private void replaceSymbol(Node node, String name) { Node parent = node.getParent(); Node replacement = IR.getprop(IR.name(globalSymbolNamespace), name); @@ -482,11 +474,11 @@ private void replaceSymbol(Node node, String name) { } /** - * Adds back declarations for variables that do not cross module boundaries. - * Must be called after RemoveGlobalVarCallback. + * Adds back declarations for variables that do not cross chunk boundaries. Must be called after + * RemoveGlobalVarCallback. */ - void declareModuleGlobals() { - for (ModuleGlobal global : preDeclarations) { + void declareChunkGlobals() { + for (ChunkGlobal global : preDeclarations) { if (global.root.hasChildren() && global.root.getFirstChild().isVar()) { global.root.getFirstChild().addChildToBack(global.name); } else { @@ -496,14 +488,12 @@ void declareModuleGlobals() { } } - /** - * Variable that doesn't cross module boundaries. - */ - private class ModuleGlobal { + /** Variable that doesn't cross chunk boundaries. */ + private class ChunkGlobal { final Node root; final Node name; - ModuleGlobal(Node root, Node name) { + ChunkGlobal(Node root, Node name) { this.root = root; this.name = name; } @@ -556,7 +546,7 @@ public void visit(NodeTraversal t, Node n, Node parent) { } } // If every child of a var declares a name, it must stay in place. - // This is the case if none of the declared variables cross module + // This is the case if none of the declared variables cross chunk // boundaries. if (allNameOrDestructuring) { return; @@ -592,4 +582,3 @@ private Node joinOnComma(List commas, Node source) { } } } - diff --git a/src/com/google/javascript/jscomp/VarCheck.java b/src/com/google/javascript/jscomp/VarCheck.java index ba31bbaf7a0..16ebf2b404b 100644 --- a/src/com/google/javascript/jscomp/VarCheck.java +++ b/src/com/google/javascript/jscomp/VarCheck.java @@ -232,17 +232,17 @@ && strengthOf(n).equals(SourceKind.STRONG)) { // Check module dependencies. JSChunk currModule = currInput.getChunk(); JSChunk varModule = varInput.getChunk(); - JSChunkGraph moduleGraph = compiler.getModuleGraph(); + JSChunkGraph chunkGraph = compiler.getChunkGraph(); if (!validityCheck && varModule != currModule && varModule != null && currModule != null) { if (varModule.isWeak()) { this.handleUndeclaredVariableRef(t, n); } - if (moduleGraph.dependsOn(currModule, varModule)) { + if (chunkGraph.dependsOn(currModule, varModule)) { // The module dependency was properly declared. } else { if (scope.isGlobal()) { - if (moduleGraph.dependsOn(varModule, currModule)) { + if (chunkGraph.dependsOn(varModule, currModule)) { // The variable reference violates a declared module dependency. t.report( n, VIOLATED_MODULE_DEP_ERROR, currModule.getName(), varModule.getName(), varName); diff --git a/test/com/google/javascript/jscomp/AliasStringsTest.java b/test/com/google/javascript/jscomp/AliasStringsTest.java index dc15a966865..a68dd2ada84 100644 --- a/test/com/google/javascript/jscomp/AliasStringsTest.java +++ b/test/com/google/javascript/jscomp/AliasStringsTest.java @@ -39,7 +39,7 @@ public AliasStringsTest() { @Override protected CompilerPass getProcessor(Compiler compiler) { AliasStrings pass = - new AliasStrings(compiler, compiler.getModuleGraph(), false, aliasStringsMode); + new AliasStrings(compiler, compiler.getChunkGraph(), false, aliasStringsMode); if (hashReduction) { pass.unitTestHashReductionMask = 0; } @@ -166,11 +166,11 @@ public void testStringsThatAreGlobalVarValues() { @Test public void testStringsInModules() { - // Aliases must be placed in the correct module. The alias for + // Aliases must be placed in the correct chunk. The alias for // '------adios------' must be lifted from m2 and m3 and go in the - // common parent module m1 + // common parent chunks m1 - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forBush() .addChunk( "function f(a) { alert('ffffffffffffffffffff' + 'ffffffffffffffffffff' + a); }" @@ -188,7 +188,7 @@ public void testStringsInModules() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "var $$S_ciaociaociaociaociao = 'ciaociaociaociaociao';" @@ -230,7 +230,7 @@ public void testStringsInModules2() { // '------adios------' must be lifted from m2 and m3 and go in the // common parent module m1 - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forBush() .addChunk("function g() { alert('ciaociaociaociaociao'); }") .addChunk( @@ -243,7 +243,7 @@ public void testStringsInModules2() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 lines( @@ -265,7 +265,7 @@ public void testStringsInModules2() { @Test public void testAliasInCommonModuleInclusive() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forBush() .addChunk("") .addChunk("function g() { alert('ciaociaociaociaociao'); }") @@ -276,7 +276,7 @@ public void testAliasInCommonModuleInclusive() { // The "ciao" string is used in m1 and m2. // Since m2 depends on m1, we should create the module there and not force it into m0. test( - srcs(modules), + srcs(chunks), expected( // m0 "", @@ -292,7 +292,7 @@ public void testAliasInCommonModuleInclusive() { @Test public void testEmptyModules() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() .addChunk("") .addChunk("function foo() { f('goodgoodgoodgoodgood') }") @@ -300,7 +300,7 @@ public void testEmptyModules() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m0 "var $$S_goodgoodgoodgoodgood='goodgoodgoodgoodgood'", diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java index 3de15f52055..cf7887e1367 100644 --- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java +++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java @@ -1388,7 +1388,7 @@ public void testSourceMapExpansion3() { testSame(new String[] {"var x = 3;", "var y = 5;"}); assertThat( lastCommandLineRunner.expandSourceMapPath( - lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootChunk())) + lastCompiler.getOptions(), lastCompiler.getChunkGraph().getRootChunk())) .isEqualTo("foo_m0.js.map"); } @@ -1700,9 +1700,9 @@ public void testModuleWrapperBaseNameExpansion() throws Exception { StringBuilder builder = new StringBuilder(); ScriptNodeLicensesOnlyTracker licenseTracker = new ScriptNodeLicensesOnlyTracker(lastCompiler); - JSChunk module = lastCompiler.getModuleGraph().getRootChunk(); - String filename = lastCommandLineRunner.getModuleOutputFileName(module); - lastCommandLineRunner.writeModuleOutput(filename, builder, licenseTracker, module); + JSChunk chunk = lastCompiler.getChunkGraph().getRootChunk(); + String filename = lastCommandLineRunner.getChunkOutputFileName(chunk); + lastCommandLineRunner.writeModuleOutput(filename, builder, licenseTracker, chunk); assertThat(builder.toString()).isEqualTo("var x=3; // m0.js\n"); } @@ -1714,9 +1714,9 @@ public void testModuleWrapperExpansion() throws Exception { StringBuilder builder = new StringBuilder(); ScriptNodeLicensesOnlyTracker licenseTracker = new ScriptNodeLicensesOnlyTracker(lastCompiler); - JSChunk module = lastCompiler.getModuleGraph().getRootChunk(); - String filename = lastCommandLineRunner.getModuleOutputFileName(module); - lastCommandLineRunner.writeModuleOutput(filename, builder, licenseTracker, module); + JSChunk chunk = lastCompiler.getChunkGraph().getRootChunk(); + String filename = lastCommandLineRunner.getChunkOutputFileName(chunk); + lastCommandLineRunner.writeModuleOutput(filename, builder, licenseTracker, chunk); assertThat(builder.toString()).isEqualTo("var x=3;\n//# SourceMappingUrl=m0.js.map\n"); } @@ -1759,8 +1759,8 @@ public void testChainModuleManifest() throws Exception { testSame(new String[] {"var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); - lastCommandLineRunner.printModuleGraphManifestOrBundleTo( - lastCompiler.getModuleGraph(), builder, true); + lastCommandLineRunner.printChunkGraphManifestOrBundleTo( + lastCompiler.getChunkGraph(), builder, true); assertThat(builder.toString()) .isEqualTo( Joiner.on('\n') @@ -1787,8 +1787,8 @@ public void testStarModuleManifest() throws Exception { testSame(new String[] {"var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); - lastCommandLineRunner.printModuleGraphManifestOrBundleTo( - lastCompiler.getModuleGraph(), builder, true); + lastCommandLineRunner.printChunkGraphManifestOrBundleTo( + lastCompiler.getChunkGraph(), builder, true); assertThat(builder.toString()) .isEqualTo( Joiner.on('\n') @@ -1810,12 +1810,12 @@ public void testStarModuleManifest() throws Exception { } @Test - public void testOutputModuleGraphJson() throws Exception { + public void testOutputChunkGraphJson() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] {"var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); - lastCommandLineRunner.printModuleGraphJsonTo(builder); + lastCommandLineRunner.printChunkGraphJsonTo(builder); assertThat(builder.toString()).contains("transitive-dependencies"); } diff --git a/test/com/google/javascript/jscomp/CompilerTest.java b/test/com/google/javascript/jscomp/CompilerTest.java index 15ba9a63385..6fdd5c2bebb 100644 --- a/test/com/google/javascript/jscomp/CompilerTest.java +++ b/test/com/google/javascript/jscomp/CompilerTest.java @@ -535,14 +535,14 @@ public void testNormalInputs() { @Test public void testRebuildInputsFromModule() { - ImmutableList modules = ImmutableList.of(new JSChunk("m1"), new JSChunk("m2")); - modules.get(0).add(SourceFile.fromCode("in1", "")); - modules.get(1).add(SourceFile.fromCode("in2", "")); + ImmutableList chunks = ImmutableList.of(new JSChunk("m1"), new JSChunk("m2")); + chunks.get(0).add(SourceFile.fromCode("in1", "")); + chunks.get(1).add(SourceFile.fromCode("in2", "")); Compiler compiler = new Compiler(); - compiler.initModules(ImmutableList.of(), modules, new CompilerOptions()); + compiler.initChunks(ImmutableList.of(), chunks, new CompilerOptions()); - modules.get(1).add(SourceFile.fromCode("in3", "")); + chunks.get(1).add(SourceFile.fromCode("in3", "")); assertThat(compiler.getInput(new InputId("in3"))).isNull(); compiler.rebuildInputsFromModules(); assertThat(compiler.getInput(new InputId("in3"))).isNotNull(); @@ -1553,7 +1553,7 @@ public void testCheckSaveRestore3StagesNoInputFiles() throws Exception { compiler.parse(); compiler.check(); final CompilerInput onlyInputBeforeSave = - getOnlyElement(compiler.getModuleGraph().getAllInputs()); + getOnlyElement(compiler.getChunkGraph().getAllInputs()); // this is the special name used for a single fill file when there are no inputs assertThat(onlyInputBeforeSave.getName()).isEqualTo("$strong$$fillFile"); @@ -1565,7 +1565,7 @@ public void testCheckSaveRestore3StagesNoInputFiles() throws Exception { // The fillFile is still listed as the only input final CompilerInput onlyInputAfterRestore = - getOnlyElement(compiler.getModuleGraph().getAllInputs()); + getOnlyElement(compiler.getChunkGraph().getAllInputs()); assertThat(onlyInputAfterRestore.getName()).isEqualTo("$strong$$fillFile"); } @@ -1616,7 +1616,7 @@ public void testCheckSaveRestoreRecoverableJsAst() throws Exception { Joiner.on('\n').join("", "function f() { return 2; }", "console.log(f());")); JsAst realAst = new JsAst(inputSourceFile); m.add(new CompilerInput(new RecoverableJsAst(realAst, /* reportParseErrors= */ true))); - compiler.initModules(externs, ImmutableList.of(m), options); + compiler.initChunks(externs, ImmutableList.of(m), options); compiler.parse(); compiler.check(); @@ -1628,7 +1628,7 @@ public void testCheckSaveRestoreRecoverableJsAst() throws Exception { compiler = new Compiler(new TestErrorManager()); m = new JSChunk("m"); m.add(new CompilerInput(new RecoverableJsAst(realAst, /* reportParseErrors= */ true))); - compiler.initModules(externs, ImmutableList.of(m), options); + compiler.initChunks(externs, ImmutableList.of(m), options); restoreCompilerState(compiler, byteArrayOutputStream.toByteArray()); compiler.performTranspilationAndOptimizations(); @@ -2565,10 +2565,10 @@ public void testWeakSources() throws Exception { compiler.check(); compiler.performTranspilationAndOptimizations(); - assertThat(compiler.getModuleGraph().getChunkCount()).isEqualTo(2); - assertThat(Iterables.get(compiler.getModuleGraph().getAllChunks(), 0).getName()) + assertThat(compiler.getChunkGraph().getChunkCount()).isEqualTo(2); + assertThat(Iterables.get(compiler.getChunkGraph().getAllChunks(), 0).getName()) .isEqualTo(JSChunk.STRONG_CHUNK_NAME); - assertThat(Iterables.get(compiler.getModuleGraph().getAllChunks(), 1).getName()) + assertThat(Iterables.get(compiler.getChunkGraph().getAllChunks(), 1).getName()) .isEqualTo(JSChunk.WEAK_CHUNK_NAME); assertThat(compiler.toSource()).isEqualTo("var a={};a.b={};var d={};"); @@ -2588,7 +2588,7 @@ private void weakSourcesModulesHelper(boolean saveAndRestore) throws Exception { Compiler compiler = new Compiler(); - compiler.initModules(ImmutableList.of(), ImmutableList.of(m1, m2), options); + compiler.initChunks(ImmutableList.of(), ImmutableList.of(m1, m2), options); compiler.parse(); compiler.check(); @@ -2605,15 +2605,15 @@ private void weakSourcesModulesHelper(boolean saveAndRestore) throws Exception { restoreCompilerState(compiler, byteArrayOutputStream.toByteArray()); // restoring state creates new JSModule objects. the old ones are stale. - m1 = compiler.getModuleGraph().getChunkByName("m1"); - m2 = compiler.getModuleGraph().getChunkByName("m2"); + m1 = compiler.getChunkGraph().getChunkByName("m1"); + m2 = compiler.getChunkGraph().getChunkByName("m2"); } compiler.performTranspilationAndOptimizations(); - assertThat(compiler.getModuleGraph().getChunkCount()).isEqualTo(3); + assertThat(compiler.getChunkGraph().getChunkCount()).isEqualTo(3); - JSChunk weakModule = compiler.getModuleGraph().getChunkByName("$weak$"); + JSChunk weakModule = compiler.getChunkGraph().getChunkByName("$weak$"); ScriptNodeLicensesOnlyTracker lt = new ScriptNodeLicensesOnlyTracker(compiler); assertThat(weakModule).isNotNull(); @@ -2687,15 +2687,15 @@ public void testPreexistingWeakModule() throws Exception { Compiler compiler = new Compiler(); - compiler.initModules(ImmutableList.of(), ImmutableList.of(strong, weak), options); + compiler.initChunks(ImmutableList.of(), ImmutableList.of(strong, weak), options); compiler.parse(); compiler.check(); compiler.performTranspilationAndOptimizations(); - assertThat(compiler.getModuleGraph().getChunkCount()).isEqualTo(2); - assertThat(Iterables.get(compiler.getModuleGraph().getAllChunks(), 0).getName()).isEqualTo("m"); - assertThat(Iterables.get(compiler.getModuleGraph().getAllChunks(), 1).getName()) + assertThat(compiler.getChunkGraph().getChunkCount()).isEqualTo(2); + assertThat(Iterables.get(compiler.getChunkGraph().getAllChunks(), 0).getName()).isEqualTo("m"); + assertThat(Iterables.get(compiler.getChunkGraph().getAllChunks(), 1).getName()) .isEqualTo(JSChunk.WEAK_CHUNK_NAME); assertThat(compiler.toSource()).isEqualTo("var a={};"); @@ -2718,8 +2718,7 @@ public void testPreexistingWeakModuleWithAdditionalStrongSources() throws Except RuntimeException e = assertThrows( RuntimeException.class, - () -> - compiler.initModules(ImmutableList.of(), ImmutableList.of(strong, weak), options)); + () -> compiler.initChunks(ImmutableList.of(), ImmutableList.of(strong, weak), options)); assertThat(e) .hasMessageThat() .contains("Found these strong sources in the weak chunk:\n weak_but_actually_strong.js"); @@ -2741,8 +2740,7 @@ public void testPreexistingWeakModuleWithMissingWeakSources() throws Exception { RuntimeException e = assertThrows( RuntimeException.class, - () -> - compiler.initModules(ImmutableList.of(), ImmutableList.of(strong, weak), options)); + () -> compiler.initChunks(ImmutableList.of(), ImmutableList.of(strong, weak), options)); assertThat(e) .hasMessageThat() .contains( @@ -2763,8 +2761,7 @@ public void testPreexistingWeakModuleWithIncorrectDependencies() throws Exceptio RuntimeException e = assertThrows( RuntimeException.class, - () -> - compiler.initModules(ImmutableList.of(), ImmutableList.of(m1, m2, weak), options)); + () -> compiler.initChunks(ImmutableList.of(), ImmutableList.of(m1, m2, weak), options)); assertThat(e) .hasMessageThat() .isEqualTo("A weak chunk already exists but it does not depend on every other chunk."); @@ -3375,14 +3372,14 @@ public void testTypedAstFilesystem_doesNotParseWeakFileTypedAstContents() { typedAstListStream); Node weakScript = compiler - .getModuleGraph() + .getChunkGraph() .getChunkByName(JSChunk.WEAK_CHUNK_NAME) .getInputs() .get(0) .getAstRoot(compiler); Node strongScript = compiler - .getModuleGraph() + .getChunkGraph() .getChunkByName(JSChunk.STRONG_CHUNK_NAME) .getInputs() .get(0) @@ -3453,7 +3450,7 @@ public void testTypedAstFilesystemWithModules_doesNotParseWeakFileTypedAstConten TypedAst.List.newBuilder().addTypedAsts(typedAst).build().toByteArray()); // When - compiler.initModulesWithTypedAstFilesystem( + compiler.initChunksWithTypedAstFilesystem( ImmutableList.of(), ImmutableList.of(strongChunk, weakChunk), compilerOptions, diff --git a/test/com/google/javascript/jscomp/CompilerTestCase.java b/test/com/google/javascript/jscomp/CompilerTestCase.java index 92e2fcdf83d..be86cdaa3e1 100644 --- a/test/com/google/javascript/jscomp/CompilerTestCase.java +++ b/test/com/google/javascript/jscomp/CompilerTestCase.java @@ -1354,7 +1354,7 @@ protected Compiler createAndInitializeCompiler(Externs externs, Sources inputs) options.setCheckTypes(parseTypeInfo || this.typeCheckEnabled); compiler.init(externs.externs, ((FlatSources) inputs).sources, options); } else { - compiler.initModules(externs.externs, ((ModuleSources) inputs).modules, getOptions()); + compiler.initChunks(externs.externs, ((ChunkSources) inputs).chunks, getOptions()); } return compiler; } @@ -2007,7 +2007,7 @@ protected void testExternChanges( if (inputs instanceof FlatSources) { compiler.init(externs.externs, ((FlatSources) inputs).sources, options); } else { - compiler.initModules(externs.externs, ((ModuleSources) inputs).modules, getOptions()); + compiler.initChunks(externs.externs, ((ChunkSources) inputs).chunks, getOptions()); } testExternChangesInternal(compiler, expectedExtern, warnings); } @@ -2177,7 +2177,7 @@ protected Sources srcs(SourceFile... files) { } protected static Sources srcs(JSChunk... modules) { - return new ModuleSources(modules); + return new ChunkSources(modules); } protected static Expected expected(String srcText) { @@ -2196,10 +2196,10 @@ protected Expected expected(SourceFile... files) { return new Expected(Arrays.asList(files)); } - protected static Expected expected(JSChunk[] modules) { + protected static Expected expected(JSChunk[] chunks) { List expectedSrcs = new ArrayList<>(); - for (JSChunk module : modules) { - for (CompilerInput input : module.getInputs()) { + for (JSChunk chunk : chunks) { + for (CompilerInput input : chunk.getInputs()) { try { expectedSrcs.add(input.getSourceFile().getCode()); } catch (IOException e) { @@ -2294,9 +2294,9 @@ private void testInternal(Iterable parts) { private static Expected fromSources(Sources srcs) { if (srcs instanceof FlatSources) { return expected(((FlatSources) srcs).sources); - } else if (srcs instanceof ModuleSources) { - ModuleSources modules = ((ModuleSources) srcs); - return expected(modules.modules.toArray(new JSChunk[0])); + } else if (srcs instanceof ChunkSources) { + ChunkSources modules = ((ChunkSources) srcs); + return expected(modules.chunks.toArray(new JSChunk[0])); } else { throw new IllegalStateException("unexpected"); } @@ -2339,11 +2339,11 @@ protected static class FlatSources extends Sources { } } - protected static final class ModuleSources extends Sources { - final ImmutableList modules; + protected static final class ChunkSources extends Sources { + final ImmutableList chunks; - ModuleSources(JSChunk[] modules) { - this.modules = ImmutableList.copyOf(modules); + ChunkSources(JSChunk[] chunks) { + this.chunks = ImmutableList.copyOf(chunks); } } diff --git a/test/com/google/javascript/jscomp/CrossChunkCodeMotionTest.java b/test/com/google/javascript/jscomp/CrossChunkCodeMotionTest.java index 6e72c5ae5c0..d1f7dc8a9dd 100644 --- a/test/com/google/javascript/jscomp/CrossChunkCodeMotionTest.java +++ b/test/com/google/javascript/jscomp/CrossChunkCodeMotionTest.java @@ -51,7 +51,7 @@ public void setUp() throws Exception { @Override protected CompilerPass getProcessor(Compiler compiler) { return new CrossChunkCodeMotion( - compiler, compiler.getModuleGraph(), parentModuleCanSeeSymbolsDeclaredInChildren); + compiler, compiler.getChunkGraph(), parentModuleCanSeeSymbolsDeclaredInChildren); } @Test @@ -64,7 +64,7 @@ public void testFunctionMovement1() { // 5) h declared in m2 and never used. It stays put // 6) f4 declared in m1 and used in m2 as var. It moves to m2 - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk( @@ -81,7 +81,7 @@ public void testFunctionMovement1() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "function f3(a) { alert(a); } function g() { alert('ciao'); }", @@ -99,7 +99,7 @@ public void testFunctionMovement1() { @Test public void testFunctionMovement2() { // having f declared as a local variable should block the migration to m2 - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("function f(a) { alert(a); } function g() {var f = 1; f++}") @@ -108,7 +108,7 @@ public void testFunctionMovement2() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "function g() {var f = 1; f++}", @@ -119,7 +119,7 @@ public void testFunctionMovement2() { @Test public void testFunctionMovement3() { // having f declared as a arg should block the migration to m2 - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("function f(a) { alert(a); } function g(f) {f++}") @@ -128,7 +128,7 @@ public void testFunctionMovement3() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "function g(f) {f++}", @@ -139,7 +139,7 @@ public void testFunctionMovement3() { @Test public void testFunctionMovement4() { // Try out moving a function which returns a closure - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("function f(){return function(a){}}") @@ -148,7 +148,7 @@ public void testFunctionMovement4() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -159,7 +159,7 @@ public void testFunctionMovement4() { @Test public void testFunctionMovement5() { // Try moving a recursive function [using factorials for kicks] - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("function f(n){return (n<1)?1:f(n-1)}") @@ -168,7 +168,7 @@ public void testFunctionMovement5() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -179,7 +179,7 @@ public void testFunctionMovement5() { @Test public void testFunctionMovement5b() { // Try moving a recursive function declared differently. - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("var f = function(n){return (n<1)?1:f(n-1)};") @@ -188,7 +188,7 @@ public void testFunctionMovement5b() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -199,7 +199,7 @@ public void testFunctionMovement5b() { @Test public void testFunctionMovement5c() { // Try moving a recursive function declared differently, in a nested block scope. - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("var f = function(n){if(true){if(true){return (n<1)?1:f(n-1)}}};") @@ -208,7 +208,7 @@ public void testFunctionMovement5c() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -221,7 +221,7 @@ public void testFunctionMovement5c() { @Test public void testFunctionMovement6() { // Try out moving to the common ancestor - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forChain() // m1 .addChunk("function f(){return 1}") @@ -232,7 +232,7 @@ public void testFunctionMovement6() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -245,7 +245,7 @@ public void testFunctionMovement6() { @Test public void testFunctionMovement7() { // Try out moving to the common ancestor with deeper ancestry chain - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forUnordered() // m1 .addChunk("function f(){return 1}") @@ -259,13 +259,13 @@ public void testFunctionMovement7() { .addChunk("var c = f();") .build(); - modules[1].addDependency(modules[0]); - modules[2].addDependency(modules[1]); - modules[3].addDependency(modules[1]); - modules[4].addDependency(modules[1]); + chunks[1].addDependency(chunks[0]); + chunks[2].addDependency(chunks[1]); + chunks[3].addDependency(chunks[1]); + chunks[4].addDependency(chunks[1]); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -282,7 +282,7 @@ public void testFunctionMovement7() { @Test public void testFunctionMovement8() { // Check what happens with named functions - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forChain() // m1 .addChunk("var v = function f(){return 1}") @@ -291,7 +291,7 @@ public void testFunctionMovement8() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -611,7 +611,7 @@ public void testClassMovement4() { @Test public void testClassMovement5() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forUnordered() // m1 .addChunk("function f(){} f.prototype.bar=3; f.prototype.baz=5;") @@ -623,13 +623,13 @@ public void testClassMovement5() { .addChunk("var a = new f();") .build(); - modules[1].addDependency(modules[0]); - modules[2].addDependency(modules[1]); - modules[3].addDependency(modules[1]); + chunks[1].addDependency(chunks[0]); + chunks[2].addDependency(chunks[1]); + chunks[3].addDependency(chunks[1]); // m4 + test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -777,7 +777,7 @@ public void testClassMovement_classStaticBlock2() { @Test public void testClassMovement_classStaticBlock3() { // TODO(bradfordcsmith):Ideally the class and var would move to m3 - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forChain() // m1 .addChunk("const x = 1; var y = 2;") @@ -788,7 +788,7 @@ public void testClassMovement_classStaticBlock3() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "const x = 1;", @@ -800,7 +800,7 @@ public void testClassMovement_classStaticBlock3() { @Test public void testClassMovement_classStaticBlock4() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forChain() // m1 .addChunk("var x =1;") @@ -818,7 +818,7 @@ public void testClassMovement_classStaticBlock4() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1084,7 +1084,7 @@ public void testStringTemplateLiteralMovement2() { @Test public void testVarMovement1() { // test moving a variable - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("var a = 0;") @@ -1093,7 +1093,7 @@ public void testVarMovement1() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1104,7 +1104,7 @@ public void testVarMovement1() { @Test public void testLetConstMovement() { // test moving a variable - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("const a = 0;") @@ -1113,7 +1113,7 @@ public void testLetConstMovement() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1124,7 +1124,7 @@ public void testLetConstMovement() { @Test public void testVarMovement2() { // Test moving 1 variable out of the block - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("var a = 0; var b = 1; var c = 2;") @@ -1133,7 +1133,7 @@ public void testVarMovement2() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "var a = 0; var c = 2;", @@ -1144,7 +1144,7 @@ public void testVarMovement2() { @Test public void testLetConstMovement2() { // Test moving 1 variable out of the block - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("const a = 0; const b = 1; const c = 2;") @@ -1153,7 +1153,7 @@ public void testLetConstMovement2() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "const a = 0; const c = 2;", @@ -1164,7 +1164,7 @@ public void testLetConstMovement2() { @Test public void testVarMovement3() { // Test moving all variables out of the block - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("var a = 0; var b = 1;") @@ -1173,7 +1173,7 @@ public void testVarMovement3() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1184,7 +1184,7 @@ public void testVarMovement3() { @Test public void testLetConstMovement3() { // Test moving all variables out of the block - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("const a = 0; const b = 1;") @@ -1193,7 +1193,7 @@ public void testLetConstMovement3() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1204,7 +1204,7 @@ public void testLetConstMovement3() { @Test public void testVarMovement4() { // Test moving a function - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("var a = function(){alert(1)};") @@ -1213,7 +1213,7 @@ public void testVarMovement4() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1224,7 +1224,7 @@ public void testVarMovement4() { @Test public void testLetConstMovement4() { // Test moving a function - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("const a = function(){alert(1)};") @@ -1233,7 +1233,7 @@ public void testLetConstMovement4() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1266,7 +1266,7 @@ public void testLetConstMovement5() { @Test public void testVarMovement6() { // Test moving a var with no assigned value - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("var a;") @@ -1275,7 +1275,7 @@ public void testVarMovement6() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1286,7 +1286,7 @@ public void testVarMovement6() { @Test public void testLetMovement6() { // Test moving a let with no assigned value - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("let a;") @@ -1295,7 +1295,7 @@ public void testLetMovement6() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1316,7 +1316,7 @@ public void testVarMovement7() { @Test public void testVarMovement8() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forBush() // m1 .addChunk("var a = 0;") @@ -1329,7 +1329,7 @@ public void testVarMovement8() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1343,7 +1343,7 @@ public void testVarMovement8() { @Test public void testLetConstMovement8() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forBush() // m1 .addChunk("const a = 0;") @@ -1356,7 +1356,7 @@ public void testLetConstMovement8() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1370,7 +1370,7 @@ public void testLetConstMovement8() { @Test public void testVarMovement9() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forTree() // m1 .addChunk("var a = 0; var b = 1; var c = 3;") @@ -1389,7 +1389,7 @@ public void testVarMovement9() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "var c = 3;", @@ -1409,7 +1409,7 @@ public void testVarMovement9() { @Test public void testConstMovement9() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forTree() // m1 .addChunk("const a = 0; const b = 1; const c = 3;") @@ -1428,7 +1428,7 @@ public void testConstMovement9() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "const c = 3;", @@ -1448,7 +1448,7 @@ public void testConstMovement9() { @Test public void testClinit1() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forChain() // m1 .addChunk("function Foo$clinit() { Foo$clinit = function() {}; }") @@ -1456,7 +1456,7 @@ public void testClinit1() { .addChunk("Foo$clinit();") .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1466,7 +1466,7 @@ public void testClinit1() { @Test public void testClinit2() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forChain() // m1 .addChunk("var Foo$clinit = function() { Foo$clinit = function() {}; };") @@ -1474,7 +1474,7 @@ public void testClinit2() { .addChunk("Foo$clinit();") .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", diff --git a/test/com/google/javascript/jscomp/CrossChunkMethodMotionTest.java b/test/com/google/javascript/jscomp/CrossChunkMethodMotionTest.java index f6c700ac6d9..8ae31988469 100644 --- a/test/com/google/javascript/jscomp/CrossChunkMethodMotionTest.java +++ b/test/com/google/javascript/jscomp/CrossChunkMethodMotionTest.java @@ -399,7 +399,7 @@ public void moveClassMethodForConstDefinition() { public void doNotMoveFunctionCall_thatIsSideEffected() { // TODO(bradfordcsmith): Stop normalizing the expected output or document why it is necessary. enableNormalizeExpectedOutput(); - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forChain() // m1 .addChunk( @@ -412,7 +412,7 @@ public void doNotMoveFunctionCall_thatIsSideEffected() { .addChunk("var c = b") .build(); - testSame(srcs(modules)); + testSame(srcs(chunks)); } @Test @@ -1046,7 +1046,7 @@ public void doNotMoveClassMethodUsedInMultiplepDependentChunks() { @Test public void movePrototypeMethodToDeepestCommonDependencyOfReferencingChunks() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forUnordered() .addChunk( lines( @@ -1061,11 +1061,11 @@ public void movePrototypeMethodToDeepestCommonDependencyOfReferencingChunks() { .addChunk("(new Foo).baz() , 2") .build(); - modules[1].addDependency(modules[0]); - modules[2].addDependency(modules[1]); - modules[3].addDependency(modules[1]); + chunks[1].addDependency(chunks[0]); + chunks[2].addDependency(chunks[1]); + chunks[3].addDependency(chunks[1]); test( - srcs(modules), + srcs(chunks), expected( lines( STUB_DECLARATIONS, // @@ -1081,7 +1081,7 @@ public void movePrototypeMethodToDeepestCommonDependencyOfReferencingChunks() { @Test public void moveClassMethodToDeepestCommonDependencyOfReferencingChunks() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forUnordered() .addChunk("class Foo { baz() {} }") // Chunk 2 @@ -1093,12 +1093,12 @@ public void moveClassMethodToDeepestCommonDependencyOfReferencingChunks() { .addChunk("(new Foo).baz() , 2") .build(); - modules[1].addDependency(modules[0]); - modules[2].addDependency(modules[1]); - modules[3].addDependency(modules[1]); + chunks[1].addDependency(chunks[0]); + chunks[2].addDependency(chunks[1]); + chunks[3].addDependency(chunks[1]); test( - srcs(modules), + srcs(chunks), expected( lines( STUB_DECLARATIONS, // diff --git a/test/com/google/javascript/jscomp/DevirtualizeMethodsTest.java b/test/com/google/javascript/jscomp/DevirtualizeMethodsTest.java index 9ad932970a0..4ad11e7b3b0 100644 --- a/test/com/google/javascript/jscomp/DevirtualizeMethodsTest.java +++ b/test/com/google/javascript/jscomp/DevirtualizeMethodsTest.java @@ -1424,7 +1424,7 @@ private ModuleTestInput() {} @Test public void testRewriteSameModule1() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk(semicolonJoin(ModuleTestInput.DEFINITION, ModuleTestInput.USE)) @@ -1433,7 +1433,7 @@ public void testRewriteSameModule1() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 semicolonJoin(ModuleTestInput.REWRITTEN_DEFINITION, ModuleTestInput.REWRITTEN_USE), @@ -1443,7 +1443,7 @@ public void testRewriteSameModule1() { @Test public void testRewriteSameModule2() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk("") @@ -1452,7 +1452,7 @@ public void testRewriteSameModule2() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 "", @@ -1462,7 +1462,7 @@ public void testRewriteSameModule2() { @Test public void testRewriteSameModule3() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk(semicolonJoin(ModuleTestInput.USE, ModuleTestInput.DEFINITION)) @@ -1471,7 +1471,7 @@ public void testRewriteSameModule3() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 semicolonJoin(ModuleTestInput.REWRITTEN_USE, ModuleTestInput.REWRITTEN_DEFINITION), @@ -1481,7 +1481,7 @@ public void testRewriteSameModule3() { @Test public void testRewrite_definitionModule_beforeUseModule() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() // m1 .addChunk(ModuleTestInput.DEFINITION) @@ -1490,7 +1490,7 @@ public void testRewrite_definitionModule_beforeUseModule() { .build(); test( - srcs(modules), + srcs(chunks), expected( // m1 ModuleTestInput.REWRITTEN_DEFINITION, @@ -1500,13 +1500,13 @@ public void testRewrite_definitionModule_beforeUseModule() { @Test public void testNoRewrite_definitionModule_afterUseModule() { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() .addChunk(ModuleTestInput.USE) .addChunk(ModuleTestInput.DEFINITION) .build(); - testSame(srcs(modules)); + testSame(srcs(chunks)); } @Override diff --git a/test/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarationsTest.java b/test/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarationsTest.java index 18f8310bcc1..ea00054c47f 100644 --- a/test/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarationsTest.java +++ b/test/com/google/javascript/jscomp/ExtractPrototypeMemberDeclarationsTest.java @@ -318,19 +318,19 @@ public void testAnonWithSideFx() { public void testNotEnoughPrototypeToExtractInChunk() { pattern = Pattern.USE_CHUNK_TEMP; for (int i = 0; i < 7; i++) { - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() .addChunk(generatePrototypeDeclarations("x", i)) .addChunk(generatePrototypeDeclarations("y", i)) .build(); - testSame(srcs(modules)); + testSame(srcs(chunks)); } } @Test public void testExtractingSingleClassPrototypeInChunk() { pattern = Pattern.USE_CHUNK_TEMP; - JSChunk[] modules = + JSChunk[] chunks = JSChunkGraphBuilder.forStar() .addChunk(generatePrototypeDeclarations("x", 7)) .addChunk(generatePrototypeDeclarations("y", 7)) @@ -353,7 +353,7 @@ public void testExtractingSingleClassPrototypeInChunk() { .addChunk(builderY.toString()) .build(); - test(srcs(modules), expected(expectedModules)); + test(srcs(chunks), expected(expectedModules)); } private String loadPrototype(String qName) { diff --git a/test/com/google/javascript/jscomp/JSChunkGraphTest.java b/test/com/google/javascript/jscomp/JSChunkGraphTest.java index a94d5c9cca3..8a610a525e0 100644 --- a/test/com/google/javascript/jscomp/JSChunkGraphTest.java +++ b/test/com/google/javascript/jscomp/JSChunkGraphTest.java @@ -45,12 +45,12 @@ @RunWith(JUnit4.class) public final class JSChunkGraphTest { - private JSChunk moduleA; - private JSChunk moduleB; - private JSChunk moduleC; - private JSChunk moduleD; - private JSChunk moduleE; - private JSChunk moduleF; + private JSChunk chunkA; + private JSChunk chunkB; + private JSChunk chunkC; + private JSChunk chunkD; + private JSChunk chunkE; + private JSChunk chunkF; private @Nullable JSChunkGraph graph = null; // For resolving dependencies only. @@ -62,24 +62,24 @@ public void setUp() throws Exception { } private void makeDeps() { - moduleA = new JSChunk("moduleA"); - moduleB = new JSChunk("moduleB"); - moduleC = new JSChunk("moduleC"); - moduleD = new JSChunk("moduleD"); - moduleE = new JSChunk("moduleE"); - moduleF = new JSChunk("moduleF"); - moduleB.addDependency(moduleA); // __A__ - moduleC.addDependency(moduleA); // / | \ - moduleD.addDependency(moduleB); // B C | - moduleE.addDependency(moduleB); // / \ /| | - moduleE.addDependency(moduleC); // D E | / - moduleF.addDependency(moduleA); // \|/ - moduleF.addDependency(moduleC); // F - moduleF.addDependency(moduleE); + chunkA = new JSChunk("chunkA"); + chunkB = new JSChunk("chunkB"); + chunkC = new JSChunk("chunkC"); + chunkD = new JSChunk("chunkD"); + chunkE = new JSChunk("chunkE"); + chunkF = new JSChunk("chunkF"); + chunkB.addDependency(chunkA); // __A__ + chunkC.addDependency(chunkA); // / | \ + chunkD.addDependency(chunkB); // B C | + chunkE.addDependency(chunkB); // / \ /| | + chunkE.addDependency(chunkC); // D E | / + chunkF.addDependency(chunkA); // \|/ + chunkF.addDependency(chunkC); // F + chunkF.addDependency(chunkE); } private void makeGraph() { - graph = new JSChunkGraph(new JSChunk[] {moduleA, moduleB, moduleC, moduleD, moduleE, moduleF}); + graph = new JSChunkGraph(new JSChunk[] {chunkA, chunkB, chunkC, chunkD, chunkE, chunkF}); } private JSChunk getWeakModule() { @@ -93,41 +93,40 @@ public void testMakesWeakModuleIfNotPassed() { assertThat(graph.getChunkCount()).isEqualTo(7); assertThat(graph.getChunksByName()).containsKey(JSChunk.WEAK_CHUNK_NAME); assertThat(getWeakModule().getAllDependencies()) - .containsExactly(moduleA, moduleB, moduleC, moduleD, moduleE, moduleF); + .containsExactly(chunkA, chunkB, chunkC, chunkD, chunkE, chunkF); } @Test public void testAcceptExistingWeakModule() { makeDeps(); - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - weakModule.addDependency(moduleA); - weakModule.addDependency(moduleB); - weakModule.addDependency(moduleC); - weakModule.addDependency(moduleD); - weakModule.addDependency(moduleE); - weakModule.addDependency(moduleF); + weakChunk.addDependency(chunkA); + weakChunk.addDependency(chunkB); + weakChunk.addDependency(chunkC); + weakChunk.addDependency(chunkD); + weakChunk.addDependency(chunkE); + weakChunk.addDependency(chunkF); - weakModule.add(SourceFile.fromCode("weak", "", SourceKind.WEAK)); + weakChunk.add(SourceFile.fromCode("weak", "", SourceKind.WEAK)); JSChunkGraph graph = - new JSChunkGraph( - new JSChunk[] {moduleA, moduleB, moduleC, moduleD, moduleE, moduleF, weakModule}); + new JSChunkGraph(new JSChunk[] {chunkA, chunkB, chunkC, chunkD, chunkE, chunkF, weakChunk}); assertThat(graph.getChunkCount()).isEqualTo(7); - assertThat(graph.getChunkByName(JSChunk.WEAK_CHUNK_NAME)).isSameInstanceAs(weakModule); + assertThat(graph.getChunkByName(JSChunk.WEAK_CHUNK_NAME)).isSameInstanceAs(weakChunk); } @Test public void testExistingWeakModuleMustHaveDependenciesOnAllOtherModules() { makeDeps(); - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - weakModule.addDependency(moduleA); - weakModule.addDependency(moduleB); - weakModule.addDependency(moduleC); - weakModule.addDependency(moduleD); - weakModule.addDependency(moduleE); + weakChunk.addDependency(chunkA); + weakChunk.addDependency(chunkB); + weakChunk.addDependency(chunkC); + weakChunk.addDependency(chunkD); + weakChunk.addDependency(chunkE); // Missing F IllegalStateException e = @@ -135,9 +134,7 @@ public void testExistingWeakModuleMustHaveDependenciesOnAllOtherModules() { IllegalStateException.class, () -> new JSChunkGraph( - new JSChunk[] { - moduleA, moduleB, moduleC, moduleD, moduleE, moduleF, weakModule - })); + new JSChunk[] {chunkA, chunkB, chunkC, chunkD, chunkE, chunkF, weakChunk})); assertThat(e) .hasMessageThat() .isEqualTo("A weak chunk already exists but it does not depend on every other chunk."); @@ -146,53 +143,49 @@ public void testExistingWeakModuleMustHaveDependenciesOnAllOtherModules() { @Test public void testWeakFileCannotExistOutsideWeakModule() { makeDeps(); - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - weakModule.addDependency(moduleA); - weakModule.addDependency(moduleB); - weakModule.addDependency(moduleC); - weakModule.addDependency(moduleD); - weakModule.addDependency(moduleE); - weakModule.addDependency(moduleF); + weakChunk.addDependency(chunkA); + weakChunk.addDependency(chunkB); + weakChunk.addDependency(chunkC); + weakChunk.addDependency(chunkD); + weakChunk.addDependency(chunkE); + weakChunk.addDependency(chunkF); - moduleA.add(SourceFile.fromCode("a", "", SourceKind.WEAK)); + chunkA.add(SourceFile.fromCode("a", "", SourceKind.WEAK)); IllegalStateException e = assertThrows( IllegalStateException.class, () -> new JSChunkGraph( - new JSChunk[] { - moduleA, moduleB, moduleC, moduleD, moduleE, moduleF, weakModule - })); + new JSChunk[] {chunkA, chunkB, chunkC, chunkD, chunkE, chunkF, weakChunk})); assertThat(e) .hasMessageThat() - .contains("Found these weak sources in other chunks:\n a (in chunk moduleA)"); + .contains("Found these weak sources in other chunks:\n a (in chunk chunkA)"); } @Test public void testStrongFileCannotExistInWeakModule() { makeDeps(); - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - weakModule.addDependency(moduleA); - weakModule.addDependency(moduleB); - weakModule.addDependency(moduleC); - weakModule.addDependency(moduleD); - weakModule.addDependency(moduleE); - weakModule.addDependency(moduleF); + weakChunk.addDependency(chunkA); + weakChunk.addDependency(chunkB); + weakChunk.addDependency(chunkC); + weakChunk.addDependency(chunkD); + weakChunk.addDependency(chunkE); + weakChunk.addDependency(chunkF); - weakModule.add(SourceFile.fromCode("a", "", SourceKind.STRONG)); + weakChunk.add(SourceFile.fromCode("a", "", SourceKind.STRONG)); IllegalStateException e = assertThrows( IllegalStateException.class, () -> new JSChunkGraph( - new JSChunk[] { - moduleA, moduleB, moduleC, moduleD, moduleE, moduleF, weakModule - })); + new JSChunk[] {chunkA, chunkB, chunkC, chunkD, chunkE, chunkF, weakChunk})); ; assertThat(e).hasMessageThat().contains("Found these strong sources in the weak chunk:\n a"); } @@ -240,105 +233,105 @@ public void testSmallerTreeBeatsDeeperTree() { public void testModuleDepth() { makeDeps(); makeGraph(); - assertWithMessage("moduleA should have depth 0").that(moduleA.getDepth()).isEqualTo(0); - assertWithMessage("moduleB should have depth 1").that(moduleB.getDepth()).isEqualTo(1); - assertWithMessage("moduleC should have depth 1").that(moduleC.getDepth()).isEqualTo(1); - assertWithMessage("moduleD should have depth 2").that(moduleD.getDepth()).isEqualTo(2); - assertWithMessage("moduleE should have depth 2").that(moduleE.getDepth()).isEqualTo(2); - assertWithMessage("moduleF should have depth 3").that(moduleF.getDepth()).isEqualTo(3); + assertWithMessage("chunkA should have depth 0").that(chunkA.getDepth()).isEqualTo(0); + assertWithMessage("chunkB should have depth 1").that(chunkB.getDepth()).isEqualTo(1); + assertWithMessage("chunkC should have depth 1").that(chunkC.getDepth()).isEqualTo(1); + assertWithMessage("chunkD should have depth 2").that(chunkD.getDepth()).isEqualTo(2); + assertWithMessage("chunkE should have depth 2").that(chunkE.getDepth()).isEqualTo(2); + assertWithMessage("chunkF should have depth 3").that(chunkF.getDepth()).isEqualTo(3); } @Test public void testDeepestCommonDep() { makeDeps(); makeGraph(); - assertDeepestCommonDep(null, moduleA, moduleA); - assertDeepestCommonDep(null, moduleA, moduleB); - assertDeepestCommonDep(null, moduleA, moduleC); - assertDeepestCommonDep(null, moduleA, moduleD); - assertDeepestCommonDep(null, moduleA, moduleE); - assertDeepestCommonDep(null, moduleA, moduleF); - assertDeepestCommonDep(moduleA, moduleB, moduleB); - assertDeepestCommonDep(moduleA, moduleB, moduleC); - assertDeepestCommonDep(moduleA, moduleB, moduleD); - assertDeepestCommonDep(moduleA, moduleB, moduleE); - assertDeepestCommonDep(moduleA, moduleB, moduleF); - assertDeepestCommonDep(moduleA, moduleC, moduleC); - assertDeepestCommonDep(moduleA, moduleC, moduleD); - assertDeepestCommonDep(moduleA, moduleC, moduleE); - assertDeepestCommonDep(moduleA, moduleC, moduleF); - assertDeepestCommonDep(moduleB, moduleD, moduleD); - assertDeepestCommonDep(moduleB, moduleD, moduleE); - assertDeepestCommonDep(moduleB, moduleD, moduleF); - assertDeepestCommonDep(moduleC, moduleE, moduleE); - assertDeepestCommonDep(moduleC, moduleE, moduleF); - assertDeepestCommonDep(moduleE, moduleF, moduleF); + assertDeepestCommonDep(null, chunkA, chunkA); + assertDeepestCommonDep(null, chunkA, chunkB); + assertDeepestCommonDep(null, chunkA, chunkC); + assertDeepestCommonDep(null, chunkA, chunkD); + assertDeepestCommonDep(null, chunkA, chunkE); + assertDeepestCommonDep(null, chunkA, chunkF); + assertDeepestCommonDep(chunkA, chunkB, chunkB); + assertDeepestCommonDep(chunkA, chunkB, chunkC); + assertDeepestCommonDep(chunkA, chunkB, chunkD); + assertDeepestCommonDep(chunkA, chunkB, chunkE); + assertDeepestCommonDep(chunkA, chunkB, chunkF); + assertDeepestCommonDep(chunkA, chunkC, chunkC); + assertDeepestCommonDep(chunkA, chunkC, chunkD); + assertDeepestCommonDep(chunkA, chunkC, chunkE); + assertDeepestCommonDep(chunkA, chunkC, chunkF); + assertDeepestCommonDep(chunkB, chunkD, chunkD); + assertDeepestCommonDep(chunkB, chunkD, chunkE); + assertDeepestCommonDep(chunkB, chunkD, chunkF); + assertDeepestCommonDep(chunkC, chunkE, chunkE); + assertDeepestCommonDep(chunkC, chunkE, chunkF); + assertDeepestCommonDep(chunkE, chunkF, chunkF); } @Test public void testDeepestCommonDepInclusive() { makeDeps(); makeGraph(); - assertDeepestCommonDepInclusive(moduleA, moduleA, moduleA); - assertDeepestCommonDepInclusive(moduleA, moduleA, moduleB); - assertDeepestCommonDepInclusive(moduleA, moduleA, moduleC); - assertDeepestCommonDepInclusive(moduleA, moduleA, moduleD); - assertDeepestCommonDepInclusive(moduleA, moduleA, moduleE); - assertDeepestCommonDepInclusive(moduleA, moduleA, moduleF); - assertDeepestCommonDepInclusive(moduleB, moduleB, moduleB); - assertDeepestCommonDepInclusive(moduleA, moduleB, moduleC); - assertDeepestCommonDepInclusive(moduleB, moduleB, moduleD); - assertDeepestCommonDepInclusive(moduleB, moduleB, moduleE); - assertDeepestCommonDepInclusive(moduleB, moduleB, moduleF); - assertDeepestCommonDepInclusive(moduleC, moduleC, moduleC); - assertDeepestCommonDepInclusive(moduleA, moduleC, moduleD); - assertDeepestCommonDepInclusive(moduleC, moduleC, moduleE); - assertDeepestCommonDepInclusive(moduleC, moduleC, moduleF); - assertDeepestCommonDepInclusive(moduleD, moduleD, moduleD); - assertDeepestCommonDepInclusive(moduleB, moduleD, moduleE); - assertDeepestCommonDepInclusive(moduleB, moduleD, moduleF); - assertDeepestCommonDepInclusive(moduleE, moduleE, moduleE); - assertDeepestCommonDepInclusive(moduleE, moduleE, moduleF); - assertDeepestCommonDepInclusive(moduleF, moduleF, moduleF); + assertDeepestCommonDepInclusive(chunkA, chunkA, chunkA); + assertDeepestCommonDepInclusive(chunkA, chunkA, chunkB); + assertDeepestCommonDepInclusive(chunkA, chunkA, chunkC); + assertDeepestCommonDepInclusive(chunkA, chunkA, chunkD); + assertDeepestCommonDepInclusive(chunkA, chunkA, chunkE); + assertDeepestCommonDepInclusive(chunkA, chunkA, chunkF); + assertDeepestCommonDepInclusive(chunkB, chunkB, chunkB); + assertDeepestCommonDepInclusive(chunkA, chunkB, chunkC); + assertDeepestCommonDepInclusive(chunkB, chunkB, chunkD); + assertDeepestCommonDepInclusive(chunkB, chunkB, chunkE); + assertDeepestCommonDepInclusive(chunkB, chunkB, chunkF); + assertDeepestCommonDepInclusive(chunkC, chunkC, chunkC); + assertDeepestCommonDepInclusive(chunkA, chunkC, chunkD); + assertDeepestCommonDepInclusive(chunkC, chunkC, chunkE); + assertDeepestCommonDepInclusive(chunkC, chunkC, chunkF); + assertDeepestCommonDepInclusive(chunkD, chunkD, chunkD); + assertDeepestCommonDepInclusive(chunkB, chunkD, chunkE); + assertDeepestCommonDepInclusive(chunkB, chunkD, chunkF); + assertDeepestCommonDepInclusive(chunkE, chunkE, chunkE); + assertDeepestCommonDepInclusive(chunkE, chunkE, chunkF); + assertDeepestCommonDepInclusive(chunkF, chunkF, chunkF); } @Test public void testSmallestCoveringSubtree() { makeDeps(); makeGraph(); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleA, moduleA); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleA, moduleB); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleA, moduleC); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleA, moduleD); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleA, moduleE); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleA, moduleF); - assertSmallestCoveringSubtree(moduleB, moduleA, moduleB, moduleB); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleB, moduleC); - assertSmallestCoveringSubtree(moduleB, moduleA, moduleB, moduleD); - assertSmallestCoveringSubtree(moduleB, moduleA, moduleB, moduleE); - assertSmallestCoveringSubtree(moduleB, moduleA, moduleB, moduleF); - assertSmallestCoveringSubtree(moduleC, moduleA, moduleC, moduleC); - assertSmallestCoveringSubtree(moduleA, moduleA, moduleC, moduleD); - assertSmallestCoveringSubtree(moduleC, moduleA, moduleC, moduleE); - assertSmallestCoveringSubtree(moduleC, moduleA, moduleC, moduleF); - assertSmallestCoveringSubtree(moduleD, moduleA, moduleD, moduleD); - assertSmallestCoveringSubtree(moduleB, moduleA, moduleD, moduleE); - assertSmallestCoveringSubtree(moduleB, moduleA, moduleD, moduleF); - assertSmallestCoveringSubtree(moduleE, moduleA, moduleE, moduleE); - assertSmallestCoveringSubtree(moduleE, moduleA, moduleE, moduleF); - assertSmallestCoveringSubtree(moduleF, moduleA, moduleF, moduleF); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkA, chunkA); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkA, chunkB); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkA, chunkC); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkA, chunkD); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkA, chunkE); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkA, chunkF); + assertSmallestCoveringSubtree(chunkB, chunkA, chunkB, chunkB); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkB, chunkC); + assertSmallestCoveringSubtree(chunkB, chunkA, chunkB, chunkD); + assertSmallestCoveringSubtree(chunkB, chunkA, chunkB, chunkE); + assertSmallestCoveringSubtree(chunkB, chunkA, chunkB, chunkF); + assertSmallestCoveringSubtree(chunkC, chunkA, chunkC, chunkC); + assertSmallestCoveringSubtree(chunkA, chunkA, chunkC, chunkD); + assertSmallestCoveringSubtree(chunkC, chunkA, chunkC, chunkE); + assertSmallestCoveringSubtree(chunkC, chunkA, chunkC, chunkF); + assertSmallestCoveringSubtree(chunkD, chunkA, chunkD, chunkD); + assertSmallestCoveringSubtree(chunkB, chunkA, chunkD, chunkE); + assertSmallestCoveringSubtree(chunkB, chunkA, chunkD, chunkF); + assertSmallestCoveringSubtree(chunkE, chunkA, chunkE, chunkE); + assertSmallestCoveringSubtree(chunkE, chunkA, chunkE, chunkF); + assertSmallestCoveringSubtree(chunkF, chunkA, chunkF, chunkF); } @Test public void testGetTransitiveDepsDeepestFirst() { makeDeps(); makeGraph(); - assertTransitiveDepsDeepestFirst(moduleA); - assertTransitiveDepsDeepestFirst(moduleB, moduleA); - assertTransitiveDepsDeepestFirst(moduleC, moduleA); - assertTransitiveDepsDeepestFirst(moduleD, moduleB, moduleA); - assertTransitiveDepsDeepestFirst(moduleE, moduleC, moduleB, moduleA); - assertTransitiveDepsDeepestFirst(moduleF, moduleE, moduleC, moduleB, moduleA); + assertTransitiveDepsDeepestFirst(chunkA); + assertTransitiveDepsDeepestFirst(chunkB, chunkA); + assertTransitiveDepsDeepestFirst(chunkC, chunkA); + assertTransitiveDepsDeepestFirst(chunkD, chunkB, chunkA); + assertTransitiveDepsDeepestFirst(chunkE, chunkC, chunkB, chunkA); + assertTransitiveDepsDeepestFirst(chunkF, chunkE, chunkC, chunkB, chunkA); } @Test @@ -349,10 +342,10 @@ public void testManageDependenciesLooseWithoutEntryPoint() throws Exception { DependencyOptions depOptions = DependencyOptions.pruneLegacyForEntryPoints(ImmutableList.of()); ImmutableList results = graph.manageDependencies(compiler, depOptions); - assertInputs(moduleA, "a1", "a3"); - assertInputs(moduleB, "a2", "b2"); - assertInputs(moduleC); // no inputs - assertInputs(moduleE, "c1", "e1", "e2"); + assertInputs(chunkA, "a1", "a3"); + assertInputs(chunkB, "a2", "b2"); + assertInputs(chunkC); // no inputs + assertInputs(chunkE, "c1", "e1", "e2"); assertThat(sourceNames(results)) .isEqualTo(ImmutableList.of("a1", "a3", "a2", "b2", "c1", "e1", "e2")); @@ -368,10 +361,10 @@ public void testManageDependenciesLooseWithEntryPoint() throws Exception { ImmutableList.of(ModuleIdentifier.forClosure("c2"))); ImmutableList results = graph.manageDependencies(compiler, depOptions); - assertInputs(moduleA, "a1", "a3"); - assertInputs(moduleB, "a2", "b2"); - assertInputs(moduleC, "c1", "c2"); - assertInputs(moduleE, "e1", "e2"); + assertInputs(chunkA, "a1", "a3"); + assertInputs(chunkB, "a2", "b2"); + assertInputs(chunkC, "c1", "c2"); + assertInputs(chunkE, "e1", "e2"); assertThat(sourceNames(results)) .isEqualTo(ImmutableList.of("a1", "a3", "a2", "b2", "c1", "c2", "e1", "e2")); @@ -388,10 +381,10 @@ public void testManageDependenciesStrictWithEntryPoint() throws Exception { // Everything gets pushed up into module c, because that's // the only one that has entry points. - assertInputs(moduleA); - assertInputs(moduleB); - assertInputs(moduleC, "a1", "c1", "c2"); - assertInputs(moduleE); + assertInputs(chunkA); + assertInputs(chunkB); + assertInputs(chunkC, "a1", "c1", "c2"); + assertInputs(chunkE); assertThat(sourceNames(results)).containsExactly("a1", "c1", "c2").inOrder(); } @@ -451,10 +444,10 @@ public void testManageDependenciesSortOnly() throws Exception { ImmutableList results = graph.manageDependencies(compiler, DependencyOptions.sortOnly()); - assertInputs(moduleA, "a1", "a2", "a3"); - assertInputs(moduleB, "b1", "b2"); - assertInputs(moduleC, "c1", "c2"); - assertInputs(moduleE, "e1", "e2"); + assertInputs(chunkA, "a1", "a2", "a3"); + assertInputs(chunkB, "b1", "b2"); + assertInputs(chunkC, "c1", "c2"); + assertInputs(chunkE, "e1", "e2"); assertThat(sourceNames(results)) .isEqualTo(ImmutableList.of("a1", "a2", "a3", "b1", "b2", "c1", "c2", "e1", "e2")); @@ -472,18 +465,18 @@ public void testManageDependenciesSortOnly() throws Exception { public void testManageDependenciesSortOnlyImpl() throws Exception { makeDeps(); makeGraph(); - moduleA.add(code("a2", provides("a2"), requires("a1"))); - moduleA.add(code("a1", provides("a1"), requires())); - moduleA.add(code("base.js", BASEJS, provides(), requires())); + chunkA.add(code("a2", provides("a2"), requires("a1"))); + chunkA.add(code("a1", provides("a1"), requires())); + chunkA.add(code("base.js", BASEJS, provides(), requires())); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } ImmutableList results = graph.manageDependencies(compiler, DependencyOptions.sortOnly()); - assertInputs(moduleA, "base.js", "a1", "a2"); + assertInputs(chunkA, "base.js", "a1", "a2"); assertThat(sourceNames(results)).containsExactly("base.js", "a1", "a2").inOrder(); } @@ -511,8 +504,8 @@ public void testToJson() { assertThat(m.get("inputs")).isNotNull(); } JsonObject m = modules.get(3).getAsJsonObject(); - assertThat(m.get("name").getAsString()).isEqualTo("moduleD"); - assertThat(m.get("dependencies").getAsJsonArray().toString()).isEqualTo("[\"moduleB\"]"); + assertThat(m.get("name").getAsString()).isEqualTo("chunkD"); + assertThat(m.get("dependencies").getAsJsonArray().toString()).isEqualTo("[\"chunkB\"]"); assertThat(m.get("transitive-dependencies").getAsJsonArray()).hasSize(2); assertThat(m.get("inputs").getAsJsonArray().toString()).isEqualTo("[]"); } @@ -520,23 +513,23 @@ public void testToJson() { private List setUpManageDependenciesTest() { List inputs = new ArrayList<>(); - moduleA.add(code("a1", provides("a1"), requires())); - moduleA.add(code("a2", provides("a2"), requires("a1"))); - moduleA.add(code("a3", provides(), requires("a1"))); + chunkA.add(code("a1", provides("a1"), requires())); + chunkA.add(code("a2", provides("a2"), requires("a1"))); + chunkA.add(code("a3", provides(), requires("a1"))); - moduleB.add(code("b1", provides("b1"), requires("a2"))); - moduleB.add(code("b2", provides(), requires("a1", "a2"))); + chunkB.add(code("b1", provides("b1"), requires("a2"))); + chunkB.add(code("b2", provides(), requires("a1", "a2"))); - moduleC.add(code("c1", provides("c1"), requires("a1"))); - moduleC.add(code("c2", provides("c2"), requires("c1"))); + chunkC.add(code("c1", provides("c1"), requires("a1"))); + chunkC.add(code("c2", provides("c2"), requires("c1"))); - moduleE.add(code("e1", provides(), requires("c1"))); - moduleE.add(code("e2", provides(), requires("c1"))); + chunkE.add(code("e1", provides(), requires("c1"))); + chunkE.add(code("e2", provides(), requires("c1"))); - inputs.addAll(moduleA.getInputs()); - inputs.addAll(moduleB.getInputs()); - inputs.addAll(moduleC.getInputs()); - inputs.addAll(moduleE.getInputs()); + inputs.addAll(chunkA.getInputs()); + inputs.addAll(chunkB.getInputs()); + inputs.addAll(chunkC.getInputs()); + inputs.addAll(chunkE.getInputs()); for (CompilerInput input : inputs) { input.setCompiler(compiler); @@ -565,18 +558,18 @@ public void testGoogBaseOrderedCorrectly() throws Exception { DependencyOptions.pruneForEntryPoints(ImmutableList.of(ModuleIdentifier.forClosure("a1"))); for (int i = 0; i < 10; i++) { shuffle(sourceFiles); - moduleA.removeAll(); + chunkA.removeAll(); for (SourceFile sourceFile : sourceFiles) { - moduleA.add(sourceFile); + chunkA.add(sourceFile); } - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } ImmutableList results = graph.manageDependencies(compiler, depOptions); - assertInputs(moduleA, "base.js", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a1"); + assertInputs(chunkA, "base.js", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a1"); assertThat(sourceNames(results)) .containsExactly("base.js", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a1") @@ -619,12 +612,12 @@ public void testProperEs6ModuleOrdering() throws Exception { ImmutableList.of(ModuleIdentifier.forFile("/entry.js"))); for (int iterationCount = 0; iterationCount < 10; iterationCount++) { shuffle(sourceFiles); - moduleA.removeAll(); + chunkA.removeAll(); for (SourceFile sourceFile : sourceFiles) { - moduleA.add(sourceFile); + chunkA.add(sourceFile); } - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); for (String require : orderedRequires.get(input.getSourceFile().getName())) { input.addOrderedRequire(Require.compilerModule(require)); @@ -635,7 +628,7 @@ public void testProperEs6ModuleOrdering() throws Exception { ImmutableList results = graph.manageDependencies(compiler, depOptions); assertInputs( - moduleA, + chunkA, "/b/c.js", "/b/b.js", "/b/a.js", @@ -660,12 +653,12 @@ public void testMoveMarkedWeakSources() throws Exception { SourceFile strong1 = SourceFile.fromCode("strong1", "", SourceKind.STRONG); SourceFile strong2 = SourceFile.fromCode("strong2", "", SourceKind.STRONG); - moduleA.add(weak1); - moduleA.add(strong1); - moduleA.add(weak2); - moduleA.add(strong2); + chunkA.add(weak1); + chunkA.add(strong1); + chunkA.add(weak2); + chunkA.add(strong2); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -673,7 +666,7 @@ public void testMoveMarkedWeakSources() throws Exception { assertThat(getWeakModule().getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(weak1, weak2); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(strong1, strong2); } @@ -686,12 +679,12 @@ public void testMoveMarkedWeakSourcesDuringManageDepsSortOnly() throws Exception SourceFile strong1 = SourceFile.fromCode("strong1", "", SourceKind.STRONG); SourceFile strong2 = SourceFile.fromCode("strong2", "", SourceKind.STRONG); - moduleA.add(weak1); - moduleA.add(strong1); - moduleA.add(weak2); - moduleA.add(strong2); + chunkA.add(weak1); + chunkA.add(strong1); + chunkA.add(weak2); + chunkA.add(strong2); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -700,7 +693,7 @@ public void testMoveMarkedWeakSourcesDuringManageDepsSortOnly() throws Exception assertThat(getWeakModule().getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(weak1, weak2); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(strong1, strong2); } @@ -713,12 +706,12 @@ public void testIgnoreMarkedWeakSourcesDuringManageDepsPrune() throws Exception SourceFile strong1 = SourceFile.fromCode("strong1", "", SourceKind.STRONG); SourceFile strong2 = SourceFile.fromCode("strong2", "", SourceKind.STRONG); - moduleA.add(weak1); - moduleA.add(strong1); - moduleA.add(weak2); - moduleA.add(strong2); + chunkA.add(weak1); + chunkA.add(strong1); + chunkA.add(weak2); + chunkA.add(strong2); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -734,7 +727,7 @@ public void testIgnoreMarkedWeakSourcesDuringManageDepsPrune() throws Exception .map(CompilerInput::getSourceFile) .collect(Collectors.toList())) .isEmpty(); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(strong1, strong2); } @@ -753,14 +746,14 @@ public void testIgnoreDepsOfMarkedWeakSourcesDuringManageDepsPrune() throws Exce SourceFile strong1 = SourceFile.fromCode("strong1", "", SourceKind.STRONG); SourceFile strong2 = SourceFile.fromCode("strong2", "", SourceKind.STRONG); - moduleA.add(weak1); - moduleA.add(strong1); - moduleA.add(weak2); - moduleA.add(strong2); - moduleA.add(weak1weak); - moduleA.add(weak2strong); + chunkA.add(weak1); + chunkA.add(strong1); + chunkA.add(weak2); + chunkA.add(strong2); + chunkA.add(weak1weak); + chunkA.add(weak2strong); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -776,7 +769,7 @@ public void testIgnoreDepsOfMarkedWeakSourcesDuringManageDepsPrune() throws Exce .map(CompilerInput::getSourceFile) .collect(Collectors.toList())) .isEmpty(); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(strong1, strong2); } @@ -788,11 +781,11 @@ public void testMoveImplicitWeakSourcesFromMoocherDuringManageDepsLegacyPrune() SourceFile strong = SourceFile.fromCode("strong", ""); SourceFile moocher = SourceFile.fromCode("moocher", "goog.requireType('weak');"); - moduleA.add(weak); - moduleA.add(strong); - moduleA.add(moocher); + chunkA.add(weak); + chunkA.add(strong); + chunkA.add(moocher); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -804,7 +797,7 @@ public void testMoveImplicitWeakSourcesFromMoocherDuringManageDepsLegacyPrune() assertThat(getWeakModule().getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(weak); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(strong, moocher); } @@ -817,12 +810,12 @@ public void testImplicitWeakSourcesNotMovedDuringManageDepsSortOnly() throws Exc SourceFile strong1 = SourceFile.fromCode("strong1", "goog.requireType('weak1');"); SourceFile strong2 = SourceFile.fromCode("strong2", "goog.requireType('weak2');"); - moduleA.add(weak1); - moduleA.add(strong1); - moduleA.add(weak2); - moduleA.add(strong2); + chunkA.add(weak1); + chunkA.add(strong1); + chunkA.add(weak2); + chunkA.add(strong2); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -830,7 +823,7 @@ public void testImplicitWeakSourcesNotMovedDuringManageDepsSortOnly() throws Exc graph.manageDependencies(compiler, DependencyOptions.sortOnly()); assertThat(getWeakModule().getInputs()).isEmpty(); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(weak1, strong1, weak2, strong2); } @@ -843,12 +836,12 @@ public void testImplicitWeakSourcesMovedDuringManageDepsPrune() throws Exception SourceFile strong1 = SourceFile.fromCode("strong1", "goog.requireType('weak1');"); SourceFile strong2 = SourceFile.fromCode("strong2", "goog.requireType('weak2');"); - moduleA.add(weak1); - moduleA.add(strong1); - moduleA.add(weak2); - moduleA.add(strong2); + chunkA.add(weak1); + chunkA.add(strong1); + chunkA.add(weak2); + chunkA.add(strong2); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -861,7 +854,7 @@ public void testImplicitWeakSourcesMovedDuringManageDepsPrune() throws Exception assertThat(getWeakModule().getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(weak1, weak2); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(strong1, strong2); } @@ -880,13 +873,13 @@ public void testTransitiveWeakSources() throws Exception { SourceFile weak3 = SourceFile.fromCode("weak3", "goog.provide('weak3');"); SourceFile strong1 = SourceFile.fromCode("strong1", "goog.requireType('weak1');"); - moduleA.add(weak1); - moduleA.add(strong1); - moduleA.add(weak2); - moduleA.add(weak3); - moduleA.add(strongFromWeak); + chunkA.add(weak1); + chunkA.add(strong1); + chunkA.add(weak2); + chunkA.add(weak3); + chunkA.add(strongFromWeak); - for (CompilerInput input : moduleA.getInputs()) { + for (CompilerInput input : chunkA.getInputs()) { input.setCompiler(compiler); } @@ -898,12 +891,12 @@ public void testTransitiveWeakSources() throws Exception { assertThat(getWeakModule().getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(weak1, weak2, weak3, strongFromWeak); - assertThat(moduleA.getInputs().stream().map(CompilerInput::getSourceFile)) + assertThat(chunkA.getInputs().stream().map(CompilerInput::getSourceFile)) .containsExactly(strong1); } - private void assertInputs(JSChunk module, String... sourceNames) { - assertThat(sourceNames(module.getInputs())).isEqualTo(ImmutableList.copyOf(sourceNames)); + private void assertInputs(JSChunk chunk, String... sourceNames) { + assertThat(sourceNames(chunk.getInputs())).isEqualTo(ImmutableList.copyOf(sourceNames)); } private List sourceNames(List inputs) { diff --git a/test/com/google/javascript/jscomp/JSModuleTest.java b/test/com/google/javascript/jscomp/JSModuleTest.java index 7db857a2ba7..d9208780655 100644 --- a/test/com/google/javascript/jscomp/JSModuleTest.java +++ b/test/com/google/javascript/jscomp/JSModuleTest.java @@ -95,7 +95,7 @@ private void assertSortedInputs(List expected, Listof(), ImmutableList.of(module), createCompilerOptions()); + JSChunk chunk = new JSChunk("m0"); + chunk.add(new CompilerInput(ast)); + var unused = + compiler.compileChunks( + ImmutableList.of(), ImmutableList.of(chunk), createCompilerOptions()); Node mainRoot = compiler.getRoot().getLastChild(); diff --git a/test/com/google/javascript/jscomp/RemoveWeakSourcesTest.java b/test/com/google/javascript/jscomp/RemoveWeakSourcesTest.java index f3beabd537c..358b84ec4de 100644 --- a/test/com/google/javascript/jscomp/RemoveWeakSourcesTest.java +++ b/test/com/google/javascript/jscomp/RemoveWeakSourcesTest.java @@ -57,22 +57,22 @@ public void testMultipleModules() { SourceFile emptyWeakSrc3 = SourceFile.fromCode("e.js", ""); SourceFile fillFileSrc = SourceFile.fromCode("$fillFile", ""); - JSChunk moduleBefore1 = new JSChunk("m1"); - moduleBefore1.add(strongSrc1); - moduleBefore1.add(weakSrc1); - JSChunk moduleAfter1 = new JSChunk("m1"); - moduleAfter1.add(strongSrc1); + JSChunk chunkBefore1 = new JSChunk("m1"); + chunkBefore1.add(strongSrc1); + chunkBefore1.add(weakSrc1); + JSChunk chunkAfter1 = new JSChunk("m1"); + chunkAfter1.add(strongSrc1); - JSChunk moduleBefore2 = new JSChunk("m2"); - moduleBefore2.add(weakSrc2); - moduleBefore2.add(strongSrc2); - JSChunk moduleAfter2 = new JSChunk("m2"); - moduleAfter2.add(strongSrc2); + JSChunk chunkBefore2 = new JSChunk("m2"); + chunkBefore2.add(weakSrc2); + chunkBefore2.add(strongSrc2); + JSChunk chunkAfter2 = new JSChunk("m2"); + chunkAfter2.add(strongSrc2); - JSChunk moduleBefore3 = new JSChunk("m3"); - moduleBefore3.add(weakSrc3); - JSChunk moduleAfter3 = new JSChunk("m3"); - moduleAfter3.add(fillFileSrc); + JSChunk chunkBefore3 = new JSChunk("m3"); + chunkBefore3.add(weakSrc3); + JSChunk chunkAfter3 = new JSChunk("m3"); + chunkAfter3.add(fillFileSrc); JSChunk weakModule = new JSChunk("$weak$"); weakModule.add(emptyWeakSrc1); @@ -81,7 +81,7 @@ public void testMultipleModules() { // Expect the weak sources to be emptied and moved to a separate final module. test( - srcs(new JSChunk[] {moduleBefore1, moduleBefore2, moduleBefore3}), - expected(new JSChunk[] {moduleAfter1, moduleAfter2, moduleAfter3, weakModule})); + srcs(new JSChunk[] {chunkBefore1, chunkBefore2, chunkBefore3}), + expected(new JSChunk[] {chunkAfter1, chunkAfter2, chunkAfter3, weakModule})); } } diff --git a/test/com/google/javascript/jscomp/RenamePropertiesTest.java b/test/com/google/javascript/jscomp/RenamePropertiesTest.java index 66d68edb096..ba1b85367c1 100644 --- a/test/com/google/javascript/jscomp/RenamePropertiesTest.java +++ b/test/com/google/javascript/jscomp/RenamePropertiesTest.java @@ -274,40 +274,40 @@ public void testGeneratePseudoNames() { } @Test - public void testModules() { - String module1Js = + public void testChunks() { + String chunk1Js = "function Bar(){} Bar.prototype.getA=function(x){};" + "var foo;foo.getA(foo);foo.doo=foo;foo.bloo=foo;"; - String module2Js = + String chunk2Js = "function Far(){} Far.prototype.getB=function(y){};" + "var too;too.getB(too);too.woo=too;too.bloo=too;"; - String module3Js = + String chunk3Js = "function Car(){} Car.prototype.getC=function(z){};" + "var noo;noo.getC(noo);noo.zoo=noo;noo.cloo=noo;"; - JSChunk module1 = new JSChunk("m1"); - module1.add(SourceFile.fromCode("input1", module1Js)); + JSChunk chunk1 = new JSChunk("m1"); + chunk1.add(SourceFile.fromCode("input1", chunk1Js)); - JSChunk module2 = new JSChunk("m2"); - module2.add(SourceFile.fromCode("input2", module2Js)); + JSChunk chunk2 = new JSChunk("m2"); + chunk2.add(SourceFile.fromCode("input2", chunk2Js)); - JSChunk module3 = new JSChunk("m3"); - module3.add(SourceFile.fromCode("input3", module3Js)); + JSChunk chunk3 = new JSChunk("m3"); + chunk3.add(SourceFile.fromCode("input3", chunk3Js)); - JSChunk[] modules = new JSChunk[] {module1, module2, module3}; - Compiler compiler = compileModules("", modules); + JSChunk[] chunks = new JSChunk[] {chunk1, chunk2, chunk3}; + Compiler compiler = compileChunks("", chunks); Result result = compiler.getResult(); assertThat(result.success).isTrue(); - assertThat(compiler.toSource(module1)) + assertThat(compiler.toSource(chunk1)) .isEqualTo( "function Bar(){}Bar.prototype.b=function(x){};" + "var foo;foo.b(foo);foo.f=foo;foo.a=foo;"); - assertThat(compiler.toSource(module2)) + assertThat(compiler.toSource(chunk2)) .isEqualTo( "function Far(){}Far.prototype.c=function(y){};" + "var too;too.c(too);too.g=too;too.a=too;"); @@ -315,10 +315,10 @@ public void testModules() { // Note that properties that occur most often globally get the earliest // names. The "getC" property, which doesn't occur until module 3, is // renamed to an earlier name in the alphabet than "woo", which appears - // in module 2, because "getC" occurs more total times across all modules. - // Might be better to give early modules the shortest names, but this is + // in module 2, because "getC" occurs more total times across all chunks. + // Might be better to give early chunks the shortest names, but this is // how the pass currently works. - assertThat(compiler.toSource(module3)) + assertThat(compiler.toSource(chunk3)) .isEqualTo( "function Car(){}Car.prototype.d=function(z){};" + "var noo;noo.d(noo);noo.h=noo;noo.e=noo;"); @@ -787,7 +787,7 @@ public void testObjectMethodProperty() { lines("var foo = { ", " a: 1, ", " b() {", " return this.a", " }", "};", "foo.b();")); } - private Compiler compileModules(String externs, JSChunk[] modules) { + private Compiler compileChunks(String externs, JSChunk[] chunks) { SourceFile externsInput = SourceFile.fromCode("externs", externs); CompilerOptions options = new CompilerOptions(); @@ -795,7 +795,9 @@ private Compiler compileModules(String externs, JSChunk[] modules) { options.setPropertyRenaming(PropertyRenamingPolicy.ALL_UNQUOTED); Compiler compiler = new Compiler(); - compiler.compileModules(ImmutableList.of(externsInput), ImmutableList.copyOf(modules), options); + var unused = + compiler.compileChunks( + ImmutableList.of(externsInput), ImmutableList.copyOf(chunks), options); return compiler; } diff --git a/test/com/google/javascript/jscomp/TypeInferenceTest.java b/test/com/google/javascript/jscomp/TypeInferenceTest.java index 3895fe9aa9b..0e9e4bdf9a2 100644 --- a/test/com/google/javascript/jscomp/TypeInferenceTest.java +++ b/test/com/google/javascript/jscomp/TypeInferenceTest.java @@ -198,12 +198,12 @@ private void inGenerator(String js) { private void withModules(ImmutableList js) { Node script = compiler.parseTestCode(js); - JSChunk module = new JSChunk("entry"); + JSChunk chunk = new JSChunk("entry"); Collection inputs = compiler.getInputsById().values(); for (CompilerInput input : inputs) { - module.add(input.getSourceFile()); + chunk.add(input.getSourceFile()); } - compiler.initModules(ImmutableList.of(), ImmutableList.of(module), compiler.getOptions()); + compiler.initChunks(ImmutableList.of(), ImmutableList.of(chunk), compiler.getOptions()); compiler.initializeModuleLoader(); assertWithMessage("parsing error: " + Joiner.on(", ").join(compiler.getErrors())) .that(compiler.getErrorCount()) diff --git a/test/com/google/javascript/jscomp/UnitTestUtils.java b/test/com/google/javascript/jscomp/UnitTestUtils.java index cb42c804308..d2bfe8d024a 100644 --- a/test/com/google/javascript/jscomp/UnitTestUtils.java +++ b/test/com/google/javascript/jscomp/UnitTestUtils.java @@ -40,7 +40,7 @@ public final class UnitTestUtils { * `TAGGED_TEMPLATE_TMP_VAR` in the test sources. This function replaces that generic name by a * specific name consisting of the runtime-computed uniqueID before test execution. * - * @param inputs input FlatSources. Does not work for ModuleSources. + * @param inputs input FlatSources. Does not work for ChunkSources. * @param outputs expected sources * @param replacementPrefixes mapping from generic variable names and actual variable name prefix * @return the updated output files with correct runtime variable names @@ -51,10 +51,10 @@ public static ImmutableList updateGenericVarNamesInExpectedFiles( // In FlatSources, we correspond each input SourceFile (i.e. each CompilerInput) with an // expected SourceFile. We can know what uniqueID to generate in the expected string by knowing // its CompilerInput. - // ModuleSources consist of JSChunks, and each chunk has multiple CompilerInputs which can + // ChunkSources consist of JSChunks, and each chunk has multiple CompilerInputs which can // correspond to an expected SourceFile. The uniqueID in the expected code could come from code // in any of those CompilerInputs, i.e. we do not know what uniqueID to generate in the expected - // string. Hence ModuleSources are unsupported. + // string. Hence ChunkSources are unsupported. int inLength = inputs.sources.size(); int outLength = outputs.expected.size(); Preconditions.checkArgument(inLength == outLength); diff --git a/test/com/google/javascript/jscomp/VarCheckTest.java b/test/com/google/javascript/jscomp/VarCheckTest.java index b87889a1dc9..f038e6177a7 100644 --- a/test/com/google/javascript/jscomp/VarCheckTest.java +++ b/test/com/google/javascript/jscomp/VarCheckTest.java @@ -1101,18 +1101,18 @@ public void testGoogModule_cannotBeReferencedInExterns() { @Test public void testReferenceToWeakVar_fromStrongFile() { - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - JSChunk strongModule = new JSChunk(JSChunk.STRONG_CHUNK_NAME); - weakModule.addDependency(strongModule); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk strongChunk = new JSChunk(JSChunk.STRONG_CHUNK_NAME); + weakChunk.addDependency(strongChunk); - weakModule.add(SourceFile.fromCode("weak.js", lines("var weakVar = 0;"), SourceKind.WEAK)); + weakChunk.add(SourceFile.fromCode("weak.js", lines("var weakVar = 0;"), SourceKind.WEAK)); - strongModule.add(SourceFile.fromCode("strong.js", lines("weakVar();"), SourceKind.STRONG)); + strongChunk.add(SourceFile.fromCode("strong.js", lines("weakVar();"), SourceKind.STRONG)); test( srcs( new JSChunk[] { - strongModule, weakModule, + strongChunk, weakChunk, }), error(VarCheck.VIOLATED_MODULE_DEP_ERROR), error(VarCheck.UNDEFINED_VAR_ERROR)); @@ -1120,8 +1120,8 @@ public void testReferenceToWeakVar_fromStrongFile() { @Test public void testReferenceToWeakVar_fromWeakFile() { - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - weakModule.add( + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + weakChunk.add( SourceFile.fromCode( "weak.js", lines( @@ -1129,16 +1129,16 @@ public void testReferenceToWeakVar_fromWeakFile() { "weakVar();"), SourceKind.WEAK)); - testSame(srcs(weakModule)); + testSame(srcs(weakChunk)); } @Test public void testReferenceToWeakNamespaceRoot_fromStrongFile() { - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - JSChunk strongModule = new JSChunk(JSChunk.STRONG_CHUNK_NAME); - weakModule.addDependency(strongModule); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk strongChunk = new JSChunk(JSChunk.STRONG_CHUNK_NAME); + weakChunk.addDependency(strongChunk); - weakModule.add( + weakChunk.add( SourceFile.fromCode( "weak.js", lines( @@ -1146,23 +1146,23 @@ public void testReferenceToWeakNamespaceRoot_fromStrongFile() { "goog.provide('foo.bar');"), SourceKind.WEAK)); - strongModule.add(SourceFile.fromCode("strong.js", lines("foo();"), SourceKind.STRONG)); + strongChunk.add(SourceFile.fromCode("strong.js", lines("foo();"), SourceKind.STRONG)); test( srcs( new JSChunk[] { - strongModule, weakModule, + strongChunk, weakChunk, }), error(VarCheck.UNDEFINED_VAR_ERROR)); } @Test public void testReferenceToWeakNamespaceRoot_fromStrongFile_synthesizesExtern() { - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - JSChunk strongModule = new JSChunk(JSChunk.STRONG_CHUNK_NAME); - weakModule.addDependency(strongModule); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk strongChunk = new JSChunk(JSChunk.STRONG_CHUNK_NAME); + weakChunk.addDependency(strongChunk); - weakModule.add( + weakChunk.add( SourceFile.fromCode( "weak.js", lines( @@ -1170,21 +1170,21 @@ public void testReferenceToWeakNamespaceRoot_fromStrongFile_synthesizesExtern() "goog.provide('foo.bar');"), SourceKind.WEAK)); - strongModule.add( + strongChunk.add( SourceFile.fromCode( "strong.js", lines("/** @suppress {undefinedVars} */", "foo();"), SourceKind.STRONG)); testExternChanges( - externs(""), srcs(strongModule, weakModule), expected("var foo;" + VAR_CHECK_EXTERNS)); + externs(""), srcs(strongChunk, weakChunk), expected("var foo;" + VAR_CHECK_EXTERNS)); } @Test - public void testReferenceToWeakModuleNamespaceRoot_fromStrongFile() { - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - JSChunk strongModule = new JSChunk(JSChunk.STRONG_CHUNK_NAME); - weakModule.addDependency(strongModule); + public void testReferenceToweakChunkNamespaceRoot_fromStrongFile() { + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk strongChunk = new JSChunk(JSChunk.STRONG_CHUNK_NAME); + weakChunk.addDependency(strongChunk); - weakModule.add( + weakChunk.add( SourceFile.fromCode( "weak.js", lines( @@ -1192,31 +1192,31 @@ public void testReferenceToWeakModuleNamespaceRoot_fromStrongFile() { "goog.module('foo.bar'); goog.module.declareLegacyNamespace();"), SourceKind.WEAK)); - strongModule.add(SourceFile.fromCode("strong.js", lines("foo();"), SourceKind.STRONG)); + strongChunk.add(SourceFile.fromCode("strong.js", lines("foo();"), SourceKind.STRONG)); - test(srcs(strongModule, weakModule), error(VarCheck.UNDEFINED_VAR_ERROR)); + test(srcs(strongChunk, weakChunk), error(VarCheck.UNDEFINED_VAR_ERROR)); } @Test public void testReferenceToStrongNamespaceRoot_withAdditionalWeakProvide_fromStrongFile() { - JSChunk weakModule = new JSChunk(JSChunk.WEAK_CHUNK_NAME); - JSChunk strongModule = new JSChunk(JSChunk.STRONG_CHUNK_NAME); - weakModule.addDependency(strongModule); + JSChunk weakChunk = new JSChunk(JSChunk.WEAK_CHUNK_NAME); + JSChunk strongChunk = new JSChunk(JSChunk.STRONG_CHUNK_NAME); + weakChunk.addDependency(strongChunk); - weakModule.add( + weakChunk.add( SourceFile.fromCode("weak.js", lines("goog.provide('foo.bar');"), SourceKind.WEAK)); - strongModule.add( + strongChunk.add( SourceFile.fromCode( "strong0.js", lines(TestExternsBuilder.getClosureExternsAsSource(), "goog.provide('foo.qux');"), SourceKind.STRONG)); - strongModule.add(SourceFile.fromCode("strong1.js", lines("foo();"), SourceKind.STRONG)); + strongChunk.add(SourceFile.fromCode("strong1.js", lines("foo();"), SourceKind.STRONG)); testSame( srcs( new JSChunk[] { - strongModule, weakModule, + strongChunk, weakChunk, })); } diff --git a/test/com/google/javascript/jscomp/integration/IntegrationTestCase.java b/test/com/google/javascript/jscomp/integration/IntegrationTestCase.java index 1760a820691..21735ba6513 100644 --- a/test/com/google/javascript/jscomp/integration/IntegrationTestCase.java +++ b/test/com/google/javascript/jscomp/integration/IntegrationTestCase.java @@ -327,14 +327,14 @@ protected Compiler compile(CompilerOptions options, String[] original) { } @CanIgnoreReturnValue - protected Compiler compile(CompilerOptions options, ImmutableList modules) { + protected Compiler compile(CompilerOptions options, ImmutableList chunks) { Compiler compiler = useNoninjectingCompiler ? createNoninjectingCompiler(new BlackHoleErrorManager()) : createCompiler(new BlackHoleErrorManager()); lastCompiler = compiler; - compiler.compileModules(externs, modules, options); + var unused = compiler.compileChunks(externs, chunks, options); return compiler; } diff --git a/test/com/google/javascript/jscomp/integration/TypedAstIntegrationTest.java b/test/com/google/javascript/jscomp/integration/TypedAstIntegrationTest.java index 9980cdaaee7..f626f0fbe4c 100644 --- a/test/com/google/javascript/jscomp/integration/TypedAstIntegrationTest.java +++ b/test/com/google/javascript/jscomp/integration/TypedAstIntegrationTest.java @@ -630,7 +630,7 @@ public void testCrossChunkMethodMotion() throws IOException { // run compilation try (InputStream inputStream = toInputStream(this.shards)) { - compiler.initModulesWithTypedAstFilesystem( + compiler.initChunksWithTypedAstFilesystem( ImmutableList.copyOf(this.externFiles), ImmutableList.of(chunk1, chunk2), options,