Walk the expression tree, resolving TVEs and function
expressions as we go.
160213
protected final void resolveChildrenForTable(Table table) {
        if (m_left != null) {
            m_left.resolveForTable(table);
        }
        if (m_right != null) {
            m_right.resolveForTable(table);
        }
        if (m_args != null) {
            for (AbstractExpression argument : m_args) {
                argument.resolveForTable(table);
            }
        }
    }
1185674
void foldExpressions() throws ClassParseException {

      // we also populate a second list of expressions held between headTail.head and headTail.tail

      for (Instruction instruction = pcHead; instruction != null; instruction = instruction.getNextPC()) {

         // Here we are going to extract loop/if/structure from the list that we have collected so far in the roots list 
         // We are looking for a new instruction which is the target of a forward branch (this is why we collected forward branch counts) we only enter this loop
         // however if roots list is not empty and it's tail is not a forward branch. 

         expressionList.foldComposite(instruction);

         // If we find a DUP then we need to txform the DUP into a set of clones on the xpressionlist
         if (instruction instanceof DUP) {
            txFormDups(expressionList, instruction);
         } else {
            if (instruction.consumesStack()) {
               // If instruction consumes n operands, then walk back until we find n roots on the xpressionlist that produce stack. 
               // we will user this cursor to track our progress
               Instruction cursor = expressionList.getTail();

               // set this flag if we pass something that does not produce stack
               boolean foundNonStackProducer = false;

               // operandStart will points to the beginning of the list of consumed operands
               Instruction operandStart = null;

               // back up from root tail past each instruction expecting to create a consumed operand for this instruction
               for (int i = 0; i < instruction.getStackConsumeCount();) {
                  if (!cursor.producesStack()) {
                     foundNonStackProducer = true; // we spotted an instruction that does not consume stack. So we need to analyze this
                  } else {
                     i++;
                  }
                  operandStart = cursor;
                  cursor = cursor.getPrevExpr();
               }

               // if we found something that did not consume stack we probably have an expression with a side effect 

               if (foundNonStackProducer) {
                  // Something like
                  //     a = b++;
                  //     foo(i++);
                  //     return(a++);
                  // so we need to check for common transformations
                  applyTransformations(expressionList, instruction, operandStart);
               }

               // cut the tail off and give it to instruction
               final Instruction childTail = expressionList.getTail();
               final Instruction childHead = expressionList.createList(cursor);

               instruction.setChildren(childHead, childTail);
            }
            // add this instruction to the tail of roots
            expressionList.add(instruction);
         }
      }
   }
144671
protected function handleSubExpression()
    {
        // Flag, checking for mismatching parentheses
        $clean = false;

        // Pop operators off the operatorStack until its empty, or
        // we find an opening parenthesis, building subexpressions
        // on the operandStack as we go.
        while ($popped = $this->operatorStack->pop()) {

            // ok, we have our matching opening parenthesis
            if ($popped instanceof SubExpressionNode) {
                $clean = true;
                break;
            }

            $node = $this->handleExpression($popped);
            $this->operandStack->push($node);

        }

        // Throw an error if the parenthesis couldn't be matched
        if (!$clean) {
            throw new ParenthesisMismatchException();
        }


        // Check to see if the parenthesis pair was in fact part
        // of a function application. If so, create the corresponding
        // FunctionNode and push it onto the operandStack.
        $previous = $this->operatorStack->peek();
        if ($previous instanceof FunctionNode) {
            $node = $this->operatorStack->pop();
            $operand = $this->operandStack->pop();
            $node->setOperand($operand);
            $this->operandStack->push($node);
        }
    }
655366
def walk(self, callback):
    """"""
    callback(self)
    for child in self._child_parsers:
      child.walk(callback)
