ide/inlay_hints/
implicit_drop.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
//! Implementation of "implicit drop" inlay hints:
//! ```ignore
//! let x = vec![2];
//! if some_condition() {
//!     /* drop(x) */return;
//! }
//! ```
use hir::{
    db::{DefDatabase as _, HirDatabase as _},
    mir::{MirSpan, TerminatorKind},
    ChalkTyInterner, DefWithBody,
};
use ide_db::{famous_defs::FamousDefs, FileRange};

use span::EditionedFileId;
use syntax::{
    ast::{self, AstNode},
    match_ast, ToSmolStr,
};

use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind};

pub(super) fn hints(
    acc: &mut Vec<InlayHint>,
    FamousDefs(sema, _): &FamousDefs<'_, '_>,
    config: &InlayHintsConfig,
    file_id: EditionedFileId,
    node: &ast::Fn,
) -> Option<()> {
    if !config.implicit_drop_hints {
        return None;
    }

    let def = sema.to_def(node)?;
    let def: DefWithBody = def.into();

    let (hir, source_map) = sema.db.body_with_source_map(def.into());

    let mir = sema.db.mir_body(def.into()).ok()?;

    let local_to_binding = mir.local_to_binding_map();

    for (_, bb) in mir.basic_blocks.iter() {
        let terminator = bb.terminator.as_ref()?;
        if let TerminatorKind::Drop { place, .. } = terminator.kind {
            if !place.projection.is_empty() {
                continue; // Ignore complex cases for now
            }
            if mir.locals[place.local].ty.adt_id(ChalkTyInterner).is_none() {
                continue; // Arguably only ADTs have significant drop impls
            }
            let Some(binding) = local_to_binding.get(place.local) else {
                continue; // Ignore temporary values
            };
            let range = match terminator.span {
                MirSpan::ExprId(e) => match source_map.expr_syntax(e) {
                    Ok(s) => {
                        let root = &s.file_syntax(sema.db);
                        let expr = s.value.to_node(root);
                        let expr = expr.syntax();
                        match_ast! {
                            match expr {
                                ast::BlockExpr(x) => x.stmt_list().and_then(|x| x.r_curly_token()).map(|x| x.text_range()).unwrap_or_else(|| expr.text_range()),
                                // make the inlay hint appear after the semicolon if there is
                                _ => {
                                    let nearest_semicolon = nearest_token_after_node(expr, syntax::SyntaxKind::SEMICOLON);
                                    nearest_semicolon.map(|x| x.text_range()).unwrap_or_else(|| expr.text_range())
                                },
                            }
                        }
                    }
                    Err(_) => continue,
                },
                MirSpan::PatId(p) => match source_map.pat_syntax(p) {
                    Ok(s) => s.value.text_range(),
                    Err(_) => continue,
                },
                MirSpan::BindingId(b) => {
                    match source_map
                        .patterns_for_binding(b)
                        .iter()
                        .find_map(|p| source_map.pat_syntax(*p).ok())
                    {
                        Some(s) => s.value.text_range(),
                        None => continue,
                    }
                }
                MirSpan::SelfParam => match source_map.self_param_syntax() {
                    Some(s) => s.value.text_range(),
                    None => continue,
                },
                MirSpan::Unknown => continue,
            };
            let binding_source = source_map
                .patterns_for_binding(*binding)
                .first()
                .and_then(|d| source_map.pat_syntax(*d).ok())
                .and_then(|d| {
                    Some(FileRange {
                        file_id: d.file_id.file_id()?.into(),
                        range: d.value.text_range(),
                    })
                });
            let binding = &hir.bindings[*binding];
            let name = binding.name.display_no_db(file_id.edition()).to_smolstr();
            if name.starts_with("<ra@") {
                continue; // Ignore desugared variables
            }
            let mut label = InlayHintLabel::simple(
                name,
                Some(crate::InlayTooltip::String("moz".into())),
                binding_source,
            );
            label.prepend_str("drop(");
            label.append_str(")");
            acc.push(InlayHint {
                range,
                position: InlayHintPosition::After,
                pad_left: true,
                pad_right: true,
                kind: InlayKind::Drop,
                label,
                text_edit: None,
                resolve_parent: Some(node.syntax().text_range()),
            })
        }
    }

    Some(())
}

fn nearest_token_after_node(
    node: &syntax::SyntaxNode,
    token_type: syntax::SyntaxKind,
) -> Option<syntax::SyntaxToken> {
    node.siblings_with_tokens(syntax::Direction::Next)
        .filter_map(|it| it.as_token().cloned())
        .find(|it| it.kind() == token_type)
}

#[cfg(test)]
mod tests {
    use crate::{
        inlay_hints::tests::{check_with_config, DISABLED_CONFIG},
        InlayHintsConfig,
    };

    const ONLY_DROP_CONFIG: InlayHintsConfig =
        InlayHintsConfig { implicit_drop_hints: true, ..DISABLED_CONFIG };

    #[test]
    fn basic() {
        check_with_config(
            ONLY_DROP_CONFIG,
            r#"
    struct X;
    fn f() {
        let x = X;
        if 2 == 5 {
            return;
                //^ drop(x)
        }
    }
  //^ drop(x)
"#,
        );
    }

    #[test]
    fn no_hint_for_copy_types_and_mutable_references() {
        // `T: Copy` and `T = &mut U` types do nothing on drop, so we should hide drop inlay hint for them.
        check_with_config(
            ONLY_DROP_CONFIG,
            r#"
//- minicore: copy, derive

    struct X(i32, i32);
    #[derive(Clone, Copy)]
    struct Y(i32, i32);
    fn f() {
        let a = 2;
        let b = a + 4;
        let mut x = X(a, b);
        let mut y = Y(a, b);
        let mx = &mut x;
        let my = &mut y;
        let c = a + b;
    }
  //^ drop(x)
"#,
        );
    }

    #[test]
    fn try_operator() {
        // We currently show drop inlay hint for every `?` operator that may potentially drop something. We probably need to
        // make it configurable as it doesn't seem very useful.
        check_with_config(
            ONLY_DROP_CONFIG,
            r#"
//- minicore: copy, try, option

    struct X;
    fn f() -> Option<()> {
        let x = X;
        let t_opt = Some(2);
        let t = t_opt?;
                    //^ drop(x)
        Some(())
    }
  //^ drop(x)
"#,
        );
    }

    #[test]
    fn if_let() {
        check_with_config(
            ONLY_DROP_CONFIG,
            r#"
    struct X;
    fn f() {
        let x = X;
        if let X = x {
            let y = X;
        }
      //^ drop(y)
    }
  //^ drop(x)
"#,
        );
    }
}