-
-
Notifications
You must be signed in to change notification settings - Fork 791
/
Copy pathengine.rs
1415 lines (1271 loc) · 53.2 KB
/
engine.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
use crate::{
analyse::name::correct_name_case,
ast::{
ArgNames, CustomType, Definition, ModuleConstant, Pattern, SrcSpan, TypedArg, TypedExpr,
TypedFunction, TypedModule, TypedPattern,
},
build::{type_constructor_from_modules, Located, Module, UnqualifiedImport},
config::PackageConfig,
io::{BeamCompiler, CommandExecutor, FileSystemReader, FileSystemWriter},
language_server::{
compiler::LspProjectCompiler, files::FileSystemProxy, progress::ProgressReporter,
},
line_numbers::LineNumbers,
paths::ProjectPaths,
type_::{
self, error::VariableOrigin, printer::Printer, Deprecation, ModuleInterface, Type,
TypeConstructor, ValueConstructor, ValueConstructorVariant,
},
Error, Result, Warning,
};
use camino::Utf8PathBuf;
use ecow::EcoString;
use itertools::Itertools;
use lsp::CodeAction;
use lsp_types::{
self as lsp, DocumentSymbol, Hover, HoverContents, MarkedString, Position,
PrepareRenameResponse, Range, SignatureHelp, SymbolKind, SymbolTag, TextEdit, Url,
WorkspaceEdit,
};
use std::sync::Arc;
use super::{
code_action::{
code_action_add_missing_patterns, code_action_convert_qualified_constructor_to_unqualified,
code_action_convert_unqualified_constructor_to_qualified, code_action_import_module,
code_action_inexhaustive_let_to_case, AddAnnotations, CodeActionBuilder, ConvertFromUse,
ConvertToFunctionCall, ConvertToPipe, ConvertToUse, ExpandFunctionCapture, ExtractVariable,
FillInMissingLabelledArgs, GenerateDynamicDecoder, GenerateFunction, GenerateJsonEncoder,
InlineVariable, LetAssertToCase, PatternMatchOnValue, RedundantTupleInCaseSubject,
UseLabelShorthandSyntax,
},
completer::Completer,
rename::{rename_local_variable, VariableRenameKind},
signature_help, src_span_to_lsp_range, DownloadDependencies, MakeLocker,
};
#[derive(Debug, PartialEq, Eq)]
pub struct Response<T> {
pub result: Result<T, Error>,
pub warnings: Vec<Warning>,
pub compilation: Compilation,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Compilation {
/// Compilation was attempted and succeeded for these modules.
Yes(Vec<Utf8PathBuf>),
/// Compilation was not attempted for this operation.
No,
}
#[derive(Debug)]
pub struct LanguageServerEngine<IO, Reporter> {
pub(crate) paths: ProjectPaths,
/// A compiler for the project that supports repeat compilation of the root
/// package.
/// In the event the project config changes this will need to be
/// discarded and reloaded to handle any changes to dependencies.
pub(crate) compiler: LspProjectCompiler<FileSystemProxy<IO>>,
modules_compiled_since_last_feedback: Vec<Utf8PathBuf>,
compiled_since_last_feedback: bool,
error: Option<Error>,
// Used to publish progress notifications to the client without waiting for
// the usual request-response loop.
progress_reporter: Reporter,
/// Used to know if to show the "View on HexDocs" link
/// when hovering on an imported value
hex_deps: std::collections::HashSet<EcoString>,
}
impl<'a, IO, Reporter> LanguageServerEngine<IO, Reporter>
where
// IO to be supplied from outside of gleam-core
IO: FileSystemReader
+ FileSystemWriter
+ BeamCompiler
+ CommandExecutor
+ DownloadDependencies
+ MakeLocker
+ Clone,
// IO to be supplied from inside of gleam-core
Reporter: ProgressReporter + Clone + 'a,
{
pub fn new(
config: PackageConfig,
progress_reporter: Reporter,
io: FileSystemProxy<IO>,
paths: ProjectPaths,
) -> Result<Self> {
let locker = io.inner().make_locker(&paths, config.target)?;
// Download dependencies to ensure they are up-to-date for this new
// configuration and new instance of the compiler
progress_reporter.dependency_downloading_started();
let manifest = io.inner().download_dependencies(&paths);
progress_reporter.dependency_downloading_finished();
// NOTE: This must come after the progress reporter has finished!
let manifest = manifest?;
let compiler: LspProjectCompiler<FileSystemProxy<IO>> =
LspProjectCompiler::new(manifest, config, paths.clone(), io.clone(), locker)?;
let hex_deps = compiler
.project_compiler
.packages
.iter()
.flat_map(|(k, v)| match &v.source {
crate::manifest::ManifestPackageSource::Hex { .. } => {
Some(EcoString::from(k.as_str()))
}
_ => None,
})
.collect();
Ok(Self {
modules_compiled_since_last_feedback: vec![],
compiled_since_last_feedback: false,
progress_reporter,
compiler,
paths,
error: None,
hex_deps,
})
}
pub fn compile_please(&mut self) -> Response<()> {
self.respond(Self::compile)
}
/// Compile the project if we are in one. Otherwise do nothing.
fn compile(&mut self) -> Result<(), Error> {
self.compiled_since_last_feedback = true;
self.progress_reporter.compilation_started();
let outcome = self.compiler.compile();
self.progress_reporter.compilation_finished();
let result = outcome
// Register which modules have changed
.map(|modules| self.modules_compiled_since_last_feedback.extend(modules))
// Return the error, if present
.into_result();
self.error = match &result {
Ok(_) => None,
Err(error) => Some(error.clone()),
};
result
}
fn take_warnings(&mut self) -> Vec<Warning> {
self.compiler.take_warnings()
}
// TODO: implement unqualified imported module functions
//
pub fn goto_definition(
&mut self,
params: lsp::GotoDefinitionParams,
) -> Response<Option<lsp::Location>> {
self.respond(|this| {
let params = params.text_document_position_params;
let (line_numbers, node) = match this.node_at_position(¶ms) {
Some(location) => location,
None => return Ok(None),
};
let location = match node
.definition_location(this.compiler.project_compiler.get_importable_modules())
{
Some(location) => location,
None => return Ok(None),
};
let (uri, line_numbers) = match location.module {
None => (params.text_document.uri, &line_numbers),
Some(name) => {
let module = match this.compiler.get_source(name) {
Some(module) => module,
_ => return Ok(None),
};
let url = Url::parse(&format!("file:///{}", &module.path))
.expect("goto definition URL parse");
(url, &module.line_numbers)
}
};
let range = src_span_to_lsp_range(location.span, line_numbers);
Ok(Some(lsp::Location { uri, range }))
})
}
pub fn completion(
&mut self,
params: lsp::TextDocumentPositionParams,
src: EcoString,
) -> Response<Option<Vec<lsp::CompletionItem>>> {
self.respond(|this| {
let module = match this.module_for_uri(¶ms.text_document.uri) {
Some(m) => m,
None => return Ok(None),
};
let completer = Completer::new(&src, ¶ms, &this.compiler, module);
let byte_index = completer
.module_line_numbers
.byte_index(params.position.line, params.position.character);
// If in comment context, do not provide completions
if module.extra.is_within_comment(byte_index) {
return Ok(None);
}
// Check current filercontents if the user is writing an import
// and handle separately from the rest of the completion flow
// Check if an import is being written
if let Some(value) = completer.import_completions() {
return value;
}
let Some(found) = module.find_node(byte_index) else {
return Ok(None);
};
let completions = match found {
Located::PatternSpread { .. } => None,
Located::Pattern(_pattern) => None,
// Do not show completions when typing inside a string.
Located::Expression(TypedExpr::String { .. }) => None,
Located::Expression(TypedExpr::Call { fun, args, .. }) => {
let mut completions = vec![];
completions.append(&mut completer.completion_values());
completions.append(&mut completer.completion_labels(fun, args));
Some(completions)
}
Located::Expression(TypedExpr::RecordAccess { record, .. }) => {
let mut completions = vec![];
completions.append(&mut completer.completion_values());
completions.append(&mut completer.completion_field_accessors(record.type_()));
Some(completions)
}
Located::Statement(_) | Located::Expression(_) => {
Some(completer.completion_values())
}
Located::ModuleStatement(Definition::Function(_)) => {
Some(completer.completion_types())
}
Located::FunctionBody(_) => Some(completer.completion_values()),
Located::ModuleStatement(Definition::TypeAlias(_) | Definition::CustomType(_)) => {
Some(completer.completion_types())
}
// If the import completions returned no results and we are in an import then
// we should try to provide completions for unqualified values
Located::ModuleStatement(Definition::Import(import)) => this
.compiler
.get_module_interface(import.module.as_str())
.map(|importing_module| {
completer.unqualified_completions_from_module(importing_module, true)
}),
Located::ModuleStatement(Definition::ModuleConstant(_)) => None,
Located::UnqualifiedImport(_) => None,
Located::Arg(_) => None,
Located::Annotation(_, _) => Some(completer.completion_types()),
Located::Label(_, _) => None,
};
Ok(completions)
})
}
pub fn code_actions(
&mut self,
params: lsp::CodeActionParams,
) -> Response<Option<Vec<CodeAction>>> {
self.respond(|this| {
let mut actions = vec![];
let Some(module) = this.module_for_uri(¶ms.text_document.uri) else {
return Ok(None);
};
let lines = LineNumbers::new(&module.code);
code_action_unused_values(module, &lines, ¶ms, &mut actions);
code_action_unused_imports(module, &lines, ¶ms, &mut actions);
code_action_convert_qualified_constructor_to_unqualified(
module,
&lines,
¶ms,
&mut actions,
);
code_action_convert_unqualified_constructor_to_qualified(
module,
&lines,
¶ms,
&mut actions,
);
code_action_fix_names(&lines, ¶ms, &this.error, &mut actions);
code_action_import_module(module, &lines, ¶ms, &this.error, &mut actions);
code_action_add_missing_patterns(module, &lines, ¶ms, &this.error, &mut actions);
code_action_inexhaustive_let_to_case(
module,
&lines,
¶ms,
&this.error,
&mut actions,
);
actions.extend(LetAssertToCase::new(module, &lines, ¶ms).code_actions());
actions
.extend(RedundantTupleInCaseSubject::new(module, &lines, ¶ms).code_actions());
actions.extend(UseLabelShorthandSyntax::new(module, &lines, ¶ms).code_actions());
actions.extend(FillInMissingLabelledArgs::new(module, &lines, ¶ms).code_actions());
actions.extend(ConvertFromUse::new(module, &lines, ¶ms).code_actions());
actions.extend(ConvertToUse::new(module, &lines, ¶ms).code_actions());
actions.extend(ExpandFunctionCapture::new(module, &lines, ¶ms).code_actions());
actions.extend(ExtractVariable::new(module, &lines, ¶ms).code_actions());
actions.extend(GenerateFunction::new(module, &lines, ¶ms).code_actions());
actions.extend(ConvertToPipe::new(module, &lines, ¶ms).code_actions());
actions.extend(ConvertToFunctionCall::new(module, &lines, ¶ms).code_actions());
actions.extend(
PatternMatchOnValue::new(module, &lines, ¶ms, &this.compiler).code_actions(),
);
actions.extend(InlineVariable::new(module, &lines, ¶ms).code_actions());
GenerateDynamicDecoder::new(module, &lines, ¶ms, &mut actions).code_actions();
GenerateJsonEncoder::new(module, &lines, ¶ms, &mut actions).code_actions();
AddAnnotations::new(module, &lines, ¶ms).code_action(&mut actions);
Ok(if actions.is_empty() {
None
} else {
Some(actions)
})
})
}
pub fn document_symbol(
&mut self,
params: lsp::DocumentSymbolParams,
) -> Response<Vec<DocumentSymbol>> {
self.respond(|this| {
let mut symbols = vec![];
let Some(module) = this.module_for_uri(¶ms.text_document.uri) else {
return Ok(symbols);
};
let line_numbers = LineNumbers::new(&module.code);
for definition in &module.ast.definitions {
match definition {
// Typically, imports aren't considered document symbols.
Definition::Import(_) => {}
Definition::Function(function) => {
// By default, the function's location ends right after the return type.
// For the full symbol range, have it end at the end of the body.
// Also include the documentation, if available.
//
// By convention, the symbol span starts from the leading slash in the
// documentation comment's marker ('///'), not from its content (of which
// we have the position), so we must convert the content start position
// to the leading slash's position using 'get_doc_marker_pos'.
let full_function_span = SrcSpan {
start: function
.documentation
.as_ref()
.map(|(doc_start, _)| get_doc_marker_pos(*doc_start))
.unwrap_or(function.location.start),
end: function.end_position,
};
let (name_location, name) = function
.name
.as_ref()
.expect("Function in a definition must be named");
// The 'deprecated' field is deprecated, but we have to specify it anyway
// to be able to construct the 'DocumentSymbol' type, so
// we suppress the warning. We specify 'None' as specifying 'Some'
// is what is actually deprecated.
#[allow(deprecated)]
symbols.push(DocumentSymbol {
name: name.to_string(),
detail: Some(
Printer::new(&module.ast.names)
.print_type(&get_function_type(function))
.to_string(),
),
kind: SymbolKind::FUNCTION,
tags: make_deprecated_symbol_tag(&function.deprecation),
deprecated: None,
range: src_span_to_lsp_range(full_function_span, &line_numbers),
selection_range: src_span_to_lsp_range(*name_location, &line_numbers),
children: None,
});
}
Definition::TypeAlias(alias) => {
let full_alias_span = match alias.documentation {
Some((doc_position, _)) => {
SrcSpan::new(get_doc_marker_pos(doc_position), alias.location.end)
}
None => alias.location,
};
// The 'deprecated' field is deprecated, but we have to specify it anyway
// to be able to construct the 'DocumentSymbol' type, so
// we suppress the warning. We specify 'None' as specifying 'Some'
// is what is actually deprecated.
#[allow(deprecated)]
symbols.push(DocumentSymbol {
name: alias.alias.to_string(),
detail: Some(
Printer::new(&module.ast.names)
// If we print with aliases, we end up printing the alias which the user
// is currently hovering, which is not helpful. Instead, we print the
// raw type, so the user can see which type the alias represents
.print_type_without_aliases(&alias.type_)
.to_string(),
),
kind: SymbolKind::CLASS,
tags: make_deprecated_symbol_tag(&alias.deprecation),
deprecated: None,
range: src_span_to_lsp_range(full_alias_span, &line_numbers),
selection_range: src_span_to_lsp_range(
alias.name_location,
&line_numbers,
),
children: None,
});
}
Definition::CustomType(type_) => {
symbols.push(custom_type_symbol(type_, &line_numbers, module));
}
Definition::ModuleConstant(constant) => {
// `ModuleConstant.location` ends at the constant's name or type.
// For the full symbol span, necessary for `range`, we need to
// include the constant value as well.
// Also include the documentation at the start, if available.
let full_constant_span = SrcSpan {
start: constant
.documentation
.as_ref()
.map(|(doc_start, _)| get_doc_marker_pos(*doc_start))
.unwrap_or(constant.location.start),
end: constant.value.location().end,
};
// The 'deprecated' field is deprecated, but we have to specify it anyway
// to be able to construct the 'DocumentSymbol' type, so
// we suppress the warning. We specify 'None' as specifying 'Some'
// is what is actually deprecated.
#[allow(deprecated)]
symbols.push(DocumentSymbol {
name: constant.name.to_string(),
detail: Some(
Printer::new(&module.ast.names)
.print_type(&constant.type_)
.to_string(),
),
kind: SymbolKind::CONSTANT,
tags: make_deprecated_symbol_tag(&constant.deprecation),
deprecated: None,
range: src_span_to_lsp_range(full_constant_span, &line_numbers),
selection_range: src_span_to_lsp_range(
constant.name_location,
&line_numbers,
),
children: None,
});
}
}
}
Ok(symbols)
})
}
pub fn prepare_rename(
&mut self,
params: lsp::TextDocumentPositionParams,
) -> Response<Option<PrepareRenameResponse>> {
self.respond(|this| {
let (lines, found) = match this.node_at_position(¶ms) {
Some(value) => value,
None => return Ok(None),
};
let success_response = |location| {
Some(PrepareRenameResponse::Range(src_span_to_lsp_range(
location, &lines,
)))
};
Ok(match found {
Located::Expression(TypedExpr::Var {
constructor:
ValueConstructor {
variant: ValueConstructorVariant::LocalVariable { origin, location },
..
},
..
})
| Located::Pattern(Pattern::Variable {
origin, location, ..
}) => match origin {
VariableOrigin::Variable(_)
| VariableOrigin::AssignmentPattern
| VariableOrigin::LabelShorthand(_) => success_response(*location),
VariableOrigin::Generated => None,
},
Located::Pattern(Pattern::VarUsage { constructor, .. }) => constructor
.as_ref()
.and_then(|constructor| match &constructor.variant {
ValueConstructorVariant::LocalVariable { origin, location } => match origin
{
VariableOrigin::Variable(_)
| VariableOrigin::AssignmentPattern
| VariableOrigin::LabelShorthand(_) => success_response(*location),
VariableOrigin::Generated => None,
},
_ => None,
}),
Located::Pattern(Pattern::Assign { location, .. }) => success_response(*location),
Located::Arg(arg) => match &arg.names {
ArgNames::Named { location, .. }
| ArgNames::NamedLabelled {
name_location: location,
..
} => success_response(*location),
ArgNames::Discard { .. } | ArgNames::LabelledDiscard { .. } => None,
},
_ => None,
})
})
}
pub fn rename(&mut self, params: lsp::RenameParams) -> Response<Option<WorkspaceEdit>> {
self.respond(|this| {
let position = ¶ms.text_document_position;
let (lines, found) = match this.node_at_position(position) {
Some(value) => value,
None => return Ok(None),
};
let Some(module) = this.module_for_uri(&position.text_document.uri) else {
return Ok(None);
};
Ok(match found {
Located::Expression(TypedExpr::Var {
constructor:
ValueConstructor {
variant: ValueConstructorVariant::LocalVariable { location, origin },
..
},
..
})
| Located::Pattern(Pattern::Variable {
location, origin, ..
}) => match origin {
VariableOrigin::Variable(_) | VariableOrigin::AssignmentPattern => {
rename_local_variable(
module,
&lines,
¶ms,
*location,
VariableRenameKind::Variable,
)
}
VariableOrigin::LabelShorthand(_) => rename_local_variable(
module,
&lines,
¶ms,
*location,
VariableRenameKind::LabelShorthand,
),
VariableOrigin::Generated => None,
},
Located::Pattern(Pattern::VarUsage { constructor, .. }) => constructor
.as_ref()
.and_then(|constructor| match &constructor.variant {
ValueConstructorVariant::LocalVariable { location, origin } => match origin
{
VariableOrigin::Variable(_) | VariableOrigin::AssignmentPattern => {
rename_local_variable(
module,
&lines,
¶ms,
*location,
VariableRenameKind::Variable,
)
}
VariableOrigin::LabelShorthand(_) => rename_local_variable(
module,
&lines,
¶ms,
*location,
VariableRenameKind::LabelShorthand,
),
VariableOrigin::Generated => None,
},
_ => None,
}),
Located::Pattern(Pattern::Assign { location, .. }) => rename_local_variable(
module,
&lines,
¶ms,
*location,
VariableRenameKind::Variable,
),
Located::Arg(arg) => match &arg.names {
ArgNames::Named { location, .. }
| ArgNames::NamedLabelled {
name_location: location,
..
} => rename_local_variable(
module,
&lines,
¶ms,
*location,
VariableRenameKind::Variable,
),
ArgNames::Discard { .. } | ArgNames::LabelledDiscard { .. } => None,
},
_ => None,
})
})
}
fn respond<T>(&mut self, handler: impl FnOnce(&mut Self) -> Result<T>) -> Response<T> {
let result = handler(self);
let warnings = self.take_warnings();
// TODO: test. Ensure hover doesn't report as compiled
let compilation = if self.compiled_since_last_feedback {
let modules = std::mem::take(&mut self.modules_compiled_since_last_feedback);
self.compiled_since_last_feedback = false;
Compilation::Yes(modules)
} else {
Compilation::No
};
Response {
result,
warnings,
compilation,
}
}
pub fn hover(&mut self, params: lsp::HoverParams) -> Response<Option<Hover>> {
self.respond(|this| {
let params = params.text_document_position_params;
let (lines, found) = match this.node_at_position(¶ms) {
Some(value) => value,
None => return Ok(None),
};
let Some(module) = this.module_for_uri(¶ms.text_document.uri) else {
return Ok(None);
};
Ok(match found {
Located::Statement(_) => None, // TODO: hover for statement
Located::ModuleStatement(Definition::Function(fun)) => {
Some(hover_for_function_head(fun, lines, module))
}
Located::ModuleStatement(Definition::ModuleConstant(constant)) => {
Some(hover_for_module_constant(constant, lines, module))
}
Located::ModuleStatement(_) => None,
Located::UnqualifiedImport(UnqualifiedImport {
name,
module: module_name,
is_type,
location,
}) => this
.compiler
.get_module_interface(module_name.as_str())
.and_then(|module_interface| {
if is_type {
module_interface.types.get(name).map(|t| {
hover_for_annotation(
*location,
t.type_.as_ref(),
Some(t),
lines,
module,
)
})
} else {
module_interface.values.get(name).map(|v| {
let m = if this.hex_deps.contains(&module_interface.package) {
Some(module_interface)
} else {
None
};
hover_for_imported_value(v, location, lines, m, name, module)
})
}
}),
Located::Pattern(pattern) => Some(hover_for_pattern(pattern, lines, module)),
Located::PatternSpread {
spread_location,
arguments,
} => {
let range = Some(src_span_to_lsp_range(spread_location, &lines));
let mut positional = vec![];
let mut labelled = vec![];
for argument in arguments {
// We only want to display the arguments that were ignored using `..`.
// Any argument ignored that way is marked as implicit, so if it is
// not implicit we just ignore it.
if !argument.is_implicit() {
continue;
}
let type_ = Printer::new(&module.ast.names)
.print_type(argument.value.type_().as_ref());
match &argument.label {
Some(label) => labelled.push(format!("- `{label}: {type_}`")),
None => positional.push(format!("- `{type_}`")),
}
}
let positional = positional.join("\n");
let labelled = labelled.join("\n");
let content = match (positional.is_empty(), labelled.is_empty()) {
(true, false) => format!("Unused labelled fields:\n{labelled}"),
(false, true) => format!("Unused positional fields:\n{positional}"),
(_, _) => format!(
"Unused positional fields:
{positional}
Unused labelled fields:
{labelled}"
),
};
Some(Hover {
contents: HoverContents::Scalar(MarkedString::from_markdown(content)),
range,
})
}
Located::Expression(expression) => Some(hover_for_expression(
expression,
lines,
module,
&this.hex_deps,
)),
Located::Arg(arg) => Some(hover_for_function_argument(arg, lines, module)),
Located::FunctionBody(_) => None,
Located::Annotation(annotation, type_) => {
let type_constructor = type_constructor_from_modules(
this.compiler.project_compiler.get_importable_modules(),
type_.clone(),
);
Some(hover_for_annotation(
annotation,
&type_,
type_constructor,
lines,
module,
))
}
Located::Label(location, type_) => {
Some(hover_for_label(location, type_, lines, module))
}
})
})
}
pub(crate) fn signature_help(
&mut self,
params: lsp_types::SignatureHelpParams,
) -> Response<Option<SignatureHelp>> {
self.respond(
|this| match this.node_at_position(¶ms.text_document_position_params) {
Some((_lines, Located::Expression(expr))) => {
Ok(signature_help::for_expression(expr))
}
Some((_lines, _located)) => Ok(None),
None => Ok(None),
},
)
}
fn module_node_at_position(
&self,
params: &lsp::TextDocumentPositionParams,
module: &'a Module,
) -> Option<(LineNumbers, Located<'a>)> {
let line_numbers = LineNumbers::new(&module.code);
let byte_index = line_numbers.byte_index(params.position.line, params.position.character);
let node = module.find_node(byte_index);
let node = node?;
Some((line_numbers, node))
}
fn node_at_position(
&self,
params: &lsp::TextDocumentPositionParams,
) -> Option<(LineNumbers, Located<'_>)> {
let module = self.module_for_uri(¶ms.text_document.uri)?;
self.module_node_at_position(params, module)
}
fn module_for_uri(&self, uri: &Url) -> Option<&Module> {
// The to_file_path method is available on these platforms
#[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
let path = uri.to_file_path().expect("URL file");
#[cfg(not(any(unix, windows, target_os = "redox", target_os = "wasi")))]
let path: Utf8PathBuf = uri.path().into();
let components = path
.strip_prefix(self.paths.root())
.ok()?
.components()
.skip(1)
.map(|c| c.as_os_str().to_string_lossy());
let module_name: EcoString = Itertools::intersperse(components, "/".into())
.collect::<String>()
.strip_suffix(".gleam")?
.into();
self.compiler.modules.get(&module_name)
}
}
fn custom_type_symbol(
type_: &CustomType<Arc<Type>>,
line_numbers: &LineNumbers,
module: &Module,
) -> DocumentSymbol {
let constructors = type_
.constructors
.iter()
.map(|constructor| {
let mut arguments = vec![];
// List named arguments as field symbols.
for argument in &constructor.arguments {
let Some((label_location, label)) = &argument.label else {
continue;
};
let full_arg_span = match argument.doc {
Some((doc_position, _)) => {
SrcSpan::new(get_doc_marker_pos(doc_position), argument.location.end)
}
None => argument.location,
};
// The 'deprecated' field is deprecated, but we have to specify it anyway
// to be able to construct the 'DocumentSymbol' type, so
// we suppress the warning. We specify 'None' as specifying 'Some'
// is what is actually deprecated.
#[allow(deprecated)]
arguments.push(DocumentSymbol {
name: label.to_string(),
detail: Some(
Printer::new(&module.ast.names)
.print_type(&argument.type_)
.to_string(),
),
kind: SymbolKind::FIELD,
tags: None,
deprecated: None,
range: src_span_to_lsp_range(full_arg_span, line_numbers),
selection_range: src_span_to_lsp_range(*label_location, line_numbers),
children: None,
});
}
// Start from the documentation if available, otherwise from the constructor's name,
// all the way to the end of its arguments.
let full_constructor_span = SrcSpan {
start: constructor
.documentation
.as_ref()
.map(|(doc_start, _)| get_doc_marker_pos(*doc_start))
.unwrap_or(constructor.location.start),
end: constructor.location.end,
};
// The 'deprecated' field is deprecated, but we have to specify it anyway
// to be able to construct the 'DocumentSymbol' type, so
// we suppress the warning. We specify 'None' as specifying 'Some'
// is what is actually deprecated.
#[allow(deprecated)]
DocumentSymbol {
name: constructor.name.to_string(),
detail: None,
kind: if constructor.arguments.is_empty() {
SymbolKind::ENUM_MEMBER
} else {
SymbolKind::CONSTRUCTOR
},
tags: make_deprecated_symbol_tag(&constructor.deprecation),
deprecated: None,
range: src_span_to_lsp_range(full_constructor_span, line_numbers),
selection_range: src_span_to_lsp_range(constructor.name_location, line_numbers),
children: if arguments.is_empty() {
None
} else {
Some(arguments)
},
}
})
.collect_vec();
// The type's location, by default, ranges from "(pub) type" to the end of its name.
// We need it to range to the end of its constructors instead for the full symbol range.
// We also include documentation, if available, by LSP convention.
let full_type_span = SrcSpan {
start: type_
.documentation
.as_ref()
.map(|(doc_start, _)| get_doc_marker_pos(*doc_start))
.unwrap_or(type_.location.start),
end: type_.end_position,
};
// The 'deprecated' field is deprecated, but we have to specify it anyway
// to be able to construct the 'DocumentSymbol' type, so
// we suppress the warning. We specify 'None' as specifying 'Some'
// is what is actually deprecated.
#[allow(deprecated)]
DocumentSymbol {
name: type_.name.to_string(),
detail: None,
kind: SymbolKind::CLASS,
tags: make_deprecated_symbol_tag(&type_.deprecation),
deprecated: None,
range: src_span_to_lsp_range(full_type_span, line_numbers),
selection_range: src_span_to_lsp_range(type_.name_location, line_numbers),
children: if constructors.is_empty() {
None
} else {
Some(constructors)
},
}
}
fn hover_for_pattern(pattern: &TypedPattern, line_numbers: LineNumbers, module: &Module) -> Hover {
let documentation = pattern.get_documentation().unwrap_or_default();
// Show the type of the hovered node to the user
let type_ = Printer::new(&module.ast.names).print_type(pattern.type_().as_ref());
let contents = format!(
"```gleam
{type_}
```
{documentation}"
);
Hover {
contents: HoverContents::Scalar(MarkedString::String(contents)),
range: Some(src_span_to_lsp_range(pattern.location(), &line_numbers)),
}
}
fn get_function_type(fun: &TypedFunction) -> Type {
Type::Fn {
args: fun.arguments.iter().map(|arg| arg.type_.clone()).collect(),
retrn: fun.return_type.clone(),
}
}
fn hover_for_function_head(
fun: &TypedFunction,
line_numbers: LineNumbers,