File: SimpleLookupQueries.swift

package info (click to toggle)
swiftlang 6.1.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,644 kB
  • sloc: cpp: 9,901,738; ansic: 2,201,433; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (214 lines) | stat: -rw-r--r-- 7,553 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
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2024 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 SwiftSyntax

extension SyntaxProtocol {
  /// Returns all labeled statements available at a particular syntax node.
  ///
  /// - Returns: Available labeled statements at a particular syntax node
  /// in the exact order they appear in the source code, starting with the innermost statement.
  ///
  /// Example usage:
  /// ```swift
  /// one: while cond1 {
  ///   func foo() {
  ///     two: while cond2 {
  ///       three: while cond3 {
  ///         break // 1
  ///       }
  ///       break // 2
  ///     }
  ///   }
  ///   break // 3
  /// }
  /// ```
  /// When calling this function at the first `break`, it returns `three` and `two` in this exact order.
  /// For the second `break`, it returns only `two`.
  /// The results don't include `one`, which is unavailable at both locations due to the encapsulating function body.
  /// For `break` numbered 3, the result is `one`, as it's outside the function body and within the labeled statement.
  /// The function returns an empty array when there are no available labeled statements.
  @_spi(Experimental) public func lookupLabeledStmts() -> [LabeledStmtSyntax] {
    collectNodesOfTypeUpToFunctionBoundary(LabeledStmtSyntax.self)
  }

  /// Returns the catch node responsible for handling an error thrown at a particular syntax node.
  ///
  /// - Returns: The catch node responsible for handling an error thrown at the lookup source node.
  /// This could be a `do` statement, `try?`, `try!`, `init`, `deinit`, accessors, closures, or function declarations.
  ///
  /// Example usage:
  /// ```swift
  /// func x() {
  ///   do {
  ///     try foo()
  ///     try? bar()
  ///   } catch {
  ///     throw error
  ///   }
  /// }
  /// ```
  /// When calling this function on `foo`, it returns the `do` statement.
  /// Calling the function on `bar` results in `try?`.
  /// When used on `error`, the function returns the function declaration `x`.
  /// The function returns `nil` when there's no available catch node.
  @_spi(Experimental) public func lookupCatchNode() -> Syntax? {
    lookupCatchNodeHelper(traversedCatchClause: false)
  }

  // MARK: - lookupCatchNode

  /// Given syntax node location, finds where an error could be caught.
  /// If `traverseCatchClause` is set to `true` lookup will skip the next do statement.
  private func lookupCatchNodeHelper(traversedCatchClause: Bool) -> Syntax? {
    guard let parent else { return nil }

    switch parent.as(SyntaxEnum.self) {
    case .doStmt:
      if traversedCatchClause {
        return parent.lookupCatchNodeHelper(traversedCatchClause: false)
      } else {
        return parent
      }
    case .catchClause:
      return parent.lookupCatchNodeHelper(traversedCatchClause: true)
    case .tryExpr(let tryExpr):
      if tryExpr.questionOrExclamationMark != nil {
        return parent
      } else {
        return parent.lookupCatchNodeHelper(traversedCatchClause: traversedCatchClause)
      }
    case .functionDecl, .accessorDecl, .initializerDecl, .deinitializerDecl, .closureExpr:
      return parent
    case .exprList(let exprList):
      if let tryExpr = exprList.first?.as(TryExprSyntax.self), tryExpr.questionOrExclamationMark != nil {
        return Syntax(tryExpr)
      }
      return parent.lookupCatchNodeHelper(traversedCatchClause: traversedCatchClause)
    default:
      return parent.lookupCatchNodeHelper(traversedCatchClause: traversedCatchClause)
    }
  }

  // MARK: - walkParentTree helper methods

  /// Returns the innermost node of the specified type up to a function boundary.
  fileprivate func innermostNodeOfTypeUpToFunctionBoundary<T: SyntaxProtocol>(
    _ type: T.Type
  ) -> T? {
    collectNodesOfTypeUpToFunctionBoundary(type, stopWithFirstMatch: true).first
  }

  /// Collect syntax nodes matching the collection type up until encountering one of the specified syntax nodes.
  /// The nodes in the array are inside out, with the innermost node being the first.
  fileprivate func collectNodesOfTypeUpToFunctionBoundary<T: SyntaxProtocol>(
    _ type: T.Type,
    stopWithFirstMatch: Bool = false
  ) -> [T] {
    collectNodes(
      ofType: type,
      upTo: [
        MemberBlockSyntax.self,
        FunctionDeclSyntax.self,
        InitializerDeclSyntax.self,
        DeinitializerDeclSyntax.self,
        AccessorDeclSyntax.self,
        ClosureExprSyntax.self,
        SubscriptDeclSyntax.self,
      ],
      stopWithFirstMatch: stopWithFirstMatch
    )
  }

  /// Collect syntax nodes matching the collection type up until encountering one of the specified syntax nodes.
  private func collectNodes<T: SyntaxProtocol>(
    ofType type: T.Type,
    upTo stopAt: [SyntaxProtocol.Type],
    stopWithFirstMatch: Bool = false
  ) -> [T] {
    var matches: [T] = []
    var nextSyntax: Syntax? = Syntax(self)
    while let currentSyntax = nextSyntax {
      if stopAt.contains(where: { currentSyntax.is($0) }) {
        break
      }

      if let matchedSyntax = currentSyntax.as(T.self) {
        matches.append(matchedSyntax)
        if stopWithFirstMatch {
          break
        }
      }

      nextSyntax = currentSyntax.parent
    }

    return matches
  }
}

extension FallThroughStmtSyntax {
  /// Returns the source and destination of a `fallthrough`.
  ///
  /// - Returns: `source` as the switch case that encapsulates the `fallthrough` keyword and
  /// `destination` as the switch case that the `fallthrough` directs to.
  ///
  /// Example usage:
  /// ```swift
  /// switch value {
  /// case 2:
  ///   doSomething()
  ///   fallthrough
  /// case 1:
  ///   doSomethingElse()
  /// default:
  ///   break
  /// }
  /// ```
  /// When calling this function at the `fallthrough`, it returns `case 2` and `case 1` in this exact order.
  /// The `nil` results handle ill-formed code: there's no `source` if the `fallthrough` is outside of a case.
  /// There's no `destination` if there is no case or `default` after the source case.
  @_spi(Experimental) public func lookupFallthroughSourceAndDestintation()
    -> (source: SwitchCaseSyntax?, destination: SwitchCaseSyntax?)
  {
    guard
      let originalSwitchCase = innermostNodeOfTypeUpToFunctionBoundary(
        SwitchCaseSyntax.self
      )
    else {
      return (nil, nil)
    }

    let nextSwitchCase = lookupNextSwitchCase(at: originalSwitchCase)

    return (originalSwitchCase, nextSwitchCase)
  }

  /// Given a switch case, returns the case that follows according to the parent.
  private func lookupNextSwitchCase(at switchCaseSyntax: SwitchCaseSyntax) -> SwitchCaseSyntax? {
    guard let switchCaseListSyntax = switchCaseSyntax.parent?.as(SwitchCaseListSyntax.self) else { return nil }

    var visitedOriginalCase = false

    for child in switchCaseListSyntax.children(viewMode: .sourceAccurate) {
      if let thisCase = child.as(SwitchCaseSyntax.self) {
        if thisCase.id == switchCaseSyntax.id {
          visitedOriginalCase = true
        } else if visitedOriginalCase {
          return thisCase
        }
      }
    }

    return nil
  }
}