-
Notifications
You must be signed in to change notification settings - Fork 440
Add a function to check if a name can be used as an identifier in a given context #2434
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no fil 8000 es selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
8000 // 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 | ||
|
||
/// Context in which to check if a name can be used as an identifier. | ||
/// | ||
/// - SeeAlso: `Swift.isValidSwiftIdentifier(for:)` extension added by SwiftParser. | ||
public enum IdentifierCheckContext { | ||
/// Check if a name can be used to declare a variable, ie. if it can be used after a `let` or `var` keyword. | ||
/// | ||
/// ### Examples | ||
/// - `test` is a valid variable name and `let test: Int` is valid Swift code | ||
/// - `class` is not a valid variable and `let class: Int` is invalid Swift code | ||
case variableName | ||
|
||
/// Check if a name can be used as a member access, ie. if it can be used after a `.`. | ||
/// | ||
/// ### Examples | ||
/// - `test` is a valid identifier for member access because `myStruct.test` is valid | ||
/// - `class` is a valid identifier for member access because `myStruct.class` is valid, even though `class` | ||
/// needs to be wrapped in backticks when used to declare a variable. | ||
/// - `self` is not a valid identifier for member access because `myStruct.self` does not access a member named | ||
/// `self` on `myStruct` and instead returns `myStruct` itself. | ||
case memberAccess | ||
} | ||
|
||
extension String { | ||
/// Checks whether `name` can be used as an identifier in a certain context. | ||
/// | ||
/// If the name cannot be used as an identifier in this context, it needs to be escaped. | ||
/// | ||
/// For example, `class` is not a valid identifier for a variable name and needs to be be wrapped in backticks | ||
/// to be valid Swift code, like the following. | ||
/// | ||
/// ```swift | ||
/// let `class`: String | ||
/// ``` | ||
/// | ||
/// The context is important here – some names can be used as identifiers in some contexts but not others. | ||
/// For example, `myStruct.class` is valid without adding backticks `class`, but as mentioned above, | ||
/// backticks need to be added when `class` is used as a variable name. | ||
/// | ||
/// - SeeAlso: ``SwiftParser/IdentifierCheckContext`` | ||
public func isValidSwiftIdentifier(for context: IdentifierCheckContext) -> Bool { | ||
switch context { | ||
case .variableName: | ||
return isValidVariableName(self) | ||
case .memberAccess: | ||
return isValidMemberAccess(self) | ||
} | ||
} | ||
} | ||
|
||
private func isValidVariableName(_ name: String) -> Bool { | ||
var parser = Parser("var \(name)") | ||
let decl = DeclSyntax.parse(from: &parser) | ||
guard parser.at(.endOfFile) else { | ||
// We didn't parse the entire name. Probably some garbage left in the name, so not an identifier. | ||
return false | ||
} | ||
guard !decl.hasError && !decl.hasWarning else { | ||
// There were syntax errors in the source code. So not valid. | ||
return false | ||
} | ||
guard let variable = decl.as(VariableDeclSyntax.self) else { | ||
return false | ||
} | ||
guard let identifier = variable.bindings.first?.pattern.as(IdentifierPatternSyntax.self)?.identifier else { | ||
return false | ||
} | ||
guard identifier.rawTokenKind == .identifier else { | ||
// We parsed the name as a keyword, eg. `self`, so not a valid identifier. | ||
return false | ||
} | ||
guard identifier.rawText.count == name.utf8.count else { | ||
// The identifier doesn't cover all the characters in `name`, so we parsed | ||
// some of these characters into trivia or another token. | ||
// Thus, `name` is not a valid identifier. | ||
return false | ||
} | ||
return true | ||
} | ||
|
||
private func isValidMemberAccess(_ name: String) -> Bool { | ||
var parser = Parser("t.\(name)") | ||
let expr = ExprSyntax.parse(from: &parser) | ||
guard parser.at(.endOfFile) else { | ||
// We didn't parse the entire name. Probably some garbage left in the name, so not an identifier. | ||
return false | ||
} | ||
guard !expr.hasError && !expr.hasWarning else { | ||
// There were syntax errors in the source code. So not valid. | ||
return false | ||
} | ||
guard let memberAccess = expr.as(MemberAccessExprSyntax.self) else { | ||
return false | ||
} | ||
let identifier = memberAccess.declName.baseName | ||
guard identifier.rawTokenKind == .identifier else { | ||
// We parsed the name as a keyword, eg. `self`, so not a valid identifier. | ||
return false | ||
} | ||
guard identifier.rawText.count == name.utf8.count else { | ||
// The identifier doesn't cover all the characters in `name`, so we parsed | ||
// some of these characters into trivia or another token. | ||
// Thus, `name` is not a valid identifier. | ||
return false | ||
} | ||
return true | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import SwiftParser | ||
import XCTest | ||
|
||
/// Defines whether a name is expected to be a valid identifier in the given contexts. | ||
private struct ValidIdentifierSpec: ExpressibleByBooleanLiteral { 8000 | ||
let variableName: Bool | ||
let memberAccess: Bool | ||
|
||
init(variableName: Bool, memberAccess: Bool) { | ||
self.variableName = variableName | ||
self.memberAccess = memberAccess | ||
} | ||
|
||
init(booleanLiteral value: BooleanLiteralType) { | ||
self.init(variableName: value, memberAccess: value) | ||
} | ||
} | ||
|
||
private func assertValidIdentifier( | ||
_ name: String, | ||
_ spec: ValidIdentifierSpec, | ||
file: StaticString = #file, | ||
line: UInt = #line | ||
) { | ||
XCTAssertEqual(name.isValidSwiftIdentifier(for: .variableName), spec.variableName, "Checking identifier for variableName context", file: file, line: line) | ||
XCTAssertEqual(name.isValidSwiftIdentifier(for: .memberAccess), spec.memberAccess, "Checking identifier for memberAccess context", file: file, line: line) | ||
} | ||
|
||
class IsValidIdentifierTests: XCTestCase { | ||
func testIsValidIdentifier() { | ||
assertValidIdentifier("test", true) | ||
assertValidIdentifier("class", ValidIdentifierSpec(variableName: false, memberAccess: true)) | ||
assertValidIdentifier("`class`", true) | ||
assertValidIdentifier("self", false) | ||
assertValidIdentifier("`self`", true) | ||
assertValidIdentifier("let", ValidIdentifierSpec(variableName: false, memberAccess: true)) | ||
assertValidIdentifier("`let`", true) | ||
assertValidIdentifier("", false) | ||
assertValidIdentifier("test: Int", false) | ||
assertValidIdentifier("test ", false) | ||
assertValidIdentifier(" test", false) | ||
assertValidIdentifier("te st", false) | ||
assertValidIdentifier("test\0", false) | ||
assertValidIdentifier("test\0test", false) | ||
assertValidIdentifier("test(x:)", false) | ||
assertValidIdentifier("👩👩👧👧", true) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should also check the current lexeme's
leadingTriviaByteLength
== 0.