com.google.javascript.jscomp.NodeTraversal Java Examples
The following examples show how to use
com.google.javascript.jscomp.NodeTraversal.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TypeConversionPass.java From clutz with MIT License | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case CLASS: addClassToScope(n); break; case EXPR_RESULT: ClassMemberDeclaration declaration = ClassMemberDeclaration.newDeclaration(n, types); if (declaration == null) { break; } if (declaration.rhs != null && declaration.rhs.isFunction()) { moveMethodsIntoClasses(declaration); } else { moveFieldsIntoClasses(declaration); } break; default: break; } }
Example #2
Source File: FileVisibilityPass.java From js-dossier with Apache License 2.0 | 6 votes |
@Override public void process(DossierCompiler compiler, Node root) { NodeTraversal.traverse( compiler, root, new NodeTraversal.AbstractShallowCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isScript()) { JsDoc docs = JsDoc.from(n.getJSDocInfo()); Visibility visibility = docs.getVisibility(); if (visibility != null && visibility != Visibility.INHERITED) { Path path = inputFs.getPath(n.getSourceFileName()); typeRegistry.setDefaultVisibility(path, visibility); } } } }); }
Example #3
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 6 votes |
@Override public void visit(NodeTraversal t, final Node n, final Node parent) { if (NodeUtil.isNameDeclaration(n)) { RequireDetector detector = new RequireDetector(); traverse(t.getCompiler(), n, detector); if (detector.foundRequire) { Node addAfter = n; for (Node last = n.getLastChild(); last != null && last != n.getFirstChild(); last = n.getLastChild()) { n.removeChild(last); Node newDecl = declaration(last, n.getToken()).srcrefTree(last); parent.addChildAfter(newDecl, addAfter); addAfter = newDecl; t.reportCodeChange(); } } } }
Example #4
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isScript()) { visitScript(t, n); } if (isCall(n, "require")) { visitRequireCall(t, n, parent); } if (n.isGetProp() && n.matchesQualifiedName("module.exports")) { if (t.getScope().getVar("module") == null) { moduleExportRefs.add(n); } } }
Example #5
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 6 votes |
@Override public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.isScript()) { checkState(currentModule == null); String sourceName = n.getSourceFileName(); Path path = inputFs.getPath(n.getSourceFileName()); if (!nodeLibrary.isModulePath(sourceName) && !modulePaths.contains(path)) { return false; } if (nodeLibrary.isModulePath(sourceName)) { currentModule = nodeLibrary.getIdFromPath(sourceName); } else { Module module = globalSymbolTable.getModule(path); checkNotNull(module, "module not found: %s", path); if (module.isEs6()) { return false; } currentModule = module.getId().getOriginalName(); } traverse(t.getCompiler(), n, new SplitRequireDeclarations()); } return true; }
Example #6
Source File: MinerrPass.java From ng-closure-runner with MIT License | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isThrow()) { if (!isMinerrInstance(n.getFirstChild())) { compiler.report(t.makeError(n, THROW_IS_NOT_MINERR_ERROR_WARNING)); unmarkInstancesBelow(n); } } if (isMinerrInstance(n)) { minerrInstances.add(n); } if (isMinerrDefinition(n)) { if (minerrDefNode == null) { minerrDefNode = n; } else { compiler.report(t.makeError(n, MULTIPLE_MINERR_DEFINITION_WARNING)); } } }
Example #7
Source File: RemoveGoogScopePass.java From clutz with MIT License | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { Node maybeCallNode = n.getFirstChild(); if (maybeCallNode == null || !maybeCallNode.isCall()) { return; } String callName = maybeCallNode.getFirstChild().getQualifiedName(); if (callName == null) { return; } switch (callName) { case "goog.provide": case "goog.require": // Register the goog.provide/require namespaces, so that we can remove any aliases. providedNamespaces.add(maybeCallNode.getLastChild().getString()); return; case "goog.scope": rewriteGoogScope(n); return; default: return; } }
Example #8
Source File: ModuleConversionPass.java From clutz with MIT License | 6 votes |
@Override public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { // Rewrite all imported variable name usages if (n.isName() || n.isGetProp()) { if (!valueRewrite.containsRow(n.getSourceFileName())) { return true; } Map<String, String> rewriteMap = valueRewrite.rowMap().get(n.getSourceFileName()); String importedNamespace = nameUtil.findLongestNamePrefix(n, rewriteMap.keySet()); // Don't rename patterns like `const rewriteCandidate = ...` if (importedNamespace != null && !isDeclaration(n)) { nameUtil.replacePrefixInName(n, importedNamespace, rewriteMap.get(importedNamespace)); return false; } } return true; }
Example #9
Source File: TypeAnnotationPass.java From clutz with MIT License | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { JSDocInfo bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo == null) { return; } // Add visibility for private and protected. if (Visibility.PRIVATE.equals(bestJSDocInfo.getVisibility())) { n.putProp(Node.ACCESS_MODIFIER, Visibility.PRIVATE); } else if (Visibility.PROTECTED.equals(bestJSDocInfo.getVisibility())) { n.putProp(Node.ACCESS_MODIFIER, Visibility.PROTECTED); } // Change variable declarations to constants if (bestJSDocInfo.isConstant() && (n.isVar() || n.isLet())) { n.setToken(Token.CONST); } }
Example #10
Source File: LinkCommentsForOneFile.java From clutz with MIT License | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (isDone()) { return; } if (n.isScript()) { // New dummy node at the end of the file Node dummy = new Node(Token.EMPTY); n.addChildToBack(dummy); while (hasRemainingComments()) { // If the new comment is separated from the current one by at least a line, // output the current group of comments. if (getFirstLineOfNextComment() - getLastLineOfCurrentComment() > 1) { dummy.getParent().addChildBefore(newFloatingCommentFromBuffer(), dummy); } addNextCommentToBuffer(); } n.addChildBefore(newFloatingCommentFromBuffer(), dummy); addNextCommentToBuffer(); n.removeChild(dummy); } }
Example #11
Source File: TypeConversionPass.java From clutz with MIT License | 6 votes |
@Override public void process(Node externs, Node root) { this.typesToRename = new LinkedHashMap<>(); this.typesToFilename = new LinkedHashMap<>(); for (Node child : root.children()) { // We convert each file independently to avoid merging class methods from different files. if (child.isScript()) { this.types = new LinkedHashMap<>(); NodeTraversal.traverse(compiler, child, new TypeConverter(this.nodeComments)); NodeTraversal.traverse(compiler, child, new TypeMemberConverter()); NodeTraversal.traverse(compiler, child, new FieldOnThisConverter()); NodeTraversal.traverse(compiler, child, new InheritanceConverter()); NodeTraversal.traverse(compiler, child, new AbstractAnnotationConverter()); NodeTraversal.traverse(compiler, child, new EnumConverter()); } } convertTypeAlias(); }
Example #12
Source File: TypeConversionPass.java From clutz with MIT License | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case VAR: case LET: case CONST: if (n.getJSDocInfo() == null || n.getJSDocInfo().getEnumParameterType() == null) return; JSTypeExpression enumExp = n.getJSDocInfo().getEnumParameterType(); if (!enumExp.getRoot().isString()) return; String enumTypeStr = enumExp.getRoot().getString(); if (!enumTypeStr.equals("number") && !enumTypeStr.equals("string")) return; Node name = n.removeFirstChild(); Node members = name.removeFirstChild(); Node enumMembers = transformMembers(members, enumTypeStr.equals("number")); Node enumNode = new Node(Token.ENUM, name, enumMembers); parent.replaceChild(n, enumNode); compiler.reportChangeToEnclosingScope(parent); break; default: break; } }
Example #13
Source File: TypeConversionPass.java From clutz with MIT License | 6 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case CLASS: case MEMBER_FUNCTION_DEF: JSDocInfo jsDoc = n.getJSDocInfo(); if (jsDoc != null && jsDoc.isAbstract()) { // This is a hack, we should be using a property like Node.IS_ABSTRACT // but it doesn't exist. So I just picked a random boolean property // that is not likely to be used on a class or member-function-def. // This is read in the GentsCodeGenerator. n.putBooleanProp(Node.WAS_PREVIOUSLY_PROVIDED, true); } break; default: break; } }
Example #14
Source File: TypeAnnotationPass.java From clutz with MIT License | 5 votes |
@Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, new TypeAnnotationConverter()); NodeTraversal.traverse(compiler, root, new AccessModifierConverter()); NodeTraversal.traverse(compiler, root, new TemplateAnnotationConverter()); for (Node script : root.children()) { addTypeOnlyImports(script); } }
Example #15
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 5 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { JSDocInfo info = n.getJSDocInfo(); if (info != null) { for (Node node : info.getTypeNodes()) { fixTypeNode(t, node); } } }
Example #16
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 5 votes |
private void visitScript(NodeTraversal t, Node script) { if (currentModule == null) { return; } // Remove any 'use strict' directives. The compiler adds these by default to // closure modules and will generate a warning if specified directly. // TODO: remove when https://github.com/google/closure-compiler/issues/1263 is fixed. Set<String> directives = script.getDirectives(); if (directives != null && directives.contains("use strict")) { // Directives is likely an immutable collection, so we need to make a copy. Set<String> newDirectives = new HashSet<>(directives); newDirectives.remove("use strict"); script.setDirectives(newDirectives); } processModuleExportRefs(t); Node moduleBody = createModuleBody(); moduleBody.srcrefTree(script); if (script.getChildCount() > 0) { moduleBody.addChildrenToBack(script.removeChildren()); } script.addChildToBack(moduleBody); script.putBooleanProp(Node.GOOG_MODULE, true); t.getInput().addProvide(currentModule); traverse(t.getCompiler(), script, new TypeCleanup()); googRequireExpr.clear(); currentModule = null; t.reportCodeChange(); }
Example #17
Source File: TypeConversionPass.java From clutz with MIT License | 5 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case EXPR_RESULT: maybeRemoveInherits(n); break; case CALL: maybeReplaceSuperCall(n); break; default: break; } }
Example #18
Source File: MinerrPass.java From ng-closure-runner with MIT License | 5 votes |
@Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); boolean codeChanged = false; PrintStream stream; for (Node instance : minerrInstances) { Node templateNode = instance.getChildAtIndex(2); Node errCodeNode = instance.getChildAtIndex(1); String namespace = getNamespace(instance); if (namespace != null) { addMessageToNamespace(namespace, getExprString(errCodeNode), getExprString(templateNode)); } else { addMessageToGlobalNamespace(getExprString(errCodeNode), getExprString(templateNode)); } instance.removeChild(templateNode); codeChanged = true; } if (minerrDefNode != null && minerrDefSource != null) { Node newMinErrDef = createSubstituteMinerrDefinition(); newMinErrDef.useSourceInfoFromForTree(minerrDefNode); minerrDefNode.getParent().replaceChild(minerrDefNode, newMinErrDef); codeChanged = true; } Map<String, Object> jsonBuilder = new HashMap<String, Object>(namespaces); jsonBuilder.putAll(globalNamespace); JSONObject json = new JSONObject(jsonBuilder); errorConfigOutput.print(json.toString()); if (codeChanged) { compiler.reportCodeChange(); } }
Example #19
Source File: MinimizeExitPoints.java From astor with GNU General Public License v2.0 | 5 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { switch (n.getType()) { case Token.LABEL: tryMinimizeExits( n.getLastChild(), Token.BREAK, n.getFirstChild().getString()); break; case Token.FOR: case Token.WHILE: tryMinimizeExits( NodeUtil.getLoopCodeBlock(n), Token.CONTINUE, null); break; case Token.DO: tryMinimizeExits( NodeUtil.getLoopCodeBlock(n), Token.CONTINUE, null); Node cond = NodeUtil.getConditionExpression(n); if (NodeUtil.getImpureBooleanValue(cond) == TernaryValue.FALSE) { // Normally, we wouldn't be able to optimize BREAKs inside a loop // but as we know the condition will always false, we can treat them // as we would a CONTINUE. tryMinimizeExits( n.getFirstChild(), Token.BREAK, null); } break; case Token.FUNCTION: tryMinimizeExits( n.getLastChild(), Token.RETURN, null); break; } }
Example #20
Source File: CommentLinkingPass.java From clutz with MIT License | 5 votes |
@Override public void process(Node externs, Node root) { for (Node script : root.children()) { if (script.isScript()) { // Note: this doesn't actually copy the list since the underlying list is already an // immutable list. ImmutableList<Comment> comments = ImmutableList.copyOf(compiler.getComments(script.getSourceFileName())); NodeTraversal.traverse( compiler, script, new LinkCommentsForOneFile(compiler, comments, nodeComments)); } } }
Example #21
Source File: MinimizeExitPoints.java From astor with GNU General Public License v2.0 | 4 votes |
@Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); }
Example #22
Source File: CollectModuleMetadata.java From clutz with MIT License | 4 votes |
@Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); }
Example #23
Source File: AbstractTopLevelCallback.java From clutz with MIT License | 4 votes |
@Override public final boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) { return parent == null || n.isScript() || parent.isScript() || parent.isModuleBody(); }
Example #24
Source File: RemoveGoogScopePass.java From clutz with MIT License | 4 votes |
@Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); }
Example #25
Source File: StyleFixPass.java From clutz with MIT License | 4 votes |
@Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); }
Example #26
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 4 votes |
private void visitRequireCall(NodeTraversal t, Node require, Node parent) { Path currentFile = inputFs.getPath(t.getSourceName()); String modulePath = require.getSecondChild().getString(); if (modulePath.isEmpty()) { t.report(require, REQUIRE_INVALID_MODULE_ID); return; } String moduleId = null; if (modulePath.startsWith(".") || modulePath.startsWith("/")) { Path moduleFile = currentFile.getParent().resolve(modulePath).normalize(); if (modulePath.endsWith("/") || (isDirectory(moduleFile) && !modulePath.endsWith(".js") && !Files.exists(moduleFile.resolveSibling(moduleFile.getFileName() + ".js")))) { moduleFile = moduleFile.resolve("index.js"); } moduleId = NODE.newId(moduleFile).getOriginalName(); } else if (nodeLibrary.canRequireId(modulePath)) { moduleId = nodeLibrary.normalizeRequireId(modulePath); } if (moduleId != null) { // Only register the require statement on this module if it occurs at the global // scope. Assume other require statements are not declared at the global scope to // avoid create a circular dependency. While node can handle these, by returning // a partial definition of the required module, the cycle would be an error for // the compiler. For more information on how Node handles cycles, see: // http://www.nodejs.org/api/modules.html#modules_cycles if (t.getScope().isGlobal()) { Node googRequire = call(getprop(name("goog"), string("require")), string(moduleId)); // ClosureCheckModule enforces that goog.require statements are at the top level. To // compensate, if we have a require statement that is not at the top level, we introduce // a hidden variable at the top level that does the actual require. The compiler should // always inline the require making this effectively a no-op. // // Example: // var Foo = require('./foo').Foo; // // Becomes: // var _some_hidden_name = require('./foo'); // var Foo = _some_hidden_name.Foo; if (!parent.isName()) { String hiddenName = Types.toInternalVar(moduleId); JSDocInfoBuilder infoBuilder = new JSDocInfoBuilder(false); infoBuilder.recordConstancy(); googRequireExpr.put( hiddenName, var(name(hiddenName).setJSDocInfo(infoBuilder.build()), googRequire)); googRequire = name(hiddenName); } parent.replaceChild(require, googRequire.srcrefTree(require)); t.getInput().addRequire(DependencyInfo.Require.googRequireSymbol(moduleId)); } else { // For goog.module('foo'), ClosureRewriteModule produces module$exports$foo = {};, so // we use the transformed name in the direct reference. parent.replaceChild(require, name("module$exports$" + moduleId).srcrefTree(require)); } t.reportCodeChange(); } // Else we have an unrecognized module ID. Do nothing, leaving it to the // type-checking gods. }
Example #27
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 4 votes |
@Override public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) { return true; }
Example #28
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 4 votes |
@Override public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) { return !foundRequire; }
Example #29
Source File: NodeModulePass.java From js-dossier with Apache License 2.0 | 4 votes |
@Override public void visit(NodeTraversal t, Node n, Node parent) { foundRequire = foundRequire || isCall(n, "require") || isCall(n, "goog.require"); }
Example #30
Source File: ModuleConversionPass.java From clutz with MIT License | 4 votes |
@Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, new ModuleExportConverter()); NodeTraversal.traverse(compiler, root, new ModuleImportConverter()); NodeTraversal.traverse(compiler, root, new ModuleImportRewriter()); }