rototo 0.1.0-alpha.6

Control plane for runtime configuration of your application.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
use std::collections::{BTreeMap, HashSet, VecDeque};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};

use serde_json::Value as JsonValue;
use tokio::io::{AsyncBufRead, AsyncWrite, BufReader};
use tokio::sync::mpsc;

use crate::error::{Result, RototoError};
use crate::lint::{LintInput, OverlayDocument, PackageLintSnapshot, lint_package_snapshot};

use super::convert::{
    lsp_completion_item, lsp_document_symbol, lsp_hover, lsp_location, lsp_reference,
    publish_diagnostics_params,
};
use super::protocol::{
    LspCompletionItem, LspDocumentSymbol, LspHover, LspLocation, PublishDiagnosticsParams,
    initialize_result,
};
use super::transport::{read_message, write_error_response, write_notification, write_response};
use super::uri::{
    initialize_package_root, json_i32, package_relative_path, path_from_file_uri,
    source_position_from_json,
};

/// JSON-RPC error code for a request the client asked to cancel (LSP
/// `RequestCancelled`).
const REQUEST_CANCELLED: i64 = -32800;

pub async fn serve_stdio() -> Result<()> {
    let stdin = tokio::io::stdin();
    let stdout = tokio::io::stdout();
    serve(BufReader::new(stdin), stdout).await
}

pub(crate) async fn serve<R, W>(reader: R, mut writer: W) -> Result<()>
where
    R: AsyncBufRead + Unpin + Send + 'static,
    W: AsyncWrite + Unpin,
{
    // A dedicated reader task pulls messages off the wire eagerly into a channel.
    // Handling stays sequential on this task, but reading ahead lets a
    // `$/cancelRequest` that the client sent right after a request be observed
    // before that request is dequeued and run — which is the only way
    // cancellation can do anything in an otherwise serial server.
    let (sender, mut receiver) = mpsc::unbounded_channel();
    tokio::spawn(async move {
        let mut reader = reader;
        while let Ok(Some(message)) = read_message(&mut reader).await {
            if sender.send(message).is_err() {
                break;
            }
        }
    });

    let mut server = LspServer::new();
    let mut queue: VecDeque<JsonValue> = VecDeque::new();
    let mut cancellations = PendingCancellations::default();

    loop {
        if queue.is_empty() {
            match receiver.recv().await {
                Some(message) => intake(message, &mut queue, &mut cancellations),
                None => break,
            }
        }
        // Drain everything already buffered so a pending cancel is recorded
        // before the request it targets reaches the front of the queue.
        while let Ok(message) = receiver.try_recv() {
            intake(message, &mut queue, &mut cancellations);
        }
        let Some(message) = queue.pop_front() else {
            continue;
        };

        let id = message.get("id").cloned();
        let method = message
            .get("method")
            .and_then(JsonValue::as_str)
            .unwrap_or_default()
            .to_owned();

        // A request the client cancelled while it waited in the queue returns the
        // standard RequestCancelled error rather than computing a result.
        if let Some(id) = &id
            && cancellations.take(id)
        {
            write_error_response(
                &mut writer,
                id.clone(),
                REQUEST_CANCELLED,
                "request cancelled",
            )
            .await?;
            continue;
        }

        match server.handle_message(message, &mut writer).await {
            Ok(true) => break,
            Ok(false) => {}
            Err(err) if id.is_some() => {
                write_error_response(
                    &mut writer,
                    id.unwrap(),
                    -32603,
                    &format!("rototo LSP request failed: {err}"),
                )
                .await?;
            }
            Err(err) if method == "exit" => return Err(err),
            Err(err) => {
                tracing::warn!(method = %method, error = %err, "rototo LSP notification failed");
            }
        }
    }
    Ok(())
}

/// Route an incoming message: a `$/cancelRequest` is consumed by recording the
/// cancelled id; everything else is queued for sequential handling.
fn intake(
    message: JsonValue,
    queue: &mut VecDeque<JsonValue>,
    cancellations: &mut PendingCancellations,
) {
    if message.get("method").and_then(JsonValue::as_str) == Some("$/cancelRequest") {
        if let Some(id) = message.get("params").and_then(|params| params.get("id")) {
            cancellations.record(id);
        }
        return;
    }
    queue.push_back(message);
}

/// Request ids cancelled by the client but not yet matched to a pending request.
/// Ids can be numbers or strings, so they are keyed by their JSON spelling.
#[derive(Default)]
struct PendingCancellations {
    ids: HashSet<String>,
}

impl PendingCancellations {
    fn record(&mut self, id: &JsonValue) {
        self.ids.insert(id.to_string());
    }

