1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use PhpParser\Node as PhpParserNode;
6: use PhpParser\Node\Arg;
7: use PhpParser\Node\Expr\Array_;
8: use PhpParser\Node\Expr\FuncCall;
9: use PhpParser\Node\Expr\MethodCall;
10: use PhpParser\Node\Expr\New_;
11: use PhpParser\Node\Expr\StaticCall;
12: use PhpParser\Node\Identifier;
13: use PhpParser\Node\Scalar\Int_;
14: use PhpParser\Node\Scalar\String_;
15: use PHPStan\Node\Expr\TypeExpr;
16: use PHPStan\Node\Printer\ExprPrinter;
17: use PHPStan\Reflection\ParametersAcceptor;
18: use PHPStan\Reflection\ParametersAcceptorSelector;
19: use PHPStan\TrinaryLogic;
20: use PHPStan\Turbo\ShadowedByTurboExtension;
21: use PHPStan\Type\Constant\ConstantArrayType;
22: use function array_is_list;
23: use function array_key_exists;
24: use function array_keys;
25: use function array_values;
26: use function count;
27: use function is_string;
28: use function key;
29: use function ksort;
30: use function max;
31:
32: /**
33: * @api
34: */
35: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ArgumentsNormalizer.cpp')]
36: final class ArgumentsNormalizer
37: {
38:
39: public const ORIGINAL_ARG_ATTRIBUTE = 'originalArg';
40:
41: /**
42: * @return array{ParametersAcceptor, FuncCall, TrinaryLogic}|null
43: */
44: public static function reorderCallUserFuncArguments(
45: FuncCall $callUserFuncCall,
46: Scope $scope,
47: ): ?array
48: {
49: $args = $callUserFuncCall->getArgs();
50: if (count($args) < 1) {
51: return null;
52: }
53:
54: $passThruArgs = [];
55: $callbackArg = null;
56: foreach ($args as $i => $arg) {
57: if ($callbackArg === null) {
58: if ($arg->name === null && $i === 0) {
59: $callbackArg = $arg;
60: continue;
61: }
62: if ($arg->name !== null && $arg->name->toString() === 'callback') {
63: $callbackArg = $arg;
64: continue;
65: }
66: }
67:
68: $passThruArgs[] = $arg;
69: }
70:
71: if ($callbackArg === null) {
72: return null;
73: }
74:
75: $calledOnType = $scope->getType($callbackArg->value);
76: if (!$calledOnType->isCallable()->yes()) {
77: return null;
78: }
79:
80: $callableParametersAcceptors = $calledOnType->getCallableParametersAcceptors($scope);
81: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
82: $scope,
83: $passThruArgs,
84: $callableParametersAcceptors,
85: null,
86: );
87:
88: $acceptsNamedArguments = TrinaryLogic::createYes();
89: foreach ($callableParametersAcceptors as $callableParametersAcceptor) {
90: $acceptsNamedArguments = $acceptsNamedArguments->and($callableParametersAcceptor->acceptsNamedArguments());
91: }
92:
93: return [$parametersAcceptor, new FuncCall(
94: $callbackArg->value,
95: $passThruArgs,
96: self::attributesWithoutPrintedForm($callUserFuncCall),
97: ), $acceptsNamedArguments];
98: }
99:
100: /**
101: * @return array{ParametersAcceptor, FuncCall, TrinaryLogic}|null
102: */
103: public static function reorderCallUserFuncArrayArguments(
104: FuncCall $callUserFuncArrayCall,
105: Scope $scope,
106: ): ?array
107: {
108: $args = $callUserFuncArrayCall->getArgs();
109: if (count($args) < 2) {
110: return null;
111: }
112:
113: $callbackArg = null;
114: $argsArrayArg = null;
115: foreach ($args as $i => $arg) {
116: if ($callbackArg === null) {
117: if ($arg->name === null && $i === 0) {
118: $callbackArg = $arg;
119: continue;
120: }
121: if ($arg->name !== null && $arg->name->toString() === 'callback') {
122: $callbackArg = $arg;
123: continue;
124: }
125: }
126:
127: if ($argsArrayArg !== null) {
128: continue;
129: }
130: if ($arg->name === null && $i === 1) {
131: $argsArrayArg = $arg;
132: continue;
133: }
134: if ($arg->name === null || $arg->name->toString() !== 'args') {
135: continue;
136: }
137: $argsArrayArg = $arg;
138: }
139:
140: if ($callbackArg === null || $argsArrayArg === null) {
141: return null;
142: }
143:
144: if (!$argsArrayArg->value instanceof Array_) {
145: return null;
146: }
147:
148: $passThruArgs = [];
149: foreach ($argsArrayArg->value->items as $item) {
150: $key = null;
151: if ($item->key instanceof String_) {
152: /** @var int|string $key */
153: $key = key([$item->key->value => null]);
154: if ($key === '') {
155: return null;
156: }
157: } elseif ($item->key !== null && !$item->key instanceof Int_) {
158: // Dynamic key, we cannot be sure.
159: return null;
160: }
161:
162: $passThruArgs[] = new Arg(
163: $item->value,
164: $item->byRef,
165: $item->unpack,
166: self::attributesWithoutPrintedForm($item),
167: is_string($key) ? new Identifier($key) : null,
168: );
169: }
170:
171: $calledOnType = $scope->getType($callbackArg->value);
172: if (!$calledOnType->isCallable()->yes()) {
173: return null;
174: }
175:
176: $callableParametersAcceptors = $calledOnType->getCallableParametersAcceptors($scope);
177: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
178: $scope,
179: $passThruArgs,
180: $callableParametersAcceptors,
181: null,
182: );
183:
184: $acceptsNamedArguments = TrinaryLogic::createYes();
185: foreach ($callableParametersAcceptors as $callableParametersAcceptor) {
186: $acceptsNamedArguments = $acceptsNamedArguments->and($callableParametersAcceptor->acceptsNamedArguments());
187: }
188:
189: return [$parametersAcceptor, new FuncCall(
190: $callbackArg->value,
191: $passThruArgs,
192: self::attributesWithoutPrintedForm($callUserFuncArrayCall),
193: ), $acceptsNamedArguments];
194: }
195:
196: public static function reorderFuncArguments(
197: ParametersAcceptor $parametersAcceptor,
198: FuncCall $functionCall,
199: ): ?FuncCall
200: {
201: $args = $functionCall->getArgs();
202: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
203:
204: if ($reorderedArgs === null) {
205: return null;
206: }
207:
208: // return identical object if not reordered, as TypeSpecifier relies on object identity
209: if ($reorderedArgs === $args) {
210: return $functionCall;
211: }
212:
213: return new FuncCall(
214: $functionCall->name,
215: $reorderedArgs,
216: self::attributesWithoutPrintedForm($functionCall),
217: );
218: }
219:
220: public static function reorderMethodArguments(
221: ParametersAcceptor $parametersAcceptor,
222: MethodCall $methodCall,
223: ): ?MethodCall
224: {
225: $args = $methodCall->getArgs();
226: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
227:
228: if ($reorderedArgs === null) {
229: return null;
230: }
231:
232: // return identical object if not reordered, as TypeSpecifier relies on object identity
233: if ($reorderedArgs === $args) {
234: return $methodCall;
235: }
236:
237: return new MethodCall(
238: $methodCall->var,
239: $methodCall->name,
240: $reorderedArgs,
241: self::attributesWithoutPrintedForm($methodCall),
242: );
243: }
244:
245: public static function reorderStaticCallArguments(
246: ParametersAcceptor $parametersAcceptor,
247: StaticCall $staticCall,
248: ): ?StaticCall
249: {
250: $args = $staticCall->getArgs();
251: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
252:
253: if ($reorderedArgs === null) {
254: return null;
255: }
256:
257: // return identical object if not reordered, as TypeSpecifier relies on object identity
258: if ($reorderedArgs === $args) {
259: return $staticCall;
260: }
261:
262: return new StaticCall(
263: $staticCall->class,
264: $staticCall->name,
265: $reorderedArgs,
266: self::attributesWithoutPrintedForm($staticCall),
267: );
268: }
269:
270: public static function reorderNewArguments(
271: ParametersAcceptor $parametersAcceptor,
272: New_ $new,
273: ): ?New_
274: {
275: $args = $new->getArgs();
276: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
277:
278: if ($reorderedArgs === null) {
279: return null;
280: }
281:
282: // return identical object if not reordered, as TypeSpecifier relies on object identity
283: if ($reorderedArgs === $args) {
284: return $new;
285: }
286:
287: return new New_(
288: $new->class,
289: $reorderedArgs,
290: self::attributesWithoutPrintedForm($new),
291: );
292: }
293:
294: /**
295: * The argument bound to the parameter at $position named $name: the
296: * positional argument at that index or the one passed by that name.
297: *
298: * This method can be useful in simple cases when no reflection is needed.
299: * In more complex cases where reflection information is available,
300: * use ParametersAcceptorSelector::selectFromArgs() and ArgumentsNormalizer::reorder*Arguments() instead.
301: *
302: * @param Arg[] $args
303: * @param 0|positive-int $position
304: * @param non-empty-string $name
305: */
306: public static function getArgByPositionOrName(array $args, int $position, string $name): ?Arg
307: {
308: $argByPosition = null;
309: $argByName = null;
310: $hasNamedArgs = false;
311: $hasUnpackedArg = false;
312: foreach ($args as $i => $arg) {
313: if ($i === $position) {
314: $argByPosition = $arg;
315: }
316: if ($arg->unpack) {
317: $hasUnpackedArg = true;
318: }
319: if ($arg->name === null) {
320: continue;
321: }
322:
323: $hasNamedArgs = true;
324: if ($arg->name->toString() !== $name) {
325: continue;
326: }
327:
328: $argByName = $arg;
329: }
330:
331: if ($hasNamedArgs && $hasUnpackedArg) {
332: // Match reorderArgs(): unpacking makes named argument positions indeterminate.
333: return null;
334: }
335:
336: return $argByName ?? $argByPosition;
337: }
338:
339: /**
340: * @param Arg[] $callArgs
341: * @return ?list<Arg>
342: */
343: public static function reorderArgs(ParametersAcceptor $parametersAcceptor, array $callArgs): ?array
344: {
345: if (count($callArgs) === 0) {
346: return [];
347: }
348:
349: $hasNamedArgs = false;
350: foreach ($callArgs as $arg) {
351: if ($arg->name !== null) {
352: $hasNamedArgs = true;
353: break;
354: }
355: }
356: if (!$hasNamedArgs) {
357: return array_values($callArgs);
358: }
359:
360: foreach ($callArgs as $arg) {
361: if ($arg->unpack) {
362: // the number of parameters an unpacked argument fills is unknown here,
363: // so the positions of the named arguments that follow it cannot be determined
364: return null;
365: }
366: }
367:
368: $hasVariadic = false;
369: $argumentPositions = [];
370: $signatureParameters = $parametersAcceptor->getParameters();
371: foreach ($signatureParameters as $i => $parameter) {
372: if ($hasVariadic) {
373: // variadic parameter must be last
374: return null;
375: }
376:
377: $hasVariadic = $parameter->isVariadic();
378: $argumentPositions[$parameter->getName()] = $i;
379: }
380:
381: $reorderedArgs = [];
382: $additionalNamedArgs = [];
383: $appendArgs = [];
384: foreach ($callArgs as $i => $arg) {
385: if ($arg->name === null) {
386: // add regular args as is
387:
388: $attributes = $arg->getAttributes();
389: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
390: $reorderedArgs[$i] = new Arg(
391: $arg->value,
392: $arg->byRef,
393: $arg->unpack,
394: $attributes,
395: null,
396: );
397: } elseif (array_key_exists($arg->name->toString(), $argumentPositions)) {
398: $argName = $arg->name->toString();
399: // order named args into the position the signature expects them
400: $attributes = $arg->getAttributes();
401: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
402: if (array_key_exists($argumentPositions[$argName], $reorderedArgs)) {
403: continue;
404: }
405: $reorderedArgs[$argumentPositions[$argName]] = new Arg(
406: $arg->value,
407: $arg->byRef,
408: $arg->unpack,
409: $attributes,
410: null,
411: );
412: } else {
413: if (!$hasVariadic) {
414: $attributes = $arg->getAttributes();
415: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
416: $appendArgs[] = new Arg(
417: $arg->value,
418: $arg->byRef,
419: $arg->unpack,
420: $attributes,
421: null,
422: );
423: continue;
424: }
425:
426: $attributes = $arg->getAttributes();
427: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
428: $additionalNamedArgs[] = new Arg(
429: $arg->value,
430: $arg->byRef,
431: $arg->unpack,
432: $attributes,
433: null,
434: );
435: }
436: }
437:
438: // replace variadic parameter with additional named args, except if it is already set
439: $additionalNamedArgsOffset = count($argumentPositions) - 1;
440: if (array_key_exists($additionalNamedArgsOffset, $reorderedArgs)) {
441: $additionalNamedArgsOffset++;
442: }
443:
444: foreach ($additionalNamedArgs as $i => $additionalNamedArg) {
445: $reorderedArgs[$additionalNamedArgsOffset + $i] = $additionalNamedArg;
446: }
447:
448: if (count($reorderedArgs) === 0) {
449: foreach ($appendArgs as $arg) {
450: $reorderedArgs[] = $arg;
451: }
452: return $reorderedArgs;
453: }
454:
455: // fill up all holes with default values until the last given argument
456: for ($j = 0; $j < max(array_keys($reorderedArgs)); $j++) {
457: if (array_key_exists($j, $reorderedArgs)) {
458: continue;
459: }
460: if (!array_key_exists($j, $signatureParameters)) {
461: return null;
462: }
463:
464: $parameter = $signatureParameters[$j];
465:
466: // we can only fill up optional parameters with default values
467: if (!$parameter->isOptional()) {
468: return null;
469: }
470:
471: $defaultValue = $parameter->getDefaultValue();
472: if ($defaultValue === null) {
473: if (!$parameter->isVariadic()) {
474: // like an optional parameter combined from variants that do not all have it
475: return null;
476: }
477: $defaultValue = new ConstantArrayType([], []);
478: }
479:
480: $reorderedArgs[$j] = new Arg(
481: new TypeExpr($defaultValue),
482: );
483: }
484:
485: ksort($reorderedArgs);
486:
487: foreach ($appendArgs as $arg) {
488: $reorderedArgs[] = $arg;
489: }
490:
491: if (!array_is_list($reorderedArgs)) {
492: $reorderedArgs = array_values($reorderedArgs);
493: }
494:
495: return $reorderedArgs;
496: }
497:
498: /**
499: * The printed form of an expression is derived from its own arguments, so
500: * it must not travel to a node whose arguments were just reordered — the
501: * normalized call would report the original's expression key, named
502: * arguments and all.
503: *
504: * @return array<string, mixed>
505: */
506: private static function attributesWithoutPrintedForm(PhpParserNode $node): array
507: {
508: $attributes = $node->getAttributes();
509: unset($attributes[ExprPrinter::ATTRIBUTE_CACHE_KEY]);
510:
511: return $attributes;
512: }
513:
514: }
515: