Skip to content

Commit 7d93ab4

Browse files
ondrejmirtesclaude
andcommitted
Apply the native NodeTraverser's splices with array_splice() semantics
php-parser applies the recorded removals and replacement arrays as array_splice($nodes, $i, 1, $replace), last first, with the element's key $i as the offset. On a list that is the element's position, which is all the native rebuild handled: for other keys the offset is clamped (keys past the end remove nothing, a negative key counts from the end), every splice renumbers the integer keys and keeps the string keys, and a string key is array_splice()'s TypeError. The native traverser spliced by position and dropped the keys. Record the key next to the position and, when the array is not a list, replay the splices one by one with array_splice()'s clamping and renumbering; a list keeps the single rebuild pass. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018Fdg8n3eEi4ZoXa4dA2k4A
1 parent a027214 commit 7d93ab4

2 files changed

Lines changed: 121 additions & 8 deletions

File tree

‎turbo-ext/src/NodeTraverser.cpp‎

Lines changed: 74 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,12 @@ typedef struct {
4747
const pt_native_visitor *native;
4848
} pt_visitor_plan;
4949

50-
/* The splices recorded by one traverseArray() pass ($doNodes in the twin). */
50+
/* The splices recorded by one traverseArray() pass ($doNodes in the twin):
51+
* the element's position, and its key — what array_splice() is handed */
5152
typedef struct {
5253
zend_ulong pos;
54+
zend_string *key; /* owned, NULL for an integer key */
55+
zend_ulong index;
5356
zval replacement; /* IS_ARRAY (owned) or IS_FALSE for remove */
5457
} pt_do_node;
5558

@@ -59,13 +62,15 @@ typedef struct {
5962
uint32_t capacity;
6063
} pt_do_nodes;
6164

