Transforms the given tree into a RipperPlus AST, using a scope stack.
 This will be recursively called through each level of the tree.
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
728557
function loadSubTree(root, own) {
            var loadSubTrees = function (nodes) {
                    for (var i = 0; i < nodes.length; i++) {
                        nodes[i] = self.loadSubTree(nodes[i], own);
                    }
                    return TASYNC.lift(nodes);

                },
                childLoading = own === true ? self.loadOwnChildren : self.loadChildren;
            return TASYNC.call(function (children) {
                if (children.length < 1) {
                    return [root];
                } else {
                    return TASYNC.call(function (subArrays) {
                        var nodes = [],
                            i;
                        for (i = 0; i < subArrays.length; i++) {
                            nodes = nodes.concat(subArrays[i]);
                        }
                        nodes.unshift(root);
                        return nodes;
                    }, loadSubTrees(children));
                }
            }, childLoading(root));
        }
1320251
public void visitTopLevel(JCCompilationUnit tree) {
        tree.defs = translate(tree.defs);
        result = tree;
    }
875701
private IQTree liftBindingFromLiftedChildren(ImmutableList<IQTree> liftedChildren, VariableGenerator variableGenerator,
                                                 IQProperties currentIQProperties) {

        /*
         * Cannot lift anything if some children do not have a construction node
         */
        if (liftedChildren.stream()
                .anyMatch(c -> !(c.getRootNode() instanceof ConstructionNode)))
            return iqFactory.createNaryIQTree(this, liftedChildren, currentIQProperties.declareLifted());

        ImmutableSubstitution<ImmutableTerm> mergedSubstitution = mergeChildSubstitutions(
                    projectedVariables,
                    liftedChildren.stream()
                            .map(c -> (ConstructionNode) c.getRootNode())
                            .map(ConstructionNode::getSubstitution)
                            .collect(ImmutableCollectors.toList()),
                    variableGenerator);

        if (mergedSubstitution.isEmpty()) {
            return iqFactory.createNaryIQTree(this, liftedChildren, currentIQProperties.declareLifted());
        }
        ConstructionNode newRootNode = iqFactory.createConstructionNode(projectedVariables, mergedSubstitution);

        ImmutableSet<Variable> unionVariables = newRootNode.getChildVariables();
        UnionNode newUnionNode = iqFactory.createUnionNode(unionVariables);

        NaryIQTree unionIQ = iqFactory.createNaryIQTree(newUnionNode,
                liftedChildren.stream()
                        .map(c -> (UnaryIQTree) c)
                        .map(c -> updateChild(c, mergedSubstitution, unionVariables))
                        .collect(ImmutableCollectors.toList()));

        return iqFactory.createUnaryIQTree(newRootNode, unionIQ);
    }
390499
@Override
  public TypedScope createScope(Node root, AbstractScope<?, ?> parent) {
    checkArgument(parent == null || parent instanceof TypedScope);
    TypedScope typedParent = (TypedScope) parent;

    TypedScope scope = memoized.get(root);
    if (scope != null) {
      checkState(typedParent == scope.getParent());
    } else {
      scope = createScopeInternal(root, typedParent);
      memoized.put(root, scope);
    }
    return scope;
  }
387002
def get_tree(cls, parent=None):
        
        cls = get_result_class(cls)

        if parent is None:
            # return the entire tree
            return cls.objects.all()
        if parent.is_leaf():
            return cls.objects.filter(pk=parent.pk)
        return cls.objects.filter(
            tree_id=parent.tree_id,
            lft__range=(parent.lft, parent.rgt - 1))
