summaryrefslogtreecommitdiff
path: root/support/texlab/tests/support/mod.rs
blob: abd1bfe3130ddad01514772e27f5586af30c94ff (plain)
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
use copy_dir::copy_dir;
use futures::lock::Mutex;
use futures_boxed::boxed;
use jsonrpc::client::Result;
use lsp_types::*;
use serde::Serialize;
use std::collections::HashMap;
use std::fs::remove_dir;
use std::path::PathBuf;
use std::sync::Arc;
use tempfile::{tempdir, TempDir};
use texlab::build::BuildOptions;
use texlab::client::LspClient;
use texlab::diagnostics::LatexLintOptions;
use texlab::formatting::bibtex::BibtexFormattingOptions;
use texlab::server::LatexLspServer;
use texlab::workspace::Uri;

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct MockLspClientOptions {
    pub bibtex_formatting: Option<BibtexFormattingOptions>,
    pub latex_lint: Option<LatexLintOptions>,
    pub latex_build: Option<BuildOptions>,
}

#[derive(Debug, Default)]
pub struct MockLspClient {
    pub messages: Mutex<Vec<ShowMessageParams>>,
    pub options: Mutex<MockLspClientOptions>,
    pub diagnostics_by_uri: Mutex<HashMap<Uri, Vec<Diagnostic>>>,
    pub log_messages: Mutex<Vec<LogMessageParams>>,
}

impl MockLspClient {
    pub fn new() -> Self {
        Self::default()
    }
}

impl LspClient for MockLspClient {
    #[boxed]
    async fn configuration(&self, params: ConfigurationParams) -> Result<serde_json::Value> {
        fn serialize<T>(options: &Option<T>) -> Result<serde_json::Value>
        where
            T: Serialize,
        {
            options
                .as_ref()
                .map(|options| serde_json::to_value(vec![options]).unwrap())
                .ok_or_else(|| jsonrpc::Error::internal_error("Internal error".to_owned()))
        }

        let options = self.options.lock().await;
        match params.items[0].section.as_ref().unwrap().as_ref() {
            "bibtex.formatting" => serialize(&options.bibtex_formatting),
            "latex.lint" => serialize(&options.latex_lint),
            "latex.build" => serialize(&options.latex_build),
            _ => panic!("Invalid language configuration!"),
        }
    }

    #[boxed]
    async fn show_message(&self, params: ShowMessageParams) {
        let mut messages = self.messages.lock().await;
        messages.push(params);
    }

    #[boxed]
    async fn register_capability(&self, _params: RegistrationParams) -> Result<()> {
        Ok(())
    }

    #[boxed]
    async fn publish_diagnostics(&self, params: PublishDiagnosticsParams) {
        let mut diagnostics_by_uri = self.diagnostics_by_uri.lock().await;
        diagnostics_by_uri.insert(params.uri.into(), params.diagnostics);
    }

    #[boxed]
    async fn work_done_progress_create(&self, _params: WorkDoneProgressCreateParams) -> Result<()> {
        Ok(())
    }

    #[boxed]
    async fn progress(&self, _params: ProgressParams) {}

    #[boxed]
    async fn log_message(&self, params: LogMessageParams) {
        let mut messages = self.log_messages.lock().await;
        messages.push(params);
    }
}

pub struct Scenario {
    pub directory: TempDir,
    pub server: LatexLspServer<MockLspClient>,
    pub client: Arc<MockLspClient>,
}

impl Scenario {
    pub fn new(name: &str, distribution: Arc<Box<dyn tex::Distribution>>) -> Self {
        let directory = tempdir().unwrap();
        remove_dir(directory.path()).unwrap();
        let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("scenarios")
            .join(name);
        copy_dir(source, directory.path()).unwrap();

        let client = Arc::new(MockLspClient::new());
        let server = LatexLspServer::new(distribution, Arc::clone(&client));
        Self {
            directory,
            server,
            client,
        }
    }

    pub async fn initialize(&self, capabilities: &ClientCapabilities) {
        let root_uri = Uri::from_file_path(self.directory.path()).unwrap();
        let params = InitializeParams {
            process_id: None,
            root_path: Some(self.directory.path().to_string_lossy().into_owned()),
            root_uri: Some(root_uri.into()),
            initialization_options: None,
            capabilities: capabilities.clone(),
            trace: None,
            workspace_folders: None,
        };

        self.server
            .execute_async(|svr| svr.initialize(params))
            .await
            .unwrap();

        self.server
            .execute(|svr| svr.initialized(InitializedParams {}))
            .await;
    }

    pub fn uri(&self, name: &str) -> Uri {
        let mut path = self.directory.path().to_owned();
        path.push(name);
        Uri::from_file_path(path).unwrap()
    }

    pub async fn read(&self, name: &'static str) -> String {
        let mut path = self.directory.path().to_owned();
        path.push(name);
        let data = tokio::fs::read(path).await.unwrap();
        let text = String::from_utf8_lossy(&data);
        text.replace('\r', "")
    }

    pub async fn open(&self, name: &'static str) {
        let text = self.read(name).await;
        let language_id = if name.ends_with(".bib") {
            "bibtex"
        } else {
            "latex"
        };

        let params = DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: self.uri(name).into(),
                version: 0,
                language_id: language_id.to_owned(),
                text,
            },
        };
        self.server.execute(|svr| svr.did_open(params)).await;
    }
}

pub mod capabilities {
    use lsp_types::*;

    pub static CLIENT_FULL_CAPABILITIES: ClientCapabilities = ClientCapabilities {
        workspace: Some(WorkspaceClientCapabilities {
            configuration: Some(true),
            did_change_watched_files: None,
            workspace_folders: None,
            apply_edit: None,
            execute_command: None,
            symbol: None,
            workspace_edit: None,
            did_change_configuration: None,
        }),
        text_document: Some(TextDocumentClientCapabilities {
            synchronization: None,
            completion: None,
            hover: None,
            signature_help: None,
            references: None,
            document_highlight: None,
            document_symbol: Some(DocumentSymbolCapability {
                dynamic_registration: None,
                hierarchical_document_symbol_support: Some(true),
                symbol_kind: None,
            }),
            formatting: None,
            range_formatting: None,
            on_type_formatting: None,
            declaration: None,
            definition: Some(GotoCapability {
                dynamic_registration: None,
                link_support: Some(true),
            }),
            type_definition: None,
            implementation: None,
            code_action: None,
            code_lens: None,
            document_link: None,
            color_provider: None,
            rename: None,
            publish_diagnostics: None,
            folding_range: None,
        }),
        experimental: None,
        window: Some(WindowClientCapabilities {
            work_done_progress: Some(true),
        }),
    };

    pub static CLIENT_NO_LINK_CAPABILITIES: ClientCapabilities = ClientCapabilities {
        workspace: Some(WorkspaceClientCapabilities {
            configuration: Some(true),
            did_change_watched_files: None,
            workspace_folders: None,
            apply_edit: None,
            execute_command: None,
            symbol: None,
            workspace_edit: None,
            did_change_configuration: None,
        }),
        text_document: Some(TextDocumentClientCapabilities {
            synchronization: None,
            completion: None,
            hover: None,
            signature_help: None,
            references: None,
            document_highlight: None,
            document_symbol: None,
            formatting: None,
            range_formatting: None,
            on_type_formatting: None,
            declaration: None,
            definition: Some(GotoCapability {
                dynamic_registration: None,
                link_support: Some(false),
            }),
            type_definition: None,
            implementation: None,
            code_action: None,
            code_lens: None,
            document_link: None,
            color_provider: None,
            rename: None,
            publish_diagnostics: None,
            folding_range: None,
        }),
        experimental: None,
        window: Some(WindowClientCapabilities {
            work_done_progress: Some(true),
        }),
    };
}

pub mod completion {
    use super::*;

    pub async fn run_list(
        scenario_short_name: &'static str,
        file: &'static str,
        line: u64,
        character: u64,
    ) -> (Scenario, Vec<CompletionItem>) {
        let scenario_name = format!("completion/{}", scenario_short_name);
        let scenario = Scenario::new(&scenario_name, Arc::new(Box::new(tex::Unknown)));
        scenario.open(file).await;
        scenario
            .initialize(&capabilities::CLIENT_FULL_CAPABILITIES)
            .await;

        let params = CompletionParams {
            text_document_position: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier::new(scenario.uri(file).into()),
                position: Position::new(line, character),
            },
            context: None,
        };

        let items = scenario
            .server
            .execute_async(|svr| svr.completion(params))
            .await
            .unwrap()
            .items;

