Given an AST and its copy, map the root node of each scope of main to the
corresponding root node of clone
967240
private void associateClones(Node n, Node snapshot) {
    // TODO(johnlenz): determine if MODULE_BODY is useful here.
    if (n.isRoot() || NodeUtil.isChangeScopeRoot(n)) {
      clonesByCurrent.put(n, snapshot);
    }

    Node child = n.getFirstChild();
    Node snapshotChild = snapshot.getFirstChild();
    while (child != null) {
      associateClones(child, snapshotChild);
      child = child.getNext();
      snapshotChild = snapshotChild.getNext();
    }
  }
126844
def transform_params(param_node, scope_stack)
      param_node = param_node[1] if param_node[0] == :paren
      if param_node
        positional_1, optional, rest, positional_2, block = param_node[1..5]
        add_variable_list(positional_1, scope_stack, false) if positional_1
        if optional
          optional.each do |var, value|
            # MUST walk value first. (def foo(y=y); end) == (def foo(y=y()); end)
            transform_tree(value, scope_stack)
            add_variables_from_node(var, scope_stack, false)
          end
        end
        if rest && rest[1]
          add_variables_from_node(rest, scope_stack, false)
        end
        add_variable_list(positional_2, scope_stack, false) if positional_2
        add_variables_from_node(block, scope_stack, false) if block
      end
    end
189080
function walkNodesBreadthFirstHelper(ast, f) {
  let childAst = [];
  (ast || []).forEach(node => {
    f(node);
    childAst = childAst.concat(getChildren(node));
  });
  if (childAst.length > 0) {
    walkNodesBreadthFirstHelper(childAst, f);
  }
}
1106125
private void rewriteAliasReferences(Name aliasingName, Ref aliasingRef, Set<AstChange> newNodes) {
    List<Ref> refs = new ArrayList<>(aliasingName.getRefs());
    for (Ref ref : refs) {
      switch (ref.type) {
        case SET_FROM_GLOBAL:
          continue;
        case DIRECT_GET:
        case ALIASING_GET:
        case PROTOTYPE_GET:
        case CALL_GET:
        case SUBCLASSING_GET:
          if (ref.getTwin() != null) {
            // The reference is the left-hand side of a nested assignment. This means we store two
            // separate 'twin' Refs with the same node of types ALIASING_GET and SET_FROM_GLOBAL.
            // For example, the read of `c.d` has a twin reference in
            //   a.b = c.d = e.f;
            // We handle this case later.
            checkState(ref.type == Type.ALIASING_GET, ref);
            break;
          }
          if (ref.getNode().isStringKey()) {
            // e.g. `y` in `const {y} = x;`
            DestructuringGlobalNameExtractor.reassignDestructringLvalue(
                ref.getNode(), aliasingRef.getNode().cloneTree(), newNodes, ref, compiler);
          } else {
            // e.g. `x.y`
            checkState(ref.getNode().isGetProp() || ref.getNode().isName());
            Node newNode = aliasingRef.getNode().cloneTree();
            Node node = ref.getNode();
            node.replaceWith(newNode);
            compiler.reportChangeToEnclosingScope(newNode);
            newNodes.add(new AstChange(ref.module, ref.scope, newNode));
          }
          aliasingName.removeRef(ref);
          break;
        default:
          throw new IllegalStateException();
      }
    }
  }
