Skip to main content

pikopiko_cli/lsp/
server.rs

1//! 言語サーバーの処理の回し方:初期化、文書の持ち方、要求と通知ごとの処理。
2
3use std::collections::HashMap;
4use std::error::Error;
5use std::path::{Path, PathBuf};
6
7use lsp_server::{Connection, ErrorCode, Message, Notification, Request, RequestId, Response};
8use lsp_types::notification::{
9    DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument, DidOpenTextDocument,
10    Notification as _, PublishDiagnostics,
11};
12use lsp_types::request::{
13    Completion, GotoDefinition, HoverRequest, Request as _, SemanticTokensFullRequest,
14};
15use lsp_types::{
16    CompletionItem, CompletionOptions, CompletionParams, CompletionResponse, CompletionTextEdit,
17    DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
18    GotoDefinitionParams, GotoDefinitionResponse, HoverContents, HoverParams,
19    HoverProviderCapability, InitializeParams, InitializeResult, MarkupContent, MarkupKind,
20    NumberOrString, OneOf, Position, PublishDiagnosticsParams, SemanticTokens,
21    SemanticTokensFullOptions, SemanticTokensOptions, SemanticTokensParams,
22    SemanticTokensServerCapabilities, ServerCapabilities, ServerInfo, TextDocumentIdentifier,
23    TextDocumentSyncCapability, TextDocumentSyncKind, TextEdit, Uri,
24};
25use pikopiko::compiler::include::Files;
26use pikopiko::language::{Analysis, Definition, HoverContext, NoteTime};
27use pikopiko::synth::tones::user::WithLibraries;
28use pikopiko::synth::SynthSpec;
29use pikopiko::CompileOptions;
30use serde::{Deserialize, Serialize};
31
32use super::convert::{self, Encoding, TokenLegend};
33use super::uri::{path_to_uri, uri_to_path};
34use crate::text::Texts;
35
36type BoxError = Box<dyn Error + Send + Sync>;
37
38/// 言語サーバーの設定。
39#[derive(Debug, Clone, Default)]
40pub struct Config {
41    /// 表示の言語(`en`・`ja`)。`None` なら環境変数、クライアントの `locale`、OS の言語の順で決める。
42    pub lang: Option<&'static str>,
43    /// 利用者の音色集(`--tones`・`PIKOPIKO_TONES`)。`#include "@名前/種類"` が読め、`#include "@` の
44    /// 補完にも出る。派生音源(`--synth-def`)は、`serve_stdio` より前に `pikopiko::synth::derived` へ
45    /// 登録しておく(音源の一覧は最初の `Server` で固まる)。
46    pub tones: Vec<pikopiko::synth::tones::user::UserLibrary>,
47    /// 音色集のフォルダー(`--tones`・`PIKOPIKO_TONES`)。空でなければ、サーバーが動いている間、
48    /// 中のファイルが変わったら読み直して、開いている文書を解析し直す(再起動は要らない)。
49    /// 変わったかは `stat`(更新時刻と大きさ)だけで見て、要求・通知が来たとき(0.3 秒に 1 回まで)に確かめる。
50    pub tone_dirs: Vec<PathBuf>,
51}
52
53/// 標準入出力で言語サーバーとして動く。クライアントが `exit` するか接続を閉じるまで戻らない。
54///
55/// 標準出力はプロトコルだけに使うので、ログは標準エラー出力へ出すこと。
56pub fn serve_stdio(config: Config) -> Result<(), BoxError> {
57    let (conn, io) = Connection::stdio();
58    run(&conn, config)?;
59    drop(conn);
60    io.join()?;
61    Ok(())
62}
63
64/// つながった `conn` で、初期化から終わり(`shutdown`)まで動く。テストではメモリの上の接続
65/// (`Connection::memory`)を渡す。
66pub fn run(conn: &Connection, config: Config) -> Result<(), BoxError> {
67    let (id, params) = conn.initialize_start()?;
68    let init: InitializeParams = serde_json::from_value(params)?;
69    let mut server = Server::new(config, &init);
70    conn.initialize_finish(id, serde_json::to_value(server.initialize_result())?)?;
71    for msg in &conn.receiver {
72        // 音色集のファイルが変わっていたら、先に読み直して解析し直す
73        let forced =
74            matches!(&msg, Message::Notification(n) if n.method == DidChangeWatchedFiles::METHOD);
75        for out in server.refresh_tones(forced) {
76            conn.sender.send(Message::Notification(out))?;
77        }
78        match msg {
79            Message::Request(req) => {
80                if conn.handle_shutdown(&req)? {
81                    return Ok(());
82                }
83                conn.sender.send(Message::Response(server.request(req)))?;
84            }
85            Message::Notification(n) => {
86                for out in server.notify(n) {
87                    conn.sender.send(Message::Notification(out))?;
88                }
89            }
90            Message::Response(_) => {}
91        }
92    }
93    Ok(())
94}
95
96/// 開いている文書 1 つ。
97struct Doc {
98    uri: Uri,
99    /// ファイルなら、`#include` をそのファイルのあるフォルダーから読む口(解析と補完で使う)。
100    files: Option<Files>,
101    /// ファイルなら、そのフォルダー(`#include "…"` の行から読み込む先を開くのに使う)。
102    dir: Option<PathBuf>,
103    analysis: Analysis,
104    /// 解析した本文と版(音色集を読み直したときに解析し直す)。
105    text: String,
106    version: i32,
107}
108
109impl Doc {
110    /// LSP の位置のバイト位置。
111    fn byte(&self, pos: Position, enc: Encoding) -> usize {
112        let a = &self.analysis;
113        convert::byte(a.source(), a.line_index(), pos, enc)
114    }
115}
116
117struct Server {
118    texts: Texts,
119    enc: Encoding,
120    legend: TokenLegend,
121    docs: HashMap<String, Doc>,
122    synths: &'static [&'static SynthSpec],
123    /// 利用者の音色集。
124    libs: Vec<pikopiko::synth::tones::user::UserLibrary>,
125    /// 音色集のフォルダーの見張り(フォルダーがなければ読み直さない)。
126    watch: ToneWatch,
127}
128
129/// 音色集のフォルダーの見張り。
130struct ToneWatch {
131    dirs: Vec<PathBuf>,
132    stamp: Vec<(PathBuf, Option<(std::time::SystemTime, u64)>)>,
133    checked: std::time::Instant,
134}
135
136/// 確かめる間隔の下限。入力のたびに `stat` を何十回もしないため。
137const WATCH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(300);
138
139/// 独自の要求 `pikopiko/notesAt` の引数。
140#[derive(Debug, Deserialize)]
141#[serde(rename_all = "camelCase")]
142struct NotesAtParams {
143    text_document: TextDocumentIdentifier,
144    position: Position,
145}
146
147/// 独自の要求 `pikopiko/soundingAt` の引数。
148#[derive(Debug, Deserialize)]
149#[serde(rename_all = "camelCase")]
150struct SoundingAtParams {
151    text_document: TextDocumentIdentifier,
152    tick: u64,
153}
154
155/// 独自の要求の結果の 1 つの音。
156#[derive(Debug, Serialize, Deserialize, PartialEq)]
157#[serde(rename_all = "camelCase")]
158pub(super) struct NoteJson {
159    pub track: u8,
160    pub track_name: String,
161    pub tick: u64,
162    pub end: u64,
163    /// 音を生んだ本文の範囲(読み込んだものの中の音は `None`)。
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub range: Option<lsp_types::Range>,
166}
167
168const NOTES_AT: &str = "pikopiko/notesAt";
169const SOUNDING_AT: &str = "pikopiko/soundingAt";
170
171impl Server {
172    fn new(config: Config, init: &InitializeParams) -> Self {
173        let lang = config
174            .lang
175            .or_else(|| {
176                let env = lingokit::locale::resolve(crate::LOCALES.env_prefix, None);
177                env.first()
178                    .and_then(|id| pikopiko::lang::lookup(id.language.as_str()))
179            })
180            .or_else(|| init.locale.as_deref().and_then(pikopiko::lang::lookup))
181            .unwrap_or_else(crate::text::detect_lang);
182        let caps = &init.capabilities;
183        let enc = Encoding::negotiate(
184            caps.general
185                .as_ref()
186                .and_then(|g| g.position_encodings.as_deref()),
187        );
188        let client_types = caps
189            .text_document
190            .as_ref()
191            .and_then(|t| t.semantic_tokens.as_ref())
192            .map(|s| s.token_types.as_slice());
193        Server {
194            texts: Texts::for_lang(lang),
195            enc,
196            legend: TokenLegend::new(client_types),
197            docs: HashMap::new(),
198            synths: pikopiko::synth::all(),
199            libs: config.tones,
200            watch: ToneWatch {
201                stamp: crate::tones::stamp(&config.tone_dirs),
202                dirs: config.tone_dirs,
203                checked: std::time::Instant::now(),
204            },
205        }
206    }
207
208    /// 音色集のフォルダーのファイルが変わっていたら、読み直して開いている文書を解析し直す。
209    /// 診断の通知を返す。`force`(クライアントがファイルの変化を知らせたとき)なら間隔を待たない。
210    /// 読み直せなかった(書きかけなど)ときは前の音色集のままにして、標準エラー出力で知らせる。
211    fn refresh_tones(&mut self, force: bool) -> Vec<Notification> {
212        if self.watch.dirs.is_empty() || (!force && self.watch.checked.elapsed() < WATCH_INTERVAL) {
213            return Vec::new();
214        }
215        self.watch.checked = std::time::Instant::now();
216        let stamp = crate::tones::stamp(&self.watch.dirs);
217        if stamp == self.watch.stamp {
218            return Vec::new();
219        }
220        self.watch.stamp = stamp;
221        match crate::tones::load_dirs(&self.watch.dirs) {
222            Ok(libs) => self.libs = libs,
223            Err(e) => {
224                eprintln!(
225                    "pikopiko-lsp: {}",
226                    self.texts.tr_args(
227                        "lsp-warn-tones-reload",
228                        &[("path", e.path().display().to_string().into())]
229                    )
230                );
231                return Vec::new();
232            }
233        }
234        let docs: Vec<(Uri, i32, String)> = self
235            .docs
236            .values()
237            .map(|d| (d.uri.clone(), d.version, d.text.clone()))
238            .collect();
239        docs.into_iter()
240            .flat_map(|(uri, version, text)| self.open(uri, version, &text))
241            .collect()
242    }
243
244    fn initialize_result(&self) -> InitializeResult {
245        InitializeResult {
246            capabilities: ServerCapabilities {
247                position_encoding: Some(self.enc.kind()),
248                text_document_sync: Some(TextDocumentSyncCapability::Kind(
249                    TextDocumentSyncKind::FULL,
250                )),
251                completion_provider: Some(CompletionOptions {
252                    trigger_characters: Some(
253                        ["@", "$", "!", "\"", " ", "#"]
254                            .iter()
255                            .map(|s| s.to_string())
256                            .collect(),
257                    ),
258                    ..CompletionOptions::default()
259                }),
260                hover_provider: Some(HoverProviderCapability::Simple(true)),
261                definition_provider: Some(OneOf::Left(true)),
262                semantic_tokens_provider: Some(
263                    SemanticTokensServerCapabilities::SemanticTokensOptions(
264                        SemanticTokensOptions {
265                            legend: self.legend.legend.clone(),
266                            full: Some(SemanticTokensFullOptions::Bool(true)),
267                            range: None,
268                            ..SemanticTokensOptions::default()
269                        },
270                    ),
271                ),
272                ..ServerCapabilities::default()
273            },
274            server_info: Some(ServerInfo {
275                name: "pikopiko-lsp".into(),
276                version: Some(env!("CARGO_PKG_VERSION").into()),
277            }),
278        }
279    }
280
281    /// 文書を解析・補完するときの設定(音源の一覧と、`#include` の読み方)で `f` を呼ぶ。`#include` は
282    /// 利用者の音色集(`@名前/種類`)と、ファイルなら文書のあるフォルダーから読む。
283    fn with_options<R>(
284        &self,
285        files: Option<&Files>,
286        f: impl FnOnce(&CompileOptions<'_>) -> R,
287    ) -> R {
288        let loader = WithLibraries::new(
289            files.map(|f| f as &dyn pikopiko::compiler::include::Include),
290            &self.libs,
291        );
292        f(&CompileOptions {
293            synths: self.synths,
294            include: Some(&loader),
295            ..CompileOptions::default()
296        })
297    }
298
299    // ---- 通知 ----
300
301    fn notify(&mut self, n: Notification) -> Vec<Notification> {
302        match n.method.as_str() {
303            DidOpenTextDocument::METHOD => {
304                let Ok(p) = serde_json::from_value::<DidOpenTextDocumentParams>(n.params) else {
305                    return Vec::new();
306                };
307                let d = p.text_document;
308                self.open(d.uri, d.version, &d.text)
309            }
310            DidChangeTextDocument::METHOD => {
311                let Ok(p) = serde_json::from_value::<DidChangeTextDocumentParams>(n.params) else {
312                    return Vec::new();
313                };
314                // 全文の同期なので、最後の変更が新しい全文
315                let Some(text) = p.content_changes.into_iter().last().map(|c| c.text) else {
316                    return Vec::new();
317                };
318                let d = p.text_document;
319                self.open(d.uri, d.version, &text)
320            }
321            DidCloseTextDocument::METHOD => {
322                let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(n.params) else {
323                    return Vec::new();
324                };
325                self.docs.remove(p.text_document.uri.as_str());
326                vec![publish(p.text_document.uri, Vec::new(), None)]
327            }
328            _ => Vec::new(),
329        }
330    }
331
332    /// 文書を(作り直して)持ち、診断を送る。
333    fn open(&mut self, uri: Uri, version: i32, text: &str) -> Vec<Notification> {
334        let path = uri_to_path(&uri);
335        let files = path.as_deref().map(Files::beside);
336        let analysis =
337            self.with_options(files.as_ref(), |o| Analysis::new(text, version as u64, o));
338        let doc = Doc {
339            uri: uri.clone(),
340            files,
341            dir: path
342                .as_deref()
343                .and_then(Path::parent)
344                .map(Path::to_path_buf),
345            analysis,
346            text: text.to_string(),
347            version,
348        };
349        let diags = self.diagnostics(&doc);
350        self.docs.insert(uri.as_str().to_string(), doc);
351        vec![publish(uri, diags, Some(version))]
352    }
353
354    fn diagnostics(&self, doc: &Doc) -> Vec<lsp_types::Diagnostic> {
355        let a = &doc.analysis;
356        a.diagnostics()
357            .iter()
358            .map(|d| {
359                let msg = self.texts.diagnostic(d);
360                let (range, message) = if d.span.source == 0 {
361                    (
362                        convert::span_range(a.source(), a.line_index(), d.span, self.enc),
363                        msg,
364                    )
365                } else {
366                    // 読み込んだものの中の診断は、文書の頭に、そのファイルの位置を添えて出す
367                    let file = d.file.as_deref().unwrap_or("");
368                    (
369                        lsp_types::Range::default(),
370                        format!("{file}:{}:{}: {msg}", d.span.line, d.span.col),
371                    )
372                };
373                lsp_types::Diagnostic {
374                    range,
375                    severity: Some(convert::severity(d.severity)),
376                    code: Some(NumberOrString::String(d.code.to_string())),
377                    source: Some("pikopiko".into()),
378                    message,
379                    ..lsp_types::Diagnostic::default()
380                }
381            })
382            .collect()
383    }
384
385    // ---- 要求 ----
386
387    fn request(&self, req: Request) -> Response {
388        let id = req.id.clone();
389        let result = match req.method.as_str() {
390            SemanticTokensFullRequest::METHOD => {
391                parse::<SemanticTokensParams>(&req).map(|p| self.semantic_tokens(&p))
392            }
393            Completion::METHOD => parse::<CompletionParams>(&req).map(|p| self.completion(&p)),
394            HoverRequest::METHOD => parse::<HoverParams>(&req).map(|p| self.hover(&p)),
395            GotoDefinition::METHOD => {
396                parse::<GotoDefinitionParams>(&req).map(|p| self.definition(&p))
397            }
398            NOTES_AT => parse::<NotesAtParams>(&req).map(|p| self.notes_at(&p)),
399            SOUNDING_AT => parse::<SoundingAtParams>(&req).map(|p| self.sounding_at(&p)),
400            _ => {
401                return Response::new_err(
402                    id,
403                    ErrorCode::MethodNotFound as i32,
404                    format!("unknown method {}", req.method),
405                )
406            }
407        };
408        match result {
409            Ok(v) => Response::new_ok(id, v),
410            Err(e) => error_response(id, e),
411        }
412    }
413
414    fn doc(&self, uri: &Uri) -> Option<&Doc> {
415        self.docs.get(uri.as_str())
416    }
417
418    fn semantic_tokens(&self, p: &SemanticTokensParams) -> serde_json::Value {
419        let Some(doc) = self.doc(&p.text_document.uri) else {
420            return serde_json::Value::Null;
421        };
422        let a = &doc.analysis;
423        let data = convert::semantic_tokens(a.source(), a.line_index(), a.tokens(), self.enc);
424        json(SemanticTokens {
425            result_id: None,
426            data,
427        })
428    }
429
430    fn completion(&self, p: &CompletionParams) -> serde_json::Value {
431        let pos = &p.text_document_position;
432        let Some(doc) = self.doc(&pos.text_document.uri) else {
433            return serde_json::Value::Null;
434        };
435        let a = &doc.analysis;
436        let cursor = doc.byte(pos.position, self.enc);
437        let explicit = p
438            .context
439            .as_ref()
440            .is_some_and(|c| c.trigger_kind == lsp_types::CompletionTriggerKind::INVOKED);
441        let c = self.with_options(doc.files.as_ref(), |o| a.complete(cursor, o, explicit));
442        let range = convert::range(a.source(), a.line_index(), c.replace, self.enc);
443        let spec = a.synth_spec(self.synths);
444        let items = c
445            .items
446            .into_iter()
447            .map(|item| {
448                let detail = match (item.detail_key.is_empty(), spec) {
449                    (false, Some(spec)) => Some(self.texts.synth_text(spec, &item.detail_key)),
450                    _ if self.texts.lang() == "ja" && !item.detail.is_empty() => {
451                        Some(item.detail.clone())
452                    }
453                    _ => None,
454                }
455                .filter(|d| !d.is_empty());
456                CompletionItem {
457                    label: item.label,
458                    kind: Some(convert::completion_kind(item.kind)),
459                    detail,
460                    text_edit: Some(CompletionTextEdit::Edit(TextEdit {
461                        range,
462                        new_text: item.insert,
463                    })),
464                    ..CompletionItem::default()
465                }
466            })
467            .collect();
468        json(CompletionResponse::Array(items))
469    }
470
471    fn hover(&self, p: &HoverParams) -> serde_json::Value {
472        let pos = &p.text_document_position_params;
473        let Some(doc) = self.doc(&pos.text_document.uri) else {
474            return serde_json::Value::Null;
475        };
476        let a = &doc.analysis;
477        let byte = doc.byte(pos.position, self.enc);
478        let over = |k: &str| self.texts.override_text(k);
479        let ctx = HoverContext {
480            lang: self.texts.lang(),
481            synths: self.synths,
482            text: &over,
483        };
484        let Some(h) = a.hover(byte, &ctx) else {
485            return serde_json::Value::Null;
486        };
487        json(lsp_types::Hover {
488            contents: HoverContents::Markup(MarkupContent {
489                kind: MarkupKind::Markdown,
490                value: h.markdown,
491            }),
492            range: h
493                .location
494                .bytes
495                .map(|b| convert::range(a.source(), a.line_index(), b, self.enc)),
496        })
497    }
498
499    fn definition(&self, p: &GotoDefinitionParams) -> serde_json::Value {
500        let pos = &p.text_document_position_params;
501        let Some(doc) = self.doc(&pos.text_document.uri) else {
502            return serde_json::Value::Null;
503        };
504        let a = &doc.analysis;
505        let byte = doc.byte(pos.position, self.enc);
506        let location = match a.definition(byte) {
507            Some(Definition::Source { location, .. }) if location.span.source == 0 => {
508                Some(lsp_types::Location {
509                    uri: doc.uri.clone(),
510                    range: convert::span_range(a.source(), a.line_index(), location.span, self.enc),
511                })
512            }
513            Some(Definition::Source { location, .. }) => {
514                // 読み込んだもの:名前はファイルのパス(ファイルから読んだときだけ開ける)
515                let path = PathBuf::from(a.source_name(location.span.source).unwrap_or(""));
516                file_location(&path, |text, ix| {
517                    convert::span_range(text, ix, location.span, self.enc)
518                })
519            }
520            Some(Definition::Include { path }) => doc
521                .dir
522                .as_deref()
523                .and_then(|dir| file_location(&dir.join(path), |_, _| lsp_types::Range::default())),
524            None => None,
525        };
526        match location {
527            Some(l) => json(GotoDefinitionResponse::Scalar(l)),
528            None => serde_json::Value::Null,
529        }
530    }
531
532    fn notes_at(&self, p: &NotesAtParams) -> serde_json::Value {
533        let Some(doc) = self.doc(&p.text_document.uri) else {
534            return serde_json::Value::Array(Vec::new());
535        };
536        let a = &doc.analysis;
537        let byte = doc.byte(p.position, self.enc);
538        json(self.notes_json(a, a.notes_at(byte)))
539    }
540
541    fn sounding_at(&self, p: &SoundingAtParams) -> serde_json::Value {
542        let Some(doc) = self.doc(&p.text_document.uri) else {
543            return serde_json::Value::Array(Vec::new());
544        };
545        let a = &doc.analysis;
546        json(self.notes_json(a, a.sounding_at(p.tick)))
547    }
548
549    fn notes_json(&self, a: &Analysis, notes: Vec<&NoteTime>) -> Vec<NoteJson> {
550        notes
551            .into_iter()
552            .map(|n| NoteJson {
553                track: n.track,
554                track_name: n.track_name.clone(),
555                tick: n.tick,
556                end: n.end,
557                range: (n.span.source == 0)
558                    .then(|| convert::span_range(a.source(), a.line_index(), n.span, self.enc)),
559            })
560            .collect()
561    }
562}
563
564/// ファイルの位置(ファイルが読めなければ `None`)。範囲は `range` でそのファイルの中身から求める。
565fn file_location(
566    path: &Path,
567    range: impl FnOnce(&str, &pikopiko::language::LineIndex) -> lsp_types::Range,
568) -> Option<lsp_types::Location> {
569    let text = std::fs::read_to_string(path).ok()?;
570    let ix = pikopiko::language::LineIndex::new(&text);
571    Some(lsp_types::Location {
572        uri: path_to_uri(path)?,
573        range: range(&text, &ix),
574    })
575}
576
577fn publish(
578    uri: Uri,
579    diagnostics: Vec<lsp_types::Diagnostic>,
580    version: Option<i32>,
581) -> Notification {
582    Notification::new(
583        PublishDiagnostics::METHOD.to_string(),
584        PublishDiagnosticsParams {
585            uri,
586            diagnostics,
587            version,
588        },
589    )
590}
591
592fn parse<P: serde::de::DeserializeOwned>(req: &Request) -> Result<P, serde_json::Error> {
593    serde_json::from_value(req.params.clone())
594}
595
596fn json<T: Serialize>(v: T) -> serde_json::Value {
597    serde_json::to_value(v).unwrap_or(serde_json::Value::Null)
598}
599
600fn error_response(id: RequestId, e: serde_json::Error) -> Response {
601    Response::new_err(id, ErrorCode::InvalidParams as i32, e.to_string())
602}