fatou 0.6.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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Server entry points: the initialize handshake, advertised capabilities, and
//! the main event loop that wires the channels, pools, and threads together.

use std::error::Error;
use std::path::PathBuf;

use crossbeam_channel::select;
use lsp_server::{Connection, Message};
use lsp_types::{
    CallHierarchyServerCapability, ClientCapabilities, CodeActionKind, CodeActionOptions,
    CodeActionProviderCapability, CompletionOptions, DiagnosticOptions,
    DiagnosticServerCapabilities, DocumentLinkOptions, FoldingRangeProviderCapability,
    HoverProviderCapability, InitializeParams, OneOf, PositionEncodingKind, RenameOptions,
    SelectionRangeProviderCapability, SemanticTokensFullOptions, SemanticTokensOptions,
    ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
    TextDocumentSyncOptions, TextDocumentSyncSaveOptions, WorkspaceFoldersServerCapabilities,
    WorkspaceServerCapabilities,
};

use std::sync::Arc;

use crate::environment::EnvContext;
use crate::incremental::normalize_path;
use crate::index::{PackageIndex, dev_packages, harvest_libraries, harvest_workspace};
use crate::text::PositionEncoding;

use super::analysis_thread::{AnalysisRequest, LibraryMessage, spawn_analysis_thread};
use super::read_jobs::ReadJob;
use super::semantic_tokens::legend;
use super::state::{GlobalState, Outbound};
use super::task_pool::{TaskPool, read_pool_size};
use super::uri::to_path;

pub(crate) type DynError = Box<dyn Error + Sync + Send>;

/// Run the language server on stdio until the client shuts it down.
pub fn run() -> Result<(), DynError> {
    let (connection, io_threads) = Connection::stdio();
    serve(&connection)?;
    io_threads.join()?;
    Ok(())
}

/// Perform the initialize handshake on `connection`, then run the message loop.
/// Split out from [`run`] so tests can drive it over an in-memory connection.
///
/// The handshake is two-step ([`Connection::initialize_start`] /
/// [`Connection::initialize_finish`]) rather than [`Connection::initialize`]
/// because the advertised capabilities depend on the client's: the position
/// encoding is negotiated from `general.positionEncodings`.
pub fn serve(connection: &Connection) -> Result<(), DynError> {
    let (id, params) = connection.initialize_start()?;
    let params: InitializeParams = serde_json::from_value(params)?;
    let encoding = negotiate_position_encoding(&params.capabilities);
    let workspace_roots = workspace_roots(&params);
    // Watching only pays off with a workspace to keep fresh; without roots the
    // harvester never runs and every watched event would be dropped anyway.
    let register_watchers =
        supports_watched_files_registration(&params.capabilities) && !workspace_roots.is_empty();
    let pull_diagnostics = supports_pull_diagnostics(&params.capabilities);
    let diagnostic_refresh = supports_diagnostic_refresh(&params.capabilities);
    let result =
        serde_json::json!({ "capabilities": capabilities_json(encoding, pull_diagnostics) });
    connection.initialize_finish(id, result)?;
    main_loop(
        connection,
        encoding,
        workspace_roots,
        register_watchers,
        pull_diagnostics,
        diagnostic_refresh,
    )
}

/// Whether the client pulls diagnostics (`textDocument/diagnostic`). With
/// pull support the server advertises a diagnostic provider and keeps the
/// push path only for files with no open buffer; without it, push stays the
/// sole channel (the fallback).
fn supports_pull_diagnostics(capabilities: &ClientCapabilities) -> bool {
    capabilities
        .text_document
        .as_ref()
        .is_some_and(|text_document| text_document.diagnostic.is_some())
}

/// Whether the client accepts `workspace/diagnostic/refresh`, the server's
/// nudge to re-pull open documents after a re-harvest changes the include
/// graph.
fn supports_diagnostic_refresh(capabilities: &ClientCapabilities) -> bool {
    capabilities
        .workspace
        .as_ref()
        .and_then(|workspace| workspace.diagnostic.as_ref())
        .and_then(|diagnostic| diagnostic.refresh_support)
        .unwrap_or(false)
}

/// Whether the client accepts a dynamic `workspace/didChangeWatchedFiles`
/// registration. File watching has no static server capability: without this,
/// the server never hears about external file events and relies on saves
/// alone.
fn supports_watched_files_registration(capabilities: &ClientCapabilities) -> bool {
    capabilities
        .workspace
        .as_ref()
        .and_then(|workspace| workspace.did_change_watched_files.as_ref())
        .and_then(|caps| caps.dynamic_registration)
        .unwrap_or(false)
}

/// The workspace roots to resolve Julia environments against: every workspace
/// folder in client order (deduped on the normalized path), falling back to the
/// (deprecated) `root_uri` when the client sent no folders. Empty when the
/// client opened no folder at all (a single loose file); the loader then does
/// nothing.
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
    let folder_uris: Vec<&lsp_types::Uri> = match params.workspace_folders.as_deref() {
        Some(folders) if !folders.is_empty() => folders.iter().map(|f| &f.uri).collect(),
        #[allow(deprecated)]
        _ => params.root_uri.iter().collect(),
    };
    let mut seen = std::collections::HashSet::new();
    folder_uris
        .into_iter()
        .filter_map(to_path)
        .filter(|path| seen.insert(normalize_path(path)))
        .collect()
}

/// Pick the position encoding for the session: UTF-8 (plain byte offsets, no
/// re-encoding on our side) when the client offers it, otherwise the mandatory
/// LSP default of UTF-16.
fn negotiate_position_encoding(capabilities: &ClientCapabilities) -> PositionEncoding {
    let offered = capabilities
        .general
        .as_ref()
        .and_then(|general| general.position_encodings.as_deref())
        .unwrap_or_default();
    if offered.contains(&PositionEncodingKind::UTF8) {
        PositionEncoding::Utf8
    } else {
        PositionEncoding::Utf16
    }
}

fn server_capabilities(encoding: PositionEncoding, pull_diagnostics: bool) -> ServerCapabilities {
    ServerCapabilities {
        // Advertised only to a client that pulls: pushing and pulling the
        // same document's diagnostics would double them up, so per-document
        // publishes are gated off in the same breath (see `GlobalState`).
        diagnostic_provider: pull_diagnostics.then(|| {
            DiagnosticServerCapabilities::Options(DiagnosticOptions {
                identifier: Some("fatou".to_string()),
                // Include-graph diagnostics cross files: an include edit in
                // one member can change another member's report.
                inter_file_dependencies: true,
                workspace_diagnostics: false,
                work_done_progress_options: Default::default(),
            })
        }),
        position_encoding: Some(match encoding {
            PositionEncoding::Utf8 => PositionEncodingKind::UTF8,
            PositionEncoding::Utf16 => PositionEncodingKind::UTF16,
        }),
        text_document_sync: Some(TextDocumentSyncCapability::Options(
            TextDocumentSyncOptions {
                open_close: Some(true),
                change: Some(TextDocumentSyncKind::INCREMENTAL),
                // Save notifications trigger a re-harvest of the workspace
                // package so cross-file navigation reflects added/removed
                // top-level symbols; the text is not needed (we read from disk).
                save: Some(TextDocumentSyncSaveOptions::Supported(true)),
                ..Default::default()
            },
        )),
        code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions {
            // Only lint quick fixes for now; organize-imports style actions are
            // a Phase 6 item.
            code_action_kinds: Some(vec![CodeActionKind::QUICKFIX]),
            work_done_progress_options: Default::default(),
            resolve_provider: None,
        })),
        document_formatting_provider: Some(OneOf::Left(true)),
        document_range_formatting_provider: Some(OneOf::Left(true)),
        document_symbol_provider: Some(OneOf::Left(true)),
        workspace_symbol_provider: Some(OneOf::Left(true)),
        completion_provider: Some(CompletionOptions {
            // `.` opens member completion, `@` opens macro completion.
            trigger_characters: Some(vec![".".to_string(), "@".to_string()]),
            resolve_provider: Some(true),
            ..Default::default()
        }),
        hover_provider: Some(HoverProviderCapability::Simple(true)),
        definition_provider: Some(OneOf::Left(true)),
        references_provider: Some(OneOf::Left(true)),
        document_highlight_provider: Some(OneOf::Left(true)),
        rename_provider: Some(OneOf::Right(RenameOptions {
            prepare_provider: Some(true),
            work_done_progress_options: Default::default(),
        })),
        call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
        signature_help_provider: Some(SignatureHelpOptions {
            // `(` opens signature help, `,` (also a retrigger) advances the
            // active parameter.
            trigger_characters: Some(vec!["(".to_string(), ",".to_string()]),
            retrigger_characters: Some(vec![",".to_string()]),
            work_done_progress_options: Default::default(),
        }),
        folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
        document_link_provider: Some(DocumentLinkOptions {
            // Targets resolve eagerly (a lexical path join, no I/O worth
            // deferring), so no `documentLink/resolve`.
            resolve_provider: Some(false),
            work_done_progress_options: Default::default(),
        }),
        selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
        semantic_tokens_provider: Some(
            SemanticTokensOptions {
                work_done_progress_options: Default::default(),
                legend: legend(),
                range: None,
                full: Some(SemanticTokensFullOptions::Bool(true)),
            }
            .into(),
        ),
        workspace: Some(WorkspaceServerCapabilities {
            // Every folder from `initialize` gets the full workspace treatment;
            // dynamic add/remove (`didChangeWorkspaceFolders`) is not handled
            // yet, so change notifications are not requested.
            workspace_folders: Some(WorkspaceFoldersServerCapabilities {
                supported: Some(true),
                change_notifications: None,
            }),
            file_operations: None,
        }),
        ..Default::default()
    }
}

/// The `initialize` result's `capabilities` value. Built from the serialized
/// [`ServerCapabilities`] because lsp-types 0.97 has no
/// `type_hierarchy_provider` field (the request, param, and item types exist;
/// the capability field was never added upstream), so it is injected into the
/// serialized map here.
fn capabilities_json(encoding: PositionEncoding, pull_diagnostics: bool) -> serde_json::Value {
    let mut capabilities = serde_json::to_value(server_capabilities(encoding, pull_diagnostics))
        .expect("server capabilities serialize");
    capabilities["typeHierarchyProvider"] = serde_json::Value::Bool(true);
    capabilities
}

/// The main event loop: dispatch incoming JSON-RPC messages and analysis
/// results. Owns no salsa database (see the module docs); joins the analysis
/// thread before returning.
fn main_loop(
    connection: &Connection,
    encoding: PositionEncoding,
    workspace_roots: Vec<PathBuf>,
    register_watchers: bool,
    pull_diagnostics: bool,
    diagnostic_refresh: bool,
) -> Result<(), DynError> {
    let (out_tx, out_rx) = crossbeam_channel::unbounded::<Outbound>();
    let (analysis_tx, analysis_rx) = crossbeam_channel::unbounded::<AnalysisRequest>();
    let (read_tx, read_rx) = crossbeam_channel::unbounded::<ReadJob>();
    let (library_tx, library_rx) = crossbeam_channel::unbounded::<LibraryMessage>();
    // Harvest signals from the main loop to the workspace harvester: a changed
    // source file's path (saves and watched events; the harvester ignores paths
    // outside every workspace package) or an environment-file change.
    let (harvest_tx, harvest_rx) = crossbeam_channel::unbounded::<HarvestSignal>();
    // Disk-sync signals from the main loop to the analysis thread: a file's
    // path, whose tracked input is reverted to on-disk text (a closed
    // document's discarded buffer, or a watched file changed outside any open
    // buffer).
    let (sync_tx, sync_rx) = crossbeam_channel::unbounded::<PathBuf>();

    // Resolve the environment and harvest its packages off the event loop: it
    // walks the filesystem and parses all of Base, so it must not block the
    // handshake (nor shutdown — the thread is detached). The result is swapped
    // into the db when it lands; every feature stays usable in the meantime, and
    // library go-to-definition/completion start answering once it arrives. The
    // same thread re-harvests the workspace package on each harvest signal.
    spawn_workspace_harvester(workspace_roots, library_tx, harvest_rx);

    // The read pool serves latency-sensitive work (formatting, the analysis
    // read-phase). Its workers must outlive both `state` and the analysis
    // thread; the drop order at the end of this function guarantees that.
    let read_pool = TaskPool::new("fatou-lsp-read", read_pool_size());
    let analysis_handle = spawn_analysis_thread(
        analysis_rx,
        read_rx,
        library_rx,
        sync_rx,
        out_tx,
        read_pool.spawner(),
        encoding,
        // The per-edit push is the fallback for a client that cannot pull.
        !pull_diagnostics,
    );

    let mut state = GlobalState::new(
        connection.sender.clone(),
        analysis_tx,
        read_tx,
        harvest_tx,
        sync_tx,
        encoding,
        pull_diagnostics,
        diagnostic_refresh,
    );

    // `initialize_finish` has already consumed the client's `initialized`
    // notification (lsp-server handles it inside the handshake), so the
    // registration request is legal from the first turn of the loop.
    if register_watchers {
        state.register_file_watchers();
    }

    loop {
        select! {
            recv(connection.receiver) -> msg => {
                let Ok(msg) = msg else { break };
                match msg {
                    Message::Request(req) => {
                        if connection.handle_shutdown(&req)? {
                            break;
                        }
                        state.on_request(req);
                    }
                    Message::Notification(note) => state.on_notification(note),
                    Message::Response(_) => {}
                }
            }
            recv(out_rx) -> outbound => {
                let Ok(outbound) = outbound else { break };
                state.on_outbound(outbound);
            }
        }
    }

    // Dropping `state` drops `analysis_tx`/`read_tx` → the analysis thread's
    // recv disconnects → it exits and drops the db. The library loader is
    // detached; it ends on its own (or when its send fails after teardown).
    drop(state);
    let _ = analysis_handle.join();
    Ok(())
}

