forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsc.rs
6382 lines (6019 loc) · 185 KB
/
tsc.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-2024 the Deno authors. All rights reserved. MIT license.
use super::analysis::CodeActionData;
use super::code_lens;
use super::config;
use super::config::LspTsConfig;
use super::documents::AssetOrDocument;
use super::documents::Document;
use super::documents::DocumentsFilter;
use super::language_server;
use super::language_server::StateSnapshot;
use super::performance::Performance;
use super::performance::PerformanceMark;
use super::refactor::RefactorCodeActionData;
use super::refactor::ALL_KNOWN_REFACTOR_ACTION_KINDS;
use super::refactor::EXTRACT_CONSTANT;
use super::refactor::EXTRACT_INTERFACE;
use super::refactor::EXTRACT_TYPE;
use super::semantic_tokens;
use super::semantic_tokens::SemanticTokensBuilder;
use super::text::LineIndex;
use super::urls::LspClientUrl;
use super::urls::INVALID_SPECIFIER;
use crate::args::jsr_url;
use crate::args::FmtOptionsConfig;
use crate::lsp::logging::lsp_warn;
use crate::tsc;
use crate::tsc::ResolveArgs;
use crate::tsc::MISSING_DEPENDENCY_SPECIFIER;
use crate::util::path::relative_specifier;
use crate::util::path::to_percent_decoded_str;
use crate::util::result::InfallibleResultExt;
use crate::util::v8::convert;
use deno_core::convert::Smi;
use deno_core::convert::ToV8;
use deno_core::error::StdAnyError;
use deno_core::futures::stream::FuturesOrdered;
use deno_core::futures::StreamExt;
use deno_runtime::fs_util::specifier_to_file_path;
use dashmap::DashMap;
use deno_ast::MediaType;
use deno_core::anyhow::anyhow;
use deno_core::anyhow::Context as _;
use deno_core::error::AnyError;
use deno_core::futures::FutureExt;
use deno_core::op2;
use deno_core::parking_lot::Mutex;
use deno_core::resolve_url;
use deno_core::serde::de;
use deno_core::serde::Deserialize;
use deno_core::serde::Serialize;
use deno_core::serde_json;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::serde_v8;
use deno_core::v8;
use deno_core::JsRuntime;
use deno_core::ModuleSpecifier;
use deno_core::OpState;
use deno_core::PollEventLoopOptions;
use deno_core::RuntimeOptions;
use deno_runtime::inspector_server::InspectorServer;
use deno_runtime::tokio_util::create_basic_runtime;
use indexmap::IndexMap;
use indexmap::IndexSet;
use lazy_regex::lazy_regex;
use log::error;
use once_cell::sync::Lazy;
use regex::Captures;
use regex::Regex;
use serde_repr::Deserialize_repr;
use serde_repr::Serialize_repr;
use std::cell::RefCell;
use std::cmp;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::ops::Range;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
use text_size::TextRange;
use text_size::TextSize;
use tokio::sync::mpsc;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use tower_lsp::jsonrpc::Error as LspError;
use tower_lsp::jsonrpc::Result as LspResult;
use tower_lsp::lsp_types as lsp;
static BRACKET_ACCESSOR_RE: Lazy<Regex> =
lazy_regex!(r#"^\[['"](.+)[\['"]\]$"#);
static CAPTION_RE: Lazy<Regex> =
lazy_regex!(r"<caption>(.*?)</caption>\s*\r?\n((?:\s|\S)*)");
static CODEBLOCK_RE: Lazy<Regex> = lazy_regex!(r"^\s*[~`]{3}"m);
static EMAIL_MATCH_RE: Lazy<Regex> = lazy_regex!(r"(.+)\s<([-.\w]+@[-.\w]+)>");
static HTTP_RE: Lazy<Regex> = lazy_regex!(r#"(?i)^https?:"#);
static JSDOC_LINKS_RE: Lazy<Regex> = lazy_regex!(
r"(?i)\{@(link|linkplain|linkcode) (https?://[^ |}]+?)(?:[| ]([^{}\n]+?))?\}"
);
static PART_KIND_MODIFIER_RE: Lazy<Regex> = lazy_regex!(r",|\s+");
static PART_RE: Lazy<Regex> = lazy_regex!(r"^(\S+)\s*-?\s*");
static SCOPE_RE: Lazy<Regex> = lazy_regex!(r"scope_(\d)");
const FILE_EXTENSION_KIND_MODIFIERS: &[&str] =
&[".d.ts", ".ts", ".tsx", ".js", ".jsx", ".json"];
type Request = (
TscRequest,
Option<ModuleSpecifier>,
Arc<StateSnapshot>,
oneshot::Sender<Result<String, AnyError>>,
CancellationToken,
Option<PendingChange>,
);
#[derive(Debug, Clone, Copy, Serialize_repr)]
#[repr(u8)]
pub enum IndentStyle {
#[allow(dead_code)]
None = 0,
Block = 1,
#[allow(dead_code)]
Smart = 2,
}
/// Relevant subset of https://github.com/denoland/deno/blob/v1.37.1/cli/tsc/dts/typescript.d.ts#L6658.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FormatCodeSettings {
base_indent_size: Option<u8>,
indent_size: Option<u8>,
tab_size: Option<u8>,
new_line_character: Option<String>,
convert_tabs_to_spaces: Option<bool>,
indent_style: Option<IndentStyle>,
trim_trailing_whitespace: Option<bool>,
insert_space_after_comma_delimiter: Option<bool>,
insert_space_after_semicolon_in_for_statements: Option<bool>,
insert_space_before_and_after_binary_operators: Option<bool>,
insert_space_after_constructor: Option<bool>,
insert_space_after_keywords_in_control_flow_statements: Option<bool>,
insert_space_after_function_keyword_for_anonymous_functions: Option<bool>,
insert_space_after_opening_and_before_closing_nonempty_parenthesis:
Option<bool>,
insert_space_after_opening_and_before_closing_nonempty_brackets: Option<bool>,
insert_space_after_opening_and_before_closing_nonempty_braces: Option<bool>,
insert_space_after_opening_and_before_closing_template_string_braces:
Option<bool>,
insert_space_after_opening_and_before_closing_jsx_expression_braces:
Option<bool>,
insert_space_after_type_assertion: Option<bool>,
insert_space_before_function_parenthesis: Option<bool>,
place_open_brace_on_new_line_for_functions: Option<bool>,
place_open_brace_on_new_line_for_control_blocks: Option<bool>,
insert_space_before_type_annotation: Option<bool>,
indent_multi_line_object_literal_beginning_on_blank_line: Option<bool>,
semicolons: Option<SemicolonPreference>,
indent_switch_case: Option<bool>,
}
impl From<&FmtOptionsConfig> for FormatCodeSettings {
fn from(config: &FmtOptionsConfig) -> Self {
FormatCodeSettings {
base_indent_size: Some(0),
indent_size: Some(config.indent_width.unwrap_or(2)),
tab_size: Some(config.indent_width.unwrap_or(2)),
new_line_character: Some("\n".to_string()),
convert_tabs_to_spaces: Some(!config.use_tabs.unwrap_or(false)),
indent_style: Some(IndentStyle::Block),
trim_trailing_whitespace: Some(false),
insert_space_after_comma_delimiter: Some(true),
insert_space_after_semicolon_in_for_statements: Some(true),
insert_space_before_and_after_binary_operators: Some(true),
insert_space_after_constructor: Some(false),
insert_space_after_keywords_in_control_flow_statements: Some(true),
insert_space_after_function_keyword_for_anonymous_functions: Some(true),
insert_space_after_opening_and_before_closing_nonempty_parenthesis: Some(
false,
),
insert_space_after_opening_and_before_closing_nonempty_brackets: Some(
false,
),
insert_space_after_opening_and_before_closing_nonempty_braces: Some(true),
insert_space_after_opening_and_before_closing_template_string_braces:
Some(false),
insert_space_after_opening_and_before_closing_jsx_expression_braces: Some(
false,
),
insert_space_after_type_assertion: Some(false),
insert_space_before_function_parenthesis: Some(false),
place_open_brace_on_new_line_for_functions: Some(false),
place_open_brace_on_new_line_for_control_blocks: Some(false),
insert_space_before_type_annotation: Some(false),
indent_multi_line_object_literal_beginning_on_blank_line: Some(false),
semicolons: match config.semi_colons {
Some(false) => Some(SemicolonPreference::Remove),
_ => Some(SemicolonPreference::Insert),
},
indent_switch_case: Some(true),
}
}
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SemicolonPreference {
Insert,
Remove,
}
fn normalize_diagnostic(
diagnostic: &mut crate::tsc::Diagnostic,
specifier_map: &TscSpecifierMap,
) -> Result<(), AnyError> {
if let Some(file_name) = &mut diagnostic.file_name {
*file_name = specifier_map.normalize(&file_name)?.to_string();
}
for ri in diagnostic.related_information.iter_mut().flatten() {
normalize_diagnostic(ri, specifier_map)?;
}
Ok(())
}
pub struct TsServer {
performance: Arc<Performance>,
sender: mpsc::UnboundedSender<Request>,
receiver: Mutex<Option<mpsc::UnboundedReceiver<Request>>>,
specifier_map: Arc<TscSpecifierMap>,
inspector_server: Mutex<Option<Arc<InspectorServer>>>,
pending_change: Mutex<Option<PendingChange>>,
}
impl std::fmt::Debug for TsServer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TsServer")
.field("performance", &self.performance)
.field("sender", &self.sender)
.field("receiver", &self.receiver)
.field("specifier_map", &self.specifier_map)
.field("inspector_server", &self.inspector_server.lock().is_some())
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(u8)]
pub enum ChangeKind {
Opened = 0,
Modified = 1,
Closed = 2,
}
impl<'a> ToV8<'a> for ChangeKind {
type Error = Infallible;
fn to_v8(
self,
scope: &mut v8::HandleScope<'a>,
) -> Result<v8::Local<'a, v8::Value>, Self::Error> {
Smi(self as u8).to_v8(scope)
}
}
impl Serialize for ChangeKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_i32(*self as i32)
}
}
#[derive(Debug)]
#[cfg_attr(test, derive(Serialize))]
pub struct PendingChange {
pub modified_scripts: Vec<(String, ChangeKind)>,
pub project_version: usize,
pub new_configs_by_scope: Option<BTreeMap<ModuleSpecifier, Arc<LspTsConfig>>>,
}
impl<'a> ToV8<'a> for PendingChange {
type Error = Infallible;
fn to_v8(
self,
scope: &mut v8::HandleScope<'a>,
) -> Result<v8::Local<'a, v8::Value>, Self::Error> {
let modified_scripts = {
let mut modified_scripts_v8 =
Vec::with_capacity(self.modified_scripts.len());
for (specifier, kind) in &self.modified_scripts {
let specifier = v8::String::new(scope, specifier).unwrap().into();
let kind = kind.to_v8(scope).unwrap_infallible();
let pair =
v8::Array::new_with_elements(scope, &[specifier, kind]).into();
modified_scripts_v8.push(pair);
}
v8::Array::new_with_elements(scope, &modified_scripts_v8).into()
};
let project_version =
v8::Integer::new_from_unsigned(scope, self.project_version as u32).into();
let new_configs_by_scope =
if let Some(new_configs_by_scope) = self.new_configs_by_scope {
serde_v8::to_v8(
scope,
new_configs_by_scope.into_iter().collect::<Vec<_>>(),
)
.unwrap_or_else(|err| {
lsp_warn!("Couldn't serialize ts configs: {err}");
v8::null(scope).into()
})
} else {
v8::null(scope).into()
};
Ok(
v8::Array::new_with_elements(
scope,
&[modified_scripts, project_version, new_configs_by_scope],
)
.into(),
)
}
}
impl PendingChange {
fn coalesce(
&mut self,
new_version: usize,
modified_scripts: Vec<(String, ChangeKind)>,
new_configs_by_scope: Option<BTreeMap<ModuleSpecifier, Arc<LspTsConfig>>>,
) {
use ChangeKind::*;
self.project_version = self.project_version.max(new_version);
if let Some(new_configs_by_scope) = new_configs_by_scope {
self.new_configs_by_scope = Some(new_configs_by_scope);
}
for (spec, new) in modified_scripts {
if let Some((_, current)) =
self.modified_scripts.iter_mut().find(|(s, _)| s == &spec)
{
// already a pending change for this specifier,
// coalesce the change kinds
match (*current, new) {
(_, Closed) => {
*current = Closed;
}
(Opened | Closed, Opened) => {
*current = Opened;
}
(Modified, Opened) => {
lsp_warn!("Unexpected change from Modified -> Opened");
*current = Opened;
}
(Opened, Modified) => {
// Opening may change the set of files in the project
*current = Opened;
}
(Closed, Modified) => {
lsp_warn!("Unexpected change from Closed -> Modifed");
// Shouldn't happen, but if it does treat it as closed
// since it's "stronger" than modifying an open doc
*current = Closed;
}
(Modified, Modified) => {
// no change
}
}
} else {
self.modified_scripts.push((spec, new));
}
}
}
}
impl TsServer {
pub fn new(performance: Arc<Performance>) -> Self {
let (tx, request_rx) = mpsc::unbounded_channel::<Request>();
Self {
performance,
sender: tx,
receiver: Mutex::new(Some(request_rx)),
specifier_map: Arc::new(TscSpecifierMap::new()),
inspector_server: Mutex::new(None),
pending_change: Mutex::new(None),
}
}
pub fn start(
&self,
inspector_server_addr: Option<String>,
) -> Result<(), AnyError> {
let maybe_inspector_server = match inspector_server_addr {
Some(addr) => {
let addr: SocketAddr = addr.parse().with_context(|| {
format!("Invalid inspector server address \"{}\"", &addr)
})?;
let server = InspectorServer::new(addr, "deno-lsp-tsc")?;
Some(Arc::new(server))
}
None => None,
};
self
.inspector_server
.lock()
.clone_from(&maybe_inspector_server);
// TODO(bartlomieju): why is the join_handle ignored here? Should we store it
// on the `TsServer` struct.
let receiver = self.receiver.lock().take().unwrap();
let performance = self.performance.clone();
let specifier_map = self.specifier_map.clone();
let _join_handle = thread::spawn(move || {
run_tsc_thread(
receiver,
performance,
specifier_map,
maybe_inspector_server,
)
});
Ok(())
}
pub fn project_changed<'a>(
&self,
snapshot: Arc<StateSnapshot>,
modified_scripts: impl IntoIterator<Item = (&'a ModuleSpecifier, ChangeKind)>,
new_configs_by_scope: Option<BTreeMap<ModuleSpecifier, Arc<LspTsConfig>>>,
) {
let modified_scripts = modified_scripts
.into_iter()
.map(|(spec, change)| (self.specifier_map.denormalize(spec), change))
.collect::<Vec<_>>();
match &mut *self.pending_change.lock() {
Some(pending_change) => {
pending_change.coalesce(
snapshot.project_version,
modified_scripts,
new_configs_by_scope,
);
}
pending => {
let pending_change = PendingChange {
modified_scripts,
project_version: snapshot.project_version,
new_configs_by_scope,
};
*pending = Some(pending_change);
}
}
}
pub async fn get_diagnostics(
&self,
snapshot: Arc<StateSnapshot>,
specifiers: Vec<ModuleSpecifier>,
token: CancellationToken,
) -> Result<IndexMap<String, Vec<crate::tsc::Diagnostic>>, AnyError> {
let mut diagnostics_map = IndexMap::with_capacity(specifiers.len());
let mut specifiers_by_scope = BTreeMap::new();
for specifier in specifiers {
let scope = if snapshot.documents.is_valid_file_referrer(&specifier) {
snapshot
.config
.tree
.scope_for_specifier(&specifier)
.cloned()
} else {
snapshot
.documents
.get(&specifier)
.and_then(|d| d.scope().cloned())
};
let specifiers = specifiers_by_scope.entry(scope).or_insert(vec![]);
specifiers.push(self.specifier_map.denormalize(&specifier));
}
let mut results = FuturesOrdered::new();
for (scope, specifiers) in specifiers_by_scope {
let req =
TscRequest::GetDiagnostics((specifiers, snapshot.project_version));
results.push_back(self.request_with_cancellation::<IndexMap<String, Vec<crate::tsc::Diagnostic>>>(snapshot.clone(), req, scope, token.clone()));
}
while let Some(raw_diagnostics) = results.next().await {
let raw_diagnostics = raw_diagnostics
.inspect_err(|err| {
if !token.is_cancelled() {
lsp_warn!("Error generating TypeScript diagnostics: {err}");
}
})
.unwrap_or_default();
for (mut specifier, mut diagnostics) in raw_diagnostics {
specifier = self.specifier_map.normalize(&specifier)?.to_string();
for diagnostic in &mut diagnostics {
normalize_diagnostic(diagnostic, &self.specifier_map)?;
}
diagnostics_map.insert(specifier, diagnostics);
}
}
Ok(diagnostics_map)
}
pub async fn cleanup_semantic_cache(&self, snapshot: Arc<StateSnapshot>) {
for scope in snapshot
.config
.tree
.data_by_scope()
.keys()
.map(Some)
.chain(std::iter::once(None))
{
let req = TscRequest::CleanupSemanticCache;
self
.request::<()>(snapshot.clone(), req, scope.cloned())
.await
.map_err(|err| {
log::error!("Failed to request to tsserver {}", err);
LspError::invalid_request()
})
.ok();
}
}
pub async fn find_references(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
) -> Result<Option<Vec<ReferencedSymbol>>, AnyError> {
let req = TscRequest::FindReferences((
self.specifier_map.denormalize(&specifier),
position,
));
let mut results = FuturesOrdered::new();
for scope in snapshot
.config
.tree
.data_by_scope()
.keys()
.map(Some)
.chain(std::iter::once(None))
{
results.push_back(self.request::<Option<Vec<ReferencedSymbol>>>(
snapshot.clone(),
req.clone(),
scope.cloned(),
));
}
let mut all_symbols = IndexSet::new();
while let Some(symbols) = results.next().await {
let symbols = symbols
.inspect_err(|err| {
let err = err.to_string();
if !err.contains("Could not find source file") {
lsp_warn!("Unable to get references from TypeScript: {err}");
}
})
.unwrap_or_default();
let Some(mut symbols) = symbols else {
continue;
};
for symbol in &mut symbols {
symbol.normalize(&self.specifier_map)?;
}
all_symbols.extend(symbols);
}
if all_symbols.is_empty() {
return Ok(None);
}
Ok(Some(all_symbols.into_iter().collect()))
}
pub async fn get_navigation_tree(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
scope: Option<ModuleSpecifier>,
) -> Result<NavigationTree, AnyError> {
let req = TscRequest::GetNavigationTree((self
.specifier_map
.denormalize(&specifier),));
self.request(snapshot, req, scope).await
}
pub async fn get_supported_code_fixes(
&self,
snapshot: Arc<StateSnapshot>,
) -> Result<Vec<String>, LspError> {
let req = TscRequest::GetSupportedCodeFixes;
self.request(snapshot, req, None).await.map_err(|err| {
log::error!("Unable to get fixable diagnostics: {}", err);
LspError::internal_error()
})
}
pub async fn get_quick_info(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
scope: Option<ModuleSpecifier>,
) -> Result<Option<QuickInfo>, LspError> {
let req = TscRequest::GetQuickInfoAtPosition((
self.specifier_map.denormalize(&specifier),
position,
));
self.request(snapshot, req, scope).await.map_err(|err| {
log::error!("Unable to get quick info: {}", err);
LspError::internal_error()
})
}
#[allow(clippy::too_many_arguments)]
pub async fn get_code_fixes(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
range: Range<u32>,
codes: Vec<i32>,
format_code_settings: FormatCodeSettings,
preferences: UserPreferences,
scope: Option<ModuleSpecifier>,
) -> Vec<CodeFixAction> {
let req = TscRequest::GetCodeFixesAtPosition(Box::new((
self.specifier_map.denormalize(&specifier),
range.start,
range.end,
codes,
format_code_settings,
preferences,
)));
let result = self
.request::<Vec<CodeFixAction>>(snapshot, req, scope)
.await
.and_then(|mut actions| {
for action in &mut actions {
action.normalize(&self.specifier_map)?;
}
Ok(actions)
});
match result {
Ok(items) => items,
Err(err) => {
// sometimes tsc reports errors when retrieving code actions
// because they don't reflect the current state of the document
// so we will log them to the output, but we won't send an error
// message back to the client.
log::error!("Error getting actions from TypeScript: {}", err);
Vec::new()
}
}
}
#[allow(clippy::too_many_arguments)]
pub async fn get_applicable_refactors(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
range: Range<u32>,
preferences: Option<UserPreferences>,
trigger_kind: Option<lsp::CodeActionTriggerKind>,
only: String,
scope: Option<ModuleSpecifier>,
) -> Result<Vec<ApplicableRefactorInfo>, LspError> {
let trigger_kind = trigger_kind.map(|reason| match reason {
lsp::CodeActionTriggerKind::INVOKED => "invoked",
lsp::CodeActionTriggerKind::AUTOMATIC => "implicit",
_ => unreachable!(),
});
let req = TscRequest::GetApplicableRefactors(Box::new((
self.specifier_map.denormalize(&specifier),
range.into(),
preferences.unwrap_or_default(),
trigger_kind,
only,
)));
self.request(snapshot, req, scope).await.map_err(|err| {
log::error!("Failed to request to tsserver {}", err);
LspError::invalid_request()
})
}
pub async fn get_combined_code_fix(
&self,
snapshot: Arc<StateSnapshot>,
code_action_data: &CodeActionData,
format_code_settings: FormatCodeSettings,
preferences: UserPreferences,
scope: Option<ModuleSpecifier>,
) -> Result<CombinedCodeActions, LspError> {
let req = TscRequest::GetCombinedCodeFix(Box::new((
CombinedCodeFixScope {
r#type: "file",
file_name: self.specifier_map.denormalize(&code_action_data.specifier),
},
code_action_data.fix_id.clone(),
format_code_settings,
preferences,
)));
self
.request::<CombinedCodeActions>(snapshot, req, scope)
.await
.and_then(|mut actions| {
actions.normalize(&self.specifier_map)?;
Ok(actions)
})
.map_err(|err| {
log::error!("Unable to get combined fix from TypeScript: {}", err);
LspError::internal_error()
})
}
#[allow(clippy::too_many_arguments)]
pub async fn get_edits_for_refactor(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
format_code_settings: FormatCodeSettings,
range: Range<u32>,
refactor_name: String,
action_name: String,
preferences: Option<UserPreferences>,
scope: Option<ModuleSpecifier>,
) -> Result<RefactorEditInfo, LspError> {
let req = TscRequest::GetEditsForRefactor(Box::new((
self.specifier_map.denormalize(&specifier),
format_code_settings,
range.into(),
refactor_name,
action_name,
preferences,
)));
self
.request::<RefactorEditInfo>(snapshot, req, scope)
.await
.and_then(|mut info| {
info.normalize(&self.specifier_map)?;
Ok(info)
})
.map_err(|err| {
log::error!("Failed to request to tsserver {}", err);
LspError::invalid_request()
})
}
pub async fn get_edits_for_file_rename(
&self,
snapshot: Arc<StateSnapshot>,
old_specifier: ModuleSpecifier,
new_specifier: ModuleSpecifier,
format_code_settings: FormatCodeSettings,
user_preferences: UserPreferences,
) -> Result<Vec<FileTextChanges>, AnyError> {
let req = TscRequest::GetEditsForFileRename(Box::new((
self.specifier_map.denormalize(&old_specifier),
self.specifier_map.denormalize(&new_specifier),
format_code_settings,
user_preferences,
)));
let mut results = FuturesOrdered::new();
for scope in snapshot
.config
.tree
.data_by_scope()
.keys()
.map(Some)
.chain(std::iter::once(None))
{
results.push_back(self.request::<Vec<FileTextChanges>>(
snapshot.clone(),
req.clone(),
scope.cloned(),
));
}
let mut all_changes = IndexSet::new();
while let Some(changes) = results.next().await {
let mut changes = changes
.inspect_err(|err| {
lsp_warn!(
"Unable to get edits for file rename from TypeScript: {err}"
);
})
.unwrap_or_default();
for changes in &mut changes {
changes.normalize(&self.specifier_map)?;
for text_changes in &mut changes.text_changes {
text_changes.new_text =
to_percent_decoded_str(&text_changes.new_text);
}
}
all_changes.extend(changes);
}
Ok(all_changes.into_iter().collect())
}
pub async fn get_document_highlights(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
files_to_search: Vec<ModuleSpecifier>,
scope: Option<ModuleSpecifier>,
) -> Result<Option<Vec<DocumentHighlights>>, LspError> {
let req = TscRequest::GetDocumentHighlights(Box::new((
self.specifier_map.denormalize(&specifier),
position,
files_to_search
.into_iter()
.map(|s| self.specifier_map.denormalize(&s))
.collect::<Vec<_>>(),
)));
self.request(snapshot, req, scope).await.map_err(|err| {
log::error!("Unable to get document highlights from TypeScript: {}", err);
LspError::internal_error()
})
}
pub async fn get_definition(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
scope: Option<ModuleSpecifier>,
) -> Result<Option<DefinitionInfoAndBoundSpan>, LspError> {
let req = TscRequest::GetDefinitionAndBoundSpan((
self.specifier_map.denormalize(&specifier),
position,
));
self
.request::<Option<DefinitionInfoAndBoundSpan>>(snapshot, req, scope)
.await
.and_then(|mut info| {
if let Some(info) = &mut info {
info.normalize(&self.specifier_map)?;
}
Ok(info)
})
.map_err(|err| {
log::error!("Unable to get definition from TypeScript: {}", err);
LspError::internal_error()
})
}
pub async fn get_type_definition(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
scope: Option<ModuleSpecifier>,
) -> Result<Option<Vec<DefinitionInfo>>, LspError> {
let req = TscRequest::GetTypeDefinitionAtPosition((
self.specifier_map.denormalize(&specifier),
position,
));
self
.request::<Option<Vec<DefinitionInfo>>>(snapshot, req, scope)
.await
.and_then(|mut infos| {
for info in infos.iter_mut().flatten() {
info.normalize(&self.specifier_map)?;
}
Ok(infos)
})
.map_err(|err| {
log::error!("Unable to get type definition from TypeScript: {}", err);
LspError::internal_error()
})
}
pub async fn get_completions(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
options: GetCompletionsAtPositionOptions,
format_code_settings: FormatCodeSettings,
scope: Option<ModuleSpecifier>,
) -> Option<CompletionInfo> {
let req = TscRequest::GetCompletionsAtPosition(Box::new((
self.specifier_map.denormalize(&specifier),
position,
options,
format_code_settings,
)));
match self.request(snapshot, req, scope).await {
Ok(maybe_info) => maybe_info,
Err(err) => {
log::error!("Unable to get completion info from TypeScript: {:#}", err);
None
}
}
}
pub async fn get_completion_details(
&self,
snapshot: Arc<StateSnapshot>,
args: GetCompletionDetailsArgs,
scope: Option<ModuleSpecifier>,
) -> Result<Option<CompletionEntryDetails>, AnyError> {
let req = TscRequest::GetCompletionEntryDetails(Box::new((
self.specifier_map.denormalize(&args.specifier),
args.position,
args.name,
args.format_code_settings.unwrap_or_default(),
args.source,
args.preferences,
args.data,
)));
self
.request::<Option<CompletionEntryDetails>>(snapshot, req, scope)
.await
.and_then(|mut details| {
if let Some(details) = &mut details {
details.normalize(&self.specifier_map)?;
}
Ok(details)
})
}
pub async fn get_implementations(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
) -> Result<Option<Vec<ImplementationLocation>>, AnyError> {
let req = TscRequest::GetImplementationAtPosition((
self.specifier_map.denormalize(&specifier),
position,
));
let mut results = FuturesOrdered::new();
for scope in snapshot
.config
.tree
.data_by_scope()
.keys()
.map(Some)
.chain(std::iter::once(None))
{
results.push_back(self.request::<Option<Vec<ImplementationLocation>>>(
snapshot.clone(),
req.clone(),
scope.cloned(),
));
}
let mut all_locations = IndexSet::new();
while let Some(locations) = results.next().await {
let locations = locations
.inspect_err(|err| {
let err = err.to_string();
if !err.contains("Could not find source file") {
lsp_warn!("Unable to get implementations from TypeScript: {err}");
}
})
.unwrap_or_default();
let Some(mut locations) = locations else {
continue;
};
for location in &mut locations {
location.normalize(&self.specifier_map)?;
}
all_locations.extend(locations);
}
if all_locations.is_empty() {
return Ok(None);
}
Ok(Some(all_locations.into_iter().collect()))
}
pub async fn get_outlining_spans(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
scope: Option<ModuleSpecifier>,
) -> Result<Vec<OutliningSpan>, LspError> {
let req = TscRequest::GetOutliningSpans((self
.specifier_map
.denormalize(&specifier),));
self.request(snapshot, req, scope).await.map_err(|err| {
log::error!("Failed to request to tsserver {}", err);
LspError::invalid_request()
})
}
pub async fn provide_call_hierarchy_incoming_calls(
&self,
snapshot: Arc<StateSnapshot>,
specifier: ModuleSpecifier,
position: u32,
) -> Result<Vec<CallHierarchyIncomingCall>, AnyError> {
let req = TscRequest::ProvideCallHierarchyIncomingCalls((
self.specifier_map.denormalize(&specifier),
position,
));
let mut results = FuturesOrdered::new();
for scope in snapshot
.config
.tree