-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathPatterns.swift
406 lines (374 loc) · 13.8 KB
/
Patterns.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
//===----------------------------------------------------------------------===//
//
// 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 compiler(>=6)
@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax
#else
@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax
#endif
extension Parser {
/// Parse a pattern.
mutating func parsePattern() -> RawPatternSyntax {
enum PatternOnlyExpectedTokens: TokenSpecSet {
case leftParen
case wildcard
case identifier
case dollarIdentifier // For recovery
init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) {
switch PrepareForKeywordMatch(lexeme) {
case TokenSpec(.leftParen): self = .leftParen
case TokenSpec(.wildcard): self = .wildcard
case TokenSpec(.identifier): self = .identifier
case TokenSpec(.dollarIdentifier): self = .dollarIdentifier
default: return nil
}
}
var spec: TokenSpec {
switch self {
case .leftParen: return .leftParen
case .wildcard: return .wildcard
case .identifier: return .identifier
case .dollarIdentifier: return .dollarIdentifier
}
}
}
typealias ExpectedTokens = EitherTokenSpecSet<
PatternOnlyExpectedTokens,
ValueBindingPatternSyntax.BindingSpecifierOptions
>
switch self.at(anyIn: ExpectedTokens.self) {
case (.lhs(.leftParen), let handle)?:
let lparen = self.eat(handle)
let elements = self.parsePatternTupleElements()
let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
return RawPatternSyntax(
RawTuplePatternSyntax(
leftParen: lparen,
elements: elements,
unexpectedBeforeRParen,
rightParen: rparen,
arena: self.arena
)
)
case (.lhs(.wildcard), let handle)?:
let wildcard = self.eat(handle)
return RawPatternSyntax(
RawWildcardPatternSyntax(
wildcard: wildcard,
arena: self.arena
)
)
case (.rhs(let introducer), let handle)?
where self.withLookahead { $0.shouldParsePatternBinding(introducer: introducer) }:
let bindingSpecifier = self.eat(handle)
let value = self.parsePattern()
return RawPatternSyntax(
RawValueBindingPatternSyntax(
bindingSpecifier: bindingSpecifier,
pattern: value,
arena: self.arena
)
)
case (.lhs(.identifier), let handle)?,
// If we shouldn't contextually parse a pattern binding introducer (because the previous pattern match guard failed), then parse it as an identifier.
(.rhs(_), let handle)?:
let identifier = self.eat(handle)
return RawPatternSyntax(
RawIdentifierPatternSyntax(
identifier: identifier,
arena: self.arena
)
)
case (.lhs(.dollarIdentifier), let handle)?:
let dollarIdent = self.eat(handle)
let unexpectedBeforeIdentifier = RawUnexpectedNodesSyntax([dollarIdent], arena: self.arena)
return RawPatternSyntax(
RawIdentifierPatternSyntax(
unexpectedBeforeIdentifier,
identifier: missingToken(.identifier),
arena: self.arena
)
)
case nil:
break
}
if self.currentToken.isLexerClassifiedKeyword, !self.atStartOfLine {
// Recover if a keyword was used instead of an identifier
let keyword = self.consumeAnyToken()
return RawPatternSyntax(
RawIdentifierPatternSyntax(
RawUnexpectedNodesSyntax([keyword], arena: self.arena),
identifier: missingToken(.identifier),
arena: self.arena
)
)
} else {
return RawPatternSyntax(RawMissingPatternSyntax(arena: self.arena))
}
}
/// Parse a typed pattern.
mutating func parseTypedPattern(
allowRecoveryFromMissingColon: Bool = true
) -> (RawPatternSyntax, RawTypeAnnotationSyntax?) {
let pattern = self.parsePattern()
// Now parse an optional type annotation.
let colon = self.consume(if: .colon)
var lookahead = self.lookahead()
var type: RawTypeAnnotationSyntax?
if let colon {
let result = self.parseResultType()
type = RawTypeAnnotationSyntax(
colon: colon,
type: result,
arena: self.arena
)
} else if allowRecoveryFromMissingColon
&& !self.atStartOfLine
&& lookahead.canParseType()
{
let (unexpectedBeforeColon, colon) = self.expect(.colon)
let result = self.parseType()
type = RawTypeAnnotationSyntax(
unexpectedBeforeColon,
colon: colon,
type: result,
arena: self.arena
)
}
return (pattern, type)
}
/// Parse the elements of a tuple pattern.
mutating func parsePatternTupleElements() -> RawTuplePatternElementListSyntax {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawTuplePatternElementListSyntax(
elements: [
RawTuplePatternElementSyntax(
remainingTokens,
label: nil,
colon: nil,
pattern: RawMissingPatternSyntax(arena: self.arena),
trailingComma: nil,
arena: self.arena
)
],
arena: self.arena
)
}
var elements = [RawTuplePatternElementSyntax]()
do {
var keepGoing = true
var loopProgress = LoopProgressCondition()
while !self.at(.endOfFile, .rightParen) && keepGoing && self.hasProgressed(&loopProgress) {
// If the tuple element has a label, parse it.
let labelAndColon = self.consume(if: .identifier, followedBy: .colon)
var (label, colon) = (labelAndColon?.0, labelAndColon?.1)
/// If we have something like `x SomeType`, use the indication that `SomeType` starts with a capital letter (and is thus probably a type name)
/// as an indication that the user forgot to write the colon instead of forgetting to write the comma to separate two elements.
if label == nil, colon == nil, self.at(.identifier), peek(isAt: .identifier),
peek().tokenText.isStartingWithUppercase
{
label = consume(if: .identifier)
colon = self.missingToken(.colon)
}
let pattern = self.parsePattern()
var trailingComma = self.consume(if: .comma)
if trailingComma == nil && self.at(TokenSpec(.identifier, allowAtStartOfLine: false)) {
trailingComma = self.missingToken(RawTokenKind.comma)
}
keepGoing = trailingComma != nil
elements.append(
RawTuplePatternElementSyntax(
label: label,
colon: colon,
pattern: pattern,
trailingComma: trailingComma,
arena: self.arena
)
)
}
}
return RawTuplePatternElementListSyntax(elements: elements, arena: self.arena)
}
}
extension Parser {
/// Parse a pattern that appears immediately under syntax for conditionals like
/// for-in loops and guard clauses.
mutating func parseMatchingPattern(context: PatternContext) -> RawPatternSyntax {
// Parse productions that can only be patterns.
switch self.at(anyIn: MatchingPatternStart.self) {
case (.lhs(.is), let handle)?:
let isKeyword = self.eat(handle)
let type = self.parseType()
return RawPatternSyntax(
RawIsTypePatternSyntax(
isKeyword: isKeyword,
type: type,
arena: self.arena
)
)
case (.rhs(let introducer), let handle)?
where self.withLookahead { $0.shouldParsePatternBinding(introducer: introducer) }:
let bindingSpecifier = self.eat(handle)
let value = self.parseMatchingPattern(context: .bindingIntroducer)
return RawPatternSyntax(
RawValueBindingPatternSyntax(
bindingSpecifier: bindingSpecifier,
pattern: value,
arena: self.arena
)
)
case (.rhs(_), _)?,
nil:
break
}
// Fall back to expression parsing for ambiguous forms. Name lookup will
// disambiguate.
let patternSyntax = self.parseSequenceExpression(flavor: .stmtCondition, pattern: context)
if let pat = patternSyntax.as(RawPatternExprSyntax.self) {
// The most common case here is to parse something that was a lexically
// obvious pattern, which will come back wrapped in an immediate
// RawUnresolvedPatternExprSyntax.
//
// FIXME: This is pretty gross. Let's find a way to disambiguate let
// binding patterns much earlier.
return RawPatternSyntax(pat.pattern)
}
return RawPatternSyntax(RawExpressionPatternSyntax(expression: patternSyntax, arena: self.arena))
}
}
// MARK: Lookahead
extension Parser.Lookahead {
/// Returns true if we should parse a pattern binding specifier contextually
/// as one.
mutating func shouldParsePatternBinding(introducer: ValueBindingPatternSyntax.BindingSpecifierOptions) -> Bool {
switch introducer {
// TODO: the other ownership modifiers (borrowing/consuming/mutating) more
// than likely need to be made contextual as well before finalizing their
// grammar.
case ._borrowing, .borrowing:
return peek(isAt: TokenSpec(.identifier, allowAtStartOfLine: false))
default:
// Other keywords can be parsed unconditionally.
return true
}
}
mutating func canParsePattern() -> Bool {
enum PurePatternStartTokens: TokenSpecSet {
case identifier
case wildcard
case leftParen
init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) {
switch PrepareForKeywordMatch(lexeme) {
case TokenSpec(.identifier): self = .identifier
case TokenSpec(.wildcard): self = .wildcard
case TokenSpec(.leftParen): self = .leftParen
default: return nil
}
}
var spec: TokenSpec {
switch self {
case .identifier: return .identifier
case .wildcard: return .wildcard
case .leftParen: return .leftParen
}
}
}
typealias PatternStartTokens = EitherTokenSpecSet<
PurePatternStartTokens,
ValueBindingPatternSyntax.BindingSpecifierOptions
>
switch self.at(anyIn: PatternStartTokens.self) {
case (.lhs(.leftParen), _)?:
return self.canParsePatternTuple()
case (.rhs(let introducer), let handle)? where shouldParsePatternBinding(introducer: introducer):
// Parse as a binding introducer, like `let x`.
self.eat(handle)
return self.canParsePattern()
case (.lhs(.identifier), let handle)?,
(.lhs(.wildcard), let handle)?,
// If a binding introducer is not contextually introducing a binding, then parse like an identifier.
(.rhs(_), let handle)?:
self.eat(handle)
return true
case nil:
return false
}
}
private mutating func canParsePatternTuple() -> Bool {
guard self.consume(if: .leftParen) != nil else {
return false
}
if !self.at(.rightParen) {
var loopProgress = LoopProgressCondition()
repeat {
guard self.canParsePattern() else {
return false
}
} while self.consume(if: .comma) != nil && self.hasProgressed(&loopProgress)
}
return self.consume(if: .rightParen) != nil
}
/// Determine whether we are at the start of a parameter name when
/// parsing a parameter.
/// If `allowMisplacedSpecifierRecovery` is `true`, then this will skip over any type
/// specifiers before checking whether this lookahead starts a parameter name.
mutating func startsParameterName(isClosure: Bool, allowMisplacedSpecifierRecovery: Bool) -> Bool {
if allowMisplacedSpecifierRecovery {
while canHaveParameterSpecifier,
self.consume(ifAnyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) != nil
{}
}
// To have a parameter name here, we need a name.
guard self.atArgumentLabel(allowDollarIdentifier: true) else {
return false
}
// If the next token is ':', this is a name.
let nextTok = self.peek()
if nextTok.rawTokenKind == .colon {
return true
}
// If the next token can be an argument label, we might have a name.
if nextTok.isArgumentLabel(allowDollarIdentifier: true) {
// If the first name wasn't a contextual keyword, we're done.
if !self.at(.keyword(.isolated))
&& !self.at(.keyword(.some))
&& !self.at(.keyword(.any))
&& !self.at(.keyword(.each))
&& !self.at(.keyword(.repeat))
&& !self.at(.keyword(.__shared))
&& !self.at(.keyword(.__owned))
&& !self.at(.keyword(._const))
&& !self.at(.keyword(.borrowing))
&& !self.at(.keyword(.consuming))
&& !self.at(.keyword(.sending))
{
return true
}
// Parameter specifiers can be an argument label, but it's also a contextual keyword,
// so look ahead one more token (two total) see if we have a ':' that would
// indicate that this is an argument label.
do {
if self.at(.colon) {
return true // isolated :
}
self.consumeAnyToken()
return self.atArgumentLabel(allowDollarIdentifier: true) && self.peek().rawTokenKind == .colon
}
}
if nextTok.rawTokenKind == .postfixQuestionMark || nextTok.rawTokenKind == .exclamationMark {
return false
}
// The identifier could be a name or it could be a type. In a closure, we
// assume it's a name, because the type can be inferred. Elsewhere, we
// assume it's a type.
return isClosure
}
}