/// A signal from the main loop to the workspace harvester thread.
pub(crate) enum HarvestSignal {
    /// A source file changed on disk (a save, or a watched create, change, or
    /// delete): re-harvest the workspace package owning it, if any.
    Source(PathBuf),
    /// An environment file (a `Project.toml` or `Manifest.toml` flavor)
    /// changed: re-resolve every workspace environment and re-harvest from
    /// scratch.
    Environment,
}

/// Resolve the Julia environment of every workspace root, harvest the merged
/// library on a detached background thread, then stay alive serving harvest
/// signals: a source signal re-harvests the workspace package owning the file,
/// and an environment signal starts the resolve-and-harvest cycle over (a
/// `Pkg.add`, or a created or deleted `Project.toml`, must reshape the whole
/// library).
///
/// Only runs when the client provided at least one workspace root: without one
/// there is no project to resolve against (a single loose file), and resolving
/// the machine's default environment would harvest all of Base for no benefit —
/// notably in the in-memory server tests, which open no folder. Best-effort: an
/// unresolved environment or harvest failure simply leaves the library empty
/// (or without that folder's contribution).
fn spawn_workspace_harvester(
    workspace_roots: Vec<PathBuf>,
    library_tx: crossbeam_channel::Sender<LibraryMessage>,
    signal_rx: crossbeam_channel::Receiver<HarvestSignal>,
) {
    if workspace_roots.is_empty() {
        return;
    }
    let spawned = std::thread::Builder::new()
        .name("fatou-index-loader".to_string())
        .spawn(move || {
            'resolve: loop {
                // One environment per folder, deduped on the resolved project file:
                // two folders under one project (or a user-set `JULIA_PROJECT`,
                // which wins over every folder's walk-up) collapse to one.
                let mut envs = Vec::new();
                let mut projects = std::collections::HashSet::new();
                for root in &workspace_roots {
                    let ctx = EnvContext::from_process(root.clone());
                    let Ok(Some(env)) = crate::environment::resolve(&ctx) else {
                        continue;
                    };
                    if projects.insert(normalize_path(&env.project_file)) {
                        envs.push(env);
                    }
                }
                // An empty resolve still sends: a deleted `Project.toml` must clear
                // the previously harvested library (and the first send with nothing
                // resolved is a cheap no-op harvest).
                let devs = dev_packages(&envs);
                if library_tx
                    .send(LibraryMessage::Full(harvest_libraries(&envs)))
                    .is_err()
                {
                    return; // The analysis thread is gone; stop harvesting.
                }

                // With packages under development, re-harvest the one whose files a
                // source signal touches (a `src/` prefix check, longest prefix
                // winning for nested folders — the same rule as
                // `workspace_package_for`). Signals elsewhere, and every source
                // signal when no folder is a package, are ignored.
                let prefixes: Vec<(crate::environment::DevPackage, PathBuf)> = devs
                    .into_iter()
                    .map(|dev| {
                        let src = normalize_path(&dev.root.join("src"));
                        (dev, src)
                    })
                    .collect();
                // The last index sent per package, so an unchanged re-harvest is
                // skipped. A save touching a `src/` file re-harvests, but body-only
                // and formatting-only edits leave the public API identical;
                // resending then would force a `set_package_index` db write that
                // needlessly cancels in-flight diagnostics (the write races the
                // very format-on-save that triggered the save). Only send on a real
                // change.
                let mut last: std::collections::HashMap<String, Arc<PackageIndex>> =
                    std::collections::HashMap::new();
                while let Ok(signal) = signal_rx.recv() {
                    let changed = match signal {
                        HarvestSignal::Environment => {
                            // Coalesce the burst (`Pkg.add` rewrites the project and
                            // manifest together; an editor save and its watched
                            // event double-fire): drain everything queued — the
                            // full re-resolve subsumes any drained source signal.
                            while signal_rx.try_recv().is_ok() {}
                            continue 'resolve;
                        }
                        HarvestSignal::Source(path) => normalize_path(&path),
                    };
                    let Some((dev, _)) = prefixes
                        .iter()
                        .filter(|(_, src)| changed.starts_with(src))
                        .max_by_key(|(_, src)| src.components().count())
                    else {
                        continue;
                    };
                    let index = Arc::new(harvest_workspace(dev));
                    if last.get(&dev.name) == Some(&index) {
                        continue;
                    }
                    last.insert(dev.name.clone(), Arc::clone(&index));
                    if library_tx
                        .send(LibraryMessage::Package {
                            name: dev.name.clone(),
                            index,
                        })
                        .is_err()
                    {
                        return; // The analysis thread is gone; stop harvesting.
                    }
                }
                return; // The main loop is gone; stop harvesting.
            }
        });
    // A spawn failure is non-fatal: the server runs without a library index.
    debug_assert!(spawned.is_ok(), "spawn index loader thread");
    drop(spawned);
}

#[cfg(test)]
mod tests {
    use lsp_types::GeneralClientCapabilities;

    use super::*;

    fn caps_offering(encodings: Option<Vec<PositionEncodingKind>>) -> ClientCapabilities {
        ClientCapabilities {
            general: Some(GeneralClientCapabilities {
                position_encodings: encodings,
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    #[test]
    fn negotiation_defaults_to_utf16() {
        // No `general` capabilities at all, and `general` without an
        // `positionEncodings` offer, both fall back to the mandatory default.
        let none = ClientCapabilities::default();
        assert_eq!(negotiate_position_encoding(&none), PositionEncoding::Utf16);
        assert_eq!(
            negotiate_position_encoding(&caps_offering(None)),
            PositionEncoding::Utf16
        );
        assert_eq!(
            negotiate_position_encoding(&caps_offering(Some(vec![
                PositionEncodingKind::UTF16,
                PositionEncodingKind::UTF32,
            ]))),
            PositionEncoding::Utf16
        );
    }

    #[test]
    fn negotiation_prefers_offered_utf8() {
        assert_eq!(
            negotiate_position_encoding(&caps_offering(Some(vec![
                PositionEncodingKind::UTF16,
                PositionEncodingKind::UTF8,
            ]))),
            PositionEncoding::Utf8
        );
    }

    fn folder(uri: &str) -> lsp_types::WorkspaceFolder {
        lsp_types::WorkspaceFolder {
            uri: uri.parse().unwrap(),
            name: String::new(),
        }
    }

    /// The platform path a `file:` URI decodes to, so assertions hold on
    /// Windows too.
    fn path_of(uri: &str) -> PathBuf {
        to_path(&uri.parse().unwrap()).unwrap()
    }

    #[test]
    fn workspace_roots_takes_every_folder_in_client_order() {
        let params = InitializeParams {
            workspace_folders: Some(vec![folder("file:///work/b"), folder("file:///work/a")]),
            ..Default::default()
        };
        assert_eq!(
            workspace_roots(&params),
            vec![path_of("file:///work/b"), path_of("file:///work/a")]
        );
    }

    #[test]
    fn workspace_roots_dedups_equivalent_folders() {
        let params = InitializeParams {
            workspace_folders: Some(vec![
                folder("file:///work/a"),
                folder("file:///work/./a"),
                folder("file:///work/b"),
            ]),
            ..Default::default()
        };
        assert_eq!(
            workspace_roots(&params),
            vec![path_of("file:///work/a"), path_of("file:///work/b")]
        );
    }

    #[test]
    fn workspace_roots_falls_back_to_root_uri() {
        #[allow(deprecated)]
        let params = InitializeParams {
            root_uri: Some("file:///work/a".parse().unwrap()),
            ..Default::default()
        };
        assert_eq!(workspace_roots(&params), vec![path_of("file:///work/a")]);

        // Folders, when present, win over the deprecated root_uri; an empty
        // folder list falls back too.
        #[allow(deprecated)]
        let both = InitializeParams {
            workspace_folders: Some(vec![folder("file:///work/b")]),
            root_uri: Some("file:///work/a".parse().unwrap()),
            ..Default::default()
        };
        assert_eq!(workspace_roots(&both), vec![path_of("file:///work/b")]);
        #[allow(deprecated)]
        let empty_folders = InitializeParams {
            workspace_folders: Some(Vec::new()),
            root_uri: Some("file:///work/a".parse().unwrap()),
            ..Default::default()
        };
        assert_eq!(
            workspace_roots(&empty_folders),
            vec![path_of("file:///work/a")]
        );
    }

    #[test]
    fn no_folders_yields_no_roots() {
        assert!(workspace_roots(&InitializeParams::default()).is_empty());
    }

    #[test]
    fn pull_diagnostics_require_the_client_capability() {
        assert!(!supports_pull_diagnostics(&ClientCapabilities::default()));
        let caps = ClientCapabilities {
            text_document: Some(lsp_types::TextDocumentClientCapabilities {
                diagnostic: Some(lsp_types::DiagnosticClientCapabilities::default()),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert!(supports_pull_diagnostics(&caps));

        // The provider is advertised exactly when the client pulls.
        assert!(
            server_capabilities(PositionEncoding::Utf16, true)
                .diagnostic_provider
                .is_some()
        );
        assert!(
            server_capabilities(PositionEncoding::Utf16, false)
                .diagnostic_provider
                .is_none()
        );
    }

    /// The type-hierarchy capability rides the serialized JSON (lsp-types 0.97
    /// has no struct field for it); the injection must not clobber the
    /// struct-borne capabilities around it.
    #[test]
    fn type_hierarchy_capability_is_injected_into_the_json() {
        let capabilities = capabilities_json(PositionEncoding::Utf16, false);
        assert_eq!(
            capabilities["typeHierarchyProvider"],
            serde_json::json!(true)
        );
        assert_eq!(
            capabilities["callHierarchyProvider"],
            serde_json::json!(true)
        );
    }

    #[test]
    fn diagnostic_refresh_requires_the_client_capability() {
        assert!(!supports_diagnostic_refresh(&ClientCapabilities::default()));
        let caps = ClientCapabilities {
            workspace: Some(lsp_types::WorkspaceClientCapabilities {
                diagnostic: Some(lsp_types::DiagnosticWorkspaceClientCapabilities {
                    refresh_support: Some(true),
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert!(supports_diagnostic_refresh(&caps));
    }

    #[test]
    fn watcher_registration_requires_the_client_capability() {
        assert!(!supports_watched_files_registration(
            &ClientCapabilities::default()
        ));
        let caps = ClientCapabilities {
            workspace: Some(lsp_types::WorkspaceClientCapabilities {
                did_change_watched_files: Some(
                    lsp_types::DidChangeWatchedFilesClientCapabilities {
                        dynamic_registration: Some(true),
                        relative_pattern_support: None,
                    },
                ),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert!(supports_watched_files_registration(&caps));
    }
}