Eclipse LSP4J is here!
This week the LSP4J repository finally got created and filled with the initial contributions. LSP4J is a Java binding of Microsoft’s Language Server Protocol (LSP) with a Java implementation of the extended JSON RPC v2.0 the LSP is based on. The project aims at simplifying implementation of a LanguageClient (an editor) or a LanguageServer (e.g. a modern compiler) in Java. Here is a short introduction of how to use it.
Implement your language server (or client)
The first thing you should do is to implement your language server. To do so just implement the interface org.eclipse.lsp4j.LanguageServer. If you are implementing a client (e.g. an editor) you would need to implement org.eclipse.lsp4j.LanguageClient instead.
Launch and connect with the other end
Now that you have an actual implementation you can connect it with a remote client. Let’s assume you have an Inputstream and an Outputstream, over which you want to communicate with a language client. The utility class LSPLauncher does most of the wiring for you. Here is the code needed.
LanguageServer server = ... ;
Launcher<LanguageClient> launcher = LSPLauncher.createServerLauncher(
server,
inputstream,
outputstream);
With this we have a Launcher object on which we can obtain the remote proxy (of type LanguageClient in this case). Usually a language server should also implement LanguageClientAware, which defines a single method connect(LanguageClient) over which you can pass the remote proxy to the language server.
if (server instanceof LanguageClientAware) {
LanguageClient client = launcher.getRemoteProxy();
((LanguageClientAware)server).connect(client);
}
Now your language server is not only able to receive messages from the other side, but can send messages back as well.
The final thing you need to to do in order to start listening on the given input stream, is calling launcher.startListening();
This will start the listening process in a new thread.
Underlying concepts
As mentioned in the beginning LSP4J is based on JSON RPC. The implementation is completely independent of the LSP, so can be used for other protocols. Also we made sure that it is easy to extend the LSP with new messages. This is important to bridge the last non-standard 20% and to prototype possible extensions for the LSP. We are for instance currently experimenting with support for semantic coloring and will submit an enhancement request once we are happy with it. Please refer to the documentation to learn more about the JSON RPC layer.
About the Author
Sven Efftinge
Sven loves finding sweet spots in product development. Always keeping an eye on pragmatism and the real benefit for the end user, he has proven to be a creative source for many sucessful technologies. He is a co-founder of TypeFox, co-lead of Eclipse Theia and product manager of Gitpod.