971771
def transform_tree(tree, scope_stack)
      if Symbol === tree[0]
        case tree[0]
        when :assign, :massign
          lhs, rhs = tree[1..2]
          begin
            add_variables_from_node(lhs, scope_stack)
          rescue SyntaxError => err
            wrap_node_with_error(tree)
          else
            transform_tree(rhs, scope_stack)
          end
        when :for
          vars, iterated, body = tree[1..3]
          add_variables_from_node(vars, scope_stack)
          transform_tree(iterated, scope_stack)
          transform_tree(body, scope_stack)
        when :var_ref
          # When we reach a :var_ref, we should know everything we need to know
          # in order to tell if it should be transformed into a :vcall.
          if tree[1][0] == :@ident && !scope_stack.has_variable?(tree[1][1])
            tree[0] = :vcall
          end
        when :class
          name, superclass, body = tree[1..3]
          if name[1][0] == :class_name_error || scope_stack.in_method?
            wrap_node_with_error(tree)
          else
            transform_tree(superclass, scope_stack) if superclass  # superclass node
            scope_stack.with_closed_scope do
              transform_tree(body, scope_stack)
            end
          end
        when :module
          name, body = tree[1..2]
          if name[1][0] == :class_name_error || scope_stack.in_method?
            wrap_node_with_error(tree)
          else
            scope_stack.with_closed_scope do
              transform_tree(body, scope_stack)  # body
            end
          end
        when :sclass
          singleton, body = tree[1..2]
          transform_tree(singleton, scope_stack)
          scope_stack.with_closed_scope do
            transform_tree(body, scope_stack)
          end
        when :def
          scope_stack.with_closed_scope(true) do
            param_node = tree[2]
            body = tree[3]
            transform_params_then_body(tree, param_node, body, scope_stack)
          end
        when :defs
          transform_tree(tree[1], scope_stack)  # singleton could be a method call!
          scope_stack.with_closed_scope(true) do
            param_node = tree[4]
            body = tree[5]
            transform_params_then_body(tree, param_node, body, scope_stack)
          end
        when :lambda
          param_node, body = tree[1..2]
          scope_stack.with_open_scope do
            transform_params_then_body(tree, param_node, body, scope_stack)
          end
        when :rescue
          list, name, body = tree[1..3]
          transform_tree(list, scope_stack) if list
          # Don't forget the rescue argument!
          if name
            add_variables_from_node(name, scope_stack)
          end
          transform_tree(body, scope_stack)
        when :method_add_block
          call, block = tree[1..2]
          # first transform the call
          transform_tree(call, scope_stack)
          # then transform the block
          param_node, body = block[1..2]
          scope_stack.with_open_scope do
            begin
              if param_node
                transform_params(param_node[1], scope_stack)
                if param_node[2]
                  add_variable_list(param_node[2], scope_stack, false)
                end
              end
            rescue SyntaxError
              wrap_node_with_error(tree)
            else
              transform_tree(body, scope_stack)
            end
          end
        when :binary
          # must check for named groups in a literal match. wowzerz.
          lhs, op, rhs = tree[1..3]
          if op == :=~
            if lhs[0] == :regexp_literal
              add_locals_from_regexp(lhs, scope_stack)
              transform_tree(rhs, scope_stack)
            elsif lhs[0] == :paren && !lhs[1].empty? && lhs[1] != [[:void_stmt]] && lhs[1].last[0] == :regexp_literal
              lhs[1][0..-2].each { |node| transform_tree(node, scope_stack) }
              add_locals_from_regexp(lhs[1].last, scope_stack)
              transform_tree(rhs, scope_stack)
            else
              transform_in_order(tree, scope_stack)
            end
          else
            transform_in_order(tree, scope_stack)
          end
        when :if_mod, :unless_mod, :while_mod, :until_mod, :rescue_mod
          # The AST is the reverse of the parse order for these nodes.
          transform_tree(tree[2], scope_stack)
          transform_tree(tree[1], scope_stack)
        when :alias_error, :assign_error  # error already top-level! wrap it again.
          wrap_node_with_error(tree)
        else
          transform_in_order(tree, scope_stack)
        end
      else
        transform_in_order(tree, scope_stack)
      end
    end
