aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/utils/insert_use.rs
blob: 0ee43482f79856a7a1f7fa963d6e89cdd3d6ac39 (plain)
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Handle syntactic aspects of inserting a new `use`.
// FIXME: rewrite according to the plan, outlined in
// https://github.com/rust-analyzer/rust-analyzer/issues/3301#issuecomment-592931553

use hir::{self, ModPath};
use ra_syntax::{
    ast::{self, NameOwner},
    AstNode, Direction, SmolStr,
    SyntaxKind::{PATH, PATH_SEGMENT},
    SyntaxNode, T,
};
use ra_text_edit::TextEditBuilder;

use crate::assist_context::AssistContext;

/// Creates and inserts a use statement for the given path to import.
/// The use statement is inserted in the scope most appropriate to the
/// the cursor position given, additionally merged with the existing use imports.
pub(crate) fn insert_use_statement(
    // Ideally the position of the cursor, used to
    position: &SyntaxNode,
    path_to_import: &ModPath,
    ctx: &AssistContext,
    builder: &mut TextEditBuilder,
) {
    let target = path_to_import.to_string().split("::").map(SmolStr::new).collect::<Vec<_>>();
    let container = ctx.sema.ancestors_with_macros(position.clone()).find_map(|n| {
        if let Some(module) = ast::Module::cast(n.clone()) {
            return module.item_list().map(|it| it.syntax().clone());
        }
        ast::SourceFile::cast(n).map(|it| it.syntax().clone())
    });

    if let Some(container) = container {
        let action = best_action_for_target(container, position.clone(), &target);
        make_assist(&action, &target, builder);
    }
}

fn collect_path_segments_raw(
    segments: &mut Vec<ast::PathSegment>,
    mut path: ast::Path,
) -> Option<usize> {
    let oldlen = segments.len();
    loop {
        let mut children = path.syntax().children_with_tokens();
        let (first, second, third) = (
            children.next().map(|n| (n.clone(), n.kind())),
            children.next().map(|n| (n.clone(), n.kind())),
            children.next().map(|n| (n.clone(), n.kind())),
        );
        match (first, second, third) {
            (Some((subpath, PATH)), Some((_, T![::])), Some((segment, PATH_SEGMENT))) => {
                path = ast::Path::cast(subpath.as_node()?.clone())?;
                segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
            }
            (Some((segment, PATH_SEGMENT)), _, _) => {
                segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
                break;
            }
            (_, _, _) => return None,
        }
    }
    // We need to reverse only the new added segments
    let only_new_segments = segments.split_at_mut(oldlen).1;
    only_new_segments.reverse();
    Some(segments.len() - oldlen)
}

fn fmt_segments_raw(segments: &[SmolStr], buf: &mut String) {
    let mut iter = segments.iter();
    if let Some(s) = iter.next() {
        buf.push_str(s);
    }
    for s in iter {
        buf.push_str("::");
        buf.push_str(s);
    }
}

/// Returns the number of common segments.
fn compare_path_segments(left: &[SmolStr], right: &[ast::PathSegment]) -> usize {
    left.iter().zip(right).take_while(|(l, r)| compare_path_segment(l, r)).count()
}

fn compare_path_segment(a: &SmolStr, b: &ast::PathSegment) -> bool {
    if let Some(kb) = b.kind() {
        match kb {
            ast::PathSegmentKind::Name(nameref_b) => a == nameref_b.text(),
            ast::PathSegmentKind::SelfKw => a == "self",
            ast::PathSegmentKind::SuperKw => a == "super",
            ast::PathSegmentKind::CrateKw => a == "crate",
            ast::PathSegmentKind::Type { .. } => false, // not allowed in imports
        }
    } else {
        false
    }
}

fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool {
    a == b.text()
}

#[derive(Clone, Debug)]
enum ImportAction {
    Nothing,
    // Add a brand new use statement.
    AddNewUse {
        anchor: Option<SyntaxNode>, // anchor node
        add_after_anchor: bool,
    },

