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
//! ink! attribute argument inlay hints.

use ink_analyzer_ir::syntax::{AstToken, TextRange, TextSize};
use ink_analyzer_ir::{InkArgValueKind, InkFile, IsInkEntity};

/// An ink! attribute argument inlay hint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InlayHint {
    /// Text of the inlay hint.
    pub label: String,
    /// Position of the inlay hint.
    pub position: TextSize,
    /// Range to which the inlay hint applies.
    pub range: TextRange,
    /// Extra details about the inlay hint.
    pub detail: Option<String>,
}

/// Computes ink! attribute argument inlay hints for the given text range (if any).
pub fn inlay_hints(file: &InkFile, range: Option<TextRange>) -> Vec<InlayHint> {
    // Iterates over all ink! attributes in the file.
    file.tree()
        .ink_attrs_in_scope()
        .flat_map(|attr| {
            // Returns inlay hints for all ink! attribute arguments with values in the selection range.
            attr.args()
                .iter()
                .filter_map(|arg| {
                    // Filters out ink! attribute arguments that aren't in the selection range.
                    (range.is_none()
                        || matches!(
                            range.as_ref().map(|it| it.contains_range(arg.text_range())),
                            Some(true)
                        ))
                    .then(|| {
                        // Creates inlay hint if a non-empty label is defined for the ink! attribute argument.
                        let arg_value_kind = InkArgValueKind::from(*arg.kind());
                        let label = arg_value_kind.to_string();
                        let doc = arg_value_kind.detail();
                        (!label.is_empty()).then_some(InlayHint {
                            label,
                            position: arg.name().map_or(arg.text_range().end(), |name| {
                                name.syntax().text_range().end()
                            }),
                            range: arg
                                .name()
                                .map_or(arg.text_range(), |name| name.syntax().text_range()),
                            detail: (!doc.is_empty()).then_some(doc.to_string()),
                        })
                    })?
                })
                .collect::<Vec<InlayHint>>()
        })
        .collect()
}

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

    #[test]
    fn inlay_hints_works() {
        for (code, selection_range_pat, expected_results) in [
            // (code, Option<(selection_pat_start, selection_pat_end)>, [(label, detail, pos_pat, (range_pat_start, range_pat_end))]) where:
            // code = source code,
            // selection_pat_start = substring used to find the start of the selection range (see `test_utils::parse_offset_at` doc),
            // selection_pat_end = substring used to find the end of the range the selection range (see `test_utils::parse_offset_at` doc).
            // label = the label text for the inlay hint,
            // detail = the optional detail text for the inlay hint,
            // pos_pat = substring used to find the cursor offset for the inlay hint (see `test_utils::parse_offset_at` doc),
            // range_pat_start = substring used to find the start of the range the inlay hint applies to (see `test_utils::parse_offset_at` doc),
            // range_pat_end = substring used to find the end of the range the inlay hint applies to (see `test_utils::parse_offset_at` doc).

            // Control tests.
            ("// Nothing", None, vec![]),
            (
                r#"
                    mod my_mod {
                        fn my_fn(a: bool, b: u8) {
                        }
                    }
                "#,
                None,
                vec![],
            ),
            // ink! attribute macros.
            ("#[ink::contract]", None, vec![]),
            ("#[ink::trait_definition]", None, vec![]),
            ("#[ink::chain_extension]", None, vec![]),
            ("#[ink::storage_item]", None, vec![]),
            ("#[ink::test]", None, vec![]),
            (
                r#"#[ink::contract(env=my::env::Types, keep_attr="foo,bar")]"#,
                None,
                vec![
                    (
                        "impl Environment",
                        Some("env"),
                        (Some("<-env"), Some("env")),
                    ),
                    (
                        "&str",
                        Some("keep_attr"),
                        (Some("<-keep_attr"), Some("keep_attr")),
                    ),
                ],
            ),
            (
                r#"#[ink::contract(env=my::env::Types, keep_attr="foo,bar")]"#,
                Some((Some("<-"), Some("->"))),
                vec![
                    (
                        "impl Environment",
                        Some("env"),
                        (Some("<-env"), Some("env")),
                    ),
                    (
                        "&str",
                        Some("keep_attr"),
                        (Some("<-keep_attr"), Some("keep_attr")),
                    ),
                ],
            ),
            (
                r#"#[ink::contract(env=my::env::Types, keep_attr="foo,bar")]"#,
                Some((Some("<-"), Some("my::env::Types"))),
                vec![(
                    "impl Environment",
                    Some("env"),
                    (Some("<-env"), Some("env")),
                )],
            ),
            (
                r#"#[ink::contract(env=my::env::Types, keep_attr="foo,bar")]"#,
                Some((Some("<-keep_attr"), Some("->"))),
                vec![(
                    "&str",
                    Some("keep_attr"),
                    (Some("<-keep_attr"), Some("keep_attr")),
                )],
            ),
            (
                r#"#[ink::trait_definition(namespace="my_namespace", keep_attr="foo,bar")]"#,
                None,
                vec![
                    (
                        "&str",
                        Some("namespace"),
                        (Some("<-namespace"), Some("namespace")),
                    ),
                    (
                        "&str",
                        Some("keep_attr"),
                        (Some("<-keep_attr"), Some("keep_attr")),
                    ),
                ],
            ),
            (
                "#[ink::storage_item(derive=true)]",
                None,
                vec![("bool", Some("derive"), (Some("<-derive"), Some("derive")))],
            ),
            (
                r#"#[ink_e2e::test(additional_contracts="adder/Cargo.toml flipper/Cargo.toml", environment=my::env::Types, keep_attr="foo,bar")]"#,
                None,
                vec![
                    (
                        "&str",
                        Some("additional_contracts"),
                        (Some("<-additional_contracts"), Some("additional_contracts")),
                    ),
                    (
                        "impl Environment",
                        Some("environment"),
                        (Some("<-environment"), Some("environment")),
                    ),
                    (
                        "&str",
                        Some("keep_attr"),
                        (Some("<-keep_attr"), Some("keep_attr")),
                    ),
                ],
            ),
            // ink! attribute arguments.
            ("#[ink(storage)]", None, vec![]),
            ("#[ink(event, anonymous)]", None, vec![]),
            (
                "#[ink(constructor, default, selector=1)]",
                None,
                vec![(
                    "u32 | _",
                    Some("selector"),
                    (Some("<-selector"), Some("selector")),
                )],
            ),
            (
                "#[ink(message, default, payable, selector=1)]",
                None,
                vec![(
                    "u32 | _",
                    Some("selector"),
                    (Some("<-selector"), Some("selector")),
                )],
            ),
            (
                r#"#[ink(impl, namespace="my_namespace")]"#,
                None,
                vec![(
                    "&str",
                    Some("namespace"),
                    (Some("<-namespace"), Some("namespace")),
                )],
            ),
            (
                "#[ink(extension=1, handle_status=true)]",
                None,
                vec![
                    (
                        "u32",
                        Some("extension"),
                        (Some("<-extension"), Some("extension")),
                    ),
                    (
                        "bool",
                        Some("handle_status"),
                        (Some("<-handle_status"), Some("handle_status")),
                    ),
                ],
            ),
        ] {
            let range = selection_range_pat.map(|(pat_start, pat_end)| {
                TextRange::new(
                    TextSize::from(parse_offset_at(code, pat_start).unwrap() as u32),
                    TextSize::from(parse_offset_at(code, pat_end).unwrap() as u32),
                )
            });
            let results = inlay_hints(&InkFile::parse(code), range);

            assert_eq!(
                results
                    .into_iter()
                    .map(|item| (item.label, item.position, item.range))
                    .collect::<Vec<(String, TextSize, TextRange)>>(),
                expected_results
                    .into_iter()
                    .map(|(label, pos_pat_start, (range_pat_start, range_pat_end))| (
                        label.to_string(),
                        TextSize::from(parse_offset_at(code, pos_pat_start).unwrap() as u32),
                        TextRange::new(
                            TextSize::from(parse_offset_at(code, range_pat_start).unwrap() as u32),
                            TextSize::from(parse_offset_at(code, range_pat_end).unwrap() as u32)
                        )
                    ))
                    .collect::<Vec<(String, TextSize, TextRange)>>(),
                "code: {code}"
            );
        }
    }
}