/
ScalaParser.scala
2101 lines (1864 loc) · 75 KB
/
ScalaParser.scala
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
package scalariform.parser
import scalariform.lexer.Tokens._
import scalariform.lexer._
import scalariform.utils.Utils._
import scalariform.ScalaVersions
import scala.collection.mutable.ListBuffer
import scala.PartialFunction._
class ScalaParser(tokens: Array[Token]) {
private val logging: Boolean = false
private val forgiving: Boolean = true
import ScalaParser._
def safeParse[T](production: ⇒ T): Option[T] = try Some(production) catch { case e: ScalaParserException ⇒ None }
require(!tokens.isEmpty) // at least EOF
def inParens[T](body: ⇒ T): (Token, T, Token) = {
val openToken = accept(LPAREN)
val contents = body
val closeToken = accept(RPAREN)
(openToken, contents, closeToken)
}
def inBraces[T](body: ⇒ T): (Token, T, Token) = {
val openToken = accept(LBRACE)
val contents = body
val closeToken = accept(RBRACE)
(openToken, contents, closeToken)
}
def dropAnyBraces[T](body: ⇒ Expr): Expr =
if (LBRACE) {
val (lbrace, contents, rbrace) = inBraces(body)
makeExpr(lbrace, contents, rbrace)
} else
body
def inBrackets[T](body: ⇒ T): (Token, T, Token) = {
val openToken = accept(LBRACKET)
val contents = body
val closeToken = accept(RBRACKET)
(openToken, contents, closeToken)
}
def makeParens[T](body: ⇒ T) = inParens { if (RPAREN) None else Some(body) }
def compilationUnitOrScript(): CompilationUnit = {
val originalPos = pos
try
compilationUnit()
catch {
case e: ScalaParserException ⇒
pos = originalPos
if (logging) println("Rewinding to try alternative: " + currentToken)
try {
scriptBody()
} catch { case e2: ScalaParserException ⇒ throw e }
}
}
def scriptBody(): CompilationUnit = {
val stmts = templateStats()
val eofToken = accept(EOF)
CompilationUnit(stmts, eofToken)
}
private def templateStats() = {
templateStatSeq()
}
private def accept(tokenType: TokenType): Token =
if (currentTokenType == tokenType)
nextToken()
else
throw new ScalaParserException("Expected token " + tokenType + " but got " + currentToken)
private def acceptStatSep(): Token = currentTokenType match {
case NEWLINE | NEWLINES ⇒ nextToken
case _ ⇒ accept(SEMI)
}
private def acceptStatSepOpt(): Option[Token] = if (!isStatSeqEnd) Some(acceptStatSep()) else None
private def isModifier = currentTokenType match {
case ABSTRACT | FINAL | SEALED | PRIVATE |
PROTECTED | OVERRIDE | IMPLICIT | LAZY ⇒ true
case _ ⇒ false
}
private def isLocalModifier: Boolean = currentTokenType match {
case ABSTRACT | FINAL | SEALED | IMPLICIT | LAZY ⇒ true
case _ ⇒ false
}
private def isTemplateIntro: Boolean = currentTokenType match {
case OBJECT | CLASS | TRAIT ⇒ true
case CASE if caseObject ⇒ true
case CASE if caseClass ⇒ true
case _ ⇒ false
}
private def isDclIntro: Boolean = currentTokenType match {
case VAL | VAR | DEF | TYPE ⇒ true
case _ ⇒ false
}
private def isDefIntro: Boolean = isTemplateIntro || isDclIntro
private def isNumericLit: Boolean = currentTokenType match {
case INTEGER_LITERAL | FLOATING_POINT_LITERAL ⇒ true
case _ ⇒ false
}
private def isUnaryOp: Boolean = currentTokenType match {
case MINUS | PLUS | TILDE | EXCLAMATION ⇒ true
case _ ⇒ false
}
private def isIdent: Boolean = isIdent(currentTokenType)
private def isIdent(tokenType: TokenType) = tokenType match {
case VARID | OTHERID | PLUS | MINUS | STAR | PIPE | TILDE | EXCLAMATION ⇒ true
case _ ⇒ false
}
private def isLiteralToken(tokenType: TokenType): Boolean = tokenType match {
case CHARACTER_LITERAL | INTEGER_LITERAL | FLOATING_POINT_LITERAL |
STRING_LITERAL | INTERPOLATION_ID | SYMBOL_LITERAL | TRUE | FALSE | NULL ⇒ true
case _ ⇒ false
}
private def isLiteral = isLiteralToken(currentTokenType)
private def isExprIntroToken(tokenType: TokenType) =
isLiteralToken(tokenType) || (tokenType match {
case THIS | SUPER | IF | FOR | NEW | USCORE | TRY | WHILE |
DO | RETURN | THROW | LPAREN | LBRACE ⇒ true
case XML_START_OPEN | XML_UNPARSED | XML_COMMENT | XML_CDATA | XML_PROCESSING_INSTRUCTION ⇒ true
case _ if isIdent(tokenType) ⇒ true
case _ ⇒ false
})
private def isExprIntro: Boolean = isExprIntroToken(currentTokenType)
private def isTypeIntroToken(tokenType: TokenType): Boolean = tokenType match {
case THIS | SUPER | USCORE | LPAREN | AT ⇒ true
case _ if isIdent(tokenType) ⇒ true
case _ ⇒ false
}
private def isTypeIntro: Boolean = isTypeIntroToken(currentTokenType)
private def isStatSeqEnd = RBRACE || EOF
private def isStatSep(tokenType: TokenType) =
tokenType == NEWLINE || tokenType == NEWLINES || tokenType == SEMI
private def isStatSep: Boolean = isStatSep(currentTokenType)
private def tokenSeparated[T](separator: TokenType, sepFirst: Boolean, part: ⇒ T): (Option[T], List[(Token, T)]) = {
val ts = new ListBuffer[(Token, T)]
val firstOpt = if (sepFirst) None else Some(part)
while (separator) {
val separatorToken = nextToken()
val nextPart = part
ts += ((separatorToken, nextPart))
}
(firstOpt, ts.toList)
}
private def commaSeparated[T](part: ⇒ T) =
tokenSeparated(COMMA, false, part) match { case (firstOpt, rest) ⇒ (firstOpt.get, rest) }
private def caseSeparated[T](part: ⇒ T) = tokenSeparated(CASE, true, part)._2
private def readAnnots[T](part: ⇒ T) = tokenSeparated(AT, true, part)._2
trait PatternContextSensitive {
def argType(): List[TypeElement]
def functionArgType(): List[TypeElement]
private def tupleInfixType() = {
val lparen = nextToken()
if (RPAREN) {
val rparen = nextToken()
val arrowToken = accept(ARROW)
val typ_ = typ()
typeElementFlatten3(lparen, rparen, arrowToken, typ_)
} else {
val types_ = functionTypes()
val rparen = accept(RPAREN)
val others = if (ARROW) {
val arrowToken = nextToken()
val typ_ = typ()
typeElementFlatten3(arrowToken, typ_)
} else {
val simpleTypeRest_ = simpleTypeRest()
val annotTypeRest_ = annotTypeRest()
val compoundTypeRest_ = compoundTypeRest()
val infixTypeRest_ = infixTypeRest()
typeElementFlatten3(simpleTypeRest_, annotTypeRest_, compoundTypeRest_, infixTypeRest_)
}
typeElementFlatten3(lparen, types_, rparen, others)
}
}
private def makeExistentialTypeTree() = refinement()
def typ(): Type = {
val others2 =
if (LPAREN) tupleInfixType()
else infixType()
val others3 = currentTokenType match {
case ARROW ⇒
val arrowToken = nextToken()
val typ_ = typ()
typeElementFlatten3(arrowToken, typ_)
case FORSOME ⇒
val forSomeToken = nextToken()
val refinement_ = makeExistentialTypeTree()
typeElementFlatten3(forSomeToken, refinement_)
case _ ⇒
Nil
}
Type(typeElementFlatten3(others2, others3))
}
def typeArgs(): List[TypeElement] = {
val (lbracket, types_, rbracket) = inBrackets(types())
typeElementFlatten3(lbracket, types_, rbracket)
}
def annotType(): List[TypeElement] = {
val simpleType_ = simpleType()
val annotTypeRest_ = annotTypeRest()
typeElementFlatten3(simpleType_, annotTypeRest_)
}
def simpleType(): List[TypeElement] = {
val firstPart = currentTokenType match {
case LPAREN ⇒
val (lparen, types_, rparen) = inParens(types())
typeElementFlatten3(lparen, types_, rparen)
case USCORE ⇒
val uscore = nextToken()
val wildcardType_ = wildcardType()
typeElementFlatten3(uscore, wildcardType_)
case _ ⇒
typeElementFlatten3(path(thisOK = false, typeOK = true))
}
val simpleTypeRest_ = simpleTypeRest()
typeElementFlatten3(firstPart, simpleTypeRest_)
}
private def typeProjection() = {
val hashToken = nextToken()
val id = ident()
(hashToken, id)
}
private def simpleTypeRest(): List[TypeElement] = currentTokenType match {
case HASH ⇒
val (hashToken, id) = typeProjection()
val simpleTypeRest_ = simpleTypeRest()
typeElementFlatten3(hashToken, id, simpleTypeRest_)
case LBRACKET ⇒
val typeArgs_ = typeArgs()
val simpleTypeRest_ = simpleTypeRest()
typeElementFlatten3(typeArgs_, simpleTypeRest_)
case _ ⇒
Nil
}
def compoundType(): List[TypeElement] = {
val annotTypeOpt = if (LBRACE) None else Some(annotType())
val rest = compoundTypeRest()
typeElementFlatten3(annotTypeOpt, rest)
}
private def compoundTypeRest(): List[TypeElement] = {
val withTypes = ListBuffer[(Token, List[TypeElement])]()
while (WITH) {
val withToken = nextToken()
val annotType_ = annotType()
withTypes += ((withToken, annotType_))
}
val newLineOpt = newLineOptWhenFollowedBy(LBRACE)
val refinementOpt = if (LBRACE) Some(refinement()) else None
typeElementFlatten3(withTypes.toList, newLineOpt, refinementOpt)
}
def infixTypeRest(): List[TypeElement] = {
if (isIdent && !STAR) {
val identToken = currentToken
val id = InfixTypeConstructor(ident())
val newLineOpt = newLineOptWhenFollowing(isTypeIntroToken)
if (isLeftAssoc(identToken)) {
val compoundType_ = compoundType()
val infixTypeRest_ = infixTypeRest()
typeElementFlatten3(id, newLineOpt, compoundType_, infixTypeRest_)
} else {
val infixType_ = infixType()
typeElementFlatten3(id, newLineOpt, infixType_)
}
} else
Nil
}
def infixType(): List[TypeElement] = {
val compoundType_ = compoundType()
val infixTypeRest_ = infixTypeRest()
typeElementFlatten3(compoundType_, infixTypeRest_)
}
private def types(): List[TypeElement] =
typeElementFlatten3(commaSeparated(argType()))
private def functionTypes(): List[TypeElement] =
typeElementFlatten3(commaSeparated(functionArgType()))
}
private def ident(): Token =
if (isIdent)
nextToken()
else
throw new ScalaParserException("Expected identifier, but got " + currentToken)
private def selector(): Token = ident()
private def pathC(thisOK: Boolean, typeOK: Boolean): CallExpr = {
if (THIS) {
val thisToken = nextToken()
val baseCall = CallExpr(None, thisToken)
if (!thisOK || DOT) {
val dot = accept(DOT)
selectors((baseCall, dot), typeOK)
} else
baseCall
} else if (SUPER) {
val superToken = nextToken()
val mixinQualifierOpt_ = mixinQualifierOpt()
val dot = accept(DOT)
val id = selector()
val subBaseCall = CallExpr(None, superToken, mixinQualifierOpt_)
val baseCall = CallExpr(Some(List(subBaseCall), dot), id)
if (DOT) {
val dot2 = nextToken()
selectors((baseCall, dot2), typeOK)
} else
baseCall
} else {
val id = ident()
val baseCall = CallExpr(None, id)
if (DOT) {
val dot = nextToken()
if (THIS) {
val thisToken = nextToken()
val baseCall2 = CallExpr(Some(List(baseCall), dot), thisToken)
if (!thisOK || DOT) {
val dot2 = accept(DOT)
selectors((baseCall2, dot2), typeOK)
} else
baseCall2
} else if (SUPER) {
val superToken = nextToken()
val mixinQualifierOpt_ = mixinQualifierOpt()
val dot2 = accept(DOT)
val id2 = selector()
val baseCall2 = CallExpr(Some(List(CallExpr(Some(List(baseCall), dot), superToken, mixinQualifierOpt_)), dot2), id2)
if (DOT) {
val dot3 = nextToken()
selectors((baseCall2, dot3), typeOK)
} else
baseCall2
} else
selectors((baseCall, dot), typeOK)
} else
baseCall
}
}
private def path(thisOK: Boolean, typeOK: Boolean): List[Token] = pathC(thisOK, typeOK).tokens
private def selectors(previousAndDot: (CallExpr, Token), typeOK: Boolean): CallExpr = {
val exprDotOpt = Some(exprElementFlatten2(previousAndDot._1), previousAndDot._2)
if (typeOK && TYPE)
CallExpr(exprDotOpt, nextToken())
else {
val id = selector()
val baseCall = CallExpr(exprDotOpt, id)
if (DOT) {
val dot = nextToken()
selectors((baseCall, dot), typeOK)
} else
baseCall
}
}
private def mixinQualifierOpt(): Option[TypeExprElement] =
if (LBRACKET) Some(TypeExprElement(typeElementFlatten3(inBrackets(ident)))) else None
private def stableId(): List[Token] = path(thisOK = false, typeOK = false)
private def qualId(): CallExpr = {
val id = ident()
val baseCall = CallExpr(None, id)
if (DOT) {
val dot = nextToken()
selectors((baseCall, dot), typeOK = false)
} else
baseCall
}
private def pkgQualId(): (CallExpr, Option[Token]) = {
val pkg = qualId()
val newLineOpt = newLineOptWhenFollowedBy(LBRACE)
(pkg, newLineOpt)
}
private def literal(inPattern: Boolean = false): List[ExprElement] =
if (INTERPOLATION_ID) {
List(interpolatedString(inPattern))
} else if (CHARACTER_LITERAL || INTEGER_LITERAL || FLOATING_POINT_LITERAL || STRING_LITERAL || SYMBOL_LITERAL || TRUE || FALSE || NULL)
exprElementFlatten2(nextToken())
else
throw new ScalaParserException("illegal literal: " + currentToken)
private def interpolatedString(inPattern: Boolean = false): StringInterpolation = {
val interpolationId = nextToken()
val stringPartsAndScala = ListBuffer[(Token, Expr)]()
while (STRING_PART) {
val stringPart = nextToken()
val scalaSegment: Expr =
if (inPattern)
dropAnyBraces(pattern())
else if (isIdent)
makeExpr(ident())
else
expr()
stringPartsAndScala += ((stringPart, scalaSegment))
}
if (!STRING_LITERAL) // TODO: Can it be absent, as allowed by Scalac?
throw new ScalaParserException("Unexpected conclusion to string interpolation: " + currentToken)
val terminalString = nextToken()
StringInterpolation(interpolationId, stringPartsAndScala.toList, terminalString)
}
private def newLineOpt(): Option[Token] = if (NEWLINE) Some(nextToken()) else None
private def newLinesOpt() = if (NEWLINE || NEWLINES) Some(nextToken()) else None
private def newLineOptWhenFollowedBy(tokenType: TokenType) =
if (NEWLINE && lookahead(1) == tokenType)
newLineOpt()
else
None
private def newLineOptWhenFollowing(pred: TokenType ⇒ Boolean) =
if (NEWLINE && pred(lookahead(1)))
newLineOpt()
else
None
private def typedOpt(): Option[(Token, Type)] =
if (COLON) {
val colonToken = nextToken()
val typ_ = typ()
Some(colonToken, typ_)
} else
None
private def typeOrInfixType(location: Location): TypeExprElement =
TypeExprElement(
if (location == Local)
typ().contents
else
startInfixType())
private def annotTypeRest(): List[TypeElement] =
typeElementFlatten3(annotations(skipNewLines = false))
private def wildcardType(): List[TypeElement] = {
typeBounds()
}
private def equalsExpr() = {
val equalsToken = accept(EQUALS)
val expr_ = expr()
(equalsToken, expr_)
}
private def condExpr(): CondExpr = {
if (LPAREN) {
val lparen = nextToken()
val expr_ = expr()
val rparen = accept(RPAREN)
CondExpr(lparen, expr_, rparen)
} else {
val lparen = accept(LPAREN)
// Seriously, WTF?
throw new ScalaParserException("Straggling lparen thing")
}
}
private def statement(location: Location): Expr = expr(location)
def expr(): Expr = { expr(Local) }
private def expr(location: Location): Expr = {
expr0(location)
}
private def expr0(location: Location): Expr = {
makeExpr(currentTokenType match {
case IF ⇒
val ifToken = nextToken()
val condExpr_ = condExpr()
val newLinesOpt_ = newLinesOpt()
val body = expr()
// nsc has merged the SEMI into the ELSE by this point:
val semiOpt = if (SEMI && lookahead(1) == ELSE) Some(nextToken()) else None
val elseClauseOption = if (ELSE) {
val elseToken = nextToken()
val expr_ = expr()
Some(ElseClause(semiOpt, elseToken, expr_))
} else
None
List(IfExpr(ifToken, condExpr_, newLinesOpt_, body, elseClauseOption))
case TRY ⇒
val tryToken = nextToken()
val body: Expr = currentTokenType match {
case LBRACE ⇒
val (lbrace, block_, rbrace) = inBraces(block())
makeExpr(BlockExpr(lbrace, Right(block_), rbrace))
case LPAREN ⇒ makeExpr(inParens(expr()))
case _ ⇒ expr
}
val catchClauseOption: Option[CatchClause] =
if (!CATCH)
None
else {
val catchToken = nextToken()
if (!LBRACE)
Some(CatchClause(catchToken, Right(expr())))
else {
val (lbrace, caseClausesOrStatSeq, rbrace) = inBraces {
if (CASE)
Left(caseClauses())
else
Right(StatSeq(selfReferenceOpt = None, firstStatOpt = Some(expr()), otherStats = Nil))
}
Some(CatchClause(catchToken, Left(BlockExpr(lbrace, caseClausesOrStatSeq, rbrace))))
}
}
val finallyClauseOption = currentTokenType match {
case FINALLY ⇒
val finallyToken = nextToken()
val finallyExpr = expr()
Some(finallyToken, finallyExpr)
case _ ⇒
None
}
List(TryExpr(tryToken, body, catchClauseOption, finallyClauseOption))
case WHILE ⇒
val whileToken = nextToken()
val condExpr_ = condExpr()
val newLinesOpt_ = newLinesOpt()
val body = expr()
List(WhileExpr(whileToken, condExpr_, newLinesOpt_, body))
case DO ⇒
val doToken = nextToken()
val body = expr()
val statSepOpt = if (isStatSep) Some(nextToken()) else None
val whileToken = accept(WHILE)
val condExpr_ = condExpr()
List(DoExpr(doToken, body, statSepOpt, whileToken, condExpr_))
case FOR ⇒
val forToken = nextToken()
val (open, close) = if (LBRACE) (LBRACE, RBRACE) else (LPAREN, RPAREN)
val (lParenOrBrace, enumerators_, rParenOrBrace) =
if (LBRACE) inBraces(enumerators())
else inParens(enumerators())
val newlinesOption = newLinesOpt()
val (yieldOption, body) = if (YIELD) {
val yieldToken = nextToken()
(Some(yieldToken), expr())
} else
(None, expr())
List(ForExpr(forToken, lParenOrBrace, enumerators_, rParenOrBrace, newlinesOption, yieldOption, body))
case RETURN ⇒
val returnToken = nextToken()
val returnExpr = if (isExprIntro) Some(expr()) else None
exprElementFlatten2(returnToken, returnExpr) // TODO: <-- use a different type?
case THROW ⇒
val throwToken = nextToken()
val throwExpr = expr()
exprElementFlatten2(throwToken, throwExpr)
case IMPLICIT ⇒
val implicitToken = nextToken()
List(implicitClosure(location, implicitToken))
case _ ⇒
val postfixExpr_ = postfixExpr()
val intermediateResult = if (EQUALS) {
optional { /* TODO: case Ident(_) | Select(_, _) | Apply(_, _) => */
(accept(EQUALS), expr())
} match {
case Some((equalsToken, equalsExpr)) ⇒ List(EqualsExpr(postfixExpr_, equalsToken, equalsExpr))
case None ⇒ postfixExpr_
}
} else if (COLON) {
val colonToken = nextToken()
val rhs = if (USCORE) {
val uscore = nextToken()
val star = accept(STAR)
exprElementFlatten2(uscore, star)
} else if (AT) {
annotations(skipNewLines = false)
} else {
val type_ = typeOrInfixType(location)
List(type_)
}
List(AscriptionExpr(postfixExpr_, colonToken, rhs))
} else if (MATCH) {
val matchToken = nextToken()
val (lbrace, caseClauses_, rbrace) = inBraces(caseClauses())
val blockExpr_ = BlockExpr(lbrace, Left(caseClauses_), rbrace)
List(MatchExpr(postfixExpr_, matchToken, blockExpr_))
} else
postfixExpr_
if (logging)
println("in expr0, postfixExpr = " + postfixExpr_)
val lhsIsTypedParamList = cond(postfixExpr_) { case List(ParenExpr(_, _, _)) ⇒ true } // TODO: is this check sufficient?
if (ARROW && (location != InTemplate || lhsIsTypedParamList)) {
val anonFuncOpt: Option[List[ExprElement]] = optional {
val arrowToken = nextToken()
val postArrow: StatSeq = if (location != InBlock) StatSeq(None, Some(expr()), Nil) else block()
exprElementFlatten2(AnonymousFunction(intermediateResult, arrowToken, postArrow))
}
anonFuncOpt match {
case None ⇒ intermediateResult
case Some(stuff) ⇒ stuff
} // erk, why can't I use getOrElse here!?
} else
intermediateResult
})
}
private def implicitClosure(location: Location, implicitToken: Token): AnonymousFunction = {
val id = ident()
val colonTypeOpt = if (COLON) {
val colonToken = nextToken()
val type_ = typeOrInfixType(location)
Some(colonToken, type_)
} else
None
val arrowToken = accept(ARROW)
val body: StatSeq = if (location != InBlock) StatSeq(None, Some(expr()), Nil) else block()
AnonymousFunction(exprElementFlatten2(implicitToken, id, colonTypeOpt), arrowToken, body)
}
private final val otherLetters = Set[Char]('\u0024', '\u005F') // '$' and '_'
private final val letterGroups = {
import java.lang.Character._
Set[Byte](LOWERCASE_LETTER, UPPERCASE_LETTER, OTHER_LETTER, TITLECASE_LETTER, LETTER_NUMBER)
}
private def isScalaLetter(ch: Char) = letterGroups(java.lang.Character.getType(ch).toByte) || otherLetters(ch)
private def isOpAssignmentName(name: String) = name match {
case "!=" | "<=" | ">=" | "" ⇒ false
case _ ⇒ name.endsWith("=") && !name.startsWith("=") && Chars.isOperatorPart(name(0))
}
private def precedence(id: String) = id(0) match {
case _ if isOpAssignmentName(id) ⇒ 0
case c if isScalaLetter(c) ⇒ 1
case '|' ⇒ 2
case '^' ⇒ 3
case '&' ⇒ 4
case '=' | '!' ⇒ 5
case '<' | '>' ⇒ 6
case ':' ⇒ 7
case '+' | '-' ⇒ 8
case '*' | '/' | '%' ⇒ 9
case _ ⇒ 10
}
private def hasSamePrecedence(token1: Token, token2: Token) = precedence(token1.text) == precedence(token2.text)
private def hasHigherPrecedence(token1: Token, token2: Token) = precedence(token1.text) > precedence(token2.text)
private def isRightAssociative(token: Token) = token.text.endsWith(":")
private object NestedInfixExpr {
def unapply(infixExpr: InfixExpr) = condOpt(infixExpr) {
case InfixExpr(List(InfixExpr(x, op1, newLineOpt1, y)), op2, newLineOpt2, z) ⇒ (x, op1, newLineOpt1, y, op2, newLineOpt2, z)
}
}
private def rotateRight(infixExpr: InfixExpr): InfixExpr = {
val NestedInfixExpr(x, op1, newLineOpt1, y, op2, newLineOpt2, z) = infixExpr
InfixExpr(x, op1, newLineOpt1, List(InfixExpr(y, op2, newLineOpt2, z)))
}
private def performRotationsForPrecedence(infixExpr: InfixExpr): InfixExpr = infixExpr match {
case NestedInfixExpr(x, op1, newLineOpt1, y, op2, newLineOpt2, z) if hasHigherPrecedence(op2, op1) ⇒
InfixExpr(x, op1, newLineOpt1, List(performRotationsForPrecedence(InfixExpr(y, op2, newLineOpt2, z))))
case _ ⇒ infixExpr
}
private def performRotationsForRightAssociativity(infixExpr: InfixExpr): InfixExpr = infixExpr match {
case NestedInfixExpr(x, op1, newLineOpt1, y, op2, newLineOpt2, z) if hasSamePrecedence(op1, op2) && isRightAssociative(op1) && isRightAssociative(op2) ⇒
InfixExpr(x, op1, newLineOpt1, List(performRotationsForRightAssociativity(InfixExpr(y, op2, newLineOpt2, z))))
case _ ⇒ infixExpr
}
private def postfixExpr(): List[ExprElement] = {
var soFar: List[ExprElement] = prefixExpr()
while (isIdent) {
val id = ident()
val newLineOpt = newLineOptWhenFollowing(isExprIntroToken)
if (isExprIntro) {
val prefixExpr_ = prefixExpr()
var infixExpr_ = InfixExpr(soFar, id, newLineOpt, prefixExpr_)
infixExpr_ = performRotationsForPrecedence(infixExpr_)
infixExpr_ = performRotationsForRightAssociativity(infixExpr_)
soFar = List(infixExpr_)
} else
soFar = List(PostfixExpr(soFar, id))
}
soFar
}
private def prefixExpr(): List[ExprElement] = {
if (isUnaryOp) {
val isMinus = MINUS
val unaryId = PrefixExprElement(ident())
if (isMinus && isNumericLit) {
val literal_ = literal()
simpleExprRest(exprElementFlatten2(unaryId, literal_), true)
} else
List(Expr(exprElementFlatten2(unaryId, simpleExpr())))
} else
simpleExpr()
}
private object PathEndingWithDotId {
def unapply(tokens: List[Token]) = condOpt(tokens.reverse) {
case (lastIdToken) :: dot :: rest if (lastIdToken.tokenType.isId || lastIdToken.tokenType == THIS) && dot.tokenType == DOT ⇒
(rest.reverse, dot, lastIdToken)
}
}
private object JustIdOrThis {
def unapply(tokens: List[Token]) = condOpt(tokens) {
case List(idToken) if (idToken.tokenType.isId || idToken.tokenType == THIS) ⇒ idToken
}
}
private def simpleExpr(): List[ExprElement] = {
var canApply = true
val firstPart =
if (isLiteral) exprElementFlatten2(literal())
else currentTokenType match {
case XML_START_OPEN | XML_COMMENT | XML_CDATA | XML_UNPARSED | XML_PROCESSING_INSTRUCTION ⇒
exprElementFlatten2(xmlLiteral())
case VARID | OTHERID | PLUS | MINUS | STAR | PIPE | TILDE | EXCLAMATION | THIS | SUPER ⇒
// val callExpr = CallExpr(Some(previousPart, dot), selector_, None, Nil, None)
List(pathC(thisOK = true, typeOK = false))
case USCORE ⇒
exprElementFlatten2(nextToken())
case LPAREN ⇒
val (lparen, parenBody, rparen) = makeParens(commaSeparated(expr))
exprElementFlatten2(ParenExpr(lparen, exprElementFlatten2(parenBody), rparen))
case LBRACE ⇒
canApply = false
exprElementFlatten2(blockExpr())
case NEW ⇒
canApply = false
val newToken = nextToken()
val template_ = template(isTrait = false)
List(New(newToken, template_))
case _ ⇒
throw new ScalaParserException("illegal start of simple expression: " + currentToken)
}
simpleExprRest(firstPart, canApply)
}
private def simpleExprRest(previousPart: List[ExprElement], canApply: Boolean): List[ExprElement] = {
val newLineOpt = if (canApply) newLineOptWhenFollowedBy(LBRACE) else None
currentTokenType match {
case DOT ⇒
require(newLineOpt.isEmpty)
val dot = nextToken()
val selector_ = selector()
val callExpr = CallExpr(Some(previousPart, dot), selector_, None, Nil, None)
simpleExprRest(List(callExpr), canApply = true)
case LBRACKET ⇒
require(newLineOpt.isEmpty)
val identifierCond = true // TODO: missing check: case Ident(_) | Select(_, _) => OK, just means we accept multiple type param [X][Y] clauses
if (identifierCond) {
val typeArgs_ = TypeExprElement(exprTypeArgs())
val updatedPart = previousPart match {
case List(callExpr: CallExpr) ⇒
if (callExpr.typeArgsOpt.isDefined || callExpr.newLineOptsAndArgumentExprss.nonEmpty)
exprElementFlatten2(previousPart, newLineOpt, typeArgs_) // TODO: put these into some new type of AST node
else
List(callExpr.copy(typeArgsOpt = Some(typeArgs_)))
case _ ⇒ exprElementFlatten2(previousPart, newLineOpt, typeArgs_)
}
simpleExprRest(updatedPart, canApply = true)
} else
exprElementFlatten2(previousPart)
case LPAREN | LBRACE if canApply ⇒
val argumentExprs_ = argumentExprs().get
val updatedPart = previousPart match {
case List(callExpr: CallExpr) ⇒ List(callExpr.copy(newLineOptsAndArgumentExprss = callExpr.newLineOptsAndArgumentExprss :+ (newLineOpt, argumentExprs_)))
case _ ⇒ exprElementFlatten2(previousPart, newLineOpt, argumentExprs_)
}
simpleExprRest(updatedPart, canApply = true)
case USCORE ⇒
require(newLineOpt.isEmpty)
val uscore = nextToken()
previousPart match {
case List(callExpr: CallExpr) ⇒ List(callExpr.copy(uscoreOpt = Some(uscore)))
case _ ⇒ List(PostfixExpr(previousPart, uscore))
}
case _ ⇒
require(newLineOpt.isEmpty)
previousPart
}
}
/**
* @return Some(..) if next token is LBRACE or LPAREN
*/
private def argumentExprs(): Option[ArgumentExprs] = {
// println("argumentExprs(): " + currentToken)
def argument() = Argument(expr())
def args() = commaSeparated(argument())
condOpt(currentTokenType) {
case LBRACE ⇒ BlockArgumentExprs(exprElementFlatten2(blockExpr()))
case LPAREN ⇒
val (lparen, body, rparen) = inParens { if (RPAREN) Nil else exprElementFlatten2(args()) }
ParenArgumentExprs(lparen, body, rparen)
}
}
private def multipleArgumentExprs(): List[ArgumentExprs] =
if (!LPAREN) Nil
else argumentExprs().get :: multipleArgumentExprs()
private def blockExpr(): BlockExpr = {
val (lbrace, body, rbrace) = inBraces {
if (justCase) Left(caseClauses())
else Right(block())
}
BlockExpr(lbrace, body, rbrace)
}
private def block(): StatSeq = blockStatSeq()
private def caseClauses(): CaseClauses = {
val caseClauses_ = caseSeparated {
(pattern(), guard(), caseBlock())
} map {
case (caseToken, (pattern_, guardOption, (arrow, blockStatSeq_))) ⇒
CaseClause(CasePattern(caseToken, pattern_, guardOption, arrow), blockStatSeq_)
}
if (caseClauses_.isEmpty)
accept(CASE)
CaseClauses(caseClauses_)
}
private def caseBlock(): (Token, StatSeq) = {
val arrowToken = accept(ARROW)
val blockStatSeq_ = block()
(arrowToken, blockStatSeq_)
}
private def guard(): Option[Guard] = {
if (IF) {
val ifToken = nextToken()
val postfixExpr_ = postfixExpr()
Some(Guard(ifToken, Expr(postfixExpr_)))
} else
None
}
private def enumerators(): Enumerators = {
val newStyle = !VAL
val initialGenerator = generator(eqOK = false)
val otherEnumerators = ListBuffer[(Token, Enumerator)]()
while (isStatSep) {
val statSep = nextToken()
val enumerator = if (newStyle) {
if (IF) guard().get
else generator(eqOK = true)
} else {
if (VAL) generator(eqOK = true)
else expr()
}
otherEnumerators += ((statSep, enumerator))
}
Enumerators(initialGenerator, otherEnumerators.toList)
}
private def generator(eqOK: Boolean): Generator = {
val valOption = if (VAL) Some(nextToken()) else None
val pattern_ = noSeq.pattern1()
val equalsOrArrowToken = if (EQUALS && eqOK) nextToken() else accept(LARROW)
val expr_ = expr()
val guards = ListBuffer[Guard]()
while (IF) guards += guard().get
Generator(valOption, pattern_, equalsOrArrowToken, expr_, guards.toList)
}
trait SeqContextSensitive extends PatternContextSensitive {
def isSequenceOK: Boolean
def isXML: Boolean = false
def functionArgType() = argType()
def argType(): List[TypeElement] = currentTokenType match {
case USCORE ⇒
val uscore = nextToken()
val wildcardTypeOpt = if (SUBTYPE || SUPERTYPE) Some(wildcardType()) else None
typeElementFlatten3(uscore, wildcardTypeOpt)
case _ if isIdent && isVariableName(currentToken.text) ⇒
typeElementFlatten3(ident())
case _ ⇒
List(typ())
}
def patterns(): List[ExprElement] = {
exprElementFlatten2(commaSeparated(pattern()))
}
def pattern(): Expr = { // Scalac now uses a loop() method, but this is still OK:
val firstPattern = pattern1()
var currentExpr: ExprElement = firstPattern
if (PIPE)
while (PIPE) {
val pipeToken = nextToken()
val otherPattern = pattern1()
currentExpr = InfixExpr(List(currentExpr), pipeToken, None, List(otherPattern))
}
makeExpr(currentExpr)
}
def pattern1(): Expr = {
val firstPattern = pattern2()
val colonTypeOpt = if (COLON) { // TODO: case Ident(name) if (treeInfo.isVarPattern(p) && in.token == COLON)
val colonToken = nextToken()
val compoundType_ = Some(TypeExprElement(compoundType()))
Some(colonToken, compoundType_)
} else
None
makeExpr(firstPattern, colonTypeOpt)
}
def pattern2(): Expr = {
val firstPattern = pattern3()
val atOtherOpt = if (AT) {
// TODO: Compare Parsers.scala
optional {
val atToken = nextToken()
val otherPattern = pattern3()
(atToken, otherPattern)
}
} else
None
makeExpr(firstPattern, atOtherOpt)
}
def pattern3(): List[ExprElement] = {
val simplePattern1 = simplePattern()
if (isSequenceOK) {
simplePattern1.flatMap(_.tokens).map(_.tokenType) match {
case List(USCORE) if STAR ⇒
lookahead(1) match {