Skip to content

Commit 0fb0018

Browse files
authored
Merge pull request #2434 from ahoppen/ahoppen/identifier-check
Add a function to check if a name can be used as an identifier in a given context
2 parents 48a0f06 + 38b7b38 commit 0fb0018

File tree

4 files changed

+185
-0
lines changed

4 files changed

+185
-0
lines changed

Release Notes/511.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@
3232
- Description: The `throwsSpecifier` for the effects nodes (`AccessorEffectSpecifiers`, `FunctionEffectSpecifiers`, `TypeEffectSpecifiers`, `EffectSpecifiers`) has been replaced with `throwsClause`, which captures both the throws specifier and the (optional) thrown error type, as introduced by SE-0413.
3333
- Pull Request: https://github.com/apple/swift-syntax/pull/2379
3434

35+
- `String.isValidIdentifier(for:)`
36+
- Description: `SwiftParser` adds an extension on `String` to check if it can be used as an identifier in a given context.
37+
- Pull Request: https://github.com/apple/swift-syntax/pull/2434
38+
3539
## API Behavior Changes
3640

3741
## Deprecations

Sources/SwiftParser/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ add_swift_syntax_library(SwiftParser
1515
Directives.swift
1616
Expressions.swift
1717
IncrementalParseTransition.swift
18+
IsValidIdentifier.swift
1819
Lookahead.swift
1920
LoopProgressCondition.swift
2021
Modifiers.swift
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
@_spi(RawSyntax) import SwiftSyntax
14+
15+
/// Context in which to check if a name can be used as an identifier.
16+
///
17+
/// - SeeAlso: `Swift.isValidSwiftIdentifier(for:)` extension added by SwiftParser.
18+
public enum IdentifierCheckContext {
19+
/// Check if a name can be used to declare a variable, ie. if it can be used after a `let` or `var` keyword.
20+
///
21+
/// ### Examples
22+
/// - `test` is a valid variable name and `let test: Int` is valid Swift code
23+
/// - `class` is not a valid variable and `let class: Int` is invalid Swift code
24+
case variableName
25+
26+
/// Check if a name can be used as a member access, ie. if it can be used after a `.`.
27+
///
28+
/// ### Examples
29+
/// - `test` is a valid identifier for member access because `myStruct.test` is valid
30+
/// - `class` is a valid identifier for member access because `myStruct.class` is valid, even though `class`
31+
/// needs to be wrapped in backticks when used to declare a variable.
32+
/// - `self` is not a valid identifier for member access because `myStruct.self` does not access a member named
33+
/// `self` on `myStruct` and instead returns `myStruct` itself.
34+
case memberAccess
35+
}
36+
37+
extension String {
38+
/// Checks whether `name` can be used as an identifier in a certain context.
39+
///
40+
/// If the name cannot be used as an identifier in this context, it needs to be escaped.
41+
///
42+
/// For example, `class` is not a valid identifier for a variable name and needs to be be wrapped in backticks
43+
/// to be valid Swift code, like the following.
44+
///
45+
/// ```swift
46+
/// let `class`: String
47+
/// ```
48+
///
49+
/// The context is important here – some names can be used as identifiers in some contexts but not others.
50+
/// For example, `myStruct.class` is valid without adding backticks `class`, but as mentioned above,
51+
/// backticks need to be added when `class` is used as a variable name.
52+
///
53+
/// - SeeAlso: ``SwiftParser/IdentifierCheckContext``
54+
public func isValidSwiftIdentifier(for context: IdentifierCheckContext) -> Bool {
55+
switch context {
56+
case .variableName:
57+
return isValidVariableName(self)
58+
case .memberAccess:
59+
return isValidMemberAccess(self)
60+
}
61+
}
62+
}
63+
64+
private func isValidVariableName(_ name: String) -> Bool {
65+
var parser = Parser("var \(name)")
66+
let decl = DeclSyntax.parse(from: &parser)
67+
guard parser.at(.endOfFile) else {
68+
// We didn't parse the entire name. Probably some garbage left in the name, so not an identifier.
69+
return false
70+
}
71+
guard !decl.hasError && !decl.hasWarning else {
72+
// There were syntax errors in the source code. So not valid.
73+
return false
74+
}
75+
guard let variable = decl.as(VariableDeclSyntax.self) else {
76+
return false
77+
}
78+
guard let identifier = variable.bindings.first?.pattern.as(IdentifierPatternSyntax.self)?.identifier else {
79+
return false
80+
}
81+
guard identifier.rawTokenKind == .identifier else {
82+
// We parsed the name as a keyword, eg. `self`, so not a valid identifier.
83+
return false
84+
}
85+
guard identifier.rawText.count == name.utf8.count else {
86+
// The identifier doesn't cover all the characters in `name`, so we parsed
87+
// some of these characters into trivia or another token.
88+
// Thus, `name` is not a valid identifier.
89+
return false
90+
}
91+
return true
92+
}
93+
94+
private func isValidMemberAccess(_ name: String) -> Bool {
95+
var parser = Parser("t.\(name)")
96+
let expr = ExprSyntax.parse(from: &parser)
97+
guard parser.at(.endOfFile) else {
98+
// We didn't parse the entire name. Probably some garbage left in the name, so not an identifier.
99+
return false
100+
}
101+
guard !expr.hasError && !expr.hasWarning else {
102+
// There were syntax errors in the source code. So not valid.
103+
return false
104+
}
105+
guard let memberAccess = expr.as(MemberAccessExprSyntax.self) else {
106+
return false
107+
}
108+
let identifier = memberAccess.declName.baseName
109+
guard identifier.rawTokenKind == .identifier else {
110+
// We parsed the name as a keyword, eg. `self`, so not a valid identifier.
111+
return false
112+
}
113+
guard identifier.rawText.count == name.utf8.count else {
114+
// The identifier doesn't cover all the characters in `name`, so we parsed
115+
// some of these characters into trivia or another token.
116+
// Thus, `name` is not a valid identifier.
117+
return false
118+
}
119+
return true
120+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
import SwiftParser
14+
import XCTest
15+
16+
/// Defines whether a name is expected to be a valid identifier in the given contexts.
17+
private struct ValidIdentifierSpec: ExpressibleByBooleanLiteral {
18+
let variableName: Bool
19+
let memberAccess: Bool
20+
21+
init(variableName: Bool, memberAccess: Bool) {
22+
self.variableName = variableName
23+
self.memberAccess = memberAccess
24+
}
25+
26+
init(booleanLiteral value: BooleanLiteralType) {
27+
self.init(variableName: value, memberAccess: value)
28+
}
29+
}
30+
31+
private func assertValidIdentifier(
32+
_ name: String,
33+
_ spec: ValidIdentifierSpec,
34+
file: StaticString = #file,
35+
line: UInt = #line
36+
) {
37+
XCTAssertEqual(name.isValidSwiftIdentifier(for: .variableName), spec.variableName, "Checking identifier for variableName context", file: file, line: line)
38+
XCTAssertEqual(name.isValidSwiftIdentifier(for: .memberAccess), spec.memberAccess, "Checking identifier for memberAccess context", file: file, line: line)
39+
}
40+
41+
class IsValidIdentifierTests: XCTestCase {
42+
func testIsValidIdentifier() {
43+
assertValidIdentifier("test", true)
44+
assertValidIdentifier("class", ValidIdentifierSpec(variableName: false, memberAccess: true))
45+
assertValidIdentifier("`class`", true)
46+
assertValidIdentifier("self", false)
47+
assertValidIdentifier("`self`", true)
48+
assertValidIdentifier("let", ValidIdentifierSpec(variableName: false, memberAccess: true))
49+
assertValidIdentifier("`let`", true)
50+
assertValidIdentifier("", false)
51+
assertValidIdentifier("test: Int", false)
52+
assertValidIdentifier("test ", false)
53+
assertValidIdentifier(" test", false)
54+
assertValidIdentifier("te st", false)
55+
assertValidIdentifier("test\0", false)
56+
assertValidIdentifier("test\0test", false)
57+
assertValidIdentifier("test(x:)", false)
58+
assertValidIdentifier("👩‍👩‍👧‍👧", true)
59+
}
60+
}

0 commit comments

Comments
 (0)