Build AST from trace.
Walk through the trace iteratively and recursively.

@param int $i Current trace index.
@param array &$children Collected children.
@return Node|int
@throws \LogicException
496978
protected function buildTree(int $i = 0, array &$children = [])
    {
        $max = \count($this->trace);

        while ($i < $max) {
            $trace = $this->trace[$i];

            if ($trace instanceof Entry) {
                $ruleName = $trace->getRule();
                $rule = $this->grammar->fetch($ruleName);
                $isRule = $trace->isTransitional() === false;
                $nextTrace = $this->trace[$i + 1];
                $id = $rule->getNodeId();

                // Optimization: Skip empty trace sequence.
                if ($nextTrace instanceof Escape && $ruleName === $nextTrace->getRule()) {
                    $i += 2;

                    continue;
                }

                if ($isRule === true) {
                    $children[] = $ruleName;
                }

                if ($id !== null) {
                    $children[] = [$id];
                }

                $i = $this->buildTree($i + 1, $children);

                if ($isRule === false) {
                    continue;
                }

                $handle = [];
                $childId = null;

                do {
                    $pop = \array_pop($children);

                    if (\is_object($pop) === true) {
                        $handle[] = $pop;
                    } elseif (\is_array($pop) && $childId === null) {
                        $childId = \reset($pop);
                    } elseif ($ruleName === $pop) {
                        break;
                    }
                } while ($pop !== null);

                if ($childId === null) {
                    $childId = $rule->getDefaultId();
                }

                if ($childId === null) {
                    for ($j = \count($handle) - 1; $j >= 0; --$j) {
                        $children[] = $handle[$j];
                    }

                    continue;
                }

                $children[] = $this->getRule(
                    (string)($id ?: $childId),
                    \array_reverse($handle),
                    $trace->getOffset()
                );
            } elseif ($trace instanceof Escape) {
                return $i + 1;
            } else {
                if (! $trace->isKept()) {
                    ++$i;
                    continue;
                }

                $children[] = new Leaf($trace->getToken());
                ++$i;
            }
        }

        return $children[0];
    }
41935
static function parseUseTrait(array $tokens, &$i) {
    ++$i;
    $names = ParserUtil::parseIdentifierList($tokens, $i);
    if (FALSE === $names) {
      return FALSE;
    }
    $id = ParserUtil::nextSubstantialIncl($tokens, $i);
    if (';' === $id) {
      ++$i;
      return new AstUseTrait($names);
    }
    elseif ('{' === $id) {
      ParserUtil::skipCurly($tokens, $i);
      return new AstUseTrait($names);
    }
    else {
      return FALSE;
    }
  }
1107430
protected static function build_tree($all, $parentid) {
        $tree = array();
        foreach ($all as $one) {
            if ($one->get('parentid') == $parentid) {
                $node = new stdClass();
                $node->competency = $one;
                $node->children = self::build_tree($all, $one->get('id'));
                $tree[] = $node;
            }
        }
        return $tree;
    }
463418
private static function toStdClass(
        SimpleXMLElement $source,
        $isArray = false
    ) {
        $destination = $isArray ? [] : new stdClass();
        foreach ($source as $key=>$value) {
            $key = Str::camel($key);
            $attrs = $value->attributes();
            if (!empty($attrs->type)) {
                $type = (string) $attrs->type;
                switch ($type) {
                    case 'integer':
                        $destination->$key = (int) $value;
                        break;
                    case 'boolean':
                        $value = (string) $value;
                        $destination->$key = (bool) $value === 'true';
                        break;
                    case 'array':
                        if (is_array($destination)) {
                            $destination[$key] = self::toStdClass($value, true);
                        } else {
                            $destination->$key = self::toStdClass($value, true);
                        }
                        break;
                    default:
                        $destination->$key = (string) $value;
                        break;
                }
            } else {
                $children = $value->children();
                if (!empty($children)) {
                    if ($isArray) {
                        $i               = count($destination);
                        $destination[$i] = self::toStdClass($value);
                    } else {
                        $destination->$key = self::toStdClass($value);
                    }
                } else {
                    $destination->$key = (string) $value;
                }
            }
        }

        return $destination;
    }
