Skip to content
Merged
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
11 changes: 10 additions & 1 deletion src/Generator/CallArgumentGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,16 @@ protected function parseNativeCallArgs(
}
}

$variadicVar ??= $this->addTmpVar(Type::ARRAY);
if ($variadicVar === null) {
// Keep the aggregation array in the function preamble
// (addTmpVar) so a forward goto can never jump across a
// call-site C++ local declaration, and reset it instead.
// The reset runs on every evaluation of the call site, so a
// call inside a loop aggregates into an empty array every
// iteration instead of accumulating arguments.
$variadicVar = $this->addTmpVar(Type::ARRAY);
$this->context->beforeStmtLines[] = $variadicVar . '.unset();';
}
if ($arg->unpack) {
$method = $argInfo->byRef ? 'mergeReferences' : 'merge';
$this->context->beforeStmtLines[] = $variadicVar . '.' . $method
Expand Down
47 changes: 47 additions & 0 deletions tests/compiler/variadic/loop-accumulation.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
--TEST--
Variadic arguments reset on every loop iteration instead of accumulating
--FILE--
<?php
class Leaf {}
class Box {
/** @var array<int, Leaf> */
public array $k = [];
public function add(...$els): void {
foreach ($els as $e) { $this->k[] = $e; }
}
public function cnt(): int { return count($this->k); }
}

function main()
{
$b = new Box();

// Positional variadic inside a for loop: 3 iterations x 2 args = 6.
for ($i = 0; $i < 3; $i++) {
$b->add(new Leaf(), new Leaf());
}

// Positional variadic inside a while loop: 2 iterations x 1 arg = 2.
$i = 0;
while ($i < 2) {
$b->add(new Leaf());
$i++;
}

// Unpacked variadic inside a for loop: 2 iterations x 2 args = 4.
$arr = [new Leaf(), new Leaf()];
for ($i = 0; $i < 2; $i++) {
$b->add(...$arr);
}

// Mixed positional + unpacked variadic enters the aggregation path
// (the single-unpack fast path does not): 2 iterations x 3 args = 6.
for ($i = 0; $i < 2; $i++) {
$b->add(new Leaf(), ...$arr);
}

var_dump($b->cnt());
}
?>
--EXPECT--
int(18)
19 changes: 19 additions & 0 deletions tests/compiler/variadic/variadic-goto-skip.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
--TEST--
A forward goto may skip a by-value variadic call without crossing an initialization
--FILE--
<?php
function count_values(...$values): int {
return count($values);
}

function main(): void {
if (time() > 0) {
goto finished;
}
count_values(1, 2);
finished:
echo "done\n";
}
?>
--EXPECT--
done
Loading