Skip to content

Add richer LSP server example (#20017) #20187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/lsp-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,7 @@ ctrlc = "3.4.7"

[lints]
workspace = true

[[example]]
name = "completion_and_formatting"
path = "examples/completion_and_formatting.rs"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need this because the new example code is located inside examples/

69 changes: 69 additions & 0 deletions lib/lsp-server/examples/completion_and_formatting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//! rust-analyzer LSP example
//!
//! A minimal Language Server Protocol server demonstrating how to embed
//! `rust-analyzer` as a library. To run it:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"embed rust-analyzer" is not a right term here. This lsp-server is just a crate that rust-analyzer dogfoods on to handle lsp requests and responses.
So, the examples are not for rust-analyer or embedding. They just show how to use this "library"

//! ```bash
//! cargo run --example rust_analyzer_lsp_example
//
#![allow(clippy::print_stderr)]

type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
use lsp_server::{Connection, Message};
use lsp_types::{
CompletionParams, DidChangeTextDocumentParams, DocumentFormattingParams, OneOf,
ServerCapabilities, TextDocumentSyncKind, TextDocumentSyncOptions,
request::{Completion, Formatting, Request as LspRequest},
};
use serde_json::json;

fn main() -> Result<()> {
// Set up a JSON-RPC connection over stdio
let (connection, io_threads) = Connection::stdio();

// Perform the initialize handshake and advertise capabilities
let (init_id, _init_params) = connection.initialize_start()?;
let capabilities = ServerCapabilities {
text_document_sync: Some(
TextDocumentSyncOptions {
change: Some(TextDocumentSyncKind::FULL),
..Default::default()
}
.into(),
),
completion_provider: Some(Default::default()),
document_formatting_provider: Some(OneOf::Left(true)),
..Default::default()
};
connection.initialize_finish(init_id, json!({ "capabilities": capabilities }))?;

// Enter the main message loop
for message in connection.receiver.iter() {
match message {
Message::Notification(notification)
if notification.method == "textDocument/didChange" =>
{
let params: DidChangeTextDocumentParams =
serde_json::from_value(notification.params).unwrap();
eprintln!("Document changed: {}", params.text_document.uri);
}
Message::Request(request) if request.method == Completion::METHOD => {
let _: CompletionParams = serde_json::from_value(request.params).unwrap();
let response = lsp_server::Response::new_ok(
request.id,
json!({ "isIncomplete": false, "items": [] }),
);
connection.sender.send(Message::Response(response)).unwrap();
}
Message::Request(request) if request.method == Formatting::METHOD => {
let _: DocumentFormattingParams = serde_json::from_value(request.params).unwrap();
let response = lsp_server::Response::new_ok(request.id, json!([]));
connection.sender.send(Message::Response(response)).unwrap();
}
Message::Request(request) if connection.handle_shutdown(&request)? => break,
_ => {} // ignore all other messages
}
}

io_threads.join().unwrap();
Ok(())
}