389941
public function getChildren($iId, $bRecursive = false, array $aData = [])
    {
        $aQueryData = $aData;
        if (!array_key_exists('where', $aQueryData)) {
            $aQueryData['where'] = [];
        }
        $aQueryData['where'][] = ['parent_id', $iId];

        $aChildren = $this->getAll($aQueryData);
        foreach ($aChildren as $oChild) {
            if ($bRecursive) {
                $oChild->children = $this->getChildren($oChild->id, $bRecursive, $aData);
            }
        }
        return $aChildren;
    }
1113552
public function setChildren(array $children): NodeInterface
    {
        foreach ($this->getChildren() as $node) {
            $this->removeChild($node->getId());
        }

        foreach ($children as $child) {
            $this->addChild($child);
        }

        return $this;
    }
954120
private function indexEntry(DirectoryIterator $i) {
        if ($i->isDot()) {
            return;
        }

        echo self::$debug ? $i->getPathname() . "\n" : "";

        $skip   = $this->isSkipped($i);
        $upload = $i->isFile() && ($this->uploadSizeLimit > $i->getSize() || $this->uploadSizeLimit === -1);

        $skip2 = false; // to be able to recursively go into directory we can't reuse $skip
        if (!$skip) {
            $class  = $i->isDir() ? $this->collectionClass : $this->binaryClass;
            $parent = $this->parent === null ? null : $this->parent->getId();
            $file   = new File($this->fedora, $i->getPathname(), $class, $parent);
            if ($this->metaLookup) {
                $file->setMetaLookup($this->metaLookup, $this->metaLookupRequire);
            }
            $skip2 = $this->isSkippedExisting($file);
        }
        if (!$skip && !$skip2) {
            $skipNotExist = $this->skipMode === self::SKIP_NOT_EXIST;
            try {
                $res = $file->updateRms(!$skipNotExist, $upload, $this->fedoraLoc);

                $this->indexedRes[$i->getPathname()] = $res;
                echo self::$debug ? "\t" . ($file->getCreated() ? "create " : "update ") . ($upload ? "+ upload " : "") . "\n" : '';
                $this->handleAutoCommit();
            } catch (MetaLookupException $e) {
                if ($this->metaLookupRequire) {
                    $skip = true;
                } else {
                    throw $e;
                }
            } catch (NotFound $e) {
                if ($skipNotExist) {
                    $skip = true;
                } else {
                    throw $e;
                }
            }
        } else if ($skip2) {
            $res = $file->getResource(false, false);
        }
        if ($skip || $skip2) {
            echo self::$debug ? "\tskip" . ($skip2 ? '2' : '') . "\n" : "";
        }

        echo self::$debug && !$skip && !$skip2 ? "\t" . $res->getId() . "\n\t" . $res->getUri() . "\n" : "";

        // recursion
        if ($i->isDir() && (!$skip || $this->flatStructure && $this->depth > 0)) {
            echo self::$debug ? "entering " . $i->getPathname() . "\n" : "";
            $ind = clone($this);
            if (!$this->flatStructure) {
                $ind->parent = $res;
            }
            $ind->setDepth($this->depth - 1);
            $path              = File::getRelPath($i->getPathname());
            $ind->setPaths(array($path));
            list($recRes, $recCom) = $ind->__index();
            $this->indexedRes  = array_merge($this->indexedRes, $recRes);
            $this->commitedRes = array_merge($this->commitedRes, $recCom);
            echo self::$debug ? "going back from " . $path : "";
            $this->handleAutoCommit();
            echo self::$debug ? "\n" : "";
        }
    }
