-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Scanners.scala
1724 lines (1548 loc) · 60.6 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
package dotty.tools
package dotc
package parsing
import scala.language.unsafeNulls
import core.Names.*, core.Contexts.*, core.Decorators.*, util.Spans.*
import core.StdNames.*, core.Comments.*
import util.SourceFile
import util.Chars.*
import util.{SourcePosition, CharBuffer}
import util.Spans.Span
import config.Config
import Tokens.*
import scala.annotation.{switch, tailrec}
import scala.collection.mutable
import scala.collection.immutable.SortedMap
import rewrites.Rewrites.patch
import config.Feature
import config.Feature.{migrateTo3, fewerBracesEnabled}
import config.SourceVersion.{`3.0`, `3.0-migration`}
import config.MigrationVersion
import reporting.{NoProfile, Profile, Message}
import java.util.Objects
import dotty.tools.dotc.reporting.Message.rewriteNotice
import dotty.tools.dotc.config.Feature.sourceVersion
object Scanners {
/** Offset into source character array */
type Offset = Int
/** An undefined offset */
val NoOffset: Offset = -1
type Token = Int
private val identity: IndentWidth => IndentWidth = Predef.identity
trait TokenData {
/** 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 offset of the newline immediately preceding the token, or -1 if
* token is not preceded by a newline.
*/
var lineOffset: Offset = -1
/** the name of an identifier */
var name: SimpleName = null
/** the string value of a literal */
var strVal: String = null
/** the base of a number */
var base: Int = 0
def copyFrom(td: TokenData): Unit = {
this.token = td.token
this.offset = td.offset
this.lastOffset = td.lastOffset
this.lineOffset = td.lineOffset
this.name = td.name
this.strVal = td.strVal
this.base = td.base
}
def isNewLine = token == NEWLINE || token == NEWLINES
def isStatSep = isNewLine || token == SEMI
def isIdent = token == IDENTIFIER || token == BACKQUOTED_IDENT
def isIdent(name: Name) = token == IDENTIFIER && this.name == name
def isNestedStart = token == LBRACE || token == INDENT
def isNestedEnd = token == RBRACE || token == OUTDENT
def isColon =
token == COLONop || token == COLONfollow || token == COLONeol
/** Is current token first one after a newline? */
def isAfterLineEnd: Boolean = lineOffset >= 0
def isOperator =
token == BACKQUOTED_IDENT
|| token == IDENTIFIER && isOperatorPart(name(name.length - 1))
def isArrow =
token == ARROW || token == CTXARROW
}
abstract class ScannerCommon(source: SourceFile)(using Context) extends CharArrayReader with TokenData {
val buf: Array[Char] = source.content
def nextToken(): Unit
// Errors -----------------------------------------------------------------
/** the last error offset
*/
var errOffset: Offset = NoOffset
/** Implements CharArrayReader's error method */
protected def error(msg: String, off: Offset): Unit =
error(msg.toMessage, off)
/** Generate an error at the given offset */
def error(msg: Message, off: Offset = offset): Unit = {
errorButContinue(msg, off)
token = ERROR
errOffset = off
}
def errorButContinue(msg: Message, off: Offset = offset): Unit =
report.error(msg, sourcePos(off))
/** signal an error where the input ended in the middle of a token */
def incompleteInputError(msg: Message): Unit = {
report.incompleteInputError(msg, sourcePos())
token = EOF
errOffset = offset
}
def sourcePos(off: Offset = offset): SourcePosition =
source.atSpan(Span(off))
// Setting token data ----------------------------------------------------
protected def initialCharBufferSize = 1024
/** A character buffer for literals
*/
protected val litBuf = CharBuffer(initialCharBufferSize)
/** append Unicode character to "litBuf" buffer
*/
protected def putChar(c: Char): Unit = litBuf.append(c)
/** Finish an IDENTIFIER with `this.name`. */
inline def finishNamed(): Unit = finishNamedToken(IDENTIFIER, this)
/** Clear buffer and set name and token.
* If `target` is different from `this`, don't treat identifiers as end tokens.
*/
def finishNamedToken(idtoken: Token, target: TokenData): Unit =
target.name = termName(litBuf.chars, 0, litBuf.length)
litBuf.clear()
target.token = idtoken
if idtoken == IDENTIFIER then
val converted = toToken(target.name)
if converted != END || (target eq this) then target.token = converted
/** The token for given `name`. Either IDENTIFIER or a keyword. */
def toToken(name: SimpleName): Token
/** Clear buffer and set string */
def setStrVal(): Unit =
strVal = litBuf.toString
litBuf.clear()
@inline def isNumberSeparator(c: Char): Boolean = c == '_'
@inline def removeNumberSeparators(s: String): String = if (s.indexOf('_') == -1) s else s.replace("_", "")
// disallow trailing numeric separator char, but continue lexing
def checkNoTrailingSeparator(): Unit =
if (!litBuf.isEmpty && isNumberSeparator(litBuf.last))
errorButContinue(em"trailing separator is not allowed", offset + litBuf.length - 1)
}
class Scanner(source: SourceFile, override val startFrom: Offset = 0, profile: Profile = NoProfile, allowIndent: Boolean = true)(using Context) extends ScannerCommon(source) {
val keepComments = !ctx.settings.XdropComments.value
/** A switch whether operators at the start of lines can be infix operators */
private[Scanners] var allowLeadingInfixOperators = true
var debugTokenStream = false
val showLookAheadOnDebug = false
val rewrite = ctx.settings.rewrite.value.isDefined
val oldSyntax = ctx.settings.oldSyntax.value
val newSyntax = ctx.settings.newSyntax.value
val rewriteToIndent = ctx.settings.indent.value && rewrite
val rewriteNoIndent = ctx.settings.noindent.value && rewrite
val noindentSyntax =
ctx.settings.noindent.value
|| ctx.settings.oldSyntax.value
|| (migrateTo3 && !ctx.settings.indent.value)
val indentSyntax =
((if (Config.defaultIndent) !noindentSyntax else ctx.settings.indent.value)
|| rewriteNoIndent)
&& allowIndent
if (rewrite) {
val s = ctx.settings
val rewriteTargets = List(s.newSyntax, s.oldSyntax, s.indent, s.noindent)
val enabled = rewriteTargets.filter(_.value)
if (enabled.length > 1)
error(em"illegal combination of -rewrite targets: ${enabled(0).name} and ${enabled(1).name}")
}
private var myLanguageImportContext: Context = ctx
def languageImportContext = myLanguageImportContext
final def languageImportContext_=(c: Context) = myLanguageImportContext = c
def featureEnabled(name: TermName) = Feature.enabled(name)(using languageImportContext)
def erasedEnabled = featureEnabled(Feature.erasedDefinitions)
private var postfixOpsEnabledCache = false
private var postfixOpsEnabledCtx: Context = NoContext
def postfixOpsEnabled =
if postfixOpsEnabledCtx ne myLanguageImportContext then
postfixOpsEnabledCache = featureEnabled(nme.postfixOps)
postfixOpsEnabledCtx = myLanguageImportContext
postfixOpsEnabledCache
/** All doc comments kept by their end position in a `Map`.
*
* Note: the map is necessary since the comments are looked up after an
* entire definition is parsed, and a definition can contain nested
* definitions with their own docstrings.
*/
private var docstringMap: SortedMap[Int, Comment] = SortedMap.empty
/* A Buffer for comments */
private val commentBuf = new mutable.ListBuffer[Comment]
/** Return a list of all the comments */
def comments: List[Comment] = commentBuf.toList
private def addComment(comment: Comment): Unit = {
val lookahead = lookaheadReader()
def nextPos: Int = (lookahead.getc(): @switch) match {
case ' ' | '\t' | CR | LF | FF => nextPos
case _ => lookahead.charOffset - 1
}
docstringMap = docstringMap + (nextPos -> comment)
}
/** Returns the closest docstring preceding the position supplied */
def getDocComment(pos: Int): Option[Comment] = docstringMap.get(pos)
/** A buffer for comments */
private val currentCommentBuf = CharBuffer(initialCharBufferSize)
def toToken(identifier: SimpleName): Token =
def handleMigration(keyword: Token): Token =
if scala3keywords.contains(keyword) && migrateTo3 then
val what = tokenString(keyword)
report.errorOrMigrationWarning(
em"$what is now a keyword, write `$what` instead of $what to keep it as an identifier${rewriteNotice("This", `3.0-migration`)}",
sourcePos(),
MigrationVersion.Scala2to3)
if MigrationVersion.Scala2to3.needsPatch then
patch(source, Span(offset), "`")
patch(source, Span(offset + identifier.length), "`")
IDENTIFIER
else keyword
val idx = identifier.start
if (idx >= 0 && idx <= lastKeywordStart) handleMigration(kwArray(idx))
else IDENTIFIER
def newTokenData: TokenData = new TokenData {}
/** We need one token lookahead and one token history
*/
val next = newTokenData
private val prev = newTokenData
/** The current region. This is initially an Indented region with zero indentation width. */
var currentRegion: Region = Indented(IndentWidth.Zero, EMPTY, null)
// Error recovery ------------------------------------------------------------
private def lastKnownIndentWidth: IndentWidth =
def recur(r: Region): IndentWidth =
if r.knownWidth == null then recur(r.enclosing) else r.knownWidth
recur(currentRegion)
private var skipping = false
/** Skip on error to next safe point.
*/
def skip(): Unit =
val lastRegion = currentRegion
skipping = true
def atStop =
token == EOF
|| (currentRegion eq lastRegion)
&& (isStatSep
|| closingParens.contains(token) && lastRegion.toList.exists(_.closedBy == token)
|| token == COMMA && lastRegion.toList.exists(_.commasExpected)
|| token == OUTDENT && indentWidth(offset) < lastKnownIndentWidth)
// stop at OUTDENT if the new indentwidth is smaller than the indent width of
// currentRegion. This corrects for the problem that sometimes we don't see an INDENT
// when skipping and therefore might erroneously end up syncing on a nested OUTDENT.
if debugTokenStream then
println(s"\nSTART SKIP AT ${sourcePos().line + 1}, $this in $currentRegion")
var noProgress = 0
// Defensive measure to ensure we always get out of the following while loop
// even if source file is weirly formatted (i.e. we never reach EOF
while !atStop && noProgress < 3 do
val prevOffset = offset
nextToken()
if offset == prevOffset then noProgress += 1 else noProgress = 0
if debugTokenStream then
println(s"\nSTOP SKIP AT ${sourcePos().line + 1}, $this in $currentRegion")
if token == OUTDENT then dropUntil(_.isInstanceOf[Indented])
skipping = false
// Get next token ------------------------------------------------------------
/** Are we directly in a multiline string interpolation expression?
* @pre inStringInterpolation
*/
private def inMultiLineInterpolation = currentRegion match {
case InString(multiLine, _) => multiLine
case _ => false
}
/** Are we in a `${ }` block? such that RBRACE exits back into multiline string. */
private def inMultiLineInterpolatedExpression =
currentRegion match {
case InBraces(InString(true, _)) => true
case _ => false
}
/** read next token and return last offset
*/
def skipToken(): Offset = {
val off = offset
nextToken()
off
}
def skipToken[T](result: T): T =
nextToken()
result
private inline def dropUntil(inline matches: Region => Boolean): Unit =
while !matches(currentRegion) && !currentRegion.isOutermost do
currentRegion = currentRegion.enclosing
def adjustSepRegions(lastToken: Token): Unit = (lastToken: @switch) match {
case LPAREN | LBRACKET =>
currentRegion = InParens(lastToken, currentRegion)
case LBRACE =>
currentRegion = InBraces(currentRegion)
case RBRACE =>
dropUntil(_.isInstanceOf[InBraces])
if !currentRegion.isOutermost then currentRegion = currentRegion.enclosing
case RPAREN | RBRACKET =>
currentRegion match {
case InParens(prefix, outer) if prefix + 1 == lastToken => currentRegion = outer
case _ =>
}
case OUTDENT =>
currentRegion match
case r: Indented => currentRegion = r.enclosing
case _ =>
case STRINGLIT =>
currentRegion match {
case InString(_, outer) => currentRegion = outer
case _ =>
}
case _ =>
}
/** Read a token or copy it from `next` tokenData */
private def getNextToken(lastToken: Token): Unit =
if next.token == EMPTY then
lastOffset = lastCharOffset
currentRegion match
case InString(multiLine, _) if lastToken != STRINGPART => fetchStringPart(multiLine)
case _ => fetchToken()
if token == ERROR then adjustSepRegions(STRINGLIT) // make sure we exit enclosing string literal
else
this.copyFrom(next)
next.token = EMPTY
/** Produce next token, filling TokenData fields of Scanner.
*/
def nextToken(): Unit =
val lastToken = token
val lastName = name
adjustSepRegions(lastToken)
getNextToken(lastToken)
if isAfterLineEnd then handleNewLine(lastToken)
postProcessToken(lastToken, lastName)
profile.recordNewToken()
printState()
final def printState() =
if debugTokenStream && (showLookAheadOnDebug || !isInstanceOf[LookaheadScanner]) then
print(s"[$show${if isInstanceOf[LookaheadScanner] then "(LA)" else ""}]")
/** Insert `token` at assumed `offset` in front of current one. */
def insert(token: Token, offset: Int) = {
assert(next.token == EMPTY, next)
next.copyFrom(this)
this.offset = offset
this.token = token
}
/** A leading symbolic or backquoted identifier is treated as an infix operator if
* - it does not follow a blank line, and
* - it is followed by at least one whitespace character and a
* token that can start an expression.
* - if the operator appears on its own line, the next line must have at least
* the same indentation width as the operator. See pos/i12395 for a test where this matters.
* If a leading infix operator is found and the source version is `3.0-migration`, emit a change warning.
*/
def isLeadingInfixOperator(nextWidth: IndentWidth = indentWidth(offset), inConditional: Boolean = true) =
allowLeadingInfixOperators
&& isOperator
&& (isWhitespace(ch) || ch == LF)
&& !pastBlankLine
&& {
// Is current lexeme assumed to start an expression?
// This is the case if the lexime is one of the tokens that
// starts an expression or it is a COLONeol. Furthermore, if
// the previous token is in backticks, the lexeme may not be a binary operator.
// I.e. in
//
// a
// `x` += 1
//
// `+=` is not assumed to start an expression since it follows an identifier
// in backticks and is a binary operator. Hence, `x` is not classified as a
// leading infix operator.
def assumeStartsExpr(lexeme: TokenData) =
(canStartExprTokens.contains(lexeme.token) || lexeme.token == COLONeol)
&& (!lexeme.isOperator || nme.raw.isUnary(lexeme.name))
val lookahead = LookaheadScanner()
lookahead.allowLeadingInfixOperators = false
// force a NEWLINE a after current token if it is on its own line
lookahead.nextToken()
assumeStartsExpr(lookahead)
|| lookahead.token == NEWLINE
&& assumeStartsExpr(lookahead.next)
&& indentWidth(offset) <= indentWidth(lookahead.next.offset)
}
&& {
currentRegion match
case r: Indented =>
r.width <= nextWidth
|| {
r.outer match
case null => true
case ro @ Indented(outerWidth, _, _) =>
outerWidth < nextWidth && !ro.otherIndentWidths.contains(nextWidth)
case outer =>
outer.indentWidth < nextWidth
}
case _ => true
}
&& {
if migrateTo3 then
val (what, previous) =
if inConditional then ("Rest of line", "previous expression in parentheses")
else ("Line", "expression on the previous line")
report.errorOrMigrationWarning(
em"""$what starts with an operator;
|it is now treated as a continuation of the $previous,
|not as a separate statement.""",
sourcePos(), MigrationVersion.Scala2to3)
true
}
/** The indentation width of the given offset. */
def indentWidth(offset: Offset): IndentWidth =
import IndentWidth.{Run, Conc}
def recur(idx: Int, ch: Char, n: Int, k: IndentWidth => IndentWidth): IndentWidth =
if (idx < 0) k(Run(ch, n))
else {
val nextChar = buf(idx)
if (nextChar == LF) k(Run(ch, n))
else if (nextChar == ' ' || nextChar == '\t')
if (nextChar == ch)
recur(idx - 1, ch, n + 1, k)
else {
val k1: IndentWidth => IndentWidth = if (n == 0) k else Conc(_, Run(ch, n))
recur(idx - 1, nextChar, 1, k1)
}
else recur(idx - 1, ' ', 0, identity)
}
recur(offset - 1, ' ', 0, identity)
end indentWidth
/** Handle newlines, possibly inserting an INDENT, OUTDENT, NEWLINE, or NEWLINES token
* in front of the current token. This depends on whether indentation is significant or not.
*
* Indentation is _significant_ if indentSyntax is set, and we are not inside a
* {...}, [...], (...), case ... => pair, nor in a if/while condition
* (i.e. currentRegion is empty).
*
* There are three rules:
*
* 1. Insert NEWLINE or NEWLINES if
*
* - the closest enclosing sepRegion is { ... } or for ... do/yield,
* or we are on the toplevel, i.e. currentRegion is empty, and
* - the previous token can end a statement, and
* - the current token can start a statement, and
* - the current token is not a leading infix operator, and
* - if indentation is significant then the current token starts at the current
* indentation width or to the right of it.
*
* The inserted token is NEWLINES if the current token is preceded by a
* whitespace line, or NEWLINE otherwise.
*
* 2. Insert INDENT if
*
* - indentation is significant, and
* - the last token can start an indentation region.
* - the indentation of the current token is strictly greater than the previous
* indentation width, or the two widths are the same and the current token is
* one of `:` or `match`.
*
* The following tokens can start an indentation region:
*
* : = => <- if then else while do try catch
* finally for yield match throw return with
*
* Inserting an INDENT starts a new indentation region with the indentation of the current
* token as indentation width.
*
* 3. Insert OUTDENT if
*
* - indentation is significant, and
* - the indentation of the current token is strictly less than the
* previous indentation width,
* - the current token is not a leading infix operator.
*
* Inserting an OUTDENT closes an indentation region. In this case, issue an error if
* the indentation of the current token does not match the indentation of some previous
* line in an enclosing indentation region.
*
* If a token is inserted and consumed, the original source token is still considered to
* start a new line, so the process that inserts an OUTDENT might repeat several times.
*
* Indentation widths are strings consisting of spaces and tabs, ordered by the prefix relation.
* I.e. `a <= b` iff `b.startsWith(a)`. If indentation is significant it is considered an error
* if the current indentation width and the indentation of the current token are incomparable.
*/
def handleNewLine(lastToken: Token) =
var indentIsSignificant = false
var newlineIsSeparating = false
var lastWidth = IndentWidth.Zero
var indentPrefix = EMPTY
val nextWidth = indentWidth(offset)
// If nextWidth is an indentation level not yet seen by enclosing indentation
// region, invoke `handler`.
inline def handleNewIndentWidth(r: Region, inline handler: Indented => Unit): Unit = r match
case r @ Indented(curWidth, prefix, outer)
if curWidth < nextWidth && !r.otherIndentWidths.contains(nextWidth) && nextWidth != lastWidth =>
handler(r)
case _ =>
/** Is this line seen as a continuation of last line? We assume that
* - last line ended in a token that can end a statement
* - current line starts with a token that can start a statement
* - current line does not start with a leading infix operator
* The answer is different for Scala-2 and Scala-3.
* - In Scala 2: Only `{` is treated as continuing, irrespective of indentation.
* But this is in fact handled by Parser.argumentStart which skips a NEWLINE,
* so we always assume false here.
* - In Scala 3: Only indented statements are treated as continuing, as long as
* they start with `(`, `[` or `{`, or the last statement ends in a `return`.
* The Scala 2 rules apply under source `3.0-migration` or under `-no-indent`.
*/
inline def isContinuing =
lastWidth < nextWidth
&& (openParensTokens.contains(token) || lastToken == RETURN)
&& !pastBlankLine
&& !migrateTo3
&& !noindentSyntax
currentRegion match
case r: Indented =>
indentIsSignificant = indentSyntax
lastWidth = r.width
newlineIsSeparating = lastWidth <= nextWidth || r.isOutermost
indentPrefix = r.prefix
case _: InString => ()
case r =>
indentIsSignificant = indentSyntax
r.proposeKnownWidth(nextWidth, lastToken)
lastWidth = r.knownWidth
newlineIsSeparating = r.isInstanceOf[InBraces]
if newlineIsSeparating
&& canEndStatTokens.contains(lastToken)
&& canStartStatTokens.contains(token)
&& !isLeadingInfixOperator(nextWidth)
&& !isContinuing
then
insert(if (pastBlankLine) NEWLINES else NEWLINE, lineOffset)
else if indentIsSignificant then
if nextWidth < lastWidth
|| nextWidth == lastWidth && (indentPrefix == MATCH || indentPrefix == CATCH) && token != CASE then
if currentRegion.isOutermost then
if nextWidth < lastWidth then currentRegion = topLevelRegion(nextWidth)
else if !isLeadingInfixOperator(nextWidth) && !statCtdTokens.contains(lastToken) && lastToken != INDENT then
currentRegion match
case r: Indented =>
insert(OUTDENT, offset)
handleNewIndentWidth(r.enclosing, ir =>
if next.token == DOT
&& !nextWidth.isClose(r.indentWidth)
&& !nextWidth.isClose(ir.indentWidth)
then
ir.otherIndentWidths += nextWidth
else
val lw = lastWidth
errorButContinue(
em"""The start of this line does not match any of the previous indentation widths.
|Indentation width of current line : $nextWidth
|This falls between previous widths: ${ir.width} and $lw"""))
case r =>
if skipping then
if r.enclosing.isClosedByUndentAt(nextWidth) then
insert(OUTDENT, offset)
else if r.isInstanceOf[InBraces] && !closingRegionTokens.contains(token) then
report.warning("Line is indented too far to the left, or a `}` is missing", sourcePos())
else if lastWidth < nextWidth
|| lastWidth == nextWidth && (lastToken == MATCH || lastToken == CATCH) && token == CASE then
if canStartIndentTokens.contains(lastToken) then
currentRegion = Indented(nextWidth, lastToken, currentRegion)
insert(INDENT, offset)
else if lastToken == SELFARROW then
currentRegion.knownWidth = nextWidth
else if (lastWidth != nextWidth)
val lw = lastWidth
errorButContinue(spaceTabMismatchMsg(lw, nextWidth))
if token != OUTDENT then
handleNewIndentWidth(currentRegion, _.otherIndentWidths += nextWidth)
if next.token == EMPTY then
profile.recordNewLine()
end handleNewLine
def spaceTabMismatchMsg(lastWidth: IndentWidth, nextWidth: IndentWidth): Message =
em"""Incompatible combinations of tabs and spaces in indentation prefixes.
|Previous indent : $lastWidth
|Latest indent : $nextWidth"""
def observeColonEOL(inTemplate: Boolean): Unit =
val enabled =
if token == COLONop && inTemplate then
report.deprecationWarning(em"`:` after symbolic operator is deprecated; use backticks around operator instead", sourcePos(offset))
true
else token == COLONfollow && (inTemplate || fewerBracesEnabled)
if enabled then
peekAhead()
val atEOL = isAfterLineEnd || token == EOF
reset()
if atEOL then token = COLONeol
def observeIndented(): Unit =
if indentSyntax && isNewLine then
val nextWidth = indentWidth(next.offset)
val lastWidth = currentRegion.indentWidth
if lastWidth < nextWidth then
currentRegion = Indented(nextWidth, COLONeol, currentRegion)
offset = next.offset
token = INDENT
end observeIndented
/** Insert an <outdent> token if next token closes an indentation region.
* Exception: continue if indentation region belongs to a `match` and next token is `case`.
*/
def observeOutdented(): Unit = currentRegion match
case r: Indented
if !r.isOutermost
&& closingRegionTokens.contains(token)
&& !(token == CASE && r.prefix == MATCH)
&& next.token == EMPTY // can be violated for ill-formed programs, e.g. neg/i12605.sala
=>
insert(OUTDENT, offset)
case _ =>
def peekAhead() =
prev.copyFrom(this)
getNextToken(token)
if token == END && !isEndMarker then token = IDENTIFIER
def reset() =
next.copyFrom(this)
this.copyFrom(prev)
def closeIndented() = currentRegion match
case r: Indented if !r.isOutermost => insert(OUTDENT, offset)
case _ =>
/** - Join CASE + CLASS => CASECLASS, CASE + OBJECT => CASEOBJECT
* SEMI + ELSE => ELSE, COLON following id/)/] => COLONfollow
* - Insert missing OUTDENTs at EOF
*/
def postProcessToken(lastToken: Token, lastName: SimpleName): Unit = {
def fuse(tok: Int) = {
token = tok
offset = prev.offset
lastOffset = prev.lastOffset
lineOffset = prev.lineOffset
}
(token: @switch) match {
case CASE =>
peekAhead()
if (token == CLASS) fuse(CASECLASS)
else if (token == OBJECT) fuse(CASEOBJECT)
else reset()
case SEMI =>
peekAhead()
if (token != ELSE) reset()
case COMMA =>
def isEnclosedInParens(r: Region): Boolean = r match
case r: Indented => isEnclosedInParens(r.outer)
case _: InParens => true
case _ => false
currentRegion match
case r: Indented if isEnclosedInParens(r.outer) =>
insert(OUTDENT, offset)
case _ =>
peekAhead()
if isAfterLineEnd
&& currentRegion.commasExpected
&& (token == RPAREN || token == RBRACKET || token == RBRACE || token == OUTDENT)
then
() /* skip the trailing comma */
else
reset()
case END =>
if !isEndMarker then token = IDENTIFIER
case COLONop =>
if lastToken == IDENTIFIER && lastName != null && isIdentifierStart(lastName.head)
|| colonEOLPredecessors.contains(lastToken)
then token = COLONfollow
case RBRACE | RPAREN | RBRACKET =>
closeIndented()
case EOF =>
if !source.maybeIncomplete then closeIndented()
case _ =>
}
}
protected def isEndMarker: Boolean =
if indentSyntax && isAfterLineEnd then
val endLine = source.offsetToLine(offset)
val lookahead = new LookaheadScanner():
override def isEndMarker = false
lookahead.nextToken()
if endMarkerTokens.contains(lookahead.token)
&& source.offsetToLine(lookahead.offset) == endLine
then
lookahead.nextToken()
if lookahead.token == EOF
|| source.offsetToLine(lookahead.offset) > endLine
then return true
false
/** Is there a blank line between the current token and the last one?
* A blank line consists only of characters <= ' '.
* @pre afterLineEnd().
*/
private def pastBlankLine: Boolean = {
val end = offset
def recur(idx: Offset, isBlank: Boolean): Boolean =
idx < end && {
val ch = buf(idx)
if (ch == LF || ch == FF) isBlank || recur(idx + 1, true)
else recur(idx + 1, isBlank && ch <= ' ')
}
recur(lastOffset, false)
}
import Character.{isHighSurrogate, isLowSurrogate, isUnicodeIdentifierPart, isUnicodeIdentifierStart, isValidCodePoint, toCodePoint}
// f"\\u$c%04x" or f"${"\\"}u$c%04x"
private def toUnicode(c: Char): String = { val s = c.toInt.toHexString; "\\u" + "0" * (4 - s.length) + s }
// 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 = lookaheadChar()
if isLowSurrogate(low) then
val codepoint = toCodePoint(high, low)
if isValidCodePoint(codepoint) then
if test(codepoint) then
putChar(high)
putChar(low)
nextChar()
nextChar()
res = true
else
error(em"illegal character '${toUnicode(high)}${toUnicode(low)}'")
else if !strict then
putChar(high)
nextChar()
res = true
else
error(em"illegal character '${toUnicode(high)}' missing low surrogate")
res
}
private def atSupplementary(ch: Char, f: Int => Boolean): Boolean =
isHighSurrogate(ch) && {
val hi = ch
val lo = lookaheadChar()
isLowSurrogate(lo) && {
val codepoint = toCodePoint(hi, lo)
isValidCodePoint(codepoint) && f(codepoint)
}
}
/** read next token, filling TokenData fields of Scanner.
*/
protected final def fetchToken(): Unit = {
offset = charOffset - 1
lineOffset = if (lastOffset < lineStartOffset) lineStartOffset else -1
name = null
(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' |
'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 xml.Utility.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 '/' =>
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)
error(em"invalid literal number")
}
fetchLeadingZero()
getNumber()
case '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' =>
base = 10
getNumber()
case '`' =>
getBackquotedIdent()
case '\"' =>
def stringPart(multiLine: Boolean) = {
getStringPart(multiLine)
currentRegion = InString(multiLine, currentRegion)
}
def fetchDoubleQuote() =
if (token == INTERPOLATIONID) {
nextRawChar()
if (ch == '\"') {
if (lookaheadChar() == '\"') {
nextRawChar()
nextRawChar()
stringPart(multiLine = true)
}
else {
nextChar()
token = STRINGLIT
strVal = ""
}
}
else {
stringPart(multiLine = false)
}
}
else {
nextChar()
if (ch == '\"') {
nextChar()
if (ch == '\"') {
nextRawChar()
getRawStringLit()
}
else {
token = STRINGLIT
strVal = ""
}
}
else
getStringLit()
}
fetchDoubleQuote()
case '\'' =>
def fetchSingleQuote(): Unit = {
nextChar()
if isIdentifierStart(ch) then
charLitOr { getIdentRest(); QUOTEID }
else if isOperatorPart(ch) && ch != '\\' then
charLitOr { getOperatorRest(); QUOTEID }
else ch match {
case '{' | '[' | ' ' | '\t' if lookaheadChar() != '\'' =>
token = QUOTE
case _ if !isAtEnd && ch != SU && ch != CR && ch != LF =>
val isEmptyCharLit = (ch == '\'')
getLitChar()
if ch == '\'' then
if isEmptyCharLit then error(em"empty character literal (use '\\'' for single quote)")
else if litBuf.length != 1 then error(em"illegal codepoint in Char constant: ${litBuf.toString.map(toUnicode).mkString("'", "", "'")}")
else finishCharLit()
else if isEmptyCharLit then error(em"empty character literal")
else error(em"unclosed character literal")
case _ =>
error(em"unclosed character literal")
}
}
fetchSingleQuote()
case '.' =>
nextChar()
if ('0' <= ch && ch <= '9') {
putChar('.'); getFraction(); setStrVal()
}
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) token = EOF
else {
error(em"illegal character")
nextChar()
}
case _ =>
def fetchOther() =
if ch == '\u21D2' then
nextChar(); token = ARROW
report.deprecationWarning(em"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.", sourcePos(offset))
else if ch == '\u2190' then