Core\Ast\Node::children
$node->children(): array<Core\Ast\Node>The parts directly inside this node, in the order they appear in the source.
Every node of a parsed file is made of smaller parts. The file's own node has one child for each top-level statement. A class has its properties and its methods. Each child is a node too, so you can step down again from any of them.
This goes one step only. Use nodes when you want everything below a node, however deep it sits. A node with nothing inside it, such as a number, gives you an empty array, and that is how you tell a leaf from a branch.
The examples below show one step down into a class, how a leaf differs from a branch, and an outline of a whole file printed level by level.
Return value
Returns array<Core\Ast\Node>. The direct children. The list is empty for a node with no children, such as an Int.
Examples
One step down into a class
<?nvs// Shows how to step one level down into a parsed file. `children` gives the// parts directly inside a node, and each of those is a node of its own.
string $source = <<<'NVS'<?nvsclass Cart { public int $total;
public function clear(): void { $this->total = 0; }}NVS;
Core\Ast\Node $file = Core\Ast::parse($source);
// The file holds one part: the class.Core\Ast\Node $class = $file->children()[0];echo $class->kind(), "\n";
// Inside the class are the property and the method.foreach ($class->children() as Core\Ast\Node $part) { echo ' ', $part->kind(), "\n";}ClassDecl Property MethodA leaf and a branch
<?nvs// Shows how to tell a part that contains other parts from one that does not.// `children` gives an empty array for a node with nothing inside it, such as a// number.
Core\Ast\Node $file = Core\Ast::parse('<?nvs echo 40 + 2;');
foreach ($file->nodes() as Core\Ast\Node $node) { uint $inside = Core\Arr::count($node->children()); if ($inside == 0) { echo $node->kind(), " contains nothing\n"; } else { echo $node->kind(), ' contains ', $inside, "\n"; }}Echo contains 1Binary contains 2Int contains nothingInt contains nothingAn outline of a whole file
<?nvs// Shows how to print an outline of a file, the way an editor shows one in a// side panel. Each level calls `children` to step down one step, so the// printing follows the shape of the code.
class Outline{ public static function show(Core\Ast\Node $node, string $indent): void { echo $indent, $node->kind(), ' on line ', $node->line(), "\n"; foreach ($node->children() as Core\Ast\Node $child) { Outline::show($child, $indent . ' '); } }}
string $source = <<<'NVS'<?nvsclass Greeter { public static function hello(): void { echo "hi\n"; }}NVS;
Outline::show(Core\Ast::parse($source), '');File on line 2 ClassDecl on line 2 Method on line 3 Echo on line 4 Str on line 4