use std::collections::HashMap;
use std::io::{self, BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use serde_json::{json, Value};
use crate::highlight::TokenKind;
use crate::snippets::Language;
#[cfg(test)]
mod tests;
const MAX_HOVER_LINES: usize = 12;
#[derive(Debug, PartialEq)]
pub struct ServerSpec {
pub command: String,
pub args: Vec<String>,
pub language_id: &'static str,
pub root_markers: &'static [&'static str],
}
impl ServerSpec {
pub fn for_file(
language: Option<Language>,
path: &str,
override_command: Option<&str>,
) -> Option<Self> {
let extension = Path::new(path)
.extension()
.and_then(|extension| extension.to_str())
.unwrap_or("")
.to_ascii_lowercase();
let (command, language_id, root_markers): (&str, &str, &[&str]) = match language {
Some(Language::Rust) => ("rust-analyzer", "rust", &["Cargo.toml"]),
Some(Language::Python) => (
"pyright-langserver --stdio",
"python",
&["pyproject.toml", "setup.py", "requirements.txt"],
),
Some(Language::JavaScript) => (
"typescript-language-server --stdio",
match extension.as_str() {
"ts" => "typescript",
"tsx" => "typescriptreact",
"jsx" => "javascriptreact",
_ => "javascript",
},
&["tsconfig.json", "package.json"],
),
Some(Language::C) => (
"clangd",
if extension == "c" { "c" } else { "cpp" },
&["compile_commands.json", "CMakeLists.txt", "Makefile"],
),
Some(Language::Go) => ("gopls", "go", &["go.mod"]),
None => ("", "plaintext", &[]),
};
let command_line = match override_command.map(str::trim) {
Some("off") => return None,
Some(custom) if !custom.is_empty() => custom,
_ => command,
};
let mut words = command_line.split_whitespace().map(String::from);
Some(Self {
command: words.next()?,
args: words.collect(),
language_id,
root_markers,
})
}
}
pub fn find_root(dir: &Path, markers: &[&str]) -> PathBuf {
dir.ancestors()
.find(|folder| {
markers
.iter()
.chain(&[".git"])
.any(|marker| folder.join(marker).exists())
})
.unwrap_or(dir)
.to_path_buf()
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Encoding {
Utf8,
Utf16,
Utf32,
}
impl Encoding {
fn from_name(name: Option<&str>) -> Self {
match name {
Some("utf-8") => Self::Utf8,
Some("utf-32") => Self::Utf32,
_ => Self::Utf16,
}
}
fn units_of(self, c: char) -> usize {
match self {
Self::Utf8 => c.len_utf8(),
Self::Utf16 => c.len_utf16(),
Self::Utf32 => 1,
}
}
pub fn to_units(self, line: &str, x: usize) -> usize {
line.chars().take(x).map(|c| self.units_of(c)).sum()
}
pub fn to_chars(self, line: &str, units: usize) -> usize {
let mut used = 0;
for (x, c) in line.chars().enumerate() {
if used >= units {
return x;
}
used += self.units_of(c);
}
line.chars().count()
}
}
pub fn encode(message: &Value) -> Vec<u8> {
let body = message.to_string();
format!("Content-Length: {}\r\n\r\n{body}", body.len()).into_bytes()
}
pub fn read_message(reader: &mut impl BufRead) -> io::Result<Option<Value>> {
let mut length = None;
loop {
let mut header = String::new();
if reader.read_line(&mut header)? == 0 {
return Ok(None);
}
let header = header.trim_end();
if header.is_empty() {
break;
}
if let Some((name, value)) = header.split_once(':')
&& name.eq_ignore_ascii_case("content-length")
{
length = value.trim().parse::<usize>().ok();
}
}
let invalid = |reason: String| io::Error::new(io::ErrorKind::InvalidData, reason);
let length = length.ok_or_else(|| invalid("message without Content-Length".into()))?;
let mut body = vec![0; length];
reader.read_exact(&mut body)?;
serde_json::from_slice(&body)
.map(Some)
.map_err(|error| invalid(error.to_string()))
}
pub fn path_to_uri(path: &Path) -> String {
let mut text = path.to_string_lossy().replace('\\', "/");
if !text.starts_with('/') {
text.insert(0, '/');
}
let mut uri = String::from("file://");
for byte in text.bytes() {
match byte {
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'/' | b'-' | b'.' | b'_' | b'~' => {
uri.push(byte as char)
}
_ => uri.push_str(&format!("%{byte:02X}")),
}
}
uri
}
pub fn uri_to_path(uri: &str) -> Option<String> {
let encoded = uri.strip_prefix("file://")?;
let mut bytes = Vec::with_capacity(encoded.len());
let mut rest = encoded.bytes();
while let Some(byte) = rest.next() {
if byte == b'%' {
let hex = [rest.next()?, rest.next()?];
let hex = std::str::from_utf8(&hex).ok()?;
bytes.push(u8::from_str_radix(hex, 16).ok()?);
} else {
bytes.push(byte);
}
}
String::from_utf8(bytes).ok()
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Severity {
#[default]
Error,
Warning,
Info,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Diagnostic {
pub line: usize,
pub start: usize,
pub end_line: usize,
pub end: usize,
pub severity: Severity,
pub message: String,
pub unnecessary: bool,
pub deprecated: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SemanticToken {
pub line: usize,
pub start: usize,
pub length: usize,
pub kind: TokenKind,
}
#[derive(Debug, PartialEq)]
pub struct Location {
pub path: String,
pub line: usize,
pub units: usize,
}
#[derive(Debug, PartialEq)]
pub enum Reply {
Ready,
Diagnostics(Vec<Diagnostic>),
Hover(Vec<String>),
Definition(Option<Location>),
Tokens(Vec<SemanticToken>),
Nothing,
}
fn parse_diagnostics(params: &Value) -> Vec<Diagnostic> {
let Some(items) = params["diagnostics"].as_array() else {
return Vec::new();
};
let mut diagnostics: Vec<Diagnostic> = items
.iter()
.map(|item| {
let number = |value: &Value| value.as_u64().unwrap_or(0) as usize;
let (start, end) = (&item["range"]["start"], &item["range"]["end"]);
let has_tag = |tag: u64| {
item["tags"]
.as_array()
.is_some_and(|tags| tags.iter().any(|value| value.as_u64() == Some(tag)))
};
Diagnostic {
line: number(&start["line"]),
start: number(&start["character"]),
end_line: number(&end["line"]).max(number(&start["line"])),
end: number(&end["character"]),
unnecessary: has_tag(1),
deprecated: has_tag(2),
severity: match item["severity"].as_u64() {
Some(1) | None => Severity::Error,
Some(2) => Severity::Warning,
_ => Severity::Info,
},
message: item["message"]
.as_str()
.unwrap_or("")
.lines()
.next()
.unwrap_or("")
.to_string(),
}
})
.collect();
diagnostics.sort_by_key(|diagnostic| diagnostic.line);
diagnostics
}
fn parse_hover(result: &Value) -> Vec<String> {
fn text_of(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Array(items) => items.iter().map(text_of).collect::<Vec<_>>().join("\n"),
other => other["value"].as_str().unwrap_or("").to_string(),
}
}
let text = text_of(&result["contents"]);
let mut lines: Vec<String> = Vec::new();
for line in text.lines().map(str::trim_end) {
let is_fence = line.trim_start().starts_with("```");
let repeats_blank = line.is_empty() && lines.last().is_none_or(|last| last.is_empty());
if !is_fence && !repeats_blank {
lines.push(line.to_string());
}
}
while lines.last().is_some_and(|line| line.is_empty()) {
lines.pop();
}
if lines.len() > MAX_HOVER_LINES {
lines.truncate(MAX_HOVER_LINES - 1);
lines.push("...".into());
}
lines
}
fn parse_location(result: &Value) -> Option<Location> {
let first = match result {
Value::Array(items) => items.first()?,
Value::Null => return None,
single => single,
};
let uri = first["uri"].as_str().or(first["targetUri"].as_str())?;
let start = if first["targetSelectionRange"].is_object() {
&first["targetSelectionRange"]["start"]
} else {
&first["range"]["start"]
};
Some(Location {
path: uri_to_path(uri)?,
line: start["line"].as_u64()? as usize,
units: start["character"].as_u64()? as usize,
})
}
fn parse_tokens(result: &Value, legend: &[Option<TokenKind>]) -> Option<Vec<SemanticToken>> {
let data: Vec<usize> = result["data"]
.as_array()?
.iter()
.map(|number| number.as_u64().unwrap_or(0) as usize)
.collect();
let mut tokens = Vec::new();
let (mut line, mut start) = (0, 0);
for token in data.as_chunks::<5>().0 {
if token[0] > 0 {
line += token[0];
start = 0;
}
start += token[1];
if let Some(kind) = legend.get(token[3]).copied().flatten() {
tokens.push(SemanticToken {
line,
start,
length: token[2],
kind,
});
}
}
Some(tokens)
}
enum Pending {
Initialize,
Hover,
Definition,
Tokens(i64),
}
pub struct Client {
child: Child,
stdin: ChildStdin,
pub name: String,
path: String,
uri: String,
language_id: &'static str,
next_id: u64,
pending: HashMap<u64, Pending>,
encoding: Encoding,
incremental: bool,
ready: bool,
version: i64,
changes: Vec<Value>,
legend: Vec<Option<TokenKind>>,
}
impl Client {
pub fn start(
spec: &ServerSpec,
path: &str,
forward: impl Fn(Option<Value>) + Send + 'static,
) -> io::Result<Self> {
let path = std::path::absolute(path)?;
let dir = path.parent().unwrap_or(Path::new("/"));
let root = find_root(dir, spec.root_markers);
let mut child = Command::new(&spec.command)
.args(&spec.args)
.current_dir(dir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let stdin = child.stdin.take().expect("stdin was piped");
let stdout = child.stdout.take().expect("stdout was piped");
std::thread::spawn(move || {
let mut reader = BufReader::new(stdout);
while let Ok(Some(message)) = read_message(&mut reader) {
forward(Some(message));
}
forward(None);
});
let mut client = Self {
child,
stdin,
name: spec.command.clone(),
path: path.to_string_lossy().into_owned(),
uri: path_to_uri(&path),
language_id: spec.language_id,
next_id: 1,
pending: HashMap::new(),
encoding: Encoding::Utf16,
incremental: false,
ready: false,
version: 0,
changes: Vec::new(),
legend: Vec::new(),
};
client.request(
Pending::Initialize,
"initialize",
json!({
"processId": std::process::id(),
"clientInfo": { "name": "curd", "version": env!("CARGO_PKG_VERSION") },
"rootUri": path_to_uri(&root),
"capabilities": {
"general": { "positionEncodings": ["utf-32", "utf-16"] },
"workspace": { "semanticTokens": { "refreshSupport": true } },
"textDocument": {
"synchronization": { "didSave": true },
"publishDiagnostics": { "tagSupport": { "valueSet": [1, 2] } },
"hover": { "contentFormat": ["plaintext", "markdown"] },
"definition": { "linkSupport": true },
"semanticTokens": {
"requests": { "full": true },
"formats": ["relative"],
"tokenTypes": [
"namespace", "type", "class", "enum", "interface", "struct",
"typeParameter", "parameter", "variable", "property",
"enumMember", "event", "function", "method", "macro",
"keyword", "modifier", "comment", "string", "number",
"regexp", "operator", "decorator",
],
"tokenModifiers": [],
"multilineTokenSupport": false,
"overlappingTokenSupport": false,
"augmentsSyntaxTokens": false,
},
},
},
}),
);
Ok(client)
}
fn send(&mut self, message: Value) {
let _ = self.stdin.write_all(&encode(&message));
let _ = self.stdin.flush();
}
fn notify(&mut self, method: &str, params: Value) {
self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
}
fn request(&mut self, kind: Pending, method: &str, params: Value) {
let id = self.next_id;
self.next_id += 1;
self.pending.insert(id, kind);
self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
}
pub fn is_ready(&self) -> bool {
self.ready
}
pub fn encoding(&self) -> Encoding {
self.encoding
}
pub fn path(&self) -> &str {
&self.path
}
pub fn handle(&mut self, message: &Value, text: &dyn Fn() -> String) -> Reply {
if let Some(method) = message["method"].as_str() {
if !message["id"].is_null() {
let result = match message["params"]["items"].as_array() {
Some(items) if method == "workspace/configuration" => {
json!(vec![Value::Null; items.len()])
}
_ => Value::Null,
};
self.send(json!({ "jsonrpc": "2.0", "id": message["id"], "result": result }));
if method == "workspace/semanticTokens/refresh" {
self.request_tokens();
}
return Reply::Nothing;
}
let params = &message["params"];
if method == "textDocument/publishDiagnostics"
&& params["uri"].as_str().and_then(uri_to_path).as_deref() == Some(&self.path)
{
return Reply::Diagnostics(parse_diagnostics(params));
}
return Reply::Nothing;
}
let Some(kind) = message["id"].as_u64().and_then(|id| self.pending.remove(&id)) else {
return Reply::Nothing;
};
let result = &message["result"];
match kind {
Pending::Initialize => {
let capabilities = &result["capabilities"];
self.encoding = Encoding::from_name(capabilities["positionEncoding"].as_str());
let sync = &capabilities["textDocumentSync"];
self.incremental = sync.as_u64().or(sync["change"].as_u64()) == Some(2);
self.notify("initialized", json!({}));
self.notify(
"textDocument/didOpen",
json!({ "textDocument": {
"uri": self.uri,
"languageId": self.language_id,
"version": self.version,
"text": text(),
}}),
);
self.ready = true;
let provider = &capabilities["semanticTokensProvider"];
if provider["full"].as_bool() != Some(false) && !provider["full"].is_null() {
self.legend = provider["legend"]["tokenTypes"]
.as_array()
.map(|names| {
names
.iter()
.map(|name| name.as_str().and_then(TokenKind::from_name))
.collect()
})
.unwrap_or_default();
}
self.request_tokens();
Reply::Ready
}
Pending::Hover => Reply::Hover(parse_hover(result)),
Pending::Definition => Reply::Definition(parse_location(result)),
Pending::Tokens(version) if version != self.version || !self.changes.is_empty() => {
Reply::Nothing
}
Pending::Tokens(_) => match parse_tokens(result, &self.legend) {
Some(tokens) => Reply::Tokens(tokens),
None => Reply::Nothing,
},
}
}
pub fn change(&mut self, start: (usize, usize), end: (usize, usize), text: &str) {
if self.ready {
self.changes.push(json!({
"range": {
"start": { "line": start.0, "character": start.1 },
"end": { "line": end.0, "character": end.1 },
},
"text": text,
}));
}
}
pub fn has_pending_changes(&self) -> bool {
!self.changes.is_empty()
}
pub fn flush(&mut self, text: &dyn Fn() -> String) {
if self.changes.is_empty() {
return;
}
let changes = std::mem::take(&mut self.changes);
self.version += 1;
let content_changes = if self.incremental {
json!(changes)
} else {
json!([{ "text": text() }])
};
self.notify(
"textDocument/didChange",
json!({
"textDocument": { "uri": self.uri, "version": self.version },
"contentChanges": content_changes,
}),
);
self.request_tokens();
}
fn request_tokens(&mut self) {
if self.ready && !self.legend.is_empty() {
let params = json!({ "textDocument": { "uri": self.uri } });
let version = self.version;
self.request(
Pending::Tokens(version),
"textDocument/semanticTokens/full",
params,
);
}
}
fn position_params(&self, line: usize, units: usize) -> Value {
json!({
"textDocument": { "uri": self.uri },
"position": { "line": line, "character": units },
})
}
pub fn hover(&mut self, line: usize, units: usize) {
let params = self.position_params(line, units);
self.request(Pending::Hover, "textDocument/hover", params);
}
pub fn definition(&mut self, line: usize, units: usize) {
let params = self.position_params(line, units);
self.request(Pending::Definition, "textDocument/definition", params);
}
pub fn did_save(&mut self) {
if self.ready {
let uri = self.uri.clone();
self.notify("textDocument/didSave", json!({ "textDocument": { "uri": uri } }));
}
}
}
impl Drop for Client {
fn drop(&mut self) {
self.send(json!({ "jsonrpc": "2.0", "id": 0, "method": "shutdown" }));
self.notify("exit", Value::Null);
let _ = self.child.kill();
let _ = self.child.wait();
}
}