1133954
def for_scope(self, scope, inherit_from_enclosing_scope=True):
    

    # First get enclosing scope's option values, if any.
    if scope == GLOBAL_SCOPE or not inherit_from_enclosing_scope:
      values = OptionValueContainer()
    else:
      values = copy.copy(self.for_scope(enclosing_scope(scope)))

    # Now add our values.
    flags_in_scope = self._scope_to_flags.get(scope, [])
    self._parser_hierarchy.get_parser_by_scope(scope).parse_args(flags_in_scope, values)

    # Check for any deprecation conditions, which are evaluated using `self._flag_matchers`.
    if inherit_from_enclosing_scope:
      self._check_and_apply_deprecations(scope, values)

    return values
477990
function rpnToTree(values) {
    let ii, len, op, stack, slice, count;

    stack = [];
    // result = [];
    for (ii = 0, len = values.length; ii < len; ii++) {
        op = values[ii];

        if (op === LEFT_PAREN) {
            // cut out this sub and convert it to a tree
            slice = findMatchingRightParam(values, ii);

            if (!slice || slice.length === 0) {
                throw new Error('mismatch parentheses');
            }

            ii += slice.length + 1;

            // evaluate this sub command before pushing it to the stack
            slice = rpnToTree(slice);

            stack.push(slice);
        } else {
            if (Array.isArray(op)) {
                stack.push(op);
            } else {
                // figure out how many arguments to take from the stack
                count = argCount(op);

                slice = stack.splice(stack.length - count, count);

                if (Array.isArray(slice) && slice.length === 1) {
                    slice = arrayFlatten(slice, true);
                }

                // TODO: ugh, occasionally args will get flattened too much
                if (slice[0] === VALUE) {
                    // note only happens with ALIAS_GET
                    // log.debug('overly flat ' + JSON.stringify([op].concat(slice)));
                    slice = [slice];
                }
                stack.push([op].concat(slice));
            }
        }
    }

    return stack;
}
193058
def dump_tree(node, name=None, initial_indent='', indentation='    ',
              maxline=120, maxmerged=80,
              # Runtime optimization
              iter_node=iter_node, special=ast.AST,
              list=list, isinstance=isinstance, type=type, len=len):
    
    def dump(node, name=None, indent=''):
        level = indent + indentation
        name = name and name + '=' or ''
        values = list(iter_node(node))
        if isinstance(node, list):
            prefix, suffix = '%s[' % name, ']'
        elif values:
            prefix, suffix = '%s%s(' % (name, type(node).__name__), ')'
        elif isinstance(node, special):
            prefix, suffix = name + type(node).__name__, ''
        else:
            return '%s%s' % (name, repr(node))
        node = [dump(a, b, level) for a, b in values if b != 'ctx']
        oneline = '%s%s%s' % (prefix, ', '.join(node), suffix)
        if len(oneline) + len(indent) < maxline:
            return '%s' % oneline
        if node and len(prefix) + len(node[0]) < maxmerged:
            prefix = '%s%s,' % (prefix, node.pop(0))
        node = (',\n%s' % level).join(node).lstrip()
        return '%s\n%s%s%s' % (prefix, level, node, suffix)
    return dump(node, name, initial_indent)