474834
private static function renderTraceStep( $trace, $i, $j )
	{
		if( $j == 0 )
			if( isset( $trace['function'] ) )
				if( in_array( $trace['function'], array( "eval", "throwException" ) ) )				//  Exception was thrown using throwException
					return "";

		$content	= "";
		if( isset( $trace["file"] ) ){
			$pathName	= self::trimRootPath( $trace["file"] );
			$fileName	= '<span class="file">'.pathinfo( $pathName, PATHINFO_FILENAME ).'</span>';
			$extension	= pathinfo( $pathName, PATHINFO_EXTENSION );
			$extension	= '<span class="ext">'.( $extension ? '.'.$extension : '' ).'</span>';
			$path		= '<span class="path">'.dirname( $pathName ).'/</span>';
			$line		= '<span class="line">['.$trace["line"].']</span>';
			$separator	= '<span class="sep1">: </span>';
			$content	.= $path.$fileName.$extension.$line.$separator;

		}
		if( array_key_exists( "class", $trace ) && array_key_exists( "type", $trace ) ){
			$class		= '<span class="class">'.$trace["class"].'</span>';
			$type		= '<span class="type">'.$trace["type"].'</span>';
			$content	.= $class.$type;
		}
		if( array_key_exists( "function", $trace ) ){
			$block	= NULL;
			if( array_key_exists( "args", $trace ) && count( $trace['args'] ) )
			{
				$argList	= array();
				foreach( $trace["args"] as $argument )
				{
					$type	= self::renderArgumentType( $argument );
					$string	= self::renderArgument( $argument );
					$argList[]	= UI_HTML_Tag::create( 'dt', $type );
					$argList[]	= UI_HTML_Tag::create( 'dd', $string );
				}
				$argList	= UI_HTML_Tag::create( 'dl', implode( $argList ) );
				$block		= UI_HTML_Tag::create( 'blockquote', $argList );
			}
			$function	= '<span class="func">'.$trace["function"].'</span>';
			$arguments	= '<span class="args">('.$block.')</span>';
			$content	.= $function.$arguments;
		}
//		else
//			die( print_m( $trace ) );
//			$content	.= $trace["function"]."(".$block.')';
		return $content;
	}
1085674
@Nullable
    public Node<I> getChild(int idx) {
        if (children == null) {
            return null;
        }
        return children.array[idx];
    }
1013680
private function doParse(array $tokens, &$i) {

    $docComment = NULL;
    $modifiers = array();

    for (;; ++$i) {

      $id = $tokens[$i][0];

      if (T_WHITESPACE === $id || T_COMMENT === $id) {
        // Continue loop.
      }
      elseif (T_DOC_COMMENT === $id) {
        $docComment = $tokens[$i][1];
        // Continue loop.
      }
      elseif (T_PROTECTED === $id || T_PRIVATE === $id || T_PUBLIC === $id || T_ABSTRACT === $id || T_FINAL === $id || T_STATIC === $id) {
        $modifiers[$id] = TRUE;
        // Continue loop.
      }
      elseif (T_FUNCTION === $id) {
        return $this->methodParser->parse($tokens, $i, $modifiers, $docComment);
      }
      elseif (FALSE && T_USE === $id) {
        return self::parseUseTrait($tokens, $i);
      }
      elseif (FALSE && T_VARIABLE === $id) {
        return self::parseMemberVariable($tokens, $i, $modifiers, $docComment);
      }
      elseif (FALSE && T_CONST === $id) {
        return self::parseClassConstant($tokens, $i, $modifiers, $docComment);
      }
      else {
        return self::ignoreMiraculousMember($tokens, $i);
      }
    }

    throw new \RuntimeException('Unreachable code.');
  }
510957
public function getChildren($id)
    {
        $table = $this->getTable();
        $closure = $table . '_closure';
        $tableAlias = 'c';
        $closureAlias = 'cc';
        $primaryKey = $this->mapper->getPrimaryKey($table);
        $fluent = $this->connection->command()
            ->select('%n.*', $tableAlias)
            ->from('%n AS %n', $table, $tableAlias)
            ->join('%n AS %n', $closure, $closureAlias)
            ->on('%n.%n = %n.descendant', $tableAlias, $primaryKey, $closureAlias)
            ->where('%n.ancestor = %s', $closureAlias, $id)
            ->where('%n.depth = 1', $closureAlias);

        $entityClass = $this->mapper->getEntityClass($this->getTable());
        $rc = new ReflectionClass($entityClass);
        $closureEntityClass = $entityClass . 'Closure';
        if ($rc->implementsInterface('Joseki\LeanMapper\ClosureTable\ISortable')) {
            $fluent->orderBy('%n.order', $tableAlias);
        } else if (class_exists($closureEntityClass)) {
            /** @var Entity $closureEntity */
            $closureEntity = new $closureEntityClass;
            if ($closureEntity->getReflection($this->mapper)->getEntityProperty('order')) {
                $fluent->orderBy('%n.order', $closureAlias);
            }
        }

        return $this->createEntities($fluent->fetchAll());
    }
519042
def traversal(root):
    ''''''
    stack = [root]
    while len(stack) > 0:
        node = stack.pop()
        if hasattr(node,'children'):
            if node.children == set():
                try:
                    stack[-1].children.remove(node)
                except:
                    pass
                yield (node,stack)
            else:
                childnode = node.children.pop()
                stack += [node,childnode]
        else: 
            children = [x for x in ast.iter_child_nodes(node)]
            node.children = set(children)
            stack.append(node)
