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
// 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

use crate::common::{
    self,
    token_info::{TokenInfo, token_info},
};
use crate::util;
use i_slint_compiler::langtype::{ElementType, Type};
use i_slint_compiler::object_tree::ElementRc;
use i_slint_compiler::parser::{SyntaxKind, SyntaxNode, SyntaxToken};
use itertools::Itertools as _;
use lsp_types::{Hover, HoverContents, MarkupContent};

pub fn get_tooltip(
    document_cache: &mut common::DocumentCache,
    token: SyntaxToken,
) -> Option<Hover> {
    let token_info = token_info(document_cache, token.clone())?;
    let documentation = token_info.declaration().and_then(|x| extract_documentation(&x));
    let documentation = documentation.as_deref();
    let contents = match token_info {
        TokenInfo::Type(ty) => match ty {
            Type::Enumeration(e) => from_slint_code(&format!("enum {}", e.name), documentation),
            Type::Struct(s) if s.name.is_some() => {
                from_slint_code(&format!("struct {}", s.name.slint_name().unwrap()), documentation)
            }
            _ => from_plain_text(ty.to_string()),
        },
        TokenInfo::ElementType(e) => match e {
            ElementType::Component(c) => {
                if c.is_global() {
                    from_slint_code(&format!("global {}", c.id), documentation)
                } else {
                    from_slint_code(&format!("component {}", c.id), documentation)
                }
            }
            ElementType::Builtin(b) => from_plain_text(format!("{} (builtin)", b.name)),
            _ => return None,
        },
        TokenInfo::ElementRc(e) => {
            let e = e.borrow();
            let component = &e.enclosing_component.upgrade().unwrap();
            if component.is_global() {
                from_slint_code(&format!("global {}", component.id), documentation)
            } else if e.id.is_empty() {
                from_slint_code(&format!("{} {{ /*...*/ }}", e.base_type), documentation)
            } else {
                from_slint_code(
                    &format!("{} := {} {{ /*...*/ }}", e.id, e.base_type),
                    documentation,
                )
            }
        }
        TokenInfo::NamedReference(nr) => {
            from_property_in_element(&nr.element(), nr.name(), documentation)?
        }
        TokenInfo::EnumerationValue(v) => {
            from_slint_code(&format!("{}.{}", v.enumeration.name, v), documentation)
        }
        TokenInfo::FileName(path) => MarkupContent {
            kind: lsp_types::MarkupKind::Markdown,
            value: format!("`{}`", path.to_string_lossy()),
        },
        TokenInfo::Image(path) => MarkupContent {
            kind: lsp_types::MarkupKind::Markdown,
            value: format!("![{0}]({0})", path.to_string_lossy()),
        },
        // Todo: this can happen when there is some syntax error
        TokenInfo::LocalProperty(_) | TokenInfo::LocalCallback(_) | TokenInfo::LocalFunction(_) => {
            return None;
        }
        TokenInfo::IncompleteNamedReference(el, name) => {
            from_property_in_type(&el, &name, documentation)?
        }
    };

    Some(Hover {
        contents: HoverContents::Markup(contents),
        range: Some(util::token_to_lsp_range(&token, document_cache.format)),
    })
}

// Given a token that declares something, find a comment before that token that could be a documentation for this
fn extract_documentation(declaration: &SyntaxNode) -> Option<String> {
    let mut token = declaration.first_token()?;
    // Loop back to find the the previous line \n
    loop {
        if token.kind() == SyntaxKind::Whitespace {
            let mut ln = token.text().bytes().filter(|c| *c == b'\n');
            // One \n
            if ln.next().is_some() {
                // Two \n
                if ln.next().is_some() {
                    return None;
                }
                token = token.prev_token()?;
                break;
            }
        }
        token = token.prev_token()?;
    }

    // find the comment
    let mut result = String::new();
    while token.kind() == SyntaxKind::Comment {
        let text = token.text().to_string();
        token = if let Some(token) = token.prev_token() { token } else { break };
        if token.kind() == SyntaxKind::Whitespace {
            let mut ln = token.text().bytes().filter(|c| *c == b'\n');
            // One \n
            if ln.next().is_some() {
                result = format!("{}{text}{result}", token.text());
                // Two \n
                if ln.next().is_some() {
                    break;
                }
                token = if let Some(token) = token.prev_token() { token } else { break };
                continue;
            }
        }
        break;
    }

    if result.is_empty() {
        return None;
    }

    // De-ident the comment
    let indentation_size =
        result.lines().filter_map(|x| x.find(|x| x != ' ' && x != '\t')).min()?;
    let mut result2 = String::new();
    for line in result.lines().skip_while(|p| p.trim().is_empty()) {
        if line.len() > indentation_size {
            result2.push_str(line[indentation_size..].trim_end());
        }
        result2.push('\n');
    }
    if result2.ends_with("\n\n") {
        result2.pop(); // remove the last newline
    }
    Some(result2)
}

fn from_property_in_element(
    element: &ElementRc,
    name: &str,
    documentation: Option<&str>,
) -> Option<MarkupContent> {
    if let Some(decl) = element.borrow().property_declarations.get(name) {
        return property_tooltip(
            &decl.property_type,
            name,
            decl.pure.unwrap_or(false),
            documentation,
        );
    }
    from_property_in_type(&element.borrow().base_type, name, documentation)
}

fn from_property_in_type(
    base: &ElementType,
    name: &str,
    documentation: Option<&str>,
) -> Option<MarkupContent> {
    match base {
        ElementType::Component(c) => from_property_in_element(&c.root_element, name, documentation),
        ElementType::Builtin(b) => {
            let resolved_name = b.native_class.lookup_alias(name).unwrap_or(name);
            let info = b.properties.get(resolved_name)?;
            property_tooltip(&info.ty, name, false, documentation)
        }
        _ => None,
    }
}

fn property_tooltip(
    ty: &Type,
    name: &str,
    pure: bool,
    documentation: Option<&str>,
) -> Option<MarkupContent> {
    let pure = if pure { "pure " } else { "" };
    if let Type::Callback(callback) = ty {
        let sig = signature_from_function_ty(callback);
        Some(from_slint_code(&format!("{pure}callback {name}{sig}"), documentation))
    } else if let Type::Function(function) = &ty {
        let sig = signature_from_function_ty(function);
        Some(from_slint_code(&format!("{pure}function {name}{sig}"), documentation))
    } else if ty.is_property_type() {
        Some(from_slint_code(&format!("property <{ty}> {name}"), documentation))
    } else {
        None
    }
}

fn signature_from_function_ty(f: &i_slint_compiler::langtype::Function) -> String {
    let ret = if matches!(f.return_type, Type::Void) {
        String::new()
    } else {
        format!(" -> {}", f.return_type)
    };
    let args = f
        .args
        .iter()
        .zip(f.arg_names.iter().chain(std::iter::repeat(&Default::default())))
        .filter(|(x, _)| *x != &Type::ElementReference)
        .map(|(ty, name)| if !name.is_empty() { format!("{name}: {ty}") } else { ty.to_string() })
        .join(", ");
    format!("({args}){ret}")
}

fn from_plain_text(value: String) -> MarkupContent {
    MarkupContent { kind: lsp_types::MarkupKind::PlainText, value }
}

fn from_slint_code(value: &str, documentation: Option<&str>) -> MarkupContent {
    let documentation = documentation.unwrap_or("");
    MarkupContent {
        kind: lsp_types::MarkupKind::Markdown,
        value: format!("```slint\n{documentation}{value}\n```"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use i_slint_compiler::parser::TextSize;

    #[test]
    fn test_tooltip() {
        let source = r#"
import { StandardTableView } from "std-widgets.slint";

/// Docs for
/// the Glob global
global Glob {
  in-out property <{a:int,b:float}> hello_world;
  // not docs

  callback cb(string, int) -> [int];
  /** The fn_glob function */
  public pure
  function fn_glob(abc: int) {}
}

/// TA is a component
component TA inherits TouchArea { // not docs
  in property <string> hello; // not docs
  /** Docs for
   * the xyz callback
   */
  callback xyz(string, int);
  /*not docs */ pure callback www;
}
/// Here some docs for Eee
enum Eee { E1, E2, E3 }
export component Test { // not docs
  // root-prop is a property
  property <string> root-prop;
  function fn_loc() -> int { 42 }
  the-ta := TA {
      property<int> local-prop: root-prop.to-float();
      hello: Glob.hello_world.a;
      xyz(abc, def) => {
         self.www();
         self.enabled = false;
         Glob.fn_glob(local-prop);
         Glob.cb("xxx", 45);
         root.fn_loc();
      }
      property <Eee> e: Eee.E2;
      pointer-event(aaa) => {}
  }
  Rectangle {
    background: red;
    border-color: self.background;
  }
  StandardTableView {
    row-pointer-event => { }
  }
  Image {
      source: @image-url("assets/unix-test.png");
  }
  Image {
      source: @image-url("assets\\windows-test.png");
  }
}"#;
        let (mut dc, uri, _) = crate::language::test::loaded_document_cache(source.into());
        let doc = dc.get_document(&uri).unwrap().node.clone().unwrap();

        let find_tk = |needle: &str, offset: TextSize| {
            crate::language::token_at_offset(
                &doc,
                TextSize::new(
                    source.find(needle).unwrap_or_else(|| panic!("'{needle}' not found")) as u32,
                ) + offset,
            )
            .unwrap()
        };

        #[track_caller]
        fn assert_tooltip(h: Option<Hover>, str: &str) {
            match h.unwrap().contents {
                HoverContents::Markup(m) => assert_eq!(m.value, str),
                x => panic!("Found {x:?} ({str})"),
            }
        }

        // properties
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("hello: Glob", 0.into())),
            "```slint\nproperty <string> hello\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("Glob.hello_world", 8.into())),
            "```slint\nproperty <{ a: int,b: float,}> hello-world\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("self.enabled", 5.into())),
            "```slint\nproperty <bool> enabled\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("fn_glob(local-prop)", 10.into())),
            "```slint\nproperty <int> local-prop\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("root-prop.to-float", 1.into())),
            "```slint\n// root-prop is a property\nproperty <string> root-prop\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("background: red", 0.into())),
            "```slint\nproperty <brush> background\n```",
        );
        // callbacks
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("self.www", 5.into())),
            "```slint\npure callback www()\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("xyz(abc", 0.into())),
            "```slint\n/** Docs for\n * the xyz callback\n */\ncallback xyz(string, int)\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("Glob.cb(", 6.into())),
            "```slint\ncallback cb(string, int) -> [int]\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("row-pointer-event", 0.into())),
            "```slint\ncallback row-pointer-event(row: int, event: PointerEvent, position: Point)\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("pointer-event", 5.into())),
            "```slint\ncallback pointer-event(event: PointerEvent)\n```",
        );
        // functions
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("fn_glob(local-prop)", 1.into())),
            "```slint\n/** The fn_glob function */\npure function fn-glob(abc: int)\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("root.fn_loc", 8.into())),
            "```slint\nfunction fn-loc() -> int\n```",
        );
        // elements
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("self.enabled", 0.into())),
            "```slint\nthe-ta := TA { /*...*/ }\n```",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("self.background", 0.into())),
            "```slint\nRectangle { /*...*/ }\n```",
        );
        // global
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("hello: Glob", 8.into())),
            "```slint\n/// Docs for\n/// the Glob global\nglobal Glob\n```",
        );

        //components
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("Rectangle {", 8.into())),
            "Rectangle (builtin)",
        );
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("the-ta := TA {", 11.into())),
            "```slint\n/// TA is a component\ncomponent TA\n```",
        );

        // @image-url
        let target_path = uri
            .join("assets/unix-test.png")
            .unwrap()
            .to_file_path()
            .unwrap()
            .to_string_lossy()
            .to_string();
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("\"assets/unix-test.png\"", 15.into())),
            &format!("![{target_path}]({target_path})"),
        );

        // @image-url
        let target_path = uri
            .join("assets/windows-test.png")
            .unwrap()
            .to_file_path()
            .unwrap()
            .to_string_lossy()
            .to_string();
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("\"assets\\\\windows-test.png\"", 15.into())),
            &format!("![{target_path}]({target_path})"),
        );

        // enums
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("Eee.E2", 0.into())),
            "```slint\n/// Here some docs for Eee\nenum Eee\n```",
        );
        // FIXME: We get the comments for the enum instead of the value
        assert_tooltip(
            get_tooltip(&mut dc, find_tk("Eee.E2", 5.into())),
            "```slint\n/// Here some docs for Eee\nEee.E2\n```",
        );
    }
}