-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Swift.g4
1133 lines (862 loc) · 39.1 KB
/
Swift.g4
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
// Downloaded on 2016/03/02 from https://github.com/sleekbyte/tailor/blob/master/src/main/antlr/com/sleekbyte/tailor/antlr/Swift.g4
// https://github.com/apple/swift/blob/master/CHANGELOG.md
/*
* [The "BSD license"]
* Copyright (c) 2014 Terence Parr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Converted from Apple's doc, http://tinyurl.com/n8rkoue, to ANTLR's
* meta-language.
*/
grammar Swift;
@header {
import net.sourceforge.pmd.lang.ast.impl.antlr4.*;
import net.sourceforge.pmd.lang.ast.AstVisitor;
}
@parser::members {
static final AntlrNameDictionary DICO = new SwiftNameDictionary(VOCABULARY, ruleNames);
@Override
protected SwiftTerminalNode createPmdTerminal(ParserRuleContext parent, Token t) {
return new SwiftTerminalNode(t);
}
@Override
protected SwiftErrorNode createPmdError(ParserRuleContext parent, Token t) {
return new SwiftErrorNode(t);
}
}
options {
contextSuperClass = 'SwiftInnerNode';
superClass = 'AntlrGeneratedParserBase<SwiftNode>';
}
topLevel : statements? EOF ;
// Statements
// GRAMMAR OF A STATEMENT
statement
: declaration ';'?
| loopStatement ';'?
| branchStatement ';'?
| labeledStatement
| controlTransferStatement ';'?
| deferStatement ';' ?
| doStatement ':'?
| compilerControlStatement ';'?
| expression ';'? // Keep expression last to handle ambiguity
;
statements : statement+ ;
// GRAMMAR OF A LOOP STATEMENT
loopStatement : forInStatement
| whileStatement
| repeatWhileStatement
;
// GRAMMAR OF A FOR_IN STATEMENT
forInStatement : 'for' 'case'? pattern 'in' expression whereClause? codeBlock ;
// GRAMMAR OF A WHILE STATEMENT
whileStatement : 'while' conditionList codeBlock ;
// GRAMMAR OF A REPEAT WHILE STATEMENT
repeatWhileStatement: 'repeat' codeBlock 'while' expression ;
// GRAMMAR OF A BRANCH STATEMENT
branchStatement : ifStatement | guardStatement | switchStatement ;
// GRAMMAR OF AN IF STATEMENT
ifStatement : 'if' conditionList codeBlock elseClause? ;
elseClause : 'else' codeBlock | 'else' ifStatement ;
// GRAMMAR OF A GUARD STATEMENT
guardStatement : 'guard' conditionList 'else' codeBlock ;
// GRAMMAR OF A SWITCH STATEMENT
switchStatement : 'switch' expression '{' switchCases? '}' ;
switchCases : switchCase+ ;
switchCase : caseLabel statements | defaultLabel statements | caseLabel ';' | defaultLabel ';' ;
caseLabel : 'case' caseItemList ':' ;
caseItemList : caseItem (',' caseItem)* ;
caseItem: pattern whereClause? ;
defaultLabel : 'default' ':' ;
// GRAMMAR OF A LABELED STATEMENT
labeledStatement : statementLabel (loopStatement | ifStatement | switchStatement | doStatement) ;
statementLabel : labelName ':' ;
labelName : identifier ;
// GRAMMAR OF A CONTROL TRANSFER STATEMENT
controlTransferStatement : breakStatement
| continueStatement
| fallthroughStatement
| returnStatement
| throwStatement
;
// GRAMMAR OF A BREAK STATEMENT
breakStatement : 'break' labelName? ;
// GRAMMAR OF A CONTINUE STATEMENT
continueStatement : 'continue' labelName? ;
// GRAMMAR OF A FALLTHROUGH STATEMENT
fallthroughStatement : 'fallthrough' ;
// GRAMMAR OF A RETURN STATEMENT
returnStatement : 'return' expression? ;
// GRAMMAR OF A THROW STATEMENT
throwStatement : 'throw' expression ;
// GRAMMAR OF A DEFER STATEMENT
deferStatement: 'defer' codeBlock ;
// GRAMMAR OF A DO STATEMENT
doStatement: 'do' codeBlock catchClauses? ;
catchClauses: catchClause catchClauses? ;
catchClause: 'catch' pattern? whereClause? codeBlock ;
conditionList : condition (',' condition)* ;
condition: availabilityCondition | caseCondition | optionalBindingCondition | expression ;
caseCondition: 'case' pattern initializer ;
optionalBindingCondition: ('let'|'var') pattern initializer ;
whereClause: 'where' whereExpression ;
whereExpression: expression ;
// GRAMMAR OF AN AVAILABILITY CONDITION
availabilityCondition: '#available' | '#unavailable' '(' availabilityArguments ')' ;
availabilityArguments: availabilityArgument (',' availabilityArguments)* ;
availabilityArgument: platformName platformVersion | '*' ;
platformName: 'iOS' | 'iOSApplicationExtension' | 'OSX' | 'OSXApplicationExtension' | 'watchOS'
| 'watchOSApplicationExtension' | 'tvOS' | 'tvOSApplicationExtension' ;
platformVersion: VersionLiteral | DecimalLiteral | FloatingPointLiteral ; // TODO: Find a way to make this only VersionLiteral
// Generic Parameters and Arguments
// GRAMMAR OF A GENERIC PARAMETER CLAUSE
genericParameterClause : '<' genericParameterList '>' ;
genericParameterList : genericParameter (',' genericParameter)* ;
genericParameter : typeName | typeName ':' typeIdentifier | typeName ':' protocolCompositionType ;
genericWhereClause : 'where' requirementList ;
requirementList : requirement (',' requirement)* ;
requirement : conformanceRequirement | sameTypeRequirement ;
conformanceRequirement : typeIdentifier ':' typeIdentifier | typeIdentifier ':' protocolCompositionType ;
sameTypeRequirement : typeIdentifier '==' sType ;
// GRAMMAR OF A GENERIC ARGUMENT CLAUSE
genericArgumentClause : '<' genericArgumentList '>' ;
genericArgumentList : genericArgument (',' genericArgument)* ;
genericArgument : sType ;
// Declarations
// GRAMMAR OF A DECLARATION
declaration
: importDeclaration ';'?
| constantDeclaration ';'?
| variableDeclaration ';'?
| typealiasDeclaration ';'?
| macroDeclaration ';'?
| functionDeclaration ';'?
| enumDeclaration ';'?
| structDeclaration ';'?
| classDeclaration ';'?
| protocolDeclaration ';'?
| initializerDeclaration ';'?
| deinitializerDeclaration ';'?
| extensionDeclaration ';'?
| subscriptDeclaration ';'?
| operatorDeclaration ';'?
// compiler-control-statement not in Swift Language Reference
| compilerControlStatement ';'?
| precedenceGroupDeclaration ';'?
;
declarations : declaration+ ;
declarationModifiers : declarationModifier+ ;
declarationModifier : 'class' | 'convenience' | 'dynamic' | 'final' | 'infix'
| 'lazy' | 'optional' | 'override' | 'postfix'
| 'prefix' | 'required' | 'static' | 'unowned' | 'unowned' '(' 'safe' ')'
| 'unowned' '(' 'unsafe' ')' | 'weak'
| accessLevelModifier
| mutationModifier ;
accessLevelModifier : 'private' | 'private' '(' 'set' ')'
| 'fileprivate' | 'fileprivate' '(' 'set' ')'
| 'internal' | 'internal' '(' 'set' ')'
| 'public' | 'public' '(' 'set' ')'
| 'open' | 'open' '(' 'set' ')' ;
accessLevelModifiers : accessLevelModifier+ ;
mutationModifier: 'mutating' | 'nonmutating' ;
// GRAMMAR OF A CODE BLOCK
codeBlock : '{' statements? '}' ;
// GRAMMAR OF AN IMPORT DECLARATION
importDeclaration : attributes? 'import' importKind? importPath ;
// Swift Language Reference does not have let
importKind : 'typealias' | 'struct' | 'class' | 'enum' | 'protocol' | 'var' | 'func' | 'let' ;
importPath : importPathIdentifier | importPathIdentifier '.' importPath ;
importPathIdentifier : identifier | operator ;
// GRAMMAR OF A CONSTANT DECLARATION
constantDeclaration : attributes? declarationModifiers? 'let' patternInitializerList ;
patternInitializerList : patternInitializer (',' patternInitializer)* ;
patternInitializer : pattern initializer? ;
initializer : '=' expression ;
// GRAMMAR OF A VARIABLE DECLARATION
variableDeclaration
: variableDeclarationHead variableName typeAnnotation getterSetterBlock
| variableDeclarationHead variableName typeAnnotation getterSetterKeywordBlock
| variableDeclarationHead variableName initializer willSetDidSetBlock
| variableDeclarationHead variableName typeAnnotation initializer? willSetDidSetBlock
// keep this below getter and setter rules for ambiguity reasons
| variableDeclarationHead variableName typeAnnotation codeBlock
| variableDeclarationHead patternInitializerList
;
variableDeclarationHead : attributes? declarationModifiers? 'var' ;
variableName : identifier ;
getterSetterBlock : '{' getterClause setterClause?'}' | '{' setterClause getterClause '}' ;
// declarationModifiers missing in the Swift Language Reference
getterClause : attributes? declarationModifiers? 'get' codeBlock ;
// declarationModifiers missing in the Swift Language Reference
setterClause : attributes? declarationModifiers? 'set' setterName? codeBlock ;
setterName : '(' identifier ')' ;
getterSetterKeywordBlock : '{' getterKeywordClause setterKeywordClause?'}' | '{' setterKeywordClause getterKeywordClause '}' ;
getterKeywordClause : attributes? 'get' ;
setterKeywordClause : attributes? 'set' ;
willSetDidSetBlock : '{' willSetClause didSetClause?'}' | '{' didSetClause willSetClause? '}' ;
willSetClause : attributes? 'willSet' setterName? codeBlock ;
didSetClause : attributes? 'didSet' setterName? codeBlock ;
// GRAMMAR OF A TYPE ALIAS DECLARATION
typealiasDeclaration : typealiasHead typealiasAssignment ;
typealiasHead : attributes? accessLevelModifier? 'typealias' typealiasName genericParameterClause? ;
typealiasName : identifier ;
typealiasAssignment : '=' sType ;
// GRAMMAR OF A MACRO DECLARATION
macroDeclaration: '#' identifier genericArgumentClause? functionCallArgumentClause? ;
// GRAMMAR OF A FUNCTION DECLARATION
/* HACK: functionBody? is intentionally not used to force the parser to try and match a functionBody first
* This can be removed once we figure out how to enforce that statements are either separated by semi colons or new line characters
*/
functionDeclaration : functionHead functionName genericParameterClause? functionSignature genericWhereClause? functionBody
| functionHead functionName genericParameterClause? functionSignature genericWhereClause?
;
functionHead : attributes? declarationModifiers? 'func' ;
functionName : identifier | operator ;
// rethrows is not marked as optional in the Swift Language Reference
functionSignature : parameterClause ('throws' | 'rethrows')? functionResult? ;
functionResult : '->' attributes? sType ;
functionBody : codeBlock ;
parameterClause : '(' ')' | '(' parameterList '...'? ')' ;
parameterList : parameter (',' parameter)* ;
// Parameters don't have attributes in the Swift Language Reference
parameter
: attributes? externalParameterName? localParameterName typeAnnotation defaultArgumentClause?
| attributes? externalParameterName? localParameterName typeAnnotation '...'
;
// Swift Language Reference does not have "keyword" or "_"
externalParameterName : identifier | keyword | '_';
localParameterName : identifier | '_' ;
defaultArgumentClause : '=' expression ;
// GRAMMAR OF AN ENUMERATION DECLARATION
enumDeclaration : attributes? accessLevelModifier? enumDef ;
enumDef: unionStyleEnum | rawValueStyleEnum ;
unionStyleEnum : 'indirect'? 'enum' enumName genericParameterClause? typeInheritanceClause? genericWhereClause? '{' unionStyleEnumMembers?'}' ;
unionStyleEnumMembers : unionStyleEnumMember+ ;
unionStyleEnumMember : declaration | unionStyleEnumCaseClause ';'? | compilerControlStatement ;
unionStyleEnumCaseClause : attributes? 'indirect'? 'case' unionStyleEnumCaseList ;
unionStyleEnumCaseList : unionStyleEnumCase (',' unionStyleEnumCase)* ;
unionStyleEnumCase : enumCaseName tupleType? ;
enumName : identifier ;
enumCaseName : identifier ;
// typeInheritanceClause is not optional in the Swift Language Reference
rawValueStyleEnum : 'enum' enumName genericParameterClause? typeInheritanceClause? genericWhereClause? '{' rawValueStyleEnumMembers?'}' ;
rawValueStyleEnumMembers : rawValueStyleEnumMember+ ;
rawValueStyleEnumMember : declaration | rawValueStyleEnumCaseClause | compilerControlStatement ;
rawValueStyleEnumCaseClause : attributes? 'case' rawValueStyleEnumCaseList ;
rawValueStyleEnumCaseList : rawValueStyleEnumCase (',' rawValueStyleEnumCase)* ;
rawValueStyleEnumCase : enumCaseName rawValueAssignment? ;
rawValueAssignment : '=' literal ;
// GRAMMAR OF A STRUCTURE DECLARATION
structDeclaration : attributes? accessLevelModifier? 'struct' structName genericParameterClause? typeInheritanceClause? genericWhereClause? structBody ;
structName : identifier ;
structBody : '{' structMembers? '}' ;
structMembers: structMember+ ;
structMember: declaration | compilerControlStatement ;
// GRAMMAR OF A CLASS DECLARATION
classDeclaration : attributes? classDeclarationModifiers? 'class' className genericParameterClause? typeInheritanceClause? genericWhereClause? classBody ;
classDeclarationModifiers: accessLevelModifier 'final'? | 'final' accessLevelModifier? ;
className : identifier ;
classBody : '{' classMembers? '}' ;
classMembers: classMember+ ;
classMember: declaration | compilerControlStatement ;
// GRAMMAR OF A PROTOCOL DECLARATION
protocolDeclaration : attributes? accessLevelModifier? 'protocol' protocolName typeInheritanceClause? protocolBody ;
protocolName : identifier ;
protocolBody : '{' protocolMembers? '}' ;
protocolMembers: protocolMember+ ;
protocolMember: protocolMemberDeclaration | compilerControlStatement ;
protocolMemberDeclaration : protocolPropertyDeclaration ';'?
| protocolMethodDeclaration ';'?
| protocolInitializerDeclaration ';'?
| protocolSubscriptDeclaration ';'?
| protocolAssociatedTypeDeclaration ';'?
;
// GRAMMAR OF A PROTOCOL PROPERTY DECLARATION
protocolPropertyDeclaration : variableDeclarationHead variableName typeAnnotation getterSetterKeywordBlock ;
// GRAMMAR OF A PROTOCOL METHOD DECLARATION
protocolMethodDeclaration : functionHead functionName genericParameterClause? functionSignature genericWhereClause? ;
// GRAMMAR OF A PROTOCOL INITIALIZER DECLARATION
protocolInitializerDeclaration : initializerHead genericParameterClause? parameterClause ('throws' | 'rethrows')? genericWhereClause? ;
// GRAMMAR OF A PROTOCOL SUBSCRIPT DECLARATION
protocolSubscriptDeclaration : subscriptHead subscriptResult getterSetterKeywordBlock ;
// GRAMMAR OF A PROTOCOL ASSOCIATED TYPE DECLARATION
protocolAssociatedTypeDeclaration : attributes? accessLevelModifier? 'associatedtype' typealiasName typeInheritanceClause? typealiasAssignment?;
// GRAMMAR OF AN INITIALIZER DECLARATION
initializerDeclaration : initializerHead genericParameterClause? parameterClause ('throws' | 'rethrows')? genericWhereClause? initializerBody ;
initializerHead : attributes? declarationModifiers? 'init' ('?' | '!')? ;
initializerBody : codeBlock ;
// GRAMMAR OF A DEINITIALIZER DECLARATION
deinitializerDeclaration : attributes? 'deinit' codeBlock ;
// GRAMMAR OF AN EXTENSION DECLARATION
extensionDeclaration : attributes? accessLevelModifier? 'extension' typeIdentifier (genericWhereClause | typeInheritanceClause)? extensionBody ;
extensionBody : '{' extensionMembers?'}' ;
extensionMembers: extensionMember+ ;
extensionMember: declaration | compilerControlStatement ;
// GRAMMAR OF A SUBSCRIPT DECLARATION
subscriptDeclaration : subscriptHead subscriptResult getterSetterBlock
| subscriptHead subscriptResult getterSetterKeywordBlock
// most general form of subscript declaration; should be kept at the bottom.
| subscriptHead subscriptResult codeBlock
;
subscriptHead : attributes? declarationModifiers? 'subscript' parameterClause ;
subscriptResult : '->' attributes? sType ;
// GRAMMAR OF AN OPERATOR DECLARATION
operatorDeclaration : prefixOperatorDeclaration | postfixOperatorDeclaration | infixOperatorDeclaration ;
prefixOperatorDeclaration : 'prefix' 'operator' operator ;
postfixOperatorDeclaration : 'postfix' 'operator' operator ;
infixOperatorDeclaration : 'infix' 'operator' operator infixOperatorGroup? ;
infixOperatorGroup: ':' precedenceGroupName ;
// GRAMMAR OF A PRECEDENCE GROUP DECLARATION
precedenceGroupDeclaration: 'precedencegroup' precedenceGroupName '{' precedenceGroupAttributes? '}' ;
precedenceGroupAttributes: precedenceGroupAttribute+;
precedenceGroupAttribute: precedenceGroupRelation | precedenceGroupAssignment | precedenceGroupAssociativity ;
precedenceGroupRelation: ('higherThan' | 'lowerThan') ':' precedenceGroupNames;
precedenceGroupAssignment: 'assignment' ':' booleanLiteral ;
precedenceGroupAssociativity: 'associativity' ':' ('left' | 'right' | 'none') ;
precedenceGroupNames: precedenceGroupName (',' precedenceGroupName)* ;
precedenceGroupName: identifier ;
// Patterns
// GRAMMAR OF A PATTERN
pattern
: wildcardPattern typeAnnotation?
| identifierPattern typeAnnotation?
| valueBindingPattern
| tuplePattern typeAnnotation?
| enumCasePattern
| 'is' sType
| pattern 'as' sType
| expressionPattern
;
// GRAMMAR OF A WILDCARD PATTERN
wildcardPattern : '_' ;
// GRAMMAR OF AN IDENTIFIER PATTERN
identifierPattern : identifier ;
// GRAMMAR OF A VALUE_BINDING PATTERN
valueBindingPattern : 'var' pattern | 'let' pattern ;
// GRAMMAR OF A TUPLE PATTERN
tuplePattern : '(' tuplePatternElementList? ')' ;
tuplePatternElementList : tuplePatternElement (',' tuplePatternElement)* ;
tuplePatternElement : pattern | identifier ':' pattern ;
// GRAMMAR OF AN ENUMERATION CASE PATTERN
// Swift Language Reference has '.' as mandatory
enumCasePattern : typeIdentifier? '.'? enumCaseName tuplePattern? ;
// GRAMMAR OF A TYPE CASTING PATTERN
typeCastingPattern : isPattern | asPattern ;
isPattern : 'is' sType ;
asPattern : pattern 'as' sType ;
// GRAMMAR OF AN EXPRESSION PATTERN
expressionPattern : expression ;
// Attributes
// GRAMMAR OF AN ATTRIBUTE
attribute : '@' attributeName attributeArgumentClause? ;
attributeName : identifier ;
attributeArgumentClause : '(' balancedTokens? ')' ;
attributes : attribute+ ;
// Swift Language Reference does not have ','
balancedTokens : balancedToken+ ;
balancedToken
: '(' balancedTokens? ')'
| '[' balancedTokens? ']'
| '{' balancedTokens? '}'
// VersionLiteral and availabilityArgument are not in the Swift Language Reference
| identifier | expression | contextSensitiveKeyword | literal | operator | VersionLiteral | availabilityArgument
// | Any punctuation except ( , ')' , '[' , ']' , { , or }
// Punctuation is very ambiguous, interpreting punctuation as defined in www.thepunctuationguide.com
| ':' | ';' | ',' | '!' | '<' | '>' | '-' | '\'' | '/' | '...' | '"'
;
// Expressions
// GRAMMAR OF AN EXPRESSION
expression : tryOperator? prefixExpression binaryExpression* ;
prefixExpression
: prefixOperator? postfixExpression ';'?
| inOutExpression
;
/*
expression
: prefixOperator expression
| inOutExpression
| primaryExpression
| expression binaryOperator expression
| expression assignmentOperator expression
| expression conditionalOperator expression
| expression typeCastingOperator
| expression postfixOperator
| expression parenthesizedExpression trailingClosure?
| expression '.' 'init'
| expression '.' DecimalLiteral
| expression '.' identifier genericArgumentClause?
| expression '.' 'self'
| expression '.' 'dynamicType'
| expression '[' expressionList ']'
| expression '!'
| expression '?'
;
*/
// GRAMMAR OF A PREFIX EXPRESSION
inOutExpression : '&' identifier ;
// GRAMMAR OF A TRY EXPRESSION
tryOperator : 'try' ('?' | '!')? ;
// GRAMMAR OF A BINARY EXPRESSION
binaryExpression
: binaryOperator prefixExpression
| assignmentOperator tryOperator? prefixExpression
| conditionalOperator tryOperator? prefixExpression
| typeCastingOperator
;
// GRAMMAR OF AN ASSIGNMENT OPERATOR
assignmentOperator : '=' ;
// GRAMMAR OF A CONDITIONAL OPERATOR
conditionalOperator : '?' tryOperator? expression ':' ;
// GRAMMAR OF A TYPE_CASTING OPERATOR
typeCastingOperator
: 'is' sType
| 'as' '?' sType
| 'as' sType
| 'as' '!' sType
;
// GRAMMAR OF A PRIMARY EXPRESSION
primaryExpression
: (identifier | operator | keyword | contextSensitiveKeyword) genericArgumentClause? // operator, keyword, and contextSensitiveKeyword are not mentioned in the Swift Language Reference
| literalExpression
| selfExpression
| superclassExpression
| closureExpression
| parenthesizedExpression
| tupleExpression
| implicitMemberExpression
// | implicit_member_expression disallow as ambig with explicit member expr in postfix_expression
| wildcardExpression
| selectorExpression
| keyPathExpression
;
// GRAMMAR OF A LITERAL EXPRESSION
literalExpression
: literal
| arrayLiteral
| dictionaryLiteral
| playgroundLiteral
| '#file' | '#line' | '#column' | '#function'
;
arrayLiteral : '[' arrayLiteralItems? ']' ;
arrayLiteralItems : arrayLiteralItem (',' arrayLiteralItem)* ','? ;
arrayLiteralItem : expression ;
dictionaryLiteral : '[' dictionaryLiteralItems ']' | '[' ':' ']' ;
dictionaryLiteralItems : dictionaryLiteralItem (',' dictionaryLiteralItem)* ','? ;
dictionaryLiteralItem : expression ':' expression ;
playgroundLiteral: '#colorLiteral' '(' 'red' ':' expression ',' 'green' ':' expression ',' 'blue' ':' expression ',' 'alpha' ':' expression ')'
| '#fileLiteral' '(' 'resourceName' ':' expression ')'
| '#imageLiteral' '(' 'resourceName' ':' expression ')' ;
// GRAMMAR OF A SELF EXPRESSION
selfExpression
: 'self'
| 'self' '.' identifier // self-method-expression
// Swift Language Reference uses expressionList
| 'self' '[' tupleElementList ']' // self-subscript-expression
| 'self' '.' 'init' // self-initializer-expression
;
// GRAMMAR OF A SUPERCLASS EXPRESSION
superclassExpression
: superclassMethodExpression
| superclassSubscriptExpression
| superclassInitializerExpression
;
superclassMethodExpression : 'super' '.' identifier ;
// Swift Language Reference uses expressionList
superclassSubscriptExpression : 'super' '[' tupleElementList ']' ;
superclassInitializerExpression : 'super' '.' 'init' ;
// GRAMMAR OF A CLOSURE EXPRESSION
closureExpression : '{' closureSignature? statements? '}' ;
closureSignature
: captureList? closureParameterClause 'throws'? functionResult? 'in'
| captureList 'in'
;
closureParameterClause: '(' ')' | '(' closureParameterList ')' | identifierList ;
closureParameterList: closureParameter (',' closureParameterList)* ;
closureParameter: closureParameterName typeAnnotation?
| closureParameterName typeAnnotation '...'
;
// Swift Language Reference does not have "_"
closureParameterName: identifier | '_';
captureList : '[' captureListItems ']' ;
captureListItems: captureListItem (',' captureListItem)* ;
captureListItem: captureSpecifier? expression ;
captureSpecifier : 'weak' | 'unowned' | 'unowned(safe)' | 'unowned(unsafe)' ;
// GRAMMAR OF A IMPLICIT MEMBER EXPRESSION
implicitMemberExpression : '.' identifier ;
// GRAMMAR OF A PARENTHESIZED EXPRESSION
parenthesizedExpression : '(' expression ')' ;
// GRAMMAR OF A TUPLE EXPRESSION
tupleExpression: '(' tupleElementList? ')' ;
tupleElementList: tupleElement (',' tupleElement)* ;
tupleElement: (identifier ':')? expression ;
// GRAMMAR OF A WILDCARD EXPRESSION
wildcardExpression : '_' ;
// GRAMMAR OF A SELECTOR EXPRESSION
selectorExpression
: '#selector' '(' expression ')'
| '#selector' '(' ('getter:' | 'setter:') expression ')'
;
// GRAMMAR OF A KEY PATH EXPRESSION
keyPathExpression
: '#keyPath' '(' expression ')'
| '\\' expression
;
// GRAMMAR OF A POSTFIX EXPRESSION
postfixExpression
: primaryExpression # primary
| postfixExpression postfixOperator # postfixOperation
// Function call with closure expression should always be above a lone parenthesized expression to reduce ambiguity
| postfixExpression functionCallArgumentClause? closureExpression # functionCallWithClosureExpression
| postfixExpression functionCallArgumentClause # functionCallExpression
| postfixExpression '.' 'init' # initializerExpression
| postfixExpression '.' 'init' '(' argumentNames ')' # initializerExpressionWithArguments
// TODO: don't allow '_' here in DecimalLiteral:
| postfixExpression '.' DecimalLiteral # explicitMemberExpression1
| postfixExpression '.' identifier genericArgumentClause? # explicitMemberExpression2
| postfixExpression '.' identifier '(' argumentNames ')' # explicitMemberExpression3
| postfixExpression '.' 'self' # postfixSelfExpression
| 'type' '(' 'of' ':' expression ')' # dynamicTypeExpression
// Swift Language Reference uses expressionList
| postfixExpression '[' tupleElementList ']' # subscriptExpression
| postfixExpression '!' # forcedValueExpression
| postfixExpression '?' # optionalChainingExpression
;
// GRAMMAR OF A FUNCTION CALL EXPRESSION
functionCallArgumentClause: '(' functionCallArgumentList? ')' ;
functionCallArgumentList: functionCallArgument (',' functionCallArgument)* ;
// (expression | operator) is optional to handle selector expressions (see #425 for example)
functionCallArgument: (functionCallIdentifier ':') (expression | operator)?
| (functionCallIdentifier ':')? (expression | operator) ;
// SwiftLanguageReference does not have keyword
functionCallIdentifier: identifier | keyword ;
// GRAMMAR OF AN ARGUMENT NAME
argumentNames : argumentName+ ;
argumentName: (identifier | '_') ':' ; // Swift Language Reference has argumentName → identifier :
//trailing_closure : closure_expression ;
//initializer_expression : postfix_expression '.' 'init' ;
/*
explicitMemberExpression
: postfixExpression '.' DecimalLiteral // TODO: don't allow '_' here in DecimalLiteral
| postfixExpression '.' identifier genericArgumentClause?
| postfixExpression '.' identifier '(' argumentNames ')'
;
*/
//postfix_self_expression : postfix_expression '.' 'self' ;
// GRAMMAR OF A DYNAMIC TYPE EXPRESSION
//dynamic_type_expression : postfix_expression '.' 'dynamicType' ;
// GRAMMAR OF A SUBSCRIPT EXPRESSION
//subscript_expression : postfix_expression '[' expression_list ']' ;
// GRAMMAR OF A FORCED_VALUE EXPRESSION
//forced_value_expression : postfix_expression '!' ;
// GRAMMAR OF AN OPTIONAL_CHAINING EXPRESSION
//optional_chaining_expression : postfix_expression '?' ;
// GRAMMAR OF OPERATORS
// split the operators out into the individual tokens as some of those tokens
// are also referenced individually. For example, type signatures use
// <...>.
operatorHead: '=' | '<' | '>' | '!' | '*' | '&' | '==' | '?' | '-' | '&&' | '||' | '/' | '>=' | '->' | OperatorHead;
operatorCharacter: operatorHead | OperatorCharacter;
operator: operatorHead operatorCharacter*
| '..' (operatorCharacter)*
| '...'
;
// WHITESPACE scariness:
/* http://tinyurl.com/oalzfus
"If an operator has no whitespace on the left but is followed
immediately by a dot (.), it is treated as a postfix unary
operator. As an example, the ++ operator in a++.b is treated as a
postfix unary operator (a++ . b rather than a ++ .b). For the
purposes of these rules, the characters (, [, and { before an
operator, the characters ), ], and } after an operator, and the
characters ,, ;, and : are also considered whitespace.
There is one caveat to the rules above. If the ! or ? operator has no
whitespace on the left, it is treated as a postfix operator,
regardless of whether it has whitespace on the right. To use the ?
operator as syntactic sugar for the Optional type, it must not have
whitespace on the left. To use it in the conditional (? :) operator,
it must have whitespace around both sides."
*/
/**
"If an operator has whitespace around both sides or around neither side,
it is treated as a binary operator. As an example, the + operator in a+b
and a + b is treated as a binary operator."
*/
binaryOperator : operator ;
/**
"If an operator has whitespace on the left side only, it is treated as a
prefix unary operator. As an example, the ++ operator in a ++b is treated
as a prefix unary operator."
*/
prefixOperator : operator ; // only if space on left but not right
/**
"If an operator has whitespace on the right side only, it is treated as a
postfix unary operator. As an example, the ++ operator in a++ b is treated
as a postfix unary operator."
*/
postfixOperator : operator ;
// Types
// GRAMMAR OF A TYPE
sType
: arrayType
| dictionaryType
| functionType
| typeIdentifier
| tupleType
| sType '?' // optional-type
| sType '!' // implicitly-unwrapped-optional-type
| protocolCompositionType
| sType '.' 'Type' | sType '.' 'Protocol' // metatype
| 'Any' | 'Self'
;
functionType: attributes? functionTypeArgumentClause ('throws' | 'rethrows')? '->' sType ;
functionTypeArgumentClause: '(' ')'
| '(' functionTypeArgumentList '...'? ')' ;
functionTypeArgumentList: functionTypeArgument (',' functionTypeArgument)* ;
functionTypeArgument: attributes? 'inout'? sType | argumentLabel typeAnnotation ;
argumentLabel: identifier ;
arrayType: '[' sType ']' ;
dictionaryType: '[' sType ':' sType ']' ;
optionalType: sType '?' ;
implicitlyUnwrappedOptionalType: sType '!' ;
// GRAMMAR OF A TYPE ANNOTATION
typeAnnotation : ':' attributes? 'inout'? sType ;
// GRAMMAR OF A TYPE IDENTIFIER
typeIdentifier
: typeName genericArgumentClause?
| typeName genericArgumentClause? '.' typeIdentifier
;
typeName : identifier ;
// GRAMMAR OF A TUPLE TYPE
tupleType : '(' tupleTypeElementList? ')' ;
tupleTypeElementList : tupleTypeElement (',' tupleTypeElement)* ;
tupleTypeElement : elementName typeAnnotation | sType ;
elementName : identifier ;
// GRAMMAR OF A PROTOCOL COMPOSITION TYPE
protocolCompositionType: protocolIdentifier '&' protocolCompositionContinuation ;
protocolCompositionContinuation: protocolIdentifier | protocolCompositionType ;
protocolIdentifier: typeIdentifier ;
// GRAMMAR OF A METATYPE TYPE
metatypeType : sType '.' 'Type' | sType '.' 'Protocol';
// GRAMMAR OF A TYPE INHERITANCE CLAUSE
typeInheritanceClause : ':' classRequirement ',' typeInheritanceList
| ':' classRequirement
| ':' typeInheritanceList
;
typeInheritanceList : typeIdentifier (',' typeIdentifier)* ;
classRequirement: 'class' ;
// GRAMMAR OF A COMPILER CONTROL STATEMENT
compilerControlStatement: conditionalCompilationBlock | lineControlStatement | warningCompilationStatement ;
// GRAMMAR OF A CONDITIONAL COMPILATION BLOCK
conditionalCompilationBlock: ifDirectiveClause elseifDirectiveClauses? elseDirectiveClause? '#endif' ;
ifDirectiveClause: '#if' compilationCondition statements? ;
elseifDirectiveClauses: elseifDirectiveClause+ ;
elseifDirectiveClause: '#elseif' compilationCondition statements? ;
elseDirectiveClause: '#else' statements? ;
compilationCondition
: platformCondition
| identifier
| booleanLiteral
| '(' compilationCondition ')'
| '!' compilationCondition
| compilationCondition ('&&' | '||') compilationCondition
;
platformCondition
: 'os' '(' operatingSystem ')'
| 'arch' '(' architecture ')'
| 'swift' '(' '>=' swiftVersion ')'
| 'canImport' '(' moduleName ')'
| 'targetEnvironment' '(' 'simulator' ')'
;
operatingSystem: 'OSX' | 'iOS' | 'watchOS' | 'tvOS' ;
architecture: 'i386' | 'x86_64' | 'arm' | 'arm64' ;
swiftVersion: FloatingPointLiteral ;
moduleName: IdentifierCharacters ;
lineControlStatement: '#sourceLocation' '(' 'file' ':' fileName ',' 'line' ':' lineNumber ')'
| '#sourceLocation' '(' ')' ;
lineNumber: integerLiteral ;
fileName: SingleStringLiteral ;
warningCompilationStatement: '#warning' | '#error' '(' SingleStringLiteral ')' ;
// ---------- Lexical Structure -----------
BooleanLiteral: 'true' | 'false' ;
NilLiteral: 'nil' ;
// GRAMMAR OF AN IDENTIFIER
identifier : Identifier | contextSensitiveKeyword | grammarString ;
keyword :
// Keywords used in declarations
'associatedtype' | 'class' | 'deinit' | 'enum' | 'extension' | 'fileprivate' | 'func' | 'import' | 'init' | 'inout'
| 'internal' | 'let' | 'open' | 'operator' | 'private' | 'protocol' | 'public' | 'static' | 'struct' | 'subscript'
| 'typealias' | 'var'
// Keywords used in statements
| 'break' | 'case' | 'continue' | 'default' | 'defer' | 'do' | 'else' | 'fallthrough' | 'for' | 'guard' | 'if' | 'in'
| 'repeat' | 'return' | 'switch' | 'where' | 'while'
// Keywords used in expressions and types
| 'as' | 'Any' | 'catch' | 'dynamicType' | 'is' | 'nil' | 'rethrows' | 'super' | 'self' | 'Self' | 'throw'
| 'throws' | 'try'
| BooleanLiteral
// Keywords used in patterns
| '_'
// Keywords that begin with a number sign (#)
| '#available' | '#unavailable' | '#colorLiteral' | '#column' | '#else' | '#elseif' | '#endif' | '#file' | 'fileLiteral' | '#function'
| '#if' | 'imageLiteral' | '#line' | '#selector'
;
contextSensitiveKeyword :
'associativity' | 'convenience' | 'dynamic' | 'didSet' | 'final' | 'get' | 'infix' | 'indirect' |
'lazy' | 'left' | 'mutating' | 'none' | 'nonmutating' | 'optional' | 'operator' | 'override' | 'postfix' | 'precedence' |
'prefix' | 'Protocol' | 'required' | 'right' | 'set' | 'Type' | 'unowned' | 'weak' | 'willSet' |
'iOS' | 'iOSApplicationExtension' | 'OSX' | 'OSXApplicationExtension' | 'watchOS' | 'x86_64' |
'arm' | 'arm64' | 'i386' | 'os' | 'arch' | 'safe' | 'tvOS' | 'file' | 'line' | 'default' | 'Self' | 'var'
;
grammarString:
'red' | 'blue' | 'green' | 'alpha' | 'resourceName' | 'of' | 'type' ;
OperatorHead
: '/' | '=' | '-' | '+' | '!' | '*' | '%' | '<' | '>' | '&' | '|' | '^' | '~' | '?' | '$'
| [\u00A1-\u00A7]
| [\u00A9\u00AB\u00AC\u00AE]
| [\u00B0-\u00B1\u00B6\u00BB\u00BF\u00D7\u00F7]
| [\u2016-\u2017\u2020-\u2027]
| [\u2030-\u203E]
| [\u2041-\u2053]
| [\u2055-\u205E]
| [\u2190-\u23FF]
| [\u2500-\u2775]
| [\u2794-\u2BFF]
| [\u2E00-\u2E7F]
| [\u3001-\u3003]
| [\u3008-\u3030]
;
OperatorCharacter
: OperatorHead
| [\u0300–\u036F]
| [\u1DC0–\u1DFF]
| [\u20D0–\u20FF]
| [\uFE00–\uFE0F]
| [\uFE20–\uFE2F]