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
|
//===----------------------------------------------------------------------===//
//
// 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
/// Describes how distinctive a token is for parser recovery.
///
/// When expecting a token, tokens with a lower token precedence may be skipped
/// and considered unexpected.
///
/// - Seealso: <doc:ParserRecovery>
enum TokenPrecedence: Comparable {
/// An unknown token. This is known garbage and should always be allowed to be skipped.
case unknownToken
/// Tokens that can be used similar to variable names or literals
case identifierLike
/// Keywords and operators that can occur in the middle of an expression
case exprKeyword
/// A token that starts a bracketed expression which typically occurs inside
/// a statement.
case weakBracketed(closingDelimiter: RawTokenKind)
/// A punctuator that can occur inside a statement
case weakPunctuator
/// A punctuator that is a fairly strong indicator of separating two distinct parts of a statement.
case mediumPunctuator
/// The closing delimiter of `weakBracketed`
case weakBracketClose
/// Keywords that start a new statement.
case stmtKeyword
/// The '{' token because it typically marks the body of a declaration.
/// `closingDelimiter` must have type `strongPunctuator`
case openingBrace(closingDelimiter: RawTokenKind)
/// A punctuator that is a strong indicator that it separates two distinct parts of the source code, like two statements
case strongPunctuator
/// The closing delimiter of `strongBracketed`
case closingBrace
/// Tokens that start a new declaration
case declKeyword
case openingPoundIf
case closingPoundIf
/// If the precedence is `weakBracketed` or `strongBracketed`, the closing delimiter of the bracketed group.
var closingTokenKind: RawTokenKind? {
switch self {
case .weakBracketed(closingDelimiter: let closingDelimiter):
return closingDelimiter
case .openingBrace(closingDelimiter: let closingDelimiter):
return closingDelimiter
case .openingPoundIf:
return .poundEndif
default:
return nil
}
}
static func < (lhs: TokenPrecedence, rhs: TokenPrecedence) -> Bool {
func precedence(_ precedence: TokenPrecedence) -> Int {
/// Should match the order of the cases in the enum.
switch precedence {
case .unknownToken:
return 0
case .identifierLike:
return 1
case .exprKeyword:
return 2
case .weakBracketed:
return 3
case .weakPunctuator:
return 4
case .mediumPunctuator:
return 5
case .weakBracketClose:
return 6
case .stmtKeyword:
return 7
case .strongPunctuator:
return 8
case .openingBrace:
return 9
case .closingBrace:
return 10
case .declKeyword:
return 11
case .openingPoundIf:
return 12
case .closingPoundIf:
return 13
}
}
return precedence(lhs) < precedence(rhs)
}
/// When expecting a token with `weakBracketClose` precedence or higher, newlines may be skipped to find that token.
/// For lower precedence groups, we consider newlines the end of the lookahead scope.
var shouldSkipOverNewlines: Bool {
return self >= .weakBracketClose
}
init(_ lexeme: Lexer.Lexeme) {
if lexeme.rawTokenKind == .keyword {
self.init(Keyword(lexeme.tokenText)!)
} else {
self.init(nonKeyword: lexeme.rawTokenKind)
}
}
init(nonKeyword tokenKind: RawTokenKind) {
switch tokenKind {
case .unknown:
self = .unknownToken
// MARK: Identifier like
case // Literals
.floatLiteral, .integerLiteral,
// Pound literals
.poundAvailable, .poundSourceLocation, .poundUnavailable,
// Identifiers
.dollarIdentifier, .identifier,
// '_' can occur in types to replace a type identifier
.wildcard,
// String segment, string interpolation anchor, pound, shebang and regex pattern don't really fit anywhere else
.pound, .stringSegment, .regexLiteralPattern, .shebang:
self = .identifierLike
// MARK: Expr keyword
case // Operators can occur inside expressions
.postfixOperator, .prefixOperator, .binaryOperator:
// Consider 'any' and 'inout' like a prefix operator to a type and a type is expression-like.
self = .exprKeyword
// MARK: Weak bracketed
case .leftParen:
self = .weakBracketed(closingDelimiter: .rightParen)
case .leftSquare:
self = .weakBracketed(closingDelimiter: .rightSquare)
case .leftAngle:
self = .weakBracketed(closingDelimiter: .rightAngle)
case .multilineStringQuote, .rawStringPoundDelimiter, .singleQuote, .stringQuote,
.regexSlash, .regexPoundDelimiter:
self = .weakBracketed(closingDelimiter: tokenKind)
case // Chaining punctuators
.infixQuestionMark, .period, .postfixQuestionMark, .exclamationMark,
// Misc
.backslash, .backtick, .ellipsis, .equal, .prefixAmpersand:
self = .weakPunctuator
case .atSign, .colon, .comma:
self = .mediumPunctuator
// MARK: Weak bracket close
case // Weak brackets
.rightAngle, .rightParen, .rightSquare:
self = .weakBracketClose
// MARK: Strong bracketed
case .leftBrace:
self = .openingBrace(closingDelimiter: .rightBrace)
case .poundElseif, .poundElse, .poundIf:
self = .openingPoundIf
// MARK: Strong punctuator
case // Semicolon separates two statements
.semicolon,
// Arrow is a strong indicator in a function type that we are now in the return type
.arrow,
// endOfFile is here because it is a very strong marker and doesn't belong anywhere else
.endOfFile:
self = .strongPunctuator
// MARK: Strong bracket close
case .rightBrace:
self = .closingBrace
case .poundEndif:
self = .closingPoundIf
case .keyword:
preconditionFailure("RawTokenKind passed to init(nonKeyword:) must not be a keyword")
}
}
init(_ keyword: Keyword) {
switch keyword {
// MARK: Identifier like
case // Literals
.Self, .false, .nil, .`self`, .super, .true:
self = .identifierLike
// MARK: Expr keyword
case // Keywords
.as, .is, .some, .try,
.await, .each, .copy,
// We don't know much about which contextual keyword it is, be conservative an allow considering it as unexpected.
// Keywords in function types (we should be allowed to skip them inside parenthesis)
.rethrows, .throws, .reasync, .async,
// Consider 'any' a prefix operator to a type and a type is expression-like.
.Any,
// 'where' can only occur in the signature of declarations. Consider the signature expression-like.
.where:
self = .exprKeyword
case // Control-flow constructs
.defer, .do, .for, .guard, .if, .repeat, .switch, .while,
// Secondary parts of control-flow constructs
.case, .catch, .default, .else,
// Return-like statements
.break, .continue, .fallthrough, .return, .throw, .then, .yield,
// 'in' occurs in closure input/output definitions and for loops. Consider both constructs expression-like.
.in:
self = .stmtKeyword
// MARK: Decl keywords
case // Types
.associatedtype, .class, .enum, .extension, .protocol, .struct, .typealias, .actor, .macro,
// Access modifiers
.fileprivate, .internal, .private, .public, .static,
// Functions
.deinit, .func, .`init`, .subscript,
// Variables
.let, .var,
// Operator stuff
.operator, .precedencegroup,
// Declaration Modifiers
.__consuming, .final, .required, .optional, .lazy, .dynamic, .infix, .postfix, .prefix, .mutating, .nonmutating,
.convenience, .override, .package, .open,
.__setter_access, .indirect, .isolated, .nonisolated, .distributed, ._local,
.inout, ._mutating, ._borrow, ._borrowing, .borrowing, ._consuming, .consuming, .consume, ._resultDependsOnSelf,
._resultDependsOn,
.dependsOn, .scoped, .sending,
// Accessors
.get, .set, .didSet, .willSet, .unsafeAddress, .addressWithOwner, .addressWithNativeOwner, .unsafeMutableAddress,
.mutableAddressWithOwner, .mutableAddressWithNativeOwner, ._read, ._modify,
// Misc
.import:
self = .declKeyword
case // `TypeAttribute`
._noMetadata,
._opaqueReturnTypeOf,
.autoclosure,
.convention,
.differentiable,
.escaping,
.noDerivative,
.noescape,
.preconcurrency,
.Sendable,
.retroactive,
.unchecked:
// Note that .isolated is preferred as a decl keyword
self = .exprKeyword
case // `DeclarationAttributeWithSpecialSyntax`
._alignment,
._backDeploy,
._cdecl,
._documentation,
._dynamicReplacement,
._effects,
._expose,
._implements,
._nonSendable,
._objcImplementation,
._objcRuntimeName,
._optimize,
._originallyDefinedIn,
._private,
._projectedValueProperty,
._semantics,
._specialize,
._spi,
._spi_available,
._swift_native_objc_runtime_base,
._typeEraser,
._unavailableFromAsync,
.attached,
.available,
.backDeployed,
.derivative,
.exclusivity,
.freestanding,
.inline,
.objc,
.transpose:
self = .exprKeyword
case // Treat all other keywords as expression keywords in the absence of any better information.
.__owned,
.__shared,
._BridgeObject,
._Class,
._compilerInitialized,
._const,
._forward,
._linear,
._move,
._NativeClass,
._NativeRefCountedObject,
._PackageDescription,
._RefCountedObject,
._Trivial,
._TrivialAtMost,
._TrivialStride,
._underlyingVersion,
._UnknownLayout,
._version,
.accesses,
.any,
.assignment,
.associativity,
.availability,
.before,
.block,
.canImport,
.compiler,
.cType,
.deprecated,
.exported,
.file,
.discard,
.forward,
.higherThan,
.initializes,
.introduced,
.kind,
.left,
.line,
.linear,
.lowerThan,
.message,
.metadata,
.module,
.noasync,
.none,
.obsoleted,
.of,
.Protocol,
.renamed,
.reverse,
.right,
.safe,
.sourceFile,
.spi,
.spiModule,
.swift,
.target,
.Type,
.unavailable,
.unowned,
.visibility,
.weak,
.witness_method,
.wrt,
.unsafe:
self = .exprKeyword
#if RESILIENT_LIBRARIES
@unknown default:
fatalError()
#endif
}
}
}
|