597284
function TemplateLiteral(node, parent, scope, file) {
    var nodes = [];

    var _arr2 = node.quasis;
    for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
      var elem = _arr2[_i2];
      nodes.push(t.literal(elem.value.cooked));

      var expr = node.expressions.shift();
      if (expr) nodes.push(expr);
    }

    // filter out empty string literals
    nodes = nodes.filter(function (n) {
      return !t.isLiteral(n, { value: "" });
    });

    // since `+` is left-to-right associative
    // ensure the first node is a string if first/second isn't
    if (!isString(nodes[0]) && !isString(nodes[1])) {
      nodes.unshift(t.literal(""));
    }

    if (nodes.length > 1) {
      var root = buildBinaryExpression(nodes.shift(), nodes.shift());

      var _arr3 = nodes;
      for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
        var _node = _arr3[_i3];
        root = buildBinaryExpression(root, _node);
      }

      this.replaceWith(root);
      //crawl(this);
    } else {
        return nodes[0];
      }
  }
1047287
function tfootNodes(ast) {
  var nodes = [];
  var tfoot;

  for (var i = 0; i < ast.nodes.length; i++) {
    var node = ast.nodes[i];
    if (node.type === 'tfoot') {
      tfoot = node.nodes;
    } else {
      nodes.push(node);
    }
  }

  if (tfoot) {
    var tbody = util.firstOfType(ast.nodes, 'tbody');
    if (tbody) {
      var len = tfoot.length;
      var idx = -1;
      while (++idx < len) {
        var tok = tfoot[idx];
        define(tok, 'parent', tbody);
        tbody.nodes.push(tok);
      }
    }
  }

  ast.nodes = nodes;
  return ast;
}
589618
function ExportNamedDeclaration(node, parent, scope) {
    var nodes = [];
    build(node, nodes, scope);
    if (!nodes.length) return;

    if (node.specifiers.length >= 1) {
      nodes.push(node);
    }

    return nodes;
  }
916555
function instructions(ast, context) {
    var buf='';
    if(!ast) return buf;
    symbols_['$']=context;
    for(var i=0,astlen=ast.length;i<astlen;i++) {
      var node = ast[i];
      //console.log(node);
      if(node && node.length>=3) {
        // assignment 
        if(node[0]=='=') {
          // [ '=', id, val ]
          var id = node[1];
          var v = getValue(node[2]);
          if(id=='_') {
            var tmp=symbols_.hasOwnProperty(id)?symbols_[id]:[];
            tmp.push(v);
            v=tmp;
          } 
          symbols_[id] = v;
        } else if(node[0]=='rem') {
          // just ignore comments
        } else {
          console.log('*** unknown tag **** ' + node[0]);
        }
      }
    }
    delete symbols_['$'];
    return buf;
  }
743734
function findVariableReferences (ast, identifier, skip) {
  var references = [];
  traverse.traverse(ast, {
    enter: function (node, parent) {
      if (node === skip) {
        this.skip();
      }
      else if (
          node.type === 'Identifier' &&
          node.name === identifier.name &&
          (parent.type !== 'MemberExpression' || parent.left !== node)
      ) {
        references.push(node);
      }
    }
  });
  return references;
}
1134174
def from_ast(
        pyast_node, node=None, node_cls=None, Node=Node,
        iter_fields=ast.iter_fields, AST=ast.AST):
    '''
    '''
    node_cls = node_cls or Node
    node = node or node_cls()
    name = pyast_node.__class__.__name__

    attrs = []
    for field, value in iter_fields(pyast_node):
        if name == 'Dict':
            for key, value in zip(pyast_node.keys, pyast_node.values):
                if isinstance(value, list):
                    for item in value:
                        if isinstance(item, AST):
                            value = from_ast(item)
                elif isinstance(value, AST):
                    value = from_ast(value)
                attrs.append((key.s, value))
        else:
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, AST):
                        value = from_ast(item)
            elif isinstance(value, AST):
                value = from_ast(value)
            attrs.append((field, value))
    node.update(attrs, type=name)
    return node
453093
def node_branch(self, astr_node, abranch):
            
            self.dict_branch[astr_node].node_dictBranch(abranch.dict_branch)
