forked from slint-ui/slint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlanguage.rs
1757 lines (1609 loc) · 66.9 KB
/
language.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 © SixtyFPS GmbH <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore descr rfind unindented
pub mod completion;
mod formatting;
mod goto;
mod hover;
mod semantic_tokens;
#[cfg(test)]
pub mod test;
pub mod token_info;
use crate::common;
use crate::util;
#[cfg(target_arch = "wasm32")]
use crate::wasm_prelude::*;
use i_slint_compiler::object_tree::ElementRc;
use i_slint_compiler::parser::{
syntax_nodes, NodeOrToken, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize,
};
use i_slint_compiler::{diagnostics::BuildDiagnostics, langtype::Type};
use lsp_types::request::{
CodeActionRequest, CodeLensRequest, ColorPresentationRequest, Completion, DocumentColor,
DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand, Formatting, GotoDefinition,
HoverRequest, PrepareRenameRequest, Rename, SemanticTokensFullRequest,
};
use lsp_types::{
ClientCapabilities, CodeActionOrCommand, CodeActionProviderCapability, CodeLens,
CodeLensOptions, Color, ColorInformation, ColorPresentation, Command, CompletionOptions,
DocumentSymbol, DocumentSymbolResponse, InitializeParams, InitializeResult, OneOf, Position,
PrepareRenameResponse, PublishDiagnosticsParams, RenameOptions, SemanticTokensFullOptions,
SemanticTokensLegend, SemanticTokensOptions, ServerCapabilities, ServerInfo,
TextDocumentSyncCapability, TextEdit, Url, WorkDoneProgressOptions,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::rc::Rc;
pub const SHOW_PREVIEW_COMMAND: &str = "slint/showPreview";
fn command_list() -> Vec<String> {
vec![
#[cfg(any(feature = "preview-builtin", feature = "preview-external"))]
SHOW_PREVIEW_COMMAND.into(),
]
}
fn create_show_preview_command(
pretty: bool,
file: &lsp_types::Url,
component_name: &str,
) -> Command {
let title = format!("{}Show Preview", if pretty { &"▶ " } else { &"" });
Command::new(
title,
SHOW_PREVIEW_COMMAND.into(),
Some(vec![file.as_str().into(), component_name.into()]),
)
}
#[cfg(any(feature = "preview-external", feature = "preview-engine"))]
pub fn request_state(ctx: &std::rc::Rc<Context>) {
let document_cache = ctx.document_cache.borrow();
for (url, d) in document_cache.all_url_documents() {
if url.scheme() == "builtin" {
continue;
}
let version = document_cache.document_version(&url);
if let Some(node) = &d.node {
ctx.server_notifier.send_message_to_preview(common::LspToPreviewMessage::SetContents {
url: common::VersionedUrl::new(url, version),
contents: node.text().to_string(),
})
}
}
ctx.server_notifier.send_message_to_preview(common::LspToPreviewMessage::SetConfiguration {
config: ctx.preview_config.borrow().clone(),
});
if let Some(c) = ctx.to_show.borrow().clone() {
ctx.server_notifier.send_message_to_preview(common::LspToPreviewMessage::ShowPreview(c))
}
}
async fn register_file_watcher(ctx: &Context) -> common::Result<()> {
use lsp_types::notification::Notification;
if ctx
.init_param
.capabilities
.workspace
.as_ref()
.and_then(|ws| ws.did_change_watched_files)
.and_then(|wf| wf.dynamic_registration)
.unwrap_or(false)
{
let fs_watcher = lsp_types::DidChangeWatchedFilesRegistrationOptions {
watchers: vec![lsp_types::FileSystemWatcher {
glob_pattern: lsp_types::GlobPattern::String("**/*".to_string()),
kind: Some(lsp_types::WatchKind::Change | lsp_types::WatchKind::Delete),
}],
};
ctx.server_notifier
.send_request::<lsp_types::request::RegisterCapability>(
lsp_types::RegistrationParams {
registrations: vec![lsp_types::Registration {
id: "slint.file_watcher.registration".to_string(),
method: lsp_types::notification::DidChangeWatchedFiles::METHOD.to_string(),
register_options: Some(serde_json::to_value(fs_watcher).unwrap()),
}],
},
)?
.await?;
}
Ok(())
}
pub struct Context {
pub document_cache: RefCell<common::DocumentCache>,
pub preview_config: RefCell<common::PreviewConfig>,
pub server_notifier: crate::ServerNotifier,
pub init_param: InitializeParams,
/// The last component for which the user clicked "show preview"
#[cfg(any(feature = "preview-external", feature = "preview-engine"))]
pub to_show: RefCell<Option<common::PreviewComponent>>,
pub open_urls: RefCell<std::collections::HashSet<lsp_types::Url>>,
}
/// An error from a LSP request
pub struct LspError {
pub code: LspErrorCode,
pub message: String,
}
/// The code of a LspError. Correspond to the lsp_server::ErrorCode
pub enum LspErrorCode {
/// Invalid method parameter(s).
InvalidParameter,
/// Internal JSON-RPC error.
#[allow(unused)]
InternalError,
/// A request failed but it was syntactically correct, e.g the
/// method name was known and the parameters were valid. The error
/// message should contain human readable information about why
/// the request failed.
RequestFailed,
/// The server detected that the content of a document got
/// modified outside normal conditions. A server should
/// NOT send this error code if it detects a content change
/// in it unprocessed messages. The result even computed
/// on an older state might still be useful for the client.
///
/// If a client decides that a result is not of any use anymore
/// the client should cancel the request.
#[allow(unused)]
ContentModified = -32801,
}
#[derive(Default)]
pub struct RequestHandler(
pub HashMap<
&'static str,
Box<
dyn Fn(
serde_json::Value,
Rc<Context>,
)
-> Pin<Box<dyn Future<Output = Result<serde_json::Value, LspError>>>>,
>,
>,
);
impl RequestHandler {
pub fn register<
R: lsp_types::request::Request,
Fut: Future<Output = std::result::Result<R::Result, LspError>> + 'static,
>(
&mut self,
handler: fn(R::Params, Rc<Context>) -> Fut,
) where
R::Params: 'static,
{
self.0.insert(
R::METHOD,
Box::new(move |value, ctx| {
Box::pin(async move {
let params = serde_json::from_value(value).map_err(|e| LspError {
code: LspErrorCode::InvalidParameter,
message: format!("error when deserializing request: {e:?}"),
})?;
handler(params, ctx).await.map(|x| serde_json::to_value(x).unwrap())
})
}),
);
}
}
pub fn server_initialize_result(client_cap: &ClientCapabilities) -> InitializeResult {
InitializeResult {
capabilities: ServerCapabilities {
hover_provider: Some(true.into()),
completion_provider: Some(CompletionOptions {
resolve_provider: None,
trigger_characters: Some(vec![".".to_owned()]),
work_done_progress_options: WorkDoneProgressOptions::default(),
all_commit_characters: None,
completion_item: None,
}),
definition_provider: Some(OneOf::Left(true)),
text_document_sync: Some(TextDocumentSyncCapability::Kind(
lsp_types::TextDocumentSyncKind::FULL,
)),
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
execute_command_provider: Some(lsp_types::ExecuteCommandOptions {
commands: command_list(),
..Default::default()
}),
document_symbol_provider: Some(OneOf::Left(true)),
color_provider: Some(true.into()),
code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(true) }),
semantic_tokens_provider: Some(
SemanticTokensOptions {
legend: SemanticTokensLegend {
token_types: semantic_tokens::LEGEND_TYPES.to_vec(),
token_modifiers: semantic_tokens::LEGEND_MODS.to_vec(),
},
full: Some(SemanticTokensFullOptions::Bool(true)),
..Default::default()
}
.into(),
),
document_highlight_provider: Some(OneOf::Left(true)),
rename_provider: Some(
if client_cap
.text_document
.as_ref()
.and_then(|td| td.rename.as_ref())
.and_then(|r| r.prepare_support)
.unwrap_or(false)
{
OneOf::Right(RenameOptions {
prepare_provider: Some(true),
work_done_progress_options: WorkDoneProgressOptions::default(),
})
} else {
OneOf::Left(true)
},
),
document_formatting_provider: Some(OneOf::Left(true)),
..ServerCapabilities::default()
},
server_info: Some(ServerInfo {
name: env!("CARGO_PKG_NAME").to_string(),
version: Some(env!("CARGO_PKG_VERSION").to_string()),
}),
offset_encoding: Some("utf-8".to_string()),
}
}
pub fn register_request_handlers(rh: &mut RequestHandler) {
rh.register::<GotoDefinition, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
let result = token_descr(
document_cache,
¶ms.text_document_position_params.text_document.uri,
¶ms.text_document_position_params.position,
)
.and_then(|token| goto::goto_definition(document_cache, token.0));
Ok(result)
});
rh.register::<Completion, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
let result = token_descr(
document_cache,
¶ms.text_document_position.text_document.uri,
¶ms.text_document_position.position,
)
.and_then(|token| {
completion::completion_at(
document_cache,
token.0,
token.1,
ctx.init_param
.capabilities
.text_document
.as_ref()
.and_then(|t| t.completion.as_ref()),
)
.map(Into::into)
});
Ok(result)
});
rh.register::<HoverRequest, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
let result = token_descr(
document_cache,
¶ms.text_document_position_params.text_document.uri,
¶ms.text_document_position_params.position,
)
.and_then(|(token, _)| hover::get_tooltip(document_cache, token));
Ok(result)
});
rh.register::<CodeActionRequest, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
let result = token_descr(document_cache, ¶ms.text_document.uri, ¶ms.range.start)
.and_then(|(token, _)| {
get_code_actions(document_cache, token, &ctx.init_param.capabilities)
});
Ok(result)
});
rh.register::<ExecuteCommand, _>(|params, _ctx| async move {
if params.command.as_str() == SHOW_PREVIEW_COMMAND {
#[cfg(any(feature = "preview-builtin", feature = "preview-external"))]
show_preview_command(¶ms.arguments, &_ctx)?;
return Ok(None::<serde_json::Value>);
}
Ok(None::<serde_json::Value>)
});
rh.register::<DocumentColor, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
Ok(get_document_color(document_cache, ¶ms.text_document).unwrap_or_default())
});
rh.register::<ColorPresentationRequest, _>(|params, _ctx| async move {
// Convert the color from the color picker to a string representation. This could try to produce a minimal
// representation.
let requested_color = params.color;
let color_literal = if requested_color.alpha < 1. {
format!(
"#{:0>2x}{:0>2x}{:0>2x}{:0>2x}",
(requested_color.red * 255.) as u8,
(requested_color.green * 255.) as u8,
(requested_color.blue * 255.) as u8,
(requested_color.alpha * 255.) as u8
)
} else {
format!(
"#{:0>2x}{:0>2x}{:0>2x}",
(requested_color.red * 255.) as u8,
(requested_color.green * 255.) as u8,
(requested_color.blue * 255.) as u8,
)
};
Ok(vec![ColorPresentation { label: color_literal, ..Default::default() }])
});
rh.register::<DocumentSymbolRequest, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
Ok(get_document_symbols(document_cache, ¶ms.text_document))
});
rh.register::<CodeLensRequest, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
Ok(get_code_lenses(document_cache, ¶ms.text_document))
});
rh.register::<SemanticTokensFullRequest, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
Ok(semantic_tokens::get_semantic_tokens(document_cache, ¶ms.text_document))
});
rh.register::<DocumentHighlightRequest, _>(|params, ctx| async move {
let document_cache = &mut ctx.document_cache.borrow_mut();
let uri = params.text_document_position_params.text_document.uri;
if let Some((tk, _)) =
token_descr(document_cache, &uri, ¶ms.text_document_position_params.position)
{
let p = tk.parent();
let gp = p.parent();
if p.kind() == SyntaxKind::DeclaredIdentifier
&& gp.as_ref().map_or(false, |n| n.kind() == SyntaxKind::Component)
{
let element = gp.as_ref().unwrap().child_node(SyntaxKind::Element).unwrap();
ctx.server_notifier.send_message_to_preview(
common::LspToPreviewMessage::HighlightFromEditor {
url: Some(uri),
offset: element.text_range().start().into(),
},
);
let range = util::node_to_lsp_range(&p);
return Ok(Some(vec![lsp_types::DocumentHighlight { range, kind: None }]));
}
if p.kind() == SyntaxKind::QualifiedName
&& gp.as_ref().map_or(false, |n| n.kind() == SyntaxKind::Element)
{
let range = util::node_to_lsp_range(&p);
if gp
.as_ref()
.unwrap()
.parent()
.as_ref()
.map_or(false, |n| n.kind() != SyntaxKind::Component)
{
ctx.server_notifier.send_message_to_preview(
common::LspToPreviewMessage::HighlightFromEditor {
url: Some(uri),
offset: gp.unwrap().text_range().start().into(),
},
);
}
return Ok(Some(vec![lsp_types::DocumentHighlight { range, kind: None }]));
}
if let Some(value) = find_element_id_for_highlight(&tk, &p) {
ctx.server_notifier.send_message_to_preview(
common::LspToPreviewMessage::HighlightFromEditor { url: None, offset: 0 },
);
return Ok(Some(
value
.into_iter()
.map(|r| lsp_types::DocumentHighlight {
range: util::text_range_to_lsp_range(&p.source_file, r),
kind: None,
})
.collect(),
));
}
}
ctx.server_notifier.send_message_to_preview(
common::LspToPreviewMessage::HighlightFromEditor { url: None, offset: 0 },
);
Ok(None)
});
rh.register::<Rename, _>(|params, ctx| async move {
let mut document_cache = ctx.document_cache.borrow_mut();
let uri = params.text_document_position.text_document.uri;
if let Some((tk, _off)) =
token_descr(&mut document_cache, &uri, ¶ms.text_document_position.position)
{
let p = tk.parent();
let version = document_cache.document_version(&uri);
if let Some(value) = find_element_id_for_highlight(&tk, &p) {
let edits: Vec<_> = value
.into_iter()
.map(|r| TextEdit {
range: util::text_range_to_lsp_range(&p.source_file, r),
new_text: params.new_name.clone(),
})
.collect();
return Ok(Some(common::create_workspace_edit(uri, version, edits)));
}
match p.kind() {
SyntaxKind::DeclaredIdentifier => {
common::rename_component::rename_component_from_definition(
&document_cache,
&p.into(),
¶ms.new_name,
)
.map(Some)
.map_err(|e| LspError {
code: LspErrorCode::RequestFailed,
message: e.to_string(),
})
}
_ => Err(LspError {
code: LspErrorCode::RequestFailed,
message: "This symbol cannot be renamed.".into(),
}),
}
} else {
Err(LspError {
code: LspErrorCode::RequestFailed,
message: "This symbol cannot be renamed.".into(),
})
}
});
rh.register::<PrepareRenameRequest, _>(|params, ctx| async move {
let mut document_cache = ctx.document_cache.borrow_mut();
let uri = params.text_document.uri;
if let Some((tk, _off)) = token_descr(&mut document_cache, &uri, ¶ms.position) {
if find_element_id_for_highlight(&tk, &tk.parent()).is_some() {
return Ok(Some(PrepareRenameResponse::Range(util::token_to_lsp_range(&tk))));
}
let p = tk.parent();
if matches!(p.kind(), SyntaxKind::DeclaredIdentifier) {
if let Some(gp) = p.parent() {
if gp.kind() == SyntaxKind::Component {
return Ok(Some(PrepareRenameResponse::Range(util::node_to_lsp_range(&p))));
}
}
}
}
Ok(None)
});
rh.register::<Formatting, _>(|params, ctx| async move {
let document_cache = ctx.document_cache.borrow_mut();
Ok(formatting::format_document(params, &document_cache))
});
}
/// extract the parameter at given index. name is used in the error
#[cfg(any(feature = "preview-builtin", feature = "preview-external"))]
fn extract_param<T: serde::de::DeserializeOwned>(
params: &[serde_json::Value],
index: usize,
name: &str,
) -> Result<T, LspError> {
let p = params.get(index).ok_or_else(|| LspError {
code: LspErrorCode::InvalidParameter,
message: format!("{} parameter is missing", name),
})?;
serde_json::from_value(p.clone()).map_err(|e| LspError {
code: LspErrorCode::InvalidParameter,
message: format!("{} parameter is invalid: {}", name, e),
})
}
#[cfg(any(feature = "preview-builtin", feature = "preview-external"))]
pub fn show_preview_command(
params: &[serde_json::Value],
ctx: &Rc<Context>,
) -> Result<(), LspError> {
let document_cache = &mut ctx.document_cache.borrow_mut();
let config = document_cache.compiler_configuration();
let url: Url = extract_param(params, 0, "url")?;
// Normalize the URL to make sure it is encoded the same way as what the preview expect from other URLs
let url =
common::uri_to_file(&url).and_then(|u| Url::from_file_path(u).ok()).ok_or_else(|| {
LspError {
code: LspErrorCode::InvalidParameter,
message: "invalid document url".into(),
}
})?;
let component =
params.get(1).and_then(|v| v.as_str()).filter(|v| !v.is_empty()).map(|v| v.to_string());
let c = common::PreviewComponent {
url,
component,
style: config.style.clone().unwrap_or_default(),
};
ctx.to_show.replace(Some(c.clone()));
ctx.server_notifier.send_message_to_preview(common::LspToPreviewMessage::ShowPreview(c));
Ok(())
}
pub(crate) async fn reload_document_impl(
ctx: Option<&Rc<Context>>,
mut content: String,
url: lsp_types::Url,
version: Option<i32>,
document_cache: &mut common::DocumentCache,
) -> HashMap<Url, Vec<lsp_types::Diagnostic>> {
let Some(path) = common::uri_to_file(&url) else { return Default::default() };
// Normalize the URL
let Ok(url) = Url::from_file_path(path.clone()) else { return Default::default() };
if path.extension().map_or(false, |e| e == "rs") {
content = match i_slint_compiler::lexer::extract_rust_macro(content) {
Some(content) => content,
// A rust file without a rust macro, just ignore it
None => return [(url, vec![])].into_iter().collect(),
};
}
if let Some(ctx) = ctx {
ctx.server_notifier.send_message_to_preview(common::LspToPreviewMessage::SetContents {
url: common::VersionedUrl::new(url.clone(), version),
contents: content.clone(),
});
}
let mut diag = BuildDiagnostics::default();
let _ = document_cache.load_url(&url, version, content, &mut diag).await; // ignore url conversion errors
// Always provide diagnostics for all files. Empty diagnostics clear any previous ones.
let mut lsp_diags: HashMap<Url, Vec<lsp_types::Diagnostic>> = core::iter::once(&path)
.chain(diag.all_loaded_files.iter())
.map(|path| {
let uri = Url::from_file_path(path).unwrap();
(uri, Default::default())
})
.collect();
for d in diag.into_iter() {
#[cfg(not(target_arch = "wasm32"))]
if d.source_file().unwrap().is_relative() {
continue;
}
let uri = Url::from_file_path(d.source_file().unwrap()).unwrap();
lsp_diags.entry(uri).or_default().push(util::to_lsp_diag(&d));
}
lsp_diags
}
pub async fn open_document(
ctx: &Rc<Context>,
content: String,
url: lsp_types::Url,
version: Option<i32>,
document_cache: &mut common::DocumentCache,
) -> common::Result<()> {
ctx.open_urls.borrow_mut().insert(url.clone());
reload_document(ctx, content, url, version, document_cache).await
}
pub async fn close_document(ctx: &Rc<Context>, url: lsp_types::Url) -> common::Result<()> {
ctx.open_urls.borrow_mut().remove(&url);
invalidate_document(ctx, url).await
}
pub async fn reload_document(
ctx: &Rc<Context>,
content: String,
url: lsp_types::Url,
version: Option<i32>,
document_cache: &mut common::DocumentCache,
) -> common::Result<()> {
let lsp_diags =
reload_document_impl(Some(ctx), content, url.clone(), version, document_cache).await;
for (uri, diagnostics) in lsp_diags {
let version = document_cache.document_version(&uri);
ctx.server_notifier.send_notification::<lsp_types::notification::PublishDiagnostics>(
PublishDiagnosticsParams { uri, diagnostics, version },
)?;
}
Ok(())
}
pub async fn invalidate_document(ctx: &Rc<Context>, url: lsp_types::Url) -> common::Result<()> {
// The preview cares about resources and slint files, so forward everything
ctx.server_notifier.send_message_to_preview(common::LspToPreviewMessage::InvalidateContents {
url: url.clone(),
});
ctx.document_cache.borrow_mut().drop_document(&url)
}
pub async fn trigger_file_watcher(ctx: &Rc<Context>, url: lsp_types::Url) -> common::Result<()> {
if !ctx.open_urls.borrow().contains(&url) {
invalidate_document(ctx, url).await?;
}
Ok(())
}
/// return the token, and the offset within the file
fn token_descr(
document_cache: &mut common::DocumentCache,
text_document_uri: &Url,
pos: &Position,
) -> Option<(SyntaxToken, TextSize)> {
let (doc, o) = document_cache.get_document_and_offset(text_document_uri, pos)?;
let node = doc.node.as_ref()?;
let token = token_at_offset(node, o)?;
Some((token, o))
}
/// Return the token that matches best the token at cursor position
pub fn token_at_offset(doc: &syntax_nodes::Document, offset: TextSize) -> Option<SyntaxToken> {
let mut taf = doc.token_at_offset(offset);
let token = match (taf.next(), taf.next()) {
(None, _) => doc.last_token()?,
(Some(t), None) => t,
(Some(l), Some(r)) => match (l.kind(), r.kind()) {
// Prioritize identifier
(SyntaxKind::Identifier, _) => l,
(_, SyntaxKind::Identifier) => r,
// then the dot
(SyntaxKind::Dot, _) => l,
(_, SyntaxKind::Dot) => r,
// de-prioritize the white spaces
(SyntaxKind::Whitespace, _) => r,
(SyntaxKind::Comment, _) => r,
(_, SyntaxKind::Whitespace) => l,
(_, SyntaxKind::Comment) => l,
_ => l,
},
};
Some(token)
}
fn has_experimental_client_capability(capabilities: &ClientCapabilities, name: &str) -> bool {
capabilities
.experimental
.as_ref()
.and_then(|o| o.get(name).and_then(|v| v.as_bool()))
.unwrap_or(false)
}
fn get_code_actions(
document_cache: &mut common::DocumentCache,
token: SyntaxToken,
client_capabilities: &ClientCapabilities,
) -> Option<Vec<CodeActionOrCommand>> {
let node = token.parent();
let uri = Url::from_file_path(token.source_file.path()).ok()?;
let mut result = vec![];
let component = syntax_nodes::Component::new(node.clone())
.or_else(|| {
syntax_nodes::DeclaredIdentifier::new(node.clone())
.and_then(|n| n.parent())
.and_then(syntax_nodes::Component::new)
})
.or_else(|| {
syntax_nodes::QualifiedName::new(node.clone())
.and_then(|n| n.parent())
.and_then(syntax_nodes::Element::new)
.and_then(|n| n.parent())
.and_then(syntax_nodes::Component::new)
});
#[cfg(any(feature = "preview-builtin", feature = "preview-external"))]
{
if let Some(component) = &component {
if let Some(component_name) =
i_slint_compiler::parser::identifier_text(&component.DeclaredIdentifier())
{
result.push(CodeActionOrCommand::Command(create_show_preview_command(
false,
&uri,
&component_name,
)))
}
}
}
if token.kind() == SyntaxKind::StringLiteral && node.kind() == SyntaxKind::Expression {
let r = util::text_range_to_lsp_range(&token.source_file, node.text_range());
let edits = vec![
TextEdit::new(lsp_types::Range::new(r.start, r.start), "@tr(".into()),
TextEdit::new(lsp_types::Range::new(r.end, r.end), ")".into()),
];
result.push(CodeActionOrCommand::CodeAction(lsp_types::CodeAction {
title: "Wrap in `@tr()`".into(),
edit: common::create_workspace_edit_from_path(
document_cache,
token.source_file.path(),
edits,
),
..Default::default()
}));
} else if token.kind() == SyntaxKind::Identifier
&& node.kind() == SyntaxKind::QualifiedName
&& node.parent().map(|n| n.kind()) == Some(SyntaxKind::Element)
{
let is_lookup_error = {
let global_tr = document_cache.global_type_registry();
let tr = document_cache
.get_document_for_source_file(&token.source_file)
.map(|doc| &doc.local_registry)
.unwrap_or(&global_tr);
util::lookup_current_element_type(node.clone(), tr).is_none()
};
if is_lookup_error {
// Couldn't lookup the element, there is probably an error. Suggest an edit
let text = token.text();
completion::build_import_statements_edits(
&token,
document_cache,
&mut |ci| !ci.is_global && ci.is_exported && ci.name == text,
&mut |_name, file, edit| {
result.push(CodeActionOrCommand::CodeAction(lsp_types::CodeAction {
title: format!("Add import from \"{file}\""),
kind: Some(lsp_types::CodeActionKind::QUICKFIX),
edit: common::create_workspace_edit_from_path(
document_cache,
token.source_file.path(),
vec![edit],
),
..Default::default()
}))
},
);
}
if has_experimental_client_capability(client_capabilities, "snippetTextEdit") {
let r = util::text_range_to_lsp_range(
&token.source_file,
node.parent().unwrap().text_range(),
);
let element = document_cache.element_at_position(&uri, &r.start);
let element_indent = element.as_ref().and_then(util::find_element_indent);
let indented_lines = node
.parent()
.unwrap()
.text()
.to_string()
.lines()
.map(
|line| if line.is_empty() { line.to_string() } else { format!(" {}", line) },
)
.collect::<Vec<String>>();
let edits = vec![TextEdit::new(
lsp_types::Range::new(r.start, r.end),
format!(
"${{0:element}} {{\n{}{}\n}}",
element_indent.unwrap_or("".into()),
indented_lines.join("\n")
),
)];
result.push(CodeActionOrCommand::CodeAction(lsp_types::CodeAction {
title: "Wrap in element".into(),
kind: Some(lsp_types::CodeActionKind::REFACTOR),
edit: common::create_workspace_edit_from_path(
document_cache,
token.source_file.path(),
edits,
),
..Default::default()
}));
// Collect all normal, repeated, and conditional sub-elements and any
// whitespace in between for substituting the parent element with its
// sub-elements, dropping its own properties, callbacks etc.
fn is_sub_element(kind: SyntaxKind) -> bool {
matches!(
kind,
SyntaxKind::SubElement
| SyntaxKind::RepeatedElement
| SyntaxKind::ConditionalElement
)
}
let sub_elements = node
.parent()
.unwrap()
.children_with_tokens()
.skip_while(|n| !is_sub_element(n.kind()))
.filter(|n| match n {
NodeOrToken::Node(_) => is_sub_element(n.kind()),
NodeOrToken::Token(t) => {
t.kind() == SyntaxKind::Whitespace
&& t.next_sibling_or_token().map_or(false, |n| is_sub_element(n.kind()))
}
})
.collect::<Vec<_>>();
if match component {
// A top-level component element can only be removed if it contains
// exactly one sub-element (without any condition or assignment)
// that can substitute the component element.
Some(_) => {
sub_elements.len() == 1
&& sub_elements.first().and_then(|n| {
n.as_node().unwrap().first_child_or_token().map(|n| n.kind())
}) == Some(SyntaxKind::Element)
}
// Any other element can be removed in favor of one or more sub-elements.
None => sub_elements.iter().any(|n| n.kind() == SyntaxKind::SubElement),
} {
let unindented_lines = sub_elements
.iter()
.map(|n| match n {
NodeOrToken::Node(n) => n
.text()
.to_string()
.lines()
.map(|line| line.strip_prefix(" ").unwrap_or(line).to_string())
.collect::<Vec<_>>()
.join("\n"),
NodeOrToken::Token(t) => {
t.text().strip_suffix(" ").unwrap_or(t.text()).to_string()
}
})
.collect::<Vec<String>>();
let edits = vec![TextEdit::new(
lsp_types::Range::new(r.start, r.end),
unindented_lines.concat(),
)];
result.push(CodeActionOrCommand::CodeAction(lsp_types::CodeAction {
title: "Remove element".into(),
kind: Some(lsp_types::CodeActionKind::REFACTOR),
edit: common::create_workspace_edit_from_path(
document_cache,
token.source_file.path(),
edits,
),
..Default::default()
}));
}
// We have already checked that the node is a qualified name of an element.
// Check whether the element is a direct sub-element of another element
// meaning that it can be repeated or made conditional.
if node // QualifiedName
.parent() // Element
.unwrap()
.parent()
.filter(|n| n.kind() == SyntaxKind::SubElement)
.and_then(|p| p.parent())
.is_some_and(|n| n.kind() == SyntaxKind::Element)
{
let edits = vec![TextEdit::new(
lsp_types::Range::new(r.start, r.start),
"for ${1:name}[index] in ${0:model} : ".to_string(),
)];
result.push(CodeActionOrCommand::CodeAction(lsp_types::CodeAction {
title: "Repeat element".into(),
kind: Some(lsp_types::CodeActionKind::REFACTOR),
edit: common::create_workspace_edit_from_path(
document_cache,
token.source_file.path(),
edits,
),
..Default::default()
}));
let edits = vec![TextEdit::new(
lsp_types::Range::new(r.start, r.start),
"if ${0:condition} : ".to_string(),
)];
result.push(CodeActionOrCommand::CodeAction(lsp_types::CodeAction {
title: "Make conditional".into(),
kind: Some(lsp_types::CodeActionKind::REFACTOR),
edit: common::create_workspace_edit_from_path(
document_cache,
token.source_file.path(),
edits,
),
..Default::default()
}));
}
}
}
(!result.is_empty()).then_some(result)
}
fn get_document_color(
document_cache: &mut common::DocumentCache,
text_document: &lsp_types::TextDocumentIdentifier,
) -> Option<Vec<ColorInformation>> {
let mut result = Vec::new();
let doc = document_cache.get_document(&text_document.uri)?;
let root_node = doc.node.as_ref()?;
let mut token = root_node.first_token()?;
loop {
if token.kind() == SyntaxKind::ColorLiteral {
(|| -> Option<()> {
let range = util::token_to_lsp_range(&token);
let col = i_slint_compiler::literals::parse_color_literal(token.text())?;
let shift = |s: u32| -> f32 { ((col >> s) & 0xff) as f32 / 255. };
result.push(ColorInformation {
range,
color: Color {
alpha: shift(24),
red: shift(16),
green: shift(8),
blue: shift(0),
},
});
Some(())
})();
}
token = match token.next_token() {
Some(token) => token,
None => break Some(result),
}
}
}
/// Retrieve the document outline
fn get_document_symbols(
document_cache: &mut common::DocumentCache,
text_document: &lsp_types::TextDocumentIdentifier,
) -> Option<DocumentSymbolResponse> {
let doc = document_cache.get_document(&text_document.uri)?;
// DocumentSymbol doesn't implement default and some field depends on features or are deprecated
let ds: DocumentSymbol = serde_json::from_value(
serde_json::json!({ "name" : "", "kind": 255, "range" : lsp_types::Range::default(), "selectionRange" : lsp_types::Range::default() })
)
.unwrap();
let inner_components = doc.inner_components.clone();
let inner_types = doc.inner_types.clone();
let mut r = inner_components
.iter()
.filter_map(|c| {
let root_element = c.root_element.borrow();
let element_node = &root_element.debug.first()?.node;
let component_node = syntax_nodes::Component::new(element_node.parent()?)?;
let selection_range = util::node_to_lsp_range(&component_node.DeclaredIdentifier());
if c.id.is_empty() {
// Symbols with empty names are invalid
return None;
}