本文整理汇总了Java中com.google.javascript.rhino.Node.cloneTree方法的典型用法代码示例。如果您正苦于以下问题:Java Node.cloneTree方法的具体用法?Java Node.cloneTree怎么用?Java Node.cloneTree使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.javascript.rhino.Node
的用法示例。
在下文中一共展示了Node.cloneTree方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: makeForwardSlashBracketSafe
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* returns a string node that can safely be rendered inside /brackets/.
*/
private static Node makeForwardSlashBracketSafe(Node n) {
String s = n.getString();
// sb contains everything in s[0:pos]
StringBuilder sb = null;
int pos = 0;
for (int i = 0; i < s.length(); ++i) {
switch (s.charAt(i)) {
case '\\': // skip over the next char after a '\\'.
++i;
break;
case '/': // escape it
if (null == sb) { sb = new StringBuilder(s.length() + 16); }
sb.append(s, pos, i).append('\\');
pos = i;
break;
}
}
// don't discard useful line-number info if there were no changes
if (null == sb) { return n.cloneTree(); }
sb.append(s, pos, s.length());
return Node.newString(sb.toString());
}
示例2: inject
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* With the map provided, replace the names with expression trees.
* @param node The root of the node tree within which to perform the
* substitutions.
* @param parent The parent root node.
* @param replacements The map of names to template node trees with which
* to replace the name Nodes.
* @returns The root node or its replacement.
*/
static Node inject(Node node, Node parent,
Map<String, Node> replacements) {
if (node.getType() == Token.NAME) {
Node replacementTemplate = replacements.get(node.getString());
if (replacementTemplate != null) {
// This should not be replacing declared names.
Preconditions.checkState(parent.getType() != Token.FUNCTION
|| parent.getType() != Token.VAR
|| parent.getType() != Token.CATCH);
// The name may need to be replaced more than once,
// so we need to clone the node.
Node replacement = replacementTemplate.cloneTree();
parent.replaceChild(node, replacement);
return replacement;
}
}
for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
// We have to reassign c in case it was replaced, because the removed c's
// getNext() would no longer be correct.
c = inject(c, node, replacements);
}
return node;
}
示例3: splitFunctions
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* Splits at function level with {@link AstParallelizer#split()}, verify the
* output matches what is expected and then verify
* {@link AstParallelizer#join()} can reverse the whole process.
*/
private void splitFunctions(String input, String ... output) {
Compiler compiler = new Compiler();
Node orginal = compiler.parseTestCode(input);
Node root = orginal.cloneTree();
AstParallelizer parallelizer =
AstParallelizer.createNewFunctionLevelAstParallelizer(root, true);
List<Node> forest = parallelizer.split();
assertEquals(output.length, forest.size());
int i = 0;
for (Node n : forest) {
Node tree = compiler.parseTestCode(output[i++]);
assertEquals(compiler.toSource(tree), compiler.toSource(n));
}
parallelizer.join();
assertTrue(orginal.checkTreeEqualsSilent(root));
}
示例4: inlineConstReturn
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* Replace the provided object and its method call with the tree specified
* in returnedValue. Should be called only if the object reference has
* no side effects.
*/
private void inlineConstReturn(Node parent, Node call,
Node returnedValue) {
Node retValue = returnedValue.cloneTree();
parent.replaceChild(call, retValue);
compiler.reportCodeChange();
}
示例5: inlineReturnValue
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* Inline a function that fulfills the requirements of
* canInlineReferenceDirectly into the call site, replacing only the CALL
* node.
*/
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
newExpression = NodeUtil.newUndefinedNode();
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
示例6: extractExpression
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* @param expr The expression to extract.
* @param injectionPoint The node before which to added the extracted
* expression.
* @return The extract statement node.
*/
private Node extractExpression(Node expr, Node injectionPoint) {
Node parent = expr.getParent();
// The temp value is known to be constant.
String tempName = getTempConstantValueName();
// Replace the expression with the temporary name.
Node replacementValueNode = Node.newString(Token.NAME, tempName);
parent.replaceChild(expr, replacementValueNode);
// Re-add the expression in the declaration of the temporary name.
Node tempNameNode = Node.newString(Token.NAME, tempName);
tempNameNode.addChildrenToBack(expr);
Node tempVarNode = new Node(Token.VAR, tempNameNode);
Node injectionPointParent = injectionPoint.getParent();
injectionPointParent.addChildBefore(tempVarNode, injectionPoint);
// If it is ASSIGN_XXX we need to assign it back to the original value.
// Note that calling the temp constant is a lie in this case, but we do know
// that it is not modified until after the exposed expression.
if (NodeUtil.isAssignmentOp(parent) && !NodeUtil.isAssign(parent)) {
Node gParent = parent.getParent();
Node assignBack = new Node(Token.ASSIGN,
expr.cloneTree(),
tempNameNode.cloneNode());
if (NodeUtil.isExpressionNode(gParent)) {
gParent.getParent().addChildAfter(
NodeUtil.newExpr(assignBack), gParent);
} else {
// TODO(user): Use comma here sucks. We might close some accuracy
// in flow sensitive passes but as far as I know it is unavoidable.
Node comma = new Node(Token.COMMA);
gParent.replaceChild(parent, comma);
comma.addChildrenToFront(assignBack);
comma.addChildrenToFront(parent);
}
}
return tempVarNode;
}
示例7: process
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
public void process(Node externs, Node root) {
sanityCheckNormalization(externs, root);
Node reparsedRoot = sanityCheckCodeGeneration(root);
if (reparsedRoot != null) {
Node clonedExterns = externs.cloneTree();
sanityCheckSymbolTable(
new Node(Token.BLOCK,
clonedExterns,
new Node(Token.BLOCK, reparsedRoot)),
root.getParent());
}
}
示例8: checkSynthesizedExtern
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
public void checkSynthesizedExtern(String input, String expectedExtern) {
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
options.setWarningLevel(
DiagnosticGroup.forType(VarCheck.UNDEFINED_VAR_ERROR),
CheckLevel.OFF);
compiler.init(
new JSSourceFile[] {},
new JSSourceFile[] { JSSourceFile.fromCode("input", input) },
options);
compiler.parseInputs();
assertFalse(compiler.hasErrors());
Node externsAndJs = compiler.getRoot();
Node root = externsAndJs.getLastChild();
Node rootOriginal = root.cloneTree();
Node externs = externsAndJs.getFirstChild();
Node expected = compiler.parseTestCode(expectedExtern);
assertFalse(compiler.hasErrors());
(new VarCheck(compiler, sanityCheck)).process(externs, root);
if (!sanityCheck) {
(new VariableTestCheck(compiler)).process(externs, root);
}
String externsCode = compiler.toSource(externs);
String expectedCode = compiler.toSource(expected);
assertEquals(expectedCode, externsCode);
}
示例9: getPropertyType
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
@Override
public JSType getPropertyType(String name) {
if ("prototype".equals(name)) {
return getPrototype();
} else {
if (!hasOwnProperty(name)) {
if ("call".equals(name)) {
// Define the "call" function lazily.
Node params = getParametersNode();
if (params == null) {
// If there's no params array, don't do any type-checking
// in this CALL function.
defineDeclaredProperty(name,
new FunctionType(registry, null, null,
null, getReturnType()),
false);
} else {
params = params.cloneTree();
Node thisTypeNode = Node.newString(Token.NAME, "thisType");
thisTypeNode.setJSType(
registry.createOptionalNullableType(getTypeOfThis()));
params.addChildToFront(thisTypeNode);
thisTypeNode.setOptionalArg(true);
defineDeclaredProperty(name,
new FunctionType(registry, null, null,
params, getReturnType()),
false);
}
} else if ("apply".equals(name)) {
// Define the "apply" function lazily.
FunctionParamBuilder builder = new FunctionParamBuilder(registry);
// Ecma-262 says that apply's second argument must be an Array
// or an arguments object. We don't model the arguments object,
// so let's just be forgiving for now.
// TODO(nicksantos): Model the Arguments object.
builder.addOptionalParams(
registry.createNullableType(getTypeOfThis()),
registry.createNullableType(
registry.getNativeType(JSTypeNative.OBJECT_TYPE)));
defineDeclaredProperty(name,
new FunctionType(registry, null, null,
builder.build(), getReturnType()),
false);
}
}
return super.getPropertyType(name);
}
}
示例10: mutate
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* @param fnName The name to use when preparing human readable names.
* @param fnNode The function to prepare.
* @param callNode The call node that will be replaced.
* @param resultName Function results should be assigned to this name.
* @param needsDefaultResult Whether the result value must be set.
* @param isCallInLoop Whether the function body must be prepared to be
* injected into the body of a loop.
* @return A clone of the function body mutated to be suitable for injection
* as a statement into another code block.
*/
Node mutate(String fnName, Node fnNode, Node callNode,
String resultName, boolean needsDefaultResult, boolean isCallInLoop) {
Node newFnNode = fnNode.cloneTree();
// Now that parameter names have been replaced, make sure all the local
// names are unique, to allow functions to be inlined multiple times
// without causing conflicts.
makeLocalNamesUnique(newFnNode, isCallInLoop);
// TODO(johnlenz): Mark NAME nodes constant for parameters that are not
// modified.
Set<String> namesToAlias =
FunctionArgumentInjector.findModifiedParameters(newFnNode);
LinkedHashMap<String, Node> args =
FunctionArgumentInjector.getFunctionCallParameterMap(
newFnNode, callNode, this.safeNameIdSupplier);
boolean hasArgs = !args.isEmpty();
if (hasArgs) {
FunctionArgumentInjector.maybeAddTempsForCallArguments(
newFnNode, args, namesToAlias, compiler.getCodingConvention());
}
Node newBlock = NodeUtil.getFunctionBody(newFnNode);
// Make the newBlock insertable .
newBlock.detachFromParent();
if (hasArgs) {
Node inlineResult = aliasAndInlineArguments(newBlock,
args, namesToAlias);
Preconditions.checkState(newBlock == inlineResult);
}
//
// For calls inlined into loops, VAR declarations are not reinitialized to
// undefined as they would have been if the function were called, so ensure
// that they are properly initialized.
//
if (isCallInLoop) {
fixUnitializedVarDeclarations(newBlock);
}
String labelName = getLabelNameForFunction(fnName);
Node injectableBlock = replaceReturns(
newBlock, resultName, labelName, needsDefaultResult);
Preconditions.checkState(injectableBlock != null);
return injectableBlock;
}
示例11: updateSimpleDeclaration
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* Updates the initial assignment to a collapsible property at global scope
* by changing it to a variable declaration (e.g. a.b = 1 -> var a$b = 1).
* The property's value may either be a primitive or an object literal or
* function whose properties aren't collapsible.
*
* @param alias The flattened property name (e.g. "a$b")
* @param refName The name for the reference being updated.
* @param ref An object containing information about the assignment getting
* updated
*/
private void updateSimpleDeclaration(String alias, Name refName, Ref ref) {
Node rvalue = ref.node.getNext();
Node parent = ref.node.getParent();
Node gramps = parent.getParent();
Node greatGramps = gramps.getParent();
Node greatGreatGramps = greatGramps.getParent();
// Create the new alias node.
Node nameNode = NodeUtil.newName(alias, gramps.getFirstChild(),
refName.fullName());
NodeUtil.copyNameAnnotations(ref.node.getLastChild(), nameNode);
if (gramps.getType() == Token.EXPR_RESULT) {
// BEFORE: a.b.c = ...;
// exprstmt
// assign
// getprop
// getprop
// name a
// string b
// string c
// NODE
// AFTER: var a$b$c = ...;
// var
// name a$b$c
// NODE
// Remove the rvalue (NODE).
parent.removeChild(rvalue);
nameNode.addChildToFront(rvalue);
Node varNode = new Node(Token.VAR, nameNode);
greatGramps.replaceChild(gramps, varNode);
} else {
// This must be a complex assignment.
Preconditions.checkNotNull(ref.getTwin());
// BEFORE:
// ... (x.y = 3);
//
// AFTER:
// var x$y;
// ... (x$y = 3);
Node current = gramps;
Node currentParent = gramps.getParent();
for (; currentParent.getType() != Token.SCRIPT &&
currentParent.getType() != Token.BLOCK;
current = currentParent,
currentParent = currentParent.getParent()) {}
// Create a stub variable declaration right
// before the current statement.
Node stubVar = new Node(Token.VAR, nameNode.cloneTree());
currentParent.addChildBefore(stubVar, current);
parent.replaceChild(ref.node, nameNode);
}
compiler.reportCodeChange();
}
示例12: testRemoveTryChild
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
public void testRemoveTryChild() {
Compiler compiler = new Compiler();
Node root = parse("try {foo()} catch(e) {} finally {}");
// Test removing the finally clause.
Node actual = root.cloneTree();
Node tryNode = actual.getFirstChild();
Node tryBlock = tryNode.getFirstChild();
Node catchBlocks = tryNode.getFirstChild().getNext();
Node finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(tryNode, finallyBlock);
String expected = "try {foo()} catch(e) {}";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the try clause.
actual = root.cloneTree();
tryNode = actual.getFirstChild();
tryBlock = tryNode.getFirstChild();
catchBlocks = tryNode.getFirstChild().getNext();
finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(tryNode, tryBlock);
expected = "try {} catch(e) {} finally {}";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the catch clause.
actual = root.cloneTree();
tryNode = actual.getFirstChild();
tryBlock = tryNode.getFirstChild();
catchBlocks = tryNode.getFirstChild().getNext();
Node catchBlock = catchBlocks.getFirstChild();
finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(catchBlocks, catchBlock);
expected = "try {foo()} finally {}";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
示例13: inlinePropertyReturn
import com.google.javascript.rhino.Node; //导入方法依赖的package包/类
/**
* Replace the provided method call with the tree specified in returnedValue
*
* Parse tree of a call is
* name
* call
* getprop
* obj
* string
*/
private void inlinePropertyReturn(Node parent, Node call,
Node returnedValue) {
Node getProp = returnedValue.cloneTree();
replaceThis(getProp, call.getFirstChild().removeFirstChild());
parent.replaceChild(call, getProp);
compiler.reportCodeChange();
}