    // To split an existing use statement creating a nested import.
    AddNestedImport {
        // how may segments matched with the target path
        common_segments: usize,
        path_to_split: ast::Path,
        // the first segment of path_to_split we want to add into the new nested list
        first_segment_to_split: Option<ast::PathSegment>,
        // Wether to add 'self' in addition to the target path
        add_self: bool,
    },
    // To add the target path to an existing nested import tree list.
    AddInTreeList {
        common_segments: usize,
        // The UseTreeList where to add the target path
        tree_list: ast::UseTreeList,
        add_self: bool,
    },
}

impl ImportAction {
    fn add_new_use(anchor: Option<SyntaxNode>, add_after_anchor: bool) -> Self {
        ImportAction::AddNewUse { anchor, add_after_anchor }
    }

    fn add_nested_import(
        common_segments: usize,
        path_to_split: ast::Path,
        first_segment_to_split: Option<ast::PathSegment>,
        add_self: bool,
    ) -> Self {
        ImportAction::AddNestedImport {
            common_segments,
            path_to_split,
            first_segment_to_split,
            add_self,
        }
    }

    fn add_in_tree_list(
        common_segments: usize,
        tree_list: ast::UseTreeList,
        add_self: bool,
    ) -> Self {
        ImportAction::AddInTreeList { common_segments, tree_list, add_self }
    }

    fn better(left: ImportAction, right: ImportAction) -> ImportAction {
        if left.is_better(&right) {
            left
        } else {
            right
        }
    }

    fn is_better(&self, other: &ImportAction) -> bool {
        match (self, other) {
            (ImportAction::Nothing, _) => true,
            (ImportAction::AddInTreeList { .. }, ImportAction::Nothing) => false,
            (
                ImportAction::AddNestedImport { common_segments: n, .. },
                ImportAction::AddInTreeList { common_segments: m, .. },
            )
            | (
                ImportAction::AddInTreeList { common_segments: n, .. },
                ImportAction::AddNestedImport { common_segments: m, .. },
            )
            | (
                ImportAction::AddInTreeList { common_segments: n, .. },
                ImportAction::AddInTreeList { common_segments: m, .. },
            )
            | (
                ImportAction::AddNestedImport { common_segments: n, .. },
                ImportAction::AddNestedImport { common_segments: m, .. },
            ) => n > m,
            (ImportAction::AddInTreeList { .. }, _) => true,
            (ImportAction::AddNestedImport { .. }, ImportAction::Nothing) => false,
            (ImportAction::AddNestedImport { .. }, _) => true,
            (ImportAction::AddNewUse { .. }, _) => false,
        }
    }
}