174666
function visit(ast, context, visitor) {
  var stack;
  var parent;
  var keys = [];
  var index = -1;

  do {
    index++;
    if (stack && index === keys.length) {
      parent = stack.parent;
      keys = stack.keys;
      index = stack.index;
      stack = stack.prev;
    } else {
      var node = parent ? parent[keys[index]] : getProgram(ast);
      if (node && typeof node === 'object' && (node.type || node.length)) {
        if (node.type) {
          var visitFn = visitor[node.type];
          if (visitFn && visitFn(context, node, ast) === false) {
            continue;
          }
        }
        stack = {parent: parent, keys: keys, index: index, prev: stack};
        parent = node;
        keys = Object.keys(node);
        index = -1;
      }
    }
  } while (stack);
}
336269
def visit_and_update_expressions(self, visitor_fn):
        """"""
        new_predicate = self.predicate.visit_and_update(visitor_fn)
        if new_predicate is not self.predicate:
            return Filter(new_predicate)
        else:
            return self
270189
public void scan(List<? extends JCTree> trees) {
        if (trees != null)
        for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
            scan(l.head);
    }


/* ***************************************************************************
 * Visitor methods
 ****************************************************************************/

    public void visitTopLevel(JCCompilationUnit tree) {
        scan(tree.packageAnnotations);
        scan(tree.pid);
        scan(tree.defs);
    }

    public void visitImport(JCImport tree) {
        scan(tree.qualid);
    }

    public void visitClassDef(JCClassDecl tree) {
        scan(tree.mods);
        scan(tree.typarams);
        scan(tree.extending);
        scan(tree.implementing);
        scan(tree.defs);
    }

    public void visitMethodDef(JCMethodDecl tree) {
        scan(tree.mods);
        scan(tree.restype);
        scan(tree.typarams);
        scan(tree.recvparam);
        scan(tree.params);
        scan(tree.thrown);
        scan(tree.defaultValue);
        scan(tree.body);
    }

    public void visitVarDef(JCVariableDecl tree) {
        scan(tree.mods);
        scan(tree.vartype);
        scan(tree.nameexpr);
        scan(tree.init);
    }

    public void visitSkip(JCSkip tree) {
    }
893836
function compilePattern(pattern) {
  // pass estree syntax tree obj
  if (pattern && pattern.type) return pattern;

  if (typeof pattern !== 'string') {
    throw new Error('input pattern is neither a string nor an estree node.');
  }

  let exp = parser(pattern);

  if (exp.type !== 'Program' || !exp.body) {
    throw new Error(`Not a valid expression:  "${pattern}".`);
  }

  if (exp.body.length === 0) {
    throw new Error(`There is no statement in pattern "${pattern}".`);
  }

  if (exp.body.length > 1) {
    throw new Error(`Multiple statements is not supported "${pattern}".`);
  }

  exp = exp.body[0];
  // get the real expression underneath
  if (exp.type === 'ExpressionStatement') exp = exp.expression;
  return exp;
}
656716
private void collectParameterValueExpressions(AbstractExpression expr, List<AbstractExpression> pves) {
        if (expr == null) {
            return;
        }

        if (expr instanceof TupleValueExpression || expr instanceof AggregateExpression) {
            // Create a matching PVE for this expression to be used on the EE side
            // to get the original expression value
            addCorrelationParameterValueExpression(expr, pves);
            return;
        }
        collectParameterValueExpressions(expr.getLeft(), pves);
        collectParameterValueExpressions(expr.getRight(), pves);
        if (expr.getArgs() != null) {
            for (AbstractExpression arg : expr.getArgs()) {
                collectParameterValueExpressions(arg, pves);
            }
        }
    }
541695
def eval_expr(expr, context):
    
    if isinstance(expr, list):
        rv = []
        for item in expr:
            rv.append(eval_expr(item, context))
        return rv
    if isinstance(expr, dict):
        rv = {}
        for k, v in expr.iteritems():
            rv[k] = eval_expr(v, context)
        kwargs = rv.pop("__kwargs", None)
        if kwargs:
            rv.update(kwargs)
        return rv
    if isinstance(expr, Expression):
        return expr.eval(context)
    return expr
104309
function visitFunctionExpressions(traverse, node, path, state) {
    functions[node.id.name] = new ValidationFunction(node.id.name, 
        node.params, 
        source.substring(node.body.range[0], node.body.range[1]),
        node.body);
    
    utils.catchup(node.range[1], state, function(value) {
      if(optimizeFunction(node.id.name)) {
        return '';
      } else if(!skipTopLevelOptimization && ast.type == 'object' && node.id.name === f('object_validation_%s', ast.id)) {
        return source.substring(node.body.range[0], node.body.range[1]);
      }

      return value;
    });
  }
411775
function findScope (ast, item) {
  var scopes = [],
      found = false;
  traverse.traverse(ast, {
    enter: function (node, parent) {
      if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') {
        scopes.push(node);
      }
      else if (node === item) {
        found = scopes[scopes.length - 1];
        this.break();
      }
    },
    leave: function (node, parent) {
      if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') {
        scopes.pop();
      }
    }
  });
  return found ? found.body : false;
}
1320129
function visitEvalCallExpressions(traverse, node, path, state) {
    utils.catchup(node.range[1], state, function(value) {
      if(optimizeFunction(node.callee.name)) {
        // Unpack the id
        var id = extractId(node.callee.name);
        // Create path and object call
        var pathDeclaration = f('var path_%s = %s;\n', id, transformedFileData1.code.substring(node.arguments[0].range[0], node.arguments[0].range[1]));
        var objectDeclaration = f('var object_%s = %s;\n', id, transformedFileData1.code.substring(node.arguments[1].range[0], node.arguments[1].range[1]));

        // Get the function code
        var code = functions[node.callee.name].code;

        // Replace path and object in source
        var functionSource = code
          .replace(/object/g, f('object_%s', id))
          .replace(/path/g, f('path_%s', id))
          .replace(/return errors\;/, '');

        // Return the in-lined function
        return f('%s\n%s\n%s', objectDeclaration, pathDeclaration, functionSource);
      } else if(!skipTopLevelOptimization && ast.type == 'object' && node.callee.name === f('object_validation_%s', ast.id)) {
        return '';
      } else {
        return value;
      }
    });
  }
396154
def stringToExpression(s, types, context):
    
    old_ctx = expressions._context.get_current_context()
    try:
        expressions._context.set_new_context(context)
        # first compile to a code object to determine the names
        if context.get('truediv', False):
            flags = __future__.division.compiler_flag
        else:
            flags = 0
        c = compile(s, '<expr>', 'eval', flags)
        # make VariableNode's for the names
        names = {}
        for name in c.co_names:
            if name == "None":
                names[name] = None
            elif name == "True":
                names[name] = True
            elif name == "False":
                names[name] = False
            else:
                t = types.get(name, default_type)
                names[name] = expressions.VariableNode(name, type_to_kind[t])
        names.update(expressions.functions)
        # now build the expression
        ex = eval(c, names)
        if expressions.isConstant(ex):
            ex = expressions.ConstantNode(ex, expressions.getKind(ex))
        elif not isinstance(ex, expressions.ExpressionNode):
            raise TypeError("unsupported expression type: %s" % type(ex))
    finally:
        expressions._context.set_new_context(old_ctx)
    return ex
193394
def find_if_expression_as_statement(node):
    """"""
    return (
        isinstance(node, ast.Expr)
        and isinstance(node.value, ast.IfExp)
    )
1258132
def make_type_replacement_visitor(find_types, replacement_func):
    """"""
    def visitor_fn(expression):
        """Return a replacement expression if the original expression is of the correct type."""
        if isinstance(expression, find_types):
            return replacement_func(expression)
        else:
            return expression

    return visitor_fn
1229161
private Description checkToString(ExpressionTree tree, VisitorState state) {
    Symbol sym = ASTHelpers.getSymbol(tree);
    if (!(sym instanceof VarSymbol || sym instanceof MethodSymbol)) {
      return NO_MATCH;
    }
    Type type = ASTHelpers.getType(tree);
    if (type instanceof MethodType) {
      type = type.getReturnType();
    }
    Tree parent = state.getPath().getParentPath().getLeaf();
    ToStringKind toStringKind = isToString(parent, tree, state);
    if (toStringKind == ToStringKind.NONE) {
      return NO_MATCH;
    }
    if (!typePredicate().apply(type, state)) {
      return NO_MATCH;
    }
    Optional<Fix> fix;
    switch (toStringKind) {
      case IMPLICIT:
        fix = implicitToStringFix(tree, state);
        break;
      case EXPLICIT:
        fix = toStringFix(parent, tree, state);
        break;
      default:
        throw new AssertionError(toStringKind);
    }
    return maybeFix(tree, state, type, fix);
  }