Skip to content

Move syntactic XCTest scanner to a separate file #1392

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 1 commit into from
Jun 2, 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
1 change: 1 addition & 0 deletions Sources/SourceKitLSP/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ target_sources(SourceKitLSP PRIVATE
Swift/SwiftLanguageService.swift
Swift/SwiftTestingScanner.swift
Swift/SymbolInfo.swift
Swift/SyntacticSwiftXCTestScanner.swift
Swift/SyntacticTestIndex.swift
Swift/SyntaxHighlightingToken.swift
Swift/SyntaxHighlightingTokenParser.swift
Expand Down
16 changes: 16 additions & 0 deletions Sources/SourceKitLSP/LanguageService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ public enum LanguageServerState {
case semanticFunctionalityDisabled
}

public struct AnnotatedTestItem: Sendable {
/// The test item to be annotated
public var testItem: TestItem

/// Whether the `TestItem` is an extension.
public var isExtension: Bool

public init(
testItem: TestItem,
isExtension: Bool
) {
self.testItem = testItem
self.isExtension = isExtension
}
}

public struct RenameLocation: Sendable {
/// How the identifier at a given location is being used.
///
Expand Down
125 changes: 125 additions & 0 deletions Sources/SourceKitLSP/Swift/SyntacticSwiftXCTestScanner.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 LanguageServerProtocol
import SwiftSyntax

/// Scans a source file for `XCTestCase` classes and test methods.
///
/// The syntax visitor scans from class and extension declarations that could be `XCTestCase` classes or extensions
/// thereof. It then calls into `findTestMethods` to find the actual test methods.
final class SyntacticSwiftXCTestScanner: SyntaxVisitor {
/// The document snapshot of the syntax tree that is being walked.
private var snapshot: DocumentSnapshot

/// The workspace symbols representing the found `XCTestCase` subclasses and test methods.
private var result: [AnnotatedTestItem] = []

private init(snapshot: DocumentSnapshot) {
self.snapshot = snapshot
super.init(viewMode: .fixedUp)
}

public static func findTestSymbols(
in snapshot: DocumentSnapshot,
syntaxTreeManager: SyntaxTreeManager
) async -> [AnnotatedTestItem] {
guard snapshot.text.contains("XCTestCase") || snapshot.text.contains("test") else {
// If the file contains tests that can be discovered syntactically, it needs to have a class inheriting from
// `XCTestCase` or a function starting with `test`.
// This is intended to filter out files that obviously do not contain tests.
return []
}
let syntaxTree = await syntaxTreeManager.syntaxTree(for: snapshot)
let visitor = SyntacticSwiftXCTestScanner(snapshot: snapshot)
visitor.walk(syntaxTree)
return visitor.result
}

private func findTestMethods(in members: MemberBlockItemListSyntax, containerName: String) -> [TestItem] {
return members.compactMap { (member) -> TestItem? in
guard let function = member.decl.as(FunctionDeclSyntax.self) else {
return nil
}
guard function.name.text.starts(with: "test") else {
return nil
}
guard function.modifiers.map(\.name.tokenKind).allSatisfy({ $0 != .keyword(.static) && $0 != .keyword(.class) })
else {
// Test methods can't be static.
return nil
}
guard function.signature.returnClause == nil, function.signature.parameterClause.parameters.isEmpty else {
// Test methods can't have a return type or have parameters.
// Technically we are also filtering out functions that have an explicit `Void` return type here but such
// declarations are probably less common than helper functions that start with `test` and have a return type.
return nil
}
let range = snapshot.absolutePositionRange(
of: function.positionAfterSkippingLeadingTrivia..<function.endPositionBeforeTrailingTrivia
)

return TestItem(
id: "\(containerName)/\(function.name.text)()",
label: "\(function.name.text)()",
disabled: false,
style: TestStyle.xcTest,
location: Location(uri: snapshot.uri, range: range),
children: [],
tags: []
)
}
}

override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind {
guard let inheritedTypes = node.inheritanceClause?.inheritedTypes, let superclass = inheritedTypes.first else {
// The class has no superclass and thus can't inherit from XCTestCase.
// Continue scanning its children in case it has a nested subclass that inherits from XCTestCase.
return .visitChildren
}
let superclassName = superclass.type.as(IdentifierTypeSyntax.self)?.name.text
if superclassName == "NSObject" {
// We know that the class can't be an subclass of `XCTestCase` so don't visit it.
// We can't explicitly check for the `XCTestCase` superclass because the class might inherit from a class that in
// turn inherits from `XCTestCase`. Resolving that inheritance hierarchy would be semantic.
return .visitChildren
}
let testMethods = findTestMethods(in: node.memberBlock.members, containerName: node.name.text)
guard !testMethods.isEmpty || superclassName == "XCTestCase" else {
// Don't report a test class if it doesn't contain any test methods.
return .visitChildren
}
let range = snapshot.absolutePositionRange(
of: node.positionAfterSkippingLeadingTrivia..<node.endPositionBeforeTrailingTrivia
)
let testItem = AnnotatedTestItem(
testItem: TestItem(
id: node.name.text,
label: node.name.text,
disabled: false,
style: TestStyle.xcTest,
location: Location(uri: snapshot.uri, range: range),
children: testMethods,
tags: []
),
isExtension: false
)
result.append(testItem)
return .visitChildren
}

override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind {
result += findTestMethods(in: node.memberBlock.members, containerName: node.extendedType.trimmedDescription)
.map { AnnotatedTestItem(testItem: $0, isExtension: true) }
return .visitChildren
}
}
129 changes: 1 addition & 128 deletions Sources/SourceKitLSP/TestDiscovery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,6 @@ public enum TestStyle {
public static let swiftTesting = "swift-testing"
}

public struct AnnotatedTestItem: Sendable {
/// The test item to be annotated
public var testItem: TestItem

/// Whether the `TestItem` is an extension.
public var isExtension: Bool

public init(
testItem: TestItem,
isExtension: Bool
) {
self.testItem = testItem
self.isExtension = isExtension
}
}

fileprivate extension SymbolOccurrence {
/// Assuming that this is a symbol occurrence returned by the index, return whether it can constitute the definition
/// of a test case.
Expand Down Expand Up @@ -352,117 +336,6 @@ extension SourceKitLSPServer {
}
}

/// Scans a source file for `XCTestCase` classes and test methods.
///
/// The syntax visitor scans from class and extension declarations that could be `XCTestCase` classes or extensions
/// thereof. It then calls into `findTestMethods` to find the actual test methods.
final class SyntacticSwiftXCTestScanner: SyntaxVisitor {
/// The document snapshot of the syntax tree that is being walked.
private var snapshot: DocumentSnapshot

/// The workspace symbols representing the found `XCTestCase` subclasses and test methods.
private var result: [AnnotatedTestItem] = []

private init(snapshot: DocumentSnapshot) {
self.snapshot = snapshot
super.init(viewMode: .fixedUp)
}

public static func findTestSymbols(
in snapshot: DocumentSnapshot,
syntaxTreeManager: SyntaxTreeManager
) async -> [AnnotatedTestItem] {
guard snapshot.text.contains("XCTestCase") || snapshot.text.contains("test") else {
// If the file contains tests that can be discovered syntactically, it needs to have a class inheriting from
// `XCTestCase` or a function starting with `test`.
// This is intended to filter out files that obviously do not contain tests.
return []
}
let syntaxTree = await syntaxTreeManager.syntaxTree(for: snapshot)
let visitor = SyntacticSwiftXCTestScanner(snapshot: snapshot)
visitor.walk(syntaxTree)
return visitor.result
}

private func findTestMethods(in members: MemberBlockItemListSyntax, containerName: String) -> [TestItem] {
return members.compactMap { (member) -> TestItem? in
guard let function = member.decl.as(FunctionDeclSyntax.self) else {
return nil
}
guard function.name.text.starts(with: "test") else {
return nil
}
guard function.modifiers.map(\.name.tokenKind).allSatisfy({ $0 != .keyword(.static) && $0 != .keyword(.class) })
else {
// Test methods can't be static.
return nil
}
guard function.signature.returnClause == nil, function.signature.parameterClause.parameters.isEmpty else {
// Test methods can't have a return type or have parameters.
// Technically we are also filtering out functions that have an explicit `Void` return type here but such
// declarations are probably less common than helper functions that start with `test` and have a return type.
return nil
}
let range = snapshot.absolutePositionRange(
of: function.positionAfterSkippingLeadingTrivia..<function.endPositionBeforeTrailingTrivia
)

return TestItem(
id: "\(containerName)/\(function.name.text)()",
label: "\(function.name.text)()",
disabled: false,
style: TestStyle.xcTest,
location: Location(uri: snapshot.uri, range: range),
children: [],
tags: []
)
}
}

override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind {
guard let inheritedTypes = node.inheritanceClause?.inheritedTypes, let superclass = inheritedTypes.first else {
// The class has no superclass and thus can't inherit from XCTestCase.
// Continue scanning its children in case it has a nested subclass that inherits from XCTestCase.
return .visitChildren
}
let superclassName = superclass.type.as(IdentifierTypeSyntax.self)?.name.text
if superclassName == "NSObject" {
// We know that the class can't be an subclass of `XCTestCase` so don't visit it.
// We can't explicitly check for the `XCTestCase` superclass because the class might inherit from a class that in
// turn inherits from `XCTestCase`. Resolving that inheritance hierarchy would be semantic.
return .visitChildren
}
let testMethods = findTestMethods(in: node.memberBlock.members, containerName: node.name.text)
guard !testMethods.isEmpty || superclassName == "XCTestCase" else {
// Don't report a test class if it doesn't contain any test methods.
return .visitChildren
}
let range = snapshot.absolutePositionRange(
of: node.positionAfterSkippingLeadingTrivia..<node.endPositionBeforeTrailingTrivia
)
let testItem = AnnotatedTestItem(
testItem: TestItem(
id: node.name.text,
label: node.name.text,
disabled: false,
style: TestStyle.xcTest,
location: Location(uri: snapshot.uri, range: range),
children: testMethods,
tags: []
),
isExtension: false
)
result.append(testItem)
return .visitChildren
}

override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind {
result += findTestMethods(in: node.memberBlock.members, containerName: node.extendedType.trimmedDescription)
.map { AnnotatedTestItem(testItem: $0, isExtension: true) }
return .visitChildren
}
}

extension TestItem {
/// Use out-of-date semantic information to filter syntactic symbols.
///
Expand Down Expand Up @@ -506,7 +379,7 @@ extension AnnotatedTestItem {
}
}

extension Array<AnnotatedTestItem> {
fileprivate extension Array<AnnotatedTestItem> {
/// When the test scanners discover tests in extensions they are captured in their own parent `TestItem`, not the
/// `TestItem` generated from the class/struct's definition. This is largely because of the syntatic nature of the
/// test scanners as they are today, which only know about tests within the context of the current file. Extensions
Expand Down