File: IsValidIdentifier.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (124 lines) | stat: -rw-r--r-- 4,866 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// 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) internal import SwiftSyntax
#else
@_spi(RawSyntax) import SwiftSyntax
#endif

/// 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
}