Skip to content

Commit a027214

Browse files
ondrejmirtesclaude
andcommitted
Traverse subnode arrays as a copy and assign the result back, like php-parser
The native NodeTraverser wrote replacement nodes straight into the property's table (shared with its own guard reference, never separated), and assigned the property only when splices were recorded. A visitor holding the parent's array saw it change mid-traversal, and a visitor reassigning the property kept its array where php-parser overwrites it with the traversal result. It also separated every subnode array up front, so each empty list - the shared [] - became a fresh heap table retained in cached ASTs (25 KB over NodeScopeResolver.php's AST). traverseArray() now holds its own reference to the array it iterates, writes replacements by key into a copy made on the first write, and returns the resulting array (the input's table when nothing changed); traverseNode() assigns it to the property through the engine write path unless the property already holds exactly that table. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018Fdg8n3eEi4ZoXa4dA2k4A
1 parent c5c78d8 commit a027214

2 files changed

Lines changed: 149 additions & 45 deletions

File tree

‎turbo-ext/src/NodeTraverser.cpp‎

Lines changed: 62 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -285,8 +285,8 @@ class NodeTraverser
285285

286286
if (UNEXPECTED(!buildVisitorPlan())) return zv::Val();
287287

288-
/* work on our own copy of the nodes array */
289-
zv::Arr nodes = zv::Arr::adoptTable(zend_array_dup(nodesTable));
288+
/* the by-value $nodes parameter */
289+
zv::Arr nodes = zv::Arr::copyOfTable(nodesTable);
290290

291291
/* beforeTraverse */
292292
for (uint32_t vi = 0; vi < nvisitors; vi++) {
@@ -300,16 +300,12 @@ class NodeTraverser
300300
if (UNEXPECTED(ret.isUndef())) return zv::Val();
301301
if (ret.ref().isArray()) {
302302
nodes = zv::Arr::adoptVal(std::move(ret));
303-
nodes.separate();
304303
}
305304
}
306305

307-
nodes.separate();
308-
zv::Arr replacement = traverseArray(nodes.arrRef());
306+
zv::Val traversed = traverseArray(nodes.ref());
309307
if (UNEXPECTED(failed)) return zv::Val();
310-
if (!replacement.isUndef()) {
311-
nodes = std::move(replacement);
312-
}
308+
nodes = zv::Arr::adoptVal(std::move(traversed));
313309