    /// Whether `id` was cancelled, consuming the record so it matches once.
    fn take(&mut self, id: &JsonValue) -> bool {
        self.ids.remove(&id.to_string())
    }
}

pub(super) struct LspServer {
    pub(super) package_root: Option<PathBuf>,
    overlays: BTreeMap<String, OverlayDocument>,
    shutdown_requested: bool,
    /// Bumped on every overlay mutation so a cached snapshot built from an older
    /// set of buffers is recognized as stale.
    revision: u64,
    /// Last package snapshot, reused while `revision` is unchanged. The lint
    /// pipeline reads the whole package from disk plus overlays, so without this
    /// every request and every keystroke would recompute the entire package.
    snapshot_cache: Mutex<Option<(u64, Arc<PackageLintSnapshot>)>>,
    /// Count of actual snapshot builds, used by tests to prove cache reuse.
    build_count: AtomicUsize,
}

impl LspServer {
    pub(super) fn new() -> Self {
        Self {
            package_root: None,
            overlays: BTreeMap::new(),
            shutdown_requested: false,
            revision: 0,
            snapshot_cache: Mutex::new(None),
            build_count: AtomicUsize::new(0),
        }
    }

    async fn handle_message<W>(&mut self, message: JsonValue, writer: &mut W) -> Result<bool>
    where
        W: AsyncWrite + Unpin,
    {
        let method = message
            .get("method")
            .and_then(JsonValue::as_str)
            .unwrap_or_default();
        let id = message.get("id").cloned();
        let params = message.get("params").cloned().unwrap_or(JsonValue::Null);

        match (id, method) {
            (Some(id), "initialize") => {
                self.package_root = initialize_package_root(&params).await?;
                write_response(writer, id, initialize_result()).await?;
            }
            (Some(id), "shutdown") => {
                self.shutdown_requested = true;
                write_response(writer, id, JsonValue::Null).await?;
            }
            (Some(id), "textDocument/documentSymbol") => {
                let symbols = self.document_symbols(params).await?;
                write_response(
                    writer,
                    id,
                    serde_json::to_value(symbols)
                        .map_err(|err| RototoError::new(err.to_string()))?,
                )
                .await?;
            }
            (Some(id), "textDocument/completion") => {
                let completions = self.completion_items(params).await?;
                write_response(
                    writer,
                    id,
                    serde_json::to_value(completions)
                        .map_err(|err| RototoError::new(err.to_string()))?,
                )
                .await?;
            }
            (Some(id), "textDocument/hover") => {
                let hover = self.hover(params).await?;
                let result = hover
                    .map(serde_json::to_value)
                    .transpose()
                    .map_err(|err| RototoError::new(err.to_string()))?
                    .unwrap_or(JsonValue::Null);
                write_response(writer, id, result).await?;
            }
            (Some(id), "textDocument/definition") => {
                let definition = self.definition(params).await?;
                let result = definition
                    .map(serde_json::to_value)
                    .transpose()
                    .map_err(|err| RototoError::new(err.to_string()))?
                    .unwrap_or(JsonValue::Null);
                write_response(writer, id, result).await?;
            }
            (Some(id), "textDocument/references") => {
                let references = self.references(params).await?;
                write_response(
                    writer,
                    id,
                    serde_json::to_value(references)
                        .map_err(|err| RototoError::new(err.to_string()))?,
                )
                .await?;
            }
            (Some(id), _) => {
                write_error_response(writer, id, -32601, "method not found").await?;
            }
            (None, "initialized") => {
                self.publish_package_diagnostics(writer).await?;
            }
            (None, "textDocument/didOpen") => {
                self.open_document(params)?;
                self.publish_package_diagnostics(writer).await?;
            }
            (None, "textDocument/didChange") => {
                self.change_document(params)?;
                self.publish_package_diagnostics(writer).await?;
            }
            (None, "textDocument/didSave") | (None, "textDocument/didClose") => {
                self.remove_document_overlay(params)?;
                self.publish_package_diagnostics(writer).await?;
            }
            (None, "exit") => {
                if self.shutdown_requested {
                    return Ok(true);
                }
                return Err(RototoError::new("LSP exit received before shutdown"));
            }
            (None, _) => {}
        }

        Ok(false)
    }

