]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/snippet.rs
Improve user snippet import performance
[rust.git] / crates / ide_completion / src / snippet.rs
1 //! User (postfix)-snippet definitions.
2 //!
3 //! Actual logic is implemented in [`crate::completions::postfix`] and [`crate::completions::snippet`] respectively.
4
5 use std::ops::Deref;
6
7 // Feature: User Snippet Completions
8 //
9 // rust-analyzer allows the user to define custom (postfix)-snippets that may depend on items to be accessible for the current scope to be applicable.
10 //
11 // A custom snippet can be defined by adding it to the `rust-analyzer.completion.snippets` object respectively.
12 //
13 // [source,json]
14 // ----
15 // {
16 //   "rust-analyzer.completion.snippets": {
17 //     "thread spawn": {
18 //       "prefix": ["spawn", "tspawn"],
19 //       "body": [
20 //         "thread::spawn(move || {",
21 //         "\t$0",
22 //         ")};",
23 //       ],
24 //       "description": "Insert a thread::spawn call",
25 //       "requires": "std::thread",
26 //       "scope": "expr",
27 //     }
28 //   }
29 // }
30 // ----
31 //
32 // In the example above:
33 //
34 // * `"thread spawn"` is the name of the snippet.
35 //
36 // * `prefix` defines one or more trigger words that will trigger the snippets completion.
37 // Using `postfix` will instead create a postfix snippet.
38 //
39 // * `body` is one or more lines of content joined via newlines for the final output.
40 //
41 // * `description` is an optional description of the snippet, if unset the snippet name will be used.
42 //
43 // * `requires` is an optional list of item paths that have to be resolvable in the current crate where the completion is rendered.
44 // On failure of resolution the snippet won't be applicable, otherwise the snippet will insert an import for the items on insertion if
45 // the items aren't yet in scope.
46 //
47 // * `scope` is an optional filter for when the snippet should be applicable. Possible values are:
48 // ** for Snippet-Scopes: `expr`, `item` (default: `item`)
49 // ** for Postfix-Snippet-Scopes: `expr`, `type` (default: `expr`)
50 //
51 // The `body` field also has access to placeholders as visible in the example as `$0`.
52 // These placeholders take the form of `$number` or `${number:placeholder_text}` which can be traversed as tabstop in ascending order starting from 1,
53 // with `$0` being a special case that always comes last.
54 //
55 // There is also a special placeholder, `${receiver}`, which will be replaced by the receiver expression for postfix snippets, or nothing in case of normal snippets.
56 // It does not act as a tabstop.
57 use ide_db::helpers::{import_assets::LocatedImport, insert_use::ImportScope};
58 use itertools::Itertools;
59 use syntax::{ast, AstNode, GreenNode, SyntaxNode};
60
61 use crate::{context::CompletionContext, ImportEdit};
62
63 /// A snippet scope describing where a snippet may apply to.
64 /// These may differ slightly in meaning depending on the snippet trigger.
65 #[derive(Clone, Debug, PartialEq, Eq)]
66 pub enum SnippetScope {
67     Item,
68     Expr,
69     Type,
70 }
71
72 /// A user supplied snippet.
73 #[derive(Clone, Debug, PartialEq, Eq)]
74 pub struct Snippet {
75     pub postfix_triggers: Box<[Box<str>]>,
76     pub prefix_triggers: Box<[Box<str>]>,
77     pub scope: SnippetScope,
78     pub description: Option<Box<str>>,
79     snippet: String,
80     // These are `ast::Path`'s but due to SyntaxNodes not being Send we store these
81     // and reconstruct them on demand instead. This is cheaper than reparsing them
82     // from strings
83     requires: Box<[GreenNode]>,
84 }
85
86 impl Snippet {
87     pub fn new(
88         prefix_triggers: &[String],
89         postfix_triggers: &[String],
90         snippet: &[String],
91         description: &str,
92         requires: &[String],
93         scope: SnippetScope,
94     ) -> Option<Self> {
95         if prefix_triggers.is_empty() && postfix_triggers.is_empty() {
96             return None;
97         }
98         let (requires, snippet, description) = validate_snippet(snippet, description, requires)?;
99         Some(Snippet {
100             // Box::into doesn't work as that has a Copy bound ðŸ˜’
101             postfix_triggers: postfix_triggers.iter().map(Deref::deref).map(Into::into).collect(),
102             prefix_triggers: prefix_triggers.iter().map(Deref::deref).map(Into::into).collect(),
103             scope,
104             snippet,
105             description,
106             requires,
107         })
108     }
109
110     /// Returns [`None`] if the required items do not resolve.
111     pub(crate) fn imports(
112         &self,
113         ctx: &CompletionContext,
114         import_scope: &ImportScope,
115     ) -> Option<Vec<ImportEdit>> {
116         import_edits(ctx, import_scope, &self.requires)
117     }
118
119     pub fn snippet(&self) -> String {
120         self.snippet.replace("${receiver}", "")
121     }
122
123     pub fn postfix_snippet(&self, receiver: &str) -> String {
124         self.snippet.replace("${receiver}", receiver)
125     }
126 }
127
128 fn import_edits(
129     ctx: &CompletionContext,
130     import_scope: &ImportScope,
131     requires: &[GreenNode],
132 ) -> Option<Vec<ImportEdit>> {
133     let resolve = |import: &GreenNode| {
134         let path = ast::Path::cast(SyntaxNode::new_root(import.clone()))?;
135         let item = match ctx.scope.speculative_resolve(&path)? {
136             hir::PathResolution::Macro(mac) => mac.into(),
137             hir::PathResolution::Def(def) => def.into(),
138             _ => return None,
139         };
140         let path = ctx.scope.module()?.find_use_path_prefixed(
141             ctx.db,
142             item,
143             ctx.config.insert_use.prefix_kind,
144         )?;
145         Some((path.len() > 1).then(|| ImportEdit {
146             import: LocatedImport::new(path.clone(), item, item, None),
147             scope: import_scope.clone(),
148         }))
149     };
150     let mut res = Vec::with_capacity(requires.len());
151     for import in requires {
152         match resolve(import) {
153             Some(first) => res.extend(first),
154             None => return None,
155         }
156     }
157     Some(res)
158 }
159
160 fn validate_snippet(
161     snippet: &[String],
162     description: &str,
163     requires: &[String],
164 ) -> Option<(Box<[GreenNode]>, String, Option<Box<str>>)> {
165     let mut imports = Vec::with_capacity(requires.len());
166     for path in requires.iter() {
167         let path = ast::Path::parse(path).ok()?;
168         let valid_use_path = path.segments().all(|seg| {
169             matches!(seg.kind(), Some(ast::PathSegmentKind::Name(_)))
170                 || seg.generic_arg_list().is_none()
171         });
172         if !valid_use_path {
173             return None;
174         }
175         let green = path.syntax().green().into_owned();
176         imports.push(green);
177     }
178     let snippet = snippet.iter().join("\n");
179     let description = if description.is_empty() { None } else { Some(description.into()) };
180     Some((imports.into_boxed_slice(), snippet, description))
181 }