simplify AssistCtx API

We never actually use ability to create multiple actions out of a
single context
This commit is contained in:
Aleksey Kladov 2019-10-27 17:35:37 +03:00
parent 9e638c9f3e
commit cda6355de2
22 changed files with 102 additions and 157 deletions

View file

@ -82,12 +82,12 @@ impl<'a, DB: HirDatabase> AssistCtx<'a, DB> {
f(ctx)
}
pub(crate) fn add_action(
&mut self,
pub(crate) fn add_assist(
mut self,
id: AssistId,
label: impl Into<String>,
f: impl FnOnce(&mut AssistBuilder),
) -> &mut Self {
) -> Option<Assist> {
let label = AssistLabel { label: label.into(), id };
match &mut self.assist {
Assist::Unresolved(labels) => labels.push(label),
@ -100,10 +100,6 @@ impl<'a, DB: HirDatabase> AssistCtx<'a, DB> {
labels_actions.push((label, action));
}
}
self
}
pub(crate) fn build(self) -> Option<Assist> {
Some(self.assist)
}

View file

@ -25,10 +25,10 @@ use crate::{Assist, AssistCtx, AssistId};
// y: u32,
// }
// ```
pub(crate) fn add_derive(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn add_derive(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let nominal = ctx.find_node_at_offset::<ast::NominalDef>()?;
let node_start = derive_insertion_offset(&nominal)?;
ctx.add_action(AssistId("add_derive"), "add `#[derive]`", |edit| {
ctx.add_assist(AssistId("add_derive"), "add `#[derive]`", |edit| {
let derive_attr = nominal
.attrs()
.filter_map(|x| x.as_simple_call())
@ -44,9 +44,7 @@ pub(crate) fn add_derive(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
};
edit.target(nominal.syntax().text_range());
edit.set_cursor(offset)
});
ctx.build()
})
}
// Insert `derive` after doc comments.

View file

@ -21,7 +21,7 @@ use crate::{Assist, AssistCtx, AssistId};
// let x: i32 = 92;
// }
// ```
pub(crate) fn add_explicit_type(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn add_explicit_type(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let stmt = ctx.find_node_at_offset::<LetStmt>()?;
let expr = stmt.initializer()?;
let pat = stmt.pat()?;
@ -47,11 +47,10 @@ pub(crate) fn add_explicit_type(mut ctx: AssistCtx<impl HirDatabase>) -> Option<
return None;
}
ctx.add_action(AssistId("add_explicit_type"), "add explicit type", |edit| {
ctx.add_assist(AssistId("add_explicit_type"), "add explicit type", |edit| {
edit.target(pat_range);
edit.insert(name_range.end(), format!(": {}", ty.display(db)));
});
ctx.build()
})
}
/// Returns true if any type parameter is unknown

View file

@ -27,10 +27,10 @@ use crate::{Assist, AssistCtx, AssistId};
//
// }
// ```
pub(crate) fn add_impl(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn add_impl(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let nominal = ctx.find_node_at_offset::<ast::NominalDef>()?;
let name = nominal.name()?;
ctx.add_action(AssistId("add_impl"), "add impl", |edit| {
ctx.add_assist(AssistId("add_impl"), "add impl", |edit| {
edit.target(nominal.syntax().text_range());
let type_params = nominal.type_param_list();
let start_offset = nominal.syntax().text_range().end();
@ -54,9 +54,7 @@ pub(crate) fn add_impl(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
edit.set_cursor(start_offset + TextUnit::of_str(&buf));
buf.push_str("\n}");
edit.insert(start_offset, buf);
});
ctx.build()
})
}
#[cfg(test)]

View file

@ -39,7 +39,7 @@ pub fn auto_import_text_edit(
}
}
pub(crate) fn add_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn add_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let path: ast::Path = ctx.find_node_at_offset()?;
// We don't want to mess with use statements
if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() {
@ -53,7 +53,7 @@ pub(crate) fn add_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
}
let module = path.syntax().ancestors().find_map(ast::Module::cast);
let anchor = match module.and_then(|it| it.item_list()) {
let position = match module.and_then(|it| it.item_list()) {
Some(item_list) => item_list.syntax().clone(),
None => {
let current_file = path.syntax().ancestors().find_map(ast::SourceFile::cast)?;
@ -61,11 +61,9 @@ pub(crate) fn add_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
}
};
ctx.add_action(AssistId("add_import"), format!("import {}", fmt_segments(&segments)), |edit| {
apply_auto_import(&anchor, &path, &segments, edit.text_edit_builder());
});
ctx.build()
ctx.add_assist(AssistId("add_import"), format!("import {}", fmt_segments(&segments)), |edit| {
apply_auto_import(&position, &path, &segments, edit.text_edit_builder());
})
}
fn collect_path_segments_raw(

View file

@ -91,7 +91,7 @@ pub(crate) fn add_missing_default_members(ctx: AssistCtx<impl HirDatabase>) -> O
}
fn add_missing_impl_members_inner(
mut ctx: AssistCtx<impl HirDatabase>,
ctx: AssistCtx<impl HirDatabase>,
mode: AddMissingImplMembersMode,
assist_id: &'static str,
label: &'static str,
@ -133,7 +133,7 @@ fn add_missing_impl_members_inner(
return None;
}
ctx.add_action(AssistId(assist_id), label, |edit| {
ctx.add_assist(AssistId(assist_id), label, |edit| {
let n_existing_items = impl_item_list.impl_items().count();
let items = missing_items
.into_iter()
@ -150,9 +150,7 @@ fn add_missing_impl_members_inner(
edit.replace_ast(impl_item_list, new_impl_item_list);
edit.set_cursor(cursor_position);
});
ctx.build()
})
}
fn add_body(fn_def: ast::FnDef) -> ast::FnDef {

View file

@ -23,7 +23,7 @@ use crate::{Assist, AssistCtx, AssistId};
// if !(x == 4 && y) {}
// }
// ```
pub(crate) fn apply_demorgan(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn apply_demorgan(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let expr = ctx.find_node_at_offset::<ast::BinExpr>()?;
let op = expr.op_kind()?;
let op_range = expr.op_token()?.text_range();
@ -39,13 +39,12 @@ pub(crate) fn apply_demorgan(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Ass
let not_lhs = undo_negation(lhs)?;
let not_rhs = undo_negation(rhs)?;
ctx.add_action(AssistId("apply_demorgan"), "apply demorgan's law", |edit| {
ctx.add_assist(AssistId("apply_demorgan"), "apply demorgan's law", |edit| {
edit.target(op_range);
edit.replace(op_range, opposite_op);
edit.replace(lhs_range, format!("!({}", not_lhs));
edit.replace(rhs_range, format!("{})", not_rhs));
});
ctx.build()
})
}
// Return the opposite text for a given logical operator, if it makes sense

View file

@ -29,7 +29,7 @@ pub(crate) fn change_visibility(ctx: AssistCtx<impl HirDatabase>) -> Option<Assi
add_vis(ctx)
}
fn add_vis(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
fn add_vis(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let item_keyword = ctx.token_at_offset().find(|leaf| match leaf.kind() {
T![fn] | T![mod] | T![struct] | T![enum] | T![trait] => true,
_ => false,
@ -57,13 +57,11 @@ fn add_vis(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
(vis_offset(field.syntax()), ident.text_range())
};
ctx.add_action(AssistId("change_visibility"), "make pub(crate)", |edit| {
ctx.add_assist(AssistId("change_visibility"), "make pub(crate)", |edit| {
edit.target(target);
edit.insert(offset, "pub(crate) ");
edit.set_cursor(offset);
});
ctx.build()
})
}
fn vis_offset(node: &SyntaxNode) -> TextUnit {
@ -77,24 +75,20 @@ fn vis_offset(node: &SyntaxNode) -> TextUnit {
.unwrap_or_else(|| node.text_range().start())
}
fn change_vis(mut ctx: AssistCtx<impl HirDatabase>, vis: ast::Visibility) -> Option<Assist> {
fn change_vis(ctx: AssistCtx<impl HirDatabase>, vis: ast::Visibility) -> Option<Assist> {
if vis.syntax().text() == "pub" {
ctx.add_action(AssistId("change_visibility"), "change to pub(crate)", |edit| {
return ctx.add_assist(AssistId("change_visibility"), "change to pub(crate)", |edit| {
edit.target(vis.syntax().text_range());
edit.replace(vis.syntax().text_range(), "pub(crate)");
edit.set_cursor(vis.syntax().text_range().start())
});
return ctx.build();
}
if vis.syntax().text() == "pub(crate)" {
ctx.add_action(AssistId("change_visibility"), "change to pub", |edit| {
return ctx.add_assist(AssistId("change_visibility"), "change to pub", |edit| {
edit.target(vis.syntax().text_range());
edit.replace(vis.syntax().text_range(), "pub");
edit.set_cursor(vis.syntax().text_range().start());
});
return ctx.build();
}
None
}

View file

@ -35,7 +35,7 @@ use crate::{
// bar();
// }
// ```
pub(crate) fn convert_to_guarded_return(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn convert_to_guarded_return(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
let expr = if_expr.condition()?.expr()?;
let then_block = if_expr.then_branch()?.block()?;
@ -75,7 +75,7 @@ pub(crate) fn convert_to_guarded_return(mut ctx: AssistCtx<impl HirDatabase>) ->
then_block.syntax().last_child_or_token().filter(|t| t.kind() == R_CURLY)?;
let cursor_position = ctx.frange.range.start();
ctx.add_action(AssistId("convert_to_guarded_return"), "convert to guarded return", |edit| {
ctx.add_assist(AssistId("convert_to_guarded_return"), "convert to guarded return", |edit| {
let if_indent_level = IndentLevel::from_node(&if_expr.syntax());
let new_if_expr =
if_indent_level.increase_indent(make::if_expression(&expr, early_expression));
@ -105,8 +105,7 @@ pub(crate) fn convert_to_guarded_return(mut ctx: AssistCtx<impl HirDatabase>) ->
edit.target(if_expr.syntax().text_range());
edit.replace_ast(parent_block, ast::Block::cast(new_block).unwrap());
edit.set_cursor(cursor_position);
});
ctx.build()
})
}
#[cfg(test)]

View file

@ -31,7 +31,7 @@ use crate::{Assist, AssistCtx, AssistId};
// }
// }
// ```
pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn fill_match_arms(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let match_expr = ctx.find_node_at_offset::<ast::MatchExpr>()?;
let match_arm_list = match_expr.match_arm_list()?;
@ -53,7 +53,7 @@ pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
};
let variant_list = enum_def.variant_list()?;
ctx.add_action(AssistId("fill_match_arms"), "fill match arms", |edit| {
ctx.add_assist(AssistId("fill_match_arms"), "fill match arms", |edit| {
let indent_level = IndentLevel::from_node(match_arm_list.syntax());
let new_arm_list = {
@ -67,9 +67,7 @@ pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
edit.target(match_expr.syntax().text_range());
edit.set_cursor(expr.syntax().text_range().start());
edit.replace_ast(match_arm_list, new_arm_list);
});
ctx.build()
})
}
fn is_trivial(arm: &ast::MatchArm) -> bool {

View file

@ -18,7 +18,7 @@ use crate::{Assist, AssistCtx, AssistId};
// let _ = 2 + 90;
// }
// ```
pub(crate) fn flip_binexpr(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn flip_binexpr(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let expr = ctx.find_node_at_offset::<BinExpr>()?;
let lhs = expr.lhs()?.syntax().clone();
let rhs = expr.rhs()?.syntax().clone();
@ -34,16 +34,14 @@ pub(crate) fn flip_binexpr(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assis
return None;
}
ctx.add_action(AssistId("flip_binexpr"), "flip binary expression", |edit| {
ctx.add_assist(AssistId("flip_binexpr"), "flip binary expression", |edit| {
edit.target(op_range);
if let FlipAction::FlipAndReplaceOp(new_op) = action {
edit.replace(op_range, new_op);
}
edit.replace(lhs.text_range(), rhs.text());
edit.replace(rhs.text_range(), lhs.text());
});
ctx.build()
})
}
enum FlipAction {

View file

@ -18,7 +18,7 @@ use crate::{Assist, AssistCtx, AssistId};
// ((3, 4), (1, 2));
// }
// ```
pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn flip_comma(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let comma = ctx.find_token_at_offset(T![,])?;
let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?;
let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?;
@ -29,13 +29,11 @@ pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
return None;
}
ctx.add_action(AssistId("flip_comma"), "flip comma", |edit| {
ctx.add_assist(AssistId("flip_comma"), "flip comma", |edit| {
edit.target(comma.text_range());
edit.replace(prev.text_range(), next.to_string());
edit.replace(next.text_range(), prev.to_string());
});
ctx.build()
})
}
#[cfg(test)]

View file

@ -18,7 +18,7 @@ use crate::{Assist, AssistCtx, AssistId};
// ```
// fn foo<T: Copy + Clone>() { }
// ```
pub(crate) fn flip_trait_bound(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn flip_trait_bound(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
// We want to replicate the behavior of `flip_binexpr` by only suggesting
// the assist when the cursor is on a `+`
let plus = ctx.find_token_at_offset(T![+])?;
@ -33,13 +33,11 @@ pub(crate) fn flip_trait_bound(mut ctx: AssistCtx<impl HirDatabase>) -> Option<A
non_trivia_sibling(plus.clone().into(), Direction::Next)?,
);
ctx.add_action(AssistId("flip_trait_bound"), "flip trait bound", |edit| {
ctx.add_assist(AssistId("flip_trait_bound"), "flip trait bound", |edit| {
edit.target(plus.text_range());
edit.replace(before.text_range(), after.to_string());
edit.replace(after.text_range(), before.to_string());
});
ctx.build()
})
}
#[cfg(test)]

View file

@ -23,7 +23,7 @@ use crate::{Assist, AssistCtx, AssistId};
// (1 + 2) * 4;
// }
// ```
pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn inline_local_varialbe(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let let_stmt = ctx.find_node_at_offset::<ast::LetStmt>()?;
let bind_pat = match let_stmt.pat()? {
ast::Pat::BindPat(pat) => pat,
@ -93,7 +93,7 @@ pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Opt
let init_str = initializer_expr.syntax().text().to_string();
let init_in_paren = format!("({})", &init_str);
ctx.add_action(
ctx.add_assist(
AssistId("inline_local_variable"),
"inline local variable",
move |edit: &mut AssistBuilder| {
@ -107,9 +107,7 @@ pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Opt
}
edit.set_cursor(delete_range.start())
},
);
ctx.build()
)
}
#[cfg(test)]

View file

@ -28,7 +28,7 @@ use crate::{Assist, AssistCtx, AssistId};
// var_name * 4;
// }
// ```
pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn introduce_variable(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
if ctx.frange.range.is_empty() {
return None;
}
@ -43,7 +43,7 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
if indent.kind() != WHITESPACE {
return None;
}
ctx.add_action(AssistId("introduce_variable"), "introduce variable", move |edit| {
ctx.add_assist(AssistId("introduce_variable"), "introduce variable", move |edit| {
let mut buf = String::new();
let cursor_offset = if wrap_in_block {
@ -88,9 +88,7 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
}
}
edit.set_cursor(anchor_stmt.text_range().start() + cursor_offset);
});
ctx.build()
})
}
/// Check whether the node is a valid expression which can be extracted to a variable.

View file

@ -26,7 +26,7 @@ use ra_syntax::ast::{AstNode, MatchArm};
// }
// }
// ```
pub(crate) fn merge_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn merge_match_arms(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let current_arm = ctx.find_node_at_offset::<MatchArm>()?;
// We check if the following match arm matches this one. We could, but don't,
@ -52,7 +52,7 @@ pub(crate) fn merge_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<A
let cursor_to_end = current_arm.syntax().text_range().end() - ctx.frange.range.start();
ctx.add_action(AssistId("merge_match_arms"), "merge match arms", |edit| {
ctx.add_assist(AssistId("merge_match_arms"), "merge match arms", |edit| {
fn contains_placeholder(a: &MatchArm) -> bool {
a.pats().any(|x| match x {
ra_syntax::ast::Pat::PlaceholderPat(..) => true,
@ -80,9 +80,7 @@ pub(crate) fn merge_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<A
edit.target(current_arm.syntax().text_range());
edit.replace(TextRange::from_to(start, end), arm);
edit.set_cursor(start + offset);
});
ctx.build()
})
}
#[cfg(test)]

View file

@ -22,7 +22,7 @@ use crate::{Assist, AssistCtx, AssistId};
// f(x)
// }
// ```
pub(crate) fn move_bounds_to_where_clause(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn move_bounds_to_where_clause(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let type_param_list = ctx.find_node_at_offset::<ast::TypeParamList>()?;
let mut type_params = type_param_list.type_params();
@ -46,38 +46,30 @@ pub(crate) fn move_bounds_to_where_clause(mut ctx: AssistCtx<impl HirDatabase>)
_ => return None,
};
ctx.add_action(
AssistId("move_bounds_to_where_clause"),
"move_bounds_to_where_clause",
|edit| {
let new_params = type_param_list
.type_params()
.filter(|it| it.type_bound_list().is_some())
.map(|type_param| {
let without_bounds = type_param.remove_bounds();
(type_param, without_bounds)
});
ctx.add_assist(AssistId("move_bounds_to_where_clause"), "move_bounds_to_where_clause", |edit| {
let new_params = type_param_list
.type_params()
.filter(|it| it.type_bound_list().is_some())
.map(|type_param| {
let without_bounds = type_param.remove_bounds();
(type_param, without_bounds)
});
let new_type_param_list = edit::replace_descendants(&type_param_list, new_params);
edit.replace_ast(type_param_list.clone(), new_type_param_list);
let new_type_param_list = edit::replace_descendants(&type_param_list, new_params);
edit.replace_ast(type_param_list.clone(), new_type_param_list);
let where_clause = {
let predicates = type_param_list.type_params().filter_map(build_predicate);
make::where_clause(predicates)
};
let where_clause = {
let predicates = type_param_list.type_params().filter_map(build_predicate);
make::where_clause(predicates)
};
let to_insert = match anchor.prev_sibling_or_token() {
Some(ref elem) if elem.kind() == WHITESPACE => {
format!("{} ", where_clause.syntax())
}
_ => format!(" {}", where_clause.syntax()),
};
edit.insert(anchor.text_range().start(), to_insert);
edit.target(type_param_list.syntax().text_range());
},
);
ctx.build()
let to_insert = match anchor.prev_sibling_or_token() {
Some(ref elem) if elem.kind() == WHITESPACE => format!("{} ", where_clause.syntax()),
_ => format!(" {}", where_clause.syntax()),
};
edit.insert(anchor.text_range().start(), to_insert);
edit.target(type_param_list.syntax().text_range());
})
}
fn build_predicate(param: ast::TypeParam) -> Option<ast::WherePred> {

View file

@ -32,7 +32,7 @@ use crate::{Assist, AssistCtx, AssistId};
// }
// }
// ```
pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn move_guard_to_arm_body(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let match_arm = ctx.find_node_at_offset::<MatchArm>()?;
let guard = match_arm.guard()?;
let space_before_guard = guard.syntax().prev_sibling_or_token();
@ -41,7 +41,7 @@ pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Op
let arm_expr = match_arm.expr()?;
let buf = format!("if {} {{ {} }}", guard_conditions.syntax().text(), arm_expr.syntax().text());
ctx.add_action(AssistId("move_guard_to_arm_body"), "move guard to arm body", |edit| {
ctx.add_assist(AssistId("move_guard_to_arm_body"), "move guard to arm body", |edit| {
edit.target(guard.syntax().text_range());
let offseting_amount = match space_before_guard.and_then(|it| it.into_token()) {
Some(tok) => {
@ -61,8 +61,7 @@ pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Op
edit.set_cursor(
arm_expr.syntax().text_range().start() + TextUnit::from(3) - offseting_amount,
);
});
ctx.build()
})
}
// Assist: move_arm_cond_to_match_guard
@ -90,7 +89,7 @@ pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Op
// }
// }
// ```
pub(crate) fn move_arm_cond_to_match_guard(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn move_arm_cond_to_match_guard(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let match_arm: MatchArm = ctx.find_node_at_offset::<MatchArm>()?;
let last_match_pat = match_arm.pats().last()?;
@ -110,7 +109,7 @@ pub(crate) fn move_arm_cond_to_match_guard(mut ctx: AssistCtx<impl HirDatabase>)
let buf = format!(" if {}", cond.syntax().text());
ctx.add_action(
ctx.add_assist(
AssistId("move_arm_cond_to_match_guard"),
"move condition to match guard",
|edit| {
@ -127,8 +126,7 @@ pub(crate) fn move_arm_cond_to_match_guard(mut ctx: AssistCtx<impl HirDatabase>)
edit.insert(last_match_pat.syntax().text_range().end(), buf);
edit.set_cursor(last_match_pat.syntax().text_range().end() + TextUnit::from(1));
},
);
ctx.build()
)
}
#[cfg(test)]

View file

@ -22,7 +22,7 @@ use crate::{Assist, AssistCtx, AssistId};
// r#"Hello, World!"#;
// }
// ```
pub(crate) fn make_raw_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn make_raw_string(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let token = ctx.find_token_at_offset(STRING)?;
let text = token.text().as_str();
let usual_string_range = find_usual_string_range(text)?;
@ -41,7 +41,7 @@ pub(crate) fn make_raw_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
if error.is_err() {
return None;
}
ctx.add_action(AssistId("make_raw_string"), "make raw string", |edit| {
ctx.add_assist(AssistId("make_raw_string"), "make raw string", |edit| {
edit.target(token.text_range());
let max_hash_streak = count_hashes(&unescaped);
let mut hashes = String::with_capacity(max_hash_streak + 1);
@ -49,8 +49,7 @@ pub(crate) fn make_raw_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
hashes.push('#');
}
edit.replace(token.text_range(), format!("r{}\"{}\"{}", hashes, unescaped, hashes));
});
ctx.build()
})
}
// Assist: make_usual_string
@ -68,11 +67,11 @@ pub(crate) fn make_raw_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
// "Hello, \"World!\"";
// }
// ```
pub(crate) fn make_usual_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn make_usual_string(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let token = ctx.find_token_at_offset(RAW_STRING)?;
let text = token.text().as_str();
let usual_string_range = find_usual_string_range(text)?;
ctx.add_action(AssistId("make_usual_string"), "make usual string", |edit| {
ctx.add_assist(AssistId("make_usual_string"), "make usual string", |edit| {
edit.target(token.text_range());
// parse inside string to escape `"`
let start_of_inside = usual_string_range.start().to_usize() + 1;
@ -80,8 +79,7 @@ pub(crate) fn make_usual_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<
let inside_str = &text[start_of_inside..end_of_inside];
let escaped = inside_str.escape_default().to_string();
edit.replace(token.text_range(), format!("\"{}\"", escaped));
});
ctx.build()
})
}
// Assist: add_hash
@ -99,14 +97,13 @@ pub(crate) fn make_usual_string(mut ctx: AssistCtx<impl HirDatabase>) -> Option<
// r##"Hello, World!"##;
// }
// ```
pub(crate) fn add_hash(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn add_hash(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let token = ctx.find_token_at_offset(RAW_STRING)?;
ctx.add_action(AssistId("add_hash"), "add hash to raw string", |edit| {
ctx.add_assist(AssistId("add_hash"), "add hash to raw string", |edit| {
edit.target(token.text_range());
edit.insert(token.text_range().start() + TextUnit::of_char('r'), "#");
edit.insert(token.text_range().end(), "#");
});
ctx.build()
})
}
// Assist: remove_hash
@ -124,14 +121,14 @@ pub(crate) fn add_hash(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
// r"Hello, World!";
// }
// ```
pub(crate) fn remove_hash(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn remove_hash(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let token = ctx.find_token_at_offset(RAW_STRING)?;
let text = token.text().as_str();
if text.starts_with("r\"") {
// no hash to remove
return None;
}
ctx.add_action(AssistId("remove_hash"), "remove hash from raw string", |edit| {
ctx.add_assist(AssistId("remove_hash"), "remove hash from raw string", |edit| {
edit.target(token.text_range());
let result = &text[2..text.len() - 1];
let result = if result.starts_with("\"") {
@ -142,8 +139,7 @@ pub(crate) fn remove_hash(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist
result.to_owned()
};
edit.replace(token.text_range(), format!("r{}", result));
});
ctx.build()
})
}
fn count_hashes(s: &str) -> usize {

View file

@ -21,7 +21,7 @@ use crate::{Assist, AssistCtx, AssistId};
// 92;
// }
// ```
pub(crate) fn remove_dbg(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn remove_dbg(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let macro_call = ctx.find_node_at_offset::<ast::MacroCall>()?;
if !is_valid_macrocall(&macro_call, "dbg")? {
@ -58,13 +58,11 @@ pub(crate) fn remove_dbg(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
text.slice(without_parens).to_string()
};
ctx.add_action(AssistId("remove_dbg"), "remove dbg!()", |edit| {
ctx.add_assist(AssistId("remove_dbg"), "remove dbg!()", |edit| {
edit.target(macro_call.syntax().text_range());
edit.replace(macro_range, macro_content);
edit.set_cursor(cursor_pos);
});
ctx.build()
})
}
/// Verifies that the given macro_call actually matches the given name

View file

@ -31,7 +31,7 @@ use crate::{Assist, AssistCtx, AssistId};
// }
// }
// ```
pub(crate) fn replace_if_let_with_match(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn replace_if_let_with_match(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
let cond = if_expr.condition()?;
let pat = cond.pat()?;
@ -42,14 +42,12 @@ pub(crate) fn replace_if_let_with_match(mut ctx: AssistCtx<impl HirDatabase>) ->
ast::ElseBranch::IfExpr(_) => return None,
};
ctx.add_action(AssistId("replace_if_let_with_match"), "replace with match", |edit| {
ctx.add_assist(AssistId("replace_if_let_with_match"), "replace with match", |edit| {
let match_expr = build_match_expr(expr, pat, then_block, else_block);
edit.target(if_expr.syntax().text_range());
edit.replace_node_and_indent(if_expr.syntax(), match_expr);
edit.set_cursor(if_expr.syntax().text_range().start())
});
ctx.build()
})
}
fn build_match_expr(

View file

@ -16,7 +16,7 @@ use crate::{Assist, AssistCtx, AssistId};
// ```
// use std::{collections::HashMap};
// ```
pub(crate) fn split_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
pub(crate) fn split_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let colon_colon = ctx.find_token_at_offset(T![::])?;
let path = ast::Path::cast(colon_colon.parent())?;
let top_path = successors(Some(path), |it| it.parent_path()).last()?;
@ -32,14 +32,12 @@ pub(crate) fn split_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assis
None => top_path.syntax().text_range().end(),
};
ctx.add_action(AssistId("split_import"), "split import", |edit| {
ctx.add_assist(AssistId("split_import"), "split import", |edit| {
edit.target(colon_colon.text_range());
edit.insert(l_curly, "{");
edit.insert(r_curly, "}");
edit.set_cursor(l_curly + TextUnit::of_str("{"));
});
ctx.build()
})
}
#[cfg(test)]