62-
static void pt_do_nodes_push(pt_do_nodes *dn, zend_ulong pos, zval *replacement)
65+
static void pt_do_nodes_push(pt_do_nodes *dn, zend_ulong pos, zend_string *key, zend_ulong index, zval *replacement)
6366
{
6467
if (dn->count == dn->capacity) {
6568
dn->capacity = dn->capacity == 0 ? 4 : dn->capacity * 2;
6669
dn->items = (pt_do_node *) erealloc(dn->items, dn->capacity * sizeof(pt_do_node));
6770
}
6871
dn->items[dn->count].pos = pos;
72+
dn->items[dn->count].key = key != NULL ? zend_string_copy(key) : NULL;
73+
dn->items[dn->count].index = index;
6974
if (replacement != NULL) {
7075
ZVAL_COPY(&dn->items[dn->count].replacement, replacement);
7176
} else {
@@ -78,6 +83,9 @@ static void pt_do_nodes_free(pt_do_nodes *dn)
7883
{
7984
uint32_t i;
8085
for (i = 0; i < dn->count; i++) {
86+
if (dn->items[i].key != NULL) {
87+
zend_string_release(dn->items[i].key);
88+
}
8189
zval_ptr_dtor(&dn->items[i].replacement);
8290
}
8391
if (dn->items != NULL) {
@@ -588,14 +596,14 @@ class NodeTraverser
588596
continue;
589597
}
590598
if (retRef.isArray()) {
591-
pt_do_nodes_push(&doNodes, i, retRef.raw());
599+
pt_do_nodes_push(&doNodes, i, key, index, retRef.raw());
592600
skipToNext = true;
593601
break;
594602
}
595603
if (retRef.isLong()) {
596604
zend_long code = retRef.asLong();
597605
if (code == REMOVE_NODE) {
598-
pt_do_nodes_push(&doNodes, i, NULL);
606+
pt_do_nodes_push(&doNodes, i, key, index, NULL);
599607
skipToNext = true;
600608
break;
601609
}
@@ -660,13 +668,13 @@ class NodeTraverser
660668
continue;
661669
}
662670
if (retRef.isArray()) {
663-
pt_do_nodes_push(&doNodes, i, retRef.raw());
671+
pt_do_nodes_push(&doNodes, i, key, index, retRef.raw());
664672
break;
665673
}
666674
if (retRef.isLong()) {
667675
zend_long code = retRef.asLong();
668676
if (code == REMOVE_NODE) {
669-
pt_do_nodes_push(&doNodes, i, NULL);
677+
pt_do_nodes_push(&doNodes, i, key, index, NULL);
670678
break;
671679
}
672680
if (code == STOP_TRAVERSAL) {
@@ -693,8 +701,23 @@ class NodeTraverser
693701
}
694702

695703
zv::Val result = working.isUndef() ? std::move(original) : std::move(working);
696-
if (doNodes.count > 0) {
697-
/* apply the recorded splices in one rebuild pass */
704+
if (doNodes.count > 0 && !zend_array_is_list(Z_ARRVAL_P(result.raw()))) {
705+
/* while (list($i, $replace) = array_pop($doNodes))
706+
* array_splice($nodes, $i, 1, $replace); */
707+
for (uint32_t k = doNodes.count; k-- > 0; ) {
708+
pt_do_node &splice = doNodes.items[k];
709+
if (splice.key != NULL) {
710+
zend_type_error("array_splice(): Argument #2 ($offset) must be of type int, string given");
711+
failed = true;
712+
pt_do_nodes_free(&doNodes);
713+
return zv::Val();
714+
}
715+
zval *replacement = &splice.replacement;
716+
result = arraySplice(Z_ARRVAL_P(result.raw()), (zend_long) splice.index, Z_TYPE_P(replacement) == IS_ARRAY ? Z_ARRVAL_P(replacement) : NULL);
717+
}
718+
} else if (doNodes.count > 0) {
719+
/* on a list every key is its position and each splice leaves
720+
* the positions below it alone: one rebuild pass does them all */
698721
zv::ArrRef nodes(result.raw());
699722
zv::Arr rebuilt = zv::Arr::create(nodes.size());
700723
uint32_t cursor = 0;
@@ -721,6 +744,49 @@ class NodeTraverser
721744
return result;
722745
}
723746

747+
/* array_splice($nodes, $offset, 1, $replacement) into a new array: the
748+
* offset clamped like array_splice() does, the integer keys renumbered,
749+
* the string keys kept; NULL replacement = [] */
750+
static zv::Val arraySplice(HashTable *nodes, zend_long offset, HashTable *replacement)
751+
{
752+
zend_long count = (zend_long) zend_hash_num_elements(nodes);
753+
if (offset > count) {
754+
offset = count;
755+
} else if (offset < 0) {
756+
offset = count + offset < 0 ? 0 : count + offset;
757+
}
758+
zend_long length = offset + 1 > count ? count - offset : 1;
759+
760+
zv::Arr spliced = zv::Arr::create((uint32_t) (count - length + (replacement != NULL ? zend_hash_num_elements(replacement) : 0)));
761+
zv::ArrRef out(spliced.raw());
762+
auto insertReplacement = [&]() {
763+
if (replacement == NULL) return;
764+
for (auto entry : zv::TableRef(replacement)) {
765+
out.push(entry.value());
766+
}
767+
};
768+
zend_long position = 0;
769+
for (auto entry : zv::TableRef(nodes)) {
770+
if (position == offset) {
771+
insertReplacement();
772+
}
773+
if (position < offset || position >= offset + length) {
774+
zend_string *key = entry.stringKeyOrNull();
775+
if (key != NULL) {
776+
Z_TRY_ADDREF_P(entry.value().raw());
777+
zend_hash_update(out.table(), key, entry.value().raw());
778+
} else {
779+
out.push(entry.value());
780+
}
781+
}
782+
position++;
783+
}
784+
if (offset == count) {
785+
insertReplacement();
786+
}
787+
return zv::Val(std::move(spliced));
788+
}
789+
724790
/* $old instanceof Stmt && $new instanceof Expr (and vice versa)
725791
* => LogicException; false means it threw */
726792
static bool ensureReplacementReasonable(zend_object *oldNode, zend_object *newNode)

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,3 +331,50 @@ public function enterNode(\PhpParser\Node $node)
331331
unset($ast, $traverser);
332332
}
333333
check($ntRetained['native'] <= max($ntRetained['php'], 0) + 1024, 'NodeTraverser: a no-op traversal retains no copies: ' . json_encode($ntRetained));
334+
335+
// the recorded splices are array_splice($nodes, $i, 1, $replace) calls, last
336+
// first: $i is the element's key used as an offset, clamped like
337+
// array_splice() clamps it, a string key is array_splice()'s TypeError, and
338+
// every splice renumbers the integer keys
339+
$ntSplicing = static fn (callable $decide) => new class ($decide) extends \PhpParser\NodeVisitorAbstract {
340+
341+
public function __construct(private $decide)
342+
{
343+
}
344+
345+
public function leaveNode(\PhpParser\Node $node)
346+
{
347+
return $node instanceof \PhpParser\Node\Stmt\Echo_ ? ($this->decide)($node->exprs[0]->value) : null;
348+
}
349+
350+
};
351+
$ntEchoes = static function (array $keyedValues): array {
352+
$nodes = [];
353+
foreach ($keyedValues as $key => $value) {
354+
$nodes[$key] = new \PhpParser\Node\Stmt\Echo_([new \PhpParser\Node\Scalar\Int_($value)]);
355+
}
356+
return $nodes;
357+
};
358+
$ntShape = static fn (array $nodes): array => array_map(static fn ($n) => $n instanceof \PhpParser\Node\Stmt\Echo_ ? $n->exprs[0]->value : $n->getType(), $nodes);
359+
$ntRemove = static fn (array $values) => static fn (int $value) => in_array($value, $values, true) ? \PhpParser\NodeVisitor::REMOVE_NODE : null;
360+
$ntSpliceCases = [
361+
'list' => [[1, 2, 3], $ntRemove([2])],
362+
'list, two removals' => [[1, 2, 3, 4], $ntRemove([2, 4])],
363+
'keys past the end' => [[5 => 1, 6 => 2, 7 => 3], $ntRemove([2])],
364+
'keys inside the range' => [[1 => 1, 2 => 2, 0 => 3], $ntRemove([1, 3])],
365+
'negative key' => [[0 => 1, -5 => 2, 1 => 3], $ntRemove([2])],
366+
'string key' => [[5 => 1, 'k' => 2, 7 => 3], $ntRemove([2, 3])],
367+
'string key, no splice' => [['a' => 1, 'b' => 2], $ntRemove([])],
368+
'replacement array at a large key' => [[3 => 1, 4 => 2], static fn (int $value) => $value === 1 ? [new \PhpParser\Node\Stmt\Nop(), new \PhpParser\Node\Stmt\Nop()] : null],
369+
'string keys kept around an int splice' => [['a' => 1, 0 => 2, 'b' => 3], $ntRemove([2])],
370+
];
371+
foreach ($ntSpliceCases as $ntLabel => [$ntKeyed, $ntDecide]) {
372+
$ntCompare("splices: $ntLabel (top level)", static function (string $side, string $traverserClass) use ($ntSplicing, $ntEchoes, $ntShape, $ntKeyed, $ntDecide): array {
373+
return $ntShape((new $traverserClass($ntSplicing($ntDecide)))->traverse($ntEchoes($ntKeyed)));
374+
});
375+
$ntCompare("splices: $ntLabel (subnode array)", static function (string $side, string $traverserClass) use ($ntSplicing, $ntEchoes, $ntShape, $ntKeyed, $ntDecide): array {
376+
$function = new \PhpParser\Node\Stmt\Function_('f', ['stmts' => $ntEchoes($ntKeyed)]);
377+
(new $traverserClass($ntSplicing($ntDecide)))->traverse([$function]);
378+
return $ntShape($function->stmts);
379+
});
380+
}

0 commit comments

Comments
 (0)