-
Notifications
You must be signed in to change notification settings - Fork 433
/
Copy pathDeclarations.swift
2070 lines (1892 loc) · 71.9 KB
/
Declarations.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) internal import SwiftSyntax
#else
@_spi(RawSyntax) import SwiftSyntax
#endif
extension DeclarationModifier {
var canHaveParenthesizedArgument: Bool {
switch self {
case .__consuming, .__setter_access, ._const, ._local, .async,
.borrowing, .class, .consuming, .convenience, .distributed, .dynamic,
.final, .indirect, .infix, .isolated, .lazy, .mutating, .nonmutating,
.optional, .override, .postfix, .prefix, .reasync, .required,
.rethrows, .static, .weak, .sending:
return false
case .fileprivate, .internal, .nonisolated, .package, .open, .private,
.public, .unowned:
return true
}
}
}
extension TokenConsumer {
mutating func atStartOfFreestandingMacroExpansion() -> Bool {
// Check if "'#' <identifier>" where the identifier is on the sameline.
if !self.at(.pound) {
return false
}
if self.peek().isAtStartOfLine {
return false
}
switch self.peek().rawTokenKind {
case .identifier:
return true
case .keyword:
// allow keywords right after '#' so we can diagnose it when parsing.
return (self.currentToken.trailingTriviaByteLength == 0 && self.peek().leadingTriviaByteLength == 0)
default:
return false
}
}
mutating func atStartOfDeclaration(
isAtTopLevel: Bool = false,
allowInitDecl: Bool = true,
allowRecovery: Bool = false
) -> Bool {
if self.at(.poundIf) {
return true
}
var subparser = self.lookahead()
var hasAttribute = false
var attributeProgress = LoopProgressCondition()
while subparser.hasProgressed(&attributeProgress) && subparser.at(.atSign) {
hasAttribute = true
_ = subparser.consumeAttributeList()
}
var hasModifier = false
if subparser.currentToken.isLexerClassifiedKeyword || subparser.currentToken.rawTokenKind == .identifier {
var modifierProgress = LoopProgressCondition()
while let (modifierKind, handle) = subparser.at(anyIn: DeclarationModifier.self),
modifierKind != .class,
subparser.hasProgressed(&modifierProgress)
{
hasModifier = true
subparser.eat(handle)
if modifierKind != .open && subparser.at(.leftParen) && modifierKind.canHaveParenthesizedArgument {
// When determining whether we are at a declaration, don't consume anything in parentheses after 'open'
// so we don't consider a function call to open as a decl modifier. This matches the C++ parser.
subparser.consumeAnyToken()
subparser.consume(to: .rightParen)
}
}
}
if hasAttribute {
if subparser.at(.rightBrace) || subparser.at(.endOfFile) || subparser.at(.poundEndif) {
return true
}
}
if subparser.at(.poundIf) {
var attrLookahead = subparser.lookahead()
return attrLookahead.consumeIfConfigOfAttributes()
}
let declStartKeyword: DeclarationKeyword?
if allowRecovery {
declStartKeyword =
subparser.canRecoverTo(
anyIn: DeclarationKeyword.self,
overrideRecoveryPrecedence: isAtTopLevel ? nil : .closingBrace
)?.0
} else {
declStartKeyword = subparser.at(anyIn: DeclarationKeyword.self)?.0
}
switch declStartKeyword {
case .lhs(.actor):
// actor Foo {}
if subparser.peek().rawTokenKind == .identifier {
return true
}
// actor may be somewhere in the modifier list. Eat the tokens until we get
// to something that isn't the start of a decl. If that is an identifier,
// it's an actor declaration, otherwise, it isn't.
var lookahead = subparser.lookahead()
repeat {
lookahead.consumeAnyToken()
} while lookahead.atStartOfDeclaration(isAtTopLevel: isAtTopLevel, allowInitDecl: allowInitDecl)
return lookahead.at(.identifier)
case .lhs(.case):
// When 'case' appears inside a function, it's probably a switch
// case, not an enum case declaration.
return false
case .lhs(.`init`):
return allowInitDecl
case .lhs(.macro):
// macro Foo ...
return subparser.peek().rawTokenKind == .identifier
case .lhs(.pound):
// Force parsing '#<identifier>' after attributes as a macro expansion decl.
if hasAttribute || hasModifier {
return true
}
// Otherwise, parse it as an expression.
return false
case .some(_):
// All other decl start keywords unconditionally start a decl.
return true
case nil:
if subparser.at(anyIn: ContextualDeclKeyword.self)?.0 != nil {
subparser.consumeAnyToken()
return subparser.atStartOfDeclaration(
isAtTopLevel: isAtTopLevel,
allowInitDecl: allowInitDecl,
allowRecovery: allowRecovery
)
}
return false
}
}
}
extension Parser {
struct DeclAttributes {
var attributes: RawAttributeListSyntax
var modifiers: RawDeclModifierListSyntax
}
/// Parse a declaration.
///
/// If `inMemberDeclList` is `true`, we know that the next item must be a
/// declaration and thus start with a keyword. This allows further recovery.
mutating func parseDeclaration(inMemberDeclList: Bool = false) -> RawDeclSyntax {
// If we are at a `#if` of attributes, the `#if` directive should be
// parsed when we're parsing the attributes.
if self.at(.poundIf) && !self.withLookahead({ $0.consumeIfConfigOfAttributes() }) {
let directive = self.parsePoundIfDirective { (parser, _) in
let parsedDecl = parser.parseDeclaration()
let semicolon = parser.consume(if: .semicolon)
return RawMemberBlockItemSyntax(
decl: parsedDecl,
semicolon: semicolon,
arena: parser.arena
)
} addSemicolonIfNeeded: { lastElement, newItemAtStartOfLine, parser in
if lastElement.semicolon == nil && !newItemAtStartOfLine {
return RawMemberBlockItemSyntax(
lastElement.unexpectedBeforeDecl,
decl: lastElement.decl,
lastElement.unexpectedBetweenDeclAndSemicolon,
semicolon: parser.missingToken(.semicolon),
lastElement.unexpectedAfterSemicolon,
arena: parser.arena
)
} else {
return nil
}
} syntax: { parser, elements in
return .decls(RawMemberBlockItemListSyntax(elements: elements, arena: parser.arena))
}
return RawDeclSyntax(directive)
}
let attrs = DeclAttributes(
attributes: self.parseAttributeList(),
modifiers: self.parseDeclModifierList()
)
let recoveryResult: (match: DeclarationKeyword, handle: RecoveryConsumptionHandle)?
if let atResult = self.at(anyIn: DeclarationKeyword.self) {
// We are at a keyword that starts a declaration. Parse that declaration.
recoveryResult = (atResult.spec, .noRecovery(atResult.handle))
} else if atFunctionDeclarationWithoutFuncKeyword() {
// We aren't at a declaration keyword and it looks like we are at a function
// declaration. Parse a function declaration.
recoveryResult = (.lhs(.func), .missing(.keyword(.func)))
} else {
// In all other cases, use standard token recovery to find the declaration
// to parse.
// If we are inside a memberDecl list, we don't want to eat closing braces (which most likely close the outer context)
// while recovering to the declaration start.
let recoveryPrecedence = inMemberDeclList ? TokenPrecedence.closingBrace : nil
recoveryResult = self.canRecoverTo(anyIn: DeclarationKeyword.self, overrideRecoveryPrecedence: recoveryPrecedence)
}
switch recoveryResult {
case (.lhs(.import), let handle)?:
return RawDeclSyntax(self.parseImportDeclaration(attrs, handle))
case (.lhs(.class), let handle)?:
return RawDeclSyntax(
self.parseNominalTypeDeclaration(for: RawClassDeclSyntax.self, attrs: attrs, introucerHandle: handle)
)
case (.lhs(.enum), let handle)?:
return RawDeclSyntax(
self.parseNominalTypeDeclaration(for: RawEnumDeclSyntax.self, attrs: attrs, introucerHandle: handle)
)
case (.lhs(.case), let handle)?:
return RawDeclSyntax(self.parseEnumCaseDeclaration(attrs, handle))
case (.lhs(.struct), let handle)?:
return RawDeclSyntax(
self.parseNominalTypeDeclaration(for: RawStructDeclSyntax.self, attrs: attrs, introucerHandle: handle)
)
case (.lhs(.protocol), let handle)?:
return RawDeclSyntax(
self.parseNominalTypeDeclaration(for: RawProtocolDeclSyntax.self, attrs: attrs, introucerHandle: handle)
)
case (.lhs(.associatedtype), let handle)?:
return RawDeclSyntax(self.parseAssociatedTypeDeclaration(attrs, handle))
case (.lhs(.typealias), let handle)?:
return RawDeclSyntax(self.parseTypealiasDeclaration(attrs, handle))
case (.lhs(.extension), let handle)?:
return RawDeclSyntax(self.parseExtensionDeclaration(attrs, handle))
case (.lhs(.func), let handle)?:
return RawDeclSyntax(self.parseFuncDeclaration(attrs, handle))
case (.lhs(.subscript), let handle)?:
return RawDeclSyntax(self.parseSubscriptDeclaration(attrs, handle))
case (.lhs(.`init`), let handle)?:
return RawDeclSyntax(self.parseInitializerDeclaration(attrs, handle))
case (.lhs(.deinit), let handle)?:
return RawDeclSyntax(self.parseDeinitializerDeclaration(attrs, handle))
case (.lhs(.operator), let handle)?:
return RawDeclSyntax(self.parseOperatorDeclaration(attrs, handle))
case (.lhs(.precedencegroup), let handle)?:
return RawDeclSyntax(self.parsePrecedenceGroupDeclaration(attrs, handle))
case (.lhs(.actor), let handle)?:
return RawDeclSyntax(
self.parseNominalTypeDeclaration(for: RawActorDeclSyntax.self, attrs: attrs, introucerHandle: handle)
)
case (.lhs(.macro), let handle)?:
return RawDeclSyntax(self.parseMacroDeclaration(attrs: attrs, introducerHandle: handle))
case (.lhs(.pound), let handle)?:
return RawDeclSyntax(self.parseMacroExpansionDeclaration(attrs, handle))
case (.rhs, let handle)?:
return RawDeclSyntax(self.parseBindingDeclaration(attrs, handle, inMemberDeclList: inMemberDeclList))
case nil:
break
}
if inMemberDeclList {
let isProbablyVarDecl = self.at(.identifier, .wildcard) && self.peek(isAt: .colon, .equal, .comma)
let isProbablyTupleDecl = self.at(.leftParen) && self.peek(isAt: .identifier, .wildcard)
if isProbablyVarDecl || isProbablyTupleDecl {
return RawDeclSyntax(self.parseBindingDeclaration(attrs, .missing(.keyword(.var))))
}
if self.currentToken.isEditorPlaceholder {
let placeholder = self.parseAnyIdentifier()
return RawDeclSyntax(
RawMissingDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
placeholder: placeholder,
arena: self.arena
)
)
}
if atFunctionDeclarationWithoutFuncKeyword() {
return RawDeclSyntax(self.parseFuncDeclaration(attrs, .missing(.keyword(.func))))
}
}
return RawDeclSyntax(
RawMissingDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
arena: self.arena
)
)
}
/// Returns `true` if it looks like the parser is positioned at a function declaration that’s missing the `func` keyword.
fileprivate mutating func atFunctionDeclarationWithoutFuncKeyword() -> Bool {
var nextTokenIsLeftParenOrLeftAngle: Bool {
self.peek(isAt: .leftParen) || self.peek().tokenText.hasPrefix("<")
}
if self.at(.identifier) {
return nextTokenIsLeftParenOrLeftAngle
} else if self.at(anyIn: Operator.self) != nil {
if self.currentToken.tokenText.hasSuffix("<") && self.peek(isAt: .identifier) {
return true
}
return nextTokenIsLeftParenOrLeftAngle
} else {
return false
}
}
}
extension Parser {
/// Parse an import declaration.
mutating func parseImportDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawImportDeclSyntax {
let (unexpectedBeforeImportKeyword, importKeyword) = self.eat(handle)
let kind = self.parseImportKind()
let path = self.parseImportPath()
return RawImportDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeImportKeyword,
importKeyword: importKeyword,
importKindSpecifier: kind,
path: path,
arena: self.arena
)
}
mutating func parseImportKind() -> RawTokenSyntax? {
return self.consume(ifAnyIn: ImportDeclSyntax.ImportKindSpecifierOptions.self)
}
mutating func parseImportPath() -> RawImportPathComponentListSyntax {
var elements = [RawImportPathComponentSyntax]()
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let name = self.parseAnyIdentifier()
keepGoing = self.consume(if: .period)
elements.append(
RawImportPathComponentSyntax(
name: name,
trailingPeriod: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && self.hasProgressed(&loopProgress)
return RawImportPathComponentListSyntax(elements: elements, arena: self.arena)
}
}
extension Parser {
/// Parse an extension declaration.
mutating func parseExtensionDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawExtensionDeclSyntax {
let (unexpectedBeforeExtensionKeyword, extensionKeyword) = self.eat(handle)
let type = self.parseType()
let inheritance: RawInheritanceClauseSyntax?
if self.at(.colon) {
inheritance = self.parseInheritance()
} else {
inheritance = nil
}
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.keyword(.where)) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
let memberBlock = self.parseMemberBlock(introducer: extensionKeyword)
return RawExtensionDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeExtensionKeyword,
extensionKeyword: extensionKeyword,
extendedType: type,
inheritanceClause: inheritance,
genericWhereClause: whereClause,
memberBlock: memberBlock,
arena: self.arena
)
}
}
extension Parser {
mutating func parseGenericParameters() -> RawGenericParameterClauseSyntax {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawGenericParameterClauseSyntax(
remainingTokens,
leftAngle: missingToken(.leftAngle),
parameters: RawGenericParameterListSyntax(elements: [], arena: self.arena),
genericWhereClause: nil,
rightAngle: missingToken(.rightAngle),
arena: self.arena
)
}
let langle = self.expectWithoutRecovery(prefix: "<", as: .leftAngle)
var elements = [RawGenericParameterSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let attributes = self.parseAttributeList()
// Parse the 'each' keyword for a type parameter pack 'each T' or a
// 'let' keyword for a value parameter 'let N: Int'.
var specifier = self.consume(if: .keyword(.each), .keyword(.let))
let (unexpectedBetweenSpecifierAndName, name) = self.expectIdentifier(allowSelfOrCapitalSelfAsIdentifier: true)
if attributes.isEmpty && specifier == nil && unexpectedBetweenSpecifierAndName == nil && name.isMissing
&& elements.isEmpty && !self.at(prefix: ">")
{
break
}
// Parse the unsupported ellipsis for a type parameter pack 'T...'.
let unexpectedBetweenNameAndColon: RawUnexpectedNodesSyntax?
if let ellipsis = self.consume(ifPrefix: "...", as: .ellipsis) {
unexpectedBetweenNameAndColon = RawUnexpectedNodesSyntax([ellipsis], arena: self.arena)
if specifier == nil {
specifier = missingToken(.each)
}
} else {
unexpectedBetweenNameAndColon = nil
}
// Parse the ':' followed by a type.
let colon = self.consume(if: .colon)
let unexpectedBeforeInherited: RawUnexpectedNodesSyntax?
let inherited: RawTypeSyntax?
if colon != nil {
if self.at(.identifier, .keyword(.protocol), .keyword(.Any)) || self.atContextualPunctuator("~") {
unexpectedBeforeInherited = nil
inherited = self.parseType()
} else if let classKeyword = self.consume(if: .keyword(.class)) {
unexpectedBeforeInherited = RawUnexpectedNodesSyntax([classKeyword], arena: self.arena)
inherited = RawTypeSyntax(
RawIdentifierTypeSyntax(
name: missingToken(.identifier, text: "AnyObject"),
genericArgumentClause: nil,
arena: self.arena
)
)
} else {
unexpectedBeforeInherited = nil
inherited = RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena))
}
} else {
unexpectedBeforeInherited = nil
inherited = nil
}
keepGoing = self.consume(if: .comma)
elements.append(
RawGenericParameterSyntax(
attributes: attributes,
specifier: specifier,
unexpectedBetweenSpecifierAndName,
name: name,
unexpectedBetweenNameAndColon,
colon: colon,
unexpectedBeforeInherited,
inheritedType: inherited,
trailingComma: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && !atGenericParametersListTerminator() && self.hasProgressed(&loopProgress)
}
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.keyword(.where)) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
let rangle = expectWithoutRecovery(prefix: ">", as: .rightAngle)
let parameters: RawGenericParameterListSyntax
if elements.isEmpty && rangle.isMissing {
parameters = RawGenericParameterListSyntax(elements: [], arena: self.arena)
} else {
parameters = RawGenericParameterListSyntax(elements: elements, arena: self.arena)
}
return RawGenericParameterClauseSyntax(
leftAngle: langle,
parameters: parameters,
genericWhereClause: whereClause,
rightAngle: rangle,
arena: self.arena
)
}
mutating func atGenericParametersListTerminator() -> Bool {
return self.at(prefix: ">")
}
mutating func parseGenericWhereClause() -> RawGenericWhereClauseSyntax {
let (unexpectedBeforeWhereKeyword, whereKeyword) = self.expect(.keyword(.where))
var elements = [RawGenericRequirementSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let firstType = self.parseType()
guard !firstType.is(RawMissingTypeSyntax.self) else {
keepGoing = self.consume(if: .comma)
elements.append(
RawGenericRequirementSyntax(
requirement: .sameTypeRequirement(
RawSameTypeRequirementSyntax(
leftType: RawMissingTypeSyntax(arena: self.arena),
equal: missingToken(.binaryOperator, text: "=="),
rightType: RawMissingTypeSyntax(arena: self.arena),
arena: self.arena
)
),
trailingComma: keepGoing,
arena: self.arena
)
)
continue
}
enum ExpectedTokenKind: TokenSpecSet {
case colon
case binaryOperator
case postfixOperator
case prefixOperator
init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) {
switch (lexeme.rawTokenKind, lexeme.tokenText) {
case (.colon, _): self = .colon
case (.binaryOperator, "=="): self = .binaryOperator
case (.postfixOperator, "=="): self = .postfixOperator
case (.prefixOperator, "=="): self = .prefixOperator
default: return nil
}
}
var spec: TokenSpec {
switch self {
case .colon: return .colon
case .binaryOperator: return .binaryOperator
case .postfixOperator: return .postfixOperator
case .prefixOperator: return .prefixOperator
}
}
}
let requirement: RawGenericRequirementSyntax.Requirement
switch self.at(anyIn: ExpectedTokenKind.self) {
case (.colon, let handle)?:
let colon = self.eat(handle)
// A conformance-requirement.
if let (layoutSpecifier, handle) = self.at(anyIn: LayoutRequirementSyntax.LayoutSpecifierOptions.self) {
// Parse a layout constraint.
let specifier = self.eat(handle)
let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax?
let leftParen: RawTokenSyntax?
let size: RawTokenSyntax?
let comma: RawTokenSyntax?
let alignment: RawTokenSyntax?
let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax?
let rightParen: RawTokenSyntax?
var hasArguments: Bool {
switch layoutSpecifier {
case ._Trivial,
._TrivialAtMost,
._TrivialStride:
return true
case ._UnknownLayout,
._RefCountedObject,
._NativeRefCountedObject,
._Class,
._NativeClass,
._BridgeObject:
return false
}
}
// Unlike the other layout constraints, _Trivial's argument list
// is optional.
if hasArguments && (layoutSpecifier != ._Trivial || self.at(.leftParen)) {
(unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen)
size = self.expectWithoutRecovery(.integerLiteral)
comma = self.consume(if: .comma)
if comma != nil {
alignment = self.expectWithoutRecovery(.integerLiteral)
} else {
alignment = nil
}
(unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
} else {
unexpectedBeforeLeftParen = nil
leftParen = nil
size = nil
comma = nil
alignment = nil
unexpectedBeforeRightParen = nil
rightParen = nil
}
requirement = .layoutRequirement(
RawLayoutRequirementSyntax(
type: firstType,
colon: colon,
layoutSpecifier: specifier,
unexpectedBeforeLeftParen,
leftParen: leftParen,
size: size,
comma: comma,
alignment: alignment,
unexpectedBeforeRightParen,
rightParen: rightParen,
arena: self.arena
)
)
} else {
// Parse the protocol or composition.
let secondType = self.parseType()
requirement = .conformanceRequirement(
RawConformanceRequirementSyntax(
leftType: firstType,
colon: colon,
rightType: secondType,
arena: self.arena
)
)
}
case (.binaryOperator, let handle)?,
(.postfixOperator, let handle)?,
(.prefixOperator, let handle)?:
let equal = self.eat(handle)
let secondType = self.parseType()
requirement = .sameTypeRequirement(
RawSameTypeRequirementSyntax(
leftType: firstType,
equal: equal,
rightType: secondType,
arena: self.arena
)
)
case nil:
requirement = .sameTypeRequirement(
RawSameTypeRequirementSyntax(
leftType: firstType,
equal: RawTokenSyntax(missing: .binaryOperator, text: "==", arena: self.arena),
rightType: RawMissingTypeSyntax(arena: self.arena),
arena: self.arena
)
)
}
keepGoing = self.consume(if: .comma)
let unexpectedBetweenBodyAndTrailingComma: RawUnexpectedNodesSyntax?
// If there's a comma, keep parsing the list.
// If there's a "&&", diagnose replace with a comma and keep parsing
if let token = self.consumeIfContextualPunctuator("&&") {
keepGoing = self.missingToken(.comma)
unexpectedBetweenBodyAndTrailingComma = RawUnexpectedNodesSyntax([token], arena: self.arena)
} else {
unexpectedBetweenBodyAndTrailingComma = nil
}
elements.append(
RawGenericRequirementSyntax(
requirement: requirement,
unexpectedBetweenBodyAndTrailingComma,
trailingComma: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && !self.atWhereClauseListTerminator() && self.hasProgressed(&loopProgress)
}
return RawGenericWhereClauseSyntax(
unexpectedBeforeWhereKeyword,
whereKeyword: whereKeyword,
requirements: RawGenericRequirementListSyntax(elements: elements, arena: self.arena),
arena: self.arena
)
}
mutating func atWhereClauseListTerminator() -> Bool {
return self.at(.leftBrace)
}
}
extension Parser {
mutating func parseMemberBlockItem() -> RawMemberBlockItemSyntax? {
let startToken = self.currentToken
if let syntax = self.loadCurrentSyntaxNodeFromCache(for: .memberBlockItem) {
self.registerNodeForIncrementalParse(node: syntax.raw, startToken: startToken)
return RawMemberBlockItemSyntax(syntax.raw)
}
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
let item = RawMemberBlockItemSyntax(
remainingTokens,
decl: RawMissingDeclSyntax(
attributes: self.emptyCollection(RawAttributeListSyntax.self),
modifiers: self.emptyCollection(RawDeclModifierListSyntax.self),
arena: self.arena
),
semicolon: nil,
arena: self.arena
)
return item
}
let decl: RawDeclSyntax
if self.at(.poundSourceLocation) {
decl = RawDeclSyntax(self.parsePoundSourceLocationDirective())
} else {
decl = self.parseDeclaration(inMemberDeclList: true)
}
let semi = self.consume(if: .semicolon)
var trailingSemis: [RawTokenSyntax] = []
while let trailingSemi = self.consume(if: .semicolon) {
trailingSemis.append(trailingSemi)
}
if decl.isEmpty && semi == nil && trailingSemis.isEmpty {
return nil
}
let result = RawMemberBlockItemSyntax(
decl: decl,
semicolon: semi,
RawUnexpectedNodesSyntax(trailingSemis, arena: self.arena),
arena: self.arena
)
self.registerNodeForIncrementalParse(node: result.raw, startToken: startToken)
return result
}
mutating func parseMemberDeclList() -> RawMemberBlockItemListSyntax {
var elements = [RawMemberBlockItemSyntax]()
do {
var loopProgress = LoopProgressCondition()
while !self.at(.endOfFile, .rightBrace) && self.hasProgressed(&loopProgress) {
let newItemAtStartOfLine = self.atStartOfLine
guard let newElement = self.parseMemberBlockItem() else {
break
}
if let lastItem = elements.last, lastItem.semicolon == nil && !newItemAtStartOfLine {
elements[elements.count - 1] = RawMemberBlockItemSyntax(
lastItem.unexpectedBeforeDecl,
decl: lastItem.decl,
lastItem.unexpectedBetweenDeclAndSemicolon,
semicolon: self.missingToken(.semicolon),
lastItem.unexpectedAfterSemicolon,
arena: self.arena
)
}
elements.append(newElement)
}
}
return RawMemberBlockItemListSyntax(elements: elements, arena: self.arena)
}
/// `introducer` is the `struct`, `class`, ... keyword that is the cause that the member decl block is being parsed.
/// If the left brace is missing, its indentation will be used to judge whether a following `}` was
/// indented to close this code block or a surrounding context. See `expectRightBrace`.
mutating func parseMemberBlock(introducer: RawTokenSyntax? = nil) -> RawMemberBlockSyntax {
let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)
let members = parseMemberDeclList()
let (unexpectedBeforeRBrace, rbrace) = self.expectRightBrace(leftBrace: lbrace, introducer: introducer)
return RawMemberBlockSyntax(
unexpectedBeforeLBrace,
leftBrace: lbrace,
members: members,
unexpectedBeforeRBrace,
rightBrace: rbrace,
arena: self.arena
)
}
}
extension Parser {
/// Parse an enum 'case' declaration.
mutating func parseEnumCaseDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawEnumCaseDeclSyntax {
let (unexpectedBeforeCaseKeyword, caseKeyword) = self.eat(handle)
var elements = [RawEnumCaseElementSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let unexpectedPeriod = self.consume(if: .period)
let (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)
let unexpectedGenericParameters: RawUnexpectedNodesSyntax?
if self.at(prefix: "<") {
let genericParameters = self.parseGenericParameters()
unexpectedGenericParameters = RawUnexpectedNodesSyntax([genericParameters], arena: self.arena)
} else {
unexpectedGenericParameters = nil
}
let parameterClause: RawEnumCaseParameterClauseSyntax?
if self.at(TokenSpec(.leftParen)) {
parameterClause = self.parseParameterClause(RawEnumCaseParameterClauseSyntax.self) { parser in
parser.parseEnumCaseParameter()
}
} else {
parameterClause = nil
}
// See if there's a raw value expression.
let rawValue: RawInitializerClauseSyntax?
if let eq = self.consume(if: .equal) {
let value = self.parseExpression(flavor: .basic, pattern: .none)
rawValue = RawInitializerClauseSyntax(
equal: eq,
value: value,
arena: self.arena
)
} else {
rawValue = nil
}
// Continue through the comma-separated list.
keepGoing = self.consume(if: .comma)
elements.append(
RawEnumCaseElementSyntax(
RawUnexpectedNodesSyntax(combining: unexpectedPeriod, unexpectedBeforeName, arena: self.arena),
name: name,
unexpectedGenericParameters,
parameterClause: parameterClause,
rawValue: rawValue,
trailingComma: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && self.hasProgressed(&loopProgress)
}
return RawEnumCaseDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeCaseKeyword,
caseKeyword: caseKeyword,
elements: RawEnumCaseElementListSyntax(elements: elements, arena: self.arena),
arena: self.arena
)
}
/// Parse an associated type declaration.
mutating func parseAssociatedTypeDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawAssociatedTypeDeclSyntax {
let (unexpectedBeforeAssocKeyword, assocKeyword) = self.eat(handle)
// Detect an attempt to use a type parameter pack.
let eachKeyword = self.consume(if: .keyword(.each))
var (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)
if eachKeyword != nil {
unexpectedBeforeName = RawUnexpectedNodesSyntax(combining: eachKeyword, unexpectedBeforeName, arena: self.arena)
}
if unexpectedBeforeName == nil && name.isMissing {
return RawAssociatedTypeDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeAssocKeyword,
associatedtypeKeyword: assocKeyword,
unexpectedBeforeName,
name: name,
inheritanceClause: nil,
initializer: nil,
genericWhereClause: nil,
arena: self.arena
)
}
// Detect an attempt to use (early syntax) type parameter pack.
let ellipsis = self.consume(ifPrefix: "...", as: .ellipsis)
// Parse optional inheritance clause.
let inheritance: RawInheritanceClauseSyntax?
if self.at(.colon) {
inheritance = self.parseInheritance()
} else {
inheritance = nil
}
// Parse default type, if any.
let defaultType: RawTypeInitializerClauseSyntax?
if let equal = self.consume(if: .equal) {
let type = self.parseType()
defaultType = RawTypeInitializerClauseSyntax(
equal: equal,
value: type,
arena: self.arena
)
} else {
defaultType = nil
}
// Parse a 'where' clause if present.
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.keyword(.where)) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
return RawAssociatedTypeDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeAssocKeyword,
associatedtypeKeyword: assocKeyword,
unexpectedBeforeName,
name: name,
RawUnexpectedNodesSyntax([ellipsis], arena: self.arena),
inheritanceClause: inheritance,
initializer: defaultType,
genericWhereClause: whereClause,
arena: self.arena
)
}
}
extension Parser {
/// Parse an initializer declaration.
mutating func parseInitializerDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawInitializerDeclSyntax {
let (unexpectedBeforeInitKeyword, initKeyword) = self.eat(handle)
// Parse the '!' or '?' for a failable initializer.
let failable: RawTokenSyntax?
if let parsedFailable = self.consume(
if: .exclamationMark,
.postfixQuestionMark,
TokenSpec(.infixQuestionMark, remapping: .postfixQuestionMark)
) {
failable = parsedFailable
} else if let parsedFailable = self.consumeIfContextualPunctuator("!", remapping: .exclamationMark) {
failable = parsedFailable
} else {
failable = nil
}
let generics: RawGenericParameterClauseSyntax?
if self.at(prefix: "<") {
generics = self.parseGenericParameters()
} else {
generics = nil
}
// Parse the signature.
let signature = self.parseFunctionSignature()
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.keyword(.where)) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}