packages/deriver/tests/Unit/Deriver/Lowerer/StatementLoweringTest.php
1<?php
2
3declare (strict_types=1);
4
5namespace Tests\Unit\Deriver\Lowerer;
6
7use Deriver\Deriver;
8use Deriver\Deriver\Candidate\ResultRef;
9use Deriver\Deriver\Candidate\Snapshot;
10use Deriver\Deriver\Candidate\Statistics;
11use Deriver\Deriver\Contributions;
12use Deriver\Deriver\DeriverConfig;
13use Deriver\Deriver\Evaluator\Call\Evaluators;
14use Deriver\Deriver\Evaluator\Call\Extensions;
15use Deriver\Deriver\Evaluator\Call\Registrations;
16use Deriver\Deriver\Evaluator\Call\StateRegistry;
17use Deriver\Deriver\Evaluator\EvaluatorConfig;
18use Deriver\Deriver\Evaluator\Evidence\Frontier;
19use Deriver\Deriver\Evaluator\Execution\Call\Allocation;
20use Deriver\Deriver\Evaluator\Execution\Call\ArgumentBinding;
21use Deriver\Deriver\Evaluator\Execution\Call\ArgumentOrder;
22use Deriver\Deriver\Evaluator\Execution\Call\CallExecutor;
23use Deriver\Deriver\Evaluator\Execution\Call\Creation\Access;
24use Deriver\Deriver\Evaluator\Execution\Call\Member\Invocation;
25use Deriver\Deriver\Evaluator\Execution\Call\Native\Invocation as NativeInvocation;
26use Deriver\Deriver\Evaluator\Execution\Call\Native\Properties;
27use Deriver\Deriver\Evaluator\Execution\Call\Native\Signatures;
28use Deriver\Deriver\Evaluator\Execution\Call\ParameterBinding;
29use Deriver\Deriver\Evaluator\Execution\Call\PassedArgument;
30use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Creation;
31use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Resolution;
32use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Target;
33use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Transfer;
34use Deriver\Deriver\Evaluator\Execution\Call\TypeBinding;
35use Deriver\Deriver\Evaluator\Execution\Call\TypeCheck;
36use Deriver\Deriver\Evaluator\Execution\Completion\Alternative;
37use Deriver\Deriver\Evaluator\Execution\Completion\Assessment;
38use Deriver\Deriver\Evaluator\Execution\Completion\Completion;
39use Deriver\Deriver\Evaluator\Execution\Completion\StorageSnapshot;
40use Deriver\Deriver\Evaluator\Execution\Context;
41use Deriver\Deriver\Evaluator\Execution\Control\ExceptionChain;
42use Deriver\Deriver\Evaluator\Execution\Control\ExceptionMatch;
43use Deriver\Deriver\Evaluator\Execution\Control\Handler;
44use Deriver\Deriver\Evaluator\Execution\Control\ObservationLimit;
45use Deriver\Deriver\Evaluator\Execution\Control\StateJoin;
46use Deriver\Deriver\Evaluator\Execution\Control\Unwinding;
47use Deriver\Deriver\Evaluator\Execution\Demand\Cell;
48use Deriver\Deriver\Evaluator\Execution\Demand\Components;
49use Deriver\Deriver\Evaluator\Execution\Demand\Discovery;
50use Deriver\Deriver\Evaluator\Execution\Demand\Key;
51use Deriver\Deriver\Evaluator\Execution\Demand\Table;
52use Deriver\Deriver\Evaluator\Execution\Dependencies;
53use Deriver\Deriver\Evaluator\Execution\Evaluator;
54use Deriver\Deriver\Evaluator\Execution\EvaluatorConfig as ExecutionEvaluatorConfig;
55use Deriver\Deriver\Evaluator\Execution\InstructionTransfer;
56use Deriver\Deriver\Evaluator\Execution\Memory\Location;
57use Deriver\Deriver\Evaluator\Execution\Memory\Materialization;
58use Deriver\Deriver\Evaluator\Execution\Memory\Memory;
59use Deriver\Deriver\Evaluator\Execution\Memory\ReferenceConstraint;
60use Deriver\Deriver\Evaluator\Execution\Memory\Slots\SlotReference;
61use Deriver\Deriver\Evaluator\Execution\Memory\Slots\StateStorage;
62use Deriver\Deriver\Evaluator\Execution\Memory\StorageCapture;
63use Deriver\Deriver\Evaluator\Execution\ObservationCollector;
64use Deriver\Deriver\Evaluator\Execution\Operation\Conversions;
65use Deriver\Deriver\Evaluator\Execution\Operation\ScalarErrors;
66use Deriver\Deriver\Evaluator\Execution\State;
67use Deriver\Deriver\Evaluator\Execution\Summary\CompletionRecord;
68use Deriver\Deriver\Evaluator\Execution\Summary\Evaluation;
69use Deriver\Deriver\Evaluator\Execution\Summary\Invocation as SummaryInvocation;
70use Deriver\Deriver\Evaluator\Execution\Summary\Isolation;
71use Deriver\Deriver\Evaluator\Execution\Trace\Derivation;
72use Deriver\Deriver\Evaluator\Execution\Transfer\MemoryStep;
73use Deriver\Deriver\Evaluator\Execution\Transfer\PureStep;
74use Deriver\Deriver\Evaluator\Execution\Transfer\ReferenceAssignment;
75use Deriver\Deriver\Evaluator\Request\Budget;
76use Deriver\Deriver\Evaluator\Request\EntryPoint;
77use Deriver\Deriver\Evaluator\Request\QueryScope;
78use Deriver\Deriver\Evaluator\Request\ReturnQuery;
79use Deriver\Deriver\Evaluator\Scalar\Arrays;
80use Deriver\Deriver\Evaluator\Scalar\Identity;
81use Deriver\Deriver\Evaluator\Scalar\Operations;
82use Deriver\Deriver\Evaluator\TargetProfile;
83use Deriver\Deriver\Evaluator\Term;
84use Deriver\Deriver\Execution\DerivationResult;
85use Deriver\Deriver\Execution\QueryExecution;
86use Deriver\Deriver\Execution\ResultAssessment;
87use Deriver\Deriver\Identity\QueryEncoding;
88use Deriver\Deriver\Identity\ValueGraph;
89use Deriver\Deriver\Lowerer\AssignmentLowering;
90use Deriver\Deriver\Lowerer\CallLowering;
91use Deriver\Deriver\Lowerer\Control\DestructuringLowering;
92use Deriver\Deriver\Lowerer\Control\ExceptionLowering;
93use Deriver\Deriver\Lowerer\Control\GotoLowering;
94use Deriver\Deriver\Lowerer\Control\StaticLowering;
95use Deriver\Deriver\Lowerer\Declaration\CallableIdentity;
96use Deriver\Deriver\Lowerer\Declaration\CallableSource;
97use Deriver\Deriver\Lowerer\Declaration\Index;
98use Deriver\Deriver\Lowerer\Declaration\Indexer;
99use Deriver\Deriver\Lowerer\Declaration\Metadata\PropertyDeclaration;
100use Deriver\Deriver\Lowerer\Declaration\Traits\Composition;
101use Deriver\Deriver\Lowerer\ExpressionLowering;
102use Deriver\Deriver\Lowerer\Graph\BasicBlock;
103use Deriver\Deriver\Lowerer\Graph\CallableGraph;
104use Deriver\Deriver\Lowerer\Graph\CatchTarget;
105use Deriver\Deriver\Lowerer\Graph\ExceptionRegion;
106use Deriver\Deriver\Lowerer\Graph\Instruction;
107use Deriver\Deriver\Lowerer\Graph\Literal;
108use Deriver\Deriver\Lowerer\Graph\Parameter;
109use Deriver\Deriver\Lowerer\Graph\Terminator;
110use Deriver\Deriver\Lowerer\Graph\TerminatorKind;
111use Deriver\Deriver\Lowerer\Hierarchy\Builtins;
112use Deriver\Deriver\Lowerer\Hierarchy\Dispatch;
113use Deriver\Deriver\Lowerer\InstructionEmitter;
114use Deriver\Deriver\Lowerer\Lowerer;
115use Deriver\Deriver\Lowerer\LoweringScope;
116use Deriver\Deriver\Lowerer\StatementLowering;
117use Deriver\Deriver\MicroEvaluatorConversion;
118use Deriver\Deriver\Parser\Node\File;
119use Deriver\Deriver\Parser\Parser;
120use Deriver\Deriver\Parser\ParserConfig;
121use Deriver\Deriver\Parser\TargetSyntax;
122use Deriver\Deriver\Providers\ProviderExpansion;
123use Deriver\Deriver\Resolver\AssignmentPatterns;
124use Deriver\Deriver\Resolver\ClassScope;
125use Deriver\Deriver\Resolver\ExpressionValidation;
126use Deriver\Deriver\Resolver\MagicContext;
127use Deriver\Deriver\Resolver\Resolver;
128use Deriver\Deriver\Selection\QueryValidation;
129use Deriver\Deriver\SnapshotIdentity;
130use Deriver\Deriver\Sources\LineMap;
131use Deriver\Deriver\Sources\Path;
132use Deriver\Deriver\Sources\Source;
133use Deriver\Deriver\Sources\SourceRef;
134use Deriver\Deriver\Sources\Sources;
135use Deriver\Exception\ParserException;
136use Deriver\Exception\ResolutionException;
137use PhpParser\Node\Const_ as NodeConst_;
138use PhpParser\Node\DeclareItem;
139use PhpParser\Node\Expr\Variable;
140use PhpParser\Node\Name;
141use PhpParser\Node\Scalar\Int_;
142use PhpParser\Node\StaticVar;
143use PhpParser\Node\Stmt;
144use PhpParser\Node\Stmt\Class_;
145use PhpParser\Node\Stmt\Const_;
146use PhpParser\Node\Stmt\Declare_;
147use PhpParser\Node\Stmt\Else_;
148use PhpParser\Node\Stmt\ElseIf_;
149use PhpParser\Node\Stmt\Expression;
150use PhpParser\Node\Stmt\Function_;
151use PhpParser\Node\Stmt\Global_;
152use PhpParser\Node\Stmt\Goto_;
153use PhpParser\Node\Stmt\GroupUse;
154use PhpParser\Node\Stmt\If_;
155use PhpParser\Node\Stmt\InlineHTML;
156use PhpParser\Node\Stmt\Interface_;
157use PhpParser\Node\Stmt\Label;
158use PhpParser\Node\Stmt\Namespace_;
159use PhpParser\Node\Stmt\Nop;
160use PhpParser\Node\Stmt\Return_;
161use PhpParser\Node\Stmt\Static_;
162use PhpParser\Node\Stmt\Trait_;
163use PhpParser\Node\Stmt\Unset_;
164use PhpParser\Node\Stmt\Use_;
165use PhpParser\Node\UseItem;
166use PHPUnit\Framework\Attributes\CoversClass;
167use PHPUnit\Framework\Attributes\DataProvider;
168use PHPUnit\Framework\Attributes\Small;
169use PHPUnit\Framework\Attributes\UsesClass;
170use PHPUnit\Framework\TestCase;
171
172#[UsesClass(Resolver::class)]
173#[UsesClass(ExpressionValidation::class)]
174#[UsesClass(ResolutionException::class)]
175#[UsesClass(ParserConfig::class)]
176#[UsesClass(ParserException::class)]
177#[CoversClass(StatementLowering::class)]
178#[UsesClass(GotoLowering::class)]
179#[UsesClass(QueryExecution::class)]
180#[UsesClass(QueryValidation::class)]
181#[UsesClass(ResultAssessment::class)]
182#[UsesClass(Deriver::class)]
183#[UsesClass(BasicBlock::class)]
184#[UsesClass(CallableGraph::class)]
185#[UsesClass(CallableIdentity::class)]
186#[UsesClass(CatchTarget::class)]
187#[UsesClass(ExceptionRegion::class)]
188#[UsesClass(Instruction::class)]
189#[UsesClass(Parameter::class)]
190#[UsesClass(PropertyDeclaration::class)]
191#[UsesClass(Terminator::class)]
192#[UsesClass(Allocation::class)]
193#[UsesClass(ArgumentBinding::class)]
194#[UsesClass(ArgumentOrder::class)]
195#[UsesClass(CallExecutor::class)]
196#[UsesClass(Access::class)]
197#[UsesClass(Builtins::class)]
198#[UsesClass(Dispatch::class)]
199#[UsesClass(Invocation::class)]
200#[UsesClass(NativeInvocation::class)]
201#[UsesClass(Properties::class)]
202#[UsesClass(Signatures::class)]
203#[UsesClass(ParameterBinding::class)]
204#[UsesClass(PassedArgument::class)]
205#[UsesClass(Creation::class)]
206#[UsesClass(Resolution::class)]
207#[UsesClass(Target::class)]
208#[UsesClass(Transfer::class)]
209#[UsesClass(TypeBinding::class)]
210#[UsesClass(TypeCheck::class)]
211#[UsesClass(Completion::class)]
212#[UsesClass(Context::class)]
213#[UsesClass(ExceptionChain::class)]
214#[UsesClass(ExceptionMatch::class)]
215#[UsesClass(Handler::class)]
216#[UsesClass(ObservationLimit::class)]
217#[UsesClass(StateJoin::class)]
218#[UsesClass(Unwinding::class)]
219#[UsesClass(Cell::class)]
220#[UsesClass(Components::class)]
221#[UsesClass(Discovery::class)]
222#[UsesClass(Key::class)]
223#[UsesClass(Table::class)]
224#[UsesClass(Dependencies::class)]
225#[UsesClass(InstructionTransfer::class)]
226#[UsesClass(Evaluator::class)]
227#[UsesClass(SlotReference::class)]
228#[UsesClass(StateStorage::class)]
229#[UsesClass(ObservationCollector::class)]
230#[UsesClass(Conversions::class)]
231#[UsesClass(ScalarErrors::class)]
232#[UsesClass(State::class)]
233#[UsesClass(CompletionRecord::class)]
234#[UsesClass(Evaluation::class)]
235#[UsesClass(SummaryInvocation::class)]
236#[UsesClass(Isolation::class)]
237#[UsesClass(MemoryStep::class)]
238#[UsesClass(PureStep::class)]
239#[UsesClass(ReferenceAssignment::class)]
240#[UsesClass(Location::class)]
241#[UsesClass(Materialization::class)]
242#[UsesClass(Memory::class)]
243#[UsesClass(ReferenceConstraint::class)]
244#[UsesClass(StorageCapture::class)]
245#[UsesClass(Extensions::class)]
246#[UsesClass(ProviderExpansion::class)]
247#[UsesClass(Evaluators::class)]
248#[UsesClass(StateRegistry::class)]
249#[UsesClass(DeriverConfig::class)]
250#[UsesClass(EntryPoint::class)]
251#[UsesClass(Sources::class)]
252#[UsesClass(Path::class)]
253#[UsesClass(Snapshot::class)]
254#[UsesClass(Source::class)]
255#[UsesClass(TargetProfile::class)]
256#[UsesClass(Budget::class)]
257#[UsesClass(QueryScope::class)]
258#[UsesClass(ReturnQuery::class)]
259#[UsesClass(ResultRef::class)]
260#[UsesClass(SourceRef::class)]
261#[UsesClass(Alternative::class)]
262#[UsesClass(Assessment::class)]
263#[UsesClass(Derivation::class)]
264#[UsesClass(DerivationResult::class)]
265#[UsesClass(QueryEncoding::class)]
266#[UsesClass(ValueGraph::class)]
267#[UsesClass(Statistics::class)]
268#[UsesClass(StorageSnapshot::class)]
269#[UsesClass(Parser::class)]
270#[UsesClass(File::class)]
271#[UsesClass(AssignmentLowering::class)]
272#[UsesClass(CallLowering::class)]
273#[UsesClass(Lowerer::class)]
274#[UsesClass(DestructuringLowering::class)]
275#[UsesClass(ExceptionLowering::class)]
276#[UsesClass(StaticLowering::class)]
277#[UsesClass(ExpressionLowering::class)]
278#[UsesClass(InstructionEmitter::class)]
279#[UsesClass(LoweringScope::class)]
280#[UsesClass(CallableSource::class)]
281#[UsesClass(Indexer::class)]
282#[UsesClass(Index::class)]
283#[UsesClass(Composition::class)]
284#[UsesClass(LineMap::class)]
285#[UsesClass(MagicContext::class)]
286#[UsesClass(AssignmentPatterns::class)]
287#[UsesClass(ClassScope::class)]
288#[UsesClass(TargetSyntax::class)]
289#[UsesClass(Arrays::class)]
290#[UsesClass(Identity::class)]
291#[UsesClass(Operations::class)]
292#[UsesClass(Literal::class)]
293#[Small]
294final class StatementLoweringTest extends TestCase
295{
296 public function testLowerPreservesTheSemanticContract(): void
297 {
298 $source = '<?php function target(){$x="before";try{$x="after";throw new RuntimeException();$x="wrong";}catch(RuntimeException $e){return $x;}}';
299 $symbol = 'target';
300 $input = new Sources([new Source('fixture.php', $source)]);
301 $configuration = new DeriverConfig();
302 $contributions = new Contributions();
303 $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
304 $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
305 $contributions1 = $providers->contributions;
306 $evaluators = new Evaluators(new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision), new Registrations($contributions1->evaluators, $contributions1->providers, $contributions1->domains, $contributions1->intrinsics, $contributions1->stateSlots), $configuration->standardEvaluators);
307 $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
308 $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
309 $snapshotId = $identity->id;
310 $input1 = $providers->input;
311 $parser = new Parser(new ParserConfig($target->version));
312 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input1, false));
313 $program = new Index($snapshotId, $trees);
314 $result = (new QueryExecution($program, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program->diagnostics()))))->derive(new ReturnQuery($symbol));
315 self::assertSame('after', $result->normalOutcomes[0]->values['return']->native());
316 self::assertSame([], $result->frontiers);
317 self::assertSame([], $result->exceptionalOutcomes);
318 }
319 public function testConditionalKeepsReturnsSeparateFromTheCommonContinuation(): void
320 {
321 $source = '<?php function target(){return 1;}';
322 $snapshotId = 'test';
323 $input = new Sources([new Source('fixture.php', $source)]);
324 $profile = new TargetProfile();
325 $parser = new Parser(new ParserConfig($profile->version));
326 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
327 $index = new Index($snapshotId, $trees);
328 $l = new LoweringScope($index->builder('fixture.php'), $index, 'target');
329 $node = new If_(new Variable('flag'), ['stmts' => [new Return_(new Int_(1))]]);
330 (new StatementLowering($l))->conditional($node);
331 self::assertSame(TerminatorKind::Return, $l->graph->terminators[2]->kind);
332 self::assertSame(TerminatorKind::Jump, $l->graph->terminators[3]->kind);
333 self::assertSame([1], $l->graph->terminators[3]->targets);
334 }
335 public function testOtherUnsetsTheStorageLocationWithoutReadingIt(): void
336 {
337 $source = '<?php function target(){return 1;}';
338 $snapshotId = 'test';
339 $input = new Sources([new Source('fixture.php', $source)]);
340 $profile = new TargetProfile();
341 $parser = new Parser(new ParserConfig($profile->version));
342 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
343 $index = new Index($snapshotId, $trees);
344 $l = new LoweringScope($index->builder('fixture.php'), $index, 'target');
345 (new StatementLowering($l))->other(new Unset_([new Variable('x')]));
346 self::assertSame(['local', 'unset'], array_column($l->graph->instructions[0], 'operation'));
347 }
348 #[DataProvider('providerIgnoredDeclarations')]
349 public function testOtherLeavesDeclarationsWithoutRuntimeEffectsUnemitted(Stmt $node): void
350 {
351 $source = '<?php function target(){return 1;}';
352 $snapshotId = 'test';
353 $input = new Sources([new Source('fixture.php', $source)]);
354 $profile = new TargetProfile();
355 $parser = new Parser(new ParserConfig($profile->version));
356 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
357 $index = new Index($snapshotId, $trees);
358 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
359 (new StatementLowering($lowering))->other($node);
360 self::assertSame([0 => []], $lowering->graph->instructions);
361 self::assertSame([], $lowering->graph->terminators);
362 self::assertSame(0, $lowering->graph->current);
363 }
364 /**
365 * @return iterable<string,array{Stmt}>
366 */
367 public static function providerIgnoredDeclarations(): iterable
368 {
369 yield 'constant' => [new Const_([new NodeConst_('VALUE', new Int_(1))])];
370 yield 'empty' => [new Nop()];
371 yield 'function' => [new Function_('declared')];
372 yield 'class' => [new Class_('Declared')];
373 yield 'interface' => [new Interface_('Declared')];
374 yield 'trait' => [new Trait_('Declared')];
375 yield 'use' => [new Use_([new UseItem(new Name('A'))])];
376 yield 'group use' => [new GroupUse(new Name('Prefix'), [new UseItem(new Name('A'))])];
377 yield 'declaration without a body' => [new Declare_([new DeclareItem('strict_types', new Int_(1))])];
378 }
379 #[DataProvider('providerNestedStatements')]
380 public function testOtherExecutesNamespaceAndDeclareBodiesInSourceOrder(Stmt $node): void
381 {
382 $source = '<?php function target(){return 1;}';
383 $snapshotId = 'test';
384 $input = new Sources([new Source('fixture.php', $source)]);
385 $profile = new TargetProfile();
386 $parser = new Parser(new ParserConfig($profile->version));
387 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
388 $index = new Index($snapshotId, $trees);
389 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
390 (new StatementLowering($lowering))->other($node);
391 self::assertSame(['constant', 'constant'], array_column($lowering->graph->instructions[0], 'operation'));
392 self::assertSame(17, $lowering->graph->instructions[0][0]->constant?->literal);
393 self::assertSame(29, $lowering->graph->instructions[0][1]->constant?->literal);
394 self::assertSame([], $lowering->graph->terminators);
395 }
396 /**
397 * @return iterable<string,array{Stmt}>
398 */
399 public static function providerNestedStatements(): iterable
400 {
401 $body = [new Expression(new Int_(17)), new Expression(new Int_(29))];
402 yield 'namespace' => [new Namespace_(new Name('Scope'), $body)];
403 yield 'declare' => [new Declare_([new DeclareItem('ticks', new Int_(1))], $body)];
404 }
405 /**
406 * @param list<string> $operations Expected memory instructions
407 */
408 #[DataProvider('providerStorageDeclarations')]
409 public function testOtherEvaluatesEachStorageAddressBeforeApplyingItsEffect(Stmt $node, array $operations): void
410 {
411 $source = '<?php function target(){return 1;}';
412 $snapshotId = 'test';
413 $input = new Sources([new Source('fixture.php', $source)]);
414 $profile = new TargetProfile();
415 $parser = new Parser(new ParserConfig($profile->version));
416 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
417 $index = new Index($snapshotId, $trees);
418 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
419 (new StatementLowering($lowering))->other($node);
420 $instructions = $lowering->graph->instructions[0];
421 self::assertSame($operations, array_column($instructions, 'operation'));
422 self::assertSame('first', $instructions[0]->name);
423 self::assertSame('second', $instructions[2]->name);
424 self::assertSame(['r0'], $instructions[1]->operands);
425 self::assertSame(['r2'], $instructions[3]->operands);
426 }
427 /**
428 * @return iterable<string,array{Stmt,list<string>}>
429 */
430 public static function providerStorageDeclarations(): iterable
431 {
432 $variables = [new Variable('first'), new Variable('second')];
433 yield 'unset' => [new Unset_($variables), ['local', 'unset', 'local', 'unset']];
434 yield 'global' => [new Global_($variables), ['local', 'global', 'local', 'global']];
435 }
436 public function testOtherInitializesEveryFunctionStaticInItsOwnConditionalBlock(): void
437 {
438 $source = '<?php function target(){return 1;}';
439 $snapshotId = 'test';
440 $input = new Sources([new Source('fixture.php', $source)]);
441 $profile = new TargetProfile();
442 $parser = new Parser(new ParserConfig($profile->version));
443 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
444 $index = new Index($snapshotId, $trees);
445 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
446 $node = new Static_([new StaticVar(new Variable('first'), new Int_(17)), new StaticVar(new Variable('second'), new Int_(29))]);
447 (new StatementLowering($lowering))->other($node);
448 self::assertSame(['local', 'static-initialized'], array_column($lowering->graph->instructions[0], 'operation'));
449 self::assertSame(['local', 'static-initialized'], array_column($lowering->graph->instructions[2], 'operation'));
450 self::assertSame('first', $lowering->graph->instructions[0][0]->name);
451 self::assertSame('second', $lowering->graph->instructions[2][0]->name);
452 self::assertSame(17, $lowering->graph->instructions[1][0]->constant?->literal);
453 self::assertSame(29, $lowering->graph->instructions[3][0]->constant?->literal);
454 self::assertSame('static-local', $lowering->graph->instructions[1][1]->operation);
455 self::assertSame('static-local', $lowering->graph->instructions[3][1]->operation);
456 self::assertSame(4, $lowering->graph->current);
457 }
458 public function testOtherMarksUnsupportedStatementsAtTheirOwnSourceRange(): void
459 {
460 $source = '<?php function target(){return 1;}';
461 $snapshotId = 'test';
462 $input = new Sources([new Source('fixture.php', $source)]);
463 $profile = new TargetProfile();
464 $parser = new Parser(new ParserConfig($profile->version));
465 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
466 $index = new Index($snapshotId, $trees);
467 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
468 $node = new InlineHTML('html', ['startFilePos' => 6, 'endFilePos' => 10]);
469 (new StatementLowering($lowering))->other($node);
470 self::assertCount(1, $lowering->graph->instructions[0]);
471 $instruction = $lowering->graph->instructions[0][0];
472 self::assertSame('unsupported', $instruction->operation);
473 self::assertSame('Stmt_InlineHTML', $instruction->name);
474 self::assertSame(6, $instruction->source->start);
475 self::assertSame(11, $instruction->source->end);
476 }
477 public function testLowerStartsALabelBlockAndDefersTheGotoTarget(): void
478 {
479 $source = '<?php function target(){return 1;}';
480 $snapshotId = 'test';
481 $input = new Sources([new Source('fixture.php', $source)]);
482 $profile = new TargetProfile();
483 $parser = new Parser(new ParserConfig($profile->version));
484 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
485 $index = new Index($snapshotId, $trees);
486 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
487 (new StatementLowering($lowering))->lower(new Label('again'));
488 (new StatementLowering($lowering))->lower(new Goto_('again'));
489 self::assertSame([], $lowering->graph->instructions[1]);
490 self::assertSame([0 => TerminatorKind::Jump, 1 => TerminatorKind::Residual], array_map(static fn ($terminator) => $terminator->kind, $lowering->graph->terminators));
491 self::assertSame(1, $lowering->graph->labels['again']['block'] ?? null);
492 self::assertSame(1, $lowering->graph->gotos[0]['block']);
493 }
494 public function testLowerBareReturnsCompleteWithoutAnImplicitValueInstruction(): void
495 {
496 $source = '<?php function target(){return 1;}';
497 $snapshotId = 'test';
498 $input = new Sources([new Source('fixture.php', $source)]);
499 $profile = new TargetProfile();
500 $parser = new Parser(new ParserConfig($profile->version));
501 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
502 $index = new Index($snapshotId, $trees);
503 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
504 (new StatementLowering($lowering))->lower(new Return_());
505 self::assertSame([0 => []], $lowering->graph->instructions);
506 self::assertSame(TerminatorKind::Return, $lowering->graph->terminators[0]->kind);
507 self::assertSame('', $lowering->graph->terminators[0]->operand);
508 }
509 public function testLowerReferenceReturnsExposeTheCellWithoutReadingIt(): void
510 {
511 $source = '<?php function target(){return 1;}';
512 $snapshotId = 'test';
513 $input = new Sources([new Source('fixture.php', $source)]);
514 $profile = new TargetProfile();
515 $parser = new Parser(new ParserConfig($profile->version));
516 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
517 $index = new Index($snapshotId, $trees);
518 $initial = new LoweringScope($index->builder('fixture.php'), $index, 'target');
519 $lowering = new LoweringScope($initial->graph, $initial->index, 'target', returnsByReference: true);
520 (new StatementLowering($lowering))->lower(new Return_(new Variable('value')));
521 self::assertSame(['local', 'reference'], array_column($lowering->graph->instructions[0], 'operation'));
522 self::assertSame('value', $lowering->graph->instructions[0][0]->name);
523 self::assertSame(['r0'], $lowering->graph->instructions[0][1]->operands);
524 self::assertSame(TerminatorKind::Return, $lowering->graph->terminators[0]->kind);
525 self::assertSame('r1', $lowering->graph->terminators[0]->operand);
526 }
527 public function testConditionalChecksElseifOnlyAfterAnEarlierFalseBranch(): void
528 {
529 $source = '<?php function target(){return 1;}';
530 $snapshotId = 'test';
531 $input = new Sources([new Source('fixture.php', $source)]);
532 $profile = new TargetProfile();
533 $parser = new Parser(new ParserConfig($profile->version));
534 $trees = array_map(static fn (Source $source1): File => (new Resolver())->resolve($parser->parse(new Source(Path::normalize($source1->path), $source1->contents, $source1->declarationsOnly))), iterator_to_array($input, false));
535 $index = new Index($snapshotId, $trees);
536 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
537 $node = new If_(new Variable('first'), ['stmts' => [new Expression(new Int_(11))], 'elseifs' => [new ElseIf_(new Variable('second'), [new Expression(new Int_(22))])], 'else' => new Else_([new Expression(new Int_(33))])]);
538 (new StatementLowering($lowering))->conditional($node);
539 self::assertSame(1, $lowering->graph->current);
540 self::assertSame('first', $lowering->graph->instructions[0][0]->name);
541 self::assertSame('second', $lowering->graph->instructions[3][0]->name);
542 self::assertSame(TerminatorKind::Branch, $lowering->graph->terminators[0]->kind);
543 self::assertSame([2, 3], $lowering->graph->terminators[0]->targets);
544 self::assertSame(TerminatorKind::Branch, $lowering->graph->terminators[3]->kind);
545 self::assertSame([4, 5], $lowering->graph->terminators[3]->targets);
546 self::assertSame(11, $lowering->graph->instructions[2][0]->constant?->literal);
547 self::assertSame(22, $lowering->graph->instructions[4][0]->constant?->literal);
548 self::assertSame(33, $lowering->graph->instructions[5][0]->constant?->literal);
549 self::assertSame([1], $lowering->graph->terminators[2]->targets);
550 self::assertSame([1], $lowering->graph->terminators[4]->targets);
551 self::assertSame([1], $lowering->graph->terminators[5]->targets);
552 }
553}
554