8000 Add a function to check if a name can be used as an identifier in a given context by ahoppen · Pull Request #2434 · swiftlang/swift-syntax · GitHub
[go: up one dir, main page]

Skip to content

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

< 8000 /details-dialog>
Merged
merged 1 commit into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Release Notes/511.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
- 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.
- Pull Request: https://github.com/apple/swift-syntax/pull/2379

- `String.isValidIdentifier(for:)`
- Description: `SwiftParser` adds an extension on `String` to check if it can be used as an identifier in a given context.
- Pull Request: https://github.com/apple/swift-syntax/pull/2434

## API Behavior Changes

## Deprecations
Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftParser/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ add_swift_syntax_library(SwiftParser
Directives.swift
Expressions.swift
IncrementalParseTransition.swift
IsValidIdentifier.swift
Lookahead.swift
LoopProgressCondition.swift
Modifiers.swift
Expand Down
120 changes: 120 additions & 0 deletions Sources/SwiftParser/IsValidIdentifier.swift
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 {
Copy link
Member

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.

// 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
}
60 changes: 60 additions & 0 deletions Tests/SwiftParserTest/IsValidIdentifierTests.swift
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)
}
}
0