        (scenario, items)
    }

    pub async fn run_empty(
        scenario_short_name: &'static str,
        file: &'static str,
        line: u64,
        character: u64,
    ) {
        assert!(run_list(scenario_short_name, file, line, character)
            .await
            .1
            .is_empty());
    }

    pub async fn run_item(
        scenario_short_name: &'static str,
        file: &'static str,
        line: u64,
        character: u64,
        item_name: &'static str,
    ) -> CompletionItem {
        let (scenario, items) = run_list(scenario_short_name, file, line, character).await;

        let item = items
            .into_iter()
            .find(|item| item.label == item_name)
            .unwrap();

        scenario
            .server
            .execute_async(|svr| svr.completion_resolve(item))
            .await
            .unwrap()
    }

    pub mod verify {
        use lsp_types::*;
        use texlab::range::RangeExt;

        pub fn text_edit(
            item: &CompletionItem,
            start_line: u64,
            start_character: u64,
            end_line: u64,
            end_character: u64,
            text: &str,
        ) {
            assert_eq!(
                item.text_edit,
                Some(TextEdit::new(
                    Range::new_simple(start_line, start_character, end_line, end_character),
                    text.into()
                ))
            );
        }

        pub fn detail(item: &CompletionItem, detail: &str) {
            assert_eq!(item.detail.as_ref().unwrap(), detail);
        }

        pub fn labels(items: &[CompletionItem], expected_labels: Vec<&'static str>) {
            let mut actual_labels: Vec<&str> =
                items.iter().map(|item| item.label.as_ref()).collect();
            actual_labels.sort();
            assert_eq!(actual_labels, expected_labels);
        }
    }
}

pub mod definition {
    use super::capabilities::*;
    use super::*;
    use texlab::definition::DefinitionResponse;

    pub async fn run(
        scenario_short_name: &'static str,
        file: &'static str,
        line: u64,
        character: u64,
        capabilities: &ClientCapabilities,
    ) -> (Scenario, DefinitionResponse) {
        let scenario_name = format!("definition/{}", scenario_short_name);
        let scenario = Scenario::new(&scenario_name, Arc::new(Box::new(tex::Unknown)));
        scenario.initialize(capabilities).await;
        scenario.open(file).await;

        let params = TextDocumentPositionParams {
            text_document: TextDocumentIdentifier::new(scenario.uri(file).into()),
            position: Position::new(line, character),
        };

        let response = scenario
            .server
            .execute_async(|svr| svr.definition(params))
            .await
            .unwrap();

        (scenario, response)
    }

    pub async fn run_link(
        scenario_short_name: &'static str,
        file: &'static str,
        line: u64,
        character: u64,
    ) -> (Scenario, Vec<LocationLink>) {
        let (scenario, response) = run(
            scenario_short_name,
            file,
            line,
            character,
            &CLIENT_FULL_CAPABILITIES,
        )
        .await;
        match response {
            DefinitionResponse::LocationLinks(links) => (scenario, links),
            DefinitionResponse::Locations(_) => unreachable!(),
        }
    }

    pub async fn run_location(
        scenario_short_name: &'static str,
        file: &'static str,
        line: u64,
        character: u64,
    ) -> (Scenario, Vec<Location>) {
        let (scenario, response) = run(
            scenario_short_name,
            file,
            line,
            character,
            &CLIENT_NO_LINK_CAPABILITIES,
        )
        .await;
        match response {
            DefinitionResponse::LocationLinks(_) => unreachable!(),
            DefinitionResponse::Locations(locations) => (scenario, locations),
        }
    }

    pub mod verify {
        use super::*;
        use texlab::range::RangeExt;

        pub fn origin_selection_range(
            link: &LocationLink,
            start_line: u64,
            start_character: u64,
            end_line: u64,
            end_character: u64,
        ) {
            assert_eq!(
                link.origin_selection_range,
                Some(Range::new_simple(
                    start_line,
                    start_character,
                    end_line,
                    end_character
                ))
            );
        }
    }
}

pub mod folding {
    use super::*;
    use std::cmp::Reverse;

    pub async fn run(file: &'static str) -> Vec<FoldingRange> {
        let scenario = Scenario::new("folding", Arc::new(Box::new(tex::Unknown)));
        scenario
            .initialize(&capabilities::CLIENT_FULL_CAPABILITIES)
            .await;
        scenario.open(file).await;
        let params = FoldingRangeParams {
            text_document: TextDocumentIdentifier::new(scenario.uri(file).into()),
        };

        let mut foldings = scenario
            .server
            .execute_async(|svr| svr.folding_range(params))
            .await
            .unwrap();

        foldings.sort_by_key(|folding| {
            let start = Position::new(folding.start_line, folding.start_character.unwrap());
            let end = Position::new(folding.end_line, folding.end_character.unwrap());
            (start, Reverse(end))
        });
        foldings
    }
}

pub mod formatting {
    use super::*;
    use texlab::formatting::bibtex::BibtexFormattingOptions;

    pub async fn run_bibtex(
        file: &'static str,
        options: Option<BibtexFormattingOptions>,
    ) -> (Scenario, Vec<TextEdit>) {
        let scenario = Scenario::new("formatting/bibtex", Arc::new(Box::new(tex::Unknown)));
        scenario
            .initialize(&capabilities::CLIENT_FULL_CAPABILITIES)
            .await;
        scenario.open(file).await;
        {
            scenario.client.options.lock().await.bibtex_formatting = options;
        }

        let params = DocumentFormattingParams {
            text_document: TextDocumentIdentifier::new(scenario.uri(file).into()),
            options: FormattingOptions {
                tab_size: 4,
                insert_spaces: true,
                properties: HashMap::new(),
            },
        };

        let edits = scenario
            .server
            .execute_async(|svr| svr.formatting(params))
            .await
            .unwrap();
        (scenario, edits)
    }
}

pub mod hover {
    use super::*;

    pub async fn run(
        scenario_short_name: &'static str,
        file: &'static str,
        line: u64,
        character: u64,
    ) -> Option<HoverContents> {
        let scenario_name = format!("hover/{}", scenario_short_name);
        let scenario = Scenario::new(&scenario_name, Arc::new(Box::new(tex::Unknown)));
        scenario
            .initialize(&capabilities::CLIENT_FULL_CAPABILITIES)
            .await;
        scenario.open(file).await;
        let identifier = TextDocumentIdentifier::new(scenario.uri(file).into());
        let params = TextDocumentPositionParams::new(identifier, Position::new(line, character));
        scenario
            .server
            .execute_async(|svr| svr.hover(params))
            .await
            .unwrap()
            .map(|hover| hover.contents)
    }
}

pub mod symbol {
    use super::*;
    use texlab::symbol::SymbolResponse;

    pub async fn run_hierarchical(file: &'static str) -> Vec<DocumentSymbol> {
        let scenario = Scenario::new("symbol/hierarchical", Arc::new(Box::new(tex::Unknown)));
        scenario
            .initialize(&capabilities::CLIENT_FULL_CAPABILITIES)
            .await;
        scenario.open(file).await;
        let params = DocumentSymbolParams {
            text_document: TextDocumentIdentifier::new(scenario.uri(file).into()),
        };

        let response = scenario
            .server
            .execute_async(|svr| svr.document_symbol(params))
            .await
            .unwrap();

        match response {
            SymbolResponse::Hierarchical(symbols) => symbols,
            SymbolResponse::Flat(_) => unreachable!(),
        }
    }

    pub async fn run_workspace(query: &'static str) -> (Scenario, Vec<SymbolInformation>) {
        let scenario = Scenario::new("symbol/workspace", Arc::new(Box::new(tex::Unknown)));
        scenario
            .initialize(&capabilities::CLIENT_FULL_CAPABILITIES)
            .await;
        scenario.open("foo.tex").await;
        scenario.open("bar.bib").await;
        let params = WorkspaceSymbolParams {
            query: query.into(),
        };
        let symbols = scenario
            .server
            .execute_async(|svr| svr.workspace_symbol(params))
            .await
            .unwrap();

        (scenario, symbols)
    }

    pub mod verify {
        use super::*;
        use texlab::range::RangeExt;

        pub fn symbol(
            symbol: &DocumentSymbol,
            name: &str,
            detail: Option<&str>,
            selection_range: Range,
            range: Range,
        ) {
            assert_eq!(symbol.name, name);
            assert_eq!(symbol.detail.as_ref().map(AsRef::as_ref), detail);
            assert_eq!(symbol.selection_range, selection_range);
            assert_eq!(symbol.range, range);
        }

        pub fn symbol_info(
            symbol: &SymbolInformation,
            scenario: &Scenario,
            file: &str,
            name: &str,
            start_line: u64,
            start_character: u64,
            end_line: u64,
            end_character: u64,
        ) {
            assert_eq!(symbol.name, name);
            let range = Range::new_simple(start_line, start_character, end_line, end_character);
            assert_eq!(
                symbol.location,
                Location::new(scenario.uri(file).into(), range)
            );
        }
    }
}