packages/deriver/tests/Unit/Deriver/Evaluator/Execution/ConstraintsTest.php

1<?php
2
3declare (strict_types=1);
4
5namespace Tests\Unit\Deriver\Evaluator\Execution;
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\Provider;
16use Deriver\Deriver\Evaluator\Call\Provider\RefinementEvaluator;
17use Deriver\Deriver\Evaluator\Call\Registrations;
18use Deriver\Deriver\Evaluator\Call\StateRegistry;
19use Deriver\Deriver\Evaluator\EvaluatorConfig;
20use Deriver\Deriver\Evaluator\Evidence\Frontier;
21use Deriver\Deriver\Evaluator\Execution\Call\ArgumentBinding;
22use Deriver\Deriver\Evaluator\Execution\Call\ArgumentOrder;
23use Deriver\Deriver\Evaluator\Execution\Call\ParameterBinding;
24use Deriver\Deriver\Evaluator\Execution\Call\TypeBinding;
25use Deriver\Deriver\Evaluator\Execution\Call\TypeCheck;
26use Deriver\Deriver\Evaluator\Execution\Completion\Alternative;
27use Deriver\Deriver\Evaluator\Execution\Completion\Assessment;
28use Deriver\Deriver\Evaluator\Execution\Completion\Completion;
29use Deriver\Deriver\Evaluator\Execution\Completion\StorageSnapshot;
30use Deriver\Deriver\Evaluator\Execution\Constraints;
31use Deriver\Deriver\Evaluator\Execution\Context;
32use Deriver\Deriver\Evaluator\Execution\Control\ObservationLimit;
33use Deriver\Deriver\Evaluator\Execution\Control\StateJoin;
34use Deriver\Deriver\Evaluator\Execution\Control\Unwinding;
35use Deriver\Deriver\Evaluator\Execution\Demand\Cell;
36use Deriver\Deriver\Evaluator\Execution\Demand\Components;
37use Deriver\Deriver\Evaluator\Execution\Demand\Discovery;
38use Deriver\Deriver\Evaluator\Execution\Demand\Key;
39use Deriver\Deriver\Evaluator\Execution\Demand\Table;
40use Deriver\Deriver\Evaluator\Execution\Dependencies;
41use Deriver\Deriver\Evaluator\Execution\Evaluator;
42use Deriver\Deriver\Evaluator\Execution\EvaluatorConfig as ExecutionEvaluatorConfig;
43use Deriver\Deriver\Evaluator\Execution\InstructionTransfer;
44use Deriver\Deriver\Evaluator\Execution\Memory\Location;
45use Deriver\Deriver\Evaluator\Execution\Memory\Materialization;
46use Deriver\Deriver\Evaluator\Execution\Memory\Memory;
47use Deriver\Deriver\Evaluator\Execution\Memory\Slots\SlotReference;
48use Deriver\Deriver\Evaluator\Execution\Memory\StorageCapture;
49use Deriver\Deriver\Evaluator\Execution\ObservationCollector;
50use Deriver\Deriver\Evaluator\Execution\Operation\Conversions;
51use Deriver\Deriver\Evaluator\Execution\Operation\ScalarErrors;
52use Deriver\Deriver\Evaluator\Execution\State;
53use Deriver\Deriver\Evaluator\Execution\Summary\CompletionRecord;
54use Deriver\Deriver\Evaluator\Execution\Summary\Evaluation;
55use Deriver\Deriver\Evaluator\Execution\Summary\Invocation;
56use Deriver\Deriver\Evaluator\Execution\Summary\Isolation;
57use Deriver\Deriver\Evaluator\Execution\Trace\Derivation;
58use Deriver\Deriver\Evaluator\Execution\Transfer\MemoryStep;
59use Deriver\Deriver\Evaluator\Execution\Transfer\PureStep;
60use Deriver\Deriver\Evaluator\Execution\Transfer\ReferenceAssignment;
61use Deriver\Deriver\Evaluator\Request\Budget;
62use Deriver\Deriver\Evaluator\Request\EntryPoint;
63use Deriver\Deriver\Evaluator\Request\QueryScope;
64use Deriver\Deriver\Evaluator\Request\ReturnQuery;
65use Deriver\Deriver\Evaluator\Scalar\Arithmetic;
66use Deriver\Deriver\Evaluator\Scalar\Comparison;
67use Deriver\Deriver\Evaluator\Scalar\Identity;
68use Deriver\Deriver\Evaluator\Scalar\Operations;
69use Deriver\Deriver\Evaluator\TargetProfile;
70use Deriver\Deriver\Evaluator\Term;
71use Deriver\Deriver\Evaluator\TermKind;
72use Deriver\Deriver\Execution\DerivationResult;
73use Deriver\Deriver\Execution\QueryExecution;
74use Deriver\Deriver\Execution\ResultAssessment;
75use Deriver\Deriver\Identity\QueryEncoding;
76use Deriver\Deriver\Identity\ValueGraph;
77use Deriver\Deriver\Lowerer\Declaration\CallableIdentity;
78use Deriver\Deriver\Lowerer\Declaration\CallableSource;
79use Deriver\Deriver\Lowerer\Declaration\Index;
80use Deriver\Deriver\Lowerer\Declaration\Indexer;
81use Deriver\Deriver\Lowerer\Declaration\Traits\Composition;
82use Deriver\Deriver\Lowerer\EffectInspection;
83use Deriver\Deriver\Lowerer\ExpressionLowering;
84use Deriver\Deriver\Lowerer\Graph\BasicBlock;
85use Deriver\Deriver\Lowerer\Graph\CallableGraph;
86use Deriver\Deriver\Lowerer\Graph\Instruction;
87use Deriver\Deriver\Lowerer\Graph\Parameter;
88use Deriver\Deriver\Lowerer\Graph\Terminator;
89use Deriver\Deriver\Lowerer\Hierarchy\Dispatch;
90use Deriver\Deriver\Lowerer\InstructionEmitter;
91use Deriver\Deriver\Lowerer\Lowerer;
92use Deriver\Deriver\Lowerer\LoweringScope;
93use Deriver\Deriver\Lowerer\StatementLowering;
94use Deriver\Deriver\MicroEvaluatorConversion;
95use Deriver\Deriver\Parser\Node\File;
96use Deriver\Deriver\Parser\Parser;
97use Deriver\Deriver\Parser\ParserConfig;
98use Deriver\Deriver\Parser\TargetSyntax;
99use Deriver\Deriver\Providers\ProviderExpansion;
100use Deriver\Deriver\Resolver\AssignmentPatterns;
101use Deriver\Deriver\Resolver\ClassScope;
102use Deriver\Deriver\Resolver\ExpressionValidation;
103use Deriver\Deriver\Resolver\MagicContext;
104use Deriver\Deriver\Resolver\Resolver;
105use Deriver\Deriver\Selection\QueryValidation;
106use Deriver\Deriver\SnapshotIdentity;
107use Deriver\Deriver\Sources\LineMap;
108use Deriver\Deriver\Sources\Path;
109use Deriver\Deriver\Sources\Source;
110use Deriver\Deriver\Sources\SourceRef;
111use Deriver\Deriver\Sources\Sources;
112use Deriver\Exception\ParserException;
113use Deriver\Exception\ResolutionException;
114use PHPUnit\Framework\Attributes\CoversClass;
115use PHPUnit\Framework\Attributes\DataProvider;
116use PHPUnit\Framework\Attributes\Small;
117use PHPUnit\Framework\Attributes\UsesClass;
118use PHPUnit\Framework\TestCase;
119use RuntimeException;
120
121#[UsesClass(Resolver::class)]
122#[UsesClass(ExpressionValidation::class)]
123#[UsesClass(ResolutionException::class)]
124#[UsesClass(ParserConfig::class)]
125#[UsesClass(ParserException::class)]
126#[CoversClass(Constraints::class)]
127#[UsesClass(QueryExecution::class)]
128#[UsesClass(QueryValidation::class)]
129#[UsesClass(ResultAssessment::class)]
130#[UsesClass(Deriver::class)]
131#[UsesClass(BasicBlock::class)]
132#[UsesClass(CallableGraph::class)]
133#[UsesClass(CallableIdentity::class)]
134#[UsesClass(Instruction::class)]
135#[UsesClass(Parameter::class)]
136#[UsesClass(Terminator::class)]
137#[UsesClass(ArgumentBinding::class)]
138#[UsesClass(ArgumentOrder::class)]
139#[UsesClass(Dispatch::class)]
140#[UsesClass(ParameterBinding::class)]
141#[UsesClass(TypeBinding::class)]
142#[UsesClass(TypeCheck::class)]
143#[UsesClass(Completion::class)]
144#[UsesClass(Context::class)]
145#[UsesClass(ObservationLimit::class)]
146#[UsesClass(StateJoin::class)]
147#[UsesClass(Unwinding::class)]
148#[UsesClass(Cell::class)]
149#[UsesClass(Components::class)]
150#[UsesClass(Discovery::class)]
151#[UsesClass(Key::class)]
152#[UsesClass(Table::class)]
153#[UsesClass(Dependencies::class)]
154#[UsesClass(InstructionTransfer::class)]
155#[UsesClass(Evaluator::class)]
156#[UsesClass(SlotReference::class)]
157#[UsesClass(ObservationCollector::class)]
158#[UsesClass(Conversions::class)]
159#[UsesClass(ScalarErrors::class)]
160#[UsesClass(State::class)]
161#[UsesClass(CompletionRecord::class)]
162#[UsesClass(Evaluation::class)]
163#[UsesClass(Invocation::class)]
164#[UsesClass(Isolation::class)]
165#[UsesClass(MemoryStep::class)]
166#[UsesClass(PureStep::class)]
167#[UsesClass(ReferenceAssignment::class)]
168#[UsesClass(Location::class)]
169#[UsesClass(Materialization::class)]
170#[UsesClass(Memory::class)]
171#[UsesClass(StorageCapture::class)]
172#[UsesClass(RefinementEvaluator::class)]
173#[UsesClass(Extensions::class)]
174#[UsesClass(ProviderExpansion::class)]
175#[UsesClass(Evaluators::class)]
176#[UsesClass(StateRegistry::class)]
177#[UsesClass(DeriverConfig::class)]
178#[UsesClass(EntryPoint::class)]
179#[UsesClass(Sources::class)]
180#[UsesClass(Path::class)]
181#[UsesClass(Snapshot::class)]
182#[UsesClass(Source::class)]
183#[UsesClass(TargetProfile::class)]
184#[UsesClass(Budget::class)]
185#[UsesClass(QueryScope::class)]
186#[UsesClass(ReturnQuery::class)]
187#[UsesClass(ResultRef::class)]
188#[UsesClass(SourceRef::class)]
189#[UsesClass(Alternative::class)]
190#[UsesClass(Assessment::class)]
191#[UsesClass(Derivation::class)]
192#[UsesClass(DerivationResult::class)]
193#[UsesClass(QueryEncoding::class)]
194#[UsesClass(ValueGraph::class)]
195#[UsesClass(Statistics::class)]
196#[UsesClass(StorageSnapshot::class)]
197#[UsesClass(Parser::class)]
198#[UsesClass(File::class)]
199#[UsesClass(Lowerer::class)]
200#[UsesClass(EffectInspection::class)]
201#[UsesClass(ExpressionLowering::class)]
202#[UsesClass(InstructionEmitter::class)]
203#[UsesClass(LoweringScope::class)]
204#[UsesClass(StatementLowering::class)]
205#[UsesClass(CallableSource::class)]
206#[UsesClass(Indexer::class)]
207#[UsesClass(Index::class)]
208#[UsesClass(Composition::class)]
209#[UsesClass(LineMap::class)]
210#[UsesClass(MagicContext::class)]
211#[UsesClass(AssignmentPatterns::class)]
212#[UsesClass(ClassScope::class)]
213#[UsesClass(TargetSyntax::class)]
214#[UsesClass(Arithmetic::class)]
215#[UsesClass(Comparison::class)]
216#[UsesClass(Identity::class)]
217#[UsesClass(Operations::class)]
218#[UsesClass(Term::class)]
219#[Small]
220final class ConstraintsTest extends TestCase
221{
222    public function testAssumePreservesTheSemanticContract(): void
223    {
224        $source = '<?php function target(int $x){if($x>0){if($x<=0)return "impossible";}return "ok";}';
225        $symbol = 'target';
226        $input = new Sources([new Source('fixture.php', $source)]);
227        $configuration = new DeriverConfig();
228        $contributions = new Contributions();
229        $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
230        $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
231        $contributions1 = $providers->contributions;
232        $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);
233        $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
234        $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
235        $snapshotId = $identity->id;
236        $input1 = $providers->input;
237        $parser = new Parser(new ParserConfig($target->version));
238        $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));
239        $program = new Index($snapshotId, $trees);
240        $result = (new QueryExecution($program, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program->diagnostics()))))->derive(new ReturnQuery($symbol));
241        self::assertSame('ok', $result->normalOutcomes[0]->values['return']->native());
242        self::assertSame('ok', $result->normalOutcomes[1]->values['return']->native());
243        self::assertSame([], $result->frontiers);
244    }
245    public function testComparisonNormalizesReversedIntegerBounds(): void
246    {
247        $constraints = new Constraints();
248        $state = new State();
249        $x = Term::parameter('x', 'int');
250        self::assertTrue($constraints->comparison($state, new Term(TermKind::Binary, '<', [Term::constant(3), $x]), true));
251        self::assertFalse($constraints->comparison($state, new Term(TermKind::Binary, '<=', [$x, Term::constant(3)]), true));
252    }
253    public function testRefineDoesNotAddFactsWithoutAProvider(): void
254    {
255        $state = new State();
256        self::assertTrue((new Constraints())->refine($state, Term::parameter('flag', 'bool'), true));
257        self::assertSame([], $state->constraints);
258    }
259    public function testBoundsIntersectsEqualitiesWithEarlierBounds(): void
260    {
261        $constraints = new Constraints();
262        $state = new State();
263        $x = Term::parameter('x', 'int');
264        self::assertTrue($constraints->bounds($state, $x, Term::constant(0), '>'));
265        self::assertFalse($constraints->bounds($state, $x, Term::constant(-1), '==='));
266    }
267    public function testBoundsPreservesExcludedConstants(): void
268    {
269        $constraints = new Constraints();
270        $state = new State();
271        $x = Term::parameter('x', 'int');
272        self::assertTrue($constraints->bounds($state, $x, Term::constant(1), '!=='));
273        self::assertFalse($constraints->bounds($state, $x, Term::constant(1), '==='));
274    }
275    public function testBoundsRejectsStrictFloatEqualityForAnInteger(): void
276    {
277        self::assertFalse((new Constraints())->bounds(new State(), Term::parameter('x', 'int'), Term::constant(1.0), '==='));
278    }
279    public function testOrderedRejectsBoundsOutsideTheIntegerDomain(): void
280    {
281        $bounds = ['min' => null, 'max' => null, 'equal' => null, 'excluded' => []];
282        $constraints = new Constraints();
283        self::assertFalse($constraints->ordered($bounds, 9223372036854775807, '>'));
284        self::assertFalse($constraints->ordered($bounds, -9223372036854775807 - 1, '<'));
285        self::assertTrue($constraints->ordered($bounds, 9223372036854775807 - 1, '>'));
286        self::assertSame(9223372036854775807, $bounds['min']);
287    }
288    #[DataProvider('providerConstantAssumptions')]
289    public function testAssumeChecksConcreteTruthWithoutAddingGuards(Term $predicate, bool $truth, bool $expected): void
290    {
291        $state = new State();
292        self::assertSame($expected, (new Constraints())->assume($state, $predicate, $truth));
293        self::assertSame([], $state->guard);
294    }
295    /**
296     * @return array<string,array{Term,bool,bool}>
297     */
298    public static function providerConstantAssumptions(): array
299    {
300        return ['true' => [Term::constant(true), true, true], 'false requested' => [Term::constant(true), false, false], 'false' => [Term::constant(false), false, true], 'null' => [Term::constant(null), true, false], 'empty array' => [Term::array([]), false, true]];
301    }
302    public function testAssumeSharesNegatedPredicateIdentityAndRejectsItsOpposite(): void
303    {
304        $state = new State();
305        $predicate = Term::parameter('flag', 'bool');
306        $constraints = new Constraints();
307        $negated = $constraints->assume($state, new Term(TermKind::Unary, '!', [$predicate]), true);
308        $repeated = $constraints->assume($state, $predicate, false);
309        $opposite = $constraints->assume($state, $predicate, true);
310        self::assertTrue($negated);
311        self::assertTrue($repeated);
312        self::assertFalse($opposite);
313        self::assertSame([(new Identity())->key($predicate) => false], $state->guard);
314    }
315    #[DataProvider('providerOrderedBounds')]
316    public function testOrderedIntersectsInclusiveIntegerAndFractionalEndpoints(int|float $number, string $operator, int|float|null $min, int|float|null $max): void
317    {
318        $bounds = ['min' => null, 'max' => null, 'equal' => null, 'excluded' => []];
319        self::assertTrue((new Constraints())->ordered($bounds, $number, $operator));
320        self::assertSame($min, $bounds['min']);
321        self::assertSame($max, $bounds['max']);
322    }
323    /**
324     * @return array<string,array{int|float,string,int|float|null,int|float|null}>
325     */
326    public static function providerOrderedBounds(): array
327    {
328        return ['greater integer' => [3, '>', 4, null], 'at least integer' => [3, '>=', 3, null], 'less integer' => [3, '<', null, 2], 'at most integer' => [3, '<=', null, 3], 'greater integral float' => [3.0, '>', 4.0, null], 'at least integral float' => [3.0, '>=', 3.0, null], 'less integral float' => [3.0, '<', null, 2.0], 'at most integral float' => [3.0, '<=', null, 3.0], 'greater fraction' => [3.5, '>', 4.0, null], 'at least fraction' => [3.5, '>=', 4.0, null], 'less fraction' => [3.5, '<', null, 3.0], 'at most fraction' => [3.5, '<=', null, 3.0], 'negative fraction lower' => [-3.5, '>', -3.0, null], 'negative fraction upper' => [-3.5, '<', null, -4.0], 'max inclusive' => [PHP_INT_MAX, '>=', PHP_INT_MAX, null], 'min inclusive' => [PHP_INT_MIN, '<=', null, PHP_INT_MIN], 'unrecognized' => [3, '==', null, null]];
329    }
330    public function testOrderedCannotWeakenExistingEndpoints(): void
331    {
332        $bounds = ['min' => 5, 'max' => 8, 'equal' => null, 'excluded' => []];
333        $constraints = new Constraints();
334        self::assertTrue($constraints->ordered($bounds, 1, '>'));
335        self::assertTrue($constraints->ordered($bounds, 20, '<'));
336        self::assertSame(5, $bounds['min']);
337        self::assertSame(8, $bounds['max']);
338    }
339    #[DataProvider('providerComparisonOrientation')]
340    public function testComparisonNormalizesOrientationAndFalseBranches(string $operator, bool $truth, bool $reversed, int|null $min, int|null $max): void
341    {
342        $state = new State();
343        $x = Term::parameter('x', 'int');
344        $operands = array_reverse([$x, Term::constant(3)]);
345        $arrangements = [[$x, Term::constant(3)], $operands];
346        $operands = $arrangements[(int) $reversed];
347        self::assertTrue((new Constraints())->comparison($state, new Term(TermKind::Binary, $operator, $operands), $truth));
348        $bounds = $state->constraints[(new Identity())->key($x)];
349        self::assertSame($min, $bounds['min']);
350        self::assertSame($max, $bounds['max']);
351    }
352    /**
353     * @return array<string,array{string,bool,bool,int|null,int|null}>
354     */
355    public static function providerComparisonOrientation(): array
356    {
357        return ['not less' => ['<', false, false, 3, null], 'not at most' => ['<=', false, false, 4, null], 'not greater' => ['>', false, false, null, 3], 'not at least' => ['>=', false, false, null, 2], 'reversed less' => ['<', true, true, 4, null], 'reversed at most' => ['<=', true, true, 3, null], 'reversed greater' => ['>', true, true, null, 2], 'reversed at least' => ['>=', true, true, null, 3], 'false inequality' => ['!==', false, false, 3, 3]];
358    }
359    public function testBoundsPreservesAnEqualityAndRejectsItsExclusion(): void
360    {
361        $state = new State();
362        $x = Term::parameter('x', 'int');
363        $constraints = new Constraints();
364        $number = Term::constant(3);
365        self::assertTrue($constraints->bounds($state, $x, $number, '==='));
366        self::assertSame($number, $state->constraints[(new Identity())->key($x)]['equal']);
367        self::assertFalse($constraints->bounds($state, $x, $number, '!=='));
368    }
369    public function testBoundsKeepsEqualityInsideEarlierLimits(): void
370    {
371        $state = new State();
372        $x = Term::parameter('x', 'int');
373        $constraints = new Constraints();
374        self::assertTrue($constraints->bounds($state, $x, Term::constant(1), '>='));
375        self::assertTrue($constraints->bounds($state, $x, Term::constant(9), '<='));
376        self::assertTrue($constraints->bounds($state, $x, Term::constant(4), '==='));
377        self::assertSame(4, $state->constraints[(new Identity())->key($x)]['min']);
378        self::assertSame(4, $state->constraints[(new Identity())->key($x)]['max']);
379    }
380    public function testBoundsIgnoresNonNumericConstantsAndStrictFloatExclusions(): void
381    {
382        $state = new State();
383        $x = Term::parameter('x', 'int');
384        $constraints = new Constraints();
385        self::assertTrue($constraints->bounds($state, $x, Term::constant('x'), '==='));
386        $beforeCount = count($state->constraints);
387        self::assertTrue($constraints->bounds($state, $x, Term::constant(3.0), '!=='));
388        self::assertSame([], $state->constraints[(new Identity())->key($x)]['excluded']);
389        self::assertSame(0, $beforeCount);
390    }
391    public function testComparisonLeavesNonIntegerAndUnresolvedOperandsUnconstrained(): void
392    {
393        $state = new State();
394        $constraints = new Constraints();
395        self::assertTrue($constraints->comparison($state, Term::parameter('x'), true));
396        self::assertTrue($constraints->comparison($state, new Term(TermKind::Binary, '<', [Term::parameter('x', 'float'), Term::constant(3)]), true));
397        self::assertTrue($constraints->comparison($state, new Term(TermKind::Binary, '<', [Term::parameter('x', 'int'), Term::parameter('y', 'int')]), true));
398        self::assertSame([], $state->constraints);
399    }
400    public function testRefineSkipsOtherProvidersAndAppliesEveryGuaranteedPredicate(): void
401    {
402        $other = self::createStub(Provider::class);
403        $other->method('id')->willReturn('other');
404        $other->method('version')->willReturn('1');
405        $x = Term::parameter('x', 'int');
406        $lower = self::createStub(RefinementEvaluator::class);
407        $lower->method('id')->willReturn('lower');
408        $lower->method('version')->willReturn('1');
409        $lower->method('refine')->willReturn(new Term(TermKind::Binary, '>=', [$x, Term::constant(3)]));
410        $upper = self::createStub(RefinementEvaluator::class);
411        $upper->method('id')->willReturn('upper');
412        $upper->method('version')->willReturn('1');
413        $upper->method('refine')->willReturn(new Term(TermKind::Binary, '<=', [$x, Term::constant(8)]));
414        $source = '<?php function target(){return 1;}';
415        $budget = new Budget();
416        $configuration = new DeriverConfig();
417        $contributions = new Contributions(providers: [$other, $lower, $upper]);
418        $input = new Sources([new Source('fixture.php', $source)]);
419        $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
420        $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
421        $contributions1 = $providers->contributions;
422        $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);
423        $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
424        $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
425        $snapshotId = $identity->id;
426        $input1 = $providers->input;
427        $parser = new Parser(new ParserConfig($target->version));
428        $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));
429        $program1 = new Index($snapshotId, $trees);
430        $execution = new QueryExecution($program1, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program1->diagnostics())));
431        $snapshotId1 = 'test';
432        $input2 = new Sources([new Source('fixture.php', $source)]);
433        $profile = $execution->configuration->target;
434        $parser1 = new Parser(new ParserConfig($profile->version));
435        $trees1 = array_map(static fn (Source $source2): File => (new Resolver())->resolve($parser1->parse(new Source(Path::normalize($source2->path), $source2->contents, $source2->declarationsOnly))), iterator_to_array($input2, false));
436        $program = new Index($snapshotId1, $trees1);
437        $context = new Context($program, new ReturnQuery('target', budget: $budget), $execution->configuration, $execution->evaluators);
438        $state = new State();
439        self::assertTrue((new Constraints($context))->refine($state, Term::parameter('condition', 'bool'), true));
440        $bounds = $state->constraints[(new Identity())->key($x)];
441        self::assertSame(3, $bounds['min']);
442        self::assertSame(8, $bounds['max']);
443        self::assertCount(2, $state->guard);
444        self::assertSame([], $context->frontiers);
445    }
446    #[DataProvider('providerRefinementResponses')]
447    public function testRefinePreservesOptionalPredicatesAndImpossibleImplications(?Term $implied, bool $expected, int $guards): void
448    {
449        $provider = self::createStub(RefinementEvaluator::class);
450        $provider->method('id')->willReturn('refinement');
451        $provider->method('version')->willReturn('1');
452        $provider->method('refine')->willReturn($implied);
453        $source = '<?php function target(){return 1;}';
454        $budget = new Budget();
455        $configuration = new DeriverConfig();
456        $contributions = new Contributions(providers: [$provider]);
457        $input = new Sources([new Source('fixture.php', $source)]);
458        $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
459        $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
460        $contributions1 = $providers->contributions;
461        $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);
462        $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
463        $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
464        $snapshotId = $identity->id;
465        $input1 = $providers->input;
466        $parser = new Parser(new ParserConfig($target->version));
467        $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));
468        $program1 = new Index($snapshotId, $trees);
469        $execution = new QueryExecution($program1, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program1->diagnostics())));
470        $snapshotId1 = 'test';
471        $input2 = new Sources([new Source('fixture.php', $source)]);
472        $profile = $execution->configuration->target;
473        $parser1 = new Parser(new ParserConfig($profile->version));
474        $trees1 = array_map(static fn (Source $source2): File => (new Resolver())->resolve($parser1->parse(new Source(Path::normalize($source2->path), $source2->contents, $source2->declarationsOnly))), iterator_to_array($input2, false));
475        $program = new Index($snapshotId1, $trees1);
476        $context = new Context($program, new ReturnQuery('target', budget: $budget), $execution->configuration, $execution->evaluators);
477        $state = new State();
478        self::assertSame($expected, (new Constraints($context))->refine($state, Term::parameter('condition'), false));
479        self::assertCount($guards, $state->guard);
480        self::assertSame([], $context->frontiers);
481    }
482    /**
483     * @return iterable<string,array{Term|null,bool,int}>
484     */
485    public static function providerRefinementResponses(): iterable
486    {
487        yield 'not applicable' => [null, true, 0];
488        yield 'impossible' => [Term::constant(false), false, 0];
489        yield 'guaranteed' => [Term::constant(true), true, 0];
490        yield 'failure spelling in a literal' => [Term::constant('EVALUATOR_CONTRACT_VIOLATION'), true, 0];
491        yield 'ordinary residual' => [Term::opaque('UNKNOWN_PREDICATE', 'bool'), true, 1];
492    }
493    public function testRefineForwardsTheObservedPredicateAndPolarity(): void
494    {
495        $predicate = Term::parameter('condition', 'bool');
496        $provider = self::createMock(RefinementEvaluator::class);
497        $provider->method('id')->willReturn('refinement');
498        $provider->method('version')->willReturn('1');
499        $provider->expects(self::once())->method('refine')->with(self::identicalTo($predicate), false)->willReturn(null);
500        $source = '<?php function target(){return 1;}';
501        $budget = new Budget();
502        $configuration = new DeriverConfig();
503        $contributions = new Contributions(providers: [$provider]);
504        $input = new Sources([new Source('fixture.php', $source)]);
505        $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
506        $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
507        $contributions1 = $providers->contributions;
508        $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);
509        $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
510        $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
511        $snapshotId = $identity->id;
512        $input1 = $providers->input;
513        $parser = new Parser(new ParserConfig($target->version));
514        $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));
515        $program1 = new Index($snapshotId, $trees);
516        $execution = new QueryExecution($program1, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program1->diagnostics())));
517        $snapshotId1 = 'test';
518        $input2 = new Sources([new Source('fixture.php', $source)]);
519        $profile = $execution->configuration->target;
520        $parser1 = new Parser(new ParserConfig($profile->version));
521        $trees1 = array_map(static fn (Source $source2): File => (new Resolver())->resolve($parser1->parse(new Source(Path::normalize($source2->path), $source2->contents, $source2->declarationsOnly))), iterator_to_array($input2, false));
522        $program = new Index($snapshotId1, $trees1);
523        $context = new Context($program, new ReturnQuery('target', budget: $budget), $execution->configuration, $execution->evaluators);
524        self::assertTrue((new Constraints($context))->refine(new State(), $predicate, false));
525    }
526    public function testRefinePropagatesProviderFailure(): void
527    {
528        $provider = self::createStub(RefinementEvaluator::class);
529        $provider->method('id')->willReturn('broken');
530        $provider->method('version')->willReturn('1');
531        $provider->method('refine')->willThrowException(new RuntimeException('provider failed'));
532        $source = '<?php function target(){return 1;}';
533        $budget = new Budget();
534        $configuration = new DeriverConfig();
535        $contributions = new Contributions(providers: [$provider]);
536        $input = new Sources([new Source('fixture.php', $source)]);
537        $target = new TargetProfile($configuration->phpVersion, $configuration->integerBits, $configuration->floatPrecision);
538        $providers = new ProviderExpansion($input, array_map(Term::fromNative(...), $configuration->environment), $contributions);
539        $contributions1 = $providers->contributions;
540        $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);
541        $settings = new EvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators, array_map((new MicroEvaluatorConversion())->convert(...), $configuration->evaluators));
542        $identity = new SnapshotIdentity($providers->input, $settings, $evaluators, $providers->manifest);
543        $snapshotId = $identity->id;
544        $input1 = $providers->input;
545        $parser = new Parser(new ParserConfig($target->version));
546        $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));
547        $program1 = new Index($snapshotId, $trees);
548        $execution = new QueryExecution($program1, new ExecutionEvaluatorConfig($target, $providers->environment, $configuration->standardEvaluators), $evaluators, $identity->snapshot(array_map(Frontier::fromDiagnostic(...), $program1->diagnostics())));
549        $snapshotId1 = 'test';
550        $input2 = new Sources([new Source('fixture.php', $source)]);
551        $profile = $execution->configuration->target;
552        $parser1 = new Parser(new ParserConfig($profile->version));
553        $trees1 = array_map(static fn (Source $source2): File => (new Resolver())->resolve($parser1->parse(new Source(Path::normalize($source2->path), $source2->contents, $source2->declarationsOnly))), iterator_to_array($input2, false));
554        $program = new Index($snapshotId1, $trees1);
555        $context = new Context($program, new ReturnQuery('target', budget: $budget), $execution->configuration, $execution->evaluators);
556        $state = new State();
557        $this->expectException(RuntimeException::class);
558        $this->expectExceptionMessage('provider failed');
559        (new Constraints($context))->refine($state, Term::parameter('condition'), true);
560    }
561    #[DataProvider('providerNonComparisonTerms')]
562    public function testComparisonLeavesIncompleteAndOtherOperationsUnconstrained(Term $predicate): void
563    {
564        $state = new State();
565        self::assertTrue((new Constraints())->comparison($state, $predicate, true));
566        self::assertSame([], $state->constraints);
567    }
568    /**
569     * @return iterable<string,array{Term}>
570     */
571    public static function providerNonComparisonTerms(): iterable
572    {
573        $x = Term::parameter('x', 'int');
574        yield 'missing right' => [new Term(TermKind::Binary, '<', [$x])];
575        yield 'missing left' => [new Term(TermKind::Binary, '<', [1 => Term::constant(3)])];
576        yield 'invalid operator' => [new Term(TermKind::Binary, null, [$x, Term::constant(3)])];
577        yield 'other operation' => [new Term(TermKind::Intrinsic, '<', [$x, Term::constant(3)])];
578        yield 'text endpoint' => [new Term(TermKind::Binary, '<', [$x, Term::constant('3')])];
579        yield 'boolean endpoint' => [new Term(TermKind::Binary, '<', [$x, Term::constant(true)])];
580        yield 'symbolic numeric payload' => [new Term(TermKind::Binary, '<', [$x, new Term(TermKind::Opaque, 3)])];
581        yield 'two constants' => [new Term(TermKind::Binary, '<', [Term::constant(2), Term::constant(3)])];
582    }
583    public function testAssumeDoesNotTreatEveryUnaryOperationAsLogicalNegation(): void
584    {
585        $value = Term::parameter('x', 'int');
586        $predicate = new Term(TermKind::Unary, '~', [$value]);
587        $state = new State();
588        self::assertTrue((new Constraints())->assume($state, $predicate, false));
589        self::assertSame([(new Identity())->key($predicate) => false], $state->guard);
590    }
591    #[DataProvider('providerImpossibleIntegerBounds')]
592    public function testBoundsRejectsStrictComparisonsPastIntegerExtrema(int $number, string $operator): void
593    {
594        $state = new State();
595        self::assertFalse((new Constraints())->bounds($state, Term::parameter('x', 'int'), Term::constant($number), $operator));
596        self::assertSame([], $state->constraints);
597    }
598    /**
599     * @return iterable<string,array{int,string}>
600     */
601    public static function providerImpossibleIntegerBounds(): iterable
602    {
603        yield 'above maximum' => [PHP_INT_MAX, '>'];
604        yield 'below minimum' => [PHP_INT_MIN, '<'];
605    }
606    public function testComparisonRoundsAFractionalLowerBoundAwayFromTheExcludedInteger(): void
607    {
608        $state = new State();
609        $x = Term::parameter('x', 'int');
610        self::assertTrue((new Constraints())->comparison($state, new Term(TermKind::Binary, '>=', [$x, Term::constant(3.2)]), true));
611        self::assertSame(4.0, $state->constraints[(new Identity())->key($x)]['min']);
612    }
613}
614