314310
/* afterTraverse, in reverse */
315311
for (int64_t vi = (int64_t) nvisitors - 1; vi >= 0; vi--) {
@@ -349,29 +345,20 @@ class NodeTraverser
349345
zv::Ref value = zv::Ref(OBJ_PROP(node, info->offsets[i])).deref();
350346

351347
if (value.isArray()) {
352-
/* separate so we can mutate in place */
353-
SEPARATE_ARRAY(value.raw());
354-
/* Hold a reference to the table for the whole traversal, the
355-
* way the PHP twin's `$subNode = $node->$name` local does.
356-
* traverseArray() walks the buckets in place while the visitor
357-
* hooks in between run arbitrary PHP, and that code can reach
358-
* this very property: PHPStan resolves a PHPDoc from inside
359-
* enterNode(), which re-enters the parser for the file being
360-
* traversed. With the array owned by the property alone,
361-
* assigning to the property - or dropping the node's last
362-
* reference - frees the table under the loop, and a write into
363-
* it reallocates the buckets the iterator holds; the traversal
364-
* then reads freed memory, which surfaces as "Invalid node
365-
* structure: Contains nested arrays" or a segfault. A reference
366-
* of our own keeps the table alive, and being shared it makes
367-
* any writer separate first, so the iteration always sees the
368-
* array it started with. */
369-
zv::Val arrayGuard = zv::Val::copyOf(zv::Ref(value.raw()));
370-
zv::Arr replacement;
371-
pt_engine_with_stack([&]() { replacement = traverseArray(zv::ArrRef(value.raw())); });
348+
/* $node->$name = $this->traverseArray($subNode): the traversal
349+
* works on its own reference to the table (the twin's
350+
* $subNode) and writes into a copy made on the first write, so
351+
* nothing - a visitor holding the parent's array, the property
352+
* itself mid-traversal - sees the table change under it, and
353+
* an untouched array (the shared [] included) is never copied */
354+
zv::Val result;
355+
pt_engine_with_stack([&]() { result = traverseArray(zv::Ref(value.raw())); });
372356
if (UNEXPECTED(failed)) return;
373-
if (!replacement.isUndef()) {
374-
value.assign(std::move(replacement));
357+
/* the assignment is skipped only when it would store the table
358+
* the property already holds; a visitor may have reassigned it */
359+
zv::Ref current = zv::Ref(OBJ_PROP(node, info->offsets[i])).deref();
360+
if (!current.isArray() || Z_ARRVAL_P(current.raw()) != Z_ARRVAL_P(result.raw())) {
361+
if (UNEXPECTED(!writeSubnode(node, info->names[i], result.ref()))) return;
375362
}
376363
if (stop) return;
377364
continue;
@@ -506,26 +493,54 @@ class NodeTraverser
506493
}
507494
}
508495

496+
/* $nodes[$i] = $node on the traversal's copy of the array, made on the
497+
* first write (the twin's local $nodes separating from its foreach) */
498+
static void writeElement(zv::Val &working, zv::Val &original, zend_string *key, zend_ulong index, zv::Ref value)
499+
{
500+
if (working.isUndef()) {
501+
zval copy;
502+
ZVAL_ARR(&copy, zend_array_dup(Z_ARRVAL_P(original.raw())));
503+
working = zv::Val::adopt(copy);
504+
}
505+
HashTable *table = Z_ARRVAL_P(working.raw());
506+
zval *slot = key != NULL ? zend_hash_find(table, key) : zend_hash_index_find(table, index);
507+
if (slot != NULL && Z_ISREF_P(slot)) {
508+
zv::Ref(Z_REFVAL_P(slot)).assign(zv::Val::copyOf(value));
509+
return;
510+
}
511+
Z_TRY_ADDREF_P(value.raw());
512+
if (key != NULL) {
513+
zend_hash_update(table, key, value.raw());
514+
} else {
515+
zend_hash_index_update(table, index, value.raw());
516+
}
517+
}
518+
509519
/*
510-
* Mirrors traverseArray(): traverses the table behind `nodes` in place
511-
* (the caller passes a separated, exclusively-owned array) and returns
512-
* the rebuilt array when splices (REMOVE_NODE / replacement arrays) were
513-
* recorded, an UNDEF Arr otherwise.
520+
* Mirrors traverseArray(): iterates the array it is handed (holding its
521+
* own reference, like the twin's by-value parameter and foreach), writes
522+
* replacements into a copy made on the first one, applies the recorded
523+
* splices (REMOVE_NODE / replacement arrays) and returns the resulting
524+
* array — the input's own table when nothing changed. UNDEF means a
525+
* pending exception.
514526
*/
515-
zv::Arr traverseArray(zv::ArrRef nodes)
527+
zv::Val traverseArray(zv::Ref nodesZv)
516528
{
529+
zv::Val original = zv::Val::copyOf(nodesZv);
530+
zv::Val working;
517531
pt_do_nodes doNodes = {};
518532
zend_class_entry *nodeIface = pt_class(PT_CLASS_NODE);
519533
if (UNEXPECTED(nodeIface == NULL)) {
520534
failed = true;
521-
return zv::Arr();
535+
return zv::Val();
522536
}
523537

524538
zend_ulong pos = 0;
525-
for (auto nodesEntry : nodes) {
539+
for (auto nodesEntry : zv::ArrRef(original.raw())) {
526540
zend_ulong i = pos++;
527-
zv::Ref slot = nodesEntry.value();
528-
zv::Ref value = slot.deref();
541+
zend_string *key = nodesEntry.stringKeyOrNull();
542+
zend_ulong index = nodesEntry.indexKey();
543+
zv::Ref value = nodesEntry.value().deref();
529544

530545
if (!value.instanceOf(nodeIface)) {
531546
if (UNEXPECTED(value.isArray())) {
@@ -568,8 +583,8 @@ class NodeTraverser
568583
break;
569584
}
570585
/* $nodes[$i] = $node = $return */
586+
writeElement(working, original, key, index, retRef);
571587
node = retRef.asObject();
572-
slot.assign(std::move(ret));
573588
continue;
574589
}
575590
if (retRef.isArray()) {
@@ -640,8 +655,8 @@ class NodeTraverser
640655
failed = true;
641656
break;
642657
}
658+
writeElement(working, original, key, index, retRef);
643659
node = retRef.asObject();
644-
slot.assign(std::move(ret));
645660
continue;
646661
}
647662
if (retRef.isArray()) {
@@ -674,13 +689,14 @@ class NodeTraverser
674689

675690
if (UNEXPECTED(failed)) {
676691
pt_do_nodes_free(&doNodes);
677-
return zv::Arr();
692+
return zv::Val();
678693
}
679694

680-
zv::Arr rebuilt;
695+
zv::Val result = working.isUndef() ? std::move(original) : std::move(working);
681696
if (doNodes.count > 0) {
682697
/* apply the recorded splices in one rebuild pass */
683-
rebuilt = zv::Arr::create(nodes.size());
698+
zv::ArrRef nodes(result.raw());
699+
zv::Arr rebuilt = zv::Arr::create(nodes.size());
684700
uint32_t cursor = 0;
685701
zend_ulong rebuildPos = 0;
686702
for (auto nodesEntry : nodes) {
@@ -698,10 +714,11 @@ class NodeTraverser
698714
}
699715
rebuildPos++;
700716
}
717+
result = zv::Val(std::move(rebuilt));
701718
}
702719

703720
pt_do_nodes_free(&doNodes);
704-
return rebuilt;
721+
return result;
705722
}
706723

707724
/* $old instanceof Stmt && $new instanceof Expr (and vice versa)

‎turbo-ext/tests/parser-visitors.php‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,3 +244,90 @@ final class NtProbing_%1$s extends \\%2$s { public function stop(): bool { retur
244244
$traverser->addVisitor(new \PhpParser\NodeVisitor\NodeConnectingVisitor());
245245
return $traverser->traverse([new \PhpParser\Node\Stmt\Nop()]);
246246
});
247+
248+
// a subnode array is traversed as a copy and assigned back once, after the
249+
// loop: a visitor holding the parent's array keeps seeing the original, the
250+
// parent's property keeps the original until the loop ends, and a visitor
251+
// reassigning the property is overwritten by the traversal result
252+
$ntMarks = static fn (array $nodes): string => implode(',', array_map(static fn ($n) => $n instanceof \PhpParser\Node ? ($n->getAttribute('r') === true ? 'R' : 'o') : gettype($n), $nodes));
253+
$ntReplacingVisitor = static fn (callable $onEcho) => new class ($onEcho) extends \PhpParser\NodeVisitorAbstract {
254+
255+
public ?\PhpParser\Node\Stmt\Function_ $function = null;
256+
257+
/** @var list<string> */
258+
public array $log = [];
259+
260+
public mixed $held = null;
261+
262+
public function __construct(private $onEcho)
263+
{
264+
}
265+
266+
public function enterNode(\PhpParser\Node $node)
267+
{
268+
if ($node instanceof \PhpParser\Node\Stmt\Function_) {
269+
$this->function = $node;
270+
$this->held = $node->stmts;
271+
return null;
272+
}
273+
if ($node instanceof \PhpParser\Node\Stmt\Echo_) {
274+
return ($this->onEcho)($this, $node);
275+
}
276+
return null;
277+
}
278+
279+
};
280+
$ntCompare('replacements in a subnode array a visitor holds', static function (string $side, string $traverserClass) use ($smokeParser, $ntMarks, $ntReplacingVisitor): array {
281+
$visitor = $ntReplacingVisitor(static function ($visitor, $node) use ($ntMarks) {
282+
$visitor->log[] = $ntMarks($visitor->function->stmts) . ' held=' . $ntMarks($visitor->held);
283+
$replacement = clone $node;
284+
$replacement->setAttribute('r', true);
285+
return $replacement;
286+
});
287+
$ast = (new $traverserClass($visitor))->traverse($smokeParser->parse('<?php function f() { echo 1; echo 2; echo 3; }'));
288+
return [$visitor->log, $ntMarks($ast[0]->stmts), $ntMarks($visitor->held)];
289+
});
290+
$ntCompare('a visitor reassigning the subnode array', static function (string $side, string $traverserClass) use ($smokeParser, $ntMarks, $ntReplacingVisitor): array {
291+
$visitor = $ntReplacingVisitor(static function ($visitor, $node) {
292+
$visitor->function->stmts = [new \PhpParser\Node\Stmt\Nop()];
293+
return null;
294+
});
295+
$ast = (new $traverserClass($visitor))->traverse($smokeParser->parse('<?php function f() { echo 1; echo 2; }'));
296+
return array_map(static fn ($n) => $n->getType(), $ast[0]->stmts);
297+
});
298+
$ntCompare('a visitor reassigning the subnode array next to a replacement', static function (string $side, string $traverserClass) use ($smokeParser, $ntMarks, $ntReplacingVisitor): array {
299+
$visitor = $ntReplacingVisitor(static function ($visitor, $node) {
300+
if ($node->exprs[0]->value === 1) {
301+
$visitor->function->stmts = [new \PhpParser\Node\Stmt\Nop()];
302+
return null;
303+
}
304+
$replacement = clone $node;
305+
$replacement->setAttribute('r', true);
306+
return $replacement;
307+
});
308+
$ast = (new $traverserClass($visitor))->traverse($smokeParser->parse('<?php function f() { echo 1; echo 2; }'));
309+
return [array_map(static fn ($n) => $n->getType(), $ast[0]->stmts), $ntMarks($ast[0]->stmts)];
310+
});
311+
312+
// an untouched subnode array is not copied: the shared [] of the parser's
313+
// empty lists stays shared, so traversing a cached AST allocates nothing
314+
$ntRetained = [];
315+
foreach ($ntSides as $side => $traverserClass) {
316+
$ast = $smokeParser->parse(file_get_contents(dirname(__DIR__, 2) . '/src/Analyser/NodeScopeResolver.php'));
317+
$traverser = new $traverserClass(new class extends \PhpParser\NodeVisitorAbstract {
318+
319+
public function enterNode(\PhpParser\Node $node)
320+
{
321+
return null;
322+
}
323+
324+
});
325+
$traverser->traverse([new \PhpParser\Node\Stmt\Nop()]);
326+
gc_collect_cycles();
327+
$before = memory_get_usage();
328+
$ast = $traverser->traverse($ast);
329+
gc_collect_cycles();
330+
$ntRetained[$side] = memory_get_usage() - $before;
331+
unset($ast, $traverser);
332+
}
333+
check($ntRetained['native'] <= max($ntRetained['php'], 0) + 1024, 'NodeTraverser: a no-op traversal retains no copies: ' . json_encode($ntRetained));

0 commit comments

Comments
 (0)