-
Notifications
You must be signed in to change notification settings - Fork 415
/
Types.swift
1134 lines (1033 loc) · 36 KB
/
Types.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if swift(>=6)
@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax
#else
@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax
#endif
extension Parser {
/// Parse a type.
mutating func parseType(misplacedSpecifiers: [RawTokenSyntax] = []) -> RawTypeSyntax {
// Parse pack expansion 'repeat T'.
if let repeatKeyword = self.consume(if: .keyword(.repeat)) {
let repetitionPattern = self.parseTypeScalar(misplacedSpecifiers: misplacedSpecifiers)
return RawTypeSyntax(
RawPackExpansionTypeSyntax(
repeatKeyword: repeatKeyword,
repetitionPattern: repetitionPattern,
arena: self.arena
)
)
}
return self.parseTypeScalar(misplacedSpecifiers: misplacedSpecifiers)
}
mutating func parseTypeScalar(misplacedSpecifiers: [RawTokenSyntax] = []) -> RawTypeSyntax {
let specifiersAndAttributes = self.parseTypeAttributeList(misplacedSpecifiers: misplacedSpecifiers)
var base = RawTypeSyntax(self.parseSimpleOrCompositionType())
if self.withLookahead({ $0.canParseFunctionTypeArrow() }) {
var effectSpecifiers = self.parseTypeEffectSpecifiers()
let returnClause = self.parseFunctionReturnClause(
effectSpecifiers: &effectSpecifiers,
allowNamedOpaqueResultType: false
)
let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax?
let leftParen: RawTokenSyntax
let unexpectedBetweenLeftParenAndElements: RawUnexpectedNodesSyntax?
let parameters: RawTupleTypeElementListSyntax
let unexpectedBetweenElementsAndRightParen: RawUnexpectedNodesSyntax?
let rightParen: RawTokenSyntax
if let input = base.as(RawTupleTypeSyntax.self) {
unexpectedBeforeLeftParen = input.unexpectedBeforeLeftParen
leftParen = input.leftParen
unexpectedBetweenLeftParenAndElements = input.unexpectedBetweenLeftParenAndElements
parameters = input.elements
unexpectedBetweenElementsAndRightParen = input.unexpectedBetweenElementsAndRightParen
rightParen = input.rightParen
} else {
unexpectedBeforeLeftParen = nil
leftParen = RawTokenSyntax(missing: .leftParen, arena: self.arena)
unexpectedBetweenLeftParenAndElements = nil
parameters = RawTupleTypeElementListSyntax(
elements: [
RawTupleTypeElementSyntax(
inoutKeyword: nil,
firstName: nil,
secondName: nil,
colon: nil,
type: base,
ellipsis: nil,
trailingComma: nil,
arena: self.arena
)
],
arena: self.arena
)
unexpectedBetweenElementsAndRightParen = nil
rightParen = RawTokenSyntax(missing: .rightParen, arena: self.arena)
}
base = RawTypeSyntax(
RawFunctionTypeSyntax(
unexpectedBeforeLeftParen,
leftParen: leftParen,
unexpectedBetweenLeftParenAndElements,
parameters: parameters,
unexpectedBetweenElementsAndRightParen,
rightParen: rightParen,
effectSpecifiers: effectSpecifiers,
returnClause: returnClause,
arena: self.arena
)
)
}
if let specifiersAndAttributes {
return RawTypeSyntax(
RawAttributedTypeSyntax(
specifiers: specifiersAndAttributes.specifiers,
attributes: specifiersAndAttributes.attributes,
baseType: base,
arena: self.arena
)
)
} else {
return RawTypeSyntax(base)
}
}
/// Parse a protocol composition involving at least one element.
mutating func parseSimpleOrCompositionType() -> RawTypeSyntax {
// 'each' is a contextual keyword for a pack reference.
if let each = consume(if: .keyword(.each)) {
let packType = parseSimpleType()
return RawTypeSyntax(
RawPackElementTypeSyntax(
eachKeyword: each,
pack: packType,
arena: self.arena
)
)
}
let someOrAny = self.consume(if: .keyword(.some), .keyword(.any))
var base = self.parseSimpleType()
guard self.atContextualPunctuator("&") else {
if let someOrAny {
return RawTypeSyntax(
RawSomeOrAnyTypeSyntax(
someOrAnySpecifier: someOrAny,
constraint: base,
arena: self.arena
)
)
} else {
return base
}
}
var elements = [RawCompositionTypeElementSyntax]()
if let firstAmpersand = self.consumeIfContextualPunctuator("&") {
elements.append(
RawCompositionTypeElementSyntax(
type: base,
ampersand: firstAmpersand,
arena: self.arena
)
)
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let elementType = self.parseSimpleType()
keepGoing = self.consumeIfContextualPunctuator("&")
elements.append(
RawCompositionTypeElementSyntax(
type: elementType,
ampersand: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && self.hasProgressed(&loopProgress)
base = RawTypeSyntax(
RawCompositionTypeSyntax(
elements: RawCompositionTypeElementListSyntax(elements: elements, arena: self.arena),
arena: self.arena
)
)
}
if let someOrAny {
return RawTypeSyntax(
RawSomeOrAnyTypeSyntax(
someOrAnySpecifier: someOrAny,
constraint: base,
arena: self.arena
)
)
} else {
return base
}
}
/// Parse the subset of types that we allow in attribute names.
mutating func parseAttributeName() -> RawTypeSyntax {
return parseSimpleType(forAttributeName: true)
}
/// Parse a "simple" type
mutating func parseSimpleType(
stopAtFirstPeriod: Bool = false,
forAttributeName: Bool = false
) -> RawTypeSyntax {
enum TypeBaseStart: TokenSpecSet {
case `Self`
case `Any`
case identifier
case leftParen
case leftSquare
case wildcard
init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) {
switch PrepareForKeywordMatch(lexeme) {
case .keyword(.Self): self = .Self
case .keyword(.Any): self = .Any
case .identifier: self = .identifier
case .leftParen: self = .leftParen
case .leftSquare: self = .leftSquare
case .wildcard: self = .wildcard
default: return nil
}
}
var spec: TokenSpec {
switch self {
case .Self: return .keyword(.Self)
case .Any: return .keyword(.Any)
case .identifier: return .identifier
case .leftParen: return .leftParen
case .leftSquare: return .leftSquare
case .wildcard: return .wildcard
}
}
}
// Eat any '~' preceding the type.
let maybeTilde = self.consumeIfContextualPunctuator("~", remapping: .prefixOperator)
// Wrap as a suppressed type if needed.
func wrapInTilde(_ node: RawTypeSyntax) -> RawTypeSyntax {
if let tilde = maybeTilde {
return RawTypeSyntax(
RawSuppressedTypeSyntax(
withoutTilde: tilde,
type: node,
arena: self.arena
)
)
}
return node
}
var base: RawTypeSyntax
switch self.at(anyIn: TypeBaseStart.self)?.spec {
case .Self, .Any, .identifier:
base = self.parseTypeIdentifier()
case .leftParen:
base = RawTypeSyntax(self.parseTupleTypeBody())
case .leftSquare:
base = RawTypeSyntax(self.parseCollectionType())
case .wildcard:
base = RawTypeSyntax(self.parsePlaceholderType())
case nil:
return wrapInTilde(RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)))
}
var loopProgress = LoopProgressCondition()
while self.hasProgressed(&loopProgress) {
if !stopAtFirstPeriod, self.at(.period) {
let (unexpectedPeriod, period, skipMemberName) = self.consumeMemberPeriod(previousNode: base)
if skipMemberName {
let missingIdentifier = missingToken(.identifier)
base = RawTypeSyntax(
RawMemberTypeSyntax(
baseType: base,
unexpectedPeriod,
period: period,
name: missingIdentifier,
genericArgumentClause: nil,
arena: self.arena
)
)
break
} else if self.at(.keyword(.Type)) || self.at(.keyword(.Protocol)) {
let metatypeSpecifier = self.consume(if: .keyword(.Type)) ?? self.consume(if: .keyword(.Protocol))!
base = RawTypeSyntax(
RawMetatypeTypeSyntax(
baseType: base,
unexpectedPeriod,
period: period,
metatypeSpecifier: metatypeSpecifier,
arena: self.arena
)
)
} else {
let name: RawTokenSyntax
if let handle = self.at(anyIn: MemberTypeSyntax.NameOptions.self)?.handle {
name = self.eat(handle)
} else if self.currentToken.isLexerClassifiedKeyword {
name = self.consumeAnyToken(remapping: .identifier)
} else {
name = missingToken(.identifier)
}
let generics: RawGenericArgumentClauseSyntax?
if self.atContextualPunctuator("<") {
generics = self.parseGenericArguments()
} else {
generics = nil
}
base = RawTypeSyntax(
RawMemberTypeSyntax(
baseType: base,
unexpectedPeriod,
period: period,
name: name,
genericArgumentClause: generics,
arena: self.arena
)
)
}
continue
}
// Do not allow ? or ! suffixes when parsing attribute names.
if forAttributeName {
break
}
if self.at(TokenSpec(.postfixQuestionMark, allowAtStartOfLine: false)) {
base = RawTypeSyntax(self.parseOptionalType(base))
continue
}
if self.at(TokenSpec(.exclamationMark, allowAtStartOfLine: false)) {
base = RawTypeSyntax(self.parseImplicitlyUnwrappedOptionalType(base))
continue
}
break
}
base = wrapInTilde(base)
return base
}
/// Parse an optional type.
mutating func parseOptionalType(_ base: RawTypeSyntax) -> RawOptionalTypeSyntax {
let (unexpectedBeforeMark, mark) = self.expect(.postfixQuestionMark)
return RawOptionalTypeSyntax(
wrappedType: base,
unexpectedBeforeMark,
questionMark: mark,
arena: self.arena
)
}
/// Parse an optional type.
mutating func parseImplicitlyUnwrappedOptionalType(
_ base: RawTypeSyntax
) -> RawImplicitlyUnwrappedOptionalTypeSyntax {
let (unexpectedBeforeMark, mark) = self.expect(.exclamationMark)
return RawImplicitlyUnwrappedOptionalTypeSyntax(
wrappedType: base,
unexpectedBeforeMark,
exclamationMark: mark,
arena: self.arena
)
}
/// Parse a type identifier.
mutating func parseTypeIdentifier() -> RawTypeSyntax {
if self.at(.keyword(.Any)) {
return RawTypeSyntax(self.parseAnyType())
}
let (unexpectedBeforeName, name) = self.expect(anyIn: IdentifierTypeSyntax.NameOptions.self, default: .identifier)
let generics: RawGenericArgumentClauseSyntax?
if self.atContextualPunctuator("<") {
generics = self.parseGenericArguments()
} else {
generics = nil
}
return RawTypeSyntax(
RawIdentifierTypeSyntax(
unexpectedBeforeName,
name: name,
genericArgumentClause: generics,
arena: self.arena
)
)
}
/// Parse the existential `Any` type.
mutating func parseAnyType() -> RawIdentifierTypeSyntax {
let (unexpectedBeforeName, name) = self.expect(.keyword(.Any))
return RawIdentifierTypeSyntax(
unexpectedBeforeName,
name: name,
genericArgumentClause: nil,
arena: self.arena
)
}
/// Parse a type placeholder.
mutating func parsePlaceholderType() -> RawIdentifierTypeSyntax {
let (unexpectedBeforeName, name) = self.expect(.wildcard)
return RawIdentifierTypeSyntax(
unexpectedBeforeName,
name: name,
genericArgumentClause: nil,
arena: self.arena
)
}
}
extension Parser {
/// Parse the generic arguments applied to a type.
mutating func parseGenericArguments() -> RawGenericArgumentClauseSyntax {
let langle = self.expectWithoutRecovery(prefix: "<", as: .leftAngle)
var arguments = [RawGenericArgumentSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let type = self.parseType()
if arguments.isEmpty && type.is(RawMissingTypeSyntax.self) {
break
}
keepGoing = self.consume(if: .comma)
arguments.append(
RawGenericArgumentSyntax(
argument: type,
trailingComma: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && self.hasProgressed(&loopProgress)
}
let rangle = self.expectWithoutRecovery(prefix: ">", as: .rightAngle)
let args: RawGenericArgumentListSyntax
if arguments.isEmpty && rangle.isMissing {
args = RawGenericArgumentListSyntax(elements: [], arena: self.arena)
} else {
args = RawGenericArgumentListSyntax(elements: arguments, arena: self.arena)
}
return RawGenericArgumentClauseSyntax(
leftAngle: langle,
arguments: args,
rightAngle: rangle,
arena: self.arena
)
}
}
extension Parser {
/// Parse a tuple type.
mutating func parseTupleTypeBody() -> RawTupleTypeSyntax {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawTupleTypeSyntax(
remainingTokens,
leftParen: missingToken(.leftParen),
elements: RawTupleTypeElementListSyntax(elements: [], arena: self.arena),
rightParen: missingToken(.rightParen),
arena: self.arena
)
}
let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen)
var elements = [RawTupleTypeElementSyntax]()
do {
var keepGoing = true
var loopProgress = LoopProgressCondition()
while !self.at(.endOfFile, .rightParen) && keepGoing && self.hasProgressed(&loopProgress) {
let unexpectedBeforeFirst: RawUnexpectedNodesSyntax?
let first: RawTokenSyntax?
let unexpectedBeforeSecond: RawUnexpectedNodesSyntax?
let second: RawTokenSyntax?
let unexpectedBeforeColon: RawUnexpectedNodesSyntax?
let colon: RawTokenSyntax?
var misplacedSpecifiers: [RawTokenSyntax] = []
if self.withLookahead({ $0.startsParameterName(isClosure: false, allowMisplacedSpecifierRecovery: true) }) {
while canHaveParameterSpecifier,
let specifier = self.consume(ifAnyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self)
{
misplacedSpecifiers.append(specifier)
}
(unexpectedBeforeFirst, first) = self.parseArgumentLabel()
if let parsedColon = self.consume(if: .colon) {
unexpectedBeforeSecond = nil
second = nil
unexpectedBeforeColon = nil
colon = parsedColon
} else if self.atArgumentLabel(allowDollarIdentifier: true) && self.peek(isAt: .colon) {
(unexpectedBeforeSecond, second) = self.parseArgumentLabel()
(unexpectedBeforeColon, colon) = self.expect(.colon)
} else {
unexpectedBeforeSecond = nil
second = nil
unexpectedBeforeColon = nil
colon = RawTokenSyntax(missing: .colon, arena: self.arena)
}
} else {
unexpectedBeforeFirst = nil
first = nil
unexpectedBeforeSecond = nil
second = nil
unexpectedBeforeColon = nil
colon = nil
}
// In the case that the input is "(foo bar)" we have to decide whether we parse it as "(foo: bar)" or "(foo, bar)".
// As most people write identifiers lowercase and types capitalized, we decide on the first character of the first token
if let first,
second == nil,
colon?.isMissing == true,
first.tokenKind == .identifier,
first.tokenText.isStartingWithUppercase
{
elements.append(
RawTupleTypeElementSyntax(
inoutKeyword: nil,
firstName: nil,
secondName: nil,
RawUnexpectedNodesSyntax(combining: misplacedSpecifiers, unexpectedBeforeColon, arena: self.arena),
colon: nil,
type: RawTypeSyntax(RawIdentifierTypeSyntax(name: first, genericArgumentClause: nil, arena: self.arena)),
ellipsis: nil,
trailingComma: self.missingToken(.comma),
arena: self.arena
)
)
keepGoing = true
continue
}
// Parse the type annotation.
let type = self.parseType(misplacedSpecifiers: misplacedSpecifiers)
let ellipsis = self.consumeIfContextualPunctuator("...", remapping: .ellipsis)
var trailingComma = self.consume(if: .comma)
if trailingComma == nil && self.withLookahead({ $0.canParseType() }) {
// If the next token does not close the tuple, it is very likely the user forgot the comma.
trailingComma = self.missingToken(.comma)
}
keepGoing = trailingComma != nil
elements.append(
RawTupleTypeElementSyntax(
inoutKeyword: nil,
RawUnexpectedNodesSyntax(combining: misplacedSpecifiers, unexpectedBeforeFirst, arena: self.arena),
firstName: first,
unexpectedBeforeSecond,
secondName: second,
unexpectedBeforeColon,
colon: colon,
type: type,
ellipsis: ellipsis,
trailingComma: trailingComma,
arena: self.arena
)
)
}
}
let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
return RawTupleTypeSyntax(
unexpectedBeforeLParen,
leftParen: lparen,
elements: RawTupleTypeElementListSyntax(elements: elements, arena: self.arena),
unexpectedBeforeRParen,
rightParen: rparen,
arena: self.arena
)
}
}
extension Parser {
/// Parse an array or dictionary type..
mutating func parseCollectionType() -> RawTypeSyntax {
if let remaingingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawTypeSyntax(
RawArrayTypeSyntax(
remaingingTokens,
leftSquare: missingToken(.leftSquare),
element: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
rightSquare: missingToken(.rightSquare),
arena: self.arena
)
)
}
let (unexpectedBeforeLSquare, leftsquare) = self.expect(.leftSquare)
let firstType = self.parseType()
if let colon = self.consume(if: .colon) {
let secondType = self.parseType()
let (unexpectedBeforeRSquareBracket, rightSquare) = self.expect(.rightSquare)
return RawTypeSyntax(
RawDictionaryTypeSyntax(
unexpectedBeforeLSquare,
leftSquare: leftsquare,
key: firstType,
colon: colon,
value: secondType,
unexpectedBeforeRSquareBracket,
rightSquare: rightSquare,
arena: self.arena
)
)
} else {
let (unexpectedBeforeRSquareBracket, rSquareBracket) = self.expect(.rightSquare)
return RawTypeSyntax(
RawArrayTypeSyntax(
unexpectedBeforeLSquare,
leftSquare: leftsquare,
element: firstType,
unexpectedBeforeRSquareBracket,
rightSquare: rSquareBracket,
arena: self.arena
)
)
}
}
}
extension Parser.Lookahead {
mutating func canParseType() -> Bool {
guard self.canParseTypeScalar() else {
return false
}
if self.atContextualPunctuator("...") {
self.consumeAnyToken()
}
return true
}
mutating func skipTypeAttributeList() {
var specifierProgress = LoopProgressCondition()
// TODO: Can we model isolated/_const so that they're specified in both canParse* and parse*?
while canHaveParameterSpecifier,
self.at(anyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) != nil || self.at(.keyword(.isolated))
|| self.at(.keyword(._const)),
self.hasProgressed(&specifierProgress)
{
self.consumeAnyToken()
}
var attributeProgress = LoopProgressCondition()
while self.at(.atSign), self.hasProgressed(&attributeProgress) {
self.consumeAnyToken()
self.skipTypeAttribute()
}
}
mutating func canParseTypeScalar() -> Bool {
// 'repeat' starts a pack expansion type
self.consume(if: .keyword(.repeat))
self.skipTypeAttributeList()
guard self.canParseSimpleOrCompositionType() else {
return false
}
if self.canParseFunctionTypeArrow() {
return self.canParseType()
}
return true
}
mutating func canParseSimpleOrCompositionType() -> Bool {
if self.at(.keyword(.some)) || self.at(.keyword(.any)) || self.at(.keyword(.each)) {
self.consumeAnyToken()
}
guard self.canParseSimpleType() else {
return false
}
var loopProgress = LoopProgressCondition()
while self.atContextualPunctuator("&") && self.hasProgressed(&loopProgress) {
self.consumeAnyToken()
guard self.canParseSimpleType() else {
return false
}
}
return true
}
mutating func canParseSimpleType() -> Bool {
switch self.currentToken {
case TokenSpec(.Any):
self.consumeAnyToken()
case TokenSpec(.prefixOperator) where self.currentToken.tokenText == "~":
self.consumeAnyToken()
fallthrough
case TokenSpec(.Self), TokenSpec(.identifier):
guard self.canParseTypeIdentifier() else {
return false
}
case TokenSpec(.leftParen):
self.consumeAnyToken()
guard self.canParseTupleBodyType() else {
return false
}
case TokenSpec(.leftSquare):
self.consumeAnyToken()
guard self.canParseType() else {
return false
}
if self.consume(if: .colon) != nil {
guard self.canParseType() else {
return false
}
}
guard self.consume(if: .rightSquare) != nil else {
return false
}
case TokenSpec(.wildcard):
self.consumeAnyToken()
case TokenSpec(.repeat):
return true
default:
return false
}
var loopProgress = LoopProgressCondition()
while self.hasProgressed(&loopProgress) {
if self.at(.period) {
self.consumeAnyToken()
if self.at(.keyword(.Type)) || self.at(.keyword(.Protocol)) {
self.consumeAnyToken()
continue
}
if self.canParseTypeIdentifier(allowKeyword: true) {
continue
}
return false
}
if self.at(TokenSpec(.postfixQuestionMark, allowAtStartOfLine: false))
|| self.at(TokenSpec(.exclamationMark, allowAtStartOfLine: false))
{
self.consumeAnyToken()
continue
}
break
}
return true
}
mutating func canParseTupleBodyType() -> Bool {
guard
!self.at(.rightParen, .rightBrace) && !self.atContextualPunctuator("...")
// In types, we do not allow for an inout binding to be declared in a
// tuple type.
&& (self.at(.keyword(.inout)) || !self.atStartOfDeclaration())
else {
return self.consume(if: .rightParen) != nil
}
var loopProgress = LoopProgressCondition()
repeat {
// The contextual inout marker is part of argument lists.
_ = self.consume(if: .keyword(.inout))
// If the tuple element starts with "ident :", then it is followed
// by a type annotation.
if self.startsParameterName(isClosure: false, allowMisplacedSpecifierRecovery: false) {
self.consumeAnyToken()
if self.atArgumentLabel() {
self.consumeAnyToken()
guard self.at(.colon) else {
return false
}
}
self.eat(.colon)
// Parse a type.
guard self.canParseType() else {
return false
}
// Parse default values. This aren't actually allowed, but we recover
// better if we skip over them.
if self.consume(if: .equal) != nil {
var skipProgress = LoopProgressCondition()
while !self.at(.endOfFile)
&& !self.at(.rightParen, .rightBrace, .comma)
&& !self.atContextualPunctuator("...")
&& !self.atStartOfDeclaration()
&& self.hasProgressed(&skipProgress)
{
self.skipSingle()
}
}
continue
}
// Otherwise, this has to be a type.
guard self.canParseType() else {
return false
}
self.consumeIfContextualPunctuator("...")
} while self.consume(if: .comma) != nil && self.hasProgressed(&loopProgress)
return self.consume(if: .rightParen) != nil
}
mutating func canParseFunctionTypeArrow() -> Bool {
if self.consume(if: .arrow) != nil {
return true
}
self.consumeEffectsSpecifiers()
return self.consume(if: .arrow) != nil
}
mutating func canParseTypeIdentifier(allowKeyword: Bool = false) -> Bool {
if self.at(.keyword(.Any)) {
self.consumeAnyToken()
return true
}
// Parse an identifier.
guard
self.at(.identifier) || self.at(.keyword(.Self)) || (allowKeyword && self.currentToken.isLexerClassifiedKeyword)
else {
return false
}
self.consumeAnyToken()
// Parse an optional generic argument list.
if self.at(prefix: "<") && !self.consumeGenericArguments() {
return false
}
return true
}
mutating func canParseAsGenericArgumentList() -> Bool {
guard self.atContextualPunctuator("<") else {
return false
}
var lookahead = self.lookahead()
guard lookahead.consumeGenericArguments() else {
return false
}
return lookahead.currentToken.isGenericTypeDisambiguatingToken
}
mutating func consumeGenericArguments() -> Bool {
// Parse the opening '<'.
guard self.consume(ifPrefix: "<", as: .leftAngle) != nil else {
return false
}
if !self.at(prefix: ">") {
var loopProgress = LoopProgressCondition()
repeat {
guard self.canParseType() else {
return false
}
// Parse the comma, if the list continues.
} while self.consume(if: .comma) != nil && self.hasProgressed(&loopProgress)
}
guard self.consume(ifPrefix: ">", as: .rightAngle) != nil else {
return false
}
return true
}
}
extension Parser {
private mutating func parseLifetimeTypeSpecifier() -> RawTypeSpecifierListSyntax.Element {
let (unexpectedBeforeDependsOnKeyword, dependsOnKeyword) = self.expect(.keyword(.dependsOn))
guard let leftParen = self.consume(if: .leftParen) else {
// If there is no left paren, add an entirely missing detail. Otherwise, we start to consume the following type
// name as a token inside the detail, which leads to confusing recovery results.
let lifetimeSpecifierArgumentList = RawLifetimeSpecifierArgumentListSyntax(
elements: [
RawLifetimeSpecifierArgumentSyntax(parameter: missingToken(.identifier), trailingComma: nil, arena: arena)
],
arena: self.arena
)
let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax(
unexpectedBeforeDependsOnKeyword,
dependsOnKeyword: dependsOnKeyword,
leftParen: missingToken(.leftParen),
scopedKeyword: nil,
arguments: lifetimeSpecifierArgumentList,
rightParen: missingToken(.rightParen),
arena: self.arena
)
return .lifetimeTypeSpecifier(lifetimeSpecifier)
}
let scoped = self.consume(if: .keyword(.scoped))
var keepGoing: RawTokenSyntax?
var arguments: [RawLifetimeSpecifierArgumentSyntax] = []
var loopProgress = LoopProgressCondition()
repeat {
let (unexpectedBeforeParameter, parameter) = self.expect(
anyIn: LifetimeSpecifierArgumentSyntax.ParameterOptions.self,
default: .identifier
)
keepGoing = self.consume(if: .comma)
arguments.append(
RawLifetimeSpecifierArgumentSyntax(
unexpectedBeforeParameter,
parameter: parameter,
trailingComma: keepGoing,
arena: arena
)
)
} while keepGoing != nil && self.hasProgressed(&loopProgress)
let lifetimeSpecifierArgumentList = RawLifetimeSpecifierArgumentListSyntax(elements: arguments, arena: self.arena)
let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax(
unexpectedBeforeDependsOnKeyword,
dependsOnKeyword: dependsOnKeyword,
leftParen: leftParen,
scopedKeyword: scoped,
arguments: lifetimeSpecifierArgumentList,
unexpectedBeforeRightParen,
rightParen: rightParen,
arena: self.arena
)
return .lifetimeTypeSpecifier(lifetimeSpecifier)
}
private mutating func parseSimpleTypeSpecifier(
specifierHandle: TokenConsumptionHandle
) -> RawTypeSpecifierListSyntax.Element {
let specifier = self.eat(specifierHandle)
let simpleSpecifier = RawSimpleTypeSpecifierSyntax(specifier: specifier, arena: arena)
return .simpleTypeSpecifier(simpleSpecifier)
}
mutating func parseTypeAttributeList(
misplacedSpecifiers: [RawTokenSyntax] = []
) -> (
specifiers: RawTypeSpecifierListSyntax,
attributes: RawAttributeListSyntax
)? {
var specifiers: [RawTypeSpecifierListSyntax.Element] = []
SPECIFIER_PARSING: while canHaveParameterSpecifier {
if let (_, specifierHandle) = self.at(anyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) {
specifiers.append(parseSimpleTypeSpecifier(specifierHandle: specifierHandle))
} else if self.at(.keyword(.dependsOn)) {
if self.experimentalFeatures.contains(.nonescapableTypes) {
specifiers.append(parseLifetimeTypeSpecifier())
} else {
break SPECIFIER_PARSING
}
} else {
break SPECIFIER_PARSING
}
}
specifiers += misplacedSpecifiers.map {
.simpleTypeSpecifier(
RawSimpleTypeSpecifierSyntax(
specifier: missingToken($0.tokenKind, text: $0.tokenText),
arena: arena
)
)
}
let attributes: RawAttributeListSyntax?
if self.at(.atSign) {
attributes = self.parseTypeAttributeListPresent()
} else {
attributes = nil
}
guard !specifiers.isEmpty || attributes != nil else {
// No specifiers or attributes on this type
return nil
}
let specifierList: RawTypeSpecifierListSyntax
if specifiers.isEmpty {
specifierList = self.emptyCollection(RawTypeSpecifierListSyntax.self)
} else {
specifierList = RawTypeSpecifierListSyntax(elements: specifiers, arena: arena)
}
return (
specifierList,
attributes ?? self.emptyCollection(RawAttributeListSyntax.self)
)
}
mutating func parseTypeAttributeListPresent() -> RawAttributeListSyntax {
var elements = [RawAttributeListSyntax.Element]()
var attributeProgress = LoopProgressCondition()
while self.at(.atSign) && self.hasProgressed(&attributeProgress) {
elements.append(self.parseTypeAttribute())