How do I use SourceKit with SwiftPM?

How do I make a SourceKit request on a file that's part of a Swift Package? I assume it's possible, I mean, Xcode does it, right?

I can use SourceKit to ask for expression types in a standalone file using this YAML:

{
	key.request: source.request.expression.type,
	key.compilerargs: [
		"/Users/vini/Desktop/main.swift",
		"-sdk",
		"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk"
	],
	key.sourcefile: "/Users/vini/Desktop/main.swift"
}

but the compilerargs key seems to need flags for a successful swiftc compilation, and I don't know how I'd turn that into something like swift build...

Paging @blangmuir

I suggest looking at SourceKit-LSP, which has support for swiftpm packages via libSwiftPM. It uses sourcekitd for its underlying swift support. We don't have anything that uses source.request.expression.type currently, but you could probably build on top of our code to do what you need.

Just to be clear, do you mean look into how SourceKit-LSP uses SourceKit and libSwiftPM or look into using SourceKit-LSP instead of SourceKit and libSwiftPM?

Without knowing more, I'm not sure how easily you could use sourcekit-lsp as a library for what you're building. That's something we want to make easier and more extensible in the future, but it may not be very convenient in terms of its public API right now. But if using it as a library doesn't fit, you could still copy and modify the implementation to suit your needs.

Ok then. My program is based on SwiftPM itself, and sourcekit-lsp has a Package.swift file which declares two libraries, _SourceKitLSP and LSPBindings. Could I use one of those?

And if I have to look into its code, could you point me to where the relevant SwiftPM/SourceKit calls might be?

The sourcekitd calls come from the files in Sources/SourceKitLSP/Swift, using a swift wrapper API for sourcekitd.

The swiftpm code is in SwiftPMWorkspace.swift.