File: VisitorTests.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; 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 (469 lines) | stat: -rw-r--r-- 12,035 bytes parent folder | download | duplicates (2)
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//===----------------------------------------------------------------------===//
//
// 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 SwiftDiagnostics
@_spi(Compiler) import SwiftIfConfig
import SwiftParser
import SwiftSyntax
@_spi(XCTestFailureLocation) @_spi(Testing) import SwiftSyntaxMacrosGenericTestSupport
import XCTest
import _SwiftSyntaxGenericTestSupport
import _SwiftSyntaxTestSupport

/// Visitor that ensures that all of the nodes we visit are active.
///
/// This cross-checks the visitor itself with the `SyntaxProtocol.isActive(in:)`
/// API.
class AllActiveVisitor: ActiveSyntaxAnyVisitor {
  let configuration: TestingBuildConfiguration

  init(
    configuration: TestingBuildConfiguration,
    configuredRegions: ConfiguredRegions? = nil
  ) {
    self.configuration = configuration

    if let configuredRegions {
      super.init(viewMode: .sourceAccurate, configuredRegions: configuredRegions)
    } else {
      super.init(viewMode: .sourceAccurate, configuration: configuration)
    }
  }

  open override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind {
    XCTAssertEqual(node.isActive(in: configuration).state, .active)
    return .visitChildren
  }
}

class NameCheckingVisitor: ActiveSyntaxAnyVisitor {
  let configuration: TestingBuildConfiguration

  /// The set of names we are expected to visit. Any syntax nodes with
  /// names that aren't here will be rejected, and each of the names listed
  /// here must occur exactly once.
  var expectedNames: Set<String>

  init(
    configuration: TestingBuildConfiguration,
    expectedNames: Set<String>,
    configuredRegions: ConfiguredRegions? = nil
  ) {
    self.configuration = configuration
    self.expectedNames = expectedNames

    if let configuredRegions {
      super.init(viewMode: .sourceAccurate, configuredRegions: configuredRegions)
    } else {
      super.init(viewMode: .sourceAccurate, configuration: configuration)
    }
  }

  deinit {
    if !expectedNames.isEmpty {
      XCTFail("No nodes with expected names visited: \(expectedNames)")
    }
  }

  func checkName(name: String, node: Syntax) {
    if !expectedNames.contains(name) {
      XCTFail("syntax node with unexpected name \(name) found: \(node.debugDescription)")
    }

    expectedNames.remove(name)
  }

  open override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind {
    if let identified = node.asProtocol(NamedDeclSyntax.self) {
      checkName(name: identified.name.text, node: node)
    } else if let identPattern = node.as(IdentifierPatternSyntax.self) {
      // FIXME: Should the above be an IdentifiedDeclSyntax?
      checkName(name: identPattern.identifier.text, node: node)
    }

    return .visitChildren
  }
}

public class VisitorTests: XCTestCase {
  let linuxBuildConfig = TestingBuildConfiguration(
    customConditions: ["DEBUG", "ASSERTS"],
    features: ["ParameterPacks"],
    attributes: ["available"]
  )

  let iosBuildConfig = TestingBuildConfiguration(
    platformName: "iOS",
    customConditions: ["DEBUG", "ASSERTS"],
    features: ["ParameterPacks"],
    attributes: ["available"]
  )

  let inputSource: SourceFileSyntax = """
    #if DEBUG
    #if os(Linux)
    #if hasAttribute(available)
    @available(*, deprecated, message: "use something else")
    #else
    @MainActor
    #endif
    func f() {
    }
    #elseif os(iOS)
    func g() {
      let a = foo
        #if hasFeature(ParameterPacks)
        .b
        #endif
        .c
    }
    #endif

    struct S {
      #if DEBUG
      var generationCount = 0
      #endif
    }

    func h() {
      switch result {
        case .success(let value):
          break
        #if os(iOS)
        case .failure(let error):
          break
        #endif
      }
    }

    func i() {
      a.b
      #if DEBUG
        .c
      #endif
      #if hasAttribute(available)
        .d()
      #endif
      #if os(iOS)
        .e[]
      #endif
    }
    #endif

    #if hasAttribute(available)
    func withAvail() { }
    #else
    func notAvail() { }
    #endif
    """

  func testAnyVisitorVisitsOnlyActive() throws {
    // Make sure that all visited nodes are active nodes.
    assertVisitedAllActive(linuxBuildConfig)
    assertVisitedAllActive(iosBuildConfig)
  }

  func testVisitsExpectedNodes() throws {
    // Check that the right set of names is visited.
    assertVisitedExpectedNames(
      linuxBuildConfig,
      expectedNames: ["f", "h", "i", "S", "generationCount", "value", "withAvail"]
    )

    assertVisitedExpectedNames(
      iosBuildConfig,
      expectedNames: ["g", "h", "i", "a", "S", "generationCount", "value", "error", "withAvail"]
    )
  }

  func testVisitorWithErrors() throws {
    var configuration = linuxBuildConfig
    configuration.badAttributes.insert("available")
    assertVisitedExpectedNames(
      configuration,
      expectedNames: ["f", "h", "i", "S", "generationCount", "value", "notAvail"],
      diagnosticCount: 3
    )
  }

  func testRemoveInactive() {
    assertRemoveInactive(
      inputSource.description,
      configuration: linuxBuildConfig,
      expectedSource: """

        @available(*, deprecated, message: "use something else")
        func f() {
        }

        struct S {
          var generationCount = 0
        }

        func h() {
          switch result {
            case .success(let value):
              break
          }
        }

        func i() {
          a.b
            .c
            .d()
        }
        func withAvail() { }
        """
    )
  }

  func testRemoveInactiveWithErrors() {
    var configuration = linuxBuildConfig
    configuration.badAttributes.insert("available")

    assertRemoveInactive(
      inputSource.description,
      configuration: configuration,
      diagnostics: [
        DiagnosticSpec(
          message: "unacceptable attribute 'available'",
          line: 3,
          column: 18
        ),
        DiagnosticSpec(
          message: "unacceptable attribute 'available'",
          line: 42,
          column: 20
        ),
        DiagnosticSpec(
          message: "unacceptable attribute 'available'",
          line: 51,
          column: 18
        ),
      ],
      expectedSource: """

        @MainActor
        func f() {
        }

        struct S {
          var generationCount = 0
        }

        func h() {
          switch result {
            case .success(let value):
              break
          }
        }

        func i() {
          a.b
            .c
        }
        func notAvail() { }
        """
    )
  }

  func testRemoveInactiveRetainingFeatureChecks() {
    assertRemoveInactive(
      """
      public func hasIfCompilerCheck(_ x: () -> Bool = {
      #if compiler(>=5.3)
        return true
      #else
        return false
      #endif

      #if $Blah
        return 0
      #else
        return 1
      #endif

      #if NOT_SET
        return 3.14159
      #else
        return 2.71828
      #endif
        }) {
      }
      """,
      configuration: linuxBuildConfig,
      retainFeatureCheckIfConfigs: true,
      expectedSource: """
        public func hasIfCompilerCheck(_ x: () -> Bool = {
        #if compiler(>=5.3)
          return true
        #else
          return false
        #endif

        #if $Blah
          return 0
        #else
          return 1
        #endif
          return 2.71828
          }) {
        }
        """
    )
  }

  func testRemoveCommentsAndSourceLocations() {
    let original: SourceFileSyntax = """

      /// This is a documentation comment
      func f() { }

      #sourceLocation(file: "if-configs.swift", line: 200)
      /** Another documentation comment
          that is split across
          multiple lines */
      func g() { }

      func h() {
        x +/*comment*/y
        // foo
      }
      """

    assertStringsEqualWithDiff(
      original.descriptionWithoutCommentsAndSourceLocations,
      """

       
      func f() { }


      func g() { }

      func h() {
        x + y
         
      }
      """
    )
  }
}

extension VisitorTests {
  /// Ensure that all visited nodes are active nodes according to the given
  /// build configuration.
  fileprivate func assertVisitedAllActive(_ configuration: TestingBuildConfiguration) {
    AllActiveVisitor(configuration: configuration).walk(inputSource)

    let configuredRegions = inputSource.configuredRegions(in: configuration)
    AllActiveVisitor(
      configuration: configuration,
      configuredRegions: configuredRegions
    ).walk(inputSource)
  }

  /// Ensure that we visit nodes with the set of names we were expecting to
  /// visit.
  fileprivate func assertVisitedExpectedNames(
    _ configuration: TestingBuildConfiguration,
    expectedNames: Set<String>,
    diagnosticCount: Int = 0
  ) {
    let firstVisitor = NameCheckingVisitor(
      configuration: configuration,
      expectedNames: expectedNames
    )
    firstVisitor.walk(inputSource)
    XCTAssertEqual(firstVisitor.diagnostics.count, diagnosticCount)

    let configuredRegions = inputSource.configuredRegions(in: configuration)
    let secondVisitor = NameCheckingVisitor(
      configuration: configuration,
      expectedNames: expectedNames,
      configuredRegions: configuredRegions
    )
    secondVisitor.walk(inputSource)
    XCTAssertEqual(secondVisitor.diagnostics.count, diagnosticCount)
  }
}

/// Assert that removing any inactive code according to the given build
/// configuration returns the expected source and diagnostics.
fileprivate func assertRemoveInactive(
  _ source: String,
  configuration: some BuildConfiguration,
  retainFeatureCheckIfConfigs: Bool = false,
  diagnostics expectedDiagnostics: [DiagnosticSpec] = [],
  expectedSource: String,
  file: StaticString = #filePath,
  line: UInt = #line
) {
  var parser = Parser(source)
  let tree = SourceFileSyntax.parse(from: &parser)

  for useConfiguredRegions in [false, true] {
    let fromDescription = useConfiguredRegions ? "configured regions" : "build configuration"
    let treeWithoutInactive: Syntax
    let actualDiagnostics: [Diagnostic]

    if useConfiguredRegions {
      let configuredRegions = tree.configuredRegions(in: configuration)
      actualDiagnostics = configuredRegions.diagnostics
      treeWithoutInactive = configuredRegions.removingInactive(
        from: tree,
        retainFeatureCheckIfConfigs: retainFeatureCheckIfConfigs
      )
    } else {
      (treeWithoutInactive, actualDiagnostics) = tree.removingInactive(
        in: configuration,
        retainFeatureCheckIfConfigs: retainFeatureCheckIfConfigs
      )
    }

    // Check the resulting tree.
    assertStringsEqualWithDiff(
      treeWithoutInactive.description,
      expectedSource,
      "Active code (\(fromDescription))",
      file: file,
      line: line
    )

    // Check the diagnostics.
    if actualDiagnostics.count != expectedDiagnostics.count {
      XCTFail(
        """
        Expected \(expectedDiagnostics.count) diagnostics, but got \(actualDiagnostics.count) via \(fromDescription):
        \(actualDiagnostics.map(\.debugDescription).joined(separator: "\n"))
        """,
        file: file,
        line: line
      )
    } else {
      for (actualDiag, expectedDiag) in zip(actualDiagnostics, expectedDiagnostics) {
        assertDiagnostic(
          actualDiag,
          in: .tree(tree),
          expected: expectedDiag,
          failureHandler: {
            XCTFail(
              $0.message + " via \(fromDescription)",
              file: $0.location.staticFilePath,
              line: $0.location.unsignedLine
            )
          }
        )
      }
    }
  }
}