Unnamed repository; edit this file 'description' to name the repository.
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
use ide_db::helpers::{import_assets::LocatedImport, insert_use::ImportScope};
use itertools::Itertools;
use syntax::ast;

use crate::{context::CompletionContext, ImportEdit};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PostfixSnippetScope {
    Expr,
    Type,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SnippetScope {
    Item,
    Expr,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PostfixSnippet {
    pub scope: PostfixSnippetScope,
    pub label: String,
    snippet: String,
    pub description: Option<String>,
    pub requires: Box<[String]>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Snippet {
    pub scope: SnippetScope,
    pub label: String,
    pub snippet: String,
    pub description: Option<String>,
    pub requires: Box<[String]>,
}

impl Snippet {
    pub fn new(
        label: String,
        snippet: &[String],
        description: &[String],
        requires: &[String],
        scope: SnippetScope,
    ) -> Option<Self> {
        // validate that these are indeed simple paths
        if requires.iter().any(|path| match ast::Path::parse(path) {
            Ok(path) => path.segments().any(|seg| {
                !matches!(seg.kind(), Some(ast::PathSegmentKind::Name(_)))
                    || seg.generic_arg_list().is_some()
            }),
            Err(_) => true,
        }) {
            return None;
        }
        let snippet = snippet.iter().join("\n");
        let description = description.iter().join("\n");
        let description = if description.is_empty() { None } else { Some(description) };
        Some(Snippet {
            scope,
            label,
            snippet,
            description,
            requires: requires.iter().cloned().collect(), // Box::into doesn't work as that has a Copy bound 😒
        })
    }

    // FIXME: This shouldn't be fallible
    pub(crate) fn imports(
        &self,
        ctx: &CompletionContext,
        import_scope: &ImportScope,
    ) -> Result<Vec<ImportEdit>, ()> {
        import_edits(ctx, import_scope, &self.requires)
    }

    pub fn is_item(&self) -> bool {
        self.scope == SnippetScope::Item
    }

    pub fn is_expr(&self) -> bool {
        self.scope == SnippetScope::Expr
    }
}

impl PostfixSnippet {
    pub fn new(
        label: String,
        snippet: &[String],
        description: &[String],
        requires: &[String],
        scope: PostfixSnippetScope,
    ) -> Option<Self> {
        // validate that these are indeed simple paths
        if requires.iter().any(|path| match ast::Path::parse(path) {
            Ok(path) => path.segments().any(|seg| {
                !matches!(seg.kind(), Some(ast::PathSegmentKind::Name(_)))
                    || seg.generic_arg_list().is_some()
            }),
            Err(_) => true,
        }) {
            return None;
        }
        let snippet = snippet.iter().join("\n");
        let description = description.iter().join("\n");
        let description = if description.is_empty() { None } else { Some(description) };
        Some(PostfixSnippet {
            scope,
            label,
            snippet,
            description,
            requires: requires.iter().cloned().collect(), // Box::into doesn't work as that has a Copy bound 😒
        })
    }

    // FIXME: This shouldn't be fallible
    pub(crate) fn imports(
        &self,
        ctx: &CompletionContext,
        import_scope: &ImportScope,
    ) -> Result<Vec<ImportEdit>, ()> {
        import_edits(ctx, import_scope, &self.requires)
    }

    pub fn snippet(&self, receiver: &str) -> String {
        self.snippet.replace("$receiver", receiver)
    }

    pub fn is_item(&self) -> bool {
        self.scope == PostfixSnippetScope::Type
    }

    pub fn is_expr(&self) -> bool {
        self.scope == PostfixSnippetScope::Expr
    }
}

fn import_edits(
    ctx: &CompletionContext,
    import_scope: &ImportScope,
    requires: &[String],
) -> Result<Vec<ImportEdit>, ()> {
    let resolve = |import| {
        let path = ast::Path::parse(import).ok()?;
        match ctx.scope.speculative_resolve(&path)? {
            hir::PathResolution::Macro(_) => None,
            hir::PathResolution::Def(def) => {
                let item = def.into();
                let path = ctx.scope.module()?.find_use_path_prefixed(
                    ctx.db,
                    item,
                    ctx.config.insert_use.prefix_kind,
                )?;
                Some((path.len() > 1).then(|| ImportEdit {
                    import: LocatedImport::new(path.clone(), item, item, None),
                    scope: import_scope.clone(),
                }))
            }
            _ => None,
        }
    };
    let mut res = Vec::with_capacity(requires.len());
    for import in requires {
        match resolve(import) {
            Some(first) => res.extend(first),
            None => return Err(()),
        }
    }
    Ok(res)
}