Java Code Examples for com.google.javascript.rhino.IR#empty()

The following examples show how to use com.google.javascript.rhino.IR#empty() . 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: ModuleConversionPass.java    From clutz with MIT License 6 votes vote down vote up
private void convertRequireForAlreadyConverted(ModuleImport moduleImport) {
  // we cannot use referencedFile here, because usually it points to the ES5 js file that is
  // the output of TS, and not the original source TS file.
  // However, we can reverse map the goog.module name to a file name.
  // TODO(rado): sync this better with the mapping done in tsickle.
  String originalPath =
      moduleImport.requiredNamespace.replace(alreadyConvertedPrefix + ".", "").replace(".", "/");
  String sourceFileName = moduleImport.originalImportNode.getSourceFileName();
  String referencedFile = pathUtil.getImportPath(sourceFileName, originalPath);
  // goog.require('...'); -> import '...';
  Node importSpec = IR.empty();
  if (moduleImport.isDestructuringImport) {
    importSpec = createNamedImports(moduleImport);
  } else if (moduleImport.isFullModuleImport()) {
    // It is safe to assume there's one full local name because this is validated before.
    String fullLocalName = moduleImport.fullLocalNames.get(0);
    importSpec = Node.newString(Token.IMPORT_STAR, fullLocalName);
  }
  Node importNode =
      new Node(Token.IMPORT, IR.empty(), importSpec, Node.newString(referencedFile));
  nodeComments.replaceWithComment(moduleImport.originalImportNode, importNode);
  compiler.reportChangeToEnclosingScope(importNode);
}
 
Example 2
Source File: TypeConversionPass.java    From clutz with MIT License 5 votes vote down vote up
/** Converts goog.defineClass calls into class definitions. */
private void convertDefineClassToClass(Node n) {
  Preconditions.checkState(n.isCall());
  Node superClass = n.getSecondChild();
  if (superClass.isNull()) {
    superClass = IR.empty();
  } else {
    superClass.detach();
  }

  Node classMembers = new Node(Token.CLASS_MEMBERS);
  classMembers.useSourceInfoFrom(n);
  for (Node child : n.getLastChild().children()) {
    if (child.isStringKey() || child.isMemberFunctionDef()) {
      // Handle static methods
      if ("statics".equals(child.getString())) {
        for (Node child2 : child.getFirstChild().children()) {
          convertObjectLiteral(classMembers, child2, true);
        }
      } else { // prototype methods
        convertObjectLiteral(classMembers, child, false);
      }
    } else {
      // Add all other members, such as EMPTY comment nodes, as is.
      child.detach();
      classMembers.addChildToBack(child);
    }
  }
  Node classNode = new Node(Token.CLASS, IR.empty(), superClass, classMembers);
  classNode.useSourceInfoFrom(n);

  nodeComments.replaceWithComment(n, classNode);
}
 
Example 3
Source File: ModuleConversionPass.java    From clutz with MIT License 5 votes vote down vote up
/**
 * Converts a destructuring Closure goog.require call into a TypeScript import statement.
 *
 * <p>The resulting node is dependent on the exports by the module being imported:
 *
 * <pre>
 *   import {A as localName, B} from "./valueExports";
 * </pre>
 */
private void convertDestructuringRequireToImportStatements(Node n, ModuleImport moduleImport) {
  // The imported file is already in TS
  if (moduleImport.isAlreadyConverted()) {
    convertRequireForAlreadyConverted(moduleImport);
    return;
  }

  // The imported file is kept in JS
  if (moduleImport.module.shouldUseOldSyntax()) {
    convertRequireToImportsIfImportedIsKeptInJs(moduleImport);
    return;
  }
  // For the rest of the function, the imported and importing files are migrating together

  // import {localName} from "./file"
  Node importSpecs = createNamedImports(moduleImport);
  Node importNode =
      new Node(
          Token.IMPORT, IR.empty(), importSpecs, Node.newString(moduleImport.referencedFile));
  addImportNode(n, importNode);

  for (int i = 0; i < moduleImport.fullLocalNames.size(); i++) {
    registerLocalSymbol(
        n.getSourceFileName(),
        moduleImport.fullLocalNames.get(i),
        moduleImport.requiredNamespace,
        moduleImport.localNames.get(i));
  }

  compiler.reportChangeToEnclosingScope(n);
  n.detach();
}
 
Example 4
Source File: Normalize.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  switch (n.getType()) {
    case Token.WHILE:
      if (CONVERT_WHILE_TO_FOR) {
        Node expr = n.getFirstChild();
        n.setType(Token.FOR);
        Node empty = IR.empty();
        empty.copyInformationFrom(n);
        n.addChildBefore(empty, expr);
        n.addChildAfter(empty.cloneNode(), expr);
        reportCodeChange("WHILE node");
      }
      break;

    case Token.FUNCTION:
      normalizeFunctionDeclaration(n);
      break;

    case Token.NAME:
    case Token.STRING:
    case Token.STRING_KEY:
    case Token.GETTER_DEF:
    case Token.SETTER_DEF:
      if (!compiler.getLifeCycleStage().isNormalizedObfuscated()) {
        annotateConstantsByConvention(n, parent);
      }
      break;

    case Token.CAST:
      parent.replaceChild(n, n.removeFirstChild());
      break;
  }
}
 
