Skip to content

Commit 9f5f06b

Browse files
authored
Merge pull request #2032 from ahoppen/ahoppen/response-file-indexing
Use response files to index files if argument list exceeds maximum number of arguments
2 parents f6a29f4 + 5541060 commit 9f5f06b

File tree

6 files changed

+170
-7
lines changed

6 files changed

+170
-7
lines changed

Sources/BuildSystemIntegration/BuildSettingsLogger.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ package actor BuildSettingsLogger {
4848
"""
4949

5050
let chunks = splitLongMultilineMessage(message: log)
51-
for (index, chunk) in chunks.enumerated() {
51+
// Only print the first 100 chunks. If the argument list gets any longer, we don't want to spam the log too much.
52+
// In practice, 100 chunks should be sufficient.
53+
for (index, chunk) in chunks.enumerated().prefix(100) {
5254
logger.log(
5355
level: level,
5456
"""

Sources/SKTestSupport/BuildServerTestProject.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ package class BuildServerTestProject: MultiFileTestProject {
6565
buildServerConfigLocation: RelativeFileLocation = ".bsp/sourcekit-lsp.json",
6666
buildServer: String,
6767
options: SourceKitLSPOptions? = nil,
68+
enableBackgroundIndexing: Bool = false,
6869
testName: String = #function
6970
) async throws {
7071
var files = files
@@ -92,6 +93,7 @@ package class BuildServerTestProject: MultiFileTestProject {
9293
try await super.init(
9394
files: files,
9495
options: options,
96+
enableBackgroundIndexing: enableBackgroundIndexing,
9597
testName: testName
9698
)
9799
}

Sources/SKTestSupport/INPUTS/AbstractBuildServer.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ def handle_message(self, message: Dict[str, object]) -> Optional[Dict[str, objec
7070
return self.initialized(params)
7171
elif method == "build/shutdown":
7272
return self.shutdown(params)
73+
elif method == "buildTarget/prepare":
74+
return self.buildtarget_prepare(params)
7375
elif method == "buildTarget/sources":
7476
return self.buildtarget_sources(params)
7577
elif method == "textDocument/registerForChanges":
@@ -80,6 +82,8 @@ def handle_message(self, message: Dict[str, object]) -> Optional[Dict[str, objec
8082
return self.workspace_did_change_watched_files(params)
8183
elif method == "workspace/buildTargets":
8284
return self.workspace_build_targets(params)
85+
elif method == "workspace/waitForBuildSystemUpdates":
86+
return self.workspace_waitForBuildSystemUpdates(params)
8387

8488
# ignore other notifications
8589
if "id" in message:
@@ -120,10 +124,8 @@ def initialize(self, request: Dict[str, object]) -> Dict[str, object]:
120124
"version": "0.1",
121125
"bspVersion": "2.0",
122126
"rootUri": "blah",
123-
"capabilities": {"languageIds": ["a", "b"]},
127+
"capabilities": {"languageIds": ["swift", "c", "cpp", "objective-c", "objective-c"]},
124128
"data": {
125-
"indexDatabasePath": "some/index/db/path",
126-
"indexStorePath": "some/index/store/path",
127129
"sourceKitOptionsProvider": True,
128130
},
129131
}
@@ -144,6 +146,11 @@ def textdocument_sourcekitoptions(
144146
def shutdown(self, request: Dict[str, object]) -> Dict[str, object]:
145147
return {}
146148

149+
def buildtarget_prepare(self, request: Dict[str, object]) -> Dict[str, object]:
150+
raise RequestError(
151+
code=-32601, message=f"'buildTarget/prepare' not implemented"
152+
)
153+
147154
def buildtarget_sources(self, request: Dict[str, object]) -> Dict[str, object]:
148155
raise RequestError(
149156
code=-32601, message=f"'buildTarget/sources' not implemented"
@@ -157,6 +164,9 @@ def workspace_build_targets(self, request: Dict[str, object]) -> Dict[str, objec
157164
code=-32601, message=f"'workspace/buildTargets' not implemented"
158165
)
159166

167+
def workspace_waitForBuildSystemUpdates(self, request: Dict[str, object]) -> Dict[str, object]:
168+
return {}
169+
160170

161171
class LegacyBuildServer(AbstractBuildServer):
162172
def send_sourcekit_options_changed(self, uri: str, options: List[str]):

Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import TSCExtensions
2424
import struct TSCBasic.AbsolutePath
2525
import class TSCBasic.Process
2626
import struct TSCBasic.ProcessResult
27+
import enum TSCBasic.SystemError
2728
#else
2829
import BuildServerProtocol
2930
import BuildSystemIntegration
@@ -38,6 +39,11 @@ import TSCExtensions
3839
import struct TSCBasic.AbsolutePath
3940
import class TSCBasic.Process
4041
import struct TSCBasic.ProcessResult
42+
import enum TSCBasic.SystemError
43+
#endif
44+
45+
#if os(Windows)
46+
import WinSDK
4147
#endif
4248

4349
private let updateIndexStoreIDForLogging = AtomicUInt32(initialValue: 1)
@@ -418,7 +424,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription {
418424
let result: ProcessResult
419425
do {
420426
result = try await withTimeout(timeout) {
421-
try await Process.run(
427+
try await Process.runUsingResponseFileIfTooManyArguments(
422428
arguments: processArguments,
423429
workingDirectory: workingDirectory,
424430
outputRedirection: .stream(
@@ -475,3 +481,66 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription {
475481
}
476482
}
477483
}
484+
485+
fileprivate extension Process {
486+
/// Run a process with the given arguments. If the number of arguments exceeds the maximum number of arguments allows,
487+
/// create a response file and use it to pass the arguments.
488+
static func runUsingResponseFileIfTooManyArguments(
489+
arguments: [String],
490+
workingDirectory: AbsolutePath?,
491+
outputRedirection: OutputRedirection = .collect(redirectStderr: false)
492+
) async throws -> ProcessResult {
493+
do {
494+
return try await Process.run(
495+
arguments: arguments,
496+
workingDirectory: workingDirectory,
497+
outputRedirection: outputRedirection
498+
)
499+
} catch {
500+
let argumentListTooLong: Bool
501+
#if os(Windows)
502+
if let error = error as? CocoaError {
503+
argumentListTooLong =
504+
error.underlyingErrors.contains(where: {
505+
return ($0 as NSError).domain == "org.swift.Foundation.WindowsError"
506+
&& ($0 as NSError).code == ERROR_FILENAME_EXCED_RANGE
507+
})
508+
} else {
509+
argumentListTooLong = false
510+
}
511+
#else
512+
if case SystemError.posix_spawn(E2BIG, _) = error {
513+
argumentListTooLong = true
514+
} else {
515+
argumentListTooLong = false
516+
}
517+
#endif
518+
519+
guard argumentListTooLong else {
520+
throw error
521+
}
522+
523+
logger.debug("Argument list is too long. Using response file.")
524+
let responseFile = FileManager.default.temporaryDirectory.appendingPathComponent(
525+
"index-response-file-\(UUID()).txt"
526+
)
527+
defer {
528+
orLog("Failed to remove temporary response file") {
529+
try FileManager.default.removeItem(at: responseFile)
530+
}
531+
}
532+
FileManager.default.createFile(atPath: try responseFile.filePath, contents: nil)
533+
let handle = try FileHandle(forWritingTo: responseFile)
534+
for argument in arguments.dropFirst() {
535+
handle.write(Data((argument.spm_shellEscaped() + "\n").utf8))
536+
}
537+
try handle.close()
538+
539+
return try await Process.run(
540+
arguments: arguments.prefix(1) + ["@\(responseFile.filePath)"],
541+
workingDirectory: workingDirectory,
542+
outputRedirection: outputRedirection
543+
)
544+
}
545+
}
546+
}

Sources/SourceKitLSP/Swift/DocumentFormatting.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import TSCExtensions
2323

2424
import struct TSCBasic.AbsolutePath
2525
import class TSCBasic.Process
26-
import func TSCBasic.withTemporaryFile
2726
#else
2827
import Foundation
2928
import LanguageServerProtocol
@@ -37,7 +36,6 @@ import TSCExtensions
3736

3837
import struct TSCBasic.AbsolutePath
3938
import class TSCBasic.Process
40-
import func TSCBasic.withTemporaryFile
4139
#endif
4240

4341
fileprivate extension String {

Tests/SourceKitLSPTests/BackgroundIndexingTests.swift

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2081,6 +2081,88 @@ final class BackgroundIndexingTests: XCTestCase {
20812081
return hoverAfterAddingDependencyDeclaration != nil
20822082
}
20832083
}
2084+
2085+
func testUseResponseFileIfTooManyArguments() async throws {
2086+
// The build system returns too many arguments to fit them into a command line invocation, so we need to use a
2087+
// response file to invoke the indexer.
2088+
2089+
let project = try await BuildServerTestProject(
2090+
files: [
2091+
// File name contains a space to ensure we escape it in the response file.
2092+
"Test File.swift": """
2093+
func 1️⃣myTestFunc() {}
2094+
"""
2095+
],
2096+
buildServer: """
2097+
class BuildServer(AbstractBuildServer):
2098+
2099+
def initialize(self, request: Dict[str, object]) -> Dict[str, object]:
2100+
return {
2101+
"displayName": "test server",
2102+
"version": "0.1",
2103+
"bspVersion": "2.0",
2104+
"rootUri": "blah",
2105+
"capabilities": {"languageIds": ["swift", "c", "cpp", "objective-c", "objective-c"]},
2106+
"data": {
2107+
"indexDatabasePath": r"$TEST_DIR/index-db",
2108+
"indexStorePath": r"$TEST_DIR/index",
2109+
"prepareProvider": True,
2110+
"sourceKitOptionsProvider": True,
2111+
},
2112+
}
2113+
2114+
def workspace_build_targets(self, request: Dict[str, object]) -> Dict[str, object]:
2115+
return {
2116+
"targets": [
2117+
{
2118+
"id": {"uri": "bsp://dummy"},
2119+
"tags": [],
2120+
"languageIds": [],
2121+
"dependencies": [],
2122+
"capabilities": {},
2123+
}
2124+
]
2125+
}
2126+
2127+
def buildtarget_sources(self, request: Dict[str, object]) -> Dict[str, object]:
2128+
return {
2129+
"items": [
2130+
{
2131+
"target": {"uri": "bsp://dummy"},
2132+
"sources": [
2133+
{"uri": "$TEST_DIR_URL/Test.swift", "kind": 1, "generated": False}
2134+
],
2135+
}
2136+
]
2137+
}
2138+
2139+
def textdocument_sourcekitoptions(self, request: Dict[str, object]) -> Dict[str, object]:
2140+
return {
2141+
"compilerArguments": [r"$TEST_DIR/Test File.swift", "-DDEBUG", $SDK_ARGS] + \
2142+
[f"-DTHIS_IS_AN_OPTION_THAT_CONTAINS_MANY_BYTES_{i}" for i in range(0, 50_000)]
2143+
}
2144+
2145+
def buildtarget_prepare(self, request: Dict[str, object]) -> Dict[str, object]:
2146+
return {}
2147+
""",
2148+
enableBackgroundIndexing: true
2149+
)
2150+
try await project.testClient.send(PollIndexRequest())
2151+
2152+
let symbols = try await project.testClient.send(WorkspaceSymbolsRequest(query: "myTestFunc"))
2153+
XCTAssertEqual(
2154+
symbols,
2155+
[
2156+
.symbolInformation(
2157+
SymbolInformation(
2158+
name: "myTestFunc()",
2159+
kind: .function,
2160+
location: try project.location(from: "1️⃣", to: "1️⃣", in: "Test File.swift")
2161+
)
2162+
)
2163+
]
2164+
)
2165+
}
20842166
}
20852167

20862168
extension HoverResponseContents {

0 commit comments

Comments
 (0)