Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/Language/Visitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,9 @@ public static function visit(object $root, array $visitor, ?array $keyMap = null
];
$inList = $node instanceof NodeList;

$keys = ($inList ? $node : $visitorKeys[$node->kind]) ?? [];
// Nodes with a kind not present in $visitorKeys (e.g. a custom
// Node subclass) are treated as leaves, i.e. no children.
$keys = $inList ? $node : ($visitorKeys[$node->kind] ?? []);
$index = -1;
$edits = [];
if ($parent !== null) {
Expand Down
66 changes: 66 additions & 0 deletions tests/Language/VisitorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1905,4 +1905,70 @@ public function testThrowsExceptionWhenAddingIntegerToNodeList(): void
]
);
}

/**
* visit() must correctly invoke generic enter/leave visitors for a Node
* whose kind is not one of the built-in NodeKind constants (e.g. a
* custom Node subclass defined by a consumer).
*/
public function testVisitCallsGenericVisitorsForCustomKind(): void
{
$customNode = new class([]) extends Node {
public string $kind = 'CustomKind';
};

$visited = [];

Visitor::visit(
$customNode,
[
'enter' => static function (Node $node) use (&$visited): void {
$visited[] = ['enter', $node->kind];
},
'leave' => static function (Node $node) use (&$visited): void {
$visited[] = ['leave', $node->kind];
},
]
);
Comment on lines +1922 to +1932

self::assertSame(
[
['enter', 'CustomKind'],
['leave', 'CustomKind'],
],
$visited
);
}

/** Same as testVisitCallsGenericVisitorsForCustomKind, but for a visitor keyed specifically by the custom kind. */
public function testVisitCallsKindSpecificVisitorForCustomKind(): void
{
$customNode = new class([]) extends Node {
public string $kind = 'CustomKind';
};

$visited = [];

Visitor::visit(
$customNode,
[
'CustomKind' => [
'enter' => static function (Node $node) use (&$visited): void {
$visited[] = ['enter', $node->kind];
},
'leave' => static function (Node $node) use (&$visited): void {
$visited[] = ['leave', $node->kind];
},
],
]
);
Comment on lines +1952 to +1964

self::assertSame(
[
['enter', 'CustomKind'],
['leave', 'CustomKind'],
],
$visited
);
}
}
Loading