/
ScalametaParser.scala
4878 lines (4403 loc) · 170 KB
/
ScalametaParser.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 scala.meta
package internal
package parsers
import scala.annotation.tailrec
import scala.collection.immutable._
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.language.implicitConversions
import scala.reflect.{ClassTag, classTag}
import scala.util.Try
import scala.util.Success
import scala.util.Failure
import scala.meta.classifiers._
import scala.meta.inputs._
import scala.meta.internal.parsers.Location._
import scala.meta.internal.parsers.Absolutize._
import scala.meta.internal.trees._
import scala.meta.parsers._
import scala.meta.prettyprinters._
import scala.meta.tokens._
import scala.meta.tokens.Token._
import scala.meta.trees.Origin
import org.scalameta._
import org.scalameta.invariants._
class ScalametaParser(input: Input)(implicit dialect: Dialect) { parser =>
import ScalametaParser._
private val scannerTokens: ScannerTokens = ScannerTokens(input)
import scannerTokens._
/* ------------- NESTED CONTEXT OBJECTS ----------------------------------------- */
// must all be parser-specific, to avoid sharing state with other parsers
private object QuotedSpliceContext extends NestedContext
private object QuotedPatternContext extends NestedContext
private object ReturnTypeContext extends NestedContext
private object TypeBracketsContext extends NestedContext
private object PatternTypeContext extends NestedContext
/* ------------- PARSER ENTRY POINTS -------------------------------------------- */
def parseRule[T <: Tree](rule: this.type => T): T = {
parseRule(rule(this))
}
def parseRule[T <: Tree](rule: => T): T = {
// NOTE: can't require in.tokenPos to be at -1, because TokIterator auto-rewinds when created
// require(in.tokenPos == -1 && debug(in.tokenPos))
accept[BOF]
parseRuleAfterBOF(rule)
}
private def parseRuleAfterBOF[T <: Tree](rule: => T): T = {
val start = prevTokenPos
val t = rule
// NOTE: can't have prevTokenPos here
// because we need to subsume all the trailing trivia
val end = tokenPos
accept[EOF]
atPos(start, end)(t)
}
// Entry points for Parse[T]
def parseStat(): Stat = parseRule {
if (dialect.allowUnquotes) quasiquoteStat() else entrypointStat()
}
def parseTerm(): Term = parseRule {
if (dialect.allowUnquotes) quasiquoteExpr() else entrypointExpr()
}
def parseUnquoteTerm(): Term = parseRule(unquoteExpr())
def parseTermParam(): Term.Param = parseRule {
if (dialect.allowUnquotes) quasiquoteTermParam() else entrypointTermParam()
}
def parseType(): Type = parseRule {
if (dialect.allowUnquotes) quasiquoteType() else entrypointType()
}
def parseTypeParam(): Type.Param = parseRule {
if (dialect.allowUnquotes) quasiquoteTypeParam() else entrypointTypeParam()
}
def parsePat(): Pat = parseRule {
if (dialect.allowUnquotes) quasiquotePattern() else entrypointPattern()
}
def parseUnquotePat(): Pat = parseRule(unquotePattern())
def parseCase(): Case = parseRule {
if (dialect.allowUnquotes) quasiquoteCase() else entrypointCase()
}
def parseCtor(): Ctor = parseRule {
if (dialect.allowUnquotes) quasiquoteCtor() else entrypointCtor()
}
def parseInit(): Init = parseRule {
if (dialect.allowUnquotes) quasiquoteInit() else entrypointInit()
}
def parseSelf(): Self = parseRule {
if (dialect.allowUnquotes) quasiquoteSelf() else entrypointSelf()
}
def parseTemplate(): Template = parseRule {
if (dialect.allowUnquotes) quasiquoteTemplate() else entrypointTemplate()
}
def parseMod(): Mod = parseRule {
if (dialect.allowUnquotes) quasiquoteModifier() else entrypointModifier()
}
def parseEnumerator(): Enumerator = parseRule {
if (dialect.allowUnquotes) quasiquoteEnumerator() else entrypointEnumerator()
}
def parseImporter(): Importer = parseRule {
if (dialect.allowUnquotes) quasiquoteImporter() else entrypointImporter()
}
def parseImportee(): Importee = parseRule {
if (dialect.allowUnquotes) quasiquoteImportee() else entrypointImportee()
}
def parseSource(): Source = parseRule(parseSourceImpl())
private def parseSourceImpl(): Source = {
if (dialect.allowUnquotes) quasiquoteSource() else entrypointSource()
}
def parseAmmonite(): MultiSource = parseRule(entryPointAmmonite())
def entryPointAmmonite(): MultiSource = {
require(input.isInstanceOf[Input.Ammonite])
val builder = List.newBuilder[Source]
doWhile {
builder += parseRuleAfterBOF(parseSourceImpl())
} {
in.token match {
case t: Token.EOF if t.end < input.chars.length =>
in.next()
accept[Token.At]
accept[Token.BOF]
true
case _ => false
}
}
MultiSource(builder.result())
}
/* ------------- TOKEN STREAM HELPERS -------------------------------------------- */
@inline private def isColonIndent(): Boolean = token.is[Colon] && isIndentAfter()
@inline private def isIndentAfter(): Boolean = peekToken.is[Indentation.Indent]
/* ------------- PARSER-SPECIFIC TOKENS -------------------------------------------- */
var in: TokenIterator = {
LazyTokenIterator(scannerTokens)
}
@inline def tokenPos = in.tokenPos
@inline def prevTokenPos = in.prevTokenPos
@inline def token = in.token
@inline def prevToken = in.prevToken
@inline def peekIndex = in.peekIndex
@inline def peekToken = in.peekToken
@inline def next() = in.next()
def nextTwice() = { next(); next() }
@inline private def nextIf(cond: Boolean): Boolean = {
if (cond) next()
cond
}
/* ------------- PARSER COMMON -------------------------------------------- */
/**
* Scoping operator used to temporarily look into the future. Backs up token iterator before
* evaluating a block and restores it after.
*/
@inline final def ahead[T](body: => T): T = {
val forked = in.fork
try next(body)
finally in = forked
}
@inline private def tryAhead[T: ClassTag]: Boolean =
nextIf(peekToken.is[T])
@inline private def tryAheadNot[T: ClassTag]: Boolean =
nextIf(!peekToken.is[T])
private def unreachable(debuggees: Map[String, Any]): Nothing = UnreachableError.raise(debuggees)
private def unreachable(token: Token): Nothing = unreachable(Map("token" -> token))
private def unreachable: Nothing = unreachable(Map.empty[String, Any])
private def tryAhead(cond: => Boolean): Boolean = {
val forked = in.fork
next()
val ok = cond
if (!ok) in = forked
ok
}
private def tryParse[A](bodyFunc: => Option[A]): Option[A] = {
val forked = in.fork
val body = bodyFunc
if (body.isEmpty) in = forked
body
}
private def tryAhead[A](bodyFunc: => Option[A]): Option[A] =
tryParse(next(bodyFunc))
/** evaluate block after shifting next */
@inline private def next[T](body: => T): T = {
next()
body
}
@inline final def inParens[T](body: => T): T = {
accept[LeftParen]
inParensAfterOpen(body)
}
@inline final def inParensOr[T](body: => T)(ifEmpty: => T): T = {
accept[LeftParen]
inParensAfterOpenOr(body)(ifEmpty)
}
@inline private def inParensOnOpen[T](body: => T): T = {
next()
inParensAfterOpen(body)
}
@inline private def inParensOnOpenOr[T](body: => T)(ifEmpty: => T): T = {
next()
inParensAfterOpenOr(body)(ifEmpty)
}
@inline private def inParensAfterOpen[T](body: T): T = {
acceptAfterOptNL[RightParen]
body
}
@inline private def inParensAfterOpenOr[T](body: => T)(ifEmpty: => T): T =
if (acceptOpt[RightParen]) ifEmpty
else inParensAfterOpen(body)
@inline final def inBraces[T](body: => T): T = {
inBracesOr(body)(syntaxErrorExpected[LeftBrace])
}
@inline final def inBracesOr[T](body: => T)(ifEmpty: => T): T = {
newLineOpt()
if (acceptOpt[LeftBrace]) inBracesAfterOpen(body) else ifEmpty
}
@inline private def inBracesOnOpen[T](body: => T): T = {
next()
inBracesAfterOpen(body)
}
@inline private def inBracesAfterOpen[T](body: T): T = {
acceptAfterOptNL[RightBrace]
body
}
@inline final def indented[T](body: => T): T = {
accept[Indentation.Indent]
indentedAfterOpen(body)
}
@inline private def indentedOnOpen[T](body: => T): T = {
next()
indentedAfterOpen(body)
}
@inline private def indentedAfterOpen[T](body: T): T = {
acceptAfterOptNL[Indentation.Outdent]
body
}
@inline final def inBracesOrNil[T](body: => List[T]): List[T] = inBracesOr(body)(Nil)
@inline final def dropAnyBraces[T](body: => T): T =
inBracesOr(body)(body)
@inline final def inBrackets[T](body: => T): T = {
accept[LeftBracket]
inBracketsAfterOpen(body)
}
@inline private def inBracketsOnOpen[T](body: => T): T = {
next()
inBracketsAfterOpen(body)
}
@inline private def inBracketsAfterOpen[T](body: T): T = {
accept[RightBracket]
body
}
/* ------------- POSITION HANDLING ------------------------------------------- */
case object AutoPos extends Pos {
def startTokenPos = tokenPos
def endTokenPos = prevTokenPos
}
case object EndPosPreOutdent extends EndPos {
def endTokenPos = if (token.is[Indentation.Outdent]) tokenPos else prevTokenPos
}
implicit def intToIndexPos(index: Int): Pos = new IndexPos(index)
implicit def treeToTreePos(tree: Tree): Pos = new TreePos(tree)
implicit def optionTreeToPos(tree: Option[Tree]): Pos = tree.fold[Pos](AutoPos)(treeToTreePos)
implicit def modsToPos(mods: List[Mod]): Pos = mods.headOption
def auto = AutoPos
def atPos[T <: Tree](start: StartPos, end: EndPos)(body: => T): T = {
atPos(start.startTokenPos, end)(body)
}
def atPosOpt[T <: Tree](start: StartPos, end: EndPos)(body: => T): T = {
atPosOpt(start.startTokenPos, end)(body)
}
@inline
def atPos[T <: Tree](start: Int, end: EndPos)(body: T): T = {
atPosWithBody(start, body, end.endTokenPos)
}
def atPosOpt[T <: Tree](start: Int, end: EndPos)(body: T): T = {
body.origin match {
case o: Origin.Parsed if o.source eq originSource => body
case _ => atPos(start, end)(body)
}
}
def atPos[T <: Tree](pos: Int)(body: => T): T = {
atPosWithBody(pos, body, pos)
}
def atCurPos[T <: Tree](body: => T): T = {
atPos(tokenPos)(body)
}
def atCurPosNext[T <: Tree](body: => T): T = {
try atCurPos(body)
finally next()
}
private val originSource = new Origin.ParsedSource(input)
def atPosWithBody[T <: Tree](startPos: Int, body: T, endPos: Int): T = {
@tailrec def getStart(pos: Int): Int =
if (pos > endPos) startPos else if (tokens(pos).is[Trivia]) getStart(pos + 1) else pos
@tailrec def getEnd(pos: Int): Int =
if (!tokens(pos).is[Whitespace]) pos else if (pos == startPos) endPos else getEnd(pos - 1)
val start = getStart(startPos)
val end = if (endPos < startPos) startPos - 1 else getEnd(endPos)
val endExcl = if (start == end && tokens(start).is[Trivia]) end else end + 1
body.withOrigin(Origin.Parsed(originSource, start, endExcl))
}
def atPosTry[T <: Tree](start: StartPos, end: EndPos)(body: => Try[T]): Try[T] = {
val startTokenPos = start.startTokenPos
body.map(atPos(startTokenPos, end))
}
def atPosTryOpt[T <: Tree](start: StartPos, end: EndPos)(body: => Try[T]): Try[T] = {
val startTokenPos = start.startTokenPos
body.map(atPosOpt(startTokenPos, end))
}
def autoPos[T <: Tree](body: => T): T = atPos(start = auto, end = auto)(body)
def autoPosOpt[T <: Tree](body: => T): T = atPosOpt(start = auto, end = auto)(body)
@inline
def autoEndPos[T <: Tree](start: Int)(body: => T): T = atPos(start = start, end = auto)(body)
@inline
def autoEndPosOpt[T <: Tree](start: Int)(body: => T): T =
atPosOpt(start = start, end = auto)(body)
@inline
def autoEndPos[T <: Tree](start: StartPos)(body: => T): T = autoEndPos(start.startTokenPos)(body)
@inline
def autoPrevPos[T <: Tree](body: => T) = autoEndPos(prevTokenPos)(body)
def autoPosTry[T <: Tree](body: => Try[T]): Try[T] =
atPosTry(start = auto, end = auto)(body)
/* ------------- ERROR HANDLING ------------------------------------------- */
final lazy val reporter = Reporter()
import this.reporter._
implicit class XtensionToken(token: Token) {
def is[T: ClassTag] = {
classTag[T].runtimeClass.isAssignableFrom(token.getClass())
}
}
def syntaxErrorExpected[T <: Token: ClassTag]: Nothing = {
val expected = classTag[T].runtimeClass.getSimpleName match {
case "Semicolon" => ";"
case "Hash" => "#"
case "Colon" => ":"
case "Viewbound" => "<%"
case "LeftArrow" => "<-"
case "Subtype" => "<:"
case "Equals" => "="
case "RightArrow" => "=>"
case "Supertype" => ">:"
case "At" => "@"
case "Underscore" => "_"
case "TypeLambdaArrow" => "=>>"
case "ContextArrow" => "?=>"
case "MacroQuote" => "'"
case "MacroSplice" => "$"
case "LeftParen" => "("
case "RightParen" => ")"
case "Comma" => ","
case "Dot" => "."
case "LeftBracket" => "["
case "RightBracket" => "]"
case "LeftBrace" => "{"
case "RightBrace" => "}"
case "Ident" => "identifier"
case "EOF" => "end of file"
case "BOF" => "beginning of file"
case other => other.toLowerCase().stripPrefix("kw")
}
syntaxError(s"${expected} expected but ${token.name} found", at = token)
}
def expect[T <: Token: ClassTag]: Unit = if (!token.is[T]) syntaxErrorExpected[T]
/** Consume one token of the specified type, or signal an error if it is not there. */
def accept[T <: Token: ClassTag]: Unit = {
expect[T]
if (token.isNot[EOF]) next()
}
/** If current token is T consume it. */
@inline private def acceptOpt[T: ClassTag]: Boolean =
nextIf(token.is[T])
/** If current token is T consume it. */
@inline private def acceptOpt(unapply: Token => Boolean): Boolean =
nextIf(unapply(token))
private def acceptIfAfterOpt[A <: Token: ClassTag, B <: Token: ClassTag]: Boolean =
if (token.is[A]) { next(); true }
else if (token.is[B] && peekToken.is[A]) { nextTwice(); true }
else false
@inline private def acceptIfAfterOptNL[T <: Token: ClassTag]: Boolean =
acceptIfAfterOpt[T, AtEOL]
@inline private def acceptAfterOpt[A <: Token: ClassTag, B <: Token: ClassTag]: Unit = {
if (token.is[B]) next()
accept[A]
}
@inline private def acceptAfterOptNL[T <: Token: ClassTag]: Unit =
acceptAfterOpt[T, AtEOL]
def acceptStatSep(): Unit = token match {
case _: AtEOL => next()
case t if isEndMarkerIntro(tokenPos) =>
case _ => accept[Semicolon]
}
def acceptStatSepOpt() =
if (!StatSeqEnd(token))
acceptStatSep()
/* ------------- MODIFIER VALIDATOR --------------------------------------- */
def rejectMod[M <: Mod](
mods: collection.Iterable[Mod],
errorMsg: String
)(implicit tag: ClassTag[M]) = {
mods.first[M].foreach(m => syntaxError(errorMsg, at = m))
}
def rejectModCombination[M1 <: Mod: ClassTag, M2 <: Mod: ClassTag](
mods: collection.Iterable[Mod],
culpritOpt: => Option[String] = None
) =
mods.first[M2].foreach(rejectModWith[M1](_, mods, culpritOpt))
def rejectModWith[M <: Mod: ClassTag](
m2: Mod,
mods: collection.Iterable[Mod],
culpritOpt: => Option[String] = None
) = mods.first[M].foreach { m =>
val errorMsg = Messages.IllegalCombinationModifiers(m, m2)
val forCulprit = culpritOpt.fold("")(formatCulprit)
val enrichedErrorMsg = errorMsg + forCulprit
syntaxError(enrichedErrorMsg, at = m)
}
private def formatCulprit(culprit: String): String = s" for: $culprit"
def onlyAllowedMods[M1 <: Mod, M2 <: Mod](mods: List[Mod], culprit: String)(
implicit classifier1: Classifier[Mod, M1],
classifier2: Classifier[Mod, M2]
): Unit = {
onlyAllowedMods(mods, List(classifier1.apply, classifier2.apply), culprit)
}
def onlyAllowedMods(mods: List[Mod], matchers: List[Mod => Boolean], culprit: String): Unit = {
mods
.foreach {
case m if matchers.exists(f => f(m)) =>
case m => syntaxError(s" Invalid modifier ${m}${formatCulprit(culprit)}", at = m)
}
}
def summonClassifierFunc[A, B](implicit v: Classifier[A, B]): A => Boolean = v.apply
def onlyAcceptMod[M <: Mod: ClassTag, T](
mods: List[Mod],
errorMsg: String
)(implicit classifier: TokenClassifier[T]) =
onlyAcceptMod[M](classifier.apply)(mods)(errorMsg)
def onlyAcceptMod[M <: Mod: ClassTag](ok: Token => Boolean)(mods: List[Mod])(errorMsg: String) =
if (!ok(token)) {
mods.first[M].foreach(m => syntaxError(errorMsg, at = m))
}
class InvalidModCombination[M1 <: Mod, M2 <: Mod](m1: M1, m2: M2) {
def errorMessage: String = Messages.IllegalCombinationModifiers(m1, m2)
}
private implicit val InvalidOpenFinal: InvalidModCombination[Mod.Open, Mod.Final] =
new InvalidModCombination(Mod.Open(), Mod.Final())
private implicit val InvalidOpenSealed: InvalidModCombination[Mod.Open, Mod.Sealed] =
new InvalidModCombination(Mod.Open(), Mod.Sealed())
private implicit val InvalidCaseImplicit: InvalidModCombination[Mod.Case, Mod.Implicit] =
new InvalidModCombination(Mod.Case(), Mod.Implicit())
private implicit val InvalidFinalAbstract: InvalidModCombination[Mod.Final, Mod.Abstract] =
new InvalidModCombination(Mod.Final(), Mod.Abstract())
private implicit val InvalidFinalSealed: InvalidModCombination[Mod.Final, Mod.Sealed] =
new InvalidModCombination(Mod.Final(), Mod.Sealed())
private implicit val InvalidOverrideAbstract: InvalidModCombination[Mod.Override, Mod.Abstract] =
new InvalidModCombination(Mod.Override(), Mod.Abstract())
private implicit val InvalidPrivateProtected: InvalidModCombination[Mod.Private, Mod.Protected] =
new InvalidModCombination(Mod.Private(Name.Anonymous()), Mod.Protected(Name.Anonymous()))
private implicit val InvalidProtectedPrivate: InvalidModCombination[Mod.Protected, Mod.Private] =
new InvalidModCombination(Mod.Protected(Name.Anonymous()), Mod.Private(Name.Anonymous()))
/* -------------- TOKEN CLASSES ------------------------------------------- */
private def isIdentAnd(token: Token, pred: String => Boolean): Boolean = token match {
case Ident(x) => pred(x)
case _ => false
}
def isUnaryOp: Boolean = isIdentAnd(token, _.isUnaryOp)
def isIdentExcept(except: String) = isIdentAnd(token, _ != except)
def isIdentOf(tok: Token, name: String) = isIdentAnd(tok, _ == name)
@inline def isStar: Boolean = isStar(token)
def isStar(tok: Token): Boolean = isIdentOf(tok, "*")
def isVarargStarParam(allowRepeated: Boolean) =
isStar && isVarargParamOnStar(allowRepeated)
def isVarargParamOnStar(allowRepeated: Boolean) =
allowRepeated && dialect.allowPostfixStarVarargSplices && peekToken.is[RightParen]
private trait MacroIdent {
protected def ident(token: Token): Option[String]
final def unapply(token: Token): Option[String] =
if (dialect.allowSpliceAndQuote && QuotedSpliceContext.isInside()) ident(token) else None
}
private object MacroSplicedIdent extends MacroIdent {
protected def ident(token: Token): Option[String] = token match {
case Ident(value) if value.length > 1 && value.charAt(0) == '$' => Some(value.substring(1))
case _ => None
}
}
private object MacroQuotedIdent extends MacroIdent {
protected def ident(token: Token): Option[String] = token match {
case Constant.Symbol(value) => Some(value.name)
case _ => None
}
}
/* ---------- TREE CONSTRUCTION ------------------------------------------- */
private def listBy[T](f: ListBuffer[T] => Unit): List[T] = {
val buf = new ListBuffer[T]
f(buf)
buf.toList
}
def ellipsis[T <: Tree: AstInfo: ClassTag](
ell: Ellipsis,
rank: Int,
extraSkip: => Unit = {}
): T = {
if (ell.rank != rank) {
syntaxError(Messages.QuasiquoteRankMismatch(ell.rank, rank), at = ell)
}
ellipsis(ell, extraSkip)
}
def ellipsis[T <: Tree: AstInfo: ClassTag](ell: Ellipsis): T with Quasi = ellipsis(ell, {})
def ellipsis[T <: Tree: AstInfo: ClassTag](
ell: Ellipsis,
extraSkip: => Unit
): T with Quasi = autoPos {
if (!dialect.allowUnquotes) {
syntaxError(s"$dialect doesn't support ellipses", at = ell)
}
next()
extraSkip
// unquote returns a rank=0 quasi tree
val tree = token match {
case LeftParen() => inParensOnOpen(unquote[T])
case LeftBrace() => inBracesOnOpen(unquote[T])
case t: Unquote => unquote[T](t)
case t => syntaxError(s"$$, ( or { expected but ${t.name} found", at = t)
}
// NOTE: In the case of an unquote nested directly under ellipsis, we get a bit of a mixup.
// Unquote's pt may not be directly equal unwrapped ellipsis's pt, but be its refinement instead.
// For example, in `new { ..$stats }`, ellipsis's pt is List[Stat], but quasi's pt is Term.
// This is an artifact of the current implementation, so we just need to keep it mind and work around it.
assert(
classTag[T].runtimeClass.isAssignableFrom(tree.pt),
s"ellipsis: ${ell},\ntree: ${tree},\nstructure: ${tree.structure}"
)
quasi[T](ell.rank, tree)
}
private def unquote[T <: Tree: AstInfo](unquote: Unquote): T with Quasi = {
require(unquote.input.chars(unquote.start + 1) != '$')
val unquoteDialect = dialect.unquoteParentDialect
if (null eq unquoteDialect) {
syntaxError(s"$dialect doesn't support unquotes", at = unquote)
}
// NOTE: I considered having Input.Slice produce absolute positions from the get-go,
// but then such positions wouldn't be usable with Input.Slice.chars.
val unquotedTree = atCurPosNext {
try {
val unquoteInput = Input.Slice(input, unquote.start + 1, unquote.end)
val unquoteParser = new ScalametaParser(unquoteInput)(unquoteDialect)
if (dialect.allowTermUnquotes) unquoteParser.parseUnquoteTerm()
else if (dialect.allowPatUnquotes) unquoteParser.parseUnquotePat()
else unreachable
} catch {
case ex: Exception => throw ex.absolutize
}
}
copyPos(unquotedTree)(quasi[T](0, unquotedTree))
}
def unquote[T <: Tree: AstInfo]: T with Quasi =
token match {
case t: Unquote => unquote[T](t)
case _ => unreachable(token)
}
final def tokenSeparated[Sep: ClassTag, T <: Tree: AstInfo: ClassTag](
sepFirst: Boolean,
part: Int => T
): List[T] = listBy[T] { ts =>
@tailrec
def iter(sep: Boolean): Unit = token match {
case t: Ellipsis =>
ts += ellipsis[T](t, 1)
iter(false)
case _ if sep =>
ts += part(ts.length)
iter(false)
case _ if acceptOpt[Sep] =>
iter(true)
case _ =>
}
iter(!sepFirst)
}
@inline final def commaSeparated[T <: Tree: AstInfo: ClassTag](part: => T): List[T] =
commaSeparatedWithIndex(_ => part)
@inline final def commaSeparatedWithIndex[T <: Tree: AstInfo: ClassTag](part: Int => T): List[T] =
tokenSeparated[Comma, T](sepFirst = false, part)
private def makeTuple[A <: Tree](lpPos: Int, body: List[A], zero: => A, tuple: List[A] => A)(
single: A => Either[List[A], A]
): A = body match {
case Nil => autoEndPos(lpPos)(zero)
case (q: Quasi) :: Nil if q.rank == 1 => copyPos(q)(tuple(body))
case t :: Nil =>
single(t) match {
case Right(x) => x
case Left(x) => autoEndPos(lpPos)(tuple(x))
}
case _ => autoEndPos(lpPos)(tuple(body))
}
private def makeTupleTerm(
single: Term => Either[List[Term], Term]
)(lpPos: Int, body: List[Term]): Term = {
makeTuple(lpPos, body, Lit.Unit(), Term.Tuple.apply)(single)
}
private def makeTupleTerm(lpPos: Int, body: List[Term]): Term = {
makeTupleTerm(Right(_))(lpPos, body)
}
private def makeTupleType(lpPos: Int, body: List[Type], zero: => Type, wrap: Boolean): Type = {
makeTuple(lpPos, body, zero, Type.Tuple.apply) {
maybeAnonymousLambda(_) match {
case t: Type.Tuple if wrap && t.args.lengthCompare(1) > 0 => Left(t :: Nil)
case t => Right(t)
}
}
}
private def makeTupleType(lpPos: Int, body: List[Type]): Type = {
def invalidLiteralUnitType =
syntaxError("illegal literal type (), use Unit instead", at = token.pos)
makeTupleType(lpPos, body, invalidLiteralUnitType, wrap = false)
}
private def inParensOrTupleOrUnitExpr(allowRepeated: Boolean): Term = {
val lpPos = tokenPos
val maybeTupleArgs = inParensOnOpenOr(
commaSeparated(expr(location = PostfixStat, allowRepeated = allowRepeated))
)(Nil)
if (maybeTupleArgs.lengthCompare(1) > 0) maybeTupleArgs.foreach {
case arg: Term.Repeated =>
syntaxError("repeated argument not allowed here", at = arg.tokens.last)
case _ =>
}
makeTupleTerm(x => Right(maybeAnonymousFunction(x)))(lpPos, maybeTupleArgs)
}
/* -------- IDENTIFIERS AND LITERALS ------------------------------------------- */
/**
* Methods which implicitly propagate the context in which they were called: either in a pattern
* context or not. Formerly, this was threaded through numerous methods as boolean isPattern.
*/
trait PatternContextSensitive {
private def tupleInfixType(allowFunctionType: Boolean = true): Type = autoPosOpt {
// NOTE: This is a really hardcore disambiguation caused by introduction of Type.Method.
// We need to accept `(T, U) => W`, `(x: T): x.U` and also support unquoting.
var hasParams = false
var hasImplicits = false
var hasTypes = false
@tailrec
def paramOrType(modsBuf: mutable.Builder[Mod, List[Mod]]): Type = token match {
case t: Ellipsis =>
ellipsis[Type](t)
case t: Unquote =>
unquote[Type](t)
case KwImplicit() if !hasImplicits =>
next()
hasImplicits = true
paramOrType(modsBuf)
case t: Ident if tryAhead[Colon] =>
if (hasTypes)
syntaxError(
"can't mix function type and dependent function type syntaxes",
at = token
)
hasParams = true
val startPos = prevTokenPos
next() // skip colon
val mods = modsBuf.result()
val modPos = if (mods.isEmpty) startPos else mods.head.startTokenPos
val name = atPos(startPos)(Type.Name(t.value))
autoEndPos(modPos)(Type.TypedParam(name, typ(), mods))
case soft.KwErased() if allowFunctionType =>
paramOrType(modsBuf += atCurPosNext(Mod.Erased()))
case _ =>
if (hasParams)
syntaxError(
"can't mix function type and dependent function type syntaxes",
at = token
)
hasTypes = true
val mods = modsBuf.result()
val tpe = paramType()
if (mods.isEmpty) tpe else autoEndPos(mods.head)(Type.FunctionArg(mods, tpe))
}
val openParenPos = tokenPos
val ts = inParensOr(commaSeparated(paramOrType(List.newBuilder[Mod])))(Nil)
// NOTE: can't have this, because otherwise we run into #312
// newLineOptWhenFollowedBy[LeftParen]
if (hasParams && !dialect.allowDependentFunctionTypes)
syntaxError("dependent function types are not supported", at = token)
if (!hasTypes && !hasImplicits && token.is[LeftParen]) {
val message = "can't have multiple parameter lists in function types"
syntaxError(message, at = token)
}
def maybeFunc = getAfterOptNewLine(token match {
case _: RightArrow => Some(typeFuncOnArrow(openParenPos, ts, Type.Function(_, _)))
case _: ContextArrow => Some(typeFuncOnArrow(openParenPos, ts, Type.ContextFunction(_, _)))
case _ => None
})
(if (allowFunctionType) maybeFunc else None).getOrElse {
ts.find {
case _: Type.ByName | _: Type.Repeated => true
case t: Type.FunctionParamOrArg => t.mods.nonEmpty
case _ => false
}.foreach { t =>
syntaxError(s"'${t.productPrefix}' type not allowed here", at = t)
}
val simple = simpleTypeRest(makeTupleType(openParenPos, ts), openParenPos)
val compound = compoundTypeRest(annotTypeRest(simple, openParenPos), openParenPos)
infixTypeRest(compound) match {
case `compound` => compound
case t => autoEndPos(openParenPos)(t)
}
}
}
private def typeLambdaOrPoly(): Type = {
val quants = typeParamClauseOpt(ownerIsType = true, ctxBoundsAllowed = false)
newLineOpt()
token match {
case _: TypeLambdaArrow => next(); Type.Lambda(quants, typeIndentedOpt())
case t: RightArrow =>
next()
typeIndentedOpt() match {
case tpe: Type.FunctionType => Type.PolyFunction(quants, tpe)
case _ => syntaxError("polymorphic function types must have a value parameter", at = t)
}
case t => syntaxError("expected =>> or =>", at = t)
}
}
def typeIndentedOpt(): Type = {
if (acceptOpt[Indentation.Indent]) {
indentedAfterOpen(typ())
} else {
typ()
}
}
def typ(): Type = autoPosOpt {
val startPos = tokenPos
val t: Type =
if (token.is[LeftBracket] && dialect.allowTypeLambdas) typeLambdaOrPoly()
else infixTypeOrTuple()
getAfterOptNewLine(token match {
case RightArrow() => Some(typeFuncOnArrow(startPos, t :: Nil, Type.Function(_, _)))
case ContextArrow() => Some(typeFuncOnArrow(startPos, t :: Nil, Type.ContextFunction(_, _)))
case _: KwForsome => next(); Some(Type.Existential(t, existentialStats()))
case _: KwMatch if dialect.allowTypeMatch => next(); Some(Type.Match(t, typeCaseClauses()))
case _ => None
}).getOrElse(t)
}
private def typeFuncOnArrow(
paramPos: Int,
params: List[Type],
ctor: (Type.FuncParamClause, Type) => Type.FunctionType
): Type.FunctionType = {
val funcParams = autoEndPos(paramPos)(params.reduceWith(Type.FuncParamClause.apply))
next()
ctor(funcParams, typeIndentedOpt())
}
def typeCaseClauses(): List[TypeCase] = {
def cases() = listBy[TypeCase] { allCases =>
while (token.is[KwCase]) {
allCases += typeCaseClause()
newLinesOpt()
}
}
if (acceptOpt[LeftBrace])
inBracesAfterOpen(cases())
else if (acceptOpt[Indentation.Indent])
indentedAfterOpen(cases())
else {
syntaxError("Expected braces or indentation", at = token.pos)
}
}
def typeCaseClause(): TypeCase = autoPos {
accept[KwCase]
val pat = infixTypeOrTuple(inMatchType = true)
accept[RightArrow]
val tpe = typeIndentedOpt()
TypeCase(
pat,
tpe
)
}
def quasiquoteType(): Type = entrypointType()
def entrypointType(): Type = paramType()
def typeArgs(): Type.ArgClause =
TypeBracketsContext.within(autoPos(inBrackets(types()).reduceWith(Type.ArgClause.apply)))
def infixTypeOrTuple(inMatchType: Boolean = false): Type = {
if (token.is[LeftParen]) tupleInfixType(allowFunctionType = !inMatchType)
else infixType(inMatchType = inMatchType)
}
@inline def infixType(inMatchType: Boolean = false): Type = maybeAnonymousLambda(
infixTypeRest(compoundType(inMatchType = inMatchType), inMatchType = inMatchType)
)
@inline
private def infixTypeRest(t: Type, inMatchType: Boolean = false): Type =
if (dialect.useInfixTypePrecedence)
infixTypeRestWithPrecedence(t, inMatchType = inMatchType)
else
infixTypeRestWithMode(
t,
InfixMode.FirstOp,
t.startTokenPos,
identity,
inMatchType = inMatchType
)
@tailrec
private final def infixTypeRestWithMode(
t: Type,
mode: InfixMode.Value,
startPos: Int,
f: Type => Type,
inMatchType: Boolean = false
): Type = {
@inline def verifyLeftAssoc(at: Tree, leftAssoc: Boolean = true) =
if (mode != InfixMode.FirstOp) checkAssoc(at, leftAssoc, mode == InfixMode.LeftOp)
token match {
case Ident("*") if (peekToken match {
case _: RightParen | _: Comma | _: Equals | _: RightBrace | _: EOF => true
case _ => false
}) => // we assume that this is a type specification for a vararg parameter
f(t)
case _: Ident | _: Unquote =>
val op = typeName()
val leftAssoc = op.isLeftAssoc
verifyLeftAssoc(op, leftAssoc)
newLineOptWhenFollowedBy(TypeIntro(_))
val typ = compoundType(inMatchType = inMatchType)
def mkOp(t1: Type) = atPos(startPos, t1)(Type.ApplyInfix(t, op, t1))
if (leftAssoc)
infixTypeRestWithMode(
mkOp(typ),
InfixMode.LeftOp,
startPos,
f,
inMatchType = inMatchType
)
else
infixTypeRestWithMode(
typ,
InfixMode.RightOp,
typ.startTokenPos,
f.compose(mkOp),
inMatchType = inMatchType
)
case _ =>
f(t)
}
}
private final def infixTypeRestWithPrecedence(t: Type, inMatchType: Boolean = false): Type = {
val ctx = TypeInfixContext
val base = ctx.stack
@inline def reduce(rhs: ctx.Typ, op: Option[ctx.Op]): ctx.Typ =
ctx.reduceStack(base, rhs, rhs, op)
def getNextRhs(op: ctx.Op, rhs: ctx.Typ): ctx.Typ = {
newLineOptWhenFollowedBy(TypeIntro(_))
ctx.push(ctx.UnfinishedInfix(reduce(rhs, Some(op)), op))
compoundType(inMatchType = inMatchType)
}
@tailrec
def loop(rhs: ctx.Typ): ctx.Typ = token match {
case Ident("*") if (peekToken match {
case _: RightParen | _: Comma | _: Equals | _: RightBrace | _: EOF => true
case _ => false
}) => // we assume that this is a type specification for a vararg parameter
reduce(rhs, None)
case _: Ident | _: Unquote =>
loop(getNextRhs(typeName(), rhs))
case _ =>
tryGetNextInfixOpIfLeading(Type.Name.apply) match {
case Some(op) => loop(getNextRhs(op, rhs))
case _ => reduce(rhs, None)
}
}
loop(t)
}
def compoundType(inMatchType: Boolean = false): Type = {
refinement(innerType = None).getOrElse {
val startPos = tokenPos
compoundTypeRest(annotType(startPos, inMatchType = inMatchType), startPos)
}
}
def compoundTypeRest(typ: Type, startPos: Int): Type = {
@tailrec
def gatherWithTypes(previousType: Type): Type = {