rust/crates/ra_assists/src/lib.rs

322 lines
11 KiB
Rust
Raw Normal View History

2019-09-08 04:10:53 -05:00
//! `ra_assists` crate provides a bunch of code assists, also known as code
2019-02-03 12:26:35 -06:00
//! 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;
2019-02-24 05:22:25 -06:00
mod marks;
2019-10-25 06:16:46 -05:00
#[cfg(test)]
mod doc_tests;
2019-11-04 13:28:47 -06:00
#[cfg(test)]
mod test_db;
pub mod ast_transform;
2019-02-03 12:26:35 -06:00
use hir::db::HirDatabase;
use ra_db::FileRange;
use ra_syntax::{TextRange, TextUnit};
use ra_text_edit::TextEdit;
2019-02-03 12:26:35 -06:00
pub(crate) use crate::assist_ctx::{Assist, AssistCtx};
pub use crate::assists::add_import::auto_import_text_edit;
2019-02-03 12:26:35 -06:00
2019-02-24 04:53:35 -06:00
/// 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)]
2019-02-03 12:26:35 -06:00
pub struct AssistLabel {
/// Short description of the assist, as shown in the UI.
pub label: String,
2019-02-24 04:53:35 -06:00
pub id: AssistId,
2019-02-03 12:26:35 -06:00
}
#[derive(Debug, Clone)]
2019-02-03 12:26:35 -06:00
pub struct AssistAction {
pub edit: TextEdit,
pub cursor_position: Option<TextUnit>,
2019-02-08 15:43:13 -06:00
pub target: Option<TextRange>,
2019-02-03 12:26:35 -06:00
}
2019-10-25 06:16:46 -05:00
/// Return all the assists applicable at the given position.
2019-02-03 12:26:35 -06:00
///
/// 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| {
2019-09-25 06:29:41 -05:00
assists::all()
2019-02-03 12:26:35 -06:00
.iter()
.filter_map(|f| f(ctx.clone()))
.map(|a| match a {
2019-10-27 10:22:14 -05:00
Assist::Unresolved { label } => label,
Assist::Resolved { .. } => unreachable!(),
2019-02-03 12:26:35 -06:00
})
2019-10-27 10:22:14 -05:00
.collect()
2019-02-03 12:26:35 -06:00
})
}
/// 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<(AssistLabel, AssistAction)>
where
H: HirDatabase + 'static,
{
2019-02-08 15:43:13 -06:00
use std::cmp::Ordering;
2019-02-06 10:15:18 -06:00
AssistCtx::with_ctx(db, range, true, |ctx| {
2019-09-25 06:29:41 -05:00
let mut a = assists::all()
2019-02-03 12:26:35 -06:00
.iter()
.filter_map(|f| f(ctx.clone()))
.map(|a| match a {
2019-10-27 10:22:14 -05:00
Assist::Resolved { label, action } => (label, action),
Assist::Unresolved { .. } => unreachable!(),
2019-02-03 12:26:35 -06:00
})
2019-10-27 10:22:14 -05:00
.collect::<Vec<_>>();
2019-02-08 18:57:08 -06:00
a.sort_by(|a, b| match (a.1.target, b.1.target) {
(Some(a), Some(b)) => a.len().cmp(&b.len()),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
2019-02-08 15:43:13 -06:00
});
a
2019-02-03 12:26:35 -06:00
})
}
2019-09-25 06:29:41 -05:00
mod assists {
use crate::{Assist, AssistCtx};
use hir::db::HirDatabase;
mod add_derive;
mod add_explicit_type;
mod add_impl;
mod add_custom_impl;
mod add_new;
mod apply_demorgan;
2019-11-21 12:51:40 -06:00
mod invert_if;
2019-09-25 06:29:41 -05:00
mod flip_comma;
mod flip_binexpr;
mod flip_trait_bound;
2019-09-25 06:29:41 -05:00
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;
2019-09-25 06:29:41 -05:00
mod add_missing_impl_members;
mod move_guard;
mod move_bounds;
mod early_return;
2019-09-25 06:29:41 -05:00
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,
2019-11-21 12:51:40 -06:00
invert_if::invert_if,
2019-09-25 06:29:41 -05:00
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,
2019-09-25 06:29:41 -05:00
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,
2019-09-25 06:29:41 -05:00
add_missing_impl_members::add_missing_impl_members,
add_missing_impl_members::add_missing_default_members,
inline_local_variable::inline_local_varialbe,
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,
2019-09-25 06:29:41 -05:00
]
}
2019-02-03 12:26:35 -06:00
}
#[cfg(test)]
mod helpers {
use ra_db::{fixture::WithFixture, FileRange};
use ra_syntax::TextRange;
use test_utils::{add_cursor, assert_eq_text, extract_offset, extract_range};
2019-02-03 12:26:35 -06:00
2019-11-04 13:28:47 -06:00
use crate::{test_db::TestDB, Assist, AssistCtx};
2019-02-03 12:26:35 -06:00
pub(crate) fn check_assist(
assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
2019-02-03 12:26:35 -06:00
before: &str,
after: &str,
) {
let (before_cursor_pos, before) = extract_offset(before);
let (db, file_id) = TestDB::with_single_file(&before);
2019-02-08 05:49:43 -06:00
let frange =
FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
2019-02-03 12:26:35 -06:00
let assist =
AssistCtx::with_ctx(&db, frange, true, assist).expect("code action is not applicable");
2019-10-27 10:22:14 -05:00
let action = match assist {
Assist::Unresolved { .. } => unreachable!(),
Assist::Resolved { action, .. } => action,
2019-02-03 12:26:35 -06:00
};
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);
}
2019-10-27 10:22:14 -05:00
pub(crate) fn check_assist_range(
assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
2019-02-03 12:26:35 -06:00
before: &str,
after: &str,
) {
let (range, before) = extract_range(before);
let (db, file_id) = TestDB::with_single_file(&before);
2019-02-03 12:26:35 -06:00
let frange = FileRange { file_id, range };
let assist =
AssistCtx::with_ctx(&db, frange, true, assist).expect("code action is not applicable");
2019-10-27 10:22:14 -05:00
let action = match assist {
Assist::Unresolved { .. } => unreachable!(),
Assist::Resolved { action, .. } => action,
2019-02-03 12:26:35 -06:00
};
let mut actual = action.edit.apply(&before);
if let Some(pos) = action.cursor_position {
actual = add_cursor(&actual, pos);
}
assert_eq_text!(after, &actual);
}
2019-10-27 10:22:14 -05:00
pub(crate) fn check_assist_target(
assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
2019-02-08 17:34:05 -06:00
before: &str,
target: &str,
) {
let (before_cursor_pos, before) = extract_offset(before);
let (db, file_id) = TestDB::with_single_file(&before);
2019-02-08 17:34:05 -06:00
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");
2019-10-27 10:22:14 -05:00
let action = match assist {
Assist::Unresolved { .. } => unreachable!(),
Assist::Resolved { action, .. } => action,
2019-02-08 17:34:05 -06:00
};
let range = action.target.expect("expected target on action");
assert_eq_text!(&before[range.start().to_usize()..range.end().to_usize()], target);
}
2019-10-27 10:22:14 -05:00
pub(crate) fn check_assist_range_target(
assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
2019-02-08 17:34:05 -06:00
before: &str,
target: &str,
) {
let (range, before) = extract_range(before);
let (db, file_id) = TestDB::with_single_file(&before);
2019-02-08 17:34:05 -06:00
let frange = FileRange { file_id, range };
let assist =
AssistCtx::with_ctx(&db, frange, true, assist).expect("code action is not applicable");
2019-10-27 10:22:14 -05:00
let action = match assist {
Assist::Unresolved { .. } => unreachable!(),
Assist::Resolved { action, .. } => action,
2019-02-08 17:34:05 -06:00
};
let range = action.target.expect("expected target on action");
assert_eq_text!(&before[range.start().to_usize()..range.end().to_usize()], target);
}
2019-02-03 12:26:35 -06:00
pub(crate) fn check_assist_not_applicable(
assist: fn(AssistCtx<TestDB>) -> Option<Assist>,
2019-02-03 12:26:35 -06:00
before: &str,
) {
let (before_cursor_pos, before) = extract_offset(before);
let (db, file_id) = TestDB::with_single_file(&before);
2019-02-08 05:49:43 -06:00
let frange =
FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
2019-02-03 12:26:35 -06:00
let assist = AssistCtx::with_ctx(&db, frange, true, assist);
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());
}
2019-02-08 15:43:13 -06:00
}
#[cfg(test)]
mod tests {
use ra_db::{fixture::WithFixture, FileRange};
use ra_syntax::TextRange;
use test_utils::{extract_offset, extract_range};
2019-02-08 15:43:13 -06:00
2019-11-04 13:28:47 -06:00
use crate::test_db::TestDB;
2019-02-08 15:43:13 -06:00
#[test]
2019-02-08 17:34:05 -06:00
fn assist_order_field_struct() {
2019-02-08 15:43:13 -06:00
let before = "struct Foo { <|>bar: u32 }";
let (before_cursor_pos, before) = extract_offset(before);
let (db, file_id) = TestDB::with_single_file(&before);
2019-02-08 15:43:13 -06:00
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();
2020-01-14 11:32:26 -06:00
assert_eq!(
assists.next().expect("expected assist").0.label,
"Change visibility to pub(crate)"
);
assert_eq!(assists.next().expect("expected assist").0.label, "Add `#[derive]`");
2019-02-08 15:43:13 -06:00
}
2019-02-03 12:26:35 -06:00
2019-02-08 17:34:05 -06:00
#[test]
fn assist_order_if_expr() {
let before = "
pub fn test_some_range(a: int) -> bool {
if let 2..6 = <|>5<|> {
2019-02-08 17:34:05 -06:00
true
} else {
false
}
}";
let (range, before) = extract_range(before);
let (db, file_id) = TestDB::with_single_file(&before);
let frange = FileRange { file_id, range };
2019-02-08 17:34:05 -06:00
let assists = super::assists(&db, frange);
let mut assists = assists.iter();
2020-01-14 11:32:26 -06:00
assert_eq!(assists.next().expect("expected assist").0.label, "Extract into variable");
assert_eq!(assists.next().expect("expected assist").0.label, "Replace with match");
2019-02-08 17:34:05 -06:00
}
2019-02-03 12:26:35 -06:00
}