From fb7d13e05f6561f54ad9413e5c3d8c1148d360dc Mon Sep 17 00:00:00 2001 From: Alex Hoppen Date: Thu, 18 Dec 2025 12:58:21 +0100 Subject: [PATCH] Format source code using `swift-format` --- .swift-format | 76 +++ Package.swift | 56 +- .../ForwardingIndexDelegate.swift | 2 +- Sources/ISDBTestSupport/TestLocation.swift | 12 +- .../ISDBTestSupport/TestLocationScanner.swift | 28 +- Sources/ISDBTestSupport/TestSources.swift | 2 +- .../ISDBTestSupport/TibsTestWorkspace.swift | 79 ++- .../ISDBTestSupport/XCTestAssertions.swift | 19 +- .../ISDBTibs/JSONCompilationDatabase.swift | 1 - Sources/ISDBTibs/OutputFileMap.swift | 9 +- Sources/ISDBTibs/Process.swift | 6 +- Sources/ISDBTibs/TibsBuilder.swift | 155 +++-- Sources/ISDBTibs/TibsManifest.swift | 4 +- Sources/ISDBTibs/TibsResolvedTarget.swift | 14 +- Sources/ISDBTibs/TibsToolchain.swift | 82 +-- Sources/IndexStoreDB/IndexStoreDB.swift | 74 ++- Sources/IndexStoreDB/IndexStoreDBError.swift | 5 +- Sources/IndexStoreDB/Symbol.swift | 11 +- Sources/IndexStoreDB/SymbolLocation.swift | 6 +- Sources/IndexStoreDB/SymbolOccurrence.swift | 21 +- Sources/IndexStoreDB/SymbolProperty.swift | 19 +- Sources/IndexStoreDB/SymbolRole.swift | 5 +- Sources/tibs/main.swift | 5 +- Tests/ISDBTibsTests/MiscTests.swift | 15 +- Tests/ISDBTibsTests/OutputFileMapTests.swift | 28 +- Tests/ISDBTibsTests/TibsBuildTests.swift | 25 +- .../TibsCompilationDatabaseTests.swift | 58 +- Tests/ISDBTibsTests/TibsManifestTests.swift | 29 +- Tests/ISDBTibsTests/TibsResolutionTests.swift | 82 ++- .../IndexStoreDBTests/IndexStoreDBTests.swift | 34 +- Tests/IndexStoreDBTests/IndexTests.swift | 614 ++++++++++++------ .../LocationScannerTests.swift | 137 ++-- Tests/IndexStoreTests/SDKDiscovery.swift | 1 - 33 files changed, 1116 insertions(+), 598 deletions(-) create mode 100644 .swift-format diff --git a/.swift-format b/.swift-format new file mode 100644 index 00000000..e882b362 --- /dev/null +++ b/.swift-format @@ -0,0 +1,76 @@ +{ + "fileScopedDeclarationPrivacy": { + "accessLevel": "private" + }, + "indentConditionalCompilationBlocks": false, + "indentSwitchCaseLabels": false, + "indentation": { + "spaces": 2 + }, + "lineBreakAroundMultilineExpressionChainComponents": false, + "lineBreakBeforeControlFlowKeywords": false, + "lineBreakBeforeEachArgument": true, + "lineBreakBeforeEachGenericRequirement": false, + "lineBreakBetweenDeclarationAttributes": false, + "lineLength": 120, + "maximumBlankLines": 1, + "multiElementCollectionTrailingCommas": true, + "noAssignmentInExpressions": { + "allowedFunctions": [ + "XCTAssertNoThrow" + ] + }, + "prioritizeKeepingFunctionOutputTogether": true, + "reflowMultilineStringLiterals": { + "never": { + + } + }, + "respectsExistingLineBreaks": true, + "rules": { + "AllPublicDeclarationsHaveDocumentation": false, + "AlwaysUseLiteralForEmptyCollectionInit": false, + "AlwaysUseLowerCamelCase": false, + "AmbiguousTrailingClosureOverload": false, + "BeginDocumentationCommentWithOneLineSummary": false, + "DoNotUseSemicolons": false, + "DontRepeatTypeInStaticProperties": false, + "FileScopedDeclarationPrivacy": true, + "FullyIndirectEnum": true, + "GroupNumericLiterals": true, + "IdentifiersMustBeASCII": true, + "NeverForceUnwrap": false, + "NeverUseForceTry": false, + "NeverUseImplicitlyUnwrappedOptionals": false, + "NoAccessLevelOnExtensionDeclaration": false, + "NoAssignmentInExpressions": true, + "NoBlockComments": false, + "NoCasesWithOnlyFallthrough": true, + "NoEmptyTrailingClosureParentheses": true, + "NoLabelsInCasePatterns": true, + "NoLeadingUnderscores": false, + "NoParensAroundConditions": true, + "NoPlaygroundLiterals": true, + "NoVoidReturnOnFunctionSignature": true, + "OmitExplicitReturns": false, + "OneCasePerLine": true, + "OneVariableDeclarationPerLine": true, + "OnlyOneTrailingClosureArgument": true, + "OrderedImports": true, + "ReplaceForEachWithForLoop": true, + "ReturnVoidInsteadOfEmptyTuple": true, + "TypeNamesShouldBeCapitalized": true, + "UseEarlyExits": false, + "UseExplicitNilCheckInConditions": true, + "UseLetInEveryBoundCaseVariable": false, + "UseShorthandTypeNames": true, + "UseSingleLinePropertyGetter": true, + "UseSynthesizedInitializer": false, + "UseTripleSlashForDocumentationComments": true, + "UseWhereClausesInForLoops": false, + "ValidateDocumentationComments": false + }, + "spacesAroundRangeFormationOperators": false, + "spacesBeforeEndOfLineComments": 2, + "version": 1, +} diff --git a/Package.swift b/Package.swift index 9b8bc6f8..5990260d 100644 --- a/Package.swift +++ b/Package.swift @@ -14,11 +14,11 @@ var useLocalDependencies: Bool { hasEnvironmentVariable("SWIFTCI_USE_LOCAL_DEPS" var dependencies: [Package.Dependency] { if useLocalDependencies { return [ - .package(path: "../swift-lmdb"), + .package(path: "../swift-lmdb") ] } else { return [ - .package(url: "https://github.com/swiftlang/swift-lmdb.git", branch: "main"), + .package(url: "https://github.com/swiftlang/swift-lmdb.git", branch: "main") ] } } @@ -29,19 +29,24 @@ let package = Package( products: [ .library( name: "IndexStoreDB", - targets: ["IndexStoreDB"]), + targets: ["IndexStoreDB"] + ), .library( name: "IndexStoreDB_CXX", - targets: ["IndexStoreDB_Index"]), + targets: ["IndexStoreDB_Index"] + ), .library( name: "ISDBTestSupport", - targets: ["ISDBTestSupport"]), + targets: ["ISDBTestSupport"] + ), .executable( name: "tibs", - targets: ["tibs"]), + targets: ["tibs"] + ), .library( name: "IndexStore", - targets: ["IndexStore"]), + targets: ["IndexStore"] + ), ], dependencies: dependencies, targets: [ @@ -57,7 +62,7 @@ let package = Package( .enableUpcomingFeature("InferIsolatedConformances"), .enableUpcomingFeature("NonisolatedNonsendingByDefault"), .enableExperimentalFeature("Lifetimes"), - .swiftLanguageMode(.v6) + .swiftLanguageMode(.v6), ] ), @@ -74,7 +79,8 @@ let package = Package( .target( name: "IndexStoreDB", dependencies: ["IndexStoreDB_CIndexStoreDB"], - exclude: ["CMakeLists.txt"]), + exclude: ["CMakeLists.txt"] + ), .testTarget( name: "IndexStoreDBTests", @@ -87,16 +93,19 @@ let package = Package( // The Test Index Build System (tibs) library. .target( name: "ISDBTibs", - dependencies: []), + dependencies: [] + ), .testTarget( name: "ISDBTibsTests", - dependencies: ["ISDBTibs", "ISDBTestSupport"]), + dependencies: ["ISDBTibs", "ISDBTestSupport"] + ), // Commandline tool for working with tibs projects. .executableTarget( name: "tibs", - dependencies: ["ISDBTibs"]), + dependencies: ["ISDBTibs"] + ), // Test support library, built on top of tibs. .target( @@ -107,7 +116,8 @@ let package = Package( ], linkerSettings: [ .linkedFramework("XCTest", .when(platforms: [.iOS, .macOS, .tvOS, .watchOS])) - ]), + ] + ), // MARK: C++ interface @@ -118,13 +128,15 @@ let package = Package( exclude: [ "CMakeLists.txt", "indexstore_functions.def", - ]), + ] + ), // C wrapper for IndexStoreDB_Index. .target( name: "IndexStoreDB_CIndexStoreDB", dependencies: ["IndexStoreDB_Index"], - exclude: ["CMakeLists.txt"]), + exclude: ["CMakeLists.txt"] + ), // The lmdb database layer. .target( @@ -134,20 +146,23 @@ let package = Package( .product(name: "CLMDB", package: "swift-lmdb"), ], exclude: [ - "CMakeLists.txt", - ]), + "CMakeLists.txt" + ] + ), // Core index types. .target( name: "IndexStoreDB_Core", dependencies: ["IndexStoreDB_Support"], - exclude: ["CMakeLists.txt"]), + exclude: ["CMakeLists.txt"] + ), // Support code that is generally useful to the C++ implementation. .target( name: "IndexStoreDB_Support", dependencies: ["IndexStoreDB_LLVMSupport"], - exclude: ["CMakeLists.txt"]), + exclude: ["CMakeLists.txt"] + ), // Copy of a subset of llvm's ADT and Support libraries. .target( @@ -178,7 +193,8 @@ let package = Package( "Windows/Signals.inc", "Windows/Threading.inc", "Windows/Watchdog.inc", - ]), + ] + ), ], swiftLanguageModes: [.v5], cxxLanguageStandard: .cxx17 diff --git a/Sources/ISDBTestSupport/ForwardingIndexDelegate.swift b/Sources/ISDBTestSupport/ForwardingIndexDelegate.swift index 5b063878..1ab4ce30 100644 --- a/Sources/ISDBTestSupport/ForwardingIndexDelegate.swift +++ b/Sources/ISDBTestSupport/ForwardingIndexDelegate.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import IndexStoreDB import Dispatch +import IndexStoreDB /// A wrapper that forwards to another delegate that can be mutated at runtime. final class ForwardingIndexDelegate: IndexDelegate { diff --git a/Sources/ISDBTestSupport/TestLocation.swift b/Sources/ISDBTestSupport/TestLocation.swift index 5b47333b..99b319be 100644 --- a/Sources/ISDBTestSupport/TestLocation.swift +++ b/Sources/ISDBTestSupport/TestLocation.swift @@ -40,7 +40,7 @@ public struct TestLocation: Hashable { } extension TestLocation: Comparable { - public static func <(a: TestLocation, b: TestLocation) -> Bool { + public static func < (a: TestLocation, b: TestLocation) -> Bool { return (a.url.path, a.line, a.utf8Column) < (b.url.path, b.line, b.utf8Column) } } @@ -55,14 +55,20 @@ extension SymbolLocation { moduleName: moduleName, isSystem: isSystem, line: loc.line, - utf8Column: loc.utf8Column) + utf8Column: loc.utf8Column + ) } } extension Symbol { /// Returns a SymbolOccurrence with the given location and roles. - public func at(_ location: TestLocation, moduleName: String = TestLocation.unknownModuleName, roles: SymbolRole, symbolProvider: SymbolProviderKind) -> SymbolOccurrence { + public func at( + _ location: TestLocation, + moduleName: String = TestLocation.unknownModuleName, + roles: SymbolRole, + symbolProvider: SymbolProviderKind + ) -> SymbolOccurrence { return self.at(SymbolLocation(location, moduleName: moduleName), symbolProvider: symbolProvider, roles: roles) } } diff --git a/Sources/ISDBTestSupport/TestLocationScanner.swift b/Sources/ISDBTestSupport/TestLocationScanner.swift index 2e59eaf1..33bf9337 100644 --- a/Sources/ISDBTestSupport/TestLocationScanner.swift +++ b/Sources/ISDBTestSupport/TestLocationScanner.swift @@ -91,10 +91,10 @@ public struct TestLocationScanner { let locIndex: String.Index if str[start] == "<" { nameStart = str.index(after: start) - locIndex = str.index(start, offsetBy: -2) // subtract '/' and '*' + locIndex = str.index(start, offsetBy: -2) // subtract '/' and '*' } else { nameStart = start - locIndex = str.index(after: i) // after trailing '/' + locIndex = str.index(after: i) // after trailing '/' } let name = String(str[nameStart.. Bool { switch ext { - case "swift", "c", "cpp", "m", "mm", "h", "hpp": - return true - default: - return false + case "swift", "c", "cpp", "m", "mm", "h", "hpp": + return true + default: + return false } } diff --git a/Sources/ISDBTestSupport/TestSources.swift b/Sources/ISDBTestSupport/TestSources.swift index a3473bfc..78cbcc41 100644 --- a/Sources/ISDBTestSupport/TestSources.swift +++ b/Sources/ISDBTestSupport/TestSources.swift @@ -93,7 +93,7 @@ public final class TestSources { /// * returns: The ChangeSet corresponding to these changes. /// * throws: Any file system errors seen while modifying the sources. If this happens, the state /// of the source files is not defined. - public func edit(_ block: (_ builder: inout ChangeBuilder) throws -> ()) throws -> ChangeSet { + public func edit(_ block: (_ builder: inout ChangeBuilder) throws -> Void) throws -> ChangeSet { var builder = ChangeBuilder() try block(&builder) try apply(builder.changes) diff --git a/Sources/ISDBTestSupport/TibsTestWorkspace.swift b/Sources/ISDBTestSupport/TibsTestWorkspace.swift index 6012adc5..ab217f20 100644 --- a/Sources/ISDBTestSupport/TibsTestWorkspace.swift +++ b/Sources/ISDBTestSupport/TibsTestWorkspace.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// -import IndexStoreDB -import ISDBTibs import Foundation +import ISDBTibs +import IndexStoreDB import XCTest /// Test workspace for a project using the tibs build system, providing convenient access to the @@ -77,8 +77,8 @@ public final class TibsTestWorkspace { tmpDir: URL, removeTmpDir: Bool = true, useExplicitOutputUnits: Bool = false, - toolchain: TibsToolchain) throws - { + toolchain: TibsToolchain + ) throws { self.projectDir = immutableProjectDir self.tmpDir = tmpDir self.mutableSources = false @@ -97,7 +97,8 @@ public final class TibsTestWorkspace { manifest: manifest, sourceRoot: projectDir, buildRoot: persistentBuildDir, - toolchain: toolchain) + toolchain: toolchain + ) try builder.writeBuildFiles() @@ -109,7 +110,8 @@ public final class TibsTestWorkspace { library: libIndexStore, delegate: wrapperDelegate, useExplicitOutputUnits: useExplicitOutputUnits, - listenToUnitEvents: false) + listenToUnitEvents: false + ) } /// Creates a tibs test workspace and copies the sources to a temporary location so that they can @@ -128,8 +130,8 @@ public final class TibsTestWorkspace { tmpDir: URL, removeTmpDir: Bool = true, useExplicitOutputUnits: Bool = false, - toolchain: TibsToolchain) throws - { + toolchain: TibsToolchain + ) throws { self.projectDir = projectDir self.tmpDir = tmpDir self.mutableSources = true @@ -150,7 +152,8 @@ public final class TibsTestWorkspace { manifest: manifest, sourceRoot: sourceDir, buildRoot: buildDir, - toolchain: toolchain) + toolchain: toolchain + ) try builder.writeBuildFiles() @@ -162,7 +165,8 @@ public final class TibsTestWorkspace { library: libIndexStore, delegate: wrapperDelegate, useExplicitOutputUnits: useExplicitOutputUnits, - listenToUnitEvents: false) + listenToUnitEvents: false + ) } static func databaseDirIn(_ tmpDir: URL) -> URL { @@ -188,7 +192,8 @@ public final class TibsTestWorkspace { waitUntilDoneInitializing: waitUntilDoneInitializing, enableOutOfDateFileWatching: enableOutOfDateFileWatching, listenToUnitEvents: listenToUnitEvents, - prefixMappings: prefixMappings) + prefixMappings: prefixMappings + ) } deinit { @@ -198,17 +203,17 @@ public final class TibsTestWorkspace { } public func buildAndIndex() throws { - try builder.build() - index.pollForUnitChangesAndWait() - } + try builder.build() + index.pollForUnitChangesAndWait() + } public func testLoc(_ name: String) -> TestLocation { sources.locations[name]! } /// Perform a group of edits to the project sources and optionally rebuild. public func edit( rebuild: Bool = false, - _ block: (inout TestSources.ChangeBuilder, _ current: SourceFileCache) throws -> ()) throws - { + _ block: (inout TestSources.ChangeBuilder, _ current: SourceFileCache) throws -> Void + ) throws { precondition(mutableSources, "tried to edit in immutable workspace") builder.toolchain.sleepForTimestamp() @@ -249,12 +254,17 @@ extension XCTestCase { tmpDir: URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("isdb-test-data/\(testDirName)", isDirectory: true), useExplicitOutputUnits: useExplicitOutputUnits, - toolchain: toolchain) + toolchain: toolchain + ) if workspace.builder.targets.contains(where: { target in !target.clangTUs.isEmpty }) - && !toolchain.clangHasIndexSupport { - fputs("warning: skipping test because '\(toolchain.clang.path)' does not have indexstore " + - "support; use swift-clang\n", stderr) + && !toolchain.clangHasIndexSupport + { + fputs( + "warning: skipping test because '\(toolchain.clang.path)' does not have indexstore " + + "support; use swift-clang\n", + stderr + ) return nil } @@ -279,12 +289,17 @@ extension XCTestCase { .appendingPathComponent(name, isDirectory: true), tmpDir: URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("isdb-test-data/\(testDirName)", isDirectory: true), - toolchain: toolchain) + toolchain: toolchain + ) if workspace.builder.targets.contains(where: { target in !target.clangTUs.isEmpty }) - && !toolchain.clangHasIndexSupport { - fputs("warning: skipping test because '\(toolchain.clang.path)' does not have indexstore " + - "support; use swift-clang\n", stderr) + && !toolchain.clangHasIndexSupport + { + fputs( + "warning: skipping test because '\(toolchain.clang.path)' does not have indexstore " + + "support; use swift-clang\n", + stderr + ) return nil } @@ -294,21 +309,21 @@ extension XCTestCase { /// The bundle of the currently executing test. public static var testBundle: Bundle = { #if os(macOS) - if let bundle = Bundle.allBundles.first(where: { $0.bundlePath.hasSuffix(".xctest") }) { - return bundle - } - fatalError("couldn't find the test bundle") + if let bundle = Bundle.allBundles.first(where: { $0.bundlePath.hasSuffix(".xctest") }) { + return bundle + } + fatalError("couldn't find the test bundle") #else - return Bundle.main + return Bundle.main #endif }() /// The path to the built products directory. public static let productsDirectory: URL = { #if os(macOS) - return testBundle.bundleURL.deletingLastPathComponent() + return testBundle.bundleURL.deletingLastPathComponent() #else - return testBundle.bundleURL + return testBundle.bundleURL #endif }() @@ -342,7 +357,7 @@ extension XCTestCase { } let className = name.dropFirst(2).prefix(while: { $0 != " " }) - let methodName = name[className.endIndex...].dropFirst().prefix(while: { $0 != "]"}) + let methodName = name[className.endIndex...].dropFirst().prefix(while: { $0 != "]" }) return "\(className).\(methodName)" } } diff --git a/Sources/ISDBTestSupport/XCTestAssertions.swift b/Sources/ISDBTestSupport/XCTestAssertions.swift index 7f81ae24..cf86246f 100644 --- a/Sources/ISDBTestSupport/XCTestAssertions.swift +++ b/Sources/ISDBTestSupport/XCTestAssertions.swift @@ -21,21 +21,18 @@ extension SymbolLocation { // the module name string in every symbol occurrence test. // Instead we ignore the module name if this `SymbolLocation` was initialized from // a test location without an explicit module name. - return path == other.path && - (moduleName == TestLocation.unknownModuleName || other.moduleName == TestLocation.unknownModuleName || moduleName == other.moduleName) && - isSystem == other.isSystem && - line == other.line && - utf8Column == other.utf8Column + return path == other.path + && (moduleName == TestLocation.unknownModuleName || other.moduleName == TestLocation.unknownModuleName + || moduleName == other.moduleName) + && isSystem == other.isSystem && line == other.line && utf8Column == other.utf8Column } } extension SymbolOccurrence { /// Special equality check for testing. func testEqual(with other: SymbolOccurrence) -> Bool { - return symbol == other.symbol && - location.testEqual(with: other.location) && - roles == other.roles && - relations == other.relations + return symbol == other.symbol && location.testEqual(with: other.location) && roles == other.roles + && relations == other.relations } } @@ -57,8 +54,8 @@ public func checkOccurrences( allowAdditionalRoles: Bool = true, expected: [SymbolOccurrence], file: StaticString = #file, - line: UInt = #line) -{ + line: UInt = #line +) { var expected: [SymbolOccurrence] = expected var actual: [SymbolOccurrence] = actual diff --git a/Sources/ISDBTibs/JSONCompilationDatabase.swift b/Sources/ISDBTibs/JSONCompilationDatabase.swift index 08e8ec33..33c20bef 100644 --- a/Sources/ISDBTibs/JSONCompilationDatabase.swift +++ b/Sources/ISDBTibs/JSONCompilationDatabase.swift @@ -12,7 +12,6 @@ import struct Foundation.URL - /// A JSON clang-compatible compilation database. /// /// * Note: this only supports the "arguments" form, not "command". It is primarily suitable for diff --git a/Sources/ISDBTibs/OutputFileMap.swift b/Sources/ISDBTibs/OutputFileMap.swift index 5b311c3d..5079d0a5 100644 --- a/Sources/ISDBTibs/OutputFileMap.swift +++ b/Sources/ISDBTibs/OutputFileMap.swift @@ -23,7 +23,12 @@ public struct OutputFileMap { public var swiftdoc: String? public var dependencies: String? - public init(object: String? = nil, swiftmodule: String? = nil, swiftdoc: String? = nil, dependencies: String? = nil) { + public init( + object: String? = nil, + swiftmodule: String? = nil, + swiftdoc: String? = nil, + dependencies: String? = nil + ) { self.object = object self.swiftmodule = swiftmodule self.swiftdoc = swiftdoc @@ -85,7 +90,7 @@ extension OutputFileMap: Codable { } extension OutputFileMap: Equatable { - public static func ==(a: OutputFileMap, b: OutputFileMap) -> Bool { + public static func == (a: OutputFileMap, b: OutputFileMap) -> Bool { return a.order == b.order && a.values.elementsEqual(b.values) } } diff --git a/Sources/ISDBTibs/Process.swift b/Sources/ISDBTibs/Process.swift index 4f845570..6fa525d7 100644 --- a/Sources/ISDBTibs/Process.swift +++ b/Sources/ISDBTibs/Process.swift @@ -53,9 +53,11 @@ extension Process { if p.terminationReason != .exit || p.terminationStatus != 0 { throw TibsProcessError.nonZeroExit( - p.terminationReason, p.terminationStatus, + p.terminationReason, + p.terminationStatus, stdout: String(data: dataOut, encoding: .utf8), - stderr: String(data: dataErr, encoding: .utf8)) + stderr: String(data: dataErr, encoding: .utf8) + ) } guard let str = String(data: dataOut, encoding: .utf8) else { diff --git a/Sources/ISDBTibs/TibsBuilder.swift b/Sources/ISDBTibs/TibsBuilder.swift index c8e637a5..4b6cc6c9 100644 --- a/Sources/ISDBTibs/TibsBuilder.swift +++ b/Sources/ISDBTibs/TibsBuilder.swift @@ -24,7 +24,7 @@ public final class TibsBuilder { public var indexstore: URL { buildRoot.appendingPathComponent("index", isDirectory: true) } public var indexOutputPaths: [URL] { - return targets.flatMap{ $0.indexOutputPaths }.map{ buildRoot.appendingPathComponent($0, isDirectory: false) } + return targets.flatMap { $0.indexOutputPaths }.map { buildRoot.appendingPathComponent($0, isDirectory: false) } } public enum Error: Swift.Error { @@ -62,7 +62,8 @@ public final class TibsBuilder { object: "\(name)-\(basename).o", swiftmodule: "\(name)-\(basename).swiftmodule~partial", swiftdoc: "\(name)-\(basename).swiftdoc~partial", - dependencies: "\(name)-\(basename).d") + dependencies: "\(name)-\(basename).d" + ) } swiftModule = TibsResolvedTarget.SwiftModule( @@ -74,7 +75,8 @@ public final class TibsBuilder { outputFileMap: outputFileMap, bridgingHeader: bridgingHeader, moduleDeps: targetDesc.dependencies?.map { "\($0).swiftmodule" } ?? [], - sdk: TibsBuilder.defaultSDKPath) + sdk: TibsBuilder.defaultSDKPath + ) } var clangTUs: [TibsResolvedTarget.ClangTU] = [] @@ -82,12 +84,13 @@ public final class TibsBuilder { let cu = TibsResolvedTarget.ClangTU( extraArgs: clangFlags, source: source, - importPaths: [/*buildRoot*/".", sourceRoot.path], + importPaths: [ /*buildRoot*/".", sourceRoot.path], // FIXME: this should be the -Swift.h file, but ninja doesn't support // having multiple output files when using gcc-style dependencies, so // use the .swiftmodule. generatedHeaderDep: swiftSources.isEmpty ? nil : "\(name).swiftmodule", - outputPath: "\(name)-\(source.lastPathComponent).o") + outputPath: "\(name)-\(source.lastPathComponent).o" + ) clangTUs.append(cu) } @@ -95,7 +98,8 @@ public final class TibsBuilder { name: name, swiftModule: swiftModule, clangTUs: clangTUs, - dependencies: targetDesc.dependencies ?? []) + dependencies: targetDesc.dependencies ?? [] + ) targets.append(target) if targetsByName.updateValue(target, forKey: name) != nil { @@ -137,8 +141,8 @@ extension TibsBuilder { var result = Set() while let range = out.range(of: "] Indexing ", range: rest) { - let srcEnd = out[range.upperBound...].firstIndex(where: {$0.isNewline}) ?? rest.upperBound - let target = String(out[range.upperBound ..< srcEnd]) + let srcEnd = out[range.upperBound...].firstIndex(where: { $0.isNewline }) ?? rest.upperBound + let target = String(out[range.upperBound..(to stream: inout Output) { - stream.write(""" + stream.write( + """ # Generated by tibs. DO NOT EDIT! ninja_required_version = 1.5 - """) + """ + ) } public func writeNinjaRules(to stream: inout Output) { -#if os(Windows) + #if os(Windows) let callCmd = "cmd.exe /C " let copyCmd = "copy NUL $out" -#else + #else let callCmd = "" let copyCmd = "touch $out" -#endif + #endif // FIXME: rdar://83355591 avoid -c, since we don't want to spend time writing .o files. - let swiftIndexCommand = callCmd + """ - \(escapeCommand([toolchain.swiftc.path])) $in $IMPORT_PATHS -module-name $MODULE_NAME \ - -index-store-path index -index-ignore-system-modules \ - -output-file-map $OUTPUT_FILE_MAP \ - -emit-module -emit-module-path $MODULE_PATH -emit-dependencies \ - -pch-output-dir pch -module-cache-path ModuleCache \ - -c \ - $EMIT_HEADER $BRIDGING_HEADER $SDK $EXTRA_ARGS \ - && \(toolchain.tibs.path) swift-deps-merge $out $DEP_FILES > $out.d - """ - - let ccIndexCommand = callCmd + """ - \(escapeCommand([toolchain.clang.path])) -fsyntax-only $in $IMPORT_PATHS -index-store-path index \ - -index-ignore-system-symbols -fmodules -fmodules-cache-path=ModuleCache \ - -MMD -MF $OUTPUT_NAME.d -o $out $EXTRA_ARGS && \(copyCmd) + let swiftIndexCommand = + callCmd + """ + \(escapeCommand([toolchain.swiftc.path])) $in $IMPORT_PATHS -module-name $MODULE_NAME \ + -index-store-path index -index-ignore-system-modules \ + -output-file-map $OUTPUT_FILE_MAP \ + -emit-module -emit-module-path $MODULE_PATH -emit-dependencies \ + -pch-output-dir pch -module-cache-path ModuleCache \ + -c \ + $EMIT_HEADER $BRIDGING_HEADER $SDK $EXTRA_ARGS \ + && \(toolchain.tibs.path) swift-deps-merge $out $DEP_FILES > $out.d + """ + + let ccIndexCommand = + callCmd + """ + \(escapeCommand([toolchain.clang.path])) -fsyntax-only $in $IMPORT_PATHS -index-store-path index \ + -index-ignore-system-symbols -fmodules -fmodules-cache-path=ModuleCache \ + -MMD -MF $OUTPUT_NAME.d -o $out $EXTRA_ARGS && \(copyCmd) + """ + stream.write( """ - stream.write(""" rule swiftc_index description = Indexing Swift Module $MODULE_NAME command = \(swiftIndexCommand) @@ -332,7 +353,8 @@ extension TibsBuilder { command = \(ccIndexCommand) depfile = $out.d deps = gcc - """) + """ + ) } public func writeNinjaSnippet(for target: TibsResolvedTarget, to stream: inout Output) { @@ -347,18 +369,23 @@ extension TibsBuilder { outputs.append(contentsOf: out) stream.write("\n\n") } - stream.write(""" + stream.write( + """ build \(target.name): phony \(escapePath(path: outputs.joined(separator: " "))) - """) + """ + ) } /// - Returns: the list of outputs. - public func writeNinjaSnippet(for module: TibsResolvedTarget.SwiftModule, to stream: inout Output) -> [String] { + public func writeNinjaSnippet( + for module: TibsResolvedTarget.SwiftModule, + to stream: inout Output + ) -> [String] { // FIXME: the generated -Swift.h header should be considered an output, but ninja does not // support multiple outputs when using gcc-style .d files. - let outputs = [module.emitModulePath, /*module.emitHeaderPath*/] + let outputs = [module.emitModulePath /*module.emitHeaderPath*/] // FIXME: some of these are deleted by the compiler!? // outputs += target.outputFileMap.allOutputs @@ -369,7 +396,8 @@ extension TibsBuilder { deps.append(bridgingHeader.path) } - stream.write(""" + stream.write( + """ build \(escapePath(path: outputs.joined(separator: " "))) : \ swiftc_index \(module.sources.map { escapePath(path: $0.path) }.joined(separator: " ")) \ | \(escapePath(path: deps.joined(separator: " "))) @@ -382,21 +410,27 @@ extension TibsBuilder { DEP_FILES = \(module.outputFileMap.values.compactMap { $0.dependencies }.joined(separator: " ")) OUTPUT_FILE_MAP = \(module.outputFileMapPath) SDK = \(module.sdk.map { "-sdk \($0)" } ?? "") - """) + """ + ) return outputs } /// - Returns: the list of outputs. - public func writeNinjaSnippet(for tu: TibsResolvedTarget.ClangTU, to stream: inout Output) -> [String] { + public func writeNinjaSnippet( + for tu: TibsResolvedTarget.ClangTU, + to stream: inout Output + ) -> [String] { - stream.write(""" + stream.write( + """ build \(escapePath(path: tu.outputPath)): \ cc_index \(escapePath(path: tu.source.path)) | \(escapePath(path: toolchain.clang.path)) \(tu.generatedHeaderDep ?? "") IMPORT_PATHS = \(tu.importPaths.map { "-I \($0)" }.joined(separator: " ")) OUTPUT_NAME = \(tu.outputPath) EXTRA_ARGS = \(tu.extraArgs.joined(separator: " ")) - """) + """ + ) return [tu.outputPath] } @@ -427,7 +461,7 @@ func quoteWindowsCommandLine(_ commandLine: [String]) -> String { func quoteWindowsCommandArg(arg: String) -> String { // Windows escaping, adapted from Daniel Colascione's "Everyone quotes // command line arguments the wrong way" - Microsoft Developer Blog - if !arg.contains(where: {" \t\n\"".contains($0)}) { + if !arg.contains(where: { " \t\n\"".contains($0) }) { return arg } @@ -462,7 +496,7 @@ func quoteWindowsCommandLine(_ commandLine: [String]) -> String { break } let backslashCount = unquoted.distance(from: unquoted.startIndex, to: firstNonBackslash) - if (unquoted[firstNonBackslash] == "\"") { + if unquoted[firstNonBackslash] == "\"" { // This is a string of \ followed by a " e.g. foo\"bar. Escape the // backslashes and the quote quoted.append(String(repeating: "\\", count: backslashCount * 2 + 1)) @@ -484,11 +518,11 @@ func quoteWindowsCommandLine(_ commandLine: [String]) -> String { func escapeCommand(_ args: [String]) -> String { let escaped: String -#if os(Windows) + #if os(Windows) escaped = quoteWindowsCommandLine(args) -#else + #else escaped = args.joined(separator: " ") -#endif + #endif return escapePath(path: escaped) } @@ -497,4 +531,3 @@ func escapePath(path: String) -> String { // since those are terminated by a : return path.replacingOccurrences(of: ":", with: "$:") } - diff --git a/Sources/ISDBTibs/TibsManifest.swift b/Sources/ISDBTibs/TibsManifest.swift index 2c52ad1f..a65546c1 100644 --- a/Sources/ISDBTibs/TibsManifest.swift +++ b/Sources/ISDBTibs/TibsManifest.swift @@ -57,8 +57,8 @@ public struct TibsManifest: Equatable { clangFlags: [String]? = nil, sources: [String], bridgingHeader: String? = nil, - dependencies: [String]? = nil) - { + dependencies: [String]? = nil + ) { self.name = name self.swiftFlags = swiftFlags self.clangFlags = clangFlags diff --git a/Sources/ISDBTibs/TibsResolvedTarget.swift b/Sources/ISDBTibs/TibsResolvedTarget.swift index 14f06392..da0ed04c 100644 --- a/Sources/ISDBTibs/TibsResolvedTarget.swift +++ b/Sources/ISDBTibs/TibsResolvedTarget.swift @@ -34,7 +34,7 @@ public final class TibsResolvedTarget { public var sdk: String? public var indexOutputPaths: [String] { - return outputFileMap.values.compactMap{ $0.object ?? $0.swiftmodule } + return outputFileMap.values.compactMap { $0.object ?? $0.swiftmodule } } public init( @@ -46,8 +46,8 @@ public final class TibsResolvedTarget { outputFileMap: OutputFileMap, bridgingHeader: URL? = nil, moduleDeps: [String] = [], - sdk: String? = nil) - { + sdk: String? = nil + ) { self.name = name self.extraArgs = extraArgs self.sources = sources @@ -72,8 +72,8 @@ public final class TibsResolvedTarget { source: URL, importPaths: [String] = [], generatedHeaderDep: String? = nil, - outputPath: String) - { + outputPath: String + ) { self.extraArgs = extraArgs self.source = source self.importPaths = importPaths @@ -88,7 +88,7 @@ public final class TibsResolvedTarget { public var dependencies: [String] public var indexOutputPaths: [String] { - return clangTUs.map{ $0.outputPath } + (swiftModule?.indexOutputPaths ?? []) + return clangTUs.map { $0.outputPath } + (swiftModule?.indexOutputPaths ?? []) } public init(name: String, swiftModule: SwiftModule?, clangTUs: [ClangTU], dependencies: [String]) { @@ -100,7 +100,7 @@ public final class TibsResolvedTarget { } extension TibsResolvedTarget: Equatable { - public static func ==(a: TibsResolvedTarget, b: TibsResolvedTarget) -> Bool { + public static func == (a: TibsResolvedTarget, b: TibsResolvedTarget) -> Bool { if a === b { return true } diff --git a/Sources/ISDBTibs/TibsToolchain.swift b/Sources/ISDBTibs/TibsToolchain.swift index 59515bdd..cba7de3b 100644 --- a/Sources/ISDBTibs/TibsToolchain.swift +++ b/Sources/ISDBTibs/TibsToolchain.swift @@ -11,6 +11,7 @@ //===----------------------------------------------------------------------===// import Foundation + #if os(Windows) import WinSDK #elseif canImport(Android) @@ -29,13 +30,15 @@ public final class TibsToolchain { self.swiftc = swiftc self.clang = clang -#if os(Windows) + #if os(Windows) let dylibFolder = "bin" -#else + #else let dylibFolder = "lib" -#endif + #endif - self.libIndexStore = libIndexStore ?? swiftc + self.libIndexStore = + libIndexStore + ?? swiftc .deletingLastPathComponent() .deletingLastPathComponent() .appendingPathComponent("\(dylibFolder)/libIndexStore\(TibsToolchain.dylibExt)", isDirectory: false) @@ -44,16 +47,16 @@ public final class TibsToolchain { self.ninja = ninja } -#if os(macOS) + #if os(macOS) public static let dylibExt = ".dylib" public static let execExt = "" -#elseif os(Windows) + #elseif os(Windows) public static let dylibExt = ".dll" public static let execExt = ".exe" -#else + #else public static let dylibExt = ".so" public static let execExt = "" -#endif + #endif public private(set) lazy var clangHasIndexSupport: Bool = { // Check clang -help for index store support. It would be better to check @@ -86,8 +89,8 @@ public final class TibsToolchain { guard let maj = Int(String(components[0])), let min = Int(String(components[1])), let patch = components.count > 2 ? Int(String(components[2])) : 0 - else { - fatalError("could not parsed ninja --version '\(out)'") + else { + fatalError("could not parsed ninja --version '\(out)'") } return (maj, min, patch) }() @@ -112,15 +115,18 @@ public final class TibsToolchain { if usec > 0 { if let warning = warning { let fsec = Float(usec) / 1_000_000 - fputs("warning: waiting \(fsec) second\(fsec == 1.0 ? "" : "s") to ensure file timestamp " + - "differs; \(warning)\n", stderr) + fputs( + "warning: waiting \(fsec) second\(fsec == 1.0 ? "" : "s") to ensure file timestamp " + + "differs; \(warning)\n", + stderr + ) } -#if os(Windows) + #if os(Windows) Sleep(usec / 1000) -#else + #else usleep(usec) -#endif + #endif } } } @@ -147,7 +153,7 @@ extension TibsToolchain { fatalError("toolchain must contain 'swiftc\(TibsToolchain.execExt)' \(envVar)=\(path)") } if !fm.fileExists(atPath: clang!.path) { - clang = nil // try to find by PATH + clang = nil // try to find by PATH } } @@ -157,25 +163,25 @@ extension TibsToolchain { var buildURL: URL? = nil #if os(macOS) - // If we are running under xctest, the build directory is the .xctest bundle. - for bundle in Bundle.allBundles { - if bundle.bundlePath.hasSuffix(".xctest") { - buildURL = bundle.bundleURL.deletingLastPathComponent() - break - } + // If we are running under xctest, the build directory is the .xctest bundle. + for bundle in Bundle.allBundles { + if bundle.bundlePath.hasSuffix(".xctest") { + buildURL = bundle.bundleURL.deletingLastPathComponent() + break } - // Otherwise, assume it is the main bundle. - if buildURL == nil { - buildURL = Bundle.main.bundleURL - } - #else + } + // Otherwise, assume it is the main bundle. + if buildURL == nil { buildURL = Bundle.main.bundleURL + } + #else + buildURL = Bundle.main.bundleURL #endif if let buildURL = buildURL { tibs = buildURL.appendingPathComponent("tibs\(TibsToolchain.execExt)", isDirectory: false) if !fm.fileExists(atPath: tibs!.path) { - tibs = nil // try to find by PATH + tibs = nil // try to find by PATH } } @@ -185,13 +191,15 @@ extension TibsToolchain { ninja = ninja ?? findTool(name: "ninja\(TibsToolchain.execExt)") guard swiftc != nil, clang != nil, tibs != nil, ninja != nil else { - fatalError(""" + fatalError( + """ missing TibsToolchain component; had swiftc = \(swiftc?.path ?? "nil") clang = \(clang?.path ?? "nil") tibs = \(tibs?.path ?? "nil") ninja = \(ninja?.path ?? "nil") - """) + """ + ) } return TibsToolchain(swiftc: swiftc!, clang: clang!, tibs: tibs!, ninja: ninja) @@ -200,27 +208,27 @@ extension TibsToolchain { /// Returns the path to the given tool, as found by `xcrun --find` on macOS, or `which` on Linux. public func findTool(name: String) -> URL? { -#if os(macOS) + #if os(macOS) let cmd = ["/usr/bin/xcrun", "--find", name] -#elseif os(Windows) + #elseif os(Windows) var buf = [WCHAR](repeating: 0, count: Int(MAX_PATH)) GetWindowsDirectoryW(&buf, DWORD(MAX_PATH)) var wherePath = String(decodingCString: &buf, as: UTF16.self) .appendingPathComponent("system32") .appendingPathComponent("where.exe") let cmd = [wherePath, name] -#elseif os(Android) + #elseif os(Android) let cmd = ["/system/bin/which", name] -#else + #else let cmd = ["/usr/bin/which", name] -#endif + #endif guard var path = try? Process.tibs_checkNonZeroExit(arguments: cmd) else { return nil } -#if os(Windows) + #if os(Windows) path = String((path.split { $0.isNewline })[0]) -#endif + #endif path = path.trimmingCharacters(in: .whitespacesAndNewlines) return URL(fileURLWithPath: path, isDirectory: false) } diff --git a/Sources/IndexStoreDB/IndexStoreDB.swift b/Sources/IndexStoreDB/IndexStoreDB.swift index c3f266aa..2445c78f 100644 --- a/Sources/IndexStoreDB/IndexStoreDB.swift +++ b/Sources/IndexStoreDB/IndexStoreDB.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import IndexStoreDB_CIndexStoreDB import Foundation +@_implementationOnly import IndexStoreDB_CIndexStoreDB + // For `strdup` #if canImport(Glibc) import Glibc @@ -58,7 +58,7 @@ public enum SymbolProviderKind: Sendable { public final class IndexStoreDB { let delegate: IndexDelegate? - let impl: UnsafeMutableRawPointer // indexstoredb_index_t + let impl: UnsafeMutableRawPointer // indexstoredb_index_t /// Create or open an IndexStoreDB at the given `databasePath`. /// @@ -90,11 +90,12 @@ public final class IndexStoreDB { ) throws { self.delegate = delegate - let libProviderFunc: indexstore_library_provider_t = { (cpath: UnsafePointer) -> indexstoredb_indexstore_library_t? in + let libProviderFunc: indexstore_library_provider_t = { + (cpath: UnsafePointer) -> indexstoredb_indexstore_library_t? in return library?.library } - let delegateFunc = { [weak delegate] (event: indexstoredb_delegate_event_t) -> () in + let delegateFunc = { [weak delegate] (event: indexstoredb_delegate_event_t) -> Void in delegate?.handleEvent(event) } let options = indexstoredb_creation_options_create() @@ -113,11 +114,16 @@ public final class IndexStoreDB { } var error: indexstoredb_error_t? = nil - guard let index = indexstoredb_index_create( - storePath, databasePath, - libProviderFunc, delegateFunc, - options, &error - ) else { + guard + let index = indexstoredb_index_create( + storePath, + databasePath, + libProviderFunc, + delegateFunc, + options, + &error + ) + else { defer { indexstoredb_error_dispose(error) } throw IndexStoreDBError.create(error?.description ?? "unknown") } @@ -131,9 +137,9 @@ public final class IndexStoreDB { /// * cIndex: An existing `indexstoredb_index_t` object. /// * delegate: The delegate to receive index events. public init( - cIndex: UnsafeMutableRawPointer/*indexstoredb_index_t*/, - delegate: IndexDelegate? = nil) - { + cIndex: UnsafeMutableRawPointer /*indexstoredb_index_t*/, + delegate: IndexDelegate? = nil + ) { self.delegate = delegate self.impl = cIndex @@ -183,7 +189,11 @@ public final class IndexStoreDB { /// Stop iteration if `body` returns `false`. /// - Returns: `false` if iteration was terminated by `body` returning `true` or `true` if iteration finished. @discardableResult - public func forEachSymbolOccurrence(byUSR usr: String, roles: SymbolRole, _ body: (SymbolOccurrence) -> Bool) -> Bool { + public func forEachSymbolOccurrence( + byUSR usr: String, + roles: SymbolRole, + _ body: (SymbolOccurrence) -> Bool + ) -> Bool { return withoutActuallyEscaping(body) { body in return indexstoredb_index_symbol_occurrences_by_usr(impl, usr, roles.rawValue) { occur in return body(SymbolOccurrence(occur)) @@ -202,7 +212,11 @@ public final class IndexStoreDB { } @discardableResult - public func forEachRelatedSymbolOccurrence(byUSR usr: String, roles: SymbolRole, _ body: (SymbolOccurrence) -> Bool) -> Bool { + public func forEachRelatedSymbolOccurrence( + byUSR usr: String, + roles: SymbolRole, + _ body: (SymbolOccurrence) -> Bool + ) -> Bool { return withoutActuallyEscaping(body) { body in return indexstoredb_index_related_symbol_occurrences_by_usr(impl, usr, roles.rawValue) { occur in @@ -220,7 +234,10 @@ public final class IndexStoreDB { return result } - @discardableResult public func forEachCanonicalSymbolOccurrence(byName: String, body: (SymbolOccurrence) -> Bool) -> Bool { + @discardableResult public func forEachCanonicalSymbolOccurrence( + byName: String, + body: (SymbolOccurrence) -> Bool + ) -> Bool { return withoutActuallyEscaping(body) { body in return indexstoredb_index_canonical_symbol_occurences_by_name(impl, byName) { occur in return body(SymbolOccurrence(occur)) @@ -272,8 +289,8 @@ public final class IndexStoreDB { anchorStart: anchorStart, anchorEnd: anchorEnd, subsequence: subsequence, - ignoreCase: ignoreCase) - { occur in + ignoreCase: ignoreCase + ) { occur in result.append(occur) return true } @@ -282,7 +299,9 @@ public final class IndexStoreDB { @discardableResult public func forEachMainFileContainingFile( - path: String, crossLanguage: Bool, body: (String) -> Bool + path: String, + crossLanguage: Bool, + body: (String) -> Bool ) -> Bool { let fromSwift = path.hasSuffix(".swift") return withoutActuallyEscaping(body) { body in @@ -338,8 +357,8 @@ public final class IndexStoreDB { public func filesIncludedByFile(path: String) -> [String] { var result: [String] = [] foreachFileIncludedByFile(path: path) { targetPath in - result.append(targetPath) - return true + result.append(targetPath) + return true } return result } @@ -357,11 +376,11 @@ public final class IndexStoreDB { public func filesIncludingFile(path: String) -> [String] { var result: [String] = [] foreachFileIncludingFile(path: path) { targetPath in - result.append(targetPath) - return true - } - return result + result.append(targetPath) + return true } + return result + } /// A recorded header `#include` from a unit file. public struct UnitIncludeEntry: Equatable { @@ -387,7 +406,8 @@ public final class IndexStoreDB { let sourcePathStr = String(cString: sourcePath) let targetPathStr = String(cString: targetPath) return body( - UnitIncludeEntry(sourcePath: sourcePathStr, targetPath: targetPathStr, line: line)) + UnitIncludeEntry(sourcePath: sourcePathStr, targetPath: targetPathStr, line: line) + ) } } } @@ -515,7 +535,7 @@ public protocol IndexStoreLibraryProvider { } public class IndexStoreLibrary { - let library: UnsafeMutableRawPointer // indexstoredb_indexstore_library_t + let library: UnsafeMutableRawPointer // indexstoredb_indexstore_library_t public var version: Version { return Version(encoded: Int(indexstoredb_store_version(library))) diff --git a/Sources/IndexStoreDB/IndexStoreDBError.swift b/Sources/IndexStoreDB/IndexStoreDBError.swift index b6292486..d82f6b52 100644 --- a/Sources/IndexStoreDB/IndexStoreDBError.swift +++ b/Sources/IndexStoreDB/IndexStoreDBError.swift @@ -10,11 +10,10 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import IndexStoreDB_CIndexStoreDB - import Foundation +@_implementationOnly import IndexStoreDB_CIndexStoreDB + public enum IndexStoreDBError: Error, Sendable { case create(String) case loadIndexStore(String) diff --git a/Sources/IndexStoreDB/Symbol.swift b/Sources/IndexStoreDB/Symbol.swift index 83c3c550..c8532bdc 100644 --- a/Sources/IndexStoreDB/Symbol.swift +++ b/Sources/IndexStoreDB/Symbol.swift @@ -10,8 +10,7 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import IndexStoreDB_CIndexStoreDB +@_implementationOnly import IndexStoreDB_CIndexStoreDB public enum IndexSymbolKind: Hashable, Sendable { case unknown @@ -76,7 +75,7 @@ public struct Symbol: Hashable, Sendable { } extension Symbol: Comparable { - public static func <(a: Symbol, b: Symbol) -> Bool { + public static func < (a: Symbol, b: Symbol) -> Bool { return (a.usr, a.name) < (b.usr, b.name) } } @@ -110,7 +109,11 @@ extension Symbol { } /// Returns a SymbolOccurrence with the given location and roles. - public func at(_ location: SymbolLocation, symbolProvider: SymbolProviderKind, roles: SymbolRole) -> SymbolOccurrence { + public func at( + _ location: SymbolLocation, + symbolProvider: SymbolProviderKind, + roles: SymbolRole + ) -> SymbolOccurrence { return SymbolOccurrence(symbol: self, location: location, roles: roles, symbolProvider: symbolProvider) } } diff --git a/Sources/IndexStoreDB/SymbolLocation.swift b/Sources/IndexStoreDB/SymbolLocation.swift index defc0293..e6001a59 100644 --- a/Sources/IndexStoreDB/SymbolLocation.swift +++ b/Sources/IndexStoreDB/SymbolLocation.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import IndexStoreDB_CIndexStoreDB import Foundation +@_implementationOnly import IndexStoreDB_CIndexStoreDB + public struct SymbolLocation: Equatable, Sendable { public var path: String /// The date at which the unit file that contains a symbol has last been modified. @@ -34,7 +34,7 @@ public struct SymbolLocation: Equatable, Sendable { } extension SymbolLocation: Comparable { - public static func <(a: SymbolLocation, b: SymbolLocation) -> Bool { + public static func < (a: SymbolLocation, b: SymbolLocation) -> Bool { return (a.path, a.moduleName, a.line, a.utf8Column, a.isSystem ? 1 : 0) < (b.path, a.moduleName, b.line, b.utf8Column, b.isSystem ? 1 : 0) } diff --git a/Sources/IndexStoreDB/SymbolOccurrence.swift b/Sources/IndexStoreDB/SymbolOccurrence.swift index 58141a44..01cb437d 100644 --- a/Sources/IndexStoreDB/SymbolOccurrence.swift +++ b/Sources/IndexStoreDB/SymbolOccurrence.swift @@ -10,8 +10,7 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import IndexStoreDB_CIndexStoreDB +@_implementationOnly import IndexStoreDB_CIndexStoreDB public struct SymbolOccurrence: Equatable, Sendable { public var symbol: Symbol @@ -20,7 +19,13 @@ public struct SymbolOccurrence: Equatable, Sendable { public var symbolProvider: SymbolProviderKind public var relations: [SymbolRelation] - public init(symbol: Symbol, location: SymbolLocation, roles: SymbolRole, symbolProvider: SymbolProviderKind, relations: [SymbolRelation] = []) { + public init( + symbol: Symbol, + location: SymbolLocation, + roles: SymbolRole, + symbolProvider: SymbolProviderKind, + relations: [SymbolRelation] = [] + ) { self.symbol = symbol self.location = location self.roles = roles @@ -30,14 +35,14 @@ public struct SymbolOccurrence: Equatable, Sendable { } extension SymbolOccurrence: Comparable { - public static func <(a: SymbolOccurrence, b: SymbolOccurrence) -> Bool { + public static func < (a: SymbolOccurrence, b: SymbolOccurrence) -> Bool { // FIXME: incorporate relations return (a.location, a.roles, a.symbol) < (b.location, b.roles, b.symbol) } } extension SymbolRelation: Comparable { - public static func <(a: SymbolRelation, b: SymbolRelation) -> Bool { + public static func < (a: SymbolRelation, b: SymbolRelation) -> Bool { (a.roles, a.symbol) < (b.roles, b.symbol) } } @@ -75,7 +80,8 @@ extension SymbolOccurrence { location: SymbolLocation(indexstoredb_symbol_occurrence_location(value)), roles: SymbolRole(rawValue: indexstoredb_symbol_occurrence_roles(value)), symbolProvider: SymbolProviderKind(indexstoredb_symbol_occurrence_symbol_provider_kind(value)), - relations: relations) + relations: relations + ) } } @@ -83,6 +89,7 @@ extension SymbolRelation { internal init(_ value: indexstoredb_symbol_relation_t) { self.init( symbol: Symbol(indexstoredb_symbol_relation_get_symbol(value)), - roles: SymbolRole(rawValue: indexstoredb_symbol_relation_get_roles(value))) + roles: SymbolRole(rawValue: indexstoredb_symbol_relation_get_roles(value)) + ) } } diff --git a/Sources/IndexStoreDB/SymbolProperty.swift b/Sources/IndexStoreDB/SymbolProperty.swift index 15924007..af5b983a 100644 --- a/Sources/IndexStoreDB/SymbolProperty.swift +++ b/Sources/IndexStoreDB/SymbolProperty.swift @@ -10,21 +10,28 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import IndexStoreDB_CIndexStoreDB +@_implementationOnly import IndexStoreDB_CIndexStoreDB public struct SymbolProperty: OptionSet, Hashable, Sendable { public var rawValue: UInt64 public static let generic: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_GENERIC) - public static let templatePartialSpecialization: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_TEMPLATE_PARTIAL_SPECIALIZATION) - public static let templateSpecialization: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_TEMPLATE_SPECIALIZATION) + public static let templatePartialSpecialization: SymbolProperty = SymbolProperty( + rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_TEMPLATE_PARTIAL_SPECIALIZATION + ) + public static let templateSpecialization: SymbolProperty = SymbolProperty( + rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_TEMPLATE_SPECIALIZATION + ) public static let unitTest: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_UNITTEST) public static let ibAnnotated: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_IBANNOTATED) - public static let ibOutletCollection: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_IBOUTLETCOLLECTION) + public static let ibOutletCollection: SymbolProperty = SymbolProperty( + rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_IBOUTLETCOLLECTION + ) public static let gkInspectable: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_GKINSPECTABLE) public static let local: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_LOCAL) - public static let protocolInterface: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_PROTOCOL_INTERFACE) + public static let protocolInterface: SymbolProperty = SymbolProperty( + rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_PROTOCOL_INTERFACE + ) public static let swiftAsync: SymbolProperty = SymbolProperty(rawValue: INDEXSTOREDB_SYMBOL_PROPERTY_SWIFT_ASYNC) public static let all: SymbolProperty = SymbolProperty(rawValue: ~0) diff --git a/Sources/IndexStoreDB/SymbolRole.swift b/Sources/IndexStoreDB/SymbolRole.swift index ebf9b146..e7f0d709 100644 --- a/Sources/IndexStoreDB/SymbolRole.swift +++ b/Sources/IndexStoreDB/SymbolRole.swift @@ -10,8 +10,7 @@ // //===----------------------------------------------------------------------===// -@_implementationOnly -import IndexStoreDB_CIndexStoreDB +@_implementationOnly import IndexStoreDB_CIndexStoreDB public struct SymbolRole: OptionSet, Hashable, Sendable { @@ -56,7 +55,7 @@ public struct SymbolRole: OptionSet, Hashable, Sendable { } extension SymbolRole: Comparable { - public static func <(a: SymbolRole, b: SymbolRole) -> Bool { + public static func < (a: SymbolRole, b: SymbolRole) -> Bool { return a.rawValue < b.rawValue } } diff --git a/Sources/tibs/main.swift b/Sources/tibs/main.swift index d8b8725c..7766a766 100644 --- a/Sources/tibs/main.swift +++ b/Sources/tibs/main.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import ISDBTibs import Foundation +import ISDBTibs extension FileHandle: TextOutputStream { public func write(_ string: String) { @@ -71,7 +71,8 @@ func main(arguments: [String]) { let toolchain = TibsToolchain( swiftc: URL(fileURLWithPath: "/usr/bin/swiftc"), clang: URL(fileURLWithPath: "/usr/bin/clang"), - tibs: Bundle.main.bundleURL.appendingPathComponent("tibs", isDirectory: false)) + tibs: Bundle.main.bundleURL.appendingPathComponent("tibs", isDirectory: false) + ) let builder: TibsBuilder do { diff --git a/Tests/ISDBTibsTests/MiscTests.swift b/Tests/ISDBTibsTests/MiscTests.swift index cd63f165..2cedbd1d 100644 --- a/Tests/ISDBTibsTests/MiscTests.swift +++ b/Tests/ISDBTibsTests/MiscTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import ISDBTibs import Foundation +import ISDBTibs import XCTest final class MiscTests: XCTestCase { @@ -44,21 +44,21 @@ final class MiscTests: XCTestCase { /*newlines*/ "target1: dep1 \ntarget2: dep1 dep2 dep3": [ (target: "target1", deps: ["dep1"]), - (target: "target2", deps: ["dep1", "dep2", "dep3"]) + (target: "target2", deps: ["dep1", "dep2", "dep3"]), ], /*nodeps*/ "target: ": [ (target: "target", deps: []) ], /*spaces*/ - "target: Dep\\ with\\ spaces" : [ + "target: Dep\\ with\\ spaces": [ (target: "target", deps: ["Dep\\ with\\ spaces"]) ], - "target\\ with\\ spaces: Dep" : [ + "target\\ with\\ spaces: Dep": [ (target: "target\\ with\\ spaces", deps: ["Dep"]) ], /*paths*/ - "target: Dep/with\\slashes" : [ + "target: Dep/with\\slashes": [ (target: "target", deps: ["Dep/with\\slashes"]) ], ] @@ -68,7 +68,10 @@ final class MiscTests: XCTestCase { XCTFail("Could not parse: \(makefile)") return } - XCTAssertTrue(outputsEqual(actual: parsed.outputs, expected: exp), "Makefile parse did not match!\nExpected: \(exp)\nAcutal: \(parsed.outputs)") + XCTAssertTrue( + outputsEqual(actual: parsed.outputs, expected: exp), + "Makefile parse did not match!\nExpected: \(exp)\nAcutal: \(parsed.outputs)" + ) } } } diff --git a/Tests/ISDBTibsTests/OutputFileMapTests.swift b/Tests/ISDBTibsTests/OutputFileMapTests.swift index a03bb740..29cebdf3 100644 --- a/Tests/ISDBTibsTests/OutputFileMapTests.swift +++ b/Tests/ISDBTibsTests/OutputFileMapTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import ISDBTibs import Foundation +import ISDBTibs import XCTest final class OutputFileMapTests: XCTestCase { @@ -21,19 +21,25 @@ final class OutputFileMapTests: XCTestCase { ofm["b"] = OutputFileMap.Entry(swiftmodule: "B") ofm["c"] = OutputFileMap.Entry(swiftmodule: "C") - XCTAssertEqual(Array(ofm.values), [ - OutputFileMap.Entry(swiftmodule: "A"), - OutputFileMap.Entry(swiftmodule: "B"), - OutputFileMap.Entry(swiftmodule: "C"), - ]) + XCTAssertEqual( + Array(ofm.values), + [ + OutputFileMap.Entry(swiftmodule: "A"), + OutputFileMap.Entry(swiftmodule: "B"), + OutputFileMap.Entry(swiftmodule: "C"), + ] + ) ofm["a"] = ofm["c"]! ofm["a"]!.swiftdoc = "D" - XCTAssertEqual(Array(ofm.values), [ - OutputFileMap.Entry(swiftmodule: "C", swiftdoc: "D"), - OutputFileMap.Entry(swiftmodule: "B"), - OutputFileMap.Entry(swiftmodule: "C"), - ]) + XCTAssertEqual( + Array(ofm.values), + [ + OutputFileMap.Entry(swiftmodule: "C", swiftdoc: "D"), + OutputFileMap.Entry(swiftmodule: "B"), + OutputFileMap.Entry(swiftmodule: "C"), + ] + ) } } diff --git a/Tests/ISDBTibsTests/TibsBuildTests.swift b/Tests/ISDBTibsTests/TibsBuildTests.swift index ac24a5db..9526fdff 100644 --- a/Tests/ISDBTibsTests/TibsBuildTests.swift +++ b/Tests/ISDBTibsTests/TibsBuildTests.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// -import ISDBTibs -import ISDBTestSupport import Foundation +import ISDBTestSupport +import ISDBTibs import XCTest final class TibsBuildTests: XCTestCase { @@ -29,7 +29,7 @@ final class TibsBuildTests: XCTestCase { .appendingPathComponent(testDirectoryName, isDirectory: true) buildRoot = testDir.appendingPathComponent("build", isDirectory: true) sourceRoot = testDir.appendingPathComponent("src", isDirectory: true) - + _ = try? fm.removeItem(at: testDir) try! fm.createDirectory(at: buildRoot, withIntermediateDirectories: true) } @@ -45,7 +45,8 @@ final class TibsBuildTests: XCTestCase { manifest: try TibsManifest.load(projectRoot: projSource), sourceRoot: sourceRoot, buildRoot: buildRoot, - toolchain: TibsBuildTests.toolchain) + toolchain: TibsBuildTests.toolchain + ) } func testBuildSwift() throws { @@ -111,8 +112,10 @@ final class TibsBuildTests: XCTestCase { let dcpp = sourceRoot.appendingPathComponent("d.cpp", isDirectory: false) let emm = sourceRoot.appendingPathComponent("e.mm", isDirectory: false) - XCTAssertEqual(try builder._buildTest(), - ["Swift Module main", bc.path, cm.path, dcpp.path, emm.path]) + XCTAssertEqual( + try builder._buildTest(), + ["Swift Module main", bc.path, cm.path, dcpp.path, emm.path] + ) XCTAssertEqual(try builder._buildTest(), []) let ch = sourceRoot.appendingPathComponent("c.h", isDirectory: false) @@ -123,14 +126,16 @@ final class TibsBuildTests: XCTestCase { builder.toolchain.sleepForTimestamp() try content.write(to: ch) // FIXME: there is a false dependency because of the generated header main-Swift.h - XCTAssertEqual(try builder._buildTest(), - ["Swift Module main", bc.path, cm.path, dcpp.path, emm.path]) + XCTAssertEqual( + try builder._buildTest(), + ["Swift Module main", bc.path, cm.path, dcpp.path, emm.path] + ) builder.toolchain.sleepForTimestamp() let dh = sourceRoot.appendingPathComponent("d.h", isDirectory: false) try """ - class D {}; - """.write(to: dh, atomically: false, encoding: .utf8) + class D {}; + """.write(to: dh, atomically: false, encoding: .utf8) XCTAssertEqual(try builder._buildTest(), [dcpp.path, emm.path]) } } diff --git a/Tests/ISDBTibsTests/TibsCompilationDatabaseTests.swift b/Tests/ISDBTibsTests/TibsCompilationDatabaseTests.swift index 32002548..700bcf1e 100644 --- a/Tests/ISDBTibsTests/TibsCompilationDatabaseTests.swift +++ b/Tests/ISDBTibsTests/TibsCompilationDatabaseTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import ISDBTibs import Foundation +import ISDBTibs import XCTest final class TibsCompilationDatabaseTests: XCTestCase { @@ -19,7 +19,8 @@ final class TibsCompilationDatabaseTests: XCTestCase { swiftc: URL(fileURLWithPath: "/swiftc"), clang: URL(fileURLWithPath: "/clang"), tibs: URL(fileURLWithPath: "/tibs"), - ninja: URL(fileURLWithPath: "/ninja")) + ninja: URL(fileURLWithPath: "/ninja") + ) typealias Command = JSONCompilationDatabase.Command @@ -48,8 +49,9 @@ final class TibsCompilationDatabaseTests: XCTestCase { "-module-cache-path", "ModuleCache", "-c", ] + sdkargs + [ - "-working-directory", "/build" - ]), + "-working-directory", "/build", + ] + ), Command( directory: "/build", file: "/src/b.swift", @@ -65,8 +67,9 @@ final class TibsCompilationDatabaseTests: XCTestCase { "-module-cache-path", "ModuleCache", "-c", ] + sdkargs + [ - "-working-directory", "/build" - ]), + "-working-directory", "/build", + ] + ), Command( directory: "/build", file: "/src/c.swift", @@ -81,8 +84,9 @@ final class TibsCompilationDatabaseTests: XCTestCase { "-module-cache-path", "ModuleCache", "-c", ] + sdkargs + [ - "-working-directory", "/build" - ]), + "-working-directory", "/build", + ] + ), ]) XCTAssertEqual(builder.compilationDatabase, expected) @@ -98,31 +102,33 @@ final class TibsCompilationDatabaseTests: XCTestCase { let sdkargs = TibsBuilder.defaultSDKPath.map { ["-sdk", $0] } ?? [] - let swiftArgs = [ - "/swiftc", "/src/a.swift", "/src/b.swift", - "-module-name", "main", - "-index-store-path", "/build/index", "-index-ignore-system-modules", - "-output-file-map", "main-output-file-map.json", - "-emit-module", "-emit-module-path", - "main.swiftmodule", "-emit-dependencies", - "-pch-output-dir", "pch", - "-module-cache-path", "ModuleCache", - "-c", - "-emit-objc-header", "-emit-objc-header-path", "main-Swift.h", - "-import-objc-header", "/src/bridging-header.h", - ] + sdkargs + [ - "-Xcc", "-Wno-objc-root-class", - "-working-directory", "/build" - ] + let swiftArgs = + [ + "/swiftc", "/src/a.swift", "/src/b.swift", + "-module-name", "main", + "-index-store-path", "/build/index", "-index-ignore-system-modules", + "-output-file-map", "main-output-file-map.json", + "-emit-module", "-emit-module-path", + "main.swiftmodule", "-emit-dependencies", + "-pch-output-dir", "pch", + "-module-cache-path", "ModuleCache", + "-c", + "-emit-objc-header", "-emit-objc-header-path", "main-Swift.h", + "-import-objc-header", "/src/bridging-header.h", + ] + sdkargs + [ + "-Xcc", "-Wno-objc-root-class", + "-working-directory", "/build", + ] let clangArgs = { (src: String) -> [String] in - return ["/clang", "-fsyntax-only", "/src/\(src)", + return [ + "/clang", "-fsyntax-only", "/src/\(src)", "-I", ".", "-I", "/src", "-index-store-path", "index", "-index-ignore-system-symbols", "-fmodules", "-fmodules-cache-path=ModuleCache", "-MMD", "-MF", "main-\(src).o.d", "-o", "main-\(src).o", - "-Wno-objc-root-class" + "-Wno-objc-root-class", ] } diff --git a/Tests/ISDBTibsTests/TibsManifestTests.swift b/Tests/ISDBTibsTests/TibsManifestTests.swift index 1addfcd5..256f0ddf 100644 --- a/Tests/ISDBTibsTests/TibsManifestTests.swift +++ b/Tests/ISDBTibsTests/TibsManifestTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import ISDBTibs import Foundation +import ISDBTibs import XCTest final class TibsManifestTests: XCTestCase { @@ -23,9 +23,12 @@ final class TibsManifestTests: XCTestCase { let decoder = JSONDecoder() let manifest1 = try decoder.decode(TibsManifest.self, from: serialized1.data(using: .utf8)!) - XCTAssertEqual(manifest1, TibsManifest(targets: [ - TibsManifest.Target(sources: ["a.swift"]), - ])) + XCTAssertEqual( + manifest1, + TibsManifest(targets: [ + TibsManifest.Target(sources: ["a.swift"]) + ]) + ) let serialized2 = """ { @@ -46,15 +49,25 @@ final class TibsManifestTests: XCTestCase { let manifest = TibsManifest.Target(sources: ["a.swift"]) let encoder = JSONEncoder() let serialized = try encoder.encode(manifest) - XCTAssertEqual(String(data: serialized, encoding: .utf8), """ + XCTAssertEqual( + String(data: serialized, encoding: .utf8), + """ {"sources":["a.swift"]} - """) + """ + ) } func testRoundTrip() throws { let manifest = TibsManifest(targets: [ - TibsManifest.Target(name: "A", swiftFlags: ["-A", "-B"], clangFlags: ["-CA"], sources: ["a.swift", "b.c"], bridgingHeader: nil, dependencies: []), - TibsManifest.Target(name: "B", sources: ["b.swift"], dependencies: ["A"]) + TibsManifest.Target( + name: "A", + swiftFlags: ["-A", "-B"], + clangFlags: ["-CA"], + sources: ["a.swift", "b.c"], + bridgingHeader: nil, + dependencies: [] + ), + TibsManifest.Target(name: "B", sources: ["b.swift"], dependencies: ["A"]), ]) let encoder = JSONEncoder() diff --git a/Tests/ISDBTibsTests/TibsResolutionTests.swift b/Tests/ISDBTibsTests/TibsResolutionTests.swift index 80209636..7b77eb71 100644 --- a/Tests/ISDBTibsTests/TibsResolutionTests.swift +++ b/Tests/ISDBTibsTests/TibsResolutionTests.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// -import ISDBTibs -import ISDBTestSupport import Foundation +import ISDBTestSupport +import ISDBTibs import XCTest final class TibsResolutionTests: XCTestCase { @@ -21,7 +21,8 @@ final class TibsResolutionTests: XCTestCase { swiftc: URL(fileURLWithPath: "/swiftc"), clang: URL(fileURLWithPath: "/clang"), tibs: URL(fileURLWithPath: "/tibs"), - ninja: URL(fileURLWithPath: "/ninja")) + ninja: URL(fileURLWithPath: "/ninja") + ) func testResolutionSingleSwiftModule() throws { let dir = projectDir("proj1") @@ -49,11 +50,14 @@ final class TibsResolutionTests: XCTestCase { XCTAssertEqual(module.moduleDeps, []) XCTAssertEqual(module.importPaths, []) XCTAssertEqual(module.extraArgs, []) - XCTAssertEqual(module.sources, [ - src.appendingPathComponent("a.swift", isDirectory: false), - src.appendingPathComponent("b.swift", isDirectory: false), - src.appendingPathComponent("rec/c.swift" , isDirectory: false), - ]) + XCTAssertEqual( + module.sources, + [ + src.appendingPathComponent("a.swift", isDirectory: false), + src.appendingPathComponent("b.swift", isDirectory: false), + src.appendingPathComponent("rec/c.swift", isDirectory: false), + ] + ) #if os(macOS) XCTAssertNotNil(module.sdk) #else @@ -82,46 +86,59 @@ final class TibsResolutionTests: XCTestCase { XCTAssertEqual(module.name, "main") XCTAssertEqual(module.emitModulePath, "main.swiftmodule") XCTAssertEqual(module.emitHeaderPath, "main-Swift.h") - XCTAssertEqual(module.bridgingHeader, - src.appendingPathComponent("bridging-header.h", isDirectory: false)) + XCTAssertEqual( + module.bridgingHeader, + src.appendingPathComponent("bridging-header.h", isDirectory: false) + ) XCTAssertEqual(module.moduleDeps, []) XCTAssertEqual(module.importPaths, []) XCTAssertEqual(module.extraArgs, ["-Xcc", "-Wno-objc-root-class"]) - XCTAssertEqual(module.sources, [ - src.appendingPathComponent("a.swift", isDirectory: false), - src.appendingPathComponent("b.swift", isDirectory: false), - ]) + XCTAssertEqual( + module.sources, + [ + src.appendingPathComponent("a.swift", isDirectory: false), + src.appendingPathComponent("b.swift", isDirectory: false), + ] + ) let clangTUs = target.clangTUs.sorted(by: { $0.outputPath < $1.outputPath }) XCTAssertEqual(clangTUs.count, 4) - if let tu = clangTUs.count >= 2 ? clangTUs[0] : nil{ + if let tu = clangTUs.count >= 2 ? clangTUs[0] : nil { XCTAssertEqual(tu.source, src.appendingPathComponent("b.c", isDirectory: false)) XCTAssertEqual(tu.outputPath, "main-b.c.o") XCTAssertEqual(tu.generatedHeaderDep, "main.swiftmodule") XCTAssertEqual(tu.importPaths, [".", "/src"]) XCTAssertEqual(tu.extraArgs, ["-Wno-objc-root-class"]) - } else { XCTFail() } + } else { + XCTFail() + } if let tu = clangTUs.count >= 2 ? clangTUs[1] : nil { XCTAssertEqual(tu.source, src.appendingPathComponent("c.m", isDirectory: false)) XCTAssertEqual(tu.outputPath, "main-c.m.o") XCTAssertEqual(tu.generatedHeaderDep, "main.swiftmodule") XCTAssertEqual(tu.importPaths, [".", "/src"]) XCTAssertEqual(tu.extraArgs, ["-Wno-objc-root-class"]) - } else { XCTFail() } + } else { + XCTFail() + } if let tu = clangTUs.count >= 3 ? clangTUs[2] : nil { XCTAssertEqual(tu.source, src.appendingPathComponent("d.cpp", isDirectory: false)) XCTAssertEqual(tu.outputPath, "main-d.cpp.o") XCTAssertEqual(tu.generatedHeaderDep, "main.swiftmodule") XCTAssertEqual(tu.importPaths, [".", "/src"]) XCTAssertEqual(tu.extraArgs, ["-Wno-objc-root-class"]) - } else { XCTFail() } + } else { + XCTFail() + } if let tu = clangTUs.count >= 4 ? clangTUs[3] : nil { XCTAssertEqual(tu.source, src.appendingPathComponent("e.mm", isDirectory: false)) XCTAssertEqual(tu.outputPath, "main-e.mm.o") XCTAssertEqual(tu.generatedHeaderDep, "main.swiftmodule") XCTAssertEqual(tu.importPaths, [".", "/src"]) XCTAssertEqual(tu.extraArgs, ["-Wno-objc-root-class"]) - } else { XCTFail() } + } else { + XCTFail() + } } func testResolutionSwiftModules() throws { @@ -150,9 +167,12 @@ final class TibsResolutionTests: XCTestCase { XCTAssertEqual(module.moduleDeps, []) XCTAssertEqual(module.importPaths, []) XCTAssertEqual(module.extraArgs, []) - XCTAssertEqual(module.sources, [ - src.appendingPathComponent("a.swift", isDirectory: false), - ]) + XCTAssertEqual( + module.sources, + [ + src.appendingPathComponent("a.swift", isDirectory: false) + ] + ) XCTAssertEqual(target.clangTUs, []) } @@ -171,9 +191,12 @@ final class TibsResolutionTests: XCTestCase { XCTAssertEqual(module.moduleDeps, ["A.swiftmodule"]) XCTAssertEqual(module.importPaths, ["."]) XCTAssertEqual(module.extraArgs, []) - XCTAssertEqual(module.sources, [ - src.appendingPathComponent("b.swift", isDirectory: false), - ]) + XCTAssertEqual( + module.sources, + [ + src.appendingPathComponent("b.swift", isDirectory: false) + ] + ) XCTAssertEqual(target.clangTUs, []) } @@ -192,9 +215,12 @@ final class TibsResolutionTests: XCTestCase { XCTAssertEqual(module.moduleDeps, ["B.swiftmodule"]) XCTAssertEqual(module.importPaths, ["."]) XCTAssertEqual(module.extraArgs, []) - XCTAssertEqual(module.sources, [ - src.appendingPathComponent("c.swift", isDirectory: false), - ]) + XCTAssertEqual( + module.sources, + [ + src.appendingPathComponent("c.swift", isDirectory: false) + ] + ) XCTAssertEqual(target.clangTUs, []) } } diff --git a/Tests/IndexStoreDBTests/IndexStoreDBTests.swift b/Tests/IndexStoreDBTests/IndexStoreDBTests.swift index 7d650d7f..6b46a6b5 100644 --- a/Tests/IndexStoreDBTests/IndexStoreDBTests.swift +++ b/Tests/IndexStoreDBTests/IndexStoreDBTests.swift @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// -import IndexStoreDB +import Foundation import ISDBTibs +import IndexStoreDB import XCTest -import Foundation let isTSanEnabled: Bool = { if let value = ProcessInfo.processInfo.environment["INDEXSTOREDB_ENABLED_THREAD_SANITIZER"] { @@ -22,7 +22,12 @@ let isTSanEnabled: Bool = { return false }() -func checkThrows(_ expected: IndexStoreDBError, file: StaticString = #file, line: UInt = #line, _ body: () throws -> ()) { +func checkThrows( + _ expected: IndexStoreDBError, + file: StaticString = #file, + line: UInt = #line, + _ body: () throws -> Void +) { do { try body() XCTFail("missing expected error \(expected)", file: file, line: line) @@ -71,11 +76,21 @@ final class IndexStoreDBTests: XCTestCase { // Readonly - do not create. checkThrows(.create("failed opening database")) { - _ = try IndexStoreDB(storePath: tmp + "/store", databasePath: tmp + "/db-readonly", library: libIndexStore, readonly: true) + _ = try IndexStoreDB( + storePath: tmp + "/store", + databasePath: tmp + "/db-readonly", + library: libIndexStore, + readonly: true + ) } // Readonly - do not create. checkThrows(.create("index store path does not exist")) { - _ = try IndexStoreDB(storePath: tmp + "/store-readonly", databasePath: tmp + "/db", library: libIndexStore, readonly: true) + _ = try IndexStoreDB( + storePath: tmp + "/store-readonly", + databasePath: tmp + "/db", + library: libIndexStore, + readonly: true + ) } } @@ -97,7 +112,7 @@ final class IndexStoreDBTests: XCTestCase { // Don't care about specific index data, just want an index store directory containing *something*. guard let ws = try staticTibsTestWorkspace(name: "SingleUnit") else { return } try ws.buildAndIndex() - indexStorePath = ws.builder.indexstore.path + indexStorePath = ws.builder.indexstore.path } let fileMgr = FileManager.default @@ -111,7 +126,12 @@ final class IndexStoreDBTests: XCTestCase { for _ in 0..Bool) -> XCTestExpectation { - self.expectation(for: NSPredicate(block: { (_, _) -> Bool in - return block() - }), evaluatedWith: nil) + func expectation(for block: @escaping () -> Bool) -> XCTestExpectation { + self.expectation( + for: NSPredicate(block: { (_, _) -> Bool in + return block() + }), + evaluatedWith: nil + ) } - func waitForBlock(timeout: TimeInterval = defaultTimeout, _ block: @escaping ()->Bool) { - let expect = self.expectation(for: block) - self.wait(for: [expect], timeout: timeout) + func waitForBlock(timeout: TimeInterval = defaultTimeout, _ block: @escaping () -> Bool) { + let expect = self.expectation(for: block) + self.wait(for: [expect], timeout: timeout) } func testBasic() throws { @@ -49,7 +52,8 @@ final class IndexTests: XCTestCase { location: SymbolLocation(ws.testLoc("c"), moduleName: "main"), roles: [.definition, .canonical], symbolProvider: .clang, - relations: []) + relations: [] + ) let ccall = SymbolOccurrence( symbol: csym, @@ -58,50 +62,93 @@ final class IndexTests: XCTestCase { symbolProvider: .clang, relations: [ .init(symbol: asym, roles: [.calledBy, .containedBy]) - ]) + ] + ) - checkOccurrences(getOccs(), ignoreRelations: false, allowAdditionalRoles: false, expected: [ - ccanon, - ccall, - ]) + checkOccurrences( + getOccs(), + ignoreRelations: false, + allowAdditionalRoles: false, + expected: [ + ccanon, + ccall, + ] + ) - checkOccurrences(index.canonicalOccurrences(ofName: "c()"), ignoreRelations: false, expected: [ - ccanon, - ]) + checkOccurrences( + index.canonicalOccurrences(ofName: "c()"), + ignoreRelations: false, + expected: [ + ccanon + ] + ) checkOccurrences(index.canonicalOccurrences(ofName: "c"), ignoreRelations: false, expected: []) - checkOccurrences(index.canonicalOccurrences(containing: "c", - anchorStart: true, anchorEnd: false, subsequence: false, - ignoreCase: false), ignoreRelations: false, expected: [ccanon]) + checkOccurrences( + index.canonicalOccurrences( + containing: "c", + anchorStart: true, + anchorEnd: false, + subsequence: false, + ignoreCase: false + ), + ignoreRelations: false, + expected: [ccanon] + ) - checkOccurrences(index.canonicalOccurrences(containing: "c", - anchorStart: true, anchorEnd: true, subsequence: false, - ignoreCase: false), ignoreRelations: false, expected: []) + checkOccurrences( + index.canonicalOccurrences( + containing: "c", + anchorStart: true, + anchorEnd: true, + subsequence: false, + ignoreCase: false + ), + ignoreRelations: false, + expected: [] + ) - checkOccurrences(index.canonicalOccurrences(containing: "C", - anchorStart: true, anchorEnd: false, subsequence: false, - ignoreCase: true), ignoreRelations: false, expected: [ccanon]) + checkOccurrences( + index.canonicalOccurrences( + containing: "C", + anchorStart: true, + anchorEnd: false, + subsequence: false, + ignoreCase: true + ), + ignoreRelations: false, + expected: [ccanon] + ) - checkOccurrences(index.canonicalOccurrences(containing: "C", - anchorStart: true, anchorEnd: false, subsequence: false, - ignoreCase: false), ignoreRelations: false, expected: []) + checkOccurrences( + index.canonicalOccurrences( + containing: "C", + anchorStart: true, + anchorEnd: false, + subsequence: false, + ignoreCase: false + ), + ignoreRelations: false, + expected: [] + ) checkOccurrences( index.occurrences(relatedToUSR: "s:4main1ayyF", roles: .calledBy), ignoreRelations: false, - expected: - [ - ccall, - SymbolOccurrence( - symbol: Symbol(usr: "s:4main1byyF", name: "b()", kind: .function, language: .swift), - location: SymbolLocation(ws.testLoc("b:call")), - roles: [.reference, .call, .calledBy, .containedBy], - symbolProvider: .swift, - relations: [ - .init(symbol: asym, roles: [.calledBy, .containedBy]) - ]) - ]) + expected: [ + ccall, + SymbolOccurrence( + symbol: Symbol(usr: "s:4main1byyF", name: "b()", kind: .function, language: .swift), + location: SymbolLocation(ws.testLoc("b:call")), + roles: [.reference, .call, .calledBy, .containedBy], + symbolProvider: .swift, + relations: [ + .init(symbol: asym, roles: [.calledBy, .containedBy]) + ] + ), + ] + ) } func testMixedLangTarget() throws { @@ -109,97 +156,139 @@ final class IndexTests: XCTestCase { try ws.buildAndIndex() let index = ws.index - #if os(macOS) + #if os(macOS) let cdecl = Symbol(usr: "c:objc(cs)C", name: "C", kind: .class, language: .objc) let cdeclOccs = index.occurrences(ofUSR: cdecl.usr, roles: .all) - checkOccurrences(cdeclOccs, expected: [ - cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), - cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), - cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .clang), - cdecl.at(ws.testLoc("C:ref:e.mm"), roles: .reference, symbolProvider: .clang), - ]) + checkOccurrences( + cdeclOccs, + expected: [ + cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), + cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), + cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .clang), + cdecl.at(ws.testLoc("C:ref:e.mm"), roles: .reference, symbolProvider: .clang), + ] + ) let cmethod = Symbol(usr: "c:objc(cs)C(im)method", name: "method", kind: .instanceMethod, language: .objc) let cmethodOccs = index.occurrences(ofUSR: cmethod.usr, roles: .all) - checkOccurrences(cmethodOccs, expected: [ - cmethod.with(name: "method()", language: .swift).at(ws.testLoc("C.method:call:swift"), roles: [.call, .dynamic], symbolProvider: .swift), - cmethod.at(ws.testLoc("C.method:decl"), roles: .declaration, symbolProvider: .clang), - cmethod.at(ws.testLoc("C.method:def"), roles: .definition, symbolProvider: .clang), - cmethod.at(ws.testLoc("C.method:call:e.mm"), roles: [.call, .dynamic], symbolProvider: .clang), - ]) - #endif + checkOccurrences( + cmethodOccs, + expected: [ + cmethod.with(name: "method()", language: .swift).at( + ws.testLoc("C.method:call:swift"), + roles: [.call, .dynamic], + symbolProvider: .swift + ), + cmethod.at(ws.testLoc("C.method:decl"), roles: .declaration, symbolProvider: .clang), + cmethod.at(ws.testLoc("C.method:def"), roles: .definition, symbolProvider: .clang), + cmethod.at(ws.testLoc("C.method:call:e.mm"), roles: [.call, .dynamic], symbolProvider: .clang), + ] + ) + #endif let ddecl = Symbol(usr: "c:@S@D", name: "D", kind: .class, language: .cxx) let dOccs = index.occurrences(ofUSR: ddecl.usr, roles: .all) - checkOccurrences(dOccs, expected: [ - ddecl.at(ws.testLoc("D:def"), roles: .definition, symbolProvider: .clang), - ddecl.at(ws.testLoc("D:ref"), roles: .reference, symbolProvider: .clang), - ddecl.at(ws.testLoc("D:ref:e.mm"), roles: .reference, symbolProvider: .clang), - ]) + checkOccurrences( + dOccs, + expected: [ + ddecl.at(ws.testLoc("D:def"), roles: .definition, symbolProvider: .clang), + ddecl.at(ws.testLoc("D:ref"), roles: .reference, symbolProvider: .clang), + ddecl.at(ws.testLoc("D:ref:e.mm"), roles: .reference, symbolProvider: .clang), + ] + ) let bhdecl = Symbol(usr: "c:@F@bridgingHeader", name: "bridgingHeader", kind: .function, language: .c) let bridgingHeaderOccs = index.occurrences(ofUSR: bhdecl.usr, roles: .all) - checkOccurrences(bridgingHeaderOccs, expected: [ - bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), - bhdecl.with(name: "bridgingHeader()", language: .swift).at(ws.testLoc("bridgingHeader:call"), roles: .call, symbolProvider: .clang), - ]) + checkOccurrences( + bridgingHeaderOccs, + expected: [ + bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), + bhdecl.with(name: "bridgingHeader()", language: .swift).at( + ws.testLoc("bridgingHeader:call"), + roles: .call, + symbolProvider: .clang + ), + ] + ) } func testHermeticMixedLang() throws { guard let ws = try staticTibsTestWorkspace(name: "HermeticMixedLang") else { return } // Provide the reverse mappings to the one in the project.json. - try ws.reinitIndexStore(waitUntilDoneInitializing: true, prefixMappings: [ - PathMapping(original: "/SRC_ROOT", replacement: ws.sources.rootDirectory.path), - PathMapping(original: "/BUILD_ROOT", replacement: ws.builder.buildRoot.path) - ]) + try ws.reinitIndexStore( + waitUntilDoneInitializing: true, + prefixMappings: [ + PathMapping(original: "/SRC_ROOT", replacement: ws.sources.rootDirectory.path), + PathMapping(original: "/BUILD_ROOT", replacement: ws.builder.buildRoot.path), + ] + ) try ws.buildAndIndex() let index = ws.index - #if os(macOS) + #if os(macOS) let cdecl = Symbol(usr: "c:objc(cs)C", name: "C", kind: .class, language: .objc) let cdeclOccs = index.occurrences(ofUSR: cdecl.usr, roles: .all) - checkOccurrences(cdeclOccs, expected: [ - cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), - cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), - cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .swift), - ]) + checkOccurrences( + cdeclOccs, + expected: [ + cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), + cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), + cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .swift), + ] + ) let cmethod = Symbol(usr: "c:objc(cs)C(im)method", name: "method", kind: .instanceMethod, language: .objc) let cmethodOccs = index.occurrences(ofUSR: cmethod.usr, roles: .all) - checkOccurrences(cmethodOccs, expected: [ - cmethod.with(name: "method()", language: .swift).at(ws.testLoc("C.method:call:swift"), roles: [.call, .dynamic], symbolProvider: .clang), - cmethod.at(ws.testLoc("C.method:decl"), roles: .declaration, symbolProvider: .clang), - cmethod.at(ws.testLoc("C.method:def"), roles: .definition, symbolProvider: .clang), - ]) - #endif + checkOccurrences( + cmethodOccs, + expected: [ + cmethod.with(name: "method()", language: .swift).at( + ws.testLoc("C.method:call:swift"), + roles: [.call, .dynamic], + symbolProvider: .clang + ), + cmethod.at(ws.testLoc("C.method:decl"), roles: .declaration, symbolProvider: .clang), + cmethod.at(ws.testLoc("C.method:def"), roles: .definition, symbolProvider: .clang), + ] + ) + #endif let bhdecl = Symbol(usr: "c:@F@bridgingHeader", name: "bridgingHeader", kind: .function, language: .c) let bridgingHeaderOccs = index.occurrences(ofUSR: bhdecl.usr, roles: .all) - checkOccurrences(bridgingHeaderOccs, expected: [ - bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), - bhdecl.with(name: "bridgingHeader()", language: .swift).at(ws.testLoc("bridgingHeader:call"), roles: .call, symbolProvider: .swift), - ]) + checkOccurrences( + bridgingHeaderOccs, + expected: [ + bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), + bhdecl.with(name: "bridgingHeader()", language: .swift).at( + ws.testLoc("bridgingHeader:call"), + roles: .call, + symbolProvider: .swift + ), + ] + ) } func testHermeticExplicitOutputUnits() throws { guard let ws = try staticTibsTestWorkspace(name: "HermeticMixedLang", useExplicitOutputUnits: true) else { return } // Provide the reverse mappings to the one in the project.json. - try ws.reinitIndexStore(useExplicitOutputUnits: true, - prefixMappings: [ - PathMapping(original: "/SRC_ROOT", replacement: ws.sources.rootDirectory.path), - PathMapping(original: "/BUILD_ROOT", replacement: ws.builder.buildRoot.path) - ]) + try ws.reinitIndexStore( + useExplicitOutputUnits: true, + prefixMappings: [ + PathMapping(original: "/SRC_ROOT", replacement: ws.sources.rootDirectory.path), + PathMapping(original: "/BUILD_ROOT", replacement: ws.builder.buildRoot.path), + ] + ) try ws.buildAndIndex() let index = ws.index - #if os(macOS) + #if os(macOS) let cdecl = Symbol(usr: "c:objc(cs)C", name: "C", kind: .class, language: .objc) let getOccs = { index.occurrences(ofUSR: cdecl.usr, roles: .all) } // Output units are not set yet. XCTAssertEqual(0, getOccs().count) - #endif + #endif // We must use the canonical output paths, not the local ones. let indexOutputPaths = ws.builder.indexOutputPaths.map { @@ -210,44 +299,60 @@ final class IndexTests: XCTestCase { // The bridging header is referenced as a PCH unit dependency, make sure we can see the data. let bhdecl = Symbol(usr: "c:@F@bridgingHeader", name: "bridgingHeader", kind: .function, language: .c) let bridgingHeaderOccs = index.occurrences(ofUSR: bhdecl.usr, roles: .all) - checkOccurrences(bridgingHeaderOccs, expected: [ - bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), - bhdecl.with(name: "bridgingHeader()", language: .swift).at(ws.testLoc("bridgingHeader:call"), roles: .call, symbolProvider: .swift), - ]) - #if os(macOS) - checkOccurrences(getOccs(), expected: [ - cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), - cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), - cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .swift), - ]) - - let outUnitASwift = try XCTUnwrap(indexOutputPaths.first{ $0.hasSuffix("-a.swift.o") }) + checkOccurrences( + bridgingHeaderOccs, + expected: [ + bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), + bhdecl.with(name: "bridgingHeader()", language: .swift).at( + ws.testLoc("bridgingHeader:call"), + roles: .call, + symbolProvider: .swift + ), + ] + ) + #if os(macOS) + checkOccurrences( + getOccs(), + expected: [ + cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), + cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), + cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .swift), + ] + ) + + let outUnitASwift = try XCTUnwrap(indexOutputPaths.first { $0.hasSuffix("-a.swift.o") }) index.removeUnitOutFilePaths([outUnitASwift], waitForProcessing: true) - checkOccurrences(getOccs(), expected: [ - cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), - cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), - ]) - #endif + checkOccurrences( + getOccs(), + expected: [ + cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), + cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), + ] + ) + #endif } /// Same as `testHermeticExplicitOutputUnits` but with remappings to make all paths relative. func testHermeticRelativePathExplicitOutputUnits() throws { - guard let ws = try staticTibsTestWorkspace(name: "HermeticMixedLangRelativePaths", useExplicitOutputUnits: true) else { return } + guard let ws = try staticTibsTestWorkspace(name: "HermeticMixedLangRelativePaths", useExplicitOutputUnits: true) + else { return } // Provide the reverse mappings to the one in the project.json. - try ws.reinitIndexStore(useExplicitOutputUnits: true, - prefixMappings: [ - PathMapping(original: ".", replacement: ws.sources.rootDirectory.path), - ]) + try ws.reinitIndexStore( + useExplicitOutputUnits: true, + prefixMappings: [ + PathMapping(original: ".", replacement: ws.sources.rootDirectory.path) + ] + ) try ws.buildAndIndex() let index = ws.index - #if os(macOS) + #if os(macOS) let cdecl = Symbol(usr: "c:objc(cs)C", name: "C", kind: .class, language: .objc) let getOccs = { index.occurrences(ofUSR: cdecl.usr, roles: .all) } // Output units are not set yet. XCTAssertEqual(0, getOccs().count) - #endif + #endif // We must use the canonical output paths, not the local ones. let indexOutputPaths = ws.builder.indexOutputPaths.map { @@ -258,24 +363,37 @@ final class IndexTests: XCTestCase { // The bridging header is referenced as a PCH unit dependency, make sure we can see the data. let bhdecl = Symbol(usr: "c:@F@bridgingHeader", name: "bridgingHeader", kind: .function, language: .c) let bridgingHeaderOccs = index.occurrences(ofUSR: bhdecl.usr, roles: .all) - checkOccurrences(bridgingHeaderOccs, expected: [ - bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), - bhdecl.with(name: "bridgingHeader()", language: .swift).at(ws.testLoc("bridgingHeader:call"), roles: .call, symbolProvider: .clang), - ]) - #if os(macOS) - checkOccurrences(getOccs(), expected: [ - cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), - cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), - cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .swift), - ]) - - let outUnitASwift = try XCTUnwrap(indexOutputPaths.first{ $0.hasSuffix("-a.swift.o") }) + checkOccurrences( + bridgingHeaderOccs, + expected: [ + bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), + bhdecl.with(name: "bridgingHeader()", language: .swift).at( + ws.testLoc("bridgingHeader:call"), + roles: .call, + symbolProvider: .clang + ), + ] + ) + #if os(macOS) + checkOccurrences( + getOccs(), + expected: [ + cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), + cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), + cdecl.with(language: .swift).at(ws.testLoc("C:ref:swift"), roles: .reference, symbolProvider: .swift), + ] + ) + + let outUnitASwift = try XCTUnwrap(indexOutputPaths.first { $0.hasSuffix("-a.swift.o") }) index.removeUnitOutFilePaths([outUnitASwift], waitForProcessing: true) - checkOccurrences(getOccs(), expected: [ - cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), - cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), - ]) - #endif + checkOccurrences( + getOccs(), + expected: [ + cdecl.at(ws.testLoc("C:decl"), roles: [.declaration, .canonical], symbolProvider: .clang), + cdecl.at(ws.testLoc("C:def"), roles: .definition, symbolProvider: .clang), + ] + ) + #endif } func testSwiftModules() throws { @@ -283,11 +401,14 @@ final class IndexTests: XCTestCase { try ws.buildAndIndex() let aaa = Symbol(usr: "s:1A3aaayyF", name: "aaa()", kind: .function, language: .swift) - checkOccurrences(ws.index.occurrences(ofUSR: aaa.usr, roles: .all), expected: [ - aaa.at(ws.testLoc("aaa:def"), moduleName: "A", roles: .definition, symbolProvider: .swift), - aaa.at(ws.testLoc("aaa:call"), moduleName: "B", roles: .call, symbolProvider: .swift), - aaa.at(ws.testLoc("aaa:call:c"), moduleName: "C", roles: .call, symbolProvider: .swift), - ]) + checkOccurrences( + ws.index.occurrences(ofUSR: aaa.usr, roles: .all), + expected: [ + aaa.at(ws.testLoc("aaa:def"), moduleName: "A", roles: .definition, symbolProvider: .swift), + aaa.at(ws.testLoc("aaa:call"), moduleName: "B", roles: .call, symbolProvider: .swift), + aaa.at(ws.testLoc("aaa:call:c"), moduleName: "C", roles: .call, symbolProvider: .swift), + ] + ) } func testEditsSimple() throws { @@ -297,28 +418,36 @@ final class IndexTests: XCTestCase { let cdecl = Symbol(usr: "s:4main1cyyF", name: "c()", kind: .function, language: .swift) let roles: SymbolRole = [.reference, .definition, .declaration] - checkOccurrences(ws.index.occurrences(ofUSR: cdecl.usr, roles: .all), expected: [ - cdecl.at(ws.testLoc("c"), roles: .definition, symbolProvider: .clang), - cdecl.at(ws.testLoc("c:call"), roles: .call, symbolProvider: .clang), - ]) + checkOccurrences( + ws.index.occurrences(ofUSR: cdecl.usr, roles: .all), + expected: [ + cdecl.at(ws.testLoc("c"), roles: .definition, symbolProvider: .clang), + cdecl.at(ws.testLoc("c:call"), roles: .call, symbolProvider: .clang), + ] + ) try ws.edit(rebuild: true) { editor, files in let url = ws.testLoc("c:call").url - let new = try files.get(url).appending(""" + let new = try files.get(url).appending( + """ func anotherOne() { /*c:anotherOne*/c() } - """) + """ + ) editor.write(new, to: url) } - checkOccurrences(ws.index.occurrences(ofUSR: cdecl.usr, roles: .all), expected: [ - cdecl.at(ws.testLoc("c"), roles: .definition, symbolProvider: .clang), - cdecl.at(ws.testLoc("c:call"), roles: .call, symbolProvider: .clang), - cdecl.at(ws.testLoc("c:anotherOne"), roles: .call, symbolProvider: .clang), - ]) + checkOccurrences( + ws.index.occurrences(ofUSR: cdecl.usr, roles: .all), + expected: [ + cdecl.at(ws.testLoc("c"), roles: .definition, symbolProvider: .clang), + cdecl.at(ws.testLoc("c:call"), roles: .call, symbolProvider: .clang), + cdecl.at(ws.testLoc("c:anotherOne"), roles: .call, symbolProvider: .clang), + ] + ) XCTAssertNotEqual(ws.testLoc("c").url, ws.testLoc("a:def").url) @@ -333,11 +462,14 @@ final class IndexTests: XCTestCase { checkOccurrences(ws.index.occurrences(ofUSR: cdecl.usr, roles: roles), expected: []) let newDecl = cdecl.with(usr: "s:4main1cSiyF") - checkOccurrences(ws.index.occurrences(ofUSR: newDecl.usr, roles: .all), expected: [ - newDecl.at(ws.testLoc("c"), roles: .definition, symbolProvider: .clang), - newDecl.at(ws.testLoc("c:call"), roles: .call, symbolProvider: .clang), - newDecl.at(ws.testLoc("c:anotherOne"), roles: .call, symbolProvider: .clang), - ]) + checkOccurrences( + ws.index.occurrences(ofUSR: newDecl.usr, roles: .all), + expected: [ + newDecl.at(ws.testLoc("c"), roles: .definition, symbolProvider: .clang), + newDecl.at(ws.testLoc("c:call"), roles: .call, symbolProvider: .clang), + newDecl.at(ws.testLoc("c:anotherOne"), roles: .call, symbolProvider: .clang), + ] + ) } func testWaitUntilDoneInitializing() throws { @@ -349,21 +481,29 @@ final class IndexTests: XCTestCase { databasePath: ws.tmpDir.appendingPathComponent("wait", isDirectory: true).path, library: libIndexStore, waitUntilDoneInitializing: true, - listenToUnitEvents: true) + listenToUnitEvents: true + ) let csym = Symbol(usr: "s:4main1cyyF", name: "c()", kind: .function, language: .swift) let waitOccs = indexWait.occurrences(ofUSR: csym.usr, roles: [.reference, .definition]) - checkOccurrences(waitOccs, expected: [ - SymbolOccurrence( - symbol: csym, - location: SymbolLocation(ws.testLoc("c")), - roles: [.definition, .canonical], symbolProvider: .clang), - SymbolOccurrence( - symbol: csym, - location: SymbolLocation(ws.testLoc("c:call")), - roles: [.reference, .call, .calledBy, .containedBy], symbolProvider: .clang), - ]) + checkOccurrences( + waitOccs, + expected: [ + SymbolOccurrence( + symbol: csym, + location: SymbolLocation(ws.testLoc("c")), + roles: [.definition, .canonical], + symbolProvider: .clang + ), + SymbolOccurrence( + symbol: csym, + location: SymbolLocation(ws.testLoc("c:call")), + roles: [.reference, .call, .calledBy, .containedBy], + symbolProvider: .clang + ), + ] + ) } func testDelegate() throws { @@ -512,10 +652,21 @@ final class IndexTests: XCTestCase { let main1Unit = try XCTUnwrap(units.first) let includes = index.includesOfUnit(unitName: main1Unit) - XCTAssertEqual(includes, [ - IndexStoreDB.UnitIncludeEntry(sourcePath: main1, targetPath: shared, line: ws.testLoc("include_main1_shared").line), - IndexStoreDB.UnitIncludeEntry(sourcePath: main1, targetPath: uniq1, line: ws.testLoc("include_main1_uniq1").line), - ]) + XCTAssertEqual( + includes, + [ + IndexStoreDB.UnitIncludeEntry( + sourcePath: main1, + targetPath: shared, + line: ws.testLoc("include_main1_shared").line + ), + IndexStoreDB.UnitIncludeEntry( + sourcePath: main1, + targetPath: uniq1, + line: ws.testLoc("include_main1_uniq1").line + ), + ] + ) } func testFilesIncludes() throws { @@ -556,28 +707,41 @@ final class IndexTests: XCTestCase { // Output units are not set yet. XCTAssertEqual(0, getOccs().count) - let indexOutputPaths = ws.builder.indexOutputPaths.map{$0.path} + let indexOutputPaths = ws.builder.indexOutputPaths.map { $0.path } index.addUnitOutFilePaths(indexOutputPaths, waitForProcessing: true) - checkOccurrences(getOccs(), expected: [ - ddecl.at(ws.testLoc("D:def"), roles: .definition, symbolProvider: .clang), - ddecl.at(ws.testLoc("D:ref"), roles: .reference, symbolProvider: .clang), - ddecl.at(ws.testLoc("D:ref:e.mm"), roles: .reference, symbolProvider: .clang), - ]) + checkOccurrences( + getOccs(), + expected: [ + ddecl.at(ws.testLoc("D:def"), roles: .definition, symbolProvider: .clang), + ddecl.at(ws.testLoc("D:ref"), roles: .reference, symbolProvider: .clang), + ddecl.at(ws.testLoc("D:ref:e.mm"), roles: .reference, symbolProvider: .clang), + ] + ) - let outUnitEMM = try XCTUnwrap(indexOutputPaths.first{ $0.hasSuffix("-e.mm.o") }) + let outUnitEMM = try XCTUnwrap(indexOutputPaths.first { $0.hasSuffix("-e.mm.o") }) index.removeUnitOutFilePaths([outUnitEMM], waitForProcessing: true) - checkOccurrences(getOccs(), expected: [ - ddecl.at(ws.testLoc("D:def"), roles: .definition, symbolProvider: .clang), - ddecl.at(ws.testLoc("D:ref"), roles: .reference, symbolProvider: .clang), - ]) + checkOccurrences( + getOccs(), + expected: [ + ddecl.at(ws.testLoc("D:def"), roles: .definition, symbolProvider: .clang), + ddecl.at(ws.testLoc("D:ref"), roles: .reference, symbolProvider: .clang), + ] + ) // The bridging header is referenced as a PCH unit dependency, make sure we can see the data. let bhdecl = Symbol(usr: "c:@F@bridgingHeader", name: "bridgingHeader", kind: .function, language: .c) let bridgingHeaderOccs = index.occurrences(ofUSR: bhdecl.usr, roles: .all) - checkOccurrences(bridgingHeaderOccs, expected: [ - bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), - bhdecl.with(name: "bridgingHeader()", language: .swift).at(ws.testLoc("bridgingHeader:call"), roles: .call, symbolProvider: .swift), - ]) + checkOccurrences( + bridgingHeaderOccs, + expected: [ + bhdecl.at(ws.testLoc("bridgingHeader:decl"), roles: .declaration, symbolProvider: .clang), + bhdecl.with(name: "bridgingHeader()", language: .swift).at( + ws.testLoc("bridgingHeader:call"), + roles: .call, + symbolProvider: .swift + ), + ] + ) } func testSymbolsInFileC() throws { @@ -624,7 +788,10 @@ final class IndexTests: XCTestCase { testSymbolsInFilePath(with: inputs, usingIndex: ws.index) } - func testSymbolsInFilePath(with inputs: [(path: String, expectedSymbolNames: [String])], usingIndex subject: IndexStoreDB) { + func testSymbolsInFilePath( + with inputs: [(path: String, expectedSymbolNames: [String])], + usingIndex subject: IndexStoreDB + ) { for (path, expectedSymbolNames) in inputs { let actualSymbolNames = subject.symbols(inFilePath: path).map(\.name) XCTAssertEqual(actualSymbolNames.sorted(), expectedSymbolNames.sorted()) @@ -637,29 +804,65 @@ final class IndexTests: XCTestCase { try ws.buildAndIndex() - let asyncFuncSym = Symbol(usr: "s:4main9asyncFuncyyYaF", name: "asyncFunc()", kind: .function, properties: .swiftAsync, language: .swift) + let asyncFuncSym = Symbol( + usr: "s:4main9asyncFuncyyYaF", + name: "asyncFunc()", + kind: .function, + properties: .swiftAsync, + language: .swift + ) let asyncFuncOccs = index.occurrences(ofUSR: asyncFuncSym.usr, roles: .definition) - checkOccurrences(asyncFuncOccs, expected: [ - asyncFuncSym.at(ws.testLoc("asyncFunc:def"), roles: .definition, symbolProvider: .swift) - ]) + checkOccurrences( + asyncFuncOccs, + expected: [ + asyncFuncSym.at(ws.testLoc("asyncFunc:def"), roles: .definition, symbolProvider: .swift) + ] + ) - let asyncMethSym = Symbol(usr: "s:4main8MyStructV11asyncMethodyyYaF", name: "asyncMethod()", kind: .instanceMethod, properties: .swiftAsync, language: .swift) + let asyncMethSym = Symbol( + usr: "s:4main8MyStructV11asyncMethodyyYaF", + name: "asyncMethod()", + kind: .instanceMethod, + properties: .swiftAsync, + language: .swift + ) let asyncMethOccs = index.occurrences(ofUSR: asyncMethSym.usr, roles: .definition) - checkOccurrences(asyncMethOccs, expected: [ - asyncMethSym.at(ws.testLoc("asyncMethod:def"), roles: .definition, symbolProvider: .swift) - ]) + checkOccurrences( + asyncMethOccs, + expected: [ + asyncMethSym.at(ws.testLoc("asyncMethod:def"), roles: .definition, symbolProvider: .swift) + ] + ) - let testMeSym = Symbol(usr: "s:4main10MyTestCaseC6testMeyyF", name: "testMe()", kind: .instanceMethod, properties: .unitTest, language: .swift) + let testMeSym = Symbol( + usr: "s:4main10MyTestCaseC6testMeyyF", + name: "testMe()", + kind: .instanceMethod, + properties: .unitTest, + language: .swift + ) let testMeOccs = index.occurrences(ofUSR: testMeSym.usr, roles: .definition) - checkOccurrences(testMeOccs, expected: [ - testMeSym.at(ws.testLoc("testMe:def"), roles: .definition, symbolProvider: .swift) - ]) + checkOccurrences( + testMeOccs, + expected: [ + testMeSym.at(ws.testLoc("testMe:def"), roles: .definition, symbolProvider: .swift) + ] + ) - let testMeAsyncSym = Symbol(usr: "s:4main10MyTestCaseC11testMeAsyncyyYaF", name: "testMeAsync()", kind: .instanceMethod, properties: [.unitTest, .swiftAsync], language: .swift) + let testMeAsyncSym = Symbol( + usr: "s:4main10MyTestCaseC11testMeAsyncyyYaF", + name: "testMeAsync()", + kind: .instanceMethod, + properties: [.unitTest, .swiftAsync], + language: .swift + ) let testMeAsyncOccs = index.occurrences(ofUSR: testMeAsyncSym.usr, roles: .definition) - checkOccurrences(testMeAsyncOccs, expected: [ - testMeAsyncSym.at(ws.testLoc("testMeAsync:def"), roles: .definition, symbolProvider: .swift) - ]) + checkOccurrences( + testMeAsyncOccs, + expected: [ + testMeAsyncSym.at(ws.testLoc("testMeAsync:def"), roles: .definition, symbolProvider: .swift) + ] + ) } func testConcepts() throws { @@ -670,9 +873,12 @@ final class IndexTests: XCTestCase { let largeType = Symbol(usr: "c:@CT@LargeType", name: "LargeType", kind: .concept, language: .c) let largeTypeOccs = ws.index.occurrences(ofUSR: largeType.usr, roles: .all) - checkOccurrences(largeTypeOccs, expected: [ - largeType.at(ws.testLoc("LargeType:def"), roles: .definition, symbolProvider: .swift), - largeType.at(ws.testLoc("LargeType:ref"), roles: .reference, symbolProvider: .swift), - ]) + checkOccurrences( + largeTypeOccs, + expected: [ + largeType.at(ws.testLoc("LargeType:def"), roles: .definition, symbolProvider: .swift), + largeType.at(ws.testLoc("LargeType:ref"), roles: .reference, symbolProvider: .swift), + ] + ) } } diff --git a/Tests/IndexStoreDBTests/LocationScannerTests.swift b/Tests/IndexStoreDBTests/LocationScannerTests.swift index 386770e5..f41b1510 100644 --- a/Tests/IndexStoreDBTests/LocationScannerTests.swift +++ b/Tests/IndexStoreDBTests/LocationScannerTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import IndexStoreDB import ISDBTestSupport +import IndexStoreDB import XCTest final class LocationScannerTests: XCTestCase { @@ -30,8 +30,8 @@ final class LocationScannerTests: XCTestCase { _ name: String, _ line: Int, utf8Column: Int, - utf16Column: Int) - { + utf16Column: Int + ) { self.url = url self.name = name self.line = line @@ -46,13 +46,14 @@ final class LocationScannerTests: XCTestCase { init(_ name: String, _ loc: TestLocation) { self.init( url: loc.url, - name, loc.line, + name, + loc.line, utf8Column: loc.utf8Column, - utf16Column: loc.utf16Column) + utf16Column: loc.utf16Column + ) } - static func <(a: Loc, b: Loc) -> Bool { - return (a.url.absoluteString, a.line, a.utf8Column, a.name) < - (b.url.absoluteString, b.line, b.utf8Column, b.name) + static func < (a: Loc, b: Loc) -> Bool { + return (a.url.absoluteString, a.line, a.utf8Column, a.name) < (b.url.absoluteString, b.line, b.utf8Column, b.name) } } @@ -103,53 +104,86 @@ final class LocationScannerTests: XCTestCase { func testLocation() throws { XCTAssertEqual(try scanString("/*a*/"), [Loc("a", 1, 6)]) XCTAssertEqual(try scanString(" /*a*/"), [Loc("a", 1, 9)]) - XCTAssertEqual(try scanString(""" - - /*a*/ - """), [Loc("a", 2, 6)]) - XCTAssertEqual(try scanString(""" - - - /*a*/ - """), [Loc("a", 3, 6)]) - XCTAssertEqual(try scanString(""" - a - b - /*a*/ - """), [Loc("a", 3, 6)]) - XCTAssertEqual(try scanString(""" - a - - b /*a*/ - """), [Loc("a", 3, 8)]) - XCTAssertEqual(try scanString(""" - - /*a*/ - - """), [Loc("a", 2, 6)]) + XCTAssertEqual( + try scanString( + """ + + /*a*/ + """ + ), + [Loc("a", 2, 6)] + ) + XCTAssertEqual( + try scanString( + """ + + + /*a*/ + """ + ), + [Loc("a", 3, 6)] + ) + XCTAssertEqual( + try scanString( + """ + a + b + /*a*/ + """ + ), + [Loc("a", 3, 6)] + ) + XCTAssertEqual( + try scanString( + """ + a + + b /*a*/ + """ + ), + [Loc("a", 3, 8)] + ) + XCTAssertEqual( + try scanString( + """ + + /*a*/ + + """ + ), + [Loc("a", 2, 6)] + ) } func testMultiple() throws { - XCTAssertEqual(try scanString(""" - func /*f*/f() { - /*g:call*/g(/*g:arg1*/1) - }/*end*/ - """), [ + XCTAssertEqual( + try scanString( + """ + func /*f*/f() { + /*g:call*/g(/*g:arg1*/1) + }/*end*/ + """ + ), + [ Loc("f", 1, 11), Loc("g:call", 2, 13), Loc("g:arg1", 2, 25), Loc("end", 3, 9), - ]) + ] + ) } func testLeft() throws { XCTAssertEqual(try scanString("/*a*/"), [Loc("a", 1, 6)]) XCTAssertEqual(try scanString("/*