1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use ArrayAccess;
6: use Closure;
7: use DivisionByZeroError;
8: use Override;
9: use PhpParser\Comment\Doc;
10: use PhpParser\Modifiers;
11: use PhpParser\Node;
12: use PhpParser\Node\Arg;
13: use PhpParser\Node\AttributeGroup;
14: use PhpParser\Node\ComplexType;
15: use PhpParser\Node\Expr;
16: use PhpParser\Node\Expr\Array_;
17: use PhpParser\Node\Expr\ArrayDimFetch;
18: use PhpParser\Node\Expr\Assign;
19: use PhpParser\Node\Expr\AssignRef;
20: use PhpParser\Node\Expr\BinaryOp;
21: use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
22: use PhpParser\Node\Expr\BinaryOp\BooleanOr;
23: use PhpParser\Node\Expr\BinaryOp\Coalesce;
24: use PhpParser\Node\Expr\BooleanNot;
25: use PhpParser\Node\Expr\CallLike;
26: use PhpParser\Node\Expr\Cast;
27: use PhpParser\Node\Expr\ConstFetch;
28: use PhpParser\Node\Expr\ErrorSuppress;
29: use PhpParser\Node\Expr\Exit_;
30: use PhpParser\Node\Expr\FuncCall;
31: use PhpParser\Node\Expr\Instanceof_;
32: use PhpParser\Node\Expr\List_;
33: use PhpParser\Node\Expr\MethodCall;
34: use PhpParser\Node\Expr\New_;
35: use PhpParser\Node\Expr\PropertyFetch;
36: use PhpParser\Node\Expr\StaticCall;
37: use PhpParser\Node\Expr\StaticPropertyFetch;
38: use PhpParser\Node\Expr\Ternary;
39: use PhpParser\Node\Expr\Variable;
40: use PhpParser\Node\Identifier;
41: use PhpParser\Node\Name;
42: use PhpParser\Node\Stmt\Break_;
43: use PhpParser\Node\Stmt\Class_;
44: use PhpParser\Node\Stmt\Continue_;
45: use PhpParser\Node\Stmt\Do_;
46: use PhpParser\Node\Stmt\Echo_;
47: use PhpParser\Node\Stmt\For_;
48: use PhpParser\Node\Stmt\Foreach_;
49: use PhpParser\Node\Stmt\If_;
50: use PhpParser\Node\Stmt\InlineHTML;
51: use PhpParser\Node\Stmt\Return_;
52: use PhpParser\Node\Stmt\Static_;
53: use PhpParser\Node\Stmt\Switch_;
54: use PhpParser\Node\Stmt\TryCatch;
55: use PhpParser\Node\Stmt\Unset_;
56: use PhpParser\Node\Stmt\While_;
57: use PhpParser\NodeFinder;
58: use PhpParser\NodeTraverser;
59: use PhpParser\NodeVisitor\CloningVisitor;
60: use PhpParser\NodeVisitorAbstract;
61: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClass;
62: use PHPStan\BetterReflection\Reflection\ReflectionEnum;
63: use PHPStan\BetterReflection\Reflector\Reflector;
64: use PHPStan\BetterReflection\SourceLocator\Ast\Strategy\NodeToReflection;
65: use PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
66: use PHPStan\DependencyInjection\AutowiredParameter;
67: use PHPStan\DependencyInjection\AutowiredService;
68: use PHPStan\DependencyInjection\Reflection\ClassReflectionExtensionRegistryProvider;
69: use PHPStan\DependencyInjection\Type\DynamicThrowTypeExtensionProvider;
70: use PHPStan\DependencyInjection\Type\ParameterClosureTypeExtensionProvider;
71: use PHPStan\DependencyInjection\Type\ParameterOutTypeExtensionProvider;
72: use PHPStan\File\FileHelper;
73: use PHPStan\File\FileReader;
74: use PHPStan\Node\BooleanAndNode;
75: use PHPStan\Node\BooleanOrNode;
76: use PHPStan\Node\BreaklessWhileLoopNode;
77: use PHPStan\Node\CatchWithUnthrownExceptionNode;
78: use PHPStan\Node\ClassConstantsNode;
79: use PHPStan\Node\ClassMethodsNode;
80: use PHPStan\Node\ClassPropertiesNode;
81: use PHPStan\Node\ClassPropertyNode;
82: use PHPStan\Node\ClassStatementsGatherer;
83: use PHPStan\Node\ClosureReturnStatementsNode;
84: use PHPStan\Node\DoWhileLoopConditionNode;
85: use PHPStan\Node\ExecutionEndNode;
86: use PHPStan\Node\Expr\AlwaysRememberedExpr;
87: use PHPStan\Node\Expr\ExistingArrayDimFetch;
88: use PHPStan\Node\Expr\GetIterableKeyTypeExpr;
89: use PHPStan\Node\Expr\GetIterableValueTypeExpr;
90: use PHPStan\Node\Expr\GetOffsetValueTypeExpr;
91: use PHPStan\Node\Expr\OriginalPropertyTypeExpr;
92: use PHPStan\Node\Expr\PropertyInitializationExpr;
93: use PHPStan\Node\Expr\SetExistingOffsetValueTypeExpr;
94: use PHPStan\Node\Expr\SetOffsetValueTypeExpr;
95: use PHPStan\Node\Expr\TypeExpr;
96: use PHPStan\Node\Expr\UnsetOffsetExpr;
97: use PHPStan\Node\FinallyExitPointsNode;
98: use PHPStan\Node\FunctionCallableNode;
99: use PHPStan\Node\FunctionReturnStatementsNode;
100: use PHPStan\Node\InArrowFunctionNode;
101: use PHPStan\Node\InClassMethodNode;
102: use PHPStan\Node\InClassNode;
103: use PHPStan\Node\InClosureNode;
104: use PHPStan\Node\InForeachNode;
105: use PHPStan\Node\InFunctionNode;
106: use PHPStan\Node\InPropertyHookNode;
107: use PHPStan\Node\InstantiationCallableNode;
108: use PHPStan\Node\InTraitNode;
109: use PHPStan\Node\InvalidateExprNode;
110: use PHPStan\Node\LiteralArrayItem;
111: use PHPStan\Node\LiteralArrayNode;
112: use PHPStan\Node\MatchExpressionArm;
113: use PHPStan\Node\MatchExpressionArmBody;
114: use PHPStan\Node\MatchExpressionArmCondition;
115: use PHPStan\Node\MatchExpressionNode;
116: use PHPStan\Node\MethodCallableNode;
117: use PHPStan\Node\MethodReturnStatementsNode;
118: use PHPStan\Node\NoopExpressionNode;
119: use PHPStan\Node\PropertyAssignNode;
120: use PHPStan\Node\PropertyHookReturnStatementsNode;
121: use PHPStan\Node\PropertyHookStatementNode;
122: use PHPStan\Node\ReturnStatement;
123: use PHPStan\Node\StaticMethodCallableNode;
124: use PHPStan\Node\UnreachableStatementNode;
125: use PHPStan\Node\VariableAssignNode;
126: use PHPStan\Node\VarTagChangedExpressionTypeNode;
127: use PHPStan\Parser\ArrowFunctionArgVisitor;
128: use PHPStan\Parser\ClosureArgVisitor;
129: use PHPStan\Parser\ImmediatelyInvokedClosureVisitor;
130: use PHPStan\Parser\LineAttributesVisitor;
131: use PHPStan\Parser\Parser;
132: use PHPStan\Php\PhpVersion;
133: use PHPStan\PhpDoc\PhpDocInheritanceResolver;
134: use PHPStan\PhpDoc\ResolvedPhpDocBlock;
135: use PHPStan\PhpDoc\StubPhpDocProvider;
136: use PHPStan\PhpDoc\Tag\VarTag;
137: use PHPStan\Reflection\Assertions;
138: use PHPStan\Reflection\AttributeReflectionFactory;
139: use PHPStan\Reflection\Callables\CallableParametersAcceptor;
140: use PHPStan\Reflection\Callables\SimpleImpurePoint;
141: use PHPStan\Reflection\Callables\SimpleThrowPoint;
142: use PHPStan\Reflection\ClassReflection;
143: use PHPStan\Reflection\Deprecation\DeprecationProvider;
144: use PHPStan\Reflection\ExtendedMethodReflection;
145: use PHPStan\Reflection\ExtendedParameterReflection;
146: use PHPStan\Reflection\ExtendedParametersAcceptor;
147: use PHPStan\Reflection\FunctionReflection;
148: use PHPStan\Reflection\InitializerExprContext;
149: use PHPStan\Reflection\InitializerExprTypeResolver;
150: use PHPStan\Reflection\MethodReflection;
151: use PHPStan\Reflection\Native\NativeMethodReflection;
152: use PHPStan\Reflection\Native\NativeParameterReflection;
153: use PHPStan\Reflection\ParameterReflection;
154: use PHPStan\Reflection\ParametersAcceptor;
155: use PHPStan\Reflection\ParametersAcceptorSelector;
156: use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection;
157: use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
158: use PHPStan\Reflection\Php\PhpMethodReflection;
159: use PHPStan\Reflection\Php\PhpPropertyReflection;
160: use PHPStan\Reflection\ReflectionProvider;
161: use PHPStan\Reflection\SignatureMap\SignatureMapProvider;
162: use PHPStan\Rules\Properties\ReadWritePropertiesExtensionProvider;
163: use PHPStan\ShouldNotHappenException;
164: use PHPStan\TrinaryLogic;
165: use PHPStan\Type\Accessory\AccessoryArrayListType;
166: use PHPStan\Type\Accessory\HasOffsetValueType;
167: use PHPStan\Type\Accessory\NonEmptyArrayType;
168: use PHPStan\Type\ArrayType;
169: use PHPStan\Type\ClosureType;
170: use PHPStan\Type\Constant\ConstantArrayType;
171: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
172: use PHPStan\Type\Constant\ConstantBooleanType;
173: use PHPStan\Type\Constant\ConstantIntegerType;
174: use PHPStan\Type\Constant\ConstantStringType;
175: use PHPStan\Type\ErrorType;
176: use PHPStan\Type\FileTypeMapper;
177: use PHPStan\Type\GeneralizePrecision;
178: use PHPStan\Type\Generic\TemplateTypeHelper;
179: use PHPStan\Type\Generic\TemplateTypeMap;
180: use PHPStan\Type\Generic\TemplateTypeVariance;
181: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
182: use PHPStan\Type\IntegerType;
183: use PHPStan\Type\IntersectionType;
184: use PHPStan\Type\MixedType;
185: use PHPStan\Type\NeverType;
186: use PHPStan\Type\NullType;
187: use PHPStan\Type\ObjectType;
188: use PHPStan\Type\ObjectWithoutClassType;
189: use PHPStan\Type\ParserNodeTypeToPHPStanType;
190: use PHPStan\Type\ResourceType;
191: use PHPStan\Type\StaticType;
192: use PHPStan\Type\StaticTypeFactory;
193: use PHPStan\Type\StringType;
194: use PHPStan\Type\ThisType;
195: use PHPStan\Type\Type;
196: use PHPStan\Type\TypeCombinator;
197: use PHPStan\Type\TypeTraverser;
198: use PHPStan\Type\TypeUtils;
199: use PHPStan\Type\UnionType;
200: use ReflectionProperty;
201: use Throwable;
202: use Traversable;
203: use TypeError;
204: use UnhandledMatchError;
205: use function array_fill_keys;
206: use function array_filter;
207: use function array_key_exists;
208: use function array_key_last;
209: use function array_keys;
210: use function array_map;
211: use function array_merge;
212: use function array_pop;
213: use function array_reverse;
214: use function array_slice;
215: use function array_values;
216: use function base64_decode;
217: use function count;
218: use function in_array;
219: use function is_array;
220: use function is_int;
221: use function is_string;
222: use function ksort;
223: use function sprintf;
224: use function str_starts_with;
225: use function strtolower;
226: use function trim;
227: use function usort;
228: use const PHP_VERSION_ID;
229: use const SORT_NUMERIC;
230:
231: #[AutowiredService]
232: final class NodeScopeResolver
233: {
234:
235: private const LOOP_SCOPE_ITERATIONS = 3;
236: private const GENERALIZE_AFTER_ITERATION = 1;
237:
238: /** @var bool[] filePath(string) => bool(true) */
239: private array $analysedFiles = [];
240:
241: /** @var array<string, true> */
242: private array $earlyTerminatingMethodNames;
243:
244: /** @var array<string, true> */
245: private array $calledMethodStack = [];
246:
247: /** @var array<string, MutatingScope|null> */
248: private array $calledMethodResults = [];
249:
250: /**
251: * @param string[][] $earlyTerminatingMethodCalls className(string) => methods(string[])
252: * @param array<int, string> $earlyTerminatingFunctionCalls
253: * @param string[] $universalObjectCratesClasses
254: */
255: public function __construct(
256: private readonly ReflectionProvider $reflectionProvider,
257: private readonly InitializerExprTypeResolver $initializerExprTypeResolver,
258: #[AutowiredParameter(ref: '@nodeScopeResolverReflector')]
259: private readonly Reflector $reflector,
260: private readonly ClassReflectionExtensionRegistryProvider $classReflectionExtensionRegistryProvider,
261: private readonly ParameterOutTypeExtensionProvider $parameterOutTypeExtensionProvider,
262: #[AutowiredParameter(ref: '@defaultAnalysisParser')]
263: private readonly Parser $parser,
264: private readonly FileTypeMapper $fileTypeMapper,
265: private readonly StubPhpDocProvider $stubPhpDocProvider,
266: private readonly PhpVersion $phpVersion,
267: private readonly SignatureMapProvider $signatureMapProvider,
268: private readonly DeprecationProvider $deprecationProvider,
269: private readonly AttributeReflectionFactory $attributeReflectionFactory,
270: private readonly PhpDocInheritanceResolver $phpDocInheritanceResolver,
271: private readonly FileHelper $fileHelper,
272: private readonly TypeSpecifier $typeSpecifier,
273: private readonly DynamicThrowTypeExtensionProvider $dynamicThrowTypeExtensionProvider,
274: private readonly ReadWritePropertiesExtensionProvider $readWritePropertiesExtensionProvider,
275: private readonly ParameterClosureTypeExtensionProvider $parameterClosureTypeExtensionProvider,
276: private readonly ScopeFactory $scopeFactory,
277: #[AutowiredParameter]
278: private readonly bool $polluteScopeWithLoopInitialAssignments,
279: #[AutowiredParameter]
280: private readonly bool $polluteScopeWithAlwaysIterableForeach,
281: #[AutowiredParameter]
282: private readonly bool $polluteScopeWithBlock,
283: #[AutowiredParameter]
284: private readonly array $earlyTerminatingMethodCalls,
285: #[AutowiredParameter]
286: private readonly array $earlyTerminatingFunctionCalls,
287: #[AutowiredParameter]
288: private readonly array $universalObjectCratesClasses,
289: #[AutowiredParameter(ref: '%exceptions.implicitThrows%')]
290: private readonly bool $implicitThrows,
291: #[AutowiredParameter]
292: private readonly bool $treatPhpDocTypesAsCertain,
293: private readonly bool $narrowMethodScopeFromConstructor = true,
294: )
295: {
296: $earlyTerminatingMethodNames = [];
297: foreach ($this->earlyTerminatingMethodCalls as $methodNames) {
298: foreach ($methodNames as $methodName) {
299: $earlyTerminatingMethodNames[strtolower($methodName)] = true;
300: }
301: }
302: $this->earlyTerminatingMethodNames = $earlyTerminatingMethodNames;
303: }
304:
305: /**
306: * @api
307: * @param string[] $files
308: */
309: public function setAnalysedFiles(array $files): void
310: {
311: $this->analysedFiles = array_fill_keys($files, true);
312: }
313:
314: /**
315: * @api
316: * @param Node[] $nodes
317: * @param callable(Node $node, Scope $scope): void $nodeCallback
318: */
319: public function processNodes(
320: array $nodes,
321: MutatingScope $scope,
322: callable $nodeCallback,
323: ): void
324: {
325: $alreadyTerminated = false;
326: foreach ($nodes as $i => $node) {
327: if (
328: !$node instanceof Node\Stmt
329: || ($alreadyTerminated && !($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassLike))
330: ) {
331: continue;
332: }
333:
334: $statementResult = $this->processStmtNode($node, $scope, $nodeCallback, StatementContext::createTopLevel());
335: $scope = $statementResult->getScope();
336: if ($alreadyTerminated || !$statementResult->isAlwaysTerminating()) {
337: continue;
338: }
339:
340: $alreadyTerminated = true;
341: $nextStmts = $this->getNextUnreachableStatements(array_slice($nodes, $i + 1), true);
342: $this->processUnreachableStatement($nextStmts, $scope, $nodeCallback);
343: }
344: }
345:
346: /**
347: * @param Node\Stmt[] $nextStmts
348: * @param callable(Node $node, Scope $scope): void $nodeCallback
349: */
350: private function processUnreachableStatement(array $nextStmts, MutatingScope $scope, callable $nodeCallback): void
351: {
352: if ($nextStmts === []) {
353: return;
354: }
355:
356: $unreachableStatement = null;
357: $nextStatements = [];
358:
359: foreach ($nextStmts as $key => $nextStmt) {
360: if ($key === 0) {
361: $unreachableStatement = $nextStmt;
362: continue;
363: }
364:
365: $nextStatements[] = $nextStmt;
366: }
367:
368: if (!$unreachableStatement instanceof Node\Stmt) {
369: return;
370: }
371:
372: $nodeCallback(new UnreachableStatementNode($unreachableStatement, $nextStatements), $scope);
373: }
374:
375: /**
376: * @api
377: * @param Node\Stmt[] $stmts
378: * @param callable(Node $node, Scope $scope): void $nodeCallback
379: */
380: public function processStmtNodes(
381: Node $parentNode,
382: array $stmts,
383: MutatingScope $scope,
384: callable $nodeCallback,
385: StatementContext $context,
386: ): StatementResult
387: {
388: $exitPoints = [];
389: $throwPoints = [];
390: $impurePoints = [];
391: $alreadyTerminated = false;
392: $hasYield = false;
393: $stmtCount = count($stmts);
394: $shouldCheckLastStatement = $parentNode instanceof Node\Stmt\Function_
395: || $parentNode instanceof Node\Stmt\ClassMethod
396: || $parentNode instanceof PropertyHookStatementNode
397: || $parentNode instanceof Expr\Closure;
398: foreach ($stmts as $i => $stmt) {
399: if ($alreadyTerminated && !($stmt instanceof Node\Stmt\Function_ || $stmt instanceof Node\Stmt\ClassLike)) {
400: continue;
401: }
402:
403: $isLast = $i === $stmtCount - 1;
404: $statementResult = $this->processStmtNode(
405: $stmt,
406: $scope,
407: $nodeCallback,
408: $context,
409: );
410: $scope = $statementResult->getScope();
411: $hasYield = $hasYield || $statementResult->hasYield();
412:
413: if ($shouldCheckLastStatement && $isLast) {
414: $endStatements = $statementResult->getEndStatements();
415: if (count($endStatements) > 0) {
416: foreach ($endStatements as $endStatement) {
417: $endStatementResult = $endStatement->getResult();
418: $nodeCallback(new ExecutionEndNode(
419: $endStatement->getStatement(),
420: new StatementResult(
421: $endStatementResult->getScope(),
422: $hasYield,
423: $endStatementResult->isAlwaysTerminating(),
424: $endStatementResult->getExitPoints(),
425: $endStatementResult->getThrowPoints(),
426: $endStatementResult->getImpurePoints(),
427: ),
428: $parentNode->getReturnType() !== null,
429: ), $endStatementResult->getScope());
430: }
431: } else {
432: $nodeCallback(new ExecutionEndNode(
433: $stmt,
434: new StatementResult(
435: $scope,
436: $hasYield,
437: $statementResult->isAlwaysTerminating(),
438: $statementResult->getExitPoints(),
439: $statementResult->getThrowPoints(),
440: $statementResult->getImpurePoints(),
441: ),
442: $parentNode->getReturnType() !== null,
443: ), $scope);
444: }
445: }
446:
447: $exitPoints = array_merge($exitPoints, $statementResult->getExitPoints());
448: $throwPoints = array_merge($throwPoints, $statementResult->getThrowPoints());
449: $impurePoints = array_merge($impurePoints, $statementResult->getImpurePoints());
450:
451: if ($alreadyTerminated || !$statementResult->isAlwaysTerminating()) {
452: continue;
453: }
454:
455: $alreadyTerminated = true;
456: $nextStmts = $this->getNextUnreachableStatements(array_slice($stmts, $i + 1), $parentNode instanceof Node\Stmt\Namespace_);
457: $this->processUnreachableStatement($nextStmts, $scope, $nodeCallback);
458: }
459:
460: $statementResult = new StatementResult($scope, $hasYield, $alreadyTerminated, $exitPoints, $throwPoints, $impurePoints);
461: if ($stmtCount === 0 && $shouldCheckLastStatement) {
462: $returnTypeNode = $parentNode->getReturnType();
463: if ($parentNode instanceof Expr\Closure) {
464: $parentNode = new Node\Stmt\Expression($parentNode, $parentNode->getAttributes());
465: }
466: $nodeCallback(new ExecutionEndNode(
467: $parentNode,
468: $statementResult,
469: $returnTypeNode !== null,
470: ), $scope);
471: }
472:
473: return $statementResult;
474: }
475:
476: /**
477: * @param callable(Node $node, Scope $scope): void $nodeCallback
478: */
479: private function processStmtNode(
480: Node\Stmt $stmt,
481: MutatingScope $scope,
482: callable $nodeCallback,
483: StatementContext $context,
484: ): StatementResult
485: {
486: if (
487: !$stmt instanceof Static_
488: && !$stmt instanceof Foreach_
489: && !$stmt instanceof Node\Stmt\Global_
490: && !$stmt instanceof Node\Stmt\Property
491: && !$stmt instanceof Node\Stmt\ClassConst
492: && !$stmt instanceof Node\Stmt\Const_
493: ) {
494: $scope = $this->processStmtVarAnnotation($scope, $stmt, null, $nodeCallback);
495: }
496:
497: if ($stmt instanceof Node\Stmt\ClassMethod) {
498: if (!$scope->isInClass()) {
499: throw new ShouldNotHappenException();
500: }
501: if (
502: $scope->isInTrait()
503: && $scope->getClassReflection()->hasNativeMethod($stmt->name->toString())
504: ) {
505: $methodReflection = $scope->getClassReflection()->getNativeMethod($stmt->name->toString());
506: if ($methodReflection instanceof NativeMethodReflection) {
507: return new StatementResult($scope, false, false, [], [], []);
508: }
509: if ($methodReflection instanceof PhpMethodReflection) {
510: $declaringTrait = $methodReflection->getDeclaringTrait();
511: if ($declaringTrait === null || $declaringTrait->getName() !== $scope->getTraitReflection()->getName()) {
512: return new StatementResult($scope, false, false, [], [], []);
513: }
514: }
515: }
516: }
517:
518: $stmtScope = $scope;
519: if ($stmt instanceof Node\Stmt\Expression && $stmt->expr instanceof Expr\Throw_) {
520: $stmtScope = $this->processStmtVarAnnotation($scope, $stmt, $stmt->expr->expr, $nodeCallback);
521: }
522: if ($stmt instanceof Return_) {
523: $stmtScope = $this->processStmtVarAnnotation($scope, $stmt, $stmt->expr, $nodeCallback);
524: }
525:
526: $nodeCallback($stmt, $stmtScope);
527:
528: $overridingThrowPoints = $this->getOverridingThrowPoints($stmt, $scope);
529:
530: if ($stmt instanceof Node\Stmt\Declare_) {
531: $hasYield = false;
532: $throwPoints = [];
533: $impurePoints = [];
534: $alwaysTerminating = false;
535: $exitPoints = [];
536: foreach ($stmt->declares as $declare) {
537: $nodeCallback($declare, $scope);
538: $nodeCallback($declare->value, $scope);
539: if (
540: $declare->key->name !== 'strict_types'
541: || !($declare->value instanceof Node\Scalar\Int_)
542: || $declare->value->value !== 1
543: ) {
544: continue;
545: }
546:
547: $scope = $scope->enterDeclareStrictTypes();
548: }
549:
550: if ($stmt->stmts !== null) {
551: $result = $this->processStmtNodes($stmt, $stmt->stmts, $scope, $nodeCallback, $context);
552: $scope = $result->getScope();
553: $hasYield = $result->hasYield();
554: $throwPoints = $result->getThrowPoints();
555: $impurePoints = $result->getImpurePoints();
556: $alwaysTerminating = $result->isAlwaysTerminating();
557: $exitPoints = $result->getExitPoints();
558: }
559:
560: return new StatementResult($scope, $hasYield, $alwaysTerminating, $exitPoints, $throwPoints, $impurePoints);
561: } elseif ($stmt instanceof Node\Stmt\Function_) {
562: $hasYield = false;
563: $throwPoints = [];
564: $impurePoints = [];
565: $this->processAttributeGroups($stmt, $stmt->attrGroups, $scope, $nodeCallback);
566: [$templateTypeMap, $phpDocParameterTypes, $phpDocImmediatelyInvokedCallableParameters, $phpDocClosureThisTypeParameters, $phpDocReturnType, $phpDocThrowType, $deprecatedDescription, $isDeprecated, $isInternal, , $isPure, $acceptsNamedArguments, , $phpDocComment, $asserts,, $phpDocParameterOutTypes] = $this->getPhpDocs($scope, $stmt);
567:
568: foreach ($stmt->params as $param) {
569: $this->processParamNode($stmt, $param, $scope, $nodeCallback);
570: }
571:
572: if ($stmt->returnType !== null) {
573: $nodeCallback($stmt->returnType, $scope);
574: }
575:
576: if (!$isDeprecated) {
577: [$isDeprecated, $deprecatedDescription] = $this->getDeprecatedAttribute($scope, $stmt);
578: }
579:
580: $functionScope = $scope->enterFunction(
581: $stmt,
582: $templateTypeMap,
583: $phpDocParameterTypes,
584: $phpDocReturnType,
585: $phpDocThrowType,
586: $deprecatedDescription,
587: $isDeprecated,
588: $isInternal,
589: $isPure,
590: $acceptsNamedArguments,
591: $asserts,
592: $phpDocComment,
593: $phpDocParameterOutTypes,
594: $phpDocImmediatelyInvokedCallableParameters,
595: $phpDocClosureThisTypeParameters,
596: );
597: $functionReflection = $functionScope->getFunction();
598: if (!$functionReflection instanceof PhpFunctionFromParserNodeReflection) {
599: throw new ShouldNotHappenException();
600: }
601:
602: $nodeCallback(new InFunctionNode($functionReflection, $stmt), $functionScope);
603:
604: $gatheredReturnStatements = [];
605: $gatheredYieldStatements = [];
606: $executionEnds = [];
607: $functionImpurePoints = [];
608: $statementResult = $this->processStmtNodes($stmt, $stmt->stmts, $functionScope, static function (Node $node, Scope $scope) use ($nodeCallback, $functionScope, &$gatheredReturnStatements, &$gatheredYieldStatements, &$executionEnds, &$functionImpurePoints): void {
609: $nodeCallback($node, $scope);
610: if ($scope->getFunction() !== $functionScope->getFunction()) {
611: return;
612: }
613: if ($scope->isInAnonymousFunction()) {
614: return;
615: }
616: if ($node instanceof PropertyAssignNode) {
617: $functionImpurePoints[] = new ImpurePoint(
618: $scope,
619: $node,
620: 'propertyAssign',
621: 'property assignment',
622: true,
623: );
624: return;
625: }
626: if ($node instanceof ExecutionEndNode) {
627: $executionEnds[] = $node;
628: return;
629: }
630: if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) {
631: $gatheredYieldStatements[] = $node;
632: }
633: if (!$node instanceof Return_) {
634: return;
635: }
636:
637: $gatheredReturnStatements[] = new ReturnStatement($scope, $node);
638: }, StatementContext::createTopLevel());
639:
640: $nodeCallback(new FunctionReturnStatementsNode(
641: $stmt,
642: $gatheredReturnStatements,
643: $gatheredYieldStatements,
644: $statementResult,
645: $executionEnds,
646: array_merge($statementResult->getImpurePoints(), $functionImpurePoints),
647: $functionReflection,
648: ), $functionScope);
649: } elseif ($stmt instanceof Node\Stmt\ClassMethod) {
650: $hasYield = false;
651: $throwPoints = [];
652: $impurePoints = [];
653: $this->processAttributeGroups($stmt, $stmt->attrGroups, $scope, $nodeCallback);
654: [$templateTypeMap, $phpDocParameterTypes, $phpDocImmediatelyInvokedCallableParameters, $phpDocClosureThisTypeParameters, $phpDocReturnType, $phpDocThrowType, $deprecatedDescription, $isDeprecated, $isInternal, $isFinal, $isPure, $acceptsNamedArguments, , $phpDocComment, $asserts, $selfOutType, $phpDocParameterOutTypes] = $this->getPhpDocs($scope, $stmt);
655:
656: foreach ($stmt->params as $param) {
657: $this->processParamNode($stmt, $param, $scope, $nodeCallback);
658: }
659:
660: if ($stmt->returnType !== null) {
661: $nodeCallback($stmt->returnType, $scope);
662: }
663:
664: if (!$isDeprecated) {
665: [$isDeprecated, $deprecatedDescription] = $this->getDeprecatedAttribute($scope, $stmt);
666: }
667:
668: $isFromTrait = $stmt->getAttribute('originalTraitMethodName') === '__construct';
669: $isConstructor = $isFromTrait || $stmt->name->toLowerString() === '__construct';
670:
671: $methodScope = $scope->enterClassMethod(
672: $stmt,
673: $templateTypeMap,
674: $phpDocParameterTypes,
675: $phpDocReturnType,
676: $phpDocThrowType,
677: $deprecatedDescription,
678: $isDeprecated,
679: $isInternal,
680: $isFinal,
681: $isPure,
682: $acceptsNamedArguments,
683: $asserts,
684: $selfOutType,
685: $phpDocComment,
686: $phpDocParameterOutTypes,
687: $phpDocImmediatelyInvokedCallableParameters,
688: $phpDocClosureThisTypeParameters,
689: $isConstructor,
690: );
691:
692: if (!$scope->isInClass()) {
693: throw new ShouldNotHappenException();
694: }
695:
696: $classReflection = $scope->getClassReflection();
697:
698: if ($isConstructor) {
699: foreach ($stmt->params as $param) {
700: if ($param->flags === 0 && $param->hooks === []) {
701: continue;
702: }
703:
704: if (!$param->var instanceof Variable || !is_string($param->var->name) || $param->var->name === '') {
705: throw new ShouldNotHappenException();
706: }
707: $phpDoc = null;
708: if ($param->getDocComment() !== null) {
709: $phpDoc = $param->getDocComment()->getText();
710: }
711: $nodeCallback(new ClassPropertyNode(
712: $param->var->name,
713: $param->flags,
714: $param->type !== null ? ParserNodeTypeToPHPStanType::resolve($param->type, $classReflection) : null,
715: null,
716: $phpDoc,
717: $phpDocParameterTypes[$param->var->name] ?? null,
718: true,
719: $isFromTrait,
720: $param,
721: false,
722: $scope->isInTrait(),
723: $classReflection->isReadOnly(),
724: false,
725: $classReflection,
726: ), $methodScope);
727: $this->processPropertyHooks(
728: $stmt,
729: $param->type,
730: $phpDocParameterTypes[$param->var->name] ?? null,
731: $param->var->name,
732: $param->hooks,
733: $scope,
734: $nodeCallback,
735: );
736: $methodScope = $methodScope->assignExpression(new PropertyInitializationExpr($param->var->name), new MixedType(), new MixedType());
737: }
738: }
739:
740: if ($stmt->getAttribute('virtual', false) === false) {
741: $methodReflection = $methodScope->getFunction();
742: if (!$methodReflection instanceof PhpMethodFromParserNodeReflection) {
743: throw new ShouldNotHappenException();
744: }
745: $nodeCallback(new InClassMethodNode($classReflection, $methodReflection, $stmt), $methodScope);
746: }
747:
748: if ($stmt->stmts !== null) {
749: $gatheredReturnStatements = [];
750: $gatheredYieldStatements = [];
751: $executionEnds = [];
752: $methodImpurePoints = [];
753: $statementResult = $this->processStmtNodes($stmt, $stmt->stmts, $methodScope, static function (Node $node, Scope $scope) use ($nodeCallback, $methodScope, &$gatheredReturnStatements, &$gatheredYieldStatements, &$executionEnds, &$methodImpurePoints): void {
754: $nodeCallback($node, $scope);
755: if ($scope->getFunction() !== $methodScope->getFunction()) {
756: return;
757: }
758: if ($scope->isInAnonymousFunction()) {
759: return;
760: }
761: if ($node instanceof PropertyAssignNode) {
762: if (
763: $node->getPropertyFetch() instanceof Expr\PropertyFetch
764: && $scope->getFunction() instanceof PhpMethodFromParserNodeReflection
765: && $scope->getFunction()->getDeclaringClass()->hasConstructor()
766: && $scope->getFunction()->getDeclaringClass()->getConstructor()->getName() === $scope->getFunction()->getName()
767: && TypeUtils::findThisType($scope->getType($node->getPropertyFetch()->var)) !== null
768: ) {
769: return;
770: }
771: $methodImpurePoints[] = new ImpurePoint(
772: $scope,
773: $node,
774: 'propertyAssign',
775: 'property assignment',
776: true,
777: );
778: return;
779: }
780: if ($node instanceof ExecutionEndNode) {
781: $executionEnds[] = $node;
782: return;
783: }
784: if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) {
785: $gatheredYieldStatements[] = $node;
786: }
787: if (!$node instanceof Return_) {
788: return;
789: }
790:
791: $gatheredReturnStatements[] = new ReturnStatement($scope, $node);
792: }, StatementContext::createTopLevel());
793:
794: $methodReflection = $methodScope->getFunction();
795: if (!$methodReflection instanceof PhpMethodFromParserNodeReflection) {
796: throw new ShouldNotHappenException();
797: }
798:
799: $nodeCallback(new MethodReturnStatementsNode(
800: $stmt,
801: $gatheredReturnStatements,
802: $gatheredYieldStatements,
803: $statementResult,
804: $executionEnds,
805: array_merge($statementResult->getImpurePoints(), $methodImpurePoints),
806: $classReflection,
807: $methodReflection,
808: ), $methodScope);
809:
810: if ($isConstructor && $this->narrowMethodScopeFromConstructor) {
811: $finalScope = null;
812:
813: foreach ($executionEnds as $executionEnd) {
814: if ($executionEnd->getStatementResult()->isAlwaysTerminating()) {
815: continue;
816: }
817:
818: $endScope = $executionEnd->getStatementResult()->getScope();
819: if ($finalScope === null) {
820: $finalScope = $endScope;
821: continue;
822: }
823:
824: $finalScope = $finalScope->mergeWith($endScope);
825: }
826:
827: foreach ($gatheredReturnStatements as $statement) {
828: if ($finalScope === null) {
829: $finalScope = $statement->getScope();
830: continue;
831: }
832:
833: $finalScope = $finalScope->mergeWith($statement->getScope());
834: }
835:
836: if ($finalScope !== null) {
837: $scope = $finalScope->rememberConstructorScope();
838: }
839:
840: }
841: }
842: } elseif ($stmt instanceof Echo_) {
843: $hasYield = false;
844: $throwPoints = [];
845: $isAlwaysTerminating = false;
846: foreach ($stmt->exprs as $echoExpr) {
847: $result = $this->processExprNode($stmt, $echoExpr, $scope, $nodeCallback, ExpressionContext::createDeep());
848: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
849: $scope = $result->getScope();
850: $hasYield = $hasYield || $result->hasYield();
851: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
852: }
853:
854: $throwPoints = $overridingThrowPoints ?? $throwPoints;
855: $impurePoints = [
856: new ImpurePoint($scope, $stmt, 'echo', 'echo', true),
857: ];
858: return new StatementResult($scope, $hasYield, $isAlwaysTerminating, [], $throwPoints, $impurePoints);
859: } elseif ($stmt instanceof Return_) {
860: if ($stmt->expr !== null) {
861: $result = $this->processExprNode($stmt, $stmt->expr, $scope, $nodeCallback, ExpressionContext::createDeep());
862: $throwPoints = $result->getThrowPoints();
863: $impurePoints = $result->getImpurePoints();
864: $scope = $result->getScope();
865: $hasYield = $result->hasYield();
866: } else {
867: $hasYield = false;
868: $throwPoints = [];
869: $impurePoints = [];
870: }
871:
872: return new StatementResult($scope, $hasYield, true, [
873: new StatementExitPoint($stmt, $scope),
874: ], $overridingThrowPoints ?? $throwPoints, $impurePoints);
875: } elseif ($stmt instanceof Continue_ || $stmt instanceof Break_) {
876: if ($stmt->num !== null) {
877: $result = $this->processExprNode($stmt, $stmt->num, $scope, $nodeCallback, ExpressionContext::createDeep());
878: $scope = $result->getScope();
879: $hasYield = $result->hasYield();
880: $throwPoints = $result->getThrowPoints();
881: $impurePoints = $result->getImpurePoints();
882: } else {
883: $hasYield = false;
884: $throwPoints = [];
885: $impurePoints = [];
886: }
887:
888: return new StatementResult($scope, $hasYield, true, [
889: new StatementExitPoint($stmt, $scope),
890: ], $overridingThrowPoints ?? $throwPoints, $impurePoints);
891: } elseif ($stmt instanceof Node\Stmt\Expression) {
892: if ($stmt->expr instanceof Expr\Throw_) {
893: $scope = $stmtScope;
894: }
895: $earlyTerminationExpr = $this->findEarlyTerminatingExpr($stmt->expr, $scope);
896: $hasAssign = false;
897: $currentScope = $scope;
898: $result = $this->processExprNode($stmt, $stmt->expr, $scope, static function (Node $node, Scope $scope) use ($nodeCallback, $currentScope, &$hasAssign): void {
899: $nodeCallback($node, $scope);
900: if ($scope->getAnonymousFunctionReflection() !== $currentScope->getAnonymousFunctionReflection()) {
901: return;
902: }
903: if ($scope->getFunction() !== $currentScope->getFunction()) {
904: return;
905: }
906: if (!$node instanceof VariableAssignNode && !$node instanceof PropertyAssignNode) {
907: return;
908: }
909:
910: $hasAssign = true;
911: }, ExpressionContext::createTopLevel());
912: $throwPoints = array_filter($result->getThrowPoints(), static fn ($throwPoint) => $throwPoint->isExplicit());
913: if (
914: count($result->getImpurePoints()) === 0
915: && count($throwPoints) === 0
916: && !$stmt->expr instanceof Expr\PostInc
917: && !$stmt->expr instanceof Expr\PreInc
918: && !$stmt->expr instanceof Expr\PostDec
919: && !$stmt->expr instanceof Expr\PreDec
920: ) {
921: $nodeCallback(new NoopExpressionNode($stmt->expr, $hasAssign), $scope);
922: }
923: $scope = $result->getScope();
924: $scope = $scope->filterBySpecifiedTypes($this->typeSpecifier->specifyTypesInCondition(
925: $scope,
926: $stmt->expr,
927: TypeSpecifierContext::createNull(),
928: ));
929: $hasYield = $result->hasYield();
930: $throwPoints = $result->getThrowPoints();
931: $impurePoints = $result->getImpurePoints();
932: $isAlwaysTerminating = $result->isAlwaysTerminating();
933:
934: if ($earlyTerminationExpr !== null) {
935: return new StatementResult($scope, $hasYield, true, [
936: new StatementExitPoint($stmt, $scope),
937: ], $overridingThrowPoints ?? $throwPoints, $impurePoints);
938: }
939: return new StatementResult($scope, $hasYield, $isAlwaysTerminating, [], $overridingThrowPoints ?? $throwPoints, $impurePoints);
940: } elseif ($stmt instanceof Node\Stmt\Namespace_) {
941: if ($stmt->name !== null) {
942: $scope = $scope->enterNamespace($stmt->name->toString());
943: }
944:
945: $scope = $this->processStmtNodes($stmt, $stmt->stmts, $scope, $nodeCallback, $context)->getScope();
946: $hasYield = false;
947: $throwPoints = [];
948: $impurePoints = [];
949: } elseif ($stmt instanceof Node\Stmt\Trait_) {
950: return new StatementResult($scope, false, false, [], [], []);
951: } elseif ($stmt instanceof Node\Stmt\ClassLike) {
952: if (!$context->isTopLevel()) {
953: return new StatementResult($scope, false, false, [], [], []);
954: }
955: $hasYield = false;
956: $throwPoints = [];
957: $impurePoints = [];
958: if (isset($stmt->namespacedName)) {
959: $classReflection = $this->getCurrentClassReflection($stmt, $stmt->namespacedName->toString(), $scope);
960: $classScope = $scope->enterClass($classReflection);
961: $nodeCallback(new InClassNode($stmt, $classReflection), $classScope);
962: } elseif ($stmt instanceof Class_) {
963: if ($stmt->name === null) {
964: throw new ShouldNotHappenException();
965: }
966: if (!$stmt->isAnonymous()) {
967: $classReflection = $this->reflectionProvider->getClass($stmt->name->toString());
968: } else {
969: $classReflection = $this->reflectionProvider->getAnonymousClassReflection($stmt, $scope);
970: }
971: $classScope = $scope->enterClass($classReflection);
972: $nodeCallback(new InClassNode($stmt, $classReflection), $classScope);
973: } else {
974: throw new ShouldNotHappenException();
975: }
976:
977: $classStatementsGatherer = new ClassStatementsGatherer($classReflection, $nodeCallback);
978: $this->processAttributeGroups($stmt, $stmt->attrGroups, $classScope, $classStatementsGatherer);
979:
980: $classLikeStatements = $stmt->stmts;
981: if ($this->narrowMethodScopeFromConstructor) {
982: // analyze static methods first; constructor next; instance methods and property hooks last so we can carry over the scope
983: usort($classLikeStatements, static function ($a, $b) {
984: if ($a instanceof Node\Stmt\Property) {
985: return 1;
986: }
987: if ($b instanceof Node\Stmt\Property) {
988: return -1;
989: }
990:
991: if (!$a instanceof Node\Stmt\ClassMethod || !$b instanceof Node\Stmt\ClassMethod) {
992: return 0;
993: }
994:
995: return [!$a->isStatic(), $a->name->toLowerString() !== '__construct'] <=> [!$b->isStatic(), $b->name->toLowerString() !== '__construct'];
996: });
997: }
998:
999: $this->processStmtNodes($stmt, $classLikeStatements, $classScope, $classStatementsGatherer, $context);
1000: $nodeCallback(new ClassPropertiesNode($stmt, $this->readWritePropertiesExtensionProvider, $classStatementsGatherer->getProperties(), $classStatementsGatherer->getPropertyUsages(), $classStatementsGatherer->getMethodCalls(), $classStatementsGatherer->getReturnStatementsNodes(), $classStatementsGatherer->getPropertyAssigns(), $classReflection), $classScope);
1001: $nodeCallback(new ClassMethodsNode($stmt, $classStatementsGatherer->getMethods(), $classStatementsGatherer->getMethodCalls(), $classReflection), $classScope);
1002: $nodeCallback(new ClassConstantsNode($stmt, $classStatementsGatherer->getConstants(), $classStatementsGatherer->getConstantFetches(), $classReflection), $classScope);
1003: $classReflection->evictPrivateSymbols();
1004: $this->calledMethodResults = [];
1005: } elseif ($stmt instanceof Node\Stmt\Property) {
1006: $hasYield = false;
1007: $throwPoints = [];
1008: $impurePoints = [];
1009: $this->processAttributeGroups($stmt, $stmt->attrGroups, $scope, $nodeCallback);
1010:
1011: $nativePropertyType = $stmt->type !== null ? ParserNodeTypeToPHPStanType::resolve($stmt->type, $scope->getClassReflection()) : null;
1012:
1013: [,,,,,,,,,,,,$isReadOnly, $docComment, ,,,$varTags, $isAllowedPrivateMutation] = $this->getPhpDocs($scope, $stmt);
1014: $phpDocType = null;
1015: if (isset($varTags[0]) && count($varTags) === 1) {
1016: $phpDocType = $varTags[0]->getType();
1017: }
1018:
1019: foreach ($stmt->props as $prop) {
1020: $nodeCallback($prop, $scope);
1021: if ($prop->default !== null) {
1022: $this->processExprNode($stmt, $prop->default, $scope, $nodeCallback, ExpressionContext::createDeep());
1023: }
1024:
1025: if (!$scope->isInClass()) {
1026: throw new ShouldNotHappenException();
1027: }
1028: $propertyName = $prop->name->toString();
1029:
1030: if ($phpDocType === null) {
1031: if (isset($varTags[$propertyName])) {
1032: $phpDocType = $varTags[$propertyName]->getType();
1033: }
1034: }
1035:
1036: $propStmt = clone $stmt;
1037: $propStmt->setAttributes($prop->getAttributes());
1038: $nodeCallback(
1039: new ClassPropertyNode(
1040: $propertyName,
1041: $stmt->flags,
1042: $nativePropertyType,
1043: $prop->default,
1044: $docComment,
1045: $phpDocType,
1046: false,
1047: false,
1048: $propStmt,
1049: $isReadOnly,
1050: $scope->isInTrait(),
1051: $scope->getClassReflection()->isReadOnly(),
1052: $isAllowedPrivateMutation,
1053: $scope->getClassReflection(),
1054: ),
1055: $scope,
1056: );
1057: }
1058:
1059: if (count($stmt->hooks) > 0) {
1060: if (!isset($propertyName)) {
1061: throw new ShouldNotHappenException('Property name should be known when analysing hooks.');
1062: }
1063: $this->processPropertyHooks(
1064: $stmt,
1065: $stmt->type,
1066: $phpDocType,
1067: $propertyName,
1068: $stmt->hooks,
1069: $scope,
1070: $nodeCallback,
1071: );
1072: }
1073:
1074: if ($stmt->type !== null) {
1075: $nodeCallback($stmt->type, $scope);
1076: }
1077: } elseif ($stmt instanceof If_) {
1078: $conditionType = ($this->treatPhpDocTypesAsCertain ? $scope->getType($stmt->cond) : $scope->getNativeType($stmt->cond))->toBoolean();
1079: $ifAlwaysTrue = $conditionType->isTrue()->yes();
1080: $condResult = $this->processExprNode($stmt, $stmt->cond, $scope, $nodeCallback, ExpressionContext::createDeep());
1081: $exitPoints = [];
1082: $throwPoints = $overridingThrowPoints ?? $condResult->getThrowPoints();
1083: $impurePoints = $condResult->getImpurePoints();
1084: $endStatements = [];
1085: $finalScope = null;
1086: $alwaysTerminating = true;
1087: $hasYield = $condResult->hasYield();
1088:
1089: $branchScopeStatementResult = $this->processStmtNodes($stmt, $stmt->stmts, $condResult->getTruthyScope(), $nodeCallback, $context);
1090:
1091: if (!$conditionType instanceof ConstantBooleanType || $conditionType->getValue()) {
1092: $exitPoints = $branchScopeStatementResult->getExitPoints();
1093: $throwPoints = array_merge($throwPoints, $branchScopeStatementResult->getThrowPoints());
1094: $impurePoints = array_merge($impurePoints, $branchScopeStatementResult->getImpurePoints());
1095: $branchScope = $branchScopeStatementResult->getScope();
1096: $finalScope = $branchScopeStatementResult->isAlwaysTerminating() ? null : $branchScope;
1097: $alwaysTerminating = $branchScopeStatementResult->isAlwaysTerminating();
1098: if (count($branchScopeStatementResult->getEndStatements()) > 0) {
1099: $endStatements = array_merge($endStatements, $branchScopeStatementResult->getEndStatements());
1100: } elseif (count($stmt->stmts) > 0) {
1101: $endStatements[] = new EndStatementResult($stmt->stmts[count($stmt->stmts) - 1], $branchScopeStatementResult);
1102: } else {
1103: $endStatements[] = new EndStatementResult($stmt, $branchScopeStatementResult);
1104: }
1105: $hasYield = $branchScopeStatementResult->hasYield() || $hasYield;
1106: }
1107:
1108: $scope = $condResult->getFalseyScope();
1109: $lastElseIfConditionIsTrue = false;
1110:
1111: $condScope = $scope;
1112: foreach ($stmt->elseifs as $elseif) {
1113: $nodeCallback($elseif, $scope);
1114: $elseIfConditionType = ($this->treatPhpDocTypesAsCertain ? $condScope->getType($elseif->cond) : $scope->getNativeType($elseif->cond))->toBoolean();
1115: $condResult = $this->processExprNode($stmt, $elseif->cond, $condScope, $nodeCallback, ExpressionContext::createDeep());
1116: $throwPoints = array_merge($throwPoints, $condResult->getThrowPoints());
1117: $impurePoints = array_merge($impurePoints, $condResult->getImpurePoints());
1118: $condScope = $condResult->getScope();
1119: $branchScopeStatementResult = $this->processStmtNodes($elseif, $elseif->stmts, $condResult->getTruthyScope(), $nodeCallback, $context);
1120:
1121: if (
1122: !$ifAlwaysTrue
1123: && (
1124: !$lastElseIfConditionIsTrue
1125: && (
1126: !$elseIfConditionType instanceof ConstantBooleanType
1127: || $elseIfConditionType->getValue()
1128: )
1129: )
1130: ) {
1131: $exitPoints = array_merge($exitPoints, $branchScopeStatementResult->getExitPoints());
1132: $throwPoints = array_merge($throwPoints, $branchScopeStatementResult->getThrowPoints());
1133: $impurePoints = array_merge($impurePoints, $branchScopeStatementResult->getImpurePoints());
1134: $branchScope = $branchScopeStatementResult->getScope();
1135: $finalScope = $branchScopeStatementResult->isAlwaysTerminating() ? $finalScope : $branchScope->mergeWith($finalScope);
1136: $alwaysTerminating = $alwaysTerminating && $branchScopeStatementResult->isAlwaysTerminating();
1137: if (count($branchScopeStatementResult->getEndStatements()) > 0) {
1138: $endStatements = array_merge($endStatements, $branchScopeStatementResult->getEndStatements());
1139: } elseif (count($elseif->stmts) > 0) {
1140: $endStatements[] = new EndStatementResult($elseif->stmts[count($elseif->stmts) - 1], $branchScopeStatementResult);
1141: } else {
1142: $endStatements[] = new EndStatementResult($elseif, $branchScopeStatementResult);
1143: }
1144: $hasYield = $hasYield || $branchScopeStatementResult->hasYield();
1145: }
1146:
1147: if (
1148: $elseIfConditionType->isTrue()->yes()
1149: ) {
1150: $lastElseIfConditionIsTrue = true;
1151: }
1152:
1153: $condScope = $condScope->filterByFalseyValue($elseif->cond);
1154: $scope = $condScope;
1155: }
1156:
1157: if ($stmt->else === null) {
1158: if (!$ifAlwaysTrue && !$lastElseIfConditionIsTrue) {
1159: $finalScope = $scope->mergeWith($finalScope);
1160: $alwaysTerminating = false;
1161: }
1162: } else {
1163: $nodeCallback($stmt->else, $scope);
1164: $branchScopeStatementResult = $this->processStmtNodes($stmt->else, $stmt->else->stmts, $scope, $nodeCallback, $context);
1165:
1166: if (!$ifAlwaysTrue && !$lastElseIfConditionIsTrue) {
1167: $exitPoints = array_merge($exitPoints, $branchScopeStatementResult->getExitPoints());
1168: $throwPoints = array_merge($throwPoints, $branchScopeStatementResult->getThrowPoints());
1169: $impurePoints = array_merge($impurePoints, $branchScopeStatementResult->getImpurePoints());
1170: $branchScope = $branchScopeStatementResult->getScope();
1171: $finalScope = $branchScopeStatementResult->isAlwaysTerminating() ? $finalScope : $branchScope->mergeWith($finalScope);
1172: $alwaysTerminating = $alwaysTerminating && $branchScopeStatementResult->isAlwaysTerminating();
1173: if (count($branchScopeStatementResult->getEndStatements()) > 0) {
1174: $endStatements = array_merge($endStatements, $branchScopeStatementResult->getEndStatements());
1175: } elseif (count($stmt->else->stmts) > 0) {
1176: $endStatements[] = new EndStatementResult($stmt->else->stmts[count($stmt->else->stmts) - 1], $branchScopeStatementResult);
1177: } else {
1178: $endStatements[] = new EndStatementResult($stmt->else, $branchScopeStatementResult);
1179: }
1180: $hasYield = $hasYield || $branchScopeStatementResult->hasYield();
1181: }
1182: }
1183:
1184: if ($finalScope === null) {
1185: $finalScope = $scope;
1186: }
1187:
1188: if ($stmt->else === null && !$ifAlwaysTrue && !$lastElseIfConditionIsTrue) {
1189: $endStatements[] = new EndStatementResult($stmt, new StatementResult($finalScope, $hasYield, $alwaysTerminating, $exitPoints, $throwPoints, $impurePoints));
1190: }
1191:
1192: return new StatementResult($finalScope, $hasYield, $alwaysTerminating, $exitPoints, $throwPoints, $impurePoints, $endStatements);
1193: } elseif ($stmt instanceof Node\Stmt\TraitUse) {
1194: $hasYield = false;
1195: $throwPoints = [];
1196: $impurePoints = [];
1197: $this->processTraitUse($stmt, $scope, $nodeCallback);
1198: } elseif ($stmt instanceof Foreach_) {
1199: $condResult = $this->processExprNode($stmt, $stmt->expr, $scope, $nodeCallback, ExpressionContext::createDeep());
1200: $throwPoints = $overridingThrowPoints ?? $condResult->getThrowPoints();
1201: $impurePoints = $condResult->getImpurePoints();
1202: $scope = $condResult->getScope();
1203: $arrayComparisonExpr = new BinaryOp\NotIdentical(
1204: $stmt->expr,
1205: new Array_([]),
1206: );
1207: if ($stmt->expr instanceof Variable && is_string($stmt->expr->name)) {
1208: $scope = $this->processVarAnnotation($scope, [$stmt->expr->name], $stmt);
1209: }
1210: $nodeCallback(new InForeachNode($stmt), $scope);
1211: $originalScope = $scope;
1212: $bodyScope = $scope;
1213:
1214: if ($context->isTopLevel()) {
1215: $originalScope = $this->polluteScopeWithAlwaysIterableForeach ? $scope->filterByTruthyValue($arrayComparisonExpr) : $scope;
1216: $bodyScope = $this->enterForeach($originalScope, $originalScope, $stmt);
1217: $count = 0;
1218: do {
1219: $prevScope = $bodyScope;
1220: $bodyScope = $bodyScope->mergeWith($this->polluteScopeWithAlwaysIterableForeach ? $scope->filterByTruthyValue($arrayComparisonExpr) : $scope);
1221: $bodyScope = $this->enterForeach($bodyScope, $originalScope, $stmt);
1222: $bodyScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, static function (): void {
1223: }, $context->enterDeep())->filterOutLoopExitPoints();
1224: $bodyScope = $bodyScopeResult->getScope();
1225: foreach ($bodyScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1226: $bodyScope = $bodyScope->mergeWith($continueExitPoint->getScope());
1227: }
1228: if ($bodyScope->equals($prevScope)) {
1229: break;
1230: }
1231:
1232: if ($count >= self::GENERALIZE_AFTER_ITERATION) {
1233: $bodyScope = $prevScope->generalizeWith($bodyScope);
1234: }
1235: $count++;
1236: } while ($count < self::LOOP_SCOPE_ITERATIONS);
1237: }
1238:
1239: $bodyScope = $bodyScope->mergeWith($this->polluteScopeWithAlwaysIterableForeach ? $scope->filterByTruthyValue($arrayComparisonExpr) : $scope);
1240: $bodyScope = $this->enterForeach($bodyScope, $originalScope, $stmt);
1241: $finalScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, $nodeCallback, $context)->filterOutLoopExitPoints();
1242: $finalScope = $finalScopeResult->getScope();
1243: foreach ($finalScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1244: $finalScope = $continueExitPoint->getScope()->mergeWith($finalScope);
1245: }
1246: foreach ($finalScopeResult->getExitPointsByType(Break_::class) as $breakExitPoint) {
1247: $finalScope = $breakExitPoint->getScope()->mergeWith($finalScope);
1248: }
1249:
1250: $exprType = $scope->getType($stmt->expr);
1251: $isIterableAtLeastOnce = $exprType->isIterableAtLeastOnce();
1252: if ($exprType->isIterable()->no() || $isIterableAtLeastOnce->maybe()) {
1253: $finalScope = $finalScope->mergeWith($scope->filterByTruthyValue(new BooleanOr(
1254: new BinaryOp\Identical(
1255: $stmt->expr,
1256: new Array_([]),
1257: ),
1258: new FuncCall(new Name\FullyQualified('is_object'), [
1259: new Arg($stmt->expr),
1260: ]),
1261: )));
1262: } elseif ($isIterableAtLeastOnce->no() || $finalScopeResult->isAlwaysTerminating()) {
1263: $finalScope = $scope;
1264: } elseif (!$this->polluteScopeWithAlwaysIterableForeach) {
1265: $finalScope = $scope->processAlwaysIterableForeachScopeWithoutPollute($finalScope);
1266: // get types from finalScope, but don't create new variables
1267: }
1268:
1269: if (!$isIterableAtLeastOnce->no()) {
1270: $throwPoints = array_merge($throwPoints, $finalScopeResult->getThrowPoints());
1271: $impurePoints = array_merge($impurePoints, $finalScopeResult->getImpurePoints());
1272: }
1273: if (!(new ObjectType(Traversable::class))->isSuperTypeOf($scope->getType($stmt->expr))->no()) {
1274: $throwPoints[] = ThrowPoint::createImplicit($scope, $stmt->expr);
1275: }
1276:
1277: return new StatementResult(
1278: $finalScope,
1279: $finalScopeResult->hasYield() || $condResult->hasYield(),
1280: $isIterableAtLeastOnce->yes() && $finalScopeResult->isAlwaysTerminating(),
1281: $finalScopeResult->getExitPointsForOuterLoop(),
1282: $throwPoints,
1283: $impurePoints,
1284: );
1285: } elseif ($stmt instanceof While_) {
1286: $condResult = $this->processExprNode($stmt, $stmt->cond, $scope, static function (): void {
1287: }, ExpressionContext::createDeep());
1288: $bodyScope = $condResult->getTruthyScope();
1289:
1290: if ($context->isTopLevel()) {
1291: $count = 0;
1292: do {
1293: $prevScope = $bodyScope;
1294: $bodyScope = $bodyScope->mergeWith($scope);
1295: $bodyScope = $this->processExprNode($stmt, $stmt->cond, $bodyScope, static function (): void {
1296: }, ExpressionContext::createDeep())->getTruthyScope();
1297: $bodyScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, static function (): void {
1298: }, $context->enterDeep())->filterOutLoopExitPoints();
1299: $bodyScope = $bodyScopeResult->getScope();
1300: foreach ($bodyScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1301: $bodyScope = $bodyScope->mergeWith($continueExitPoint->getScope());
1302: }
1303: if ($bodyScope->equals($prevScope)) {
1304: break;
1305: }
1306:
1307: if ($count >= self::GENERALIZE_AFTER_ITERATION) {
1308: $bodyScope = $prevScope->generalizeWith($bodyScope);
1309: }
1310: $count++;
1311: } while ($count < self::LOOP_SCOPE_ITERATIONS);
1312: }
1313:
1314: $bodyScope = $bodyScope->mergeWith($scope);
1315: $bodyScopeMaybeRan = $bodyScope;
1316: $bodyScope = $this->processExprNode($stmt, $stmt->cond, $bodyScope, $nodeCallback, ExpressionContext::createDeep())->getTruthyScope();
1317: $finalScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, $nodeCallback, $context)->filterOutLoopExitPoints();
1318: $finalScope = $finalScopeResult->getScope()->filterByFalseyValue($stmt->cond);
1319:
1320: $condBooleanType = ($this->treatPhpDocTypesAsCertain ? $bodyScopeMaybeRan->getType($stmt->cond) : $bodyScopeMaybeRan->getNativeType($stmt->cond))->toBoolean();
1321: $alwaysIterates = $condBooleanType->isTrue()->yes() && $context->isTopLevel();
1322: $neverIterates = $condBooleanType->isFalse()->yes() && $context->isTopLevel();
1323: if (!$alwaysIterates) {
1324: foreach ($finalScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1325: $finalScope = $finalScope->mergeWith($continueExitPoint->getScope());
1326: }
1327: }
1328:
1329: $breakExitPoints = $finalScopeResult->getExitPointsByType(Break_::class);
1330: foreach ($breakExitPoints as $breakExitPoint) {
1331: $finalScope = $finalScope->mergeWith($breakExitPoint->getScope());
1332: }
1333:
1334: $beforeCondBooleanType = ($this->treatPhpDocTypesAsCertain ? $scope->getType($stmt->cond) : $scope->getNativeType($stmt->cond))->toBoolean();
1335: $isIterableAtLeastOnce = $beforeCondBooleanType->isTrue()->yes();
1336: $nodeCallback(new BreaklessWhileLoopNode($stmt, $finalScopeResult->getExitPoints()), $bodyScopeMaybeRan);
1337:
1338: if ($alwaysIterates) {
1339: $isAlwaysTerminating = count($finalScopeResult->getExitPointsByType(Break_::class)) === 0;
1340: } elseif ($isIterableAtLeastOnce) {
1341: $isAlwaysTerminating = $finalScopeResult->isAlwaysTerminating();
1342: } else {
1343: $isAlwaysTerminating = false;
1344: }
1345: $condScope = $condResult->getFalseyScope();
1346: if (!$isIterableAtLeastOnce) {
1347: if (!$this->polluteScopeWithLoopInitialAssignments) {
1348: $condScope = $condScope->mergeWith($scope);
1349: }
1350: $finalScope = $finalScope->mergeWith($condScope);
1351: }
1352:
1353: $throwPoints = $overridingThrowPoints ?? $condResult->getThrowPoints();
1354: $impurePoints = $condResult->getImpurePoints();
1355: if (!$neverIterates) {
1356: $throwPoints = array_merge($throwPoints, $finalScopeResult->getThrowPoints());
1357: $impurePoints = array_merge($impurePoints, $finalScopeResult->getImpurePoints());
1358: }
1359:
1360: return new StatementResult(
1361: $finalScope,
1362: $finalScopeResult->hasYield() || $condResult->hasYield(),
1363: $isAlwaysTerminating,
1364: $finalScopeResult->getExitPointsForOuterLoop(),
1365: $throwPoints,
1366: $impurePoints,
1367: );
1368: } elseif ($stmt instanceof Do_) {
1369: $finalScope = null;
1370: $bodyScope = $scope;
1371: $count = 0;
1372: $hasYield = false;
1373: $throwPoints = [];
1374: $impurePoints = [];
1375:
1376: if ($context->isTopLevel()) {
1377: do {
1378: $prevScope = $bodyScope;
1379: $bodyScope = $bodyScope->mergeWith($scope);
1380: $bodyScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, static function (): void {
1381: }, $context->enterDeep())->filterOutLoopExitPoints();
1382: $alwaysTerminating = $bodyScopeResult->isAlwaysTerminating();
1383: $bodyScope = $bodyScopeResult->getScope();
1384: foreach ($bodyScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1385: $bodyScope = $bodyScope->mergeWith($continueExitPoint->getScope());
1386: }
1387: $finalScope = $alwaysTerminating ? $finalScope : $bodyScope->mergeWith($finalScope);
1388: foreach ($bodyScopeResult->getExitPointsByType(Break_::class) as $breakExitPoint) {
1389: $finalScope = $breakExitPoint->getScope()->mergeWith($finalScope);
1390: }
1391: $bodyScope = $this->processExprNode($stmt, $stmt->cond, $bodyScope, static function (): void {
1392: }, ExpressionContext::createDeep())->getTruthyScope();
1393: if ($bodyScope->equals($prevScope)) {
1394: break;
1395: }
1396:
1397: if ($count >= self::GENERALIZE_AFTER_ITERATION) {
1398: $bodyScope = $prevScope->generalizeWith($bodyScope);
1399: }
1400: $count++;
1401: } while ($count < self::LOOP_SCOPE_ITERATIONS);
1402:
1403: $bodyScope = $bodyScope->mergeWith($scope);
1404: }
1405:
1406: $bodyScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, $nodeCallback, $context)->filterOutLoopExitPoints();
1407: $bodyScope = $bodyScopeResult->getScope();
1408: foreach ($bodyScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1409: $bodyScope = $bodyScope->mergeWith($continueExitPoint->getScope());
1410: }
1411: $condBooleanType = ($this->treatPhpDocTypesAsCertain ? $bodyScope->getType($stmt->cond) : $bodyScope->getNativeType($stmt->cond))->toBoolean();
1412: $alwaysIterates = $condBooleanType->isTrue()->yes() && $context->isTopLevel();
1413:
1414: $nodeCallback(new DoWhileLoopConditionNode($stmt->cond, $bodyScopeResult->getExitPoints()), $bodyScope);
1415:
1416: if ($alwaysIterates) {
1417: $alwaysTerminating = count($bodyScopeResult->getExitPointsByType(Break_::class)) === 0;
1418: } else {
1419: $alwaysTerminating = $bodyScopeResult->isAlwaysTerminating();
1420: }
1421: $finalScope = $alwaysTerminating ? $finalScope : $bodyScope->mergeWith($finalScope);
1422: if ($finalScope === null) {
1423: $finalScope = $scope;
1424: }
1425: if (!$alwaysTerminating) {
1426: $condResult = $this->processExprNode($stmt, $stmt->cond, $bodyScope, $nodeCallback, ExpressionContext::createDeep());
1427: $hasYield = $condResult->hasYield();
1428: $throwPoints = $condResult->getThrowPoints();
1429: $impurePoints = $condResult->getImpurePoints();
1430: $finalScope = $condResult->getFalseyScope();
1431: } else {
1432: $this->processExprNode($stmt, $stmt->cond, $bodyScope, $nodeCallback, ExpressionContext::createDeep());
1433: }
1434: foreach ($bodyScopeResult->getExitPointsByType(Break_::class) as $breakExitPoint) {
1435: $finalScope = $breakExitPoint->getScope()->mergeWith($finalScope);
1436: }
1437:
1438: return new StatementResult(
1439: $finalScope,
1440: $bodyScopeResult->hasYield() || $hasYield,
1441: $alwaysTerminating,
1442: $bodyScopeResult->getExitPointsForOuterLoop(),
1443: array_merge($throwPoints, $bodyScopeResult->getThrowPoints()),
1444: array_merge($impurePoints, $bodyScopeResult->getImpurePoints()),
1445: );
1446: } elseif ($stmt instanceof For_) {
1447: $initScope = $scope;
1448: $hasYield = false;
1449: $throwPoints = [];
1450: $impurePoints = [];
1451: foreach ($stmt->init as $initExpr) {
1452: $initResult = $this->processExprNode($stmt, $initExpr, $initScope, $nodeCallback, ExpressionContext::createTopLevel());
1453: $initScope = $initResult->getScope();
1454: $hasYield = $hasYield || $initResult->hasYield();
1455: $throwPoints = array_merge($throwPoints, $initResult->getThrowPoints());
1456: $impurePoints = array_merge($impurePoints, $initResult->getImpurePoints());
1457: }
1458:
1459: $bodyScope = $initScope;
1460: $isIterableAtLeastOnce = TrinaryLogic::createYes();
1461: $lastCondExpr = $stmt->cond[count($stmt->cond) - 1] ?? null;
1462: foreach ($stmt->cond as $condExpr) {
1463: $condResult = $this->processExprNode($stmt, $condExpr, $bodyScope, static function (): void {
1464: }, ExpressionContext::createDeep());
1465: $initScope = $condResult->getScope();
1466: $condResultScope = $condResult->getScope();
1467:
1468: if ($condExpr === $lastCondExpr) {
1469: $condTruthiness = ($this->treatPhpDocTypesAsCertain ? $condResultScope->getType($condExpr) : $condResultScope->getNativeType($condExpr))->toBoolean();
1470: $isIterableAtLeastOnce = $isIterableAtLeastOnce->and($condTruthiness->isTrue());
1471: }
1472:
1473: $hasYield = $hasYield || $condResult->hasYield();
1474: $throwPoints = array_merge($throwPoints, $condResult->getThrowPoints());
1475: $impurePoints = array_merge($impurePoints, $condResult->getImpurePoints());
1476: $bodyScope = $condResult->getTruthyScope();
1477: }
1478:
1479: if ($context->isTopLevel()) {
1480: $count = 0;
1481: do {
1482: $prevScope = $bodyScope;
1483: $bodyScope = $bodyScope->mergeWith($initScope);
1484: if ($lastCondExpr !== null) {
1485: $bodyScope = $this->processExprNode($stmt, $lastCondExpr, $bodyScope, static function (): void {
1486: }, ExpressionContext::createDeep())->getTruthyScope();
1487: }
1488: $bodyScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, static function (): void {
1489: }, $context->enterDeep())->filterOutLoopExitPoints();
1490: $bodyScope = $bodyScopeResult->getScope();
1491: foreach ($bodyScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1492: $bodyScope = $bodyScope->mergeWith($continueExitPoint->getScope());
1493: }
1494: foreach ($stmt->loop as $loopExpr) {
1495: $exprResult = $this->processExprNode($stmt, $loopExpr, $bodyScope, static function (): void {
1496: }, ExpressionContext::createTopLevel());
1497: $bodyScope = $exprResult->getScope();
1498: $hasYield = $hasYield || $exprResult->hasYield();
1499: $throwPoints = array_merge($throwPoints, $exprResult->getThrowPoints());
1500: $impurePoints = array_merge($impurePoints, $exprResult->getImpurePoints());
1501: }
1502:
1503: if ($bodyScope->equals($prevScope)) {
1504: break;
1505: }
1506:
1507: if ($count >= self::GENERALIZE_AFTER_ITERATION) {
1508: $bodyScope = $prevScope->generalizeWith($bodyScope);
1509: }
1510: $count++;
1511: } while ($count < self::LOOP_SCOPE_ITERATIONS);
1512: }
1513:
1514: $bodyScope = $bodyScope->mergeWith($initScope);
1515:
1516: $alwaysIterates = TrinaryLogic::createFromBoolean($context->isTopLevel());
1517: if ($lastCondExpr !== null) {
1518: $alwaysIterates = $alwaysIterates->and($bodyScope->getType($lastCondExpr)->toBoolean()->isTrue());
1519: $bodyScope = $this->processExprNode($stmt, $lastCondExpr, $bodyScope, $nodeCallback, ExpressionContext::createDeep())->getTruthyScope();
1520: }
1521:
1522: $finalScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, $nodeCallback, $context)->filterOutLoopExitPoints();
1523: $finalScope = $finalScopeResult->getScope();
1524: foreach ($finalScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1525: $finalScope = $continueExitPoint->getScope()->mergeWith($finalScope);
1526: }
1527:
1528: $loopScope = $finalScope;
1529: foreach ($stmt->loop as $loopExpr) {
1530: $loopScope = $this->processExprNode($stmt, $loopExpr, $loopScope, $nodeCallback, ExpressionContext::createTopLevel())->getScope();
1531: }
1532: $finalScope = $finalScope->generalizeWith($loopScope);
1533:
1534: if ($lastCondExpr !== null) {
1535: $finalScope = $finalScope->filterByFalseyValue($lastCondExpr);
1536: }
1537:
1538: foreach ($finalScopeResult->getExitPointsByType(Break_::class) as $breakExitPoint) {
1539: $finalScope = $breakExitPoint->getScope()->mergeWith($finalScope);
1540: }
1541:
1542: if ($isIterableAtLeastOnce->no() || $finalScopeResult->isAlwaysTerminating()) {
1543: if ($this->polluteScopeWithLoopInitialAssignments) {
1544: $finalScope = $initScope;
1545: } else {
1546: $finalScope = $scope;
1547: }
1548:
1549: } elseif ($isIterableAtLeastOnce->maybe()) {
1550: if ($this->polluteScopeWithLoopInitialAssignments) {
1551: $finalScope = $finalScope->mergeWith($initScope);
1552: } else {
1553: $finalScope = $finalScope->mergeWith($scope);
1554: }
1555: } else {
1556: if (!$this->polluteScopeWithLoopInitialAssignments) {
1557: $finalScope = $finalScope->mergeWith($scope);
1558: }
1559: }
1560:
1561: if ($alwaysIterates->yes()) {
1562: $isAlwaysTerminating = count($finalScopeResult->getExitPointsByType(Break_::class)) === 0;
1563: } elseif ($isIterableAtLeastOnce->yes()) {
1564: $isAlwaysTerminating = $finalScopeResult->isAlwaysTerminating();
1565: } else {
1566: $isAlwaysTerminating = false;
1567: }
1568:
1569: return new StatementResult(
1570: $finalScope,
1571: $finalScopeResult->hasYield() || $hasYield,
1572: $isAlwaysTerminating,
1573: $finalScopeResult->getExitPointsForOuterLoop(),
1574: array_merge($throwPoints, $finalScopeResult->getThrowPoints()),
1575: array_merge($impurePoints, $finalScopeResult->getImpurePoints()),
1576: );
1577: } elseif ($stmt instanceof Switch_) {
1578: $condResult = $this->processExprNode($stmt, $stmt->cond, $scope, $nodeCallback, ExpressionContext::createDeep());
1579: $scope = $condResult->getScope();
1580: $scopeForBranches = $scope;
1581: $finalScope = null;
1582: $prevScope = null;
1583: $hasDefaultCase = false;
1584: $alwaysTerminating = true;
1585: $hasYield = $condResult->hasYield();
1586: $exitPointsForOuterLoop = [];
1587: $throwPoints = $condResult->getThrowPoints();
1588: $impurePoints = $condResult->getImpurePoints();
1589: $fullCondExpr = null;
1590: foreach ($stmt->cases as $caseNode) {
1591: if ($caseNode->cond !== null) {
1592: $condExpr = new BinaryOp\Equal($stmt->cond, $caseNode->cond);
1593: $fullCondExpr = $fullCondExpr === null ? $condExpr : new BooleanOr($fullCondExpr, $condExpr);
1594: $caseResult = $this->processExprNode($stmt, $caseNode->cond, $scopeForBranches, $nodeCallback, ExpressionContext::createDeep());
1595: $scopeForBranches = $caseResult->getScope();
1596: $hasYield = $hasYield || $caseResult->hasYield();
1597: $throwPoints = array_merge($throwPoints, $caseResult->getThrowPoints());
1598: $impurePoints = array_merge($impurePoints, $caseResult->getImpurePoints());
1599: $branchScope = $caseResult->getTruthyScope()->filterByTruthyValue($condExpr);
1600: } else {
1601: $hasDefaultCase = true;
1602: $fullCondExpr = null;
1603: $branchScope = $scopeForBranches;
1604: }
1605:
1606: $branchScope = $branchScope->mergeWith($prevScope);
1607: $branchScopeResult = $this->processStmtNodes($caseNode, $caseNode->stmts, $branchScope, $nodeCallback, $context);
1608: $branchScope = $branchScopeResult->getScope();
1609: $branchFinalScopeResult = $branchScopeResult->filterOutLoopExitPoints();
1610: $hasYield = $hasYield || $branchFinalScopeResult->hasYield();
1611: foreach ($branchScopeResult->getExitPointsByType(Break_::class) as $breakExitPoint) {
1612: $alwaysTerminating = false;
1613: $finalScope = $breakExitPoint->getScope()->mergeWith($finalScope);
1614: }
1615: foreach ($branchScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
1616: $finalScope = $continueExitPoint->getScope()->mergeWith($finalScope);
1617: }
1618: $exitPointsForOuterLoop = array_merge($exitPointsForOuterLoop, $branchFinalScopeResult->getExitPointsForOuterLoop());
1619: $throwPoints = array_merge($throwPoints, $branchFinalScopeResult->getThrowPoints());
1620: $impurePoints = array_merge($impurePoints, $branchFinalScopeResult->getImpurePoints());
1621: if ($branchScopeResult->isAlwaysTerminating()) {
1622: $alwaysTerminating = $alwaysTerminating && $branchFinalScopeResult->isAlwaysTerminating();
1623: $prevScope = null;
1624: if (isset($fullCondExpr)) {
1625: $scopeForBranches = $scopeForBranches->filterByFalseyValue($fullCondExpr);
1626: $fullCondExpr = null;
1627: }
1628: if (!$branchFinalScopeResult->isAlwaysTerminating()) {
1629: $finalScope = $branchScope->mergeWith($finalScope);
1630: }
1631: } else {
1632: $prevScope = $branchScope;
1633: }
1634: }
1635:
1636: $exhaustive = $scopeForBranches->getType($stmt->cond) instanceof NeverType;
1637:
1638: if (!$hasDefaultCase && !$exhaustive) {
1639: $alwaysTerminating = false;
1640: }
1641:
1642: if ($prevScope !== null && isset($branchFinalScopeResult)) {
1643: $finalScope = $prevScope->mergeWith($finalScope);
1644: $alwaysTerminating = $alwaysTerminating && $branchFinalScopeResult->isAlwaysTerminating();
1645: }
1646:
1647: if ((!$hasDefaultCase && !$exhaustive) || $finalScope === null) {
1648: $finalScope = $scope->mergeWith($finalScope);
1649: }
1650:
1651: return new StatementResult($finalScope, $hasYield, $alwaysTerminating, $exitPointsForOuterLoop, $throwPoints, $impurePoints);
1652: } elseif ($stmt instanceof TryCatch) {
1653: $branchScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $scope, $nodeCallback, $context);
1654: $branchScope = $branchScopeResult->getScope();
1655: $finalScope = $branchScopeResult->isAlwaysTerminating() ? null : $branchScope;
1656:
1657: $exitPoints = [];
1658: $finallyExitPoints = [];
1659: $alwaysTerminating = $branchScopeResult->isAlwaysTerminating();
1660: $hasYield = $branchScopeResult->hasYield();
1661:
1662: if ($stmt->finally !== null) {
1663: $finallyScope = $branchScope;
1664: } else {
1665: $finallyScope = null;
1666: }
1667: foreach ($branchScopeResult->getExitPoints() as $exitPoint) {
1668: $finallyExitPoints[] = $exitPoint;
1669: if ($exitPoint->getStatement() instanceof Node\Stmt\Expression && $exitPoint->getStatement()->expr instanceof Expr\Throw_) {
1670: continue;
1671: }
1672: if ($finallyScope !== null) {
1673: $finallyScope = $finallyScope->mergeWith($exitPoint->getScope());
1674: }
1675: $exitPoints[] = $exitPoint;
1676: }
1677:
1678: $throwPoints = $branchScopeResult->getThrowPoints();
1679: $impurePoints = $branchScopeResult->getImpurePoints();
1680: $throwPointsForLater = [];
1681: $pastCatchTypes = new NeverType();
1682:
1683: foreach ($stmt->catches as $catchNode) {
1684: $nodeCallback($catchNode, $scope);
1685:
1686: $originalCatchTypes = array_map(static fn (Name $name): Type => new ObjectType($name->toString()), $catchNode->types);
1687: $catchTypes = array_map(static fn (Type $type): Type => TypeCombinator::remove($type, $pastCatchTypes), $originalCatchTypes);
1688:
1689: $originalCatchType = TypeCombinator::union(...$originalCatchTypes);
1690: $catchType = TypeCombinator::union(...$catchTypes);
1691: $pastCatchTypes = TypeCombinator::union($pastCatchTypes, $originalCatchType);
1692:
1693: $matchingThrowPoints = [];
1694: $matchingCatchTypes = array_fill_keys(array_keys($originalCatchTypes), false);
1695:
1696: // throwable matches all
1697: foreach ($originalCatchTypes as $catchTypeIndex => $catchTypeItem) {
1698: if (!$catchTypeItem->isSuperTypeOf(new ObjectType(Throwable::class))->yes()) {
1699: continue;
1700: }
1701:
1702: foreach ($throwPoints as $throwPointIndex => $throwPoint) {
1703: $matchingThrowPoints[$throwPointIndex] = $throwPoint;
1704: $matchingCatchTypes[$catchTypeIndex] = true;
1705: }
1706: }
1707:
1708: // explicit only
1709: $onlyExplicitIsThrow = true;
1710: if (count($matchingThrowPoints) === 0) {
1711: foreach ($throwPoints as $throwPointIndex => $throwPoint) {
1712: foreach ($catchTypes as $catchTypeIndex => $catchTypeItem) {
1713: if ($catchTypeItem->isSuperTypeOf($throwPoint->getType())->no()) {
1714: continue;
1715: }
1716:
1717: $matchingCatchTypes[$catchTypeIndex] = true;
1718: if (!$throwPoint->isExplicit()) {
1719: continue;
1720: }
1721: $throwNode = $throwPoint->getNode();
1722: if (
1723: !$throwNode instanceof Expr\Throw_
1724: && !($throwNode instanceof Node\Stmt\Expression && $throwNode->expr instanceof Expr\Throw_)
1725: ) {
1726: $onlyExplicitIsThrow = false;
1727: }
1728: $matchingThrowPoints[$throwPointIndex] = $throwPoint;
1729: }
1730: }
1731: }
1732:
1733: // implicit only
1734: if (count($matchingThrowPoints) === 0 || $onlyExplicitIsThrow) {
1735: foreach ($throwPoints as $throwPointIndex => $throwPoint) {
1736: if ($throwPoint->isExplicit()) {
1737: continue;
1738: }
1739:
1740: foreach ($catchTypes as $catchTypeIndex => $catchTypeItem) {
1741: if ($catchTypeItem->isSuperTypeOf($throwPoint->getType())->no()) {
1742: continue;
1743: }
1744:
1745: $matchingThrowPoints[$throwPointIndex] = $throwPoint;
1746: }
1747: }
1748: }
1749:
1750: // include previously removed throw points
1751: if (count($matchingThrowPoints) === 0) {
1752: if ($originalCatchType->isSuperTypeOf(new ObjectType(Throwable::class))->yes()) {
1753: foreach ($branchScopeResult->getThrowPoints() as $originalThrowPoint) {
1754: if (!$originalThrowPoint->canContainAnyThrowable()) {
1755: continue;
1756: }
1757:
1758: $matchingThrowPoints[] = $originalThrowPoint;
1759: $matchingCatchTypes = array_fill_keys(array_keys($originalCatchTypes), true);
1760: }
1761: }
1762: }
1763:
1764: // emit error
1765: foreach ($matchingCatchTypes as $catchTypeIndex => $matched) {
1766: if ($matched) {
1767: continue;
1768: }
1769: $nodeCallback(new CatchWithUnthrownExceptionNode($catchNode, $catchTypes[$catchTypeIndex], $originalCatchTypes[$catchTypeIndex]), $scope);
1770: }
1771:
1772: if (count($matchingThrowPoints) === 0) {
1773: continue;
1774: }
1775:
1776: // recompute throw points
1777: $newThrowPoints = [];
1778: foreach ($throwPoints as $throwPoint) {
1779: $newThrowPoint = $throwPoint->subtractCatchType($originalCatchType);
1780:
1781: if ($newThrowPoint->getType() instanceof NeverType) {
1782: continue;
1783: }
1784:
1785: $newThrowPoints[] = $newThrowPoint;
1786: }
1787: $throwPoints = $newThrowPoints;
1788:
1789: $catchScope = null;
1790: foreach ($matchingThrowPoints as $matchingThrowPoint) {
1791: if ($catchScope === null) {
1792: $catchScope = $matchingThrowPoint->getScope();
1793: } else {
1794: $catchScope = $catchScope->mergeWith($matchingThrowPoint->getScope());
1795: }
1796: }
1797:
1798: $variableName = null;
1799: if ($catchNode->var !== null) {
1800: if (!is_string($catchNode->var->name)) {
1801: throw new ShouldNotHappenException();
1802: }
1803:
1804: $variableName = $catchNode->var->name;
1805: }
1806:
1807: $catchScopeResult = $this->processStmtNodes($catchNode, $catchNode->stmts, $catchScope->enterCatchType($catchType, $variableName), $nodeCallback, $context);
1808: $catchScopeForFinally = $catchScopeResult->getScope();
1809:
1810: $finalScope = $catchScopeResult->isAlwaysTerminating() ? $finalScope : $catchScopeResult->getScope()->mergeWith($finalScope);
1811: $alwaysTerminating = $alwaysTerminating && $catchScopeResult->isAlwaysTerminating();
1812: $hasYield = $hasYield || $catchScopeResult->hasYield();
1813: $catchThrowPoints = $catchScopeResult->getThrowPoints();
1814: $impurePoints = array_merge($impurePoints, $catchScopeResult->getImpurePoints());
1815: $throwPointsForLater = array_merge($throwPointsForLater, $catchThrowPoints);
1816:
1817: if ($finallyScope !== null) {
1818: $finallyScope = $finallyScope->mergeWith($catchScopeForFinally);
1819: }
1820: foreach ($catchScopeResult->getExitPoints() as $exitPoint) {
1821: $finallyExitPoints[] = $exitPoint;
1822: if ($exitPoint->getStatement() instanceof Node\Stmt\Expression && $exitPoint->getStatement()->expr instanceof Expr\Throw_) {
1823: continue;
1824: }
1825: if ($finallyScope !== null) {
1826: $finallyScope = $finallyScope->mergeWith($exitPoint->getScope());
1827: }
1828: $exitPoints[] = $exitPoint;
1829: }
1830:
1831: foreach ($catchThrowPoints as $catchThrowPoint) {
1832: if ($finallyScope === null) {
1833: continue;
1834: }
1835: $finallyScope = $finallyScope->mergeWith($catchThrowPoint->getScope());
1836: }
1837: }
1838:
1839: if ($finalScope === null) {
1840: $finalScope = $scope;
1841: }
1842:
1843: foreach ($throwPoints as $throwPoint) {
1844: if ($finallyScope === null) {
1845: continue;
1846: }
1847: $finallyScope = $finallyScope->mergeWith($throwPoint->getScope());
1848: }
1849:
1850: if ($finallyScope !== null) {
1851: $originalFinallyScope = $finallyScope;
1852: $finallyResult = $this->processStmtNodes($stmt->finally, $stmt->finally->stmts, $finallyScope, $nodeCallback, $context);
1853: $alwaysTerminating = $alwaysTerminating || $finallyResult->isAlwaysTerminating();
1854: $hasYield = $hasYield || $finallyResult->hasYield();
1855: $throwPointsForLater = array_merge($throwPointsForLater, $finallyResult->getThrowPoints());
1856: $impurePoints = array_merge($impurePoints, $finallyResult->getImpurePoints());
1857: $finallyScope = $finallyResult->getScope();
1858: $finalScope = $finallyResult->isAlwaysTerminating() ? $finalScope : $finalScope->processFinallyScope($finallyScope, $originalFinallyScope);
1859: if (count($finallyResult->getExitPoints()) > 0) {
1860: $nodeCallback(new FinallyExitPointsNode(
1861: $finallyResult->getExitPoints(),
1862: $finallyExitPoints,
1863: ), $scope);
1864: }
1865: $exitPoints = array_merge($exitPoints, $finallyResult->getExitPoints());
1866: }
1867:
1868: return new StatementResult($finalScope, $hasYield, $alwaysTerminating, $exitPoints, array_merge($throwPoints, $throwPointsForLater), $impurePoints);
1869: } elseif ($stmt instanceof Unset_) {
1870: $hasYield = false;
1871: $throwPoints = [];
1872: $impurePoints = [];
1873: foreach ($stmt->vars as $var) {
1874: $scope = $this->lookForSetAllowedUndefinedExpressions($scope, $var);
1875: $exprResult = $this->processExprNode($stmt, $var, $scope, $nodeCallback, ExpressionContext::createDeep());
1876: $scope = $exprResult->getScope();
1877: $scope = $this->lookForUnsetAllowedUndefinedExpressions($scope, $var);
1878: $hasYield = $hasYield || $exprResult->hasYield();
1879: $throwPoints = array_merge($throwPoints, $exprResult->getThrowPoints());
1880: $impurePoints = array_merge($impurePoints, $exprResult->getImpurePoints());
1881: if ($var instanceof ArrayDimFetch && $var->dim !== null) {
1882: $cloningTraverser = new NodeTraverser();
1883: $cloningTraverser->addVisitor(new CloningVisitor());
1884:
1885: /** @var Expr $clonedVar */
1886: [$clonedVar] = $cloningTraverser->traverse([$var->var]);
1887:
1888: $traverser = new NodeTraverser();
1889: $traverser->addVisitor(new class () extends NodeVisitorAbstract {
1890:
1891: #[Override]
1892: public function leaveNode(Node $node): ?ExistingArrayDimFetch
1893: {
1894: if (!$node instanceof ArrayDimFetch || $node->dim === null) {
1895: return null;
1896: }
1897:
1898: return new ExistingArrayDimFetch($node->var, $node->dim);
1899: }
1900:
1901: });
1902:
1903: /** @var Expr $clonedVar */
1904: [$clonedVar] = $traverser->traverse([$clonedVar]);
1905: $scope = $this->processAssignVar(
1906: $scope,
1907: $stmt,
1908: $clonedVar,
1909: new UnsetOffsetExpr($var->var, $var->dim),
1910: static function (Node $node, Scope $scope) use ($nodeCallback): void {
1911: if (!$node instanceof PropertyAssignNode && !$node instanceof VariableAssignNode) {
1912: return;
1913: }
1914:
1915: $nodeCallback($node, $scope);
1916: },
1917: ExpressionContext::createDeep(),
1918: static fn (MutatingScope $scope): ExpressionResult => new ExpressionResult($scope, false, false, [], []),
1919: false,
1920: )->getScope();
1921: } elseif ($var instanceof PropertyFetch) {
1922: $scope = $scope->invalidateExpression($var);
1923: $impurePoints[] = new ImpurePoint(
1924: $scope,
1925: $var,
1926: 'propertyUnset',
1927: 'property unset',
1928: true,
1929: );
1930: } else {
1931: $scope = $scope->invalidateExpression($var);
1932: }
1933:
1934: }
1935: } elseif ($stmt instanceof Node\Stmt\Use_) {
1936: $hasYield = false;
1937: $throwPoints = [];
1938: $impurePoints = [];
1939: foreach ($stmt->uses as $use) {
1940: $nodeCallback($use, $scope);
1941: }
1942: } elseif ($stmt instanceof Node\Stmt\Global_) {
1943: $hasYield = false;
1944: $throwPoints = [];
1945: $impurePoints = [
1946: new ImpurePoint(
1947: $scope,
1948: $stmt,
1949: 'global',
1950: 'global variable',
1951: true,
1952: ),
1953: ];
1954: $vars = [];
1955: foreach ($stmt->vars as $var) {
1956: if (!$var instanceof Variable) {
1957: throw new ShouldNotHappenException();
1958: }
1959: $scope = $this->lookForSetAllowedUndefinedExpressions($scope, $var);
1960: $varResult = $this->processExprNode($stmt, $var, $scope, $nodeCallback, ExpressionContext::createDeep());
1961: $impurePoints = array_merge($impurePoints, $varResult->getImpurePoints());
1962: $scope = $this->lookForUnsetAllowedUndefinedExpressions($scope, $var);
1963:
1964: if (!is_string($var->name)) {
1965: continue;
1966: }
1967:
1968: $scope = $scope->assignVariable($var->name, new MixedType(), new MixedType(), TrinaryLogic::createYes());
1969: $vars[] = $var->name;
1970: }
1971: $scope = $this->processVarAnnotation($scope, $vars, $stmt);
1972: } elseif ($stmt instanceof Static_) {
1973: $hasYield = false;
1974: $throwPoints = [];
1975: $impurePoints = [
1976: new ImpurePoint(
1977: $scope,
1978: $stmt,
1979: 'static',
1980: 'static variable',
1981: true,
1982: ),
1983: ];
1984:
1985: $vars = [];
1986: foreach ($stmt->vars as $var) {
1987: if (!is_string($var->var->name)) {
1988: throw new ShouldNotHappenException();
1989: }
1990:
1991: if ($var->default !== null) {
1992: $defaultExprResult = $this->processExprNode($stmt, $var->default, $scope, $nodeCallback, ExpressionContext::createDeep());
1993: $impurePoints = array_merge($impurePoints, $defaultExprResult->getImpurePoints());
1994: }
1995:
1996: $scope = $scope->enterExpressionAssign($var->var);
1997: $varResult = $this->processExprNode($stmt, $var->var, $scope, $nodeCallback, ExpressionContext::createDeep());
1998: $impurePoints = array_merge($impurePoints, $varResult->getImpurePoints());
1999: $scope = $scope->exitExpressionAssign($var->var);
2000:
2001: $scope = $scope->assignVariable($var->var->name, new MixedType(), new MixedType(), TrinaryLogic::createYes());
2002: $vars[] = $var->var->name;
2003: }
2004:
2005: $scope = $this->processVarAnnotation($scope, $vars, $stmt);
2006: } elseif ($stmt instanceof Node\Stmt\Const_) {
2007: $hasYield = false;
2008: $throwPoints = [];
2009: $impurePoints = [];
2010: foreach ($stmt->consts as $const) {
2011: $nodeCallback($const, $scope);
2012: $constResult = $this->processExprNode($stmt, $const->value, $scope, $nodeCallback, ExpressionContext::createDeep());
2013: $impurePoints = array_merge($impurePoints, $constResult->getImpurePoints());
2014: if ($const->namespacedName !== null) {
2015: $constantName = new Name\FullyQualified($const->namespacedName->toString());
2016: } else {
2017: $constantName = new Name\FullyQualified($const->name->toString());
2018: }
2019: $scope = $scope->assignExpression(new ConstFetch($constantName), $scope->getType($const->value), $scope->getNativeType($const->value));
2020: }
2021: } elseif ($stmt instanceof Node\Stmt\ClassConst) {
2022: $hasYield = false;
2023: $throwPoints = [];
2024: $impurePoints = [];
2025: $this->processAttributeGroups($stmt, $stmt->attrGroups, $scope, $nodeCallback);
2026: foreach ($stmt->consts as $const) {
2027: $nodeCallback($const, $scope);
2028: $constResult = $this->processExprNode($stmt, $const->value, $scope, $nodeCallback, ExpressionContext::createDeep());
2029: $impurePoints = array_merge($impurePoints, $constResult->getImpurePoints());
2030: if ($scope->getClassReflection() === null) {
2031: throw new ShouldNotHappenException();
2032: }
2033: $scope = $scope->assignExpression(
2034: new Expr\ClassConstFetch(new Name\FullyQualified($scope->getClassReflection()->getName()), $const->name),
2035: $scope->getType($const->value),
2036: $scope->getNativeType($const->value),
2037: );
2038: }
2039: } elseif ($stmt instanceof Node\Stmt\EnumCase) {
2040: $hasYield = false;
2041: $throwPoints = [];
2042: $this->processAttributeGroups($stmt, $stmt->attrGroups, $scope, $nodeCallback);
2043: $impurePoints = [];
2044: if ($stmt->expr !== null) {
2045: $exprResult = $this->processExprNode($stmt, $stmt->expr, $scope, $nodeCallback, ExpressionContext::createDeep());
2046: $impurePoints = $exprResult->getImpurePoints();
2047: }
2048: } elseif ($stmt instanceof InlineHTML) {
2049: $hasYield = false;
2050: $throwPoints = [];
2051: $impurePoints = [
2052: new ImpurePoint($scope, $stmt, 'betweenPhpTags', 'output between PHP opening and closing tags', true),
2053: ];
2054: } elseif ($stmt instanceof Node\Stmt\Block) {
2055: $result = $this->processStmtNodes($stmt, $stmt->stmts, $scope, $nodeCallback, $context);
2056: if ($this->polluteScopeWithBlock) {
2057: return $result;
2058: }
2059:
2060: return new StatementResult(
2061: $scope->mergeWith($result->getScope()),
2062: $result->hasYield(),
2063: $result->isAlwaysTerminating(),
2064: $result->getExitPoints(),
2065: $result->getThrowPoints(),
2066: $result->getImpurePoints(),
2067: $result->getEndStatements(),
2068: );
2069: } elseif ($stmt instanceof Node\Stmt\Nop) {
2070: $hasYield = false;
2071: $throwPoints = $overridingThrowPoints ?? [];
2072: $impurePoints = [];
2073: } elseif ($stmt instanceof Node\Stmt\GroupUse) {
2074: $hasYield = false;
2075: $throwPoints = [];
2076: foreach ($stmt->uses as $use) {
2077: $nodeCallback($use, $scope);
2078: }
2079: $impurePoints = [];
2080: } else {
2081: $hasYield = false;
2082: $throwPoints = $overridingThrowPoints ?? [];
2083: $impurePoints = [];
2084: }
2085:
2086: return new StatementResult($scope, $hasYield, false, [], $throwPoints, $impurePoints);
2087: }
2088:
2089: /**
2090: * @return array{bool, string|null}
2091: */
2092: private function getDeprecatedAttribute(Scope $scope, Node\Stmt\Function_|Node\Stmt\ClassMethod|Node\PropertyHook $stmt): array
2093: {
2094: $initializerExprContext = InitializerExprContext::fromStubParameter(
2095: $scope->isInClass() ? $scope->getClassReflection()->getName() : null,
2096: $scope->getFile(),
2097: $stmt,
2098: );
2099: $isDeprecated = false;
2100: $deprecatedDescription = null;
2101: $deprecatedDescriptionType = null;
2102: foreach ($stmt->attrGroups as $attrGroup) {
2103: foreach ($attrGroup->attrs as $attr) {
2104: if ($attr->name->toString() !== 'Deprecated') {
2105: continue;
2106: }
2107: $isDeprecated = true;
2108: $arguments = $attr->args;
2109: foreach ($arguments as $i => $arg) {
2110: $argName = $arg->name;
2111: if ($argName === null) {
2112: if ($i !== 0) {
2113: continue;
2114: }
2115:
2116: $deprecatedDescriptionType = $this->initializerExprTypeResolver->getType($arg->value, $initializerExprContext);
2117: break;
2118: }
2119:
2120: if ($argName->toString() !== 'message') {
2121: continue;
2122: }
2123:
2124: $deprecatedDescriptionType = $this->initializerExprTypeResolver->getType($arg->value, $initializerExprContext);
2125: break;
2126: }
2127: }
2128: }
2129:
2130: if ($deprecatedDescriptionType !== null) {
2131: $constantStrings = $deprecatedDescriptionType->getConstantStrings();
2132: if (count($constantStrings) === 1) {
2133: $deprecatedDescription = $constantStrings[0]->getValue();
2134: }
2135: }
2136:
2137: return [$isDeprecated, $deprecatedDescription];
2138: }
2139:
2140: /**
2141: * @return ThrowPoint[]|null
2142: */
2143: private function getOverridingThrowPoints(Node\Stmt $statement, MutatingScope $scope): ?array
2144: {
2145: foreach ($statement->getComments() as $comment) {
2146: if (!$comment instanceof Doc) {
2147: continue;
2148: }
2149:
2150: $function = $scope->getFunction();
2151: $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
2152: $scope->getFile(),
2153: $scope->isInClass() ? $scope->getClassReflection()->getName() : null,
2154: $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
2155: $function !== null ? $function->getName() : null,
2156: $comment->getText(),
2157: );
2158:
2159: $throwsTag = $resolvedPhpDoc->getThrowsTag();
2160: if ($throwsTag !== null) {
2161: $throwsType = $throwsTag->getType();
2162: if ($throwsType->isVoid()->yes()) {
2163: return [];
2164: }
2165:
2166: return [ThrowPoint::createExplicit($scope, $throwsType, $statement, false)];
2167: }
2168: }
2169:
2170: return null;
2171: }
2172:
2173: private function getCurrentClassReflection(Node\Stmt\ClassLike $stmt, string $className, Scope $scope): ClassReflection
2174: {
2175: if (!$this->reflectionProvider->hasClass($className)) {
2176: return $this->createAstClassReflection($stmt, $className, $scope);
2177: }
2178:
2179: $defaultClassReflection = $this->reflectionProvider->getClass($className);
2180: if ($defaultClassReflection->getFileName() !== $scope->getFile()) {
2181: return $this->createAstClassReflection($stmt, $className, $scope);
2182: }
2183:
2184: $startLine = $defaultClassReflection->getNativeReflection()->getStartLine();
2185: if ($startLine !== $stmt->getStartLine()) {
2186: return $this->createAstClassReflection($stmt, $className, $scope);
2187: }
2188:
2189: return $defaultClassReflection;
2190: }
2191:
2192: private function createAstClassReflection(Node\Stmt\ClassLike $stmt, string $className, Scope $scope): ClassReflection
2193: {
2194: $nodeToReflection = new NodeToReflection();
2195: $betterReflectionClass = $nodeToReflection->__invoke(
2196: $this->reflector,
2197: $stmt,
2198: new LocatedSource(FileReader::read($scope->getFile()), $className, $scope->getFile()),
2199: $scope->getNamespace() !== null ? new Node\Stmt\Namespace_(new Name($scope->getNamespace())) : null,
2200: );
2201: if (!$betterReflectionClass instanceof \PHPStan\BetterReflection\Reflection\ReflectionClass) {
2202: throw new ShouldNotHappenException();
2203: }
2204:
2205: $enumAdapter = base64_decode('UEhQU3RhblxCZXR0ZXJSZWZsZWN0aW9uXFJlZmxlY3Rpb25cQWRhcHRlclxSZWZsZWN0aW9uRW51bQ==', true);
2206:
2207: return new ClassReflection(
2208: $this->reflectionProvider,
2209: $this->initializerExprTypeResolver,
2210: $this->fileTypeMapper,
2211: $this->stubPhpDocProvider,
2212: $this->phpDocInheritanceResolver,
2213: $this->phpVersion,
2214: $this->signatureMapProvider,
2215: $this->deprecationProvider,
2216: $this->attributeReflectionFactory,
2217: $this->classReflectionExtensionRegistryProvider->getRegistry()->getPropertiesClassReflectionExtensions(),
2218: $this->classReflectionExtensionRegistryProvider->getRegistry()->getMethodsClassReflectionExtensions(),
2219: $this->classReflectionExtensionRegistryProvider->getRegistry()->getAllowedSubTypesClassReflectionExtensions(),
2220: $this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsPropertyClassReflectionExtension(),
2221: $this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsMethodsClassReflectionExtension(),
2222: $betterReflectionClass->getName(),
2223: $betterReflectionClass instanceof ReflectionEnum && PHP_VERSION_ID >= 80000 ? new $enumAdapter($betterReflectionClass) : new ReflectionClass($betterReflectionClass),
2224: null,
2225: null,
2226: null,
2227: $this->universalObjectCratesClasses,
2228: sprintf('%s:%d', $scope->getFile(), $stmt->getStartLine()),
2229: );
2230: }
2231:
2232: private function lookForSetAllowedUndefinedExpressions(MutatingScope $scope, Expr $expr): MutatingScope
2233: {
2234: return $this->lookForExpressionCallback($scope, $expr, static fn (MutatingScope $scope, Expr $expr): MutatingScope => $scope->setAllowedUndefinedExpression($expr));
2235: }
2236:
2237: private function lookForUnsetAllowedUndefinedExpressions(MutatingScope $scope, Expr $expr): MutatingScope
2238: {
2239: return $this->lookForExpressionCallback($scope, $expr, static fn (MutatingScope $scope, Expr $expr): MutatingScope => $scope->unsetAllowedUndefinedExpression($expr));
2240: }
2241:
2242: /**
2243: * @param Closure(MutatingScope $scope, Expr $expr): MutatingScope $callback
2244: */
2245: private function lookForExpressionCallback(MutatingScope $scope, Expr $expr, Closure $callback): MutatingScope
2246: {
2247: if (!$expr instanceof ArrayDimFetch || $expr->dim !== null) {
2248: $scope = $callback($scope, $expr);
2249: }
2250:
2251: if ($expr instanceof ArrayDimFetch) {
2252: $scope = $this->lookForExpressionCallback($scope, $expr->var, $callback);
2253: } elseif ($expr instanceof PropertyFetch || $expr instanceof Expr\NullsafePropertyFetch) {
2254: $scope = $this->lookForExpressionCallback($scope, $expr->var, $callback);
2255: } elseif ($expr instanceof StaticPropertyFetch && $expr->class instanceof Expr) {
2256: $scope = $this->lookForExpressionCallback($scope, $expr->class, $callback);
2257: } elseif ($expr instanceof List_) {
2258: foreach ($expr->items as $item) {
2259: if ($item === null) {
2260: continue;
2261: }
2262:
2263: $scope = $this->lookForExpressionCallback($scope, $item->value, $callback);
2264: }
2265: }
2266:
2267: return $scope;
2268: }
2269:
2270: private function ensureShallowNonNullability(MutatingScope $scope, Scope $originalScope, Expr $exprToSpecify): EnsuredNonNullabilityResult
2271: {
2272: $exprType = $scope->getType($exprToSpecify);
2273: $isNull = $exprType->isNull();
2274: if ($isNull->yes()) {
2275: return new EnsuredNonNullabilityResult($scope, []);
2276: }
2277:
2278: // keep certainty
2279: $certainty = TrinaryLogic::createYes();
2280: $hasExpressionType = $originalScope->hasExpressionType($exprToSpecify);
2281: if (!$hasExpressionType->no()) {
2282: $certainty = $hasExpressionType;
2283: }
2284:
2285: $exprTypeWithoutNull = TypeCombinator::removeNull($exprType);
2286: if ($exprType->equals($exprTypeWithoutNull)) {
2287: $originalExprType = $originalScope->getType($exprToSpecify);
2288: if (!$originalExprType->equals($exprTypeWithoutNull)) {
2289: $originalNativeType = $originalScope->getNativeType($exprToSpecify);
2290:
2291: return new EnsuredNonNullabilityResult($scope, [
2292: new EnsuredNonNullabilityResultExpression($exprToSpecify, $originalExprType, $originalNativeType, $certainty),
2293: ]);
2294: }
2295: return new EnsuredNonNullabilityResult($scope, []);
2296: }
2297:
2298: $nativeType = $scope->getNativeType($exprToSpecify);
2299: $scope = $scope->specifyExpressionType(
2300: $exprToSpecify,
2301: $exprTypeWithoutNull,
2302: TypeCombinator::removeNull($nativeType),
2303: TrinaryLogic::createYes(),
2304: );
2305:
2306: return new EnsuredNonNullabilityResult(
2307: $scope,
2308: [
2309: new EnsuredNonNullabilityResultExpression($exprToSpecify, $exprType, $nativeType, $certainty),
2310: ],
2311: );
2312: }
2313:
2314: private function ensureNonNullability(MutatingScope $scope, Expr $expr): EnsuredNonNullabilityResult
2315: {
2316: $specifiedExpressions = [];
2317: $originalScope = $scope;
2318: $scope = $this->lookForExpressionCallback($scope, $expr, function ($scope, $expr) use (&$specifiedExpressions, $originalScope) {
2319: $result = $this->ensureShallowNonNullability($scope, $originalScope, $expr);
2320: foreach ($result->getSpecifiedExpressions() as $specifiedExpression) {
2321: $specifiedExpressions[] = $specifiedExpression;
2322: }
2323: return $result->getScope();
2324: });
2325:
2326: return new EnsuredNonNullabilityResult($scope, $specifiedExpressions);
2327: }
2328:
2329: /**
2330: * @param EnsuredNonNullabilityResultExpression[] $specifiedExpressions
2331: */
2332: private function revertNonNullability(MutatingScope $scope, array $specifiedExpressions): MutatingScope
2333: {
2334: foreach ($specifiedExpressions as $specifiedExpressionResult) {
2335: $scope = $scope->specifyExpressionType(
2336: $specifiedExpressionResult->getExpression(),
2337: $specifiedExpressionResult->getOriginalType(),
2338: $specifiedExpressionResult->getOriginalNativeType(),
2339: $specifiedExpressionResult->getCertainty(),
2340: );
2341: }
2342:
2343: return $scope;
2344: }
2345:
2346: private function findEarlyTerminatingExpr(Expr $expr, Scope $scope): ?Expr
2347: {
2348: if (($expr instanceof MethodCall || $expr instanceof Expr\StaticCall) && $expr->name instanceof Node\Identifier) {
2349: if (array_key_exists($expr->name->toLowerString(), $this->earlyTerminatingMethodNames)) {
2350: if ($expr instanceof MethodCall) {
2351: $methodCalledOnType = $scope->getType($expr->var);
2352: } else {
2353: if ($expr->class instanceof Name) {
2354: $methodCalledOnType = $scope->resolveTypeByName($expr->class);
2355: } else {
2356: $methodCalledOnType = $scope->getType($expr->class);
2357: }
2358: }
2359:
2360: foreach ($methodCalledOnType->getObjectClassNames() as $referencedClass) {
2361: if (!$this->reflectionProvider->hasClass($referencedClass)) {
2362: continue;
2363: }
2364:
2365: $classReflection = $this->reflectionProvider->getClass($referencedClass);
2366: foreach (array_merge([$referencedClass], $classReflection->getParentClassesNames(), $classReflection->getNativeReflection()->getInterfaceNames()) as $className) {
2367: if (!isset($this->earlyTerminatingMethodCalls[$className])) {
2368: continue;
2369: }
2370:
2371: if (in_array((string) $expr->name, $this->earlyTerminatingMethodCalls[$className], true)) {
2372: return $expr;
2373: }
2374: }
2375: }
2376: }
2377: }
2378:
2379: if ($expr instanceof FuncCall && $expr->name instanceof Name) {
2380: if (in_array((string) $expr->name, $this->earlyTerminatingFunctionCalls, true)) {
2381: return $expr;
2382: }
2383: }
2384:
2385: if ($expr instanceof Expr\Exit_ || $expr instanceof Expr\Throw_) {
2386: return $expr;
2387: }
2388:
2389: $exprType = $scope->getType($expr);
2390: if ($exprType instanceof NeverType && $exprType->isExplicit()) {
2391: return $expr;
2392: }
2393:
2394: return null;
2395: }
2396:
2397: /**
2398: * @param callable(Node $node, Scope $scope): void $nodeCallback
2399: */
2400: public function processExprNode(Node\Stmt $stmt, Expr $expr, MutatingScope $scope, callable $nodeCallback, ExpressionContext $context): ExpressionResult
2401: {
2402: if ($expr instanceof Expr\CallLike && $expr->isFirstClassCallable()) {
2403: if ($expr instanceof FuncCall) {
2404: $newExpr = new FunctionCallableNode($expr->name, $expr);
2405: } elseif ($expr instanceof MethodCall) {
2406: $newExpr = new MethodCallableNode($expr->var, $expr->name, $expr);
2407: } elseif ($expr instanceof StaticCall) {
2408: $newExpr = new StaticMethodCallableNode($expr->class, $expr->name, $expr);
2409: } elseif ($expr instanceof New_ && !$expr->class instanceof Class_) {
2410: $newExpr = new InstantiationCallableNode($expr->class, $expr);
2411: } else {
2412: throw new ShouldNotHappenException();
2413: }
2414:
2415: return $this->processExprNode($stmt, $newExpr, $scope, $nodeCallback, $context);
2416: }
2417:
2418: $this->callNodeCallbackWithExpression($nodeCallback, $expr, $scope, $context);
2419:
2420: if ($expr instanceof Variable) {
2421: $hasYield = false;
2422: $throwPoints = [];
2423: $impurePoints = [];
2424: $isAlwaysTerminating = false;
2425: if ($expr->name instanceof Expr) {
2426: return $this->processExprNode($stmt, $expr->name, $scope, $nodeCallback, $context->enterDeep());
2427: } elseif (in_array($expr->name, Scope::SUPERGLOBAL_VARIABLES, true)) {
2428: $impurePoints[] = new ImpurePoint($scope, $expr, 'superglobal', 'access to superglobal variable', true);
2429: }
2430: } elseif ($expr instanceof Assign || $expr instanceof AssignRef) {
2431: $result = $this->processAssignVar(
2432: $scope,
2433: $stmt,
2434: $expr->var,
2435: $expr->expr,
2436: $nodeCallback,
2437: $context,
2438: function (MutatingScope $scope) use ($stmt, $expr, $nodeCallback, $context): ExpressionResult {
2439: $impurePoints = [];
2440: if ($expr instanceof AssignRef) {
2441: $referencedExpr = $expr->expr;
2442: while ($referencedExpr instanceof ArrayDimFetch) {
2443: $referencedExpr = $referencedExpr->var;
2444: }
2445:
2446: if ($referencedExpr instanceof PropertyFetch || $referencedExpr instanceof StaticPropertyFetch) {
2447: $impurePoints[] = new ImpurePoint(
2448: $scope,
2449: $expr,
2450: 'propertyAssignByRef',
2451: 'property assignment by reference',
2452: false,
2453: );
2454: }
2455:
2456: $scope = $scope->enterExpressionAssign($expr->expr);
2457: }
2458:
2459: if ($expr->var instanceof Variable && is_string($expr->var->name)) {
2460: $context = $context->enterRightSideAssign(
2461: $expr->var->name,
2462: $scope->getType($expr->expr),
2463: $scope->getNativeType($expr->expr),
2464: );
2465: }
2466:
2467: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
2468: $hasYield = $result->hasYield();
2469: $throwPoints = $result->getThrowPoints();
2470: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
2471: $isAlwaysTerminating = $result->isAlwaysTerminating();
2472: $scope = $result->getScope();
2473:
2474: if ($expr instanceof AssignRef) {
2475: $scope = $scope->exitExpressionAssign($expr->expr);
2476: }
2477:
2478: return new ExpressionResult($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints);
2479: },
2480: true,
2481: );
2482: $scope = $result->getScope();
2483: $hasYield = $result->hasYield();
2484: $throwPoints = $result->getThrowPoints();
2485: $impurePoints = $result->getImpurePoints();
2486: $isAlwaysTerminating = $result->isAlwaysTerminating();
2487: $vars = $this->getAssignedVariables($expr->var);
2488: if (count($vars) > 0) {
2489: $varChangedScope = false;
2490: $scope = $this->processVarAnnotation($scope, $vars, $stmt, $varChangedScope);
2491: if (!$varChangedScope) {
2492: $scope = $this->processStmtVarAnnotation($scope, $stmt, null, $nodeCallback);
2493: }
2494: }
2495: } elseif ($expr instanceof Expr\AssignOp) {
2496: $result = $this->processAssignVar(
2497: $scope,
2498: $stmt,
2499: $expr->var,
2500: $expr,
2501: $nodeCallback,
2502: $context,
2503: function (MutatingScope $scope) use ($stmt, $expr, $nodeCallback, $context): ExpressionResult {
2504: $originalScope = $scope;
2505: if ($expr instanceof Expr\AssignOp\Coalesce) {
2506: $scope = $scope->filterByFalseyValue(
2507: new BinaryOp\NotIdentical($expr->var, new ConstFetch(new Name('null'))),
2508: );
2509: }
2510:
2511: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
2512: if ($expr instanceof Expr\AssignOp\Coalesce) {
2513: return new ExpressionResult(
2514: $result->getScope()->mergeWith($originalScope),
2515: $result->hasYield(),
2516: $result->isAlwaysTerminating(),
2517: $result->getThrowPoints(),
2518: $result->getImpurePoints(),
2519: );
2520: }
2521:
2522: return $result;
2523: },
2524: $expr instanceof Expr\AssignOp\Coalesce,
2525: );
2526: $scope = $result->getScope();
2527: $hasYield = $result->hasYield();
2528: $throwPoints = $result->getThrowPoints();
2529: $impurePoints = $result->getImpurePoints();
2530: $isAlwaysTerminating = $result->isAlwaysTerminating();
2531: if (
2532: ($expr instanceof Expr\AssignOp\Div || $expr instanceof Expr\AssignOp\Mod) &&
2533: !$scope->getType($expr->expr)->toNumber()->isSuperTypeOf(new ConstantIntegerType(0))->no()
2534: ) {
2535: $throwPoints[] = ThrowPoint::createExplicit($scope, new ObjectType(DivisionByZeroError::class), $expr, false);
2536: }
2537: } elseif ($expr instanceof FuncCall) {
2538: $parametersAcceptor = null;
2539: $functionReflection = null;
2540: $throwPoints = [];
2541: $impurePoints = [];
2542: $isAlwaysTerminating = false;
2543: if ($expr->name instanceof Expr) {
2544: $nameType = $scope->getType($expr->name);
2545: if (!$nameType->isCallable()->no()) {
2546: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
2547: $scope,
2548: $expr->getArgs(),
2549: $nameType->getCallableParametersAcceptors($scope),
2550: null,
2551: );
2552: }
2553:
2554: $nameResult = $this->processExprNode($stmt, $expr->name, $scope, $nodeCallback, $context->enterDeep());
2555: $scope = $nameResult->getScope();
2556: $throwPoints = $nameResult->getThrowPoints();
2557: $impurePoints = $nameResult->getImpurePoints();
2558: $isAlwaysTerminating = $nameResult->isAlwaysTerminating();
2559: if (
2560: $nameType->isObject()->yes()
2561: && $nameType->isCallable()->yes()
2562: && (new ObjectType(Closure::class))->isSuperTypeOf($nameType)->no()
2563: ) {
2564: $invokeResult = $this->processExprNode(
2565: $stmt,
2566: new MethodCall($expr->name, '__invoke', $expr->getArgs(), $expr->getAttributes()),
2567: $scope,
2568: static function (): void {
2569: },
2570: $context->enterDeep(),
2571: );
2572: $throwPoints = array_merge($throwPoints, $invokeResult->getThrowPoints());
2573: $impurePoints = array_merge($impurePoints, $invokeResult->getImpurePoints());
2574: $isAlwaysTerminating = $invokeResult->isAlwaysTerminating();
2575: } elseif ($parametersAcceptor instanceof CallableParametersAcceptor) {
2576: $callableThrowPoints = array_map(static fn (SimpleThrowPoint $throwPoint) => $throwPoint->isExplicit() ? ThrowPoint::createExplicit($scope, $throwPoint->getType(), $expr, $throwPoint->canContainAnyThrowable()) : ThrowPoint::createImplicit($scope, $expr), $parametersAcceptor->getThrowPoints());
2577: if (!$this->implicitThrows) {
2578: $callableThrowPoints = array_values(array_filter($callableThrowPoints, static fn (ThrowPoint $throwPoint) => $throwPoint->isExplicit()));
2579: }
2580: $throwPoints = array_merge($throwPoints, $callableThrowPoints);
2581: $impurePoints = array_merge($impurePoints, array_map(static fn (SimpleImpurePoint $impurePoint) => new ImpurePoint($scope, $expr, $impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain()), $parametersAcceptor->getImpurePoints()));
2582:
2583: $scope = $this->processImmediatelyCalledCallable($scope, $parametersAcceptor->getInvalidateExpressions(), $parametersAcceptor->getUsedVariables());
2584: }
2585: } elseif ($this->reflectionProvider->hasFunction($expr->name, $scope)) {
2586: $functionReflection = $this->reflectionProvider->getFunction($expr->name, $scope);
2587: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
2588: $scope,
2589: $expr->getArgs(),
2590: $functionReflection->getVariants(),
2591: $functionReflection->getNamedArgumentsVariants(),
2592: );
2593: $impurePoint = SimpleImpurePoint::createFromVariant($functionReflection, $parametersAcceptor);
2594: if ($impurePoint !== null) {
2595: $impurePoints[] = new ImpurePoint($scope, $expr, $impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain());
2596: }
2597: } else {
2598: $impurePoints[] = new ImpurePoint(
2599: $scope,
2600: $expr,
2601: 'functionCall',
2602: 'call to unknown function',
2603: false,
2604: );
2605: }
2606:
2607: if ($parametersAcceptor !== null) {
2608: $expr = ArgumentsNormalizer::reorderFuncArguments($parametersAcceptor, $expr) ?? $expr;
2609: $returnType = $parametersAcceptor->getReturnType();
2610: $isAlwaysTerminating = $isAlwaysTerminating || $returnType instanceof NeverType && $returnType->isExplicit();
2611: }
2612: $result = $this->processArgs($stmt, $functionReflection, null, $parametersAcceptor, $expr, $scope, $nodeCallback, $context);
2613: $scope = $result->getScope();
2614: $hasYield = $result->hasYield();
2615: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
2616: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
2617: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
2618:
2619: if ($functionReflection !== null) {
2620: $functionThrowPoint = $this->getFunctionThrowPoint($functionReflection, $parametersAcceptor, $expr, $scope);
2621: if ($functionThrowPoint !== null) {
2622: $throwPoints[] = $functionThrowPoint;
2623: }
2624: } else {
2625: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
2626: }
2627:
2628: if (
2629: $parametersAcceptor instanceof ClosureType && count($parametersAcceptor->getImpurePoints()) > 0
2630: && $scope->isInClass()
2631: ) {
2632: $scope = $scope->invalidateExpression(new Variable('this'), true);
2633: }
2634:
2635: if (
2636: $functionReflection !== null
2637: && in_array($functionReflection->getName(), ['json_encode', 'json_decode'], true)
2638: ) {
2639: $scope = $scope->invalidateExpression(new FuncCall(new Name('json_last_error'), []))
2640: ->invalidateExpression(new FuncCall(new Name\FullyQualified('json_last_error'), []))
2641: ->invalidateExpression(new FuncCall(new Name('json_last_error_msg'), []))
2642: ->invalidateExpression(new FuncCall(new Name\FullyQualified('json_last_error_msg'), []));
2643: }
2644:
2645: if (
2646: $functionReflection !== null
2647: && $functionReflection->getName() === 'file_put_contents'
2648: && count($expr->getArgs()) > 0
2649: ) {
2650: $scope = $scope->invalidateExpression(new FuncCall(new Name('file_get_contents'), [$expr->getArgs()[0]]))
2651: ->invalidateExpression(new FuncCall(new Name\FullyQualified('file_get_contents'), [$expr->getArgs()[0]]));
2652: }
2653:
2654: if (
2655: $functionReflection !== null
2656: && in_array($functionReflection->getName(), ['array_pop', 'array_shift'], true)
2657: && count($expr->getArgs()) >= 1
2658: ) {
2659: $arrayArg = $expr->getArgs()[0]->value;
2660:
2661: $arrayArgType = $scope->getType($arrayArg);
2662: $arrayArgNativeType = $scope->getNativeType($arrayArg);
2663:
2664: $isArrayPop = $functionReflection->getName() === 'array_pop';
2665: $scope = $scope->invalidateExpression($arrayArg)->assignExpression(
2666: $arrayArg,
2667: $isArrayPop ? $arrayArgType->popArray() : $arrayArgType->shiftArray(),
2668: $isArrayPop ? $arrayArgNativeType->popArray() : $arrayArgNativeType->shiftArray(),
2669: );
2670: }
2671:
2672: if (
2673: $functionReflection !== null
2674: && in_array($functionReflection->getName(), ['array_push', 'array_unshift'], true)
2675: && count($expr->getArgs()) >= 2
2676: ) {
2677: $arrayType = $this->getArrayFunctionAppendingType($functionReflection, $scope, $expr);
2678: $arrayNativeType = $this->getArrayFunctionAppendingType($functionReflection, $scope->doNotTreatPhpDocTypesAsCertain(), $expr);
2679:
2680: $arrayArg = $expr->getArgs()[0]->value;
2681: $scope = $scope->invalidateExpression($arrayArg)->assignExpression($arrayArg, $arrayType, $arrayNativeType);
2682: }
2683:
2684: if (
2685: $functionReflection !== null
2686: && in_array($functionReflection->getName(), ['fopen', 'file_get_contents'], true)
2687: ) {
2688: $scope = $scope->assignVariable('http_response_header', TypeCombinator::intersect(new ArrayType(new IntegerType(), new StringType()), new AccessoryArrayListType()), new ArrayType(new IntegerType(), new StringType()), TrinaryLogic::createYes());
2689: }
2690:
2691: if (
2692: $functionReflection !== null
2693: && $functionReflection->getName() === 'shuffle'
2694: ) {
2695: $arrayArg = $expr->getArgs()[0]->value;
2696: $scope = $scope->assignExpression(
2697: $arrayArg,
2698: $scope->getType($arrayArg)->shuffleArray(),
2699: $scope->getNativeType($arrayArg)->shuffleArray(),
2700: );
2701: }
2702:
2703: if (
2704: $functionReflection !== null
2705: && $functionReflection->getName() === 'array_splice'
2706: && count($expr->getArgs()) >= 2
2707: ) {
2708: $arrayArg = $expr->getArgs()[0]->value;
2709: $arrayArgType = $scope->getType($arrayArg);
2710: $arrayArgNativeType = $scope->getNativeType($arrayArg);
2711:
2712: $offsetType = $scope->getType($expr->getArgs()[1]->value);
2713: $lengthType = isset($expr->getArgs()[2]) ? $scope->getType($expr->getArgs()[2]->value) : new NullType();
2714: $replacementType = isset($expr->getArgs()[3]) ? $scope->getType($expr->getArgs()[3]->value) : new ConstantArrayType([], []);
2715:
2716: $scope = $scope->invalidateExpression($arrayArg)->assignExpression(
2717: $arrayArg,
2718: $arrayArgType->spliceArray($offsetType, $lengthType, $replacementType),
2719: $arrayArgNativeType->spliceArray($offsetType, $lengthType, $replacementType),
2720: );
2721: }
2722:
2723: if (
2724: $functionReflection !== null
2725: && in_array($functionReflection->getName(), ['sort', 'rsort', 'usort'], true)
2726: && count($expr->getArgs()) >= 1
2727: ) {
2728: $arrayArg = $expr->getArgs()[0]->value;
2729: $scope = $scope->assignExpression(
2730: $arrayArg,
2731: $this->getArraySortPreserveListFunctionType($scope->getType($arrayArg)),
2732: $this->getArraySortPreserveListFunctionType($scope->getNativeType($arrayArg)),
2733: );
2734: }
2735:
2736: if (
2737: $functionReflection !== null
2738: && in_array($functionReflection->getName(), ['natcasesort', 'natsort', 'arsort', 'asort', 'ksort', 'krsort', 'uasort', 'uksort'], true)
2739: && count($expr->getArgs()) >= 1
2740: ) {
2741: $arrayArg = $expr->getArgs()[0]->value;
2742: $scope = $scope->assignExpression(
2743: $arrayArg,
2744: $this->getArraySortDoNotPreserveListFunctionType($scope->getType($arrayArg)),
2745: $this->getArraySortDoNotPreserveListFunctionType($scope->getNativeType($arrayArg)),
2746: );
2747: }
2748:
2749: if (
2750: $functionReflection !== null
2751: && $functionReflection->getName() === 'extract'
2752: ) {
2753: $extractedArg = $expr->getArgs()[0]->value;
2754: $extractedType = $scope->getType($extractedArg);
2755: $constantArrays = $extractedType->getConstantArrays();
2756: if (count($constantArrays) > 0) {
2757: $properties = [];
2758: $optionalProperties = [];
2759: $refCount = [];
2760: foreach ($constantArrays as $constantArray) {
2761: foreach ($constantArray->getKeyTypes() as $i => $keyType) {
2762: if ($keyType->isString()->no()) {
2763: // integers as variable names not allowed
2764: continue;
2765: }
2766: $key = (string) $keyType->getValue();
2767: $valueType = $constantArray->getValueTypes()[$i];
2768: $optional = $constantArray->isOptionalKey($i);
2769: if ($optional) {
2770: $optionalProperties[] = $key;
2771: }
2772: if (isset($properties[$key])) {
2773: $properties[$key] = TypeCombinator::union($properties[$key], $valueType);
2774: $refCount[$key]++;
2775: } else {
2776: $properties[$key] = $valueType;
2777: $refCount[$key] = 1;
2778: }
2779: }
2780: }
2781: foreach ($properties as $name => $type) {
2782: $optional = in_array($name, $optionalProperties, true) || $refCount[$name] < count($constantArrays);
2783: $scope = $scope->assignVariable($name, $type, $type, $optional ? TrinaryLogic::createMaybe() : TrinaryLogic::createYes());
2784: }
2785: } else {
2786: $scope = $scope->afterExtractCall();
2787: }
2788: }
2789:
2790: if (
2791: $functionReflection !== null
2792: && in_array($functionReflection->getName(), ['clearstatcache', 'unlink'], true)
2793: ) {
2794: $scope = $scope->afterClearstatcacheCall();
2795: }
2796:
2797: if (
2798: $functionReflection !== null
2799: && str_starts_with($functionReflection->getName(), 'openssl')
2800: ) {
2801: $scope = $scope->afterOpenSslCall($functionReflection->getName());
2802: }
2803:
2804: } elseif ($expr instanceof MethodCall) {
2805: $originalScope = $scope;
2806: if (
2807: ($expr->var instanceof Expr\Closure || $expr->var instanceof Expr\ArrowFunction)
2808: && $expr->name instanceof Node\Identifier
2809: && strtolower($expr->name->name) === 'call'
2810: && isset($expr->getArgs()[0])
2811: ) {
2812: $closureCallScope = $scope->enterClosureCall(
2813: $scope->getType($expr->getArgs()[0]->value),
2814: $scope->getNativeType($expr->getArgs()[0]->value),
2815: );
2816: }
2817:
2818: $result = $this->processExprNode($stmt, $expr->var, $closureCallScope ?? $scope, $nodeCallback, $context->enterDeep());
2819: $hasYield = $result->hasYield();
2820: $throwPoints = $result->getThrowPoints();
2821: $impurePoints = $result->getImpurePoints();
2822: $isAlwaysTerminating = $result->isAlwaysTerminating();
2823: $scope = $result->getScope();
2824: if (isset($closureCallScope)) {
2825: $scope = $scope->restoreOriginalScopeAfterClosureBind($originalScope);
2826: }
2827: $parametersAcceptor = null;
2828: $methodReflection = null;
2829: $calledOnType = $scope->getType($expr->var);
2830: if ($expr->name instanceof Expr) {
2831: $methodNameResult = $this->processExprNode($stmt, $expr->name, $scope, $nodeCallback, $context->enterDeep());
2832: $throwPoints = array_merge($throwPoints, $methodNameResult->getThrowPoints());
2833: $scope = $methodNameResult->getScope();
2834: } else {
2835: $methodName = $expr->name->name;
2836: $methodReflection = $scope->getMethodReflection($calledOnType, $methodName);
2837: if ($methodReflection !== null) {
2838: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
2839: $scope,
2840: $expr->getArgs(),
2841: $methodReflection->getVariants(),
2842: $methodReflection->getNamedArgumentsVariants(),
2843: );
2844:
2845: $methodThrowPoint = $this->getMethodThrowPoint($methodReflection, $parametersAcceptor, $expr, $scope);
2846: if ($methodThrowPoint !== null) {
2847: $throwPoints[] = $methodThrowPoint;
2848: }
2849: }
2850: }
2851:
2852: if ($methodReflection !== null) {
2853: $impurePoint = SimpleImpurePoint::createFromVariant($methodReflection, $parametersAcceptor);
2854: if ($impurePoint !== null) {
2855: $impurePoints[] = new ImpurePoint($scope, $expr, $impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain());
2856: }
2857: } else {
2858: $impurePoints[] = new ImpurePoint(
2859: $scope,
2860: $expr,
2861: 'methodCall',
2862: 'call to unknown method',
2863: false,
2864: );
2865: }
2866:
2867: if ($parametersAcceptor !== null) {
2868: $expr = ArgumentsNormalizer::reorderMethodArguments($parametersAcceptor, $expr) ?? $expr;
2869: $returnType = $parametersAcceptor->getReturnType();
2870: $isAlwaysTerminating = $returnType instanceof NeverType && $returnType->isExplicit();
2871: }
2872:
2873: $result = $this->processArgs(
2874: $stmt,
2875: $methodReflection,
2876: $methodReflection !== null ? $scope->getNakedMethod($calledOnType, $methodReflection->getName()) : null,
2877: $parametersAcceptor,
2878: $expr,
2879: $scope,
2880: $nodeCallback,
2881: $context,
2882: );
2883: $scope = $result->getScope();
2884:
2885: if ($methodReflection !== null) {
2886: $hasSideEffects = $methodReflection->hasSideEffects();
2887: if ($hasSideEffects->yes() || $methodReflection->getName() === '__construct') {
2888: $nodeCallback(new InvalidateExprNode($expr->var), $scope);
2889: $scope = $scope->invalidateExpression($expr->var, true);
2890: }
2891: if ($parametersAcceptor !== null && !$methodReflection->isStatic()) {
2892: $selfOutType = $methodReflection->getSelfOutType();
2893: if ($selfOutType !== null) {
2894: $scope = $scope->assignExpression(
2895: $expr->var,
2896: TemplateTypeHelper::resolveTemplateTypes(
2897: $selfOutType,
2898: $parametersAcceptor->getResolvedTemplateTypeMap(),
2899: $parametersAcceptor instanceof ExtendedParametersAcceptor ? $parametersAcceptor->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
2900: TemplateTypeVariance::createCovariant(),
2901: ),
2902: $scope->getNativeType($expr->var),
2903: );
2904: }
2905: }
2906:
2907: if (
2908: $scope->isInClass()
2909: && $scope->getClassReflection()->getName() === $methodReflection->getDeclaringClass()->getName()
2910: /*&& (
2911: // should not be allowed but in practice has to be
2912: $scope->getClassReflection()->isFinal()
2913: || $methodReflection->isFinal()->yes()
2914: || $methodReflection->isPrivate()
2915: )*/
2916: && TypeUtils::findThisType($calledOnType) !== null
2917: ) {
2918: $calledMethodScope = $this->processCalledMethod($methodReflection);
2919: if ($calledMethodScope !== null) {
2920: $scope = $scope->mergeInitializedProperties($calledMethodScope);
2921: }
2922: }
2923: } else {
2924: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
2925: }
2926: $hasYield = $hasYield || $result->hasYield();
2927: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
2928: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
2929: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
2930: } elseif ($expr instanceof Expr\NullsafeMethodCall) {
2931: $nonNullabilityResult = $this->ensureShallowNonNullability($scope, $scope, $expr->var);
2932: $exprResult = $this->processExprNode($stmt, new MethodCall($expr->var, $expr->name, $expr->args, array_merge($expr->getAttributes(), ['virtualNullsafeMethodCall' => true])), $nonNullabilityResult->getScope(), $nodeCallback, $context);
2933: $scope = $this->revertNonNullability($exprResult->getScope(), $nonNullabilityResult->getSpecifiedExpressions());
2934:
2935: return new ExpressionResult(
2936: $scope,
2937: $exprResult->hasYield(),
2938: false,
2939: $exprResult->getThrowPoints(),
2940: $exprResult->getImpurePoints(),
2941: static fn (): MutatingScope => $scope->filterByTruthyValue($expr),
2942: static fn (): MutatingScope => $scope->filterByFalseyValue($expr),
2943: );
2944: } elseif ($expr instanceof StaticCall) {
2945: $hasYield = false;
2946: $throwPoints = [];
2947: $impurePoints = [];
2948: $isAlwaysTerminating = false;
2949: if ($expr->class instanceof Expr) {
2950: $objectClasses = $scope->getType($expr->class)->getObjectClassNames();
2951: if (count($objectClasses) !== 1) {
2952: $objectClasses = $scope->getType(new New_($expr->class))->getObjectClassNames();
2953: }
2954: if (count($objectClasses) === 1) {
2955: $objectExprResult = $this->processExprNode($stmt, new StaticCall(new Name($objectClasses[0]), $expr->name, []), $scope, static function (): void {
2956: }, $context->enterDeep());
2957: $additionalThrowPoints = $objectExprResult->getThrowPoints();
2958: } else {
2959: $additionalThrowPoints = [ThrowPoint::createImplicit($scope, $expr)];
2960: }
2961: $classResult = $this->processExprNode($stmt, $expr->class, $scope, $nodeCallback, $context->enterDeep());
2962: $hasYield = $classResult->hasYield();
2963: $throwPoints = array_merge($throwPoints, $classResult->getThrowPoints());
2964: $impurePoints = array_merge($impurePoints, $classResult->getImpurePoints());
2965: $isAlwaysTerminating = $classResult->isAlwaysTerminating();
2966: foreach ($additionalThrowPoints as $throwPoint) {
2967: $throwPoints[] = $throwPoint;
2968: }
2969: $scope = $classResult->getScope();
2970: }
2971:
2972: $parametersAcceptor = null;
2973: $methodReflection = null;
2974: if ($expr->name instanceof Expr) {
2975: $result = $this->processExprNode($stmt, $expr->name, $scope, $nodeCallback, $context->enterDeep());
2976: $hasYield = $hasYield || $result->hasYield();
2977: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
2978: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
2979: $scope = $result->getScope();
2980: } elseif ($expr->class instanceof Name) {
2981: $classType = $scope->resolveTypeByName($expr->class);
2982: $methodName = $expr->name->name;
2983: if ($classType->hasMethod($methodName)->yes()) {
2984: $methodReflection = $classType->getMethod($methodName, $scope);
2985: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
2986: $scope,
2987: $expr->getArgs(),
2988: $methodReflection->getVariants(),
2989: $methodReflection->getNamedArgumentsVariants(),
2990: );
2991:
2992: $methodThrowPoint = $this->getStaticMethodThrowPoint($methodReflection, $parametersAcceptor, $expr, $scope);
2993: if ($methodThrowPoint !== null) {
2994: $throwPoints[] = $methodThrowPoint;
2995: }
2996:
2997: $declaringClass = $methodReflection->getDeclaringClass();
2998: if (
2999: $declaringClass->getName() === 'Closure'
3000: && strtolower($methodName) === 'bind'
3001: ) {
3002: $thisType = null;
3003: $nativeThisType = null;
3004: if (isset($expr->getArgs()[1])) {
3005: $argType = $scope->getType($expr->getArgs()[1]->value);
3006: if ($argType->isNull()->yes()) {
3007: $thisType = null;
3008: } else {
3009: $thisType = $argType;
3010: }
3011:
3012: $nativeArgType = $scope->getNativeType($expr->getArgs()[1]->value);
3013: if ($nativeArgType->isNull()->yes()) {
3014: $nativeThisType = null;
3015: } else {
3016: $nativeThisType = $nativeArgType;
3017: }
3018: }
3019: $scopeClasses = ['static'];
3020: if (isset($expr->getArgs()[2])) {
3021: $argValue = $expr->getArgs()[2]->value;
3022: $argValueType = $scope->getType($argValue);
3023:
3024: $directClassNames = $argValueType->getObjectClassNames();
3025: if (count($directClassNames) > 0) {
3026: $scopeClasses = $directClassNames;
3027: $thisTypes = [];
3028: foreach ($directClassNames as $directClassName) {
3029: $thisTypes[] = new ObjectType($directClassName);
3030: }
3031: $thisType = TypeCombinator::union(...$thisTypes);
3032: } else {
3033: $thisType = $argValueType->getClassStringObjectType();
3034: $scopeClasses = $thisType->getObjectClassNames();
3035: }
3036: }
3037: $closureBindScope = $scope->enterClosureBind($thisType, $nativeThisType, $scopeClasses);
3038: }
3039: } else {
3040: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
3041: }
3042: }
3043:
3044: if ($methodReflection !== null) {
3045: $impurePoint = SimpleImpurePoint::createFromVariant($methodReflection, $parametersAcceptor);
3046: if ($impurePoint !== null) {
3047: $impurePoints[] = new ImpurePoint($scope, $expr, $impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain());
3048: }
3049: } else {
3050: $impurePoints[] = new ImpurePoint(
3051: $scope,
3052: $expr,
3053: 'methodCall',
3054: 'call to unknown method',
3055: false,
3056: );
3057: }
3058:
3059: if ($parametersAcceptor !== null) {
3060: $expr = ArgumentsNormalizer::reorderStaticCallArguments($parametersAcceptor, $expr) ?? $expr;
3061: $returnType = $parametersAcceptor->getReturnType();
3062: $isAlwaysTerminating = $returnType instanceof NeverType && $returnType->isExplicit();
3063: }
3064: $result = $this->processArgs($stmt, $methodReflection, null, $parametersAcceptor, $expr, $scope, $nodeCallback, $context, $closureBindScope ?? null);
3065: $scope = $result->getScope();
3066: $scopeFunction = $scope->getFunction();
3067:
3068: if (
3069: $methodReflection !== null
3070: && (
3071: $methodReflection->hasSideEffects()->yes()
3072: || (
3073: !$methodReflection->isStatic()
3074: && $methodReflection->getName() === '__construct'
3075: )
3076: )
3077: && $scope->isInClass()
3078: && $scope->getClassReflection()->is($methodReflection->getDeclaringClass()->getName())
3079: ) {
3080: $scope = $scope->invalidateExpression(new Variable('this'), true);
3081: }
3082:
3083: if (
3084: $methodReflection !== null
3085: && !$methodReflection->isStatic()
3086: && $methodReflection->getName() === '__construct'
3087: && $scopeFunction instanceof MethodReflection
3088: && !$scopeFunction->isStatic()
3089: && $scope->isInClass()
3090: && $scope->getClassReflection()->isSubclassOfClass($methodReflection->getDeclaringClass())
3091: ) {
3092: $thisType = $scope->getType(new Variable('this'));
3093: $methodClassReflection = $methodReflection->getDeclaringClass();
3094: foreach ($methodClassReflection->getNativeReflection()->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED) as $property) {
3095: if (!$property->isPromoted() || $property->getDeclaringClass()->getName() !== $methodClassReflection->getName()) {
3096: continue;
3097: }
3098:
3099: $scope = $scope->assignInitializedProperty($thisType, $property->getName());
3100: }
3101: }
3102:
3103: $hasYield = $hasYield || $result->hasYield();
3104: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3105: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3106: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3107: } elseif ($expr instanceof PropertyFetch) {
3108: $scopeBeforeVar = $scope;
3109: $result = $this->processExprNode($stmt, $expr->var, $scope, $nodeCallback, $context->enterDeep());
3110: $hasYield = $result->hasYield();
3111: $throwPoints = $result->getThrowPoints();
3112: $impurePoints = $result->getImpurePoints();
3113: $isAlwaysTerminating = $result->isAlwaysTerminating();
3114: $scope = $result->getScope();
3115: if ($expr->name instanceof Expr) {
3116: $result = $this->processExprNode($stmt, $expr->name, $scope, $nodeCallback, $context->enterDeep());
3117: $hasYield = $hasYield || $result->hasYield();
3118: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3119: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3120: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3121: $scope = $result->getScope();
3122: if ($this->phpVersion->supportsPropertyHooks()) {
3123: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
3124: }
3125: } else {
3126: $propertyName = $expr->name->toString();
3127: $propertyHolderType = $scopeBeforeVar->getType($expr->var);
3128: $propertyReflection = $scopeBeforeVar->getPropertyReflection($propertyHolderType, $propertyName);
3129: if ($propertyReflection !== null && $this->phpVersion->supportsPropertyHooks()) {
3130: $propertyDeclaringClass = $propertyReflection->getDeclaringClass();
3131: if ($propertyDeclaringClass->hasNativeProperty($propertyName)) {
3132: $nativeProperty = $propertyDeclaringClass->getNativeProperty($propertyName);
3133: $throwPoints = array_merge($throwPoints, $this->getPropertyReadThrowPointsFromGetHook($scopeBeforeVar, $expr, $nativeProperty));
3134: }
3135: }
3136: }
3137: } elseif ($expr instanceof Expr\NullsafePropertyFetch) {
3138: $nonNullabilityResult = $this->ensureShallowNonNullability($scope, $scope, $expr->var);
3139: $exprResult = $this->processExprNode($stmt, new PropertyFetch($expr->var, $expr->name, array_merge($expr->getAttributes(), ['virtualNullsafePropertyFetch' => true])), $nonNullabilityResult->getScope(), $nodeCallback, $context);
3140: $scope = $this->revertNonNullability($exprResult->getScope(), $nonNullabilityResult->getSpecifiedExpressions());
3141:
3142: return new ExpressionResult(
3143: $scope,
3144: $exprResult->hasYield(),
3145: false,
3146: $exprResult->getThrowPoints(),
3147: $exprResult->getImpurePoints(),
3148: static fn (): MutatingScope => $scope->filterByTruthyValue($expr),
3149: static fn (): MutatingScope => $scope->filterByFalseyValue($expr),
3150: );
3151: } elseif ($expr instanceof StaticPropertyFetch) {
3152: $hasYield = false;
3153: $throwPoints = [];
3154: $impurePoints = [
3155: new ImpurePoint(
3156: $scope,
3157: $expr,
3158: 'staticPropertyAccess',
3159: 'static property access',
3160: true,
3161: ),
3162: ];
3163: $isAlwaysTerminating = false;
3164: if ($expr->class instanceof Expr) {
3165: $result = $this->processExprNode($stmt, $expr->class, $scope, $nodeCallback, $context->enterDeep());
3166: $hasYield = $result->hasYield();
3167: $throwPoints = $result->getThrowPoints();
3168: $impurePoints = $result->getImpurePoints();
3169: $isAlwaysTerminating = $result->isAlwaysTerminating();
3170: $scope = $result->getScope();
3171: }
3172: if ($expr->name instanceof Expr) {
3173: $result = $this->processExprNode($stmt, $expr->name, $scope, $nodeCallback, $context->enterDeep());
3174: $hasYield = $hasYield || $result->hasYield();
3175: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3176: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3177: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3178: $scope = $result->getScope();
3179: }
3180: } elseif ($expr instanceof Expr\Closure) {
3181: $processClosureResult = $this->processClosureNode($stmt, $expr, $scope, $nodeCallback, $context, null);
3182:
3183: return new ExpressionResult(
3184: $processClosureResult->getScope(),
3185: false,
3186: false,
3187: [],
3188: [],
3189: );
3190: } elseif ($expr instanceof Expr\ArrowFunction) {
3191: $result = $this->processArrowFunctionNode($stmt, $expr, $scope, $nodeCallback, null);
3192: return new ExpressionResult(
3193: $result->getScope(),
3194: $result->hasYield(),
3195: $result->isAlwaysTerminating(),
3196: [],
3197: [],
3198: );
3199: } elseif ($expr instanceof ErrorSuppress) {
3200: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context);
3201: $hasYield = $result->hasYield();
3202: $throwPoints = $result->getThrowPoints();
3203: $impurePoints = $result->getImpurePoints();
3204: $isAlwaysTerminating = $result->isAlwaysTerminating();
3205: $scope = $result->getScope();
3206: } elseif ($expr instanceof Exit_) {
3207: $hasYield = false;
3208: $throwPoints = [];
3209: $kind = $expr->getAttribute('kind', Exit_::KIND_EXIT);
3210: $identifier = $kind === Exit_::KIND_DIE ? 'die' : 'exit';
3211: $impurePoints = [
3212: new ImpurePoint($scope, $expr, $identifier, $identifier, true),
3213: ];
3214: $isAlwaysTerminating = true;
3215: if ($expr->expr !== null) {
3216: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3217: $hasYield = $result->hasYield();
3218: $throwPoints = $result->getThrowPoints();
3219: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3220: $scope = $result->getScope();
3221: }
3222: } elseif ($expr instanceof Node\Scalar\InterpolatedString) {
3223: $hasYield = false;
3224: $throwPoints = [];
3225: $impurePoints = [];
3226: $isAlwaysTerminating = false;
3227: foreach ($expr->parts as $part) {
3228: if (!$part instanceof Expr) {
3229: continue;
3230: }
3231: $result = $this->processExprNode($stmt, $part, $scope, $nodeCallback, $context->enterDeep());
3232: $hasYield = $hasYield || $result->hasYield();
3233: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3234: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3235: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3236: $scope = $result->getScope();
3237: }
3238: } elseif ($expr instanceof ArrayDimFetch) {
3239: $hasYield = false;
3240: $throwPoints = [];
3241: $impurePoints = [];
3242: $isAlwaysTerminating = false;
3243: if ($expr->dim !== null) {
3244: $result = $this->processExprNode($stmt, $expr->dim, $scope, $nodeCallback, $context->enterDeep());
3245: $hasYield = $result->hasYield();
3246: $throwPoints = $result->getThrowPoints();
3247: $impurePoints = $result->getImpurePoints();
3248: $isAlwaysTerminating = $result->isAlwaysTerminating();
3249: $scope = $result->getScope();
3250: }
3251:
3252: $result = $this->processExprNode($stmt, $expr->var, $scope, $nodeCallback, $context->enterDeep());
3253: $hasYield = $hasYield || $result->hasYield();
3254: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3255: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3256: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3257: $scope = $result->getScope();
3258: } elseif ($expr instanceof Array_) {
3259: $itemNodes = [];
3260: $hasYield = false;
3261: $throwPoints = [];
3262: $impurePoints = [];
3263: $isAlwaysTerminating = false;
3264: foreach ($expr->items as $arrayItem) {
3265: $itemNodes[] = new LiteralArrayItem($scope, $arrayItem);
3266: $nodeCallback($arrayItem, $scope);
3267: if ($arrayItem->key !== null) {
3268: $keyResult = $this->processExprNode($stmt, $arrayItem->key, $scope, $nodeCallback, $context->enterDeep());
3269: $hasYield = $hasYield || $keyResult->hasYield();
3270: $throwPoints = array_merge($throwPoints, $keyResult->getThrowPoints());
3271: $impurePoints = array_merge($impurePoints, $keyResult->getImpurePoints());
3272: $isAlwaysTerminating = $isAlwaysTerminating || $keyResult->isAlwaysTerminating();
3273: $scope = $keyResult->getScope();
3274: }
3275:
3276: $valueResult = $this->processExprNode($stmt, $arrayItem->value, $scope, $nodeCallback, $context->enterDeep());
3277: $hasYield = $hasYield || $valueResult->hasYield();
3278: $throwPoints = array_merge($throwPoints, $valueResult->getThrowPoints());
3279: $impurePoints = array_merge($impurePoints, $valueResult->getImpurePoints());
3280: $isAlwaysTerminating = $isAlwaysTerminating || $valueResult->isAlwaysTerminating();
3281: $scope = $valueResult->getScope();
3282: }
3283: $nodeCallback(new LiteralArrayNode($expr, $itemNodes), $scope);
3284: } elseif ($expr instanceof BooleanAnd || $expr instanceof BinaryOp\LogicalAnd) {
3285: $leftResult = $this->processExprNode($stmt, $expr->left, $scope, $nodeCallback, $context->enterDeep());
3286: $rightResult = $this->processExprNode($stmt, $expr->right, $leftResult->getTruthyScope(), $nodeCallback, $context);
3287: $rightExprType = $rightResult->getScope()->getType($expr->right);
3288: if ($rightExprType instanceof NeverType && $rightExprType->isExplicit()) {
3289: $leftMergedWithRightScope = $leftResult->getFalseyScope();
3290: } else {
3291: $leftMergedWithRightScope = $leftResult->getScope()->mergeWith($rightResult->getScope());
3292: }
3293:
3294: $this->callNodeCallbackWithExpression($nodeCallback, new BooleanAndNode($expr, $leftResult->getTruthyScope()), $scope, $context);
3295:
3296: return new ExpressionResult(
3297: $leftMergedWithRightScope,
3298: $leftResult->hasYield() || $rightResult->hasYield(),
3299: $leftResult->isAlwaysTerminating(),
3300: array_merge($leftResult->getThrowPoints(), $rightResult->getThrowPoints()),
3301: array_merge($leftResult->getImpurePoints(), $rightResult->getImpurePoints()),
3302: static fn (): MutatingScope => $rightResult->getScope()->filterByTruthyValue($expr),
3303: static fn (): MutatingScope => $leftMergedWithRightScope->filterByFalseyValue($expr),
3304: );
3305: } elseif ($expr instanceof BooleanOr || $expr instanceof BinaryOp\LogicalOr) {
3306: $leftResult = $this->processExprNode($stmt, $expr->left, $scope, $nodeCallback, $context->enterDeep());
3307: $rightResult = $this->processExprNode($stmt, $expr->right, $leftResult->getFalseyScope(), $nodeCallback, $context);
3308: $rightExprType = $rightResult->getScope()->getType($expr->right);
3309: if ($rightExprType instanceof NeverType && $rightExprType->isExplicit()) {
3310: $leftMergedWithRightScope = $leftResult->getTruthyScope();
3311: } else {
3312: $leftMergedWithRightScope = $leftResult->getScope()->mergeWith($rightResult->getScope());
3313: }
3314:
3315: $this->callNodeCallbackWithExpression($nodeCallback, new BooleanOrNode($expr, $leftResult->getFalseyScope()), $scope, $context);
3316:
3317: return new ExpressionResult(
3318: $leftMergedWithRightScope,
3319: $leftResult->hasYield() || $rightResult->hasYield(),
3320: $leftResult->isAlwaysTerminating(),
3321: array_merge($leftResult->getThrowPoints(), $rightResult->getThrowPoints()),
3322: array_merge($leftResult->getImpurePoints(), $rightResult->getImpurePoints()),
3323: static fn (): MutatingScope => $leftMergedWithRightScope->filterByTruthyValue($expr),
3324: static fn (): MutatingScope => $rightResult->getScope()->filterByFalseyValue($expr),
3325: );
3326: } elseif ($expr instanceof Coalesce) {
3327: $nonNullabilityResult = $this->ensureNonNullability($scope, $expr->left);
3328: $condScope = $this->lookForSetAllowedUndefinedExpressions($nonNullabilityResult->getScope(), $expr->left);
3329: $condResult = $this->processExprNode($stmt, $expr->left, $condScope, $nodeCallback, $context->enterDeep());
3330: $scope = $this->revertNonNullability($condResult->getScope(), $nonNullabilityResult->getSpecifiedExpressions());
3331: $scope = $this->lookForUnsetAllowedUndefinedExpressions($scope, $expr->left);
3332:
3333: $rightScope = $scope->filterByFalseyValue($expr);
3334: $rightResult = $this->processExprNode($stmt, $expr->right, $rightScope, $nodeCallback, $context->enterDeep());
3335: $rightExprType = $scope->getType($expr->right);
3336: if ($rightExprType instanceof NeverType && $rightExprType->isExplicit()) {
3337: $scope = $scope->filterByTruthyValue(new Expr\Isset_([$expr->left]));
3338: } else {
3339: $scope = $scope->filterByTruthyValue(new Expr\Isset_([$expr->left]))->mergeWith($rightResult->getScope());
3340: }
3341:
3342: $hasYield = $condResult->hasYield() || $rightResult->hasYield();
3343: $throwPoints = array_merge($condResult->getThrowPoints(), $rightResult->getThrowPoints());
3344: $impurePoints = array_merge($condResult->getImpurePoints(), $rightResult->getImpurePoints());
3345: $isAlwaysTerminating = $condResult->isAlwaysTerminating();
3346: } elseif ($expr instanceof BinaryOp) {
3347: $result = $this->processExprNode($stmt, $expr->left, $scope, $nodeCallback, $context->enterDeep());
3348: $scope = $result->getScope();
3349: $hasYield = $result->hasYield();
3350: $throwPoints = $result->getThrowPoints();
3351: $impurePoints = $result->getImpurePoints();
3352: $isAlwaysTerminating = $result->isAlwaysTerminating();
3353: $result = $this->processExprNode($stmt, $expr->right, $scope, $nodeCallback, $context->enterDeep());
3354: if (
3355: ($expr instanceof BinaryOp\Div || $expr instanceof BinaryOp\Mod) &&
3356: !$scope->getType($expr->right)->toNumber()->isSuperTypeOf(new ConstantIntegerType(0))->no()
3357: ) {
3358: $throwPoints[] = ThrowPoint::createExplicit($scope, new ObjectType(DivisionByZeroError::class), $expr, false);
3359: }
3360: $scope = $result->getScope();
3361: $hasYield = $hasYield || $result->hasYield();
3362: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3363: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3364: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3365: } elseif ($expr instanceof Expr\Include_) {
3366: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3367: $throwPoints = $result->getThrowPoints();
3368: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
3369: $impurePoints = $result->getImpurePoints();
3370: $impurePoints[] = new ImpurePoint(
3371: $scope,
3372: $expr,
3373: in_array($expr->type, [Expr\Include_::TYPE_INCLUDE, Expr\Include_::TYPE_INCLUDE_ONCE], true) ? 'include' : 'require',
3374: in_array($expr->type, [Expr\Include_::TYPE_INCLUDE, Expr\Include_::TYPE_INCLUDE_ONCE], true) ? 'include' : 'require',
3375: true,
3376: );
3377: $hasYield = $result->hasYield();
3378: $isAlwaysTerminating = $result->isAlwaysTerminating();
3379: $scope = $result->getScope()->afterExtractCall();
3380: } elseif ($expr instanceof Expr\Print_) {
3381: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3382: $throwPoints = $result->getThrowPoints();
3383: $impurePoints = $result->getImpurePoints();
3384: $isAlwaysTerminating = $result->isAlwaysTerminating();
3385: $impurePoints[] = new ImpurePoint($scope, $expr, 'print', 'print', true);
3386: $hasYield = $result->hasYield();
3387:
3388: $scope = $result->getScope();
3389: } elseif ($expr instanceof Cast\String_) {
3390: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3391: $throwPoints = $result->getThrowPoints();
3392: $impurePoints = $result->getImpurePoints();
3393: $isAlwaysTerminating = $result->isAlwaysTerminating();
3394: $hasYield = $result->hasYield();
3395:
3396: $exprType = $scope->getType($expr->expr);
3397: $toStringMethod = $scope->getMethodReflection($exprType, '__toString');
3398: if ($toStringMethod !== null) {
3399: if (!$toStringMethod->hasSideEffects()->no()) {
3400: $impurePoints[] = new ImpurePoint(
3401: $scope,
3402: $expr,
3403: 'methodCall',
3404: sprintf('call to method %s::%s()', $toStringMethod->getDeclaringClass()->getDisplayName(), $toStringMethod->getName()),
3405: $toStringMethod->isPure()->no(),
3406: );
3407: }
3408: }
3409:
3410: $scope = $result->getScope();
3411: } elseif (
3412: $expr instanceof Expr\BitwiseNot
3413: || $expr instanceof Cast
3414: || $expr instanceof Expr\Clone_
3415: || $expr instanceof Expr\UnaryMinus
3416: || $expr instanceof Expr\UnaryPlus
3417: ) {
3418: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3419: $throwPoints = $result->getThrowPoints();
3420: $impurePoints = $result->getImpurePoints();
3421: $isAlwaysTerminating = $result->isAlwaysTerminating();
3422: $hasYield = $result->hasYield();
3423:
3424: $scope = $result->getScope();
3425: } elseif ($expr instanceof Expr\Eval_) {
3426: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3427: $throwPoints = $result->getThrowPoints();
3428: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
3429: $impurePoints = $result->getImpurePoints();
3430: $impurePoints[] = new ImpurePoint($scope, $expr, 'eval', 'eval', true);
3431: $hasYield = $result->hasYield();
3432: $isAlwaysTerminating = $result->isAlwaysTerminating();
3433:
3434: $scope = $result->getScope();
3435: } elseif ($expr instanceof Expr\YieldFrom) {
3436: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3437: $throwPoints = $result->getThrowPoints();
3438: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
3439: $impurePoints = $result->getImpurePoints();
3440: $impurePoints[] = new ImpurePoint(
3441: $scope,
3442: $expr,
3443: 'yieldFrom',
3444: 'yield from',
3445: true,
3446: );
3447: $hasYield = true;
3448: $isAlwaysTerminating = $result->isAlwaysTerminating();
3449:
3450: $scope = $result->getScope();
3451: } elseif ($expr instanceof BooleanNot) {
3452: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3453: $scope = $result->getScope();
3454: $hasYield = $result->hasYield();
3455: $throwPoints = $result->getThrowPoints();
3456: $impurePoints = $result->getImpurePoints();
3457: $isAlwaysTerminating = $result->isAlwaysTerminating();
3458: } elseif ($expr instanceof Expr\ClassConstFetch) {
3459: $isAlwaysTerminating = false;
3460:
3461: if ($expr->class instanceof Expr) {
3462: $result = $this->processExprNode($stmt, $expr->class, $scope, $nodeCallback, $context->enterDeep());
3463: $scope = $result->getScope();
3464: $hasYield = $result->hasYield();
3465: $throwPoints = $result->getThrowPoints();
3466: $impurePoints = $result->getImpurePoints();
3467: $isAlwaysTerminating = $result->isAlwaysTerminating();
3468: } else {
3469: $hasYield = false;
3470: $throwPoints = [];
3471: $impurePoints = [];
3472: $nodeCallback($expr->class, $scope);
3473: }
3474:
3475: if ($expr->name instanceof Expr) {
3476: $result = $this->processExprNode($stmt, $expr->name, $scope, $nodeCallback, $context->enterDeep());
3477: $scope = $result->getScope();
3478: $hasYield = $hasYield || $result->hasYield();
3479: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3480: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3481: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3482: } else {
3483: $nodeCallback($expr->name, $scope);
3484: }
3485: } elseif ($expr instanceof Expr\Empty_) {
3486: $nonNullabilityResult = $this->ensureNonNullability($scope, $expr->expr);
3487: $scope = $this->lookForSetAllowedUndefinedExpressions($nonNullabilityResult->getScope(), $expr->expr);
3488: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3489: $scope = $result->getScope();
3490: $hasYield = $result->hasYield();
3491: $throwPoints = $result->getThrowPoints();
3492: $impurePoints = $result->getImpurePoints();
3493: $isAlwaysTerminating = $result->isAlwaysTerminating();
3494: $scope = $this->revertNonNullability($scope, $nonNullabilityResult->getSpecifiedExpressions());
3495: $scope = $this->lookForUnsetAllowedUndefinedExpressions($scope, $expr->expr);
3496: } elseif ($expr instanceof Expr\Isset_) {
3497: $hasYield = false;
3498: $throwPoints = [];
3499: $impurePoints = [];
3500: $nonNullabilityResults = [];
3501: $isAlwaysTerminating = false;
3502: foreach ($expr->vars as $var) {
3503: $nonNullabilityResult = $this->ensureNonNullability($scope, $var);
3504: $scope = $this->lookForSetAllowedUndefinedExpressions($nonNullabilityResult->getScope(), $var);
3505: $result = $this->processExprNode($stmt, $var, $scope, $nodeCallback, $context->enterDeep());
3506: $scope = $result->getScope();
3507: $hasYield = $hasYield || $result->hasYield();
3508: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3509: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3510: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3511: $nonNullabilityResults[] = $nonNullabilityResult;
3512: }
3513: foreach (array_reverse($expr->vars) as $var) {
3514: $scope = $this->lookForUnsetAllowedUndefinedExpressions($scope, $var);
3515: }
3516: foreach (array_reverse($nonNullabilityResults) as $nonNullabilityResult) {
3517: $scope = $this->revertNonNullability($scope, $nonNullabilityResult->getSpecifiedExpressions());
3518: }
3519: } elseif ($expr instanceof Instanceof_) {
3520: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, $context->enterDeep());
3521: $scope = $result->getScope();
3522: $hasYield = $result->hasYield();
3523: $throwPoints = $result->getThrowPoints();
3524: $impurePoints = $result->getImpurePoints();
3525: $isAlwaysTerminating = $result->isAlwaysTerminating();
3526: if ($expr->class instanceof Expr) {
3527: $result = $this->processExprNode($stmt, $expr->class, $scope, $nodeCallback, $context->enterDeep());
3528: $scope = $result->getScope();
3529: $hasYield = $hasYield || $result->hasYield();
3530: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3531: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3532: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3533: }
3534: } elseif ($expr instanceof List_) {
3535: // only in assign and foreach, processed elsewhere
3536: return new ExpressionResult($scope, false, false, [], []);
3537: } elseif ($expr instanceof New_) {
3538: $parametersAcceptor = null;
3539: $constructorReflection = null;
3540: $hasYield = false;
3541: $throwPoints = [];
3542: $impurePoints = [];
3543: $isAlwaysTerminating = false;
3544: $className = null;
3545: if ($expr->class instanceof Expr || $expr->class instanceof Name) {
3546: if ($expr->class instanceof Expr) {
3547: $objectClasses = $scope->getType($expr)->getObjectClassNames();
3548: if (count($objectClasses) === 1) {
3549: $objectExprResult = $this->processExprNode($stmt, new New_(new Name($objectClasses[0])), $scope, static function (): void {
3550: }, $context->enterDeep());
3551: $className = $objectClasses[0];
3552: $additionalThrowPoints = $objectExprResult->getThrowPoints();
3553: } else {
3554: $additionalThrowPoints = [ThrowPoint::createImplicit($scope, $expr)];
3555: }
3556:
3557: $result = $this->processExprNode($stmt, $expr->class, $scope, $nodeCallback, $context->enterDeep());
3558: $scope = $result->getScope();
3559: $hasYield = $result->hasYield();
3560: $throwPoints = $result->getThrowPoints();
3561: $impurePoints = $result->getImpurePoints();
3562: $isAlwaysTerminating = $result->isAlwaysTerminating();
3563: foreach ($additionalThrowPoints as $throwPoint) {
3564: $throwPoints[] = $throwPoint;
3565: }
3566: } else {
3567: $className = $scope->resolveName($expr->class);
3568: }
3569:
3570: $classReflection = null;
3571: if ($className !== null && $this->reflectionProvider->hasClass($className)) {
3572: $classReflection = $this->reflectionProvider->getClass($className);
3573: if ($classReflection->hasConstructor()) {
3574: $constructorReflection = $classReflection->getConstructor();
3575: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
3576: $scope,
3577: $expr->getArgs(),
3578: $constructorReflection->getVariants(),
3579: $constructorReflection->getNamedArgumentsVariants(),
3580: );
3581: $constructorThrowPoint = $this->getConstructorThrowPoint($constructorReflection, $parametersAcceptor, $classReflection, $expr, new Name\FullyQualified($className), $expr->getArgs(), $scope);
3582: if ($constructorThrowPoint !== null) {
3583: $throwPoints[] = $constructorThrowPoint;
3584: }
3585: }
3586: } else {
3587: $throwPoints[] = ThrowPoint::createImplicit($scope, $expr);
3588: }
3589:
3590: if ($constructorReflection !== null) {
3591: if (!$constructorReflection->hasSideEffects()->no()) {
3592: $certain = $constructorReflection->isPure()->no();
3593: $impurePoints[] = new ImpurePoint(
3594: $scope,
3595: $expr,
3596: 'new',
3597: sprintf('instantiation of class %s', $constructorReflection->getDeclaringClass()->getDisplayName()),
3598: $certain,
3599: );
3600: }
3601: } elseif ($classReflection === null) {
3602: $impurePoints[] = new ImpurePoint(
3603: $scope,
3604: $expr,
3605: 'new',
3606: 'instantiation of unknown class',
3607: false,
3608: );
3609: }
3610:
3611: if ($parametersAcceptor !== null) {
3612: $expr = ArgumentsNormalizer::reorderNewArguments($parametersAcceptor, $expr) ?? $expr;
3613: }
3614:
3615: } else {
3616: $classReflection = $this->reflectionProvider->getAnonymousClassReflection($expr->class, $scope); // populates $expr->class->name
3617: $constructorResult = null;
3618: $this->processStmtNode($expr->class, $scope, static function (Node $node, Scope $scope) use ($nodeCallback, $classReflection, &$constructorResult): void {
3619: $nodeCallback($node, $scope);
3620: if (!$node instanceof MethodReturnStatementsNode) {
3621: return;
3622: }
3623: if ($constructorResult !== null) {
3624: return;
3625: }
3626: $currentClassReflection = $node->getClassReflection();
3627: if ($currentClassReflection->getName() !== $classReflection->getName()) {
3628: return;
3629: }
3630: if (!$currentClassReflection->hasConstructor()) {
3631: return;
3632: }
3633: if ($currentClassReflection->getConstructor()->getName() !== $node->getMethodReflection()->getName()) {
3634: return;
3635: }
3636: $constructorResult = $node;
3637: }, StatementContext::createTopLevel());
3638: if ($constructorResult !== null) {
3639: $throwPoints = array_merge($throwPoints, $constructorResult->getStatementResult()->getThrowPoints());
3640: $impurePoints = array_merge($impurePoints, $constructorResult->getImpurePoints());
3641: }
3642: if ($classReflection->hasConstructor()) {
3643: $constructorReflection = $classReflection->getConstructor();
3644: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
3645: $scope,
3646: $expr->getArgs(),
3647: $constructorReflection->getVariants(),
3648: $constructorReflection->getNamedArgumentsVariants(),
3649: );
3650: }
3651: }
3652:
3653: $result = $this->processArgs($stmt, $constructorReflection, null, $parametersAcceptor, $expr, $scope, $nodeCallback, $context);
3654: $scope = $result->getScope();
3655: $hasYield = $hasYield || $result->hasYield();
3656: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
3657: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
3658: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
3659: } elseif (
3660: $expr instanceof Expr\PreInc
3661: || $expr instanceof Expr\PostInc
3662: || $expr instanceof Expr\PreDec
3663: || $expr instanceof Expr\PostDec
3664: ) {
3665: $result = $this->processExprNode($stmt, $expr->var, $scope, $nodeCallback, $context->enterDeep());
3666: $scope = $result->getScope();
3667: $hasYield = $result->hasYield();
3668: $throwPoints = $result->getThrowPoints();
3669: $impurePoints = $result->getImpurePoints();
3670: $isAlwaysTerminating = $result->isAlwaysTerminating();
3671:
3672: $newExpr = $expr;
3673: if ($expr instanceof Expr\PostInc) {
3674: $newExpr = new Expr\PreInc($expr->var);
3675: } elseif ($expr instanceof Expr\PostDec) {
3676: $newExpr = new Expr\PreDec($expr->var);
3677: }
3678:
3679: $scope = $this->processAssignVar(
3680: $scope,
3681: $stmt,
3682: $expr->var,
3683: $newExpr,
3684: static function (Node $node, Scope $scope) use ($nodeCallback): void {
3685: if (!$node instanceof PropertyAssignNode && !$node instanceof VariableAssignNode) {
3686: return;
3687: }
3688:
3689: $nodeCallback($node, $scope);
3690: },
3691: $context,
3692: static fn (MutatingScope $scope): ExpressionResult => new ExpressionResult($scope, false, false, [], []),
3693: false,
3694: )->getScope();
3695: } elseif ($expr instanceof Ternary) {
3696: $ternaryCondResult = $this->processExprNode($stmt, $expr->cond, $scope, $nodeCallback, $context->enterDeep());
3697: $throwPoints = $ternaryCondResult->getThrowPoints();
3698: $impurePoints = $ternaryCondResult->getImpurePoints();
3699: $isAlwaysTerminating = $ternaryCondResult->isAlwaysTerminating();
3700: $ifTrueScope = $ternaryCondResult->getTruthyScope();
3701: $ifFalseScope = $ternaryCondResult->getFalseyScope();
3702: $ifTrueType = null;
3703: if ($expr->if !== null) {
3704: $ifResult = $this->processExprNode($stmt, $expr->if, $ifTrueScope, $nodeCallback, $context);
3705: $throwPoints = array_merge($throwPoints, $ifResult->getThrowPoints());
3706: $impurePoints = array_merge($impurePoints, $ifResult->getImpurePoints());
3707: $ifTrueScope = $ifResult->getScope();
3708: $ifTrueType = $ifTrueScope->getType($expr->if);
3709: }
3710:
3711: $elseResult = $this->processExprNode($stmt, $expr->else, $ifFalseScope, $nodeCallback, $context);
3712: $throwPoints = array_merge($throwPoints, $elseResult->getThrowPoints());
3713: $impurePoints = array_merge($impurePoints, $elseResult->getImpurePoints());
3714: $ifFalseScope = $elseResult->getScope();
3715:
3716: $condType = $scope->getType($expr->cond);
3717: if ($condType->isTrue()->yes()) {
3718: $finalScope = $ifTrueScope;
3719: } elseif ($condType->isFalse()->yes()) {
3720: $finalScope = $ifFalseScope;
3721: } else {
3722: if ($ifTrueType instanceof NeverType && $ifTrueType->isExplicit()) {
3723: $finalScope = $ifFalseScope;
3724: } else {
3725: $ifFalseType = $ifFalseScope->getType($expr->else);
3726:
3727: if ($ifFalseType instanceof NeverType && $ifFalseType->isExplicit()) {
3728: $finalScope = $ifTrueScope;
3729: } else {
3730: $finalScope = $ifTrueScope->mergeWith($ifFalseScope);
3731: }
3732: }
3733: }
3734:
3735: return new ExpressionResult(
3736: $finalScope,
3737: $ternaryCondResult->hasYield(),
3738: $isAlwaysTerminating,
3739: $throwPoints,
3740: $impurePoints,
3741: static fn (): MutatingScope => $finalScope->filterByTruthyValue($expr),
3742: static fn (): MutatingScope => $finalScope->filterByFalseyValue($expr),
3743: );
3744:
3745: } elseif ($expr instanceof Expr\Yield_) {
3746: $throwPoints = [
3747: ThrowPoint::createImplicit($scope, $expr),
3748: ];
3749: $impurePoints = [
3750: new ImpurePoint(
3751: $scope,
3752: $expr,
3753: 'yield',
3754: 'yield',
3755: true,
3756: ),
3757: ];
3758: $isAlwaysTerminating = false;
3759: if ($expr->key !== null) {
3760: $keyResult = $this->processExprNode($stmt, $expr->key, $scope, $nodeCallback, $context->enterDeep());
3761: $scope = $keyResult->getScope();
3762: $throwPoints = $keyResult->getThrowPoints();
3763: $impurePoints = array_merge($impurePoints, $keyResult->getImpurePoints());
3764: $isAlwaysTerminating = $keyResult->isAlwaysTerminating();
3765: }
3766: if ($expr->value !== null) {
3767: $valueResult = $this->processExprNode($stmt, $expr->value, $scope, $nodeCallback, $context->enterDeep());
3768: $scope = $valueResult->getScope();
3769: $throwPoints = array_merge($throwPoints, $valueResult->getThrowPoints());
3770: $impurePoints = array_merge($impurePoints, $valueResult->getImpurePoints());
3771: $isAlwaysTerminating = $isAlwaysTerminating || $valueResult->isAlwaysTerminating();
3772: }
3773: $hasYield = true;
3774: } elseif ($expr instanceof Expr\Match_) {
3775: $deepContext = $context->enterDeep();
3776: $condType = $scope->getType($expr->cond);
3777: $condResult = $this->processExprNode($stmt, $expr->cond, $scope, $nodeCallback, $deepContext);
3778: $scope = $condResult->getScope();
3779: $hasYield = $condResult->hasYield();
3780: $throwPoints = $condResult->getThrowPoints();
3781: $impurePoints = $condResult->getImpurePoints();
3782: $isAlwaysTerminating = $condResult->isAlwaysTerminating();
3783: $matchScope = $scope->enterMatch($expr);
3784: $armNodes = [];
3785: $hasDefaultCond = false;
3786: $hasAlwaysTrueCond = false;
3787: $arms = $expr->arms;
3788: if ($condType->isEnum()->yes()) {
3789: // enum match analysis would work even without this if branch
3790: // but would be much slower
3791: // this avoids using ObjectType::$subtractedType which is slow for huge enums
3792: // because of repeated union type normalization
3793: $enumCases = $condType->getEnumCases();
3794: if (count($enumCases) > 0) {
3795: $indexedEnumCases = [];
3796: foreach ($enumCases as $enumCase) {
3797: $indexedEnumCases[strtolower($enumCase->getClassName())][$enumCase->getEnumCaseName()] = $enumCase;
3798: }
3799: $unusedIndexedEnumCases = $indexedEnumCases;
3800: foreach ($arms as $i => $arm) {
3801: if ($arm->conds === null) {
3802: continue;
3803: }
3804:
3805: $condNodes = [];
3806: $conditionCases = [];
3807: $conditionExprs = [];
3808: foreach ($arm->conds as $cond) {
3809: if (!$cond instanceof Expr\ClassConstFetch) {
3810: continue 2;
3811: }
3812: if (!$cond->class instanceof Name) {
3813: continue 2;
3814: }
3815: if (!$cond->name instanceof Node\Identifier) {
3816: continue 2;
3817: }
3818: $fetchedClassName = $scope->resolveName($cond->class);
3819: $loweredFetchedClassName = strtolower($fetchedClassName);
3820: if (!array_key_exists($loweredFetchedClassName, $indexedEnumCases)) {
3821: continue 2;
3822: }
3823:
3824: if (!array_key_exists($loweredFetchedClassName, $unusedIndexedEnumCases)) {
3825: throw new ShouldNotHappenException();
3826: }
3827:
3828: $caseName = $cond->name->toString();
3829: if (!array_key_exists($caseName, $indexedEnumCases[$loweredFetchedClassName])) {
3830: continue 2;
3831: }
3832:
3833: $enumCase = $indexedEnumCases[$loweredFetchedClassName][$caseName];
3834: $conditionCases[] = $enumCase;
3835: $armConditionScope = $matchScope;
3836: if (!array_key_exists($caseName, $unusedIndexedEnumCases[$loweredFetchedClassName])) {
3837: // force "always false"
3838: $armConditionScope = $armConditionScope->removeTypeFromExpression(
3839: $expr->cond,
3840: $enumCase,
3841: );
3842: } else {
3843: $unusedCasesCount = 0;
3844: foreach ($unusedIndexedEnumCases as $cases) {
3845: $unusedCasesCount += count($cases);
3846: }
3847: if ($unusedCasesCount === 1) {
3848: $hasAlwaysTrueCond = true;
3849:
3850: // force "always true"
3851: $armConditionScope = $armConditionScope->addTypeToExpression(
3852: $expr->cond,
3853: $enumCase,
3854: );
3855: }
3856: }
3857:
3858: $this->processExprNode($stmt, $cond, $armConditionScope, $nodeCallback, $deepContext);
3859:
3860: $condNodes[] = new MatchExpressionArmCondition(
3861: $cond,
3862: $armConditionScope,
3863: $cond->getStartLine(),
3864: );
3865: $conditionExprs[] = $cond;
3866:
3867: unset($unusedIndexedEnumCases[$loweredFetchedClassName][$caseName]);
3868: }
3869:
3870: $conditionCasesCount = count($conditionCases);
3871: if ($conditionCasesCount === 0) {
3872: throw new ShouldNotHappenException();
3873: } elseif ($conditionCasesCount === 1) {
3874: $conditionCaseType = $conditionCases[0];
3875: } else {
3876: $conditionCaseType = new UnionType($conditionCases);
3877: }
3878:
3879: $filteringExpr = $this->getFilteringExprForMatchArm($expr, $conditionExprs);
3880: $matchArmBodyScope = $matchScope->addTypeToExpression(
3881: $expr->cond,
3882: $conditionCaseType,
3883: )->filterByTruthyValue($filteringExpr);
3884: $matchArmBody = new MatchExpressionArmBody($matchArmBodyScope, $arm->body);
3885: $armNodes[$i] = new MatchExpressionArm($matchArmBody, $condNodes, $arm->getStartLine());
3886:
3887: $armResult = $this->processExprNode(
3888: $stmt,
3889: $arm->body,
3890: $matchArmBodyScope,
3891: $nodeCallback,
3892: ExpressionContext::createTopLevel(),
3893: );
3894: $armScope = $armResult->getScope();
3895: $scope = $scope->mergeWith($armScope);
3896: $hasYield = $hasYield || $armResult->hasYield();
3897: $throwPoints = array_merge($throwPoints, $armResult->getThrowPoints());
3898: $impurePoints = array_merge($impurePoints, $armResult->getImpurePoints());
3899:
3900: unset($arms[$i]);
3901: }
3902:
3903: $remainingCases = [];
3904: foreach ($unusedIndexedEnumCases as $cases) {
3905: foreach ($cases as $case) {
3906: $remainingCases[] = $case;
3907: }
3908: }
3909:
3910: $remainingCasesCount = count($remainingCases);
3911: if ($remainingCasesCount === 0) {
3912: $remainingType = new NeverType();
3913: } elseif ($remainingCasesCount === 1) {
3914: $remainingType = $remainingCases[0];
3915: } else {
3916: $remainingType = new UnionType($remainingCases);
3917: }
3918:
3919: $matchScope = $matchScope->addTypeToExpression($expr->cond, $remainingType);
3920: }
3921: }
3922: foreach ($arms as $i => $arm) {
3923: if ($arm->conds === null) {
3924: $hasDefaultCond = true;
3925: $matchArmBody = new MatchExpressionArmBody($matchScope, $arm->body);
3926: $armNodes[$i] = new MatchExpressionArm($matchArmBody, [], $arm->getStartLine());
3927: $armResult = $this->processExprNode($stmt, $arm->body, $matchScope, $nodeCallback, ExpressionContext::createTopLevel());
3928: $matchScope = $armResult->getScope();
3929: $hasYield = $hasYield || $armResult->hasYield();
3930: $throwPoints = array_merge($throwPoints, $armResult->getThrowPoints());
3931: $impurePoints = array_merge($impurePoints, $armResult->getImpurePoints());
3932: $scope = $scope->mergeWith($matchScope);
3933: continue;
3934: }
3935:
3936: if (count($arm->conds) === 0) {
3937: throw new ShouldNotHappenException();
3938: }
3939:
3940: $filteringExprs = [];
3941: $armCondScope = $matchScope;
3942: $condNodes = [];
3943: foreach ($arm->conds as $armCond) {
3944: $condNodes[] = new MatchExpressionArmCondition($armCond, $armCondScope, $armCond->getStartLine());
3945: $armCondResult = $this->processExprNode($stmt, $armCond, $armCondScope, $nodeCallback, $deepContext);
3946: $hasYield = $hasYield || $armCondResult->hasYield();
3947: $throwPoints = array_merge($throwPoints, $armCondResult->getThrowPoints());
3948: $impurePoints = array_merge($impurePoints, $armCondResult->getImpurePoints());
3949: $armCondExpr = new BinaryOp\Identical($expr->cond, $armCond);
3950: $armCondResultScope = $armCondResult->getScope();
3951: $armCondType = $this->treatPhpDocTypesAsCertain ? $armCondResultScope->getType($armCondExpr) : $armCondResultScope->getNativeType($armCondExpr);
3952: if ($armCondType->isTrue()->yes()) {
3953: $hasAlwaysTrueCond = true;
3954: }
3955: $armCondScope = $armCondResult->getScope()->filterByFalseyValue($armCondExpr);
3956: $filteringExprs[] = $armCond;
3957: }
3958:
3959: $filteringExpr = $this->getFilteringExprForMatchArm($expr, $filteringExprs);
3960:
3961: $bodyScope = $this->processExprNode($stmt, $filteringExpr, $matchScope, static function (): void {
3962: }, $deepContext)->getTruthyScope();
3963: $matchArmBody = new MatchExpressionArmBody($bodyScope, $arm->body);
3964: $armNodes[$i] = new MatchExpressionArm($matchArmBody, $condNodes, $arm->getStartLine());
3965:
3966: $armResult = $this->processExprNode(
3967: $stmt,
3968: $arm->body,
3969: $bodyScope,
3970: $nodeCallback,
3971: ExpressionContext::createTopLevel(),
3972: );
3973: $armScope = $armResult->getScope();
3974: $scope = $scope->mergeWith($armScope);
3975: $hasYield = $hasYield || $armResult->hasYield();
3976: $throwPoints = array_merge($throwPoints, $armResult->getThrowPoints());
3977: $impurePoints = array_merge($impurePoints, $armResult->getImpurePoints());
3978: $matchScope = $matchScope->filterByFalseyValue($filteringExpr);
3979: }
3980:
3981: $remainingType = $matchScope->getType($expr->cond);
3982: if (!$hasDefaultCond && !$hasAlwaysTrueCond && !$remainingType instanceof NeverType) {
3983: $throwPoints[] = ThrowPoint::createExplicit($scope, new ObjectType(UnhandledMatchError::class), $expr, false);
3984: }
3985:
3986: ksort($armNodes, SORT_NUMERIC);
3987:
3988: $nodeCallback(new MatchExpressionNode($expr->cond, array_values($armNodes), $expr, $matchScope), $scope);
3989: } elseif ($expr instanceof AlwaysRememberedExpr) {
3990: $result = $this->processExprNode($stmt, $expr->getExpr(), $scope, $nodeCallback, $context);
3991: $hasYield = $result->hasYield();
3992: $throwPoints = $result->getThrowPoints();
3993: $impurePoints = $result->getImpurePoints();
3994: $isAlwaysTerminating = $result->isAlwaysTerminating();
3995: $scope = $result->getScope();
3996: } elseif ($expr instanceof Expr\Throw_) {
3997: $hasYield = false;
3998: $result = $this->processExprNode($stmt, $expr->expr, $scope, $nodeCallback, ExpressionContext::createDeep());
3999: $throwPoints = $result->getThrowPoints();
4000: $impurePoints = $result->getImpurePoints();
4001: $isAlwaysTerminating = $result->isAlwaysTerminating();
4002: $throwPoints[] = ThrowPoint::createExplicit($scope, $scope->getType($expr->expr), $expr, false);
4003: } elseif ($expr instanceof FunctionCallableNode) {
4004: $throwPoints = [];
4005: $impurePoints = [];
4006: $hasYield = false;
4007: $isAlwaysTerminating = false;
4008: if ($expr->getName() instanceof Expr) {
4009: $result = $this->processExprNode($stmt, $expr->getName(), $scope, $nodeCallback, ExpressionContext::createDeep());
4010: $scope = $result->getScope();
4011: $hasYield = $result->hasYield();
4012: $throwPoints = $result->getThrowPoints();
4013: $impurePoints = $result->getImpurePoints();
4014: $isAlwaysTerminating = $result->isAlwaysTerminating();
4015: }
4016: } elseif ($expr instanceof MethodCallableNode) {
4017: $result = $this->processExprNode($stmt, $expr->getVar(), $scope, $nodeCallback, ExpressionContext::createDeep());
4018: $scope = $result->getScope();
4019: $hasYield = $result->hasYield();
4020: $throwPoints = $result->getThrowPoints();
4021: $impurePoints = $result->getImpurePoints();
4022: $isAlwaysTerminating = false;
4023: if ($expr->getName() instanceof Expr) {
4024: $nameResult = $this->processExprNode($stmt, $expr->getVar(), $scope, $nodeCallback, ExpressionContext::createDeep());
4025: $scope = $nameResult->getScope();
4026: $hasYield = $hasYield || $nameResult->hasYield();
4027: $throwPoints = array_merge($throwPoints, $nameResult->getThrowPoints());
4028: $impurePoints = array_merge($impurePoints, $nameResult->getImpurePoints());
4029: $isAlwaysTerminating = $nameResult->isAlwaysTerminating();
4030: }
4031: } elseif ($expr instanceof StaticMethodCallableNode) {
4032: $throwPoints = [];
4033: $impurePoints = [];
4034: $hasYield = false;
4035: $isAlwaysTerminating = false;
4036: if ($expr->getClass() instanceof Expr) {
4037: $classResult = $this->processExprNode($stmt, $expr->getClass(), $scope, $nodeCallback, ExpressionContext::createDeep());
4038: $scope = $classResult->getScope();
4039: $hasYield = $classResult->hasYield();
4040: $throwPoints = $classResult->getThrowPoints();
4041: $impurePoints = $classResult->getImpurePoints();
4042: $isAlwaysTerminating = $classResult->isAlwaysTerminating();
4043: }
4044: if ($expr->getName() instanceof Expr) {
4045: $nameResult = $this->processExprNode($stmt, $expr->getName(), $scope, $nodeCallback, ExpressionContext::createDeep());
4046: $scope = $nameResult->getScope();
4047: $hasYield = $hasYield || $nameResult->hasYield();
4048: $throwPoints = array_merge($throwPoints, $nameResult->getThrowPoints());
4049: $impurePoints = array_merge($impurePoints, $nameResult->getImpurePoints());
4050: $isAlwaysTerminating = $isAlwaysTerminating || $nameResult->isAlwaysTerminating();
4051: }
4052: } elseif ($expr instanceof InstantiationCallableNode) {
4053: $throwPoints = [];
4054: $impurePoints = [];
4055: $hasYield = false;
4056: $isAlwaysTerminating = false;
4057: if ($expr->getClass() instanceof Expr) {
4058: $classResult = $this->processExprNode($stmt, $expr->getClass(), $scope, $nodeCallback, ExpressionContext::createDeep());
4059: $scope = $classResult->getScope();
4060: $hasYield = $classResult->hasYield();
4061: $throwPoints = $classResult->getThrowPoints();
4062: $impurePoints = $classResult->getImpurePoints();
4063: $isAlwaysTerminating = $classResult->isAlwaysTerminating();
4064: }
4065: } elseif ($expr instanceof Node\Scalar) {
4066: $hasYield = false;
4067: $throwPoints = [];
4068: $impurePoints = [];
4069: $isAlwaysTerminating = false;
4070: } elseif ($expr instanceof ConstFetch) {
4071: $hasYield = false;
4072: $throwPoints = [];
4073: $impurePoints = [];
4074: $isAlwaysTerminating = false;
4075: $nodeCallback($expr->name, $scope);
4076: } else {
4077: $hasYield = false;
4078: $throwPoints = [];
4079: $impurePoints = [];
4080: $isAlwaysTerminating = false;
4081: }
4082:
4083: return new ExpressionResult(
4084: $scope,
4085: $hasYield,
4086: $isAlwaysTerminating,
4087: $throwPoints,
4088: $impurePoints,
4089: static fn (): MutatingScope => $scope->filterByTruthyValue($expr),
4090: static fn (): MutatingScope => $scope->filterByFalseyValue($expr),
4091: );
4092: }
4093:
4094: private function getArrayFunctionAppendingType(FunctionReflection $functionReflection, Scope $scope, FuncCall $expr): Type
4095: {
4096: $arrayArg = $expr->getArgs()[0]->value;
4097: $arrayType = $scope->getType($arrayArg);
4098: $callArgs = array_slice($expr->getArgs(), 1);
4099:
4100: /**
4101: * @param Arg[] $callArgs
4102: * @param callable(?Type, Type, bool): void $setOffsetValueType
4103: */
4104: $setOffsetValueTypes = static function (Scope $scope, array $callArgs, callable $setOffsetValueType, ?bool &$nonConstantArrayWasUnpacked = null): void {
4105: foreach ($callArgs as $callArg) {
4106: $callArgType = $scope->getType($callArg->value);
4107: if ($callArg->unpack) {
4108: $constantArrays = $callArgType->getConstantArrays();
4109: if (count($constantArrays) === 1) {
4110: $iterableValueTypes = $constantArrays[0]->getValueTypes();
4111: } else {
4112: $iterableValueTypes = [$callArgType->getIterableValueType()];
4113: $nonConstantArrayWasUnpacked = true;
4114: }
4115:
4116: $isOptional = !$callArgType->isIterableAtLeastOnce()->yes();
4117: foreach ($iterableValueTypes as $iterableValueType) {
4118: if ($iterableValueType instanceof UnionType) {
4119: foreach ($iterableValueType->getTypes() as $innerType) {
4120: $setOffsetValueType(null, $innerType, $isOptional);
4121: }
4122: } else {
4123: $setOffsetValueType(null, $iterableValueType, $isOptional);
4124: }
4125: }
4126: continue;
4127: }
4128: $setOffsetValueType(null, $callArgType, false);
4129: }
4130: };
4131:
4132: $constantArrays = $arrayType->getConstantArrays();
4133: if (count($constantArrays) > 0) {
4134: $newArrayTypes = [];
4135: $prepend = $functionReflection->getName() === 'array_unshift';
4136: foreach ($constantArrays as $constantArray) {
4137: $arrayTypeBuilder = $prepend ? ConstantArrayTypeBuilder::createEmpty() : ConstantArrayTypeBuilder::createFromConstantArray($constantArray);
4138:
4139: $setOffsetValueTypes(
4140: $scope,
4141: $callArgs,
4142: static function (?Type $offsetType, Type $valueType, bool $optional) use (&$arrayTypeBuilder): void {
4143: $arrayTypeBuilder->setOffsetValueType($offsetType, $valueType, $optional);
4144: },
4145: $nonConstantArrayWasUnpacked,
4146: );
4147:
4148: if ($prepend) {
4149: $keyTypes = $constantArray->getKeyTypes();
4150: $valueTypes = $constantArray->getValueTypes();
4151: foreach ($keyTypes as $k => $keyType) {
4152: $arrayTypeBuilder->setOffsetValueType(
4153: count($keyType->getConstantStrings()) === 1 ? $keyType->getConstantStrings()[0] : null,
4154: $valueTypes[$k],
4155: $constantArray->isOptionalKey($k),
4156: );
4157: }
4158: }
4159:
4160: $constantArray = $arrayTypeBuilder->getArray();
4161:
4162: if ($constantArray->isConstantArray()->yes() && $nonConstantArrayWasUnpacked) {
4163: $array = new ArrayType($constantArray->generalize(GeneralizePrecision::lessSpecific())->getIterableKeyType(), $constantArray->getIterableValueType());
4164: $isList = $constantArray->isList()->yes();
4165: $constantArray = $constantArray->isIterableAtLeastOnce()->yes()
4166: ? TypeCombinator::intersect($array, new NonEmptyArrayType())
4167: : $array;
4168: $constantArray = $isList
4169: ? TypeCombinator::intersect($constantArray, new AccessoryArrayListType())
4170: : $constantArray;
4171: }
4172:
4173: $newArrayTypes[] = $constantArray;
4174: }
4175:
4176: return TypeCombinator::union(...$newArrayTypes);
4177: }
4178:
4179: $setOffsetValueTypes(
4180: $scope,
4181: $callArgs,
4182: static function (?Type $offsetType, Type $valueType, bool $optional) use (&$arrayType): void {
4183: $isIterableAtLeastOnce = $arrayType->isIterableAtLeastOnce()->yes() || !$optional;
4184: $arrayType = $arrayType->setOffsetValueType($offsetType, $valueType);
4185: if ($isIterableAtLeastOnce) {
4186: return;
4187: }
4188:
4189: $arrayType = TypeCombinator::union($arrayType, new ConstantArrayType([], []));
4190: },
4191: );
4192:
4193: return $arrayType;
4194: }
4195:
4196: private function getArraySortPreserveListFunctionType(Type $type): Type
4197: {
4198: $isIterableAtLeastOnce = $type->isIterableAtLeastOnce();
4199: if ($isIterableAtLeastOnce->no()) {
4200: return $type;
4201: }
4202:
4203: return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($isIterableAtLeastOnce): Type {
4204: if ($type instanceof UnionType || $type instanceof IntersectionType) {
4205: return $traverse($type);
4206: }
4207:
4208: if (!$type instanceof ArrayType && !$type instanceof ConstantArrayType) {
4209: return $type;
4210: }
4211:
4212: $newArrayType = TypeCombinator::intersect(new ArrayType(new IntegerType(), $type->getIterableValueType()), new AccessoryArrayListType());
4213: if ($isIterableAtLeastOnce->yes()) {
4214: $newArrayType = TypeCombinator::intersect($newArrayType, new NonEmptyArrayType());
4215: }
4216:
4217: return $newArrayType;
4218: });
4219: }
4220:
4221: private function getArraySortDoNotPreserveListFunctionType(Type $type): Type
4222: {
4223: $isIterableAtLeastOnce = $type->isIterableAtLeastOnce();
4224: if ($isIterableAtLeastOnce->no()) {
4225: return $type;
4226: }
4227:
4228: return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($isIterableAtLeastOnce): Type {
4229: if ($type instanceof UnionType) {
4230: return $traverse($type);
4231: }
4232:
4233: $constantArrays = $type->getConstantArrays();
4234: if (count($constantArrays) > 0) {
4235: $types = [];
4236: foreach ($constantArrays as $constantArray) {
4237: $types[] = new ConstantArrayType(
4238: $constantArray->getKeyTypes(),
4239: $constantArray->getValueTypes(),
4240: $constantArray->getNextAutoIndexes(),
4241: $constantArray->getOptionalKeys(),
4242: $constantArray->isList()->and(TrinaryLogic::createMaybe()),
4243: );
4244: }
4245:
4246: return TypeCombinator::union(...$types);
4247: }
4248:
4249: $newArrayType = new ArrayType($type->getIterableKeyType(), $type->getIterableValueType());
4250: if ($isIterableAtLeastOnce->yes()) {
4251: $newArrayType = TypeCombinator::intersect($newArrayType, new NonEmptyArrayType());
4252: }
4253:
4254: return $newArrayType;
4255: });
4256: }
4257:
4258: private function getFunctionThrowPoint(
4259: FunctionReflection $functionReflection,
4260: ?ParametersAcceptor $parametersAcceptor,
4261: FuncCall $funcCall,
4262: MutatingScope $scope,
4263: ): ?ThrowPoint
4264: {
4265: $normalizedFuncCall = $funcCall;
4266: if ($parametersAcceptor !== null) {
4267: $normalizedFuncCall = ArgumentsNormalizer::reorderFuncArguments($parametersAcceptor, $funcCall);
4268: }
4269:
4270: if ($normalizedFuncCall !== null) {
4271: foreach ($this->dynamicThrowTypeExtensionProvider->getDynamicFunctionThrowTypeExtensions() as $extension) {
4272: if (!$extension->isFunctionSupported($functionReflection)) {
4273: continue;
4274: }
4275:
4276: $throwType = $extension->getThrowTypeFromFunctionCall($functionReflection, $normalizedFuncCall, $scope);
4277: if ($throwType === null) {
4278: return null;
4279: }
4280:
4281: return ThrowPoint::createExplicit($scope, $throwType, $funcCall, false);
4282: }
4283: }
4284:
4285: $throwType = $functionReflection->getThrowType();
4286: if ($throwType === null && $parametersAcceptor !== null) {
4287: $returnType = $parametersAcceptor->getReturnType();
4288: if ($returnType instanceof NeverType && $returnType->isExplicit()) {
4289: $throwType = new ObjectType(Throwable::class);
4290: }
4291: }
4292:
4293: if ($throwType !== null) {
4294: if (!$throwType->isVoid()->yes()) {
4295: return ThrowPoint::createExplicit($scope, $throwType, $funcCall, true);
4296: }
4297: } elseif ($this->implicitThrows) {
4298: $requiredParameters = null;
4299: if ($parametersAcceptor !== null) {
4300: $requiredParameters = 0;
4301: foreach ($parametersAcceptor->getParameters() as $parameter) {
4302: if ($parameter->isOptional()) {
4303: continue;
4304: }
4305:
4306: $requiredParameters++;
4307: }
4308: }
4309: if (
4310: !$functionReflection->isBuiltin()
4311: || $requiredParameters === null
4312: || $requiredParameters > 0
4313: || count($funcCall->getArgs()) > 0
4314: ) {
4315: $functionReturnedType = $scope->getType($funcCall);
4316: if (!(new ObjectType(Throwable::class))->isSuperTypeOf($functionReturnedType)->yes()) {
4317: return ThrowPoint::createImplicit($scope, $funcCall);
4318: }
4319: }
4320: }
4321:
4322: return null;
4323: }
4324:
4325: private function getMethodThrowPoint(MethodReflection $methodReflection, ParametersAcceptor $parametersAcceptor, MethodCall $methodCall, MutatingScope $scope): ?ThrowPoint
4326: {
4327: $normalizedMethodCall = ArgumentsNormalizer::reorderMethodArguments($parametersAcceptor, $methodCall);
4328: if ($normalizedMethodCall !== null) {
4329: foreach ($this->dynamicThrowTypeExtensionProvider->getDynamicMethodThrowTypeExtensions() as $extension) {
4330: if (!$extension->isMethodSupported($methodReflection)) {
4331: continue;
4332: }
4333:
4334: $throwType = $extension->getThrowTypeFromMethodCall($methodReflection, $normalizedMethodCall, $scope);
4335: if ($throwType === null) {
4336: return null;
4337: }
4338:
4339: return ThrowPoint::createExplicit($scope, $throwType, $methodCall, false);
4340: }
4341: }
4342:
4343: $throwType = $methodReflection->getThrowType();
4344: if ($throwType === null) {
4345: $returnType = $parametersAcceptor->getReturnType();
4346: if ($returnType instanceof NeverType && $returnType->isExplicit()) {
4347: $throwType = new ObjectType(Throwable::class);
4348: }
4349: }
4350:
4351: if ($throwType !== null) {
4352: if (!$throwType->isVoid()->yes()) {
4353: return ThrowPoint::createExplicit($scope, $throwType, $methodCall, true);
4354: }
4355: } elseif ($this->implicitThrows) {
4356: $methodReturnedType = $scope->getType($methodCall);
4357: if (!(new ObjectType(Throwable::class))->isSuperTypeOf($methodReturnedType)->yes()) {
4358: return ThrowPoint::createImplicit($scope, $methodCall);
4359: }
4360: }
4361:
4362: return null;
4363: }
4364:
4365: /**
4366: * @param Node\Arg[] $args
4367: */
4368: private function getConstructorThrowPoint(MethodReflection $constructorReflection, ParametersAcceptor $parametersAcceptor, ClassReflection $classReflection, New_ $new, Name $className, array $args, MutatingScope $scope): ?ThrowPoint
4369: {
4370: $methodCall = new StaticCall($className, $constructorReflection->getName(), $args);
4371: $normalizedMethodCall = ArgumentsNormalizer::reorderStaticCallArguments($parametersAcceptor, $methodCall);
4372: if ($normalizedMethodCall !== null) {
4373: foreach ($this->dynamicThrowTypeExtensionProvider->getDynamicStaticMethodThrowTypeExtensions() as $extension) {
4374: if (!$extension->isStaticMethodSupported($constructorReflection)) {
4375: continue;
4376: }
4377:
4378: $throwType = $extension->getThrowTypeFromStaticMethodCall($constructorReflection, $normalizedMethodCall, $scope);
4379: if ($throwType === null) {
4380: return null;
4381: }
4382:
4383: return ThrowPoint::createExplicit($scope, $throwType, $new, false);
4384: }
4385: }
4386:
4387: if ($constructorReflection->getThrowType() !== null) {
4388: $throwType = $constructorReflection->getThrowType();
4389: if (!$throwType->isVoid()->yes()) {
4390: return ThrowPoint::createExplicit($scope, $throwType, $new, true);
4391: }
4392: } elseif ($this->implicitThrows) {
4393: if (!$classReflection->is(Throwable::class)) {
4394: return ThrowPoint::createImplicit($scope, $methodCall);
4395: }
4396: }
4397:
4398: return null;
4399: }
4400:
4401: private function getStaticMethodThrowPoint(MethodReflection $methodReflection, ParametersAcceptor $parametersAcceptor, StaticCall $methodCall, MutatingScope $scope): ?ThrowPoint
4402: {
4403: $normalizedMethodCall = ArgumentsNormalizer::reorderStaticCallArguments($parametersAcceptor, $methodCall);
4404: if ($normalizedMethodCall !== null) {
4405: foreach ($this->dynamicThrowTypeExtensionProvider->getDynamicStaticMethodThrowTypeExtensions() as $extension) {
4406: if (!$extension->isStaticMethodSupported($methodReflection)) {
4407: continue;
4408: }
4409:
4410: $throwType = $extension->getThrowTypeFromStaticMethodCall($methodReflection, $normalizedMethodCall, $scope);
4411: if ($throwType === null) {
4412: return null;
4413: }
4414:
4415: return ThrowPoint::createExplicit($scope, $throwType, $methodCall, false);
4416: }
4417: }
4418:
4419: if ($methodReflection->getThrowType() !== null) {
4420: $throwType = $methodReflection->getThrowType();
4421: if (!$throwType->isVoid()->yes()) {
4422: return ThrowPoint::createExplicit($scope, $throwType, $methodCall, true);
4423: }
4424: } elseif ($this->implicitThrows) {
4425: $methodReturnedType = $scope->getType($methodCall);
4426: if (!(new ObjectType(Throwable::class))->isSuperTypeOf($methodReturnedType)->yes()) {
4427: return ThrowPoint::createImplicit($scope, $methodCall);
4428: }
4429: }
4430:
4431: return null;
4432: }
4433:
4434: /**
4435: * @return ThrowPoint[]
4436: */
4437: private function getPropertyReadThrowPointsFromGetHook(
4438: MutatingScope $scope,
4439: PropertyFetch $propertyFetch,
4440: PhpPropertyReflection $propertyReflection,
4441: ): array
4442: {
4443: return $this->getThrowPointsFromPropertyHook($scope, $propertyFetch, $propertyReflection, 'get');
4444: }
4445:
4446: /**
4447: * @return ThrowPoint[]
4448: */
4449: private function getPropertyAssignThrowPointsFromSetHook(
4450: MutatingScope $scope,
4451: PropertyFetch $propertyFetch,
4452: PhpPropertyReflection $propertyReflection,
4453: ): array
4454: {
4455: return $this->getThrowPointsFromPropertyHook($scope, $propertyFetch, $propertyReflection, 'set');
4456: }
4457:
4458: /**
4459: * @param 'get'|'set' $hookName
4460: * @return ThrowPoint[]
4461: */
4462: private function getThrowPointsFromPropertyHook(
4463: MutatingScope $scope,
4464: PropertyFetch $propertyFetch,
4465: PhpPropertyReflection $propertyReflection,
4466: string $hookName,
4467: ): array
4468: {
4469: $scopeFunction = $scope->getFunction();
4470: if (
4471: $scopeFunction instanceof PhpMethodFromParserNodeReflection
4472: && $scopeFunction->isPropertyHook()
4473: && $propertyFetch->var instanceof Variable
4474: && $propertyFetch->var->name === 'this'
4475: && $propertyFetch->name instanceof Identifier
4476: && $propertyFetch->name->toString() === $scopeFunction->getHookedPropertyName()
4477: ) {
4478: return [];
4479: }
4480: $declaringClass = $propertyReflection->getDeclaringClass();
4481: if (!$propertyReflection->hasHook($hookName)) {
4482: if (
4483: $propertyReflection->isPrivate()
4484: || $propertyReflection->isFinal()->yes()
4485: || $declaringClass->isFinal()
4486: ) {
4487: return [];
4488: }
4489:
4490: if ($this->implicitThrows) {
4491: return [ThrowPoint::createImplicit($scope, $propertyFetch)];
4492: }
4493:
4494: return [];
4495: }
4496:
4497: $getHook = $propertyReflection->getHook($hookName);
4498: $throwType = $getHook->getThrowType();
4499:
4500: if ($throwType !== null) {
4501: if (!$throwType->isVoid()->yes()) {
4502: return [ThrowPoint::createExplicit($scope, $throwType, $propertyFetch, true)];
4503: }
4504: } elseif ($this->implicitThrows) {
4505: return [ThrowPoint::createImplicit($scope, $propertyFetch)];
4506: }
4507:
4508: return [];
4509: }
4510:
4511: /**
4512: * @return string[]
4513: */
4514: private function getAssignedVariables(Expr $expr): array
4515: {
4516: if ($expr instanceof Expr\Variable) {
4517: if (is_string($expr->name)) {
4518: return [$expr->name];
4519: }
4520:
4521: return [];
4522: }
4523:
4524: if ($expr instanceof Expr\List_) {
4525: $names = [];
4526: foreach ($expr->items as $item) {
4527: if ($item === null) {
4528: continue;
4529: }
4530:
4531: $names = array_merge($names, $this->getAssignedVariables($item->value));
4532: }
4533:
4534: return $names;
4535: }
4536:
4537: if ($expr instanceof ArrayDimFetch) {
4538: return $this->getAssignedVariables($expr->var);
4539: }
4540:
4541: return [];
4542: }
4543:
4544: /**
4545: * @param callable(Node $node, Scope $scope): void $nodeCallback
4546: */
4547: private function callNodeCallbackWithExpression(
4548: callable $nodeCallback,
4549: Expr $expr,
4550: MutatingScope $scope,
4551: ExpressionContext $context,
4552: ): void
4553: {
4554: if ($context->isDeep()) {
4555: $scope = $scope->exitFirstLevelStatements();
4556: }
4557: $nodeCallback($expr, $scope);
4558: }
4559:
4560: /**
4561: * @param callable(Node $node, Scope $scope): void $nodeCallback
4562: */
4563: private function processClosureNode(
4564: Node\Stmt $stmt,
4565: Expr\Closure $expr,
4566: MutatingScope $scope,
4567: callable $nodeCallback,
4568: ExpressionContext $context,
4569: ?Type $passedToType,
4570: ): ProcessClosureResult
4571: {
4572: foreach ($expr->params as $param) {
4573: $this->processParamNode($stmt, $param, $scope, $nodeCallback);
4574: }
4575:
4576: $byRefUses = [];
4577:
4578: $closureCallArgs = $expr->getAttribute(ClosureArgVisitor::ATTRIBUTE_NAME);
4579: $callableParameters = $this->createCallableParameters(
4580: $scope,
4581: $expr,
4582: $closureCallArgs,
4583: $passedToType,
4584: );
4585:
4586: $useScope = $scope;
4587: foreach ($expr->uses as $use) {
4588: if ($use->byRef) {
4589: $byRefUses[] = $use;
4590: $useScope = $useScope->enterExpressionAssign($use->var);
4591:
4592: $inAssignRightSideVariableName = $context->getInAssignRightSideVariableName();
4593: $inAssignRightSideType = $context->getInAssignRightSideType();
4594: $inAssignRightSideNativeType = $context->getInAssignRightSideNativeType();
4595: if (
4596: $inAssignRightSideVariableName === $use->var->name
4597: && $inAssignRightSideType !== null
4598: && $inAssignRightSideNativeType !== null
4599: ) {
4600: if ($inAssignRightSideType instanceof ClosureType) {
4601: $variableType = $inAssignRightSideType;
4602: } else {
4603: $alreadyHasVariableType = $scope->hasVariableType($inAssignRightSideVariableName);
4604: if ($alreadyHasVariableType->no()) {
4605: $variableType = TypeCombinator::union(new NullType(), $inAssignRightSideType);
4606: } else {
4607: $variableType = TypeCombinator::union($scope->getVariableType($inAssignRightSideVariableName), $inAssignRightSideType);
4608: }
4609: }
4610: if ($inAssignRightSideNativeType instanceof ClosureType) {
4611: $variableNativeType = $inAssignRightSideNativeType;
4612: } else {
4613: $alreadyHasVariableType = $scope->hasVariableType($inAssignRightSideVariableName);
4614: if ($alreadyHasVariableType->no()) {
4615: $variableNativeType = TypeCombinator::union(new NullType(), $inAssignRightSideNativeType);
4616: } else {
4617: $variableNativeType = TypeCombinator::union($scope->getVariableType($inAssignRightSideVariableName), $inAssignRightSideNativeType);
4618: }
4619: }
4620: $scope = $scope->assignVariable($inAssignRightSideVariableName, $variableType, $variableNativeType, TrinaryLogic::createYes());
4621: }
4622: }
4623: $this->processExprNode($stmt, $use->var, $useScope, $nodeCallback, $context);
4624: if (!$use->byRef) {
4625: continue;
4626: }
4627:
4628: $useScope = $useScope->exitExpressionAssign($use->var);
4629: }
4630:
4631: if ($expr->returnType !== null) {
4632: $nodeCallback($expr->returnType, $scope);
4633: }
4634:
4635: $closureScope = $scope->enterAnonymousFunction($expr, $callableParameters);
4636: $closureScope = $closureScope->processClosureScope($scope, null, $byRefUses);
4637: $closureType = $closureScope->getAnonymousFunctionReflection();
4638: if (!$closureType instanceof ClosureType) {
4639: throw new ShouldNotHappenException();
4640: }
4641:
4642: $nodeCallback(new InClosureNode($closureType, $expr), $closureScope);
4643:
4644: $executionEnds = [];
4645: $gatheredReturnStatements = [];
4646: $gatheredYieldStatements = [];
4647: $closureImpurePoints = [];
4648: $invalidateExpressions = [];
4649: $closureStmtsCallback = static function (Node $node, Scope $scope) use ($nodeCallback, &$executionEnds, &$gatheredReturnStatements, &$gatheredYieldStatements, &$closureScope, &$closureImpurePoints, &$invalidateExpressions): void {
4650: $nodeCallback($node, $scope);
4651: if ($scope->getAnonymousFunctionReflection() !== $closureScope->getAnonymousFunctionReflection()) {
4652: return;
4653: }
4654: if ($node instanceof PropertyAssignNode) {
4655: $closureImpurePoints[] = new ImpurePoint(
4656: $scope,
4657: $node,
4658: 'propertyAssign',
4659: 'property assignment',
4660: true,
4661: );
4662: return;
4663: }
4664: if ($node instanceof ExecutionEndNode) {
4665: $executionEnds[] = $node;
4666: return;
4667: }
4668: if ($node instanceof InvalidateExprNode) {
4669: $invalidateExpressions[] = $node;
4670: return;
4671: }
4672: if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) {
4673: $gatheredYieldStatements[] = $node;
4674: }
4675: if (!$node instanceof Return_) {
4676: return;
4677: }
4678:
4679: $gatheredReturnStatements[] = new ReturnStatement($scope, $node);
4680: };
4681:
4682: if (count($byRefUses) === 0) {
4683: $statementResult = $this->processStmtNodes($expr, $expr->stmts, $closureScope, $closureStmtsCallback, StatementContext::createTopLevel());
4684: $nodeCallback(new ClosureReturnStatementsNode(
4685: $expr,
4686: $gatheredReturnStatements,
4687: $gatheredYieldStatements,
4688: $statementResult,
4689: $executionEnds,
4690: array_merge($statementResult->getImpurePoints(), $closureImpurePoints),
4691: ), $closureScope);
4692:
4693: return new ProcessClosureResult($scope, $statementResult->getThrowPoints(), $statementResult->getImpurePoints(), $invalidateExpressions);
4694: }
4695:
4696: $count = 0;
4697: $closureResultScope = null;
4698: do {
4699: $prevScope = $closureScope;
4700:
4701: $intermediaryClosureScopeResult = $this->processStmtNodes($expr, $expr->stmts, $closureScope, static function (): void {
4702: }, StatementContext::createTopLevel());
4703: $intermediaryClosureScope = $intermediaryClosureScopeResult->getScope();
4704: foreach ($intermediaryClosureScopeResult->getExitPoints() as $exitPoint) {
4705: $intermediaryClosureScope = $intermediaryClosureScope->mergeWith($exitPoint->getScope());
4706: }
4707:
4708: if ($expr->getAttribute(ImmediatelyInvokedClosureVisitor::ATTRIBUTE_NAME) === true) {
4709: $closureResultScope = $intermediaryClosureScope;
4710: break;
4711: }
4712:
4713: $closureScope = $scope->enterAnonymousFunction($expr, $callableParameters);
4714: $closureScope = $closureScope->processClosureScope($intermediaryClosureScope, $prevScope, $byRefUses);
4715:
4716: if ($closureScope->equals($prevScope)) {
4717: break;
4718: }
4719: if ($count >= self::GENERALIZE_AFTER_ITERATION) {
4720: $closureScope = $prevScope->generalizeWith($closureScope);
4721: }
4722: $count++;
4723: } while ($count < self::LOOP_SCOPE_ITERATIONS);
4724:
4725: if ($closureResultScope === null) {
4726: $closureResultScope = $closureScope;
4727: }
4728:
4729: $statementResult = $this->processStmtNodes($expr, $expr->stmts, $closureScope, $closureStmtsCallback, StatementContext::createTopLevel());
4730: $nodeCallback(new ClosureReturnStatementsNode(
4731: $expr,
4732: $gatheredReturnStatements,
4733: $gatheredYieldStatements,
4734: $statementResult,
4735: $executionEnds,
4736: array_merge($statementResult->getImpurePoints(), $closureImpurePoints),
4737: ), $closureScope);
4738:
4739: return new ProcessClosureResult($scope->processClosureScope($closureResultScope, null, $byRefUses), $statementResult->getThrowPoints(), $statementResult->getImpurePoints(), $invalidateExpressions);
4740: }
4741:
4742: /**
4743: * @param InvalidateExprNode[] $invalidatedExpressions
4744: * @param string[] $uses
4745: */
4746: private function processImmediatelyCalledCallable(MutatingScope $scope, array $invalidatedExpressions, array $uses): MutatingScope
4747: {
4748: if ($scope->isInClass()) {
4749: $uses[] = 'this';
4750: }
4751:
4752: $finder = new NodeFinder();
4753: foreach ($invalidatedExpressions as $invalidateExpression) {
4754: $found = false;
4755: foreach ($uses as $use) {
4756: $result = $finder->findFirst([$invalidateExpression->getExpr()], static fn ($node) => $node instanceof Variable && $node->name === $use);
4757: if ($result === null) {
4758: continue;
4759: }
4760:
4761: $found = true;
4762: break;
4763: }
4764:
4765: if (!$found) {
4766: continue;
4767: }
4768:
4769: $scope = $scope->invalidateExpression($invalidateExpression->getExpr(), true);
4770: }
4771:
4772: return $scope;
4773: }
4774:
4775: /**
4776: * @param callable(Node $node, Scope $scope): void $nodeCallback
4777: */
4778: private function processArrowFunctionNode(
4779: Node\Stmt $stmt,
4780: Expr\ArrowFunction $expr,
4781: MutatingScope $scope,
4782: callable $nodeCallback,
4783: ?Type $passedToType,
4784: ): ExpressionResult
4785: {
4786: foreach ($expr->params as $param) {
4787: $this->processParamNode($stmt, $param, $scope, $nodeCallback);
4788: }
4789: if ($expr->returnType !== null) {
4790: $nodeCallback($expr->returnType, $scope);
4791: }
4792:
4793: $arrowFunctionCallArgs = $expr->getAttribute(ArrowFunctionArgVisitor::ATTRIBUTE_NAME);
4794: $arrowFunctionScope = $scope->enterArrowFunction($expr, $this->createCallableParameters(
4795: $scope,
4796: $expr,
4797: $arrowFunctionCallArgs,
4798: $passedToType,
4799: ));
4800: $arrowFunctionType = $arrowFunctionScope->getAnonymousFunctionReflection();
4801: if (!$arrowFunctionType instanceof ClosureType) {
4802: throw new ShouldNotHappenException();
4803: }
4804: $nodeCallback(new InArrowFunctionNode($arrowFunctionType, $expr), $arrowFunctionScope);
4805: $exprResult = $this->processExprNode($stmt, $expr->expr, $arrowFunctionScope, $nodeCallback, ExpressionContext::createTopLevel());
4806:
4807: return new ExpressionResult($scope, false, false, $exprResult->getThrowPoints(), $exprResult->getImpurePoints());
4808: }
4809:
4810: /**
4811: * @param Node\Arg[] $args
4812: * @return ParameterReflection[]|null
4813: */
4814: public function createCallableParameters(Scope $scope, Expr $closureExpr, ?array $args, ?Type $passedToType): ?array
4815: {
4816: $callableParameters = null;
4817: if ($args !== null) {
4818: $closureType = $scope->getType($closureExpr);
4819:
4820: if ($closureType->isCallable()->no()) {
4821: return null;
4822: }
4823:
4824: $acceptors = $closureType->getCallableParametersAcceptors($scope);
4825: if (count($acceptors) === 1) {
4826: $callableParameters = $acceptors[0]->getParameters();
4827:
4828: foreach ($callableParameters as $index => $callableParameter) {
4829: if (!isset($args[$index])) {
4830: continue;
4831: }
4832:
4833: $type = $scope->getType($args[$index]->value);
4834: $callableParameters[$index] = new NativeParameterReflection(
4835: $callableParameter->getName(),
4836: $callableParameter->isOptional(),
4837: $type,
4838: $callableParameter->passedByReference(),
4839: $callableParameter->isVariadic(),
4840: $callableParameter->getDefaultValue(),
4841: );
4842: }
4843: }
4844: } elseif ($passedToType !== null && !$passedToType->isCallable()->no()) {
4845: if ($passedToType instanceof UnionType) {
4846: $passedToType = TypeCombinator::union(...array_filter(
4847: $passedToType->getTypes(),
4848: static fn (Type $type) => $type->isCallable()->yes(),
4849: ));
4850:
4851: if ($passedToType->isCallable()->no()) {
4852: return null;
4853: }
4854: }
4855:
4856: $acceptors = $passedToType->getCallableParametersAcceptors($scope);
4857: if (count($acceptors) > 0) {
4858: foreach ($acceptors as $acceptor) {
4859: if ($callableParameters === null) {
4860: $callableParameters = array_map(static fn (ParameterReflection $callableParameter) => new NativeParameterReflection(
4861: $callableParameter->getName(),
4862: $callableParameter->isOptional(),
4863: $callableParameter->getType(),
4864: $callableParameter->passedByReference(),
4865: $callableParameter->isVariadic(),
4866: $callableParameter->getDefaultValue(),
4867: ), $acceptor->getParameters());
4868: continue;
4869: }
4870:
4871: $newParameters = [];
4872: foreach ($acceptor->getParameters() as $i => $callableParameter) {
4873: if (!array_key_exists($i, $callableParameters)) {
4874: $newParameters[] = $callableParameter;
4875: continue;
4876: }
4877:
4878: $newParameters[] = $callableParameters[$i]->union(new NativeParameterReflection(
4879: $callableParameter->getName(),
4880: $callableParameter->isOptional(),
4881: $callableParameter->getType(),
4882: $callableParameter->passedByReference(),
4883: $callableParameter->isVariadic(),
4884: $callableParameter->getDefaultValue(),
4885: ));
4886: }
4887:
4888: $callableParameters = $newParameters;
4889: }
4890: }
4891: }
4892:
4893: return $callableParameters;
4894: }
4895:
4896: /**
4897: * @param callable(Node $node, Scope $scope): void $nodeCallback
4898: */
4899: private function processParamNode(
4900: Node\Stmt $stmt,
4901: Node\Param $param,
4902: MutatingScope $scope,
4903: callable $nodeCallback,
4904: ): void
4905: {
4906: $this->processAttributeGroups($stmt, $param->attrGroups, $scope, $nodeCallback);
4907: $nodeCallback($param, $scope);
4908: if ($param->type !== null) {
4909: $nodeCallback($param->type, $scope);
4910: }
4911: if ($param->default === null) {
4912: return;
4913: }
4914:
4915: $this->processExprNode($stmt, $param->default, $scope, $nodeCallback, ExpressionContext::createDeep());
4916: }
4917:
4918: /**
4919: * @param AttributeGroup[] $attrGroups
4920: * @param callable(Node $node, Scope $scope): void $nodeCallback
4921: */
4922: private function processAttributeGroups(
4923: Node\Stmt $stmt,
4924: array $attrGroups,
4925: MutatingScope $scope,
4926: callable $nodeCallback,
4927: ): void
4928: {
4929: foreach ($attrGroups as $attrGroup) {
4930: foreach ($attrGroup->attrs as $attr) {
4931: foreach ($attr->args as $arg) {
4932: $this->processExprNode($stmt, $arg->value, $scope, $nodeCallback, ExpressionContext::createDeep());
4933: $nodeCallback($arg, $scope);
4934: }
4935: $nodeCallback($attr, $scope);
4936: }
4937: $nodeCallback($attrGroup, $scope);
4938: }
4939: }
4940:
4941: /**
4942: * @param Node\PropertyHook[] $hooks
4943: * @param callable(Node $node, Scope $scope): void $nodeCallback
4944: */
4945: private function processPropertyHooks(
4946: Node\Stmt $stmt,
4947: Identifier|Name|ComplexType|null $nativeTypeNode,
4948: ?Type $phpDocType,
4949: string $propertyName,
4950: array $hooks,
4951: MutatingScope $scope,
4952: callable $nodeCallback,
4953: ): void
4954: {
4955: if (!$scope->isInClass()) {
4956: throw new ShouldNotHappenException();
4957: }
4958:
4959: $classReflection = $scope->getClassReflection();
4960:
4961: foreach ($hooks as $hook) {
4962: $nodeCallback($hook, $scope);
4963: $this->processAttributeGroups($stmt, $hook->attrGroups, $scope, $nodeCallback);
4964:
4965: [, $phpDocParameterTypes,,,, $phpDocThrowType,,,,,,,, $phpDocComment] = $this->getPhpDocs($scope, $hook);
4966:
4967: foreach ($hook->params as $param) {
4968: $this->processParamNode($stmt, $param, $scope, $nodeCallback);
4969: }
4970:
4971: [$isDeprecated, $deprecatedDescription] = $this->getDeprecatedAttribute($scope, $hook);
4972:
4973: $hookScope = $scope->enterPropertyHook(
4974: $hook,
4975: $propertyName,
4976: $nativeTypeNode,
4977: $phpDocType,
4978: $phpDocParameterTypes,
4979: $phpDocThrowType,
4980: $deprecatedDescription,
4981: $isDeprecated,
4982: $phpDocComment,
4983: );
4984: $hookReflection = $hookScope->getFunction();
4985: if (!$hookReflection instanceof PhpMethodFromParserNodeReflection) {
4986: throw new ShouldNotHappenException();
4987: }
4988:
4989: if (!$classReflection->hasNativeProperty($propertyName)) {
4990: throw new ShouldNotHappenException();
4991: }
4992:
4993: $propertyReflection = $classReflection->getNativeProperty($propertyName);
4994:
4995: $nodeCallback(new InPropertyHookNode(
4996: $classReflection,
4997: $hookReflection,
4998: $propertyReflection,
4999: $hook,
5000: ), $hookScope);
5001:
5002: $stmts = $hook->getStmts();
5003: if ($stmts === null) {
5004: return;
5005: }
5006:
5007: if ($hook->body instanceof Expr) {
5008: // enrich attributes of nodes in short hook body statements
5009: $traverser = new NodeTraverser(
5010: new LineAttributesVisitor($hook->body->getStartLine(), $hook->body->getEndLine()),
5011: );
5012: $traverser->traverse($stmts);
5013: }
5014:
5015: $gatheredReturnStatements = [];
5016: $executionEnds = [];
5017: $methodImpurePoints = [];
5018: $statementResult = $this->processStmtNodes(new PropertyHookStatementNode($hook), $stmts, $hookScope, static function (Node $node, Scope $scope) use ($nodeCallback, $hookScope, &$gatheredReturnStatements, &$executionEnds, &$hookImpurePoints): void {
5019: $nodeCallback($node, $scope);
5020: if ($scope->getFunction() !== $hookScope->getFunction()) {
5021: return;
5022: }
5023: if ($scope->isInAnonymousFunction()) {
5024: return;
5025: }
5026: if ($node instanceof PropertyAssignNode) {
5027: $hookImpurePoints[] = new ImpurePoint(
5028: $scope,
5029: $node,
5030: 'propertyAssign',
5031: 'property assignment',
5032: true,
5033: );
5034: return;
5035: }
5036: if ($node instanceof ExecutionEndNode) {
5037: $executionEnds[] = $node;
5038: return;
5039: }
5040: if (!$node instanceof Return_) {
5041: return;
5042: }
5043:
5044: $gatheredReturnStatements[] = new ReturnStatement($scope, $node);
5045: }, StatementContext::createTopLevel());
5046:
5047: $nodeCallback(new PropertyHookReturnStatementsNode(
5048: $hook,
5049: $gatheredReturnStatements,
5050: $statementResult,
5051: $executionEnds,
5052: array_merge($statementResult->getImpurePoints(), $methodImpurePoints),
5053: $classReflection,
5054: $hookReflection,
5055: $propertyReflection,
5056: ), $hookScope);
5057: }
5058: }
5059:
5060: /**
5061: * @param MethodReflection|FunctionReflection|null $calleeReflection
5062: * @param callable(Node $node, Scope $scope): void $nodeCallback
5063: */
5064: private function processArgs(
5065: Node\Stmt $stmt,
5066: $calleeReflection,
5067: ?ExtendedMethodReflection $nakedMethodReflection,
5068: ?ParametersAcceptor $parametersAcceptor,
5069: CallLike $callLike,
5070: MutatingScope $scope,
5071: callable $nodeCallback,
5072: ExpressionContext $context,
5073: ?MutatingScope $closureBindScope = null,
5074: ): ExpressionResult
5075: {
5076: $args = $callLike->getArgs();
5077:
5078: if ($parametersAcceptor !== null) {
5079: $parameters = $parametersAcceptor->getParameters();
5080: }
5081:
5082: $hasYield = false;
5083: $throwPoints = [];
5084: $impurePoints = [];
5085: $isAlwaysTerminating = false;
5086: foreach ($args as $i => $arg) {
5087: $assignByReference = false;
5088: $parameter = null;
5089: $parameterType = null;
5090: $parameterNativeType = null;
5091: if (isset($parameters) && $parametersAcceptor !== null) {
5092: if (isset($parameters[$i])) {
5093: $assignByReference = $parameters[$i]->passedByReference()->createsNewVariable();
5094: $parameterType = $parameters[$i]->getType();
5095:
5096: if ($parameters[$i] instanceof ExtendedParameterReflection) {
5097: $parameterNativeType = $parameters[$i]->getNativeType();
5098: }
5099: $parameter = $parameters[$i];
5100: } elseif (count($parameters) > 0 && $parametersAcceptor->isVariadic()) {
5101: $lastParameter = $parameters[count($parameters) - 1];
5102: $assignByReference = $lastParameter->passedByReference()->createsNewVariable();
5103: $parameterType = $lastParameter->getType();
5104:
5105: if ($lastParameter instanceof ExtendedParameterReflection) {
5106: $parameterNativeType = $lastParameter->getNativeType();
5107: }
5108: $parameter = $lastParameter;
5109: }
5110: }
5111:
5112: $lookForUnset = false;
5113: if ($assignByReference) {
5114: $isBuiltin = false;
5115: if ($calleeReflection instanceof FunctionReflection && $calleeReflection->isBuiltin()) {
5116: $isBuiltin = true;
5117: } elseif ($calleeReflection instanceof ExtendedMethodReflection && $calleeReflection->getDeclaringClass()->isBuiltin()) {
5118: $isBuiltin = true;
5119: }
5120: if (
5121: $isBuiltin
5122: || ($parameterNativeType === null || !$parameterNativeType->isNull()->no())
5123: ) {
5124: $scope = $this->lookForSetAllowedUndefinedExpressions($scope, $arg->value);
5125: $lookForUnset = true;
5126: }
5127: }
5128:
5129: if ($calleeReflection !== null) {
5130: $scope = $scope->pushInFunctionCall($calleeReflection, $parameter);
5131: }
5132:
5133: $originalArg = $arg->getAttribute(ArgumentsNormalizer::ORIGINAL_ARG_ATTRIBUTE) ?? $arg;
5134: $nodeCallback($originalArg, $scope);
5135:
5136: $originalScope = $scope;
5137: $scopeToPass = $scope;
5138: if ($i === 0 && $closureBindScope !== null) {
5139: $scopeToPass = $closureBindScope;
5140: }
5141:
5142: $parameterCallableType = null;
5143: if ($parameterType !== null) {
5144: $parameterCallableType = TypeUtils::findCallableType($parameterType);
5145: }
5146:
5147: if ($parameter instanceof ExtendedParameterReflection) {
5148: $parameterCallImmediately = $parameter->isImmediatelyInvokedCallable();
5149: if ($parameterCallImmediately->maybe()) {
5150: $callCallbackImmediately = $parameterCallableType !== null && $calleeReflection instanceof FunctionReflection;
5151: } else {
5152: $callCallbackImmediately = $parameterCallImmediately->yes();
5153: }
5154: } else {
5155: $callCallbackImmediately = $parameterCallableType !== null && $calleeReflection instanceof FunctionReflection;
5156: }
5157:
5158: if ($arg->value instanceof Expr\Closure) {
5159: $restoreThisScope = null;
5160: if (
5161: $closureBindScope === null
5162: && $parameter instanceof ExtendedParameterReflection
5163: && $parameter->getClosureThisType() !== null
5164: && !$arg->value->static
5165: ) {
5166: $restoreThisScope = $scopeToPass;
5167: $scopeToPass = $scopeToPass->assignVariable('this', $parameter->getClosureThisType(), new ObjectWithoutClassType(), TrinaryLogic::createYes());
5168: }
5169:
5170: if ($parameter !== null) {
5171: $overwritingParameterType = $this->getParameterTypeFromParameterClosureTypeExtension($callLike, $calleeReflection, $parameter, $scopeToPass);
5172:
5173: if ($overwritingParameterType !== null) {
5174: $parameterType = $overwritingParameterType;
5175: }
5176: }
5177:
5178: $this->callNodeCallbackWithExpression($nodeCallback, $arg->value, $scopeToPass, $context);
5179: $closureResult = $this->processClosureNode($stmt, $arg->value, $scopeToPass, $nodeCallback, $context, $parameterType ?? null);
5180: if ($callCallbackImmediately) {
5181: $throwPoints = array_merge($throwPoints, array_map(static fn (ThrowPoint $throwPoint) => $throwPoint->isExplicit() ? ThrowPoint::createExplicit($scope, $throwPoint->getType(), $arg->value, $throwPoint->canContainAnyThrowable()) : ThrowPoint::createImplicit($scope, $arg->value), $closureResult->getThrowPoints()));
5182: $impurePoints = array_merge($impurePoints, $closureResult->getImpurePoints());
5183: }
5184:
5185: $uses = [];
5186: foreach ($arg->value->uses as $use) {
5187: if (!is_string($use->var->name)) {
5188: continue;
5189: }
5190:
5191: $uses[] = $use->var->name;
5192: }
5193:
5194: $scope = $closureResult->getScope();
5195: $invalidateExpressions = $closureResult->getInvalidateExpressions();
5196: if ($restoreThisScope !== null) {
5197: $nodeFinder = new NodeFinder();
5198: $cb = static fn ($expr) => $expr instanceof Variable && $expr->name === 'this';
5199: foreach ($invalidateExpressions as $j => $invalidateExprNode) {
5200: $foundThis = $nodeFinder->findFirst([$invalidateExprNode->getExpr()], $cb);
5201: if ($foundThis === null) {
5202: continue;
5203: }
5204:
5205: unset($invalidateExpressions[$j]);
5206: }
5207: $invalidateExpressions = array_values($invalidateExpressions);
5208: $scope = $scope->restoreThis($restoreThisScope);
5209: }
5210:
5211: $scope = $this->processImmediatelyCalledCallable($scope, $invalidateExpressions, $uses);
5212: } elseif ($arg->value instanceof Expr\ArrowFunction) {
5213: if (
5214: $closureBindScope === null
5215: && $parameter instanceof ExtendedParameterReflection
5216: && $parameter->getClosureThisType() !== null
5217: && !$arg->value->static
5218: ) {
5219: $scopeToPass = $scopeToPass->assignVariable('this', $parameter->getClosureThisType(), new ObjectWithoutClassType(), TrinaryLogic::createYes());
5220: }
5221:
5222: if ($parameter !== null) {
5223: $overwritingParameterType = $this->getParameterTypeFromParameterClosureTypeExtension($callLike, $calleeReflection, $parameter, $scopeToPass);
5224:
5225: if ($overwritingParameterType !== null) {
5226: $parameterType = $overwritingParameterType;
5227: }
5228: }
5229:
5230: $this->callNodeCallbackWithExpression($nodeCallback, $arg->value, $scopeToPass, $context);
5231: $arrowFunctionResult = $this->processArrowFunctionNode($stmt, $arg->value, $scopeToPass, $nodeCallback, $parameterType ?? null);
5232: if ($callCallbackImmediately) {
5233: $throwPoints = array_merge($throwPoints, array_map(static fn (ThrowPoint $throwPoint) => $throwPoint->isExplicit() ? ThrowPoint::createExplicit($scope, $throwPoint->getType(), $arg->value, $throwPoint->canContainAnyThrowable()) : ThrowPoint::createImplicit($scope, $arg->value), $arrowFunctionResult->getThrowPoints()));
5234: $impurePoints = array_merge($impurePoints, $arrowFunctionResult->getImpurePoints());
5235: }
5236: } else {
5237: $exprType = $scope->getType($arg->value);
5238: $exprResult = $this->processExprNode($stmt, $arg->value, $scopeToPass, $nodeCallback, $context->enterDeep());
5239: $throwPoints = array_merge($throwPoints, $exprResult->getThrowPoints());
5240: $impurePoints = array_merge($impurePoints, $exprResult->getImpurePoints());
5241: $isAlwaysTerminating = $isAlwaysTerminating || $exprResult->isAlwaysTerminating();
5242: $scope = $exprResult->getScope();
5243: $hasYield = $hasYield || $exprResult->hasYield();
5244:
5245: if ($exprType->isCallable()->yes()) {
5246: $acceptors = $exprType->getCallableParametersAcceptors($scope);
5247: if (count($acceptors) === 1) {
5248: $scope = $this->processImmediatelyCalledCallable($scope, $acceptors[0]->getInvalidateExpressions(), $acceptors[0]->getUsedVariables());
5249: if ($callCallbackImmediately) {
5250: $callableThrowPoints = array_map(static fn (SimpleThrowPoint $throwPoint) => $throwPoint->isExplicit() ? ThrowPoint::createExplicit($scope, $throwPoint->getType(), $arg->value, $throwPoint->canContainAnyThrowable()) : ThrowPoint::createImplicit($scope, $arg->value), $acceptors[0]->getThrowPoints());
5251: if (!$this->implicitThrows) {
5252: $callableThrowPoints = array_values(array_filter($callableThrowPoints, static fn (ThrowPoint $throwPoint) => $throwPoint->isExplicit()));
5253: }
5254: $throwPoints = array_merge($throwPoints, $callableThrowPoints);
5255: $impurePoints = array_merge($impurePoints, array_map(static fn (SimpleImpurePoint $impurePoint) => new ImpurePoint($scope, $arg->value, $impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain()), $acceptors[0]->getImpurePoints()));
5256: $returnType = $acceptors[0]->getReturnType();
5257: $isAlwaysTerminating = $isAlwaysTerminating || ($returnType instanceof NeverType && $returnType->isExplicit());
5258: }
5259: }
5260: }
5261: }
5262:
5263: if ($assignByReference && $lookForUnset) {
5264: $scope = $this->lookForUnsetAllowedUndefinedExpressions($scope, $arg->value);
5265: }
5266:
5267: if ($calleeReflection !== null) {
5268: $scope = $scope->popInFunctionCall();
5269: }
5270:
5271: if ($i !== 0 || $closureBindScope === null) {
5272: continue;
5273: }
5274:
5275: $scope = $scope->restoreOriginalScopeAfterClosureBind($originalScope);
5276: }
5277: foreach ($args as $i => $arg) {
5278: if (!isset($parameters) || $parametersAcceptor === null) {
5279: continue;
5280: }
5281:
5282: $byRefType = new MixedType();
5283: $assignByReference = false;
5284: $currentParameter = null;
5285: if (isset($parameters[$i])) {
5286: $currentParameter = $parameters[$i];
5287: } elseif (count($parameters) > 0 && $parametersAcceptor->isVariadic()) {
5288: $currentParameter = $parameters[count($parameters) - 1];
5289: }
5290:
5291: if ($currentParameter !== null) {
5292: $assignByReference = $currentParameter->passedByReference()->createsNewVariable();
5293: if ($assignByReference) {
5294: if ($currentParameter instanceof ExtendedParameterReflection && $currentParameter->getOutType() !== null) {
5295: $byRefType = $currentParameter->getOutType();
5296: } elseif (
5297: $calleeReflection instanceof MethodReflection
5298: && !$calleeReflection->getDeclaringClass()->isBuiltin()
5299: ) {
5300: $byRefType = $currentParameter->getType();
5301: } elseif (
5302: $calleeReflection instanceof FunctionReflection
5303: && !$calleeReflection->isBuiltin()
5304: ) {
5305: $byRefType = $currentParameter->getType();
5306: }
5307: }
5308: }
5309:
5310: if ($assignByReference) {
5311: if ($currentParameter === null) {
5312: throw new ShouldNotHappenException();
5313: }
5314:
5315: $argValue = $arg->value;
5316: if (!$argValue instanceof Variable || $argValue->name !== 'this') {
5317: $paramOutType = $this->getParameterOutExtensionsType($callLike, $calleeReflection, $currentParameter, $scope);
5318: if ($paramOutType !== null) {
5319: $byRefType = $paramOutType;
5320: }
5321:
5322: $result = $this->processAssignVar(
5323: $scope,
5324: $stmt,
5325: $argValue,
5326: new TypeExpr($byRefType),
5327: static function (Node $node, Scope $scope) use ($nodeCallback): void {
5328: if (!$node instanceof PropertyAssignNode && !$node instanceof VariableAssignNode) {
5329: return;
5330: }
5331:
5332: $nodeCallback($node, $scope);
5333: },
5334: $context,
5335: static fn (MutatingScope $scope): ExpressionResult => new ExpressionResult($scope, false, false, [], []),
5336: true,
5337: );
5338: $scope = $result->getScope();
5339: }
5340: } elseif ($calleeReflection !== null && $calleeReflection->hasSideEffects()->yes()) {
5341: $argType = $scope->getType($arg->value);
5342: if (!$argType->isObject()->no()) {
5343: $nakedReturnType = null;
5344: if ($nakedMethodReflection !== null) {
5345: $nakedParametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
5346: $scope,
5347: $args,
5348: $nakedMethodReflection->getVariants(),
5349: $nakedMethodReflection->getNamedArgumentsVariants(),
5350: );
5351: $nakedReturnType = $nakedParametersAcceptor->getReturnType();
5352: }
5353: if (
5354: $nakedReturnType === null
5355: || !(new ThisType($nakedMethodReflection->getDeclaringClass()))->isSuperTypeOf($nakedReturnType)->yes()
5356: || $nakedMethodReflection->isPure()->no()
5357: ) {
5358: $nodeCallback(new InvalidateExprNode($arg->value), $scope);
5359: $scope = $scope->invalidateExpression($arg->value, true);
5360: }
5361: } elseif (!(new ResourceType())->isSuperTypeOf($argType)->no()) {
5362: $nodeCallback(new InvalidateExprNode($arg->value), $scope);
5363: $scope = $scope->invalidateExpression($arg->value, true);
5364: }
5365: }
5366: }
5367:
5368: return new ExpressionResult($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints);
5369: }
5370:
5371: /**
5372: * @param MethodReflection|FunctionReflection|null $calleeReflection
5373: */
5374: private function getParameterTypeFromParameterClosureTypeExtension(CallLike $callLike, $calleeReflection, ParameterReflection $parameter, MutatingScope $scope): ?Type
5375: {
5376: if ($callLike instanceof FuncCall && $calleeReflection instanceof FunctionReflection) {
5377: foreach ($this->parameterClosureTypeExtensionProvider->getFunctionParameterClosureTypeExtensions() as $functionParameterClosureTypeExtension) {
5378: if ($functionParameterClosureTypeExtension->isFunctionSupported($calleeReflection, $parameter)) {
5379: return $functionParameterClosureTypeExtension->getTypeFromFunctionCall($calleeReflection, $callLike, $parameter, $scope);
5380: }
5381: }
5382: } elseif ($calleeReflection instanceof MethodReflection) {
5383: if ($callLike instanceof StaticCall) {
5384: foreach ($this->parameterClosureTypeExtensionProvider->getStaticMethodParameterClosureTypeExtensions() as $staticMethodParameterClosureTypeExtension) {
5385: if ($staticMethodParameterClosureTypeExtension->isStaticMethodSupported($calleeReflection, $parameter)) {
5386: return $staticMethodParameterClosureTypeExtension->getTypeFromStaticMethodCall($calleeReflection, $callLike, $parameter, $scope);
5387: }
5388: }
5389: } elseif ($callLike instanceof MethodCall) {
5390: foreach ($this->parameterClosureTypeExtensionProvider->getMethodParameterClosureTypeExtensions() as $methodParameterClosureTypeExtension) {
5391: if ($methodParameterClosureTypeExtension->isMethodSupported($calleeReflection, $parameter)) {
5392: return $methodParameterClosureTypeExtension->getTypeFromMethodCall($calleeReflection, $callLike, $parameter, $scope);
5393: }
5394: }
5395: }
5396: }
5397:
5398: return null;
5399: }
5400:
5401: /**
5402: * @param MethodReflection|FunctionReflection|null $calleeReflection
5403: */
5404: private function getParameterOutExtensionsType(CallLike $callLike, $calleeReflection, ParameterReflection $currentParameter, MutatingScope $scope): ?Type
5405: {
5406: $paramOutTypes = [];
5407: if ($callLike instanceof FuncCall && $calleeReflection instanceof FunctionReflection) {
5408: foreach ($this->parameterOutTypeExtensionProvider->getFunctionParameterOutTypeExtensions() as $functionParameterOutTypeExtension) {
5409: if (!$functionParameterOutTypeExtension->isFunctionSupported($calleeReflection, $currentParameter)) {
5410: continue;
5411: }
5412:
5413: $resolvedType = $functionParameterOutTypeExtension->getParameterOutTypeFromFunctionCall($calleeReflection, $callLike, $currentParameter, $scope);
5414: if ($resolvedType === null) {
5415: continue;
5416: }
5417: $paramOutTypes[] = $resolvedType;
5418: }
5419: } elseif ($callLike instanceof MethodCall && $calleeReflection instanceof MethodReflection) {
5420: foreach ($this->parameterOutTypeExtensionProvider->getMethodParameterOutTypeExtensions() as $methodParameterOutTypeExtension) {
5421: if (!$methodParameterOutTypeExtension->isMethodSupported($calleeReflection, $currentParameter)) {
5422: continue;
5423: }
5424:
5425: $resolvedType = $methodParameterOutTypeExtension->getParameterOutTypeFromMethodCall($calleeReflection, $callLike, $currentParameter, $scope);
5426: if ($resolvedType === null) {
5427: continue;
5428: }
5429: $paramOutTypes[] = $resolvedType;
5430: }
5431: } elseif ($callLike instanceof StaticCall && $calleeReflection instanceof MethodReflection) {
5432: foreach ($this->parameterOutTypeExtensionProvider->getStaticMethodParameterOutTypeExtensions() as $staticMethodParameterOutTypeExtension) {
5433: if (!$staticMethodParameterOutTypeExtension->isStaticMethodSupported($calleeReflection, $currentParameter)) {
5434: continue;
5435: }
5436:
5437: $resolvedType = $staticMethodParameterOutTypeExtension->getParameterOutTypeFromStaticMethodCall($calleeReflection, $callLike, $currentParameter, $scope);
5438: if ($resolvedType === null) {
5439: continue;
5440: }
5441: $paramOutTypes[] = $resolvedType;
5442: }
5443: }
5444:
5445: if (count($paramOutTypes) === 1) {
5446: return $paramOutTypes[0];
5447: }
5448:
5449: if (count($paramOutTypes) > 1) {
5450: return TypeCombinator::union(...$paramOutTypes);
5451: }
5452:
5453: return null;
5454: }
5455:
5456: /**
5457: * @param callable(Node $node, Scope $scope): void $nodeCallback
5458: * @param Closure(MutatingScope $scope): ExpressionResult $processExprCallback
5459: */
5460: private function processAssignVar(
5461: MutatingScope $scope,
5462: Node\Stmt $stmt,
5463: Expr $var,
5464: Expr $assignedExpr,
5465: callable $nodeCallback,
5466: ExpressionContext $context,
5467: Closure $processExprCallback,
5468: bool $enterExpressionAssign,
5469: ): ExpressionResult
5470: {
5471: $nodeCallback($var, $enterExpressionAssign ? $scope->enterExpressionAssign($var) : $scope);
5472: $hasYield = false;
5473: $throwPoints = [];
5474: $impurePoints = [];
5475: $isAlwaysTerminating = false;
5476: $isAssignOp = $assignedExpr instanceof Expr\AssignOp && !$enterExpressionAssign;
5477: if ($var instanceof Variable && is_string($var->name)) {
5478: $result = $processExprCallback($scope);
5479: $hasYield = $result->hasYield();
5480: $throwPoints = $result->getThrowPoints();
5481: $impurePoints = $result->getImpurePoints();
5482: $isAlwaysTerminating = $result->isAlwaysTerminating();
5483: if (in_array($var->name, Scope::SUPERGLOBAL_VARIABLES, true)) {
5484: $impurePoints[] = new ImpurePoint($scope, $var, 'superglobal', 'assign to superglobal variable', true);
5485: }
5486: $assignedExpr = $this->unwrapAssign($assignedExpr);
5487: $type = $scope->getType($assignedExpr);
5488:
5489: $conditionalExpressions = [];
5490: if ($assignedExpr instanceof Ternary) {
5491: $if = $assignedExpr->if;
5492: if ($if === null) {
5493: $if = $assignedExpr->cond;
5494: }
5495: $condScope = $this->processExprNode($stmt, $assignedExpr->cond, $scope, static function (): void {
5496: }, ExpressionContext::createDeep())->getScope();
5497: $truthySpecifiedTypes = $this->typeSpecifier->specifyTypesInCondition($condScope, $assignedExpr->cond, TypeSpecifierContext::createTruthy());
5498: $falseySpecifiedTypes = $this->typeSpecifier->specifyTypesInCondition($condScope, $assignedExpr->cond, TypeSpecifierContext::createFalsey());
5499: $truthyScope = $condScope->filterBySpecifiedTypes($truthySpecifiedTypes);
5500: $falsyScope = $condScope->filterBySpecifiedTypes($falseySpecifiedTypes);
5501: $truthyType = $truthyScope->getType($if);
5502: $falseyType = $falsyScope->getType($assignedExpr->else);
5503:
5504: if (
5505: $truthyType->isSuperTypeOf($falseyType)->no()
5506: && $falseyType->isSuperTypeOf($truthyType)->no()
5507: ) {
5508: $conditionalExpressions = $this->processSureTypesForConditionalExpressionsAfterAssign($condScope, $var->name, $conditionalExpressions, $truthySpecifiedTypes, $truthyType);
5509: $conditionalExpressions = $this->processSureNotTypesForConditionalExpressionsAfterAssign($condScope, $var->name, $conditionalExpressions, $truthySpecifiedTypes, $truthyType);
5510: $conditionalExpressions = $this->processSureTypesForConditionalExpressionsAfterAssign($condScope, $var->name, $conditionalExpressions, $falseySpecifiedTypes, $falseyType);
5511: $conditionalExpressions = $this->processSureNotTypesForConditionalExpressionsAfterAssign($condScope, $var->name, $conditionalExpressions, $falseySpecifiedTypes, $falseyType);
5512: }
5513: }
5514:
5515: $scopeBeforeAssignEval = $scope;
5516: $scope = $result->getScope();
5517: $truthySpecifiedTypes = $this->typeSpecifier->specifyTypesInCondition($scope, $assignedExpr, TypeSpecifierContext::createTruthy());
5518: $falseySpecifiedTypes = $this->typeSpecifier->specifyTypesInCondition($scope, $assignedExpr, TypeSpecifierContext::createFalsey());
5519:
5520: $truthyType = TypeCombinator::removeFalsey($type);
5521: $falseyType = TypeCombinator::intersect($type, StaticTypeFactory::falsey());
5522:
5523: $conditionalExpressions = $this->processSureTypesForConditionalExpressionsAfterAssign($scope, $var->name, $conditionalExpressions, $truthySpecifiedTypes, $truthyType);
5524: $conditionalExpressions = $this->processSureNotTypesForConditionalExpressionsAfterAssign($scope, $var->name, $conditionalExpressions, $truthySpecifiedTypes, $truthyType);
5525: $conditionalExpressions = $this->processSureTypesForConditionalExpressionsAfterAssign($scope, $var->name, $conditionalExpressions, $falseySpecifiedTypes, $falseyType);
5526: $conditionalExpressions = $this->processSureNotTypesForConditionalExpressionsAfterAssign($scope, $var->name, $conditionalExpressions, $falseySpecifiedTypes, $falseyType);
5527:
5528: $nodeCallback(new VariableAssignNode($var, $assignedExpr), $scopeBeforeAssignEval);
5529: $scope = $scope->assignVariable($var->name, $type, $scope->getNativeType($assignedExpr), TrinaryLogic::createYes());
5530: foreach ($conditionalExpressions as $exprString => $holders) {
5531: $scope = $scope->addConditionalExpressions($exprString, $holders);
5532: }
5533: } elseif ($var instanceof ArrayDimFetch) {
5534: $dimFetchStack = [];
5535: $originalVar = $var;
5536: $assignedPropertyExpr = $assignedExpr;
5537: while ($var instanceof ArrayDimFetch) {
5538: if (
5539: $var->var instanceof PropertyFetch
5540: || $var->var instanceof StaticPropertyFetch
5541: ) {
5542: if (((new ObjectType(ArrayAccess::class))->isSuperTypeOf($scope->getType($var->var))->yes())) {
5543: $varForSetOffsetValue = $var->var;
5544: } else {
5545: $varForSetOffsetValue = new OriginalPropertyTypeExpr($var->var);
5546: }
5547: } else {
5548: $varForSetOffsetValue = $var->var;
5549: }
5550: $assignedPropertyExpr = new SetOffsetValueTypeExpr(
5551: $varForSetOffsetValue,
5552: $var->dim,
5553: $assignedPropertyExpr,
5554: );
5555: $dimFetchStack[] = $var;
5556: $var = $var->var;
5557: }
5558:
5559: // 1. eval root expr
5560: if ($enterExpressionAssign) {
5561: $scope = $scope->enterExpressionAssign($var);
5562: }
5563: $result = $this->processExprNode($stmt, $var, $scope, $nodeCallback, $context->enterDeep());
5564: $hasYield = $result->hasYield();
5565: $throwPoints = $result->getThrowPoints();
5566: $impurePoints = $result->getImpurePoints();
5567: $isAlwaysTerminating = $result->isAlwaysTerminating();
5568: $scope = $result->getScope();
5569: if ($enterExpressionAssign) {
5570: $scope = $scope->exitExpressionAssign($var);
5571: }
5572:
5573: // 2. eval dimensions
5574: $offsetTypes = [];
5575: $offsetNativeTypes = [];
5576: $dimFetchStack = array_reverse($dimFetchStack);
5577: $lastDimKey = array_key_last($dimFetchStack);
5578: foreach ($dimFetchStack as $key => $dimFetch) {
5579: $dimExpr = $dimFetch->dim;
5580:
5581: // Callback was already called for last dim at the beginning of the method.
5582: if ($key !== $lastDimKey) {
5583: $nodeCallback($dimFetch, $enterExpressionAssign ? $scope->enterExpressionAssign($dimFetch) : $scope);
5584: }
5585:
5586: if ($dimExpr === null) {
5587: $offsetTypes[] = null;
5588: $offsetNativeTypes[] = null;
5589:
5590: } else {
5591: $offsetTypes[] = $scope->getType($dimExpr);
5592: $offsetNativeTypes[] = $scope->getNativeType($dimExpr);
5593:
5594: if ($enterExpressionAssign) {
5595: $scope->enterExpressionAssign($dimExpr);
5596: }
5597: $result = $this->processExprNode($stmt, $dimExpr, $scope, $nodeCallback, $context->enterDeep());
5598: $hasYield = $hasYield || $result->hasYield();
5599: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
5600: $scope = $result->getScope();
5601:
5602: if ($enterExpressionAssign) {
5603: $scope = $scope->exitExpressionAssign($dimExpr);
5604: }
5605: }
5606: }
5607:
5608: $valueToWrite = $scope->getType($assignedExpr);
5609: $nativeValueToWrite = $scope->getNativeType($assignedExpr);
5610: $originalValueToWrite = $valueToWrite;
5611: $originalNativeValueToWrite = $nativeValueToWrite;
5612: $scopeBeforeAssignEval = $scope;
5613:
5614: // 3. eval assigned expr
5615: $result = $processExprCallback($scope);
5616: $hasYield = $hasYield || $result->hasYield();
5617: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
5618: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
5619: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
5620: $scope = $result->getScope();
5621:
5622: $varType = $scope->getType($var);
5623: $varNativeType = $scope->getNativeType($var);
5624:
5625: // 4. compose types
5626: if ($varType instanceof ErrorType) {
5627: $varType = new ConstantArrayType([], []);
5628: }
5629: if ($varNativeType instanceof ErrorType) {
5630: $varNativeType = new ConstantArrayType([], []);
5631: }
5632: $offsetValueType = $varType;
5633: $offsetNativeValueType = $varNativeType;
5634:
5635: $valueToWrite = $this->produceArrayDimFetchAssignValueToWrite($dimFetchStack, $offsetTypes, $offsetValueType, $valueToWrite, $scope);
5636:
5637: if (!$offsetValueType->equals($offsetNativeValueType) || !$valueToWrite->equals($nativeValueToWrite)) {
5638: $nativeValueToWrite = $this->produceArrayDimFetchAssignValueToWrite($dimFetchStack, $offsetNativeTypes, $offsetNativeValueType, $nativeValueToWrite, $scope);
5639: } else {
5640: $rewritten = false;
5641: foreach ($offsetTypes as $i => $offsetType) {
5642: $offsetNativeType = $offsetNativeTypes[$i];
5643:
5644: if ($offsetType === null) {
5645: if ($offsetNativeType !== null) {
5646: throw new ShouldNotHappenException();
5647: }
5648:
5649: continue;
5650: } elseif ($offsetNativeType === null) {
5651: throw new ShouldNotHappenException();
5652: }
5653: if ($offsetType->equals($offsetNativeType)) {
5654: continue;
5655: }
5656:
5657: $nativeValueToWrite = $this->produceArrayDimFetchAssignValueToWrite($dimFetchStack, $offsetNativeTypes, $offsetNativeValueType, $nativeValueToWrite, $scope);
5658: $rewritten = true;
5659: break;
5660: }
5661:
5662: if (!$rewritten) {
5663: $nativeValueToWrite = $valueToWrite;
5664: }
5665: }
5666:
5667: if ($varType->isArray()->yes() || !(new ObjectType(ArrayAccess::class))->isSuperTypeOf($varType)->yes()) {
5668: if ($var instanceof Variable && is_string($var->name)) {
5669: $nodeCallback(new VariableAssignNode($var, $assignedPropertyExpr), $scopeBeforeAssignEval);
5670: $scope = $scope->assignVariable($var->name, $valueToWrite, $nativeValueToWrite, TrinaryLogic::createYes());
5671: } else {
5672: if ($var instanceof PropertyFetch || $var instanceof StaticPropertyFetch) {
5673: $nodeCallback(new PropertyAssignNode($var, $assignedPropertyExpr, $isAssignOp), $scopeBeforeAssignEval);
5674: if ($var instanceof PropertyFetch && $var->name instanceof Node\Identifier && !$isAssignOp) {
5675: $scope = $scope->assignInitializedProperty($scope->getType($var->var), $var->name->toString());
5676: }
5677: }
5678: $scope = $scope->assignExpression(
5679: $var,
5680: $valueToWrite,
5681: $nativeValueToWrite,
5682: );
5683: }
5684:
5685: if ($originalVar->dim instanceof Variable || $originalVar->dim instanceof Node\Scalar) {
5686: $currentVarType = $scope->getType($originalVar);
5687: $currentVarNativeType = $scope->getNativeType($originalVar);
5688: if (
5689: !$originalValueToWrite->isSuperTypeOf($currentVarType)->yes()
5690: || !$originalNativeValueToWrite->isSuperTypeOf($currentVarNativeType)->yes()
5691: ) {
5692: $scope = $scope->assignExpression(
5693: $originalVar,
5694: $originalValueToWrite,
5695: $originalNativeValueToWrite,
5696: );
5697: }
5698: }
5699: } else {
5700: if ($var instanceof Variable) {
5701: $nodeCallback(new VariableAssignNode($var, $assignedPropertyExpr), $scopeBeforeAssignEval);
5702: } elseif ($var instanceof PropertyFetch || $var instanceof StaticPropertyFetch) {
5703: $nodeCallback(new PropertyAssignNode($var, $assignedPropertyExpr, $isAssignOp), $scopeBeforeAssignEval);
5704: if ($var instanceof PropertyFetch && $var->name instanceof Node\Identifier && !$isAssignOp) {
5705: $scope = $scope->assignInitializedProperty($scope->getType($var->var), $var->name->toString());
5706: }
5707: }
5708: }
5709:
5710: if (!$varType->isArray()->yes() && !(new ObjectType(ArrayAccess::class))->isSuperTypeOf($varType)->no()) {
5711: $throwPoints = array_merge($throwPoints, $this->processExprNode(
5712: $stmt,
5713: new MethodCall($var, 'offsetSet'),
5714: $scope,
5715: static function (): void {
5716: },
5717: $context,
5718: )->getThrowPoints());
5719: }
5720: } elseif ($var instanceof PropertyFetch) {
5721: $objectResult = $this->processExprNode($stmt, $var->var, $scope, $nodeCallback, $context);
5722: $hasYield = $objectResult->hasYield();
5723: $throwPoints = $objectResult->getThrowPoints();
5724: $impurePoints = $objectResult->getImpurePoints();
5725: $isAlwaysTerminating = $objectResult->isAlwaysTerminating();
5726: $scope = $objectResult->getScope();
5727:
5728: $propertyName = null;
5729: if ($var->name instanceof Node\Identifier) {
5730: $propertyName = $var->name->name;
5731: } else {
5732: $propertyNameResult = $this->processExprNode($stmt, $var->name, $scope, $nodeCallback, $context);
5733: $hasYield = $hasYield || $propertyNameResult->hasYield();
5734: $throwPoints = array_merge($throwPoints, $propertyNameResult->getThrowPoints());
5735: $impurePoints = array_merge($impurePoints, $propertyNameResult->getImpurePoints());
5736: $isAlwaysTerminating = $isAlwaysTerminating || $propertyNameResult->isAlwaysTerminating();
5737: $scope = $propertyNameResult->getScope();
5738: }
5739:
5740: $scopeBeforeAssignEval = $scope;
5741: $result = $processExprCallback($scope);
5742: $hasYield = $hasYield || $result->hasYield();
5743: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
5744: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
5745: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
5746: $scope = $result->getScope();
5747:
5748: if ($var->name instanceof Expr && $this->phpVersion->supportsPropertyHooks()) {
5749: $throwPoints[] = ThrowPoint::createImplicit($scope, $var);
5750: }
5751:
5752: $propertyHolderType = $scope->getType($var->var);
5753: if ($propertyName !== null && $propertyHolderType->hasProperty($propertyName)->yes()) {
5754: $propertyReflection = $propertyHolderType->getProperty($propertyName, $scope);
5755: $assignedExprType = $scope->getType($assignedExpr);
5756: $nodeCallback(new PropertyAssignNode($var, $assignedExpr, $isAssignOp), $scopeBeforeAssignEval);
5757: if ($propertyReflection->canChangeTypeAfterAssignment()) {
5758: if ($propertyReflection->hasNativeType()) {
5759: $propertyNativeType = $propertyReflection->getNativeType();
5760:
5761: $assignedTypeIsCompatible = $propertyNativeType->isSuperTypeOf($assignedExprType)->yes();
5762: if (!$assignedTypeIsCompatible) {
5763: foreach (TypeUtils::flattenTypes($propertyNativeType) as $type) {
5764: if ($type->isSuperTypeOf($assignedExprType)->yes()) {
5765: $assignedTypeIsCompatible = true;
5766: break;
5767: }
5768: }
5769: }
5770:
5771: if ($assignedTypeIsCompatible) {
5772: $scope = $scope->assignExpression($var, $assignedExprType, $scope->getNativeType($assignedExpr));
5773: } else {
5774: $scope = $scope->assignExpression(
5775: $var,
5776: TypeCombinator::intersect($assignedExprType->toCoercedArgumentType($scope->isDeclareStrictTypes()), $propertyNativeType),
5777: TypeCombinator::intersect($scope->getNativeType($assignedExpr)->toCoercedArgumentType($scope->isDeclareStrictTypes()), $propertyNativeType),
5778: );
5779: }
5780: } else {
5781: $scope = $scope->assignExpression($var, $assignedExprType, $scope->getNativeType($assignedExpr));
5782: }
5783: }
5784: $declaringClass = $propertyReflection->getDeclaringClass();
5785: if ($declaringClass->hasNativeProperty($propertyName)) {
5786: $nativeProperty = $declaringClass->getNativeProperty($propertyName);
5787: if (
5788: !$nativeProperty->getNativeType()->accepts($assignedExprType, true)->yes()
5789: ) {
5790: $throwPoints[] = ThrowPoint::createExplicit($scope, new ObjectType(TypeError::class), $assignedExpr, false);
5791: }
5792: if ($this->phpVersion->supportsPropertyHooks()) {
5793: $throwPoints = array_merge($throwPoints, $this->getPropertyAssignThrowPointsFromSetHook($scope, $var, $nativeProperty));
5794: }
5795: if ($enterExpressionAssign) {
5796: $scope = $scope->assignInitializedProperty($propertyHolderType, $propertyName);
5797: }
5798: }
5799: } else {
5800: // fallback
5801: $assignedExprType = $scope->getType($assignedExpr);
5802: $nodeCallback(new PropertyAssignNode($var, $assignedExpr, $isAssignOp), $scopeBeforeAssignEval);
5803: $scope = $scope->assignExpression($var, $assignedExprType, $scope->getNativeType($assignedExpr));
5804: // simulate dynamic property assign by __set to get throw points
5805: if (!$propertyHolderType->hasMethod('__set')->no()) {
5806: $throwPoints = array_merge($throwPoints, $this->processExprNode(
5807: $stmt,
5808: new MethodCall($var->var, '__set'),
5809: $scope,
5810: static function (): void {
5811: },
5812: $context,
5813: )->getThrowPoints());
5814: }
5815: }
5816:
5817: } elseif ($var instanceof Expr\StaticPropertyFetch) {
5818: if ($var->class instanceof Node\Name) {
5819: $propertyHolderType = $scope->resolveTypeByName($var->class);
5820: } else {
5821: $this->processExprNode($stmt, $var->class, $scope, $nodeCallback, $context);
5822: $propertyHolderType = $scope->getType($var->class);
5823: }
5824:
5825: $propertyName = null;
5826: if ($var->name instanceof Node\Identifier) {
5827: $propertyName = $var->name->name;
5828: } else {
5829: $propertyNameResult = $this->processExprNode($stmt, $var->name, $scope, $nodeCallback, $context);
5830: $hasYield = $propertyNameResult->hasYield();
5831: $throwPoints = $propertyNameResult->getThrowPoints();
5832: $impurePoints = $propertyNameResult->getImpurePoints();
5833: $isAlwaysTerminating = $propertyNameResult->isAlwaysTerminating();
5834: $scope = $propertyNameResult->getScope();
5835: }
5836:
5837: $scopeBeforeAssignEval = $scope;
5838: $result = $processExprCallback($scope);
5839: $hasYield = $hasYield || $result->hasYield();
5840: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
5841: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
5842: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
5843: $scope = $result->getScope();
5844:
5845: if ($propertyName !== null) {
5846: $propertyReflection = $scope->getPropertyReflection($propertyHolderType, $propertyName);
5847: $assignedExprType = $scope->getType($assignedExpr);
5848: $nodeCallback(new PropertyAssignNode($var, $assignedExpr, $isAssignOp), $scopeBeforeAssignEval);
5849: if ($propertyReflection !== null && $propertyReflection->canChangeTypeAfterAssignment()) {
5850: if ($propertyReflection->hasNativeType()) {
5851: $propertyNativeType = $propertyReflection->getNativeType();
5852: $assignedTypeIsCompatible = $propertyNativeType->isSuperTypeOf($assignedExprType)->yes();
5853:
5854: if (!$assignedTypeIsCompatible) {
5855: foreach (TypeUtils::flattenTypes($propertyNativeType) as $type) {
5856: if ($type->isSuperTypeOf($assignedExprType)->yes()) {
5857: $assignedTypeIsCompatible = true;
5858: break;
5859: }
5860: }
5861: }
5862:
5863: if ($assignedTypeIsCompatible) {
5864: $scope = $scope->assignExpression($var, $assignedExprType, $scope->getNativeType($assignedExpr));
5865: } else {
5866: $scope = $scope->assignExpression(
5867: $var,
5868: TypeCombinator::intersect($assignedExprType->toCoercedArgumentType($scope->isDeclareStrictTypes()), $propertyNativeType),
5869: TypeCombinator::intersect($scope->getNativeType($assignedExpr)->toCoercedArgumentType($scope->isDeclareStrictTypes()), $propertyNativeType),
5870: );
5871: }
5872: } else {
5873: $scope = $scope->assignExpression($var, $assignedExprType, $scope->getNativeType($assignedExpr));
5874: }
5875: }
5876: } else {
5877: // fallback
5878: $assignedExprType = $scope->getType($assignedExpr);
5879: $nodeCallback(new PropertyAssignNode($var, $assignedExpr, $isAssignOp), $scopeBeforeAssignEval);
5880: $scope = $scope->assignExpression($var, $assignedExprType, $scope->getNativeType($assignedExpr));
5881: }
5882: } elseif ($var instanceof List_) {
5883: $result = $processExprCallback($scope);
5884: $hasYield = $result->hasYield();
5885: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
5886: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
5887: $isAlwaysTerminating = $result->isAlwaysTerminating();
5888: $scope = $result->getScope();
5889: foreach ($var->items as $i => $arrayItem) {
5890: if ($arrayItem === null) {
5891: continue;
5892: }
5893:
5894: $itemScope = $scope;
5895: if ($enterExpressionAssign) {
5896: $itemScope = $itemScope->enterExpressionAssign($arrayItem->value);
5897: }
5898: $itemScope = $this->lookForSetAllowedUndefinedExpressions($itemScope, $arrayItem->value);
5899: $nodeCallback($arrayItem, $itemScope);
5900: if ($arrayItem->key !== null) {
5901: $keyResult = $this->processExprNode($stmt, $arrayItem->key, $itemScope, $nodeCallback, $context->enterDeep());
5902: $hasYield = $hasYield || $keyResult->hasYield();
5903: $throwPoints = array_merge($throwPoints, $keyResult->getThrowPoints());
5904: $impurePoints = array_merge($impurePoints, $keyResult->getImpurePoints());
5905: $isAlwaysTerminating = $isAlwaysTerminating || $keyResult->isAlwaysTerminating();
5906: $itemScope = $keyResult->getScope();
5907: }
5908:
5909: $valueResult = $this->processExprNode($stmt, $arrayItem->value, $itemScope, $nodeCallback, $context->enterDeep());
5910: $hasYield = $hasYield || $valueResult->hasYield();
5911: $throwPoints = array_merge($throwPoints, $valueResult->getThrowPoints());
5912: $impurePoints = array_merge($impurePoints, $valueResult->getImpurePoints());
5913: $isAlwaysTerminating = $isAlwaysTerminating || $valueResult->isAlwaysTerminating();
5914:
5915: if ($arrayItem->key === null) {
5916: $dimExpr = new Node\Scalar\Int_($i);
5917: } else {
5918: $dimExpr = $arrayItem->key;
5919: }
5920: $result = $this->processAssignVar(
5921: $scope,
5922: $stmt,
5923: $arrayItem->value,
5924: new GetOffsetValueTypeExpr($assignedExpr, $dimExpr),
5925: $nodeCallback,
5926: $context,
5927: static fn (MutatingScope $scope): ExpressionResult => new ExpressionResult($scope, false, false, [], []),
5928: $enterExpressionAssign,
5929: );
5930: $scope = $result->getScope();
5931: $hasYield = $hasYield || $result->hasYield();
5932: $throwPoints = array_merge($throwPoints, $result->getThrowPoints());
5933: $impurePoints = array_merge($impurePoints, $result->getImpurePoints());
5934: $isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
5935: }
5936: } elseif ($var instanceof ExistingArrayDimFetch) {
5937: $dimFetchStack = [];
5938: $assignedPropertyExpr = $assignedExpr;
5939: while ($var instanceof ExistingArrayDimFetch) {
5940: if (
5941: $var->getVar() instanceof PropertyFetch
5942: || $var->getVar() instanceof StaticPropertyFetch
5943: ) {
5944: if (((new ObjectType(ArrayAccess::class))->isSuperTypeOf($scope->getType($var->getVar()))->yes())) {
5945: $varForSetOffsetValue = $var->getVar();
5946: } else {
5947: $varForSetOffsetValue = new OriginalPropertyTypeExpr($var->getVar());
5948: }
5949: } else {
5950: $varForSetOffsetValue = $var->getVar();
5951: }
5952: $assignedPropertyExpr = new SetExistingOffsetValueTypeExpr(
5953: $varForSetOffsetValue,
5954: $var->getDim(),
5955: $assignedPropertyExpr,
5956: );
5957: $dimFetchStack[] = $var;
5958: $var = $var->getVar();
5959: }
5960:
5961: $offsetTypes = [];
5962: $offsetNativeTypes = [];
5963: foreach (array_reverse($dimFetchStack) as $dimFetch) {
5964: $dimExpr = $dimFetch->getDim();
5965: $offsetTypes[] = $scope->getType($dimExpr);
5966: $offsetNativeTypes[] = $scope->getNativeType($dimExpr);
5967: }
5968:
5969: $valueToWrite = $scope->getType($assignedExpr);
5970: $nativeValueToWrite = $scope->getNativeType($assignedExpr);
5971: $varType = $scope->getType($var);
5972: $varNativeType = $scope->getNativeType($var);
5973:
5974: $offsetValueType = $varType;
5975: $offsetNativeValueType = $varNativeType;
5976: $offsetValueTypeStack = [$offsetValueType];
5977: $offsetValueNativeTypeStack = [$offsetNativeValueType];
5978: foreach (array_slice($offsetTypes, 0, -1) as $offsetType) {
5979: $offsetValueType = $offsetValueType->getOffsetValueType($offsetType);
5980: $offsetValueTypeStack[] = $offsetValueType;
5981: }
5982: foreach (array_slice($offsetNativeTypes, 0, -1) as $offsetNativeType) {
5983: $offsetNativeValueType = $offsetNativeValueType->getOffsetValueType($offsetNativeType);
5984: $offsetValueNativeTypeStack[] = $offsetNativeValueType;
5985: }
5986:
5987: foreach (array_reverse($offsetTypes) as $offsetType) {
5988: /** @var Type $offsetValueType */
5989: $offsetValueType = array_pop($offsetValueTypeStack);
5990: $valueToWrite = $offsetValueType->setExistingOffsetValueType($offsetType, $valueToWrite);
5991: }
5992: foreach (array_reverse($offsetNativeTypes) as $offsetNativeType) {
5993: /** @var Type $offsetNativeValueType */
5994: $offsetNativeValueType = array_pop($offsetValueNativeTypeStack);
5995: $nativeValueToWrite = $offsetNativeValueType->setExistingOffsetValueType($offsetNativeType, $nativeValueToWrite);
5996: }
5997:
5998: if ($var instanceof Variable && is_string($var->name)) {
5999: $nodeCallback(new VariableAssignNode($var, $assignedPropertyExpr), $scope);
6000: $scope = $scope->assignVariable($var->name, $valueToWrite, $nativeValueToWrite, TrinaryLogic::createYes());
6001: } else {
6002: if ($var instanceof PropertyFetch || $var instanceof StaticPropertyFetch) {
6003: $nodeCallback(new PropertyAssignNode($var, $assignedPropertyExpr, $isAssignOp), $scope);
6004: }
6005: $scope = $scope->assignExpression(
6006: $var,
6007: $valueToWrite,
6008: $nativeValueToWrite,
6009: );
6010: }
6011: }
6012:
6013: return new ExpressionResult($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints);
6014: }
6015:
6016: /**
6017: * @param list<ArrayDimFetch> $dimFetchStack
6018: * @param list<Type|null> $offsetTypes
6019: */
6020: private function produceArrayDimFetchAssignValueToWrite(array $dimFetchStack, array $offsetTypes, Type $offsetValueType, Type $valueToWrite, Scope $scope): Type
6021: {
6022: $offsetValueTypeStack = [$offsetValueType];
6023: foreach (array_slice($offsetTypes, 0, -1) as $offsetType) {
6024: if ($offsetType === null) {
6025: $offsetValueType = new ConstantArrayType([], []);
6026:
6027: } else {
6028: $offsetValueType = $offsetValueType->getOffsetValueType($offsetType);
6029: if ($offsetValueType instanceof ErrorType) {
6030: $offsetValueType = new ConstantArrayType([], []);
6031: }
6032: }
6033:
6034: $offsetValueTypeStack[] = $offsetValueType;
6035: }
6036:
6037: foreach (array_reverse($offsetTypes) as $i => $offsetType) {
6038: /** @var Type $offsetValueType */
6039: $offsetValueType = array_pop($offsetValueTypeStack);
6040: if (
6041: !$offsetValueType instanceof MixedType
6042: && !$offsetValueType->isConstantArray()->yes()
6043: ) {
6044: $types = [
6045: new ArrayType(new MixedType(), new MixedType()),
6046: new ObjectType(ArrayAccess::class),
6047: new NullType(),
6048: ];
6049: if ($offsetType !== null && $offsetType->isInteger()->yes()) {
6050: $types[] = new StringType();
6051: }
6052: $offsetValueType = TypeCombinator::intersect($offsetValueType, TypeCombinator::union(...$types));
6053: }
6054:
6055: $arrayDimFetch = $dimFetchStack[$i] ?? null;
6056: if (
6057: $offsetType !== null
6058: && $arrayDimFetch !== null
6059: && $scope->hasExpressionType($arrayDimFetch)->yes()
6060: ) {
6061: $hasOffsetType = null;
6062: if ($offsetType instanceof ConstantStringType || $offsetType instanceof ConstantIntegerType) {
6063: $hasOffsetType = new HasOffsetValueType($offsetType, $valueToWrite);
6064: }
6065: $valueToWrite = $offsetValueType->setExistingOffsetValueType($offsetType, $valueToWrite);
6066:
6067: if ($hasOffsetType !== null) {
6068: $valueToWrite = TypeCombinator::intersect(
6069: $valueToWrite,
6070: $hasOffsetType,
6071: );
6072: } elseif ($valueToWrite->isArray()->yes()) {
6073: $valueToWrite = TypeCombinator::intersect(
6074: $valueToWrite,
6075: new NonEmptyArrayType(),
6076: );
6077: }
6078:
6079: } else {
6080: $valueToWrite = $offsetValueType->setOffsetValueType($offsetType, $valueToWrite, $i === 0);
6081: }
6082:
6083: if ($arrayDimFetch === null || !$offsetValueType->isList()->yes()) {
6084: continue;
6085: }
6086:
6087: if ($scope->hasExpressionType($arrayDimFetch)->yes()) { // keep list for $list[$index] assignments
6088: $valueToWrite = TypeCombinator::intersect($valueToWrite, new AccessoryArrayListType());
6089: } elseif ($arrayDimFetch->dim instanceof BinaryOp\Plus) {
6090: if ( // keep list for $list[$index + 1] assignments
6091: $arrayDimFetch->dim->right instanceof Variable
6092: && $arrayDimFetch->dim->left instanceof Node\Scalar\Int_
6093: && $arrayDimFetch->dim->left->value === 1
6094: && $scope->hasExpressionType(new ArrayDimFetch($arrayDimFetch->var, $arrayDimFetch->dim->right))->yes()
6095: ) {
6096: $valueToWrite = TypeCombinator::intersect($valueToWrite, new AccessoryArrayListType());
6097: } elseif ( // keep list for $list[1 + $index] assignments
6098: $arrayDimFetch->dim->left instanceof Variable
6099: && $arrayDimFetch->dim->right instanceof Node\Scalar\Int_
6100: && $arrayDimFetch->dim->right->value === 1
6101: && $scope->hasExpressionType(new ArrayDimFetch($arrayDimFetch->var, $arrayDimFetch->dim->left))->yes()
6102: ) {
6103: $valueToWrite = TypeCombinator::intersect($valueToWrite, new AccessoryArrayListType());
6104: }
6105: }
6106: }
6107:
6108: return $valueToWrite;
6109: }
6110:
6111: private function unwrapAssign(Expr $expr): Expr
6112: {
6113: if ($expr instanceof Assign) {
6114: return $this->unwrapAssign($expr->expr);
6115: }
6116:
6117: return $expr;
6118: }
6119:
6120: /**
6121: * @param array<string, ConditionalExpressionHolder[]> $conditionalExpressions
6122: * @return array<string, ConditionalExpressionHolder[]>
6123: */
6124: private function processSureTypesForConditionalExpressionsAfterAssign(Scope $scope, string $variableName, array $conditionalExpressions, SpecifiedTypes $specifiedTypes, Type $variableType): array
6125: {
6126: foreach ($specifiedTypes->getSureTypes() as $exprString => [$expr, $exprType]) {
6127: if (!$expr instanceof Variable) {
6128: continue;
6129: }
6130: if (!is_string($expr->name)) {
6131: continue;
6132: }
6133:
6134: if ($expr->name === $variableName) {
6135: continue;
6136: }
6137:
6138: if (!isset($conditionalExpressions[$exprString])) {
6139: $conditionalExpressions[$exprString] = [];
6140: }
6141:
6142: $holder = new ConditionalExpressionHolder([
6143: '$' . $variableName => ExpressionTypeHolder::createYes(new Variable($variableName), $variableType),
6144: ], ExpressionTypeHolder::createYes(
6145: $expr,
6146: TypeCombinator::intersect($scope->getType($expr), $exprType),
6147: ));
6148: $conditionalExpressions[$exprString][$holder->getKey()] = $holder;
6149: }
6150:
6151: return $conditionalExpressions;
6152: }
6153:
6154: /**
6155: * @param array<string, ConditionalExpressionHolder[]> $conditionalExpressions
6156: * @return array<string, ConditionalExpressionHolder[]>
6157: */
6158: private function processSureNotTypesForConditionalExpressionsAfterAssign(Scope $scope, string $variableName, array $conditionalExpressions, SpecifiedTypes $specifiedTypes, Type $variableType): array
6159: {
6160: foreach ($specifiedTypes->getSureNotTypes() as $exprString => [$expr, $exprType]) {
6161: if (!$expr instanceof Variable) {
6162: continue;
6163: }
6164: if (!is_string($expr->name)) {
6165: continue;
6166: }
6167:
6168: if ($expr->name === $variableName) {
6169: continue;
6170: }
6171:
6172: if (!isset($conditionalExpressions[$exprString])) {
6173: $conditionalExpressions[$exprString] = [];
6174: }
6175:
6176: $holder = new ConditionalExpressionHolder([
6177: '$' . $variableName => ExpressionTypeHolder::createYes(new Variable($variableName), $variableType),
6178: ], ExpressionTypeHolder::createYes(
6179: $expr,
6180: TypeCombinator::remove($scope->getType($expr), $exprType),
6181: ));
6182: $conditionalExpressions[$exprString][$holder->getKey()] = $holder;
6183: }
6184:
6185: return $conditionalExpressions;
6186: }
6187:
6188: /**
6189: * @param callable(Node $node, Scope $scope): void $nodeCallback
6190: */
6191: private function processStmtVarAnnotation(MutatingScope $scope, Node\Stmt $stmt, ?Expr $defaultExpr, callable $nodeCallback): MutatingScope
6192: {
6193: $function = $scope->getFunction();
6194: $variableLessTags = [];
6195:
6196: foreach ($stmt->getComments() as $comment) {
6197: if (!$comment instanceof Doc) {
6198: continue;
6199: }
6200:
6201: $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
6202: $scope->getFile(),
6203: $scope->isInClass() ? $scope->getClassReflection()->getName() : null,
6204: $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
6205: $function !== null ? $function->getName() : null,
6206: $comment->getText(),
6207: );
6208:
6209: $assignedVariable = null;
6210: if (
6211: $stmt instanceof Node\Stmt\Expression
6212: && ($stmt->expr instanceof Assign || $stmt->expr instanceof AssignRef)
6213: && $stmt->expr->var instanceof Variable
6214: && is_string($stmt->expr->var->name)
6215: ) {
6216: $assignedVariable = $stmt->expr->var->name;
6217: }
6218:
6219: foreach ($resolvedPhpDoc->getVarTags() as $name => $varTag) {
6220: if (is_int($name)) {
6221: $variableLessTags[] = $varTag;
6222: continue;
6223: }
6224:
6225: if ($name === $assignedVariable) {
6226: continue;
6227: }
6228:
6229: $certainty = $scope->hasVariableType($name);
6230: if ($certainty->no()) {
6231: continue;
6232: }
6233:
6234: if ($scope->isInClass() && $scope->getFunction() === null) {
6235: continue;
6236: }
6237:
6238: if ($scope->canAnyVariableExist()) {
6239: $certainty = TrinaryLogic::createYes();
6240: }
6241:
6242: $variableNode = new Variable($name, $stmt->getAttributes());
6243: $originalType = $scope->getVariableType($name);
6244: if (!$originalType->equals($varTag->getType())) {
6245: $nodeCallback(new VarTagChangedExpressionTypeNode($varTag, $variableNode), $scope);
6246: }
6247:
6248: $scope = $scope->assignVariable(
6249: $name,
6250: $varTag->getType(),
6251: $scope->getNativeType($variableNode),
6252: $certainty,
6253: );
6254: }
6255: }
6256:
6257: if (count($variableLessTags) === 1 && $defaultExpr !== null) {
6258: $originalType = $scope->getType($defaultExpr);
6259: $varTag = $variableLessTags[0];
6260: if (!$originalType->equals($varTag->getType())) {
6261: $nodeCallback(new VarTagChangedExpressionTypeNode($varTag, $defaultExpr), $scope);
6262: }
6263: $scope = $scope->assignExpression($defaultExpr, $varTag->getType(), new MixedType());
6264: }
6265:
6266: return $scope;
6267: }
6268:
6269: /**
6270: * @param array<int, string> $variableNames
6271: */
6272: private function processVarAnnotation(MutatingScope $scope, array $variableNames, Node\Stmt $node, bool &$changed = false): MutatingScope
6273: {
6274: $function = $scope->getFunction();
6275: $varTags = [];
6276: foreach ($node->getComments() as $comment) {
6277: if (!$comment instanceof Doc) {
6278: continue;
6279: }
6280:
6281: $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
6282: $scope->getFile(),
6283: $scope->isInClass() ? $scope->getClassReflection()->getName() : null,
6284: $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
6285: $function !== null ? $function->getName() : null,
6286: $comment->getText(),
6287: );
6288: foreach ($resolvedPhpDoc->getVarTags() as $key => $varTag) {
6289: $varTags[$key] = $varTag;
6290: }
6291: }
6292:
6293: if (count($varTags) === 0) {
6294: return $scope;
6295: }
6296:
6297: foreach ($variableNames as $variableName) {
6298: if (!isset($varTags[$variableName])) {
6299: continue;
6300: }
6301:
6302: $variableType = $varTags[$variableName]->getType();
6303: $changed = true;
6304: $scope = $scope->assignVariable($variableName, $variableType, new MixedType(), TrinaryLogic::createYes());
6305: }
6306:
6307: if (count($variableNames) === 1 && count($varTags) === 1 && isset($varTags[0])) {
6308: $variableType = $varTags[0]->getType();
6309: $changed = true;
6310: $scope = $scope->assignVariable($variableNames[0], $variableType, new MixedType(), TrinaryLogic::createYes());
6311: }
6312:
6313: return $scope;
6314: }
6315:
6316: private function enterForeach(MutatingScope $scope, MutatingScope $originalScope, Foreach_ $stmt): MutatingScope
6317: {
6318: if ($stmt->expr instanceof Variable && is_string($stmt->expr->name)) {
6319: $scope = $this->processVarAnnotation($scope, [$stmt->expr->name], $stmt);
6320: }
6321: $iterateeType = $originalScope->getType($stmt->expr);
6322: if (
6323: ($stmt->valueVar instanceof Variable && is_string($stmt->valueVar->name))
6324: && ($stmt->keyVar === null || ($stmt->keyVar instanceof Variable && is_string($stmt->keyVar->name)))
6325: ) {
6326: $keyVarName = null;
6327: if ($stmt->keyVar instanceof Variable && is_string($stmt->keyVar->name)) {
6328: $keyVarName = $stmt->keyVar->name;
6329: }
6330: $scope = $scope->enterForeach(
6331: $originalScope,
6332: $stmt->expr,
6333: $stmt->valueVar->name,
6334: $keyVarName,
6335: );
6336: $vars = [$stmt->valueVar->name];
6337: if ($keyVarName !== null) {
6338: $vars[] = $keyVarName;
6339: }
6340: } else {
6341: $scope = $this->processAssignVar(
6342: $scope,
6343: $stmt,
6344: $stmt->valueVar,
6345: new GetIterableValueTypeExpr($stmt->expr),
6346: static function (): void {
6347: },
6348: ExpressionContext::createDeep(),
6349: static fn (MutatingScope $scope): ExpressionResult => new ExpressionResult($scope, false, false, [], []),
6350: true,
6351: )->getScope();
6352: $vars = $this->getAssignedVariables($stmt->valueVar);
6353: if (
6354: $stmt->keyVar instanceof Variable && is_string($stmt->keyVar->name)
6355: ) {
6356: $scope = $scope->enterForeachKey($originalScope, $stmt->expr, $stmt->keyVar->name);
6357: $vars[] = $stmt->keyVar->name;
6358: } elseif ($stmt->keyVar !== null) {
6359: $scope = $this->processAssignVar(
6360: $scope,
6361: $stmt,
6362: $stmt->keyVar,
6363: new GetIterableKeyTypeExpr($stmt->expr),
6364: static function (): void {
6365: },
6366: ExpressionContext::createDeep(),
6367: static fn (MutatingScope $scope): ExpressionResult => new ExpressionResult($scope, false, false, [], []),
6368: true,
6369: )->getScope();
6370: $vars = array_merge($vars, $this->getAssignedVariables($stmt->keyVar));
6371: }
6372: }
6373:
6374: $constantArrays = $iterateeType->getConstantArrays();
6375: if (
6376: $stmt->getDocComment() === null
6377: && $iterateeType->isConstantArray()->yes()
6378: && count($constantArrays) === 1
6379: && $stmt->valueVar instanceof Variable && is_string($stmt->valueVar->name)
6380: && $stmt->keyVar instanceof Variable && is_string($stmt->keyVar->name)
6381: ) {
6382: $valueConditionalHolders = [];
6383: $arrayDimFetchConditionalHolders = [];
6384: foreach ($constantArrays[0]->getKeyTypes() as $i => $keyType) {
6385: $valueType = $constantArrays[0]->getValueTypes()[$i];
6386: $holder = new ConditionalExpressionHolder([
6387: '$' . $stmt->keyVar->name => ExpressionTypeHolder::createYes(new Variable($stmt->keyVar->name), $keyType),
6388: ], new ExpressionTypeHolder($stmt->valueVar, $valueType, TrinaryLogic::createYes()));
6389: $valueConditionalHolders[$holder->getKey()] = $holder;
6390: $arrayDimFetchHolder = new ConditionalExpressionHolder([
6391: '$' . $stmt->keyVar->name => ExpressionTypeHolder::createYes(new Variable($stmt->keyVar->name), $keyType),
6392: ], new ExpressionTypeHolder(new ArrayDimFetch($stmt->expr, $stmt->keyVar), $valueType, TrinaryLogic::createYes()));
6393: $arrayDimFetchConditionalHolders[$arrayDimFetchHolder->getKey()] = $arrayDimFetchHolder;
6394: }
6395:
6396: $scope = $scope->addConditionalExpressions(
6397: '$' . $stmt->valueVar->name,
6398: $valueConditionalHolders,
6399: );
6400: if ($stmt->expr instanceof Variable && is_string($stmt->expr->name)) {
6401: $scope = $scope->addConditionalExpressions(
6402: sprintf('$%s[$%s]', $stmt->expr->name, $stmt->keyVar->name),
6403: $arrayDimFetchConditionalHolders,
6404: );
6405: }
6406: }
6407:
6408: return $this->processVarAnnotation($scope, $vars, $stmt);
6409: }
6410:
6411: /**
6412: * @param callable(Node $node, Scope $scope): void $nodeCallback
6413: */
6414: private function processTraitUse(Node\Stmt\TraitUse $node, MutatingScope $classScope, callable $nodeCallback): void
6415: {
6416: $parentTraitNames = [];
6417: $parent = $classScope->getParentScope();
6418: while ($parent !== null) {
6419: if ($parent->isInTrait()) {
6420: $parentTraitNames[] = $parent->getTraitReflection()->getName();
6421: }
6422: $parent = $parent->getParentScope();
6423: }
6424:
6425: foreach ($node->traits as $trait) {
6426: $traitName = (string) $trait;
6427: if (in_array($traitName, $parentTraitNames, true)) {
6428: continue;
6429: }
6430: if (!$this->reflectionProvider->hasClass($traitName)) {
6431: continue;
6432: }
6433: $traitReflection = $this->reflectionProvider->getClass($traitName);
6434: $traitFileName = $traitReflection->getFileName();
6435: if ($traitFileName === null) {
6436: continue; // trait from eval or from PHP itself
6437: }
6438: $fileName = $this->fileHelper->normalizePath($traitFileName);
6439: if (!isset($this->analysedFiles[$fileName])) {
6440: continue;
6441: }
6442: $adaptations = [];
6443: foreach ($node->adaptations as $adaptation) {
6444: if ($adaptation->trait === null) {
6445: $adaptations[] = $adaptation;
6446: continue;
6447: }
6448: if ($adaptation->trait->toLowerString() !== $trait->toLowerString()) {
6449: continue;
6450: }
6451:
6452: $adaptations[] = $adaptation;
6453: }
6454: $parserNodes = $this->parser->parseFile($fileName);
6455: $this->processNodesForTraitUse($parserNodes, $traitReflection, $classScope, $adaptations, $nodeCallback);
6456: }
6457: }
6458:
6459: /**
6460: * @param Node[]|Node|scalar|null $node
6461: * @param Node\Stmt\TraitUseAdaptation[] $adaptations
6462: * @param callable(Node $node, Scope $scope): void $nodeCallback
6463: */
6464: private function processNodesForTraitUse($node, ClassReflection $traitReflection, MutatingScope $scope, array $adaptations, callable $nodeCallback): void
6465: {
6466: if ($node instanceof Node) {
6467: if ($node instanceof Node\Stmt\Trait_ && $traitReflection->getName() === (string) $node->namespacedName && $traitReflection->getNativeReflection()->getStartLine() === $node->getStartLine()) {
6468: $methodModifiers = [];
6469: $methodNames = [];
6470: foreach ($adaptations as $adaptation) {
6471: if (!$adaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
6472: continue;
6473: }
6474:
6475: $methodName = $adaptation->method->toLowerString();
6476: if ($adaptation->newModifier !== null) {
6477: $methodModifiers[$methodName] = $adaptation->newModifier;
6478: }
6479:
6480: if ($adaptation->newName === null) {
6481: continue;
6482: }
6483:
6484: $methodNames[$methodName] = $adaptation->newName;
6485: }
6486:
6487: $stmts = $node->stmts;
6488: foreach ($stmts as $i => $stmt) {
6489: if (!$stmt instanceof Node\Stmt\ClassMethod) {
6490: continue;
6491: }
6492: $methodName = $stmt->name->toLowerString();
6493: $methodAst = clone $stmt;
6494: $stmts[$i] = $methodAst;
6495: if (array_key_exists($methodName, $methodModifiers)) {
6496: $methodAst->flags = ($methodAst->flags & ~ Modifiers::VISIBILITY_MASK) | $methodModifiers[$methodName];
6497: }
6498:
6499: if (!array_key_exists($methodName, $methodNames)) {
6500: continue;
6501: }
6502:
6503: $methodAst->setAttribute('originalTraitMethodName', $methodAst->name->toLowerString());
6504: $methodAst->name = $methodNames[$methodName];
6505: }
6506:
6507: if (!$scope->isInClass()) {
6508: throw new ShouldNotHappenException();
6509: }
6510: $traitScope = $scope->enterTrait($traitReflection);
6511: $nodeCallback(new InTraitNode($node, $traitReflection, $scope->getClassReflection()), $traitScope);
6512: $this->processStmtNodes($node, $stmts, $traitScope, $nodeCallback, StatementContext::createTopLevel());
6513: return;
6514: }
6515: if ($node instanceof Node\Stmt\ClassLike) {
6516: return;
6517: }
6518: if ($node instanceof Node\FunctionLike) {
6519: return;
6520: }
6521: foreach ($node->getSubNodeNames() as $subNodeName) {
6522: $subNode = $node->{$subNodeName};
6523: $this->processNodesForTraitUse($subNode, $traitReflection, $scope, $adaptations, $nodeCallback);
6524: }
6525: } elseif (is_array($node)) {
6526: foreach ($node as $subNode) {
6527: $this->processNodesForTraitUse($subNode, $traitReflection, $scope, $adaptations, $nodeCallback);
6528: }
6529: }
6530: }
6531:
6532: private function processCalledMethod(MethodReflection $methodReflection): ?MutatingScope
6533: {
6534: $declaringClass = $methodReflection->getDeclaringClass();
6535: if ($declaringClass->isAnonymous()) {
6536: return null;
6537: }
6538: if ($declaringClass->getFileName() === null) {
6539: return null;
6540: }
6541:
6542: $stackName = sprintf('%s::%s', $declaringClass->getName(), $methodReflection->getName());
6543: if (array_key_exists($stackName, $this->calledMethodResults)) {
6544: return $this->calledMethodResults[$stackName];
6545: }
6546:
6547: if (array_key_exists($stackName, $this->calledMethodStack)) {
6548: return null;
6549: }
6550:
6551: if (count($this->calledMethodStack) > 0) {
6552: return null;
6553: }
6554:
6555: $this->calledMethodStack[$stackName] = true;
6556:
6557: $fileName = $this->fileHelper->normalizePath($declaringClass->getFileName());
6558: if (!isset($this->analysedFiles[$fileName])) {
6559: return null;
6560: }
6561: $parserNodes = $this->parser->parseFile($fileName);
6562:
6563: $returnStatement = null;
6564: $this->processNodesForCalledMethod($parserNodes, $fileName, $methodReflection, static function (Node $node, Scope $scope) use ($methodReflection, &$returnStatement): void {
6565: if (!$node instanceof MethodReturnStatementsNode) {
6566: return;
6567: }
6568:
6569: if ($node->getClassReflection()->getName() !== $methodReflection->getDeclaringClass()->getName()) {
6570: return;
6571: }
6572:
6573: if ($returnStatement !== null) {
6574: return;
6575: }
6576:
6577: $returnStatement = $node;
6578: });
6579:
6580: $calledMethodEndScope = null;
6581: if ($returnStatement !== null) {
6582: foreach ($returnStatement->getExecutionEnds() as $executionEnd) {
6583: $statementResult = $executionEnd->getStatementResult();
6584: $endNode = $executionEnd->getNode();
6585: if ($endNode instanceof Node\Stmt\Expression) {
6586: $exprType = $statementResult->getScope()->getType($endNode->expr);
6587: if ($exprType instanceof NeverType && $exprType->isExplicit()) {
6588: continue;
6589: }
6590: }
6591: if ($calledMethodEndScope === null) {
6592: $calledMethodEndScope = $statementResult->getScope();
6593: continue;
6594: }
6595:
6596: $calledMethodEndScope = $calledMethodEndScope->mergeWith($statementResult->getScope());
6597: }
6598: foreach ($returnStatement->getReturnStatements() as $statement) {
6599: if ($calledMethodEndScope === null) {
6600: $calledMethodEndScope = $statement->getScope();
6601: continue;
6602: }
6603:
6604: $calledMethodEndScope = $calledMethodEndScope->mergeWith($statement->getScope());
6605: }
6606: }
6607:
6608: unset($this->calledMethodStack[$stackName]);
6609:
6610: $this->calledMethodResults[$stackName] = $calledMethodEndScope;
6611:
6612: return $calledMethodEndScope;
6613: }
6614:
6615: /**
6616: * @param Node[]|Node|scalar|null $node
6617: * @param callable(Node $node, Scope $scope): void $nodeCallback
6618: */
6619: private function processNodesForCalledMethod($node, string $fileName, MethodReflection $methodReflection, callable $nodeCallback): void
6620: {
6621: if ($node instanceof Node) {
6622: $declaringClass = $methodReflection->getDeclaringClass();
6623: if (
6624: $node instanceof Node\Stmt\Class_
6625: && isset($node->namespacedName)
6626: && $declaringClass->getName() === (string) $node->namespacedName
6627: && $declaringClass->getNativeReflection()->getStartLine() === $node->getStartLine()
6628: ) {
6629:
6630: $stmts = $node->stmts;
6631: foreach ($stmts as $stmt) {
6632: if (!$stmt instanceof Node\Stmt\ClassMethod) {
6633: continue;
6634: }
6635:
6636: if ($stmt->name->toString() !== $methodReflection->getName()) {
6637: continue;
6638: }
6639:
6640: if ($stmt->getEndLine() - $stmt->getStartLine() > 50) {
6641: continue;
6642: }
6643:
6644: $scope = $this->scopeFactory->create(ScopeContext::create($fileName))->enterClass($declaringClass);
6645: $this->processStmtNode($stmt, $scope, $nodeCallback, StatementContext::createTopLevel());
6646: }
6647: return;
6648: }
6649: if ($node instanceof Node\Stmt\ClassLike) {
6650: return;
6651: }
6652: if ($node instanceof Node\FunctionLike) {
6653: return;
6654: }
6655: foreach ($node->getSubNodeNames() as $subNodeName) {
6656: $subNode = $node->{$subNodeName};
6657: $this->processNodesForCalledMethod($subNode, $fileName, $methodReflection, $nodeCallback);
6658: }
6659: } elseif (is_array($node)) {
6660: foreach ($node as $subNode) {
6661: $this->processNodesForCalledMethod($subNode, $fileName, $methodReflection, $nodeCallback);
6662: }
6663: }
6664: }
6665:
6666: /**
6667: * @return array{TemplateTypeMap, array<string, Type>, array<string, bool>, array<string, Type>, ?Type, ?Type, ?string, bool, bool, bool, bool|null, bool, bool, string|null, Assertions, ?Type, array<string, Type>, array<(string|int), VarTag>, bool}
6668: */
6669: public function getPhpDocs(Scope $scope, Node\FunctionLike|Node\Stmt\Property $node): array
6670: {
6671: $templateTypeMap = TemplateTypeMap::createEmpty();
6672: $phpDocParameterTypes = [];
6673: $phpDocImmediatelyInvokedCallableParameters = [];
6674: $phpDocClosureThisTypeParameters = [];
6675: $phpDocReturnType = null;
6676: $phpDocThrowType = null;
6677: $deprecatedDescription = null;
6678: $isDeprecated = false;
6679: $isInternal = false;
6680: $isFinal = false;
6681: $isPure = null;
6682: $isAllowedPrivateMutation = false;
6683: $acceptsNamedArguments = true;
6684: $isReadOnly = $scope->isInClass() && $scope->getClassReflection()->isImmutable();
6685: $asserts = Assertions::createEmpty();
6686: $selfOutType = null;
6687: $docComment = $node->getDocComment() !== null
6688: ? $node->getDocComment()->getText()
6689: : null;
6690:
6691: $file = $scope->getFile();
6692: $class = $scope->isInClass() ? $scope->getClassReflection()->getName() : null;
6693: $trait = $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null;
6694: $resolvedPhpDoc = null;
6695: $functionName = null;
6696: $phpDocParameterOutTypes = [];
6697:
6698: if ($node instanceof Node\Stmt\ClassMethod) {
6699: if (!$scope->isInClass()) {
6700: throw new ShouldNotHappenException();
6701: }
6702: $functionName = $node->name->name;
6703: $positionalParameterNames = array_map(static function (Node\Param $param): string {
6704: if (!$param->var instanceof Variable || !is_string($param->var->name)) {
6705: throw new ShouldNotHappenException();
6706: }
6707:
6708: return $param->var->name;
6709: }, $node->getParams());
6710: $resolvedPhpDoc = $this->phpDocInheritanceResolver->resolvePhpDocForMethod(
6711: $docComment,
6712: $file,
6713: $scope->getClassReflection(),
6714: $trait,
6715: $node->name->name,
6716: $positionalParameterNames,
6717: );
6718:
6719: if ($node->name->toLowerString() === '__construct') {
6720: foreach ($node->params as $param) {
6721: if ($param->flags === 0) {
6722: continue;
6723: }
6724:
6725: if ($param->getDocComment() === null) {
6726: continue;
6727: }
6728:
6729: if (
6730: !$param->var instanceof Variable
6731: || !is_string($param->var->name)
6732: ) {
6733: throw new ShouldNotHappenException();
6734: }
6735:
6736: $paramPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
6737: $file,
6738: $class,
6739: $trait,
6740: '__construct',
6741: $param->getDocComment()->getText(),
6742: );
6743: $varTags = $paramPhpDoc->getVarTags();
6744: if (isset($varTags[0]) && count($varTags) === 1) {
6745: $phpDocType = $varTags[0]->getType();
6746: } elseif (isset($varTags[$param->var->name])) {
6747: $phpDocType = $varTags[$param->var->name]->getType();
6748: } else {
6749: continue;
6750: }
6751:
6752: $phpDocParameterTypes[$param->var->name] = $phpDocType;
6753: }
6754: }
6755: } elseif ($node instanceof Node\Stmt\Function_) {
6756: $functionName = trim($scope->getNamespace() . '\\' . $node->name->name, '\\');
6757: } elseif ($node instanceof Node\PropertyHook) {
6758: $propertyName = $node->getAttribute('propertyName');
6759: if ($propertyName !== null) {
6760: $functionName = sprintf('$%s::%s', $propertyName, $node->name->toString());
6761: }
6762: }
6763:
6764: if ($docComment !== null && $resolvedPhpDoc === null) {
6765: $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
6766: $file,
6767: $class,
6768: $trait,
6769: $functionName,
6770: $docComment,
6771: );
6772: }
6773:
6774: $varTags = [];
6775: if ($resolvedPhpDoc !== null) {
6776: $templateTypeMap = $resolvedPhpDoc->getTemplateTypeMap();
6777: $phpDocImmediatelyInvokedCallableParameters = $resolvedPhpDoc->getParamsImmediatelyInvokedCallable();
6778: foreach ($resolvedPhpDoc->getParamTags() as $paramName => $paramTag) {
6779: if (array_key_exists($paramName, $phpDocParameterTypes)) {
6780: continue;
6781: }
6782: $paramType = $paramTag->getType();
6783: if ($scope->isInClass()) {
6784: $paramType = $this->transformStaticType($scope->getClassReflection(), $paramType);
6785: }
6786: $phpDocParameterTypes[$paramName] = $paramType;
6787: }
6788: foreach ($resolvedPhpDoc->getParamClosureThisTags() as $paramName => $paramClosureThisTag) {
6789: if (array_key_exists($paramName, $phpDocClosureThisTypeParameters)) {
6790: continue;
6791: }
6792: $paramClosureThisType = $paramClosureThisTag->getType();
6793: if ($scope->isInClass()) {
6794: $paramClosureThisType = $this->transformStaticType($scope->getClassReflection(), $paramClosureThisType);
6795: }
6796: $phpDocClosureThisTypeParameters[$paramName] = $paramClosureThisType;
6797: }
6798:
6799: foreach ($resolvedPhpDoc->getParamOutTags() as $paramName => $paramOutTag) {
6800: $phpDocParameterOutTypes[$paramName] = $paramOutTag->getType();
6801: }
6802: if ($node instanceof Node\FunctionLike) {
6803: $nativeReturnType = $scope->getFunctionType($node->getReturnType(), false, false);
6804: $phpDocReturnType = $this->getPhpDocReturnType($resolvedPhpDoc, $nativeReturnType);
6805: if ($phpDocReturnType !== null && $scope->isInClass()) {
6806: $phpDocReturnType = $this->transformStaticType($scope->getClassReflection(), $phpDocReturnType);
6807: }
6808: }
6809: $phpDocThrowType = $resolvedPhpDoc->getThrowsTag() !== null ? $resolvedPhpDoc->getThrowsTag()->getType() : null;
6810: $deprecatedDescription = $resolvedPhpDoc->getDeprecatedTag() !== null ? $resolvedPhpDoc->getDeprecatedTag()->getMessage() : null;
6811: $isDeprecated = $resolvedPhpDoc->isDeprecated();
6812: $isInternal = $resolvedPhpDoc->isInternal();
6813: $isFinal = $resolvedPhpDoc->isFinal();
6814: $isPure = $resolvedPhpDoc->isPure();
6815: $isAllowedPrivateMutation = $resolvedPhpDoc->isAllowedPrivateMutation();
6816: $acceptsNamedArguments = $resolvedPhpDoc->acceptsNamedArguments();
6817: if ($acceptsNamedArguments && $scope->isInClass()) {
6818: $acceptsNamedArguments = $scope->getClassReflection()->acceptsNamedArguments();
6819: }
6820: $isReadOnly = $isReadOnly || $resolvedPhpDoc->isReadOnly();
6821: $asserts = Assertions::createFromResolvedPhpDocBlock($resolvedPhpDoc);
6822: $selfOutType = $resolvedPhpDoc->getSelfOutTag() !== null ? $resolvedPhpDoc->getSelfOutTag()->getType() : null;
6823: $varTags = $resolvedPhpDoc->getVarTags();
6824: }
6825:
6826: return [$templateTypeMap, $phpDocParameterTypes, $phpDocImmediatelyInvokedCallableParameters, $phpDocClosureThisTypeParameters, $phpDocReturnType, $phpDocThrowType, $deprecatedDescription, $isDeprecated, $isInternal, $isFinal, $isPure, $acceptsNamedArguments, $isReadOnly, $docComment, $asserts, $selfOutType, $phpDocParameterOutTypes, $varTags, $isAllowedPrivateMutation];
6827: }
6828:
6829: private function transformStaticType(ClassReflection $declaringClass, Type $type): Type
6830: {
6831: return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($declaringClass): Type {
6832: if ($type instanceof StaticType) {
6833: $changedType = $type->changeBaseClass($declaringClass);
6834: if ($declaringClass->isFinal() && !$type instanceof ThisType) {
6835: $changedType = $changedType->getStaticObjectType();
6836: }
6837: return $traverse($changedType);
6838: }
6839:
6840: return $traverse($type);
6841: });
6842: }
6843:
6844: private function getPhpDocReturnType(ResolvedPhpDocBlock $resolvedPhpDoc, Type $nativeReturnType): ?Type
6845: {
6846: $returnTag = $resolvedPhpDoc->getReturnTag();
6847:
6848: if ($returnTag === null) {
6849: return null;
6850: }
6851:
6852: $phpDocReturnType = $returnTag->getType();
6853:
6854: if ($returnTag->isExplicit()) {
6855: return $phpDocReturnType;
6856: }
6857:
6858: if ($nativeReturnType->isSuperTypeOf(TemplateTypeHelper::resolveToBounds($phpDocReturnType))->yes()) {
6859: return $phpDocReturnType;
6860: }
6861:
6862: return null;
6863: }
6864:
6865: /**
6866: * @param array<Node> $nodes
6867: * @return list<Node\Stmt>
6868: */
6869: private function getNextUnreachableStatements(array $nodes, bool $earlyBinding): array
6870: {
6871: $stmts = [];
6872: $isPassedUnreachableStatement = false;
6873: foreach ($nodes as $node) {
6874: if ($earlyBinding && ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\HaltCompiler)) {
6875: continue;
6876: }
6877: if ($isPassedUnreachableStatement && $node instanceof Node\Stmt) {
6878: $stmts[] = $node;
6879: continue;
6880: }
6881: if ($node instanceof Node\Stmt\Nop || $node instanceof Node\Stmt\InlineHTML) {
6882: continue;
6883: }
6884: if (!$node instanceof Node\Stmt) {
6885: continue;
6886: }
6887: $stmts[] = $node;
6888: $isPassedUnreachableStatement = true;
6889: }
6890: return $stmts;
6891: }
6892:
6893: /**
6894: * @param array<Expr> $conditions
6895: */
6896: public function getFilteringExprForMatchArm(Expr\Match_ $expr, array $conditions): BinaryOp\Identical|FuncCall
6897: {
6898: if (count($conditions) === 1) {
6899: return new BinaryOp\Identical($expr->cond, $conditions[0]);
6900: }
6901:
6902: $items = [];
6903: foreach ($conditions as $filteringExpr) {
6904: $items[] = new Node\ArrayItem($filteringExpr);
6905: }
6906:
6907: return new FuncCall(
6908: new Name\FullyQualified('in_array'),
6909: [
6910: new Arg($expr->cond),
6911: new Arg(new Array_($items)),
6912: new Arg(new ConstFetch(new Name\FullyQualified('true'))),
6913: ],
6914: );
6915: }
6916:
6917: }
6918: