slint-lsp 1.16.1

A language server protocol implementation for Slint
Documentation
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
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

//! Data structures common between LSP and previewer

use i_slint_compiler::diagnostics::{BuildDiagnostics, SourceFile};
use i_slint_compiler::object_tree::Document;
use i_slint_compiler::parser::{TextSize, syntax_nodes};
use i_slint_compiler::typeloader::TypeLoader;
use i_slint_compiler::typeregister::TypeRegister;
use lsp_types::Url;

use std::{
    cell::RefCell,
    collections::HashMap,
    future::Future,
    path::{Path, PathBuf},
    pin::Pin,
    rc::Rc,
};

use crate::common::{ElementRcNode, Result, file_to_uri, uri_to_file};
use std::collections::HashSet;

pub type SourceFileVersion = Option<i32>;

pub type SourceFileVersionMap = HashMap<PathBuf, SourceFileVersion>;

fn default_cc() -> i_slint_compiler::CompilerConfiguration {
    i_slint_compiler::CompilerConfiguration::new(
        i_slint_compiler::generator::OutputFormat::Interpreter,
    )
}

/// This is i_slint_compiler::OpenImportCallback with version information
pub type OpenImportCallback = Rc<
    dyn Fn(
        String,
    )
        -> Pin<Box<dyn Future<Output = Option<std::io::Result<(SourceFileVersion, String)>>>>>,
>;

pub struct CompilerConfiguration {
    pub include_paths: Vec<std::path::PathBuf>,
    pub library_paths: HashMap<String, std::path::PathBuf>,
    pub style: Option<String>,
    pub open_import_callback: Option<OpenImportCallback>,
    pub resource_url_mapper:
        Option<Rc<dyn Fn(&str) -> Pin<Box<dyn Future<Output = Option<String>>>>>>,
    pub format: super::ByteFormat,
    /// Whether to enable experimental features.
    /// Note that the i_slint_compiler::CompilerConfiguration still reads the environment variable
    /// in native build, so this is used to transmit the value when compiled to WASM.
    pub enable_experimental: bool,
}

impl Default for CompilerConfiguration {
    fn default() -> Self {
        let mut cc = default_cc();

        Self {
            include_paths: std::mem::take(&mut cc.include_paths),
            library_paths: std::mem::take(&mut cc.library_paths),
            style: std::mem::take(&mut cc.style),
            open_import_callback: None,
            resource_url_mapper: std::mem::take(&mut cc.resource_url_mapper),
            format: super::ByteFormat::Utf8,
            enable_experimental: cc.enable_experimental,
        }
    }
}

impl CompilerConfiguration {
    fn build(mut self) -> (i_slint_compiler::CompilerConfiguration, Option<OpenImportCallback>) {
        let mut result = default_cc();
        result.include_paths = std::mem::take(&mut self.include_paths);
        result.library_paths = std::mem::take(&mut self.library_paths);
        result.style = std::mem::take(&mut self.style);
        result.resource_url_mapper = std::mem::take(&mut self.resource_url_mapper);
        result.enable_experimental |= self.enable_experimental;

        (result, self.open_import_callback)
    }
}

/// A cache of loaded documents
pub struct DocumentCache {
    type_loader: TypeLoader,
    open_import_callback: Option<OpenImportCallback>,
    source_file_versions: Rc<RefCell<SourceFileVersionMap>>,
    pub format: super::ByteFormat,
}

#[cfg(feature = "preview-engine")]
pub fn document_cache_parts_setup(
    compiler_config: &mut i_slint_compiler::CompilerConfiguration,
    open_import_callback: Option<OpenImportCallback>,
    initial_file_versions: SourceFileVersionMap,
) -> (Option<OpenImportCallback>, Rc<RefCell<SourceFileVersionMap>>) {
    let source_file_versions = Rc::new(RefCell::new(initial_file_versions));
    DocumentCache::wire_up_import_fallback(
        compiler_config,
        open_import_callback,
        source_file_versions,
    )
}

impl DocumentCache {
    fn wire_up_import_fallback(
        compiler_config: &mut i_slint_compiler::CompilerConfiguration,
        open_import_callback: Option<OpenImportCallback>,
        source_file_versions: Rc<RefCell<SourceFileVersionMap>>,
    ) -> (Option<OpenImportCallback>, Rc<RefCell<SourceFileVersionMap>>) {
        let source_versions = source_file_versions.clone();
        if let Some(open_import_callback) = open_import_callback.clone() {
            compiler_config.open_import_callback = Some(Rc::new(move |file_name: String| {
                let open_import = open_import_callback(file_name.clone());
                let source_versions = source_versions.clone();
                Box::pin(async move {
                    open_import.await.map(|r| {
                        let path = PathBuf::from(file_name);
                        match r {
                            Ok((v, c)) => {
                                source_versions.borrow_mut().insert(path, v);
                                Ok(c)
                            }
                            Err(e) => {
                                source_versions.borrow_mut().remove(&path);
                                Err(e)
                            }
                        }
                    })
                })
            }))
        }

        (open_import_callback, source_file_versions)
    }

    pub fn new(config: CompilerConfiguration) -> Self {
        let format = config.format;
        let (mut compiler_config, open_import_callback) = config.build();

        let (open_import_callback, source_file_versions) = Self::wire_up_import_fallback(
            &mut compiler_config,
            open_import_callback,
            Rc::new(RefCell::new(SourceFileVersionMap::default())),
        );

        Self {
            type_loader: TypeLoader::new(compiler_config, &mut BuildDiagnostics::default()),
            open_import_callback,
            source_file_versions,
            format,
        }
    }

    pub fn new_from_raw_parts(
        mut type_loader: TypeLoader,
        open_import_callback: Option<OpenImportCallback>,
        source_file_versions: Rc<RefCell<SourceFileVersionMap>>,
        format: super::ByteFormat,
    ) -> Self {
        let (open_import_callback, source_file_versions) = Self::wire_up_import_fallback(
            &mut type_loader.compiler_config,
            open_import_callback,
            source_file_versions,
        );

        Self { type_loader, open_import_callback, source_file_versions, format }
    }

    pub fn snapshot(&self) -> Option<Self> {
        let open_import_callback = self.open_import_callback.clone();
        let source_file_versions =
            Rc::new(RefCell::new(self.source_file_versions.borrow().clone()));
        i_slint_compiler::typeloader::snapshot(&self.type_loader).map(|tl| {
            Self::new_from_raw_parts(tl, open_import_callback, source_file_versions, self.format)
        })
    }

    pub fn resolve_import_path(
        &self,
        import_token: Option<&i_slint_compiler::parser::NodeOrToken>,
        maybe_relative_path_or_url: &str,
    ) -> Option<(PathBuf, Option<&'static [u8]>)> {
        self.type_loader.resolve_import_path(import_token, maybe_relative_path_or_url)
    }

    pub fn document_version(&self, target_uri: &Url) -> SourceFileVersion {
        self.document_version_by_path(&uri_to_file(target_uri).unwrap_or_default())
    }

    pub fn document_version_by_path(&self, path: &Path) -> SourceFileVersion {
        self.source_file_versions.borrow().get(path).and_then(|v| *v)
    }

    pub fn get_document<'a>(&'a self, url: &'_ Url) -> Option<&'a Document> {
        let path = uri_to_file(url)?;
        self.type_loader.get_document(&path)
    }

    fn uses_widgets_impl(&self, doc_path: PathBuf, dedup: &mut HashSet<PathBuf>) -> bool {
        if dedup.contains(&doc_path) {
            return false;
        }

        if doc_path.starts_with("builtin:/") && doc_path.ends_with("std-widgets.slint") {
            return true;
        }

        let Some(doc) = self.get_document_by_path(&doc_path) else {
            return false;
        };

        dedup.insert(doc_path.to_path_buf());

        for import in doc.imports.iter().map(|i| PathBuf::from(&i.file)) {
            if self.uses_widgets_impl(import, dedup) {
                return true;
            }
        }

        false
    }

    /// Returns true if doc_url uses (possibly indirectly) widgets from "std-widgets.slint"
    pub fn uses_widgets(&self, doc_url: &Url) -> bool {
        let Some(doc_path) = uri_to_file(doc_url) else {
            return false;
        };

        let mut dedup = HashSet::new();

        self.uses_widgets_impl(doc_path, &mut dedup)
    }

    pub fn get_document_by_path<'a>(&'a self, path: &'_ Path) -> Option<&'a Document> {
        self.type_loader.get_document(path)
    }

    pub fn get_document_for_source_file<'a>(
        &'a self,
        source_file: &'_ SourceFile,
    ) -> Option<&'a Document> {
        self.type_loader.get_document(source_file.path())
    }

    pub fn get_document_and_offset<'a>(
        &'a self,
        text_document_uri: &'_ Url,
        pos: &'_ lsp_types::Position,
    ) -> Option<(&'a i_slint_compiler::object_tree::Document, TextSize)> {
        let doc = self.get_document(text_document_uri)?;
        let o = (doc.node.as_ref()?.source_file.offset(
            pos.line as usize + 1,
            pos.character as usize + 1,
            self.format,
        ) as u32)
            .into();
        doc.node.as_ref()?.text_range().contains_inclusive(o).then_some((doc, o))
    }

    pub fn all_url_documents(&self) -> impl Iterator<Item = (Url, &syntax_nodes::Document)> + '_ {
        self.type_loader.all_file_documents().filter_map(|(p, d)| Some((file_to_uri(p)?, d)))
    }

    pub fn all_urls(&self) -> impl Iterator<Item = Url> + '_ {
        self.type_loader.all_files().filter_map(|p| file_to_uri(p))
    }

    pub fn global_type_registry(&self) -> std::cell::Ref<'_, TypeRegister> {
        self.type_loader.global_type_registry.borrow()
    }

    fn invalidate_everything(&mut self) {
        let all_files = self.type_loader.all_files().cloned().collect::<Vec<_>>();

        for path in all_files {
            self.type_loader.invalidate_document(&path);
        }
    }

    /// Apply a new configuration to the document cache
    ///
    /// This will invalidate and reload all loaded documents.
    ///
    /// Returns the new compiler configuration and the set of paths that were reloaded.
    pub async fn reconfigure(
        &mut self,
        style: Option<String>,
        include_paths: Option<Vec<PathBuf>>,
        library_paths: Option<HashMap<String, PathBuf>>,
        enable_experimental: bool,
        diag: &mut BuildDiagnostics,
    ) -> (CompilerConfiguration, HashSet<lsp_types::Url>) {
        if let Some(s) = style {
            if s.is_empty() {
                self.type_loader.compiler_config.style = None;
            } else {
                self.type_loader.compiler_config.style = Some(s);
            }
        }

        if let Some(ip) = include_paths {
            self.type_loader.compiler_config.include_paths = ip;
        }

        if let Some(lp) = library_paths {
            self.type_loader.compiler_config.library_paths = lp;
        }

        if enable_experimental && !self.type_loader.compiler_config.enable_experimental {
            self.type_loader.compiler_config.enable_experimental = true;
            *self.type_loader.global_type_registry.borrow_mut() =
                Rc::into_inner(TypeRegister::builtin_experimental()).unwrap().into_inner();
        }

        self.invalidate_everything();

        self.preload_builtins().await;

        let all_urls = self.all_urls().collect::<HashSet<_>>();
        for url in &all_urls {
            self.reload_cached_file(url, diag).await;
        }

        (self.compiler_configuration(), all_urls)
    }

    pub async fn preload_builtins(&mut self) {
        // Always load the widgets so we can auto-complete them
        let mut diag = BuildDiagnostics::default();
        self.type_loader.import_component("std-widgets.slint", "StyleMetrics", &mut diag).await;
        assert!(!diag.has_errors());
    }

    pub async fn load_url(
        &mut self,
        url: &Url,
        version: SourceFileVersion,
        content: String,
        diag: &mut BuildDiagnostics,
    ) -> Result<()> {
        let path =
            uri_to_file(url).ok_or_else(|| format!("Failed to convert path for loading: {url}"))?;
        self.type_loader.load_file(&path, &path, content, false, diag).await;
        self.source_file_versions.borrow_mut().insert(path, version);
        Ok(())
    }

    pub async fn reload_cached_file(&mut self, url: &Url, diag: &mut BuildDiagnostics) {
        let Some(path) = uri_to_file(url) else { return };
        self.type_loader.reload_cached_file(&path, diag).await;
    }

    /// Drop a document from the cache.
    /// Returns the list of dependencies that were invalidated.
    ///
    /// Compared to [Self::invalidate_url], this actually causes the document to be reloaded from
    /// disk, not just reparsed.
    pub fn drop_document(&mut self, url: &Url) -> Result<HashSet<Url>> {
        let Some(path) = uri_to_file(url) else {
            // This isn't fatal, but we might want to learn about paths/schemes to support in the future.
            tracing::error!("Failed to convert path for dropping document: {url}");
            return Ok(Default::default());
        };
        Ok(self
            .type_loader
            .drop_document(&path)?
            .iter()
            .filter_map(|path| file_to_uri(path))
            .collect())
    }

    /// Invalidate a document and all its dependencies.
    /// return the list of dependencies that were invalidated.
    ///
    /// Compared to [Self::drop_document], the CST remains in the cache, and only the type
    /// information is dropped from the cache, which causes the document to be re-analyzed.
    pub fn invalidate_url(&mut self, url: &Url) -> HashSet<Url> {
        let Some(path) = uri_to_file(url) else { return HashSet::new() };
        self.type_loader
            .invalidate_document(&path)
            .into_iter()
            .filter_map(|x| file_to_uri(&x))
            .collect()
    }

    pub fn compiler_configuration(&self) -> CompilerConfiguration {
        CompilerConfiguration {
            include_paths: self.type_loader.compiler_config.include_paths.clone(),
            library_paths: self.type_loader.compiler_config.library_paths.clone(),
            style: self.type_loader.compiler_config.style.clone(),
            open_import_callback: None, // We need to re-generate this anyway
            resource_url_mapper: self.type_loader.compiler_config.resource_url_mapper.clone(),
            format: self.format,
            enable_experimental: self.type_loader.compiler_config.enable_experimental,
        }
    }

    fn element_at_document_and_offset(
        &self,
        document: &i_slint_compiler::object_tree::Document,
        offset: TextSize,
    ) -> Option<ElementRcNode> {
        fn element_contains(
            element: &i_slint_compiler::object_tree::ElementRc,
            offset: TextSize,
        ) -> Option<usize> {
            element
                .borrow()
                .debug
                .iter()
                .position(|n| n.node.parent().is_some_and(|n| n.text_range().contains(offset)))
        }

        for component in &document.inner_components {
            let root_element = component.root_element.clone();
            let Some(root_debug_index) = element_contains(&root_element, offset) else {
                continue;
            };

            let mut element =
                ElementRcNode { element: root_element, debug_index: root_debug_index };
            while element.contains_offset(offset) {
                if let Some((c, i)) = element
                    .element
                    .clone()
                    .borrow()
                    .children
                    .iter()
                    .find_map(|c| element_contains(c, offset).map(|i| (c, i)))
                {
                    element = ElementRcNode { element: c.clone(), debug_index: i };
                } else {
                    return Some(element);
                }
            }
        }
        None
    }

    pub fn element_at_offset(
        &self,
        text_document_uri: &Url,
        offset: TextSize,
    ) -> Option<ElementRcNode> {
        let doc = self.get_document(text_document_uri)?;
        self.element_at_document_and_offset(doc, offset)
    }

    pub fn element_at_position(
        &self,
        text_document_uri: &Url,
        pos: &lsp_types::Position,
    ) -> Option<ElementRcNode> {
        let (doc, offset) = self.get_document_and_offset(text_document_uri, pos)?;
        self.element_at_document_and_offset(doc, offset)
    }
}

#[cfg(test)]
mod tests {
    use crate::language::test::complex_document_cache;

    use super::*;

    fn id_at_position(dc: &DocumentCache, url: &Url, line: u32, character: u32) -> Option<String> {
        let result = dc.element_at_position(url, &lsp_types::Position { line, character })?;
        let element = result.element.borrow();
        Some(element.id.to_string())
    }

    fn base_type_at_position(
        dc: &DocumentCache,
        url: &Url,
        line: u32,
        character: u32,
    ) -> Option<String> {
        let result = dc.element_at_position(url, &lsp_types::Position { line, character })?;
        let element = result.element.borrow();
        Some(format!("{}", &element.base_type))
    }

    #[test]
    fn test_element_at_position_no_element() {
        let (dc, url, _) = complex_document_cache();
        assert_eq!(id_at_position(&dc, &url, 0, 10), None);
        // TODO: This is past the end of the line and should thus return None
        assert_eq!(id_at_position(&dc, &url, 42, 90), Some(String::new()));
        assert_eq!(id_at_position(&dc, &url, 1, 0), None);
        assert_eq!(id_at_position(&dc, &url, 55, 1), None);
        assert_eq!(id_at_position(&dc, &url, 56, 5), None);
    }

    #[test]
    fn test_document_version() {
        let (dc, url, _) = complex_document_cache();
        assert_eq!(dc.document_version(&url), Some(42));
    }

    #[test]
    fn test_element_at_position_no_such_document() {
        let (dc, _, _) = complex_document_cache();
        assert_eq!(id_at_position(&dc, &Url::parse("https://foo.bar/baz").unwrap(), 5, 0), None);
    }

    #[test]
    fn test_element_at_position_root() {
        let (dc, url, _) = complex_document_cache();

        assert_eq!(id_at_position(&dc, &url, 2, 30), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 2, 32), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 2, 42), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 3, 0), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 3, 53), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 4, 19), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 5, 0), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 6, 8), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 6, 15), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 6, 23), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 8, 15), Some("root".to_string()));
        assert_eq!(id_at_position(&dc, &url, 12, 3), Some("root".to_string())); // right before child // TODO: Seems wrong!
        assert_eq!(id_at_position(&dc, &url, 51, 5), Some("root".to_string())); // right after child // TODO: Why does this not work?
        assert_eq!(id_at_position(&dc, &url, 52, 0), Some("root".to_string()));
    }

    #[test]
    fn test_element_at_position_child() {
        let (dc, url, _) = complex_document_cache();

        assert_eq!(base_type_at_position(&dc, &url, 12, 4), Some("VerticalBox".to_string()));
        assert_eq!(base_type_at_position(&dc, &url, 14, 22), Some("HorizontalBox".to_string()));
        assert_eq!(base_type_at_position(&dc, &url, 15, 33), Some("Text".to_string()));
        assert_eq!(base_type_at_position(&dc, &url, 27, 4), Some("VerticalBox".to_string()));
        assert_eq!(base_type_at_position(&dc, &url, 28, 8), Some("Text".to_string()));
        assert_eq!(base_type_at_position(&dc, &url, 51, 4), Some("VerticalBox".to_string()));
    }
}