aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/lib.rs
blob: 625ebc4a2d306a7767b6850871cbc05a4bf5ca8a (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
//! `ra_assists` crate provides a bunch of code assists, also known as code
//! actions (in LSP) or intentions (in IntelliJ).
//!
//! An assist is a micro-refactoring, which is automatically activated in
//! certain context. For example, if the cursor is over `,`, a "swap `,`" assist
//! becomes available.

mod assist_ctx;
mod marks;
#[cfg(test)]
mod doc_tests;
#[cfg(test)]
mod test_db;
pub mod ast_transform;

use either::Either;
use hir::{db::HirDatabase, ModuleDef};
use ra_db::FileRange;
use ra_syntax::{TextRange, TextUnit};
use ra_text_edit::TextEdit;

pub(crate) use crate::assist_ctx::{Assist, AssistCtx};
pub use crate::assists::add_import::auto_import_text_edit;

/// Unique identifier of the assist, should not be shown to the user
/// directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AssistId(pub &'static str);

#[derive(Debug, Clone)]
pub struct AssistLabel {
    /// Short description of the assist, as shown in the UI.
    pub label: String,
    pub id: AssistId,
}

#[derive(Debug, Clone)]
pub struct AssistAction {
    pub label: Option<String>,
    pub edit: TextEdit,
    pub cursor_position: Option<TextUnit>,
    pub target: Option<TextRange>,
}

#[derive(Debug, Clone)]
pub struct ResolvedAssist {
    pub label: AssistLabel,
    pub action_data: Either<AssistAction, Vec<AssistAction>>,
}

impl ResolvedAssist {
    pub fn get_first_action(&self) -> AssistAction {
        match &self.action_data {
            Either::Left(action) => action.clone(),
            Either::Right(actions) => actions[0].clone(),
        }
    }
}

/// Return all the assists applicable at the given position.
///
/// Assists are returned in the "unresolved" state, that is only labels are
/// returned, without actual edits.
pub fn applicable_assists<H>(db: &H, range: FileRange) -> Vec<AssistLabel>
where
    H: HirDatabase + 'static,
{
    AssistCtx::with_ctx(db, range, false, |ctx| {
        assists::all()
            .iter()
            .filter_map(|f| f(ctx.clone()))
            .map(|a| match a {
                Assist::Unresolved { label } => label,
                Assist::Resolved { .. } => unreachable!(),
            })
            .collect()
    })
}

/// A functionality for locating imports for the given name.
///
/// Currently has to be a trait with the real implementation provided by the ra_ide_api crate,
/// due to the search functionality located there.
/// Later, this trait should be removed completely and the search functionality moved to a separate crate,
/// accessible from the ra_assists crate.
pub trait ImportsLocator {
    /// Finds all imports for the given name and the module that contains this name.
    fn find_imports(&mut self, name_to_import: &str) -> Vec<ModuleDef>;
}

/// Return all the assists applicable at the given position
/// and additional assists that need the imports locator functionality to work.
///
/// Assists are returned in the "resolved" state, that is with edit fully
/// computed.
pub fn assists_with_imports_locator<H, F>(
    db: &H,
    range: FileRange,
    mut imports_locator: F,
) -> Vec<ResolvedAssist>
where
    H: HirDatabase + 'static,
    F: ImportsLocator,
{
    AssistCtx::with_ctx(db, range, true, |ctx| {
        let mut assists = assists::all()
            .iter()
            .map(|f| f(ctx.clone()))
            .chain(
                assists::all_with_imports_locator()
                    .iter()
                    .map(|f| f(ctx.clone(), &mut imports_locator)),
            )
            .filter_map(std::convert::identity)
            .map(|a| match a {
                Assist::Resolved { assist } => assist,
                Assist::Unresolved { .. } => unreachable!(),
            })
            .collect();
        sort_assists(&mut assists);
        assists
    })
}

/// Return all the assists applicable at the given position.
///
/// Assists are returned in the "resolved" state, that is with edit fully
/// computed.
pub fn assists<H>(db: &H, range: FileRange) -> Vec<ResolvedAssist>
where
    H: HirDatabase + 'static,
{
    AssistCtx::with_ctx(db, range, true, |ctx| {
        let mut a = assists::all()
            .iter()
            .filter_map(|f| f(ctx.clone()))
            .map(|a| match a {
                Assist::Resolved { assist } => assist,
                Assist::Unresolved { .. } => unreachable!(),
            })
            .collect();
        sort_assists(&mut a);
        a
    })
}

fn sort_assists(assists: &mut Vec<ResolvedAssist>) {
    use std::cmp::Ordering;
    assists.sort_by(|a, b| match (a.get_first_action().target, b.get_first_action().target) {
        (Some(a), Some(b)) => a.len().cmp(&b.len()),
        (Some(_), None) => Ordering::Less,
        (None, Some(_)) => Ordering::Greater,
        (None, None) => Ordering::Equal,
    });
}

mod assists {
    use crate::{Assist, AssistCtx, ImportsLocator};
    use hir::db::HirDatabase;

    mod add_derive;
    mod add_explicit_type;
    mod add_impl;
    mod add_custom_impl;
    mod add_new;
    mod apply_demorgan;
    mod auto_import;
    mod invert_if;
    mod flip_comma;
    mod flip_binexpr;
    mod flip_trait_bound;
    mod change_visibility;
    mod fill_match_arms;
    mod merge_match_arms;
    mod introduce_variable;
    mod inline_local_variable;
    mod raw_string;
    mod replace_if_let_with_match;
    mod split_import;
    mod remove_dbg;
    pub(crate) mod add_import;
    mod add_missing_impl_members;
    mod move_guard;
    mod move_bounds;
    mod early_return;

    pub(crate) fn all<DB: HirDatabase>() -> &'static [fn(AssistCtx<DB>) -> Option<Assist>] {
        &[
            add_derive::add_derive,
            add_explicit_type::add_explicit_type,
            add_impl::add_impl,
            add_custom_impl::add_custom_impl,
            add_new::add_new,
            apply_demorgan::apply_demorgan,
            invert_if::invert_if,
            change_visibility::change_visibility,
            fill_match_arms::fill_match_arms,
            merge_match_arms::merge_match_arms,
            flip_comma::flip_comma,
            flip_binexpr::flip_binexpr,
            flip_trait_bound::flip_trait_bound,
            introduce_variable::introduce_variable,
            replace_if_let_with_match::replace_if_let_with_match,
            split_import::split_import,
            remove_dbg::remove_dbg,
            add_import::add_import,
            add_missing_impl_members::add_missing_impl_members,
            add_missing_impl_members::add_missing_default_members,
            inline_local_variable::inline_local_variable,
            move_guard::move_guard_to_arm_body,
            move_guard::move_arm_cond_to_match_guard,
            move_bounds::move_bounds_to_where_clause,
            raw_string::add_hash,
            raw_string::make_raw_string,
            raw_string::make_usual_string,
            raw_string::remove_hash,
            early_return::convert_to_guarded_return,
        ]
    }

    pub(crate) fn all_with_imports_locator<'a, DB: HirDatabase, F: ImportsLocator>(
    ) -> &'a [fn(AssistCtx<DB>, &mut F) -> Option<Assist>] {
        &[auto_import::auto_import]
    }
}

