-
Notifications
You must be signed in to change notification settings - Fork 622
/
Tokenizer.swift
1993 lines (1885 loc) · 70.3 KB
/
Tokenizer.swift
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
//
// Tokenizer.swift
// SwiftFormat
//
// Created by Nick Lockwood on 11/08/2016.
// Copyright 2016 Nick Lockwood
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/nicklockwood/SwiftFormat
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html
/// Used to speed up matching
// Note: Any, Self, self, super, nil, true and false have been omitted deliberately, as they
/// behave like identifiers. So too have context-specific keywords such as the following:
/// any, associativity, async, convenience, didSet, dynamic, final, get, indirect, infix, lazy,
/// left, mutating, none, nonmutating, open, optional, override, postfix, precedence,
/// prefix, Protocol, required, right, set, some, any, Type, unowned, weak, willSet
let swiftKeywords = Set([
"let", "return", "func", "var", "if", "public", "as", "else", "in", "import",
"class", "try", "guard", "case", "for", "init", "extension", "private", "static",
"fileprivate", "internal", "switch", "do", "catch", "enum", "struct", "throws",
"throw", "typealias", "where", "break", "deinit", "subscript", "is", "while",
"associatedtype", "inout", "continue", "fallthrough", "operator", "precedencegroup",
"repeat", "rethrows", "default", "protocol", "defer", "await", "consume", "discard",
/* Any, Self, self, super, nil, true, false */
])
public extension String {
/// Is this string a reserved keyword in Swift?
var isSwiftKeyword: Bool {
swiftKeywords.contains(self)
}
/// Is this string a valid operator?
var isOperator: Bool {
let tokens = tokenize(self)
return tokens.count == 1 && tokens[0].isOperator
}
/// Is this string a comment directive (MARK:, TODO:, swiftlint:, etc)?
var isCommentDirective: Bool {
commentDirective != nil
}
/// Returns comment directive prefix (MARK:, TODO:, swiftlint:, etc)?
var commentDirective: String? {
let parts = split(separator: ":")
guard parts.count > 1 else {
return nil
}
let exclude = ["note", "warning"]
guard !parts[0].contains(" "), !exclude.contains(parts[0].lowercased()), !parts[1].hasPrefix("//") else {
return nil
}
return String(parts[0])
}
}
/// Classes of token used for matching
public enum TokenType {
case space
case comment
case linebreak
case endOfStatement
case startOfScope
case endOfScope
case keyword
case delimiter
case identifier
case attribute
case `operator`
case unwrapOperator
case rangeOperator
case number
case error
/// OR types
case spaceOrComment
case spaceOrLinebreak
case spaceOrCommentOrLinebreak
case keywordOrAttribute
case identifierOrKeyword
/// NOT types
case nonSpace
case nonLinebreak
case nonSpaceOrComment
case nonSpaceOrLinebreak
case nonSpaceOrCommentOrLinebreak
}
/// Numeric literal types
public enum NumberType {
case integer
case decimal
case binary
case octal
case hex
}
/// Operator/operator types
public enum OperatorType {
case none
case infix
case prefix
case postfix
}
/// Original line number for token
public typealias OriginalLine = Int
/// All token types
public enum Token: Equatable {
case number(String, NumberType)
case linebreak(String, OriginalLine)
case startOfScope(String)
case endOfScope(String)
case delimiter(String)
case `operator`(String, OperatorType)
case stringBody(String)
case keyword(String)
case identifier(String)
case space(String)
case commentBody(String)
case error(String)
}
private extension Token {
/// Test if token matches type of another token
func hasType(of token: Token) -> Bool {
switch (self, token) {
case (.number, .number),
(.operator, .operator),
(.linebreak, .linebreak),
(.startOfScope, .startOfScope),
(.endOfScope, .endOfScope),
(.delimiter, .delimiter),
(.keyword, .keyword),
(.identifier, .identifier),
(.stringBody, .stringBody),
(.commentBody, .commentBody),
(.space, .space),
(.error, .error):
return true
case (.number, _),
(.operator, _),
(.linebreak, _),
(.startOfScope, _),
(.endOfScope, _),
(.delimiter, _),
(.keyword, _),
(.identifier, _),
(.stringBody, _),
(.commentBody, _),
(.space, _),
(.error, _):
return false
}
}
struct StringDelimiterType {
var isRegex: Bool
var isMultiline: Bool
var hashCount: Int
}
var stringDelimiterType: StringDelimiterType? {
switch self {
case let .startOfScope(string), let .endOfScope(string):
var quoteCount = 0, hashCount = 0, slashCount = 0
for c in string {
switch c {
case "#": hashCount += 1
case "\"": quoteCount += 1
case "/": slashCount += 1
default: return nil
}
}
let isRegex = slashCount == 1
guard quoteCount > 0 || isRegex else {
return nil
}
return StringDelimiterType(
isRegex: isRegex,
isMultiline: quoteCount == 3 || (isRegex && hashCount > 0),
hashCount: hashCount
)
default:
return nil
}
}
}
public extension Token {
/// The original token string
var string: String {
switch self {
case let .number(string, _),
let .linebreak(string, _),
let .startOfScope(string),
let .endOfScope(string),
let .delimiter(string),
let .operator(string, _),
let .stringBody(string),
let .keyword(string),
let .identifier(string),
let .space(string),
let .commentBody(string),
let .error(string):
return string
}
}
/// Returns the width (in characters) of the token
func columnWidth(tabWidth: Int) -> Int {
switch self {
case let .space(string), let .stringBody(string), let .commentBody(string):
guard tabWidth > 1 else {
return string.count
}
return string.reduce(0) { count, character in
count + (character == "\t" ? tabWidth : 1)
}
case .linebreak:
return 0
default:
return string.count
}
}
/// Returns the unescaped token string
func unescaped() -> String {
switch self {
case let .stringBody(string):
var input = UnicodeScalarView(string.unicodeScalars)
var output = String.UnicodeScalarView()
while let c = input.popFirst() {
if c == "\\" {
_ = input.readCharacters { $0 == "#" }
if let c = input.popFirst() {
switch c {
case "\0":
output.append("\0")
case "\\":
output.append("\\")
case "t":
output.append("\t")
case "n":
output.append("\n")
case "r":
output.append("\r")
case "\"":
output.append("\"")
case "\'":
output.append("\'")
case "u":
guard input.read("{"),
let hex = input.readCharacters(where: { $0.isHexDigit }),
input.read("}"),
let codepoint = Int(hex, radix: 16),
let c = UnicodeScalar(codepoint)
else {
// Invalid. Recover and continue
continue
}
output.append(c)
default:
// Invalid, but doesn't affect parsing
output.append(c)
}
} else {
// If a string body ends with \, it's probably part of a string
// interpolation expression, so the next token should be a `(`
}
} else {
output.append(c)
}
}
return String(output)
case let .identifier(string):
if string.hasPrefix("$") {
return String(string.dropFirst())
}
return string.replacingOccurrences(of: "`", with: "")
case let .number(string, .integer), let .number(string, .decimal):
return string.replacingOccurrences(of: "_", with: "")
case let .number(s, .binary), let .number(s, .octal), let .number(s, .hex):
var characters = UnicodeScalarView(s.unicodeScalars)
guard characters.read("0"), characters.readCharacter(where: {
"oxb".unicodeScalars.contains($0)
}) != nil else {
return s.replacingOccurrences(of: "_", with: "")
}
return String(characters).replacingOccurrences(of: "_", with: "")
default:
return string
}
}
/// Test if token is of the specified type
func `is`(_ type: TokenType) -> Bool {
switch type {
case .space:
return isSpace
case .comment:
return isComment
case .spaceOrComment:
return isSpaceOrComment
case .spaceOrLinebreak:
return isSpaceOrLinebreak
case .spaceOrCommentOrLinebreak:
return isSpaceOrCommentOrLinebreak
case .linebreak:
return isLinebreak
case .endOfStatement:
return isEndOfStatement
case .startOfScope:
return isStartOfScope
case .endOfScope:
return isEndOfScope
case .keyword:
return isKeyword
case .keywordOrAttribute:
return isKeywordOrAttribute
case .identifier:
return isIdentifier
case .identifierOrKeyword:
return isIdentifierOrKeyword
case .attribute:
return isAttribute
case .delimiter:
return isDelimiter
case .operator:
return isOperator
case .unwrapOperator:
return isUnwrapOperator
case .rangeOperator:
return isRangeOperator
case .number:
return isNumber
case .error:
return isError
case .nonSpace:
return !isSpace
case .nonLinebreak:
return !isLinebreak
case .nonSpaceOrComment:
return !isSpaceOrComment
case .nonSpaceOrLinebreak:
return !isSpaceOrLinebreak
case .nonSpaceOrCommentOrLinebreak:
return !isSpaceOrCommentOrLinebreak
}
}
var isAttribute: Bool { isKeywordOrAttribute && string.hasPrefix("@") }
var isDelimiter: Bool { hasType(of: .delimiter("")) }
var isOperator: Bool { hasType(of: .operator("", .none)) }
var isUnwrapOperator: Bool { isOperator("?", .postfix) || isOperator("!", .postfix) }
var isRangeOperator: Bool { isOperator("...") || isOperator("..<") }
var isNumber: Bool { hasType(of: .number("", .integer)) }
var isError: Bool { hasType(of: .error("")) }
var isStartOfScope: Bool { hasType(of: .startOfScope("")) }
var isEndOfScope: Bool { hasType(of: .endOfScope("")) }
var isKeyword: Bool { isKeywordOrAttribute && !string.hasPrefix("@") }
var isKeywordOrAttribute: Bool { hasType(of: .keyword("")) }
var isIdentifier: Bool { hasType(of: .identifier("")) }
var isIdentifierOrKeyword: Bool { isIdentifier || isKeywordOrAttribute }
var isSpace: Bool { hasType(of: .space("")) }
var isLinebreak: Bool { hasType(of: .linebreak("", 0)) }
var isEndOfStatement: Bool { self == .delimiter(";") || isLinebreak }
var isSpaceOrLinebreak: Bool { isSpace || isLinebreak }
var isSpaceOrComment: Bool { isSpace || isComment }
var isSpaceOrCommentOrLinebreak: Bool { isSpaceOrComment || isLinebreak }
var isCommentOrLinebreak: Bool { isComment || isLinebreak }
var isSwitchCaseOrDefault: Bool {
if case let .endOfScope(string) = self {
return ["case", "default"].contains(string)
}
return self == .keyword("@unknown") // support `@unknown default` as well
}
func isOperator(_ string: String) -> Bool {
if case .operator(string, _) = self {
return true
}
return false
}
func isOperator(ofType type: OperatorType) -> Bool {
if case .operator(_, type) = self {
return true
}
return false
}
func isOperator(_ string: String, _ type: OperatorType) -> Bool {
if case .operator(string, type) = self {
return true
}
return false
}
var isComment: Bool {
switch self {
case .commentBody,
.startOfScope("//"),
.startOfScope("/*"),
.endOfScope("*/"):
return true
default:
return false
}
}
var isCommentBody: Bool {
switch self {
case .commentBody:
return true
default:
return false
}
}
var isStringBody: Bool {
switch self {
case .stringBody:
return true
default:
return false
}
}
var isStringDelimiter: Bool {
switch self {
case let .startOfScope(string), let .endOfScope(string):
return string.contains("\"") || string == "/" || string.hasSuffix("#")
|| (string.hasPrefix("#") && string.hasSuffix("/"))
default:
return false
}
}
var isMultilineStringDelimiter: Bool {
stringDelimiterType?.isMultiline == true
}
func isEndOfScope(_ token: Token) -> Bool {
switch self {
case let .endOfScope(closing):
guard case let .startOfScope(opening) = token else {
return false
}
switch opening {
case "(":
return closing == ")"
case "[":
return closing == "]"
case "<":
return closing == ">"
case "{", ":":
switch closing {
case "}", "case", "default":
return true
default:
return false
}
case "/*":
return closing == "*/"
case "#if":
return closing == "#endif"
default:
if let delimiterType = stringDelimiterType {
let quotes = delimiterType.isRegex ? "/" : (
delimiterType.isMultiline ? "\"\"\"" : "\""
)
let hashes = String(repeating: "#", count: delimiterType.hashCount)
return closing == "\(quotes)\(hashes)"
}
return false
}
case .linebreak:
switch token {
case .startOfScope("//"), .startOfScope("#!"):
return true
default:
return false
}
case .delimiter(":"), .startOfScope(":"):
switch token {
case .endOfScope("case"), .endOfScope("default"), .operator("?", .infix):
return true
default:
return false
}
default:
return false
}
}
}
extension Token {
var isLvalue: Bool {
switch self {
case .identifier, .number, .operator(_, .postfix),
.endOfScope(")"), .endOfScope("]"),
.endOfScope("}"), .endOfScope(">"),
.endOfScope where isStringDelimiter:
return true
case let .keyword(name) where name.hasPrefix("#"):
return true
default:
return false
}
}
var isRvalue: Bool {
switch self {
case .operator(_, .infix), .operator(_, .postfix):
return false
case .identifier, .number, .operator,
.startOfScope("("), .startOfScope("["), .startOfScope("{"),
.startOfScope where isStringDelimiter:
return true
case let .keyword(name) where name.hasPrefix("#"):
return true
default:
return false
}
}
}
extension Collection where Element == Token {
var string: String {
map { $0.string }.joined()
}
}
extension UnicodeScalar {
var isDigit: Bool { isdigit(Int32(value)) > 0 }
var isHexDigit: Bool { isxdigit(Int32(value)) > 0 }
var isLinebreak: Bool { "\n\r\u{000B}\u{000C}".unicodeScalars.contains(self) }
var isSpace: Bool {
switch value {
case 0x0009, 0x0011, 0x0012, 0x0020,
0x0085, 0x00A0, 0x1680, 0x2000 ... 0x200A,
0x2028, 0x2029, 0x202F, 0x205F, 0x3000:
return true
default:
return false
}
}
var isSpaceOrLinebreak: Bool {
isSpace || isLinebreak
}
}
// Workaround for horribly slow String.UnicodeScalarView.Subsequence perf
private struct UnicodeScalarView {
public typealias Index = String.UnicodeScalarView.Index
private let characters: String.UnicodeScalarView
public private(set) var startIndex: Index
public private(set) var endIndex: Index
public init(_ unicodeScalars: String.UnicodeScalarView) {
characters = unicodeScalars
startIndex = characters.startIndex
endIndex = characters.endIndex
}
public init(_ unicodeScalars: String.UnicodeScalarView.SubSequence) {
self.init(String.UnicodeScalarView(unicodeScalars))
}
public init(_ string: String) {
self.init(string.unicodeScalars)
}
public var first: UnicodeScalar? {
isEmpty ? nil : characters[startIndex]
}
@available(*, deprecated, message: "Really hurts performance - use a different approach")
public var count: Int {
characters.distance(from: startIndex, to: endIndex)
}
public var isEmpty: Bool {
startIndex >= endIndex
}
public subscript(_ index: Index) -> UnicodeScalar {
characters[index]
}
public func index(after index: Index) -> Index {
characters.index(after: index)
}
public func prefix(upTo index: Index) -> UnicodeScalarView {
var view = UnicodeScalarView(characters)
view.startIndex = startIndex
view.endIndex = index
return view
}
public func suffix(from index: Index) -> UnicodeScalarView {
var view = UnicodeScalarView(characters)
view.startIndex = index
view.endIndex = endIndex
return view
}
public func dropFirst() -> UnicodeScalarView {
var view = UnicodeScalarView(characters)
view.startIndex = characters.index(after: startIndex)
view.endIndex = endIndex
return view
}
public mutating func popFirst() -> UnicodeScalar? {
if isEmpty {
return nil
}
let char = characters[startIndex]
startIndex = characters.index(after: startIndex)
return char
}
/// Will crash if n > remaining char count
public mutating func removeFirst(_ n: Int) {
startIndex = characters.index(startIndex, offsetBy: n)
}
/// Will crash if collection is empty
@discardableResult
public mutating func removeFirst() -> UnicodeScalar {
let oldIndex = startIndex
startIndex = characters.index(after: startIndex)
return characters[oldIndex]
}
/// Returns the remaining characters
fileprivate var unicodeScalars: String.UnicodeScalarView.SubSequence {
characters[startIndex ..< endIndex]
}
}
private typealias _UnicodeScalarView = UnicodeScalarView
private extension String {
init(_ unicodeScalarView: _UnicodeScalarView) {
self.init(unicodeScalarView.unicodeScalars)
}
}
private extension String.UnicodeScalarView {
init(_ unicodeScalarView: _UnicodeScalarView) {
self.init(unicodeScalarView.unicodeScalars)
}
}
private extension String.UnicodeScalarView.SubSequence {
init(_ unicodeScalarView: _UnicodeScalarView) {
self.init(unicodeScalarView.unicodeScalars)
}
}
private extension UnicodeScalarView {
mutating func readCharacters(where matching: (UnicodeScalar) -> Bool) -> String? {
var index = startIndex
while index < endIndex {
if !matching(self[index]) {
break
}
index = self.index(after: index)
}
if index > startIndex {
let string = String(prefix(upTo: index))
self = suffix(from: index)
return string
}
return nil
}
mutating func read(head: (UnicodeScalar) -> Bool, tail: (UnicodeScalar) -> Bool) -> String? {
if let c = first, head(c) {
var index = self.index(after: startIndex)
while index < endIndex {
if !tail(self[index]) {
break
}
index = self.index(after: index)
}
let string = String(prefix(upTo: index))
self = suffix(from: index)
return string
}
return nil
}
mutating func readCharacter(where matching: (UnicodeScalar) -> Bool) -> UnicodeScalar? {
if let c = first, matching(c) {
self = dropFirst()
return c
}
return nil
}
mutating func read(_ character: UnicodeScalar) -> Bool {
if first == character {
self = dropFirst()
return true
}
return false
}
mutating func readString(_ string: String) -> Bool {
let scalars = string.unicodeScalars
var index = startIndex
for c in scalars {
guard index < endIndex, self[index] == c else {
return false
}
index = self.index(after: index)
}
removeFirst(scalars.count)
return true
}
mutating func readToEndOfToken() -> String {
readCharacters { !$0.isSpaceOrLinebreak } ?? ""
}
}
private extension UnicodeScalarView {
mutating func parseSpace() -> Token? {
readCharacters(where: { $0.isSpace }).map { .space($0) }
}
mutating func parseLineBreak() -> Token? {
switch first {
case "\r":
removeFirst()
if read("\n") {
return .linebreak("\r\n", 0)
}
return .linebreak("\r", 0)
case "\n", "\u{000B}", "\u{000C}":
return .linebreak(String(removeFirst()), 0)
default:
return nil
}
}
mutating func parseDelimiter() -> Token? {
readCharacter(where: {
":;,".unicodeScalars.contains($0)
}).map { .delimiter(String($0)) }
}
mutating func parseStartOfString() -> Token? {
guard read("\"") else {
return nil
}
let start = self
if readString("\"\"") {
if first?.isLinebreak ?? true {
return .startOfScope("\"\"\"")
}
self = start
}
return .startOfScope("\"")
}
mutating func parseStartOfScope() -> Token? {
parseStartOfString() ?? readCharacter(where: {
"<([{".unicodeScalars.contains($0)
}).map { .startOfScope(String($0)) }
}
mutating func parseEndOfScope() -> Token? {
readCharacter(where: {
"}])>".unicodeScalars.contains($0)
}).map { .endOfScope(String($0)) }
}
mutating func parseOperator() -> Token? {
func isHead(_ c: UnicodeScalar) -> Bool {
if "./\\=-+!*%&|^~?".unicodeScalars.contains(c) {
return true
}
switch c.value {
case 0x00A1 ... 0x00A7,
0x00A9, 0x00AB, 0x00AC, 0x00AE,
0x00B0 ... 0x00B1,
0x00B6, 0x00BB, 0x00BF, 0x00D7, 0x00F7,
0x2016 ... 0x2017,
0x2020 ... 0x2027,
0x2030 ... 0x203E,
0x2041 ... 0x2053,
0x2055 ... 0x205E,
0x2190 ... 0x23FF,
0x2500 ... 0x2775,
0x2794 ... 0x2BFF,
0x2E00 ... 0x2E7F,
0x3001 ... 0x3003,
0x3008 ... 0x3030:
return true
default:
return false
}
}
func isTail(_ c: UnicodeScalar) -> Bool {
if isHead(c) {
return true
}
switch c.value {
case 0x0300 ... 0x036F,
0x1DC0 ... 0x1DFF,
0x20D0 ... 0x20FF,
0xFE00 ... 0xFE0F,
0xFE20 ... 0xFE2F,
0xE0100 ... 0xE01EF:
return true
default:
return c == ">"
}
}
var start = self
if var tail = readCharacter(where: isHead) {
switch tail {
case "/" where !["*", "/"].contains(first), "?", "!", "\\":
return .operator(String(tail), .none)
default:
start = self
}
var head = ""
// Tail may only contain dot if head does
let headWasDot = (tail == ".")
while let c = readCharacter(where: { isTail($0) && (headWasDot || $0 != ".") }) {
if tail == "/" {
switch c {
case "*":
if head == "" {
return .startOfScope("/*")
}
// Can't return two tokens, so put /* back to be parsed next time
self = start
return .operator(head, .none)
case "/":
if head == "" {
return .startOfScope("//")
}
// Can't return two tokens, so put // back to be parsed next time
self = start
return .operator(head, .none)
default:
break
}
}
if c != "/" {
start = self
}
head.append(Character(tail))
tail = c
}
head.append(Character(tail))
return .operator(head, .none)
}
return nil
}
mutating func parseIdentifier() -> Token? {
func isHead(_ c: UnicodeScalar) -> Bool {
switch c.value {
case 0x41 ... 0x5A, // A-Z
0x61 ... 0x7A, // a-z
0x5F, 0x24, // _ and $
0x00A8, 0x00AA, 0x00AD, 0x00AF,
0x00B2 ... 0x00B5,
0x00B7 ... 0x00BA,
0x00BC ... 0x00BE,
0x00C0 ... 0x00D6,
0x00D8 ... 0x00F6,
0x00F8 ... 0x00FF,
0x0100 ... 0x02FF,
0x0370 ... 0x167F,
0x1681 ... 0x180D,
0x180F ... 0x1DBF,
0x1E00 ... 0x1FFF,
0x200B ... 0x200D,
0x202A ... 0x202E,
0x203F ... 0x2040,
0x2054,
0x2060 ... 0x206F,
0x2070 ... 0x20CF,
0x2100 ... 0x218F,
0x2460 ... 0x24FF,
0x2776 ... 0x2793,
0x2C00 ... 0x2DFF,
0x2E80 ... 0x2FFF,
0x3004 ... 0x3007,
0x3021 ... 0x302F,
0x3031 ... 0x303F,
0x3040 ... 0xD7FF,
0xF900 ... 0xFD3D,
0xFD40 ... 0xFDCF,
0xFDF0 ... 0xFE1F,
0xFE30 ... 0xFE44,
0xFE47 ... 0xFFFD,
0x10000 ... 0x1FFFD,
0x20000 ... 0x2FFFD,
0x30000 ... 0x3FFFD,
0x40000 ... 0x4FFFD,
0x50000 ... 0x5FFFD,
0x60000 ... 0x6FFFD,
0x70000 ... 0x7FFFD,
0x80000 ... 0x8FFFD,
0x90000 ... 0x9FFFD,
0xA0000 ... 0xAFFFD,
0xB0000 ... 0xBFFFD,
0xC0000 ... 0xCFFFD,
0xD0000 ... 0xDFFFD,
0xE0000 ... 0xEFFFD:
return true
default:
return false
}
}
func isTail(_ c: UnicodeScalar) -> Bool {
switch c.value {
case 0x30 ... 0x39, // 0-9
0x0300 ... 0x036F,
0x1DC0 ... 0x1DFF,
0x20D0 ... 0x20FF,
0xFE20 ... 0xFE2F:
return true
default:
return isHead(c)
}
}
func readIdentifier() -> String? {
read(head: isHead, tail: isTail)
}
let start = self
if read("`") {
if let identifier = readIdentifier(), read("`") {
return .identifier("`" + identifier + "`")
}
self = start
} else if read("<") {
if read("#") {
// look for closing Xcode token
var previousWasHash = false
var index = startIndex
var found = false
while index < endIndex {
let idx = index
index = self.index(after: index)
if self[idx] == ">" {
if previousWasHash {
found = true
break
}
} else {
previousWasHash = self[idx] == "#"
}