use std::collections::HashMap;
use std::error::Error;
use std::path::{Path, PathBuf};
use lsp_server::{Connection, ErrorCode, Message, Notification, Request, RequestId, Response};
use lsp_types::notification::{
DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument, DidOpenTextDocument,
Notification as _, PublishDiagnostics,
};
use lsp_types::request::{
Completion, GotoDefinition, HoverRequest, Request as _, SemanticTokensFullRequest,
};
use lsp_types::{
CompletionItem, CompletionOptions, CompletionParams, CompletionResponse, CompletionTextEdit,
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
GotoDefinitionParams, GotoDefinitionResponse, HoverContents, HoverParams,
HoverProviderCapability, InitializeParams, InitializeResult, MarkupContent, MarkupKind,
NumberOrString, OneOf, Position, PublishDiagnosticsParams, SemanticTokens,
SemanticTokensFullOptions, SemanticTokensOptions, SemanticTokensParams,
SemanticTokensServerCapabilities, ServerCapabilities, ServerInfo, TextDocumentIdentifier,
TextDocumentSyncCapability, TextDocumentSyncKind, TextEdit, Uri,
};
use pikopiko::compiler::include::Files;
use pikopiko::language::{Analysis, Definition, HoverContext, NoteTime};
use pikopiko::synth::tones::user::WithLibraries;
use pikopiko::synth::SynthSpec;
use pikopiko::CompileOptions;
use serde::{Deserialize, Serialize};
use super::convert::{self, Encoding, TokenLegend};
use super::uri::{path_to_uri, uri_to_path};
use crate::text::Texts;
type BoxError = Box<dyn Error + Send + Sync>;
#[derive(Debug, Clone, Default)]
pub struct Config {
pub lang: Option<&'static str>,
pub tones: Vec<pikopiko::synth::tones::user::UserLibrary>,
pub tone_dirs: Vec<PathBuf>,
}
pub fn serve_stdio(config: Config) -> Result<(), BoxError> {
let (conn, io) = Connection::stdio();
run(&conn, config)?;
drop(conn);
io.join()?;
Ok(())
}
pub fn run(conn: &Connection, config: Config) -> Result<(), BoxError> {
let (id, params) = conn.initialize_start()?;
let init: InitializeParams = serde_json::from_value(params)?;
let mut server = Server::new(config, &init);
conn.initialize_finish(id, serde_json::to_value(server.initialize_result())?)?;
for msg in &conn.receiver {
let forced =
matches!(&msg, Message::Notification(n) if n.method == DidChangeWatchedFiles::METHOD);
for out in server.refresh_tones(forced) {
conn.sender.send(Message::Notification(out))?;
}
match msg {
Message::Request(req) => {
if conn.handle_shutdown(&req)? {
return Ok(());
}
conn.sender.send(Message::Response(server.request(req)))?;
}
Message::Notification(n) => {
for out in server.notify(n) {
conn.sender.send(Message::Notification(out))?;
}
}
Message::Response(_) => {}
}
}
Ok(())
}
struct Doc {
uri: Uri,
files: Option<Files>,
dir: Option<PathBuf>,
analysis: Analysis,
text: String,
version: i32,
}
impl Doc {
fn byte(&self, pos: Position, enc: Encoding) -> usize {
let a = &self.analysis;
convert::byte(a.source(), a.line_index(), pos, enc)
}
}
struct Server {
texts: Texts,
enc: Encoding,
legend: TokenLegend,
docs: HashMap<String, Doc>,
synths: &'static [&'static SynthSpec],
libs: Vec<pikopiko::synth::tones::user::UserLibrary>,
watch: ToneWatch,
}
struct ToneWatch {
dirs: Vec<PathBuf>,
stamp: Vec<(PathBuf, Option<(std::time::SystemTime, u64)>)>,
checked: std::time::Instant,
}
const WATCH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(300);
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NotesAtParams {
text_document: TextDocumentIdentifier,
position: Position,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SoundingAtParams {
text_document: TextDocumentIdentifier,
tick: u64,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub(super) struct NoteJson {
pub track: u8,
pub track_name: String,
pub tick: u64,
pub end: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub range: Option<lsp_types::Range>,
}
const NOTES_AT: &str = "pikopiko/notesAt";
const SOUNDING_AT: &str = "pikopiko/soundingAt";
impl Server {
fn new(config: Config, init: &InitializeParams) -> Self {
let lang = config
.lang
.or_else(|| {
let env = lingokit::locale::resolve(crate::LOCALES.env_prefix, None);
env.first()
.and_then(|id| pikopiko::lang::lookup(id.language.as_str()))
})
.or_else(|| init.locale.as_deref().and_then(pikopiko::lang::lookup))
.unwrap_or_else(crate::text::detect_lang);
let caps = &init.capabilities;
let enc = Encoding::negotiate(
caps.general
.as_ref()
.and_then(|g| g.position_encodings.as_deref()),
);
let client_types = caps
.text_document
.as_ref()
.and_then(|t| t.semantic_tokens.as_ref())
.map(|s| s.token_types.as_slice());
Server {
texts: Texts::for_lang(lang),
enc,
legend: TokenLegend::new(client_types),
docs: HashMap::new(),
synths: pikopiko::synth::all(),
libs: config.tones,
watch: ToneWatch {
stamp: crate::tones::stamp(&config.tone_dirs),
dirs: config.tone_dirs,
checked: std::time::Instant::now(),
},
}
}
fn refresh_tones(&mut self, force: bool) -> Vec<Notification> {
if self.watch.dirs.is_empty() || (!force && self.watch.checked.elapsed() < WATCH_INTERVAL) {
return Vec::new();
}
self.watch.checked = std::time::Instant::now();
let stamp = crate::tones::stamp(&self.watch.dirs);
if stamp == self.watch.stamp {
return Vec::new();
}
self.watch.stamp = stamp;
match crate::tones::load_dirs(&self.watch.dirs) {
Ok(libs) => self.libs = libs,
Err(e) => {
eprintln!(
"pikopiko-lsp: {}",
self.texts.tr_args(
"lsp-warn-tones-reload",
&[("path", e.path().display().to_string().into())]
)
);
return Vec::new();
}
}
let docs: Vec<(Uri, i32, String)> = self
.docs
.values()
.map(|d| (d.uri.clone(), d.version, d.text.clone()))
.collect();
docs.into_iter()
.flat_map(|(uri, version, text)| self.open(uri, version, &text))
.collect()
}
fn initialize_result(&self) -> InitializeResult {
InitializeResult {
capabilities: ServerCapabilities {
position_encoding: Some(self.enc.kind()),
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::FULL,
)),
completion_provider: Some(CompletionOptions {
trigger_characters: Some(
["@", "$", "!", "\"", " ", "#"]
.iter()
.map(|s| s.to_string())
.collect(),
),
..CompletionOptions::default()
}),
hover_provider: Some(HoverProviderCapability::Simple(true)),
definition_provider: Some(OneOf::Left(true)),
semantic_tokens_provider: Some(
SemanticTokensServerCapabilities::SemanticTokensOptions(
SemanticTokensOptions {
legend: self.legend.legend.clone(),
full: Some(SemanticTokensFullOptions::Bool(true)),
range: None,
..SemanticTokensOptions::default()
},
),
),
..ServerCapabilities::default()
},
server_info: Some(ServerInfo {
name: "pikopiko-lsp".into(),
version: Some(env!("CARGO_PKG_VERSION").into()),
}),
}
}
fn with_options<R>(
&self,
files: Option<&Files>,
f: impl FnOnce(&CompileOptions<'_>) -> R,
) -> R {
let loader = WithLibraries::new(
files.map(|f| f as &dyn pikopiko::compiler::include::Include),
&self.libs,
);
f(&CompileOptions {
synths: self.synths,
include: Some(&loader),
..CompileOptions::default()
})
}
fn notify(&mut self, n: Notification) -> Vec<Notification> {
match n.method.as_str() {
DidOpenTextDocument::METHOD => {
let Ok(p) = serde_json::from_value::<DidOpenTextDocumentParams>(n.params) else {
return Vec::new();
};
let d = p.text_document;
self.open(d.uri, d.version, &d.text)
}
DidChangeTextDocument::METHOD => {
let Ok(p) = serde_json::from_value::<DidChangeTextDocumentParams>(n.params) else {
return Vec::new();
};
let Some(text) = p.content_changes.into_iter().last().map(|c| c.text) else {
return Vec::new();
};
let d = p.text_document;
self.open(d.uri, d.version, &text)
}
DidCloseTextDocument::METHOD => {
let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(n.params) else {
return Vec::new();
};
self.docs.remove(p.text_document.uri.as_str());
vec![publish(p.text_document.uri, Vec::new(), None)]
}
_ => Vec::new(),
}
}
fn open(&mut self, uri: Uri, version: i32, text: &str) -> Vec<Notification> {
let path = uri_to_path(&uri);
let files = path.as_deref().map(Files::beside);
let analysis =
self.with_options(files.as_ref(), |o| Analysis::new(text, version as u64, o));
let doc = Doc {
uri: uri.clone(),
files,
dir: path
.as_deref()
.and_then(Path::parent)
.map(Path::to_path_buf),
analysis,
text: text.to_string(),
version,
};
let diags = self.diagnostics(&doc);
self.docs.insert(uri.as_str().to_string(), doc);
vec![publish(uri, diags, Some(version))]
}
fn diagnostics(&self, doc: &Doc) -> Vec<lsp_types::Diagnostic> {
let a = &doc.analysis;
a.diagnostics()
.iter()
.map(|d| {
let msg = self.texts.diagnostic(d);
let (range, message) = if d.span.source == 0 {
(
convert::span_range(a.source(), a.line_index(), d.span, self.enc),
msg,
)
} else {
let file = d.file.as_deref().unwrap_or("");
(
lsp_types::Range::default(),
format!("{file}:{}:{}: {msg}", d.span.line, d.span.col),
)
};
lsp_types::Diagnostic {
range,
severity: Some(convert::severity(d.severity)),
code: Some(NumberOrString::String(d.code.to_string())),
source: Some("pikopiko".into()),
message,
..lsp_types::Diagnostic::default()
}
})
.collect()
}
fn request(&self, req: Request) -> Response {
let id = req.id.clone();
let result = match req.method.as_str() {
SemanticTokensFullRequest::METHOD => {
parse::<SemanticTokensParams>(&req).map(|p| self.semantic_tokens(&p))
}
Completion::METHOD => parse::<CompletionParams>(&req).map(|p| self.completion(&p)),
HoverRequest::METHOD => parse::<HoverParams>(&req).map(|p| self.hover(&p)),
GotoDefinition::METHOD => {
parse::<GotoDefinitionParams>(&req).map(|p| self.definition(&p))
}
NOTES_AT => parse::<NotesAtParams>(&req).map(|p| self.notes_at(&p)),
SOUNDING_AT => parse::<SoundingAtParams>(&req).map(|p| self.sounding_at(&p)),
_ => {
return Response::new_err(
id,
ErrorCode::MethodNotFound as i32,
format!("unknown method {}", req.method),
)
}
};
match result {
Ok(v) => Response::new_ok(id, v),
Err(e) => error_response(id, e),
}
}
fn doc(&self, uri: &Uri) -> Option<&Doc> {
self.docs.get(uri.as_str())
}
fn semantic_tokens(&self, p: &SemanticTokensParams) -> serde_json::Value {
let Some(doc) = self.doc(&p.text_document.uri) else {
return serde_json::Value::Null;
};
let a = &doc.analysis;
let data = convert::semantic_tokens(a.source(), a.line_index(), a.tokens(), self.enc);
json(SemanticTokens {
result_id: None,
data,
})
}
fn completion(&self, p: &CompletionParams) -> serde_json::Value {
let pos = &p.text_document_position;
let Some(doc) = self.doc(&pos.text_document.uri) else {
return serde_json::Value::Null;
};
let a = &doc.analysis;
let cursor = doc.byte(pos.position, self.enc);
let explicit = p
.context
.as_ref()
.is_some_and(|c| c.trigger_kind == lsp_types::CompletionTriggerKind::INVOKED);
let c = self.with_options(doc.files.as_ref(), |o| a.complete(cursor, o, explicit));
let range = convert::range(a.source(), a.line_index(), c.replace, self.enc);
let spec = a.synth_spec(self.synths);
let items = c
.items
.into_iter()
.map(|item| {
let detail = match (item.detail_key.is_empty(), spec) {
(false, Some(spec)) => Some(self.texts.synth_text(spec, &item.detail_key)),
_ if self.texts.lang() == "ja" && !item.detail.is_empty() => {
Some(item.detail.clone())
}
_ => None,
}
.filter(|d| !d.is_empty());
CompletionItem {
label: item.label,
kind: Some(convert::completion_kind(item.kind)),
detail,
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range,
new_text: item.insert,
})),
..CompletionItem::default()
}
})
.collect();
json(CompletionResponse::Array(items))
}
fn hover(&self, p: &HoverParams) -> serde_json::Value {
let pos = &p.text_document_position_params;
let Some(doc) = self.doc(&pos.text_document.uri) else {
return serde_json::Value::Null;
};
let a = &doc.analysis;
let byte = doc.byte(pos.position, self.enc);
let over = |k: &str| self.texts.override_text(k);
let ctx = HoverContext {
lang: self.texts.lang(),
synths: self.synths,
text: &over,
};
let Some(h) = a.hover(byte, &ctx) else {
return serde_json::Value::Null;
};
json(lsp_types::Hover {
contents: HoverContents::Markup(MarkupContent {
kind: MarkupKind::Markdown,
value: h.markdown,
}),
range: h
.location
.bytes
.map(|b| convert::range(a.source(), a.line_index(), b, self.enc)),
})
}
fn definition(&self, p: &GotoDefinitionParams) -> serde_json::Value {
let pos = &p.text_document_position_params;
let Some(doc) = self.doc(&pos.text_document.uri) else {
return serde_json::Value::Null;
};
let a = &doc.analysis;
let byte = doc.byte(pos.position, self.enc);
let location = match a.definition(byte) {
Some(Definition::Source { location, .. }) if location.span.source == 0 => {
Some(lsp_types::Location {
uri: doc.uri.clone(),
range: convert::span_range(a.source(), a.line_index(), location.span, self.enc),
})
}
Some(Definition::Source { location, .. }) => {
let path = PathBuf::from(a.source_name(location.span.source).unwrap_or(""));
file_location(&path, |text, ix| {
convert::span_range(text, ix, location.span, self.enc)
})
}
Some(Definition::Include { path }) => doc
.dir
.as_deref()
.and_then(|dir| file_location(&dir.join(path), |_, _| lsp_types::Range::default())),
None => None,
};
match location {
Some(l) => json(GotoDefinitionResponse::Scalar(l)),
None => serde_json::Value::Null,
}
}
fn notes_at(&self, p: &NotesAtParams) -> serde_json::Value {
let Some(doc) = self.doc(&p.text_document.uri) else {
return serde_json::Value::Array(Vec::new());
};
let a = &doc.analysis;
let byte = doc.byte(p.position, self.enc);
json(self.notes_json(a, a.notes_at(byte)))
}
fn sounding_at(&self, p: &SoundingAtParams) -> serde_json::Value {
let Some(doc) = self.doc(&p.text_document.uri) else {
return serde_json::Value::Array(Vec::new());
};
let a = &doc.analysis;
json(self.notes_json(a, a.sounding_at(p.tick)))
}
fn notes_json(&self, a: &Analysis, notes: Vec<&NoteTime>) -> Vec<NoteJson> {
notes
.into_iter()
.map(|n| NoteJson {
track: n.track,
track_name: n.track_name.clone(),
tick: n.tick,
end: n.end,
range: (n.span.source == 0)
.then(|| convert::span_range(a.source(), a.line_index(), n.span, self.enc)),
})
.collect()
}
}
fn file_location(
path: &Path,
range: impl FnOnce(&str, &pikopiko::language::LineIndex) -> lsp_types::Range,
) -> Option<lsp_types::Location> {
let text = std::fs::read_to_string(path).ok()?;
let ix = pikopiko::language::LineIndex::new(&text);
Some(lsp_types::Location {
uri: path_to_uri(path)?,
range: range(&text, &ix),
})
}
fn publish(
uri: Uri,
diagnostics: Vec<lsp_types::Diagnostic>,
version: Option<i32>,
) -> Notification {
Notification::new(
PublishDiagnostics::METHOD.to_string(),
PublishDiagnosticsParams {
uri,
diagnostics,
version,
},
)
}
fn parse<P: serde::de::DeserializeOwned>(req: &Request) -> Result<P, serde_json::Error> {
serde_json::from_value(req.params.clone())
}
fn json<T: Serialize>(v: T) -> serde_json::Value {
serde_json::to_value(v).unwrap_or(serde_json::Value::Null)
}
fn error_response(id: RequestId, e: serde_json::Error) -> Response {
Response::new_err(id, ErrorCode::InvalidParams as i32, e.to_string())
}