Example 5
Source File: ModuleConversionPass.java    From clutz with MIT License 4 votes vote down vote up
private void convertRequireForSideEffectOnlyImport(ModuleImport moduleImport) {
  Node importNode =
      new Node(Token.IMPORT, IR.empty(), IR.empty(), Node.newString(moduleImport.referencedFile));
  addImportNode(moduleImport.originalImportNode, importNode);
}
 
Example 6
Source File: ExternExportsPass.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Appends the exported function and all paths necessary for the path to be
 * declared. For example, for a property "a.b.c", the initializers for
 * paths "a", "a.b" will be appended (if they have not already) and a.b.c
 * will be initialized with the exported version of the function:
 * <pre>
 * var a = {};
 * a.b = {};
 * a.b.c = function(x,y) { }
 * </pre>
 */
void appendExtern(String path, Node valueToExport) {
  List<String> pathPrefixes = computePathPrefixes(path);

  for (int i = 0; i < pathPrefixes.size(); ++i) {
    String pathPrefix = pathPrefixes.get(i);

    /* The complete path (the last path prefix) must be emitted and
     * it gets initialized to the externed version of the value.
     */
    boolean isCompletePathPrefix = (i == pathPrefixes.size() - 1);

    boolean skipPathPrefix = pathPrefix.endsWith(".prototype")
        || (alreadyExportedPaths.contains(pathPrefix)
            && !isCompletePathPrefix);

    if (!skipPathPrefix) {
       Node initializer;

      /* Namespaces get initialized to {}, functions to
       * externed versions of their value, and if we can't
       * figure out where the value came from we initialize
       * it to {}.
       *
       * Since externs are always exported in sorted order,
       * we know that if we export a.b = function() {} and later
       * a.b.c = function then a.b will always be in alreadyExportedPaths
       * when we emit a.b.c and thus we will never overwrite the function
       * exported for a.b with a namespace.
       */

      if (isCompletePathPrefix && valueToExport != null) {
        if (valueToExport.isFunction()) {
          initializer = createExternFunction(valueToExport);
        } else {
          Preconditions.checkState(valueToExport.isObjectLit());
          initializer = createExternObjectLit(valueToExport);
        }
      } else {
        initializer = IR.empty();
      }

      appendPathDefinition(pathPrefix, initializer);
    }
  }
}
 
Example 7
Source File: GroupVariableDeclarations.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Attempts to collapse groupVar. This can only happen if groupVar has at most
 * one variable initialization (it may have multiple variable declarations).
 * If successful, then detaches groupVar's children and appends them to
 * firstVar
 *
 * @param firstVar The first VAR {@code Node} in that scope. This is the node
 *                 that we want to collapse groupVar into
 * @param groupVar The VAR {@code Node} that we want to try collapsing
 *                 into the first VAR node of that scope
 */
private void applyGroupingToVar(Node firstVar, Node groupVar) {
  Node child = groupVar.getFirstChild();
  // if some variable is initialized, then the corresponding NAME node will be
  // stored here
  Node initializedName = null;
  while (child != null) {
    if (child.hasChildren()) {
      // check that no more than one var is initialized
      if (initializedName != null) {
        return;
      }
      initializedName = child;
    }
    child = child.getNext();
  }

  // we will be modifying the groupVar subtree so get its parent
  Node groupVarParent = groupVar.getParent();


  if (initializedName != null) {
    if (NodeUtil.isForIn(groupVarParent)) {
      // The target of the for-in expression must be an assignable expression.
      return;
    }

    // we have an initialized var in the VAR node. We will replace the
    // VAR node with an assignment.

    // first create a detached childless clone of initializedName.
    Node clone = initializedName.cloneNode();
    // replace
    groupVar.replaceChild(initializedName, clone);
    // add the assignment now.
    Node initializedVal = initializedName.removeFirstChild();
    Node assignmentNode = IR.assign(initializedName, initializedVal);
    if (groupVarParent.isFor()) {
      // Handle For and For-In Loops specially. For these, we do not need
      // to construct an EXPR_RESULT node.
      groupVarParent.replaceChild(groupVar, assignmentNode);
    } else {
      Node exprNode = NodeUtil.newExpr(assignmentNode);
      groupVarParent.replaceChild(groupVar, exprNode);
    }
  } else {
    // There is no initialized var. But we need to handle FOR and
    // FOR-IN loops specially
    if (groupVarParent.isFor()) {
      if (NodeUtil.isForIn(groupVarParent)) {
        // In For-In loop, we replace the VAR node with a NAME node
        Node nameNodeClone = groupVar.getFirstChild().cloneNode();
        groupVarParent.replaceChild(groupVar, nameNodeClone);
      } else {
        // In For loop, we replace the VAR node with an EMPTY node
        Node emptyNode = IR.empty();
        groupVarParent.replaceChild(groupVar, emptyNode);
      }
    } else {
      // we can safely remove the VAR node
      groupVarParent.removeChild(groupVar);
    }
  }

  Node children = groupVar.removeChildren();
  firstVar.addChildrenToBack(children);

  compiler.reportCodeChange();
}