Repository navigation
Expand file tree
/
Copy pathjava.iggy
More file actions
1050 lines (858 loc) · 32.5 KB
/
Copy pathjava.iggy
File metadata and controls
1050 lines (858 loc) · 32.5 KB
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
grammar Java
CompilationUnit
= OrdinaryCompilationUnit
| CompactCompilationUnit
| ModularCompilationUnit
OrdinaryCompilationUnit
= PackageDeclaration? ImportDeclaration* TypeDeclaration*
CompactCompilationUnit
= ImportDeclaration* ClassMemberDeclarationNoMethod* MethodDeclaration
ClassMemberDeclaration*
ClassMemberDeclarationNoMethod
= FieldDeclaration
| ClassDeclaration
| InterfaceDeclaration
| ";"
ClassMemberDeclaration
= ClassMemberDeclarationNoMethod
| MethodDeclaration
ModularCompilationUnit
= ImportDeclaration* ModuleDeclaration
ModuleDeclaration
= Annotation* "open"? "module" QualifiedIdentifier "{" ModuleDirective* "}"
ModuleDirective
= "requires" RequiresModifier* QualifiedIdentifier ";" #Requires
| "exports" QualifiedIdentifier ("to" { QualifiedIdentifier "," }+)? ";" #Exports
| "opens" QualifiedIdentifier ("to" { QualifiedIdentifier "," }+)? ";" #Opens
| "uses" TypeName ";" #Uses
| "provides" TypeName "with" { TypeName "," }+ ";" #Provides
RequiresModifier
= "transitive"
| "static"
PackageDeclaration
= Annotation* "package" QualifiedIdentifier ";"
// JLS §7.5 defines five import forms, which differ in what each may name. A
// TypeName ends in a TypeIdentifier, so `import yield;` is not valid. The qualifier of
// a non-static on-demand import and the member of a single static import are ordinary
// identifiers, so `import yield.*;` and `import static A.yield;` are valid.
ImportDeclaration
= "import" TypeName ";" #SingleType
| "import" QualifiedIdentifier "." "*" ";" #TypeImportOnDemand
| "import" "static" TypeName "." Identifier ";" #SingleStaticImport
| "import" "static" TypeName "." "*" ";" #StaticImportOnDemand
| "import" "module" QualifiedIdentifier ";" #SingleModuleImport
TypeDeclaration
= ClassDeclaration
| InterfaceDeclaration
| ";"
ClassDeclaration
= NormalClassDeclaration
| EnumDeclaration
| RecordDeclaration
NormalClassDeclaration
= ClassModifier* "class" TypeIdentifier TypeParameters? ("extends" ClassType)?
("implements" ClassTypeList)? ("permits" { TypeName "," }+)? ClassBody
EnumDeclaration
= ClassModifier* "enum" TypeIdentifier ("implements" ClassTypeList)? EnumBody
RecordDeclaration
= ClassModifier* "record" TypeIdentifier TypeParameters? RecordHeader
("implements" ClassTypeList)? RecordBody
RecordHeader
= "(" RecordComponentList? ")"
RecordComponentList
= { RecordComponent "," }+
RecordComponent
= Annotation* UnannType Identifier
| VariableArityRecordComponent
VariableArityRecordComponent
= Annotation* UnannType Annotation* "..." Identifier
RecordBody
= "{" RecordBodyDeclaration* "}"
RecordBodyDeclaration
= ClassBodyDeclaration
| CompactConstructorDeclaration
CompactConstructorDeclaration
= ConstructorModifier* TypeIdentifier ConstructorBody
InterfaceDeclaration
= NormalInterfaceDeclaration
| AnnotationTypeDeclaration
NormalInterfaceDeclaration
= InterfaceModifier* "interface" TypeIdentifier TypeParameters?
("extends" ClassTypeList)? ("permits" { TypeName "," }+)? InterfaceBody
AnnotationTypeDeclaration
= InterfaceModifier* "@" "interface" TypeIdentifier AnnotationTypeBody
ClassBody
= "{" ClassBodyDeclaration* "}"
ClassBodyDeclaration
= Initializer
| ConstructorDeclaration
| FieldDeclaration
| MethodDeclaration
| ClassDeclaration
| InterfaceDeclaration
| ";"
MethodDeclaration
= MethodModifier* (TypeParameters Annotation*)? Result MethodDeclarator
Throws? MethodBody
MethodDeclarator
= Identifier "(" FormalParameterList? ")" (Annotation* "[" "]")*
FormalParameterList
= ReceiverParameter ("," { FormalParameter "," }+)?
| { FormalParameter "," }+
FormalParameter
= VariableModifier* UnannType VariableDeclaratorId
| VariableArityParameter
VariableArityParameter
= VariableModifier* UnannType Annotation* "..." Identifier
ReceiverParameter
= Annotation* UnannType (Identifier ".")? "this"
Result
= UnannType
| "void"
Throws
= "throws" { ClassType "," }+
MethodBody
= Block
| ";"
ConstructorDeclaration
= ConstructorModifier* TypeParameters? TypeIdentifier "(" FormalParameterList?
")" Throws? ConstructorBody
ConstructorBody
= "{" (BlockStatement* ConstructorInvocation)? BlockStatement* "}"
// JLS §8.8.7.1 allows an expression name or a primary expression before `.super`. The
// grammar uses Primary, which is narrower than the JLS primary expressions: method
// invocation, field access, array access, and instance creation are alternatives of
// Expression here. So `outer.super()`, `Outer.this.super()`, and `(a.b).super()` are
// valid, while `holder.outer.super()`, `outer().super()`, and `new Outer().super()` are
// not. Restricting Expression to the JLS primary expressions needs a way to admit only
// the named alternatives of a nonterminal, which Iggy does not have.
ConstructorInvocation
= constructorInvocation:NonWildTypeArguments? "this" Arguments ";"
| superConstructorInvocation:(Primary ".")? NonWildTypeArguments? "super"
Arguments ";"
TypeList
= { Type "," }+
ClassTypeList
= { ClassType "," }+
TypeParameters
= "<" { TypeParameter "," }+ ">"
TypeParameter
= Annotation* TypeIdentifier TypeBound?
TypeBound
= "extends" ReferenceType ("&" ReferenceType)*
Initializer
= "static"? Block
EnumBody
= "{" { EnumConstant "," }* ","? EnumBodyDeclarations? "}"
EnumConstant
= Annotation* Identifier Arguments? ClassBody?
Arguments
= "(" { Expression "," }* ")"
EnumBodyDeclarations
= ";" ClassBodyDeclaration*
Block
= "{" BlockStatement* "}"
BlockStatement
= LocalVariableDeclarationStatement
| ClassDeclaration
| NormalInterfaceDeclaration
| Statement
LocalVariableDeclarationStatement
= VariableModifier* LocalVariableType { VariableDeclarator "," }+ ";"
LocalVariableType
= UnannType
| "var"
FieldDeclaration
= FieldModifier* UnannType { VariableDeclarator "," }+ ";"
VariableDeclarator
= VariableDeclaratorId ("=" VariableInitializer)?
VariableDeclaratorId
= Identifier (Annotation* "[" "]")*
| "_"
VariableInitializer
= ArrayInitializer
| Expression
ArrayInitializer
= "{" { VariableInitializer "," }* ","? "}"
Annotation
= "@" TypeName Values?
Values
= "(" AnnotationElement? ")"
AnnotationElement
= { ElementValuePair "," }+
| { ElementValue "," }+
ElementValuePair
= Identifier "=" ElementValue
ElementValue
// JLS defines ElementValue as a ConditionalExpression, which cannot be an assignment or
// a lambda expression at the top level. The grammar uses Expression!Assignment!Lambda
// for the same restriction.
// !Assignment `@A(x = y)` is parsed as an ElementValuePair, setting the element `x`
// to `y`, and not as a single ElementValue holding the assignment
// `x = y`.
// !Lambda `@A(x -> x)` is not valid.
= Expression!Assignment!Lambda
| Annotation
| ElementValueArrayInitializer
ElementValueArrayInitializer
= "{" { ElementValue "," }* ","? "}"
InterfaceBody
= "{" InterfaceMemberDeclaration* "}"
InterfaceMemberDeclaration
= ConstantDeclaration
| InterfaceMethodDeclaration
| ClassDeclaration
| InterfaceDeclaration
| ";"
ConstantDeclaration
= ConstantModifier* UnannType { VariableDeclarator "," }+ ";"
InterfaceMethodDeclaration
= InterfaceMethodModifier* (TypeParameters Annotation*)? Result
MethodDeclarator Throws? (Block | ";")
AnnotationTypeBody
= "{" AnnotationTypeElementDeclaration* "}"
AnnotationTypeElementDeclaration
= AnnotationMethodDeclaration
| ConstantDeclaration
| ClassDeclaration
| InterfaceDeclaration
| ";"
AnnotationMethodDeclaration
= InterfaceMethodModifier* UnannType Identifier "(" ")" (Annotation* "[" "]")*
DefaultValue? ";"
DefaultValue
= "default" ElementValue
ClassModifier
= Annotation
| "public"
| "protected"
| "private"
| "abstract"
| "static"
| "final"
| "sealed"
| NonSealed
| "strictfp"
ConstructorModifier
= Annotation
| "public"
| "protected"
| "private"
InterfaceModifier
= Annotation
| "public"
| "protected"
| "private"
| "abstract"
| "static"
| "sealed"
| NonSealed
| "strictfp"
ConstantModifier
= Annotation
| "public"
| "static"
| "final"
InterfaceMethodModifier
= Annotation
| "public"
| "abstract"
| "default"
| "static"
| "strictfp"
| "private"
FieldModifier
= Annotation
| "public"
| "protected"
| "private"
| "static"
| "final"
| "transient"
| "volatile"
MethodModifier
= Annotation
| "public"
| "protected"
| "private"
| "abstract"
| "static"
| "final"
| "synchronized"
| "native"
| "strictfp"
VariableModifier
= Annotation
| "final"
Statement
= Block #Block
| ";" #Empty
| StatementExpression ";" #Expression
| "assert" Expression (":" Expression)? ";" #Assert
| "switch" "(" Expression ")" SwitchBlock #Switch
| "do" Statement "while" "(" Expression ")" ";" #Do
| "break" Identifier? ";" #Break
| "continue" Identifier? ";" #Continue
| "return" Expression? ";" #Return
| "synchronized" "(" Expression ")" Block #Synchronized
| "throw" Expression ";" #Throw
| "yield" Expression ";" #Yield
| "try" Block CatchClause+ #Try
| "try" Block CatchClause* Finally #TryFinally
| "try" ResourceSpecification Block CatchClause* Finally? #TryWithResourcesStmt
| Identifier ":" Statement #Label
| "if" "(" Expression ")" Statement !>>> Else #If
| "if" "(" Expression ")" Statement Else Statement #IfElse
| "while" "(" Expression ")" Statement #While
| "for" "(" ForControl ")" Statement #For
StatementExpression
// JLS defines StatementExpression as an assignment, an increment or decrement, a method
// invocation, or a class instance creation. The grammar uses Expression with three
// exclusions instead. The rule is broader than JLS: `1;` and `a * b;` are valid here.
// The exclusions remove the ambiguities that Expression would otherwise cause:
// !Comparison `Map<K> m;` is parsed as a LocalVariableDeclarationStatement and
// not as an expression statement with the comparisons
// `(Map < K) > m`.
// !SwitchExpression `switch (d) { case 1: f(); };` is parsed as a switch statement
// followed by an empty statement, and not as an expression
// statement with a switch expression.
// !Additive `yield -1;` is parsed as a yield statement of `-1` and not as an
// expression statement with the subtraction `yield - 1`.
= Expression!Comparison!SwitchExpression!Additive
SwitchBlock
= "{" SwitchRule+ "}" #Rules
| "{" SwitchBlockStatementGroup* (SwitchLabel ":")* "}" #Groups
SwitchRule
= SwitchLabel "->" Expression ";" #Expression
| SwitchLabel "->" Block #Block
| SwitchLabel "->" "throw" Expression ";" #Throw
SwitchBlockStatementGroup
= (SwitchLabel ":")+ BlockStatement+
// JLS §14.11.1 writes the null label as `case null [, default]`. A CaseConstant can also
// be `null`, so `case null` is ambiguous: it is both a constant label and a null label.
// The grammar deliberately makes `, default` required in its NullDefault alternative, so
// that `case null` cannot be parsed as a NullDefault label and is parsed only as a Case
// label.
SwitchLabel
= "case" { CaseConstant "," }+ #Case
| "case" NullLiteral "," "default" #NullDefault
| "case" { Pattern "," }+ Guard? #Pattern
| "default" #Default
CaseConstant
// JLS 25 defines CaseConstant as a ConditionalExpression, which cannot be an assignment
// or a lambda expression at the top level. The grammar uses Expression!Lambda!Assignment
// for the same restriction. A lambda can still occur inside a constant, as the operand
// of a reference cast or the third operand of a conditional. The Lambda alternative of
// Expression resolves the ambiguities that such a lambda causes.
// !Lambda `case x -> y:` is not valid.
// !Assignment `case a = 1:` is not valid.
// !Comparison `case Map<K, V> m` should be parsed as `case (Map<K, V> m)`,
// i.e., a type pattern, not as the two case constants in
// `case (Map < K), (V > m)`. A comparison is never a valid case
// constant: it has type boolean, and JLS 25 §14.11.1 allows a
// constant only for a selector of type char, byte, short, int,
// Character, Byte, Short, Integer, or String.
// !MethodInvocation `case Foo()` should be parsed as a record pattern, i.e., the
// record `Foo` deconstructed with no components, not as the
// constant `Foo()`, a call of a method named Foo. JLS §14.11.1
// requires a case constant to be a constant expression or the
// name of an enum constant, and a method call is neither.
// !FieldAccess `case a.Foo()` should be parsed as a record pattern of the type
// `a.Foo`, not as the constant `a.Foo()`, a call of Foo on `a`.
// A field access is not a constant expression either, except for
// a qualified name such as `Color.RED` (§15.29). A qualified name
// is valid through the QualifiedName alternative.
= Expression!Lambda!Assignment!Comparison!MethodInvocation!FieldAccess
| (Identifier ".")+ Identifier #QualifiedName
Guard
= "when" Expression
ForControl
= ForInit? ";" Expression? ";" ForUpdate? #Traditional
| VariableModifier* LocalVariableType VariableDeclaratorId ":" Expression #Enhanced
CatchClause
= "catch" "(" VariableModifier* CatchType VariableDeclaratorId ")" Block
CatchType
= UnannClassType ("|" ClassType)*
Finally
= "finally" Block
ResourceSpecification
= "(" { Resource ";" }+ ";"? ")"
Resource
= VariableModifier* (UnannReferenceType | "var") VariableDeclaratorId "="
Expression
| QualifiedIdentifier
| "this" "." Identifier
ForInit
= expressions:{ StatementExpression "," }+
| variableDecl:VariableModifier* LocalVariableType { VariableDeclarator "," }+
ForUpdate
= { Expression "," }+
Expression
= Primary #Primary
| "switch" "(" Expression ")" SwitchBlock #SwitchExpression
| MethodInvocation #MethodInvocation
| MarkedClassType "::" TypeArguments? Identifier #TypeMethodRef
| ClassType "::" TypeArguments? "new" #ConstructorRef
| ArrayType "::" "new" #ArrayConstructorRef
| ArrayType "::" TypeArguments? Identifier #ArrayMethodRef
| "super" "::" TypeArguments? Identifier #SuperMethodRef
| TypeName "." "super" "::" TypeArguments? Identifier #QualifiedSuperMethodRef
| "new" (ClassInstanceCreationExpression | ArrayCreationExpression) #New
// !InstanceOf The exclusion covers two cases:
// - In FieldAccess, a disambiguation. `a instanceof Foo.Bar`
// should be parsed as `a instanceof (Foo.Bar)`, i.e., one
// InstanceOf over the qualified type `Foo.Bar`, not as
// `(a instanceof Foo).Bar`.
// - In the other three alternatives below, a language reduction.
// JLS §19 makes InstanceofExpression a RelationalExpression,
// so a postfix operator cannot follow it. `a instanceof Foo[0]`
// and `a instanceof Foo f++` are not valid.
// !SwitchExpression A language reduction, not a disambiguation. JLS §19 makes
// SwitchExpression an alternative of UnaryExpressionNotPlusMinus
// rather than of Primary or PostfixExpression, so a postfix
// operator cannot follow a switch expression:
// `switch (d) { ... }.f` is not valid, and
// `(switch (d) { ... }).f` is, because a parenthesized expression
// is a Primary. The exclusion applies to all four alternatives
// below.
> Expression!InstanceOf!SwitchExpression "." Selector #FieldAccess
| Expression!InstanceOf!SwitchExpression "[" Expression "]" #ArrayAccess
| Expression!InstanceOf!SwitchExpression ("++" | "--") #Postfix
| Expression!InstanceOf!SwitchExpression "::" TypeArguments? Identifier #MethodRef
// !Lambda JLS §15.15 to §15.24 take the operands of the unary and binary operators
// from expression levels that do not include a lambda, so `!x -> y` and
// `a + x -> y` are not valid. The exclusion applies to the operand of the
// three alternatives below and to the right operand of every binary operator.
// A reference cast, the third operand of a conditional, and the right side of
// an assignment take a lambda in JLS, so they keep it.
> ("+" !>> Plus | "-" !>> Minus | "++" | "--") Expression!Lambda #Prefix
| ("!" | "~") Expression!Lambda #Complement
| "(" PrimitiveType ")" Expression!Lambda #PrimitiveCast
// !Prefix `(a) - b` should be parsed as `((a) - b)`, i.e., a subtraction, not as
// `((a) (-b))`, a reference cast of `-b`. JLS §15.16 rules out the cast: a
// reference cast takes a unary expression that is not prefixed by + or -.
// The Complement alternative is untouched, so `(Integer) ~x` is still a
// cast.
| "(" { ReferenceType "&" }+ ")" Expression!Prefix #RefCast
> left Expression ("*" | "/" | "%") Expression!Lambda
> left Expression ("+" | "-") !>> Plus !>> Minus Expression!Lambda #Additive
> left Expression ("<<" | ">>" | ">>>") Expression!Lambda
// !InstanceOf The exclusion covers two cases:
// - A disambiguation. `o instanceof List<T> list` should be parsed as
// `o instanceof (List<T> list)`, i.e., an InstanceOf with a type
// pattern, not as the comparisons `((o instanceof List) < T) > list`.
// JLS §15.20 derives both.
// - A language reduction. `a instanceof B < c` is not valid. JLS syntax
// allows it, but it never compiles: the operands of a comparison must
// be numeric (§15.20.1), and an instanceof expression has type boolean.
> left Expression!InstanceOf ("<" | ">" | "<=" | ">=") Expression!Lambda #Comparison
> Expression "instanceof" (ReferenceType | Pattern) #InstanceOf
> left Expression ("==" | "!=") Expression!Lambda
> left Expression "&" Expression!Lambda
> left Expression "^" Expression!Lambda
> left Expression "|" Expression!Lambda
> left Expression "&&" Expression!Lambda
> left Expression "||" Expression!Lambda
> right Expression "?" Expression ":" Expression #Conditional
// JLS §15.26 takes the left side of an assignment from expression names, field
// accesses, and array accesses. The grammar uses Expression with two exclusions
// instead. The rule is broader than JLS: `1 = x` and `a + b = c` are valid here.
// !Comparison `List<T> m = x;` is parsed as a LocalVariableDeclarationStatement and
// not as an assignment to the comparisons `(List < T) > m`. As a
// result, `a < b = c` is not valid.
// !InstanceOf `o instanceof String s = null` is not valid.
> right Expression!Comparison!InstanceOf AssignmentOperator Expression #Assignment
// !>>> Arrow A lambda followed by `->` ends a case constant or a guard, and such a
// lambda never compiles: a case constant is a constant expression or the
// name of an enum constant, and a guard has type boolean or Boolean. The
// follow restriction drops these lambdas, which resolves three related
// ambiguities:
// - `case A a when b -> c -> d;` should be parsed as
// `case A a when (b) -> (c -> d);`, i.e., with the guard `b` and the
// rule's expression `c -> d`, not with the guard `b -> c` as in
// `case A a when (b -> c) -> d;`.
// - `case A a when (B) c -> d -> e;` should be parsed as
// `case A a when ((B) c) -> (d -> e);`, not with the guard `(B) (c -> d)`
// as in `case A a when ((B) (c -> d)) -> e;`. JLS derives both, because a
// reference cast takes a lambda (§15.16), and an exclusion on the guard
// cannot reach the cast's operand.
// - `case K > 0 ? 1 : Q -> x -> x;` should be parsed as
// `case (K > 0 ? 1 : Q) -> (x -> x);`, not with the constant
// `K > 0 ? 1 : (Q -> x)` as in `case (K > 0 ? 1 : (Q -> x)) -> x;`. JLS
// derives both, because the third operand of a conditional takes a
// lambda (§15.25). The right side of an assignment takes a lambda too
// (§15.26).
> Lambda !>>> Arrow #Lambda
Pattern
= TypePattern
| RecordPattern
// JLS §14.30.1 defines a type pattern as a local variable declaration, which allows a
// list of declarators and an initializer. Both make the grammar ambiguous:
// - `f(o instanceof A a, b)` should be parsed as `f((o instanceof A a), b)`, i.e., with
// two arguments, not with one pattern that declares `a` and `b` as in
// `f((o instanceof A a, b))`.
// - `a && o instanceof B b = c && d` could be parsed as `a && o instanceof B b = (c && d)`
// or as `(a && o instanceof B b = c) && d`, with the initializer ending at `d` or at
// `c`.
// §14.30.1 allows only one declarator without an initializer, so a type pattern here has
// a single VariableDeclaratorId, which resolves both.
TypePattern
= VariableModifier* LocalVariableType VariableDeclaratorId
RecordPattern
= ReferenceType "(" { ComponentPattern "," }* ")"
ComponentPattern
= Pattern
| "_"
Primary
= Literal #Literal
| Identifier #Identifier
| (TypeName ".")? "this" #This
| "super" SuperSuffix #Super
| (Type | "void") "." "class" #Type
| "(" Expression ")" #Expression
QualifiedIdentifier
= { Identifier "." }+
// JLS §6.5 takes the last component of a type name from TypeIdentifier and the
// qualifier before it from ordinary identifiers, so `yield.Foo` is valid while `@yield`
// and `yield.this` are not.
TypeName
= (Identifier ".")* TypeIdentifier
SuperSuffix
= "." NonWildTypeArguments? Identifier Arguments?
NonWildTypeArguments
= "<" { Type "," }+ ">"
Type
= PrimitiveType
| ReferenceType
PrimitiveType
= Annotation*
("byte" | "short" | "char" | "int" | "long" | "float" | "double" | "boolean")
ReferenceType
= ClassType
| ArrayType
// JLS §4.3 qualifies a class type with either a package name, whose components are
// ordinary identifiers, or another class or interface type, whose components are type
// identifiers. A component with annotations or type arguments is therefore a type
// component, and every component after it is one too, since a package name cannot
// follow a class or interface type. So `yield.Foo` names a type in a package called
// yield, while `yield<T>.Foo` and `A<T>.yield.Foo` do not.
MarkedTypeComponent
= Annotation+ TypeIdentifier TypeArguments?
| TypeIdentifier TypeArguments
MarkedClassType
= (Identifier ".")* MarkedTypeComponent ("." Annotation* TypeIdentifier TypeArguments?)*
ClassType
= (Identifier ".")* TypeIdentifier
| MarkedClassType
ClassTypeToInstantiate
= Annotation* Identifier ("." Annotation* Identifier)* TypeArgumentsOrDiamond?
TypeArguments
= "<" { TypeArgument "," }+ ">"
TypeArgument
= ReferenceType #Simple
| wildCardTypeArgument:Annotation* "?" (("extends" | "super") ReferenceType)? #WildCard
ArrayType
= (ClassType | PrimitiveType) (Annotation* "[" "]")+
UnannType
= UnannPrimitiveType
| UnannReferenceType
UnannPrimitiveType
= "byte"
| "short"
| "char"
| "int"
| "long"
| "float"
| "double"
| "boolean"
UnannReferenceType
= UnannClassType
| UnannArrayType
// An unannotated class type cannot begin with an annotation. A type component at the
// start can therefore be distinguished from a package component only through type
// arguments.
UnannClassType
= (Identifier ".")* TypeIdentifier
| TypeIdentifier TypeArguments ("." Annotation* TypeIdentifier TypeArguments?)*
| (Identifier ".")+ MarkedTypeComponent ("." Annotation* TypeIdentifier TypeArguments?)*
UnannArrayType
= (UnannClassType | UnannPrimitiveType) (Annotation* "[" "]")+
Literal
= IntegerLiteral !>> Dot #Integer
| FloatingPointLiteral #Float
| BooleanLiteral #Boolean
| CharacterLiteral #Character
| StringLiteral #String
| TextBlock #TextBlock
| NullLiteral #Null
Selector
= Identifier #Identifier
| NonWildTypeArguments? Identifier Arguments #Method
| "super" SuperSuffix #Super
| "new" TypeArguments? Identifier TypeArgumentsOrDiamond? Arguments ClassBody? #New
MethodInvocation
= UnqualifiedMethodIdentifier Arguments
TypeArgumentsOrDiamond
= "<" ">"
| TypeArguments
ClassInstanceCreationExpression
= TypeArguments? ClassTypeToInstantiate Arguments ClassBody?
ArrayCreationExpression
= (PrimitiveType | ReferenceType) (Annotation* "[" Expression "]")+
(Annotation* "[" "]")* !>> OpenBracket
| (PrimitiveType | ClassType) (Annotation* "[" "]")+ ArrayInitializer
Lambda
= LambdaParameters "->" LambdaBody
LambdaParameters
= "(" LambdaParameterList? ")"
| ConciseLambdaParameter
LambdaParameterList
= { NormalLambdaParameter "," }+
| { ConciseLambdaParameter "," }+
ConciseLambdaParameter
= Identifier
| "_"
NormalLambdaParameter
= VariableModifier* LambdaParameterType VariableDeclaratorId
| VariableModifier* UnannType Annotation* "..." Identifier
LambdaParameterType
= UnannType
| "var"
LambdaBody
= Expression
| Block
@Layout
Layout
= (WhiteSpace | Comment)* !>> WhiteSpace !>> Comment
@Regex
HexDigit = [0-9a-fA-F]
@Regex
IntegerLiteral
= DecimalIntegerLiteral
| HexIntegerLiteral
| OctalIntegerLiteral
| BinaryIntegerLiteral
@Regex
FloatingPointLiteral
= DecimalFloatingPointLiteral
| HexadecimalFloatingPointLiteral
@Regex
BooleanLiteral
= "true"
| "false"
@Regex
CharacterLiteral = ['] (SingleCharacter | EscapeSequence) [']
@Regex
DecimalIntegerLiteral = ([0] | ([1-9] (Digits? | ([_]+ Digits)))) [lL]?
@Regex
StringLiteral = ["] StringCharacter* ["]
// JLS §3.10.6 opens a text block with three double quotes, optional spaces, tabs, or
// form feeds, and a line terminator. The text block ends at the first three double quotes
// that are not part of an escape sequence, so its content never has three in a row.
@Regex
TextBlock = ["] ["] ["] [\ \t\f]* LineTerminator TextBlockPart* ["] ["] ["]
@Regex
TextBlockPart = (["] ["]?)? TextBlockCharacter
// JLS §3.10.7 lists a backslash before a line terminator as an escape sequence, which
// joins two lines of a text block. A string literal cannot contain a line terminator, even
// after a backslash (§3.10.5), so the escape is part of TextBlockCharacter rather than
// EscapeSequence.
@Regex
TextBlockCharacter
= ![\\"]
| UnicodeEscape
| EscapeSequence
| [\\] LineTerminator
@Regex
LineTerminator
= [\n]
| [\r]
| [\r] [\n]
@Regex
NullLiteral = "null"
@Regex
Dot = "."
@Regex
HexIntegerLiteral = [0] [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?
@Regex
OctalIntegerLiteral = [0] [_]* [0-7] ([0-7_]* [0-7])? [lL]?
@Regex
BinaryIntegerLiteral = [0] [bB] [01] ([01_]* [01])? [lL]?
@Regex
HexadecimalFloatingPointLiteral
= [0] [xX] ((HexDigits [.]?) | (HexDigits? [.] HexDigits)) [pP] Sign? Digits
FloatTypeSuffix?
@Regex
HexDigits = HexDigit (HexDigitOrUnderscore* HexDigit)?
@Regex
HexDigitOrUnderscore = [0-9a-fA-F_]
@Regex
DecimalFloatingPointLiteral
= ((Digits '.' Digits?) | ('.' Digits)) ExponentPart? FloatTypeSuffix?
| Digits ((ExponentPart FloatTypeSuffix?) | FloatTypeSuffix)
@Regex
ExponentPart = ExponentIndicator SignedInteger
@Regex
ExponentIndicator = [eE]
@Regex
SignedInteger = Sign? Digits
@Regex
Sign = [+\-]
@Regex
Digits = [0-9] ([0-9_]* [0-9])?
@Regex
FloatTypeSuffix = [fFdD]
@Regex
OctalNumeral = [0] [_]* OctalDigits
@Regex
OctalDigits = OctalDigit (OctalDigitOrUnderscore* OctalDigit)?
@Regex
OctalDigit = [0-7]
@Regex
OctalDigitOrUnderscore = [0-7_]
@Regex
SingleCharacter
= ![\\\n\r']
| UnicodeEscape
@Regex
StringCharacter
= ![\\\n\r"]
| UnicodeEscape
| EscapeSequence
@Regex
EscapeSequence
= "\\" [bstnfr"'\\]
| "\\" (ZeroToThree? OctalDigit)? OctalDigit
@Regex
UnicodeEscape = [\\] [u]+ HexDigit HexDigit HexDigit HexDigit
@Regex
ZeroToThree = [0-3]
@Regex
AssignmentOperator
= "="
| "+="
| "-="
| "*="
| "/="
| "&="
| "|="
| "^="
| "%="
| "<<="
| ">>="
| ">>>="
// JLS §3.8 takes an identifier from the identifier characters and excludes the
// reserved words, `true`, `false`, and `null`, so none of them is a valid variable name.
@Identifier @Regex
Identifier = IdentifierChars \ Keyword \ BooleanLiteral \ NullLiteral
@Regex
TypeKeyword
= "permits"
| "record"
| "sealed"
| "var"
| "yield"
// JLS 25 §3.8 excludes five contextual keywords from TypeIdentifier: `permits`, `record`,
// `sealed`, `var`, and `yield`. So `class var {}` and `class record {}` are not valid. The
// restriction is on TypeIdentifier rather than on every identifier of a type name, which
// is why `yield.Foo` and `record.Foo` are valid. The five words are ordinary identifiers in
// every other position, and `yield` is barred from one more, as the next rule says.
@Regex
TypeIdentifier = Identifier \ TypeKeyword
@Regex
Yield = "yield"
@Regex
Arrow = "->"
// JLS §3.8 defines UnqualifiedMethodIdentifier as an Identifier other than `yield`, and
// the `\ Yield` here does the same. As a result, `yield(x);` is parsed as a yield
// statement and not as an invocation of a method named yield. `this.yield(x)` is valid
// because Selector uses Identifier.
@Regex
UnqualifiedMethodIdentifier = Identifier \ Yield
@Regex
IdentifierChars = JavaLetter (JavaLetter | JavaLetterOrDigit)*
@Regex
JavaLetter = [A-Za-z$_]
@Regex
JavaLetterOrDigit = [A-Za-z$_0-9]
@Regex
Else = "else" !>> JavaLetterOrDigit
// JLS §3.9 makes `non-sealed` one contextual keyword rather than `non`, `-`, and
// `sealed`, and no letter or digit may immediately precede or follow it.
@Regex
NonSealed = JavaLetterOrDigit !<< "non-sealed" !>> JavaLetterOrDigit
@Regex
OpenBracket = "["
@Regex
Plus = "+"
@Regex
Minus = "-"
@Regex
Keyword
= "abstract"
| "continue"
| "for"
| "new"
| "switch"
| "assert"
| "default"
| "if"
| "package"
| "synchronized"
| "boolean"
| "do"
| "goto"
| "private"
| "this"
| "break"
| "double"
| "implements"
| "protected"
| "throw"
| "byte"
| "else"