750408
def copy_tree(src, dst, symlinks=False, ignore=[]):
    
    names = os.listdir(src)

    if not os.path.exists(dst):
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignore:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copy_tree(srcname, dstname, symlinks, ignore)
            else:
                copy_file(srcname, dstname)
        except (IOError, os.error) as exc:
            errors.append((srcname, dstname, str(exc)))
        except CTError as exc:
            errors.extend(exc.errors)
    if errors:
        raise CTError(errors)
810196
def build_ast(self):
        """"""
        n = self.root_node
        if n.type == syms.file_input:
            stmts = []
            for i in range(len(n.children) - 1):
                stmt = n.children[i]
                if stmt.type == tokens.NEWLINE:
                    continue
                sub_stmts_count = self.number_of_statements(stmt)
                if sub_stmts_count == 1:
                    stmts.append(self.handle_stmt(stmt))
                else:
                    stmt = stmt.children[0]
                    for j in range(sub_stmts_count):
                        small_stmt = stmt.children[j * 2]
                        stmts.append(self.handle_stmt(small_stmt))
            return ast.Module(stmts)
        elif n.type == syms.eval_input:
            body = self.handle_testlist(n.children[0])
            return ast.Expression(body)
        elif n.type == syms.single_input:
            first_child = n.children[0]
            if first_child.type == tokens.NEWLINE:
                # An empty line.
                return ast.Interactive([])
            else:
                num_stmts = self.number_of_statements(first_child)
                if num_stmts == 1:
                    stmts = [self.handle_stmt(first_child)]
                else:
                    stmts = []
                    for i in range(0, len(first_child.children), 2):
                        stmt = first_child.children[i]
                        if stmt.type == tokens.NEWLINE:
                            break
                        stmts.append(self.handle_stmt(stmt))
                return ast.Interactive(stmts)
        else:
            raise AssertionError("unknown root node")