676530
def convert_tree(self, ptb_tree, representation='basic',
                     include_punct=True, include_erased=False,
                     add_lemmas=False, universal=True):
        """"""
        self._raise_on_bad_input(ptb_tree)
        self._raise_on_bad_representation(representation)
        tree = self.treeReader(ptb_tree)
        if tree is None:
            raise ValueError("Invalid Penn Treebank tree: %r" % ptb_tree)
        deps = self._get_deps(tree, include_punct, representation,
                              universal=universal)

        tagged_yield = self._listify(tree.taggedYield())
        indices_to_words = dict(enumerate(tagged_yield, 1))
        sentence = Sentence()
        covered_indices = set()

        def add_token(index, form, head, deprel, extra):
            tag = indices_to_words[index].tag()
            if add_lemmas:
                lemma = self.stem(form, tag)
            else:
                lemma = None
            token = Token(index=index, form=form, lemma=lemma, cpos=tag,
                          pos=tag, feats=None, head=head, deprel=deprel,
                          phead=None, pdeprel=None, extra=extra)
            sentence.append(token)

        # add token for each dependency
        for dep in deps:
            index = dep.dep().index()
            head = dep.gov().index()
            deprel = dep.reln().toString()
            form = indices_to_words[index].value()

            dep_is_copy = dep.dep().copyCount()
            gov_is_copy = dep.gov().copyCount()
            if dep_is_copy or gov_is_copy:
                extra = {}
                if dep_is_copy:
                    extra['dep_is_copy'] = dep_is_copy
                if gov_is_copy:
                    extra['gov_is_copy'] = gov_is_copy
            else:
                extra = None
            add_token(index, form, head, deprel, extra)
            covered_indices.add(index)
        if include_erased:
            # see if there are any tokens that were erased
            # and add them as well
            all_indices = set(indices_to_words.keys())
            for index in all_indices - covered_indices:
                form = indices_to_words[index].value()
                if not include_punct and not self.puncFilter(form):
                    continue
                add_token(index, form, head=0, deprel='erased', extra=None)
            # erased generally disrupt the ordering of the sentence
            sentence.sort()

        if representation == 'basic':
            sentence.renumber()
        return sentence
520109
private static List<JoinNode> generateFullJoinOrdersForTree(JoinNode subTree) {
        assert(subTree != null);
        List<JoinNode> joinOrders = new ArrayList<>();
        if (!(subTree instanceof BranchNode)) {
            // End of recursion
            joinOrders.add(subTree);
            return joinOrders;
        }
        BranchNode branchNode = (BranchNode) subTree;
        // Descend to the left branch
        assert(branchNode.getLeftNode() != null);
        List<JoinNode> leftJoinOrders = generateFullJoinOrdersForTree(branchNode.getLeftNode());
        assert(!leftJoinOrders.isEmpty());
        // Descend to the right branch
        assert(branchNode.getRightNode() != null);
        List<JoinNode> rightJoinOrders = generateFullJoinOrdersForTree(branchNode.getRightNode());
        assert(!rightJoinOrders.isEmpty());
        // Create permutation pairing left and right nodes and the revere variant
        for (JoinNode leftNode : leftJoinOrders) {
            for (JoinNode rightNode : rightJoinOrders) {
                JoinNode resultOne = new BranchNode(branchNode.getId(), branchNode.getJoinType(),
                        (JoinNode) leftNode.clone(), (JoinNode) rightNode.clone());
                JoinNode resultTwo = new BranchNode(branchNode.getId(), branchNode.getJoinType(),
                        (JoinNode) rightNode.clone(), (JoinNode) leftNode.clone());
                if (branchNode.getJoinExpression() != null) {
                    resultOne.setJoinExpression(branchNode.getJoinExpression().clone());
                    resultTwo.setJoinExpression(branchNode.getJoinExpression().clone());
                }
                if (branchNode.getWhereExpression() != null) {
                    resultOne.setWhereExpression(branchNode.getWhereExpression().clone());
                    resultTwo.setWhereExpression(branchNode.getWhereExpression().clone());
                }
                joinOrders.add(resultOne);
                joinOrders.add(resultTwo);
            }
        }
        return joinOrders;
    }
1186792
public Tree transformTree(Tree t) {
    if (VERBOSE) {
      System.err.println("Input to CoordinationTransformer: " + t);
    }
    Tree tx = tn.transformTree(t);
    if (VERBOSE) {
      System.err.println("After DependencyTreeTransformer:  " + tx);
    }
    if (tx == null) {
      return tx;
    }
    Tree tt = UCPtransform(tx);
    if (VERBOSE) {
      System.err.println("After UCPTransformer:             " + t);
    }
    Tree ttt = CCtransform(tt);
    if (VERBOSE) {
      System.err.println("After CCTransformer:              " + t);
    }
    Tree ret = qp.transformTree(ttt);
    if (VERBOSE) {
      System.err.println("After QPTreeTransformer:          " + t);
    }
    return ret;
  }
