-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathParser.php
4202 lines (3618 loc) · 179 KB
/
Parser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft\PhpParser;
use Closure;
use Microsoft\PhpParser\Node\AnonymousFunctionUseClause;
use Microsoft\PhpParser\Node\ArrayElement;
use Microsoft\PhpParser\Node\Attribute;
use Microsoft\PhpParser\Node\AttributeGroup;
use Microsoft\PhpParser\Node\CaseStatementNode;
use Microsoft\PhpParser\Node\CatchClause;
use Microsoft\PhpParser\Node\ClassBaseClause;
use Microsoft\PhpParser\Node\ClassInterfaceClause;
use Microsoft\PhpParser\Node\ClassMembersNode;
use Microsoft\PhpParser\Node\ConstElement;
use Microsoft\PhpParser\Node\EnumCaseDeclaration;
use Microsoft\PhpParser\Node\EnumMembers;
use Microsoft\PhpParser\Node\Expression;
use Microsoft\PhpParser\Node\Expression\{
AnonymousFunctionCreationExpression,
ArgumentExpression,
ArrayCreationExpression,
ArrowFunctionCreationExpression,
AssignmentExpression,
BinaryExpression,
BracedExpression,
CallExpression,
CastExpression,
CloneExpression,
EmptyIntrinsicExpression,
ErrorControlExpression,
EvalIntrinsicExpression,
ExitIntrinsicExpression,
IssetIntrinsicExpression,
MatchExpression,
MemberAccessExpression,
ParenthesizedExpression,
PrefixUpdateExpression,
PrintIntrinsicExpression,
ListIntrinsicExpression,
ObjectCreationExpression,
ScriptInclusionExpression,
PostfixUpdateExpression,
ScopedPropertyAccessExpression,
SubscriptExpression,
TernaryExpression,
ThrowExpression,
UnaryExpression,
UnaryOpExpression,
Variable,
YieldExpression
};
use Microsoft\PhpParser\Node\StaticVariableDeclaration;
use Microsoft\PhpParser\Node\ClassConstDeclaration;
use Microsoft\PhpParser\Node\DeclareDirective;
use Microsoft\PhpParser\Node\DelimitedList;
use Microsoft\PhpParser\Node\ElseClauseNode;
use Microsoft\PhpParser\Node\ElseIfClauseNode;
use Microsoft\PhpParser\Node\FinallyClause;
use Microsoft\PhpParser\Node\ForeachKey;
use Microsoft\PhpParser\Node\ForeachValue;
use Microsoft\PhpParser\Node\InterfaceBaseClause;
use Microsoft\PhpParser\Node\InterfaceMembers;
use Microsoft\PhpParser\Node\MatchArm;
use Microsoft\PhpParser\Node\MissingDeclaration;
use Microsoft\PhpParser\Node\MissingMemberDeclaration;
use Microsoft\PhpParser\Node\NamespaceAliasingClause;
use Microsoft\PhpParser\Node\NamespaceUseGroupClause;
use Microsoft\PhpParser\Node\NumericLiteral;
use Microsoft\PhpParser\Node\ParenthesizedIntersectionType;
use Microsoft\PhpParser\Node\PropertyDeclaration;
use Microsoft\PhpParser\Node\ReservedWord;
use Microsoft\PhpParser\Node\StringLiteral;
use Microsoft\PhpParser\Node\MethodDeclaration;
use Microsoft\PhpParser\Node\Parameter;
use Microsoft\PhpParser\Node\QualifiedName;
use Microsoft\PhpParser\Node\RelativeSpecifier;
use Microsoft\PhpParser\Node\SourceFileNode;
use Microsoft\PhpParser\Node\Statement\{
ClassDeclaration,
ConstDeclaration,
CompoundStatementNode,
FunctionStaticDeclaration,
GlobalDeclaration,
BreakOrContinueStatement,
DeclareStatement,
DoStatement,
EchoStatement,
EmptyStatement,
EnumDeclaration,
ExpressionStatement,
ForeachStatement,
ForStatement,
FunctionDeclaration,
GotoStatement,
HaltCompilerStatement,
IfStatementNode,
InlineHtml,
InterfaceDeclaration,
NamespaceDefinition,
NamespaceUseDeclaration,
NamedLabelStatement,
ReturnStatement,
SwitchStatementNode,
TraitDeclaration,
TryStatement,
UnsetStatement,
WhileStatement
};
use Microsoft\PhpParser\Node\TraitMembers;
use Microsoft\PhpParser\Node\TraitSelectOrAliasClause;
use Microsoft\PhpParser\Node\TraitUseClause;
use Microsoft\PhpParser\Node\UseVariableName;
use Microsoft\PhpParser\Node\NamespaceUseClause;
class Parser {
/** @var TokenStreamProviderInterface */
private $lexer;
private $currentParseContext;
public $sourceFile;
private $nameOrKeywordOrReservedWordTokens;
private $nameOrReservedWordTokens;
private $nameOrStaticOrReservedWordTokens;
private $reservedWordTokens;
private $keywordTokens;
private $argumentStartTokensSet;
// TODO consider validating parameter and return types on post-parse instead so we can be more permissive
private $parameterTypeDeclarationTokens;
private $returnTypeDeclarationTokens;
public function __construct() {
$this->reservedWordTokens = \array_values(TokenStringMaps::RESERVED_WORDS);
$this->keywordTokens = \array_values(TokenStringMaps::KEYWORDS);
$this->argumentStartTokensSet = \array_flip(TokenStringMaps::KEYWORDS);
unset($this->argumentStartTokensSet[TokenKind::YieldFromKeyword]);
$this->argumentStartTokensSet[TokenKind::DotDotDotToken] = '...';
$this->nameOrKeywordOrReservedWordTokens = \array_merge([TokenKind::Name], $this->keywordTokens, $this->reservedWordTokens);
$this->nameOrReservedWordTokens = \array_merge([TokenKind::Name], $this->reservedWordTokens);
$this->nameOrStaticOrReservedWordTokens = \array_merge([TokenKind::Name, TokenKind::StaticKeyword], $this->reservedWordTokens);
$this->parameterTypeDeclarationTokens =
[TokenKind::ArrayKeyword, TokenKind::CallableKeyword, TokenKind::BoolReservedWord,
TokenKind::FloatReservedWord, TokenKind::IntReservedWord, TokenKind::StringReservedWord,
TokenKind::ObjectReservedWord, TokenKind::NullReservedWord, TokenKind::FalseReservedWord,
TokenKind::TrueReservedWord, TokenKind::IterableReservedWord, TokenKind::MixedReservedWord,
TokenKind::VoidReservedWord, TokenKind::NeverReservedWord]; // TODO update spec
$this->returnTypeDeclarationTokens = \array_merge([TokenKind::StaticKeyword], $this->parameterTypeDeclarationTokens);
}
/**
* This method exists so that it can be overridden in subclasses.
* Any subclass must return a token stream that is equivalent to the contents in $fileContents for this to work properly.
*
* Possible reasons for applications to override the lexer:
*
* - Imitate token stream of a newer/older PHP version (e.g. T_FN is only available in php 7.4)
* - Reuse the result of token_get_all to create a Node again.
* - Reuse the result of token_get_all in a different library.
*/
protected function makeLexer(string $fileContents): TokenStreamProviderInterface
{
return TokenStreamProviderFactory::GetTokenStreamProvider($fileContents);
}
/**
* Generates AST from source file contents. Returns an instance of SourceFileNode, which is always the top-most
* Node-type of the tree.
*
* @param string $fileContents
* @return SourceFileNode
*/
public function parseSourceFile(string $fileContents, string $uri = null) : SourceFileNode {
$this->lexer = $this->makeLexer($fileContents);
$this->reset();
$sourceFile = new SourceFileNode();
$this->sourceFile = $sourceFile;
$sourceFile->fileContents = $fileContents;
$sourceFile->uri = $uri;
$sourceFile->statementList = [];
if ($this->getCurrentToken()->kind !== TokenKind::EndOfFileToken) {
$inlineHTML = $this->parseInlineHtml($sourceFile);
$sourceFile->statementList[] = $inlineHTML;
if ($inlineHTML->echoStatement) {
$sourceFile->statementList[] = $inlineHTML->echoStatement;
$inlineHTML->echoStatement->parent = $sourceFile;
$inlineHTML->echoStatement = null;
}
}
$sourceFile->statementList =
\array_merge($sourceFile->statementList, $this->parseList($sourceFile, ParseContext::SourceElements));
$this->sourceFile->endOfFileToken = $this->eat1(TokenKind::EndOfFileToken);
$this->advanceToken();
$sourceFile->parent = null;
return $sourceFile;
}
private function reset() {
$this->advanceToken();
// Stores the current parse context, which includes the current and enclosing lists.
$this->currentParseContext = 0;
}
/**
* Parse a list of elements for a given ParseContext until a list terminator associated
* with that ParseContext is reached. Additionally abort parsing when an element is reached
* that is invalid in the current context, but valid in an enclosing context. If an element
* is invalid in both current and enclosing contexts, generate a SkippedToken, and continue.
* @param Node $parentNode
* @param int $listParseContext
* @return array
*/
private function parseList($parentNode, int $listParseContext) {
$savedParseContext = $this->currentParseContext;
$this->currentParseContext |= 1 << $listParseContext;
$parseListElementFn = $this->getParseListElementFn($listParseContext);
$nodeArray = [];
while (!$this->isListTerminator($listParseContext)) {
if ($this->isValidListElement($listParseContext, $this->getCurrentToken())) {
$element = $parseListElementFn($parentNode);
$nodeArray[] = $element;
if ($element instanceof Node) {
$element->parent = $parentNode;
if ($element instanceof InlineHtml && $element->echoStatement) {
$nodeArray[] = $element->echoStatement;
$element->echoStatement->parent = $parentNode;
$element->echoStatement = null;
}
}
continue;
}
// Error handling logic:
// The current parse context does not know how to handle the current token,
// so check if the enclosing contexts know what to do. If so, we assume that
// the list has completed parsing, and return to the enclosing context.
//
// Example:
// class A {
// function foo() {
// return;
// // } <- MissingToken (generated when we try to "eat" the closing brace)
//
// public function bar() {
// }
// }
//
// In the case above, the Method ParseContext doesn't know how to handle "public", but
// the Class ParseContext will know what to do with it. So we abort the Method ParseContext,
// and return to the Class ParseContext. This enables us to generate a tree with a single
// class that contains two method nodes, even though there was an error present in the first method.
if ($this->isCurrentTokenValidInEnclosingContexts()) {
break;
}
// None of the enclosing contexts know how to handle the token. Generate a
// SkippedToken, and continue parsing in the current context.
// Example:
// class A {
// function foo() {
// return;
// & // <- SkippedToken
// }
// }
$token = new SkippedToken($this->getCurrentToken());
$nodeArray[] = $token;
$this->advanceToken();
}
$this->currentParseContext = $savedParseContext;
return $nodeArray;
}
private function isListTerminator(int $parseContext) {
$tokenKind = $this->getCurrentToken()->kind;
if ($tokenKind === TokenKind::EndOfFileToken) {
// Being at the end of the file ends all lists.
return true;
}
switch ($parseContext) {
case ParseContext::SourceElements:
return false;
case ParseContext::InterfaceMembers:
case ParseContext::ClassMembers:
case ParseContext::BlockStatements:
case ParseContext::TraitMembers:
case ParseContext::EnumMembers:
return $tokenKind === TokenKind::CloseBraceToken;
case ParseContext::SwitchStatementElements:
return $tokenKind === TokenKind::CloseBraceToken || $tokenKind === TokenKind::EndSwitchKeyword;
case ParseContext::IfClause2Elements:
return
$tokenKind === TokenKind::ElseIfKeyword ||
$tokenKind === TokenKind::ElseKeyword ||
$tokenKind === TokenKind::EndIfKeyword;
case ParseContext::WhileStatementElements:
return $tokenKind === TokenKind::EndWhileKeyword;
case ParseContext::CaseStatementElements:
return
$tokenKind === TokenKind::CaseKeyword ||
$tokenKind === TokenKind::DefaultKeyword;
case ParseContext::ForStatementElements:
return
$tokenKind === TokenKind::EndForKeyword;
case ParseContext::ForeachStatementElements:
return $tokenKind === TokenKind::EndForEachKeyword;
case ParseContext::DeclareStatementElements:
return $tokenKind === TokenKind::EndDeclareKeyword;
}
// TODO warn about unhandled parse context
return false;
}
private function isValidListElement($context, Token $token) {
// TODO
switch ($context) {
case ParseContext::SourceElements:
case ParseContext::BlockStatements:
case ParseContext::IfClause2Elements:
case ParseContext::CaseStatementElements:
case ParseContext::WhileStatementElements:
case ParseContext::ForStatementElements:
case ParseContext::ForeachStatementElements:
case ParseContext::DeclareStatementElements:
return $this->isStatementStart($token);
case ParseContext::ClassMembers:
return $this->isClassMemberDeclarationStart($token);
case ParseContext::TraitMembers:
return $this->isTraitMemberDeclarationStart($token);
case ParseContext::EnumMembers:
return $this->isEnumMemberDeclarationStart($token);
case ParseContext::InterfaceMembers:
return $this->isInterfaceMemberDeclarationStart($token);
case ParseContext::SwitchStatementElements:
return
$token->kind === TokenKind::CaseKeyword ||
$token->kind === TokenKind::DefaultKeyword;
}
return false;
}
private function getParseListElementFn($context) {
switch ($context) {
case ParseContext::SourceElements:
case ParseContext::BlockStatements:
case ParseContext::IfClause2Elements:
case ParseContext::CaseStatementElements:
case ParseContext::WhileStatementElements:
case ParseContext::ForStatementElements:
case ParseContext::ForeachStatementElements:
case ParseContext::DeclareStatementElements:
return $this->parseStatementFn();
case ParseContext::ClassMembers:
return $this->parseClassElementFn();
case ParseContext::TraitMembers:
return $this->parseTraitElementFn();
case ParseContext::InterfaceMembers:
return $this->parseInterfaceElementFn();
case ParseContext::EnumMembers:
return $this->parseEnumElementFn();
case ParseContext::SwitchStatementElements:
return $this->parseCaseOrDefaultStatement();
default:
throw new \Exception("Unrecognized parse context");
}
}
/**
* Aborts parsing list when one of the parent contexts understands something
* @return bool
*/
private function isCurrentTokenValidInEnclosingContexts() {
for ($contextKind = 0; $contextKind < ParseContext::Count; $contextKind++) {
if ($this->isInParseContext($contextKind)) {
if ($this->isValidListElement($contextKind, $this->getCurrentToken()) || $this->isListTerminator($contextKind)) {
return true;
}
}
}
return false;
}
private function isInParseContext($contextToCheck) {
return ($this->currentParseContext & (1 << $contextToCheck));
}
/**
* Retrieve the current token, and check that it's of the expected TokenKind.
* If so, advance and return the token. Otherwise return a MissingToken for
* the expected token.
* @param int|int[] ...$kinds
* @return Token
*/
private function eat(...$kinds) {
$token = $this->token;
if (\is_array($kinds[0])) {
$kinds = $kinds[0];
}
foreach ($kinds as $kind) {
if ($token->kind === $kind) {
$this->token = $this->lexer->scanNextToken();
return $token;
}
}
// TODO include optional grouping for token kinds
return new MissingToken($kinds[0], $token->fullStart);
}
/**
* Retrieve the current token, and check that it's of the kind $kind.
* If so, advance and return the token. Otherwise return a MissingToken for
* the expected token.
*
* This is faster than calling eat() if there is a single token.
*
* @param int $kind
* @return Token
*/
private function eat1($kind) {
$token = $this->token;
if ($token->kind === $kind) {
$this->token = $this->lexer->scanNextToken();
return $token;
}
// TODO include optional grouping for token kinds
return new MissingToken($kind, $token->fullStart);
}
/**
* @param int|int[] ...$kinds (Can provide a single value with a list of kinds, or multiple kinds)
* @return Token|null
*/
private function eatOptional(...$kinds) {
$token = $this->token;
if (\is_array($kinds[0])) {
$kinds = $kinds[0];
}
if (\in_array($token->kind, $kinds)) {
$this->token = $this->lexer->scanNextToken();
return $token;
}
return null;
}
/**
* @param int $kind a single kind
* @return Token|null
*/
private function eatOptional1($kind) {
$token = $this->token;
if ($token->kind === $kind) {
$this->token = $this->lexer->scanNextToken();
return $token;
}
return null;
}
private $token;
private function getCurrentToken() : Token {
return $this->token;
}
private function advanceToken() {
$this->token = $this->lexer->scanNextToken();
}
private function parseStatement($parentNode) {
return ($this->parseStatementFn())($parentNode);
}
private function parseStatementFn() {
return function ($parentNode) {
$token = $this->getCurrentToken();
switch ($token->kind) {
// compound-statement
case TokenKind::OpenBraceToken:
return $this->parseCompoundStatement($parentNode);
// labeled-statement
case TokenKind::Name:
if ($this->lookahead(TokenKind::ColonToken)) {
return $this->parseNamedLabelStatement($parentNode);
}
break;
// selection-statement
case TokenKind::IfKeyword:
return $this->parseIfStatement($parentNode);
case TokenKind::SwitchKeyword:
return $this->parseSwitchStatement($parentNode);
// iteration-statement
case TokenKind::WhileKeyword: // while-statement
return $this->parseWhileStatement($parentNode);
case TokenKind::DoKeyword: // do-statement
return $this->parseDoStatement($parentNode);
case TokenKind::ForKeyword: // for-statement
return $this->parseForStatement($parentNode);
case TokenKind::ForeachKeyword: // foreach-statement
return $this->parseForeachStatement($parentNode);
// jump-statement
case TokenKind::GotoKeyword: // goto-statement
return $this->parseGotoStatement($parentNode);
case TokenKind::ContinueKeyword: // continue-statement
case TokenKind::BreakKeyword: // break-statement
return $this->parseBreakOrContinueStatement($parentNode);
case TokenKind::ReturnKeyword: // return-statement
return $this->parseReturnStatement($parentNode);
// try-statement
case TokenKind::TryKeyword:
return $this->parseTryStatement($parentNode);
// declare-statement
case TokenKind::DeclareKeyword:
return $this->parseDeclareStatement($parentNode);
// attribute before statement or anonymous function
case TokenKind::AttributeToken:
return $this->parseAttributeStatement($parentNode);
// function-declaration
case TokenKind::FunctionKeyword:
// Check that this is not an anonymous-function-creation-expression
if ($this->lookahead($this->nameOrKeywordOrReservedWordTokens) || $this->lookahead(TokenKind::AmpersandToken, $this->nameOrKeywordOrReservedWordTokens)) {
return $this->parseFunctionDeclaration($parentNode);
}
break;
// class-declaration
case TokenKind::FinalKeyword:
case TokenKind::AbstractKeyword:
case TokenKind::ReadonlyKeyword:
// fallthrough
case TokenKind::ClassKeyword:
return $this->parseClassDeclaration($parentNode);
// interface-declaration
case TokenKind::InterfaceKeyword:
return $this->parseInterfaceDeclaration($parentNode);
// namespace-definition
case TokenKind::NamespaceKeyword:
if (!$this->lookahead(TokenKind::BackslashToken)) {
// TODO add error handling for the case where a namespace definition does not occur in the outer-most scope
return $this->parseNamespaceDefinition($parentNode);
}
break;
// namespace-use-declaration
case TokenKind::UseKeyword:
return $this->parseNamespaceUseDeclaration($parentNode);
case TokenKind::SemicolonToken:
return $this->parseEmptyStatement($parentNode);
case TokenKind::EchoKeyword:
return $this->parseEchoStatement($parentNode);
// trait-declaration
case TokenKind::TraitKeyword:
return $this->parseTraitDeclaration($parentNode);
case TokenKind::EnumKeyword:
return $this->parseEnumDeclaration($parentNode);
// global-declaration
case TokenKind::GlobalKeyword:
return $this->parseGlobalDeclaration($parentNode);
// const-declaration
case TokenKind::ConstKeyword:
return $this->parseConstDeclaration($parentNode);
// function-static-declaration
case TokenKind::StaticKeyword:
// Check that this is not an anonymous-function-creation-expression
if (!$this->lookahead([TokenKind::FunctionKeyword, TokenKind::FnKeyword, TokenKind::OpenParenToken, TokenKind::ColonColonToken])) {
return $this->parseFunctionStaticDeclaration($parentNode);
}
break;
case TokenKind::ScriptSectionEndTag:
return $this->parseInlineHtml($parentNode);
case TokenKind::UnsetKeyword:
return $this->parseUnsetStatement($parentNode);
case TokenKind::HaltCompilerKeyword:
if ($parentNode instanceof SourceFileNode) {
return $this->parseHaltCompilerStatement($parentNode);
}
// __halt_compiler is a fatal compile error anywhere other than the top level.
// It won't be seen elsewhere in other programs - warn about the token being unexpected.
$this->advanceToken();
return new SkippedToken($token);
}
$expressionStatement = new ExpressionStatement();
$expressionStatement->parent = $parentNode;
$expressionStatement->expression = $this->parseExpression($expressionStatement, true);
$expressionStatement->semicolon = $this->eatSemicolonOrAbortStatement();
return $expressionStatement;
};
}
private function parseClassElementFn() {
return function ($parentNode) {
$modifiers = $this->parseModifiers();
$token = $this->getCurrentToken();
switch ($token->kind) {
case TokenKind::ConstKeyword:
return $this->parseClassConstDeclaration($parentNode, $modifiers);
case TokenKind::FunctionKeyword:
return $this->parseMethodDeclaration($parentNode, $modifiers);
case TokenKind::QuestionToken:
return $this->parseRemainingPropertyDeclarationOrMissingMemberDeclaration(
$parentNode,
$modifiers,
$this->eat1(TokenKind::QuestionToken)
);
case TokenKind::VariableName:
return $this->parsePropertyDeclaration($parentNode, $modifiers);
case TokenKind::UseKeyword:
return $this->parseTraitUseClause($parentNode);
case TokenKind::AttributeToken:
return $this->parseAttributeStatement($parentNode);
default:
return $this->parseRemainingPropertyDeclarationOrMissingMemberDeclaration($parentNode, $modifiers);
}
};
}
/** @return Token[] */
private function parseClassModifiers(): array {
$modifiers = [];
while ($token = $this->eatOptional(TokenKind::AbstractKeyword, TokenKind::FinalKeyword, TokenKind::ReadonlyKeyword)) {
$modifiers[] = $token;
}
return $modifiers;
}
private function parseClassDeclaration($parentNode) : Node {
$classNode = new ClassDeclaration(); // TODO verify not nested
$classNode->parent = $parentNode;
$classNode->abstractOrFinalModifier = $this->eatOptional(TokenKind::AbstractKeyword, TokenKind::FinalKeyword, TokenKind::ReadonlyKeyword);
$classNode->modifiers = $this->parseClassModifiers();
$classNode->classKeyword = $this->eat1(TokenKind::ClassKeyword);
$classNode->name = $this->eat($this->nameOrReservedWordTokens); // TODO should be any
$classNode->name->kind = TokenKind::Name;
$classNode->classBaseClause = $this->parseClassBaseClause($classNode);
$classNode->classInterfaceClause = $this->parseClassInterfaceClause($classNode);
$classNode->classMembers = $this->parseClassMembers($classNode);
return $classNode;
}
private function parseClassMembers($parentNode) : Node {
$classMembers = new ClassMembersNode();
$classMembers->openBrace = $this->eat1(TokenKind::OpenBraceToken);
$classMembers->classMemberDeclarations = $this->parseList($classMembers, ParseContext::ClassMembers);
$classMembers->closeBrace = $this->eat1(TokenKind::CloseBraceToken);
$classMembers->parent = $parentNode;
return $classMembers;
}
private function parseFunctionDeclaration($parentNode) {
$functionNode = new FunctionDeclaration();
$this->parseFunctionType($functionNode);
$functionNode->parent = $parentNode;
return $functionNode;
}
/**
* @return Node
*/
private function parseAttributeExpression($parentNode) {
$attributeGroups = $this->parseAttributeGroups(null);
// Warn about invalid syntax for attributed declarations
// Lookahead for static, function, or fn for the only type of expressions that can have attributes (anonymous functions)
if (in_array($this->token->kind, [TokenKind::FunctionKeyword, TokenKind::FnKeyword], true) ||
$this->token->kind === TokenKind::StaticKeyword && $this->lookahead([TokenKind::FunctionKeyword, TokenKind::FnKeyword])) {
$expression = $this->parsePrimaryExpression($parentNode);
} else {
// Create a MissingToken so that diagnostics indicate that the attributes did not match up with an expression/declaration.
$expression = new MissingDeclaration();
$expression->parent = $parentNode;
$expression->declaration = new MissingToken(TokenKind::Expression, $this->token->fullStart);
}
if ($expression instanceof AnonymousFunctionCreationExpression ||
$expression instanceof ArrowFunctionCreationExpression ||
$expression instanceof MissingDeclaration) {
$expression->attributes = $attributeGroups;
foreach ($attributeGroups as $attributeGroup) {
$attributeGroup->parent = $expression;
}
}
return $expression;
}
/**
* Precondition: The next token is an AttributeToken
* @return Node
*/
private function parseAttributeStatement($parentNode) {
$attributeGroups = $this->parseAttributeGroups(null);
if ($parentNode instanceof ClassMembersNode) {
// Create a class element or a MissingMemberDeclaration
$statement = $this->parseClassElementFn()($parentNode);
} elseif ($parentNode instanceof TraitMembers) {
// Create a trait element or a MissingMemberDeclaration
$statement = $this->parseTraitElementFn()($parentNode);
} elseif ($parentNode instanceof EnumMembers) {
// Create a enum element or a MissingMemberDeclaration
$statement = $this->parseEnumElementFn()($parentNode);
} elseif ($parentNode instanceof InterfaceMembers) {
// Create an interface element or a MissingMemberDeclaration
$statement = $this->parseInterfaceElementFn()($parentNode);
} else {
// Classlikes, anonymous functions, global functions, and arrow functions can have attributes. Global constants cannot.
if (in_array($this->token->kind, [TokenKind::ClassKeyword, TokenKind::TraitKeyword, TokenKind::InterfaceKeyword, TokenKind::AbstractKeyword, TokenKind::FinalKeyword, TokenKind::FunctionKeyword, TokenKind::FnKeyword, TokenKind::EnumKeyword], true) ||
$this->token->kind === TokenKind::StaticKeyword && $this->lookahead([TokenKind::FunctionKeyword, TokenKind::FnKeyword])) {
$statement = $this->parseStatement($parentNode);
} else {
// Create a MissingToken so that diagnostics indicate that the attributes did not match up with an expression/declaration.
$statement = new MissingDeclaration();
$statement->parent = $parentNode;
$statement->declaration = new MissingToken(TokenKind::Expression, $this->token->fullStart);
}
}
if ($statement instanceof FunctionLike ||
$statement instanceof ClassDeclaration ||
$statement instanceof TraitDeclaration ||
$statement instanceof EnumDeclaration ||
$statement instanceof EnumCaseDeclaration ||
$statement instanceof InterfaceDeclaration ||
$statement instanceof ClassConstDeclaration ||
$statement instanceof PropertyDeclaration ||
$statement instanceof MissingDeclaration ||
$statement instanceof MissingMemberDeclaration) {
$statement->attributes = $attributeGroups;
foreach ($attributeGroups as $attributeGroup) {
$attributeGroup->parent = $statement;
}
}
return $statement;
}
/**
* @param Node|null $parentNode
* @return AttributeGroup[]
*/
private function parseAttributeGroups($parentNode): array
{
$attributeGroups = [];
while ($attributeToken = $this->eatOptional1(TokenKind::AttributeToken)) {
$attributeGroup = new AttributeGroup();
$attributeGroup->startToken = $attributeToken;
$attributeGroup->attributes = $this->parseAttributeElementList($attributeGroup)
?: (new MissingToken(TokenKind::Name, $this->token->fullStart));
$attributeGroup->endToken = $this->eat1(TokenKind::CloseBracketToken);
$attributeGroup->parent = $parentNode;
$attributeGroups[] = $attributeGroup;
}
return $attributeGroups;
}
/**
* @return DelimitedList\AttributeElementList
*/
private function parseAttributeElementList(AttributeGroup $parentNode) {
return $this->parseDelimitedList(
DelimitedList\AttributeElementList::class,
TokenKind::CommaToken,
$this->isQualifiedNameStartFn(),
$this->parseAttributeFn(),
$parentNode,
false);
}
private function parseAttributeFn()
{
return function ($parentNode): Attribute {
$attribute = new Attribute();
$attribute->parent = $parentNode;
$attribute->name = $this->parseQualifiedName($attribute);
$attribute->openParen = $this->eatOptional1(TokenKind::OpenParenToken);
if ($attribute->openParen) {
$attribute->argumentExpressionList = $this->parseArgumentExpressionList($attribute);
$attribute->closeParen = $this->eat1(TokenKind::CloseParenToken);
}
return $attribute;
};
}
private function parseMethodDeclaration($parentNode, $modifiers) {
$methodDeclaration = new MethodDeclaration();
$methodDeclaration->modifiers = $modifiers;
$this->parseFunctionType($methodDeclaration, true);
$methodDeclaration->parent = $parentNode;
return $methodDeclaration;
}
private function parseParameterFn() {
return function ($parentNode) {
$parameter = new Parameter();
$parameter->parent = $parentNode;
if ($this->token->kind === TokenKind::AttributeToken) {
$parameter->attributes = $this->parseAttributeGroups($parameter);
}
// Note that parameter modifiers are allowed to be repeated by the parser in php 8.1 (it is a compiler error)
//
// TODO: Remove the visibilityToken in a future backwards incompatible release
$parameter->visibilityToken = $this->eatOptional([TokenKind::PublicKeyword, TokenKind::ProtectedKeyword, TokenKind::PrivateKeyword]);
$parameter->modifiers = $this->parseParameterModifiers() ?: null;
$parameter->questionToken = $this->eatOptional1(TokenKind::QuestionToken);
$parameter->typeDeclarationList = $this->tryParseParameterTypeDeclarationList($parameter);
if ($parameter->typeDeclarationList) {
$children = $parameter->typeDeclarationList->children;
if (end($children) instanceof MissingToken && ($children[\count($children) - 2]->kind ?? null) === TokenKind::AmpersandToken) {
array_pop($parameter->typeDeclarationList->children);
$parameter->byRefToken = array_pop($parameter->typeDeclarationList->children);
}
} elseif ($parameter->questionToken) {
// TODO ParameterType?
$parameter->typeDeclarationList = new MissingToken(TokenKind::PropertyType, $this->token->fullStart);
}
if (!$parameter->byRefToken) {
$parameter->byRefToken = $this->eatOptional1(TokenKind::AmpersandToken);
}
// TODO add post-parse rule that prevents assignment
// TODO add post-parse rule that requires only last parameter be variadic
$parameter->dotDotDotToken = $this->eatOptional1(TokenKind::DotDotDotToken);
$parameter->variableName = $this->eat1(TokenKind::VariableName);
$parameter->equalsToken = $this->eatOptional1(TokenKind::EqualsToken);
if ($parameter->equalsToken !== null) {
// TODO add post-parse rule that checks for invalid assignments
$parameter->default = $this->parseExpression($parameter);
}
return $parameter;
};
}
/**
* @param ArrowFunctionCreationExpression|AnonymousFunctionCreationExpression|FunctionDeclaration|MethodDeclaration $parentNode a node with FunctionReturnType trait
*/
private function parseAndSetReturnTypeDeclarationList($parentNode) {
$returnTypeList = $this->parseReturnTypeDeclarationList($parentNode);
if (!$returnTypeList) {
$parentNode->returnTypeList = new MissingToken(TokenKind::ReturnType, $this->token->fullStart);
return;
}
$parentNode->returnTypeList = $returnTypeList;
}
const TYPE_DELIMITER_TOKENS = [
TokenKind::BarToken,
TokenKind::AmpersandToken,
];
/**
* Attempt to parse the return type after the `:` and optional `?` token.
*
* TODO: Consider changing the return type to a new class TypeList in a future major release?
* ParenthesizedIntersectionType is not a qualified name.
* @return DelimitedList\QualifiedNameList|null
*/
private function parseReturnTypeDeclarationList($parentNode) {
return $this->parseUnionTypeDeclarationList(
$parentNode,
function ($token): bool {
return \in_array($token->kind, $this->returnTypeDeclarationTokens, true) ||
$this->isQualifiedNameStart($token);
},
function ($parentNode) {
return $this->parseReturnTypeDeclaration($parentNode);
},
TokenKind::ReturnType
);
}
private function parseReturnTypeDeclaration($parentNode) {
return $this->eatOptional($this->returnTypeDeclarationTokens)
?? $this->parseQualifiedName($parentNode);
}
private function tryParseParameterTypeDeclaration($parentNode) {
$parameterTypeDeclaration =
$this->eatOptional($this->parameterTypeDeclarationTokens) ?? $this->parseQualifiedName($parentNode);
return $parameterTypeDeclaration;
}
/**
* Parse a union type such as A, A|B, A&B, A|(B&C), rejecting invalid syntax combinations.
*
* @param Node $parentNode
* @param Closure(Token):bool $isTypeStart
* @param Closure(Node):(Node|Token|null) $parseType
* @param int $expectedTypeKind expected kind for token type
* @return DelimitedList\QualifiedNameList|null
*/
private function parseUnionTypeDeclarationList($parentNode, Closure $isTypeStart, Closure $parseType, int $expectedTypeKind) {
$result = new DelimitedList\QualifiedNameList();
$token = $this->getCurrentToken();
$delimiter = self::TYPE_DELIMITER_TOKENS;
do {
if ($token->kind === TokenKind::OpenParenToken || $isTypeStart($token)) {
// Forbid mixing A&(B&C) if '&' was already seen
$openParen = in_array(TokenKind::BarToken, $delimiter, true)
? $this->eatOptional(TokenKind::OpenParenToken)
: null;
if ($openParen) {
$element = $this->parseParenthesizedIntersectionType($result, $openParen, $isTypeStart, $parseType);
// Forbid mixing (A&B)&C by forbidding `&` separator after a parenthesized intersection type.
$delimiter = [TokenKind::BarToken];
} else {
$element = $parseType($result);
}
$result->addElement($element);
} else {
break;
}
$delimiterToken = $this->eatOptional($delimiter);
if ($delimiterToken !== null) {
$result->addElement($delimiterToken);
$delimiter = [$delimiterToken->kind];
}
$token = $this->getCurrentToken();
} while ($delimiterToken !== null);
$result->parent = $parentNode;
if ($result->children === null) {
return null;
}
if (in_array(end($result->children)->kind ?? null, $delimiter, true)) {
// Add a MissingToken so that this will warn about `function () : T| {}`
$result->children[] = new MissingToken($expectedTypeKind, $this->token->fullStart);
} elseif (count($result->children) === 1 && $result->children[0] instanceof ParenthesizedIntersectionType) {
// dnf types with parenthesized intersection types are a union type of at least 2 types.
$result->children[] = new MissingToken(TokenKind::BarToken, $this->token->fullStart);
}
return $result;
}
/**
* @param Node $parentNode
* @param Token $openParen
* @param Closure(Token):bool $isTypeStart
* @param Closure(Node):(Node|Token|null) $parseType
*/
private function parseParenthesizedIntersectionType($parentNode, Token $openParen, Closure $isTypeStart, Closure $parseType): ParenthesizedIntersectionType {
$node = new ParenthesizedIntersectionType();
$node->parent = $parentNode;
$node->openParen = $openParen;
$node->children = $this->parseDelimitedList(
DelimitedList\QualifiedNameList::class,
TokenKind::AmpersandToken,
$isTypeStart,
$parseType,