291226
protected function fromChildOverDescendantsNodeIteratorParts( $context, $nodeTest, $iter )
	{
		$this->context = $context;
		$this->nodeTest = $nodeTest;
		$this->iter = $iter;
		$this->lastTest = $nodeTest[ count( $nodeTest ) - 1 ];
		$this->kind = XPathNodeType::All;
		if ( isset( $this->lastTest->nameTest ) || ( isset( $this->lastTest->typeTest ) && $this->lastTest->typeTest->GetNodeKind() == XPathNodeType::Element ) )
		{
			$this->kind = XPathNodeType::Element;
		}
	}
613654
public function buildLineages() {				
		$indis = \Fisharebest\Webtrees\Query\QueryName::individuals($this->tree, $this->surname, null, null, false, false);
		
		if(count($indis) == 0) return null;
		
		$root_lineages = array();
		
		foreach($indis as $indi) {
			$pid = $indi->getXref();
			if(!isset($this->used_indis[$pid])){
				//Find the root of the lineage
				/** @var Fisharebest\Webtrees\Individual $indiFirst  */
				$indiFirst= $this->getLineageRootIndividual($indi);
				if($indiFirst){
					$this->used_indis[$indiFirst->getXref()] = true;
					if($indiFirst->canShow()){
						//Check if the root individual has brothers and sisters, without parents
						$indiChildFamily = $indiFirst->getPrimaryChildFamily();
						if($indiChildFamily !== null){
							$root_node = new LineageRootNode(null); 
							$root_node->addFamily($indiChildFamily);
						}
						else{
							$root_node = new LineageRootNode($indiFirst);
						}
						$root_node = $this->buildLineage($root_node);		
						if($root_node) $root_lineages[] = $root_node;
					}
				}
			}
		}
		
		return $root_lineages;		
	}
658058
function _buildTree(&$tree, &$element) {
        $tree[$element->name()] = $element;
        if ($element->superclass()) {
            $rootDoc = & $this->_doclet->rootDoc();
            $superclass = & $rootDoc->classNamed($element->superclass());
            if ($superclass) {
                $this->_buildTree($tree, $superclass);
            }
        }
    }
220581
public function find($path, $i = 0)
    {
        Argument::i()
            //Argument 1 must be a string
            ->test(1, 'string')
            //Argument 2 must be an integer
            ->test(2, 'int');
        
        if ($i >= count($this->tree)) {
            return null;
        }

        $current = $this->tree[$i];

        //if they are asking for the parent
        if (strpos($path, '../') === 0) {
            return $this->find(substr($path, 3), $i + 1);
        }
        
        if (strpos($path, './') === 0) {
            return $this->find(substr($path, 2), $i);
        }
        
        //separate by .
        $path = explode('.', $path);
        $last = count($path) - 1;

        foreach ($path as $i => $node) {
            //is it the last ?
            if ($i === $last) {
                //does it exist?
                if (isset($current[$node])) {
                    return $current[$node];
                }
                
                //is it length ?
                if ($node === 'length') {
                    //is it a string?
                    if (is_string($current)) {
                        return strlen($current);
                    }
                    
                    //is it an array?
                    if (is_array($current) || $current instanceof \Countable) {
                        return count($current);
                    }
                    
                    //we cant count it, so it's 0
                    return 0;
                }
            }
            
            //we are not at the last node...
            
            //does the node exist and is it an array ?
            if (isset($current[$node]) && is_array($current[$node])) {
                //great we can continue
                $current = $current[$node];
                continue;
            }
            
            //if it exists and we are just getting the length
            if (isset($current[$node]) && $path[$i + 1] === 'length' && ($i + 1) === $last) {
                //let it continue
                continue;
            }
            
            //if we are here, then there maybe a node in current,
            //but there's still more nodes to process
            //either way it cannot be what we are searching for
            break;
        }

        return null;
    }
594140
static function nextSubstantialIncl(array $tokens, &$i) {
    while (TRUE) {
      $id = $tokens[$i][0];
      if (T_WHITESPACE !== $id && T_COMMENT !== $id && T_DOC_COMMENT !== $id) {
        return $id;
      }
      ++$i;
    }
    throw new \RuntimeException('Unreachable!');
  }