-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathSyntaxExtensions.swift
223 lines (204 loc) · 7.05 KB
/
SyntaxExtensions.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
//===----------------------------------------------------------------------===//
//
// 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)
internal import SwiftBasicFormat
@_spi(Diagnostics) internal import SwiftParser
@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax
#else
import SwiftBasicFormat
@_spi(Diagnostics) import SwiftParser
@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax
#endif
extension UnexpectedNodesSyntax {
func presentTokens(satisfying isIncluded: (TokenSyntax) -> Bool) -> [TokenSyntax] {
return self.children(viewMode: .sourceAccurate).compactMap({ $0.as(TokenSyntax.self) }).filter(isIncluded)
}
func presentTokens(withKind kind: TokenKind) -> [TokenSyntax] {
return self.presentTokens(satisfying: { $0.tokenKind == kind })
}
/// If this only contains a single item, which is a present token satisfying `condition`, return that token, otherwise return `nil`.
func onlyPresentToken(where condition: (TokenSyntax) -> Bool) -> TokenSyntax? {
if self.count == 1,
let token = self.first?.as(TokenSyntax.self),
condition(token),
token.presence == .present
{
return token
} else {
return nil
}
}
/// If this only contains present tokens satisfying `condition`, return an array containing those tokens, otherwise return `nil`.
func onlyPresentTokens(satisfying condition: (TokenSyntax) -> Bool) -> [TokenSyntax]? {
let tokens = presentTokens(satisfying: condition)
if tokens.count == self.count {
return tokens
} else {
return nil
}
}
/// If this only contains two present tokens, the first satisfying `firstCondition`, and the second satisfying `secondCondition`,
/// return these tokens as a tuple, otherwise return `nil`.
func twoPresentTokens(
firstSatisfying firstCondition: (TokenSyntax) -> Bool,
secondSatisfying secondCondition: (TokenSyntax) -> Bool
) -> (first: TokenSyntax, second: TokenSyntax)? {
let sourceAccurateChildren = self.children(viewMode: .sourceAccurate).compactMap({ $0.as(TokenSyntax.self) })
guard sourceAccurateChildren.count == 2 else {
return nil
}
guard firstCondition(sourceAccurateChildren[0]) && secondCondition(sourceAccurateChildren[1]) else {
return nil
}
return (sourceAccurateChildren[0], sourceAccurateChildren[1])
}
}
extension Syntax {
func hasParent(_ expectedParent: Syntax) -> Bool {
var walk = self.parent
while walk != nil {
if walk == expectedParent {
return true
}
walk = walk?.parent
}
return false
}
}
extension SyntaxProtocol {
/// A name that can be used to describe this node's type in diagnostics or `nil` if there is no good name for this node.
/// If `allowBlockNames` is `false`, ``CodeBlockSyntax`` and ``MemberDeclBlockSyntax`` are not considered to have a good name and will return `nil`.
func nodeTypeNameForDiagnostics(allowBlockNames: Bool) -> String? {
let syntax = Syntax(self)
if !allowBlockNames && (syntax.is(CodeBlockSyntax.self) || syntax.is(MemberBlockSyntax.self)) {
return nil
}
return syntax.kind.nameForDiagnostics
}
/// A short description of this node that can be displayed inline in a single line.
/// If the syntax node (excluding leading and trailing trivia) only spans a
/// single line and has less than 100 characters (and thus fits into a
/// diagnostic message), return that.
/// Otherwise, return a generic message that describes the tokens in this node.
var shortSingleLineContentDescription: String {
let contentWithoutTrivia = self.trimmedDescription
if self.children(viewMode: .sourceAccurate).allSatisfy({ $0.as(TokenSyntax.self)?.tokenKind == .rightBrace }) {
if self.children(viewMode: .sourceAccurate).count == 1 {
return "brace"
} else {
return "braces"
}
} else if let token = Syntax(self).as(UnexpectedNodesSyntax.self)?.onlyPresentTokens(satisfying: {
$0.tokenKind.isLexerClassifiedKeyword
})?.only {
return "'\(token.text)' keyword"
} else if let token = Syntax(self).as(TokenSyntax.self) {
return "'\(token.text)' keyword"
} else if contentWithoutTrivia.contains("\n") || contentWithoutTrivia.count > 100 {
return "code"
} else {
return "code '\(contentWithoutTrivia)'"
}
}
/// Returns `true` if the next token's leading trivia should be made leading trivia
/// of this mode, when it is switched from being missing to present.
var shouldBeInsertedAfterNextTokenTrivia: Bool {
if !self.raw.kind.isMissing,
let memberDeclItem = self.ancestorOrSelf(mapping: { $0.as(MemberBlockItemSyntax.self) }),
memberDeclItem.firstToken(viewMode: .all) == self.firstToken(viewMode: .all)
{
return true
} else {
return false
}
}
/// Returns `true` if the previous token and this node don't need to be separated,
/// when it is switched from being missing to present.
var shouldBeInsertedBeforePreviousTokenTrivia: Bool {
if let previousToken = self.previousToken(viewMode: .fixedUp),
previousToken.isPresent,
let firstToken = self.firstToken(viewMode: .all),
previousToken.trailingTrivia.allSatisfy({ $0.isWhitespace }),
!BasicFormat().requiresWhitespace(between: previousToken, and: firstToken),
!BasicFormat().requiresNewline(between: previousToken, and: firstToken)
{
return true
} else {
return false
}
}
}
extension TokenKind {
var isIdentifier: Bool {
switch self {
case .identifier:
return true
default:
return false
}
}
var isDollarIdentifier: Bool {
switch self {
case .dollarIdentifier:
return true
default:
return false
}
}
var isIntegerLiteral: Bool {
switch self {
case .integerLiteral:
return true
default:
return false
}
}
var isRawStringDelimiter: Bool {
switch self {
case .rawStringPoundDelimiter:
return true
default:
return false
}
}
}
extension TriviaPiece {
var isBackslash: Bool {
switch self {
case .backslashes: return true
default: return false
}
}
}
extension TokenSyntax {
var isMissing: Bool {
return presence == .missing
}
var isPresent: Bool {
return presence == .present
}
}
extension TypeSpecifierListSyntax {
var simpleSpecifiers: [TokenSyntax] {
return self.compactMap { specifier in
switch specifier {
case .simpleTypeSpecifier(let specifier): return specifier.specifier
case .lifetimeTypeSpecifier: return nil
case .nonisolatedTypeSpecifier: return nil
#if RESILIENT_LIBRARIES
@unknown default:
fatalError()
#endif
}
}
}
}