-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
language_server.rs
2750 lines (2543 loc) · 85.3 KB
/
language_server.rs
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use deno_ast::MediaType;
use deno_core::anyhow::anyhow;
use deno_core::error::AnyError;
use deno_core::resolve_url;
use deno_core::serde_json;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ModuleSpecifier;
use import_map::ImportMap;
use log::error;
use log::info;
use log::warn;
use lspower::jsonrpc::Error as LspError;
use lspower::jsonrpc::Result as LspResult;
use lspower::lsp::request::*;
use lspower::lsp::*;
use serde_json::from_value;
use std::env;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use tokio::fs;
use super::analysis::fix_ts_import_changes;
use super::analysis::ts_changes_to_edit;
use super::analysis::CodeActionCollection;
use super::analysis::CodeActionData;
use super::cache::CacheServer;
use super::capabilities;
use super::client::Client;
use super::code_lens;
use super::completions;
use super::config::Config;
use super::config::ConfigSnapshot;
use super::config::SETTINGS_SECTION;
use super::diagnostics;
use super::diagnostics::DiagnosticSource;
use super::documents::to_hover_text;
use super::documents::to_lsp_range;
use super::documents::AssetOrDocument;
use super::documents::Documents;
use super::documents::LanguageId;
use super::lsp_custom;
use super::parent_process_checker;
use super::performance::Performance;
use super::refactor;
use super::registries;
use super::text;
use super::tsc;
use super::tsc::AssetDocument;
use super::tsc::Assets;
use super::tsc::TsServer;
use super::urls;
use crate::config_file::ConfigFile;
use crate::config_file::FmtConfig;
use crate::config_file::LintConfig;
use crate::config_file::TsConfig;
use crate::deno_dir;
use crate::file_fetcher::get_source_from_data_url;
use crate::fs_util;
use crate::logger;
use crate::lsp::logging::lsp_log;
use crate::tools::fmt::format_file;
use crate::tools::fmt::format_parsed_source;
pub const REGISTRIES_PATH: &str = "registries";
const CACHE_PATH: &str = "deps";
#[derive(Debug, Clone)]
pub struct LanguageServer(Arc<tokio::sync::Mutex<Inner>>);
#[derive(Debug, Default)]
pub(crate) struct StateSnapshot {
pub assets: Assets,
pub config: ConfigSnapshot,
pub documents: Documents,
pub maybe_lint_config: Option<LintConfig>,
pub maybe_fmt_config: Option<FmtConfig>,
pub maybe_config_uri: Option<ModuleSpecifier>,
pub module_registries: registries::ModuleRegistry,
pub performance: Performance,
pub url_map: urls::LspUrlMap,
}
#[derive(Debug)]
pub(crate) struct Inner {
/// Cached versions of "fixed" assets that can either be inlined in Rust or
/// are part of the TypeScript snapshot and have to be fetched out.
assets: Assets,
/// The LSP client that this LSP server is connected to.
pub(crate) client: Client,
/// Configuration information.
pub(crate) config: Config,
diagnostics_server: diagnostics::DiagnosticsServer,
/// The collection of documents that the server is currently handling, either
/// on disk or "open" within the client.
documents: Documents,
/// Handles module registries, which allow discovery of modules
module_registries: registries::ModuleRegistry,
/// The path to the module registries cache
module_registries_location: PathBuf,
/// An optional path to the DENO_DIR which has been specified in the client
/// options.
maybe_cache_path: Option<PathBuf>,
/// A lazily created "server" for handling cache requests.
maybe_cache_server: Option<CacheServer>,
/// An optional configuration file which has been specified in the client
/// options.
maybe_config_file: Option<ConfigFile>,
/// An optional configuration for linter which has been taken from specified config file.
maybe_lint_config: Option<LintConfig>,
/// An optional configuration for formatter which has been taken from specified config file.
maybe_fmt_config: Option<FmtConfig>,
/// An optional URL which provides the location of a TypeScript configuration
/// file which will be used by the Deno LSP.
maybe_config_uri: Option<Url>,
/// An optional import map which is used to resolve modules.
pub(crate) maybe_import_map: Option<Arc<ImportMap>>,
/// The URL for the import map which is used to determine relative imports.
maybe_import_map_uri: Option<Url>,
/// A collection of measurements which instrument that performance of the LSP.
performance: Performance,
/// A memoized version of fixable diagnostic codes retrieved from TypeScript.
ts_fixable_diagnostics: Vec<String>,
/// An abstraction that handles interactions with TypeScript.
pub(crate) ts_server: Arc<TsServer>,
/// A map of specifiers and URLs used to translate over the LSP.
pub(crate) url_map: urls::LspUrlMap,
}
impl LanguageServer {
pub fn new(client: Client) -> Self {
Self(Arc::new(tokio::sync::Mutex::new(Inner::new(client))))
}
}
impl Inner {
fn new(client: Client) -> Self {
let maybe_custom_root = env::var("DENO_DIR").map(String::into).ok();
let dir = deno_dir::DenoDir::new(maybe_custom_root)
.expect("could not access DENO_DIR");
let module_registries_location = dir.root.join(REGISTRIES_PATH);
let module_registries =
registries::ModuleRegistry::new(&module_registries_location);
let location = dir.root.join(CACHE_PATH);
let documents = Documents::new(&location);
let ts_server = Arc::new(TsServer::new());
let config = Config::new(client.clone());
Self {
assets: Default::default(),
client,
config,
diagnostics_server: Default::default(),
documents,
maybe_cache_path: None,
maybe_lint_config: None,
maybe_fmt_config: None,
maybe_cache_server: None,
maybe_config_file: None,
maybe_config_uri: None,
maybe_import_map: None,
maybe_import_map_uri: None,
module_registries,
module_registries_location,
performance: Default::default(),
ts_fixable_diagnostics: Default::default(),
ts_server,
url_map: Default::default(),
}
}
/// Searches assets and open documents which might be performed asynchronously,
/// hydrating in memory caches for subsequent requests.
pub(crate) async fn get_asset_or_document(
&mut self,
specifier: &ModuleSpecifier,
) -> LspResult<AssetOrDocument> {
self
.get_maybe_asset_or_document(specifier)
.await?
.map_or_else(
|| {
Err(LspError::invalid_params(format!(
"Unable to find asset or document for: {}",
specifier
)))
},
Ok,
)
}
/// Searches assets and open documents which might be performed asynchronously,
/// hydrating in memory caches for subsequent requests.
pub(crate) async fn get_maybe_asset_or_document(
&mut self,
specifier: &ModuleSpecifier,
) -> LspResult<Option<AssetOrDocument>> {
let mark = self.performance.mark(
"get_maybe_asset_or_document",
Some(json!({ "specifier": specifier })),
);
let result = if specifier.scheme() == "asset" {
self.get_asset(specifier).await?.map(AssetOrDocument::Asset)
} else {
self.documents.get(specifier).map(AssetOrDocument::Document)
};
self.performance.measure(mark);
Ok(result)
}
/// Only searches already cached assets and documents. If
/// the asset or document cannot be found an error is returned.
pub(crate) fn get_cached_asset_or_document(
&self,
specifier: &ModuleSpecifier,
) -> LspResult<AssetOrDocument> {
self
.get_maybe_cached_asset_or_document(specifier)
.map_or_else(
|| {
Err(LspError::invalid_params(format!(
"An unexpected specifier ({}) was provided.",
specifier
)))
},
Ok,
)
}
/// Only searches already cached assets and documents. If
/// the asset or document cannot be found, `None` is returned.
pub(crate) fn get_maybe_cached_asset_or_document(
&self,
specifier: &ModuleSpecifier,
) -> Option<AssetOrDocument> {
if specifier.scheme() == "asset" {
self
.assets
.get(specifier)
.map(|maybe_asset| {
maybe_asset
.as_ref()
.map(|asset| AssetOrDocument::Asset(asset.clone()))
})
.flatten()
} else {
self.documents.get(specifier).map(AssetOrDocument::Document)
}
}
pub(crate) async fn get_navigation_tree(
&mut self,
specifier: &ModuleSpecifier,
) -> Result<Arc<tsc::NavigationTree>, AnyError> {
let mark = self.performance.mark(
"get_navigation_tree",
Some(json!({ "specifier": specifier })),
);
let asset_or_doc = self.get_cached_asset_or_document(specifier)?;
let navigation_tree =
if let Some(navigation_tree) = asset_or_doc.maybe_navigation_tree() {
navigation_tree
} else {
let navigation_tree: tsc::NavigationTree = self
.ts_server
.request(
self.snapshot()?,
tsc::RequestMethod::GetNavigationTree(specifier.clone()),
)
.await?;
let navigation_tree = Arc::new(navigation_tree);
match asset_or_doc {
AssetOrDocument::Asset(_) => self
.assets
.cache_navigation_tree(specifier, navigation_tree.clone())?,
AssetOrDocument::Document(doc) => {
self.documents.try_cache_navigation_tree(
specifier,
&doc.script_version(),
navigation_tree.clone(),
)?
}
}
navigation_tree
};
self.performance.measure(mark);
Ok(navigation_tree)
}
/// Returns a tuple with parsed `ConfigFile` and `Url` pointing to that file.
/// If there's no config file specified in settings returns `None`.
fn get_config_file_and_url(
&self,
) -> Result<Option<(ConfigFile, Url)>, AnyError> {
let workspace_settings = self.config.get_workspace_settings();
let maybe_root_uri = self.config.root_uri.clone();
let maybe_config = workspace_settings.config;
if let Some(config_str) = &maybe_config {
if !config_str.is_empty() {
lsp_log!("Setting TypeScript configuration from: \"{}\"", config_str);
let config_url = if let Ok(url) = Url::from_file_path(config_str) {
Ok(url)
} else if let Some(root_uri) = maybe_root_uri {
root_uri.join(config_str).map_err(|_| {
anyhow!("Bad file path for configuration file: \"{}\"", config_str)
})
} else {
Err(anyhow!(
"The path to the configuration file (\"{}\") is not resolvable.",
config_str
))
}?;
lsp_log!(" Resolved configuration file: \"{}\"", config_url);
let config_file = ConfigFile::from_specifier(&config_url)?;
return Ok(Some((config_file, config_url)));
}
}
Ok(None)
}
fn is_diagnosable(&self, specifier: &ModuleSpecifier) -> bool {
if specifier.scheme() == "asset" {
matches!(
MediaType::from(specifier),
MediaType::JavaScript
| MediaType::Jsx
| MediaType::Mjs
| MediaType::Cjs
| MediaType::TypeScript
| MediaType::Tsx
| MediaType::Mts
| MediaType::Cts
| MediaType::Dts
| MediaType::Dmts
| MediaType::Dcts
)
} else {
self
.documents
.get(specifier)
.map(|d| d.is_diagnosable())
.unwrap_or(false)
}
}
fn merge_user_tsconfig(
&mut self,
tsconfig: &mut TsConfig,
) -> Result<(), AnyError> {
if let Some(config_file) = self.maybe_config_file.as_ref() {
let (value, maybe_ignored_options) = config_file.to_compiler_options()?;
tsconfig.merge(&value);
if let Some(ignored_options) = maybe_ignored_options {
// TODO(@kitsonk) turn these into diagnostics that can be sent to the
// client
warn!("{}", ignored_options);
}
}
Ok(())
}
pub(crate) fn snapshot(&self) -> LspResult<Arc<StateSnapshot>> {
Ok(Arc::new(StateSnapshot {
assets: self.assets.clone(),
config: self.config.snapshot().map_err(|err| {
error!("{}", err);
LspError::internal_error()
})?,
documents: self.documents.clone(),
maybe_lint_config: self.maybe_lint_config.clone(),
maybe_fmt_config: self.maybe_fmt_config.clone(),
maybe_config_uri: self.maybe_config_uri.clone(),
module_registries: self.module_registries.clone(),
performance: self.performance.clone(),
url_map: self.url_map.clone(),
}))
}
pub fn update_cache(&mut self) -> Result<(), AnyError> {
let mark = self.performance.mark("update_cache", None::<()>);
self.performance.measure(mark);
self.maybe_cache_server = None;
let (maybe_cache, maybe_root_uri) = {
let config = &self.config;
(
config.get_workspace_settings().cache,
config.root_uri.clone(),
)
};
let maybe_cache_path = if let Some(cache_str) = &maybe_cache {
lsp_log!("Setting cache path from: \"{}\"", cache_str);
let cache_url = if let Ok(url) = Url::from_file_path(cache_str) {
Ok(url)
} else if let Some(root_uri) = &maybe_root_uri {
let root_path = fs_util::specifier_to_file_path(root_uri)?;
let cache_path = root_path.join(cache_str);
Url::from_file_path(cache_path).map_err(|_| {
anyhow!("Bad file path for import path: {:?}", cache_str)
})
} else {
Err(anyhow!(
"The path to the cache path (\"{}\") is not resolvable.",
cache_str
))
}?;
let cache_path = fs_util::specifier_to_file_path(&cache_url)?;
lsp_log!(
" Resolved cache path: \"{}\"",
cache_path.to_string_lossy()
);
Some(cache_path)
} else {
None
};
if self.maybe_cache_path != maybe_cache_path {
let maybe_custom_root = maybe_cache_path
.clone()
.or_else(|| env::var("DENO_DIR").map(String::into).ok());
let dir = deno_dir::DenoDir::new(maybe_custom_root)
.expect("could not access DENO_DIR");
let module_registries_location = dir.root.join(REGISTRIES_PATH);
self.module_registries =
registries::ModuleRegistry::new(&module_registries_location);
self.module_registries_location = module_registries_location;
self.documents.set_location(dir.root.join(CACHE_PATH));
self.maybe_cache_path = maybe_cache_path;
}
Ok(())
}
pub async fn update_import_map(&mut self) -> Result<(), AnyError> {
let mark = self.performance.mark("update_import_map", None::<()>);
self.maybe_cache_server = None;
let (maybe_import_map, maybe_root_uri) = {
let config = &self.config;
(
config.get_workspace_settings().import_map,
config.root_uri.clone(),
)
};
if let Some(import_map_str) = &maybe_import_map {
lsp_log!("Setting import map from: \"{}\"", import_map_str);
let import_map_url = if let Ok(url) = Url::from_file_path(import_map_str)
{
Ok(url)
} else if import_map_str.starts_with("data:") {
Url::parse(import_map_str).map_err(|_| {
anyhow!("Bad data url for import map: {:?}", import_map_str)
})
} else if let Some(root_uri) = &maybe_root_uri {
let root_path = fs_util::specifier_to_file_path(root_uri)?;
let import_map_path = root_path.join(import_map_str);
Url::from_file_path(import_map_path).map_err(|_| {
anyhow!("Bad file path for import map: {:?}", import_map_str)
})
} else {
Err(anyhow!(
"The path to the import map (\"{}\") is not resolvable.",
import_map_str
))
}?;
let import_map_json = if import_map_url.scheme() == "data" {
get_source_from_data_url(&import_map_url)?.0
} else {
let import_map_path = fs_util::specifier_to_file_path(&import_map_url)?;
lsp_log!(
" Resolved import map: \"{}\"",
import_map_path.to_string_lossy()
);
fs::read_to_string(import_map_path).await.map_err(|err| {
anyhow!(
"Failed to load the import map at: {}. [{}]",
import_map_url,
err
)
})?
};
let import_map = Arc::new(ImportMap::from_json(
&import_map_url.to_string(),
&import_map_json,
)?);
self.maybe_import_map_uri = Some(import_map_url);
self.maybe_import_map = Some(import_map);
} else {
self.maybe_import_map = None;
}
self.performance.measure(mark);
Ok(())
}
pub fn update_debug_flag(&self) {
let internal_debug = self.config.get_workspace_settings().internal_debug;
super::logging::set_lsp_debug_flag(internal_debug)
}
async fn update_registries(&mut self) -> Result<(), AnyError> {
let mark = self.performance.mark("update_registries", None::<()>);
for (registry, enabled) in self
.config
.get_workspace_settings()
.suggest
.imports
.hosts
.iter()
{
if *enabled {
lsp_log!("Enabling import suggestions for: {}", registry);
self.module_registries.enable(registry).await?;
} else {
self.module_registries.disable(registry).await?;
}
}
self.performance.measure(mark);
Ok(())
}
fn update_config_file(&mut self) -> Result<(), AnyError> {
self.maybe_config_file = None;
self.maybe_config_uri = None;
self.maybe_fmt_config = None;
self.maybe_lint_config = None;
let maybe_file_and_url = self.get_config_file_and_url()?;
if let Some((config_file, config_url)) = maybe_file_and_url {
let lint_config = config_file
.to_lint_config()
.map_err(|err| {
anyhow!("Unable to update lint configuration: {:?}", err)
})?
.unwrap_or_default();
let fmt_config = config_file
.to_fmt_config()
.map_err(|err| {
anyhow!("Unable to update formatter configuration: {:?}", err)
})?
.unwrap_or_default();
self.maybe_config_file = Some(config_file);
self.maybe_config_uri = Some(config_url);
self.maybe_lint_config = Some(lint_config);
self.maybe_fmt_config = Some(fmt_config);
}
Ok(())
}
async fn update_tsconfig(&mut self) -> Result<(), AnyError> {
let mark = self.performance.mark("update_tsconfig", None::<()>);
let mut tsconfig = TsConfig::new(json!({
"allowJs": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["deno.ns", "deno.window"],
"module": "esnext",
"noEmit": true,
"resolveJsonModule": true,
"strict": true,
"target": "esnext",
"useDefineForClassFields": true,
// TODO(@kitsonk) remove for Deno 1.15
"useUnknownInCatchVariables": false,
}));
let config = &self.config;
let workspace_settings = config.get_workspace_settings();
if workspace_settings.unstable {
let unstable_libs = json!({
"lib": ["deno.ns", "deno.window", "deno.unstable"]
});
tsconfig.merge(&unstable_libs);
}
if let Err(err) = self.merge_user_tsconfig(&mut tsconfig) {
self.client.show_message(MessageType::WARNING, err).await;
}
let _ok: bool = self
.ts_server
.request(self.snapshot()?, tsc::RequestMethod::Configure(tsconfig))
.await?;
self.performance.measure(mark);
Ok(())
}
async fn get_asset(
&mut self,
specifier: &ModuleSpecifier,
) -> LspResult<Option<AssetDocument>> {
if let Some(maybe_asset) = self.assets.get(specifier) {
Ok(maybe_asset.clone())
} else {
let maybe_asset =
tsc::get_asset(specifier, &self.ts_server, self.snapshot()?)
.await
.map_err(|err| {
error!("Error getting asset {}: {}", specifier, err);
LspError::internal_error()
})?;
self.assets.insert(specifier.clone(), maybe_asset.clone());
Ok(maybe_asset)
}
}
}
// lspower::LanguageServer methods. This file's LanguageServer delegates to us.
impl Inner {
async fn initialize(
&mut self,
params: InitializeParams,
) -> LspResult<InitializeResult> {
lsp_log!("Starting Deno language server...");
let mark = self.performance.mark("initialize", Some(¶ms));
// exit this process when the parent is lost
if let Some(parent_pid) = params.process_id {
parent_process_checker::start(parent_pid)
}
let capabilities = capabilities::server_capabilities(¶ms.capabilities);
let version = format!(
"{} ({}, {})",
crate::version::deno(),
env!("PROFILE"),
env!("TARGET")
);
lsp_log!(" version: {}", version);
if let Ok(path) = std::env::current_exe() {
lsp_log!(" executable: {}", path.to_string_lossy());
}
let server_info = ServerInfo {
name: "deno-language-server".to_string(),
version: Some(version),
};
if let Some(client_info) = params.client_info {
lsp_log!(
"Connected to \"{}\" {}",
client_info.name,
client_info.version.unwrap_or_default(),
);
}
{
let config = &mut self.config;
// sometimes this root uri may not have a trailing slash, so force it to
config.root_uri = params
.root_uri
.map(|s| self.url_map.normalize_url(&s))
.map(fs_util::ensure_directory_specifier);
if let Some(value) = params.initialization_options {
config.set_workspace_settings(value).map_err(|err| {
error!("Cannot set workspace settings: {}", err);
LspError::internal_error()
})?;
}
config.update_capabilities(¶ms.capabilities);
}
self.update_debug_flag();
// Check to see if we need to change the cache path
if let Err(err) = self.update_cache() {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.update_config_file() {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.update_tsconfig().await {
self.client.show_message(MessageType::WARNING, err).await;
}
if capabilities.code_action_provider.is_some() {
let fixable_diagnostics: Vec<String> = self
.ts_server
.request(self.snapshot()?, tsc::RequestMethod::GetSupportedCodeFixes)
.await
.map_err(|err| {
error!("Unable to get fixable diagnostics: {}", err);
LspError::internal_error()
})?;
self.ts_fixable_diagnostics = fixable_diagnostics;
}
// Check to see if we need to setup the import map
if let Err(err) = self.update_import_map().await {
self.client.show_message(MessageType::WARNING, err).await;
}
// Check to see if we need to setup any module registries
if let Err(err) = self.update_registries().await {
self.client.show_message(MessageType::WARNING, err).await;
}
self.documents.update_config(
self.maybe_import_map.clone(),
self.maybe_config_file.as_ref(),
);
self.performance.measure(mark);
Ok(InitializeResult {
capabilities,
server_info: Some(server_info),
})
}
async fn initialized(&mut self, _: InitializedParams) {
if self
.config
.client_capabilities
.workspace_did_change_watched_files
{
// we are going to watch all the JSON files in the workspace, and the
// notification handler will pick up any of the changes of those files we
// are interested in.
let watch_registration_options =
DidChangeWatchedFilesRegistrationOptions {
watchers: vec![FileSystemWatcher {
glob_pattern: "**/*.json".to_string(),
kind: Some(WatchKind::Change),
}],
};
let registration = Registration {
id: "workspace/didChangeWatchedFiles".to_string(),
method: "workspace/didChangeWatchedFiles".to_string(),
register_options: Some(
serde_json::to_value(watch_registration_options).unwrap(),
),
};
if let Err(err) =
self.client.register_capability(vec![registration]).await
{
warn!("Client errored on capabilities.\n{}", err);
}
}
lsp_log!("Server ready.");
}
async fn shutdown(&self) -> LspResult<()> {
Ok(())
}
async fn did_open(&mut self, params: DidOpenTextDocumentParams) {
let mark = self.performance.mark("did_open", Some(¶ms));
let specifier = self.url_map.normalize_url(¶ms.text_document.uri);
if let Err(err) = self
.config
.update_specifier_settings(&specifier, ¶ms.text_document.uri)
.await
{
error!("Error updating specifier settings: {}", err);
}
if params.text_document.uri.scheme() == "deno" {
// we can ignore virtual text documents opening, as they don't need to
// be tracked in memory, as they are static assets that won't change
// already managed by the language service
return;
}
let language_id =
params
.text_document
.language_id
.parse()
.unwrap_or_else(|err| {
error!("{}", err);
LanguageId::Unknown
});
if language_id == LanguageId::Unknown {
warn!(
"Unsupported language id \"{}\" received for document \"{}\".",
params.text_document.language_id, params.text_document.uri
);
}
let content = Arc::new(params.text_document.text);
let document = self.documents.open(
specifier.clone(),
params.text_document.version,
params.text_document.language_id.parse().unwrap(),
content,
);
if document.is_diagnosable() {
self
.diagnostics_server
.invalidate(self.documents.dependents(&specifier))
.await;
if let Err(err) = self.diagnostics_server.update() {
error!("{}", err);
}
}
self.performance.measure(mark);
}
async fn did_change(&mut self, params: DidChangeTextDocumentParams) {
let mark = self.performance.mark("did_change", Some(¶ms));
let specifier = self.url_map.normalize_url(¶ms.text_document.uri);
match self.documents.change(
&specifier,
params.text_document.version,
params.content_changes,
) {
Ok(document) => {
if document.is_diagnosable() {
self
.diagnostics_server
.invalidate(self.documents.dependents(&specifier))
.await;
if let Err(err) = self.diagnostics_server.update() {
error!("{}", err);
}
}
}
Err(err) => error!("{}", err),
}
self.performance.measure(mark);
}
async fn did_close(&mut self, params: DidCloseTextDocumentParams) {
let mark = self.performance.mark("did_close", Some(¶ms));
if params.text_document.uri.scheme() == "deno" {
// we can ignore virtual text documents closing, as they don't need to
// be tracked in memory, as they are static assets that won't change
// already managed by the language service
return;
}
let specifier = self.url_map.normalize_url(¶ms.text_document.uri);
if let Err(err) = self.documents.close(&specifier) {
error!("{}", err);
}
if self.is_diagnosable(&specifier) {
let mut specifiers = self.documents.dependents(&specifier);
specifiers.push(specifier.clone());
self.diagnostics_server.invalidate(specifiers).await;
if let Err(err) = self.diagnostics_server.update() {
error!("{}", err);
}
}
self.performance.measure(mark);
}
async fn did_change_configuration(
&mut self,
params: DidChangeConfigurationParams,
) {
let mark = self
.performance
.mark("did_change_configuration", Some(¶ms));
let maybe_config =
if self.config.client_capabilities.workspace_configuration {
let config_response = self
.client
.configuration(vec![ConfigurationItem {
scope_uri: None,
section: Some(SETTINGS_SECTION.to_string()),
}])
.await;
if let Err(err) = self.config.update_all_settings().await {
error!("Cannot request updating all settings: {}", err);
}
match config_response {
Ok(value_vec) => value_vec.get(0).cloned(),
Err(err) => {
error!("Error getting workspace configuration: {}", err);
None
}
}
} else {
params
.settings
.as_object()
.map(|settings| settings.get(SETTINGS_SECTION))
.flatten()
.cloned()
};
if let Some(value) = maybe_config {
if let Err(err) = self.config.set_workspace_settings(value) {
error!("failed to update settings: {}", err);
}
}
self.update_debug_flag();
if let Err(err) = self.update_cache() {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.update_import_map().await {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.update_registries().await {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.update_config_file() {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.update_tsconfig().await {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.diagnostics_server.update() {
error!("{}", err);
}
self.documents.update_config(
self.maybe_import_map.clone(),
self.maybe_config_file.as_ref(),
);
self.performance.measure(mark);
}
async fn did_change_watched_files(
&mut self,
params: DidChangeWatchedFilesParams,
) {
let mark = self
.performance
.mark("did_change_watched_files", Some(¶ms));
let mut touched = false;
let changes: Vec<Url> = params
.changes
.iter()
.map(|f| self.url_map.normalize_url(&f.uri))
.collect();
// if the current import map has changed, we need to reload it
if let Some(import_map_uri) = &self.maybe_import_map_uri {
if changes.iter().any(|uri| import_map_uri == uri) {
if let Err(err) = self.update_import_map().await {
self.client.show_message(MessageType::WARNING, err).await;
}
touched = true;
}
}
// if the current tsconfig has changed, we need to reload it
if let Some(config_uri) = &self.maybe_config_uri {
if changes.iter().any(|uri| config_uri == uri) {
if let Err(err) = self.update_config_file() {
self.client.show_message(MessageType::WARNING, err).await;
}
if let Err(err) = self.update_tsconfig().await {
self.client.show_message(MessageType::WARNING, err).await;
}
touched = true;
}
}
if touched {
self.documents.update_config(
self.maybe_import_map.clone(),
self.maybe_config_file.as_ref(),
);
self.diagnostics_server.invalidate_all().await;
if let Err(err) = self.diagnostics_server.update() {
error!("Cannot update diagnostics: {}", err);
}
}
self.performance.measure(mark);
}
async fn document_symbol(
&mut self,
params: DocumentSymbolParams,
) -> LspResult<Option<DocumentSymbolResponse>> {
let specifier = self.url_map.normalize_url(¶ms.text_document.uri);
if !self.is_diagnosable(&specifier)
|| !self.config.specifier_enabled(&specifier)
{
return Ok(None);
}
let mark = self.performance.mark("document_symbol", Some(¶ms));
let asset_or_document = self.get_cached_asset_or_document(&specifier)?;
let line_index = asset_or_document.line_index();
let navigation_tree =
self.get_navigation_tree(&specifier).await.map_err(|err| {
error!(
"Error getting document symbols for \"{}\": {}",
specifier, err
);
LspError::internal_error()
})?;
let response = if let Some(child_items) = &navigation_tree.child_items {
let mut document_symbols = Vec::<DocumentSymbol>::new();
for item in child_items {
item
.collect_document_symbols(line_index.clone(), &mut document_symbols);
}
Some(DocumentSymbolResponse::Nested(document_symbols))
} else {