1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\PhpDocParser\Parser;
4:
5: use LogicException;
6: use PHPStan\PhpDocParser\Ast;
7: use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
8: use PHPStan\PhpDocParser\Lexer\Lexer;
9: use PHPStan\PhpDocParser\ParserConfig;
10: use function in_array;
11: use function strlen;
12: use function strpos;
13: use function substr_compare;
14:
15: class TypeParser
16: {
17:
18: private ParserConfig $config;
19:
20: private ConstExprParser $constExprParser;
21:
22: public function __construct(
23: ParserConfig $config,
24: ConstExprParser $constExprParser
25: )
26: {
27: $this->config = $config;
28: $this->constExprParser = $constExprParser;
29: }
30:
31: /** @phpstan-impure */
32: public function parse(TokenIterator $tokens): Ast\Type\TypeNode
33: {
34: $startLine = $tokens->currentTokenLine();
35: $startIndex = $tokens->currentTokenIndex();
36: if ($tokens->isCurrentTokenType(Lexer::TOKEN_NULLABLE)) {
37: $type = $this->parseNullable($tokens);
38:
39: } else {
40: $type = $this->parseAtomic($tokens);
41:
42: $tokens->pushSavePoint();
43: $tokens->skipNewLineTokensAndConsumeComments();
44:
45: try {
46: $enrichedType = $this->enrichTypeOnUnionOrIntersection($tokens, $type);
47:
48: } catch (ParserException $parserException) {
49: $enrichedType = null;
50: }
51:
52: if ($enrichedType !== null) {
53: $type = $enrichedType;
54: $tokens->dropSavePoint();
55:
56: } else {
57: $tokens->rollback();
58: $type = $this->enrichTypeOnUnionOrIntersection($tokens, $type) ?? $type;
59: }
60: }
61:
62: return $this->enrichWithAttributes($tokens, $type, $startLine, $startIndex);
63: }
64:
65: /** @phpstan-impure */
66: private function enrichTypeOnUnionOrIntersection(TokenIterator $tokens, Ast\Type\TypeNode $type): ?Ast\Type\TypeNode
67: {
68: if ($tokens->isCurrentTokenType(Lexer::TOKEN_UNION)) {
69: return $this->parseUnion($tokens, $type);
70:
71: }
72:
73: if ($tokens->isCurrentTokenType(Lexer::TOKEN_INTERSECTION)) {
74: return $this->parseIntersection($tokens, $type);
75: }
76:
77: return null;
78: }
79:
80: /**
81: * @internal
82: * @template T of Ast\Node
83: * @param T $type
84: * @return T
85: */
86: public function enrichWithAttributes(TokenIterator $tokens, Ast\Node $type, int $startLine, int $startIndex): Ast\Node
87: {
88: if ($this->config->useLinesAttributes) {
89: $type->setAttribute(Ast\Attribute::START_LINE, $startLine);
90: $type->setAttribute(Ast\Attribute::END_LINE, $tokens->currentTokenLine());
91: }
92:
93: $comments = $tokens->flushComments();
94: if ($this->config->useCommentsAttributes) {
95: $type->setAttribute(Ast\Attribute::COMMENTS, $comments);
96: }
97:
98: if ($this->config->useIndexAttributes) {
99: $type->setAttribute(Ast\Attribute::START_INDEX, $startIndex);
100: $type->setAttribute(Ast\Attribute::END_INDEX, $tokens->endIndexOfLastRelevantToken());
101: }
102:
103: return $type;
104: }
105:
106: /** @phpstan-impure */
107: private function subParse(TokenIterator $tokens): Ast\Type\TypeNode
108: {
109: $startLine = $tokens->currentTokenLine();
110: $startIndex = $tokens->currentTokenIndex();
111:
112: if ($tokens->isCurrentTokenType(Lexer::TOKEN_NULLABLE)) {
113: $type = $this->parseNullable($tokens);
114:
115: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_VARIABLE)) {
116: $type = $this->parseConditionalForParameter($tokens, $tokens->currentTokenValue());
117:
118: } else {
119: $type = $this->parseAtomic($tokens);
120:
121: if ($tokens->isCurrentTokenValue('is')) {
122: $type = $this->parseConditional($tokens, $type);
123: } else {
124: $tokens->skipNewLineTokensAndConsumeComments();
125:
126: if ($tokens->isCurrentTokenType(Lexer::TOKEN_UNION)) {
127: $type = $this->subParseUnion($tokens, $type);
128:
129: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_INTERSECTION)) {
130: $type = $this->subParseIntersection($tokens, $type);
131: }
132: }
133: }
134:
135: return $this->enrichWithAttributes($tokens, $type, $startLine, $startIndex);
136: }
137:
138: /** @phpstan-impure */
139: private function parseAtomic(TokenIterator $tokens): Ast\Type\TypeNode
140: {
141: $startLine = $tokens->currentTokenLine();
142: $startIndex = $tokens->currentTokenIndex();
143:
144: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_OPEN_PARENTHESES)) {
145: $tokens->skipNewLineTokensAndConsumeComments();
146: $type = $this->subParse($tokens);
147: $tokens->skipNewLineTokensAndConsumeComments();
148:
149: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_PARENTHESES);
150:
151: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
152: $type = $this->tryParseArrayOrOffsetAccess($tokens, $type);
153: }
154:
155: return $this->enrichWithAttributes($tokens, $type, $startLine, $startIndex);
156: }
157:
158: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_THIS_VARIABLE)) {
159: $type = $this->enrichWithAttributes($tokens, new Ast\Type\ThisTypeNode(), $startLine, $startIndex);
160:
161: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
162: $type = $this->tryParseArrayOrOffsetAccess($tokens, $type);
163: }
164:
165: return $this->enrichWithAttributes($tokens, $type, $startLine, $startIndex);
166: }
167:
168: $currentTokenValue = $tokens->currentTokenValue();
169: $tokens->pushSavePoint(); // because of ConstFetchNode
170: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_IDENTIFIER)) {
171: $type = $this->enrichWithAttributes($tokens, new Ast\Type\IdentifierTypeNode($currentTokenValue), $startLine, $startIndex);
172:
173: if (!$tokens->isCurrentTokenType(Lexer::TOKEN_DOUBLE_COLON)) {
174: $tokens->dropSavePoint(); // because of ConstFetchNode
175: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET)) {
176: $tokens->pushSavePoint();
177:
178: $isHtml = $this->isHtml($tokens);
179: $tokens->rollback();
180: if ($isHtml) {
181: return $type;
182: }
183:
184: $origType = $type;
185: $type = $this->tryParseCallable($tokens, $type, true);
186: if ($type === $origType) {
187: $type = $this->parseGeneric($tokens, $type);
188:
189: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
190: $type = $this->tryParseArrayOrOffsetAccess($tokens, $type);
191: }
192: }
193: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_PARENTHESES)) {
194: $type = $this->tryParseCallable($tokens, $type, false);
195:
196: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
197: $type = $this->tryParseArrayOrOffsetAccess($tokens, $type);
198:
199: } elseif (in_array($type->name, [
200: Ast\Type\ArrayShapeNode::KIND_ARRAY,
201: Ast\Type\ArrayShapeNode::KIND_LIST,
202: Ast\Type\ArrayShapeNode::KIND_NON_EMPTY_ARRAY,
203: Ast\Type\ArrayShapeNode::KIND_NON_EMPTY_LIST,
204: 'object',
205: ], true) && $tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_CURLY_BRACKET) && !$tokens->isPrecededByHorizontalWhitespace()) {
206: if ($type->name === 'object') {
207: $type = $this->parseObjectShape($tokens);
208: } else {
209: $type = $this->parseArrayShape($tokens, $type, $type->name);
210: }
211:
212: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
213: $type = $this->tryParseArrayOrOffsetAccess(
214: $tokens,
215: $this->enrichWithAttributes($tokens, $type, $startLine, $startIndex),
216: );
217: }
218: }
219:
220: return $this->enrichWithAttributes($tokens, $type, $startLine, $startIndex);
221: } else {
222: $tokens->rollback(); // because of ConstFetchNode
223: }
224: } else {
225: $tokens->dropSavePoint(); // because of ConstFetchNode
226: }
227:
228: $currentTokenValue = $tokens->currentTokenValue();
229: $currentTokenType = $tokens->currentTokenType();
230: $currentTokenOffset = $tokens->currentTokenOffset();
231: $currentTokenLine = $tokens->currentTokenLine();
232:
233: try {
234: $constExpr = $this->constExprParser->parse($tokens);
235: if ($constExpr instanceof Ast\ConstExpr\ConstExprArrayNode) {
236: throw new ParserException(
237: $currentTokenValue,
238: $currentTokenType,
239: $currentTokenOffset,
240: Lexer::TOKEN_IDENTIFIER,
241: null,
242: $currentTokenLine,
243: );
244: }
245:
246: $type = $this->enrichWithAttributes(
247: $tokens,
248: new Ast\Type\ConstTypeNode($constExpr),
249: $startLine,
250: $startIndex,
251: );
252: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
253: $type = $this->tryParseArrayOrOffsetAccess($tokens, $type);
254: }
255:
256: return $type;
257: } catch (LogicException $e) {
258: throw new ParserException(
259: $currentTokenValue,
260: $currentTokenType,
261: $currentTokenOffset,
262: Lexer::TOKEN_IDENTIFIER,
263: null,
264: $currentTokenLine,
265: );
266: }
267: }
268:
269: /** @phpstan-impure */
270: private function parseUnion(TokenIterator $tokens, Ast\Type\TypeNode $type): Ast\Type\TypeNode
271: {
272: $types = [$type];
273:
274: while ($tokens->tryConsumeTokenType(Lexer::TOKEN_UNION)) {
275: $types[] = $this->parseAtomic($tokens);
276: $tokens->pushSavePoint();
277: $tokens->skipNewLineTokensAndConsumeComments();
278: if (!$tokens->isCurrentTokenType(Lexer::TOKEN_UNION)) {
279: $tokens->rollback();
280: break;
281: }
282:
283: $tokens->dropSavePoint();
284: }
285:
286: return new Ast\Type\UnionTypeNode($types);
287: }
288:
289: /** @phpstan-impure */
290: private function subParseUnion(TokenIterator $tokens, Ast\Type\TypeNode $type): Ast\Type\TypeNode
291: {
292: $types = [$type];
293:
294: while ($tokens->tryConsumeTokenType(Lexer::TOKEN_UNION)) {
295: $tokens->skipNewLineTokensAndConsumeComments();
296: $types[] = $this->parseAtomic($tokens);
297: $tokens->skipNewLineTokensAndConsumeComments();
298: }
299:
300: return new Ast\Type\UnionTypeNode($types);
301: }
302:
303: /** @phpstan-impure */
304: private function parseIntersection(TokenIterator $tokens, Ast\Type\TypeNode $type): Ast\Type\TypeNode
305: {
306: $types = [$type];
307:
308: while ($tokens->tryConsumeTokenType(Lexer::TOKEN_INTERSECTION)) {
309: $types[] = $this->parseAtomic($tokens);
310: $tokens->pushSavePoint();
311: $tokens->skipNewLineTokensAndConsumeComments();
312: if (!$tokens->isCurrentTokenType(Lexer::TOKEN_INTERSECTION)) {
313: $tokens->rollback();
314: break;
315: }
316:
317: $tokens->dropSavePoint();
318: }
319:
320: return new Ast\Type\IntersectionTypeNode($types);
321: }
322:
323: /** @phpstan-impure */
324: private function subParseIntersection(TokenIterator $tokens, Ast\Type\TypeNode $type): Ast\Type\TypeNode
325: {
326: $types = [$type];
327:
328: while ($tokens->tryConsumeTokenType(Lexer::TOKEN_INTERSECTION)) {
329: $tokens->skipNewLineTokensAndConsumeComments();
330: $types[] = $this->parseAtomic($tokens);
331: $tokens->skipNewLineTokensAndConsumeComments();
332: }
333:
334: return new Ast\Type\IntersectionTypeNode($types);
335: }
336:
337: /** @phpstan-impure */
338: private function parseConditional(TokenIterator $tokens, Ast\Type\TypeNode $subjectType): Ast\Type\TypeNode
339: {
340: $tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
341:
342: $negated = false;
343: if ($tokens->isCurrentTokenValue('not')) {
344: $negated = true;
345: $tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
346: }
347:
348: $targetType = $this->parse($tokens);
349:
350: $tokens->skipNewLineTokensAndConsumeComments();
351: $tokens->consumeTokenType(Lexer::TOKEN_NULLABLE);
352: $tokens->skipNewLineTokensAndConsumeComments();
353:
354: $ifType = $this->parse($tokens);
355:
356: $tokens->skipNewLineTokensAndConsumeComments();
357: $tokens->consumeTokenType(Lexer::TOKEN_COLON);
358: $tokens->skipNewLineTokensAndConsumeComments();
359:
360: $elseType = $this->subParse($tokens);
361:
362: return new Ast\Type\ConditionalTypeNode($subjectType, $targetType, $ifType, $elseType, $negated);
363: }
364:
365: /** @phpstan-impure */
366: private function parseConditionalForParameter(TokenIterator $tokens, string $parameterName): Ast\Type\TypeNode
367: {
368: $tokens->consumeTokenType(Lexer::TOKEN_VARIABLE);
369: $tokens->consumeTokenValue(Lexer::TOKEN_IDENTIFIER, 'is');
370:
371: $negated = false;
372: if ($tokens->isCurrentTokenValue('not')) {
373: $negated = true;
374: $tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
375: }
376:
377: $targetType = $this->parse($tokens);
378:
379: $tokens->skipNewLineTokensAndConsumeComments();
380: $tokens->consumeTokenType(Lexer::TOKEN_NULLABLE);
381: $tokens->skipNewLineTokensAndConsumeComments();
382:
383: $ifType = $this->parse($tokens);
384:
385: $tokens->skipNewLineTokensAndConsumeComments();
386: $tokens->consumeTokenType(Lexer::TOKEN_COLON);
387: $tokens->skipNewLineTokensAndConsumeComments();
388:
389: $elseType = $this->subParse($tokens);
390:
391: return new Ast\Type\ConditionalTypeForParameterNode($parameterName, $targetType, $ifType, $elseType, $negated);
392: }
393:
394: /** @phpstan-impure */
395: private function parseNullable(TokenIterator $tokens): Ast\Type\TypeNode
396: {
397: $tokens->consumeTokenType(Lexer::TOKEN_NULLABLE);
398:
399: $type = $this->parseAtomic($tokens);
400:
401: return new Ast\Type\NullableTypeNode($type);
402: }
403:
404: /** @phpstan-impure */
405: public function isHtml(TokenIterator $tokens): bool
406: {
407: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET);
408:
409: if (!$tokens->isCurrentTokenType(Lexer::TOKEN_IDENTIFIER)) {
410: return false;
411: }
412:
413: $htmlTagName = $tokens->currentTokenValue();
414:
415: $tokens->next();
416:
417: if (!$tokens->tryConsumeTokenType(Lexer::TOKEN_CLOSE_ANGLE_BRACKET)) {
418: return false;
419: }
420:
421: // every end tag the walk below looks for contains this
422: if (!$tokens->hasEndTagCandidateAhead($htmlTagName)) {
423: return false;
424: }
425:
426: $endTag = '</' . $htmlTagName . '>';
427: $endTagSearchOffset = - strlen($endTag);
428:
429: while (!$tokens->isCurrentTokenType(Lexer::TOKEN_END)) {
430: if (
431: (
432: $tokens->tryConsumeTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET)
433: && strpos($tokens->currentTokenValue(), '/' . $htmlTagName . '>') !== false
434: )
435: || substr_compare($tokens->currentTokenValue(), $endTag, $endTagSearchOffset) === 0
436: ) {
437: return true;
438: }
439:
440: $tokens->next();
441: }
442:
443: return false;
444: }
445:
446: /** @phpstan-impure */
447: public function parseGeneric(TokenIterator $tokens, Ast\Type\IdentifierTypeNode $baseType): Ast\Type\GenericTypeNode
448: {
449: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET);
450: $tokens->skipNewLineTokensAndConsumeComments();
451:
452: $startLine = $baseType->getAttribute(Ast\Attribute::START_LINE);
453: $startIndex = $baseType->getAttribute(Ast\Attribute::START_INDEX);
454: $genericTypes = [];
455: $variances = [];
456:
457: $isFirst = true;
458: while (
459: $isFirst
460: || $tokens->tryConsumeTokenType(Lexer::TOKEN_COMMA)
461: ) {
462: $tokens->skipNewLineTokensAndConsumeComments();
463:
464: // trailing comma case
465: if (!$isFirst && $tokens->isCurrentTokenType(Lexer::TOKEN_CLOSE_ANGLE_BRACKET)) {
466: break;
467: }
468: $isFirst = false;
469:
470: [$genericTypes[], $variances[]] = $this->parseGenericTypeArgument($tokens);
471: $tokens->skipNewLineTokensAndConsumeComments();
472: }
473:
474: $type = new Ast\Type\GenericTypeNode($baseType, $genericTypes, $variances);
475: if ($startLine !== null && $startIndex !== null) {
476: $type = $this->enrichWithAttributes($tokens, $type, $startLine, $startIndex);
477: } else {
478: // The comments read between the arguments have to be given away
479: // even where the node is not placed, or they would still be waiting
480: // for a node once the whole PHPDoc has been read
481: $tokens->flushComments();
482: }
483:
484: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_ANGLE_BRACKET);
485:
486: return $type;
487: }
488:
489: /**
490: * @phpstan-impure
491: * @return array{Ast\Type\TypeNode, Ast\Type\GenericTypeNode::VARIANCE_*}
492: */
493: public function parseGenericTypeArgument(TokenIterator $tokens): array
494: {
495: $startLine = $tokens->currentTokenLine();
496: $startIndex = $tokens->currentTokenIndex();
497: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_WILDCARD)) {
498: return [
499: $this->enrichWithAttributes($tokens, new Ast\Type\IdentifierTypeNode('mixed'), $startLine, $startIndex),
500: Ast\Type\GenericTypeNode::VARIANCE_BIVARIANT,
501: ];
502: }
503:
504: if ($tokens->tryConsumeTokenValue('contravariant')) {
505: $variance = Ast\Type\GenericTypeNode::VARIANCE_CONTRAVARIANT;
506: } elseif ($tokens->tryConsumeTokenValue('covariant')) {
507: $variance = Ast\Type\GenericTypeNode::VARIANCE_COVARIANT;
508: } else {
509: $variance = Ast\Type\GenericTypeNode::VARIANCE_INVARIANT;
510:
511: $templateDeclaration = $this->tryParseTemplateDeclaration($tokens);
512: if ($templateDeclaration !== null) {
513: return [$templateDeclaration, $variance];
514: }
515: }
516:
517: $type = $this->parse($tokens);
518: return [$type, $variance];
519: }
520:
521: /**
522: * Reads a template declared in a generic type argument, like "T of Foo".
523: * Returns null when the argument is not one, leaving the tokens untouched.
524: *
525: * @phpstan-impure
526: */
527: private function tryParseTemplateDeclaration(TokenIterator $tokens): ?Ast\Type\TemplateDeclarationTypeNode
528: {
529: if (!$tokens->isCurrentTokenType(Lexer::TOKEN_IDENTIFIER)) {
530: return null;
531: }
532:
533: $startLine = $tokens->currentTokenLine();
534: $startIndex = $tokens->currentTokenIndex();
535: $name = $tokens->currentTokenValue();
536:
537: $tokens->pushSavePoint();
538: $tokens->next();
539: if (!$tokens->tryConsumeTokenValue('of') && !$tokens->tryConsumeTokenValue('as')) {
540: $tokens->rollback();
541: return null;
542: }
543: $tokens->dropSavePoint();
544:
545: // The comments written before the template belong to it, not to its bound
546: $comments = $tokens->flushComments();
547: $bound = $this->parse($tokens);
548: $template = $this->enrichWithAttributes(
549: $tokens,
550: new Ast\Type\TemplateDeclarationTypeNode($name, $bound),
551: $startLine,
552: $startIndex,
553: );
554: if ($this->config->useCommentsAttributes) {
555: $template->setAttribute(Ast\Attribute::COMMENTS, $comments);
556: }
557:
558: return $template;
559: }
560:
561: /**
562: * @throws ParserException
563: * @param ?callable(TokenIterator): string $parseDescription
564: */
565: public function parseTemplateTagValue(
566: TokenIterator $tokens,
567: ?callable $parseDescription = null
568: ): TemplateTagValueNode
569: {
570: $name = $tokens->currentTokenValue();
571: $tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
572:
573: $upperBound = $lowerBound = null;
574:
575: if ($tokens->tryConsumeTokenValue('of') || $tokens->tryConsumeTokenValue('as')) {
576: $upperBound = $this->parse($tokens);
577: }
578:
579: if ($tokens->tryConsumeTokenValue('super')) {
580: $lowerBound = $this->parse($tokens);
581: }
582:
583: if ($tokens->tryConsumeTokenValue('=')) {
584: $default = $this->parse($tokens);
585: } else {
586: $default = null;
587: }
588:
589: if ($parseDescription !== null) {
590: $description = $parseDescription($tokens);
591: } else {
592: $description = '';
593: }
594:
595: if ($name === '') {
596: throw new LogicException('Template tag name cannot be empty.');
597: }
598:
599: return new Ast\PhpDoc\TemplateTagValueNode($name, $upperBound, $description, $default, $lowerBound);
600: }
601:
602: /** @phpstan-impure */
603: private function parseCallable(TokenIterator $tokens, Ast\Type\IdentifierTypeNode $identifier, bool $hasTemplate): Ast\Type\TypeNode
604: {
605: $templates = $hasTemplate
606: ? $this->parseTemplateTypes($tokens)
607: : [];
608:
609: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_PARENTHESES);
610: $tokens->skipNewLineTokensAndConsumeComments();
611:
612: $parameters = [];
613: if (!$tokens->isCurrentTokenType(Lexer::TOKEN_CLOSE_PARENTHESES)) {
614: $parameters[] = $this->parseCallableParameter($tokens);
615: $tokens->skipNewLineTokensAndConsumeComments();
616: while ($tokens->tryConsumeTokenType(Lexer::TOKEN_COMMA)) {
617: $tokens->skipNewLineTokensAndConsumeComments();
618: if ($tokens->isCurrentTokenType(Lexer::TOKEN_CLOSE_PARENTHESES)) {
619: break;
620: }
621: $parameters[] = $this->parseCallableParameter($tokens);
622: $tokens->skipNewLineTokensAndConsumeComments();
623: }
624: }
625:
626: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_PARENTHESES);
627: $tokens->consumeTokenType(Lexer::TOKEN_COLON);
628:
629: $startLine = $tokens->currentTokenLine();
630: $startIndex = $tokens->currentTokenIndex();
631: $returnType = $this->enrichWithAttributes($tokens, $this->parseCallableReturnType($tokens), $startLine, $startIndex);
632:
633: return new Ast\Type\CallableTypeNode($identifier, $parameters, $returnType, $templates);
634: }
635:
636: /**
637: * Parses a list of templates in angle brackets, like the "<T, U of Foo>"
638: * of a callable type or of a type alias.
639: *
640: * @return Ast\PhpDoc\TemplateTagValueNode[]
641: *
642: * @phpstan-impure
643: */
644: public function parseTemplateTypes(TokenIterator $tokens): array
645: {
646: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET);
647:
648: $templates = [];
649:
650: $isFirst = true;
651: while ($isFirst || $tokens->tryConsumeTokenType(Lexer::TOKEN_COMMA)) {
652: $tokens->skipNewLineTokensAndConsumeComments();
653:
654: // trailing comma case
655: if (!$isFirst && $tokens->isCurrentTokenType(Lexer::TOKEN_CLOSE_ANGLE_BRACKET)) {
656: break;
657: }
658: $isFirst = false;
659:
660: $templates[] = $this->parseCallableTemplateArgument($tokens);
661: $tokens->skipNewLineTokensAndConsumeComments();
662: }
663:
664: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_ANGLE_BRACKET);
665:
666: return $templates;
667: }
668:
669: private function parseCallableTemplateArgument(TokenIterator $tokens): Ast\PhpDoc\TemplateTagValueNode
670: {
671: $startLine = $tokens->currentTokenLine();
672: $startIndex = $tokens->currentTokenIndex();
673:
674: return $this->enrichWithAttributes(
675: $tokens,
676: $this->parseTemplateTagValue($tokens),
677: $startLine,
678: $startIndex,
679: );
680: }
681:
682: /** @phpstan-impure */
683: private function parseCallableParameter(TokenIterator $tokens): Ast\Type\CallableTypeParameterNode
684: {
685: $startLine = $tokens->currentTokenLine();
686: $startIndex = $tokens->currentTokenIndex();
687: $type = $this->parse($tokens);
688: $isReference = $tokens->tryConsumeTokenType(Lexer::TOKEN_REFERENCE);
689: $isVariadic = $tokens->tryConsumeTokenType(Lexer::TOKEN_VARIADIC);
690:
691: if ($tokens->isCurrentTokenType(Lexer::TOKEN_VARIABLE)) {
692: $parameterName = $tokens->currentTokenValue();
693: $tokens->consumeTokenType(Lexer::TOKEN_VARIABLE);
694:
695: } else {
696: $parameterName = '';
697: }
698:
699: $isOptional = $tokens->tryConsumeTokenType(Lexer::TOKEN_EQUAL);
700: return $this->enrichWithAttributes(
701: $tokens,
702: new Ast\Type\CallableTypeParameterNode($type, $isReference, $isVariadic, $parameterName, $isOptional),
703: $startLine,
704: $startIndex,
705: );
706: }
707:
708: /** @phpstan-impure */
709: private function parseCallableReturnType(TokenIterator $tokens): Ast\Type\TypeNode
710: {
711: $startLine = $tokens->currentTokenLine();
712: $startIndex = $tokens->currentTokenIndex();
713: if ($tokens->isCurrentTokenType(Lexer::TOKEN_NULLABLE)) {
714: return $this->parseNullable($tokens);
715:
716: } elseif ($tokens->tryConsumeTokenType(Lexer::TOKEN_OPEN_PARENTHESES)) {
717: $type = $this->subParse($tokens);
718: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_PARENTHESES);
719: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
720: $type = $this->tryParseArrayOrOffsetAccess($tokens, $type);
721: }
722:
723: return $type;
724: } elseif ($tokens->tryConsumeTokenType(Lexer::TOKEN_THIS_VARIABLE)) {
725: $type = new Ast\Type\ThisTypeNode();
726: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
727: $type = $this->tryParseArrayOrOffsetAccess($tokens, $this->enrichWithAttributes(
728: $tokens,
729: $type,
730: $startLine,
731: $startIndex,
732: ));
733: }
734:
735: return $type;
736: } else {
737: $currentTokenValue = $tokens->currentTokenValue();
738: $tokens->pushSavePoint(); // because of ConstFetchNode
739: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_IDENTIFIER)) {
740: $type = new Ast\Type\IdentifierTypeNode($currentTokenValue);
741:
742: if (!$tokens->isCurrentTokenType(Lexer::TOKEN_DOUBLE_COLON)) {
743: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET)) {
744: $type = $this->parseGeneric(
745: $tokens,
746: $this->enrichWithAttributes(
747: $tokens,
748: $type,
749: $startLine,
750: $startIndex,
751: ),
752: );
753: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
754: $type = $this->tryParseArrayOrOffsetAccess($tokens, $this->enrichWithAttributes(
755: $tokens,
756: $type,
757: $startLine,
758: $startIndex,
759: ));
760: }
761:
762: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
763: $type = $this->tryParseArrayOrOffsetAccess($tokens, $this->enrichWithAttributes(
764: $tokens,
765: $type,
766: $startLine,
767: $startIndex,
768: ));
769:
770: } elseif (in_array($type->name, [
771: Ast\Type\ArrayShapeNode::KIND_ARRAY,
772: Ast\Type\ArrayShapeNode::KIND_LIST,
773: Ast\Type\ArrayShapeNode::KIND_NON_EMPTY_ARRAY,
774: Ast\Type\ArrayShapeNode::KIND_NON_EMPTY_LIST,
775: 'object',
776: ], true) && $tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_CURLY_BRACKET) && !$tokens->isPrecededByHorizontalWhitespace()) {
777: if ($type->name === 'object') {
778: $type = $this->parseObjectShape($tokens);
779: } else {
780: $type = $this->parseArrayShape($tokens, $this->enrichWithAttributes(
781: $tokens,
782: $type,
783: $startLine,
784: $startIndex,
785: ), $type->name);
786: }
787:
788: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
789: $type = $this->tryParseArrayOrOffsetAccess($tokens, $this->enrichWithAttributes(
790: $tokens,
791: $type,
792: $startLine,
793: $startIndex,
794: ));
795: }
796: }
797:
798: return $type;
799: } else {
800: $tokens->rollback(); // because of ConstFetchNode
801: }
802: } else {
803: $tokens->dropSavePoint(); // because of ConstFetchNode
804: }
805: }
806:
807: $currentTokenValue = $tokens->currentTokenValue();
808: $currentTokenType = $tokens->currentTokenType();
809: $currentTokenOffset = $tokens->currentTokenOffset();
810: $currentTokenLine = $tokens->currentTokenLine();
811:
812: try {
813: $constExpr = $this->constExprParser->parse($tokens);
814: if ($constExpr instanceof Ast\ConstExpr\ConstExprArrayNode) {
815: throw new ParserException(
816: $currentTokenValue,
817: $currentTokenType,
818: $currentTokenOffset,
819: Lexer::TOKEN_IDENTIFIER,
820: null,
821: $currentTokenLine,
822: );
823: }
824:
825: $type = $this->enrichWithAttributes(
826: $tokens,
827: new Ast\Type\ConstTypeNode($constExpr),
828: $startLine,
829: $startIndex,
830: );
831: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
832: $type = $this->tryParseArrayOrOffsetAccess($tokens, $type);
833: }
834:
835: return $type;
836: } catch (LogicException $e) {
837: throw new ParserException(
838: $currentTokenValue,
839: $currentTokenType,
840: $currentTokenOffset,
841: Lexer::TOKEN_IDENTIFIER,
842: null,
843: $currentTokenLine,
844: );
845: }
846: }
847:
848: /** @phpstan-impure */
849: private function tryParseCallable(TokenIterator $tokens, Ast\Type\IdentifierTypeNode $identifier, bool $hasTemplate): Ast\Type\TypeNode
850: {
851: try {
852: $tokens->pushSavePoint();
853: $type = $this->parseCallable($tokens, $identifier, $hasTemplate);
854: $tokens->dropSavePoint();
855:
856: } catch (ParserException $e) {
857: $tokens->rollback();
858: $type = $identifier;
859: }
860:
861: return $type;
862: }
863:
864: /** @phpstan-impure */
865: private function tryParseArrayOrOffsetAccess(TokenIterator $tokens, Ast\Type\TypeNode $type): Ast\Type\TypeNode
866: {
867: $startLine = $type->getAttribute(Ast\Attribute::START_LINE);
868: $startIndex = $type->getAttribute(Ast\Attribute::START_INDEX);
869: try {
870: while ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET)) {
871: $tokens->pushSavePoint();
872:
873: $canBeOffsetAccessType = !$tokens->isPrecededByHorizontalWhitespace();
874: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_SQUARE_BRACKET);
875:
876: if ($canBeOffsetAccessType && !$tokens->isCurrentTokenType(Lexer::TOKEN_CLOSE_SQUARE_BRACKET)) {
877: $offset = $this->parse($tokens);
878: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_SQUARE_BRACKET);
879: $tokens->dropSavePoint();
880: $type = new Ast\Type\OffsetAccessTypeNode($type, $offset);
881:
882: if ($startLine !== null && $startIndex !== null) {
883: $type = $this->enrichWithAttributes(
884: $tokens,
885: $type,
886: $startLine,
887: $startIndex,
888: );
889: }
890: } else {
891: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_SQUARE_BRACKET);
892: $tokens->dropSavePoint();
893: $type = new Ast\Type\ArrayTypeNode($type);
894:
895: if ($startLine !== null && $startIndex !== null) {
896: $type = $this->enrichWithAttributes(
897: $tokens,
898: $type,
899: $startLine,
900: $startIndex,
901: );
902: }
903: }
904: }
905:
906: } catch (ParserException $e) {
907: $tokens->rollback();
908: }
909:
910: return $type;
911: }
912:
913: /**
914: * @phpstan-impure
915: * @param Ast\Type\ArrayShapeNode::KIND_* $kind
916: */
917: private function parseArrayShape(TokenIterator $tokens, Ast\Type\TypeNode $type, string $kind): Ast\Type\ArrayShapeNode
918: {
919: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_CURLY_BRACKET);
920:
921: $items = [];
922: $sealed = true;
923: $unsealedType = null;
924:
925: $done = false;
926:
927: do {
928: $tokens->skipNewLineTokensAndConsumeComments();
929:
930: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET)) {
931: return Ast\Type\ArrayShapeNode::createSealed($items, $kind);
932: }
933:
934: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_VARIADIC)) {
935: $sealed = false;
936:
937: $tokens->skipNewLineTokensAndConsumeComments();
938: if ($tokens->isCurrentTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET)) {
939: if ($kind === Ast\Type\ArrayShapeNode::KIND_ARRAY) {
940: $unsealedType = $this->parseArrayShapeUnsealedType($tokens);
941: } else {
942: $unsealedType = $this->parseListShapeUnsealedType($tokens);
943: }
944: $tokens->skipNewLineTokensAndConsumeComments();
945: }
946:
947: $tokens->tryConsumeTokenType(Lexer::TOKEN_COMMA);
948: break;
949: }
950:
951: $items[] = $this->parseArrayShapeItem($tokens);
952: $tokens->skipNewLineTokensAndConsumeComments();
953: if (!$tokens->tryConsumeTokenType(Lexer::TOKEN_COMMA)) {
954: $done = true;
955: }
956: if ($tokens->currentTokenType() !== Lexer::TOKEN_COMMENT) {
957: continue;
958: }
959:
960: $tokens->next();
961:
962: } while (!$done);
963:
964: $tokens->skipNewLineTokensAndConsumeComments();
965: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET);
966:
967: if ($sealed) {
968: return Ast\Type\ArrayShapeNode::createSealed($items, $kind);
969: }
970:
971: return Ast\Type\ArrayShapeNode::createUnsealed($items, $unsealedType, $kind);
972: }
973:
974: /** @phpstan-impure */
975: private function parseArrayShapeItem(TokenIterator $tokens): Ast\Type\ArrayShapeItemNode
976: {
977: $startLine = $tokens->currentTokenLine();
978: $startIndex = $tokens->currentTokenIndex();
979:
980: // parse any comments above the item
981: $tokens->skipNewLineTokensAndConsumeComments();
982:
983: try {
984: $tokens->pushSavePoint();
985: $key = $this->parseArrayShapeKey($tokens);
986: $optional = $tokens->tryConsumeTokenType(Lexer::TOKEN_NULLABLE);
987: $tokens->consumeTokenType(Lexer::TOKEN_COLON);
988: $value = $this->parse($tokens);
989:
990: $tokens->dropSavePoint();
991:
992: return $this->enrichWithAttributes(
993: $tokens,
994: new Ast\Type\ArrayShapeItemNode($key, $optional, $value),
995: $startLine,
996: $startIndex,
997: );
998: } catch (ParserException $e) {
999: $tokens->rollback();
1000: $value = $this->parse($tokens);
1001:
1002: return $this->enrichWithAttributes(
1003: $tokens,
1004: new Ast\Type\ArrayShapeItemNode(null, false, $value),
1005: $startLine,
1006: $startIndex,
1007: );
1008: }
1009: }
1010:
1011: /**
1012: * @phpstan-impure
1013: * @return Ast\ConstExpr\ConstExprIntegerNode|Ast\ConstExpr\ConstExprStringNode|Ast\ConstExpr\ConstFetchNode|Ast\Type\IdentifierTypeNode
1014: */
1015: private function parseArrayShapeKey(TokenIterator $tokens)
1016: {
1017: $startIndex = $tokens->currentTokenIndex();
1018: $startLine = $tokens->currentTokenLine();
1019:
1020: if ($tokens->isCurrentTokenType(Lexer::TOKEN_INTEGER)) {
1021: $key = new Ast\ConstExpr\ConstExprIntegerNode(IntegerLiteralNormalizer::normalizeToDecimal($tokens->currentTokenValue()));
1022: $tokens->next();
1023:
1024: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_SINGLE_QUOTED_STRING)) {
1025: $key = new Ast\ConstExpr\ConstExprStringNode(StringUnescaper::unescapeString($tokens->currentTokenValue()), Ast\ConstExpr\ConstExprStringNode::SINGLE_QUOTED);
1026: $tokens->next();
1027:
1028: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_DOUBLE_QUOTED_STRING)) {
1029: $key = new Ast\ConstExpr\ConstExprStringNode(StringUnescaper::unescapeString($tokens->currentTokenValue()), Ast\ConstExpr\ConstExprStringNode::DOUBLE_QUOTED);
1030:
1031: $tokens->next();
1032:
1033: } else {
1034: $identifier = $tokens->currentTokenValue();
1035: $tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
1036:
1037: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_DOUBLE_COLON)) {
1038: $classConstantName = $tokens->currentTokenValue();
1039: $tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
1040:
1041: $key = new Ast\ConstExpr\ConstFetchNode($identifier, $classConstantName);
1042: } else {
1043: $key = new Ast\Type\IdentifierTypeNode($identifier);
1044: }
1045: }
1046:
1047: return $this->enrichWithAttributes(
1048: $tokens,
1049: $key,
1050: $startLine,
1051: $startIndex,
1052: );
1053: }
1054:
1055: /**
1056: * @phpstan-impure
1057: */
1058: private function parseArrayShapeUnsealedType(TokenIterator $tokens): Ast\Type\ArrayShapeUnsealedTypeNode
1059: {
1060: $startLine = $tokens->currentTokenLine();
1061: $startIndex = $tokens->currentTokenIndex();
1062:
1063: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET);
1064: $tokens->skipNewLineTokensAndConsumeComments();
1065:
1066: // a template may be declared by the key, as in ...<K of key-of<Config>, Config[K]>,
1067: // so a declaration has to be followed by the value type
1068: $templateDeclaration = $this->tryParseTemplateDeclaration($tokens);
1069: $valueType = $templateDeclaration ?? $this->parse($tokens);
1070: $tokens->skipNewLineTokensAndConsumeComments();
1071:
1072: $keyType = null;
1073: if ($templateDeclaration !== null) {
1074: $tokens->consumeTokenType(Lexer::TOKEN_COMMA);
1075: $tokens->skipNewLineTokensAndConsumeComments();
1076:
1077: $keyType = $valueType;
1078: $valueType = $this->parse($tokens);
1079: $tokens->skipNewLineTokensAndConsumeComments();
1080: } elseif ($tokens->tryConsumeTokenType(Lexer::TOKEN_COMMA)) {
1081: $tokens->skipNewLineTokensAndConsumeComments();
1082:
1083: $keyType = $valueType;
1084: $valueType = $this->parse($tokens);
1085: $tokens->skipNewLineTokensAndConsumeComments();
1086: }
1087:
1088: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_ANGLE_BRACKET);
1089:
1090: return $this->enrichWithAttributes(
1091: $tokens,
1092: new Ast\Type\ArrayShapeUnsealedTypeNode($valueType, $keyType),
1093: $startLine,
1094: $startIndex,
1095: );
1096: }
1097:
1098: /**
1099: * @phpstan-impure
1100: */
1101: private function parseListShapeUnsealedType(TokenIterator $tokens): Ast\Type\ArrayShapeUnsealedTypeNode
1102: {
1103: $startLine = $tokens->currentTokenLine();
1104: $startIndex = $tokens->currentTokenIndex();
1105:
1106: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_ANGLE_BRACKET);
1107: $tokens->skipNewLineTokensAndConsumeComments();
1108:
1109: $valueType = $this->parse($tokens);
1110: $tokens->skipNewLineTokensAndConsumeComments();
1111:
1112: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_ANGLE_BRACKET);
1113:
1114: return $this->enrichWithAttributes(
1115: $tokens,
1116: new Ast\Type\ArrayShapeUnsealedTypeNode($valueType, null),
1117: $startLine,
1118: $startIndex,
1119: );
1120: }
1121:
1122: /**
1123: * @phpstan-impure
1124: */
1125: private function parseObjectShape(TokenIterator $tokens): Ast\Type\ObjectShapeNode
1126: {
1127: $tokens->consumeTokenType(Lexer::TOKEN_OPEN_CURLY_BRACKET);
1128:
1129: $items = [];
1130:
1131: do {
1132: $tokens->skipNewLineTokensAndConsumeComments();
1133:
1134: if ($tokens->tryConsumeTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET)) {
1135: return new Ast\Type\ObjectShapeNode($items);
1136: }
1137:
1138: $items[] = $this->parseObjectShapeItem($tokens);
1139:
1140: $tokens->skipNewLineTokensAndConsumeComments();
1141: } while ($tokens->tryConsumeTokenType(Lexer::TOKEN_COMMA));
1142:
1143: $tokens->skipNewLineTokensAndConsumeComments();
1144: $tokens->consumeTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET);
1145:
1146: return new Ast\Type\ObjectShapeNode($items);
1147: }
1148:
1149: /** @phpstan-impure */
1150: private function parseObjectShapeItem(TokenIterator $tokens): Ast\Type\ObjectShapeItemNode
1151: {
1152: $startLine = $tokens->currentTokenLine();
1153: $startIndex = $tokens->currentTokenIndex();
1154:
1155: $tokens->skipNewLineTokensAndConsumeComments();
1156:
1157: $key = $this->parseObjectShapeKey($tokens);
1158: $optional = $tokens->tryConsumeTokenType(Lexer::TOKEN_NULLABLE);
1159: $tokens->consumeTokenType(Lexer::TOKEN_COLON);
1160: $value = $this->parse($tokens);
1161:
1162: return $this->enrichWithAttributes(
1163: $tokens,
1164: new Ast\Type\ObjectShapeItemNode($key, $optional, $value),
1165: $startLine,
1166: $startIndex,
1167: );
1168: }
1169:
1170: /**
1171: * @phpstan-impure
1172: * @return Ast\ConstExpr\ConstExprStringNode|Ast\Type\IdentifierTypeNode
1173: */
1174: private function parseObjectShapeKey(TokenIterator $tokens)
1175: {
1176: $startLine = $tokens->currentTokenLine();
1177: $startIndex = $tokens->currentTokenIndex();
1178:
1179: if ($tokens->isCurrentTokenType(Lexer::TOKEN_SINGLE_QUOTED_STRING)) {
1180: $key = new Ast\ConstExpr\ConstExprStringNode(StringUnescaper::unescapeString($tokens->currentTokenValue()), Ast\ConstExpr\ConstExprStringNode::SINGLE_QUOTED);
1181: $tokens->next();
1182:
1183: } elseif ($tokens->isCurrentTokenType(Lexer::TOKEN_DOUBLE_QUOTED_STRING)) {
1184: $key = new Ast\ConstExpr\ConstExprStringNode(StringUnescaper::unescapeString($tokens->currentTokenValue()), Ast\ConstExpr\ConstExprStringNode::DOUBLE_QUOTED);
1185: $tokens->next();
1186:
1187: } else {
1188: $key = new Ast\Type\IdentifierTypeNode($tokens->currentTokenValue());
1189: $tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
1190: }
1191:
1192: return $this->enrichWithAttributes($tokens, $key, $startLine, $startIndex);
1193: }
1194:
1195: }
1196: