Search in sources :

Example 1 with LogFile

use of com.google.javascript.jscomp.diagnostic.LogFile in project closure-compiler by google.

the class OptimizeReturns method process.

@Override
public void process(Node externs, Node root, ReferenceMap definitions) {
    try (LogFile logFile = compiler.createOrReopenIndexedLog(this.getClass(), "decisions.log")) {
        // avoid passing the log file through a bunch of methods
        decisionsLog = logFile;
        // Find all function nodes whose callers ignore the return values.
        List<ArrayList<Node>> toOptimize = new ArrayList<>();
        // Find all the candidates before modifying the AST.
        for (Entry<String, ArrayList<Node>> entry : definitions.getNameReferences()) {
            String key = entry.getKey();
            ArrayList<Node> refs = entry.getValue();
            if (isCandidate(key, refs)) {
                decisionsLog.log("name %s\tremoving return value", key);
                toOptimize.add(refs);
            }
        }
        for (Entry<String, ArrayList<Node>> entry : definitions.getPropReferences()) {
            String key = entry.getKey();
            ArrayList<Node> refs = entry.getValue();
            if (isCandidate(key, refs)) {
                decisionsLog.log("property %s\tremoving return value", key);
                toOptimize.add(refs);
            }
        }
        // Now modify the AST
        for (ArrayList<Node> refs : toOptimize) {
            for (Node fn : ReferenceMap.getFunctionNodes(refs).values()) {
                rewriteReturns(fn);
            }
        }
    } finally {
        decisionsLog = null;
    }
}
Also used : LogFile(com.google.javascript.jscomp.diagnostic.LogFile) Node(com.google.javascript.rhino.Node) ArrayList(java.util.ArrayList)

Example 2 with LogFile

use of com.google.javascript.jscomp.diagnostic.LogFile in project closure-compiler by google.

the class OptimizeParameters method process.

@Override
public void process(Node externs, Node root, ReferenceMap refMap) {
    try (LogFile decisionsLog = compiler.createOrReopenIndexedLog(this.getClass(), "decisions.log")) {
        // Save the LogFile into a field to avoid bucket-brigade passing it through a bunch of methods
        this.decisionsLog = decisionsLog;
        this.globalScope = refMap.getGlobalScope();
        // Find all function nodes that are possible candidates for parameter removal.
        List<ArrayList<Node>> toOptimize = new ArrayList<>();
        for (Map.Entry<String, ArrayList<Node>> entry : refMap.getNameReferences()) {
            String key = entry.getKey();
            ArrayList<Node> refs = entry.getValue();
            final CandidateAnalysis candidateAnalysis = analyzeCandidateName(key, refs);
            if (candidateAnalysis.shouldConvertTaggedTemplateLiterals()) {
                candidateAnalysis.convertTaggedTemplateLiterals();
            }
            if (candidateAnalysis.isSafeToOptimize()) {
                toOptimize.add(refs);
            }
        }
        for (Map.Entry<String, ArrayList<Node>> entry : refMap.getPropReferences()) {
            String key = entry.getKey();
            ArrayList<Node> refs = entry.getValue();
            final CandidateAnalysis candidateAnalysis = analyzeCandidateProperty(key, refs);
            if (candidateAnalysis.shouldConvertTaggedTemplateLiterals()) {
                candidateAnalysis.convertTaggedTemplateLiterals();
            }
            if (candidateAnalysis.isSafeToOptimize()) {
                toOptimize.add(refs);
            }
        }
        for (ArrayList<Node> refs : toOptimize) {
            tryEliminateOptionalArgs(refs);
        }
        for (ArrayList<Node> refs : toOptimize) {
            tryEliminateConstantArgs(refs);
        }
        // tryEliminateUnusedArgs may mutate
        UnusedParameterOptimizer optimizer = new UnusedParameterOptimizer();
        for (ArrayList<Node> refs : toOptimize) {
            optimizer.tryEliminateUnusedArgs(refs);
        }
        optimizer.applyChanges();
    } finally {
        this.decisionsLog = null;
    }
}
Also used : LogFile(com.google.javascript.jscomp.diagnostic.LogFile) Node(com.google.javascript.rhino.Node) ArrayList(java.util.ArrayList) ReferenceMap(com.google.javascript.jscomp.OptimizeCalls.ReferenceMap) Map(java.util.Map)

Example 3 with LogFile

use of com.google.javascript.jscomp.diagnostic.LogFile in project closure-compiler by google.

the class Compiler method initModules.

/**
 * Initializes the instance state needed for a compile job if the sources are in modules.
 */
public void initModules(List<SourceFile> externs, List<JSChunk> modules, CompilerOptions options) {
    initOptions(options);
    checkFirstModule(modules);
    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.
    try {
        this.moduleGraph = new JSChunkGraph(modules);
    } catch (ChunkDependenceException e) {
        // problems with the module format.  Report as an error.  The
        // message gives all details.
        report(JSError.make(MODULE_DEPENDENCY_ERROR, e.getChunk().getName(), e.getDependentChunk().getName()));
        return;
    }
    // Creating the module graph can move weak source around, and end up with empty modules.
    fillEmptyModules(getModules());
    this.commentsPerFile = new ConcurrentHashMap<>(moduleGraph.getInputCount());
    initBasedOnOptions();
    initInputsByIdMap();
    initAST();
    // `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()));
    }
}
Also used : LogFile(com.google.javascript.jscomp.diagnostic.LogFile) ChunkDependenceException(com.google.javascript.jscomp.JSChunkGraph.ChunkDependenceException)

Example 4 with LogFile

use of com.google.javascript.jscomp.diagnostic.LogFile in project closure-compiler by google.

the class Compiler method maybePrintSourceAfterEachPass.

private void maybePrintSourceAfterEachPass(String passName) {
    if (!options.printSourceAfterEachPass) {
        return;
    }
    String currentJsSource = getCurrentJsSource();
    if (currentJsSource.equals(this.lastJsSource)) {
        return;
    }
    if (this.isDebugLoggingEnabled()) {
        try (LogFile log = this.createOrReopenIndexedLog(this.getClass(), "source_after_pass", passName)) {
            log.log(currentJsSource);
        }
    } else {
        System.err.println();
        System.err.println("// " + passName + " yields:");
        System.err.println("// ************************************");
        System.err.println(currentJsSource);
        System.err.println("// ************************************");
    }
    this.lastJsSource = currentJsSource;
}
Also used : LogFile(com.google.javascript.jscomp.diagnostic.LogFile)

Example 5 with LogFile

use of com.google.javascript.jscomp.diagnostic.LogFile in project closure-compiler by google.

the class TypeInferencePass method inferAllScopes.

/**
 * Execute type inference running over part of the scope tree.
 *
 * @return the top scope, either newly created, or patched by this inference.
 */
TypedScope inferAllScopes(Node inferenceRoot) {
    // order to propagate the type of ns.method in the outer scope.
    try (JSTypeResolver.Closer closer = this.registry.getResolver().openForDefinition()) {
        checkState(inferenceRoot.isRoot());
        checkState(inferenceRoot.getParent() == null);
        checkState(this.topScope == null);
        this.topScope = scopeCreator.createScope(inferenceRoot, null);
        NodeTraversal.builder().setCompiler(compiler).setCallback(new FirstScopeBuildingCallback()).setScopeCreator(scopeCreator).traverseWithScope(inferenceRoot, this.topScope);
        scopeCreator.resolveWeakImportsPreResolution();
    }
    scopeCreator.finishAndFreeze();
    NodeTraversal.builder().setCompiler(compiler).setCallback(new SecondScopeBuildingCallback()).setScopeCreator(scopeCreator).traverseWithScope(inferenceRoot, this.topScope);
    // Normalize TypedVars to have the '?' type instead of null after inference is complete. This
    // currently cannot be done any earlier because it breaks inference of variables assigned in
    // local scopes.
    // TODO(b/149843534): this should be a crash instead.
    final JSType unknownType = this.registry.getNativeType(UNKNOWN_TYPE);
    for (TypedVar var : this.scopeCreator.getAllSymbols()) {
        if (var.getType() == null) {
            var.setType(unknownType);
        }
    }
    if (this.stepCountHistogram != null) {
        try (LogFile histogram = this.compiler.createOrReopenLog(this.getClass(), "step_histogram.log")) {
            histogram.log("step_count token population");
            int[] totals = new int[] { 0, 0 };
            this.stepCountHistogram.keySet().stream().sorted(Comparator.<Integer>naturalOrder().reversed()).forEach((stepCount) -> this.stepCountHistogram.get(stepCount).entrySet().stream().sorted(comparingInt(Multiset.Entry::getCount)).forEach((e) -> {
                totals[0] += stepCount * e.getCount();
                totals[1] += e.getCount();
                histogram.log("%s %s %s", stepCount, e.getElement(), e.getCount());
            }));
            histogram.log("%s TOTAL %s", totals[0], totals[1]);
        }
    }
    return this.topScope;
}
Also used : LogFile(com.google.javascript.jscomp.diagnostic.LogFile) Comparator.comparingInt(java.util.Comparator.comparingInt) LinearFlowState(com.google.javascript.jscomp.DataFlowAnalysis.LinearFlowState) AssertionFunctionLookup(com.google.javascript.jscomp.CodingConvention.AssertionFunctionLookup) AbstractScopedCallback(com.google.javascript.jscomp.NodeTraversal.AbstractScopedCallback) Token(com.google.javascript.rhino.Token) JSType(com.google.javascript.rhino.jstype.JSType) DiGraphNode(com.google.javascript.jscomp.graph.DiGraph.DiGraphNode) ReverseAbstractInterpreter(com.google.javascript.jscomp.type.ReverseAbstractInterpreter) Multiset(com.google.common.collect.Multiset) UNKNOWN_TYPE(com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE) JSTypeResolver(com.google.javascript.rhino.jstype.JSTypeResolver) Preconditions.checkState(com.google.common.base.Preconditions.checkState) LinkedHashMap(java.util.LinkedHashMap) HashMultiset(com.google.common.collect.HashMultiset) JSTypeRegistry(com.google.javascript.rhino.jstype.JSTypeRegistry) LogFile(com.google.javascript.jscomp.diagnostic.LogFile) Comparator(java.util.Comparator) Node(com.google.javascript.rhino.Node) JSType(com.google.javascript.rhino.jstype.JSType) JSTypeResolver(com.google.javascript.rhino.jstype.JSTypeResolver) Multiset(com.google.common.collect.Multiset) HashMultiset(com.google.common.collect.HashMultiset)

Aggregations

LogFile (com.google.javascript.jscomp.diagnostic.LogFile)7 Node (com.google.javascript.rhino.Node)3 ArrayList (java.util.ArrayList)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 HashMultiset (com.google.common.collect.HashMultiset)1 Multiset (com.google.common.collect.Multiset)1 AssertionFunctionLookup (com.google.javascript.jscomp.CodingConvention.AssertionFunctionLookup)1 LinearFlowState (com.google.javascript.jscomp.DataFlowAnalysis.LinearFlowState)1 ChunkDependenceException (com.google.javascript.jscomp.JSChunkGraph.ChunkDependenceException)1 AbstractScopedCallback (com.google.javascript.jscomp.NodeTraversal.AbstractScopedCallback)1 ReferenceMap (com.google.javascript.jscomp.OptimizeCalls.ReferenceMap)1 DiGraphNode (com.google.javascript.jscomp.graph.DiGraph.DiGraphNode)1 ReverseAbstractInterpreter (com.google.javascript.jscomp.type.ReverseAbstractInterpreter)1 Token (com.google.javascript.rhino.Token)1 JSType (com.google.javascript.rhino.jstype.JSType)1 UNKNOWN_TYPE (com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE)1 JSTypeRegistry (com.google.javascript.rhino.jstype.JSTypeRegistry)1 JSTypeResolver (com.google.javascript.rhino.jstype.JSTypeResolver)1 Comparator (java.util.Comparator)1 Comparator.comparingInt (java.util.Comparator.comparingInt)1