packages/deriver/tests/Unit/Deriver/Lowerer/ExpressionLoweringTest.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\Provider\DispatchDecision;
16use Deriver\Deriver\Evaluator\Call\Registrations;
17use Deriver\Deriver\Evaluator\Call\StateRegistry;
18use Deriver\Deriver\Evaluator\EvaluatorConfig;
19use Deriver\Deriver\Evaluator\Evidence\Frontier;
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\CallResolution;
24use Deriver\Deriver\Evaluator\Execution\Call\Member\Invocation;
25use Deriver\Deriver\Evaluator\Execution\Call\MethodInvocation;
26use Deriver\Deriver\Evaluator\Execution\Call\ParameterBinding;
27use Deriver\Deriver\Evaluator\Execution\Call\PassedArgument;
28use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Methods;
29use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Resolution;
30use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Target;
31use Deriver\Deriver\Evaluator\Execution\Call\Preparation\Transfer;
32use Deriver\Deriver\Evaluator\Execution\Call\TypeBinding;
33use Deriver\Deriver\Evaluator\Execution\Call\TypeCheck;
34use Deriver\Deriver\Evaluator\Execution\Completion\Alternative;
35use Deriver\Deriver\Evaluator\Execution\Completion\Assessment;
36use Deriver\Deriver\Evaluator\Execution\Completion\Completion;
37use Deriver\Deriver\Evaluator\Execution\Completion\StorageSnapshot;
38use Deriver\Deriver\Evaluator\Execution\Constant\ClassNames;
39use Deriver\Deriver\Evaluator\Execution\Context;
40use Deriver\Deriver\Evaluator\Execution\Control\ObservationLimit;
41use Deriver\Deriver\Evaluator\Execution\Control\StateJoin;
42use Deriver\Deriver\Evaluator\Execution\Control\Unwinding;
43use Deriver\Deriver\Evaluator\Execution\Demand\Cell;
44use Deriver\Deriver\Evaluator\Execution\Demand\Components;
45use Deriver\Deriver\Evaluator\Execution\Demand\Discovery;
46use Deriver\Deriver\Evaluator\Execution\Demand\Key;
47use Deriver\Deriver\Evaluator\Execution\Demand\Table;
48use Deriver\Deriver\Evaluator\Execution\Dependencies;
49use Deriver\Deriver\Evaluator\Execution\Evaluator;
50use Deriver\Deriver\Evaluator\Execution\EvaluatorConfig as ExecutionEvaluatorConfig;
51use Deriver\Deriver\Evaluator\Execution\InstructionTransfer;
52use Deriver\Deriver\Evaluator\Execution\Memory\Location;
53use Deriver\Deriver\Evaluator\Execution\Memory\Materialization;
54use Deriver\Deriver\Evaluator\Execution\Memory\Memory;
55use Deriver\Deriver\Evaluator\Execution\Memory\Slots\SlotReference;
56use Deriver\Deriver\Evaluator\Execution\Memory\StorageCapture;
57use Deriver\Deriver\Evaluator\Execution\ObservationCollector;
58use Deriver\Deriver\Evaluator\Execution\Operation\Conversions;
59use Deriver\Deriver\Evaluator\Execution\Operation\ScalarErrors;
60use Deriver\Deriver\Evaluator\Execution\State;
61use Deriver\Deriver\Evaluator\Execution\Summary\CompletionRecord;
62use Deriver\Deriver\Evaluator\Execution\Summary\Evaluation;
63use Deriver\Deriver\Evaluator\Execution\Summary\Invocation as SummaryInvocation;
64use Deriver\Deriver\Evaluator\Execution\Summary\Isolation;
65use Deriver\Deriver\Evaluator\Execution\Trace\Derivation;
66use Deriver\Deriver\Evaluator\Execution\Transfer\MemoryStep;
67use Deriver\Deriver\Evaluator\Execution\Transfer\PureStep;
68use Deriver\Deriver\Evaluator\Execution\Transfer\ReferenceAssignment;
69use Deriver\Deriver\Evaluator\Request\Budget;
70use Deriver\Deriver\Evaluator\Request\EntryPoint;
71use Deriver\Deriver\Evaluator\Request\QueryScope;
72use Deriver\Deriver\Evaluator\Request\ReturnQuery;
73use Deriver\Deriver\Evaluator\Scalar\Arithmetic;
74use Deriver\Deriver\Evaluator\Scalar\Arrays;
75use Deriver\Deriver\Evaluator\Scalar\Identity;
76use Deriver\Deriver\Evaluator\Scalar\Operations;
77use Deriver\Deriver\Evaluator\TargetProfile;
78use Deriver\Deriver\Evaluator\Term;
79use Deriver\Deriver\Execution\DerivationResult;
80use Deriver\Deriver\Execution\QueryExecution;
81use Deriver\Deriver\Execution\ResultAssessment;
82use Deriver\Deriver\Identity\QueryEncoding;
83use Deriver\Deriver\Identity\ValueGraph;
84use Deriver\Deriver\Lowerer\AggregateLowering;
85use Deriver\Deriver\Lowerer\AssignmentLowering;
86use Deriver\Deriver\Lowerer\CallLowering;
87use Deriver\Deriver\Lowerer\Declaration\CallableIdentity;
88use Deriver\Deriver\Lowerer\Declaration\CallableSource;
89use Deriver\Deriver\Lowerer\Declaration\ConstantSignatures;
90use Deriver\Deriver\Lowerer\Declaration\Index;
91use Deriver\Deriver\Lowerer\Declaration\Indexer;
92use Deriver\Deriver\Lowerer\Declaration\Metadata\ClassDeclaration;
93use Deriver\Deriver\Lowerer\Declaration\Traits\Composition;
94use Deriver\Deriver\Lowerer\EffectInspection;
95use Deriver\Deriver\Lowerer\ExpressionLowering;
96use Deriver\Deriver\Lowerer\Graph\BasicBlock;
97use Deriver\Deriver\Lowerer\Graph\CallableGraph;
98use Deriver\Deriver\Lowerer\Graph\Instruction;
99use Deriver\Deriver\Lowerer\Graph\Literal;
100use Deriver\Deriver\Lowerer\Graph\Parameter;
101use Deriver\Deriver\Lowerer\Graph\Terminator;
102use Deriver\Deriver\Lowerer\Graph\TerminatorKind;
103use Deriver\Deriver\Lowerer\Hierarchy\Access;
104use Deriver\Deriver\Lowerer\Hierarchy\Dispatch;
105use Deriver\Deriver\Lowerer\InstructionEmitter;
106use Deriver\Deriver\Lowerer\Lowerer;
107use Deriver\Deriver\Lowerer\LoweringScope;
108use Deriver\Deriver\Lowerer\StatementLowering;
109use Deriver\Deriver\MicroEvaluatorConversion;
110use Deriver\Deriver\Parser\Node\File;
111use Deriver\Deriver\Parser\Parser;
112use Deriver\Deriver\Parser\ParserConfig;
113use Deriver\Deriver\Parser\TargetSyntax;
114use Deriver\Deriver\Providers\ProviderExpansion;
115use Deriver\Deriver\Resolver\AssignmentPatterns;
116use Deriver\Deriver\Resolver\ClassScope;
117use Deriver\Deriver\Resolver\ExpressionValidation;
118use Deriver\Deriver\Resolver\MagicContext;
119use Deriver\Deriver\Resolver\Resolver;
120use Deriver\Deriver\Selection\QueryValidation;
121use Deriver\Deriver\SnapshotIdentity;
122use Deriver\Deriver\Sources\LineMap;
123use Deriver\Deriver\Sources\Path;
124use Deriver\Deriver\Sources\Source;
125use Deriver\Deriver\Sources\SourceRef;
126use Deriver\Deriver\Sources\Sources;
127use Deriver\Exception\ParserException;
128use Deriver\Exception\ResolutionException;
129use PhpParser\Node\Expr;
130use PhpParser\Node\Expr\Array_ as ExprArray_;
131use PhpParser\Node\Expr\ArrayDimFetch;
132use PhpParser\Node\Expr\ArrowFunction;
133use PhpParser\Node\Expr\BinaryOp\Plus;
134use PhpParser\Node\Expr\BitwiseNot;
135use PhpParser\Node\Expr\BooleanNot;
136use PhpParser\Node\Expr\Cast\Array_;
137use PhpParser\Node\Expr\Cast\Bool_;
138use PhpParser\Node\Expr\Cast\Double;
139use PhpParser\Node\Expr\Cast\Int_ as CastInt_;
140use PhpParser\Node\Expr\Cast\Object_;
141use PhpParser\Node\Expr\Cast\String_ as CastString_;
142use PhpParser\Node\Expr\ClassConstFetch;
143use PhpParser\Node\Expr\Clone_;
144use PhpParser\Node\Expr\ConstFetch;
145use PhpParser\Node\Expr\Eval_;
146use PhpParser\Node\Expr\FuncCall;
147use PhpParser\Node\Expr\Include_;
148use PhpParser\Node\Expr\Instanceof_;
149use PhpParser\Node\Expr\PostInc;
150use PhpParser\Node\Expr\Print_;
151use PhpParser\Node\Expr\Throw_;
152use PhpParser\Node\Expr\UnaryMinus;
153use PhpParser\Node\Expr\UnaryPlus;
154use PhpParser\Node\Expr\Variable;
155use PhpParser\Node\Name;
156use PhpParser\Node\Scalar\Float_;
157use PhpParser\Node\Scalar\Int_;
158use PhpParser\Node\Scalar\MagicConst;
159use PhpParser\Node\Scalar\MagicConst\Function_;
160use PhpParser\Node\Scalar\MagicConst\Line;
161use PhpParser\Node\Scalar\MagicConst\Method;
162use PhpParser\Node\Scalar\MagicConst\Namespace_;
163use PhpParser\Node\Scalar\String_;
164use PHPUnit\Framework\Attributes\CoversClass;
165use PHPUnit\Framework\Attributes\DataProvider;
166use PHPUnit\Framework\Attributes\Small;
167use PHPUnit\Framework\Attributes\UsesClass;
168use PHPUnit\Framework\TestCase;
169
170#[UsesClass(Resolver::class)]
171#[UsesClass(ExpressionValidation::class)]
172#[UsesClass(ResolutionException::class)]
173#[UsesClass(ParserConfig::class)]
174#[UsesClass(ParserException::class)]
175#[CoversClass(ExpressionLowering::class)]
176#[UsesClass(QueryExecution::class)]
177#[UsesClass(QueryValidation::class)]
178#[UsesClass(ResultAssessment::class)]
179#[UsesClass(Deriver::class)]
180#[UsesClass(BasicBlock::class)]
181#[UsesClass(CallableGraph::class)]
182#[UsesClass(CallableIdentity::class)]
183#[UsesClass(ClassDeclaration::class)]
184#[UsesClass(Instruction::class)]
185#[UsesClass(Parameter::class)]
186#[UsesClass(Terminator::class)]
187#[UsesClass(ArgumentBinding::class)]
188#[UsesClass(ArgumentOrder::class)]
189#[UsesClass(CallExecutor::class)]
190#[UsesClass(CallResolution::class)]
191#[UsesClass(Dispatch::class)]
192#[UsesClass(Access::class)]
193#[UsesClass(Invocation::class)]
194#[UsesClass(MethodInvocation::class)]
195#[UsesClass(ParameterBinding::class)]
196#[UsesClass(PassedArgument::class)]
197#[UsesClass(Methods::class)]
198#[UsesClass(Resolution::class)]
199#[UsesClass(Target::class)]
200#[UsesClass(Transfer::class)]
201#[UsesClass(TypeBinding::class)]
202#[UsesClass(TypeCheck::class)]
203#[UsesClass(Completion::class)]
204#[UsesClass(ClassNames::class)]
205#[UsesClass(Context::class)]
206#[UsesClass(ObservationLimit::class)]
207#[UsesClass(StateJoin::class)]
208#[UsesClass(Unwinding::class)]
209#[UsesClass(Cell::class)]
210#[UsesClass(Components::class)]
211#[UsesClass(Discovery::class)]
212#[UsesClass(Key::class)]
213#[UsesClass(Table::class)]
214#[UsesClass(Dependencies::class)]
215#[UsesClass(InstructionTransfer::class)]
216#[UsesClass(Evaluator::class)]
217#[UsesClass(SlotReference::class)]
218#[UsesClass(ObservationCollector::class)]
219#[UsesClass(Conversions::class)]
220#[UsesClass(ScalarErrors::class)]
221#[UsesClass(State::class)]
222#[UsesClass(CompletionRecord::class)]
223#[UsesClass(Evaluation::class)]
224#[UsesClass(SummaryInvocation::class)]
225#[UsesClass(Isolation::class)]
226#[UsesClass(MemoryStep::class)]
227#[UsesClass(PureStep::class)]
228#[UsesClass(ReferenceAssignment::class)]
229#[UsesClass(Location::class)]
230#[UsesClass(Materialization::class)]
231#[UsesClass(Memory::class)]
232#[UsesClass(StorageCapture::class)]
233#[UsesClass(DispatchDecision::class)]
234#[UsesClass(Extensions::class)]
235#[UsesClass(ProviderExpansion::class)]
236#[UsesClass(Evaluators::class)]
237#[UsesClass(StateRegistry::class)]
238#[UsesClass(DeriverConfig::class)]
239#[UsesClass(EntryPoint::class)]
240#[UsesClass(Sources::class)]
241#[UsesClass(Path::class)]
242#[UsesClass(Snapshot::class)]
243#[UsesClass(Source::class)]
244#[UsesClass(TargetProfile::class)]
245#[UsesClass(Budget::class)]
246#[UsesClass(QueryScope::class)]
247#[UsesClass(ReturnQuery::class)]
248#[UsesClass(ResultRef::class)]
249#[UsesClass(SourceRef::class)]
250#[UsesClass(Alternative::class)]
251#[UsesClass(Assessment::class)]
252#[UsesClass(Derivation::class)]
253#[UsesClass(DerivationResult::class)]
254#[UsesClass(QueryEncoding::class)]
255#[UsesClass(ValueGraph::class)]
256#[UsesClass(Statistics::class)]
257#[UsesClass(StorageSnapshot::class)]
258#[UsesClass(Parser::class)]
259#[UsesClass(File::class)]
260#[UsesClass(AggregateLowering::class)]
261#[UsesClass(AssignmentLowering::class)]
262#[UsesClass(CallLowering::class)]
263#[UsesClass(Lowerer::class)]
264#[UsesClass(EffectInspection::class)]
265#[UsesClass(InstructionEmitter::class)]
266#[UsesClass(LoweringScope::class)]
267#[UsesClass(StatementLowering::class)]
268#[UsesClass(ConstantSignatures::class)]
269#[UsesClass(CallableSource::class)]
270#[UsesClass(Indexer::class)]
271#[UsesClass(Index::class)]
272#[UsesClass(Composition::class)]
273#[UsesClass(LineMap::class)]
274#[UsesClass(MagicContext::class)]
275#[UsesClass(AssignmentPatterns::class)]
276#[UsesClass(ClassScope::class)]
277#[UsesClass(TargetSyntax::class)]
278#[UsesClass(Arithmetic::class)]
279#[UsesClass(Arrays::class)]
280#[UsesClass(Identity::class)]
281#[UsesClass(Operations::class)]
282#[UsesClass(Literal::class)]
283#[Small]
284final class ExpressionLoweringTest extends TestCase
285{
286 public function testLowerPreservesTheSemanticContract(): void
287 {
288 $source = '<?php function target(){return [2=>"left","x"=>1]+[2=>"right",3=>"new"];}';
289 $symbol = 'target';
290 $input = new Sources([new Source('fixture.php', $source)]);
291 $configuration = new DeriverConfig();
292 $contributions = new Contributions();
293 $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
294 $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
295 $contributions1 = $providers->contributions;
296 $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);
297 $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
298 $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
299 $snapshotId = $identity->id;
300 $input1 = $providers->input;
301 $parser = new Parser(new ParserConfig($target->version));
302 $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));
303 $program = new Index($snapshotId, $trees);
304 $result = (new QueryExecution($program, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program->diagnostics()))))->derive(new ReturnQuery($symbol));
305 self::assertSame([2 => 'left', 'x' => 1, 3 => 'new'], $result->normalOutcomes[0]->values['return']->native());
306 self::assertSame([], $result->frontiers);
307 self::assertSame([], $result->exceptionalOutcomes);
308 }
309 public function testOperationReadsAnAddressableVariable(): void
310 {
311 $source = '<?php function target(){return 1;}';
312 $snapshotId = 'test';
313 $input = new Sources([new Source('fixture.php', $source)]);
314 $profile = new TargetProfile();
315 $parser = new Parser(new ParserConfig($profile->version));
316 $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));
317 $index = new Index($snapshotId, $trees);
318 $l = new LoweringScope($index->builder('fixture.php'), $index, 'target');
319 (new ExpressionLowering($l))->operation(new Variable('x'));
320 self::assertSame(['local', 'read'], array_column($l->graph->instructions[0], 'operation'));
321 }
322 public function testBinaryMarksInteractingEffectsWithUnspecifiedOrder(): void
323 {
324 $source = '<?php function target(){return 1;}';
325 $snapshotId = 'test';
326 $input = new Sources([new Source('fixture.php', $source)]);
327 $profile = new TargetProfile();
328 $parser = new Parser(new ParserConfig($profile->version));
329 $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));
330 $index = new Index($snapshotId, $trees);
331 $l = new LoweringScope($index->builder('fixture.php'), $index, 'target');
332 $node = new Plus(new PostInc(new Variable('x')), new Variable('x'));
333 (new ExpressionLowering($l))->binary($node);
334 self::assertSame(['evaluation-order'], array_column($l->graph->instructions[0], 'operation'));
335 self::assertCount(4, $l->graph->instructions);
336 self::assertSame(TerminatorKind::Branch, $l->graph->terminators[0]->kind);
337 }
338 public function testOtherMakesEvalASymbolTableBoundary(): void
339 {
340 $source = '<?php function target(){return 1;}';
341 $snapshotId = 'test';
342 $input = new Sources([new Source('fixture.php', $source)]);
343 $profile = new TargetProfile();
344 $parser = new Parser(new ParserConfig($profile->version));
345 $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));
346 $index = new Index($snapshotId, $trees);
347 $l = new LoweringScope($index->builder('fixture.php'), $index, 'target');
348 (new ExpressionLowering($l))->other(new Eval_(new String_('return 1;')));
349 self::assertSame('symbol-table-boundary', $l->graph->instructions[0][1]->operation);
350 }
351 public function testComputedRegistersAClosureWithoutLoweringItsBody(): void
352 {
353 $source = '<?php function target(){return 1;}';
354 $snapshotId = 'test';
355 $input = new Sources([new Source('fixture.php', $source)]);
356 $profile = new TargetProfile();
357 $parser = new Parser(new ParserConfig($profile->version));
358 $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));
359 $index = new Index($snapshotId, $trees);
360 $l = new LoweringScope($index->builder('fixture.php'), $index, 'target');
361 (new ExpressionLowering($l))->computed(new ArrowFunction(['expr' => new FuncCall(new Name('sideEffect'))]));
362 self::assertSame(['closure'], array_column($l->graph->instructions[0], 'operation'));
363 self::assertSame(0, $l->index->graphCount());
364 }
365 public function testMagicUsesLexicalNamesForSeparateDefaultGraphs(): void
366 {
367 $source = '<?php class Box{static function value($name=__METHOD__){return $name;}}function target(){return Box::value();}';
368 $symbol = 'target';
369 $input = new Sources([new Source('fixture.php', $source)]);
370 $configuration = new DeriverConfig();
371 $contributions = new Contributions();
372 $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
373 $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
374 $contributions1 = $providers->contributions;
375 $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);
376 $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
377 $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
378 $snapshotId = $identity->id;
379 $input1 = $providers->input;
380 $parser = new Parser(new ParserConfig($target->version));
381 $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));
382 $program = new Index($snapshotId, $trees);
383 $result = (new QueryExecution($program, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program->diagnostics()))))->derive(new ReturnQuery($symbol));
384 self::assertSame('Box::value', $result->normalOutcomes[0]->values['return']->native());
385 }
386 #[DataProvider('providerLiteralNodes')]
387 public function testLowerPreservesLiteralTypesAndBytes(Expr $node, mixed $expected): void
388 {
389 $source = '<?php function target(){return 1;}';
390 $snapshotId = 'test';
391 $input = new Sources([new Source('fixture.php', $source)]);
392 $profile = new TargetProfile();
393 $parser = new Parser(new ParserConfig($profile->version));
394 $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));
395 $index = new Index($snapshotId, $trees);
396 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
397 $register = (new ExpressionLowering($lowering))->lower($node);
398 self::assertCount(1, $lowering->graph->instructions[0]);
399 self::assertSame('constant', $lowering->graph->instructions[0][0]->operation);
400 self::assertSame($expected, $lowering->graph->instructions[0][0]->constant?->native());
401 self::assertSame($register, $lowering->graph->instructions[0][0]->result);
402 }
403 /**
404 * @return iterable<string,array{Expr,mixed}>
405 */
406 public static function providerLiteralNodes(): iterable
407 {
408 yield 'integer' => [new Int_(42), 42];
409 yield 'float' => [new Float_(2.5), 2.5];
410 yield 'string' => [new String_("\x00\xff"), "\x00\xff"];
411 }
412 public function testLowerRetainsUnresolvedConstantNames(): void
413 {
414 $source = '<?php function target(){return 1;}';
415 $snapshotId = 'test';
416 $input = new Sources([new Source('fixture.php', $source)]);
417 $profile = new TargetProfile();
418 $parser = new Parser(new ParserConfig($profile->version));
419 $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));
420 $index = new Index($snapshotId, $trees);
421 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
422 $register = (new ExpressionLowering($lowering))->lower(new ConstFetch(new Name('EXAMPLE')));
423 self::assertSame('constant-fetch', $lowering->graph->instructions[0][0]->operation);
424 self::assertSame('EXAMPLE', $lowering->graph->instructions[0][0]->name);
425 self::assertSame($register, $lowering->graph->instructions[0][0]->result);
426 }
427 #[DataProvider('providerLexicalMagic')]
428 public function testMagicSelectsOnlyTheMatchingCapturedLexicalName(MagicConst $node, string $key, string $expected): void
429 {
430 $node->setAttribute('deriver-lexical', [$key => $expected, 'unrelated' => 'wrong']);
431 $source = '<?php function target(){return 1;}';
432 $snapshotId = 'test';
433 $input = new Sources([new Source('fixture.php', $source)]);
434 $profile = new TargetProfile();
435 $parser = new Parser(new ParserConfig($profile->version));
436 $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));
437 $index = new Index($snapshotId, $trees);
438 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
439 $register = (new ExpressionLowering($lowering))->magic($node);
440 self::assertSame('constant', $lowering->graph->instructions[0][0]->operation);
441 self::assertSame($expected, $lowering->graph->instructions[0][0]->constant?->native());
442 self::assertSame($register, $lowering->graph->instructions[0][0]->result);
443 }
444 /**
445 * @return iterable<string,array{MagicConst,string,string}>
446 */
447 public static function providerLexicalMagic(): iterable
448 {
449 yield 'function' => [new Function_(), 'function', 'Example\run'];
450 yield 'method' => [new Method(), 'method', 'Example\Box::run'];
451 yield 'namespace' => [new Namespace_(), 'namespace', 'Example'];
452 }
453 public function testLowerResolvesSourceLineWithoutLexicalMetadata(): void
454 {
455 $source = '<?php function target(){return 1;}';
456 $snapshotId = 'test';
457 $input = new Sources([new Source('fixture.php', $source)]);
458 $profile = new TargetProfile();
459 $parser = new Parser(new ParserConfig($profile->version));
460 $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));
461 $index = new Index($snapshotId, $trees);
462 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
463 $node = new Line(['startLine' => 7]);
464 $node->setAttribute('deriver-lexical', ['function' => 'irrelevant']);
465 $register = (new ExpressionLowering($lowering))->lower($node);
466 self::assertSame('constant', $lowering->graph->instructions[0][0]->operation);
467 self::assertSame(7, $lowering->graph->instructions[0][0]->constant?->native());
468 self::assertSame($register, $lowering->graph->instructions[0][0]->result);
469 }
470 public function testMagicRejectsNonStringLexicalMetadata(): void
471 {
472 $source = '<?php function target(){return 1;}';
473 $snapshotId = 'test';
474 $input = new Sources([new Source('fixture.php', $source)]);
475 $profile = new TargetProfile();
476 $parser = new Parser(new ParserConfig($profile->version));
477 $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));
478 $index = new Index($snapshotId, $trees);
479 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
480 $node = new Function_();
481 $node->setAttribute('deriver-lexical', ['function' => 42]);
482 (new ExpressionLowering($lowering))->magic($node);
483 self::assertSame('magic-constant', $lowering->graph->instructions[0][0]->operation);
484 self::assertSame('__FUNCTION__', $lowering->graph->instructions[0][0]->name);
485 }
486 #[DataProvider('providerUnaryAndCasts')]
487 public function testOtherPreservesUnaryAndCastOperations(Expr $node, string $operation, string $name): void
488 {
489 $source = '<?php function target(){return 1;}';
490 $snapshotId = 'test';
491 $input = new Sources([new Source('fixture.php', $source)]);
492 $profile = new TargetProfile();
493 $parser = new Parser(new ParserConfig($profile->version));
494 $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));
495 $index = new Index($snapshotId, $trees);
496 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
497 $register = (new ExpressionLowering($lowering))->other($node);
498 self::assertSame(['constant', $operation], array_column($lowering->graph->instructions[0], 'operation'));
499 self::assertSame($name, $lowering->graph->instructions[0][1]->name);
500 self::assertSame([$lowering->graph->instructions[0][0]->result], $lowering->graph->instructions[0][1]->operands);
501 self::assertSame($register, $lowering->graph->instructions[0][1]->result);
502 }
503 /**
504 * @return iterable<string,array{Expr,string,string}>
505 */
506 public static function providerUnaryAndCasts(): iterable
507 {
508 $value = new Int_(5);
509 yield 'boolean not' => [new BooleanNot($value), 'unary', 'Expr_BooleanNot'];
510 yield 'unary minus' => [new UnaryMinus($value), 'unary', 'Expr_UnaryMinus'];
511 yield 'unary plus' => [new UnaryPlus($value), 'unary', 'Expr_UnaryPlus'];
512 yield 'bitwise not' => [new BitwiseNot($value), 'unary', 'Expr_BitwiseNot'];
513 yield 'integer cast' => [new CastInt_($value), 'cast', 'Int'];
514 yield 'string cast' => [new CastString_($value), 'cast', 'String'];
515 yield 'boolean cast' => [new Bool_($value), 'cast', 'Bool'];
516 yield 'float cast' => [new Double($value), 'cast', 'Double'];
517 yield 'array cast' => [new Array_($value), 'cast', 'Array'];
518 yield 'object cast' => [new Object_($value), 'cast', 'Object'];
519 }
520 public function testOtherPreservesCloneIdentityAsAnExplicitOperation(): void
521 {
522 $source = '<?php function target(){return 1;}';
523 $snapshotId = 'test';
524 $input = new Sources([new Source('fixture.php', $source)]);
525 $profile = new TargetProfile();
526 $parser = new Parser(new ParserConfig($profile->version));
527 $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));
528 $index = new Index($snapshotId, $trees);
529 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
530 $register = (new ExpressionLowering($lowering))->other(new Clone_(new Variable('object')));
531 self::assertSame(['local', 'read', 'clone'], array_column($lowering->graph->instructions[0], 'operation'));
532 self::assertSame([$lowering->graph->instructions[0][1]->result], $lowering->graph->instructions[0][2]->operands);
533 self::assertSame($register, $lowering->graph->instructions[0][2]->result);
534 }
535 public function testOtherKeepsTheThrowOperandAndItsResultRegister(): void
536 {
537 $source = '<?php function target(){return 1;}';
538 $snapshotId = 'test';
539 $input = new Sources([new Source('fixture.php', $source)]);
540 $profile = new TargetProfile();
541 $parser = new Parser(new ParserConfig($profile->version));
542 $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));
543 $index = new Index($snapshotId, $trees);
544 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
545 $register = (new ExpressionLowering($lowering))->other(new Throw_(new Variable('error')));
546 self::assertSame(['local', 'read', 'throw'], array_column($lowering->graph->instructions[0], 'operation'));
547 self::assertSame([$lowering->graph->instructions[0][1]->result], $lowering->graph->instructions[0][2]->operands);
548 self::assertSame($register, $lowering->graph->instructions[0][2]->result);
549 }
550 public function testOtherKeepsBothClassConstantNames(): void
551 {
552 $source = '<?php function target(){return 1;}';
553 $snapshotId = 'test';
554 $input = new Sources([new Source('fixture.php', $source)]);
555 $profile = new TargetProfile();
556 $parser = new Parser(new ParserConfig($profile->version));
557 $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));
558 $index = new Index($snapshotId, $trees);
559 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
560 $register = (new ExpressionLowering($lowering))->other(new ClassConstFetch(new Name('Box'), 'VALUE'));
561 self::assertSame(['constant', 'constant', 'class-constant'], array_column($lowering->graph->instructions[0], 'operation'));
562 self::assertSame('Box', $lowering->graph->instructions[0][0]->constant?->native());
563 self::assertSame('VALUE', $lowering->graph->instructions[0][1]->constant?->native());
564 self::assertSame([$lowering->graph->instructions[0][0]->result, $lowering->graph->instructions[0][1]->result], $lowering->graph->instructions[0][2]->operands);
565 self::assertSame($register, $lowering->graph->instructions[0][2]->result);
566 }
567 public function testOtherKeepsTheInstanceofReceiverAndClass(): void
568 {
569 $source = '<?php function target(){return 1;}';
570 $snapshotId = 'test';
571 $input = new Sources([new Source('fixture.php', $source)]);
572 $profile = new TargetProfile();
573 $parser = new Parser(new ParserConfig($profile->version));
574 $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));
575 $index = new Index($snapshotId, $trees);
576 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
577 $register = (new ExpressionLowering($lowering))->other(new Instanceof_(new Variable('object'), new Name('Box')));
578 self::assertSame(['local', 'read', 'constant', 'instanceof'], array_column($lowering->graph->instructions[0], 'operation'));
579 self::assertSame('Box', $lowering->graph->instructions[0][2]->constant?->native());
580 self::assertSame([$lowering->graph->instructions[0][1]->result, $lowering->graph->instructions[0][2]->result], $lowering->graph->instructions[0][3]->operands);
581 self::assertSame($register, $lowering->graph->instructions[0][3]->result);
582 }
583 public function testOtherCapturesIncludeBoundariesWithoutReadingTheFile(): void
584 {
585 $source = '<?php function target(){return 1;}';
586 $snapshotId = 'test';
587 $input = new Sources([new Source('fixture.php', $source)]);
588 $profile = new TargetProfile();
589 $parser = new Parser(new ParserConfig($profile->version));
590 $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));
591 $index = new Index($snapshotId, $trees);
592 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
593 $register = (new ExpressionLowering($lowering))->other(new Include_(new String_('unread.php'), Include_::TYPE_REQUIRE_ONCE));
594 self::assertSame(['constant', 'symbol-table-boundary'], array_column($lowering->graph->instructions[0], 'operation'));
595 self::assertSame('unread.php', $lowering->graph->instructions[0][0]->constant?->native());
596 self::assertSame('INCLUDE_SEMANTICS_UNSUPPORTED', $lowering->graph->instructions[0][1]->name);
597 self::assertSame([$lowering->graph->instructions[0][0]->result], $lowering->graph->instructions[0][1]->operands);
598 self::assertSame($register, $lowering->graph->instructions[0][1]->result);
599 }
600 public function testComputedPreservesPrintOperandConversion(): void
601 {
602 $source = '<?php function target(){return 1;}';
603 $snapshotId = 'test';
604 $input = new Sources([new Source('fixture.php', $source)]);
605 $profile = new TargetProfile();
606 $parser = new Parser(new ParserConfig($profile->version));
607 $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));
608 $index = new Index($snapshotId, $trees);
609 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
610 $register = (new ExpressionLowering($lowering))->computed(new Print_(new String_('not emitted')));
611 self::assertSame(['constant', 'cast', 'print'], array_column($lowering->graph->instructions[0], 'operation'));
612 self::assertSame('string', $lowering->graph->instructions[0][1]->name);
613 self::assertSame($register, $lowering->graph->instructions[0][2]->result);
614 }
615 public function testComputedReadsOffsetsWithoutCreatingAnAddress(): void
616 {
617 $source = '<?php function target(){return 1;}';
618 $snapshotId = 'test';
619 $input = new Sources([new Source('fixture.php', $source)]);
620 $profile = new TargetProfile();
621 $parser = new Parser(new ParserConfig($profile->version));
622 $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));
623 $index = new Index($snapshotId, $trees);
624 $lowering = new LoweringScope($index->builder('fixture.php'), $index, 'target');
625 $register = (new ExpressionLowering($lowering))->computed(new ArrayDimFetch(new ExprArray_([]), new Int_(2)));
626 self::assertSame(['constant', 'constant', 'array-read'], array_column($lowering->graph->instructions[0], 'operation'));
627 self::assertSame([$lowering->graph->instructions[0][0]->result, $lowering->graph->instructions[0][1]->result], $lowering->graph->instructions[0][2]->operands);
628 self::assertSame(2, $lowering->graph->instructions[0][1]->constant?->native());
629 self::assertSame($register, $lowering->graph->instructions[0][2]->result);
630 }
631 #[DataProvider('providerClassFetchSyntax')]
632 public function testLowerKeepsLiteralClassSyntaxDistinctFromEvaluatedClassValues(string $expression, bool $literal, bool $className): void
633 {
634 $source = '<?php function target($x,$name){return ' . $expression . ';}';
635 $snapshotId = 'test';
636 $input = new Sources([new Source('fixture.php', $source)]);
637 $profile = new TargetProfile();
638 $parser = new Parser(new ParserConfig($profile->version));
639 $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));
640 $index = new Index($snapshotId, $trees);
641 $body = $index->callable('target');
642 self::assertNotNull($body);
643 $instructions = array_values(array_filter($body->blocks[0]->instructions, static fn (Instruction $instruction): bool => $instruction->operation === 'class-constant'));
644 self::assertCount(1, $instructions);
645 self::assertSame($literal, $instructions[0]->attributes['literal-class']);
646 self::assertSame($className, $instructions[0]->attributes['class-name']);
647 }
648 /**
649 * @return iterable<string,array{string,bool,bool}>
650 */
651 public static function providerClassFetchSyntax(): iterable
652 {
653 yield 'literal class name' => ['Missing::class', true, true];
654 yield 'dynamic class name' => ['$x::class', false, true];
655 yield 'literal class dynamic constant' => ['Box::{$name}', true, false];
656 yield 'dynamic class dynamic constant' => ['$x::{$name}', false, false];
657 yield 'class keyword case' => ['Box::ClAsS', true, true];
658 yield 'ordinary constant' => ['Box::VALUE', true, false];
659 }
660 #[DataProvider('providerClassOperandSyntax')]
661 public function testOtherPreservesWhetherAClassOperandIsLiteral(string $expression, bool $literal): void
662 {
663 $source = '<?php function target($class,$value){return ' . $expression . ';}';
664 $snapshotId = 'test';
665 $input = new Sources([new Source('fixture.php', $source)]);
666 $profile = new TargetProfile();
667 $parser = new Parser(new ParserConfig($profile->version));
668 $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));
669 $index = new Index($snapshotId, $trees);
670 $body = $index->callable('target');
671 self::assertNotNull($body);
672 $instructions = array_values(array_filter($body->blocks[0]->instructions, static fn (Instruction $instruction): bool => $instruction->operation === 'instanceof'));
673 self::assertCount(1, $instructions);
674 self::assertSame($literal, $instructions[0]->attributes['literal-class']);
675 }
676 /**
677 * @return iterable<string,array{string,bool}>
678 */
679 public static function providerClassOperandSyntax(): iterable
680 {
681 yield '$value instanceof Box' => ['$value instanceof Box', true];
682 yield '$value instanceof $class' => ['$value instanceof $class', false];
683 }
684}
685