598816
function asyncLoops_1(ast, state) {
        treeWalk(ast, function (node, descend, path) {
            function mapContinue(label) {
                return {
                    type: 'ReturnStatement',
                    argument: {
                        type: 'UnaryExpression',
                        operator: 'void',
                        prefix: true,
                        argument: thisCall(label || symContinue)
                    }
                };
            }
            
            ;
            function mapExits(n, descend) {
                if (n.type === 'BreakStatement') {
                    coerce(n, cloneNode(mapBreak(n.label && opts.generatedSymbolPrefix + "Loop_" + n.label.name + "_exit")));
                } else if (n.type === 'ContinueStatement') {
                    coerce(n, cloneNode(mapContinue(n.label && opts.generatedSymbolPrefix + "Loop_" + n.label.name + "_next")));
                } else if (examine(n).isFunction) {
                    return true;
                }
                descend();
            }
            
            if (node.type === 'ForInStatement' && containsAwait(node)) {
                transformForIn(node, path);
            } else if (node.type === 'ForOfStatement' && containsAwait(node)) {
                iterizeForOf(node, path);
            }
            descend();
            var p;
            if (examine(node).isLoop && containsAwait(node)) {
                var init = node.init;
                var condition = node.test || literal(true);
                var step = node.update;
                var body = node.body;
                var loopUsesThis = containsThis(body);
                if (init) {
                    if (!examine(init).isStatement) {
                        init = {
                            type: 'ExpressionStatement',
                            expression: init
                        };
                    }
                }
                step = step && {
                    type: 'ExpressionStatement',
                    expression: step
                };
                body = examine(body).isBlockStatement ? cloneNode(body).body : [cloneNode(body)];
                var label = node.$label && node.$label.name;
                label = "Loop_" + (label || generatedSymbol++);
                var symExit = opts.generatedSymbolPrefix + (label + "_exit");
                var symContinue = opts.generatedSymbolPrefix + (label + "_next");
                var loop = ident(opts.generatedSymbolPrefix + label);
                // How to exit the loop
                var mapBreak = function (label) {
                    return {
                        type: 'ReturnStatement',
                        argument: {
                            type: 'UnaryExpression',
                            operator: 'void',
                            prefix: true,
                            argument: {
                                type: 'CallExpression',
                                callee: ident(label || symExit),
                                arguments: []
                            }
                        }
                    };
                };
                // How to continue the loop
                var defContinue = makeContinuation(symContinue, [{
                    type: 'ReturnStatement',
                    argument: {
                        type: 'CallExpression',
                        callee: loopUsesThis ? bindAsync(loop) : loop,
                        arguments: [ident(symExit),genIdent.error]
                    }
                }]);
                if (step) 
                    defContinue.body.body.unshift(step);
                for (var i = 0;i < body.length; i++) {
                    treeWalk(body[i], mapExits);
                }
                body.push(cloneNode(mapContinue()));
                var subCall = {
                    type: 'FunctionExpression',
                    id: loop,
                    params: [ident(symExit),genIdent.error],
                    body: {
                        type: 'BlockStatement',
                        body: [defContinue]
                    }
                };
                if (node.type === 'DoWhileStatement') {
                    defContinue.body.body = [{
                        type: 'IfStatement',
                        test: cloneNode(condition),
                        consequent: {
                            type: 'BlockStatement',
                            body: cloneNode(defContinue.body.body)
                        },
                        alternate: {
                            type: 'ReturnStatement',
                            argument: {
                                type: 'CallExpression',
                                callee: ident(symExit),
                                arguments: []
                            }
                        }
                    }];
                    subCall.body.body = [defContinue].concat(body);
                } else {
                    var nextTest = {
                        type: 'IfStatement',
                        test: cloneNode(condition),
                        consequent: {
                            type: 'BlockStatement',
                            body: body
                        },
                        alternate: cloneNode(mapBreak())
                    };
                    subCall.body.body.push(nextTest);
                }
                var replace = {
                    type: 'ExpressionStatement',
                    expression: {
                        type: 'AwaitExpression',
                        argument: bindAsync(subCall, literal(0))
                    }
                };
                if (init && init.type === 'VariableDeclaration' && (init.kind === 'let' || init.kind === 'const')) {
                    if (init.kind === 'const') 
                        init.kind = 'let';
                    replace = {
                        type: 'BlockStatement',
                        body: [cloneNode(init),replace]
                    };
                    init = null;
                }
                for (p = 0; p < path.length; p++) {
                    var ref = path[p];
                    if ('index' in ref) {
                        if (init) {
                            ref.parent[ref.field].splice(ref.index, 1, cloneNode(init), replace);
                        } else {
                            ref.parent[ref.field][ref.index] = replace;
                        }
                        return true;
                    }
                }
            }
            return true;
        }, state);
        return ast;
    }
411843
def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False):
  
  with util.LogTime('enumerate_scope'):
    scope = {}
    for node in reversed(ast_rootpath):
      if is_tuple_node(node):
        for member in node.members:
          if member.name not in scope:
            scope[member.name] = Completion(member.name, False, member.comment.as_string(), member.location)

    if include_default_builtins:  # Backwards compat flag
      root_env = gcl.default_env

    if root_env:
      for k in root_env.keys():
        if k not in scope and not hide_from_autocomplete(root_env[k]):
          v = root_env[k]
          scope[k] = Completion(k, True, dedent(v.__doc__ or ''), None)

    return scope
1274169
def convert_tloc(ast):
    """"""

    from_loc_arg = ast.args[1]
    to_loc_arg = ast.args[2]
    from_loc = Function("fromLoc", spec, parent_function=ast)
    from_loc.add_argument(
        NSArg(from_loc_arg.namespace, from_loc_arg.value, parent_function=from_loc)
    )
    to_loc = Function("toLoc", spec, parent_function=ast)
    to_loc.add_argument(
        NSArg(to_loc_arg.namespace, to_loc_arg.value, parent_function=to_loc)
    )

    ast.args[1] = from_loc
    ast.args[2] = to_loc

    return ast