#[cfg(test)]
mod helpers {
    use hir::db::DefDatabase;
    use ra_db::{fixture::WithFixture, FileId, FileRange};
    use ra_syntax::TextRange;
    use test_utils::{add_cursor, assert_eq_text, extract_offset, extract_range};

    use crate::{test_db::TestDB, Assist, AssistCtx, ImportsLocator};
    use std::sync::Arc;

    // FIXME remove the `ModuleDefId` reexport from `ra_hir` when this gets removed.
    pub(crate) struct TestImportsLocator {
        db: Arc<TestDB>,
        test_file_id: FileId,
    }

    impl TestImportsLocator {
        pub(crate) fn new(db: Arc<TestDB>, test_file_id: FileId) -> Self {
            TestImportsLocator { db, test_file_id }
        }
    }

    impl ImportsLocator for TestImportsLocator {
        fn find_imports(&mut self, name_to_import: &str) -> Vec<hir::ModuleDef> {
            let crate_def_map = self.db.crate_def_map(self.db.test_crate());
            let mut findings = Vec::new();

            let mut module_ids_to_process =
                crate_def_map.modules_for_file(self.test_file_id).collect::<Vec<_>>();

            while !module_ids_to_process.is_empty() {
                let mut more_ids_to_process = Vec::new();
                for local_module_id in module_ids_to_process.drain(..) {
                    for (name, namespace_data) in
                        crate_def_map[local_module_id].scope.entries_without_primitives()
                    {
                        let found_a_match = &name.to_string() == name_to_import;
                        vec![namespace_data.types, namespace_data.values]
                            .into_iter()
                            .filter_map(std::convert::identity)
                            .for_each(|(module_def_id, _)| {
                                if found_a_match {
                                    findings.push(module_def_id.into());
                                }
                                if let hir::ModuleDefId::ModuleId(module_id) = module_def_id {
                                    more_ids_to_process.push(module_id.local_id);
                                }
                            });
                    }
                }
                module_ids_to_process = more_ids_to_process;
            }

            findings
        }
    }

    pub(crate) fn check_assist(
        assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
        before: &str,
        after: &str,
    ) {
        let (before_cursor_pos, before) = extract_offset(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange =
            FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
        let assist =
            AssistCtx::with_ctx(&db, frange, true, assist).expect("code action is not applicable");
        let action = match assist {
            Assist::Unresolved { .. } => unreachable!(),
            Assist::Resolved { assist } => assist.get_first_action(),
        };

        let actual = action.edit.apply(&before);
        let actual_cursor_pos = match action.cursor_position {
            None => action
                .edit
                .apply_to_offset(before_cursor_pos)
                .expect("cursor position is affected by the edit"),
            Some(off) => off,
        };
        let actual = add_cursor(&actual, actual_cursor_pos);
        assert_eq_text!(after, &actual);
    }

    pub(crate) fn check_assist_with_imports_locator<F: ImportsLocator>(
        assist: fn(AssistCtx<TestDB>, &mut F) -> Option<Assist>,
        imports_locator_provider: fn(db: Arc<TestDB>, file_id: FileId) -> F,
        before: &str,
        after: &str,
    ) {
        let (before_cursor_pos, before) = extract_offset(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let db = Arc::new(db);
        let mut imports_locator = imports_locator_provider(Arc::clone(&db), file_id);
        let frange =
            FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
        let assist =
            AssistCtx::with_ctx(db.as_ref(), frange, true, |ctx| assist(ctx, &mut imports_locator))
                .expect("code action is not applicable");
        let action = match assist {
            Assist::Unresolved { .. } => unreachable!(),
            Assist::Resolved { assist } => assist.get_first_action(),
        };

        let actual = action.edit.apply(&before);
        let actual_cursor_pos = match action.cursor_position {
            None => action
                .edit
                .apply_to_offset(before_cursor_pos)
                .expect("cursor position is affected by the edit"),
            Some(off) => off,
        };
        let actual = add_cursor(&actual, actual_cursor_pos);
        assert_eq_text!(after, &actual);
    }

    pub(crate) fn check_assist_range(
        assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
        before: &str,
        after: &str,
    ) {
        let (range, before) = extract_range(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange = FileRange { file_id, range };
        let assist =
            AssistCtx::with_ctx(&db, frange, true, assist).expect("code action is not applicable");
        let action = match assist {
            Assist::Unresolved { .. } => unreachable!(),
            Assist::Resolved { assist } => assist.get_first_action(),
        };

        let mut actual = action.edit.apply(&before);
        if let Some(pos) = action.cursor_position {
            actual = add_cursor(&actual, pos);
        }
        assert_eq_text!(after, &actual);
    }

    pub(crate) fn check_assist_target(
        assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
        before: &str,
        target: &str,
    ) {
        let (before_cursor_pos, before) = extract_offset(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange =
            FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
        let assist =
            AssistCtx::with_ctx(&db, frange, true, assist).expect("code action is not applicable");
        let action = match assist {
            Assist::Unresolved { .. } => unreachable!(),
            Assist::Resolved { assist } => assist.get_first_action(),
        };

        let range = action.target.expect("expected target on action");
        assert_eq_text!(&before[range.start().to_usize()..range.end().to_usize()], target);
    }

    pub(crate) fn check_assist_range_target(
        assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
        before: &str,
        target: &str,
    ) {
        let (range, before) = extract_range(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange = FileRange { file_id, range };
        let assist =
            AssistCtx::with_ctx(&db, frange, true, assist).expect("code action is not applicable");
        let action = match assist {
            Assist::Unresolved { .. } => unreachable!(),
            Assist::Resolved { assist } => assist.get_first_action(),
        };

        let range = action.target.expect("expected target on action");
        assert_eq_text!(&before[range.start().to_usize()..range.end().to_usize()], target);
    }

    pub(crate) fn check_assist_not_applicable(
        assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
        before: &str,
    ) {
        let (before_cursor_pos, before) = extract_offset(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange =
            FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
        let assist = AssistCtx::with_ctx(&db, frange, true, assist);
        assert!(assist.is_none());
    }

    pub(crate) fn check_assist_with_imports_locator_not_applicable<F: ImportsLocator>(
        assist: fn(AssistCtx<TestDB>, &mut F) -> Option<Assist>,
        imports_locator_provider: fn(db: Arc<TestDB>, file_id: FileId) -> F,
        before: &str,
    ) {
        let (before_cursor_pos, before) = extract_offset(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let db = Arc::new(db);
        let mut imports_locator = imports_locator_provider(Arc::clone(&db), file_id);
        let frange =
            FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
        let assist =
            AssistCtx::with_ctx(db.as_ref(), frange, true, |ctx| assist(ctx, &mut imports_locator));
        assert!(assist.is_none());
    }

    pub(crate) fn check_assist_range_not_applicable(
        assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
        before: &str,
    ) {
        let (range, before) = extract_range(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange = FileRange { file_id, range };
        let assist = AssistCtx::with_ctx(&db, frange, true, assist);
        assert!(assist.is_none());
    }
}

#[cfg(test)]
mod tests {
    use ra_db::{fixture::WithFixture, FileRange};
    use ra_syntax::TextRange;
    use test_utils::{extract_offset, extract_range};

    use crate::test_db::TestDB;

    #[test]
    fn assist_order_field_struct() {
        let before = "struct Foo { <|>bar: u32 }";
        let (before_cursor_pos, before) = extract_offset(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange =
            FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
        let assists = super::assists(&db, frange);
        let mut assists = assists.iter();

        assert_eq!(
            assists.next().expect("expected assist").label.label,
            "Change visibility to pub(crate)"
        );
        assert_eq!(assists.next().expect("expected assist").label.label, "Add `#[derive]`");
    }

    #[test]
    fn assist_order_if_expr() {
        let before = "
        pub fn test_some_range(a: int) -> bool {
            if let 2..6 = <|>5<|> {
                true
            } else {
                false
            }
        }";
        let (range, before) = extract_range(before);
        let (db, file_id) = TestDB::with_single_file(&before);
        let frange = FileRange { file_id, range };
        let assists = super::assists(&db, frange);
        let mut assists = assists.iter();

        assert_eq!(assists.next().expect("expected assist").label.label, "Extract into variable");
        assert_eq!(assists.next().expect("expected assist").label.label, "Replace with match");
    }
}