feat: implement LSP document lifecycle
This commit is contained in:
parent
837b1fce55
commit
453f99f70d
|
|
@ -1,10 +1,14 @@
|
|||
//! Language-server adapter scaffold.
|
||||
//! Stdio language-server adapter.
|
||||
|
||||
#[path = "editor_help.rs"]
|
||||
mod editor_help;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Parser;
|
||||
use miette::{Result, miette};
|
||||
use john_slop::{ConfigLoader, ConfigName, lsp::LspBackend};
|
||||
use miette::Result;
|
||||
use tower_lsp_server::{LspService, Server};
|
||||
|
||||
/// Publish John Slop replacement diagnostics and quick fixes over stdio.
|
||||
#[derive(Debug, Parser)]
|
||||
|
|
@ -14,11 +18,24 @@ use miette::{Result, miette};
|
|||
about,
|
||||
after_help = editor_help::EDITOR_SETUP
|
||||
)]
|
||||
struct Cli {}
|
||||
struct Cli {
|
||||
/// Load a named user configuration from the platform config directory.
|
||||
#[arg(long, value_name = "NAME")]
|
||||
config_name: Option<ConfigName>,
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let _cli = Cli::parse();
|
||||
Err(miette!(
|
||||
"john-slop-lsp is not implemented yet; LSP support is planned for Milestone 6"
|
||||
))
|
||||
/// Load an explicit TOML configuration after user configuration.
|
||||
#[arg(long, value_name = "FILE")]
|
||||
config: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
let loader = ConfigLoader::discover(cli.config_name.as_ref(), cli.config)?;
|
||||
let config = loader.load()?;
|
||||
let (service, socket) = LspService::new(|client| LspBackend::new(client, loader, config));
|
||||
Server::new(tokio::io::stdin(), tokio::io::stdout(), socket)
|
||||
.serve(service)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ mod detector;
|
|||
mod diagnostic;
|
||||
mod error;
|
||||
mod input;
|
||||
pub mod lsp;
|
||||
mod model;
|
||||
mod replacement;
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,204 @@
|
|||
//! Language Server Protocol state and adapter implementation.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use tokio::sync::RwLock;
|
||||
use tower_lsp_server::{
|
||||
Client, LanguageServer,
|
||||
jsonrpc::Result,
|
||||
ls_types::{
|
||||
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
|
||||
InitializeParams, InitializeResult, InitializedParams, ServerCapabilities, ServerInfo,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, Uri,
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{Config, ConfigLoader};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct OpenDocument {
|
||||
version: i32,
|
||||
language_id: String,
|
||||
text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct DocumentStore {
|
||||
documents: HashMap<Uri, OpenDocument>,
|
||||
}
|
||||
|
||||
impl DocumentStore {
|
||||
fn open(&mut self, params: DidOpenTextDocumentParams) {
|
||||
let document = params.text_document;
|
||||
self.documents.insert(
|
||||
document.uri,
|
||||
OpenDocument {
|
||||
version: document.version,
|
||||
language_id: document.language_id,
|
||||
text: document.text,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn change(&mut self, params: DidChangeTextDocumentParams) -> bool {
|
||||
let Some(document) = self.documents.get_mut(¶ms.text_document.uri) else {
|
||||
return false;
|
||||
};
|
||||
if params.text_document.version <= document.version {
|
||||
return false;
|
||||
}
|
||||
let [change] = params.content_changes.as_slice() else {
|
||||
return false;
|
||||
};
|
||||
if change.range.is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
document.version = params.text_document.version;
|
||||
document.text.clone_from(&change.text);
|
||||
true
|
||||
}
|
||||
|
||||
fn close(&mut self, uri: &Uri) -> bool {
|
||||
self.documents.remove(uri).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Stdio LSP backend backed by authoritative snapshots of open documents.
|
||||
#[derive(Debug)]
|
||||
pub struct LspBackend {
|
||||
client: Client,
|
||||
_config_loader: ConfigLoader,
|
||||
_config: RwLock<Config>,
|
||||
documents: RwLock<DocumentStore>,
|
||||
}
|
||||
|
||||
impl LspBackend {
|
||||
/// Construct a backend from the same resolved configuration used by other adapters.
|
||||
pub fn new(client: Client, config_loader: ConfigLoader, config: Config) -> Self {
|
||||
Self {
|
||||
client,
|
||||
_config_loader: config_loader,
|
||||
_config: RwLock::new(config),
|
||||
documents: RwLock::new(DocumentStore::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageServer for LspBackend {
|
||||
async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
|
||||
Ok(InitializeResult {
|
||||
server_info: Some(ServerInfo {
|
||||
name: "john-slop-lsp".to_owned(),
|
||||
version: Some(env!("CARGO_PKG_VERSION").to_owned()),
|
||||
}),
|
||||
capabilities: ServerCapabilities {
|
||||
text_document_sync: Some(TextDocumentSyncCapability::Kind(
|
||||
TextDocumentSyncKind::FULL,
|
||||
)),
|
||||
..ServerCapabilities::default()
|
||||
},
|
||||
offset_encoding: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn initialized(&self, _: InitializedParams) {}
|
||||
|
||||
async fn shutdown(&self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn did_open(&self, params: DidOpenTextDocumentParams) {
|
||||
self.documents.write().await.open(params);
|
||||
}
|
||||
|
||||
async fn did_change(&self, params: DidChangeTextDocumentParams) {
|
||||
self.documents.write().await.change(params);
|
||||
}
|
||||
|
||||
async fn did_close(&self, params: DidCloseTextDocumentParams) {
|
||||
let uri = params.text_document.uri;
|
||||
self.documents.write().await.close(&uri);
|
||||
self.client.publish_diagnostics(uri, Vec::new(), None).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::str::FromStr;
|
||||
|
||||
use tower_lsp_server::ls_types::{
|
||||
DidChangeTextDocumentParams, DidOpenTextDocumentParams, TextDocumentContentChangeEvent,
|
||||
TextDocumentItem, Uri, VersionedTextDocumentIdentifier,
|
||||
};
|
||||
|
||||
use super::DocumentStore;
|
||||
|
||||
fn uri() -> Uri {
|
||||
Uri::from_str("file:///tmp/example.txt").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracks_language_version_and_full_document_text() {
|
||||
let mut store = DocumentStore::default();
|
||||
store.open(DidOpenTextDocumentParams {
|
||||
text_document: TextDocumentItem::new(
|
||||
uri(),
|
||||
"plaintext".to_owned(),
|
||||
4,
|
||||
"old".to_owned(),
|
||||
),
|
||||
});
|
||||
assert!(!store.change(DidChangeTextDocumentParams {
|
||||
text_document: VersionedTextDocumentIdentifier::new(uri(), 3),
|
||||
content_changes: vec![TextDocumentContentChangeEvent {
|
||||
range: None,
|
||||
range_length: None,
|
||||
text: "stale".to_owned(),
|
||||
}],
|
||||
}));
|
||||
assert!(store.change(DidChangeTextDocumentParams {
|
||||
text_document: VersionedTextDocumentIdentifier::new(uri(), 5),
|
||||
content_changes: vec![TextDocumentContentChangeEvent {
|
||||
range: None,
|
||||
range_length: None,
|
||||
text: "current".to_owned(),
|
||||
}],
|
||||
}));
|
||||
|
||||
let document = &store.documents[&uri()];
|
||||
assert_eq!(document.language_id, "plaintext");
|
||||
assert_eq!(document.version, 5);
|
||||
assert_eq!(document.text, "current");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_unknown_incremental_and_ambiguous_changes() {
|
||||
let mut store = DocumentStore::default();
|
||||
let change = TextDocumentContentChangeEvent {
|
||||
range: None,
|
||||
range_length: None,
|
||||
text: "replacement".to_owned(),
|
||||
};
|
||||
assert!(!store.change(DidChangeTextDocumentParams {
|
||||
text_document: VersionedTextDocumentIdentifier::new(uri(), 1),
|
||||
content_changes: vec![change.clone()],
|
||||
}));
|
||||
|
||||
store.open(DidOpenTextDocumentParams {
|
||||
text_document: TextDocumentItem::new(
|
||||
uri(),
|
||||
"text".to_owned(),
|
||||
1,
|
||||
"original".to_owned(),
|
||||
),
|
||||
});
|
||||
assert!(!store.change(DidChangeTextDocumentParams {
|
||||
text_document: VersionedTextDocumentIdentifier::new(uri(), 2),
|
||||
content_changes: vec![change.clone(), change],
|
||||
}));
|
||||
assert_eq!(store.documents[&uri()].text, "original");
|
||||
assert!(store.close(&uri()));
|
||||
assert!(!store.close(&uri()));
|
||||
}
|
||||
}
|
||||
2
tasks.md
2
tasks.md
|
|
@ -190,7 +190,7 @@ first formatter milestone tag.
|
|||
- [x] Select an actively maintained LSP framework after a short dependency/API
|
||||
review (evaluate `tower-lsp-server`); pin the decision and protocol assumptions
|
||||
in a decision record.
|
||||
- [ ] Implement stdio initialization/shutdown and incremental or full document
|
||||
- [x] Implement stdio initialization/shutdown and incremental or full document
|
||||
synchronization with URI, version, language ID, and current text tracked per
|
||||
open document.
|
||||
- [ ] Build and thoroughly test byte-offset to LSP UTF-16 line/character mapping,
|
||||
|
|
|
|||
Loading…
Reference in New Issue