Protect side-effect free nodes by making them parameters
to a extern function call.  This call will be removed
after all the optimizations passes have run.
963938
private void protectSideEffects() {
    if (!problemNodes.isEmpty()) {
      if (!preserveFunctionInjected) {
        addExtern(compiler);
      }
      for (Node n : problemNodes) {
        Node name = IR.name(PROTECTOR_FN).srcref(n);
        name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
        Node replacement = IR.call(name).srcref(n);
        replacement.putBooleanProp(Node.FREE_CALL, true);
        n.replaceWith(replacement);
        replacement.addChildToBack(n);
        compiler.reportChangeToEnclosingScope(replacement);
      }
    }
  }
1210584
def prepare(self, node):
        
        super(ArgumentEffects, self).prepare(node)
        for n in self.global_declarations.values():
            fe = FunctionEffects(n)
            self.node_to_functioneffect[n] = fe
            self.result.add_node(fe)
1226894
function decorateFunctions(node) {
    var i;
    var funcNode = getCommentedFunctionNode(node);
    if (!funcNode || !funcNode.jsdoc) {
        return;
    }

    // Pair up the function params with the JSDoc params (if they exist)
    funcNode.node.params.forEach(function(param) {
        for (i = 0; i < funcNode.jsdoc.params.length; i++) {
            if (!funcNode.jsdoc.params[i].type) {
                continue;
            }

            // If default options are set keep the assignment in flow
            if (param.type === 'AssignmentPattern') {
                if (funcNode.jsdoc.params[i].name === param.left.name) {
                    // Remove ? if default value is set
                    var type = funcNode.jsdoc.params[i].type.replace(/^\?/, '');

                    param.update(
                        param.left.source() + ": " + type + ' = ' + param.right.source()
                    );
                }
            } else {
                if (funcNode.jsdoc.params[i].name === param.name) {
                    param.update(
                        param.source() + ": " + funcNode.jsdoc.params[i].type
                    );
                }
            }
        }
    });

    // Pair up the return value if possible
    // we only support 1 return type currently
    var returnDoc = funcNode.jsdoc.returns[0];
    if (returnDoc && returnDoc.type && funcNode.node.body) {
        if (funcNode.node.type === "ArrowFunctionExpression") {
            // we can't just add this to the end as it will then appear AFTER the =>
            // whereas we actually want it BEFORE the =>
            // Sadly, there isn't a nice way to access the bit before the =>. We do
            // however know that the node source is the entire function, and the node
            // body is the stuff between the { }. We can therefore grab the function
            // header portion and find/replace on the fat arrow.
            var funcHeader = funcNode.node.source().replace(funcNode.node.body.source(), "");
            var arrowIndex = funcHeader.lastIndexOf("=>");
            if (arrowIndex === -1) {
                // well this was unexpected...
                return;
            }
            // inject annotation before the arrow
            funcHeader = (
                funcHeader.slice(0, arrowIndex) + ": " + returnDoc.type + " " + funcHeader.slice(arrowIndex)
            );
            // replace the entire function to replace the header portion
            funcNode.node.update(
                funcHeader + funcNode.node.body.source()
            );
        }
        else {
            funcNode.node.body.update(
                ": " + returnDoc.type + " " + funcNode.node.body.source()
            );
        }
    }
}
501133
private void checkNormalization(Node externs, Node root) {
    // Verify nothing has inappropriately denormalize the AST.
    CodeChangeHandler handler = new ForbiddenChange();
    compiler.addChangeHandler(handler);

    // TODO(johnlenz): Change these normalization checks Preconditions and
    // Exceptions into Errors so that it is easier to find the root cause
    // when there are cascading issues.
    new PrepareAst(compiler, true).process(null, root);
    if (compiler.getLifeCycleStage().isNormalized()) {
      (new Normalize(compiler, true)).process(externs, root);

      if (compiler.getLifeCycleStage().isNormalizedUnobfuscated()) {
        boolean checkUserDeclarations = true;
        CompilerPass pass = new Normalize.VerifyConstants(compiler, checkUserDeclarations);
        pass.process(externs, root);
      }
    }

    compiler.removeChangeHandler(handler);
  }
620331
void addGuardParameters( Map<String, Expression> parameters, boolean isDefault ) {
        isGuard = true;
        wasDefaultFunction = false;
        guardDefault = isDefault;
        if( parameters != null ) {
            addMixin( null, parameters, null );
        }
    }
668485
@Override
  protected SoyValue visitFunctionNode(FunctionNode node) {
    Object soyFunction = node.getSoyFunction();
    // Handle nonplugin functions.
    if (soyFunction instanceof BuiltinFunction) {
      BuiltinFunction nonpluginFn = (BuiltinFunction) soyFunction;
      switch (nonpluginFn) {
        case IS_FIRST:
          return visitIsFirstFunction(node);
        case IS_LAST:
          return visitIsLastFunction(node);
        case INDEX:
          return visitIndexFunction(node);
        case CHECK_NOT_NULL:
          return visitCheckNotNullFunction(node.getChild(0));
        case CSS:
          return visitCssFunction(node);
        case XID:
          return visitXidFunction(node);
        case IS_PRIMARY_MSG_IN_USE:
          return visitIsPrimaryMsgInUseFunction(node);
        case V1_EXPRESSION:
          throw new UnsupportedOperationException(
              "the v1Expression function can't be used in templates compiled to Java");
        case TO_FLOAT:
          return visitToFloatFunction(node);
        case DEBUG_SOY_TEMPLATE_INFO:
          return BooleanData.forValue(debugSoyTemplateInfo);
        case VE_DATA:
          return NullData.INSTANCE;
        case MSG_WITH_ID:
        case REMAINDER:
          // should have been removed earlier in the compiler
          throw new AssertionError();
      }
      throw new AssertionError();
    } else if (soyFunction instanceof SoyJavaFunction) {
      List<SoyValue> args = this.visitChildren(node);
      SoyJavaFunction fn = (SoyJavaFunction) soyFunction;
      // Note: Arity has already been checked by CheckFunctionCallsVisitor.
      return computeFunctionHelper(fn, args, node);
    } else if (soyFunction instanceof SoyJavaSourceFunction) {
      List<SoyValue> args = this.visitChildren(node);
      SoyJavaSourceFunction fn = (SoyJavaSourceFunction) soyFunction;
      // Note: Arity has already been checked by CheckFunctionCallsVisitor.
      return computeFunctionHelper(fn, args, node);
    } else if (soyFunction instanceof LoggingFunction) {
      return StringData.forValue(((LoggingFunction) soyFunction).getPlaceholder());
    } else {
      throw RenderException.create(
          "Failed to find Soy function with name '"
              + node.getFunctionName()
              + "'"
              + " (function call \""
              + node.toSourceString()
              + "\").");
    }
  }
722009
private void replaceGetCompilerOverridesCalls(
      List<TweakFunctionCall> calls) {
    for (TweakFunctionCall call : calls) {
      Node callNode = call.callNode;
      Node objNode = createCompilerDefaultValueOverridesVarNode(callNode);
      callNode.replaceWith(objNode);
      compiler.reportChangeToEnclosingScope(objNode);
    }
  }
1016578
def add_external_parameter(self, parameter):
        

        assert isinstance(parameter, Parameter), "Variable must be an instance of IndependentVariable"

        if self._has_child(parameter.name):

            # Remove it from the children only if it is a Parameter instance, otherwise don't, which will
            # make the _add_child call fail (which is the expected behaviour! You shouldn't call two children
            # with the same name)

            if isinstance(self._get_child(parameter.name), Parameter):

                warnings.warn("External parameter %s already exist in the model. Overwriting it..." % parameter.name,
                              RuntimeWarning)

                self._remove_child(parameter.name)

        # This will fail if another node with the same name is already in the model

        self._add_child(parameter)
343370
def prepare(self, node):
        ''''''
        if isinstance(node, ast.Module):
            self.ctx.module = node
        elif isinstance(node, ast.FunctionDef):
            self.ctx.function = node

        for D in self.deps:
            d = D()
            d.attach(self.passmanager, self.ctx)
            result = d.run(node)
            setattr(self, uncamel(D.__name__), result)
172432
@Override
  public void process(Node externs, Node root) {
    ReferenceCollectingCallback callback =
      new ReferenceCollectingCallback(compiler,
          ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR, new Es6SyntacticScopeCreator(compiler));

    callback.process(root);

    for (Var variable : callback.getAllSymbols()) {
      ReferenceCollection referenceCollection =
          callback.getReferences(variable);

      VariableVisibility visibility;

      if (variableIsParameter(variable)) {
        visibility = VariableVisibility.PARAMETER;
      } else if (variable.isLocal()) {
        if (referenceCollection.isEscaped()) {
          visibility = VariableVisibility.CAPTURED_LOCAL;
        } else {
          visibility = VariableVisibility.LOCAL;
        }
      } else if (variable.isGlobal()) {
        visibility = VariableVisibility.GLOBAL;
      } else {
        throw new IllegalStateException("Un-handled variable visibility for " + variable);
      }

      visibilityByDeclaringNameNode.put(variable.getNameNode(), visibility);
    }
  }
148055
private void eliminateCallTargetArgAt(Node ref, int argIndex) {
    Node callArgNode = ReferenceMap.getArgumentForCallOrNewOrDotCall(ref, argIndex);
    if (callArgNode != null) {
      NodeUtil.deleteNode(callArgNode, compiler);
    }
  }
1118017
function templateNodeTransformation( $functionName, &$node,
                                         $tpl, $parameters, $privateData )
    {
        $tpl->ElseifCounter++;
        $newNodes       = array();
        $nodesToPrepend = array();
        $nodesToAppend  = array();
        $nodePlacement  = eZTemplateNodeTool::extractFunctionNodePlacement( $node );
        $uniqid        =  md5( $nodePlacement[2] ) . "_" . $tpl->ElseifCounter;
        $children       = eZTemplateNodeTool::extractFunctionNodeChildren( $node );


        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// if begins" );
        $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['condition'], $nodePlacement, array( 'treat-value-as-non-object' => true ), 'if_cond' );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$if_cond )\n{" );
        $newNodes[] = eZTemplateNodeTool::createSpacingIncreaseNode();

        if ( is_array( $children ) )
        {
            foreach ( array_keys( $children ) as $childKey )
            {
                $child =& $children[$childKey];

                if ( $child[0] == eZTemplate::NODE_FUNCTION )
                {
                    $childFunctionName =& $child[2];
                    $childChildren     = eZTemplateNodeTool::extractFunctionNodeChildren( $child );
                    $childFunctionArgs =& $child[3];

                    if ( $childFunctionName == 'elseif' )
                    {
                        $compiledElseifCondition = eZTemplateCompiler::processElementTransformationList( $tpl, $child, $childFunctionArgs['condition'], $privateData );
                        $nodesToPrepend[] = eZTemplateNodeTool::createVariableNode( false, $compiledElseifCondition,
                                                                                    $nodePlacement,
                                                                                    array( 'text-result' => true ),
                                                                                    "elseif_cond_$uniqid" );
                        $newNodes[] = eZTemplateNodeTool::createSpacingDecreaseNode();
                        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "}\nelseif ( \$elseif_cond_$uniqid )\n{" );
                        $newNodes[] = eZTemplateNodeTool::createSpacingIncreaseNode();
                        $nodesToAppend[] = eZTemplateNodeTool::createVariableUnsetNode( "elseif_cond_$uniqid" );
                        // increment unique elseif counter
                        $uniqid        =  md5( $nodePlacement[2] ) . "_" . ++$tpl->ElseifCounter;
                    }
                    elseif ( $childFunctionName == 'else' )
                    {
                        $newNodes[] = eZTemplateNodeTool::createSpacingDecreaseNode();
                        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "}\nelse\n{" );
                        $newNodes[] = eZTemplateNodeTool::createSpacingIncreaseNode();
                    }
                    elseif ( $childFunctionName == 'break' )
                        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "break;\n" );
                    elseif ( $childFunctionName == 'continue' )
                        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "continue;\n" );
                    elseif ( $childFunctionName == 'skip' )
                        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$skipDelimiter = true;\ncontinue;\n" );

                    // let other functions (ones not listed in the conditions above) be transformed
                    if ( in_array( $childFunctionName, array( 'elseif', 'else', 'break', 'continue', 'skip' ) ) )
                         continue;
                }
                $newNodes[] = $child;
            }
        }

        $newNodes[] = eZTemplateNodeTool::createSpacingDecreaseNode();
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "}" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "unset( \$if_cond );" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// if ends\n" );

        $newNodes = array_merge( $nodesToPrepend, $newNodes, $nodesToAppend );

        return $newNodes;
    }
1159772
@Override
  public void process(Node externs, Node root) {
    checkState(compiler.getLifeCycleStage().isNormalized());
    if (!allowRemovalOfExternProperties) {
      referencedPropertyNames.addAll(compiler.getExternProperties());
    }
    traverseAndRemoveUnusedReferences(root);
    // This pass may remove definitions of getter or setter properties.
    GatherGettersAndSetterProperties.update(compiler, externs, root);
  }
370961
function unprotectValues(node) {
    traverse(node, function(node) {
        if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) {
            node.removeAttribute(XmlNames.Attr.Protected);
            node.setAttribute(XmlNames.Attr.ProtectedInMemPlainXml, 'True');
            node.textContent = node.protectedValue.getText();
        }
    });
}
627520
def prepare(self, node):
        
        super(GlobalEffects, self).prepare(node)

        def register_node(module):
            """ Recursively save globals effect for all functions. """
            for v in module.values():
                if isinstance(v, dict):  # Submodule case
                    register_node(v)
                else:
                    fe = GlobalEffects.FunctionEffect(v)
                    self.node_to_functioneffect[v] = fe
                    self.result.add_node(fe)
                    if isinstance(v, intrinsic.Class):
                        register_node(v.fields)

        register_node(self.global_declarations)
        for module in MODULES.values():
            register_node(module)
        self.node_to_functioneffect[intrinsic.UnboundValue] = \
            GlobalEffects.FunctionEffect(intrinsic.UnboundValue)
310302
private void inlineEmptyMethod(NodeTraversal t, Node parent, Node call) {
    // If the return value of the method call is read,
    // replace it with "void 0". Otherwise, remove the call entirely.

    if (NodeUtil.isExprCall(parent)) {
      parent.replaceWith(IR.empty());
      NodeUtil.markFunctionsDeleted(parent, compiler);
    } else {
      Node srcLocation = call;
      parent.replaceChild(call, NodeUtil.newUndefinedNode(srcLocation));
      NodeUtil.markFunctionsDeleted(call, compiler);
    }
    t.reportCodeChange();
  }
360478
private boolean validateUnaliasablePrimitiveCall(NodeTraversal t, Node n, String methodName) {
    return validatePrimitiveCallWithMessage(t, n, methodName, CLOSURE_CALL_CANNOT_BE_ALIASED_ERROR);
  }