Implementing an LSP for XBPS (Void Linux) packages templates

  • 5 min read

As you might (or might not) know, I'm maintaining some packages for Void Linux in my free time (packages I maintain). Void Linux is a rolling release Linux distribution (similar to Arch), with the difference that it is (at least from my experience) much more stable. The package manager is uses is called xbps, short for X Binary Package System. Void Linux already has a great manual on adding new packages to the official Void Linux repositories by writing XBPS package templates.

XBPS templates

XBPS templates are basically recipes that contain the steps required to build a package, e.g. something like cargo build and cargo install for Rust packages). A very simple template looks like this (taken from void-packages):

# Template file for 'buf'
pkgname=buf
version=1.71.0
revision=2
build_style=go
go_import_path=github.com/bufbuild/buf
go_package="${go_import_path}/cmd/buf"
short_desc="Protobuf language server"
maintainer="Bnyro <bnyro@tutanota.com>"
license="Apache-2.0"
homepage="https://buf.build"
changelog="https://raw.githubusercontent.com/bufbuild/buf/refs/heads/main/CHANGELOG.md"
distfiles="https://github.com/bufbuild/buf/archive/refs/tags/v${version}.tar.gz"
checksum=fad7621cfcf54891a7b1c82c060b7a54c2ad6d13e0a1c99aea2d744e43bc82b7
make_check=no

I've already written templates like this for a bunch of packages, so I could claim that I am already kind of familiar with how XBPS templates and the possible configuration options work. However, I still find myself looking into the manual quite a lot of times, e.g. because I forget the specific name of a package template variable that's not used often. What if there was an LSP tool that can provide me with auto completions, documentation on hover and diagnostics about possible errors in XBPS package templates? Surprise, that's what xbps-lsp does. I wrote it on a weekend, so it doesn't have a lot of features, but it does enough to make the experience when writing XBPS package templates much more pleasant.

xbps-lsp features

Short demo:

As of now, xbps-lsp has three main features:

  • linter diagnostics via xlint (the tool also used by the Void Linux CI)
  • hover information on variables/functions, automatically generated from Void Linux's Manual.md
  • diagnostic that shows if the version of the package is not up to date (i.e. a wrapper around ./xbps-src update-check <pkgname>)

Going in depth on the specific xbps-lsp implementation is beyond the scope of this post, we only want to quickly look into the basic idea behind how tower-lsp can be used to implement an LSP server.

LSP protocol

The Language Server Protocol is a specification how LSP servers (the program that analyzes your source code and provides hints, e.g. rust-analyzer) should communicate with LSP clients (e.g. text editors).

flowchart LR
    subgraph te[Text Editor]
      direction RL
      client[LSP client] --> ui[Editor UI]
    end
    subgraph ls[Language Server]
      direction RL
      server[LSP server]
      etc[...] --> server
      diags[Diagnostics] --> server
      compls[Completions] --> server
    end

    te <-. Language Server Protocol .-> ls
LSP client-server architecture in a nutshell (the "Language Server Protocol" edge should be between "LSP client" and "LSP server", I lost when fighting against directions in Mermaid subgraphs)

The nice thing about this is that the LSP client protocol is implemented by many different text editors, including VSCode, Helix, Vim, …. As a result, language servers that implement the LSP protocol are not limited to a single text editor or IDE, you can use them with whichever you prefer.

The tower-lsp crate

tower-lsp is an LSP server (see diagram above) framework. It allows you to implement LSPs in Rust even if you have no idea how the Language Server Protocol (LSP) works (like me). In essence, you can pass diagnostics, auto-completions, etc. to tower-lsp and it translates these into the Language Server Protocol so that the information can be forwarded by the LSP client (and then show by e.g. your text editor). The name tower-lsp comes from the tower framework which tower-lsp uses internally for handling the networking part (i.e. communication with the LSP client). The original tower-lsp doesn't seem to be maintained anymore, so there is a maintained fork of it: tower-lsp-community. There's also async-lsp which claims to be similar and a bit more modern, but I haven't used it yet.

The boilerplate code for using it looks as following (please refer to the minimal example from tower-lsp's docs):

#[derive(Debug)]
struct Backend {
    client: Client,
}

impl LanguageServer for Backend {
    async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                hover_provider: Some(HoverProviderCapability::Simple(true)),
                completion_provider: Some(CompletionOptions::default()),
                ..Default::default()
            },
            ..Default::default()
        })
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }
}

#[tokio::main]
async fn main() {
    let stdin = tokio::io::stdin();
    let stdout = tokio::io::stdout();

    let (service, socket) = LspService::new(|client| Backend { client });
    Server::new(stdin, stdout, socket).serve(service).await;
}

The most interesting part here is the initialize method. It allows you to define the capabilities your language server implementation has. For example, if you want to support hover information, you can enable the hover_provider capability, or if you want to provide diagnostics, you can enable the diagnostic_provider, …. Each of the providers you can enable has its own method that is automatically called by the tower-lsp when needed. The (probably) simplest provider to get started with is the completion provider, which provides auto-completions while typing code

impl LanguageServer for Backend {
    async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                completion_provider: Some(CompletionOptions::default()),
                ..Default::default()
            },
            ..Default::default()
        })
    }

    async fn completion(
        &self,
        _: tower_lsp_server::ls_types::CompletionParams,
    ) -> Result<Option<tower_lsp_server::ls_types::CompletionResponse>> {
        Ok(Some(
          vec![CompletionItem {
            label: String::from("Hello World"),
            ..Default::default()
          }].into()
        ))
    }
}

If you now install this with cargo install --path . and configure your text editor to use the LSP server binary you just installed (e.g. as done here for Helix editor), you should see Hello World pop up as auto-completed suggestion when typing Hel. Nice!

Obviously that's just a very simple example, I only included it here to give you an intuition for how tower-lsp works. Please see tower-lsp-boilerplate for more advanced examples.

xbps-lsp implementation

There's not a lot to say about the specific xbps-lsp implementation, it's pretty much fetching diagnostics from xlint and documentation from Manual.md and wraps them into the LSPServer trait's functionality by implementing the corresponding hover, completion, … providers.

One thing I found very ugly is the implementation of diagnostics. tower-lsp has a method called diagnostic, and I thought I would just need to implement that method to support diagnostics (show code warnings, errors, …). However, contrary to the other providers that use a polling-based approach (i.e. automatically call the corresponding method in LSPServer), diagnostics seem to use a push-based approach. This means that whenever the document has changed (you can listen for that with did_open and did_change), you have to manually emit the diagnostics by calling self.client.publish_diagnostics(...) with the diagnostics you generated (see code here). Pull Diagnostics apparently have been introduced recently and are therefore not yet widely supported, so maybe it'll be possible in the future once my editor of choice (Helix) supports it :)

Closing words

If you're interested you can find the xbps-lsp project and setup instructions on GitHub. I'll eventually try to get it into the official Void Linux package repositories some day, but it's not there yet. Thanks for reading!