forked from swiftlang/swift-syntax
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeclarations.swift
More file actions
2173 lines (2005 loc) · 77.9 KB
/
Declarations.swift
File metadata and controls
2173 lines (2005 loc) · 77.9 KB
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
//
//===----------------------------------------------------------------------===//
@_spi(RawSyntax) import SwiftSyntax
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, .nonisolated,
.nonmutating, .optional, .override, .postfix, .prefix, .reasync,
.required, .rethrows, .static, .weak:
return false
case .fileprivate, .internal, .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(.poundIfKeyword) {
return true
}
var subparser = self.lookahead()
var hasAttribute = false
var attributeProgress = LoopProgressCondition()
while attributeProgress.evaluate(subparser.currentToken) && 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,
modifierProgress.evaluate(subparser.currentToken)
{
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(.eof) || subparser.at(.poundEndifKeyword) {
return true
}
}
if subparser.at(.poundIfKeyword) {
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 .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 .case:
// When 'case' appears inside a function, it's probably a switch
// case, not an enum case declaration.
return false
case .`init`:
return allowInitDecl
case .macro:
// macro Foo ...
return subparser.peek().rawTokenKind == .identifier
case .pound:
// Force parsing '#<identifier>' after attributes as a macro expansion decl.
if hasAttribute || hasModifier {
return true
}
// Otherwise, parse it as a expression.
// FIXME: C++ parser returns true if this is a top-level non-"script" files.
// But we don't have "is library" flag.
return false
case .some(_):
// All other decl start keywords unconditonally 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: RawModifierListSyntax?
init(attributes: RawAttributeListSyntax?, modifiers: RawModifierListSyntax?) {
self.attributes = attributes
self.modifiers = modifiers
}
}
/// Parse a declaration.
///
/// Grammar
/// =======
///
/// declaration → import-declaration
/// declaration → constant-declaration
/// declaration → variable-declaration
/// declaration → typealias-declaration
/// declaration → function-declaration
/// declaration → enum-declaration
/// declaration → struct-declaration
/// declaration → class-declaration
/// declaration → actor-declaration
/// declaration → protocol-declaration
/// declaration → initializer-declaration
/// declaration → deinitializer-declaration
/// declaration → extension-declaration
/// declaration → subscript-declaration
/// declaration → operator-declaration
/// declaration → precedence-group-declaration
/// declaration → macro-declaration
///
/// declarations → declaration declarations?
///
/// If `inMemberDeclList` is `true`, we know that the next item must be a
/// declaration and thus start with a keyword. This allows futher 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(.poundIfKeyword) && !self.withLookahead({ $0.consumeIfConfigOfAttributes() }) {
let directive = self.parsePoundIfDirective { (parser, _) in
let parsedDecl = parser.parseDeclaration()
let semicolon = parser.consume(if: .semicolon)
return RawMemberDeclListItemSyntax(
decl: parsedDecl,
semicolon: semicolon,
arena: parser.arena
)
} addSemicolonIfNeeded: { lastElement, newItemAtStartOfLine, parser in
if lastElement.semicolon == nil && !newItemAtStartOfLine {
return RawMemberDeclListItemSyntax(
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(RawMemberDeclListSyntax(elements: elements, arena: parser.arena))
}
return RawDeclSyntax(directive)
}
let attrs = DeclAttributes(
attributes: self.parseAttributeList(),
modifiers: self.parseModifierList()
)
// If we are inside a memberDecl list, we don't want to eat closing braces (which most likely close the outer context)
// while recoverying to the declaration start.
let recoveryPrecedence = inMemberDeclList ? TokenPrecedence.closingBrace : nil
switch self.canRecoverTo(anyIn: DeclarationKeyword.self, overrideRecoveryPrecedence: recoveryPrecedence) {
case (.import, let handle)?:
return RawDeclSyntax(self.parseImportDeclaration(attrs, handle))
case (.class, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawClassDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.enum, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawEnumDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.case, let handle)?:
return RawDeclSyntax(self.parseEnumCaseDeclaration(attrs, handle))
case (.struct, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawStructDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.protocol, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawProtocolDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.associatedtype, let handle)?:
return RawDeclSyntax(self.parseAssociatedTypeDeclaration(attrs, handle))
case (.typealias, let handle)?:
return RawDeclSyntax(self.parseTypealiasDeclaration(attrs, handle))
case (.extension, let handle)?:
return RawDeclSyntax(self.parseExtensionDeclaration(attrs, handle))
case (.func, let handle)?:
return RawDeclSyntax(self.parseFuncDeclaration(attrs, handle))
case (.subscript, let handle)?:
return RawDeclSyntax(self.parseSubscriptDeclaration(attrs, handle))
case (.let, let handle)?, (.var, let handle)?,
(.inout, let handle)?:
return RawDeclSyntax(self.parseBindingDeclaration(attrs, handle, inMemberDeclList: inMemberDeclList))
case (.`init`, let handle)?:
return RawDeclSyntax(self.parseInitializerDeclaration(attrs, handle))
case (.deinit, let handle)?:
return RawDeclSyntax(self.parseDeinitializerDeclaration(attrs, handle))
case (.operator, let handle)?:
return RawDeclSyntax(self.parseOperatorDeclaration(attrs, handle))
case (.precedencegroup, let handle)?:
return RawDeclSyntax(self.parsePrecedenceGroupDeclaration(attrs, handle))
case (.actor, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawActorDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.macro, let handle)?:
return RawDeclSyntax(self.parseMacroDeclaration(attrs: attrs, introducerHandle: handle))
case (.pound, let handle)?:
return RawDeclSyntax(self.parseMacroExpansionDeclaration(attrs, handle))
case nil:
if inMemberDeclList {
let isProbablyVarDecl = self.at(.identifier, .wildcard) && self.peek().rawTokenKind.is(.colon, .equal, .comma)
let isProbablyTupleDecl = self.at(.leftParen) && self.peek().rawTokenKind.is(.identifier, .wildcard)
if isProbablyVarDecl || isProbablyTupleDecl {
return RawDeclSyntax(self.parseBindingDeclaration(attrs, .missing(.keyword(.var))))
}
if self.currentToken.isEditorPlaceholder {
let placeholder = self.consumeAnyToken()
return RawDeclSyntax(
RawEditorPlaceholderDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
placeholder: placeholder,
arena: self.arena
)
)
}
let isProbablyFuncDecl = self.at(.identifier, .wildcard) || self.at(anyIn: Operator.self) != nil
if isProbablyFuncDecl {
return RawDeclSyntax(self.parseFuncDeclaration(attrs, .missing(.keyword(.func))))
}
}
return RawDeclSyntax(
RawMissingDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
arena: self.arena
)
)
}
}
}
extension Parser {
/// Parse an import declaration.
///
/// Grammar
/// =======
///
/// import-declaration → attributes? 'import' import-kind? import-path
/// import-kind → 'typealias' | 'struct' | 'class' | 'enum' | 'protocol' | 'let' | 'var' | 'func'
/// import-path → identifier | identifier '.' import-path
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,
importTok: importKeyword,
importKind: kind,
path: path,
arena: self.arena
)
}
mutating func parseImportKind() -> RawTokenSyntax? {
enum ImportKind: TokenSpecSet {
case `typealias`
case `struct`
case `class`
case `enum`
case `protocol`
case `var`
case `let`
case `func`
case `inout`
var spec: TokenSpec {
switch self {
case .typealias: return .keyword(.typealias)
case .struct: return .keyword(.struct)
case .class: return .keyword(.class)
case .enum: return .keyword(.enum)
case .protocol: return .keyword(.protocol)
case .var: return .keyword(.var)
case .let: return .keyword(.let)
case .func: return .keyword(.func)
case .inout: return .keyword(.inout)
}
}
init?(lexeme: Lexer.Lexeme) {
switch PrepareForKeywordMatch(lexeme) {
case TokenSpec(.typealias): self = .typealias
case TokenSpec(.struct): self = .struct
case TokenSpec(.class): self = .class
case TokenSpec(.enum): self = .enum
case TokenSpec(.protocol): self = .protocol
case TokenSpec(.var): self = .var
case TokenSpec(.let): self = .let
case TokenSpec(.func): self = .func
case TokenSpec(.inout): self = .inout
default: return nil
}
}
}
return self.consume(ifAnyIn: ImportKind.self)
}
mutating func parseImportPath() -> RawImportPathSyntax {
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,
trailingDot: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && loopProgress.evaluate(currentToken)
return RawImportPathSyntax(elements: elements, arena: self.arena)
}
}
extension Parser {
/// Parse an extension declaration.
///
/// Grammar
/// =======
///
/// extension-declaration → attributes? access-level-modifier? 'extension' type-identifier type-inheritance-clause? generic-where-clause?t extension-body
/// extension-body → '{' extension-members? '}'
/// extension-members → extension-member extension-members?
/// extension-member → declaration | compiler-control-statement
mutating func parseExtensionDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawExtensionDeclSyntax {
let (unexpectedBeforeExtensionKeyword, extensionKeyword) = self.eat(handle)
let type = self.parseType()
let inheritance: RawTypeInheritanceClauseSyntax?
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.parseMemberDeclList(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 {
/// Attempt to consume an ellipsis prefix, splitting the current token if
/// necessary.
mutating func tryConsumeEllipsisPrefix() -> RawTokenSyntax? {
// It is not sufficient to check currentToken.isEllipsis here, as we may
// have something like '...>'.
// TODO: Recovery for different numbers of dots (which also needs to be
// done for regular variadics).
guard self.at(anyIn: Operator.self) != nil else { return nil }
let text = self.currentToken.tokenText
guard text.hasPrefix("...") else { return nil }
return self.consumePrefix(
SyntaxText(rebasing: text.prefix(3)),
as: .ellipsis
)
}
mutating func parseGenericParameters() -> RawGenericParameterClauseSyntax {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawGenericParameterClauseSyntax(
remainingTokens,
leftAngleBracket: missingToken(.leftAngle),
genericParameterList: RawGenericParameterListSyntax(elements: [], arena: self.arena),
genericWhereClause: nil,
rightAngleBracket: missingToken(.rightAngle),
arena: self.arena
)
}
let langle: RawTokenSyntax
if self.currentToken.starts(with: "<") {
langle = self.consumePrefix("<", as: .leftAngle)
} else {
langle = missingToken(.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'.
var each = self.consume(if: .keyword(.each))
let (unexpectedBetweenEachAndName, name) = self.expectIdentifier(allowSelfOrCapitalSelfAsIdentifier: true)
if attributes == nil && each == nil && unexpectedBetweenEachAndName == nil && name.isMissing && elements.isEmpty && !self.currentToken.starts(with: ">")
{
break
}
// Parse the unsupported ellipsis for a type parameter pack 'T...'.
let unexpectedBetweenNameAndColon: RawUnexpectedNodesSyntax?
if let ellipsis = tryConsumeEllipsisPrefix() {
unexpectedBetweenNameAndColon = RawUnexpectedNodesSyntax([ellipsis], arena: self.arena)
if each == nil {
each = 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(
RawSimpleTypeIdentifierSyntax(
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,
each: each,
unexpectedBetweenEachAndName,
name: name,
unexpectedBetweenNameAndColon,
colon: colon,
unexpectedBeforeInherited,
inheritedType: inherited,
trailingComma: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.keyword(.where)) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
let rangle: RawTokenSyntax
if self.currentToken.starts(with: ">") {
rangle = self.consumePrefix(">", as: .rightAngle)
} else {
rangle = RawTokenSyntax(missing: .rightAngle, arena: self.arena)
}
let parameters: RawGenericParameterListSyntax
if elements.isEmpty && rangle.isMissing {
parameters = RawGenericParameterListSyntax(elements: [], arena: self.arena)
} else {
parameters = RawGenericParameterListSyntax(elements: elements, arena: self.arena)
}
return RawGenericParameterClauseSyntax(
leftAngleBracket: langle,
genericParameterList: parameters,
genericWhereClause: whereClause,
rightAngleBracket: rangle,
arena: self.arena
)
}
enum LayoutConstraint: TokenSpecSet {
case _Trivial
case _TrivialAtMost
case _UnknownLayout
case _RefCountedObjectLayout
case _NativeRefCountedObjectLayout
case _Class
case _NativeClass
init?(lexeme: Lexer.Lexeme) {
switch PrepareForKeywordMatch(lexeme) {
case TokenSpec(._Trivial): self = ._Trivial
case TokenSpec(._TrivialAtMost): self = ._TrivialAtMost
case TokenSpec(._UnknownLayout): self = ._UnknownLayout
case TokenSpec(._RefCountedObject): self = ._RefCountedObjectLayout
case TokenSpec(._NativeRefCountedObject): self = ._NativeRefCountedObjectLayout
case TokenSpec(._Class): self = ._Class
case TokenSpec(._NativeClass): self = ._NativeClass
default: return nil
}
}
var spec: TokenSpec {
switch self {
case ._Trivial: return .keyword(._Trivial)
case ._TrivialAtMost: return .keyword(._TrivialAtMost)
case ._UnknownLayout: return .keyword(._UnknownLayout)
case ._RefCountedObjectLayout: return .keyword(._RefCountedObject)
case ._NativeRefCountedObjectLayout: return .keyword(._NativeRefCountedObject)
case ._Class: return .keyword(._Class)
case ._NativeClass: return .keyword(._NativeClass)
}
}
var hasArguments: Bool {
switch self {
case ._Trivial,
._TrivialAtMost:
return true
case ._UnknownLayout,
._RefCountedObjectLayout,
._NativeRefCountedObjectLayout,
._Class,
._NativeClass:
return false
}
}
}
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(
body: .sameTypeRequirement(
RawSameTypeRequirementSyntax(
leftTypeIdentifier: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
equalityToken: missingToken(.binaryOperator, text: "=="),
rightTypeIdentifier: RawTypeSyntax(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) {
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.Body
switch self.at(anyIn: ExpectedTokenKind.self) {
case (.colon, let handle)?:
let colon = self.eat(handle)
// A conformance-requirement.
if let (layoutConstraint, handle) = self.at(anyIn: LayoutConstraint.self) {
// Parse a layout constraint.
let constraint = self.eat(handle)
let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax?
let leftParen: RawTokenSyntax?
let size: RawTokenSyntax?
let comma: RawTokenSyntax?
let alignment: RawTokenSyntax?
let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax?
let rightParen: RawTokenSyntax?
// Unlike the other layout constraints, _Trivial's argument list
// is optional.
if layoutConstraint.hasArguments && (layoutConstraint != ._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(
typeIdentifier: firstType,
colon: colon,
layoutConstraint: constraint,
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(
leftTypeIdentifier: firstType,
colon: colon,
rightTypeIdentifier: 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(
leftTypeIdentifier: firstType,
equalityToken: equal,
rightTypeIdentifier: secondType,
arena: self.arena
)
)
case nil:
requirement = .sameTypeRequirement(
RawSameTypeRequirementSyntax(
leftTypeIdentifier: firstType,
equalityToken: RawTokenSyntax(missing: .binaryOperator, text: "==", arena: self.arena),
rightTypeIdentifier: RawTypeSyntax(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(
body: requirement,
unexpectedBetweenBodyAndTrailingComma,
trailingComma: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
return RawGenericWhereClauseSyntax(
unexpectedBeforeWhereKeyword,
whereKeyword: whereKeyword,
requirementList: RawGenericRequirementListSyntax(elements: elements, arena: self.arena),
arena: self.arena
)
}
}
extension Parser {
mutating func parseMemberDeclListItem() -> RawMemberDeclListItemSyntax? {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
let item = RawMemberDeclListItemSyntax(
remainingTokens,
decl: RawDeclSyntax(RawMissingDeclSyntax(attributes: nil, modifiers: nil, arena: self.arena)),
semicolon: nil,
arena: self.arena
)
return item
}
let decl: RawDeclSyntax
if self.at(.poundSourceLocationKeyword) {
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
}
return RawMemberDeclListItemSyntax(
decl: decl,
semicolon: semi,
RawUnexpectedNodesSyntax(trailingSemis, arena: self.arena),
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 parseMemberDeclList(introducer: RawTokenSyntax? = nil) -> RawMemberDeclBlockSyntax {
var elements = [RawMemberDeclListItemSyntax]()
let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)
do {
var loopProgress = LoopProgressCondition()
while !self.at(.eof, .rightBrace) && loopProgress.evaluate(currentToken) {
let newItemAtStartOfLine = self.currentToken.isAtStartOfLine
guard let newElement = self.parseMemberDeclListItem() else {
break
}
if let lastItem = elements.last, lastItem.semicolon == nil && !newItemAtStartOfLine {
elements[elements.count - 1] = RawMemberDeclListItemSyntax(
lastItem.unexpectedBeforeDecl,
decl: lastItem.decl,
lastItem.unexpectedBetweenDeclAndSemicolon,
semicolon: self.missingToken(.semicolon),
lastItem.unexpectedAfterSemicolon,
arena: self.arena
)
}
elements.append(newElement)
}
}
let (unexpectedBeforeRBrace, rbrace) = self.expectRightBrace(leftBrace: lbrace, introducer: introducer)
let members: RawMemberDeclListSyntax
if elements.isEmpty && (lbrace.isMissing || rbrace.isMissing) {
members = RawMemberDeclListSyntax(elements: [], arena: self.arena)
} else {
members = RawMemberDeclListSyntax(elements: elements, arena: self.arena)
}
return RawMemberDeclBlockSyntax(
unexpectedBeforeLBrace,
leftBrace: lbrace,
members: members,
unexpectedBeforeRBrace,
rightBrace: rbrace,
arena: self.arena
)
}
}
extension Parser {
/// Parse an enum 'case' declaration.
///
/// Grammar
/// =======
///
/// union-style-enum-case-clause → attributes? 'indirect'? 'case' union-style-enum-case-list
/// union-style-enum-case-list → union-style-enum-case | union-style-enum-case ',' union-style-enum-case-list
/// union-style-enum-case → enum-case-name tuple-type?
///
/// raw-value-style-enum-case-clause → attributes? 'case' raw-value-style-enum-case-list
/// raw-value-style-enum-case-list → raw-value-style-enum-case | raw-value-style-enum-case ',' raw-value-style-enum-case-list
/// raw-value-style-enum-case → enum-case-name raw-value-assignment?
/// raw-value-assignment → = raw-value-literal
/// raw-value-literal → numeric-literal | static-string-literal | boolean-literal
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 associatedValue: RawEnumCaseParameterClauseSyntax?
if self.at(TokenSpec(.leftParen, allowAtStartOfLine: false)) {
associatedValue = self.parseParameterClause(RawEnumCaseParameterClauseSyntax.self) { parser in
parser.parseEnumCaseParameter()
}
} else {
associatedValue = nil
}
// See if there's a raw value expression.
let rawValue: RawInitializerClauseSyntax?
if let eq = self.consume(if: .equal) {
let value = self.parseExpression()
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),
identifier: name,
associatedValue: associatedValue,
rawValue: rawValue,
trailingComma: keepGoing,
arena: self.arena
)
)
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
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.
///
/// Grammar
/// =======
///
/// protocol-associated-type-declaration → attributes? access-level-modifier? 'associatedtype' typealias-name type-inheritance-clause? typealias-assignment? generic-where-clause?
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,
identifier: name,
inheritanceClause: nil,
initializer: nil,
genericWhereClause: nil,
arena: self.arena
)
}