365136
function slice(tree, from, to) {
	var max = tree.size;

	if (to === undefined) to = max;

	if (from >= max) {
		return EMPTY;
	}

	if (to > max) {
		to = max;
	}
	//invert negative numbers
	function confine(i) {
		return i < 0 ? i + max : i;
	}
	from = confine(from);
	to = confine(to);
	var offset = (0, _util.tailOffset)(tree);var newRoot, newTail;
	if (from >= offset) {
		newRoot = null;
		newTail = tree.tail.slice(from - offset, to - offset);
	} else if (to <= offset) {
		newRoot = (0, _slice.sliceRoot)(tree.root, from, to);
		newTail = [];
	} else {
		newRoot = (0, _slice.sliceRoot)(tree.root, from, offset);
		newTail = tree.tail.slice(0, to - offset);
	}
	newTail.height = 0;
	return new Tree(to - from, newRoot, newTail);
}
1298806
def transform_in_order(tree, scope_stack)
      # some nodes have no type: include the first element in this case
      range = Symbol === tree[0] ? 1..-1 : 0..-1
      tree[range].each do |subtree|
        # obviously don't transform literals or token locations
        if Array === subtree && !(Fixnum === subtree[0])
          transform_tree(subtree, scope_stack)
        end
      end
    end
930293
function (oTree, sSeparator) {
			var oObject = this.toHierarchy(oTree),
				aFilters = [];

			function collect(sName, oObject) {
				var aChildren, bChildren;
				if (typeof oObject === 'object') {
					if (oObject['']) {
						aFilters.push(sName + '/');
						return;
					}
					aChildren = Object.keys(oObject);
					bChildren = aChildren.length;
				}
				if (bChildren) {
					aChildren.forEach(function (sChild) {
						if (sChild === '') {
							return;
						}
						if (oObject[sChild] === true) {
							aFilters.push((sName ? sName + '/' : '') + sChild);
						} else if (typeof oObject[sChild] === 'object') {
							collect((sName ? sName + '/' : '') + sChild, oObject[sChild]);
						}
					});
				}
			}

			if (this.get(oObject, '/')) {
				return true;
			}

			collect('', oObject);

			return (aFilters.length > 0 ? aFilters.join(sSeparator || ',') : false);
		}
737013
private void decomposeInIIFE(NodeTraversal t, Node classNode) {
    // converts
    // `class X extends something {}`
    // to
    // `(function() { return class X extends something {}; })()`
    Node functionBody = IR.block();
    Node function = IR.function(IR.name(""), IR.paramList(), functionBody);
    Node call = NodeUtil.newCallNode(function);
    classNode.replaceWith(call);
    functionBody.addChildToBack(IR.returnNode(classNode));
    call.useSourceInfoIfMissingFromForTree(classNode);
    // NOTE: extractExtends() will end up reporting the change for the new function, so we only
    //     need to report the change to the enclosing scope
    t.reportCodeChange(call);
    // Now do the extends expression extraction within the IIFE
    extractExtends(t, classNode);
  }
1160729
private Node tryFoldAssignment(Node subtree) {
    checkState(subtree.isAssign());
    Node left = subtree.getFirstChild();
    Node right = subtree.getLastChild();
    if (left.isName()
        && right.isName()
        && left.getString().equals(right.getString())) {
      // Only names
      subtree.replaceWith(right.detach());
      reportChangeToEnclosingScope(right);
      return right;
    } else if (left.isDestructuringPattern() && !left.hasChildren()) {
      // `[] = <expr>` becomes `<expr>`
      // Note that this does potentially change behavior. If `<expr>` is not iterable and this
      // code originally threw, it will no longer throw.
      subtree.replaceWith(right.detach());
      reportChangeToEnclosingScope(right);
      return right;
    }
    return subtree;
  }