    pub(super) fn open_document(&mut self, params: JsonValue) -> Result<()> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("didOpen missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("didOpen missing textDocument.uri"))?;
        let text = text_document
            .get("text")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("didOpen missing textDocument.text"))?;
        let version = json_i32(text_document.get("version"));
        let path = self.package_path_for_uri(uri)?;
        self.overlays.insert(
            path,
            OverlayDocument {
                text: text.to_owned(),
                version,
            },
        );
        self.revision += 1;
        Ok(())
    }

    pub(super) fn change_document(&mut self, params: JsonValue) -> Result<()> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("didChange missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("didChange missing textDocument.uri"))?;
        let version = json_i32(text_document.get("version"));
        let changes = params
            .get("contentChanges")
            .and_then(JsonValue::as_array)
            .ok_or_else(|| RototoError::new("didChange missing contentChanges"))?;
        let path = self.package_path_for_uri(uri)?;

        // Apply each change to the running buffer in order: a change with a
        // `range` splices that span (its positions are UTF-16, like every other
        // LSP position), and a change without one replaces the whole document.
        let mut text = self
            .overlays
            .get(&path)
            .map(|document| document.text.clone())
            .unwrap_or_default();
        for change in changes {
            let new_text = change
                .get("text")
                .and_then(JsonValue::as_str)
                .ok_or_else(|| RototoError::new("didChange content change missing text"))?;
            match change.get("range") {
                None => text = new_text.to_owned(),
                Some(range) => {
                    let start = source_position_from_json(
                        range
                            .get("start")
                            .ok_or_else(|| RototoError::new("didChange range missing start"))?,
                    )?;
                    let end = source_position_from_json(
                        range
                            .get("end")
                            .ok_or_else(|| RototoError::new("didChange range missing end"))?,
                    )?;
                    let start_byte = byte_offset_for_position(&text, start.line, start.character);
                    let end_byte = byte_offset_for_position(&text, end.line, end.character);
                    if start_byte > end_byte {
                        return Err(RototoError::new("didChange range start is after its end"));
                    }
                    text.replace_range(start_byte..end_byte, new_text);
                }
            }
        }

        self.overlays
            .insert(path, OverlayDocument { text, version });
        self.revision += 1;
        Ok(())
    }

    pub(super) fn remove_document_overlay(&mut self, params: JsonValue) -> Result<()> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("document notification missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("document notification missing textDocument.uri"))?;
        let path = self.package_path_for_uri(uri)?;
        self.overlays.remove(&path);
        self.revision += 1;
        Ok(())
    }

    async fn publish_package_diagnostics<W>(&self, writer: &mut W) -> Result<()>
    where
        W: AsyncWrite + Unpin,
    {
        for publication in self.package_diagnostics().await? {
            write_notification(
                writer,
                "textDocument/publishDiagnostics",
                serde_json::to_value(publication)
                    .map_err(|err| RototoError::new(err.to_string()))?,
            )
            .await?;
        }
        Ok(())
    }

    pub(super) async fn package_diagnostics(&self) -> Result<Vec<PublishDiagnosticsParams>> {
        let Some(snapshot) = self.package_snapshot().await? else {
            return Ok(Vec::new());
        };
        Ok(publish_diagnostics_params(&snapshot.lint))
    }

    pub(super) async fn document_symbols(
        &self,
        params: JsonValue,
    ) -> Result<Vec<LspDocumentSymbol>> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("documentSymbol missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("documentSymbol missing textDocument.uri"))?;
        let path = self.package_path_for_uri(uri)?;
        let Some(snapshot) = self.package_snapshot().await? else {
            return Ok(Vec::new());
        };
        Ok(snapshot
            .document_symbols(&path)
            .iter()
            .map(lsp_document_symbol)
            .collect())
    }

    pub(super) async fn completion_items(
        &self,
        params: JsonValue,
    ) -> Result<Vec<LspCompletionItem>> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("completion missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("completion missing textDocument.uri"))?;
        let position = source_position_from_json(
            params
                .get("position")
                .ok_or_else(|| RototoError::new("completion missing position"))?,
        )?;
        let path = self.package_path_for_uri(uri)?;
        let Some(snapshot) = self.package_snapshot().await? else {
            return Ok(Vec::new());
        };
        Ok(snapshot
            .completion_items(&path, position)
            .iter()
            .map(lsp_completion_item)
            .collect())
    }

    pub(super) async fn hover(&self, params: JsonValue) -> Result<Option<LspHover>> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("hover missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("hover missing textDocument.uri"))?;
        let position = source_position_from_json(
            params
                .get("position")
                .ok_or_else(|| RototoError::new("hover missing position"))?,
        )?;
        let path = self.package_path_for_uri(uri)?;
        let Some(snapshot) = self.package_snapshot().await? else {
            return Ok(None);
        };
        Ok(snapshot.hover(&path, position).map(lsp_hover))
    }

    pub(super) async fn definition(&self, params: JsonValue) -> Result<Option<LspLocation>> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("definition missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("definition missing textDocument.uri"))?;
        let position = source_position_from_json(
            params
                .get("position")
                .ok_or_else(|| RototoError::new("definition missing position"))?,
        )?;
        let path = self.package_path_for_uri(uri)?;
        let Some(snapshot) = self.package_snapshot().await? else {
            return Ok(None);
        };
        Ok(snapshot.definition(&path, position).map(lsp_location))
    }

    pub(super) async fn references(&self, params: JsonValue) -> Result<Vec<LspLocation>> {
        let text_document = params
            .get("textDocument")
            .ok_or_else(|| RototoError::new("references missing textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| RototoError::new("references missing textDocument.uri"))?;
        let position = source_position_from_json(
            params
                .get("position")
                .ok_or_else(|| RototoError::new("references missing position"))?,
        )?;
        let include_declaration = params
            .get("context")
            .and_then(|context| context.get("includeDeclaration"))
            .and_then(JsonValue::as_bool)
            .unwrap_or(false);
        let path = self.package_path_for_uri(uri)?;
        let Some(snapshot) = self.package_snapshot().await? else {
            return Ok(Vec::new());
        };
        Ok(snapshot
            .references(&path, position, include_declaration)
            .iter()
            .map(lsp_reference)
            .collect())
    }

    async fn package_snapshot(&self) -> Result<Option<Arc<PackageLintSnapshot>>> {
        let Some(root) = &self.package_root else {
            return Ok(None);
        };
        let revision = self.revision;
        if let Some((cached_revision, snapshot)) = self.snapshot_cache.lock().unwrap().as_ref()
            && *cached_revision == revision
        {
            return Ok(Some(Arc::clone(snapshot)));
        }
        let mut input = LintInput::new(root.clone());
        input.overlays = self.overlays.clone();
        self.build_count.fetch_add(1, Ordering::Relaxed);
        let snapshot = Arc::new(lint_package_snapshot(input).await?);
        *self.snapshot_cache.lock().unwrap() = Some((revision, Arc::clone(&snapshot)));
        Ok(Some(snapshot))
    }

    #[cfg(test)]
    pub(super) fn snapshot_build_count(&self) -> usize {
        self.build_count.load(Ordering::Relaxed)
    }

    #[cfg(test)]
    pub(super) fn overlay_text(&self, path: &str) -> Option<&str> {
        self.overlays
            .get(path)
            .map(|document| document.text.as_str())
    }

    fn package_path_for_uri(&self, uri: &str) -> Result<String> {
        let Some(root) = &self.package_root else {
            return Err(RototoError::new("LSP package root is not initialized"));
        };
        let path = path_from_file_uri(uri)?;
        package_relative_path(root, &path)
    }
}

/// Byte offset in `text` of an LSP position. `line` counts `\n`-delimited lines
/// and `character` counts UTF-16 code units into that line (the encoding the
/// server advertises). A position past the end of its line clamps to the line
/// break, and a position past the end of the text clamps to its length, so an
/// out-of-range edit splices at the boundary rather than panicking.
fn byte_offset_for_position(text: &str, line: usize, character: usize) -> usize {
    let line_start = if line == 0 {
        0
    } else {
        let mut seen = 0;
        let mut start = text.len();
        for (byte, ch) in text.char_indices() {
            if ch == '\n' {
                seen += 1;
                if seen == line {
                    start = byte + 1;
                    break;
                }
            }
        }
        start
    };

    let mut utf16 = 0;
    for (byte, ch) in text[line_start..].char_indices() {
        if utf16 >= character || ch == '\n' {
            return line_start + byte;
        }
        utf16 += ch.len_utf16();
    }
    text.len()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn intake_records_cancellations_and_queues_other_messages() {
        let mut queue = VecDeque::new();
        let mut cancellations = PendingCancellations::default();

        intake(
            json!({"id": 1, "method": "textDocument/completion"}),
            &mut queue,
            &mut cancellations,
        );
        intake(
            json!({"method": "$/cancelRequest", "params": {"id": 1}}),
            &mut queue,
            &mut cancellations,
        );

        // The cancel is consumed into the registry, not queued for handling.
        assert_eq!(queue.len(), 1);
        assert_eq!(queue[0]["id"], 1);

        // The matching request id is cancelled exactly once.
        assert!(cancellations.take(&json!(1)));
        assert!(!cancellations.take(&json!(1)));
        // An unrelated id was never cancelled.
        assert!(!cancellations.take(&json!(2)));
    }

    #[test]
    fn cancellations_distinguish_numeric_and_string_ids() {
        let mut cancellations = PendingCancellations::default();
        cancellations.record(&json!("abc"));
        assert!(!cancellations.take(&json!(1)));
        assert!(cancellations.take(&json!("abc")));
    }
}