-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Scanners.scala
1839 lines (1674 loc) · 62.8 KB
/
Scanners.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
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.tools.nsc
package ast.parser
import scala.annotation.{switch, tailrec}
import scala.collection.mutable, mutable.{ArrayBuffer, ListBuffer}
import scala.reflect.internal.Chars._
import scala.reflect.internal.util._
import scala.tools.nsc.Reporting.WarningCategory, WarningCategory.Scala3Migration
import scala.tools.nsc.ast.parser.xml.Utility.isNameStart
import scala.tools.nsc.settings.ScalaVersion
import scala.tools.nsc.util.{CharArrayReader, CharArrayReaderData}
import Tokens._
import java.lang.StringBuilder
object Cbuf {
final val TargetCapacity = 256
def create(): StringBuilder = new StringBuilder(TargetCapacity)
implicit class StringBuilderOps(val sb: StringBuilder) extends AnyVal {
def clear(): Unit = {
if (sb.capacity() > TargetCapacity) {
sb.setLength(TargetCapacity)
sb.trimToSize()
}
sb.setLength(0)
}
def toCharArray: Array[Char] = {
val n = sb.length()
val res = new Array[Char](n)
sb.getChars(0, n, res, 0)
res
}
def isEmpty = sb.length() == 0
def last = sb.charAt(sb.length() - 1)
}
}
import Cbuf.StringBuilderOps
/** See Parsers.scala / ParsersCommon for some explanation of ScannersCommon.
*/
trait ScannersCommon {
val global : Global
import global._
/** Offset into source character array */
type Offset = Int
type Token = Int
trait CommonTokenData {
def token: Token
def name: TermName
}
trait ScannerCommon extends CommonTokenData {
/** Consume and discard the next token. */
def nextToken(): Unit
// things to fill in, in addition to buf, decodeUni which come from CharArrayReader
def error(off: Offset, msg: String): Unit
def incompleteInputError(off: Offset, msg: String): Unit
def warning(off: Offset, msg: String, category: WarningCategory): Unit
def deprecationWarning(off: Offset, msg: String, since: String, actions: List[CodeAction] = Nil): Unit
// advance past COMMA NEWLINE RBRACE (to whichever token is the matching close bracket)
def skipTrailingComma(right: Token): Boolean = false
}
// Hooks for ScaladocUnitScanner and ScaladocJavaUnitScanner
trait DocScanner {
protected def beginDocComment(prefix: String): Unit = {}
protected def processCommentChar(): Unit = {}
protected def finishDocComment(): Unit = {}
private var lastDoc: DocComment = null
// get last doc comment
def flushDoc(): DocComment = try lastDoc finally lastDoc = null
def registerDocComment(raw: String, pos: Position) = {
lastDoc = DocComment(raw, pos)
signalParsedDocComment(raw, pos)
}
/** To prevent doc comments attached to expressions from leaking out of scope
* onto the next documentable entity, they are discarded upon passing a right
* brace, bracket, or parenthesis.
*/
def discardDocBuffer(): Unit = {}
}
def createKeywordArray(keywords: Seq[(Name, Token)], defaultToken: Token): (Token, Array[Token]) = {
val names = keywords.sortBy(_._1.start).map { case (k, v) => (k.start, v) }
val low = names.head._1
val high = names.last._1
val arr = Array.fill(high - low + 1)(defaultToken)
names foreach { case (k, v) => arr(k + low) = v }
(low, arr)
}
}
trait Scanners extends ScannersCommon {
val global : Global
import global._
trait TokenData extends CommonTokenData {
/** the next token */
var token: Token = EMPTY
/** the offset of the first character of the current token */
var offset: Offset = 0
/** the offset of the character following the token preceding this one */
var lastOffset: Offset = 0
/** the name of an identifier */
var name: TermName = null
/** the string value of a literal */
var strVal: String = null
/** the base of a number */
var base: Int = 0
def copyFrom(td: TokenData): this.type = {
this.token = td.token
this.offset = td.offset
this.lastOffset = td.lastOffset
this.name = td.name
this.strVal = td.strVal
this.base = td.base
this
}
}
/** An interface to most of mutable data in Scanner defined in TokenData
* and CharArrayReader (+ next, prev fields) with copyFrom functionality
* to backup/restore data (used by quasiquotes' lookingAhead).
*/
trait ScannerData extends TokenData with CharArrayReaderData {
/** we need one token lookahead and one token history
*/
val next: TokenData = new TokenData{}
val prev: TokenData = new TokenData{}
def copyFrom(sd: ScannerData): this.type = {
this.next copyFrom sd.next
this.prev copyFrom sd.prev
super[CharArrayReaderData].copyFrom(sd)
super[TokenData].copyFrom(sd)
this
}
}
abstract class Scanner extends CharArrayReader with TokenData with ScannerData with ScannerCommon with DocScanner {
def unit: CompilationUnit
/** A switch whether operators at the start of lines can be infix operators. */
private var allowLeadingInfixOperators = true
private def isDigit(c: Char) = Character.isDigit(c)
import Character.{isHighSurrogate, isLowSurrogate, isUnicodeIdentifierPart, isUnicodeIdentifierStart, isValidCodePoint, toCodePoint}
// given char (ch) is high surrogate followed by low, codepoint passes predicate.
// true means supplementary chars were put to buffer.
// strict to require low surrogate (if not in string literal).
private def isSupplementary(high: Char, test: Int => Boolean, strict: Boolean = true): Boolean =
isHighSurrogate(high) && {
var res = false
val low = lookaheadReader.getc()
if (isLowSurrogate(low)) {
val codePoint = toCodePoint(high, low)
if (isValidCodePoint(codePoint)) {
if (test(codePoint)) {
putChar(high)
putChar(low)
nextChar()
nextChar()
res = true
}
}
else syntaxError(f"illegal character '\\u$high%04x\\u$low%04x'")
}
else if (!strict) {
putChar(high)
nextChar()
res = true
}
else syntaxError(f"illegal character '\\u$high%04x' missing low surrogate")
res
}
private def atSupplementary(ch: Char, f: Int => Boolean): Boolean =
isHighSurrogate(ch) && {
val hi = ch
val r = lookaheadReader
r.nextRawChar()
val lo = r.ch
isLowSurrogate(lo) && {
val codepoint = toCodePoint(hi, lo)
isValidCodePoint(codepoint) && f(codepoint)
}
}
private var openComments = 0
final protected def putCommentChar(): Unit = { processCommentChar(); nextChar() }
@tailrec private def skipLineComment(): Unit = ch match {
case SU | CR | LF =>
case _ => nextChar() ; skipLineComment()
}
private def maybeOpen(): Unit = {
putCommentChar()
if (ch == '*') {
putCommentChar()
openComments += 1
}
}
private def maybeClose(): Boolean = {
putCommentChar()
(ch == '/') && {
putCommentChar()
openComments -= 1
openComments == 0
}
}
@tailrec final def skipNestedComments(): Unit = ch match {
case '/' => maybeOpen() ; skipNestedComments()
case '*' => if (!maybeClose()) skipNestedComments()
case SU => incompleteInputError("unclosed comment")
case _ => putCommentChar() ; skipNestedComments()
}
private def skipToCommentEnd(isLineComment: Boolean): Unit = {
nextChar()
if (isLineComment) skipLineComment()
else {
openComments = 1
val isDocComment = (ch == '*') && { nextChar(); true }
if (isDocComment) {
// Check for the amazing corner case of /**/
if (ch == '/')
nextChar()
else {
beginDocComment("/**")
skipNestedComments()
}
}
else skipNestedComments()
}
}
/** Returns true if a comment was skipped.
* @note Pre-condition: ch == '/'
*/
final def skipComment(): Boolean = ch match {
case '/' | '*' => skipToCommentEnd(isLineComment = ch == '/') ; finishDocComment(); true
case _ => false
}
def isAtEnd = charOffset >= buf.length
def resume(lastCode: Token) = {
token = lastCode
if (next.token != EMPTY && !reporter.hasErrors)
syntaxError("unexpected end of input: possible missing '}' in XML block")
nextToken()
}
/** A character buffer for literals
*/
val cbuf = Cbuf.create()
/** append Unicode character to "cbuf" buffer
*/
protected def putChar(c: Char): Unit = cbuf.append(c)
/** Determines whether this scanner should emit identifier deprecation warnings,
* e.g. when seeing `macro` or `then`, which are planned to become keywords in future versions of Scala.
*/
protected def emitIdentifierDeprecationWarnings = true
/** Clear buffer and set name and token */
private def finishNamed(idtoken: Token = IDENTIFIER): Unit = {
name = newTermName(cbuf.toCharArray)
cbuf.clear()
token = idtoken
if (idtoken == IDENTIFIER) {
val idx = name.start - kwOffset
if (idx >= 0 && idx < kwArray.length) {
token = kwArray(idx)
if (token == IDENTIFIER && allowIdent != name) {
if (name == nme.MACROkw)
syntaxError(s"$name is now a reserved word; usage as an identifier is disallowed")
else if (emitIdentifierDeprecationWarnings)
deprecationWarning(s"$name is a reserved word (since 2.10.0); usage as an identifier is deprecated", "2.10.0")
}
}
}
}
/** Clear buffer and set string */
private def setStrVal(): Unit = {
strVal = cbuf.toString
cbuf.clear()
}
/** a stack of tokens which indicates whether line-ends can be statement separators
* also used for keeping track of nesting levels.
* We keep track of the closing symbol of a region. This can be
* RPAREN if region starts with '('
* RBRACKET if region starts with '['
* RBRACE if region starts with '{'
* ARROW if region starts with 'case'
* STRINGLIT if region is a string interpolation expression starting with '${'
* (the STRINGLIT appears twice in succession on the stack iff the
* expression is a multiline string literal).
*/
var sepRegions: List[Token] = List()
// Get next token ------------------------------------------------------------
/** Are we directly in a string interpolation expression?
*/
private def inStringInterpolation =
sepRegions.nonEmpty && sepRegions.head == STRINGLIT
/** Are we directly in a multiline string interpolation expression?
* @pre inStringInterpolation
*/
private def inMultiLineInterpolation =
inStringInterpolation && sepRegions.tail.nonEmpty && sepRegions.tail.head == STRINGPART
/** Are we in a `${ }` block? such that RBRACE exits back into multiline string. */
private def inMultiLineInterpolatedExpression = {
sepRegions match {
case RBRACE :: STRINGLIT :: STRINGPART :: rest => true
case _ => false
}
}
def lookingAhead[A](body: => A): A = {
val saved = new ScannerData {} copyFrom this
val aLIO = allowLeadingInfixOperators
allowLeadingInfixOperators = false
nextToken()
try body finally {
this copyFrom saved
allowLeadingInfixOperators = aLIO
}
}
/** read next token and return last offset
*/
def skipToken(): Offset = {
val off = offset
nextToken()
off
}
// used by parser to distinguish pattern P(_*, p) from trailing comma.
// EOF is accepted for REPL, which can't look ahead past the current line.
def isTrailingComma(right: Token): Boolean =
token == COMMA && lookingAhead(afterLineEnd() && token == right || token == EOF)
override def skipTrailingComma(right: Token): Boolean =
if (token == COMMA) {
// SIP-27 Trailing Comma (multi-line only) support
// If a comma is followed by a new line & then a closing paren, bracket or brace
// then it is a trailing comma and is ignored
val saved = new ScannerData {} copyFrom this
fetchToken()
(afterLineEnd() && token == right || token == EOF) || { copyFrom(saved) ; false }
} else false
/** Allow an otherwise deprecated ident here */
private var allowIdent: Name = nme.EMPTY
/** Get next token, and allow the otherwise deprecated ident `name` */
def nextTokenAllow(name: Name) = {
val prev = allowIdent
allowIdent = name
try {
nextToken()
} finally {
allowIdent = prev
}
}
// Adapt sepRegions according to last token
def adjustSepRegions(lastToken: Token): Unit = (lastToken: @switch) match {
case LPAREN =>
sepRegions = RPAREN :: sepRegions
case LBRACKET =>
sepRegions = RBRACKET :: sepRegions
case LBRACE =>
sepRegions = RBRACE :: sepRegions
case CASE =>
sepRegions = ARROW :: sepRegions
case RBRACE =>
while (!sepRegions.isEmpty && sepRegions.head != RBRACE)
sepRegions = sepRegions.tail
if (!sepRegions.isEmpty)
sepRegions = sepRegions.tail
discardDocBuffer()
case RBRACKET | RPAREN =>
if (!sepRegions.isEmpty && sepRegions.head == lastToken)
sepRegions = sepRegions.tail
discardDocBuffer()
case ARROW =>
if (!sepRegions.isEmpty && sepRegions.head == lastToken)
sepRegions = sepRegions.tail
case STRINGLIT =>
if (inMultiLineInterpolation)
sepRegions = sepRegions.tail.tail
else if (inStringInterpolation)
sepRegions = sepRegions.tail
case _ =>
}
/** Advance beyond a case token without marking the CASE in sepRegions.
* This method should be called to skip beyond CASE tokens that are
* not part of matches, i.e. no ARROW is expected after them.
*/
def skipCASE(): Unit = {
assert(token == CASE, s"Internal error: skipCASE() called on non-case token $token")
nextToken()
sepRegions = sepRegions.tail
}
/** True to warn about migration change in infix syntax. */
private val infixMigration = settings.Xmigration.value <= ScalaVersion("2.13.2")
/** Produce next token, filling TokenData fields of Scanner.
*/
def nextToken(): Unit = {
val lastToken = token
adjustSepRegions(lastToken)
// Read a token or copy it from `next` tokenData
if (next.token == EMPTY) {
lastOffset = charOffset - 1
if (lastOffset > 0 && buf(lastOffset) == '\n' && buf(lastOffset - 1) == '\r') {
lastOffset -= 1
}
if (inStringInterpolation) fetchStringPart() else fetchToken()
if (token == ERROR) {
if (inMultiLineInterpolation)
sepRegions = sepRegions.tail.tail
else if (inStringInterpolation)
sepRegions = sepRegions.tail
}
} else {
this copyFrom next
next.token = EMPTY
}
def isSimpleExprIntroToken(token: Token): Boolean = token match {
case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT |
STRINGLIT | INTERPOLATIONID | SYMBOLLIT | TRUE | FALSE | NULL | // literals
IDENTIFIER | BACKQUOTED_IDENT | THIS | SUPER | NEW | USCORE |
LPAREN | LBRACE | XMLSTART => true
case _ => false
}
def insertNL(nl: Token): Unit = {
next.copyFrom(this)
// todo: make offset line-end of previous line?
offset = if (lineStartOffset <= offset) lineStartOffset else lastLineStartOffset
token = nl
}
def isOperator: Boolean = token == BACKQUOTED_IDENT || token == IDENTIFIER && isOperatorPart(name.charAt(name.length - 1))
/* A leading infix operator must be followed by a lexically suitable expression.
* Usually any simple expr will do. However, a backquoted identifier may serve as
* either an op or a reference. So the additional constraint is that the following
* token can't be an assignment operator. (Dotty disallows binary ops, hence the
* test for unary.) See run/multiLineOps.scala for 42 + `x` on 3 lines, where +
* is not leading infix because backquoted x is non-unary op.
*/
def followedByInfixRHS: Boolean = {
//def isCandidateInfixRHS: Boolean = isSimpleExprIntroToken(token) && (!isOperator || nme.raw.isUnary(name) || token == BACKQUOTED_IDENT)
def isAssignmentOperator: Boolean =
name.endsWith('=') && !name.startsWith('=') && isOperatorPart(name.startChar) &&
(name.length != 2 || (name.startChar match { case '!' | '<' | '>' => false case _ => true }))
def isCandidateInfixRHS: Boolean = isSimpleExprIntroToken(token) && (!isOperator || token == BACKQUOTED_IDENT || !isAssignmentOperator)
lookingAhead {
isCandidateInfixRHS || token == NEWLINE && { nextToken() ; isCandidateInfixRHS }
}
}
/* A leading symbolic or backquoted identifier is treated as an infix operator
* if it is followed by at least one ' ' and a token on the same line
* that can start an expression.
*/
def isLeadingInfixOperator =
allowLeadingInfixOperators &&
isOperator &&
(isWhitespace(ch) || ch == LF) &&
followedByInfixRHS
/* Insert NEWLINE or NEWLINES if
* - we are after a newline
* - we are within a { ... } or on toplevel (wrt sepRegions)
* - the current token can start a statement and the one before can end it
* insert NEWLINES if we are past a blank line, NEWLINE otherwise
*/
if (!applyBracePatch() && afterLineEnd() && inLastOfStat(lastToken) && inFirstOfStat(token) &&
(sepRegions.isEmpty || sepRegions.head == RBRACE)) {
if (pastBlankLine()) insertNL(NEWLINES)
else if (!isLeadingInfixOperator) insertNL(NEWLINE)
else if (!currentRun.sourceFeatures.leadingInfix) {
val msg =
sm"""Lines starting with an operator are taken as an infix expression continued from the previous line in Scala 3 (or with -Xsource-features:leading-infix).
|To force the current interpretation as a separate statement, add an explicit `;`, add an empty line, or remove spaces after the operator."""
if (currentRun.isScala3) warning(offset, msg, Scala3Migration)
else if (infixMigration) deprecationWarning(msg, "2.13.2")
insertNL(NEWLINE)
}
}
postProcessToken()
// print("["+this+"]")
} // end nextToken
// Join CASE + CLASS => CASECLASS, CASE + OBJECT => CASEOBJECT, SEMI + ELSE => ELSE
def postProcessToken(): Unit =
if (token == CASE) {
prev copyFrom this
val nextLastOffset = charOffset - 1
fetchToken()
def resetOffset(): Unit = {
offset = prev.offset
lastOffset = prev.lastOffset
}
if (token == CLASS) {
token = CASECLASS
resetOffset()
} else if (token == OBJECT) {
token = CASEOBJECT
resetOffset()
} else {
lastOffset = nextLastOffset
next copyFrom this
this copyFrom prev
}
} else if (token == SEMI) {
prev copyFrom this
fetchToken()
if (token != ELSE) {
next copyFrom this
this copyFrom prev
}
}
/** Is current token first one after a newline? */
private def afterLineEnd(): Boolean =
lastOffset < lineStartOffset &&
(lineStartOffset <= offset ||
lastOffset < lastLineStartOffset && lastLineStartOffset <= offset)
/** Is there a blank line between the current token and the last one?
* @pre afterLineEnd().
*/
private def pastBlankLine(): Boolean = {
var idx = lastOffset
var ch = buf(idx)
val end = offset
while (idx < end) {
if (ch == LF || ch == FF) {
do {
idx += 1; ch = buf(idx)
if (ch == LF || ch == FF) {
// println("blank line found at "+lastOffset+":"+(lastOffset to idx).map(buf(_)).toList)
return true
}
if (idx == end) return false
} while (ch <= ' ')
}
idx += 1; ch = buf(idx)
}
false
}
/** read next token, filling TokenData fields of Scanner.
*/
@tailrec
protected final def fetchToken(): Unit = {
offset = charOffset - 1
(ch: @switch) match {
case ' ' | '\t' | CR | LF | FF =>
nextChar()
fetchToken()
case 'A' | 'B' | 'C' | 'D' | 'E' |
'F' | 'G' | 'H' | 'I' | 'J' |
'K' | 'L' | 'M' | 'N' | 'O' |
'P' | 'Q' | 'R' | 'S' | 'T' |
'U' | 'V' | 'W' | 'X' | 'Y' |
'Z' | '$' | '_' |
'a' | 'b' | 'c' | 'd' | 'e' |
'f' | 'g' | 'h' | 'i' | 'j' |
'k' | 'l' | 'm' | 'n' | 'o' |
'p' | 'q' | 'r' | 's' | 't' |
'u' | 'v' | 'w' | 'x' | 'y' | // scala-mode: need to understand multi-line case patterns
'z' =>
putChar(ch)
nextChar()
getIdentRest()
if (ch == '"' && token == IDENTIFIER) token = INTERPOLATIONID
case '<' => // is XMLSTART?
def fetchLT() = {
val last = if (charOffset >= 2) buf(charOffset - 2) else ' '
nextChar()
last match {
case ' ' | '\t' | '\n' | '{' | '(' | '>' if isNameStart(ch) || ch == '!' || ch == '?' =>
token = XMLSTART
case _ =>
// Console.println("found '<', but last is '"+in.last+"'"); // DEBUG
putChar('<')
getOperatorRest()
}
}
fetchLT()
case '~' | '!' | '@' | '#' | '%' |
'^' | '*' | '+' | '-' | /*'<' | */
'>' | '?' | ':' | '=' | '&' |
'|' | '\\' =>
putChar(ch)
nextChar()
getOperatorRest()
case '/' =>
nextChar()
if (skipComment()) {
fetchToken()
} else {
putChar('/')
getOperatorRest()
}
case '0' =>
def fetchLeadingZero(): Unit = {
nextChar()
ch match {
case 'x' | 'X' => base = 16 ; nextChar()
case 'b' | 'B' => base = 2 ; nextChar()
case _ => base = 10 ; putChar('0')
}
if (base != 10 && !isNumberSeparator(ch) && digit2int(ch, base) < 0)
syntaxError("invalid literal number")
}
fetchLeadingZero()
getNumber()
case '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' =>
base = 10
getNumber()
case '`' =>
getBackquotedIdent()
case '\"' =>
def fetchDoubleQuote() = {
if (token == INTERPOLATIONID) {
nextRawChar()
if (ch == '\"') {
val lookahead = lookaheadReader
lookahead.nextChar()
if (lookahead.ch == '\"') {
nextRawChar() // now eat it
offset += 3
nextRawChar()
getStringPart(multiLine = true)
sepRegions = STRINGPART :: sepRegions // indicate string part
sepRegions = STRINGLIT :: sepRegions // once more to indicate multi line string part
} else {
nextChar()
token = STRINGLIT
strVal = ""
}
} else {
offset += 1
getStringPart(multiLine = false)
sepRegions = STRINGLIT :: sepRegions // indicate single line string part
}
} else {
nextChar()
if (ch == '\"') {
nextChar()
if (ch == '\"') {
nextRawChar()
getRawStringLit()
} else {
token = STRINGLIT
strVal = ""
}
} else {
getStringLit()
}
}
}
fetchDoubleQuote()
case '\'' =>
def unclosedCharLit() = {
val unclosed = "unclosed character literal"
// advise if previous token was Symbol contiguous with the orphan single quote at offset
val msg = {
val maybeMistakenQuote =
this match {
case sfs: SourceFileScanner =>
val wholeLine = sfs.source.lineToString(sfs.source.offsetToLine(offset))
wholeLine.count(_ == '\'') > 1
case _ => false
}
if (token == SYMBOLLIT && offset == lastOffset) s"""$unclosed (or use " for string literal "$strVal")"""
else if (maybeMistakenQuote) s"""$unclosed (or use " not ' for string literal)"""
else unclosed
}
syntaxError(msg)
}
/** Either at closing quote of charlit
* or run the op and take it as a (deprecated) Symbol identifier.
*/
def charLitOrSymbolAfter(op: () => Unit): Unit =
if (ch == '\'') {
nextChar()
token = CHARLIT
setStrVal()
} else {
op()
token = SYMBOLLIT
strVal = name.toString
}
def fetchSingleQuote() = {
nextChar()
if (isIdentifierStart(ch)) {
putChar(ch)
nextChar()
charLitOrSymbolAfter(() => getIdentRest())
}
else if (isOperatorPart(ch) && (ch != '\\')) {
putChar(ch)
nextChar()
charLitOrSymbolAfter(() => getOperatorRest())
}
else if (!isAtEnd && (ch != SU && ch != CR && ch != LF)) {
val isEmptyCharLit = (ch == '\'')
getLitChar()
if (ch == '\'') {
if (isEmptyCharLit)
syntaxError("empty character literal (use '\\'' for single quote)")
else {
nextChar()
if (cbuf.length != 1)
syntaxError("illegal codepoint in Char constant: " + cbuf.toString.map(c => f"\\u$c%04x").mkString("'", "", "'"))
else {
token = CHARLIT
setStrVal()
}
}
}
else if (isEmptyCharLit)
syntaxError("empty character literal")
else
unclosedCharLit()
}
else unclosedCharLit()
}
fetchSingleQuote()
case '.' =>
nextChar()
if ('0' <= ch && ch <= '9') {
putChar('.'); getFraction()
} else {
token = DOT
}
case ';' =>
nextChar(); token = SEMI
case ',' =>
nextChar(); token = COMMA
case '(' =>
nextChar(); token = LPAREN
case '{' =>
nextChar(); token = LBRACE
case ')' =>
nextChar(); token = RPAREN
case '}' =>
if (inMultiLineInterpolatedExpression) nextRawChar() else nextChar()
token = RBRACE
case '[' =>
nextChar(); token = LBRACKET
case ']' =>
nextChar(); token = RBRACKET
case SU =>
if (isAtEnd) {
bidiChars.foreach { case (char, offset) =>
syntaxError(offset, f"found unicode bidirectional character '\\u$char%04x'; in a string or character literal, use a unicode escape instead")
}
token = EOF
}
else {
syntaxError("illegal character")
nextChar()
}
case _ =>
def fetchOther() = {
if (ch == '\u21D2') {
val msg = "The unicode arrow `⇒` is deprecated, use `=>` instead. If you still wish to display it as one character, consider using a font with programming ligatures such as Fira Code."
deprecationWarning(msg, "2.13.0",
runReporting.codeAction("replace unicode arrow", unit.position(offset).withEnd(offset + 1), "=>", msg, expected = Some(("⇒", unit))))
nextChar(); token = ARROW
} else if (ch == '\u2190') {
val msg = "The unicode arrow `←` is deprecated, use `<-` instead. If you still wish to display it as one character, consider using a font with programming ligatures such as Fira Code."
deprecationWarning(msg, "2.13.0",
runReporting.codeAction("replace unicode arrow", unit.position(offset).withEnd(offset + 1), "<-", msg, expected = Some(("←", unit))))
nextChar(); token = LARROW
} else if (isUnicodeIdentifierStart(ch)) {
putChar(ch)
nextChar()
getIdentRest()
if (ch == '"' && token == IDENTIFIER) token = INTERPOLATIONID
} else if (isSpecial(ch)) {
putChar(ch)
nextChar()
getOperatorRest()
} else if (isSupplementary(ch, isUnicodeIdentifierStart)) {
getIdentRest()
if (ch == '"' && token == IDENTIFIER) token = INTERPOLATIONID
} else if (isSupplementary(ch, isSpecial)) {
getOperatorRest()
} else {
syntaxError(f"illegal character '\\u$ch%04x'")
nextChar()
}
}
fetchOther()
}
}
/** Can token start a statement? */
def inFirstOfStat(token: Token) = token match {
case EOF | CATCH | ELSE | EXTENDS | FINALLY | FORSOME | MATCH | WITH | YIELD |
COMMA | SEMI | NEWLINE | NEWLINES | DOT | COLON | EQUALS | ARROW | LARROW |
SUBTYPE | VIEWBOUND | SUPERTYPE | HASH | RPAREN | RBRACKET | RBRACE | LBRACKET =>
false
case _ =>
true
}
/** Can token end a statement? */
def inLastOfStat(token: Token) = token match {
case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | SYMBOLLIT |
IDENTIFIER | BACKQUOTED_IDENT | THIS | NULL | TRUE | FALSE | RETURN | USCORE |
TYPE | XMLSTART | RPAREN | RBRACKET | RBRACE =>
true
case _ =>
false
}
// Identifiers ---------------------------------------------------------------
private def getBackquotedIdent(): Unit = {
nextChar()
getLitChars('`')
if (ch == '`') {
nextChar()
finishNamed(BACKQUOTED_IDENT)
if (name.length == 0) syntaxError("empty quoted identifier")
}
else syntaxError("unclosed quoted identifier")
}
@tailrec
private def getIdentRest(): Unit = (ch: @switch) match {
case 'A' | 'B' | 'C' | 'D' | 'E' |
'F' | 'G' | 'H' | 'I' | 'J' |
'K' | 'L' | 'M' | 'N' | 'O' |
'P' | 'Q' | 'R' | 'S' | 'T' |
'U' | 'V' | 'W' | 'X' | 'Y' |
'Z' | '$' |
'a' | 'b' | 'c' | 'd' | 'e' |
'f' | 'g' | 'h' | 'i' | 'j' |
'k' | 'l' | 'm' | 'n' | 'o' |
'p' | 'q' | 'r' | 's' | 't' |
'u' | 'v' | 'w' | 'x' | 'y' |
'z' |
'0' | '1' | '2' | '3' | '4' |
'5' | '6' | '7' | '8' | '9' =>
putChar(ch)
nextChar()
getIdentRest()
case '_' =>
putChar(ch)
nextChar()
getIdentOrOperatorRest()
case ' ' | LF | // optimize for common whitespace
SU => // strangely enough, Character.isUnicodeIdentifierPart(SU) returns true!
finishNamed()
case _ =>
if (isUnicodeIdentifierPart(ch)) {
putChar(ch)
nextChar()
getIdentRest()
}
else if (isSupplementary(ch, isUnicodeIdentifierPart))
getIdentRest()
else
finishNamed()
}
@tailrec
private def getOperatorRest(): Unit = (ch: @switch) match {
case ' ' | LF => finishNamed() // optimize
case '~' | '!' | '@' | '#' | '%' |
'^' | '*' | '+' | '-' | '<' |
'>' | '?' | ':' | '=' | '&' |
'|' | '\\' =>
putChar(ch); nextChar(); getOperatorRest()
case '/' =>
nextChar()
if (skipComment()) finishNamed()
else { putChar('/'); getOperatorRest() }
case _ =>
if (isSpecial(ch)) { putChar(ch); nextChar(); getOperatorRest() }
else if (isSupplementary(ch, isSpecial)) getOperatorRest()
else finishNamed()
}
private def getIdentOrOperatorRest(): Unit =
if (isIdentifierPart(ch) || isSupplementary(ch, isIdentifierPart)) getIdentRest() else getOperatorRest()
// Literals -----------------------------------------------------------------
private def getStringLit() = {
getLitChars('"')
if (ch == '"') {
setStrVal()
nextChar()
token = STRINGLIT
} else unclosedStringLit()
}
private def unclosedStringLit(seenEscapedQuoteInInterpolation: Boolean = false): Unit = {
val note =
if (seenEscapedQuoteInInterpolation) "; note that `\\\"` no longer closes single-quoted interpolated string literals since 2.13.6, you can use a triple-quoted string instead"
else ""
syntaxError(s"unclosed string literal$note")
}
private def replaceUnicodeEscapesInTriple(): Unit =
if (strVal != null)
try {
val processed = StringContext.processUnicode(strVal)
if (processed != strVal && !currentRun.sourceFeatures.unicodeEscapesRaw) {
val diffPosition = processed.zip(strVal).zipWithIndex.collectFirst { case ((r, o), i) if r != o => i }.getOrElse(processed.length - 1)
val pos = offset + 3 + diffPosition
def msg(what: String) = s"Unicode escapes in triple quoted strings are $what; use the literal character instead"
if (currentRun.isScala3)
warning(pos, msg("ignored in Scala 3 (or with -Xsource-features:unicode-escapes-raw)"), WarningCategory.Scala3Migration)
else
deprecationWarning(pos, msg("deprecated"), since="2.13.2")
strVal = processed
}
} catch {
case ue: StringContext.InvalidUnicodeEscapeException =>
if (!currentRun.sourceFeatures.unicodeEscapesRaw)
syntaxError(offset + 3 + ue.index, ue.getMessage())
}
@tailrec private def getRawStringLit(): Unit = {
if (ch == '\"') {
nextRawChar()
if (isTripleQuote()) {
setStrVal()
replaceUnicodeEscapesInTriple()
token = STRINGLIT
} else
getRawStringLit()
} else if (ch == SU) {
incompleteInputError("unclosed multi-line string literal")
} else {
putChar(ch)
nextRawChar()
getRawStringLit()
}
}