fatou 0.9.0

A language server, formatter, and linter for Julia
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
//! Read-only jobs serviced off the analysis thread's cached state.

use std::path::PathBuf;

use crossbeam_channel::{SendError, Sender};
use lsp_server::{ErrorCode, Message, RequestId, Response};

use lsp_types::{
    CallHierarchyItem, CodeActionOrCommand, CompletionItem, CompletionResponse,
    DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentSymbolResponse,
    FullDocumentDiagnosticReport, GotoDefinitionResponse, Position, Range,
    RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport,
    TypeHierarchyItem, UnchangedDocumentDiagnosticReport, Uri, WorkspaceSymbolResponse,
};

use std::sync::Arc;

use crate::formatter::FormatStyle;
use crate::incremental::Analysis;
use crate::text::PositionEncoding;

use super::call_hierarchy::{
    incoming_calls_via_db, outgoing_calls_via_db, prepare_call_hierarchy_via_db,
};
use super::code_action::code_actions_via_db;
use super::completion::{completion_via_db, resolve_completion};
use super::definition::definition_via_db;
use super::document_link::document_links_via_db;
use super::folding::folding_ranges_via_db;
use super::format::{format_edits_via_db, format_range_edits_via_db};
use super::hover::hover_via_db;
use super::lint::ServerRules;
use super::pull_diagnostics::document_diagnostics_via_db;
use super::references::{document_highlights_via_db, references_via_db};
use super::rename::{prepare_rename_via_db, rename_via_db};
use super::result_id::content_hash;
use super::selection::selection_ranges_via_db;
use super::semantic_tokens::{semantic_tokens_delta, semantic_tokens_via_db};
use super::signature_help::signature_help_via_db;
use super::state::Outbound;
use super::symbols::document_symbols_via_db;
use super::type_hierarchy::{prepare_type_hierarchy_via_db, subtypes_via_db, supertypes_via_db};
use super::workspace_symbols::workspace_symbols_via_db;

/// A read job's reply channel. Rather than answering the client directly, a
/// worker routes its response back through the main loop (as
/// [`Outbound::ReadReply`]), which owns the document versions: it gates the
/// reply on the version the read was dispatched against (a superseded buffer
/// becomes `ContentModified`) and drops it entirely when a `$/cancelRequest`
/// landed while the job ran. The `send` shape mirrors the `Sender<Message>` the
/// workers replied on before, so [`run_read`] is unchanged.
pub(crate) struct ReadReply {
    out_tx: Sender<Outbound>,
}

impl ReadReply {
    pub(crate) fn new(out_tx: Sender<Outbound>) -> Self {
        Self { out_tx }
    }

    /// Route `message` (always a `Message::Response`) to the main loop for
    /// gating. Errors only if the main loop is gone (shutdown), like the old
    /// direct send.
    pub(crate) fn send(self, message: Message) -> Result<(), SendError<Outbound>> {
        self.out_tx.send(Outbound::ReadReply { message })
    }
}

/// A read-only request the analysis thread services by cloning its salsa db
/// and running the work off-thread on the read pool. Each variant carries the
/// live buffer `text` and the [`ReadReply`] channel so the worker can reply;
/// the analysis thread only adds the db snapshot. See [`run_read`].
pub(crate) enum ReadJob {
    CodeAction {
        id: RequestId,
        uri: Uri,
        path: PathBuf,
        text: String,
        range: Range,
        rules: Arc<ServerRules>,
        sender: ReadReply,
    },
    DocumentDiagnostic {
        id: RequestId,
        path: PathBuf,
        text: String,
        rules: Arc<ServerRules>,
        /// The `resultId` the client last held for this document, if any; a
        /// match against the freshly computed id collapses the report to
        /// `Unchanged` (see [`diagnostic_report`]).
        previous_result_id: Option<String>,
        sender: ReadReply,
    },
    Format {
        id: RequestId,
        path: PathBuf,
        text: String,
        style: FormatStyle,
        sender: ReadReply,
    },
    FormatRange {
        id: RequestId,
        path: PathBuf,
        text: String,
        range: Range,
        style: FormatStyle,
        sender: ReadReply,
    },
    DocumentSymbols {
        id: RequestId,
        path: PathBuf,
        text: String,
        sender: ReadReply,
    },
    WorkspaceSymbols {
        id: RequestId,
        query: String,
        sender: ReadReply,
    },
    FoldingRanges {
        id: RequestId,
        path: PathBuf,
        text: String,
        sender: ReadReply,
    },
    DocumentLinks {
        id: RequestId,
        path: PathBuf,
        text: String,
        sender: ReadReply,
    },
    SelectionRanges {
        id: RequestId,
        path: PathBuf,
        text: String,
        positions: Vec<Position>,
        sender: ReadReply,
    },
    SemanticTokensFull {
        id: RequestId,
        path: PathBuf,
        text: String,
        sender: ReadReply,
    },
    SemanticTokensDelta {
        id: RequestId,
        path: PathBuf,
        text: String,
        /// The `resultId` from the client's last full or delta response; a
        /// match against the freshly computed id answers an empty delta.
        previous_result_id: String,
        sender: ReadReply,
    },
    Completion {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    CompletionResolve {
        id: RequestId,
        item: Box<CompletionItem>,
        sender: ReadReply,
    },
    Hover {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    SignatureHelp {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    Definition {
        id: RequestId,
        uri: Uri,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    References {
        id: RequestId,
        uri: Uri,
        path: PathBuf,
        text: String,
        position: Position,
        include_declaration: bool,
        sender: ReadReply,
    },
    DocumentHighlight {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    PrepareRename {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    Rename {
        id: RequestId,
        uri: Uri,
        path: PathBuf,
        text: String,
        position: Position,
        new_name: String,
        sender: ReadReply,
    },
    PrepareCallHierarchy {
        id: RequestId,
        uri: Uri,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    /// Document-less (like `CompletionResolve`): the item's file may be a
    /// closed member, so the worker resolves its text off the snapshot.
    CallHierarchyIncoming {
        id: RequestId,
        item: Box<CallHierarchyItem>,
        sender: ReadReply,
    },
    CallHierarchyOutgoing {
        id: RequestId,
        item: Box<CallHierarchyItem>,
        sender: ReadReply,
    },
    PrepareTypeHierarchy {
        id: RequestId,
        uri: Uri,
        path: PathBuf,
        text: String,
        position: Position,
        sender: ReadReply,
    },
    /// Document-less (like `CallHierarchyIncoming`): the item's file may be a
    /// closed member, so the worker resolves its text off the snapshot.
    TypeHierarchySupertypes {
        id: RequestId,
        item: Box<TypeHierarchyItem>,
        sender: ReadReply,
    },
    TypeHierarchySubtypes {
        id: RequestId,
        item: Box<TypeHierarchyItem>,
        sender: ReadReply,
    },
}

impl ReadJob {
    /// Recover the request `id` and reply channel from an undeliverable job so
    /// the client still gets a (null) response instead of hanging.
    pub(crate) fn into_reply_parts(self) -> (RequestId, ReadReply) {
        match self {
            ReadJob::CodeAction { id, sender, .. } => (id, sender),
            ReadJob::DocumentDiagnostic { id, sender, .. } => (id, sender),
            ReadJob::Format { id, sender, .. } => (id, sender),
            ReadJob::FormatRange { id, sender, .. } => (id, sender),
            ReadJob::DocumentSymbols { id, sender, .. } => (id, sender),
            ReadJob::WorkspaceSymbols { id, sender, .. } => (id, sender),
            ReadJob::FoldingRanges { id, sender, .. } => (id, sender),
            ReadJob::DocumentLinks { id, sender, .. } => (id, sender),
            ReadJob::SelectionRanges { id, sender, .. } => (id, sender),
            ReadJob::SemanticTokensFull { id, sender, .. } => (id, sender),
            ReadJob::SemanticTokensDelta { id, sender, .. } => (id, sender),
            ReadJob::Completion { id, sender, .. } => (id, sender),
            ReadJob::CompletionResolve { id, sender, .. } => (id, sender),
            ReadJob::Hover { id, sender, .. } => (id, sender),
            ReadJob::SignatureHelp { id, sender, .. } => (id, sender),
            ReadJob::Definition { id, sender, .. } => (id, sender),
            ReadJob::References { id, sender, .. } => (id, sender),
            ReadJob::DocumentHighlight { id, sender, .. } => (id, sender),
            ReadJob::PrepareRename { id, sender, .. } => (id, sender),
            ReadJob::Rename { id, sender, .. } => (id, sender),
            ReadJob::PrepareCallHierarchy { id, sender, .. } => (id, sender),
            ReadJob::CallHierarchyIncoming { id, sender, .. } => (id, sender),
            ReadJob::CallHierarchyOutgoing { id, sender, .. } => (id, sender),
            ReadJob::PrepareTypeHierarchy { id, sender, .. } => (id, sender),
            ReadJob::TypeHierarchySupertypes { id, sender, .. } => (id, sender),
            ReadJob::TypeHierarchySubtypes { id, sender, .. } => (id, sender),
        }
    }
}

/// An id-less full report, used for the unknown-document case (a never-opened
/// path the client can't hold a prior `resultId` for, so there is nothing to
/// match against). Reports for open documents go through [`diagnostic_report`],
/// which keys them by content so a re-pull can answer `Unchanged`.
pub(crate) fn full_report(items: Vec<lsp_types::Diagnostic>) -> DocumentDiagnosticReportResult {
    DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
        RelatedFullDocumentDiagnosticReport {
            related_documents: None,
            full_document_diagnostic_report: FullDocumentDiagnosticReport {
                result_id: None,
                items,
            },
        },
    ))
}

/// Build the pull-diagnostic report for `items`, keyed by a content hash so an
/// unchanged file re-pulls cheaply. When the client's `previous_result_id`
/// matches the freshly computed id the findings are unchanged since its last
/// pull, so the report collapses to `Unchanged` (id only, no items); otherwise
/// it is a `Full` report carrying the new id for the client to echo back next
/// time.
pub(crate) fn diagnostic_report(
    items: Vec<lsp_types::Diagnostic>,
    previous_result_id: Option<&str>,
) -> DocumentDiagnosticReportResult {
    let result_id = content_hash(&items);
    if previous_result_id == Some(result_id.as_str()) {
        return DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Unchanged(
            RelatedUnchangedDocumentDiagnosticReport {
                related_documents: None,
                unchanged_document_diagnostic_report: UnchangedDocumentDiagnosticReport {
                    result_id,
                },
            },
        ));
    }
    DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
        RelatedFullDocumentDiagnosticReport {
            related_documents: None,
            full_document_diagnostic_report: FullDocumentDiagnosticReport {
                result_id: Some(result_id),
                items,
            },
        },
    ))
}

/// Service a read-only job against a db `snapshot`, replying to the client.
/// Runs on a read-pool worker; the `snapshot` is dropped on return so it never
/// blocks the analysis thread's next write longer than the job itself.
pub(crate) fn run_read(snapshot: Analysis, job: ReadJob, encoding: PositionEncoding) {
    match job {
        ReadJob::CodeAction {
            id,
            uri,
            path,
            text,
            range,
            rules,
            sender,
        } => {
            let actions: Vec<CodeActionOrCommand> =
                code_actions_via_db(&snapshot, &uri, &path, &text, range, encoding, &rules);
            let _ = sender.send(Message::Response(Response::new_ok(id, actions)));
        }
        ReadJob::DocumentDiagnostic {
            id,
            path,
            text,
            rules,
            previous_result_id,
            sender,
        } => {
            let items = document_diagnostics_via_db(&snapshot, &path, &text, encoding, &rules);
            let result = diagnostic_report(items, previous_result_id.as_deref());
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::Format {
            id,
            path,
            text,
            style,
            sender,
        } => {
            let result = format_edits_via_db(&snapshot, &path, &text, style, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::FormatRange {
            id,
            path,
            text,
            range,
            style,
            sender,
        } => {
            let result = format_range_edits_via_db(&snapshot, &path, &text, range, style, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::DocumentSymbols {
            id,
            path,
            text,
            sender,
        } => {
            let symbols = document_symbols_via_db(&snapshot, &path, &text, encoding);
            let result = DocumentSymbolResponse::Nested(symbols);
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::WorkspaceSymbols { id, query, sender } => {
            let symbols = workspace_symbols_via_db(&snapshot, &query, encoding);
            let result = WorkspaceSymbolResponse::Nested(symbols);
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::FoldingRanges {
            id,
            path,
            text,
            sender,
        } => {
            // Folds are line-only, so the position encoding is irrelevant.
            let folds = folding_ranges_via_db(&snapshot, &path, &text);
            let _ = sender.send(Message::Response(Response::new_ok(id, folds)));
        }
        ReadJob::DocumentLinks {
            id,
            path,
            text,
            sender,
        } => {
            let links = document_links_via_db(&snapshot, &path, &text, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, links)));
        }
        ReadJob::SelectionRanges {
            id,
            path,
            text,
            positions,
            sender,
        } => {
            let ranges = selection_ranges_via_db(&snapshot, &path, &text, &positions, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, ranges)));
        }
        ReadJob::SemanticTokensFull {
            id,
            path,
            text,
            sender,
        } => {
            let tokens = semantic_tokens_via_db(&snapshot, &path, &text, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, tokens)));
        }
        ReadJob::SemanticTokensDelta {
            id,
            path,
            text,
            previous_result_id,
            sender,
        } => {
            let tokens = semantic_tokens_via_db(&snapshot, &path, &text, encoding);
            let result = semantic_tokens_delta(tokens, &previous_result_id);
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::Completion {
            id,
            path,
            text,
            position,
            sender,
        } => {
            let items = completion_via_db(&snapshot, &path, &text, position, encoding);
            let result = CompletionResponse::Array(items);
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::CompletionResolve { id, item, sender } => {
            let resolved = resolve_completion(&snapshot, *item);
            let _ = sender.send(Message::Response(Response::new_ok(id, resolved)));
        }
        ReadJob::Hover {
            id,
            path,
            text,
            position,
            sender,
        } => {
            let hover = hover_via_db(&snapshot, &path, &text, position, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, hover)));
        }
        ReadJob::SignatureHelp {
            id,
            path,
            text,
            position,
            sender,
        } => {
            let help = signature_help_via_db(&snapshot, &path, &text, position, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, help)));
        }
        ReadJob::Definition {
            id,
            uri,
            path,
            text,
            position,
            sender,
        } => {
            let mut locations =
                definition_via_db(&snapshot, &uri, &path, &text, position, encoding);
            // A single site stays scalar (a plain jump); several methods of a
            // function come back as an array (the client shows a picker).
            let result = match locations.len() {
                0 => None,
                1 => Some(GotoDefinitionResponse::Scalar(locations.remove(0))),
                _ => Some(GotoDefinitionResponse::Array(locations)),
            };
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::References {
            id,
            uri,
            path,
            text,
            position,
            include_declaration,
            sender,
        } => {
            let locations = references_via_db(
                &snapshot,
                &uri,
                &path,
                &text,
                position,
                encoding,
                include_declaration,
            );
            let _ = sender.send(Message::Response(Response::new_ok(id, locations)));
        }
        ReadJob::DocumentHighlight {
            id,
            path,
            text,
            position,
            sender,
        } => {
            let highlights =
                document_highlights_via_db(&snapshot, &path, &text, position, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, highlights)));
        }
        ReadJob::PrepareRename {
            id,
            path,
            text,
            position,
            sender,
        } => {
            let result = prepare_rename_via_db(&snapshot, &path, &text, position, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, result)));
        }
        ReadJob::Rename {
            id,
            uri,
            path,
            text,
            position,
            new_name,
            sender,
        } => {
            let response =
                match rename_via_db(&snapshot, &uri, &path, &text, position, &new_name, encoding) {
                    Ok(edit) => Response::new_ok(id, edit),
                    Err(message) => Response::new_err(id, ErrorCode::InvalidParams as i32, message),
                };
            let _ = sender.send(Message::Response(response));
        }
        ReadJob::PrepareCallHierarchy {
            id,
            uri,
            path,
            text,
            position,
            sender,
        } => {
            let items =
                prepare_call_hierarchy_via_db(&snapshot, &uri, &path, &text, position, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, items)));
        }
        ReadJob::CallHierarchyIncoming { id, item, sender } => {
            let calls = incoming_calls_via_db(&snapshot, &item, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, calls)));
        }
        ReadJob::CallHierarchyOutgoing { id, item, sender } => {
            let calls = outgoing_calls_via_db(&snapshot, &item, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, calls)));
        }
        ReadJob::PrepareTypeHierarchy {
            id,
            uri,
            path,
            text,
            position,
            sender,
        } => {
            let items =
                prepare_type_hierarchy_via_db(&snapshot, &uri, &path, &text, position, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, items)));
        }
        ReadJob::TypeHierarchySupertypes { id, item, sender } => {
            let items = supertypes_via_db(&snapshot, &item, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, items)));
        }
        ReadJob::TypeHierarchySubtypes { id, item, sender } => {
            let items = subtypes_via_db(&snapshot, &item, encoding);
            let _ = sender.send(Message::Response(Response::new_ok(id, items)));
        }
    }
}