// Find out the best ImportAction to import target path against current_use_tree.
// If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList.
fn walk_use_tree_for_best_action(
    current_path_segments: &mut Vec<ast::PathSegment>, // buffer containing path segments
    current_parent_use_tree_list: Option<ast::UseTreeList>, // will be Some value if we are in a nested import
    current_use_tree: ast::UseTree, // the use tree we are currently examinating
    target: &[SmolStr],             // the path we want to import
) -> ImportAction {
    // We save the number of segments in the buffer so we can restore the correct segments
    // before returning. Recursive call will add segments so we need to delete them.
    let prev_len = current_path_segments.len();

    let tree_list = current_use_tree.use_tree_list();
    let alias = current_use_tree.alias();

    let path = match current_use_tree.path() {
        Some(path) => path,
        None => {
            // If the use item don't have a path, it means it's broken (syntax error)
            return ImportAction::add_new_use(
                current_use_tree
                    .syntax()
                    .ancestors()
                    .find_map(ast::UseItem::cast)
                    .map(|it| it.syntax().clone()),
                true,
            );
        }
    };

    // This can happen only if current_use_tree is a direct child of a UseItem
    if let Some(name) = alias.and_then(|it| it.name()) {
        if compare_path_segment_with_name(&target[0], &name) {
            return ImportAction::Nothing;
        }
    }

    collect_path_segments_raw(current_path_segments, path.clone());

    // We compare only the new segments added in the line just above.
    // The first prev_len segments were already compared in 'parent' recursive calls.
    let left = target.split_at(prev_len).1;
    let right = current_path_segments.split_at(prev_len).1;
    let common = compare_path_segments(left, &right);
    let mut action = match common {
        0 => ImportAction::add_new_use(
            // e.g: target is std::fmt and we can have
            // use foo::bar
            // We add a brand new use statement
            current_use_tree
                .syntax()
                .ancestors()
                .find_map(ast::UseItem::cast)
                .map(|it| it.syntax().clone()),
            true,
        ),
        common if common == left.len() && left.len() == right.len() => {
            // e.g: target is std::fmt and we can have
            // 1- use std::fmt;
            // 2- use std::fmt::{ ... }
            if let Some(list) = tree_list {
                // In case 2 we need to add self to the nested list
                // unless it's already there
                let has_self = list.use_trees().map(|it| it.path()).any(|p| {
                    p.and_then(|it| it.segment())
                        .and_then(|it| it.kind())
                        .filter(|k| *k == ast::PathSegmentKind::SelfKw)
                        .is_some()
                });

                if has_self {
                    ImportAction::Nothing
                } else {
                    ImportAction::add_in_tree_list(current_path_segments.len(), list, true)
                }
            } else {
                // Case 1
                ImportAction::Nothing
            }
        }
        common if common != left.len() && left.len() == right.len() => {
            // e.g: target is std::fmt and we have
            // use std::io;
            // We need to split.
            let segments_to_split = current_path_segments.split_at(prev_len + common).1;
            ImportAction::add_nested_import(
                prev_len + common,
                path,
                Some(segments_to_split[0].clone()),
                false,
            )
        }
        common if common == right.len() && left.len() > right.len() => {
            // e.g: target is std::fmt and we can have
            // 1- use std;
            // 2- use std::{ ... };

            // fallback action
            let mut better_action = ImportAction::add_new_use(
                current_use_tree
                    .syntax()
                    .ancestors()
                    .find_map(ast::UseItem::cast)
                    .map(|it| it.syntax().clone()),
                true,
            );
            if let Some(list) = tree_list {
                // Case 2, check recursively if the path is already imported in the nested list
                for u in list.use_trees() {
                    let child_action = walk_use_tree_for_best_action(
                        current_path_segments,
                        Some(list.clone()),
                        u,
                        target,
                    );
                    if child_action.is_better(&better_action) {
                        better_action = child_action;
                        if let ImportAction::Nothing = better_action {
                            return better_action;
                        }
                    }
                }
            } else {
                // Case 1, split adding self
                better_action = ImportAction::add_nested_import(prev_len + common, path, None, true)
            }
            better_action
        }
        common if common == left.len() && left.len() < right.len() => {
            // e.g: target is std::fmt and we can have
            // use std::fmt::Debug;
            let segments_to_split = current_path_segments.split_at(prev_len + common).1;
            ImportAction::add_nested_import(
                prev_len + common,
                path,
                Some(segments_to_split[0].clone()),
                true,
            )
        }
        common if common < left.len() && common < right.len() => {
            // e.g: target is std::fmt::nested::Debug
            // use std::fmt::Display
            let segments_to_split = current_path_segments.split_at(prev_len + common).1;
            ImportAction::add_nested_import(
                prev_len + common,
                path,
                Some(segments_to_split[0].clone()),
                false,
            )
        }
        _ => unreachable!(),
    };

    // If we are inside a UseTreeList adding a use statement become adding to the existing
    // tree list.
    action = match (current_parent_use_tree_list, action.clone()) {
        (Some(use_tree_list), ImportAction::AddNewUse { .. }) => {
            ImportAction::add_in_tree_list(prev_len, use_tree_list, false)
        }
        (_, _) => action,
    };

    // We remove the segments added
    current_path_segments.truncate(prev_len);
    action
}

