1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Php;
4:
5: use PhpParser\Node\Expr;
6: use PHPStan\Analyser\Scope;
7: use PHPStan\DependencyInjection\AutowiredService;
8: use PHPStan\Php\PhpVersion;
9: use PHPStan\TrinaryLogic;
10: use PHPStan\Type\Accessory\AccessoryArrayListType;
11: use PHPStan\Type\Accessory\NonEmptyArrayType;
12: use PHPStan\Type\ArrayType;
13: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
14: use PHPStan\Type\Constant\ConstantIntegerType;
15: use PHPStan\Type\Constant\ConstantStringType;
16: use PHPStan\Type\IntegerRangeType;
17: use PHPStan\Type\IntersectionType;
18: use PHPStan\Type\NullType;
19: use PHPStan\Type\Regex\RegexCapturingGroup;
20: use PHPStan\Type\Regex\RegexExpressionHelper;
21: use PHPStan\Type\Regex\RegexGroupList;
22: use PHPStan\Type\Regex\RegexGroupParser;
23: use PHPStan\Type\StringType;
24: use PHPStan\Type\Type;
25: use PHPStan\Type\TypeCombinator;
26: use function count;
27: use function in_array;
28: use function is_string;
29: use const PREG_OFFSET_CAPTURE;
30: use const PREG_PATTERN_ORDER;
31: use const PREG_SET_ORDER;
32: use const PREG_UNMATCHED_AS_NULL;
33:
34: /**
35: * @api
36: */
37: #[AutowiredService]
38: final class RegexArrayShapeMatcher
39: {
40:
41: /**
42: * Pass this into $flagsType as well if the library supports emulating PREG_UNMATCHED_AS_NULL on PHP 7.2 and 7.3
43: */
44: public const PREG_UNMATCHED_AS_NULL_ON_72_73 = 2048;
45:
46: public function __construct(
47: private RegexGroupParser $regexGroupParser,
48: private RegexExpressionHelper $regexExpressionHelper,
49: private PhpVersion $phpVersion,
50: )
51: {
52: }
53:
54: public function matchAllExpr(Expr $patternExpr, ?Type $flagsType, TrinaryLogic $wasMatched, Scope $scope): ?Type
55: {
56: return $this->matchPatternType($this->getPatternType($patternExpr, $scope), $flagsType, $wasMatched, true);
57: }
58:
59: public function matchExpr(Expr $patternExpr, ?Type $flagsType, TrinaryLogic $wasMatched, Scope $scope): ?Type
60: {
61: return $this->matchPatternType($this->getPatternType($patternExpr, $scope), $flagsType, $wasMatched, false);
62: }
63:
64: public function matchSubjectExpr(Expr $patternExpr, Scope $scope): ?Type
65: {
66: $patternType = $this->getPatternType($patternExpr, $scope);
67: $constantStrings = $patternType->getConstantStrings();
68: if (count($constantStrings) === 0) {
69: return null;
70: }
71:
72: $subjectTypes = [];
73: foreach ($constantStrings as $constantString) {
74: $astWalkResult = $this->regexGroupParser->parseGroups($constantString->getValue());
75: if ($astWalkResult === null) {
76: return null;
77: }
78:
79: $subjectTypes[] = $astWalkResult->getSubjectBaseType();
80: }
81:
82: return TypeCombinator::union(...$subjectTypes);
83: }
84:
85: private function matchPatternType(Type $patternType, ?Type $flagsType, TrinaryLogic $wasMatched, bool $matchesAll): ?Type
86: {
87: if ($wasMatched->no()) {
88: return ConstantArrayTypeBuilder::createEmpty()->getArray();
89: }
90:
91: $constantStrings = $patternType->getConstantStrings();
92: if (count($constantStrings) === 0) {
93: return null;
94: }
95:
96: $flags = null;
97: if ($flagsType !== null) {
98: if (!$flagsType instanceof ConstantIntegerType) {
99: return null;
100: }
101:
102: /** @var int-mask<PREG_OFFSET_CAPTURE | PREG_PATTERN_ORDER | PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL | self::PREG_UNMATCHED_AS_NULL_ON_72_73> $flags */
103: $flags = $flagsType->getValue() & (PREG_OFFSET_CAPTURE | PREG_PATTERN_ORDER | PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL | self::PREG_UNMATCHED_AS_NULL_ON_72_73);
104:
105: // some other unsupported/unexpected flag was passed in
106: if ($flags !== $flagsType->getValue()) {
107: return null;
108: }
109: }
110:
111: $matchedTypes = [];
112: foreach ($constantStrings as $constantString) {
113: $matched = $this->matchRegex($constantString->getValue(), $flags, $wasMatched, $matchesAll);
114: if ($matched === null) {
115: return null;
116: }
117:
118: $matchedTypes[] = $matched;
119: }
120:
121: if (count($matchedTypes) === 1) {
122: return $matchedTypes[0];
123: }
124:
125: return TypeCombinator::union(...$matchedTypes);
126: }
127:
128: /**
129: * @param int-mask<PREG_OFFSET_CAPTURE|PREG_PATTERN_ORDER|PREG_SET_ORDER|PREG_UNMATCHED_AS_NULL|self::PREG_UNMATCHED_AS_NULL_ON_72_73>|null $flags
130: */
131: private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched, bool $matchesAll): ?Type
132: {
133: $astWalkResult = $this->regexGroupParser->parseGroups($regex);
134: if ($astWalkResult === null) {
135: // regex could not be parsed by RegexParser
136: return null;
137: }
138: $groupList = $astWalkResult->getCapturingGroups();
139: $markVerbs = $astWalkResult->getMarkVerbs();
140: $subjectBaseType = new StringType();
141: if ($wasMatched->yes()) {
142: $subjectBaseType = $astWalkResult->getSubjectBaseType();
143: }
144:
145: $regexGroupList = new RegexGroupList($groupList);
146: $trailingOptionals = $regexGroupList->countTrailingOptionals();
147: $onlyOptionalTopLevelGroup = $regexGroupList->getOnlyOptionalTopLevelGroup();
148: $onlyTopLevelAlternation = $regexGroupList->getOnlyTopLevelAlternation();
149: $flags ??= 0;
150:
151: if ($regexGroupList->hasDuplicateNamesOutsideOfAlternationBranches(
152: !$matchesAll && $onlyOptionalTopLevelGroup === null && !$this->containsUnmatchedAsNull($flags, $matchesAll)
153: ? $onlyTopLevelAlternation
154: : null,
155: )) {
156: // which of the groups sharing a name sets the named offset is only modelled
157: // for groups in different branches of a top level alternation
158: return null;
159: }
160:
161: if (
162: $regexGroupList->hasGroupResettingGroupCounter()
163: && (
164: $matchesAll
165: || $onlyOptionalTopLevelGroup !== null
166: || $onlyTopLevelAlternation === null
167: || $this->containsUnmatchedAsNull($flags, $matchesAll)
168: )
169: ) {
170: // groups in a branch reset (?|...) share offsets, which is only modelled
171: // when its alternation is the only top level alternation
172: return null;
173: }
174:
175: if (
176: !$matchesAll
177: && $wasMatched->yes()
178: && $onlyOptionalTopLevelGroup !== null
179: ) {
180: // if only one top level capturing optional group exists
181: // we build a more precise tagged union of a empty-match and a match with the group
182: $regexGroupList = $regexGroupList->forceGroupNonOptional($onlyOptionalTopLevelGroup);
183:
184: $combiType = $this->buildArrayType(
185: $subjectBaseType,
186: $regexGroupList,
187: $wasMatched,
188: $trailingOptionals,
189: $flags,
190: $markVerbs,
191: $matchesAll,
192: );
193:
194: if (!$this->containsUnmatchedAsNull($flags, $matchesAll)) {
195: // positive match has a subject but not any capturing group
196: $builder = ConstantArrayTypeBuilder::createEmpty();
197: $builder->makeKeyOrderKnown();
198: $builder->setOffsetValueType(new ConstantIntegerType(0), $this->createSubjectValueType($subjectBaseType, $flags, $matchesAll, $wasMatched));
199:
200: $combiType = TypeCombinator::union(
201: $builder->getArray(),
202: $combiType,
203: );
204: }
205:
206: return $combiType;
207: } elseif (
208: !$matchesAll
209: && $onlyOptionalTopLevelGroup === null
210: && $onlyTopLevelAlternation !== null
211: && !$wasMatched->no()
212: ) {
213: // if only a single top level alternation exist built a more precise tagged union
214:
215: $combiTypes = [];
216: $isOptionalAlternation = false;
217: foreach ($onlyTopLevelAlternation->getGroupCombinations() as $groupCombo) {
218: $comboList = new RegexGroupList($groupList);
219:
220: $beforeCurrentCombo = true;
221: foreach ($comboList as $group) {
222: if (in_array($group->getId(), $groupCombo, true)) {
223: $isOptionalAlternation = $group->inOptionalAlternation();
224: $comboList = $comboList->forceGroupAlternationBranchMatched($group);
225: $beforeCurrentCombo = false;
226: } elseif ($beforeCurrentCombo && !$group->resetsGroupCounter()) {
227: $comboList = $comboList->forceGroupTypeAndNonOptional(
228: $group,
229: $this->getUnmatchedGroupType($flags),
230: );
231: } elseif (
232: $group->getAlternationId() === $onlyTopLevelAlternation->getId()
233: && !$this->containsUnmatchedAsNull($flags, $matchesAll)
234: ) {
235: $comboList = $comboList->removeGroup($group);
236: }
237: }
238:
239: $combiType = $this->buildArrayType(
240: $subjectBaseType,
241: $comboList,
242: $wasMatched,
243: $trailingOptionals,
244: $flags,
245: $markVerbs,
246: $matchesAll,
247: );
248:
249: $combiTypes[] = $combiType;
250: }
251:
252: if (
253: !$this->containsUnmatchedAsNull($flags, $matchesAll)
254: && (
255: $onlyTopLevelAlternation->getAlternationsCount() !== count($onlyTopLevelAlternation->getGroupCombinations())
256: || $isOptionalAlternation
257: )
258: ) {
259: // positive match has a subject but not any capturing group
260: $builder = ConstantArrayTypeBuilder::createEmpty();
261: $builder->makeKeyOrderKnown();
262: $builder->setOffsetValueType(new ConstantIntegerType(0), $this->createSubjectValueType($subjectBaseType, $flags, $matchesAll, $wasMatched));
263:
264: $combiTypes[] = $builder->getArray();
265: }
266:
267: return TypeCombinator::union(...$combiTypes);
268: }
269:
270: // the general case, which should work in all cases but does not yield the most
271: // precise result possible in some cases
272: return $this->buildArrayType(
273: $subjectBaseType,
274: $regexGroupList,
275: $wasMatched,
276: $trailingOptionals,
277: $flags,
278: $markVerbs,
279: $matchesAll,
280: );
281: }
282:
283: /**
284: * @param list<string> $markVerbs
285: */
286: private function buildArrayType(
287: Type $subjectBaseType,
288: RegexGroupList $captureGroups,
289: TrinaryLogic $wasMatched,
290: int $trailingOptionals,
291: int $flags,
292: array $markVerbs,
293: bool $matchesAll,
294: ): Type
295: {
296: $forceList = count($markVerbs) === 0;
297: $builder = ConstantArrayTypeBuilder::createEmpty();
298: $builder->makeKeyOrderKnown();
299:
300: // first item in matches contains the overall match.
301: $builder->setOffsetValueType(
302: $this->getKeyType(0),
303: $this->createSubjectValueType($subjectBaseType, $flags, $matchesAll, $wasMatched),
304: $this->isSubjectOptional($wasMatched, $matchesAll),
305: );
306:
307: $countGroups = count($captureGroups);
308: $i = 0;
309: foreach ($captureGroups as $captureGroup) {
310: $isTrailingOptional = $i >= $countGroups - $trailingOptionals;
311: $isLastGroup = $i === $countGroups - 1;
312: $groupValueType = $this->createGroupValueType($captureGroup, $wasMatched, $flags, $isTrailingOptional, $isLastGroup, $matchesAll);
313: $optional = $this->isGroupOptional($captureGroup, $wasMatched, $flags, $isTrailingOptional, $matchesAll);
314:
315: if ($captureGroup->isNamed()) {
316: $forceList = false;
317:
318: $builder->setOffsetValueType(
319: $this->getKeyType($captureGroup->getName()),
320: $groupValueType,
321: $optional,
322: );
323: }
324:
325: $builder->setOffsetValueType(
326: $this->getKeyType($i + 1),
327: $groupValueType,
328: $optional,
329: );
330:
331: $i++;
332: }
333:
334: if (count($markVerbs) > 0) {
335: $markTypes = [];
336: foreach ($markVerbs as $mark) {
337: $markTypes[] = new ConstantStringType($mark);
338: }
339: $markType = TypeCombinator::union(...$markTypes);
340: if ($matchesAll && $this->containsPatternOrder($flags)) {
341: // marks are keyed by the index of the match that set them, matches without a mark are left out
342: $markType = new IntersectionType([
343: new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $markType),
344: new NonEmptyArrayType(),
345: ]);
346: }
347:
348: $builder->setOffsetValueType(
349: $this->getKeyType('MARK'),
350: $markType,
351: true,
352: );
353: }
354:
355: if ($matchesAll && $this->containsSetOrder($flags)) {
356: $accessoryTypes = [new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $builder->getArray()), new AccessoryArrayListType()];
357: if ($wasMatched->yes()) {
358: $accessoryTypes[] = new NonEmptyArrayType();
359: }
360:
361: return new IntersectionType($accessoryTypes);
362: }
363:
364: if ($forceList) {
365: return TypeCombinator::intersect($builder->getArray(), new AccessoryArrayListType());
366: }
367:
368: return $builder->getArray();
369: }
370:
371: private function isSubjectOptional(TrinaryLogic $wasMatched, bool $matchesAll): bool
372: {
373: if ($matchesAll) {
374: return false;
375: }
376:
377: return !$wasMatched->yes();
378: }
379:
380: /**
381: * @param Type $baseType A string type (or string variant) representing the subject of the match
382: */
383: private function createSubjectValueType(Type $baseType, int $flags, bool $matchesAll, TrinaryLogic $wasMatched): Type
384: {
385: $subjectValueType = TypeCombinator::removeNull($this->getValueType($baseType, $flags, $matchesAll));
386:
387: if ($matchesAll) {
388: $subjectValueType = TypeCombinator::removeNull($this->getValueType(new StringType(), $flags, $matchesAll));
389:
390: if ($this->containsPatternOrder($flags)) {
391: $accessoryTypes = [
392: new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $subjectValueType),
393: new AccessoryArrayListType(),
394: ];
395: if ($wasMatched->yes()) {
396: $accessoryTypes[] = new NonEmptyArrayType();
397: }
398:
399: $subjectValueType = new IntersectionType($accessoryTypes);
400: }
401: }
402:
403: return $subjectValueType;
404: }
405:
406: private function isGroupOptional(RegexCapturingGroup $captureGroup, TrinaryLogic $wasMatched, int $flags, bool $isTrailingOptional, bool $matchesAll): bool
407: {
408: if ($matchesAll) {
409: if ($isTrailingOptional && !$this->containsUnmatchedAsNull($flags, $matchesAll) && $this->containsSetOrder($flags)) {
410: return true;
411: }
412:
413: return false;
414: }
415:
416: if (!$wasMatched->yes()) {
417: $optional = true;
418: } else {
419: if (!$isTrailingOptional) {
420: $optional = false;
421: } elseif ($this->containsUnmatchedAsNull($flags, $matchesAll)) {
422: $optional = false;
423: } else {
424: $optional = $captureGroup->isOptional();
425: }
426: }
427:
428: return $optional;
429: }
430:
431: private function createGroupValueType(RegexCapturingGroup $captureGroup, TrinaryLogic $wasMatched, int $flags, bool $isTrailingOptional, bool $isLastGroup, bool $matchesAll): Type
432: {
433: if ($matchesAll) {
434: if (
435: (
436: !$this->containsSetOrder($flags)
437: && !$this->containsUnmatchedAsNull($flags, $matchesAll)
438: && $captureGroup->isOptional()
439: )
440: ||
441: (
442: $this->containsSetOrder($flags)
443: && !$this->containsUnmatchedAsNull($flags, $matchesAll)
444: && $captureGroup->isOptional()
445: // an unmatched group followed by a matched one is reported as ''
446: && !$isLastGroup
447: )
448: ) {
449: $groupValueType = $this->getValueType(
450: TypeCombinator::union($captureGroup->getType(), new ConstantStringType('')),
451: $flags,
452: $matchesAll,
453: );
454: $groupValueType = TypeCombinator::removeNull($groupValueType);
455: } else {
456: $groupValueType = $this->getValueType($captureGroup->getType(), $flags, $matchesAll);
457: }
458:
459: if (!$isTrailingOptional && $this->containsUnmatchedAsNull($flags, $matchesAll) && !$captureGroup->isOptional()) {
460: $groupValueType = TypeCombinator::removeNull($groupValueType);
461: }
462:
463: if ($this->containsPatternOrder($flags)) {
464: $accessoryTypes = [new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $groupValueType), new AccessoryArrayListType()];
465: if ($wasMatched->yes()) {
466: $accessoryTypes[] = new NonEmptyArrayType();
467: }
468:
469: $groupValueType = new IntersectionType($accessoryTypes);
470: }
471:
472: return $groupValueType;
473: }
474:
475: if (!$isLastGroup && !$this->containsUnmatchedAsNull($flags, $matchesAll) && $captureGroup->isOptional()) {
476: $groupValueType = $this->getValueType(
477: TypeCombinator::union($captureGroup->getType(), $this->getUnmatchedGroupType($flags)),
478: $flags,
479: $matchesAll,
480: );
481: } else {
482: $groupValueType = $this->getValueType($captureGroup->getType(), $flags, $matchesAll);
483: }
484:
485: if ($wasMatched->yes()) {
486: if (!$isTrailingOptional && $this->containsUnmatchedAsNull($flags, $matchesAll) && !$captureGroup->isOptional()) {
487: $groupValueType = TypeCombinator::removeNull($groupValueType);
488: }
489: }
490:
491: return $groupValueType;
492: }
493:
494: private function containsOffsetCapture(int $flags): bool
495: {
496: return ($flags & PREG_OFFSET_CAPTURE) !== 0;
497: }
498:
499: private function containsPatternOrder(int $flags): bool
500: {
501: // If no order flag is given, PREG_PATTERN_ORDER is assumed.
502: return !$this->containsSetOrder($flags);
503: }
504:
505: private function containsSetOrder(int $flags): bool
506: {
507: return ($flags & PREG_SET_ORDER) !== 0;
508: }
509:
510: private function containsUnmatchedAsNull(int $flags, bool $matchesAll): bool
511: {
512: if ($matchesAll) {
513: // preg_match_all() with PREG_UNMATCHED_AS_NULL works consistently across php-versions
514: // https://3v4l.org/tKmPn
515: return ($flags & PREG_UNMATCHED_AS_NULL) !== 0;
516: }
517:
518: return ($flags & PREG_UNMATCHED_AS_NULL) !== 0 && (($flags & self::PREG_UNMATCHED_AS_NULL_ON_72_73) !== 0 || $this->phpVersion->supportsPregUnmatchedAsNull());
519: }
520:
521: /**
522: * Type of an unmatched group followed by a matched one.
523: *
524: * PHP 7.2 and 7.3 already report it as null with PREG_UNMATCHED_AS_NULL,
525: * only the trailing unmatched groups are omitted there.
526: */
527: private function getUnmatchedGroupType(int $flags): Type
528: {
529: if (($flags & PREG_UNMATCHED_AS_NULL) !== 0) {
530: return new NullType();
531: }
532:
533: return new ConstantStringType('');
534: }
535:
536: private function getKeyType(int|string $key): Type
537: {
538: if (is_string($key)) {
539: return new ConstantStringType($key);
540: }
541:
542: return new ConstantIntegerType($key);
543: }
544:
545: private function getValueType(Type $baseType, int $flags, bool $matchesAll): Type
546: {
547: $valueType = $baseType;
548:
549: // unmatched groups return -1 as offset
550: $offsetType = IntegerRangeType::fromInterval(-1, null);
551: if ($this->containsUnmatchedAsNull($flags, $matchesAll)) {
552: $valueType = TypeCombinator::addNull($valueType);
553: }
554:
555: if ($this->containsOffsetCapture($flags)) {
556: $builder = ConstantArrayTypeBuilder::createEmpty();
557: $builder->makeKeyOrderKnown();
558:
559: $builder->setOffsetValueType(
560: new ConstantIntegerType(0),
561: $valueType,
562: );
563: $builder->setOffsetValueType(
564: new ConstantIntegerType(1),
565: $offsetType,
566: );
567:
568: return $builder->getArray();
569: }
570:
571: return $valueType;
572: }
573:
574: private function getPatternType(Expr $patternExpr, Scope $scope): Type
575: {
576: if ($patternExpr instanceof Expr\BinaryOp\Concat) {
577: return $this->regexExpressionHelper->resolvePatternConcat($patternExpr, $scope);
578: }
579:
580: return $scope->getType($patternExpr);
581: }
582:
583: }
584: