How to use Background Indexing in sourcekit-lsp?

The sourcekit-lsp documentation at sourcekit-lsp/Documentation/Enable Experimental Background Indexing.md at main · swiftlang/sourcekit-lsp · GitHub
says:

Background indexing in SourceKit-LSP is enabled by default in Swift 6.1 toolchains and above.

With background indexing disabled, SourceKit-LSP does not update its global index in the background or build Swift modules in the background. Thus, a lot of cross-module or global functionality is limited if the project hasn't been built recently. For example, consider two modules: Lib and Exec, where Exec depends on Lib: Without background indexing, if a function is added to Lib, completion/jump to definition/etc in Exec would not be able to see that function until after a build. Background indexing solves that issue.

The documentation mentions example modules Lib and Exec. But IMHO the same should apply to different source files within one module. For example, if I have main.swift and helpers.swift files in my swiftPM project, then I open my project folder with VS Code, declare a new let fooConst = 42 in helpers.swift, then start typing foo in main.swift, then I don't see fooConst in code suggestions, until I rebuild the project or close it and reopen in VS Code.

Can this be fixed somehow? Should my code editor (e.g. VS Code or similar) issue a special reindex request to sourcekit-lsp? @ahoppen

That is odd, cross-file functionality within the same module doesn’t require background indexing. Could you file an issue for this at GitHub · Where software is built?

This is really strange. I started filing an issue on Github, and found that actually the missing code suggestion is shown, but only when you type more characters. When the new identifier is added in the same file, one character is enough, but when it is added in a different file, more characters are required. Here are steps to reproduce:

  1. Create a Swift package:
mkdir test
cd test
swift package init --type executable
  1. Add a new Swift file in the Sources folder of the package, e.g. helpers.swift in addition to the default main.swift .
  2. Open the test package folder in Visual Studio Code.
  3. Edit the helpers.swift in VS Code: add for example let zzzConst = 42 .
  4. Switch to main.swift file in VS Code and type something that would use the new constant from helpers.swift, e.g "let aaa = z"
  5. Code completion does not show zzzConst (shows only two suggestions starting with "zip")
  6. Add more text, now "let aaa = zz"
  7. Code completion does not show any suggestions at all.
  8. Add more text, now "let aaa = zzz"
  9. At last zzzConst appears in code suggestions.

Not sure if I still should file an issue. This behavior still looks wrong to me, though the missing code suggestion is ultimately shown.

Filed an issue Code completion does not show cross-file new identifiers (unless more characters are typed) · Issue #2122 · swiftlang/sourcekit-lsp · GitHub

1 Like