fn best_action_for_target(
    container: SyntaxNode,
    anchor: SyntaxNode,
    target: &[SmolStr],
) -> ImportAction {
    let mut storage = Vec::with_capacity(16); // this should be the only allocation
    let best_action = container
        .children()
        .filter_map(ast::UseItem::cast)
        .filter_map(|it| it.use_tree())
        .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
        .fold(None, |best, a| match best {
            Some(best) => Some(ImportAction::better(best, a)),
            None => Some(a),
        });

    match best_action {
        Some(action) => action,
        None => {
            // We have no action and no UseItem was found in container so we find
            // another item and we use it as anchor.
            // If there are no items above, we choose the target path itself as anchor.
            // todo: we should include even whitespace blocks as anchor candidates
            let anchor = container.children().next().or_else(|| Some(anchor));

            let add_after_anchor = anchor
                .clone()
                .and_then(ast::Attr::cast)
                .map(|attr| attr.kind() == ast::AttrKind::Inner)
                .unwrap_or(false);
            ImportAction::add_new_use(anchor, add_after_anchor)
        }
    }
}

fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBuilder) {
    match action {
        ImportAction::AddNewUse { anchor, add_after_anchor } => {
            make_assist_add_new_use(anchor, *add_after_anchor, target, edit)
        }
        ImportAction::AddInTreeList { common_segments, tree_list, add_self } => {
            // We know that the fist n segments already exists in the use statement we want
            // to modify, so we want to add only the last target.len() - n segments.
            let segments_to_add = target.split_at(*common_segments).1;
            make_assist_add_in_tree_list(tree_list, segments_to_add, *add_self, edit)
        }
        ImportAction::AddNestedImport {
            common_segments,
            path_to_split,
            first_segment_to_split,
            add_self,
        } => {
            let segments_to_add = target.split_at(*common_segments).1;
            make_assist_add_nested_import(
                path_to_split,
                first_segment_to_split,
                segments_to_add,
                *add_self,
                edit,
            )
        }
        _ => {}
    }
}

fn make_assist_add_new_use(
    anchor: &Option<SyntaxNode>,
    after: bool,
    target: &[SmolStr],
    edit: &mut TextEditBuilder,
) {
    if let Some(anchor) = anchor {
        let indent = ra_fmt::leading_indent(anchor);
        let mut buf = String::new();
        if after {
            buf.push_str("\n");
            if let Some(spaces) = &indent {
                buf.push_str(spaces);
            }
        }
        buf.push_str("use ");
        fmt_segments_raw(target, &mut buf);
        buf.push_str(";");
        if !after {
            buf.push_str("\n\n");
            if let Some(spaces) = &indent {
                buf.push_str(&spaces);
            }
        }
        let position = if after { anchor.text_range().end() } else { anchor.text_range().start() };
        edit.insert(position, buf);
    }
}

fn make_assist_add_in_tree_list(
    tree_list: &ast::UseTreeList,
    target: &[SmolStr],
    add_self: bool,
    edit: &mut TextEditBuilder,
) {
    let last = tree_list.use_trees().last();
    if let Some(last) = last {
        let mut buf = String::new();
        let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == T![,]);
        let offset = if let Some(comma) = comma {
            comma.text_range().end()
        } else {
            buf.push_str(",");
            last.syntax().text_range().end()
        };
        if add_self {
            buf.push_str(" self")
        } else {
            buf.push_str(" ");
        }
        fmt_segments_raw(target, &mut buf);
        edit.insert(offset, buf);
    } else {
    }
}

fn make_assist_add_nested_import(
    path: &ast::Path,
    first_segment_to_split: &Option<ast::PathSegment>,
    target: &[SmolStr],
    add_self: bool,
    edit: &mut TextEditBuilder,
) {
    let use_tree = path.syntax().ancestors().find_map(ast::UseTree::cast);
    if let Some(use_tree) = use_tree {
        let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split
        {
            (first_segment_to_split.syntax().text_range().start(), false)
        } else {
            (use_tree.syntax().text_range().end(), true)
        };
        let end = use_tree.syntax().text_range().end();

        let mut buf = String::new();
        if add_colon_colon {
            buf.push_str("::");
        }
        buf.push_str("{");
        if add_self {
            buf.push_str("self, ");
        }
        fmt_segments_raw(target, &mut buf);
        if !target.is_empty() {
            buf.push_str(", ");
        }
        edit.insert(start, buf);
        edit.insert(end, "}".to_string());
    }
}