From e4756cb4f6e66097638b9d101589358976be2ba8 Mon Sep 17 00:00:00 2001 From: Chetan Khilosiya Date: Tue, 23 Feb 2021 00:17:48 +0530 Subject: 7526: Rename crate assists to ide_assists. --- crates/ide_assists/Cargo.toml | 26 + crates/ide_assists/src/assist_config.rs | 16 + crates/ide_assists/src/assist_context.rs | 253 ++ crates/ide_assists/src/ast_transform.rs | 213 ++ .../ide_assists/src/handlers/add_explicit_type.rs | 207 ++ .../src/handlers/add_lifetime_to_type.rs | 228 ++ .../src/handlers/add_missing_impl_members.rs | 814 +++++ crates/ide_assists/src/handlers/add_turbo_fish.rs | 164 + crates/ide_assists/src/handlers/apply_demorgan.rs | 93 + crates/ide_assists/src/handlers/auto_import.rs | 970 ++++++ .../ide_assists/src/handlers/change_visibility.rs | 212 ++ .../src/handlers/convert_integer_literal.rs | 268 ++ crates/ide_assists/src/handlers/early_return.rs | 515 +++ .../ide_assists/src/handlers/expand_glob_import.rs | 907 ++++++ .../ide_assists/src/handlers/extract_function.rs | 3378 ++++++++++++++++++++ .../handlers/extract_struct_from_enum_variant.rs | 520 +++ .../ide_assists/src/handlers/extract_variable.rs | 588 ++++ crates/ide_assists/src/handlers/fill_match_arms.rs | 787 +++++ crates/ide_assists/src/handlers/fix_visibility.rs | 607 ++++ crates/ide_assists/src/handlers/flip_binexpr.rs | 134 + crates/ide_assists/src/handlers/flip_comma.rs | 84 + .../ide_assists/src/handlers/flip_trait_bound.rs | 121 + .../handlers/generate_default_from_enum_variant.rs | 175 + crates/ide_assists/src/handlers/generate_derive.rs | 132 + .../src/handlers/generate_enum_match_method.rs | 240 ++ .../src/handlers/generate_from_impl_for_enum.rs | 268 ++ .../ide_assists/src/handlers/generate_function.rs | 1071 +++++++ crates/ide_assists/src/handlers/generate_getter.rs | 192 ++ .../src/handlers/generate_getter_mut.rs | 195 ++ crates/ide_assists/src/handlers/generate_impl.rs | 166 + crates/ide_assists/src/handlers/generate_new.rs | 315 ++ crates/ide_assists/src/handlers/generate_setter.rs | 198 ++ .../src/handlers/infer_function_return_type.rs | 345 ++ crates/ide_assists/src/handlers/inline_function.rs | 202 ++ .../src/handlers/inline_local_variable.rs | 732 +++++ .../src/handlers/introduce_named_lifetime.rs | 315 ++ crates/ide_assists/src/handlers/invert_if.rs | 146 + crates/ide_assists/src/handlers/merge_imports.rs | 343 ++ .../ide_assists/src/handlers/merge_match_arms.rs | 248 ++ crates/ide_assists/src/handlers/move_bounds.rs | 152 + crates/ide_assists/src/handlers/move_guard.rs | 367 +++ .../src/handlers/move_module_to_file.rs | 188 ++ .../ide_assists/src/handlers/pull_assignment_up.rs | 400 +++ crates/ide_assists/src/handlers/qualify_path.rs | 1205 +++++++ crates/ide_assists/src/handlers/raw_string.rs | 512 +++ crates/ide_assists/src/handlers/remove_dbg.rs | 421 +++ crates/ide_assists/src/handlers/remove_mut.rs | 37 + .../src/handlers/remove_unused_param.rs | 288 ++ crates/ide_assists/src/handlers/reorder_fields.rs | 227 ++ crates/ide_assists/src/handlers/reorder_impl.rs | 201 ++ .../handlers/replace_derive_with_manual_impl.rs | 404 +++ .../src/handlers/replace_if_let_with_match.rs | 599 ++++ .../handlers/replace_impl_trait_with_generic.rs | 168 + .../src/handlers/replace_let_with_if_let.rs | 101 + .../handlers/replace_qualified_name_with_use.rs | 678 ++++ .../src/handlers/replace_string_with_char.rs | 137 + .../src/handlers/replace_unwrap_with_match.rs | 188 ++ crates/ide_assists/src/handlers/split_import.rs | 79 + crates/ide_assists/src/handlers/toggle_ignore.rs | 98 + crates/ide_assists/src/handlers/unmerge_use.rs | 231 ++ crates/ide_assists/src/handlers/unwrap_block.rs | 582 ++++ .../src/handlers/wrap_return_type_in_result.rs | 1158 +++++++ crates/ide_assists/src/lib.rs | 246 ++ crates/ide_assists/src/tests.rs | 275 ++ crates/ide_assists/src/tests/generated.rs | 1329 ++++++++ crates/ide_assists/src/utils.rs | 434 +++ 66 files changed, 27093 insertions(+) create mode 100644 crates/ide_assists/Cargo.toml create mode 100644 crates/ide_assists/src/assist_config.rs create mode 100644 crates/ide_assists/src/assist_context.rs create mode 100644 crates/ide_assists/src/ast_transform.rs create mode 100644 crates/ide_assists/src/handlers/add_explicit_type.rs create mode 100644 crates/ide_assists/src/handlers/add_lifetime_to_type.rs create mode 100644 crates/ide_assists/src/handlers/add_missing_impl_members.rs create mode 100644 crates/ide_assists/src/handlers/add_turbo_fish.rs create mode 100644 crates/ide_assists/src/handlers/apply_demorgan.rs create mode 100644 crates/ide_assists/src/handlers/auto_import.rs create mode 100644 crates/ide_assists/src/handlers/change_visibility.rs create mode 100644 crates/ide_assists/src/handlers/convert_integer_literal.rs create mode 100644 crates/ide_assists/src/handlers/early_return.rs create mode 100644 crates/ide_assists/src/handlers/expand_glob_import.rs create mode 100644 crates/ide_assists/src/handlers/extract_function.rs create mode 100644 crates/ide_assists/src/handlers/extract_struct_from_enum_variant.rs create mode 100644 crates/ide_assists/src/handlers/extract_variable.rs create mode 100644 crates/ide_assists/src/handlers/fill_match_arms.rs create mode 100644 crates/ide_assists/src/handlers/fix_visibility.rs create mode 100644 crates/ide_assists/src/handlers/flip_binexpr.rs create mode 100644 crates/ide_assists/src/handlers/flip_comma.rs create mode 100644 crates/ide_assists/src/handlers/flip_trait_bound.rs create mode 100644 crates/ide_assists/src/handlers/generate_default_from_enum_variant.rs create mode 100644 crates/ide_assists/src/handlers/generate_derive.rs create mode 100644 crates/ide_assists/src/handlers/generate_enum_match_method.rs create mode 100644 crates/ide_assists/src/handlers/generate_from_impl_for_enum.rs create mode 100644 crates/ide_assists/src/handlers/generate_function.rs create mode 100644 crates/ide_assists/src/handlers/generate_getter.rs create mode 100644 crates/ide_assists/src/handlers/generate_getter_mut.rs create mode 100644 crates/ide_assists/src/handlers/generate_impl.rs create mode 100644 crates/ide_assists/src/handlers/generate_new.rs create mode 100644 crates/ide_assists/src/handlers/generate_setter.rs create mode 100644 crates/ide_assists/src/handlers/infer_function_return_type.rs create mode 100644 crates/ide_assists/src/handlers/inline_function.rs create mode 100644 crates/ide_assists/src/handlers/inline_local_variable.rs create mode 100644 crates/ide_assists/src/handlers/introduce_named_lifetime.rs create mode 100644 crates/ide_assists/src/handlers/invert_if.rs create mode 100644 crates/ide_assists/src/handlers/merge_imports.rs create mode 100644 crates/ide_assists/src/handlers/merge_match_arms.rs create mode 100644 crates/ide_assists/src/handlers/move_bounds.rs create mode 100644 crates/ide_assists/src/handlers/move_guard.rs create mode 100644 crates/ide_assists/src/handlers/move_module_to_file.rs create mode 100644 crates/ide_assists/src/handlers/pull_assignment_up.rs create mode 100644 crates/ide_assists/src/handlers/qualify_path.rs create mode 100644 crates/ide_assists/src/handlers/raw_string.rs create mode 100644 crates/ide_assists/src/handlers/remove_dbg.rs create mode 100644 crates/ide_assists/src/handlers/remove_mut.rs create mode 100644 crates/ide_assists/src/handlers/remove_unused_param.rs create mode 100644 crates/ide_assists/src/handlers/reorder_fields.rs create mode 100644 crates/ide_assists/src/handlers/reorder_impl.rs create mode 100644 crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs create mode 100644 crates/ide_assists/src/handlers/replace_if_let_with_match.rs create mode 100644 crates/ide_assists/src/handlers/replace_impl_trait_with_generic.rs create mode 100644 crates/ide_assists/src/handlers/replace_let_with_if_let.rs create mode 100644 crates/ide_assists/src/handlers/replace_qualified_name_with_use.rs create mode 100644 crates/ide_assists/src/handlers/replace_string_with_char.rs create mode 100644 crates/ide_assists/src/handlers/replace_unwrap_with_match.rs create mode 100644 crates/ide_assists/src/handlers/split_import.rs create mode 100644 crates/ide_assists/src/handlers/toggle_ignore.rs create mode 100644 crates/ide_assists/src/handlers/unmerge_use.rs create mode 100644 crates/ide_assists/src/handlers/unwrap_block.rs create mode 100644 crates/ide_assists/src/handlers/wrap_return_type_in_result.rs create mode 100644 crates/ide_assists/src/lib.rs create mode 100644 crates/ide_assists/src/tests.rs create mode 100644 crates/ide_assists/src/tests/generated.rs create mode 100644 crates/ide_assists/src/utils.rs (limited to 'crates/ide_assists') diff --git a/crates/ide_assists/Cargo.toml b/crates/ide_assists/Cargo.toml new file mode 100644 index 000000000..a34bdd6c3 --- /dev/null +++ b/crates/ide_assists/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "ide_assists" +version = "0.0.0" +description = "TBD" +license = "MIT OR Apache-2.0" +authors = ["rust-analyzer developers"] +edition = "2018" + +[lib] +doctest = false + +[dependencies] +rustc-hash = "1.1.0" +itertools = "0.10.0" +either = "1.6.1" + +stdx = { path = "../stdx", version = "0.0.0" } +syntax = { path = "../syntax", version = "0.0.0" } +text_edit = { path = "../text_edit", version = "0.0.0" } +profile = { path = "../profile", version = "0.0.0" } +ide_db = { path = "../ide_db", version = "0.0.0" } +hir = { path = "../hir", version = "0.0.0" } +test_utils = { path = "../test_utils", version = "0.0.0" } + +[dev-dependencies] +expect-test = "1.1" diff --git a/crates/ide_assists/src/assist_config.rs b/crates/ide_assists/src/assist_config.rs new file mode 100644 index 000000000..9cabf037c --- /dev/null +++ b/crates/ide_assists/src/assist_config.rs @@ -0,0 +1,16 @@ +//! Settings for tweaking assists. +//! +//! The fun thing here is `SnippetCap` -- this type can only be created in this +//! module, and we use to statically check that we only produce snippet +//! assists if we are allowed to. + +use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap}; + +use crate::AssistKind; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AssistConfig { + pub snippet_cap: Option, + pub allowed: Option>, + pub insert_use: InsertUseConfig, +} diff --git a/crates/ide_assists/src/assist_context.rs b/crates/ide_assists/src/assist_context.rs new file mode 100644 index 000000000..bba6c08e0 --- /dev/null +++ b/crates/ide_assists/src/assist_context.rs @@ -0,0 +1,253 @@ +//! See `AssistContext` + +use std::mem; + +use hir::Semantics; +use ide_db::{ + base_db::{AnchoredPathBuf, FileId, FileRange}, + helpers::SnippetCap, +}; +use ide_db::{ + label::Label, + source_change::{FileSystemEdit, SourceChange}, + RootDatabase, +}; +use syntax::{ + algo::{self, find_node_at_offset, SyntaxRewriter}, + AstNode, AstToken, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange, TextSize, + TokenAtOffset, +}; +use text_edit::{TextEdit, TextEditBuilder}; + +use crate::{assist_config::AssistConfig, Assist, AssistId, AssistKind, GroupLabel}; + +/// `AssistContext` allows to apply an assist or check if it could be applied. +/// +/// Assists use a somewhat over-engineered approach, given the current needs. +/// The assists workflow consists of two phases. In the first phase, a user asks +/// for the list of available assists. In the second phase, the user picks a +/// particular assist and it gets applied. +/// +/// There are two peculiarities here: +/// +/// * first, we ideally avoid computing more things then necessary to answer "is +/// assist applicable" in the first phase. +/// * second, when we are applying assist, we don't have a guarantee that there +/// weren't any changes between the point when user asked for assists and when +/// they applied a particular assist. So, when applying assist, we need to do +/// all the checks from scratch. +/// +/// To avoid repeating the same code twice for both "check" and "apply" +/// functions, we use an approach reminiscent of that of Django's function based +/// views dealing with forms. Each assist receives a runtime parameter, +/// `resolve`. It first check if an edit is applicable (potentially computing +/// info required to compute the actual edit). If it is applicable, and +/// `resolve` is `true`, it then computes the actual edit. +/// +/// So, to implement the original assists workflow, we can first apply each edit +/// with `resolve = false`, and then applying the selected edit again, with +/// `resolve = true` this time. +/// +/// Note, however, that we don't actually use such two-phase logic at the +/// moment, because the LSP API is pretty awkward in this place, and it's much +/// easier to just compute the edit eagerly :-) +pub(crate) struct AssistContext<'a> { + pub(crate) config: &'a AssistConfig, + pub(crate) sema: Semantics<'a, RootDatabase>, + pub(crate) frange: FileRange, + source_file: SourceFile, +} + +impl<'a> AssistContext<'a> { + pub(crate) fn new( + sema: Semantics<'a, RootDatabase>, + config: &'a AssistConfig, + frange: FileRange, + ) -> AssistContext<'a> { + let source_file = sema.parse(frange.file_id); + AssistContext { config, sema, frange, source_file } + } + + pub(crate) fn db(&self) -> &RootDatabase { + self.sema.db + } + + // NB, this ignores active selection. + pub(crate) fn offset(&self) -> TextSize { + self.frange.range.start() + } + + pub(crate) fn token_at_offset(&self) -> TokenAtOffset { + self.source_file.syntax().token_at_offset(self.offset()) + } + pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option { + self.token_at_offset().find(|it| it.kind() == kind) + } + pub(crate) fn find_token_at_offset(&self) -> Option { + self.token_at_offset().find_map(T::cast) + } + pub(crate) fn find_node_at_offset(&self) -> Option { + find_node_at_offset(self.source_file.syntax(), self.offset()) + } + pub(crate) fn find_node_at_offset_with_descend(&self) -> Option { + self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset()) + } + pub(crate) fn covering_element(&self) -> SyntaxElement { + self.source_file.syntax().covering_element(self.frange.range) + } + // FIXME: remove + pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement { + self.source_file.syntax().covering_element(range) + } +} + +pub(crate) struct Assists { + resolve: bool, + file: FileId, + buf: Vec, + allowed: Option>, +} + +impl Assists { + pub(crate) fn new(ctx: &AssistContext, resolve: bool) -> Assists { + Assists { + resolve, + file: ctx.frange.file_id, + buf: Vec::new(), + allowed: ctx.config.allowed.clone(), + } + } + + pub(crate) fn finish(mut self) -> Vec { + self.buf.sort_by_key(|assist| assist.target.len()); + self.buf + } + + pub(crate) fn add( + &mut self, + id: AssistId, + label: impl Into, + target: TextRange, + f: impl FnOnce(&mut AssistBuilder), + ) -> Option<()> { + if !self.is_allowed(&id) { + return None; + } + let label = Label::new(label.into()); + let assist = Assist { id, label, group: None, target, source_change: None }; + self.add_impl(assist, f) + } + + pub(crate) fn add_group( + &mut self, + group: &GroupLabel, + id: AssistId, + label: impl Into, + target: TextRange, + f: impl FnOnce(&mut AssistBuilder), + ) -> Option<()> { + if !self.is_allowed(&id) { + return None; + } + let label = Label::new(label.into()); + let assist = Assist { id, label, group: Some(group.clone()), target, source_change: None }; + self.add_impl(assist, f) + } + + fn add_impl(&mut self, mut assist: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> { + let source_change = if self.resolve { + let mut builder = AssistBuilder::new(self.file); + f(&mut builder); + Some(builder.finish()) + } else { + None + }; + assist.source_change = source_change; + + self.buf.push(assist); + Some(()) + } + + fn is_allowed(&self, id: &AssistId) -> bool { + match &self.allowed { + Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)), + None => true, + } + } +} + +pub(crate) struct AssistBuilder { + edit: TextEditBuilder, + file_id: FileId, + source_change: SourceChange, +} + +impl AssistBuilder { + pub(crate) fn new(file_id: FileId) -> AssistBuilder { + AssistBuilder { edit: TextEdit::builder(), file_id, source_change: SourceChange::default() } + } + + pub(crate) fn edit_file(&mut self, file_id: FileId) { + self.commit(); + self.file_id = file_id; + } + + fn commit(&mut self) { + let edit = mem::take(&mut self.edit).finish(); + if !edit.is_empty() { + self.source_change.insert_source_edit(self.file_id, edit); + } + } + + /// Remove specified `range` of text. + pub(crate) fn delete(&mut self, range: TextRange) { + self.edit.delete(range) + } + /// Append specified `text` at the given `offset` + pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into) { + self.edit.insert(offset, text.into()) + } + /// Append specified `snippet` at the given `offset` + pub(crate) fn insert_snippet( + &mut self, + _cap: SnippetCap, + offset: TextSize, + snippet: impl Into, + ) { + self.source_change.is_snippet = true; + self.insert(offset, snippet); + } + /// Replaces specified `range` of text with a given string. + pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into) { + self.edit.replace(range, replace_with.into()) + } + /// Replaces specified `range` of text with a given `snippet`. + pub(crate) fn replace_snippet( + &mut self, + _cap: SnippetCap, + range: TextRange, + snippet: impl Into, + ) { + self.source_change.is_snippet = true; + self.replace(range, snippet); + } + pub(crate) fn replace_ast(&mut self, old: N, new: N) { + algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit) + } + pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) { + if let Some(node) = rewriter.rewrite_root() { + let new = rewriter.rewrite(&node); + algo::diff(&node, &new).into_text_edit(&mut self.edit); + } + } + pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into) { + let file_system_edit = + FileSystemEdit::CreateFile { dst: dst, initial_contents: content.into() }; + self.source_change.push_file_system_edit(file_system_edit); + } + + fn finish(mut self) -> SourceChange { + self.commit(); + mem::take(&mut self.source_change) + } +} diff --git a/crates/ide_assists/src/ast_transform.rs b/crates/ide_assists/src/ast_transform.rs new file mode 100644 index 000000000..4a3ed7783 --- /dev/null +++ b/crates/ide_assists/src/ast_transform.rs @@ -0,0 +1,213 @@ +//! `AstTransformer`s are functions that replace nodes in an AST and can be easily combined. +use hir::{HirDisplay, PathResolution, SemanticsScope}; +use ide_db::helpers::mod_path_to_ast; +use rustc_hash::FxHashMap; +use syntax::{ + algo::SyntaxRewriter, + ast::{self, AstNode}, + SyntaxNode, +}; + +pub fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: N) -> N { + SyntaxRewriter::from_fn(|element| match element { + syntax::SyntaxElement::Node(n) => { + let replacement = transformer.get_substitution(&n, transformer)?; + Some(replacement.into()) + } + _ => None, + }) + .rewrite_ast(&node) +} + +/// `AstTransform` helps with applying bulk transformations to syntax nodes. +/// +/// This is mostly useful for IDE code generation. If you paste some existing +/// code into a new context (for example, to add method overrides to an `impl` +/// block), you generally want to appropriately qualify the names, and sometimes +/// you might want to substitute generic parameters as well: +/// +/// ``` +/// mod x { +/// pub struct A; +/// pub trait T { fn foo(&self, _: U) -> A; } +/// } +/// +/// mod y { +/// use x::T; +/// +/// impl T<()> for () { +/// // If we invoke **Add Missing Members** here, we want to copy-paste `foo`. +/// // But we want a slightly-modified version of it: +/// fn foo(&self, _: ()) -> x::A {} +/// } +/// } +/// ``` +/// +/// So, a single `AstTransform` describes such function from `SyntaxNode` to +/// `SyntaxNode`. Note that the API here is a bit too high-order and high-brow. +/// We'd want to somehow express this concept simpler, but so far nobody got to +/// simplifying this! +pub trait AstTransform<'a> { + fn get_substitution( + &self, + node: &SyntaxNode, + recur: &dyn AstTransform<'a>, + ) -> Option; + + fn or + 'a>(self, other: T) -> Box + 'a> + where + Self: Sized + 'a, + { + Box::new(Or(Box::new(self), Box::new(other))) + } +} + +struct Or<'a>(Box + 'a>, Box + 'a>); + +impl<'a> AstTransform<'a> for Or<'a> { + fn get_substitution( + &self, + node: &SyntaxNode, + recur: &dyn AstTransform<'a>, + ) -> Option { + self.0.get_substitution(node, recur).or_else(|| self.1.get_substitution(node, recur)) + } +} + +pub struct SubstituteTypeParams<'a> { + source_scope: &'a SemanticsScope<'a>, + substs: FxHashMap, +} + +impl<'a> SubstituteTypeParams<'a> { + pub fn for_trait_impl( + source_scope: &'a SemanticsScope<'a>, + // FIXME: there's implicit invariant that `trait_` and `source_scope` match... + trait_: hir::Trait, + impl_def: ast::Impl, + ) -> SubstituteTypeParams<'a> { + let substs = get_syntactic_substs(impl_def).unwrap_or_default(); + let generic_def: hir::GenericDef = trait_.into(); + let substs_by_param: FxHashMap<_, _> = generic_def + .type_params(source_scope.db) + .into_iter() + // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky + .skip(1) + // The actual list of trait type parameters may be longer than the one + // used in the `impl` block due to trailing default type parameters. + // For that case we extend the `substs` with an empty iterator so we + // can still hit those trailing values and check if they actually have + // a default type. If they do, go for that type from `hir` to `ast` so + // the resulting change can be applied correctly. + .zip(substs.into_iter().map(Some).chain(std::iter::repeat(None))) + .filter_map(|(k, v)| match v { + Some(v) => Some((k, v)), + None => { + let default = k.default(source_scope.db)?; + Some(( + k, + ast::make::ty( + &default + .display_source_code(source_scope.db, source_scope.module()?.into()) + .ok()?, + ), + )) + } + }) + .collect(); + return SubstituteTypeParams { source_scope, substs: substs_by_param }; + + // FIXME: It would probably be nicer if we could get this via HIR (i.e. get the + // trait ref, and then go from the types in the substs back to the syntax). + fn get_syntactic_substs(impl_def: ast::Impl) -> Option> { + let target_trait = impl_def.trait_()?; + let path_type = match target_trait { + ast::Type::PathType(path) => path, + _ => return None, + }; + let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?; + + let mut result = Vec::new(); + for generic_arg in generic_arg_list.generic_args() { + match generic_arg { + ast::GenericArg::TypeArg(type_arg) => result.push(type_arg.ty()?), + ast::GenericArg::AssocTypeArg(_) + | ast::GenericArg::LifetimeArg(_) + | ast::GenericArg::ConstArg(_) => (), + } + } + + Some(result) + } + } +} + +impl<'a> AstTransform<'a> for SubstituteTypeParams<'a> { + fn get_substitution( + &self, + node: &SyntaxNode, + _recur: &dyn AstTransform<'a>, + ) -> Option { + let type_ref = ast::Type::cast(node.clone())?; + let path = match &type_ref { + ast::Type::PathType(path_type) => path_type.path()?, + _ => return None, + }; + let resolution = self.source_scope.speculative_resolve(&path)?; + match resolution { + hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()), + _ => None, + } + } +} + +pub struct QualifyPaths<'a> { + target_scope: &'a SemanticsScope<'a>, + source_scope: &'a SemanticsScope<'a>, +} + +impl<'a> QualifyPaths<'a> { + pub fn new(target_scope: &'a SemanticsScope<'a>, source_scope: &'a SemanticsScope<'a>) -> Self { + Self { target_scope, source_scope } + } +} + +impl<'a> AstTransform<'a> for QualifyPaths<'a> { + fn get_substitution( + &self, + node: &SyntaxNode, + recur: &dyn AstTransform<'a>, + ) -> Option { + // FIXME handle value ns? + let from = self.target_scope.module()?; + let p = ast::Path::cast(node.clone())?; + if p.segment().and_then(|s| s.param_list()).is_some() { + // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway + return None; + } + let resolution = self.source_scope.speculative_resolve(&p)?; + match resolution { + PathResolution::Def(def) => { + let found_path = from.find_use_path(self.source_scope.db.upcast(), def)?; + let mut path = mod_path_to_ast(&found_path); + + let type_args = p + .segment() + .and_then(|s| s.generic_arg_list()) + .map(|arg_list| apply(recur, arg_list)); + if let Some(type_args) = type_args { + let last_segment = path.segment().unwrap(); + path = path.with_segment(last_segment.with_generic_args(type_args)) + } + + Some(path.syntax().clone()) + } + PathResolution::Local(_) + | PathResolution::TypeParam(_) + | PathResolution::SelfType(_) + | PathResolution::ConstParam(_) => None, + PathResolution::Macro(_) => None, + PathResolution::AssocItem(_) => None, + } + } +} diff --git a/crates/ide_assists/src/handlers/add_explicit_type.rs b/crates/ide_assists/src/handlers/add_explicit_type.rs new file mode 100644 index 000000000..cb1548cef --- /dev/null +++ b/crates/ide_assists/src/handlers/add_explicit_type.rs @@ -0,0 +1,207 @@ +use hir::HirDisplay; +use syntax::{ + ast::{self, AstNode, LetStmt, NameOwner}, + TextRange, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: add_explicit_type +// +// Specify type for a let binding. +// +// ``` +// fn main() { +// let x$0 = 92; +// } +// ``` +// -> +// ``` +// fn main() { +// let x: i32 = 92; +// } +// ``` +pub(crate) fn add_explicit_type(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let let_stmt = ctx.find_node_at_offset::()?; + let module = ctx.sema.scope(let_stmt.syntax()).module()?; + let expr = let_stmt.initializer()?; + // Must be a binding + let pat = match let_stmt.pat()? { + ast::Pat::IdentPat(bind_pat) => bind_pat, + _ => return None, + }; + let pat_range = pat.syntax().text_range(); + // The binding must have a name + let name = pat.name()?; + let name_range = name.syntax().text_range(); + let stmt_range = let_stmt.syntax().text_range(); + let eq_range = let_stmt.eq_token()?.text_range(); + // Assist should only be applicable if cursor is between 'let' and '=' + let let_range = TextRange::new(stmt_range.start(), eq_range.start()); + let cursor_in_range = let_range.contains_range(ctx.frange.range); + if !cursor_in_range { + return None; + } + // Assist not applicable if the type has already been specified + // and it has no placeholders + let ascribed_ty = let_stmt.ty(); + if let Some(ty) = &ascribed_ty { + if ty.syntax().descendants().find_map(ast::InferType::cast).is_none() { + return None; + } + } + // Infer type + let ty = ctx.sema.type_of_expr(&expr)?; + + if ty.contains_unknown() || ty.is_closure() { + return None; + } + + let inferred_type = ty.display_source_code(ctx.db(), module.into()).ok()?; + acc.add( + AssistId("add_explicit_type", AssistKind::RefactorRewrite), + format!("Insert explicit type `{}`", inferred_type), + pat_range, + |builder| match ascribed_ty { + Some(ascribed_ty) => { + builder.replace(ascribed_ty.syntax().text_range(), inferred_type); + } + None => { + builder.insert(name_range.end(), format!(": {}", inferred_type)); + } + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + #[test] + fn add_explicit_type_target() { + check_assist_target(add_explicit_type, "fn f() { let a$0 = 1; }", "a"); + } + + #[test] + fn add_explicit_type_works_for_simple_expr() { + check_assist(add_explicit_type, "fn f() { let a$0 = 1; }", "fn f() { let a: i32 = 1; }"); + } + + #[test] + fn add_explicit_type_works_for_underscore() { + check_assist(add_explicit_type, "fn f() { let a$0: _ = 1; }", "fn f() { let a: i32 = 1; }"); + } + + #[test] + fn add_explicit_type_works_for_nested_underscore() { + check_assist( + add_explicit_type, + r#" + enum Option { + Some(T), + None + } + + fn f() { + let a$0: Option<_> = Option::Some(1); + }"#, + r#" + enum Option { + Some(T), + None + } + + fn f() { + let a: Option = Option::Some(1); + }"#, + ); + } + + #[test] + fn add_explicit_type_works_for_macro_call() { + check_assist( + add_explicit_type, + r"macro_rules! v { () => {0u64} } fn f() { let a$0 = v!(); }", + r"macro_rules! v { () => {0u64} } fn f() { let a: u64 = v!(); }", + ); + } + + #[test] + fn add_explicit_type_works_for_macro_call_recursive() { + check_assist( + add_explicit_type, + r#"macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a$0 = v!(); }"#, + r#"macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a: u64 = v!(); }"#, + ); + } + + #[test] + fn add_explicit_type_not_applicable_if_ty_not_inferred() { + check_assist_not_applicable(add_explicit_type, "fn f() { let a$0 = None; }"); + } + + #[test] + fn add_explicit_type_not_applicable_if_ty_already_specified() { + check_assist_not_applicable(add_explicit_type, "fn f() { let a$0: i32 = 1; }"); + } + + #[test] + fn add_explicit_type_not_applicable_if_specified_ty_is_tuple() { + check_assist_not_applicable(add_explicit_type, "fn f() { let a$0: (i32, i32) = (3, 4); }"); + } + + #[test] + fn add_explicit_type_not_applicable_if_cursor_after_equals() { + check_assist_not_applicable( + add_explicit_type, + "fn f() {let a =$0 match 1 {2 => 3, 3 => 5};}", + ) + } + + #[test] + fn add_explicit_type_not_applicable_if_cursor_before_let() { + check_assist_not_applicable( + add_explicit_type, + "fn f() $0{let a = match 1 {2 => 3, 3 => 5};}", + ) + } + + #[test] + fn closure_parameters_are_not_added() { + check_assist_not_applicable( + add_explicit_type, + r#" +fn main() { + let multiply_by_two$0 = |i| i * 3; + let six = multiply_by_two(2); +}"#, + ) + } + + #[test] + fn default_generics_should_not_be_added() { + check_assist( + add_explicit_type, + r#" +struct Test { + k: K, + t: T, +} + +fn main() { + let test$0 = Test { t: 23u8, k: 33 }; +}"#, + r#" +struct Test { + k: K, + t: T, +} + +fn main() { + let test: Test = Test { t: 23u8, k: 33 }; +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/add_lifetime_to_type.rs b/crates/ide_assists/src/handlers/add_lifetime_to_type.rs new file mode 100644 index 000000000..2edf7b204 --- /dev/null +++ b/crates/ide_assists/src/handlers/add_lifetime_to_type.rs @@ -0,0 +1,228 @@ +use ast::FieldList; +use syntax::ast::{self, AstNode, GenericParamsOwner, NameOwner, RefType, Type}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: add_lifetime_to_type +// +// Adds a new lifetime to a struct, enum or union. +// +// ``` +// struct Point { +// x: &$0u32, +// y: u32, +// } +// ``` +// -> +// ``` +// struct Point<'a> { +// x: &'a u32, +// y: u32, +// } +// ``` +pub(crate) fn add_lifetime_to_type(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let ref_type_focused = ctx.find_node_at_offset::()?; + if ref_type_focused.lifetime().is_some() { + return None; + } + + let node = ctx.find_node_at_offset::()?; + let has_lifetime = node + .generic_param_list() + .map(|gen_list| gen_list.lifetime_params().count() > 0) + .unwrap_or_default(); + + if has_lifetime { + return None; + } + + let ref_types = fetch_borrowed_types(&node)?; + let target = node.syntax().text_range(); + + acc.add( + AssistId("add_lifetime_to_type", AssistKind::Generate), + "Add lifetime`", + target, + |builder| { + match node.generic_param_list() { + Some(gen_param) => { + if let Some(left_angle) = gen_param.l_angle_token() { + builder.insert(left_angle.text_range().end(), "'a, "); + } + } + None => { + if let Some(name) = node.name() { + builder.insert(name.syntax().text_range().end(), "<'a>"); + } + } + } + + for ref_type in ref_types { + if let Some(amp_token) = ref_type.amp_token() { + builder.insert(amp_token.text_range().end(), "'a "); + } + } + }, + ) +} + +fn fetch_borrowed_types(node: &ast::Adt) -> Option> { + let ref_types: Vec = match node { + ast::Adt::Enum(enum_) => { + let variant_list = enum_.variant_list()?; + variant_list + .variants() + .filter_map(|variant| { + let field_list = variant.field_list()?; + + find_ref_types_from_field_list(&field_list) + }) + .flatten() + .collect() + } + ast::Adt::Struct(strukt) => { + let field_list = strukt.field_list()?; + find_ref_types_from_field_list(&field_list)? + } + ast::Adt::Union(un) => { + let record_field_list = un.record_field_list()?; + record_field_list + .fields() + .filter_map(|r_field| { + if let Type::RefType(ref_type) = r_field.ty()? { + if ref_type.lifetime().is_none() { + return Some(ref_type); + } + } + + None + }) + .collect() + } + }; + + if ref_types.is_empty() { + None + } else { + Some(ref_types) + } +} + +fn find_ref_types_from_field_list(field_list: &FieldList) -> Option> { + let ref_types: Vec = match field_list { + ast::FieldList::RecordFieldList(record_list) => record_list + .fields() + .filter_map(|f| { + if let Type::RefType(ref_type) = f.ty()? { + if ref_type.lifetime().is_none() { + return Some(ref_type); + } + } + + None + }) + .collect(), + ast::FieldList::TupleFieldList(tuple_field_list) => tuple_field_list + .fields() + .filter_map(|f| { + if let Type::RefType(ref_type) = f.ty()? { + if ref_type.lifetime().is_none() { + return Some(ref_type); + } + } + + None + }) + .collect(), + }; + + if ref_types.is_empty() { + None + } else { + Some(ref_types) + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn add_lifetime_to_struct() { + check_assist( + add_lifetime_to_type, + "struct Foo { a: &$0i32 }", + "struct Foo<'a> { a: &'a i32 }", + ); + + check_assist( + add_lifetime_to_type, + "struct Foo { a: &$0i32, b: &usize }", + "struct Foo<'a> { a: &'a i32, b: &'a usize }", + ); + + check_assist( + add_lifetime_to_type, + "struct Foo { a: &$0i32, b: usize }", + "struct Foo<'a> { a: &'a i32, b: usize }", + ); + + check_assist( + add_lifetime_to_type, + "struct Foo { a: &$0T, b: usize }", + "struct Foo<'a, T> { a: &'a T, b: usize }", + ); + + check_assist_not_applicable(add_lifetime_to_type, "struct Foo<'a> { a: &$0'a i32 }"); + check_assist_not_applicable(add_lifetime_to_type, "struct Foo { a: &'a$0 i32 }"); + } + + #[test] + fn add_lifetime_to_enum() { + check_assist( + add_lifetime_to_type, + "enum Foo { Bar { a: i32 }, Other, Tuple(u32, &$0u32)}", + "enum Foo<'a> { Bar { a: i32 }, Other, Tuple(u32, &'a u32)}", + ); + + check_assist( + add_lifetime_to_type, + "enum Foo { Bar { a: &$0i32 }}", + "enum Foo<'a> { Bar { a: &'a i32 }}", + ); + + check_assist( + add_lifetime_to_type, + "enum Foo { Bar { a: &$0i32, b: &T }}", + "enum Foo<'a, T> { Bar { a: &'a i32, b: &'a T }}", + ); + + check_assist_not_applicable(add_lifetime_to_type, "enum Foo<'a> { Bar { a: &$0'a i32 }}"); + check_assist_not_applicable(add_lifetime_to_type, "enum Foo { Bar, $0Misc }"); + } + + #[test] + fn add_lifetime_to_union() { + check_assist( + add_lifetime_to_type, + "union Foo { a: &$0i32 }", + "union Foo<'a> { a: &'a i32 }", + ); + + check_assist( + add_lifetime_to_type, + "union Foo { a: &$0i32, b: &usize }", + "union Foo<'a> { a: &'a i32, b: &'a usize }", + ); + + check_assist( + add_lifetime_to_type, + "union Foo { a: &$0T, b: usize }", + "union Foo<'a, T> { a: &'a T, b: usize }", + ); + + check_assist_not_applicable(add_lifetime_to_type, "struct Foo<'a> { a: &'a $0i32 }"); + } +} diff --git a/crates/ide_assists/src/handlers/add_missing_impl_members.rs b/crates/ide_assists/src/handlers/add_missing_impl_members.rs new file mode 100644 index 000000000..63cea754d --- /dev/null +++ b/crates/ide_assists/src/handlers/add_missing_impl_members.rs @@ -0,0 +1,814 @@ +use ide_db::traits::resolve_target_trait; +use syntax::ast::{self, AstNode}; + +use crate::{ + assist_context::{AssistContext, Assists}, + utils::add_trait_assoc_items_to_impl, + utils::DefaultMethods, + utils::{filter_assoc_items, render_snippet, Cursor}, + AssistId, AssistKind, +}; + +// Assist: add_impl_missing_members +// +// Adds scaffold for required impl members. +// +// ``` +// trait Trait { +// type X; +// fn foo(&self) -> T; +// fn bar(&self) {} +// } +// +// impl Trait for () {$0 +// +// } +// ``` +// -> +// ``` +// trait Trait { +// type X; +// fn foo(&self) -> T; +// fn bar(&self) {} +// } +// +// impl Trait for () { +// $0type X; +// +// fn foo(&self) -> u32 { +// todo!() +// } +// } +// ``` +pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + add_missing_impl_members_inner( + acc, + ctx, + DefaultMethods::No, + "add_impl_missing_members", + "Implement missing members", + ) +} + +// Assist: add_impl_default_members +// +// Adds scaffold for overriding default impl members. +// +// ``` +// trait Trait { +// type X; +// fn foo(&self); +// fn bar(&self) {} +// } +// +// impl Trait for () { +// type X = (); +// fn foo(&self) {}$0 +// +// } +// ``` +// -> +// ``` +// trait Trait { +// type X; +// fn foo(&self); +// fn bar(&self) {} +// } +// +// impl Trait for () { +// type X = (); +// fn foo(&self) {} +// +// $0fn bar(&self) {} +// } +// ``` +pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + add_missing_impl_members_inner( + acc, + ctx, + DefaultMethods::Only, + "add_impl_default_members", + "Implement default members", + ) +} + +fn add_missing_impl_members_inner( + acc: &mut Assists, + ctx: &AssistContext, + mode: DefaultMethods, + assist_id: &'static str, + label: &'static str, +) -> Option<()> { + let _p = profile::span("add_missing_impl_members_inner"); + let impl_def = ctx.find_node_at_offset::()?; + let trait_ = resolve_target_trait(&ctx.sema, &impl_def)?; + + let missing_items = filter_assoc_items( + ctx.db(), + &ide_db::traits::get_missing_assoc_items(&ctx.sema, &impl_def), + mode, + ); + + if missing_items.is_empty() { + return None; + } + + let target = impl_def.syntax().text_range(); + acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| { + let target_scope = ctx.sema.scope(impl_def.syntax()); + let (new_impl_def, first_new_item) = + add_trait_assoc_items_to_impl(&ctx.sema, missing_items, trait_, impl_def, target_scope); + match ctx.config.snippet_cap { + None => builder.replace(target, new_impl_def.to_string()), + Some(cap) => { + let mut cursor = Cursor::Before(first_new_item.syntax()); + let placeholder; + if let ast::AssocItem::Fn(func) = &first_new_item { + if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) { + if m.syntax().text() == "todo!()" { + placeholder = m; + cursor = Cursor::Replace(placeholder.syntax()); + } + } + } + builder.replace_snippet( + cap, + target, + render_snippet(cap, new_impl_def.syntax(), cursor), + ) + } + }; + }) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn test_add_missing_impl_members() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { + type Output; + + const CONST: usize = 42; + + fn foo(&self); + fn bar(&self); + fn baz(&self); +} + +struct S; + +impl Foo for S { + fn bar(&self) {} +$0 +}"#, + r#" +trait Foo { + type Output; + + const CONST: usize = 42; + + fn foo(&self); + fn bar(&self); + fn baz(&self); +} + +struct S; + +impl Foo for S { + fn bar(&self) {} + + $0type Output; + + const CONST: usize = 42; + + fn foo(&self) { + todo!() + } + + fn baz(&self) { + todo!() + } +}"#, + ); + } + + #[test] + fn test_copied_overriden_members() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { + fn foo(&self); + fn bar(&self) -> bool { true } + fn baz(&self) -> u32 { 42 } +} + +struct S; + +impl Foo for S { + fn bar(&self) {} +$0 +}"#, + r#" +trait Foo { + fn foo(&self); + fn bar(&self) -> bool { true } + fn baz(&self) -> u32 { 42 } +} + +struct S; + +impl Foo for S { + fn bar(&self) {} + + fn foo(&self) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_empty_impl_def() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { fn foo(&self); } +struct S; +impl Foo for S { $0 }"#, + r#" +trait Foo { fn foo(&self); } +struct S; +impl Foo for S { + fn foo(&self) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_impl_def_without_braces() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { fn foo(&self); } +struct S; +impl Foo for S$0"#, + r#" +trait Foo { fn foo(&self); } +struct S; +impl Foo for S { + fn foo(&self) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn fill_in_type_params_1() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { fn foo(&self, t: T) -> &T; } +struct S; +impl Foo for S { $0 }"#, + r#" +trait Foo { fn foo(&self, t: T) -> &T; } +struct S; +impl Foo for S { + fn foo(&self, t: u32) -> &u32 { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn fill_in_type_params_2() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { fn foo(&self, t: T) -> &T; } +struct S; +impl Foo for S { $0 }"#, + r#" +trait Foo { fn foo(&self, t: T) -> &T; } +struct S; +impl Foo for S { + fn foo(&self, t: U) -> &U { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_cursor_after_empty_impl_def() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { fn foo(&self); } +struct S; +impl Foo for S {}$0"#, + r#" +trait Foo { fn foo(&self); } +struct S; +impl Foo for S { + fn foo(&self) { + ${0:todo!()} + } +}"#, + ) + } + + #[test] + fn test_qualify_path_1() { + check_assist( + add_missing_impl_members, + r#" +mod foo { + pub struct Bar; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { $0 }"#, + r#" +mod foo { + pub struct Bar; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { + fn foo(&self, bar: foo::Bar) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_qualify_path_2() { + check_assist( + add_missing_impl_members, + r#" +mod foo { + pub mod bar { + pub struct Bar; + pub trait Foo { fn foo(&self, bar: Bar); } + } +} + +use foo::bar; + +struct S; +impl bar::Foo for S { $0 }"#, + r#" +mod foo { + pub mod bar { + pub struct Bar; + pub trait Foo { fn foo(&self, bar: Bar); } + } +} + +use foo::bar; + +struct S; +impl bar::Foo for S { + fn foo(&self, bar: bar::Bar) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_qualify_path_generic() { + check_assist( + add_missing_impl_members, + r#" +mod foo { + pub struct Bar; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { $0 }"#, + r#" +mod foo { + pub struct Bar; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { + fn foo(&self, bar: foo::Bar) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_qualify_path_and_substitute_param() { + check_assist( + add_missing_impl_members, + r#" +mod foo { + pub struct Bar; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { $0 }"#, + r#" +mod foo { + pub struct Bar; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { + fn foo(&self, bar: foo::Bar) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_substitute_param_no_qualify() { + // when substituting params, the substituted param should not be qualified! + check_assist( + add_missing_impl_members, + r#" +mod foo { + trait Foo { fn foo(&self, bar: T); } + pub struct Param; +} +struct Param; +struct S; +impl foo::Foo for S { $0 }"#, + r#" +mod foo { + trait Foo { fn foo(&self, bar: T); } + pub struct Param; +} +struct Param; +struct S; +impl foo::Foo for S { + fn foo(&self, bar: Param) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_qualify_path_associated_item() { + check_assist( + add_missing_impl_members, + r#" +mod foo { + pub struct Bar; + impl Bar { type Assoc = u32; } + trait Foo { fn foo(&self, bar: Bar::Assoc); } +} +struct S; +impl foo::Foo for S { $0 }"#, + r#" +mod foo { + pub struct Bar; + impl Bar { type Assoc = u32; } + trait Foo { fn foo(&self, bar: Bar::Assoc); } +} +struct S; +impl foo::Foo for S { + fn foo(&self, bar: foo::Bar::Assoc) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_qualify_path_nested() { + check_assist( + add_missing_impl_members, + r#" +mod foo { + pub struct Bar; + pub struct Baz; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { $0 }"#, + r#" +mod foo { + pub struct Bar; + pub struct Baz; + trait Foo { fn foo(&self, bar: Bar); } +} +struct S; +impl foo::Foo for S { + fn foo(&self, bar: foo::Bar) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_qualify_path_fn_trait_notation() { + check_assist( + add_missing_impl_members, + r#" +mod foo { + pub trait Fn { type Output; } + trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } +} +struct S; +impl foo::Foo for S { $0 }"#, + r#" +mod foo { + pub trait Fn { type Output; } + trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } +} +struct S; +impl foo::Foo for S { + fn foo(&self, bar: dyn Fn(u32) -> i32) { + ${0:todo!()} + } +}"#, + ); + } + + #[test] + fn test_empty_trait() { + check_assist_not_applicable( + add_missing_impl_members, + r#" +trait Foo; +struct S; +impl Foo for S { $0 }"#, + ) + } + + #[test] + fn test_ignore_unnamed_trait_members_and_default_methods() { + check_assist_not_applicable( + add_missing_impl_members, + r#" +trait Foo { + fn (arg: u32); + fn valid(some: u32) -> bool { false } +} +struct S; +impl Foo for S { $0 }"#, + ) + } + + #[test] + fn test_with_docstring_and_attrs() { + check_assist( + add_missing_impl_members, + r#" +#[doc(alias = "test alias")] +trait Foo { + /// doc string + type Output; + + #[must_use] + fn foo(&self); +} +struct S; +impl Foo for S {}$0"#, + r#" +#[doc(alias = "test alias")] +trait Foo { + /// doc string + type Output; + + #[must_use] + fn foo(&self); +} +struct S; +impl Foo for S { + $0type Output; + + fn foo(&self) { + todo!() + } +}"#, + ) + } + + #[test] + fn test_default_methods() { + check_assist( + add_missing_default_members, + r#" +trait Foo { + type Output; + + const CONST: usize = 42; + + fn valid(some: u32) -> bool { false } + fn foo(some: u32) -> bool; +} +struct S; +impl Foo for S { $0 }"#, + r#" +trait Foo { + type Output; + + const CONST: usize = 42; + + fn valid(some: u32) -> bool { false } + fn foo(some: u32) -> bool; +} +struct S; +impl Foo for S { + $0fn valid(some: u32) -> bool { false } +}"#, + ) + } + + #[test] + fn test_generic_single_default_parameter() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { + fn bar(&self, other: &T); +} + +struct S; +impl Foo for S { $0 }"#, + r#" +trait Foo { + fn bar(&self, other: &T); +} + +struct S; +impl Foo for S { + fn bar(&self, other: &Self) { + ${0:todo!()} + } +}"#, + ) + } + + #[test] + fn test_generic_default_parameter_is_second() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { + fn bar(&self, this: &T1, that: &T2); +} + +struct S; +impl Foo for S { $0 }"#, + r#" +trait Foo { + fn bar(&self, this: &T1, that: &T2); +} + +struct S; +impl Foo for S { + fn bar(&self, this: &T, that: &Self) { + ${0:todo!()} + } +}"#, + ) + } + + #[test] + fn test_assoc_type_bounds_are_removed() { + check_assist( + add_missing_impl_members, + r#" +trait Tr { + type Ty: Copy + 'static; +} + +impl Tr for ()$0 { +}"#, + r#" +trait Tr { + type Ty: Copy + 'static; +} + +impl Tr for () { + $0type Ty; +}"#, + ) + } + + #[test] + fn test_whitespace_fixup_preserves_bad_tokens() { + check_assist( + add_missing_impl_members, + r#" +trait Tr { + fn foo(); +} + +impl Tr for ()$0 { + +++ +}"#, + r#" +trait Tr { + fn foo(); +} + +impl Tr for () { + fn foo() { + ${0:todo!()} + } + +++ +}"#, + ) + } + + #[test] + fn test_whitespace_fixup_preserves_comments() { + check_assist( + add_missing_impl_members, + r#" +trait Tr { + fn foo(); +} + +impl Tr for ()$0 { + // very important +}"#, + r#" +trait Tr { + fn foo(); +} + +impl Tr for () { + fn foo() { + ${0:todo!()} + } + // very important +}"#, + ) + } + + #[test] + fn weird_path() { + check_assist( + add_missing_impl_members, + r#" +trait Test { + fn foo(&self, x: crate) +} +impl Test for () { + $0 +} +"#, + r#" +trait Test { + fn foo(&self, x: crate) +} +impl Test for () { + fn foo(&self, x: crate) { + ${0:todo!()} + } +} +"#, + ) + } + + #[test] + fn missing_generic_type() { + check_assist( + add_missing_impl_members, + r#" +trait Foo { + fn foo(&self, bar: BAR); +} +impl Foo for () { + $0 +} +"#, + r#" +trait Foo { + fn foo(&self, bar: BAR); +} +impl Foo for () { + fn foo(&self, bar: BAR) { + ${0:todo!()} + } +} +"#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/add_turbo_fish.rs b/crates/ide_assists/src/handlers/add_turbo_fish.rs new file mode 100644 index 000000000..8e9ea4fad --- /dev/null +++ b/crates/ide_assists/src/handlers/add_turbo_fish.rs @@ -0,0 +1,164 @@ +use ide_db::defs::{Definition, NameRefClass}; +use syntax::{ast, AstNode, SyntaxKind, T}; +use test_utils::mark; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, AssistKind, +}; + +// Assist: add_turbo_fish +// +// Adds `::<_>` to a call of a generic method or function. +// +// ``` +// fn make() -> T { todo!() } +// fn main() { +// let x = make$0(); +// } +// ``` +// -> +// ``` +// fn make() -> T { todo!() } +// fn main() { +// let x = make::<${0:_}>(); +// } +// ``` +pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let ident = ctx.find_token_syntax_at_offset(SyntaxKind::IDENT).or_else(|| { + let arg_list = ctx.find_node_at_offset::()?; + if arg_list.args().count() > 0 { + return None; + } + mark::hit!(add_turbo_fish_after_call); + arg_list.l_paren_token()?.prev_token().filter(|it| it.kind() == SyntaxKind::IDENT) + })?; + let next_token = ident.next_token()?; + if next_token.kind() == T![::] { + mark::hit!(add_turbo_fish_one_fish_is_enough); + return None; + } + let name_ref = ast::NameRef::cast(ident.parent())?; + let def = match NameRefClass::classify(&ctx.sema, &name_ref)? { + NameRefClass::Definition(def) => def, + NameRefClass::ExternCrate(_) | NameRefClass::FieldShorthand { .. } => return None, + }; + let fun = match def { + Definition::ModuleDef(hir::ModuleDef::Function(it)) => it, + _ => return None, + }; + let generics = hir::GenericDef::Function(fun).params(ctx.sema.db); + if generics.is_empty() { + mark::hit!(add_turbo_fish_non_generic); + return None; + } + acc.add( + AssistId("add_turbo_fish", AssistKind::RefactorRewrite), + "Add `::<>`", + ident.text_range(), + |builder| match ctx.config.snippet_cap { + Some(cap) => builder.insert_snippet(cap, ident.text_range().end(), "::<${0:_}>"), + None => builder.insert(ident.text_range().end(), "::<_>"), + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + use test_utils::mark; + + #[test] + fn add_turbo_fish_function() { + check_assist( + add_turbo_fish, + r#" +fn make() -> T {} +fn main() { + make$0(); +} +"#, + r#" +fn make() -> T {} +fn main() { + make::<${0:_}>(); +} +"#, + ); + } + + #[test] + fn add_turbo_fish_after_call() { + mark::check!(add_turbo_fish_after_call); + check_assist( + add_turbo_fish, + r#" +fn make() -> T {} +fn main() { + make()$0; +} +"#, + r#" +fn make() -> T {} +fn main() { + make::<${0:_}>(); +} +"#, + ); + } + + #[test] + fn add_turbo_fish_method() { + check_assist( + add_turbo_fish, + r#" +struct S; +impl S { + fn make(&self) -> T {} +} +fn main() { + S.make$0(); +} +"#, + r#" +struct S; +impl S { + fn make(&self) -> T {} +} +fn main() { + S.make::<${0:_}>(); +} +"#, + ); + } + + #[test] + fn add_turbo_fish_one_fish_is_enough() { + mark::check!(add_turbo_fish_one_fish_is_enough); + check_assist_not_applicable( + add_turbo_fish, + r#" +fn make() -> T {} +fn main() { + make$0::<()>(); +} +"#, + ); + } + + #[test] + fn add_turbo_fish_non_generic() { + mark::check!(add_turbo_fish_non_generic); + check_assist_not_applicable( + add_turbo_fish, + r#" +fn make() -> () {} +fn main() { + make$0(); +} +"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/apply_demorgan.rs b/crates/ide_assists/src/handlers/apply_demorgan.rs new file mode 100644 index 000000000..ed4d11455 --- /dev/null +++ b/crates/ide_assists/src/handlers/apply_demorgan.rs @@ -0,0 +1,93 @@ +use syntax::ast::{self, AstNode}; + +use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKind, Assists}; + +// Assist: apply_demorgan +// +// Apply https://en.wikipedia.org/wiki/De_Morgan%27s_laws[De Morgan's law]. +// This transforms expressions of the form `!l || !r` into `!(l && r)`. +// This also works with `&&`. This assist can only be applied with the cursor +// on either `||` or `&&`, with both operands being a negation of some kind. +// This means something of the form `!x` or `x != y`. +// +// ``` +// fn main() { +// if x != 4 ||$0 !y {} +// } +// ``` +// -> +// ``` +// fn main() { +// if !(x == 4 && y) {} +// } +// ``` +pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let expr = ctx.find_node_at_offset::()?; + let op = expr.op_kind()?; + let op_range = expr.op_token()?.text_range(); + let opposite_op = opposite_logic_op(op)?; + let cursor_in_range = op_range.contains_range(ctx.frange.range); + if !cursor_in_range { + return None; + } + + let lhs = expr.lhs()?; + let lhs_range = lhs.syntax().text_range(); + let not_lhs = invert_boolean_expression(lhs); + + let rhs = expr.rhs()?; + let rhs_range = rhs.syntax().text_range(); + let not_rhs = invert_boolean_expression(rhs); + + acc.add( + AssistId("apply_demorgan", AssistKind::RefactorRewrite), + "Apply De Morgan's law", + op_range, + |edit| { + edit.replace(op_range, opposite_op); + edit.replace(lhs_range, format!("!({}", not_lhs.syntax().text())); + edit.replace(rhs_range, format!("{})", not_rhs.syntax().text())); + }, + ) +} + +// Return the opposite text for a given logical operator, if it makes sense +fn opposite_logic_op(kind: ast::BinOp) -> Option<&'static str> { + match kind { + ast::BinOp::BooleanOr => Some("&&"), + ast::BinOp::BooleanAnd => Some("||"), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + #[test] + fn demorgan_turns_and_into_or() { + check_assist(apply_demorgan, "fn f() { !x &&$0 !x }", "fn f() { !(x || x) }") + } + + #[test] + fn demorgan_turns_or_into_and() { + check_assist(apply_demorgan, "fn f() { !x ||$0 !x }", "fn f() { !(x && x) }") + } + + #[test] + fn demorgan_removes_inequality() { + check_assist(apply_demorgan, "fn f() { x != x ||$0 !x }", "fn f() { !(x == x && x) }") + } + + #[test] + fn demorgan_general_case() { + check_assist(apply_demorgan, "fn f() { x ||$0 x }", "fn f() { !(!x && !x) }") + } + + #[test] + fn demorgan_doesnt_apply_with_cursor_not_on_op() { + check_assist_not_applicable(apply_demorgan, "fn f() { $0 !x || !x }") + } +} diff --git a/crates/ide_assists/src/handlers/auto_import.rs b/crates/ide_assists/src/handlers/auto_import.rs new file mode 100644 index 000000000..e93901cb3 --- /dev/null +++ b/crates/ide_assists/src/handlers/auto_import.rs @@ -0,0 +1,970 @@ +use ide_db::helpers::{ + import_assets::{ImportAssets, ImportCandidate}, + insert_use::{insert_use, ImportScope}, + mod_path_to_ast, +}; +use syntax::{ast, AstNode, SyntaxNode}; + +use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; + +// Feature: Auto Import +// +// Using the `auto-import` assist it is possible to insert missing imports for unresolved items. +// When inserting an import it will do so in a structured manner by keeping imports grouped, +// separated by a newline in the following order: +// +// - `std` and `core` +// - External Crates +// - Current Crate, paths prefixed by `crate` +// - Current Module, paths prefixed by `self` +// - Super Module, paths prefixed by `super` +// +// Example: +// ```rust +// use std::fs::File; +// +// use itertools::Itertools; +// use syntax::ast; +// +// use crate::utils::insert_use; +// +// use self::auto_import; +// +// use super::AssistContext; +// ``` +// +// .Merge Behaviour +// +// It is possible to configure how use-trees are merged with the `importMergeBehaviour` setting. +// It has the following configurations: +// +// - `full`: This setting will cause auto-import to always completely merge use-trees that share the +// same path prefix while also merging inner trees that share the same path-prefix. This kind of +// nesting is only supported in Rust versions later than 1.24. +// - `last`: This setting will cause auto-import to merge use-trees as long as the resulting tree +// will only contain a nesting of single segment paths at the very end. +// - `none`: This setting will cause auto-import to never merge use-trees keeping them as simple +// paths. +// +// In `VS Code` the configuration for this is `rust-analyzer.assist.importMergeBehaviour`. +// +// .Import Prefix +// +// The style of imports in the same crate is configurable through the `importPrefix` setting. +// It has the following configurations: +// +// - `by_crate`: This setting will force paths to be always absolute, starting with the `crate` +// prefix, unless the item is defined outside of the current crate. +// - `by_self`: This setting will force paths that are relative to the current module to always +// start with `self`. This will result in paths that always start with either `crate`, `self`, +// `super` or an extern crate identifier. +// - `plain`: This setting does not impose any restrictions in imports. +// +// In `VS Code` the configuration for this is `rust-analyzer.assist.importPrefix`. + +// Assist: auto_import +// +// If the name is unresolved, provides all possible imports for it. +// +// ``` +// fn main() { +// let map = HashMap$0::new(); +// } +// # pub mod std { pub mod collections { pub struct HashMap { } } } +// ``` +// -> +// ``` +// use std::collections::HashMap; +// +// fn main() { +// let map = HashMap::new(); +// } +// # pub mod std { pub mod collections { pub struct HashMap { } } } +// ``` +pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; + let proposed_imports = + import_assets.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind); + if proposed_imports.is_empty() { + return None; + } + + let range = ctx.sema.original_range(&syntax_under_caret).range; + let group = import_group_message(import_assets.import_candidate()); + let scope = ImportScope::find_insert_use_container(&syntax_under_caret, &ctx.sema)?; + for (import, _) in proposed_imports { + acc.add_group( + &group, + AssistId("auto_import", AssistKind::QuickFix), + format!("Import `{}`", &import), + range, + |builder| { + let rewriter = + insert_use(&scope, mod_path_to_ast(&import), ctx.config.insert_use.merge); + builder.rewrite(rewriter); + }, + ); + } + Some(()) +} + +pub(super) fn find_importable_node(ctx: &AssistContext) -> Option<(ImportAssets, SyntaxNode)> { + if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::() { + ImportAssets::for_exact_path(&path_under_caret, &ctx.sema) + .zip(Some(path_under_caret.syntax().clone())) + } else if let Some(method_under_caret) = + ctx.find_node_at_offset_with_descend::() + { + ImportAssets::for_method_call(&method_under_caret, &ctx.sema) + .zip(Some(method_under_caret.syntax().clone())) + } else { + None + } +} + +fn import_group_message(import_candidate: &ImportCandidate) -> GroupLabel { + let name = match import_candidate { + ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()), + ImportCandidate::TraitAssocItem(candidate) => { + format!("Import a trait for item {}", candidate.name.text()) + } + ImportCandidate::TraitMethod(candidate) => { + format!("Import a trait for method {}", candidate.name.text()) + } + }; + GroupLabel(name) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + #[test] + fn applicable_when_found_an_import_partial() { + check_assist( + auto_import, + r" + mod std { + pub mod fmt { + pub struct Formatter; + } + } + + use std::fmt; + + $0Formatter + ", + r" + mod std { + pub mod fmt { + pub struct Formatter; + } + } + + use std::fmt::{self, Formatter}; + + Formatter + ", + ); + } + + #[test] + fn applicable_when_found_an_import() { + check_assist( + auto_import, + r" + $0PubStruct + + pub mod PubMod { + pub struct PubStruct; + } + ", + r" + use PubMod::PubStruct; + + PubStruct + + pub mod PubMod { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn applicable_when_found_an_import_in_macros() { + check_assist( + auto_import, + r" + macro_rules! foo { + ($i:ident) => { fn foo(a: $i) {} } + } + foo!(Pub$0Struct); + + pub mod PubMod { + pub struct PubStruct; + } + ", + r" + use PubMod::PubStruct; + + macro_rules! foo { + ($i:ident) => { fn foo(a: $i) {} } + } + foo!(PubStruct); + + pub mod PubMod { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn auto_imports_are_merged() { + check_assist( + auto_import, + r" + use PubMod::PubStruct1; + + struct Test { + test: Pub$0Struct2, + } + + pub mod PubMod { + pub struct PubStruct1; + pub struct PubStruct2 { + _t: T, + } + } + ", + r" + use PubMod::{PubStruct1, PubStruct2}; + + struct Test { + test: PubStruct2, + } + + pub mod PubMod { + pub struct PubStruct1; + pub struct PubStruct2 { + _t: T, + } + } + ", + ); + } + + #[test] + fn applicable_when_found_multiple_imports() { + check_assist( + auto_import, + r" + PubSt$0ruct + + pub mod PubMod1 { + pub struct PubStruct; + } + pub mod PubMod2 { + pub struct PubStruct; + } + pub mod PubMod3 { + pub struct PubStruct; + } + ", + r" + use PubMod3::PubStruct; + + PubStruct + + pub mod PubMod1 { + pub struct PubStruct; + } + pub mod PubMod2 { + pub struct PubStruct; + } + pub mod PubMod3 { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn not_applicable_for_already_imported_types() { + check_assist_not_applicable( + auto_import, + r" + use PubMod::PubStruct; + + PubStruct$0 + + pub mod PubMod { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn not_applicable_for_types_with_private_paths() { + check_assist_not_applicable( + auto_import, + r" + PrivateStruct$0 + + pub mod PubMod { + struct PrivateStruct; + } + ", + ); + } + + #[test] + fn not_applicable_when_no_imports_found() { + check_assist_not_applicable( + auto_import, + " + PubStruct$0", + ); + } + + #[test] + fn not_applicable_in_import_statements() { + check_assist_not_applicable( + auto_import, + r" + use PubStruct$0; + + pub mod PubMod { + pub struct PubStruct; + }", + ); + } + + #[test] + fn function_import() { + check_assist( + auto_import, + r" + test_function$0 + + pub mod PubMod { + pub fn test_function() {}; + } + ", + r" + use PubMod::test_function; + + test_function + + pub mod PubMod { + pub fn test_function() {}; + } + ", + ); + } + + #[test] + fn macro_import() { + check_assist( + auto_import, + r" +//- /lib.rs crate:crate_with_macro +#[macro_export] +macro_rules! foo { + () => () +} + +//- /main.rs crate:main deps:crate_with_macro +fn main() { + foo$0 +} +", + r"use crate_with_macro::foo; + +fn main() { + foo +} +", + ); + } + + #[test] + fn auto_import_target() { + check_assist_target( + auto_import, + r" + struct AssistInfo { + group_label: Option<$0GroupLabel>, + } + + mod m { pub struct GroupLabel; } + ", + "GroupLabel", + ) + } + + #[test] + fn not_applicable_when_path_start_is_imported() { + check_assist_not_applicable( + auto_import, + r" + pub mod mod1 { + pub mod mod2 { + pub mod mod3 { + pub struct TestStruct; + } + } + } + + use mod1::mod2; + fn main() { + mod2::mod3::TestStruct$0 + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_function() { + check_assist_not_applicable( + auto_import, + r" + pub mod test_mod { + pub fn test_function() {} + } + + use test_mod::test_function; + fn main() { + test_function$0 + } + ", + ); + } + + #[test] + fn associated_struct_function() { + check_assist( + auto_import, + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + pub fn test_function() {} + } + } + + fn main() { + TestStruct::test_function$0 + } + ", + r" + use test_mod::TestStruct; + + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + pub fn test_function() {} + } + } + + fn main() { + TestStruct::test_function + } + ", + ); + } + + #[test] + fn associated_struct_const() { + check_assist( + auto_import, + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + TestStruct::TEST_CONST$0 + } + ", + r" + use test_mod::TestStruct; + + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + TestStruct::TEST_CONST + } + ", + ); + } + + #[test] + fn associated_trait_function() { + check_assist( + auto_import, + r" + mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + + fn main() { + test_mod::TestStruct::test_function$0 + } + ", + r" + use test_mod::TestTrait; + + mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + + fn main() { + test_mod::TestStruct::test_function + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_trait_for_function() { + check_assist_not_applicable( + auto_import, + r" + mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub trait TestTrait2 { + fn test_function(); + } + pub enum TestEnum { + One, + Two, + } + impl TestTrait2 for TestEnum { + fn test_function() {} + } + impl TestTrait for TestEnum { + fn test_function() {} + } + } + + use test_mod::TestTrait2; + fn main() { + test_mod::TestEnum::test_function$0; + } + ", + ) + } + + #[test] + fn associated_trait_const() { + check_assist( + auto_import, + r" + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + test_mod::TestStruct::TEST_CONST$0 + } + ", + r" + use test_mod::TestTrait; + + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + test_mod::TestStruct::TEST_CONST + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_trait_for_const() { + check_assist_not_applicable( + auto_import, + r" + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub trait TestTrait2 { + const TEST_CONST: f64; + } + pub enum TestEnum { + One, + Two, + } + impl TestTrait2 for TestEnum { + const TEST_CONST: f64 = 42.0; + } + impl TestTrait for TestEnum { + const TEST_CONST: u8 = 42; + } + } + + use test_mod::TestTrait2; + fn main() { + test_mod::TestEnum::TEST_CONST$0; + } + ", + ) + } + + #[test] + fn trait_method() { + check_assist( + auto_import, + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_struct.test_meth$0od() + } + ", + r" + use test_mod::TestTrait; + + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_struct.test_method() + } + ", + ); + } + + #[test] + fn trait_method_cross_crate() { + check_assist( + auto_import, + r" + //- /main.rs crate:main deps:dep + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + test_struct.test_meth$0od() + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + ", + r" + use dep::test_mod::TestTrait; + + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + test_struct.test_method() + } + ", + ); + } + + #[test] + fn assoc_fn_cross_crate() { + check_assist( + auto_import, + r" + //- /main.rs crate:main deps:dep + fn main() { + dep::test_mod::TestStruct::test_func$0tion + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + ", + r" + use dep::test_mod::TestTrait; + + fn main() { + dep::test_mod::TestStruct::test_function + } + ", + ); + } + + #[test] + fn assoc_const_cross_crate() { + check_assist( + auto_import, + r" + //- /main.rs crate:main deps:dep + fn main() { + dep::test_mod::TestStruct::CONST$0 + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + const CONST: bool; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const CONST: bool = true; + } + } + ", + r" + use dep::test_mod::TestTrait; + + fn main() { + dep::test_mod::TestStruct::CONST + } + ", + ); + } + + #[test] + fn assoc_fn_as_method_cross_crate() { + check_assist_not_applicable( + auto_import, + r" + //- /main.rs crate:main deps:dep + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + test_struct.test_func$0tion() + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + ", + ); + } + + #[test] + fn private_trait_cross_crate() { + check_assist_not_applicable( + auto_import, + r" + //- /main.rs crate:main deps:dep + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + test_struct.test_meth$0od() + } + //- /dep.rs crate:dep + pub mod test_mod { + trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_trait_for_method() { + check_assist_not_applicable( + auto_import, + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub trait TestTrait2 { + fn test_method(&self); + } + pub enum TestEnum { + One, + Two, + } + impl TestTrait2 for TestEnum { + fn test_method(&self) {} + } + impl TestTrait for TestEnum { + fn test_method(&self) {} + } + } + + use test_mod::TestTrait2; + fn main() { + let one = test_mod::TestEnum::One; + one.test$0_method(); + } + ", + ) + } + + #[test] + fn dep_import() { + check_assist( + auto_import, + r" +//- /lib.rs crate:dep +pub struct Struct; + +//- /main.rs crate:main deps:dep +fn main() { + Struct$0 +} +", + r"use dep::Struct; + +fn main() { + Struct +} +", + ); + } + + #[test] + fn whole_segment() { + // Tests that only imports whose last segment matches the identifier get suggested. + check_assist( + auto_import, + r" +//- /lib.rs crate:dep +pub mod fmt { + pub trait Display {} +} + +pub fn panic_fmt() {} + +//- /main.rs crate:main deps:dep +struct S; + +impl f$0mt::Display for S {} +", + r"use dep::fmt; + +struct S; + +impl fmt::Display for S {} +", + ); + } + + #[test] + fn macro_generated() { + // Tests that macro-generated items are suggested from external crates. + check_assist( + auto_import, + r" +//- /lib.rs crate:dep +macro_rules! mac { + () => { + pub struct Cheese; + }; +} + +mac!(); + +//- /main.rs crate:main deps:dep +fn main() { + Cheese$0; +} +", + r"use dep::Cheese; + +fn main() { + Cheese; +} +", + ); + } + + #[test] + fn casing() { + // Tests that differently cased names don't interfere and we only suggest the matching one. + check_assist( + auto_import, + r" +//- /lib.rs crate:dep +pub struct FMT; +pub struct fmt; + +//- /main.rs crate:main deps:dep +fn main() { + FMT$0; +} +", + r"use dep::FMT; + +fn main() { + FMT; +} +", + ); + } +} diff --git a/crates/ide_assists/src/handlers/change_visibility.rs b/crates/ide_assists/src/handlers/change_visibility.rs new file mode 100644 index 000000000..ac8c44124 --- /dev/null +++ b/crates/ide_assists/src/handlers/change_visibility.rs @@ -0,0 +1,212 @@ +use syntax::{ + ast::{self, NameOwner, VisibilityOwner}, + AstNode, + SyntaxKind::{CONST, ENUM, FN, MODULE, STATIC, STRUCT, TRAIT, TYPE_ALIAS, VISIBILITY}, + T, +}; +use test_utils::mark; + +use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists}; + +// Assist: change_visibility +// +// Adds or changes existing visibility specifier. +// +// ``` +// $0fn frobnicate() {} +// ``` +// -> +// ``` +// pub(crate) fn frobnicate() {} +// ``` +pub(crate) fn change_visibility(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + if let Some(vis) = ctx.find_node_at_offset::() { + return change_vis(acc, vis); + } + add_vis(acc, ctx) +} + +fn add_vis(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let item_keyword = ctx.token_at_offset().find(|leaf| { + matches!( + leaf.kind(), + T![const] + | T![static] + | T![fn] + | T![mod] + | T![struct] + | T![enum] + | T![trait] + | T![type] + ) + }); + + let (offset, target) = if let Some(keyword) = item_keyword { + let parent = keyword.parent(); + let def_kws = vec![CONST, STATIC, TYPE_ALIAS, FN, MODULE, STRUCT, ENUM, TRAIT]; + // Parent is not a definition, can't add visibility + if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) { + return None; + } + // Already have visibility, do nothing + if parent.children().any(|child| child.kind() == VISIBILITY) { + return None; + } + (vis_offset(&parent), keyword.text_range()) + } else if let Some(field_name) = ctx.find_node_at_offset::() { + let field = field_name.syntax().ancestors().find_map(ast::RecordField::cast)?; + if field.name()? != field_name { + mark::hit!(change_visibility_field_false_positive); + return None; + } + if field.visibility().is_some() { + return None; + } + (vis_offset(field.syntax()), field_name.syntax().text_range()) + } else if let Some(field) = ctx.find_node_at_offset::() { + if field.visibility().is_some() { + return None; + } + (vis_offset(field.syntax()), field.syntax().text_range()) + } else { + return None; + }; + + acc.add( + AssistId("change_visibility", AssistKind::RefactorRewrite), + "Change visibility to pub(crate)", + target, + |edit| { + edit.insert(offset, "pub(crate) "); + }, + ) +} + +fn change_vis(acc: &mut Assists, vis: ast::Visibility) -> Option<()> { + if vis.syntax().text() == "pub" { + let target = vis.syntax().text_range(); + return acc.add( + AssistId("change_visibility", AssistKind::RefactorRewrite), + "Change Visibility to pub(crate)", + target, + |edit| { + edit.replace(vis.syntax().text_range(), "pub(crate)"); + }, + ); + } + if vis.syntax().text() == "pub(crate)" { + let target = vis.syntax().text_range(); + return acc.add( + AssistId("change_visibility", AssistKind::RefactorRewrite), + "Change visibility to pub", + target, + |edit| { + edit.replace(vis.syntax().text_range(), "pub"); + }, + ); + } + None +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn change_visibility_adds_pub_crate_to_items() { + check_assist(change_visibility, "$0fn foo() {}", "pub(crate) fn foo() {}"); + check_assist(change_visibility, "f$0n foo() {}", "pub(crate) fn foo() {}"); + check_assist(change_visibility, "$0struct Foo {}", "pub(crate) struct Foo {}"); + check_assist(change_visibility, "$0mod foo {}", "pub(crate) mod foo {}"); + check_assist(change_visibility, "$0trait Foo {}", "pub(crate) trait Foo {}"); + check_assist(change_visibility, "m$0od {}", "pub(crate) mod {}"); + check_assist(change_visibility, "unsafe f$0n foo() {}", "pub(crate) unsafe fn foo() {}"); + } + + #[test] + fn change_visibility_works_with_struct_fields() { + check_assist( + change_visibility, + r"struct S { $0field: u32 }", + r"struct S { pub(crate) field: u32 }", + ); + check_assist(change_visibility, r"struct S ( $0u32 )", r"struct S ( pub(crate) u32 )"); + } + + #[test] + fn change_visibility_field_false_positive() { + mark::check!(change_visibility_field_false_positive); + check_assist_not_applicable( + change_visibility, + r"struct S { field: [(); { let $0x = ();}] }", + ) + } + + #[test] + fn change_visibility_pub_to_pub_crate() { + check_assist(change_visibility, "$0pub fn foo() {}", "pub(crate) fn foo() {}") + } + + #[test] + fn change_visibility_pub_crate_to_pub() { + check_assist(change_visibility, "$0pub(crate) fn foo() {}", "pub fn foo() {}") + } + + #[test] + fn change_visibility_const() { + check_assist(change_visibility, "$0const FOO = 3u8;", "pub(crate) const FOO = 3u8;"); + } + + #[test] + fn change_visibility_static() { + check_assist(change_visibility, "$0static FOO = 3u8;", "pub(crate) static FOO = 3u8;"); + } + + #[test] + fn change_visibility_type_alias() { + check_assist(change_visibility, "$0type T = ();", "pub(crate) type T = ();"); + } + + #[test] + fn change_visibility_handles_comment_attrs() { + check_assist( + change_visibility, + r" + /// docs + + // comments + + #[derive(Debug)] + $0struct Foo; + ", + r" + /// docs + + // comments + + #[derive(Debug)] + pub(crate) struct Foo; + ", + ) + } + + #[test] + fn not_applicable_for_enum_variants() { + check_assist_not_applicable( + change_visibility, + r"mod foo { pub enum Foo {Foo1} } + fn main() { foo::Foo::Foo1$0 } ", + ); + } + + #[test] + fn change_visibility_target() { + check_assist_target(change_visibility, "$0fn foo() {}", "fn"); + check_assist_target(change_visibility, "pub(crate)$0 fn foo() {}", "pub(crate)"); + check_assist_target(change_visibility, "struct S { $0field: u32 }", "field"); + } +} diff --git a/crates/ide_assists/src/handlers/convert_integer_literal.rs b/crates/ide_assists/src/handlers/convert_integer_literal.rs new file mode 100644 index 000000000..a8a819cfc --- /dev/null +++ b/crates/ide_assists/src/handlers/convert_integer_literal.rs @@ -0,0 +1,268 @@ +use syntax::{ast, ast::Radix, AstToken}; + +use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; + +// Assist: convert_integer_literal +// +// Converts the base of integer literals to other bases. +// +// ``` +// const _: i32 = 10$0; +// ``` +// -> +// ``` +// const _: i32 = 0b1010; +// ``` +pub(crate) fn convert_integer_literal(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let literal = ctx.find_node_at_offset::()?; + let literal = match literal.kind() { + ast::LiteralKind::IntNumber(it) => it, + _ => return None, + }; + let radix = literal.radix(); + let value = literal.value()?; + let suffix = literal.suffix(); + + let range = literal.syntax().text_range(); + let group_id = GroupLabel("Convert integer base".into()); + + for &target_radix in Radix::ALL { + if target_radix == radix { + continue; + } + + let mut converted = match target_radix { + Radix::Binary => format!("0b{:b}", value), + Radix::Octal => format!("0o{:o}", value), + Radix::Decimal => value.to_string(), + Radix::Hexadecimal => format!("0x{:X}", value), + }; + + let label = format!("Convert {} to {}{}", literal, converted, suffix.unwrap_or_default()); + + // Appends the type suffix back into the new literal if it exists. + if let Some(suffix) = suffix { + converted.push_str(suffix); + } + + acc.add_group( + &group_id, + AssistId("convert_integer_literal", AssistKind::RefactorInline), + label, + range, + |builder| builder.replace(range, converted), + ); + } + + Some(()) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist_by_label, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn binary_target() { + check_assist_target(convert_integer_literal, "const _: i32 = 0b1010$0;", "0b1010"); + } + + #[test] + fn octal_target() { + check_assist_target(convert_integer_literal, "const _: i32 = 0o12$0;", "0o12"); + } + + #[test] + fn decimal_target() { + check_assist_target(convert_integer_literal, "const _: i32 = 10$0;", "10"); + } + + #[test] + fn hexadecimal_target() { + check_assist_target(convert_integer_literal, "const _: i32 = 0xA$0;", "0xA"); + } + + #[test] + fn binary_target_with_underscores() { + check_assist_target(convert_integer_literal, "const _: i32 = 0b10_10$0;", "0b10_10"); + } + + #[test] + fn octal_target_with_underscores() { + check_assist_target(convert_integer_literal, "const _: i32 = 0o1_2$0;", "0o1_2"); + } + + #[test] + fn decimal_target_with_underscores() { + check_assist_target(convert_integer_literal, "const _: i32 = 1_0$0;", "1_0"); + } + + #[test] + fn hexadecimal_target_with_underscores() { + check_assist_target(convert_integer_literal, "const _: i32 = 0x_A$0;", "0x_A"); + } + + #[test] + fn convert_decimal_integer() { + let before = "const _: i32 = 1000$0;"; + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0b1111101000;", + "Convert 1000 to 0b1111101000", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0o1750;", + "Convert 1000 to 0o1750", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0x3E8;", + "Convert 1000 to 0x3E8", + ); + } + + #[test] + fn convert_hexadecimal_integer() { + let before = "const _: i32 = 0xFF$0;"; + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0b11111111;", + "Convert 0xFF to 0b11111111", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0o377;", + "Convert 0xFF to 0o377", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 255;", + "Convert 0xFF to 255", + ); + } + + #[test] + fn convert_binary_integer() { + let before = "const _: i32 = 0b11111111$0;"; + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0o377;", + "Convert 0b11111111 to 0o377", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 255;", + "Convert 0b11111111 to 255", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0xFF;", + "Convert 0b11111111 to 0xFF", + ); + } + + #[test] + fn convert_octal_integer() { + let before = "const _: i32 = 0o377$0;"; + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0b11111111;", + "Convert 0o377 to 0b11111111", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 255;", + "Convert 0o377 to 255", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0xFF;", + "Convert 0o377 to 0xFF", + ); + } + + #[test] + fn convert_integer_with_underscores() { + let before = "const _: i32 = 1_00_0$0;"; + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0b1111101000;", + "Convert 1_00_0 to 0b1111101000", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0o1750;", + "Convert 1_00_0 to 0o1750", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0x3E8;", + "Convert 1_00_0 to 0x3E8", + ); + } + + #[test] + fn convert_integer_with_suffix() { + let before = "const _: i32 = 1000i32$0;"; + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0b1111101000i32;", + "Convert 1000i32 to 0b1111101000i32", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0o1750i32;", + "Convert 1000i32 to 0o1750i32", + ); + + check_assist_by_label( + convert_integer_literal, + before, + "const _: i32 = 0x3E8i32;", + "Convert 1000i32 to 0x3E8i32", + ); + } + + #[test] + fn convert_overflowing_literal() { + let before = "const _: i32 = + 111111111111111111111111111111111111111111111111111111111111111111111111$0;"; + check_assist_not_applicable(convert_integer_literal, before); + } +} diff --git a/crates/ide_assists/src/handlers/early_return.rs b/crates/ide_assists/src/handlers/early_return.rs new file mode 100644 index 000000000..6b87c3c05 --- /dev/null +++ b/crates/ide_assists/src/handlers/early_return.rs @@ -0,0 +1,515 @@ +use std::{iter::once, ops::RangeInclusive}; + +use syntax::{ + algo::replace_children, + ast::{ + self, + edit::{AstNodeEdit, IndentLevel}, + make, + }, + AstNode, + SyntaxKind::{FN, LOOP_EXPR, L_CURLY, R_CURLY, WHILE_EXPR, WHITESPACE}, + SyntaxNode, +}; + +use crate::{ + assist_context::{AssistContext, Assists}, + utils::invert_boolean_expression, + AssistId, AssistKind, +}; + +// Assist: convert_to_guarded_return +// +// Replace a large conditional with a guarded return. +// +// ``` +// fn main() { +// $0if cond { +// foo(); +// bar(); +// } +// } +// ``` +// -> +// ``` +// fn main() { +// if !cond { +// return; +// } +// foo(); +// bar(); +// } +// ``` +pub(crate) fn convert_to_guarded_return(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let if_expr: ast::IfExpr = ctx.find_node_at_offset()?; + if if_expr.else_branch().is_some() { + return None; + } + + let cond = if_expr.condition()?; + + // Check if there is an IfLet that we can handle. + let if_let_pat = match cond.pat() { + None => None, // No IfLet, supported. + Some(ast::Pat::TupleStructPat(pat)) if pat.fields().count() == 1 => { + let path = pat.path()?; + match path.qualifier() { + None => { + let bound_ident = pat.fields().next().unwrap(); + Some((path, bound_ident)) + } + Some(_) => return None, + } + } + Some(_) => return None, // Unsupported IfLet. + }; + + let cond_expr = cond.expr()?; + let then_block = if_expr.then_branch()?; + + let parent_block = if_expr.syntax().parent()?.ancestors().find_map(ast::BlockExpr::cast)?; + + if parent_block.tail_expr()? != if_expr.clone().into() { + return None; + } + + // check for early return and continue + let first_in_then_block = then_block.syntax().first_child()?; + if ast::ReturnExpr::can_cast(first_in_then_block.kind()) + || ast::ContinueExpr::can_cast(first_in_then_block.kind()) + || first_in_then_block + .children() + .any(|x| ast::ReturnExpr::can_cast(x.kind()) || ast::ContinueExpr::can_cast(x.kind())) + { + return None; + } + + let parent_container = parent_block.syntax().parent()?; + + let early_expression: ast::Expr = match parent_container.kind() { + WHILE_EXPR | LOOP_EXPR => make::expr_continue(), + FN => make::expr_return(None), + _ => return None, + }; + + if then_block.syntax().first_child_or_token().map(|t| t.kind() == L_CURLY).is_none() { + return None; + } + + then_block.syntax().last_child_or_token().filter(|t| t.kind() == R_CURLY)?; + + let target = if_expr.syntax().text_range(); + acc.add( + AssistId("convert_to_guarded_return", AssistKind::RefactorRewrite), + "Convert to guarded return", + target, + |edit| { + let if_indent_level = IndentLevel::from_node(&if_expr.syntax()); + let new_block = match if_let_pat { + None => { + // If. + let new_expr = { + let then_branch = + make::block_expr(once(make::expr_stmt(early_expression).into()), None); + let cond = invert_boolean_expression(cond_expr); + make::expr_if(make::condition(cond, None), then_branch, None) + .indent(if_indent_level) + }; + replace(new_expr.syntax(), &then_block, &parent_block, &if_expr) + } + Some((path, bound_ident)) => { + // If-let. + let match_expr = { + let happy_arm = { + let pat = make::tuple_struct_pat( + path, + once(make::ident_pat(make::name("it")).into()), + ); + let expr = { + let name_ref = make::name_ref("it"); + let segment = make::path_segment(name_ref); + let path = make::path_unqualified(segment); + make::expr_path(path) + }; + make::match_arm(once(pat.into()), expr) + }; + + let sad_arm = make::match_arm( + // FIXME: would be cool to use `None` or `Err(_)` if appropriate + once(make::wildcard_pat().into()), + early_expression, + ); + + make::expr_match(cond_expr, make::match_arm_list(vec![happy_arm, sad_arm])) + }; + + let let_stmt = make::let_stmt( + make::ident_pat(make::name(&bound_ident.syntax().to_string())).into(), + Some(match_expr), + ); + let let_stmt = let_stmt.indent(if_indent_level); + replace(let_stmt.syntax(), &then_block, &parent_block, &if_expr) + } + }; + edit.replace_ast(parent_block, ast::BlockExpr::cast(new_block).unwrap()); + + fn replace( + new_expr: &SyntaxNode, + then_block: &ast::BlockExpr, + parent_block: &ast::BlockExpr, + if_expr: &ast::IfExpr, + ) -> SyntaxNode { + let then_block_items = then_block.dedent(IndentLevel(1)); + let end_of_then = then_block_items.syntax().last_child_or_token().unwrap(); + let end_of_then = + if end_of_then.prev_sibling_or_token().map(|n| n.kind()) == Some(WHITESPACE) { + end_of_then.prev_sibling_or_token().unwrap() + } else { + end_of_then + }; + let mut then_statements = new_expr.children_with_tokens().chain( + then_block_items + .syntax() + .children_with_tokens() + .skip(1) + .take_while(|i| *i != end_of_then), + ); + replace_children( + &parent_block.syntax(), + RangeInclusive::new( + if_expr.clone().syntax().clone().into(), + if_expr.syntax().clone().into(), + ), + &mut then_statements, + ) + } + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn convert_inside_fn() { + check_assist( + convert_to_guarded_return, + r#" + fn main() { + bar(); + if$0 true { + foo(); + + //comment + bar(); + } + } + "#, + r#" + fn main() { + bar(); + if !true { + return; + } + foo(); + + //comment + bar(); + } + "#, + ); + } + + #[test] + fn convert_let_inside_fn() { + check_assist( + convert_to_guarded_return, + r#" + fn main(n: Option) { + bar(); + if$0 let Some(n) = n { + foo(n); + + //comment + bar(); + } + } + "#, + r#" + fn main(n: Option) { + bar(); + let n = match n { + Some(it) => it, + _ => return, + }; + foo(n); + + //comment + bar(); + } + "#, + ); + } + + #[test] + fn convert_if_let_result() { + check_assist( + convert_to_guarded_return, + r#" + fn main() { + if$0 let Ok(x) = Err(92) { + foo(x); + } + } + "#, + r#" + fn main() { + let x = match Err(92) { + Ok(it) => it, + _ => return, + }; + foo(x); + } + "#, + ); + } + + #[test] + fn convert_let_ok_inside_fn() { + check_assist( + convert_to_guarded_return, + r#" + fn main(n: Option) { + bar(); + if$0 let Ok(n) = n { + foo(n); + + //comment + bar(); + } + } + "#, + r#" + fn main(n: Option) { + bar(); + let n = match n { + Ok(it) => it, + _ => return, + }; + foo(n); + + //comment + bar(); + } + "#, + ); + } + + #[test] + fn convert_inside_while() { + check_assist( + convert_to_guarded_return, + r#" + fn main() { + while true { + if$0 true { + foo(); + bar(); + } + } + } + "#, + r#" + fn main() { + while true { + if !true { + continue; + } + foo(); + bar(); + } + } + "#, + ); + } + + #[test] + fn convert_let_inside_while() { + check_assist( + convert_to_guarded_return, + r#" + fn main() { + while true { + if$0 let Some(n) = n { + foo(n); + bar(); + } + } + } + "#, + r#" + fn main() { + while true { + let n = match n { + Some(it) => it, + _ => continue, + }; + foo(n); + bar(); + } + } + "#, + ); + } + + #[test] + fn convert_inside_loop() { + check_assist( + convert_to_guarded_return, + r#" + fn main() { + loop { + if$0 true { + foo(); + bar(); + } + } + } + "#, + r#" + fn main() { + loop { + if !true { + continue; + } + foo(); + bar(); + } + } + "#, + ); + } + + #[test] + fn convert_let_inside_loop() { + check_assist( + convert_to_guarded_return, + r#" + fn main() { + loop { + if$0 let Some(n) = n { + foo(n); + bar(); + } + } + } + "#, + r#" + fn main() { + loop { + let n = match n { + Some(it) => it, + _ => continue, + }; + foo(n); + bar(); + } + } + "#, + ); + } + + #[test] + fn ignore_already_converted_if() { + check_assist_not_applicable( + convert_to_guarded_return, + r#" + fn main() { + if$0 true { + return; + } + } + "#, + ); + } + + #[test] + fn ignore_already_converted_loop() { + check_assist_not_applicable( + convert_to_guarded_return, + r#" + fn main() { + loop { + if$0 true { + continue; + } + } + } + "#, + ); + } + + #[test] + fn ignore_return() { + check_assist_not_applicable( + convert_to_guarded_return, + r#" + fn main() { + if$0 true { + return + } + } + "#, + ); + } + + #[test] + fn ignore_else_branch() { + check_assist_not_applicable( + convert_to_guarded_return, + r#" + fn main() { + if$0 true { + foo(); + } else { + bar() + } + } + "#, + ); + } + + #[test] + fn ignore_statements_aftert_if() { + check_assist_not_applicable( + convert_to_guarded_return, + r#" + fn main() { + if$0 true { + foo(); + } + bar(); + } + "#, + ); + } + + #[test] + fn ignore_statements_inside_if() { + check_assist_not_applicable( + convert_to_guarded_return, + r#" + fn main() { + if false { + if$0 true { + foo(); + } + } + } + "#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/expand_glob_import.rs b/crates/ide_assists/src/handlers/expand_glob_import.rs new file mode 100644 index 000000000..5fe617ba4 --- /dev/null +++ b/crates/ide_assists/src/handlers/expand_glob_import.rs @@ -0,0 +1,907 @@ +use either::Either; +use hir::{AssocItem, MacroDef, Module, ModuleDef, Name, PathResolution, ScopeDef}; +use ide_db::{ + defs::{Definition, NameRefClass}, + search::SearchScope, +}; +use syntax::{ + algo::SyntaxRewriter, + ast::{self, make}, + AstNode, Direction, SyntaxNode, SyntaxToken, T, +}; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, AssistKind, +}; + +// Assist: expand_glob_import +// +// Expands glob imports. +// +// ``` +// mod foo { +// pub struct Bar; +// pub struct Baz; +// } +// +// use foo::*$0; +// +// fn qux(bar: Bar, baz: Baz) {} +// ``` +// -> +// ``` +// mod foo { +// pub struct Bar; +// pub struct Baz; +// } +// +// use foo::{Baz, Bar}; +// +// fn qux(bar: Bar, baz: Baz) {} +// ``` +pub(crate) fn expand_glob_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let star = ctx.find_token_syntax_at_offset(T![*])?; + let (parent, mod_path) = find_parent_and_path(&star)?; + let target_module = match ctx.sema.resolve_path(&mod_path)? { + PathResolution::Def(ModuleDef::Module(it)) => it, + _ => return None, + }; + + let current_scope = ctx.sema.scope(&star.parent()); + let current_module = current_scope.module()?; + + let refs_in_target = find_refs_in_mod(ctx, target_module, Some(current_module))?; + let imported_defs = find_imported_defs(ctx, star)?; + let names_to_import = find_names_to_import(ctx, refs_in_target, imported_defs); + + let target = parent.clone().either(|n| n.syntax().clone(), |n| n.syntax().clone()); + acc.add( + AssistId("expand_glob_import", AssistKind::RefactorRewrite), + "Expand glob import", + target.text_range(), + |builder| { + let mut rewriter = SyntaxRewriter::default(); + replace_ast(&mut rewriter, parent, mod_path, names_to_import); + builder.rewrite(rewriter); + }, + ) +} + +fn find_parent_and_path( + star: &SyntaxToken, +) -> Option<(Either, ast::Path)> { + return star.ancestors().find_map(|n| { + find_use_tree_list(n.clone()) + .and_then(|(u, p)| Some((Either::Right(u), p))) + .or_else(|| find_use_tree(n).and_then(|(u, p)| Some((Either::Left(u), p)))) + }); + + fn find_use_tree_list(n: SyntaxNode) -> Option<(ast::UseTreeList, ast::Path)> { + let use_tree_list = ast::UseTreeList::cast(n)?; + let path = use_tree_list.parent_use_tree().path()?; + Some((use_tree_list, path)) + } + + fn find_use_tree(n: SyntaxNode) -> Option<(ast::UseTree, ast::Path)> { + let use_tree = ast::UseTree::cast(n)?; + let path = use_tree.path()?; + Some((use_tree, path)) + } +} + +#[derive(Debug, PartialEq, Clone)] +enum Def { + ModuleDef(ModuleDef), + MacroDef(MacroDef), +} + +impl Def { + fn is_referenced_in(&self, ctx: &AssistContext) -> bool { + let def = match self { + Def::ModuleDef(def) => Definition::ModuleDef(*def), + Def::MacroDef(def) => Definition::Macro(*def), + }; + + let search_scope = SearchScope::single_file(ctx.frange.file_id); + def.usages(&ctx.sema).in_scope(search_scope).at_least_one() + } +} + +#[derive(Debug, Clone)] +struct Ref { + // could be alias + visible_name: Name, + def: Def, +} + +impl Ref { + fn from_scope_def(name: Name, scope_def: ScopeDef) -> Option { + match scope_def { + ScopeDef::ModuleDef(def) => Some(Ref { visible_name: name, def: Def::ModuleDef(def) }), + ScopeDef::MacroDef(def) => Some(Ref { visible_name: name, def: Def::MacroDef(def) }), + _ => None, + } + } +} + +#[derive(Debug, Clone)] +struct Refs(Vec); + +impl Refs { + fn used_refs(&self, ctx: &AssistContext) -> Refs { + Refs( + self.0 + .clone() + .into_iter() + .filter(|r| { + if let Def::ModuleDef(ModuleDef::Trait(tr)) = r.def { + if tr + .items(ctx.db()) + .into_iter() + .find(|ai| { + if let AssocItem::Function(f) = *ai { + Def::ModuleDef(ModuleDef::Function(f)).is_referenced_in(ctx) + } else { + false + } + }) + .is_some() + { + return true; + } + } + + r.def.is_referenced_in(ctx) + }) + .collect(), + ) + } + + fn filter_out_by_defs(&self, defs: Vec) -> Refs { + Refs(self.0.clone().into_iter().filter(|r| !defs.contains(&r.def)).collect()) + } +} + +fn find_refs_in_mod( + ctx: &AssistContext, + module: Module, + visible_from: Option, +) -> Option { + if let Some(from) = visible_from { + if !is_mod_visible_from(ctx, module, from) { + return None; + } + } + + let module_scope = module.scope(ctx.db(), visible_from); + let refs = module_scope.into_iter().filter_map(|(n, d)| Ref::from_scope_def(n, d)).collect(); + Some(Refs(refs)) +} + +fn is_mod_visible_from(ctx: &AssistContext, module: Module, from: Module) -> bool { + match module.parent(ctx.db()) { + Some(parent) => { + parent.visibility_of(ctx.db(), &ModuleDef::Module(module)).map_or(true, |vis| { + vis.is_visible_from(ctx.db(), from.into()) && is_mod_visible_from(ctx, parent, from) + }) + } + None => true, + } +} + +// looks for name refs in parent use block's siblings +// +// mod bar { +// mod qux { +// struct Qux; +// } +// +// pub use qux::Qux; +// } +// +// ↓ --------------- +// use foo::*$0; +// use baz::Baz; +// ↑ --------------- +fn find_imported_defs(ctx: &AssistContext, star: SyntaxToken) -> Option> { + let parent_use_item_syntax = + star.ancestors().find_map(|n| if ast::Use::can_cast(n.kind()) { Some(n) } else { None })?; + + Some( + [Direction::Prev, Direction::Next] + .iter() + .map(|dir| { + parent_use_item_syntax + .siblings(dir.to_owned()) + .filter(|n| ast::Use::can_cast(n.kind())) + }) + .flatten() + .filter_map(|n| Some(n.descendants().filter_map(ast::NameRef::cast))) + .flatten() + .filter_map(|r| match NameRefClass::classify(&ctx.sema, &r)? { + NameRefClass::Definition(Definition::ModuleDef(def)) => Some(Def::ModuleDef(def)), + NameRefClass::Definition(Definition::Macro(def)) => Some(Def::MacroDef(def)), + _ => None, + }) + .collect(), + ) +} + +fn find_names_to_import( + ctx: &AssistContext, + refs_in_target: Refs, + imported_defs: Vec, +) -> Vec { + let used_refs = refs_in_target.used_refs(ctx).filter_out_by_defs(imported_defs); + used_refs.0.iter().map(|r| r.visible_name.clone()).collect() +} + +fn replace_ast( + rewriter: &mut SyntaxRewriter, + parent: Either, + path: ast::Path, + names_to_import: Vec, +) { + let existing_use_trees = match parent.clone() { + Either::Left(_) => vec![], + Either::Right(u) => u + .use_trees() + .filter(|n| + // filter out star + n.star_token().is_none()) + .collect(), + }; + + let new_use_trees: Vec = names_to_import + .iter() + .map(|n| { + let path = make::path_unqualified(make::path_segment(make::name_ref(&n.to_string()))); + make::use_tree(path, None, None, false) + }) + .collect(); + + let use_trees = [&existing_use_trees[..], &new_use_trees[..]].concat(); + + match use_trees.as_slice() { + [name] => { + if let Some(end_path) = name.path() { + rewriter.replace_ast( + &parent.left_or_else(|tl| tl.parent_use_tree()), + &make::use_tree(make::path_concat(path, end_path), None, None, false), + ); + } + } + names => match &parent { + Either::Left(parent) => rewriter.replace_ast( + parent, + &make::use_tree(path, Some(make::use_tree_list(names.to_owned())), None, false), + ), + Either::Right(parent) => { + rewriter.replace_ast(parent, &make::use_tree_list(names.to_owned())) + } + }, + }; +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn expanding_glob_import() { + check_assist( + expand_glob_import, + r" +mod foo { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} +} + +use foo::*$0; + +fn qux(bar: Bar, baz: Baz) { + f(); +} +", + r" +mod foo { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} +} + +use foo::{Baz, Bar, f}; + +fn qux(bar: Bar, baz: Baz) { + f(); +} +", + ) + } + + #[test] + fn expanding_glob_import_with_existing_explicit_names() { + check_assist( + expand_glob_import, + r" +mod foo { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} +} + +use foo::{*$0, f}; + +fn qux(bar: Bar, baz: Baz) { + f(); +} +", + r" +mod foo { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} +} + +use foo::{f, Baz, Bar}; + +fn qux(bar: Bar, baz: Baz) { + f(); +} +", + ) + } + + #[test] + fn expanding_glob_import_with_existing_uses_in_same_module() { + check_assist( + expand_glob_import, + r" +mod foo { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} +} + +use foo::Bar; +use foo::{*$0, f}; + +fn qux(bar: Bar, baz: Baz) { + f(); +} +", + r" +mod foo { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} +} + +use foo::Bar; +use foo::{f, Baz}; + +fn qux(bar: Bar, baz: Baz) { + f(); +} +", + ) + } + + #[test] + fn expanding_nested_glob_import() { + check_assist( + expand_glob_import, + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + } +} + +use foo::{bar::{*$0, f}, baz::*}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); +} +", + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + } +} + +use foo::{bar::{f, Baz, Bar}, baz::*}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); +} +", + ); + + check_assist( + expand_glob_import, + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + } +} + +use foo::{bar::{Bar, Baz, f}, baz::*$0}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); +} +", + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + } +} + +use foo::{bar::{Bar, Baz, f}, baz::g}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); +} +", + ); + + check_assist( + expand_glob_import, + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + + pub mod qux { + pub fn h() {} + pub fn m() {} + + pub mod q { + pub fn j() {} + } + } + } +} + +use foo::{ + bar::{*, f}, + baz::{g, qux::*$0} +}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); + h(); + q::j(); +} +", + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + + pub mod qux { + pub fn h() {} + pub fn m() {} + + pub mod q { + pub fn j() {} + } + } + } +} + +use foo::{ + bar::{*, f}, + baz::{g, qux::{q, h}} +}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); + h(); + q::j(); +} +", + ); + + check_assist( + expand_glob_import, + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + + pub mod qux { + pub fn h() {} + pub fn m() {} + + pub mod q { + pub fn j() {} + } + } + } +} + +use foo::{ + bar::{*, f}, + baz::{g, qux::{h, q::*$0}} +}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); + h(); + j(); +} +", + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + + pub mod qux { + pub fn h() {} + pub fn m() {} + + pub mod q { + pub fn j() {} + } + } + } +} + +use foo::{ + bar::{*, f}, + baz::{g, qux::{h, q::j}} +}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); + h(); + j(); +} +", + ); + + check_assist( + expand_glob_import, + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + + pub mod qux { + pub fn h() {} + pub fn m() {} + + pub mod q { + pub fn j() {} + } + } + } +} + +use foo::{ + bar::{*, f}, + baz::{g, qux::{q::j, *$0}} +}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); + h(); + j(); +} +", + r" +mod foo { + pub mod bar { + pub struct Bar; + pub struct Baz; + pub struct Qux; + + pub fn f() {} + } + + pub mod baz { + pub fn g() {} + + pub mod qux { + pub fn h() {} + pub fn m() {} + + pub mod q { + pub fn j() {} + } + } + } +} + +use foo::{ + bar::{*, f}, + baz::{g, qux::{q::j, h}} +}; + +fn qux(bar: Bar, baz: Baz) { + f(); + g(); + h(); + j(); +} +", + ); + } + + #[test] + fn expanding_glob_import_with_macro_defs() { + // FIXME: this is currently fails because `Definition::find_usages` ignores macros + // https://github.com/rust-analyzer/rust-analyzer/issues/3484 + // + // check_assist( + // expand_glob_import, + // r" + // //- /lib.rs crate:foo + // #[macro_export] + // macro_rules! bar { + // () => () + // } + + // pub fn baz() {} + + // //- /main.rs crate:main deps:foo + // use foo::*$0; + + // fn main() { + // bar!(); + // baz(); + // } + // ", + // r" + // use foo::{bar, baz}; + + // fn main() { + // bar!(); + // baz(); + // } + // ", + // ) + } + + #[test] + fn expanding_glob_import_with_trait_method_uses() { + check_assist( + expand_glob_import, + r" +//- /lib.rs crate:foo +pub trait Tr { + fn method(&self) {} +} +impl Tr for () {} + +//- /main.rs crate:main deps:foo +use foo::*$0; + +fn main() { + ().method(); +} +", + r" +use foo::Tr; + +fn main() { + ().method(); +} +", + ); + + check_assist( + expand_glob_import, + r" +//- /lib.rs crate:foo +pub trait Tr { + fn method(&self) {} +} +impl Tr for () {} + +pub trait Tr2 { + fn method2(&self) {} +} +impl Tr2 for () {} + +//- /main.rs crate:main deps:foo +use foo::*$0; + +fn main() { + ().method(); +} +", + r" +use foo::Tr; + +fn main() { + ().method(); +} +", + ); + } + + #[test] + fn expanding_is_not_applicable_if_target_module_is_not_accessible_from_current_scope() { + check_assist_not_applicable( + expand_glob_import, + r" +mod foo { + mod bar { + pub struct Bar; + } +} + +use foo::bar::*$0; + +fn baz(bar: Bar) {} +", + ); + + check_assist_not_applicable( + expand_glob_import, + r" +mod foo { + mod bar { + pub mod baz { + pub struct Baz; + } + } +} + +use foo::bar::baz::*$0; + +fn qux(baz: Baz) {} +", + ); + } + + #[test] + fn expanding_is_not_applicable_if_cursor_is_not_in_star_token() { + check_assist_not_applicable( + expand_glob_import, + r" + mod foo { + pub struct Bar; + pub struct Baz; + pub struct Qux; + } + + use foo::Bar$0; + + fn qux(bar: Bar, baz: Baz) {} + ", + ) + } + + #[test] + fn expanding_glob_import_single_nested_glob_only() { + check_assist( + expand_glob_import, + r" +mod foo { + pub struct Bar; +} + +use foo::{*$0}; + +struct Baz { + bar: Bar +} +", + r" +mod foo { + pub struct Bar; +} + +use foo::Bar; + +struct Baz { + bar: Bar +} +", + ); + } +} diff --git a/crates/ide_assists/src/handlers/extract_function.rs b/crates/ide_assists/src/handlers/extract_function.rs new file mode 100644 index 000000000..9f34cc725 --- /dev/null +++ b/crates/ide_assists/src/handlers/extract_function.rs @@ -0,0 +1,3378 @@ +use std::iter; + +use ast::make; +use either::Either; +use hir::{HirDisplay, Local}; +use ide_db::{ + defs::{Definition, NameRefClass}, + search::{FileReference, ReferenceAccess, SearchScope}, +}; +use itertools::Itertools; +use stdx::format_to; +use syntax::{ + algo::SyntaxRewriter, + ast::{ + self, + edit::{AstNodeEdit, IndentLevel}, + AstNode, + }, + SyntaxElement, + SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR}, + SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T, +}; +use test_utils::mark; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, +}; + +// Assist: extract_function +// +// Extracts selected statements into new function. +// +// ``` +// fn main() { +// let n = 1; +// $0let m = n + 2; +// let k = m + n;$0 +// let g = 3; +// } +// ``` +// -> +// ``` +// fn main() { +// let n = 1; +// fun_name(n); +// let g = 3; +// } +// +// fn $0fun_name(n: i32) { +// let m = n + 2; +// let k = m + n; +// } +// ``` +pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + if ctx.frange.range.is_empty() { + return None; + } + + let node = ctx.covering_element(); + if node.kind() == COMMENT { + mark::hit!(extract_function_in_comment_is_not_applicable); + return None; + } + + let node = element_to_node(node); + + let body = extraction_target(&node, ctx.frange.range)?; + + let vars_used_in_body = vars_used_in_body(ctx, &body); + let self_param = self_param_from_usages(ctx, &body, &vars_used_in_body); + + let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding }; + let insert_after = scope_for_fn_insertion(&body, anchor)?; + let module = ctx.sema.scope(&insert_after).module()?; + + let vars_defined_in_body_and_outlive = vars_defined_in_body_and_outlive(ctx, &body); + let ret_ty = body_return_ty(ctx, &body)?; + + // FIXME: we compute variables that outlive here just to check `never!` condition + // this requires traversing whole `body` (cheap) and finding all references (expensive) + // maybe we can move this check to `edit` closure somehow? + if stdx::never!(!vars_defined_in_body_and_outlive.is_empty() && !ret_ty.is_unit()) { + // We should not have variables that outlive body if we have expression block + return None; + } + let control_flow = external_control_flow(ctx, &body)?; + + let target_range = body.text_range(); + + acc.add( + AssistId("extract_function", crate::AssistKind::RefactorExtract), + "Extract into function", + target_range, + move |builder| { + let params = extracted_function_params(ctx, &body, &vars_used_in_body); + + let fun = Function { + name: "fun_name".to_string(), + self_param: self_param.map(|(_, pat)| pat), + params, + control_flow, + ret_ty, + body, + vars_defined_in_body_and_outlive, + }; + + let new_indent = IndentLevel::from_node(&insert_after); + let old_indent = fun.body.indent_level(); + + builder.replace(target_range, format_replacement(ctx, &fun, old_indent)); + + let fn_def = format_function(ctx, module, &fun, old_indent, new_indent); + let insert_offset = insert_after.text_range().end(); + builder.insert(insert_offset, fn_def); + }, + ) +} + +fn external_control_flow(ctx: &AssistContext, body: &FunctionBody) -> Option { + let mut ret_expr = None; + let mut try_expr = None; + let mut break_expr = None; + let mut continue_expr = None; + let (syntax, text_range) = match body { + FunctionBody::Expr(expr) => (expr.syntax(), expr.syntax().text_range()), + FunctionBody::Span { parent, text_range } => (parent.syntax(), *text_range), + }; + + let mut nested_loop = None; + let mut nested_scope = None; + + for e in syntax.preorder() { + let e = match e { + WalkEvent::Enter(e) => e, + WalkEvent::Leave(e) => { + if nested_loop.as_ref() == Some(&e) { + nested_loop = None; + } + if nested_scope.as_ref() == Some(&e) { + nested_scope = None; + } + continue; + } + }; + if nested_scope.is_some() { + continue; + } + if !text_range.contains_range(e.text_range()) { + continue; + } + match e.kind() { + SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => { + if nested_loop.is_none() { + nested_loop = Some(e); + } + } + SyntaxKind::FN + | SyntaxKind::CONST + | SyntaxKind::STATIC + | SyntaxKind::IMPL + | SyntaxKind::MODULE => { + if nested_scope.is_none() { + nested_scope = Some(e); + } + } + SyntaxKind::RETURN_EXPR => { + ret_expr = Some(ast::ReturnExpr::cast(e).unwrap()); + } + SyntaxKind::TRY_EXPR => { + try_expr = Some(ast::TryExpr::cast(e).unwrap()); + } + SyntaxKind::BREAK_EXPR if nested_loop.is_none() => { + break_expr = Some(ast::BreakExpr::cast(e).unwrap()); + } + SyntaxKind::CONTINUE_EXPR if nested_loop.is_none() => { + continue_expr = Some(ast::ContinueExpr::cast(e).unwrap()); + } + _ => {} + } + } + + let kind = match (try_expr, ret_expr, break_expr, continue_expr) { + (Some(e), None, None, None) => { + let func = e.syntax().ancestors().find_map(ast::Fn::cast)?; + let def = ctx.sema.to_def(&func)?; + let ret_ty = def.ret_type(ctx.db()); + let kind = try_kind_of_ty(ret_ty, ctx)?; + + Some(FlowKind::Try { kind }) + } + (Some(_), Some(r), None, None) => match r.expr() { + Some(expr) => { + if let Some(kind) = expr_err_kind(&expr, ctx) { + Some(FlowKind::TryReturn { expr, kind }) + } else { + mark::hit!(external_control_flow_try_and_return_non_err); + return None; + } + } + None => return None, + }, + (Some(_), _, _, _) => { + mark::hit!(external_control_flow_try_and_bc); + return None; + } + (None, Some(r), None, None) => match r.expr() { + Some(expr) => Some(FlowKind::ReturnValue(expr)), + None => Some(FlowKind::Return), + }, + (None, Some(_), _, _) => { + mark::hit!(external_control_flow_return_and_bc); + return None; + } + (None, None, Some(_), Some(_)) => { + mark::hit!(external_control_flow_break_and_continue); + return None; + } + (None, None, Some(b), None) => match b.expr() { + Some(expr) => Some(FlowKind::BreakValue(expr)), + None => Some(FlowKind::Break), + }, + (None, None, None, Some(_)) => Some(FlowKind::Continue), + (None, None, None, None) => None, + }; + + Some(ControlFlow { kind }) +} + +/// Checks is expr is `Err(_)` or `None` +fn expr_err_kind(expr: &ast::Expr, ctx: &AssistContext) -> Option { + let func_name = match expr { + ast::Expr::CallExpr(call_expr) => call_expr.expr()?, + ast::Expr::PathExpr(_) => expr.clone(), + _ => return None, + }; + let text = func_name.syntax().text(); + + if text == "Err" { + Some(TryKind::Result { ty: ctx.sema.type_of_expr(expr)? }) + } else if text == "None" { + Some(TryKind::Option) + } else { + None + } +} + +#[derive(Debug)] +struct Function { + name: String, + self_param: Option, + params: Vec, + control_flow: ControlFlow, + ret_ty: RetType, + body: FunctionBody, + vars_defined_in_body_and_outlive: Vec, +} + +#[derive(Debug)] +struct Param { + var: Local, + ty: hir::Type, + has_usages_afterwards: bool, + has_mut_inside_body: bool, + is_copy: bool, +} + +#[derive(Debug)] +struct ControlFlow { + kind: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ParamKind { + Value, + MutValue, + SharedRef, + MutRef, +} + +#[derive(Debug, Eq, PartialEq)] +enum FunType { + Unit, + Single(hir::Type), + Tuple(Vec), +} + +impl Function { + fn return_type(&self, ctx: &AssistContext) -> FunType { + match &self.ret_ty { + RetType::Expr(ty) if ty.is_unit() => FunType::Unit, + RetType::Expr(ty) => FunType::Single(ty.clone()), + RetType::Stmt => match self.vars_defined_in_body_and_outlive.as_slice() { + [] => FunType::Unit, + [var] => FunType::Single(var.ty(ctx.db())), + vars => { + let types = vars.iter().map(|v| v.ty(ctx.db())).collect(); + FunType::Tuple(types) + } + }, + } + } +} + +impl ParamKind { + fn is_ref(&self) -> bool { + matches!(self, ParamKind::SharedRef | ParamKind::MutRef) + } +} + +impl Param { + fn kind(&self) -> ParamKind { + match (self.has_usages_afterwards, self.has_mut_inside_body, self.is_copy) { + (true, true, _) => ParamKind::MutRef, + (true, false, false) => ParamKind::SharedRef, + (false, true, _) => ParamKind::MutValue, + (true, false, true) | (false, false, _) => ParamKind::Value, + } + } + + fn to_arg(&self, ctx: &AssistContext) -> ast::Expr { + let var = path_expr_from_local(ctx, self.var); + match self.kind() { + ParamKind::Value | ParamKind::MutValue => var, + ParamKind::SharedRef => make::expr_ref(var, false), + ParamKind::MutRef => make::expr_ref(var, true), + } + } + + fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param { + let var = self.var.name(ctx.db()).unwrap().to_string(); + let var_name = make::name(&var); + let pat = match self.kind() { + ParamKind::MutValue => make::ident_mut_pat(var_name), + ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => { + make::ident_pat(var_name) + } + }; + + let ty = make_ty(&self.ty, ctx, module); + let ty = match self.kind() { + ParamKind::Value | ParamKind::MutValue => ty, + ParamKind::SharedRef => make::ty_ref(ty, false), + ParamKind::MutRef => make::ty_ref(ty, true), + }; + + make::param(pat.into(), ty) + } +} + +/// Control flow that is exported from extracted function +/// +/// E.g.: +/// ```rust,no_run +/// loop { +/// $0 +/// if 42 == 42 { +/// break; +/// } +/// $0 +/// } +/// ``` +#[derive(Debug, Clone)] +enum FlowKind { + /// Return without value (`return;`) + Return, + /// Return with value (`return $expr;`) + ReturnValue(ast::Expr), + Try { + kind: TryKind, + }, + TryReturn { + expr: ast::Expr, + kind: TryKind, + }, + /// Break without value (`return;`) + Break, + /// Break with value (`break $expr;`) + BreakValue(ast::Expr), + /// Continue + Continue, +} + +#[derive(Debug, Clone)] +enum TryKind { + Option, + Result { ty: hir::Type }, +} + +impl FlowKind { + fn make_result_handler(&self, expr: Option) -> ast::Expr { + match self { + FlowKind::Return | FlowKind::ReturnValue(_) => make::expr_return(expr), + FlowKind::Break | FlowKind::BreakValue(_) => make::expr_break(expr), + FlowKind::Try { .. } | FlowKind::TryReturn { .. } => { + stdx::never!("cannot have result handler with try"); + expr.unwrap_or_else(|| make::expr_return(None)) + } + FlowKind::Continue => { + stdx::always!(expr.is_none(), "continue with value is not possible"); + make::expr_continue() + } + } + } + + fn expr_ty(&self, ctx: &AssistContext) -> Option { + match self { + FlowKind::ReturnValue(expr) + | FlowKind::BreakValue(expr) + | FlowKind::TryReturn { expr, .. } => ctx.sema.type_of_expr(expr), + FlowKind::Try { .. } => { + stdx::never!("try does not have defined expr_ty"); + None + } + FlowKind::Return | FlowKind::Break | FlowKind::Continue => None, + } + } +} + +fn try_kind_of_ty(ty: hir::Type, ctx: &AssistContext) -> Option { + if ty.is_unknown() { + // We favour Result for `expr?` + return Some(TryKind::Result { ty }); + } + let adt = ty.as_adt()?; + let name = adt.name(ctx.db()); + // FIXME: use lang items to determine if it is std type or user defined + // E.g. if user happens to define type named `Option`, we would have false positive + match name.to_string().as_str() { + "Option" => Some(TryKind::Option), + "Result" => Some(TryKind::Result { ty }), + _ => None, + } +} + +#[derive(Debug)] +enum RetType { + Expr(hir::Type), + Stmt, +} + +impl RetType { + fn is_unit(&self) -> bool { + match self { + RetType::Expr(ty) => ty.is_unit(), + RetType::Stmt => true, + } + } +} + +/// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block +#[derive(Debug)] +enum FunctionBody { + Expr(ast::Expr), + Span { parent: ast::BlockExpr, text_range: TextRange }, +} + +impl FunctionBody { + fn from_whole_node(node: SyntaxNode) -> Option { + match node.kind() { + PATH_EXPR => None, + BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr), + RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr), + BLOCK_EXPR => ast::BlockExpr::cast(node) + .filter(|it| it.is_standalone()) + .map(Into::into) + .map(Self::Expr), + _ => ast::Expr::cast(node).map(Self::Expr), + } + } + + fn from_range(node: SyntaxNode, text_range: TextRange) -> Option { + let block = ast::BlockExpr::cast(node)?; + Some(Self::Span { parent: block, text_range }) + } + + fn indent_level(&self) -> IndentLevel { + match &self { + FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()), + FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1, + } + } + + fn tail_expr(&self) -> Option { + match &self { + FunctionBody::Expr(expr) => Some(expr.clone()), + FunctionBody::Span { parent, text_range } => { + let tail_expr = parent.tail_expr()?; + if text_range.contains_range(tail_expr.syntax().text_range()) { + Some(tail_expr) + } else { + None + } + } + } + } + + fn descendants(&self) -> impl Iterator + '_ { + match self { + FunctionBody::Expr(expr) => Either::Right(expr.syntax().descendants()), + FunctionBody::Span { parent, text_range } => Either::Left( + parent + .syntax() + .descendants() + .filter(move |it| text_range.contains_range(it.text_range())), + ), + } + } + + fn text_range(&self) -> TextRange { + match self { + FunctionBody::Expr(expr) => expr.syntax().text_range(), + FunctionBody::Span { parent: _, text_range } => *text_range, + } + } + + fn contains_range(&self, range: TextRange) -> bool { + self.text_range().contains_range(range) + } + + fn preceedes_range(&self, range: TextRange) -> bool { + self.text_range().end() <= range.start() + } + + fn contains_node(&self, node: &SyntaxNode) -> bool { + self.contains_range(node.text_range()) + } +} + +impl HasTokenAtOffset for FunctionBody { + fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset { + match self { + FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset), + FunctionBody::Span { parent, text_range } => { + match parent.syntax().token_at_offset(offset) { + TokenAtOffset::None => TokenAtOffset::None, + TokenAtOffset::Single(t) => { + if text_range.contains_range(t.text_range()) { + TokenAtOffset::Single(t) + } else { + TokenAtOffset::None + } + } + TokenAtOffset::Between(a, b) => { + match ( + text_range.contains_range(a.text_range()), + text_range.contains_range(b.text_range()), + ) { + (true, true) => TokenAtOffset::Between(a, b), + (true, false) => TokenAtOffset::Single(a), + (false, true) => TokenAtOffset::Single(b), + (false, false) => TokenAtOffset::None, + } + } + } + } + } + } +} + +/// node or token's parent +fn element_to_node(node: SyntaxElement) -> SyntaxNode { + match node { + syntax::NodeOrToken::Node(n) => n, + syntax::NodeOrToken::Token(t) => t.parent(), + } +} + +/// Try to guess what user wants to extract +/// +/// We have basically have two cases: +/// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs. +/// Then we can use `ast::Expr` +/// * We want a few statements for a block. E.g. +/// ```rust,no_run +/// fn foo() -> i32 { +/// let m = 1; +/// $0 +/// let n = 2; +/// let k = 3; +/// k + n +/// $0 +/// } +/// ``` +/// +fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option { + // we have selected exactly the expr node + // wrap it before anything else + if node.text_range() == selection_range { + let body = FunctionBody::from_whole_node(node.clone()); + if body.is_some() { + return body; + } + } + + // we have selected a few statements in a block + // so covering_element returns the whole block + if node.kind() == BLOCK_EXPR { + let body = FunctionBody::from_range(node.clone(), selection_range); + if body.is_some() { + return body; + } + } + + // we have selected single statement + // `from_whole_node` failed because (let) statement is not and expression + // so we try to expand covering_element to parent and repeat the previous + if let Some(parent) = node.parent() { + if parent.kind() == BLOCK_EXPR { + let body = FunctionBody::from_range(parent, selection_range); + if body.is_some() { + return body; + } + } + } + + // select the closest containing expr (both ifs are used) + std::iter::once(node.clone()).chain(node.ancestors()).find_map(FunctionBody::from_whole_node) +} + +/// list local variables that are referenced in `body` +fn vars_used_in_body(ctx: &AssistContext, body: &FunctionBody) -> Vec { + // FIXME: currently usages inside macros are not found + body.descendants() + .filter_map(ast::NameRef::cast) + .filter_map(|name_ref| NameRefClass::classify(&ctx.sema, &name_ref)) + .map(|name_kind| name_kind.referenced(ctx.db())) + .filter_map(|definition| match definition { + Definition::Local(local) => Some(local), + _ => None, + }) + .unique() + .collect() +} + +/// find `self` param, that was not defined inside `body` +/// +/// It should skip `self` params from impls inside `body` +fn self_param_from_usages( + ctx: &AssistContext, + body: &FunctionBody, + vars_used_in_body: &[Local], +) -> Option<(Local, ast::SelfParam)> { + let mut iter = vars_used_in_body + .iter() + .filter(|var| var.is_self(ctx.db())) + .map(|var| (var, var.source(ctx.db()))) + .filter(|(_, src)| is_defined_before(ctx, body, src)) + .filter_map(|(&node, src)| match src.value { + Either::Right(it) => Some((node, it)), + Either::Left(_) => { + stdx::never!(false, "Local::is_self returned true, but source is IdentPat"); + None + } + }); + + let self_param = iter.next(); + stdx::always!( + iter.next().is_none(), + "body references two different self params, both defined outside" + ); + + self_param +} + +/// find variables that should be extracted as params +/// +/// Computes additional info that affects param type and mutability +fn extracted_function_params( + ctx: &AssistContext, + body: &FunctionBody, + vars_used_in_body: &[Local], +) -> Vec { + vars_used_in_body + .iter() + .filter(|var| !var.is_self(ctx.db())) + .map(|node| (node, node.source(ctx.db()))) + .filter(|(_, src)| is_defined_before(ctx, body, src)) + .filter_map(|(&node, src)| { + if src.value.is_left() { + Some(node) + } else { + stdx::never!(false, "Local::is_self returned false, but source is SelfParam"); + None + } + }) + .map(|var| { + let usages = LocalUsages::find(ctx, var); + let ty = var.ty(ctx.db()); + let is_copy = ty.is_copy(ctx.db()); + Param { + var, + ty, + has_usages_afterwards: has_usages_after_body(&usages, body), + has_mut_inside_body: has_exclusive_usages(ctx, &usages, body), + is_copy, + } + }) + .collect() +} + +fn has_usages_after_body(usages: &LocalUsages, body: &FunctionBody) -> bool { + usages.iter().any(|reference| body.preceedes_range(reference.range)) +} + +/// checks if relevant var is used with `&mut` access inside body +fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool { + usages + .iter() + .filter(|reference| body.contains_range(reference.range)) + .any(|reference| reference_is_exclusive(reference, body, ctx)) +} + +/// checks if this reference requires `&mut` access inside body +fn reference_is_exclusive( + reference: &FileReference, + body: &FunctionBody, + ctx: &AssistContext, +) -> bool { + // we directly modify variable with set: `n = 0`, `n += 1` + if reference.access == Some(ReferenceAccess::Write) { + return true; + } + + // we take `&mut` reference to variable: `&mut v` + let path = match path_element_of_reference(body, reference) { + Some(path) => path, + None => return false, + }; + + expr_require_exclusive_access(ctx, &path).unwrap_or(false) +} + +/// checks if this expr requires `&mut` access, recurses on field access +fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option { + let parent = expr.syntax().parent()?; + + if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) { + if bin_expr.op_kind()?.is_assignment() { + return Some(bin_expr.lhs()?.syntax() == expr.syntax()); + } + return Some(false); + } + + if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) { + return Some(ref_expr.mut_token().is_some()); + } + + if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) { + let func = ctx.sema.resolve_method_call(&method_call)?; + let self_param = func.self_param(ctx.db())?; + let access = self_param.access(ctx.db()); + + return Some(matches!(access, hir::Access::Exclusive)); + } + + if let Some(field) = ast::FieldExpr::cast(parent) { + return expr_require_exclusive_access(ctx, &field.into()); + } + + Some(false) +} + +/// Container of local varaible usages +/// +/// Semanticall same as `UsageSearchResult`, but provides more convenient interface +struct LocalUsages(ide_db::search::UsageSearchResult); + +impl LocalUsages { + fn find(ctx: &AssistContext, var: Local) -> Self { + Self( + Definition::Local(var) + .usages(&ctx.sema) + .in_scope(SearchScope::single_file(ctx.frange.file_id)) + .all(), + ) + } + + fn iter(&self) -> impl Iterator + '_ { + self.0.iter().flat_map(|(_, rs)| rs.iter()) + } +} + +trait HasTokenAtOffset { + fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset; +} + +impl HasTokenAtOffset for SyntaxNode { + fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset { + SyntaxNode::token_at_offset(&self, offset) + } +} + +/// find relevant `ast::PathExpr` for reference +/// +/// # Preconditions +/// +/// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)` +fn path_element_of_reference( + node: &dyn HasTokenAtOffset, + reference: &FileReference, +) -> Option { + let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| { + stdx::never!(false, "cannot find token at variable usage: {:?}", reference); + None + })?; + let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| { + stdx::never!(false, "cannot find path parent of variable usage: {:?}", token); + None + })?; + stdx::always!(matches!(path, ast::Expr::PathExpr(_))); + Some(path) +} + +/// list local variables defined inside `body` +fn vars_defined_in_body(body: &FunctionBody, ctx: &AssistContext) -> Vec { + // FIXME: this doesn't work well with macros + // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550 + body.descendants() + .filter_map(ast::IdentPat::cast) + .filter_map(|let_stmt| ctx.sema.to_def(&let_stmt)) + .unique() + .collect() +} + +/// list local variables defined inside `body` that should be returned from extracted function +fn vars_defined_in_body_and_outlive(ctx: &AssistContext, body: &FunctionBody) -> Vec { + let mut vars_defined_in_body = vars_defined_in_body(&body, ctx); + vars_defined_in_body.retain(|var| var_outlives_body(ctx, body, var)); + vars_defined_in_body +} + +/// checks if the relevant local was defined before(outside of) body +fn is_defined_before( + ctx: &AssistContext, + body: &FunctionBody, + src: &hir::InFile>, +) -> bool { + src.file_id.original_file(ctx.db()) == ctx.frange.file_id + && !body.contains_node(&either_syntax(&src.value)) +} + +fn either_syntax(value: &Either) -> &SyntaxNode { + match value { + Either::Left(pat) => pat.syntax(), + Either::Right(it) => it.syntax(), + } +} + +/// checks if local variable is used after(outside of) body +fn var_outlives_body(ctx: &AssistContext, body: &FunctionBody, var: &Local) -> bool { + let usages = LocalUsages::find(ctx, *var); + let has_usages = usages.iter().any(|reference| body.preceedes_range(reference.range)); + has_usages +} + +fn body_return_ty(ctx: &AssistContext, body: &FunctionBody) -> Option { + match body.tail_expr() { + Some(expr) => { + let ty = ctx.sema.type_of_expr(&expr)?; + Some(RetType::Expr(ty)) + } + None => Some(RetType::Stmt), + } +} +/// Where to put extracted function definition +#[derive(Debug)] +enum Anchor { + /// Extract free function and put right after current top-level function + Freestanding, + /// Extract method and put right after current function in the impl-block + Method, +} + +/// find where to put extracted function definition +/// +/// Function should be put right after returned node +fn scope_for_fn_insertion(body: &FunctionBody, anchor: Anchor) -> Option { + match body { + FunctionBody::Expr(e) => scope_for_fn_insertion_node(e.syntax(), anchor), + FunctionBody::Span { parent, .. } => scope_for_fn_insertion_node(parent.syntax(), anchor), + } +} + +fn scope_for_fn_insertion_node(node: &SyntaxNode, anchor: Anchor) -> Option { + let mut ancestors = node.ancestors().peekable(); + let mut last_ancestor = None; + while let Some(next_ancestor) = ancestors.next() { + match next_ancestor.kind() { + SyntaxKind::SOURCE_FILE => break, + SyntaxKind::ITEM_LIST => { + if !matches!(anchor, Anchor::Freestanding) { + continue; + } + if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) { + break; + } + } + SyntaxKind::ASSOC_ITEM_LIST => { + if !matches!(anchor, Anchor::Method) { + continue; + } + if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) { + break; + } + } + _ => {} + } + last_ancestor = Some(next_ancestor); + } + last_ancestor +} + +fn format_replacement(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String { + let ret_ty = fun.return_type(ctx); + + let args = fun.params.iter().map(|param| param.to_arg(ctx)); + let args = make::arg_list(args); + let call_expr = if fun.self_param.is_some() { + let self_arg = make::expr_path(make_path_from_text("self")); + make::expr_method_call(self_arg, &fun.name, args) + } else { + let func = make::expr_path(make_path_from_text(&fun.name)); + make::expr_call(func, args) + }; + + let handler = FlowHandler::from_ret_ty(fun, &ret_ty); + + let expr = handler.make_call_expr(call_expr).indent(indent); + + let mut buf = String::new(); + match fun.vars_defined_in_body_and_outlive.as_slice() { + [] => {} + [var] => format_to!(buf, "let {} = ", var.name(ctx.db()).unwrap()), + [v0, vs @ ..] => { + buf.push_str("let ("); + format_to!(buf, "{}", v0.name(ctx.db()).unwrap()); + for var in vs { + format_to!(buf, ", {}", var.name(ctx.db()).unwrap()); + } + buf.push_str(") = "); + } + } + format_to!(buf, "{}", expr); + if fun.ret_ty.is_unit() + && (!fun.vars_defined_in_body_and_outlive.is_empty() || !expr.is_block_like()) + { + buf.push(';'); + } + buf +} + +enum FlowHandler { + None, + Try { kind: TryKind }, + If { action: FlowKind }, + IfOption { action: FlowKind }, + MatchOption { none: FlowKind }, + MatchResult { err: FlowKind }, +} + +impl FlowHandler { + fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler { + match &fun.control_flow.kind { + None => FlowHandler::None, + Some(flow_kind) => { + let action = flow_kind.clone(); + if *ret_ty == FunType::Unit { + match flow_kind { + FlowKind::Return | FlowKind::Break | FlowKind::Continue => { + FlowHandler::If { action } + } + FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => { + FlowHandler::IfOption { action } + } + FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => { + FlowHandler::Try { kind: kind.clone() } + } + } + } else { + match flow_kind { + FlowKind::Return | FlowKind::Break | FlowKind::Continue => { + FlowHandler::MatchOption { none: action } + } + FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => { + FlowHandler::MatchResult { err: action } + } + FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => { + FlowHandler::Try { kind: kind.clone() } + } + } + } + } + } + } + + fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr { + match self { + FlowHandler::None => call_expr, + FlowHandler::Try { kind: _ } => make::expr_try(call_expr), + FlowHandler::If { action } => { + let action = action.make_result_handler(None); + let stmt = make::expr_stmt(action); + let block = make::block_expr(iter::once(stmt.into()), None); + let condition = make::condition(call_expr, None); + make::expr_if(condition, block, None) + } + FlowHandler::IfOption { action } => { + let path = make_path_from_text("Some"); + let value_pat = make::ident_pat(make::name("value")); + let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into())); + let cond = make::condition(call_expr, Some(pattern.into())); + let value = make::expr_path(make_path_from_text("value")); + let action_expr = action.make_result_handler(Some(value)); + let action_stmt = make::expr_stmt(action_expr); + let then = make::block_expr(iter::once(action_stmt.into()), None); + make::expr_if(cond, then, None) + } + FlowHandler::MatchOption { none } => { + let some_name = "value"; + + let some_arm = { + let path = make_path_from_text("Some"); + let value_pat = make::ident_pat(make::name(some_name)); + let pat = make::tuple_struct_pat(path, iter::once(value_pat.into())); + let value = make::expr_path(make_path_from_text(some_name)); + make::match_arm(iter::once(pat.into()), value) + }; + let none_arm = { + let path = make_path_from_text("None"); + let pat = make::path_pat(path); + make::match_arm(iter::once(pat), none.make_result_handler(None)) + }; + let arms = make::match_arm_list(vec![some_arm, none_arm]); + make::expr_match(call_expr, arms) + } + FlowHandler::MatchResult { err } => { + let ok_name = "value"; + let err_name = "value"; + + let ok_arm = { + let path = make_path_from_text("Ok"); + let value_pat = make::ident_pat(make::name(ok_name)); + let pat = make::tuple_struct_pat(path, iter::once(value_pat.into())); + let value = make::expr_path(make_path_from_text(ok_name)); + make::match_arm(iter::once(pat.into()), value) + }; + let err_arm = { + let path = make_path_from_text("Err"); + let value_pat = make::ident_pat(make::name(err_name)); + let pat = make::tuple_struct_pat(path, iter::once(value_pat.into())); + let value = make::expr_path(make_path_from_text(err_name)); + make::match_arm(iter::once(pat.into()), err.make_result_handler(Some(value))) + }; + let arms = make::match_arm_list(vec![ok_arm, err_arm]); + make::expr_match(call_expr, arms) + } + } + } +} + +fn make_path_from_text(text: &str) -> ast::Path { + make::path_unqualified(make::path_segment(make::name_ref(text))) +} + +fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr { + let name = var.name(ctx.db()).unwrap().to_string(); + make::expr_path(make_path_from_text(&name)) +} + +fn format_function( + ctx: &AssistContext, + module: hir::Module, + fun: &Function, + old_indent: IndentLevel, + new_indent: IndentLevel, +) -> String { + let mut fn_def = String::new(); + let params = make_param_list(ctx, module, fun); + let ret_ty = make_ret_ty(ctx, module, fun); + let body = make_body(ctx, old_indent, new_indent, fun); + format_to!(fn_def, "\n\n{}fn $0{}{}", new_indent, fun.name, params); + if let Some(ret_ty) = ret_ty { + format_to!(fn_def, " {}", ret_ty); + } + format_to!(fn_def, " {}", body); + + fn_def +} + +fn make_param_list(ctx: &AssistContext, module: hir::Module, fun: &Function) -> ast::ParamList { + let self_param = fun.self_param.clone(); + let params = fun.params.iter().map(|param| param.to_param(ctx, module)); + make::param_list(self_param, params) +} + +impl FunType { + fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type { + match self { + FunType::Unit => make::ty_unit(), + FunType::Single(ty) => make_ty(ty, ctx, module), + FunType::Tuple(types) => match types.as_slice() { + [] => { + stdx::never!("tuple type with 0 elements"); + make::ty_unit() + } + [ty] => { + stdx::never!("tuple type with 1 element"); + make_ty(ty, ctx, module) + } + types => { + let types = types.iter().map(|ty| make_ty(ty, ctx, module)); + make::ty_tuple(types) + } + }, + } + } +} + +fn make_ret_ty(ctx: &AssistContext, module: hir::Module, fun: &Function) -> Option { + let fun_ty = fun.return_type(ctx); + let handler = FlowHandler::from_ret_ty(fun, &fun_ty); + let ret_ty = match &handler { + FlowHandler::None => { + if matches!(fun_ty, FunType::Unit) { + return None; + } + fun_ty.make_ty(ctx, module) + } + FlowHandler::Try { kind: TryKind::Option } => { + make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module))) + } + FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => { + let handler_ty = parent_ret_ty + .type_parameters() + .nth(1) + .map(|ty| make_ty(&ty, ctx, module)) + .unwrap_or_else(make::ty_unit); + make::ty_generic( + make::name_ref("Result"), + vec![fun_ty.make_ty(ctx, module), handler_ty], + ) + } + FlowHandler::If { .. } => make::ty("bool"), + FlowHandler::IfOption { action } => { + let handler_ty = action + .expr_ty(ctx) + .map(|ty| make_ty(&ty, ctx, module)) + .unwrap_or_else(make::ty_unit); + make::ty_generic(make::name_ref("Option"), iter::once(handler_ty)) + } + FlowHandler::MatchOption { .. } => { + make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module))) + } + FlowHandler::MatchResult { err } => { + let handler_ty = + err.expr_ty(ctx).map(|ty| make_ty(&ty, ctx, module)).unwrap_or_else(make::ty_unit); + make::ty_generic( + make::name_ref("Result"), + vec![fun_ty.make_ty(ctx, module), handler_ty], + ) + } + }; + Some(make::ret_type(ret_ty)) +} + +fn make_body( + ctx: &AssistContext, + old_indent: IndentLevel, + new_indent: IndentLevel, + fun: &Function, +) -> ast::BlockExpr { + let ret_ty = fun.return_type(ctx); + let handler = FlowHandler::from_ret_ty(fun, &ret_ty); + let block = match &fun.body { + FunctionBody::Expr(expr) => { + let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax()); + let expr = ast::Expr::cast(expr).unwrap(); + let expr = expr.dedent(old_indent).indent(IndentLevel(1)); + + make::block_expr(Vec::new(), Some(expr)) + } + FunctionBody::Span { parent, text_range } => { + let mut elements: Vec<_> = parent + .syntax() + .children() + .filter(|it| text_range.contains_range(it.text_range())) + .map(|it| rewrite_body_segment(ctx, &fun.params, &handler, &it)) + .collect(); + + let mut tail_expr = match elements.pop() { + Some(node) => ast::Expr::cast(node.clone()).or_else(|| { + elements.push(node); + None + }), + None => None, + }; + + if tail_expr.is_none() { + match fun.vars_defined_in_body_and_outlive.as_slice() { + [] => {} + [var] => { + tail_expr = Some(path_expr_from_local(ctx, *var)); + } + vars => { + let exprs = vars.iter().map(|var| path_expr_from_local(ctx, *var)); + let expr = make::expr_tuple(exprs); + tail_expr = Some(expr); + } + } + } + + let elements = elements.into_iter().filter_map(|node| match ast::Stmt::cast(node) { + Some(stmt) => Some(stmt), + None => { + stdx::never!("block contains non-statement"); + None + } + }); + + let body_indent = IndentLevel(1); + let elements = elements.map(|stmt| stmt.dedent(old_indent).indent(body_indent)); + let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent)); + + make::block_expr(elements, tail_expr) + } + }; + + let block = match &handler { + FlowHandler::None => block, + FlowHandler::Try { kind } => { + let block = with_default_tail_expr(block, make::expr_unit()); + map_tail_expr(block, |tail_expr| { + let constructor = match kind { + TryKind::Option => "Some", + TryKind::Result { .. } => "Ok", + }; + let func = make::expr_path(make_path_from_text(constructor)); + let args = make::arg_list(iter::once(tail_expr)); + make::expr_call(func, args) + }) + } + FlowHandler::If { .. } => { + let lit_false = ast::Literal::cast(make::tokens::literal("false").parent()).unwrap(); + with_tail_expr(block, lit_false.into()) + } + FlowHandler::IfOption { .. } => { + let none = make::expr_path(make_path_from_text("None")); + with_tail_expr(block, none) + } + FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| { + let some = make::expr_path(make_path_from_text("Some")); + let args = make::arg_list(iter::once(tail_expr)); + make::expr_call(some, args) + }), + FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| { + let ok = make::expr_path(make_path_from_text("Ok")); + let args = make::arg_list(iter::once(tail_expr)); + make::expr_call(ok, args) + }), + }; + + block.indent(new_indent) +} + +fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr { + let tail_expr = match block.tail_expr() { + Some(tail_expr) => tail_expr, + None => return block, + }; + make::block_expr(block.statements(), Some(f(tail_expr))) +} + +fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr { + match block.tail_expr() { + Some(_) => block, + None => make::block_expr(block.statements(), Some(tail_expr)), + } +} + +fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr { + let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into()); + let stmts = block.statements().chain(stmt_tail); + make::block_expr(stmts, Some(tail_expr)) +} + +fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String { + ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "()".to_string()) +} + +fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type { + let ty_str = format_type(ty, ctx, module); + make::ty(&ty_str) +} + +fn rewrite_body_segment( + ctx: &AssistContext, + params: &[Param], + handler: &FlowHandler, + syntax: &SyntaxNode, +) -> SyntaxNode { + let syntax = fix_param_usages(ctx, params, syntax); + update_external_control_flow(handler, &syntax) +} + +/// change all usages to account for added `&`/`&mut` for some params +fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode { + let mut rewriter = SyntaxRewriter::default(); + for param in params { + if !param.kind().is_ref() { + continue; + } + + let usages = LocalUsages::find(ctx, param.var); + let usages = usages + .iter() + .filter(|reference| syntax.text_range().contains_range(reference.range)) + .filter_map(|reference| path_element_of_reference(syntax, reference)); + for path in usages { + match path.syntax().ancestors().skip(1).find_map(ast::Expr::cast) { + Some(ast::Expr::MethodCallExpr(_)) | Some(ast::Expr::FieldExpr(_)) => { + // do nothing + } + Some(ast::Expr::RefExpr(node)) + if param.kind() == ParamKind::MutRef && node.mut_token().is_some() => + { + rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap()); + } + Some(ast::Expr::RefExpr(node)) + if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() => + { + rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap()); + } + Some(_) | None => { + rewriter.replace_ast(&path, &make::expr_prefix(T![*], path.clone())); + } + }; + } + } + + rewriter.rewrite(syntax) +} + +fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) -> SyntaxNode { + let mut rewriter = SyntaxRewriter::default(); + + let mut nested_loop = None; + let mut nested_scope = None; + for event in syntax.preorder() { + let node = match event { + WalkEvent::Enter(e) => { + match e.kind() { + SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => { + if nested_loop.is_none() { + nested_loop = Some(e.clone()); + } + } + SyntaxKind::FN + | SyntaxKind::CONST + | SyntaxKind::STATIC + | SyntaxKind::IMPL + | SyntaxKind::MODULE => { + if nested_scope.is_none() { + nested_scope = Some(e.clone()); + } + } + _ => {} + } + e + } + WalkEvent::Leave(e) => { + if nested_loop.as_ref() == Some(&e) { + nested_loop = None; + } + if nested_scope.as_ref() == Some(&e) { + nested_scope = None; + } + continue; + } + }; + if nested_scope.is_some() { + continue; + } + let expr = match ast::Expr::cast(node) { + Some(e) => e, + None => continue, + }; + match expr { + ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => { + let expr = return_expr.expr(); + if let Some(replacement) = make_rewritten_flow(handler, expr) { + rewriter.replace_ast(&return_expr.into(), &replacement); + } + } + ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => { + let expr = break_expr.expr(); + if let Some(replacement) = make_rewritten_flow(handler, expr) { + rewriter.replace_ast(&break_expr.into(), &replacement); + } + } + ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => { + if let Some(replacement) = make_rewritten_flow(handler, None) { + rewriter.replace_ast(&continue_expr.into(), &replacement); + } + } + _ => { + // do nothing + } + } + } + + rewriter.rewrite(syntax) +} + +fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option) -> Option { + let value = match handler { + FlowHandler::None | FlowHandler::Try { .. } => return None, + FlowHandler::If { .. } => { + ast::Literal::cast(make::tokens::literal("true").parent()).unwrap().into() + } + FlowHandler::IfOption { .. } => { + let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new())); + let args = make::arg_list(iter::once(expr)); + make::expr_call(make::expr_path(make_path_from_text("Some")), args) + } + FlowHandler::MatchOption { .. } => make::expr_path(make_path_from_text("None")), + FlowHandler::MatchResult { .. } => { + let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new())); + let args = make::arg_list(iter::once(expr)); + make::expr_call(make::expr_path(make_path_from_text("Err")), args) + } + }; + Some(make::expr_return(Some(value))) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn no_args_from_binary_expr() { + check_assist( + extract_function, + r#" +fn foo() { + foo($01 + 1$0); +}"#, + r#" +fn foo() { + foo(fun_name()); +} + +fn $0fun_name() -> i32 { + 1 + 1 +}"#, + ); + } + + #[test] + fn no_args_from_binary_expr_in_module() { + check_assist( + extract_function, + r#" +mod bar { + fn foo() { + foo($01 + 1$0); + } +}"#, + r#" +mod bar { + fn foo() { + foo(fun_name()); + } + + fn $0fun_name() -> i32 { + 1 + 1 + } +}"#, + ); + } + + #[test] + fn no_args_from_binary_expr_indented() { + check_assist( + extract_function, + r#" +fn foo() { + $0{ 1 + 1 }$0; +}"#, + r#" +fn foo() { + fun_name(); +} + +fn $0fun_name() -> i32 { + { 1 + 1 } +}"#, + ); + } + + #[test] + fn no_args_from_stmt_with_last_expr() { + check_assist( + extract_function, + r#" +fn foo() -> i32 { + let k = 1; + $0let m = 1; + m + 1$0 +}"#, + r#" +fn foo() -> i32 { + let k = 1; + fun_name() +} + +fn $0fun_name() -> i32 { + let m = 1; + m + 1 +}"#, + ); + } + + #[test] + fn no_args_from_stmt_unit() { + check_assist( + extract_function, + r#" +fn foo() { + let k = 3; + $0let m = 1; + let n = m + 1;$0 + let g = 5; +}"#, + r#" +fn foo() { + let k = 3; + fun_name(); + let g = 5; +} + +fn $0fun_name() { + let m = 1; + let n = m + 1; +}"#, + ); + } + + #[test] + fn no_args_if() { + check_assist( + extract_function, + r#" +fn foo() { + $0if true { }$0 +}"#, + r#" +fn foo() { + fun_name(); +} + +fn $0fun_name() { + if true { } +}"#, + ); + } + + #[test] + fn no_args_if_else() { + check_assist( + extract_function, + r#" +fn foo() -> i32 { + $0if true { 1 } else { 2 }$0 +}"#, + r#" +fn foo() -> i32 { + fun_name() +} + +fn $0fun_name() -> i32 { + if true { 1 } else { 2 } +}"#, + ); + } + + #[test] + fn no_args_if_let_else() { + check_assist( + extract_function, + r#" +fn foo() -> i32 { + $0if let true = false { 1 } else { 2 }$0 +}"#, + r#" +fn foo() -> i32 { + fun_name() +} + +fn $0fun_name() -> i32 { + if let true = false { 1 } else { 2 } +}"#, + ); + } + + #[test] + fn no_args_match() { + check_assist( + extract_function, + r#" +fn foo() -> i32 { + $0match true { + true => 1, + false => 2, + }$0 +}"#, + r#" +fn foo() -> i32 { + fun_name() +} + +fn $0fun_name() -> i32 { + match true { + true => 1, + false => 2, + } +}"#, + ); + } + + #[test] + fn no_args_while() { + check_assist( + extract_function, + r#" +fn foo() { + $0while true { }$0 +}"#, + r#" +fn foo() { + fun_name(); +} + +fn $0fun_name() { + while true { } +}"#, + ); + } + + #[test] + fn no_args_for() { + check_assist( + extract_function, + r#" +fn foo() { + $0for v in &[0, 1] { }$0 +}"#, + r#" +fn foo() { + fun_name(); +} + +fn $0fun_name() { + for v in &[0, 1] { } +}"#, + ); + } + + #[test] + fn no_args_from_loop_unit() { + check_assist( + extract_function, + r#" +fn foo() { + $0loop { + let m = 1; + }$0 +}"#, + r#" +fn foo() { + fun_name() +} + +fn $0fun_name() -> ! { + loop { + let m = 1; + } +}"#, + ); + } + + #[test] + fn no_args_from_loop_with_return() { + check_assist( + extract_function, + r#" +fn foo() { + let v = $0loop { + let m = 1; + break m; + }$0; +}"#, + r#" +fn foo() { + let v = fun_name(); +} + +fn $0fun_name() -> i32 { + loop { + let m = 1; + break m; + } +}"#, + ); + } + + #[test] + fn no_args_from_match() { + check_assist( + extract_function, + r#" +fn foo() { + let v: i32 = $0match Some(1) { + Some(x) => x, + None => 0, + }$0; +}"#, + r#" +fn foo() { + let v: i32 = fun_name(); +} + +fn $0fun_name() -> i32 { + match Some(1) { + Some(x) => x, + None => 0, + } +}"#, + ); + } + + #[test] + fn argument_form_expr() { + check_assist( + extract_function, + r" +fn foo() -> u32 { + let n = 2; + $0n+2$0 +}", + r" +fn foo() -> u32 { + let n = 2; + fun_name(n) +} + +fn $0fun_name(n: u32) -> u32 { + n+2 +}", + ) + } + + #[test] + fn argument_used_twice_form_expr() { + check_assist( + extract_function, + r" +fn foo() -> u32 { + let n = 2; + $0n+n$0 +}", + r" +fn foo() -> u32 { + let n = 2; + fun_name(n) +} + +fn $0fun_name(n: u32) -> u32 { + n+n +}", + ) + } + + #[test] + fn two_arguments_form_expr() { + check_assist( + extract_function, + r" +fn foo() -> u32 { + let n = 2; + let m = 3; + $0n+n*m$0 +}", + r" +fn foo() -> u32 { + let n = 2; + let m = 3; + fun_name(n, m) +} + +fn $0fun_name(n: u32, m: u32) -> u32 { + n+n*m +}", + ) + } + + #[test] + fn argument_and_locals() { + check_assist( + extract_function, + r" +fn foo() -> u32 { + let n = 2; + $0let m = 1; + n + m$0 +}", + r" +fn foo() -> u32 { + let n = 2; + fun_name(n) +} + +fn $0fun_name(n: u32) -> u32 { + let m = 1; + n + m +}", + ) + } + + #[test] + fn in_comment_is_not_applicable() { + mark::check!(extract_function_in_comment_is_not_applicable); + check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }"); + } + + #[test] + fn part_of_expr_stmt() { + check_assist( + extract_function, + " +fn foo() { + $01$0 + 1; +}", + " +fn foo() { + fun_name() + 1; +} + +fn $0fun_name() -> i32 { + 1 +}", + ); + } + + #[test] + fn function_expr() { + check_assist( + extract_function, + r#" +fn foo() { + $0bar(1 + 1)$0 +}"#, + r#" +fn foo() { + fun_name(); +} + +fn $0fun_name() { + bar(1 + 1) +}"#, + ) + } + + #[test] + fn extract_from_nested() { + check_assist( + extract_function, + r" +fn main() { + let x = true; + let tuple = match x { + true => ($02 + 2$0, true) + _ => (0, false) + }; +}", + r" +fn main() { + let x = true; + let tuple = match x { + true => (fun_name(), true) + _ => (0, false) + }; +} + +fn $0fun_name() -> i32 { + 2 + 2 +}", + ); + } + + #[test] + fn param_from_closure() { + check_assist( + extract_function, + r" +fn main() { + let lambda = |x: u32| $0x * 2$0; +}", + r" +fn main() { + let lambda = |x: u32| fun_name(x); +} + +fn $0fun_name(x: u32) -> u32 { + x * 2 +}", + ); + } + + #[test] + fn extract_return_stmt() { + check_assist( + extract_function, + r" +fn foo() -> u32 { + $0return 2 + 2$0; +}", + r" +fn foo() -> u32 { + return fun_name(); +} + +fn $0fun_name() -> u32 { + 2 + 2 +}", + ); + } + + #[test] + fn does_not_add_extra_whitespace() { + check_assist( + extract_function, + r" +fn foo() -> u32 { + + + $0return 2 + 2$0; +}", + r" +fn foo() -> u32 { + + + return fun_name(); +} + +fn $0fun_name() -> u32 { + 2 + 2 +}", + ); + } + + #[test] + fn break_stmt() { + check_assist( + extract_function, + r" +fn main() { + let result = loop { + $0break 2 + 2$0; + }; +}", + r" +fn main() { + let result = loop { + break fun_name(); + }; +} + +fn $0fun_name() -> i32 { + 2 + 2 +}", + ); + } + + #[test] + fn extract_cast() { + check_assist( + extract_function, + r" +fn main() { + let v = $00f32 as u32$0; +}", + r" +fn main() { + let v = fun_name(); +} + +fn $0fun_name() -> u32 { + 0f32 as u32 +}", + ); + } + + #[test] + fn return_not_applicable() { + check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } "); + } + + #[test] + fn method_to_freestanding() { + check_assist( + extract_function, + r" +struct S; + +impl S { + fn foo(&self) -> i32 { + $01+1$0 + } +}", + r" +struct S; + +impl S { + fn foo(&self) -> i32 { + fun_name() + } +} + +fn $0fun_name() -> i32 { + 1+1 +}", + ); + } + + #[test] + fn method_with_reference() { + check_assist( + extract_function, + r" +struct S { f: i32 }; + +impl S { + fn foo(&self) -> i32 { + $01+self.f$0 + } +}", + r" +struct S { f: i32 }; + +impl S { + fn foo(&self) -> i32 { + self.fun_name() + } + + fn $0fun_name(&self) -> i32 { + 1+self.f + } +}", + ); + } + + #[test] + fn method_with_mut() { + check_assist( + extract_function, + r" +struct S { f: i32 }; + +impl S { + fn foo(&mut self) { + $0self.f += 1;$0 + } +}", + r" +struct S { f: i32 }; + +impl S { + fn foo(&mut self) { + self.fun_name(); + } + + fn $0fun_name(&mut self) { + self.f += 1; + } +}", + ); + } + + #[test] + fn variable_defined_inside_and_used_after_no_ret() { + check_assist( + extract_function, + r" +fn foo() { + let n = 1; + $0let k = n * n;$0 + let m = k + 1; +}", + r" +fn foo() { + let n = 1; + let k = fun_name(n); + let m = k + 1; +} + +fn $0fun_name(n: i32) -> i32 { + let k = n * n; + k +}", + ); + } + + #[test] + fn two_variables_defined_inside_and_used_after_no_ret() { + check_assist( + extract_function, + r" +fn foo() { + let n = 1; + $0let k = n * n; + let m = k + 2;$0 + let h = k + m; +}", + r" +fn foo() { + let n = 1; + let (k, m) = fun_name(n); + let h = k + m; +} + +fn $0fun_name(n: i32) -> (i32, i32) { + let k = n * n; + let m = k + 2; + (k, m) +}", + ); + } + + #[test] + fn nontrivial_patterns_define_variables() { + check_assist( + extract_function, + r" +struct Counter(i32); +fn foo() { + $0let Counter(n) = Counter(0);$0 + let m = n; +}", + r" +struct Counter(i32); +fn foo() { + let n = fun_name(); + let m = n; +} + +fn $0fun_name() -> i32 { + let Counter(n) = Counter(0); + n +}", + ); + } + + #[test] + fn struct_with_two_fields_pattern_define_variables() { + check_assist( + extract_function, + r" +struct Counter { n: i32, m: i32 }; +fn foo() { + $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0 + let h = n + k; +}", + r" +struct Counter { n: i32, m: i32 }; +fn foo() { + let (n, k) = fun_name(); + let h = n + k; +} + +fn $0fun_name() -> (i32, i32) { + let Counter { n, m: k } = Counter { n: 1, m: 2 }; + (n, k) +}", + ); + } + + #[test] + fn mut_var_from_outer_scope() { + check_assist( + extract_function, + r" +fn foo() { + let mut n = 1; + $0n += 1;$0 + let m = n + 1; +}", + r" +fn foo() { + let mut n = 1; + fun_name(&mut n); + let m = n + 1; +} + +fn $0fun_name(n: &mut i32) { + *n += 1; +}", + ); + } + + #[test] + fn mut_field_from_outer_scope() { + check_assist( + extract_function, + r" +struct C { n: i32 } +fn foo() { + let mut c = C { n: 0 }; + $0c.n += 1;$0 + let m = c.n + 1; +}", + r" +struct C { n: i32 } +fn foo() { + let mut c = C { n: 0 }; + fun_name(&mut c); + let m = c.n + 1; +} + +fn $0fun_name(c: &mut C) { + c.n += 1; +}", + ); + } + + #[test] + fn mut_nested_field_from_outer_scope() { + check_assist( + extract_function, + r" +struct P { n: i32} +struct C { p: P } +fn foo() { + let mut c = C { p: P { n: 0 } }; + let mut v = C { p: P { n: 0 } }; + let u = C { p: P { n: 0 } }; + $0c.p.n += u.p.n; + let r = &mut v.p.n;$0 + let m = c.p.n + v.p.n + u.p.n; +}", + r" +struct P { n: i32} +struct C { p: P } +fn foo() { + let mut c = C { p: P { n: 0 } }; + let mut v = C { p: P { n: 0 } }; + let u = C { p: P { n: 0 } }; + fun_name(&mut c, &u, &mut v); + let m = c.p.n + v.p.n + u.p.n; +} + +fn $0fun_name(c: &mut C, u: &C, v: &mut C) { + c.p.n += u.p.n; + let r = &mut v.p.n; +}", + ); + } + + #[test] + fn mut_param_many_usages_stmt() { + check_assist( + extract_function, + r" +fn bar(k: i32) {} +trait I: Copy { + fn succ(&self) -> Self; + fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v } +} +impl I for i32 { + fn succ(&self) -> Self { *self + 1 } +} +fn foo() { + let mut n = 1; + $0n += n; + bar(n); + bar(n+1); + bar(n*n); + bar(&n); + n.inc(); + let v = &mut n; + *v = v.succ(); + n.succ();$0 + let m = n + 1; +}", + r" +fn bar(k: i32) {} +trait I: Copy { + fn succ(&self) -> Self; + fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v } +} +impl I for i32 { + fn succ(&self) -> Self { *self + 1 } +} +fn foo() { + let mut n = 1; + fun_name(&mut n); + let m = n + 1; +} + +fn $0fun_name(n: &mut i32) { + *n += *n; + bar(*n); + bar(*n+1); + bar(*n**n); + bar(&*n); + n.inc(); + let v = n; + *v = v.succ(); + n.succ(); +}", + ); + } + + #[test] + fn mut_param_many_usages_expr() { + check_assist( + extract_function, + r" +fn bar(k: i32) {} +trait I: Copy { + fn succ(&self) -> Self; + fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v } +} +impl I for i32 { + fn succ(&self) -> Self { *self + 1 } +} +fn foo() { + let mut n = 1; + $0{ + n += n; + bar(n); + bar(n+1); + bar(n*n); + bar(&n); + n.inc(); + let v = &mut n; + *v = v.succ(); + n.succ(); + }$0 + let m = n + 1; +}", + r" +fn bar(k: i32) {} +trait I: Copy { + fn succ(&self) -> Self; + fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v } +} +impl I for i32 { + fn succ(&self) -> Self { *self + 1 } +} +fn foo() { + let mut n = 1; + fun_name(&mut n); + let m = n + 1; +} + +fn $0fun_name(n: &mut i32) { + { + *n += *n; + bar(*n); + bar(*n+1); + bar(*n**n); + bar(&*n); + n.inc(); + let v = n; + *v = v.succ(); + n.succ(); + } +}", + ); + } + + #[test] + fn mut_param_by_value() { + check_assist( + extract_function, + r" +fn foo() { + let mut n = 1; + $0n += 1;$0 +}", + r" +fn foo() { + let mut n = 1; + fun_name(n); +} + +fn $0fun_name(mut n: i32) { + n += 1; +}", + ); + } + + #[test] + fn mut_param_because_of_mut_ref() { + check_assist( + extract_function, + r" +fn foo() { + let mut n = 1; + $0let v = &mut n; + *v += 1;$0 + let k = n; +}", + r" +fn foo() { + let mut n = 1; + fun_name(&mut n); + let k = n; +} + +fn $0fun_name(n: &mut i32) { + let v = n; + *v += 1; +}", + ); + } + + #[test] + fn mut_param_by_value_because_of_mut_ref() { + check_assist( + extract_function, + r" +fn foo() { + let mut n = 1; + $0let v = &mut n; + *v += 1;$0 +}", + r" +fn foo() { + let mut n = 1; + fun_name(n); +} + +fn $0fun_name(mut n: i32) { + let v = &mut n; + *v += 1; +}", + ); + } + + #[test] + fn mut_method_call() { + check_assist( + extract_function, + r" +trait I { + fn inc(&mut self); +} +impl I for i32 { + fn inc(&mut self) { *self += 1 } +} +fn foo() { + let mut n = 1; + $0n.inc();$0 +}", + r" +trait I { + fn inc(&mut self); +} +impl I for i32 { + fn inc(&mut self) { *self += 1 } +} +fn foo() { + let mut n = 1; + fun_name(n); +} + +fn $0fun_name(mut n: i32) { + n.inc(); +}", + ); + } + + #[test] + fn shared_method_call() { + check_assist( + extract_function, + r" +trait I { + fn succ(&self); +} +impl I for i32 { + fn succ(&self) { *self + 1 } +} +fn foo() { + let mut n = 1; + $0n.succ();$0 +}", + r" +trait I { + fn succ(&self); +} +impl I for i32 { + fn succ(&self) { *self + 1 } +} +fn foo() { + let mut n = 1; + fun_name(n); +} + +fn $0fun_name(n: i32) { + n.succ(); +}", + ); + } + + #[test] + fn mut_method_call_with_other_receiver() { + check_assist( + extract_function, + r" +trait I { + fn inc(&mut self, n: i32); +} +impl I for i32 { + fn inc(&mut self, n: i32) { *self += n } +} +fn foo() { + let mut n = 1; + $0let mut m = 2; + m.inc(n);$0 +}", + r" +trait I { + fn inc(&mut self, n: i32); +} +impl I for i32 { + fn inc(&mut self, n: i32) { *self += n } +} +fn foo() { + let mut n = 1; + fun_name(n); +} + +fn $0fun_name(n: i32) { + let mut m = 2; + m.inc(n); +}", + ); + } + + #[test] + fn non_copy_without_usages_after() { + check_assist( + extract_function, + r" +struct Counter(i32); +fn foo() { + let c = Counter(0); + $0let n = c.0;$0 +}", + r" +struct Counter(i32); +fn foo() { + let c = Counter(0); + fun_name(c); +} + +fn $0fun_name(c: Counter) { + let n = c.0; +}", + ); + } + + #[test] + fn non_copy_used_after() { + check_assist( + extract_function, + r" +struct Counter(i32); +fn foo() { + let c = Counter(0); + $0let n = c.0;$0 + let m = c.0; +}", + r" +struct Counter(i32); +fn foo() { + let c = Counter(0); + fun_name(&c); + let m = c.0; +} + +fn $0fun_name(c: &Counter) { + let n = c.0; +}", + ); + } + + #[test] + fn copy_used_after() { + check_assist( + extract_function, + r##" +#[lang = "copy"] +pub trait Copy {} +impl Copy for i32 {} +fn foo() { + let n = 0; + $0let m = n;$0 + let k = n; +}"##, + r##" +#[lang = "copy"] +pub trait Copy {} +impl Copy for i32 {} +fn foo() { + let n = 0; + fun_name(n); + let k = n; +} + +fn $0fun_name(n: i32) { + let m = n; +}"##, + ) + } + + #[test] + fn copy_custom_used_after() { + check_assist( + extract_function, + r##" +#[lang = "copy"] +pub trait Copy {} +struct Counter(i32); +impl Copy for Counter {} +fn foo() { + let c = Counter(0); + $0let n = c.0;$0 + let m = c.0; +}"##, + r##" +#[lang = "copy"] +pub trait Copy {} +struct Counter(i32); +impl Copy for Counter {} +fn foo() { + let c = Counter(0); + fun_name(c); + let m = c.0; +} + +fn $0fun_name(c: Counter) { + let n = c.0; +}"##, + ); + } + + #[test] + fn indented_stmts() { + check_assist( + extract_function, + r" +fn foo() { + if true { + loop { + $0let n = 1; + let m = 2;$0 + } + } +}", + r" +fn foo() { + if true { + loop { + fun_name(); + } + } +} + +fn $0fun_name() { + let n = 1; + let m = 2; +}", + ); + } + + #[test] + fn indented_stmts_inside_mod() { + check_assist( + extract_function, + r" +mod bar { + fn foo() { + if true { + loop { + $0let n = 1; + let m = 2;$0 + } + } + } +}", + r" +mod bar { + fn foo() { + if true { + loop { + fun_name(); + } + } + } + + fn $0fun_name() { + let n = 1; + let m = 2; + } +}", + ); + } + + #[test] + fn break_loop() { + check_assist( + extract_function, + r##" +enum Option { + #[lang = "None"] None, + #[lang = "Some"] Some(T), +} +use Option::*; +fn foo() { + loop { + let n = 1; + $0let m = n + 1; + break; + let k = 2;$0 + let h = 1 + k; + } +}"##, + r##" +enum Option { + #[lang = "None"] None, + #[lang = "Some"] Some(T), +} +use Option::*; +fn foo() { + loop { + let n = 1; + let k = match fun_name(n) { + Some(value) => value, + None => break, + }; + let h = 1 + k; + } +} + +fn $0fun_name(n: i32) -> Option { + let m = n + 1; + return None; + let k = 2; + Some(k) +}"##, + ); + } + + #[test] + fn return_to_parent() { + check_assist( + extract_function, + r##" +#[lang = "copy"] +pub trait Copy {} +impl Copy for i32 {} +enum Result { + #[lang = "Ok"] Ok(T), + #[lang = "Err"] Err(E), +} +use Result::*; +fn foo() -> i64 { + let n = 1; + $0let m = n + 1; + return 1; + let k = 2;$0 + (n + k) as i64 +}"##, + r##" +#[lang = "copy"] +pub trait Copy {} +impl Copy for i32 {} +enum Result { + #[lang = "Ok"] Ok(T), + #[lang = "Err"] Err(E), +} +use Result::*; +fn foo() -> i64 { + let n = 1; + let k = match fun_name(n) { + Ok(value) => value, + Err(value) => return value, + }; + (n + k) as i64 +} + +fn $0fun_name(n: i32) -> Result { + let m = n + 1; + return Err(1); + let k = 2; + Ok(k) +}"##, + ); + } + + #[test] + fn break_and_continue() { + mark::check!(external_control_flow_break_and_continue); + check_assist_not_applicable( + extract_function, + r##" +fn foo() { + loop { + let n = 1; + $0let m = n + 1; + break; + let k = 2; + continue; + let k = k + 1;$0 + let r = n + k; + } +}"##, + ); + } + + #[test] + fn return_and_break() { + mark::check!(external_control_flow_return_and_bc); + check_assist_not_applicable( + extract_function, + r##" +fn foo() { + loop { + let n = 1; + $0let m = n + 1; + break; + let k = 2; + return; + let k = k + 1;$0 + let r = n + k; + } +}"##, + ); + } + + #[test] + fn break_loop_with_if() { + check_assist( + extract_function, + r##" +fn foo() { + loop { + let mut n = 1; + $0let m = n + 1; + break; + n += m;$0 + let h = 1 + n; + } +}"##, + r##" +fn foo() { + loop { + let mut n = 1; + if fun_name(&mut n) { + break; + } + let h = 1 + n; + } +} + +fn $0fun_name(n: &mut i32) -> bool { + let m = *n + 1; + return true; + *n += m; + false +}"##, + ); + } + + #[test] + fn break_loop_nested() { + check_assist( + extract_function, + r##" +fn foo() { + loop { + let mut n = 1; + $0let m = n + 1; + if m == 42 { + break; + }$0 + let h = 1; + } +}"##, + r##" +fn foo() { + loop { + let mut n = 1; + if fun_name(n) { + break; + } + let h = 1; + } +} + +fn $0fun_name(n: i32) -> bool { + let m = n + 1; + if m == 42 { + return true; + } + false +}"##, + ); + } + + #[test] + fn return_from_nested_loop() { + check_assist( + extract_function, + r##" +fn foo() { + loop { + let n = 1; + $0 + let k = 1; + loop { + return; + } + let m = k + 1;$0 + let h = 1 + m; + } +}"##, + r##" +fn foo() { + loop { + let n = 1; + let m = match fun_name() { + Some(value) => value, + None => return, + }; + let h = 1 + m; + } +} + +fn $0fun_name() -> Option { + let k = 1; + loop { + return None; + } + let m = k + 1; + Some(m) +}"##, + ); + } + + #[test] + fn break_from_nested_loop() { + check_assist( + extract_function, + r##" +fn foo() { + loop { + let n = 1; + $0let k = 1; + loop { + break; + } + let m = k + 1;$0 + let h = 1 + m; + } +}"##, + r##" +fn foo() { + loop { + let n = 1; + let m = fun_name(); + let h = 1 + m; + } +} + +fn $0fun_name() -> i32 { + let k = 1; + loop { + break; + } + let m = k + 1; + m +}"##, + ); + } + + #[test] + fn break_from_nested_and_outer_loops() { + check_assist( + extract_function, + r##" +fn foo() { + loop { + let n = 1; + $0let k = 1; + loop { + break; + } + if k == 42 { + break; + } + let m = k + 1;$0 + let h = 1 + m; + } +}"##, + r##" +fn foo() { + loop { + let n = 1; + let m = match fun_name() { + Some(value) => value, + None => break, + }; + let h = 1 + m; + } +} + +fn $0fun_name() -> Option { + let k = 1; + loop { + break; + } + if k == 42 { + return None; + } + let m = k + 1; + Some(m) +}"##, + ); + } + + #[test] + fn return_from_nested_fn() { + check_assist( + extract_function, + r##" +fn foo() { + loop { + let n = 1; + $0let k = 1; + fn test() { + return; + } + let m = k + 1;$0 + let h = 1 + m; + } +}"##, + r##" +fn foo() { + loop { + let n = 1; + let m = fun_name(); + let h = 1 + m; + } +} + +fn $0fun_name() -> i32 { + let k = 1; + fn test() { + return; + } + let m = k + 1; + m +}"##, + ); + } + + #[test] + fn break_with_value() { + check_assist( + extract_function, + r##" +fn foo() -> i32 { + loop { + let n = 1; + $0let k = 1; + if k == 42 { + break 3; + } + let m = k + 1;$0 + let h = 1; + } +}"##, + r##" +fn foo() -> i32 { + loop { + let n = 1; + if let Some(value) = fun_name() { + break value; + } + let h = 1; + } +} + +fn $0fun_name() -> Option { + let k = 1; + if k == 42 { + return Some(3); + } + let m = k + 1; + None +}"##, + ); + } + + #[test] + fn break_with_value_and_return() { + check_assist( + extract_function, + r##" +fn foo() -> i64 { + loop { + let n = 1; + $0 + let k = 1; + if k == 42 { + break 3; + } + let m = k + 1;$0 + let h = 1 + m; + } +}"##, + r##" +fn foo() -> i64 { + loop { + let n = 1; + let m = match fun_name() { + Ok(value) => value, + Err(value) => break value, + }; + let h = 1 + m; + } +} + +fn $0fun_name() -> Result { + let k = 1; + if k == 42 { + return Err(3); + } + let m = k + 1; + Ok(m) +}"##, + ); + } + + #[test] + fn try_option() { + check_assist( + extract_function, + r##" +enum Option { None, Some(T), } +use Option::*; +fn bar() -> Option { None } +fn foo() -> Option<()> { + let n = bar()?; + $0let k = foo()?; + let m = k + 1;$0 + let h = 1 + m; + Some(()) +}"##, + r##" +enum Option { None, Some(T), } +use Option::*; +fn bar() -> Option { None } +fn foo() -> Option<()> { + let n = bar()?; + let m = fun_name()?; + let h = 1 + m; + Some(()) +} + +fn $0fun_name() -> Option { + let k = foo()?; + let m = k + 1; + Some(m) +}"##, + ); + } + + #[test] + fn try_option_unit() { + check_assist( + extract_function, + r##" +enum Option { None, Some(T), } +use Option::*; +fn foo() -> Option<()> { + let n = 1; + $0let k = foo()?; + let m = k + 1;$0 + let h = 1 + n; + Some(()) +}"##, + r##" +enum Option { None, Some(T), } +use Option::*; +fn foo() -> Option<()> { + let n = 1; + fun_name()?; + let h = 1 + n; + Some(()) +} + +fn $0fun_name() -> Option<()> { + let k = foo()?; + let m = k + 1; + Some(()) +}"##, + ); + } + + #[test] + fn try_result() { + check_assist( + extract_function, + r##" +enum Result { Ok(T), Err(E), } +use Result::*; +fn foo() -> Result<(), i64> { + let n = 1; + $0let k = foo()?; + let m = k + 1;$0 + let h = 1 + m; + Ok(()) +}"##, + r##" +enum Result { Ok(T), Err(E), } +use Result::*; +fn foo() -> Result<(), i64> { + let n = 1; + let m = fun_name()?; + let h = 1 + m; + Ok(()) +} + +fn $0fun_name() -> Result { + let k = foo()?; + let m = k + 1; + Ok(m) +}"##, + ); + } + + #[test] + fn try_option_with_return() { + check_assist( + extract_function, + r##" +enum Option { None, Some(T) } +use Option::*; +fn foo() -> Option<()> { + let n = 1; + $0let k = foo()?; + if k == 42 { + return None; + } + let m = k + 1;$0 + let h = 1 + m; + Some(()) +}"##, + r##" +enum Option { None, Some(T) } +use Option::*; +fn foo() -> Option<()> { + let n = 1; + let m = fun_name()?; + let h = 1 + m; + Some(()) +} + +fn $0fun_name() -> Option { + let k = foo()?; + if k == 42 { + return None; + } + let m = k + 1; + Some(m) +}"##, + ); + } + + #[test] + fn try_result_with_return() { + check_assist( + extract_function, + r##" +enum Result { Ok(T), Err(E), } +use Result::*; +fn foo() -> Result<(), i64> { + let n = 1; + $0let k = foo()?; + if k == 42 { + return Err(1); + } + let m = k + 1;$0 + let h = 1 + m; + Ok(()) +}"##, + r##" +enum Result { Ok(T), Err(E), } +use Result::*; +fn foo() -> Result<(), i64> { + let n = 1; + let m = fun_name()?; + let h = 1 + m; + Ok(()) +} + +fn $0fun_name() -> Result { + let k = foo()?; + if k == 42 { + return Err(1); + } + let m = k + 1; + Ok(m) +}"##, + ); + } + + #[test] + fn try_and_break() { + mark::check!(external_control_flow_try_and_bc); + check_assist_not_applicable( + extract_function, + r##" +enum Option { None, Some(T) } +use Option::*; +fn foo() -> Option<()> { + loop { + let n = Some(1); + $0let m = n? + 1; + break; + let k = 2; + let k = k + 1;$0 + let r = n + k; + } + Some(()) +}"##, + ); + } + + #[test] + fn try_and_return_ok() { + mark::check!(external_control_flow_try_and_return_non_err); + check_assist_not_applicable( + extract_function, + r##" +enum Result { Ok(T), Err(E), } +use Result::*; +fn foo() -> Result<(), i64> { + let n = 1; + $0let k = foo()?; + if k == 42 { + return Ok(1); + } + let m = k + 1;$0 + let h = 1 + m; + Ok(()) +}"##, + ); + } +} diff --git a/crates/ide_assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ide_assists/src/handlers/extract_struct_from_enum_variant.rs new file mode 100644 index 000000000..5c7678b53 --- /dev/null +++ b/crates/ide_assists/src/handlers/extract_struct_from_enum_variant.rs @@ -0,0 +1,520 @@ +use std::iter; + +use either::Either; +use hir::{AsName, Module, ModuleDef, Name, Variant}; +use ide_db::{ + defs::Definition, + helpers::{ + insert_use::{insert_use, ImportScope}, + mod_path_to_ast, + }, + search::FileReference, + RootDatabase, +}; +use rustc_hash::FxHashSet; +use syntax::{ + algo::{find_node_at_offset, SyntaxRewriter}, + ast::{self, edit::IndentLevel, make, AstNode, NameOwner, VisibilityOwner}, + SourceFile, SyntaxElement, SyntaxNode, T, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: extract_struct_from_enum_variant +// +// Extracts a struct from enum variant. +// +// ``` +// enum A { $0One(u32, u32) } +// ``` +// -> +// ``` +// struct One(pub u32, pub u32); +// +// enum A { One(One) } +// ``` +pub(crate) fn extract_struct_from_enum_variant( + acc: &mut Assists, + ctx: &AssistContext, +) -> Option<()> { + let variant = ctx.find_node_at_offset::()?; + let field_list = extract_field_list_if_applicable(&variant)?; + + let variant_name = variant.name()?; + let variant_hir = ctx.sema.to_def(&variant)?; + if existing_definition(ctx.db(), &variant_name, &variant_hir) { + return None; + } + + let enum_ast = variant.parent_enum(); + let enum_hir = ctx.sema.to_def(&enum_ast)?; + let target = variant.syntax().text_range(); + acc.add( + AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite), + "Extract struct from enum variant", + target, + |builder| { + let variant_hir_name = variant_hir.name(ctx.db()); + let enum_module_def = ModuleDef::from(enum_hir); + let usages = + Definition::ModuleDef(ModuleDef::Variant(variant_hir)).usages(&ctx.sema).all(); + + let mut visited_modules_set = FxHashSet::default(); + let current_module = enum_hir.module(ctx.db()); + visited_modules_set.insert(current_module); + let mut def_rewriter = None; + for (file_id, references) in usages { + let mut rewriter = SyntaxRewriter::default(); + let source_file = ctx.sema.parse(file_id); + for reference in references { + update_reference( + ctx, + &mut rewriter, + reference, + &source_file, + &enum_module_def, + &variant_hir_name, + &mut visited_modules_set, + ); + } + if file_id == ctx.frange.file_id { + def_rewriter = Some(rewriter); + continue; + } + builder.edit_file(file_id); + builder.rewrite(rewriter); + } + let mut rewriter = def_rewriter.unwrap_or_default(); + update_variant(&mut rewriter, &variant); + extract_struct_def( + &mut rewriter, + &enum_ast, + variant_name.clone(), + &field_list, + &variant.parent_enum().syntax().clone().into(), + enum_ast.visibility(), + ); + builder.edit_file(ctx.frange.file_id); + builder.rewrite(rewriter); + }, + ) +} + +fn extract_field_list_if_applicable( + variant: &ast::Variant, +) -> Option> { + match variant.kind() { + ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => { + Some(Either::Left(field_list)) + } + ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => { + Some(Either::Right(field_list)) + } + _ => None, + } +} + +fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &Variant) -> bool { + variant + .parent_enum(db) + .module(db) + .scope(db, None) + .into_iter() + .filter(|(_, def)| match def { + // only check type-namespace + hir::ScopeDef::ModuleDef(def) => matches!( + def, + ModuleDef::Module(_) + | ModuleDef::Adt(_) + | ModuleDef::Variant(_) + | ModuleDef::Trait(_) + | ModuleDef::TypeAlias(_) + | ModuleDef::BuiltinType(_) + ), + _ => false, + }) + .any(|(name, _)| name == variant_name.as_name()) +} + +fn insert_import( + ctx: &AssistContext, + rewriter: &mut SyntaxRewriter, + scope_node: &SyntaxNode, + module: &Module, + enum_module_def: &ModuleDef, + variant_hir_name: &Name, +) -> Option<()> { + let db = ctx.db(); + let mod_path = module.find_use_path_prefixed( + db, + enum_module_def.clone(), + ctx.config.insert_use.prefix_kind, + ); + if let Some(mut mod_path) = mod_path { + mod_path.pop_segment(); + mod_path.push_segment(variant_hir_name.clone()); + let scope = ImportScope::find_insert_use_container(scope_node, &ctx.sema)?; + *rewriter += insert_use(&scope, mod_path_to_ast(&mod_path), ctx.config.insert_use.merge); + } + Some(()) +} + +fn extract_struct_def( + rewriter: &mut SyntaxRewriter, + enum_: &ast::Enum, + variant_name: ast::Name, + field_list: &Either, + start_offset: &SyntaxElement, + visibility: Option, +) -> Option<()> { + let pub_vis = Some(make::visibility_pub()); + let field_list = match field_list { + Either::Left(field_list) => { + make::record_field_list(field_list.fields().flat_map(|field| { + Some(make::record_field(pub_vis.clone(), field.name()?, field.ty()?)) + })) + .into() + } + Either::Right(field_list) => make::tuple_field_list( + field_list + .fields() + .flat_map(|field| Some(make::tuple_field(pub_vis.clone(), field.ty()?))), + ) + .into(), + }; + + rewriter.insert_before( + start_offset, + make::struct_(visibility, variant_name, None, field_list).syntax(), + ); + rewriter.insert_before(start_offset, &make::tokens::blank_line()); + + if let indent_level @ 1..=usize::MAX = IndentLevel::from_node(enum_.syntax()).0 as usize { + rewriter + .insert_before(start_offset, &make::tokens::whitespace(&" ".repeat(4 * indent_level))); + } + Some(()) +} + +fn update_variant(rewriter: &mut SyntaxRewriter, variant: &ast::Variant) -> Option<()> { + let name = variant.name()?; + let tuple_field = make::tuple_field(None, make::ty(name.text())); + let replacement = make::variant( + name, + Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))), + ); + rewriter.replace(variant.syntax(), replacement.syntax()); + Some(()) +} + +fn update_reference( + ctx: &AssistContext, + rewriter: &mut SyntaxRewriter, + reference: FileReference, + source_file: &SourceFile, + enum_module_def: &ModuleDef, + variant_hir_name: &Name, + visited_modules_set: &mut FxHashSet, +) -> Option<()> { + let offset = reference.range.start(); + let (segment, expr) = if let Some(path_expr) = + find_node_at_offset::(source_file.syntax(), offset) + { + // tuple variant + (path_expr.path()?.segment()?, path_expr.syntax().parent()?) + } else if let Some(record_expr) = + find_node_at_offset::(source_file.syntax(), offset) + { + // record variant + (record_expr.path()?.segment()?, record_expr.syntax().clone()) + } else { + return None; + }; + + let module = ctx.sema.scope(&expr).module()?; + if !visited_modules_set.contains(&module) { + if insert_import(ctx, rewriter, &expr, &module, enum_module_def, variant_hir_name).is_some() + { + visited_modules_set.insert(module); + } + } + rewriter.insert_after(segment.syntax(), &make::token(T!['('])); + rewriter.insert_after(segment.syntax(), segment.syntax()); + rewriter.insert_after(&expr, &make::token(T![')'])); + Some(()) +} + +#[cfg(test)] +mod tests { + use ide_db::helpers::FamousDefs; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn test_extract_struct_several_fields_tuple() { + check_assist( + extract_struct_from_enum_variant, + "enum A { $0One(u32, u32) }", + r#"struct One(pub u32, pub u32); + +enum A { One(One) }"#, + ); + } + + #[test] + fn test_extract_struct_several_fields_named() { + check_assist( + extract_struct_from_enum_variant, + "enum A { $0One { foo: u32, bar: u32 } }", + r#"struct One{ pub foo: u32, pub bar: u32 } + +enum A { One(One) }"#, + ); + } + + #[test] + fn test_extract_struct_one_field_named() { + check_assist( + extract_struct_from_enum_variant, + "enum A { $0One { foo: u32 } }", + r#"struct One{ pub foo: u32 } + +enum A { One(One) }"#, + ); + } + + #[test] + fn test_extract_enum_variant_name_value_namespace() { + check_assist( + extract_struct_from_enum_variant, + r#"const One: () = (); +enum A { $0One(u32, u32) }"#, + r#"const One: () = (); +struct One(pub u32, pub u32); + +enum A { One(One) }"#, + ); + } + + #[test] + fn test_extract_struct_pub_visibility() { + check_assist( + extract_struct_from_enum_variant, + "pub enum A { $0One(u32, u32) }", + r#"pub struct One(pub u32, pub u32); + +pub enum A { One(One) }"#, + ); + } + + #[test] + fn test_extract_struct_with_complex_imports() { + check_assist( + extract_struct_from_enum_variant, + r#"mod my_mod { + fn another_fn() { + let m = my_other_mod::MyEnum::MyField(1, 1); + } + + pub mod my_other_mod { + fn another_fn() { + let m = MyEnum::MyField(1, 1); + } + + pub enum MyEnum { + $0MyField(u8, u8), + } + } +} + +fn another_fn() { + let m = my_mod::my_other_mod::MyEnum::MyField(1, 1); +}"#, + r#"use my_mod::my_other_mod::MyField; + +mod my_mod { + use self::my_other_mod::MyField; + + fn another_fn() { + let m = my_other_mod::MyEnum::MyField(MyField(1, 1)); + } + + pub mod my_other_mod { + fn another_fn() { + let m = MyEnum::MyField(MyField(1, 1)); + } + + pub struct MyField(pub u8, pub u8); + + pub enum MyEnum { + MyField(MyField), + } + } +} + +fn another_fn() { + let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1)); +}"#, + ); + } + + #[test] + fn extract_record_fix_references() { + check_assist( + extract_struct_from_enum_variant, + r#" +enum E { + $0V { i: i32, j: i32 } +} + +fn f() { + let e = E::V { i: 9, j: 2 }; +} +"#, + r#" +struct V{ pub i: i32, pub j: i32 } + +enum E { + V(V) +} + +fn f() { + let e = E::V(V { i: 9, j: 2 }); +} +"#, + ) + } + + #[test] + fn test_several_files() { + check_assist( + extract_struct_from_enum_variant, + r#" +//- /main.rs +enum E { + $0V(i32, i32) +} +mod foo; + +//- /foo.rs +use crate::E; +fn f() { + let e = E::V(9, 2); +} +"#, + r#" +//- /main.rs +struct V(pub i32, pub i32); + +enum E { + V(V) +} +mod foo; + +//- /foo.rs +use crate::{E, V}; +fn f() { + let e = E::V(V(9, 2)); +} +"#, + ) + } + + #[test] + fn test_several_files_record() { + check_assist( + extract_struct_from_enum_variant, + r#" +//- /main.rs +enum E { + $0V { i: i32, j: i32 } +} +mod foo; + +//- /foo.rs +use crate::E; +fn f() { + let e = E::V { i: 9, j: 2 }; +} +"#, + r#" +//- /main.rs +struct V{ pub i: i32, pub j: i32 } + +enum E { + V(V) +} +mod foo; + +//- /foo.rs +use crate::{E, V}; +fn f() { + let e = E::V(V { i: 9, j: 2 }); +} +"#, + ) + } + + #[test] + fn test_extract_struct_record_nested_call_exp() { + check_assist( + extract_struct_from_enum_variant, + r#" +enum A { $0One { a: u32, b: u32 } } + +struct B(A); + +fn foo() { + let _ = B(A::One { a: 1, b: 2 }); +} +"#, + r#" +struct One{ pub a: u32, pub b: u32 } + +enum A { One(One) } + +struct B(A); + +fn foo() { + let _ = B(A::One(One { a: 1, b: 2 })); +} +"#, + ); + } + + fn check_not_applicable(ra_fixture: &str) { + let fixture = + format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE); + check_assist_not_applicable(extract_struct_from_enum_variant, &fixture) + } + + #[test] + fn test_extract_enum_not_applicable_for_element_with_no_fields() { + check_not_applicable("enum A { $0One }"); + } + + #[test] + fn test_extract_enum_not_applicable_if_struct_exists() { + check_not_applicable( + r#"struct One; + enum A { $0One(u8, u32) }"#, + ); + } + + #[test] + fn test_extract_not_applicable_one_field() { + check_not_applicable(r"enum A { $0One(u32) }"); + } + + #[test] + fn test_extract_not_applicable_no_field_tuple() { + check_not_applicable(r"enum A { $0None() }"); + } + + #[test] + fn test_extract_not_applicable_no_field_named() { + check_not_applicable(r"enum A { $0None {} }"); + } +} diff --git a/crates/ide_assists/src/handlers/extract_variable.rs b/crates/ide_assists/src/handlers/extract_variable.rs new file mode 100644 index 000000000..98f3dc6ca --- /dev/null +++ b/crates/ide_assists/src/handlers/extract_variable.rs @@ -0,0 +1,588 @@ +use stdx::format_to; +use syntax::{ + ast::{self, AstNode}, + SyntaxKind::{ + BLOCK_EXPR, BREAK_EXPR, CLOSURE_EXPR, COMMENT, LOOP_EXPR, MATCH_ARM, PATH_EXPR, RETURN_EXPR, + }, + SyntaxNode, +}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: extract_variable +// +// Extracts subexpression into a variable. +// +// ``` +// fn main() { +// $0(1 + 2)$0 * 4; +// } +// ``` +// -> +// ``` +// fn main() { +// let $0var_name = (1 + 2); +// var_name * 4; +// } +// ``` +pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + if ctx.frange.range.is_empty() { + return None; + } + let node = ctx.covering_element(); + if node.kind() == COMMENT { + mark::hit!(extract_var_in_comment_is_not_applicable); + return None; + } + let to_extract = node.ancestors().find_map(valid_target_expr)?; + let anchor = Anchor::from(&to_extract)?; + let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone(); + let target = to_extract.syntax().text_range(); + acc.add( + AssistId("extract_variable", AssistKind::RefactorExtract), + "Extract into variable", + target, + move |edit| { + let field_shorthand = + match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) { + Some(field) => field.name_ref(), + None => None, + }; + + let mut buf = String::new(); + + let var_name = match &field_shorthand { + Some(it) => it.to_string(), + None => "var_name".to_string(), + }; + let expr_range = match &field_shorthand { + Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()), + None => to_extract.syntax().text_range(), + }; + + if let Anchor::WrapInBlock(_) = anchor { + format_to!(buf, "{{ let {} = ", var_name); + } else { + format_to!(buf, "let {} = ", var_name); + }; + format_to!(buf, "{}", to_extract.syntax()); + + if let Anchor::Replace(stmt) = anchor { + mark::hit!(test_extract_var_expr_stmt); + if stmt.semicolon_token().is_none() { + buf.push_str(";"); + } + match ctx.config.snippet_cap { + Some(cap) => { + let snip = buf + .replace(&format!("let {}", var_name), &format!("let $0{}", var_name)); + edit.replace_snippet(cap, expr_range, snip) + } + None => edit.replace(expr_range, buf), + } + return; + } + + buf.push_str(";"); + + // We want to maintain the indent level, + // but we do not want to duplicate possible + // extra newlines in the indent block + let text = indent.text(); + if text.starts_with('\n') { + buf.push('\n'); + buf.push_str(text.trim_start_matches('\n')); + } else { + buf.push_str(text); + } + + edit.replace(expr_range, var_name.clone()); + let offset = anchor.syntax().text_range().start(); + match ctx.config.snippet_cap { + Some(cap) => { + let snip = + buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name)); + edit.insert_snippet(cap, offset, snip) + } + None => edit.insert(offset, buf), + } + + if let Anchor::WrapInBlock(_) = anchor { + edit.insert(anchor.syntax().text_range().end(), " }"); + } + }, + ) +} + +/// Check whether the node is a valid expression which can be extracted to a variable. +/// In general that's true for any expression, but in some cases that would produce invalid code. +fn valid_target_expr(node: SyntaxNode) -> Option { + match node.kind() { + PATH_EXPR | LOOP_EXPR => None, + BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()), + RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()), + BLOCK_EXPR => { + ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from) + } + _ => ast::Expr::cast(node), + } +} + +enum Anchor { + Before(SyntaxNode), + Replace(ast::ExprStmt), + WrapInBlock(SyntaxNode), +} + +impl Anchor { + fn from(to_extract: &ast::Expr) -> Option { + to_extract.syntax().ancestors().find_map(|node| { + if let Some(expr) = + node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.tail_expr()) + { + if expr.syntax() == &node { + mark::hit!(test_extract_var_last_expr); + return Some(Anchor::Before(node)); + } + } + + if let Some(parent) = node.parent() { + if parent.kind() == MATCH_ARM || parent.kind() == CLOSURE_EXPR { + return Some(Anchor::WrapInBlock(node)); + } + } + + if let Some(stmt) = ast::Stmt::cast(node.clone()) { + if let ast::Stmt::ExprStmt(stmt) = stmt { + if stmt.expr().as_ref() == Some(to_extract) { + return Some(Anchor::Replace(stmt)); + } + } + return Some(Anchor::Before(node)); + } + None + }) + } + + fn syntax(&self) -> &SyntaxNode { + match self { + Anchor::Before(it) | Anchor::WrapInBlock(it) => it, + Anchor::Replace(stmt) => stmt.syntax(), + } + } +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn test_extract_var_simple() { + check_assist( + extract_variable, + r#" +fn foo() { + foo($01 + 1$0); +}"#, + r#" +fn foo() { + let $0var_name = 1 + 1; + foo(var_name); +}"#, + ); + } + + #[test] + fn extract_var_in_comment_is_not_applicable() { + mark::check!(extract_var_in_comment_is_not_applicable); + check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }"); + } + + #[test] + fn test_extract_var_expr_stmt() { + mark::check!(test_extract_var_expr_stmt); + check_assist( + extract_variable, + r#" +fn foo() { + $01 + 1$0; +}"#, + r#" +fn foo() { + let $0var_name = 1 + 1; +}"#, + ); + check_assist( + extract_variable, + " +fn foo() { + $0{ let x = 0; x }$0 + something_else(); +}", + " +fn foo() { + let $0var_name = { let x = 0; x }; + something_else(); +}", + ); + } + + #[test] + fn test_extract_var_part_of_expr_stmt() { + check_assist( + extract_variable, + " +fn foo() { + $01$0 + 1; +}", + " +fn foo() { + let $0var_name = 1; + var_name + 1; +}", + ); + } + + #[test] + fn test_extract_var_last_expr() { + mark::check!(test_extract_var_last_expr); + check_assist( + extract_variable, + r#" +fn foo() { + bar($01 + 1$0) +} +"#, + r#" +fn foo() { + let $0var_name = 1 + 1; + bar(var_name) +} +"#, + ); + check_assist( + extract_variable, + r#" +fn foo() { + $0bar(1 + 1)$0 +} +"#, + r#" +fn foo() { + let $0var_name = bar(1 + 1); + var_name +} +"#, + ) + } + + #[test] + fn test_extract_var_in_match_arm_no_block() { + check_assist( + extract_variable, + " +fn main() { + let x = true; + let tuple = match x { + true => ($02 + 2$0, true) + _ => (0, false) + }; +} +", + " +fn main() { + let x = true; + let tuple = match x { + true => { let $0var_name = 2 + 2; (var_name, true) } + _ => (0, false) + }; +} +", + ); + } + + #[test] + fn test_extract_var_in_match_arm_with_block() { + check_assist( + extract_variable, + " +fn main() { + let x = true; + let tuple = match x { + true => { + let y = 1; + ($02 + y$0, true) + } + _ => (0, false) + }; +} +", + " +fn main() { + let x = true; + let tuple = match x { + true => { + let y = 1; + let $0var_name = 2 + y; + (var_name, true) + } + _ => (0, false) + }; +} +", + ); + } + + #[test] + fn test_extract_var_in_closure_no_block() { + check_assist( + extract_variable, + " +fn main() { + let lambda = |x: u32| $0x * 2$0; +} +", + " +fn main() { + let lambda = |x: u32| { let $0var_name = x * 2; var_name }; +} +", + ); + } + + #[test] + fn test_extract_var_in_closure_with_block() { + check_assist( + extract_variable, + " +fn main() { + let lambda = |x: u32| { $0x * 2$0 }; +} +", + " +fn main() { + let lambda = |x: u32| { let $0var_name = x * 2; var_name }; +} +", + ); + } + + #[test] + fn test_extract_var_path_simple() { + check_assist( + extract_variable, + " +fn main() { + let o = $0Some(true)$0; +} +", + " +fn main() { + let $0var_name = Some(true); + let o = var_name; +} +", + ); + } + + #[test] + fn test_extract_var_path_method() { + check_assist( + extract_variable, + " +fn main() { + let v = $0bar.foo()$0; +} +", + " +fn main() { + let $0var_name = bar.foo(); + let v = var_name; +} +", + ); + } + + #[test] + fn test_extract_var_return() { + check_assist( + extract_variable, + " +fn foo() -> u32 { + $0return 2 + 2$0; +} +", + " +fn foo() -> u32 { + let $0var_name = 2 + 2; + return var_name; +} +", + ); + } + + #[test] + fn test_extract_var_does_not_add_extra_whitespace() { + check_assist( + extract_variable, + " +fn foo() -> u32 { + + + $0return 2 + 2$0; +} +", + " +fn foo() -> u32 { + + + let $0var_name = 2 + 2; + return var_name; +} +", + ); + + check_assist( + extract_variable, + " +fn foo() -> u32 { + + $0return 2 + 2$0; +} +", + " +fn foo() -> u32 { + + let $0var_name = 2 + 2; + return var_name; +} +", + ); + + check_assist( + extract_variable, + " +fn foo() -> u32 { + let foo = 1; + + // bar + + + $0return 2 + 2$0; +} +", + " +fn foo() -> u32 { + let foo = 1; + + // bar + + + let $0var_name = 2 + 2; + return var_name; +} +", + ); + } + + #[test] + fn test_extract_var_break() { + check_assist( + extract_variable, + " +fn main() { + let result = loop { + $0break 2 + 2$0; + }; +} +", + " +fn main() { + let result = loop { + let $0var_name = 2 + 2; + break var_name; + }; +} +", + ); + } + + #[test] + fn test_extract_var_for_cast() { + check_assist( + extract_variable, + " +fn main() { + let v = $00f32 as u32$0; +} +", + " +fn main() { + let $0var_name = 0f32 as u32; + let v = var_name; +} +", + ); + } + + #[test] + fn extract_var_field_shorthand() { + check_assist( + extract_variable, + r#" +struct S { + foo: i32 +} + +fn main() { + S { foo: $01 + 1$0 } +} +"#, + r#" +struct S { + foo: i32 +} + +fn main() { + let $0foo = 1 + 1; + S { foo } +} +"#, + ) + } + + #[test] + fn test_extract_var_for_return_not_applicable() { + check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } "); + } + + #[test] + fn test_extract_var_for_break_not_applicable() { + check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }"); + } + + // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic + #[test] + fn extract_var_target() { + check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2"); + + check_assist_target( + extract_variable, + " +fn main() { + let x = true; + let tuple = match x { + true => ($02 + 2$0, true) + _ => (0, false) + }; +} +", + "2 + 2", + ); + } +} diff --git a/crates/ide_assists/src/handlers/fill_match_arms.rs b/crates/ide_assists/src/handlers/fill_match_arms.rs new file mode 100644 index 000000000..7086e47d2 --- /dev/null +++ b/crates/ide_assists/src/handlers/fill_match_arms.rs @@ -0,0 +1,787 @@ +use std::iter; + +use hir::{Adt, HasSource, ModuleDef, Semantics}; +use ide_db::helpers::{mod_path_to_ast, FamousDefs}; +use ide_db::RootDatabase; +use itertools::Itertools; +use syntax::ast::{self, make, AstNode, MatchArm, NameOwner, Pat}; +use test_utils::mark; + +use crate::{ + utils::{does_pat_match_variant, render_snippet, Cursor}, + AssistContext, AssistId, AssistKind, Assists, +}; + +// Assist: fill_match_arms +// +// Adds missing clauses to a `match` expression. +// +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// $0 +// } +// } +// ``` +// -> +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// $0Action::Move { distance } => {} +// Action::Stop => {} +// } +// } +// ``` +pub(crate) fn fill_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let match_expr = ctx.find_node_at_offset_with_descend::()?; + let match_arm_list = match_expr.match_arm_list()?; + + let expr = match_expr.expr()?; + + let mut arms: Vec = match_arm_list.arms().collect(); + if arms.len() == 1 { + if let Some(Pat::WildcardPat(..)) = arms[0].pat() { + arms.clear(); + } + } + + let module = ctx.sema.scope(expr.syntax()).module()?; + + let missing_arms: Vec = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) { + let variants = enum_def.variants(ctx.db()); + + let mut variants = variants + .into_iter() + .filter_map(|variant| build_pat(ctx.db(), module, variant)) + .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat)) + .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block())) + .collect::>(); + if Some(enum_def) == FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option() { + // Match `Some` variant first. + mark::hit!(option_order); + variants.reverse() + } + variants + } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) { + // Partial fill not currently supported for tuple of enums. + if !arms.is_empty() { + return None; + } + + // We do not currently support filling match arms for a tuple + // containing a single enum. + if enum_defs.len() < 2 { + return None; + } + + // When calculating the match arms for a tuple of enums, we want + // to create a match arm for each possible combination of enum + // values. The `multi_cartesian_product` method transforms + // Vec> into Vec<(EnumVariant, .., EnumVariant)> + // where each tuple represents a proposed match arm. + enum_defs + .into_iter() + .map(|enum_def| enum_def.variants(ctx.db())) + .multi_cartesian_product() + .map(|variants| { + let patterns = + variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant)); + ast::Pat::from(make::tuple_pat(patterns)) + }) + .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat)) + .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block())) + .collect() + } else { + return None; + }; + + if missing_arms.is_empty() { + return None; + } + + let target = ctx.sema.original_range(match_expr.syntax()).range; + acc.add( + AssistId("fill_match_arms", AssistKind::QuickFix), + "Fill match arms", + target, + |builder| { + let new_arm_list = match_arm_list.remove_placeholder(); + let n_old_arms = new_arm_list.arms().count(); + let new_arm_list = new_arm_list.append_arms(missing_arms); + let first_new_arm = new_arm_list.arms().nth(n_old_arms); + let old_range = ctx.sema.original_range(match_arm_list.syntax()).range; + match (first_new_arm, ctx.config.snippet_cap) { + (Some(first_new_arm), Some(cap)) => { + let extend_lifetime; + let cursor = + match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast) + { + Some(it) => { + extend_lifetime = it.syntax().clone(); + Cursor::Replace(&extend_lifetime) + } + None => Cursor::Before(first_new_arm.syntax()), + }; + let snippet = render_snippet(cap, new_arm_list.syntax(), cursor); + builder.replace_snippet(cap, old_range, snippet); + } + _ => builder.replace(old_range, new_arm_list.to_string()), + } + }, + ) +} + +fn is_variant_missing(existing_arms: &mut Vec, var: &Pat) -> bool { + existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| { + // Special casee OrPat as separate top-level pats + let top_level_pats: Vec = match pat { + Pat::OrPat(pats) => pats.pats().collect::>(), + _ => vec![pat], + }; + + !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var)) + }) +} + +fn resolve_enum_def(sema: &Semantics, expr: &ast::Expr) -> Option { + sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() { + Some(Adt::Enum(e)) => Some(e), + _ => None, + }) +} + +fn resolve_tuple_of_enum_def( + sema: &Semantics, + expr: &ast::Expr, +) -> Option> { + sema.type_of_expr(&expr)? + .tuple_fields(sema.db) + .iter() + .map(|ty| { + ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() { + Some(Adt::Enum(e)) => Some(e), + // For now we only handle expansion for a tuple of enums. Here + // we map non-enum items to None and rely on `collect` to + // convert Vec> into Option>. + _ => None, + }) + }) + .collect() +} + +fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::Variant) -> Option { + let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?); + + // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though + let pat: ast::Pat = match var.source(db)?.value.kind() { + ast::StructKind::Tuple(field_list) => { + let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count()); + make::tuple_struct_pat(path, pats).into() + } + ast::StructKind::Record(field_list) => { + let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into()); + make::record_pat(path, pats).into() + } + ast::StructKind::Unit => make::path_pat(path), + }; + + Some(pat) +} + +#[cfg(test)] +mod tests { + use ide_db::helpers::FamousDefs; + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::fill_match_arms; + + #[test] + fn all_match_arms_provided() { + check_assist_not_applicable( + fill_match_arms, + r#" + enum A { + As, + Bs{x:i32, y:Option}, + Cs(i32, Option), + } + fn main() { + match A::As$0 { + A::As, + A::Bs{x,y:Some(_)} => {} + A::Cs(_, Some(_)) => {} + } + } + "#, + ); + } + + #[test] + fn tuple_of_non_enum() { + // for now this case is not handled, although it potentially could be + // in the future + check_assist_not_applicable( + fill_match_arms, + r#" + fn main() { + match (0, false)$0 { + } + } + "#, + ); + } + + #[test] + fn partial_fill_record_tuple() { + check_assist( + fill_match_arms, + r#" + enum A { + As, + Bs { x: i32, y: Option }, + Cs(i32, Option), + } + fn main() { + match A::As$0 { + A::Bs { x, y: Some(_) } => {} + A::Cs(_, Some(_)) => {} + } + } + "#, + r#" + enum A { + As, + Bs { x: i32, y: Option }, + Cs(i32, Option), + } + fn main() { + match A::As { + A::Bs { x, y: Some(_) } => {} + A::Cs(_, Some(_)) => {} + $0A::As => {} + } + } + "#, + ); + } + + #[test] + fn partial_fill_option() { + check_assist( + fill_match_arms, + r#" +enum Option { Some(T), None } +use Option::*; + +fn main() { + match None$0 { + None => {} + } +} + "#, + r#" +enum Option { Some(T), None } +use Option::*; + +fn main() { + match None { + None => {} + Some(${0:_}) => {} + } +} + "#, + ); + } + + #[test] + fn partial_fill_or_pat() { + check_assist( + fill_match_arms, + r#" +enum A { As, Bs, Cs(Option) } +fn main() { + match A::As$0 { + A::Cs(_) | A::Bs => {} + } +} +"#, + r#" +enum A { As, Bs, Cs(Option) } +fn main() { + match A::As { + A::Cs(_) | A::Bs => {} + $0A::As => {} + } +} +"#, + ); + } + + #[test] + fn partial_fill() { + check_assist( + fill_match_arms, + r#" +enum A { As, Bs, Cs, Ds(String), Es(B) } +enum B { Xs, Ys } +fn main() { + match A::As$0 { + A::Bs if 0 < 1 => {} + A::Ds(_value) => { let x = 1; } + A::Es(B::Xs) => (), + } +} +"#, + r#" +enum A { As, Bs, Cs, Ds(String), Es(B) } +enum B { Xs, Ys } +fn main() { + match A::As { + A::Bs if 0 < 1 => {} + A::Ds(_value) => { let x = 1; } + A::Es(B::Xs) => (), + $0A::As => {} + A::Cs => {} + } +} +"#, + ); + } + + #[test] + fn partial_fill_bind_pat() { + check_assist( + fill_match_arms, + r#" +enum A { As, Bs, Cs(Option) } +fn main() { + match A::As$0 { + A::As(_) => {} + a @ A::Bs(_) => {} + } +} +"#, + r#" +enum A { As, Bs, Cs(Option) } +fn main() { + match A::As { + A::As(_) => {} + a @ A::Bs(_) => {} + A::Cs(${0:_}) => {} + } +} +"#, + ); + } + + #[test] + fn fill_match_arms_empty_body() { + check_assist( + fill_match_arms, + r#" +enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } } + +fn main() { + let a = A::As; + match a$0 {} +} +"#, + r#" +enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } } + +fn main() { + let a = A::As; + match a { + $0A::As => {} + A::Bs => {} + A::Cs(_) => {} + A::Ds(_, _) => {} + A::Es { x, y } => {} + } +} +"#, + ); + } + + #[test] + fn fill_match_arms_tuple_of_enum() { + check_assist( + fill_match_arms, + r#" + enum A { One, Two } + enum B { One, Two } + + fn main() { + let a = A::One; + let b = B::One; + match (a$0, b) {} + } + "#, + r#" + enum A { One, Two } + enum B { One, Two } + + fn main() { + let a = A::One; + let b = B::One; + match (a, b) { + $0(A::One, B::One) => {} + (A::One, B::Two) => {} + (A::Two, B::One) => {} + (A::Two, B::Two) => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_tuple_of_enum_ref() { + check_assist( + fill_match_arms, + r#" + enum A { One, Two } + enum B { One, Two } + + fn main() { + let a = A::One; + let b = B::One; + match (&a$0, &b) {} + } + "#, + r#" + enum A { One, Two } + enum B { One, Two } + + fn main() { + let a = A::One; + let b = B::One; + match (&a, &b) { + $0(A::One, B::One) => {} + (A::One, B::Two) => {} + (A::Two, B::One) => {} + (A::Two, B::Two) => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_tuple_of_enum_partial() { + check_assist_not_applicable( + fill_match_arms, + r#" + enum A { One, Two } + enum B { One, Two } + + fn main() { + let a = A::One; + let b = B::One; + match (a$0, b) { + (A::Two, B::One) => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_tuple_of_enum_not_applicable() { + check_assist_not_applicable( + fill_match_arms, + r#" + enum A { One, Two } + enum B { One, Two } + + fn main() { + let a = A::One; + let b = B::One; + match (a$0, b) { + (A::Two, B::One) => {} + (A::One, B::One) => {} + (A::One, B::Two) => {} + (A::Two, B::Two) => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_single_element_tuple_of_enum() { + // For now we don't hande the case of a single element tuple, but + // we could handle this in the future if `make::tuple_pat` allowed + // creating a tuple with a single pattern. + check_assist_not_applicable( + fill_match_arms, + r#" + enum A { One, Two } + + fn main() { + let a = A::One; + match (a$0, ) { + } + } + "#, + ); + } + + #[test] + fn test_fill_match_arm_refs() { + check_assist( + fill_match_arms, + r#" + enum A { As } + + fn foo(a: &A) { + match a$0 { + } + } + "#, + r#" + enum A { As } + + fn foo(a: &A) { + match a { + $0A::As => {} + } + } + "#, + ); + + check_assist( + fill_match_arms, + r#" + enum A { + Es { x: usize, y: usize } + } + + fn foo(a: &mut A) { + match a$0 { + } + } + "#, + r#" + enum A { + Es { x: usize, y: usize } + } + + fn foo(a: &mut A) { + match a { + $0A::Es { x, y } => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_target() { + check_assist_target( + fill_match_arms, + r#" + enum E { X, Y } + + fn main() { + match E::X$0 {} + } + "#, + "match E::X {}", + ); + } + + #[test] + fn fill_match_arms_trivial_arm() { + check_assist( + fill_match_arms, + r#" + enum E { X, Y } + + fn main() { + match E::X { + $0_ => {} + } + } + "#, + r#" + enum E { X, Y } + + fn main() { + match E::X { + $0E::X => {} + E::Y => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_qualifies_path() { + check_assist( + fill_match_arms, + r#" + mod foo { pub enum E { X, Y } } + use foo::E::X; + + fn main() { + match X { + $0 + } + } + "#, + r#" + mod foo { pub enum E { X, Y } } + use foo::E::X; + + fn main() { + match X { + $0X => {} + foo::E::Y => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_preserves_comments() { + check_assist( + fill_match_arms, + r#" + enum A { One, Two } + fn foo(a: A) { + match a { + // foo bar baz$0 + A::One => {} + // This is where the rest should be + } + } + "#, + r#" + enum A { One, Two } + fn foo(a: A) { + match a { + // foo bar baz + A::One => {} + // This is where the rest should be + $0A::Two => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_preserves_comments_empty() { + check_assist( + fill_match_arms, + r#" + enum A { One, Two } + fn foo(a: A) { + match a { + // foo bar baz$0 + } + } + "#, + r#" + enum A { One, Two } + fn foo(a: A) { + match a { + // foo bar baz + $0A::One => {} + A::Two => {} + } + } + "#, + ); + } + + #[test] + fn fill_match_arms_placeholder() { + check_assist( + fill_match_arms, + r#" + enum A { One, Two, } + fn foo(a: A) { + match a$0 { + _ => (), + } + } + "#, + r#" + enum A { One, Two, } + fn foo(a: A) { + match a { + $0A::One => {} + A::Two => {} + } + } + "#, + ); + } + + #[test] + fn option_order() { + mark::check!(option_order); + let before = r#" +fn foo(opt: Option) { + match opt$0 { + } +} +"#; + let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE); + + check_assist( + fill_match_arms, + before, + r#" +fn foo(opt: Option) { + match opt { + Some(${0:_}) => {} + None => {} + } +} +"#, + ); + } + + #[test] + fn works_inside_macro_call() { + check_assist( + fill_match_arms, + r#" +macro_rules! m { ($expr:expr) => {$expr}} +enum Test { + A, + B, + C, +} + +fn foo(t: Test) { + m!(match t$0 {}); +}"#, + r#"macro_rules! m { ($expr:expr) => {$expr}} +enum Test { + A, + B, + C, +} + +fn foo(t: Test) { + m!(match t { + $0Test::A => {} + Test::B => {} + Test::C => {} +}); +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/fix_visibility.rs b/crates/ide_assists/src/handlers/fix_visibility.rs new file mode 100644 index 000000000..6c7824e55 --- /dev/null +++ b/crates/ide_assists/src/handlers/fix_visibility.rs @@ -0,0 +1,607 @@ +use hir::{db::HirDatabase, HasSource, HasVisibility, PathResolution}; +use ide_db::base_db::FileId; +use syntax::{ + ast::{self, VisibilityOwner}, + AstNode, TextRange, TextSize, +}; + +use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists}; + +// FIXME: this really should be a fix for diagnostic, rather than an assist. + +// Assist: fix_visibility +// +// Makes inaccessible item public. +// +// ``` +// mod m { +// fn frobnicate() {} +// } +// fn main() { +// m::frobnicate$0() {} +// } +// ``` +// -> +// ``` +// mod m { +// $0pub(crate) fn frobnicate() {} +// } +// fn main() { +// m::frobnicate() {} +// } +// ``` +pub(crate) fn fix_visibility(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + add_vis_to_referenced_module_def(acc, ctx) + .or_else(|| add_vis_to_referenced_record_field(acc, ctx)) +} + +fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let path: ast::Path = ctx.find_node_at_offset()?; + let path_res = ctx.sema.resolve_path(&path)?; + let def = match path_res { + PathResolution::Def(def) => def, + _ => return None, + }; + + let current_module = ctx.sema.scope(&path.syntax()).module()?; + let target_module = def.module(ctx.db())?; + + let vis = target_module.visibility_of(ctx.db(), &def)?; + if vis.is_visible_from(ctx.db(), current_module.into()) { + return None; + }; + + let (offset, current_visibility, target, target_file, target_name) = + target_data_for_def(ctx.db(), def)?; + + let missing_visibility = + if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" }; + + let assist_label = match target_name { + None => format!("Change visibility to {}", missing_visibility), + Some(name) => format!("Change visibility of {} to {}", name, missing_visibility), + }; + + acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| { + builder.edit_file(target_file); + match ctx.config.snippet_cap { + Some(cap) => match current_visibility { + Some(current_visibility) => builder.replace_snippet( + cap, + current_visibility.syntax().text_range(), + format!("$0{}", missing_visibility), + ), + None => builder.insert_snippet(cap, offset, format!("$0{} ", missing_visibility)), + }, + None => match current_visibility { + Some(current_visibility) => { + builder.replace(current_visibility.syntax().text_range(), missing_visibility) + } + None => builder.insert(offset, format!("{} ", missing_visibility)), + }, + } + }) +} + +fn add_vis_to_referenced_record_field(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let record_field: ast::RecordExprField = ctx.find_node_at_offset()?; + let (record_field_def, _) = ctx.sema.resolve_record_field(&record_field)?; + + let current_module = ctx.sema.scope(record_field.syntax()).module()?; + let visibility = record_field_def.visibility(ctx.db()); + if visibility.is_visible_from(ctx.db(), current_module.into()) { + return None; + } + + let parent = record_field_def.parent_def(ctx.db()); + let parent_name = parent.name(ctx.db()); + let target_module = parent.module(ctx.db()); + + let in_file_source = record_field_def.source(ctx.db())?; + let (offset, current_visibility, target) = match in_file_source.value { + hir::FieldSource::Named(it) => { + let s = it.syntax(); + (vis_offset(s), it.visibility(), s.text_range()) + } + hir::FieldSource::Pos(it) => { + let s = it.syntax(); + (vis_offset(s), it.visibility(), s.text_range()) + } + }; + + let missing_visibility = + if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" }; + let target_file = in_file_source.file_id.original_file(ctx.db()); + + let target_name = record_field_def.name(ctx.db()); + let assist_label = + format!("Change visibility of {}.{} to {}", parent_name, target_name, missing_visibility); + + acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| { + builder.edit_file(target_file); + match ctx.config.snippet_cap { + Some(cap) => match current_visibility { + Some(current_visibility) => builder.replace_snippet( + cap, + current_visibility.syntax().text_range(), + format!("$0{}", missing_visibility), + ), + None => builder.insert_snippet(cap, offset, format!("$0{} ", missing_visibility)), + }, + None => match current_visibility { + Some(current_visibility) => { + builder.replace(current_visibility.syntax().text_range(), missing_visibility) + } + None => builder.insert(offset, format!("{} ", missing_visibility)), + }, + } + }) +} + +fn target_data_for_def( + db: &dyn HirDatabase, + def: hir::ModuleDef, +) -> Option<(TextSize, Option, TextRange, FileId, Option)> { + fn offset_target_and_file_id( + db: &dyn HirDatabase, + x: S, + ) -> Option<(TextSize, Option, TextRange, FileId)> + where + S: HasSource, + Ast: AstNode + ast::VisibilityOwner, + { + let source = x.source(db)?; + let in_file_syntax = source.syntax(); + let file_id = in_file_syntax.file_id; + let syntax = in_file_syntax.value; + let current_visibility = source.value.visibility(); + Some(( + vis_offset(syntax), + current_visibility, + syntax.text_range(), + file_id.original_file(db.upcast()), + )) + } + + let target_name; + let (offset, current_visibility, target, target_file) = match def { + hir::ModuleDef::Function(f) => { + target_name = Some(f.name(db)); + offset_target_and_file_id(db, f)? + } + hir::ModuleDef::Adt(adt) => { + target_name = Some(adt.name(db)); + match adt { + hir::Adt::Struct(s) => offset_target_and_file_id(db, s)?, + hir::Adt::Union(u) => offset_target_and_file_id(db, u)?, + hir::Adt::Enum(e) => offset_target_and_file_id(db, e)?, + } + } + hir::ModuleDef::Const(c) => { + target_name = c.name(db); + offset_target_and_file_id(db, c)? + } + hir::ModuleDef::Static(s) => { + target_name = s.name(db); + offset_target_and_file_id(db, s)? + } + hir::ModuleDef::Trait(t) => { + target_name = Some(t.name(db)); + offset_target_and_file_id(db, t)? + } + hir::ModuleDef::TypeAlias(t) => { + target_name = Some(t.name(db)); + offset_target_and_file_id(db, t)? + } + hir::ModuleDef::Module(m) => { + target_name = m.name(db); + let in_file_source = m.declaration_source(db)?; + let file_id = in_file_source.file_id.original_file(db.upcast()); + let syntax = in_file_source.value.syntax(); + (vis_offset(syntax), in_file_source.value.visibility(), syntax.text_range(), file_id) + } + // Enum variants can't be private, we can't modify builtin types + hir::ModuleDef::Variant(_) | hir::ModuleDef::BuiltinType(_) => return None, + }; + + Some((offset, current_visibility, target, target_file, target_name)) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn fix_visibility_of_fn() { + check_assist( + fix_visibility, + r"mod foo { fn foo() {} } + fn main() { foo::foo$0() } ", + r"mod foo { $0pub(crate) fn foo() {} } + fn main() { foo::foo() } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub fn foo() {} } + fn main() { foo::foo$0() } ", + ) + } + + #[test] + fn fix_visibility_of_adt_in_submodule() { + check_assist( + fix_visibility, + r"mod foo { struct Foo; } + fn main() { foo::Foo$0 } ", + r"mod foo { $0pub(crate) struct Foo; } + fn main() { foo::Foo } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub struct Foo; } + fn main() { foo::Foo$0 } ", + ); + check_assist( + fix_visibility, + r"mod foo { enum Foo; } + fn main() { foo::Foo$0 } ", + r"mod foo { $0pub(crate) enum Foo; } + fn main() { foo::Foo } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub enum Foo; } + fn main() { foo::Foo$0 } ", + ); + check_assist( + fix_visibility, + r"mod foo { union Foo; } + fn main() { foo::Foo$0 } ", + r"mod foo { $0pub(crate) union Foo; } + fn main() { foo::Foo } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub union Foo; } + fn main() { foo::Foo$0 } ", + ); + } + + #[test] + fn fix_visibility_of_adt_in_other_file() { + check_assist( + fix_visibility, + r" +//- /main.rs +mod foo; +fn main() { foo::Foo$0 } + +//- /foo.rs +struct Foo; +", + r"$0pub(crate) struct Foo; +", + ); + } + + #[test] + fn fix_visibility_of_struct_field() { + check_assist( + fix_visibility, + r"mod foo { pub struct Foo { bar: (), } } + fn main() { foo::Foo { $0bar: () }; } ", + r"mod foo { pub struct Foo { $0pub(crate) bar: (), } } + fn main() { foo::Foo { bar: () }; } ", + ); + check_assist( + fix_visibility, + r" +//- /lib.rs +mod foo; +fn main() { foo::Foo { $0bar: () }; } +//- /foo.rs +pub struct Foo { bar: () } +", + r"pub struct Foo { $0pub(crate) bar: () } +", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub struct Foo { pub bar: (), } } + fn main() { foo::Foo { $0bar: () }; } ", + ); + check_assist_not_applicable( + fix_visibility, + r" +//- /lib.rs +mod foo; +fn main() { foo::Foo { $0bar: () }; } +//- /foo.rs +pub struct Foo { pub bar: () } +", + ); + } + + #[test] + fn fix_visibility_of_enum_variant_field() { + // Enum variants, as well as their fields, always get the enum's visibility. In fact, rustc + // rejects any visibility specifiers on them, so this assist should never fire on them. + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub enum Foo { Bar { bar: () } } } + fn main() { foo::Foo::Bar { $0bar: () }; } ", + ); + check_assist_not_applicable( + fix_visibility, + r" +//- /lib.rs +mod foo; +fn main() { foo::Foo::Bar { $0bar: () }; } +//- /foo.rs +pub enum Foo { Bar { bar: () } } +", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub struct Foo { pub bar: (), } } + fn main() { foo::Foo { $0bar: () }; } ", + ); + check_assist_not_applicable( + fix_visibility, + r" +//- /lib.rs +mod foo; +fn main() { foo::Foo { $0bar: () }; } +//- /foo.rs +pub struct Foo { pub bar: () } +", + ); + } + + #[test] + #[ignore] + // FIXME reenable this test when `Semantics::resolve_record_field` works with union fields + fn fix_visibility_of_union_field() { + check_assist( + fix_visibility, + r"mod foo { pub union Foo { bar: (), } } + fn main() { foo::Foo { $0bar: () }; } ", + r"mod foo { pub union Foo { $0pub(crate) bar: (), } } + fn main() { foo::Foo { bar: () }; } ", + ); + check_assist( + fix_visibility, + r" +//- /lib.rs +mod foo; +fn main() { foo::Foo { $0bar: () }; } +//- /foo.rs +pub union Foo { bar: () } +", + r"pub union Foo { $0pub(crate) bar: () } +", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub union Foo { pub bar: (), } } + fn main() { foo::Foo { $0bar: () }; } ", + ); + check_assist_not_applicable( + fix_visibility, + r" +//- /lib.rs +mod foo; +fn main() { foo::Foo { $0bar: () }; } +//- /foo.rs +pub union Foo { pub bar: () } +", + ); + } + + #[test] + fn fix_visibility_of_const() { + check_assist( + fix_visibility, + r"mod foo { const FOO: () = (); } + fn main() { foo::FOO$0 } ", + r"mod foo { $0pub(crate) const FOO: () = (); } + fn main() { foo::FOO } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub const FOO: () = (); } + fn main() { foo::FOO$0 } ", + ); + } + + #[test] + fn fix_visibility_of_static() { + check_assist( + fix_visibility, + r"mod foo { static FOO: () = (); } + fn main() { foo::FOO$0 } ", + r"mod foo { $0pub(crate) static FOO: () = (); } + fn main() { foo::FOO } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub static FOO: () = (); } + fn main() { foo::FOO$0 } ", + ); + } + + #[test] + fn fix_visibility_of_trait() { + check_assist( + fix_visibility, + r"mod foo { trait Foo { fn foo(&self) {} } } + fn main() { let x: &dyn foo::$0Foo; } ", + r"mod foo { $0pub(crate) trait Foo { fn foo(&self) {} } } + fn main() { let x: &dyn foo::Foo; } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub trait Foo { fn foo(&self) {} } } + fn main() { let x: &dyn foo::Foo$0; } ", + ); + } + + #[test] + fn fix_visibility_of_type_alias() { + check_assist( + fix_visibility, + r"mod foo { type Foo = (); } + fn main() { let x: foo::Foo$0; } ", + r"mod foo { $0pub(crate) type Foo = (); } + fn main() { let x: foo::Foo; } ", + ); + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub type Foo = (); } + fn main() { let x: foo::Foo$0; } ", + ); + } + + #[test] + fn fix_visibility_of_module() { + check_assist( + fix_visibility, + r"mod foo { mod bar { fn bar() {} } } + fn main() { foo::bar$0::bar(); } ", + r"mod foo { $0pub(crate) mod bar { fn bar() {} } } + fn main() { foo::bar::bar(); } ", + ); + + check_assist( + fix_visibility, + r" +//- /main.rs +mod foo; +fn main() { foo::bar$0::baz(); } + +//- /foo.rs +mod bar { + pub fn baz() {} +} +", + r"$0pub(crate) mod bar { + pub fn baz() {} +} +", + ); + + check_assist_not_applicable( + fix_visibility, + r"mod foo { pub mod bar { pub fn bar() {} } } + fn main() { foo::bar$0::bar(); } ", + ); + } + + #[test] + fn fix_visibility_of_inline_module_in_other_file() { + check_assist( + fix_visibility, + r" +//- /main.rs +mod foo; +fn main() { foo::bar$0::baz(); } + +//- /foo.rs +mod bar; +//- /foo/bar.rs +pub fn baz() {} +", + r"$0pub(crate) mod bar; +", + ); + } + + #[test] + fn fix_visibility_of_module_declaration_in_other_file() { + check_assist( + fix_visibility, + r" +//- /main.rs +mod foo; +fn main() { foo::bar$0>::baz(); } + +//- /foo.rs +mod bar { + pub fn baz() {} +} +", + r"$0pub(crate) mod bar { + pub fn baz() {} +} +", + ); + } + + #[test] + fn adds_pub_when_target_is_in_another_crate() { + check_assist( + fix_visibility, + r" +//- /main.rs crate:a deps:foo +foo::Bar$0 +//- /lib.rs crate:foo +struct Bar; +", + r"$0pub struct Bar; +", + ) + } + + #[test] + fn replaces_pub_crate_with_pub() { + check_assist( + fix_visibility, + r" +//- /main.rs crate:a deps:foo +foo::Bar$0 +//- /lib.rs crate:foo +pub(crate) struct Bar; +", + r"$0pub struct Bar; +", + ); + check_assist( + fix_visibility, + r" +//- /main.rs crate:a deps:foo +fn main() { + foo::Foo { $0bar: () }; +} +//- /lib.rs crate:foo +pub struct Foo { pub(crate) bar: () } +", + r"pub struct Foo { $0pub bar: () } +", + ); + } + + #[test] + #[ignore] + // FIXME handle reexports properly + fn fix_visibility_of_reexport() { + check_assist( + fix_visibility, + r" + mod foo { + use bar::Baz; + mod bar { pub(super) struct Baz; } + } + foo::Baz$0 + ", + r" + mod foo { + $0pub(crate) use bar::Baz; + mod bar { pub(super) struct Baz; } + } + foo::Baz + ", + ) + } +} diff --git a/crates/ide_assists/src/handlers/flip_binexpr.rs b/crates/ide_assists/src/handlers/flip_binexpr.rs new file mode 100644 index 000000000..209e5d43c --- /dev/null +++ b/crates/ide_assists/src/handlers/flip_binexpr.rs @@ -0,0 +1,134 @@ +use syntax::ast::{AstNode, BinExpr, BinOp}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: flip_binexpr +// +// Flips operands of a binary expression. +// +// ``` +// fn main() { +// let _ = 90 +$0 2; +// } +// ``` +// -> +// ``` +// fn main() { +// let _ = 2 + 90; +// } +// ``` +pub(crate) fn flip_binexpr(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let expr = ctx.find_node_at_offset::()?; + let lhs = expr.lhs()?.syntax().clone(); + let rhs = expr.rhs()?.syntax().clone(); + let op_range = expr.op_token()?.text_range(); + // The assist should be applied only if the cursor is on the operator + let cursor_in_range = op_range.contains_range(ctx.frange.range); + if !cursor_in_range { + return None; + } + let action: FlipAction = expr.op_kind()?.into(); + // The assist should not be applied for certain operators + if let FlipAction::DontFlip = action { + return None; + } + + acc.add( + AssistId("flip_binexpr", AssistKind::RefactorRewrite), + "Flip binary expression", + op_range, + |edit| { + 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()); + }, + ) +} + +enum FlipAction { + // Flip the expression + Flip, + // Flip the expression and replace the operator with this string + FlipAndReplaceOp(&'static str), + // Do not flip the expression + DontFlip, +} + +impl From for FlipAction { + fn from(op_kind: BinOp) -> Self { + match op_kind { + kind if kind.is_assignment() => FlipAction::DontFlip, + BinOp::GreaterTest => FlipAction::FlipAndReplaceOp("<"), + BinOp::GreaterEqualTest => FlipAction::FlipAndReplaceOp("<="), + BinOp::LesserTest => FlipAction::FlipAndReplaceOp(">"), + BinOp::LesserEqualTest => FlipAction::FlipAndReplaceOp(">="), + _ => FlipAction::Flip, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + #[test] + fn flip_binexpr_target_is_the_op() { + check_assist_target(flip_binexpr, "fn f() { let res = 1 ==$0 2; }", "==") + } + + #[test] + fn flip_binexpr_not_applicable_for_assignment() { + check_assist_not_applicable(flip_binexpr, "fn f() { let mut _x = 1; _x +=$0 2 }") + } + + #[test] + fn flip_binexpr_works_for_eq() { + check_assist(flip_binexpr, "fn f() { let res = 1 ==$0 2; }", "fn f() { let res = 2 == 1; }") + } + + #[test] + fn flip_binexpr_works_for_gt() { + check_assist(flip_binexpr, "fn f() { let res = 1 >$0 2; }", "fn f() { let res = 2 < 1; }") + } + + #[test] + fn flip_binexpr_works_for_lteq() { + check_assist(flip_binexpr, "fn f() { let res = 1 <=$0 2; }", "fn f() { let res = 2 >= 1; }") + } + + #[test] + fn flip_binexpr_works_for_complex_expr() { + check_assist( + flip_binexpr, + "fn f() { let res = (1 + 1) ==$0 (2 + 2); }", + "fn f() { let res = (2 + 2) == (1 + 1); }", + ) + } + + #[test] + fn flip_binexpr_works_inside_match() { + check_assist( + flip_binexpr, + r#" + fn dyn_eq(&self, other: &dyn Diagnostic) -> bool { + match other.downcast_ref::() { + None => false, + Some(it) => it ==$0 self, + } + } + "#, + r#" + fn dyn_eq(&self, other: &dyn Diagnostic) -> bool { + match other.downcast_ref::() { + None => false, + Some(it) => self == it, + } + } + "#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/flip_comma.rs b/crates/ide_assists/src/handlers/flip_comma.rs new file mode 100644 index 000000000..18cf64a34 --- /dev/null +++ b/crates/ide_assists/src/handlers/flip_comma.rs @@ -0,0 +1,84 @@ +use syntax::{algo::non_trivia_sibling, Direction, T}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: flip_comma +// +// Flips two comma-separated items. +// +// ``` +// fn main() { +// ((1, 2),$0 (3, 4)); +// } +// ``` +// -> +// ``` +// fn main() { +// ((3, 4), (1, 2)); +// } +// ``` +pub(crate) fn flip_comma(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let comma = ctx.find_token_syntax_at_offset(T![,])?; + let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?; + let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?; + + // Don't apply a "flip" in case of a last comma + // that typically comes before punctuation + if next.kind().is_punct() { + return None; + } + + acc.add( + AssistId("flip_comma", AssistKind::RefactorRewrite), + "Flip comma", + comma.text_range(), + |edit| { + edit.replace(prev.text_range(), next.to_string()); + edit.replace(next.text_range(), prev.to_string()); + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_target}; + + #[test] + fn flip_comma_works_for_function_parameters() { + check_assist( + flip_comma, + r#"fn foo(x: i32,$0 y: Result<(), ()>) {}"#, + r#"fn foo(y: Result<(), ()>, x: i32) {}"#, + ) + } + + #[test] + fn flip_comma_target() { + check_assist_target(flip_comma, r#"fn foo(x: i32,$0 y: Result<(), ()>) {}"#, ",") + } + + #[test] + #[should_panic] + fn flip_comma_before_punct() { + // See https://github.com/rust-analyzer/rust-analyzer/issues/1619 + // "Flip comma" assist shouldn't be applicable to the last comma in enum or struct + // declaration body. + check_assist_target( + flip_comma, + "pub enum Test { \ + A,$0 \ + }", + ",", + ); + + check_assist_target( + flip_comma, + "pub struct Test { \ + foo: usize,$0 \ + }", + ",", + ); + } +} diff --git a/crates/ide_assists/src/handlers/flip_trait_bound.rs b/crates/ide_assists/src/handlers/flip_trait_bound.rs new file mode 100644 index 000000000..d419d263e --- /dev/null +++ b/crates/ide_assists/src/handlers/flip_trait_bound.rs @@ -0,0 +1,121 @@ +use syntax::{ + algo::non_trivia_sibling, + ast::{self, AstNode}, + Direction, T, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: flip_trait_bound +// +// Flips two trait bounds. +// +// ``` +// fn foo() { } +// ``` +// -> +// ``` +// fn foo() { } +// ``` +pub(crate) fn flip_trait_bound(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + // 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_syntax_at_offset(T![+])?; + + // Make sure we're in a `TypeBoundList` + if ast::TypeBoundList::cast(plus.parent()).is_none() { + return None; + } + + let (before, after) = ( + non_trivia_sibling(plus.clone().into(), Direction::Prev)?, + non_trivia_sibling(plus.clone().into(), Direction::Next)?, + ); + + let target = plus.text_range(); + acc.add( + AssistId("flip_trait_bound", AssistKind::RefactorRewrite), + "Flip trait bounds", + target, + |edit| { + edit.replace(before.text_range(), after.to_string()); + edit.replace(after.text_range(), before.to_string()); + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + #[test] + fn flip_trait_bound_assist_available() { + check_assist_target(flip_trait_bound, "struct S where T: A $0+ B + C { }", "+") + } + + #[test] + fn flip_trait_bound_not_applicable_for_single_trait_bound() { + check_assist_not_applicable(flip_trait_bound, "struct S where T: $0A { }") + } + + #[test] + fn flip_trait_bound_works_for_struct() { + check_assist( + flip_trait_bound, + "struct S where T: A $0+ B { }", + "struct S where T: B + A { }", + ) + } + + #[test] + fn flip_trait_bound_works_for_trait_impl() { + check_assist( + flip_trait_bound, + "impl X for S where T: A +$0 B { }", + "impl X for S where T: B + A { }", + ) + } + + #[test] + fn flip_trait_bound_works_for_fn() { + check_assist(flip_trait_bound, "fn f(t: T) { }", "fn f(t: T) { }") + } + + #[test] + fn flip_trait_bound_works_for_fn_where_clause() { + check_assist( + flip_trait_bound, + "fn f(t: T) where T: A +$0 B { }", + "fn f(t: T) where T: B + A { }", + ) + } + + #[test] + fn flip_trait_bound_works_for_lifetime() { + check_assist( + flip_trait_bound, + "fn f(t: T) where T: A $0+ 'static { }", + "fn f(t: T) where T: 'static + A { }", + ) + } + + #[test] + fn flip_trait_bound_works_for_complex_bounds() { + check_assist( + flip_trait_bound, + "struct S where T: A $0+ b_mod::B + C { }", + "struct S where T: b_mod::B + A + C { }", + ) + } + + #[test] + fn flip_trait_bound_works_for_long_bounds() { + check_assist( + flip_trait_bound, + "struct S where T: A + B + C + D + E + F +$0 G + H + I + J { }", + "struct S where T: A + B + C + D + E + G + F + H + I + J { }", + ) + } +} diff --git a/crates/ide_assists/src/handlers/generate_default_from_enum_variant.rs b/crates/ide_assists/src/handlers/generate_default_from_enum_variant.rs new file mode 100644 index 000000000..6a2ab9596 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_default_from_enum_variant.rs @@ -0,0 +1,175 @@ +use ide_db::helpers::FamousDefs; +use ide_db::RootDatabase; +use syntax::ast::{self, AstNode, NameOwner}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: generate_default_from_enum_variant +// +// Adds a Default impl for an enum using a variant. +// +// ``` +// enum Version { +// Undefined, +// Minor$0, +// Major, +// } +// ``` +// -> +// ``` +// enum Version { +// Undefined, +// Minor, +// Major, +// } +// +// impl Default for Version { +// fn default() -> Self { +// Self::Minor +// } +// } +// ``` +pub(crate) fn generate_default_from_enum_variant( + acc: &mut Assists, + ctx: &AssistContext, +) -> Option<()> { + let variant = ctx.find_node_at_offset::()?; + let variant_name = variant.name()?; + let enum_name = variant.parent_enum().name()?; + if !matches!(variant.kind(), ast::StructKind::Unit) { + mark::hit!(test_gen_default_on_non_unit_variant_not_implemented); + return None; + } + + if existing_default_impl(&ctx.sema, &variant).is_some() { + mark::hit!(test_gen_default_impl_already_exists); + return None; + } + + let target = variant.syntax().text_range(); + acc.add( + AssistId("generate_default_from_enum_variant", AssistKind::Generate), + "Generate `Default` impl from this enum variant", + target, + |edit| { + let start_offset = variant.parent_enum().syntax().text_range().end(); + let buf = format!( + r#" + +impl Default for {0} {{ + fn default() -> Self {{ + Self::{1} + }} +}}"#, + enum_name, variant_name + ); + edit.insert(start_offset, buf); + }, + ) +} + +fn existing_default_impl( + sema: &'_ hir::Semantics<'_, RootDatabase>, + variant: &ast::Variant, +) -> Option<()> { + let variant = sema.to_def(variant)?; + let enum_ = variant.parent_enum(sema.db); + let krate = enum_.module(sema.db).krate(); + + let default_trait = FamousDefs(sema, Some(krate)).core_default_Default()?; + let enum_type = enum_.ty(sema.db); + + if enum_type.impls_trait(sema.db, default_trait, &[]) { + Some(()) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + fn check_not_applicable(ra_fixture: &str) { + let fixture = + format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE); + check_assist_not_applicable(generate_default_from_enum_variant, &fixture) + } + + #[test] + fn test_generate_default_from_variant() { + check_assist( + generate_default_from_enum_variant, + r#" +enum Variant { + Undefined, + Minor$0, + Major, +}"#, + r#"enum Variant { + Undefined, + Minor, + Major, +} + +impl Default for Variant { + fn default() -> Self { + Self::Minor + } +}"#, + ); + } + + #[test] + fn test_generate_default_already_implemented() { + mark::check!(test_gen_default_impl_already_exists); + check_not_applicable( + r#" +enum Variant { + Undefined, + Minor$0, + Major, +} + +impl Default for Variant { + fn default() -> Self { + Self::Minor + } +}"#, + ); + } + + #[test] + fn test_add_from_impl_no_element() { + mark::check!(test_gen_default_on_non_unit_variant_not_implemented); + check_not_applicable( + r#" +enum Variant { + Undefined, + Minor(u32)$0, + Major, +}"#, + ); + } + + #[test] + fn test_generate_default_from_variant_with_one_variant() { + check_assist( + generate_default_from_enum_variant, + r#"enum Variant { Undefi$0ned }"#, + r#" +enum Variant { Undefined } + +impl Default for Variant { + fn default() -> Self { + Self::Undefined + } +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_derive.rs b/crates/ide_assists/src/handlers/generate_derive.rs new file mode 100644 index 000000000..adae8ab7e --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_derive.rs @@ -0,0 +1,132 @@ +use syntax::{ + ast::{self, AstNode, AttrsOwner}, + SyntaxKind::{COMMENT, WHITESPACE}, + TextSize, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: generate_derive +// +// Adds a new `#[derive()]` clause to a struct or enum. +// +// ``` +// struct Point { +// x: u32, +// y: u32,$0 +// } +// ``` +// -> +// ``` +// #[derive($0)] +// struct Point { +// x: u32, +// y: u32, +// } +// ``` +pub(crate) fn generate_derive(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let cap = ctx.config.snippet_cap?; + let nominal = ctx.find_node_at_offset::()?; + let node_start = derive_insertion_offset(&nominal)?; + let target = nominal.syntax().text_range(); + acc.add( + AssistId("generate_derive", AssistKind::Generate), + "Add `#[derive]`", + target, + |builder| { + let derive_attr = nominal + .attrs() + .filter_map(|x| x.as_simple_call()) + .filter(|(name, _arg)| name == "derive") + .map(|(_name, arg)| arg) + .next(); + match derive_attr { + None => { + builder.insert_snippet(cap, node_start, "#[derive($0)]\n"); + } + Some(tt) => { + // Just move the cursor. + builder.insert_snippet( + cap, + tt.syntax().text_range().end() - TextSize::of(')'), + "$0", + ) + } + }; + }, + ) +} + +// Insert `derive` after doc comments. +fn derive_insertion_offset(nominal: &ast::Adt) -> Option { + let non_ws_child = nominal + .syntax() + .children_with_tokens() + .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?; + Some(non_ws_child.text_range().start()) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_target}; + + use super::*; + + #[test] + fn add_derive_new() { + check_assist( + generate_derive, + "struct Foo { a: i32, $0}", + "#[derive($0)]\nstruct Foo { a: i32, }", + ); + check_assist( + generate_derive, + "struct Foo { $0 a: i32, }", + "#[derive($0)]\nstruct Foo { a: i32, }", + ); + } + + #[test] + fn add_derive_existing() { + check_assist( + generate_derive, + "#[derive(Clone)]\nstruct Foo { a: i32$0, }", + "#[derive(Clone$0)]\nstruct Foo { a: i32, }", + ); + } + + #[test] + fn add_derive_new_with_doc_comment() { + check_assist( + generate_derive, + " +/// `Foo` is a pretty important struct. +/// It does stuff. +struct Foo { a: i32$0, } + ", + " +/// `Foo` is a pretty important struct. +/// It does stuff. +#[derive($0)] +struct Foo { a: i32, } + ", + ); + } + + #[test] + fn add_derive_target() { + check_assist_target( + generate_derive, + " +struct SomeThingIrrelevant; +/// `Foo` is a pretty important struct. +/// It does stuff. +struct Foo { a: i32$0, } +struct EvenMoreIrrelevant; + ", + "/// `Foo` is a pretty important struct. +/// It does stuff. +struct Foo { a: i32, }", + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_enum_match_method.rs b/crates/ide_assists/src/handlers/generate_enum_match_method.rs new file mode 100644 index 000000000..aeb887e71 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_enum_match_method.rs @@ -0,0 +1,240 @@ +use stdx::{format_to, to_lower_snake_case}; +use syntax::ast::VisibilityOwner; +use syntax::ast::{self, AstNode, NameOwner}; +use test_utils::mark; + +use crate::{ + utils::{find_impl_block_end, find_struct_impl, generate_impl_text}, + AssistContext, AssistId, AssistKind, Assists, +}; + +// Assist: generate_enum_match_method +// +// Generate an `is_` method for an enum variant. +// +// ``` +// enum Version { +// Undefined, +// Minor$0, +// Major, +// } +// ``` +// -> +// ``` +// enum Version { +// Undefined, +// Minor, +// Major, +// } +// +// impl Version { +// /// Returns `true` if the version is [`Minor`]. +// fn is_minor(&self) -> bool { +// matches!(self, Self::Minor) +// } +// } +// ``` +pub(crate) fn generate_enum_match_method(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let variant = ctx.find_node_at_offset::()?; + let variant_name = variant.name()?; + let parent_enum = variant.parent_enum(); + if !matches!(variant.kind(), ast::StructKind::Unit) { + mark::hit!(test_gen_enum_match_on_non_unit_variant_not_implemented); + return None; + } + + let enum_lowercase_name = to_lower_snake_case(&parent_enum.name()?.to_string()); + let fn_name = to_lower_snake_case(&variant_name.to_string()); + + // Return early if we've found an existing new fn + let impl_def = find_struct_impl( + &ctx, + &ast::Adt::Enum(parent_enum.clone()), + format!("is_{}", fn_name).as_str(), + )?; + + let target = variant.syntax().text_range(); + acc.add( + AssistId("generate_enum_match_method", AssistKind::Generate), + "Generate an `is_` method for an enum variant", + target, + |builder| { + let mut buf = String::with_capacity(512); + + if impl_def.is_some() { + buf.push('\n'); + } + + let vis = parent_enum.visibility().map_or(String::new(), |v| format!("{} ", v)); + format_to!( + buf, + " /// Returns `true` if the {} is [`{}`]. + {}fn is_{}(&self) -> bool {{ + matches!(self, Self::{}) + }}", + enum_lowercase_name, + variant_name, + vis, + fn_name, + variant_name + ); + + let start_offset = impl_def + .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf)) + .unwrap_or_else(|| { + buf = generate_impl_text(&ast::Adt::Enum(parent_enum.clone()), &buf); + parent_enum.syntax().text_range().end() + }); + + builder.insert(start_offset, buf); + }, + ) +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + fn check_not_applicable(ra_fixture: &str) { + check_assist_not_applicable(generate_enum_match_method, ra_fixture) + } + + #[test] + fn test_generate_enum_match_from_variant() { + check_assist( + generate_enum_match_method, + r#" +enum Variant { + Undefined, + Minor$0, + Major, +}"#, + r#"enum Variant { + Undefined, + Minor, + Major, +} + +impl Variant { + /// Returns `true` if the variant is [`Minor`]. + fn is_minor(&self) -> bool { + matches!(self, Self::Minor) + } +}"#, + ); + } + + #[test] + fn test_generate_enum_match_already_implemented() { + check_not_applicable( + r#" +enum Variant { + Undefined, + Minor$0, + Major, +} + +impl Variant { + fn is_minor(&self) -> bool { + matches!(self, Self::Minor) + } +}"#, + ); + } + + #[test] + fn test_add_from_impl_no_element() { + mark::check!(test_gen_enum_match_on_non_unit_variant_not_implemented); + check_not_applicable( + r#" +enum Variant { + Undefined, + Minor(u32)$0, + Major, +}"#, + ); + } + + #[test] + fn test_generate_enum_match_from_variant_with_one_variant() { + check_assist( + generate_enum_match_method, + r#"enum Variant { Undefi$0ned }"#, + r#" +enum Variant { Undefined } + +impl Variant { + /// Returns `true` if the variant is [`Undefined`]. + fn is_undefined(&self) -> bool { + matches!(self, Self::Undefined) + } +}"#, + ); + } + + #[test] + fn test_generate_enum_match_from_variant_with_visibility_marker() { + check_assist( + generate_enum_match_method, + r#" +pub(crate) enum Variant { + Undefined, + Minor$0, + Major, +}"#, + r#"pub(crate) enum Variant { + Undefined, + Minor, + Major, +} + +impl Variant { + /// Returns `true` if the variant is [`Minor`]. + pub(crate) fn is_minor(&self) -> bool { + matches!(self, Self::Minor) + } +}"#, + ); + } + + #[test] + fn test_multiple_generate_enum_match_from_variant() { + check_assist( + generate_enum_match_method, + r#" +enum Variant { + Undefined, + Minor, + Major$0, +} + +impl Variant { + /// Returns `true` if the variant is [`Minor`]. + fn is_minor(&self) -> bool { + matches!(self, Self::Minor) + } +}"#, + r#"enum Variant { + Undefined, + Minor, + Major, +} + +impl Variant { + /// Returns `true` if the variant is [`Minor`]. + fn is_minor(&self) -> bool { + matches!(self, Self::Minor) + } + + /// Returns `true` if the variant is [`Major`]. + fn is_major(&self) -> bool { + matches!(self, Self::Major) + } +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_from_impl_for_enum.rs b/crates/ide_assists/src/handlers/generate_from_impl_for_enum.rs new file mode 100644 index 000000000..d9388a737 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_from_impl_for_enum.rs @@ -0,0 +1,268 @@ +use ide_db::helpers::FamousDefs; +use ide_db::RootDatabase; +use syntax::ast::{self, AstNode, NameOwner}; +use test_utils::mark; + +use crate::{utils::generate_trait_impl_text, AssistContext, AssistId, AssistKind, Assists}; + +// Assist: generate_from_impl_for_enum +// +// Adds a From impl for an enum variant with one tuple field. +// +// ``` +// enum A { $0One(u32) } +// ``` +// -> +// ``` +// enum A { One(u32) } +// +// impl From for A { +// fn from(v: u32) -> Self { +// Self::One(v) +// } +// } +// ``` +pub(crate) fn generate_from_impl_for_enum(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let variant = ctx.find_node_at_offset::()?; + let variant_name = variant.name()?; + let enum_ = ast::Adt::Enum(variant.parent_enum()); + let (field_name, field_type) = match variant.kind() { + ast::StructKind::Tuple(field_list) => { + if field_list.fields().count() != 1 { + return None; + } + (None, field_list.fields().next()?.ty()?) + } + ast::StructKind::Record(field_list) => { + if field_list.fields().count() != 1 { + return None; + } + let field = field_list.fields().next()?; + (Some(field.name()?), field.ty()?) + } + ast::StructKind::Unit => return None, + }; + + if existing_from_impl(&ctx.sema, &variant).is_some() { + mark::hit!(test_add_from_impl_already_exists); + return None; + } + + let target = variant.syntax().text_range(); + acc.add( + AssistId("generate_from_impl_for_enum", AssistKind::Generate), + "Generate `From` impl for this enum variant", + target, + |edit| { + let start_offset = variant.parent_enum().syntax().text_range().end(); + let from_trait = format!("From<{}>", field_type.syntax()); + let impl_code = if let Some(name) = field_name { + format!( + r#" fn from({0}: {1}) -> Self {{ + Self::{2} {{ {0} }} + }}"#, + name.text(), + field_type.syntax(), + variant_name, + ) + } else { + format!( + r#" fn from(v: {}) -> Self {{ + Self::{}(v) + }}"#, + field_type.syntax(), + variant_name, + ) + }; + let from_impl = generate_trait_impl_text(&enum_, &from_trait, &impl_code); + edit.insert(start_offset, from_impl); + }, + ) +} + +fn existing_from_impl( + sema: &'_ hir::Semantics<'_, RootDatabase>, + variant: &ast::Variant, +) -> Option<()> { + let variant = sema.to_def(variant)?; + let enum_ = variant.parent_enum(sema.db); + let krate = enum_.module(sema.db).krate(); + + let from_trait = FamousDefs(sema, Some(krate)).core_convert_From()?; + + let enum_type = enum_.ty(sema.db); + + let wrapped_type = variant.fields(sema.db).get(0)?.signature_ty(sema.db); + + if enum_type.impls_trait(sema.db, from_trait, &[wrapped_type]) { + Some(()) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn test_generate_from_impl_for_enum() { + check_assist( + generate_from_impl_for_enum, + "enum A { $0One(u32) }", + r#"enum A { One(u32) } + +impl From for A { + fn from(v: u32) -> Self { + Self::One(v) + } +}"#, + ); + } + + #[test] + fn test_generate_from_impl_for_enum_complicated_path() { + check_assist( + generate_from_impl_for_enum, + r#"enum A { $0One(foo::bar::baz::Boo) }"#, + r#"enum A { One(foo::bar::baz::Boo) } + +impl From for A { + fn from(v: foo::bar::baz::Boo) -> Self { + Self::One(v) + } +}"#, + ); + } + + fn check_not_applicable(ra_fixture: &str) { + let fixture = + format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE); + check_assist_not_applicable(generate_from_impl_for_enum, &fixture) + } + + #[test] + fn test_add_from_impl_no_element() { + check_not_applicable("enum A { $0One }"); + } + + #[test] + fn test_add_from_impl_more_than_one_element_in_tuple() { + check_not_applicable("enum A { $0One(u32, String) }"); + } + + #[test] + fn test_add_from_impl_struct_variant() { + check_assist( + generate_from_impl_for_enum, + "enum A { $0One { x: u32 } }", + r#"enum A { One { x: u32 } } + +impl From for A { + fn from(x: u32) -> Self { + Self::One { x } + } +}"#, + ); + } + + #[test] + fn test_add_from_impl_already_exists() { + mark::check!(test_add_from_impl_already_exists); + check_not_applicable( + r#" +enum A { $0One(u32), } + +impl From for A { + fn from(v: u32) -> Self { + Self::One(v) + } +} +"#, + ); + } + + #[test] + fn test_add_from_impl_different_variant_impl_exists() { + check_assist( + generate_from_impl_for_enum, + r#"enum A { $0One(u32), Two(String), } + +impl From for A { + fn from(v: String) -> Self { + A::Two(v) + } +} + +pub trait From { + fn from(T) -> Self; +}"#, + r#"enum A { One(u32), Two(String), } + +impl From for A { + fn from(v: u32) -> Self { + Self::One(v) + } +} + +impl From for A { + fn from(v: String) -> Self { + A::Two(v) + } +} + +pub trait From { + fn from(T) -> Self; +}"#, + ); + } + + #[test] + fn test_add_from_impl_static_str() { + check_assist( + generate_from_impl_for_enum, + "enum A { $0One(&'static str) }", + r#"enum A { One(&'static str) } + +impl From<&'static str> for A { + fn from(v: &'static str) -> Self { + Self::One(v) + } +}"#, + ); + } + + #[test] + fn test_add_from_impl_generic_enum() { + check_assist( + generate_from_impl_for_enum, + "enum Generic { $0One(T), Two(U) }", + r#"enum Generic { One(T), Two(U) } + +impl From for Generic { + fn from(v: T) -> Self { + Self::One(v) + } +}"#, + ); + } + + #[test] + fn test_add_from_impl_with_lifetime() { + check_assist( + generate_from_impl_for_enum, + "enum Generic<'a> { $0One(&'a i32) }", + r#"enum Generic<'a> { One(&'a i32) } + +impl<'a> From<&'a i32> for Generic<'a> { + fn from(v: &'a i32) -> Self { + Self::One(v) + } +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_function.rs b/crates/ide_assists/src/handlers/generate_function.rs new file mode 100644 index 000000000..959824981 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_function.rs @@ -0,0 +1,1071 @@ +use hir::HirDisplay; +use ide_db::{base_db::FileId, helpers::SnippetCap}; +use rustc_hash::{FxHashMap, FxHashSet}; +use syntax::{ + ast::{ + self, + edit::{AstNodeEdit, IndentLevel}, + make, ArgListOwner, AstNode, ModuleItemOwner, + }, + SyntaxKind, SyntaxNode, TextSize, +}; + +use crate::{ + utils::{render_snippet, Cursor}, + AssistContext, AssistId, AssistKind, Assists, +}; + +// Assist: generate_function +// +// Adds a stub function with a signature matching the function under the cursor. +// +// ``` +// struct Baz; +// fn baz() -> Baz { Baz } +// fn foo() { +// bar$0("", baz()); +// } +// +// ``` +// -> +// ``` +// struct Baz; +// fn baz() -> Baz { Baz } +// fn foo() { +// bar("", baz()); +// } +// +// fn bar(arg: &str, baz: Baz) ${0:-> ()} { +// todo!() +// } +// +// ``` +pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let path_expr: ast::PathExpr = ctx.find_node_at_offset()?; + let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?; + let path = path_expr.path()?; + + if ctx.sema.resolve_path(&path).is_some() { + // The function call already resolves, no need to add a function + return None; + } + + let target_module = match path.qualifier() { + Some(qualifier) => match ctx.sema.resolve_path(&qualifier) { + Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module), + _ => return None, + }, + None => None, + }; + + let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?; + + let target = call.syntax().text_range(); + acc.add( + AssistId("generate_function", AssistKind::Generate), + format!("Generate `{}` function", function_builder.fn_name), + target, + |builder| { + let function_template = function_builder.render(); + builder.edit_file(function_template.file); + let new_fn = function_template.to_string(ctx.config.snippet_cap); + match ctx.config.snippet_cap { + Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn), + None => builder.insert(function_template.insert_offset, new_fn), + } + }, + ) +} + +struct FunctionTemplate { + insert_offset: TextSize, + leading_ws: String, + fn_def: ast::Fn, + ret_type: ast::RetType, + trailing_ws: String, + file: FileId, +} + +impl FunctionTemplate { + fn to_string(&self, cap: Option) -> String { + let f = match cap { + Some(cap) => { + render_snippet(cap, self.fn_def.syntax(), Cursor::Replace(self.ret_type.syntax())) + } + None => self.fn_def.to_string(), + }; + format!("{}{}{}", self.leading_ws, f, self.trailing_ws) + } +} + +struct FunctionBuilder { + target: GeneratedFunctionTarget, + fn_name: ast::Name, + type_params: Option, + params: ast::ParamList, + file: FileId, + needs_pub: bool, +} + +impl FunctionBuilder { + /// Prepares a generated function that matches `call`. + /// The function is generated in `target_module` or next to `call` + fn from_call( + ctx: &AssistContext, + call: &ast::CallExpr, + path: &ast::Path, + target_module: Option, + ) -> Option { + let mut file = ctx.frange.file_id; + let target = match &target_module { + Some(target_module) => { + let module_source = target_module.definition_source(ctx.db()); + let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?; + file = in_file; + target + } + None => next_space_for_fn_after_call_site(&call)?, + }; + let needs_pub = target_module.is_some(); + let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; + let fn_name = fn_name(&path)?; + let (type_params, params) = fn_args(ctx, target_module, &call)?; + + Some(Self { target, fn_name, type_params, params, file, needs_pub }) + } + + fn render(self) -> FunctionTemplate { + let placeholder_expr = make::expr_todo(); + let fn_body = make::block_expr(vec![], Some(placeholder_expr)); + let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None }; + let mut fn_def = make::fn_( + visibility, + self.fn_name, + self.type_params, + self.params, + fn_body, + Some(make::ret_type(make::ty_unit())), + ); + let leading_ws; + let trailing_ws; + + let insert_offset = match self.target { + GeneratedFunctionTarget::BehindItem(it) => { + let indent = IndentLevel::from_node(&it); + leading_ws = format!("\n\n{}", indent); + fn_def = fn_def.indent(indent); + trailing_ws = String::new(); + it.text_range().end() + } + GeneratedFunctionTarget::InEmptyItemList(it) => { + let indent = IndentLevel::from_node(&it); + leading_ws = format!("\n{}", indent + 1); + fn_def = fn_def.indent(indent + 1); + trailing_ws = format!("\n{}", indent); + it.text_range().start() + TextSize::of('{') + } + }; + + FunctionTemplate { + insert_offset, + leading_ws, + ret_type: fn_def.ret_type().unwrap(), + fn_def, + trailing_ws, + file: self.file, + } + } +} + +enum GeneratedFunctionTarget { + BehindItem(SyntaxNode), + InEmptyItemList(SyntaxNode), +} + +impl GeneratedFunctionTarget { + fn syntax(&self) -> &SyntaxNode { + match self { + GeneratedFunctionTarget::BehindItem(it) => it, + GeneratedFunctionTarget::InEmptyItemList(it) => it, + } + } +} + +fn fn_name(call: &ast::Path) -> Option { + let name = call.segment()?.syntax().to_string(); + Some(make::name(&name)) +} + +/// Computes the type variables and arguments required for the generated function +fn fn_args( + ctx: &AssistContext, + target_module: hir::Module, + call: &ast::CallExpr, +) -> Option<(Option, ast::ParamList)> { + let mut arg_names = Vec::new(); + let mut arg_types = Vec::new(); + for arg in call.arg_list()?.args() { + arg_names.push(match fn_arg_name(&arg) { + Some(name) => name, + None => String::from("arg"), + }); + arg_types.push(match fn_arg_type(ctx, target_module, &arg) { + Some(ty) => ty, + None => String::from("()"), + }); + } + deduplicate_arg_names(&mut arg_names); + let params = arg_names + .into_iter() + .zip(arg_types) + .map(|(name, ty)| make::param(make::ident_pat(make::name(&name)).into(), make::ty(&ty))); + Some((None, make::param_list(None, params))) +} + +/// Makes duplicate argument names unique by appending incrementing numbers. +/// +/// ``` +/// let mut names: Vec = +/// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()]; +/// deduplicate_arg_names(&mut names); +/// let expected: Vec = +/// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()]; +/// assert_eq!(names, expected); +/// ``` +fn deduplicate_arg_names(arg_names: &mut Vec) { + let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| { + *m.entry(name).or_insert(0) += 1; + m + }); + let duplicate_arg_names: FxHashSet = arg_name_counts + .into_iter() + .filter(|(_, count)| *count >= 2) + .map(|(name, _)| name.clone()) + .collect(); + + let mut counter_per_name = FxHashMap::default(); + for arg_name in arg_names.iter_mut() { + if duplicate_arg_names.contains(arg_name) { + let counter = counter_per_name.entry(arg_name.clone()).or_insert(1); + arg_name.push('_'); + arg_name.push_str(&counter.to_string()); + *counter += 1; + } + } +} + +fn fn_arg_name(fn_arg: &ast::Expr) -> Option { + match fn_arg { + ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?), + _ => Some( + fn_arg + .syntax() + .descendants() + .filter(|d| ast::NameRef::can_cast(d.kind())) + .last()? + .to_string(), + ), + } +} + +fn fn_arg_type( + ctx: &AssistContext, + target_module: hir::Module, + fn_arg: &ast::Expr, +) -> Option { + let ty = ctx.sema.type_of_expr(fn_arg)?; + if ty.is_unknown() { + return None; + } + + if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) { + Some(rendered) + } else { + None + } +} + +/// Returns the position inside the current mod or file +/// directly after the current block +/// We want to write the generated function directly after +/// fns, impls or macro calls, but inside mods +fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option { + let mut ancestors = expr.syntax().ancestors().peekable(); + let mut last_ancestor: Option = None; + while let Some(next_ancestor) = ancestors.next() { + match next_ancestor.kind() { + SyntaxKind::SOURCE_FILE => { + break; + } + SyntaxKind::ITEM_LIST => { + if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) { + break; + } + } + _ => {} + } + last_ancestor = Some(next_ancestor); + } + last_ancestor.map(GeneratedFunctionTarget::BehindItem) +} + +fn next_space_for_fn_in_module( + db: &dyn hir::db::AstDatabase, + module_source: &hir::InFile, +) -> Option<(FileId, GeneratedFunctionTarget)> { + let file = module_source.file_id.original_file(db); + let assist_item = match &module_source.value { + hir::ModuleSource::SourceFile(it) => { + if let Some(last_item) = it.items().last() { + GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) + } else { + GeneratedFunctionTarget::BehindItem(it.syntax().clone()) + } + } + hir::ModuleSource::Module(it) => { + if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) { + GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) + } else { + GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone()) + } + } + hir::ModuleSource::BlockExpr(it) => { + if let Some(last_item) = + it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last() + { + GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) + } else { + GeneratedFunctionTarget::InEmptyItemList(it.syntax().clone()) + } + } + }; + Some((file, assist_item)) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn add_function_with_no_args() { + check_assist( + generate_function, + r" +fn foo() { + bar$0(); +} +", + r" +fn foo() { + bar(); +} + +fn bar() ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_from_method() { + // This ensures that the function is correctly generated + // in the next outer mod or file + check_assist( + generate_function, + r" +impl Foo { + fn foo() { + bar$0(); + } +} +", + r" +impl Foo { + fn foo() { + bar(); + } +} + +fn bar() ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_directly_after_current_block() { + // The new fn should not be created at the end of the file or module + check_assist( + generate_function, + r" +fn foo1() { + bar$0(); +} + +fn foo2() {} +", + r" +fn foo1() { + bar(); +} + +fn bar() ${0:-> ()} { + todo!() +} + +fn foo2() {} +", + ) + } + + #[test] + fn add_function_with_no_args_in_same_module() { + check_assist( + generate_function, + r" +mod baz { + fn foo() { + bar$0(); + } +} +", + r" +mod baz { + fn foo() { + bar(); + } + + fn bar() ${0:-> ()} { + todo!() + } +} +", + ) + } + + #[test] + fn add_function_with_function_call_arg() { + check_assist( + generate_function, + r" +struct Baz; +fn baz() -> Baz { todo!() } +fn foo() { + bar$0(baz()); +} +", + r" +struct Baz; +fn baz() -> Baz { todo!() } +fn foo() { + bar(baz()); +} + +fn bar(baz: Baz) ${0:-> ()} { + todo!() +} +", + ); + } + + #[test] + fn add_function_with_method_call_arg() { + check_assist( + generate_function, + r" +struct Baz; +impl Baz { + fn foo(&self) -> Baz { + ba$0r(self.baz()) + } + fn baz(&self) -> Baz { + Baz + } +} +", + r" +struct Baz; +impl Baz { + fn foo(&self) -> Baz { + bar(self.baz()) + } + fn baz(&self) -> Baz { + Baz + } +} + +fn bar(baz: Baz) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_with_string_literal_arg() { + check_assist( + generate_function, + r#" +fn foo() { + $0bar("bar") +} +"#, + r#" +fn foo() { + bar("bar") +} + +fn bar(arg: &str) ${0:-> ()} { + todo!() +} +"#, + ) + } + + #[test] + fn add_function_with_char_literal_arg() { + check_assist( + generate_function, + r#" +fn foo() { + $0bar('x') +} +"#, + r#" +fn foo() { + bar('x') +} + +fn bar(arg: char) ${0:-> ()} { + todo!() +} +"#, + ) + } + + #[test] + fn add_function_with_int_literal_arg() { + check_assist( + generate_function, + r" +fn foo() { + $0bar(42) +} +", + r" +fn foo() { + bar(42) +} + +fn bar(arg: i32) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_with_cast_int_literal_arg() { + check_assist( + generate_function, + r" +fn foo() { + $0bar(42 as u8) +} +", + r" +fn foo() { + bar(42 as u8) +} + +fn bar(arg: u8) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn name_of_cast_variable_is_used() { + // Ensures that the name of the cast type isn't used + // in the generated function signature. + check_assist( + generate_function, + r" +fn foo() { + let x = 42; + bar$0(x as u8) +} +", + r" +fn foo() { + let x = 42; + bar(x as u8) +} + +fn bar(x: u8) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_with_variable_arg() { + check_assist( + generate_function, + r" +fn foo() { + let worble = (); + $0bar(worble) +} +", + r" +fn foo() { + let worble = (); + bar(worble) +} + +fn bar(worble: ()) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_with_impl_trait_arg() { + check_assist( + generate_function, + r" +trait Foo {} +fn foo() -> impl Foo { + todo!() +} +fn baz() { + $0bar(foo()) +} +", + r" +trait Foo {} +fn foo() -> impl Foo { + todo!() +} +fn baz() { + bar(foo()) +} + +fn bar(foo: impl Foo) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn borrowed_arg() { + check_assist( + generate_function, + r" +struct Baz; +fn baz() -> Baz { todo!() } + +fn foo() { + bar$0(&baz()) +} +", + r" +struct Baz; +fn baz() -> Baz { todo!() } + +fn foo() { + bar(&baz()) +} + +fn bar(baz: &Baz) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_with_qualified_path_arg() { + check_assist( + generate_function, + r" +mod Baz { + pub struct Bof; + pub fn baz() -> Bof { Bof } +} +fn foo() { + $0bar(Baz::baz()) +} +", + r" +mod Baz { + pub struct Bof; + pub fn baz() -> Bof { Bof } +} +fn foo() { + bar(Baz::baz()) +} + +fn bar(baz: Baz::Bof) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + #[ignore] + // FIXME fix printing the generics of a `Ty` to make this test pass + fn add_function_with_generic_arg() { + check_assist( + generate_function, + r" +fn foo(t: T) { + $0bar(t) +} +", + r" +fn foo(t: T) { + bar(t) +} + +fn bar(t: T) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + #[ignore] + // FIXME Fix function type printing to make this test pass + fn add_function_with_fn_arg() { + check_assist( + generate_function, + r" +struct Baz; +impl Baz { + fn new() -> Self { Baz } +} +fn foo() { + $0bar(Baz::new); +} +", + r" +struct Baz; +impl Baz { + fn new() -> Self { Baz } +} +fn foo() { + bar(Baz::new); +} + +fn bar(arg: fn() -> Baz) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + #[ignore] + // FIXME Fix closure type printing to make this test pass + fn add_function_with_closure_arg() { + check_assist( + generate_function, + r" +fn foo() { + let closure = |x: i64| x - 1; + $0bar(closure) +} +", + r" +fn foo() { + let closure = |x: i64| x - 1; + bar(closure) +} + +fn bar(closure: impl Fn(i64) -> i64) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn unresolveable_types_default_to_unit() { + check_assist( + generate_function, + r" +fn foo() { + $0bar(baz) +} +", + r" +fn foo() { + bar(baz) +} + +fn bar(baz: ()) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn arg_names_dont_overlap() { + check_assist( + generate_function, + r" +struct Baz; +fn baz() -> Baz { Baz } +fn foo() { + $0bar(baz(), baz()) +} +", + r" +struct Baz; +fn baz() -> Baz { Baz } +fn foo() { + bar(baz(), baz()) +} + +fn bar(baz_1: Baz, baz_2: Baz) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn arg_name_counters_start_at_1_per_name() { + check_assist( + generate_function, + r#" +struct Baz; +fn baz() -> Baz { Baz } +fn foo() { + $0bar(baz(), baz(), "foo", "bar") +} +"#, + r#" +struct Baz; +fn baz() -> Baz { Baz } +fn foo() { + bar(baz(), baz(), "foo", "bar") +} + +fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) ${0:-> ()} { + todo!() +} +"#, + ) + } + + #[test] + fn add_function_in_module() { + check_assist( + generate_function, + r" +mod bar {} + +fn foo() { + bar::my_fn$0() +} +", + r" +mod bar { + pub(crate) fn my_fn() ${0:-> ()} { + todo!() + } +} + +fn foo() { + bar::my_fn() +} +", + ) + } + + #[test] + #[ignore] + // Ignored until local imports are supported. + // See https://github.com/rust-analyzer/rust-analyzer/issues/1165 + fn qualified_path_uses_correct_scope() { + check_assist( + generate_function, + " +mod foo { + pub struct Foo; +} +fn bar() { + use foo::Foo; + let foo = Foo; + baz$0(foo) +} +", + " +mod foo { + pub struct Foo; +} +fn bar() { + use foo::Foo; + let foo = Foo; + baz(foo) +} + +fn baz(foo: foo::Foo) ${0:-> ()} { + todo!() +} +", + ) + } + + #[test] + fn add_function_in_module_containing_other_items() { + check_assist( + generate_function, + r" +mod bar { + fn something_else() {} +} + +fn foo() { + bar::my_fn$0() +} +", + r" +mod bar { + fn something_else() {} + + pub(crate) fn my_fn() ${0:-> ()} { + todo!() + } +} + +fn foo() { + bar::my_fn() +} +", + ) + } + + #[test] + fn add_function_in_nested_module() { + check_assist( + generate_function, + r" +mod bar { + mod baz {} +} + +fn foo() { + bar::baz::my_fn$0() +} +", + r" +mod bar { + mod baz { + pub(crate) fn my_fn() ${0:-> ()} { + todo!() + } + } +} + +fn foo() { + bar::baz::my_fn() +} +", + ) + } + + #[test] + fn add_function_in_another_file() { + check_assist( + generate_function, + r" +//- /main.rs +mod foo; + +fn main() { + foo::bar$0() +} +//- /foo.rs +", + r" + + +pub(crate) fn bar() ${0:-> ()} { + todo!() +}", + ) + } + + #[test] + fn add_function_not_applicable_if_function_already_exists() { + check_assist_not_applicable( + generate_function, + r" +fn foo() { + bar$0(); +} + +fn bar() {} +", + ) + } + + #[test] + fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() { + check_assist_not_applicable( + // bar is resolved, but baz isn't. + // The assist is only active if the cursor is on an unresolved path, + // but the assist should only be offered if the path is a function call. + generate_function, + r" +fn foo() { + bar(b$0az); +} + +fn bar(baz: ()) {} +", + ) + } + + #[test] + #[ignore] + fn create_method_with_no_args() { + check_assist( + generate_function, + r" +struct Foo; +impl Foo { + fn foo(&self) { + self.bar()$0; + } +} + ", + r" +struct Foo; +impl Foo { + fn foo(&self) { + self.bar(); + } + fn bar(&self) { + todo!(); + } +} + ", + ) + } +} diff --git a/crates/ide_assists/src/handlers/generate_getter.rs b/crates/ide_assists/src/handlers/generate_getter.rs new file mode 100644 index 000000000..df7d1bb95 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_getter.rs @@ -0,0 +1,192 @@ +use stdx::{format_to, to_lower_snake_case}; +use syntax::ast::{self, AstNode, NameOwner, VisibilityOwner}; + +use crate::{ + utils::{find_impl_block_end, find_struct_impl, generate_impl_text}, + AssistContext, AssistId, AssistKind, Assists, GroupLabel, +}; + +// Assist: generate_getter +// +// Generate a getter method. +// +// ``` +// struct Person { +// nam$0e: String, +// } +// ``` +// -> +// ``` +// struct Person { +// name: String, +// } +// +// impl Person { +// /// Get a reference to the person's name. +// fn name(&self) -> &String { +// &self.name +// } +// } +// ``` +pub(crate) fn generate_getter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let strukt = ctx.find_node_at_offset::()?; + let field = ctx.find_node_at_offset::()?; + + let strukt_name = strukt.name()?; + let field_name = field.name()?; + let field_ty = field.ty()?; + + // Return early if we've found an existing fn + let fn_name = to_lower_snake_case(&field_name.to_string()); + let impl_def = find_struct_impl(&ctx, &ast::Adt::Struct(strukt.clone()), fn_name.as_str())?; + + let target = field.syntax().text_range(); + acc.add_group( + &GroupLabel("Generate getter/setter".to_owned()), + AssistId("generate_getter", AssistKind::Generate), + "Generate a getter method", + target, + |builder| { + let mut buf = String::with_capacity(512); + + let fn_name_spaced = fn_name.replace('_', " "); + let strukt_name_spaced = + to_lower_snake_case(&strukt_name.to_string()).replace('_', " "); + + if impl_def.is_some() { + buf.push('\n'); + } + + let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v)); + format_to!( + buf, + " /// Get a reference to the {}'s {}. + {}fn {}(&self) -> &{} {{ + &self.{} + }}", + strukt_name_spaced, + fn_name_spaced, + vis, + fn_name, + field_ty, + fn_name, + ); + + let start_offset = impl_def + .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf)) + .unwrap_or_else(|| { + buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf); + strukt.syntax().text_range().end() + }); + + builder.insert(start_offset, buf); + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + fn check_not_applicable(ra_fixture: &str) { + check_assist_not_applicable(generate_getter, ra_fixture) + } + + #[test] + fn test_generate_getter_from_field() { + check_assist( + generate_getter, + r#" +struct Context { + dat$0a: T, +}"#, + r#" +struct Context { + data: T, +} + +impl Context { + /// Get a reference to the context's data. + fn data(&self) -> &T { + &self.data + } +}"#, + ); + } + + #[test] + fn test_generate_getter_already_implemented() { + check_not_applicable( + r#" +struct Context { + dat$0a: T, +} + +impl Context { + fn data(&self) -> &T { + &self.data + } +}"#, + ); + } + + #[test] + fn test_generate_getter_from_field_with_visibility_marker() { + check_assist( + generate_getter, + r#" +pub(crate) struct Context { + dat$0a: T, +}"#, + r#" +pub(crate) struct Context { + data: T, +} + +impl Context { + /// Get a reference to the context's data. + pub(crate) fn data(&self) -> &T { + &self.data + } +}"#, + ); + } + + #[test] + fn test_multiple_generate_getter() { + check_assist( + generate_getter, + r#" +struct Context { + data: T, + cou$0nt: usize, +} + +impl Context { + /// Get a reference to the context's data. + fn data(&self) -> &T { + &self.data + } +}"#, + r#" +struct Context { + data: T, + count: usize, +} + +impl Context { + /// Get a reference to the context's data. + fn data(&self) -> &T { + &self.data + } + + /// Get a reference to the context's count. + fn count(&self) -> &usize { + &self.count + } +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_getter_mut.rs b/crates/ide_assists/src/handlers/generate_getter_mut.rs new file mode 100644 index 000000000..821c2eed5 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_getter_mut.rs @@ -0,0 +1,195 @@ +use stdx::{format_to, to_lower_snake_case}; +use syntax::ast::{self, AstNode, NameOwner, VisibilityOwner}; + +use crate::{ + utils::{find_impl_block_end, find_struct_impl, generate_impl_text}, + AssistContext, AssistId, AssistKind, Assists, GroupLabel, +}; + +// Assist: generate_getter_mut +// +// Generate a mut getter method. +// +// ``` +// struct Person { +// nam$0e: String, +// } +// ``` +// -> +// ``` +// struct Person { +// name: String, +// } +// +// impl Person { +// /// Get a mutable reference to the person's name. +// fn name_mut(&mut self) -> &mut String { +// &mut self.name +// } +// } +// ``` +pub(crate) fn generate_getter_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let strukt = ctx.find_node_at_offset::()?; + let field = ctx.find_node_at_offset::()?; + + let strukt_name = strukt.name()?; + let field_name = field.name()?; + let field_ty = field.ty()?; + + // Return early if we've found an existing fn + let fn_name = to_lower_snake_case(&field_name.to_string()); + let impl_def = find_struct_impl( + &ctx, + &ast::Adt::Struct(strukt.clone()), + format!("{}_mut", fn_name).as_str(), + )?; + + let target = field.syntax().text_range(); + acc.add_group( + &GroupLabel("Generate getter/setter".to_owned()), + AssistId("generate_getter_mut", AssistKind::Generate), + "Generate a mut getter method", + target, + |builder| { + let mut buf = String::with_capacity(512); + let fn_name_spaced = fn_name.replace('_', " "); + let strukt_name_spaced = + to_lower_snake_case(&strukt_name.to_string()).replace('_', " "); + + if impl_def.is_some() { + buf.push('\n'); + } + + let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v)); + format_to!( + buf, + " /// Get a mutable reference to the {}'s {}. + {}fn {}_mut(&mut self) -> &mut {} {{ + &mut self.{} + }}", + strukt_name_spaced, + fn_name_spaced, + vis, + fn_name, + field_ty, + fn_name, + ); + + let start_offset = impl_def + .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf)) + .unwrap_or_else(|| { + buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf); + strukt.syntax().text_range().end() + }); + + builder.insert(start_offset, buf); + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + fn check_not_applicable(ra_fixture: &str) { + check_assist_not_applicable(generate_getter_mut, ra_fixture) + } + + #[test] + fn test_generate_getter_mut_from_field() { + check_assist( + generate_getter_mut, + r#" +struct Context { + dat$0a: T, +}"#, + r#" +struct Context { + data: T, +} + +impl Context { + /// Get a mutable reference to the context's data. + fn data_mut(&mut self) -> &mut T { + &mut self.data + } +}"#, + ); + } + + #[test] + fn test_generate_getter_mut_already_implemented() { + check_not_applicable( + r#" +struct Context { + dat$0a: T, +} + +impl Context { + fn data_mut(&mut self) -> &mut T { + &mut self.data + } +}"#, + ); + } + + #[test] + fn test_generate_getter_mut_from_field_with_visibility_marker() { + check_assist( + generate_getter_mut, + r#" +pub(crate) struct Context { + dat$0a: T, +}"#, + r#" +pub(crate) struct Context { + data: T, +} + +impl Context { + /// Get a mutable reference to the context's data. + pub(crate) fn data_mut(&mut self) -> &mut T { + &mut self.data + } +}"#, + ); + } + + #[test] + fn test_multiple_generate_getter_mut() { + check_assist( + generate_getter_mut, + r#" +struct Context { + data: T, + cou$0nt: usize, +} + +impl Context { + /// Get a mutable reference to the context's data. + fn data_mut(&mut self) -> &mut T { + &mut self.data + } +}"#, + r#" +struct Context { + data: T, + count: usize, +} + +impl Context { + /// Get a mutable reference to the context's data. + fn data_mut(&mut self) -> &mut T { + &mut self.data + } + + /// Get a mutable reference to the context's count. + fn count_mut(&mut self) -> &mut usize { + &mut self.count + } +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_impl.rs b/crates/ide_assists/src/handlers/generate_impl.rs new file mode 100644 index 000000000..a8e3c4fc2 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_impl.rs @@ -0,0 +1,166 @@ +use syntax::ast::{self, AstNode, NameOwner}; + +use crate::{utils::generate_impl_text, AssistContext, AssistId, AssistKind, Assists}; + +// Assist: generate_impl +// +// Adds a new inherent impl for a type. +// +// ``` +// struct Ctx { +// data: T,$0 +// } +// ``` +// -> +// ``` +// struct Ctx { +// data: T, +// } +// +// impl Ctx { +// $0 +// } +// ``` +pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let nominal = ctx.find_node_at_offset::()?; + let name = nominal.name()?; + let target = nominal.syntax().text_range(); + + acc.add( + AssistId("generate_impl", AssistKind::Generate), + format!("Generate impl for `{}`", name), + target, + |edit| { + let start_offset = nominal.syntax().text_range().end(); + match ctx.config.snippet_cap { + Some(cap) => { + let snippet = generate_impl_text(&nominal, " $0"); + edit.insert_snippet(cap, start_offset, snippet); + } + None => { + let snippet = generate_impl_text(&nominal, ""); + edit.insert(start_offset, snippet); + } + } + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_target}; + + use super::*; + + #[test] + fn test_add_impl() { + check_assist( + generate_impl, + "struct Foo {$0}\n", + "struct Foo {}\n\nimpl Foo {\n $0\n}\n", + ); + check_assist( + generate_impl, + "struct Foo {$0}", + "struct Foo {}\n\nimpl Foo {\n $0\n}", + ); + check_assist( + generate_impl, + "struct Foo<'a, T: Foo<'a>> {$0}", + "struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n $0\n}", + ); + check_assist( + generate_impl, + r#" + #[cfg(feature = "foo")] + struct Foo<'a, T: Foo<'a>> {$0}"#, + r#" + #[cfg(feature = "foo")] + struct Foo<'a, T: Foo<'a>> {} + + #[cfg(feature = "foo")] + impl<'a, T: Foo<'a>> Foo<'a, T> { + $0 + }"#, + ); + + check_assist( + generate_impl, + r#" + #[cfg(not(feature = "foo"))] + struct Foo<'a, T: Foo<'a>> {$0}"#, + r#" + #[cfg(not(feature = "foo"))] + struct Foo<'a, T: Foo<'a>> {} + + #[cfg(not(feature = "foo"))] + impl<'a, T: Foo<'a>> Foo<'a, T> { + $0 + }"#, + ); + + check_assist( + generate_impl, + r#" + struct Defaulted {}$0"#, + r#" + struct Defaulted {} + + impl Defaulted { + $0 + }"#, + ); + + check_assist( + generate_impl, + r#" + struct Defaulted<'a, 'b: 'a, T: Debug + Clone + 'a + 'b = String> {}$0"#, + r#" + struct Defaulted<'a, 'b: 'a, T: Debug + Clone + 'a + 'b = String> {} + + impl<'a, 'b: 'a, T: Debug + Clone + 'a + 'b> Defaulted<'a, 'b, T> { + $0 + }"#, + ); + + check_assist( + generate_impl, + r#"pub trait Trait {} +struct Struct$0 +where + T: Trait, +{ + inner: T, +}"#, + r#"pub trait Trait {} +struct Struct +where + T: Trait, +{ + inner: T, +} + +impl Struct +where + T: Trait, +{ + $0 +}"#, + ); + } + + #[test] + fn add_impl_target() { + check_assist_target( + generate_impl, + " +struct SomeThingIrrelevant; +/// Has a lifetime parameter +struct Foo<'a, T: Foo<'a>> {$0} +struct EvenMoreIrrelevant; +", + "/// Has a lifetime parameter +struct Foo<'a, T: Foo<'a>> {}", + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_new.rs b/crates/ide_assists/src/handlers/generate_new.rs new file mode 100644 index 000000000..8ce5930b7 --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_new.rs @@ -0,0 +1,315 @@ +use ast::Adt; +use itertools::Itertools; +use stdx::format_to; +use syntax::ast::{self, AstNode, NameOwner, StructKind, VisibilityOwner}; + +use crate::{ + utils::{find_impl_block_start, find_struct_impl, generate_impl_text}, + AssistContext, AssistId, AssistKind, Assists, +}; + +// Assist: generate_new +// +// Adds a new inherent impl for a type. +// +// ``` +// struct Ctx { +// data: T,$0 +// } +// ``` +// -> +// ``` +// struct Ctx { +// data: T, +// } +// +// impl Ctx { +// fn $0new(data: T) -> Self { Self { data } } +// } +// ``` +pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let strukt = ctx.find_node_at_offset::()?; + + // We want to only apply this to non-union structs with named fields + let field_list = match strukt.kind() { + StructKind::Record(named) => named, + _ => return None, + }; + + // Return early if we've found an existing new fn + let impl_def = find_struct_impl(&ctx, &Adt::Struct(strukt.clone()), "new")?; + + let target = strukt.syntax().text_range(); + acc.add(AssistId("generate_new", AssistKind::Generate), "Generate `new`", target, |builder| { + let mut buf = String::with_capacity(512); + + if impl_def.is_some() { + buf.push('\n'); + } + + let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v)); + + let params = field_list + .fields() + .filter_map(|f| Some(format!("{}: {}", f.name()?.syntax(), f.ty()?.syntax()))) + .format(", "); + let fields = field_list.fields().filter_map(|f| f.name()).format(", "); + + format_to!(buf, " {}fn new({}) -> Self {{ Self {{ {} }} }}", vis, params, fields); + + let start_offset = impl_def + .and_then(|impl_def| find_impl_block_start(impl_def, &mut buf)) + .unwrap_or_else(|| { + buf = generate_impl_text(&Adt::Struct(strukt.clone()), &buf); + strukt.syntax().text_range().end() + }); + + match ctx.config.snippet_cap { + None => builder.insert(start_offset, buf), + Some(cap) => { + buf = buf.replace("fn new", "fn $0new"); + builder.insert_snippet(cap, start_offset, buf); + } + } + }) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + #[rustfmt::skip] + fn test_generate_new() { + // Check output of generation + check_assist( + generate_new, +"struct Foo {$0}", +"struct Foo {} + +impl Foo { + fn $0new() -> Self { Self { } } +}", + ); + check_assist( + generate_new, +"struct Foo {$0}", +"struct Foo {} + +impl Foo { + fn $0new() -> Self { Self { } } +}", + ); + check_assist( + generate_new, +"struct Foo<'a, T: Foo<'a>> {$0}", +"struct Foo<'a, T: Foo<'a>> {} + +impl<'a, T: Foo<'a>> Foo<'a, T> { + fn $0new() -> Self { Self { } } +}", + ); + check_assist( + generate_new, +"struct Foo { baz: String $0}", +"struct Foo { baz: String } + +impl Foo { + fn $0new(baz: String) -> Self { Self { baz } } +}", + ); + check_assist( + generate_new, +"struct Foo { baz: String, qux: Vec $0}", +"struct Foo { baz: String, qux: Vec } + +impl Foo { + fn $0new(baz: String, qux: Vec) -> Self { Self { baz, qux } } +}", + ); + + // Check that visibility modifiers don't get brought in for fields + check_assist( + generate_new, +"struct Foo { pub baz: String, pub qux: Vec $0}", +"struct Foo { pub baz: String, pub qux: Vec } + +impl Foo { + fn $0new(baz: String, qux: Vec) -> Self { Self { baz, qux } } +}", + ); + + // Check that it reuses existing impls + check_assist( + generate_new, +"struct Foo {$0} + +impl Foo {} +", +"struct Foo {} + +impl Foo { + fn $0new() -> Self { Self { } } +} +", + ); + check_assist( + generate_new, +"struct Foo {$0} + +impl Foo { + fn qux(&self) {} +} +", +"struct Foo {} + +impl Foo { + fn $0new() -> Self { Self { } } + + fn qux(&self) {} +} +", + ); + + check_assist( + generate_new, +"struct Foo {$0} + +impl Foo { + fn qux(&self) {} + fn baz() -> i32 { + 5 + } +} +", +"struct Foo {} + +impl Foo { + fn $0new() -> Self { Self { } } + + fn qux(&self) {} + fn baz() -> i32 { + 5 + } +} +", + ); + + // Check visibility of new fn based on struct + check_assist( + generate_new, +"pub struct Foo {$0}", +"pub struct Foo {} + +impl Foo { + pub fn $0new() -> Self { Self { } } +}", + ); + check_assist( + generate_new, +"pub(crate) struct Foo {$0}", +"pub(crate) struct Foo {} + +impl Foo { + pub(crate) fn $0new() -> Self { Self { } } +}", + ); + } + + #[test] + fn generate_new_not_applicable_if_fn_exists() { + check_assist_not_applicable( + generate_new, + " +struct Foo {$0} + +impl Foo { + fn new() -> Self { + Self + } +}", + ); + + check_assist_not_applicable( + generate_new, + " +struct Foo {$0} + +impl Foo { + fn New() -> Self { + Self + } +}", + ); + } + + #[test] + fn generate_new_target() { + check_assist_target( + generate_new, + " +struct SomeThingIrrelevant; +/// Has a lifetime parameter +struct Foo<'a, T: Foo<'a>> {$0} +struct EvenMoreIrrelevant; +", + "/// Has a lifetime parameter +struct Foo<'a, T: Foo<'a>> {}", + ); + } + + #[test] + fn test_unrelated_new() { + check_assist( + generate_new, + r##" +pub struct AstId { + file_id: HirFileId, + file_ast_id: FileAstId, +} + +impl AstId { + pub fn new(file_id: HirFileId, file_ast_id: FileAstId) -> AstId { + AstId { file_id, file_ast_id } + } +} + +pub struct Source { + pub file_id: HirFileId,$0 + pub ast: T, +} + +impl Source { + pub fn map U, U>(self, f: F) -> Source { + Source { file_id: self.file_id, ast: f(self.ast) } + } +}"##, + r##" +pub struct AstId { + file_id: HirFileId, + file_ast_id: FileAstId, +} + +impl AstId { + pub fn new(file_id: HirFileId, file_ast_id: FileAstId) -> AstId { + AstId { file_id, file_ast_id } + } +} + +pub struct Source { + pub file_id: HirFileId, + pub ast: T, +} + +impl Source { + pub fn $0new(file_id: HirFileId, ast: T) -> Self { Self { file_id, ast } } + + pub fn map U, U>(self, f: F) -> Source { + Source { file_id: self.file_id, ast: f(self.ast) } + } +}"##, + ); + } +} diff --git a/crates/ide_assists/src/handlers/generate_setter.rs b/crates/ide_assists/src/handlers/generate_setter.rs new file mode 100644 index 000000000..288cf745d --- /dev/null +++ b/crates/ide_assists/src/handlers/generate_setter.rs @@ -0,0 +1,198 @@ +use stdx::{format_to, to_lower_snake_case}; +use syntax::ast::{self, AstNode, NameOwner, VisibilityOwner}; + +use crate::{ + utils::{find_impl_block_end, find_struct_impl, generate_impl_text}, + AssistContext, AssistId, AssistKind, Assists, GroupLabel, +}; + +// Assist: generate_setter +// +// Generate a setter method. +// +// ``` +// struct Person { +// nam$0e: String, +// } +// ``` +// -> +// ``` +// struct Person { +// name: String, +// } +// +// impl Person { +// /// Set the person's name. +// fn set_name(&mut self, name: String) { +// self.name = name; +// } +// } +// ``` +pub(crate) fn generate_setter(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let strukt = ctx.find_node_at_offset::()?; + let field = ctx.find_node_at_offset::()?; + + let strukt_name = strukt.name()?; + let field_name = field.name()?; + let field_ty = field.ty()?; + + // Return early if we've found an existing fn + let fn_name = to_lower_snake_case(&field_name.to_string()); + let impl_def = find_struct_impl( + &ctx, + &ast::Adt::Struct(strukt.clone()), + format!("set_{}", fn_name).as_str(), + )?; + + let target = field.syntax().text_range(); + acc.add_group( + &GroupLabel("Generate getter/setter".to_owned()), + AssistId("generate_setter", AssistKind::Generate), + "Generate a setter method", + target, + |builder| { + let mut buf = String::with_capacity(512); + + let fn_name_spaced = fn_name.replace('_', " "); + let strukt_name_spaced = + to_lower_snake_case(&strukt_name.to_string()).replace('_', " "); + + if impl_def.is_some() { + buf.push('\n'); + } + + let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v)); + format_to!( + buf, + " /// Set the {}'s {}. + {}fn set_{}(&mut self, {}: {}) {{ + self.{} = {}; + }}", + strukt_name_spaced, + fn_name_spaced, + vis, + fn_name, + fn_name, + field_ty, + fn_name, + fn_name, + ); + + let start_offset = impl_def + .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf)) + .unwrap_or_else(|| { + buf = generate_impl_text(&ast::Adt::Struct(strukt.clone()), &buf); + strukt.syntax().text_range().end() + }); + + builder.insert(start_offset, buf); + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + fn check_not_applicable(ra_fixture: &str) { + check_assist_not_applicable(generate_setter, ra_fixture) + } + + #[test] + fn test_generate_setter_from_field() { + check_assist( + generate_setter, + r#" +struct Person { + dat$0a: T, +}"#, + r#" +struct Person { + data: T, +} + +impl Person { + /// Set the person's data. + fn set_data(&mut self, data: T) { + self.data = data; + } +}"#, + ); + } + + #[test] + fn test_generate_setter_already_implemented() { + check_not_applicable( + r#" +struct Person { + dat$0a: T, +} + +impl Person { + fn set_data(&mut self, data: T) { + self.data = data; + } +}"#, + ); + } + + #[test] + fn test_generate_setter_from_field_with_visibility_marker() { + check_assist( + generate_setter, + r#" +pub(crate) struct Person { + dat$0a: T, +}"#, + r#" +pub(crate) struct Person { + data: T, +} + +impl Person { + /// Set the person's data. + pub(crate) fn set_data(&mut self, data: T) { + self.data = data; + } +}"#, + ); + } + + #[test] + fn test_multiple_generate_setter() { + check_assist( + generate_setter, + r#" +struct Context { + data: T, + cou$0nt: usize, +} + +impl Context { + /// Set the context's data. + fn set_data(&mut self, data: T) { + self.data = data; + } +}"#, + r#" +struct Context { + data: T, + count: usize, +} + +impl Context { + /// Set the context's data. + fn set_data(&mut self, data: T) { + self.data = data; + } + + /// Set the context's count. + fn set_count(&mut self, count: usize) { + self.count = count; + } +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/infer_function_return_type.rs b/crates/ide_assists/src/handlers/infer_function_return_type.rs new file mode 100644 index 000000000..5279af1f3 --- /dev/null +++ b/crates/ide_assists/src/handlers/infer_function_return_type.rs @@ -0,0 +1,345 @@ +use hir::HirDisplay; +use syntax::{ast, AstNode, TextRange, TextSize}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: infer_function_return_type +// +// Adds the return type to a function or closure inferred from its tail expression if it doesn't have a return +// type specified. This assists is useable in a functions or closures tail expression or return type position. +// +// ``` +// fn foo() { 4$02i32 } +// ``` +// -> +// ``` +// fn foo() -> i32 { 42i32 } +// ``` +pub(crate) fn infer_function_return_type(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let (fn_type, tail_expr, builder_edit_pos) = extract_tail(ctx)?; + let module = ctx.sema.scope(tail_expr.syntax()).module()?; + let ty = ctx.sema.type_of_expr(&tail_expr)?; + if ty.is_unit() { + return None; + } + let ty = ty.display_source_code(ctx.db(), module.into()).ok()?; + + acc.add( + AssistId("infer_function_return_type", AssistKind::RefactorRewrite), + match fn_type { + FnType::Function => "Add this function's return type", + FnType::Closure { .. } => "Add this closure's return type", + }, + tail_expr.syntax().text_range(), + |builder| { + match builder_edit_pos { + InsertOrReplace::Insert(insert_pos) => { + builder.insert(insert_pos, &format!("-> {} ", ty)) + } + InsertOrReplace::Replace(text_range) => { + builder.replace(text_range, &format!("-> {}", ty)) + } + } + if let FnType::Closure { wrap_expr: true } = fn_type { + mark::hit!(wrap_closure_non_block_expr); + // `|x| x` becomes `|x| -> T x` which is invalid, so wrap it in a block + builder.replace(tail_expr.syntax().text_range(), &format!("{{{}}}", tail_expr)); + } + }, + ) +} + +enum InsertOrReplace { + Insert(TextSize), + Replace(TextRange), +} + +/// Check the potentially already specified return type and reject it or turn it into a builder command +/// if allowed. +fn ret_ty_to_action(ret_ty: Option, insert_pos: TextSize) -> Option { + match ret_ty { + Some(ret_ty) => match ret_ty.ty() { + Some(ast::Type::InferType(_)) | None => { + mark::hit!(existing_infer_ret_type); + mark::hit!(existing_infer_ret_type_closure); + Some(InsertOrReplace::Replace(ret_ty.syntax().text_range())) + } + _ => { + mark::hit!(existing_ret_type); + mark::hit!(existing_ret_type_closure); + None + } + }, + None => Some(InsertOrReplace::Insert(insert_pos + TextSize::from(1))), + } +} + +enum FnType { + Function, + Closure { wrap_expr: bool }, +} + +fn extract_tail(ctx: &AssistContext) -> Option<(FnType, ast::Expr, InsertOrReplace)> { + let (fn_type, tail_expr, return_type_range, action) = + if let Some(closure) = ctx.find_node_at_offset::() { + let rpipe_pos = closure.param_list()?.syntax().last_token()?.text_range().end(); + let action = ret_ty_to_action(closure.ret_type(), rpipe_pos)?; + + let body = closure.body()?; + let body_start = body.syntax().first_token()?.text_range().start(); + let (tail_expr, wrap_expr) = match body { + ast::Expr::BlockExpr(block) => (block.tail_expr()?, false), + body => (body, true), + }; + + let ret_range = TextRange::new(rpipe_pos, body_start); + (FnType::Closure { wrap_expr }, tail_expr, ret_range, action) + } else { + let func = ctx.find_node_at_offset::()?; + let rparen_pos = func.param_list()?.r_paren_token()?.text_range().end(); + let action = ret_ty_to_action(func.ret_type(), rparen_pos)?; + + let body = func.body()?; + let tail_expr = body.tail_expr()?; + + let ret_range_end = body.l_curly_token()?.text_range().start(); + let ret_range = TextRange::new(rparen_pos, ret_range_end); + (FnType::Function, tail_expr, ret_range, action) + }; + let frange = ctx.frange.range; + if return_type_range.contains_range(frange) { + mark::hit!(cursor_in_ret_position); + mark::hit!(cursor_in_ret_position_closure); + } else if tail_expr.syntax().text_range().contains_range(frange) { + mark::hit!(cursor_on_tail); + mark::hit!(cursor_on_tail_closure); + } else { + return None; + } + Some((fn_type, tail_expr, action)) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn infer_return_type_specified_inferred() { + mark::check!(existing_infer_ret_type); + check_assist( + infer_function_return_type, + r#"fn foo() -> $0_ { + 45 +}"#, + r#"fn foo() -> i32 { + 45 +}"#, + ); + } + + #[test] + fn infer_return_type_specified_inferred_closure() { + mark::check!(existing_infer_ret_type_closure); + check_assist( + infer_function_return_type, + r#"fn foo() { + || -> _ {$045}; +}"#, + r#"fn foo() { + || -> i32 {45}; +}"#, + ); + } + + #[test] + fn infer_return_type_cursor_at_return_type_pos() { + mark::check!(cursor_in_ret_position); + check_assist( + infer_function_return_type, + r#"fn foo() $0{ + 45 +}"#, + r#"fn foo() -> i32 { + 45 +}"#, + ); + } + + #[test] + fn infer_return_type_cursor_at_return_type_pos_closure() { + mark::check!(cursor_in_ret_position_closure); + check_assist( + infer_function_return_type, + r#"fn foo() { + || $045 +}"#, + r#"fn foo() { + || -> i32 {45} +}"#, + ); + } + + #[test] + fn infer_return_type() { + mark::check!(cursor_on_tail); + check_assist( + infer_function_return_type, + r#"fn foo() { + 45$0 +}"#, + r#"fn foo() -> i32 { + 45 +}"#, + ); + } + + #[test] + fn infer_return_type_nested() { + check_assist( + infer_function_return_type, + r#"fn foo() { + if true { + 3$0 + } else { + 5 + } +}"#, + r#"fn foo() -> i32 { + if true { + 3 + } else { + 5 + } +}"#, + ); + } + + #[test] + fn not_applicable_ret_type_specified() { + mark::check!(existing_ret_type); + check_assist_not_applicable( + infer_function_return_type, + r#"fn foo() -> i32 { + ( 45$0 + 32 ) * 123 +}"#, + ); + } + + #[test] + fn not_applicable_non_tail_expr() { + check_assist_not_applicable( + infer_function_return_type, + r#"fn foo() { + let x = $03; + ( 45 + 32 ) * 123 +}"#, + ); + } + + #[test] + fn not_applicable_unit_return_type() { + check_assist_not_applicable( + infer_function_return_type, + r#"fn foo() { + ($0) +}"#, + ); + } + + #[test] + fn infer_return_type_closure_block() { + mark::check!(cursor_on_tail_closure); + check_assist( + infer_function_return_type, + r#"fn foo() { + |x: i32| { + x$0 + }; +}"#, + r#"fn foo() { + |x: i32| -> i32 { + x + }; +}"#, + ); + } + + #[test] + fn infer_return_type_closure() { + check_assist( + infer_function_return_type, + r#"fn foo() { + |x: i32| { x$0 }; +}"#, + r#"fn foo() { + |x: i32| -> i32 { x }; +}"#, + ); + } + + #[test] + fn infer_return_type_closure_wrap() { + mark::check!(wrap_closure_non_block_expr); + check_assist( + infer_function_return_type, + r#"fn foo() { + |x: i32| x$0; +}"#, + r#"fn foo() { + |x: i32| -> i32 {x}; +}"#, + ); + } + + #[test] + fn infer_return_type_nested_closure() { + check_assist( + infer_function_return_type, + r#"fn foo() { + || { + if true { + 3$0 + } else { + 5 + } + } +}"#, + r#"fn foo() { + || -> i32 { + if true { + 3 + } else { + 5 + } + } +}"#, + ); + } + + #[test] + fn not_applicable_ret_type_specified_closure() { + mark::check!(existing_ret_type_closure); + check_assist_not_applicable( + infer_function_return_type, + r#"fn foo() { + || -> i32 { 3$0 } +}"#, + ); + } + + #[test] + fn not_applicable_non_tail_expr_closure() { + check_assist_not_applicable( + infer_function_return_type, + r#"fn foo() { + || -> i32 { + let x = 3$0; + 6 + } +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/inline_function.rs b/crates/ide_assists/src/handlers/inline_function.rs new file mode 100644 index 000000000..6ec99b09b --- /dev/null +++ b/crates/ide_assists/src/handlers/inline_function.rs @@ -0,0 +1,202 @@ +use ast::make; +use hir::{HasSource, PathResolution}; +use syntax::{ + ast::{self, edit::AstNodeEdit, ArgListOwner}, + AstNode, +}; +use test_utils::mark; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, AssistKind, +}; + +// Assist: inline_function +// +// Inlines a function body. +// +// ``` +// fn add(a: u32, b: u32) -> u32 { a + b } +// fn main() { +// let x = add$0(1, 2); +// } +// ``` +// -> +// ``` +// fn add(a: u32, b: u32) -> u32 { a + b } +// fn main() { +// let x = { +// let a = 1; +// let b = 2; +// a + b +// }; +// } +// ``` +pub(crate) fn inline_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let path_expr: ast::PathExpr = ctx.find_node_at_offset()?; + let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?; + let path = path_expr.path()?; + + let function = match ctx.sema.resolve_path(&path)? { + PathResolution::Def(hir::ModuleDef::Function(f)) => f, + _ => return None, + }; + + let function_source = function.source(ctx.db())?; + let arguments: Vec<_> = call.arg_list()?.args().collect(); + let parameters = function_parameter_patterns(&function_source.value)?; + + if arguments.len() != parameters.len() { + // Can't inline the function because they've passed the wrong number of + // arguments to this function + mark::hit!(inline_function_incorrect_number_of_arguments); + return None; + } + + let new_bindings = parameters.into_iter().zip(arguments); + + let body = function_source.value.body()?; + + acc.add( + AssistId("inline_function", AssistKind::RefactorInline), + format!("Inline `{}`", path), + call.syntax().text_range(), + |builder| { + let mut statements: Vec = Vec::new(); + + for (pattern, value) in new_bindings { + statements.push(make::let_stmt(pattern, Some(value)).into()); + } + + statements.extend(body.statements()); + + let original_indentation = call.indent_level(); + let replacement = make::block_expr(statements, body.tail_expr()) + .reset_indent() + .indent(original_indentation); + + builder.replace_ast(ast::Expr::CallExpr(call), ast::Expr::BlockExpr(replacement)); + }, + ) +} + +fn function_parameter_patterns(value: &ast::Fn) -> Option> { + let mut patterns = Vec::new(); + + for param in value.param_list()?.params() { + let pattern = param.pat()?; + patterns.push(pattern); + } + + Some(patterns) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn no_args_or_return_value_gets_inlined_without_block() { + check_assist( + inline_function, + r#" +fn foo() { println!("Hello, World!"); } +fn main() { + fo$0o(); +} +"#, + r#" +fn foo() { println!("Hello, World!"); } +fn main() { + { + println!("Hello, World!"); + }; +} +"#, + ); + } + + #[test] + fn args_with_side_effects() { + check_assist( + inline_function, + r#" +fn foo(name: String) { println!("Hello, {}!", name); } +fn main() { + foo$0(String::from("Michael")); +} +"#, + r#" +fn foo(name: String) { println!("Hello, {}!", name); } +fn main() { + { + let name = String::from("Michael"); + println!("Hello, {}!", name); + }; +} +"#, + ); + } + + #[test] + fn method_inlining_isnt_supported() { + check_assist_not_applicable( + inline_function, + r" +struct Foo; +impl Foo { fn bar(&self) {} } + +fn main() { Foo.bar$0(); } +", + ); + } + + #[test] + fn not_applicable_when_incorrect_number_of_parameters_are_provided() { + mark::check!(inline_function_incorrect_number_of_arguments); + check_assist_not_applicable( + inline_function, + r#" +fn add(a: u32, b: u32) -> u32 { a + b } +fn main() { let x = add$0(42); } +"#, + ); + } + + #[test] + fn function_with_multiple_statements() { + check_assist( + inline_function, + r#" +fn foo(a: u32, b: u32) -> u32 { + let x = a + b; + let y = x - b; + x * y +} + +fn main() { + let x = foo$0(1, 2); +} +"#, + r#" +fn foo(a: u32, b: u32) -> u32 { + let x = a + b; + let y = x - b; + x * y +} + +fn main() { + let x = { + let a = 1; + let b = 2; + let x = a + b; + let y = x - b; + x * y + }; +} +"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/inline_local_variable.rs b/crates/ide_assists/src/handlers/inline_local_variable.rs new file mode 100644 index 000000000..da5522670 --- /dev/null +++ b/crates/ide_assists/src/handlers/inline_local_variable.rs @@ -0,0 +1,732 @@ +use ide_db::{defs::Definition, search::FileReference}; +use rustc_hash::FxHashMap; +use syntax::{ + ast::{self, AstNode, AstToken}, + TextRange, +}; +use test_utils::mark; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, AssistKind, +}; + +// Assist: inline_local_variable +// +// Inlines local variable. +// +// ``` +// fn main() { +// let x$0 = 1 + 2; +// x * 4; +// } +// ``` +// -> +// ``` +// fn main() { +// (1 + 2) * 4; +// } +// ``` +pub(crate) fn inline_local_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let let_stmt = ctx.find_node_at_offset::()?; + let bind_pat = match let_stmt.pat()? { + ast::Pat::IdentPat(pat) => pat, + _ => return None, + }; + if bind_pat.mut_token().is_some() { + mark::hit!(test_not_inline_mut_variable); + return None; + } + if !bind_pat.syntax().text_range().contains_inclusive(ctx.offset()) { + mark::hit!(not_applicable_outside_of_bind_pat); + return None; + } + let initializer_expr = let_stmt.initializer()?; + + let def = ctx.sema.to_def(&bind_pat)?; + let def = Definition::Local(def); + let usages = def.usages(&ctx.sema).all(); + if usages.is_empty() { + mark::hit!(test_not_applicable_if_variable_unused); + return None; + }; + + let delete_range = if let Some(whitespace) = let_stmt + .syntax() + .next_sibling_or_token() + .and_then(|it| ast::Whitespace::cast(it.as_token()?.clone())) + { + TextRange::new( + let_stmt.syntax().text_range().start(), + whitespace.syntax().text_range().end(), + ) + } else { + let_stmt.syntax().text_range() + }; + + let wrap_in_parens = usages + .references + .iter() + .map(|(&file_id, refs)| { + refs.iter() + .map(|&FileReference { range, .. }| { + let usage_node = ctx + .covering_node_for_range(range) + .ancestors() + .find_map(ast::PathExpr::cast)?; + let usage_parent_option = + usage_node.syntax().parent().and_then(ast::Expr::cast); + let usage_parent = match usage_parent_option { + Some(u) => u, + None => return Some(false), + }; + + Some(!matches!( + (&initializer_expr, usage_parent), + (ast::Expr::CallExpr(_), _) + | (ast::Expr::IndexExpr(_), _) + | (ast::Expr::MethodCallExpr(_), _) + | (ast::Expr::FieldExpr(_), _) + | (ast::Expr::TryExpr(_), _) + | (ast::Expr::RefExpr(_), _) + | (ast::Expr::Literal(_), _) + | (ast::Expr::TupleExpr(_), _) + | (ast::Expr::ArrayExpr(_), _) + | (ast::Expr::ParenExpr(_), _) + | (ast::Expr::PathExpr(_), _) + | (ast::Expr::BlockExpr(_), _) + | (ast::Expr::EffectExpr(_), _) + | (_, ast::Expr::CallExpr(_)) + | (_, ast::Expr::TupleExpr(_)) + | (_, ast::Expr::ArrayExpr(_)) + | (_, ast::Expr::ParenExpr(_)) + | (_, ast::Expr::ForExpr(_)) + | (_, ast::Expr::WhileExpr(_)) + | (_, ast::Expr::BreakExpr(_)) + | (_, ast::Expr::ReturnExpr(_)) + | (_, ast::Expr::MatchExpr(_)) + )) + }) + .collect::>() + .map(|b| (file_id, b)) + }) + .collect::>>>()?; + + let init_str = initializer_expr.syntax().text().to_string(); + let init_in_paren = format!("({})", &init_str); + + let target = bind_pat.syntax().text_range(); + acc.add( + AssistId("inline_local_variable", AssistKind::RefactorInline), + "Inline variable", + target, + move |builder| { + builder.delete(delete_range); + for (file_id, references) in usages.references { + for (&should_wrap, reference) in wrap_in_parens[&file_id].iter().zip(references) { + let replacement = + if should_wrap { init_in_paren.clone() } else { init_str.clone() }; + match reference.name.as_name_ref() { + Some(name_ref) + if ast::RecordExprField::for_field_name(name_ref).is_some() => + { + mark::hit!(inline_field_shorthand); + builder.insert(reference.range.end(), format!(": {}", replacement)); + } + _ => builder.replace(reference.range, replacement), + } + } + } + }, + ) +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn test_inline_let_bind_literal_expr() { + check_assist( + inline_local_variable, + r" +fn bar(a: usize) {} +fn foo() { + let a$0 = 1; + a + 1; + if a > 10 { + } + + while a > 10 { + + } + let b = a * 10; + bar(a); +}", + r" +fn bar(a: usize) {} +fn foo() { + 1 + 1; + if 1 > 10 { + } + + while 1 > 10 { + + } + let b = 1 * 10; + bar(1); +}", + ); + } + + #[test] + fn test_inline_let_bind_bin_expr() { + check_assist( + inline_local_variable, + r" +fn bar(a: usize) {} +fn foo() { + let a$0 = 1 + 1; + a + 1; + if a > 10 { + } + + while a > 10 { + + } + let b = a * 10; + bar(a); +}", + r" +fn bar(a: usize) {} +fn foo() { + (1 + 1) + 1; + if (1 + 1) > 10 { + } + + while (1 + 1) > 10 { + + } + let b = (1 + 1) * 10; + bar(1 + 1); +}", + ); + } + + #[test] + fn test_inline_let_bind_function_call_expr() { + check_assist( + inline_local_variable, + r" +fn bar(a: usize) {} +fn foo() { + let a$0 = bar(1); + a + 1; + if a > 10 { + } + + while a > 10 { + + } + let b = a * 10; + bar(a); +}", + r" +fn bar(a: usize) {} +fn foo() { + bar(1) + 1; + if bar(1) > 10 { + } + + while bar(1) > 10 { + + } + let b = bar(1) * 10; + bar(bar(1)); +}", + ); + } + + #[test] + fn test_inline_let_bind_cast_expr() { + check_assist( + inline_local_variable, + r" +fn bar(a: usize): usize { a } +fn foo() { + let a$0 = bar(1) as u64; + a + 1; + if a > 10 { + } + + while a > 10 { + + } + let b = a * 10; + bar(a); +}", + r" +fn bar(a: usize): usize { a } +fn foo() { + (bar(1) as u64) + 1; + if (bar(1) as u64) > 10 { + } + + while (bar(1) as u64) > 10 { + + } + let b = (bar(1) as u64) * 10; + bar(bar(1) as u64); +}", + ); + } + + #[test] + fn test_inline_let_bind_block_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = { 10 + 1 }; + a + 1; + if a > 10 { + } + + while a > 10 { + + } + let b = a * 10; + bar(a); +}", + r" +fn foo() { + { 10 + 1 } + 1; + if { 10 + 1 } > 10 { + } + + while { 10 + 1 } > 10 { + + } + let b = { 10 + 1 } * 10; + bar({ 10 + 1 }); +}", + ); + } + + #[test] + fn test_inline_let_bind_paren_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = ( 10 + 1 ); + a + 1; + if a > 10 { + } + + while a > 10 { + + } + let b = a * 10; + bar(a); +}", + r" +fn foo() { + ( 10 + 1 ) + 1; + if ( 10 + 1 ) > 10 { + } + + while ( 10 + 1 ) > 10 { + + } + let b = ( 10 + 1 ) * 10; + bar(( 10 + 1 )); +}", + ); + } + + #[test] + fn test_not_inline_mut_variable() { + mark::check!(test_not_inline_mut_variable); + check_assist_not_applicable( + inline_local_variable, + r" +fn foo() { + let mut a$0 = 1 + 1; + a + 1; +}", + ); + } + + #[test] + fn test_call_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = bar(10 + 1); + let b = a * 10; + let c = a as usize; +}", + r" +fn foo() { + let b = bar(10 + 1) * 10; + let c = bar(10 + 1) as usize; +}", + ); + } + + #[test] + fn test_index_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let x = vec![1, 2, 3]; + let a$0 = x[0]; + let b = a * 10; + let c = a as usize; +}", + r" +fn foo() { + let x = vec![1, 2, 3]; + let b = x[0] * 10; + let c = x[0] as usize; +}", + ); + } + + #[test] + fn test_method_call_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let bar = vec![1]; + let a$0 = bar.len(); + let b = a * 10; + let c = a as usize; +}", + r" +fn foo() { + let bar = vec![1]; + let b = bar.len() * 10; + let c = bar.len() as usize; +}", + ); + } + + #[test] + fn test_field_expr() { + check_assist( + inline_local_variable, + r" +struct Bar { + foo: usize +} + +fn foo() { + let bar = Bar { foo: 1 }; + let a$0 = bar.foo; + let b = a * 10; + let c = a as usize; +}", + r" +struct Bar { + foo: usize +} + +fn foo() { + let bar = Bar { foo: 1 }; + let b = bar.foo * 10; + let c = bar.foo as usize; +}", + ); + } + + #[test] + fn test_try_expr() { + check_assist( + inline_local_variable, + r" +fn foo() -> Option { + let bar = Some(1); + let a$0 = bar?; + let b = a * 10; + let c = a as usize; + None +}", + r" +fn foo() -> Option { + let bar = Some(1); + let b = bar? * 10; + let c = bar? as usize; + None +}", + ); + } + + #[test] + fn test_ref_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let bar = 10; + let a$0 = &bar; + let b = a * 10; +}", + r" +fn foo() { + let bar = 10; + let b = &bar * 10; +}", + ); + } + + #[test] + fn test_tuple_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = (10, 20); + let b = a[0]; +}", + r" +fn foo() { + let b = (10, 20)[0]; +}", + ); + } + + #[test] + fn test_array_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = [1, 2, 3]; + let b = a.len(); +}", + r" +fn foo() { + let b = [1, 2, 3].len(); +}", + ); + } + + #[test] + fn test_paren() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = (10 + 20); + let b = a * 10; + let c = a as usize; +}", + r" +fn foo() { + let b = (10 + 20) * 10; + let c = (10 + 20) as usize; +}", + ); + } + + #[test] + fn test_path_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let d = 10; + let a$0 = d; + let b = a * 10; + let c = a as usize; +}", + r" +fn foo() { + let d = 10; + let b = d * 10; + let c = d as usize; +}", + ); + } + + #[test] + fn test_block_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = { 10 }; + let b = a * 10; + let c = a as usize; +}", + r" +fn foo() { + let b = { 10 } * 10; + let c = { 10 } as usize; +}", + ); + } + + #[test] + fn test_used_in_different_expr1() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = 10 + 20; + let b = a * 10; + let c = (a, 20); + let d = [a, 10]; + let e = (a); +}", + r" +fn foo() { + let b = (10 + 20) * 10; + let c = (10 + 20, 20); + let d = [10 + 20, 10]; + let e = (10 + 20); +}", + ); + } + + #[test] + fn test_used_in_for_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = vec![10, 20]; + for i in a {} +}", + r" +fn foo() { + for i in vec![10, 20] {} +}", + ); + } + + #[test] + fn test_used_in_while_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = 1 > 0; + while a {} +}", + r" +fn foo() { + while 1 > 0 {} +}", + ); + } + + #[test] + fn test_used_in_break_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = 1 + 1; + loop { + break a; + } +}", + r" +fn foo() { + loop { + break 1 + 1; + } +}", + ); + } + + #[test] + fn test_used_in_return_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = 1 > 0; + return a; +}", + r" +fn foo() { + return 1 > 0; +}", + ); + } + + #[test] + fn test_used_in_match_expr() { + check_assist( + inline_local_variable, + r" +fn foo() { + let a$0 = 1 > 0; + match a {} +}", + r" +fn foo() { + match 1 > 0 {} +}", + ); + } + + #[test] + fn inline_field_shorthand() { + mark::check!(inline_field_shorthand); + check_assist( + inline_local_variable, + r" +struct S { foo: i32} +fn main() { + let $0foo = 92; + S { foo } +} +", + r" +struct S { foo: i32} +fn main() { + S { foo: 92 } +} +", + ); + } + + #[test] + fn test_not_applicable_if_variable_unused() { + mark::check!(test_not_applicable_if_variable_unused); + check_assist_not_applicable( + inline_local_variable, + r" +fn foo() { + let $0a = 0; +} + ", + ) + } + + #[test] + fn not_applicable_outside_of_bind_pat() { + mark::check!(not_applicable_outside_of_bind_pat); + check_assist_not_applicable( + inline_local_variable, + r" +fn main() { + let x = $01 + 2; + x * 4; +} +", + ) + } +} diff --git a/crates/ide_assists/src/handlers/introduce_named_lifetime.rs b/crates/ide_assists/src/handlers/introduce_named_lifetime.rs new file mode 100644 index 000000000..02782eb6d --- /dev/null +++ b/crates/ide_assists/src/handlers/introduce_named_lifetime.rs @@ -0,0 +1,315 @@ +use rustc_hash::FxHashSet; +use syntax::{ + ast::{self, GenericParamsOwner, NameOwner}, + AstNode, TextRange, TextSize, +}; + +use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists}; + +static ASSIST_NAME: &str = "introduce_named_lifetime"; +static ASSIST_LABEL: &str = "Introduce named lifetime"; + +// Assist: introduce_named_lifetime +// +// Change an anonymous lifetime to a named lifetime. +// +// ``` +// impl Cursor<'_$0> { +// fn node(self) -> &SyntaxNode { +// match self { +// Cursor::Replace(node) | Cursor::Before(node) => node, +// } +// } +// } +// ``` +// -> +// ``` +// impl<'a> Cursor<'a> { +// fn node(self) -> &SyntaxNode { +// match self { +// Cursor::Replace(node) | Cursor::Before(node) => node, +// } +// } +// } +// ``` +// FIXME: How can we handle renaming any one of multiple anonymous lifetimes? +// FIXME: should also add support for the case fun(f: &Foo) -> &$0Foo +pub(crate) fn introduce_named_lifetime(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let lifetime = + ctx.find_node_at_offset::().filter(|lifetime| lifetime.text() == "'_")?; + if let Some(fn_def) = lifetime.syntax().ancestors().find_map(ast::Fn::cast) { + generate_fn_def_assist(acc, &fn_def, lifetime.lifetime_ident_token()?.text_range()) + } else if let Some(impl_def) = lifetime.syntax().ancestors().find_map(ast::Impl::cast) { + generate_impl_def_assist(acc, &impl_def, lifetime.lifetime_ident_token()?.text_range()) + } else { + None + } +} + +/// Generate the assist for the fn def case +fn generate_fn_def_assist( + acc: &mut Assists, + fn_def: &ast::Fn, + lifetime_loc: TextRange, +) -> Option<()> { + let param_list: ast::ParamList = fn_def.param_list()?; + let new_lifetime_param = generate_unique_lifetime_param_name(&fn_def.generic_param_list())?; + let end_of_fn_ident = fn_def.name()?.ident_token()?.text_range().end(); + let self_param = + // use the self if it's a reference and has no explicit lifetime + param_list.self_param().filter(|p| p.lifetime().is_none() && p.amp_token().is_some()); + // compute the location which implicitly has the same lifetime as the anonymous lifetime + let loc_needing_lifetime = if let Some(self_param) = self_param { + // if we have a self reference, use that + Some(self_param.name()?.syntax().text_range().start()) + } else { + // otherwise, if there's a single reference parameter without a named liftime, use that + let fn_params_without_lifetime: Vec<_> = param_list + .params() + .filter_map(|param| match param.ty() { + Some(ast::Type::RefType(ascribed_type)) if ascribed_type.lifetime().is_none() => { + Some(ascribed_type.amp_token()?.text_range().end()) + } + _ => None, + }) + .collect(); + match fn_params_without_lifetime.len() { + 1 => Some(fn_params_without_lifetime.into_iter().nth(0)?), + 0 => None, + // multiple unnnamed is invalid. assist is not applicable + _ => return None, + } + }; + acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| { + add_lifetime_param(fn_def, builder, end_of_fn_ident, new_lifetime_param); + builder.replace(lifetime_loc, format!("'{}", new_lifetime_param)); + loc_needing_lifetime.map(|loc| builder.insert(loc, format!("'{} ", new_lifetime_param))); + }) +} + +/// Generate the assist for the impl def case +fn generate_impl_def_assist( + acc: &mut Assists, + impl_def: &ast::Impl, + lifetime_loc: TextRange, +) -> Option<()> { + let new_lifetime_param = generate_unique_lifetime_param_name(&impl_def.generic_param_list())?; + let end_of_impl_kw = impl_def.impl_token()?.text_range().end(); + acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| { + add_lifetime_param(impl_def, builder, end_of_impl_kw, new_lifetime_param); + builder.replace(lifetime_loc, format!("'{}", new_lifetime_param)); + }) +} + +/// Given a type parameter list, generate a unique lifetime parameter name +/// which is not in the list +fn generate_unique_lifetime_param_name( + existing_type_param_list: &Option, +) -> Option { + match existing_type_param_list { + Some(type_params) => { + let used_lifetime_params: FxHashSet<_> = type_params + .lifetime_params() + .map(|p| p.syntax().text().to_string()[1..].to_owned()) + .collect(); + (b'a'..=b'z').map(char::from).find(|c| !used_lifetime_params.contains(&c.to_string())) + } + None => Some('a'), + } +} + +/// Add the lifetime param to `builder`. If there are type parameters in `type_params_owner`, add it to the end. Otherwise +/// add new type params brackets with the lifetime parameter at `new_type_params_loc`. +fn add_lifetime_param( + type_params_owner: &TypeParamsOwner, + builder: &mut AssistBuilder, + new_type_params_loc: TextSize, + new_lifetime_param: char, +) { + match type_params_owner.generic_param_list() { + // add the new lifetime parameter to an existing type param list + Some(type_params) => { + builder.insert( + (u32::from(type_params.syntax().text_range().end()) - 1).into(), + format!(", '{}", new_lifetime_param), + ); + } + // create a new type param list containing only the new lifetime parameter + None => { + builder.insert(new_type_params_loc, format!("<'{}>", new_lifetime_param)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{check_assist, check_assist_not_applicable}; + + #[test] + fn test_example_case() { + check_assist( + introduce_named_lifetime, + r#"impl Cursor<'_$0> { + fn node(self) -> &SyntaxNode { + match self { + Cursor::Replace(node) | Cursor::Before(node) => node, + } + } + }"#, + r#"impl<'a> Cursor<'a> { + fn node(self) -> &SyntaxNode { + match self { + Cursor::Replace(node) | Cursor::Before(node) => node, + } + } + }"#, + ); + } + + #[test] + fn test_example_case_simplified() { + check_assist( + introduce_named_lifetime, + r#"impl Cursor<'_$0> {"#, + r#"impl<'a> Cursor<'a> {"#, + ); + } + + #[test] + fn test_example_case_cursor_after_tick() { + check_assist( + introduce_named_lifetime, + r#"impl Cursor<'$0_> {"#, + r#"impl<'a> Cursor<'a> {"#, + ); + } + + #[test] + fn test_impl_with_other_type_param() { + check_assist( + introduce_named_lifetime, + "impl fmt::Display for SepByBuilder<'_$0, I> + where + I: Iterator, + I::Item: fmt::Display, + {", + "impl fmt::Display for SepByBuilder<'a, I> + where + I: Iterator, + I::Item: fmt::Display, + {", + ) + } + + #[test] + fn test_example_case_cursor_before_tick() { + check_assist( + introduce_named_lifetime, + r#"impl Cursor<$0'_> {"#, + r#"impl<'a> Cursor<'a> {"#, + ); + } + + #[test] + fn test_not_applicable_cursor_position() { + check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'_>$0 {"#); + check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor$0<'_> {"#); + } + + #[test] + fn test_not_applicable_lifetime_already_name() { + check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'a$0> {"#); + check_assist_not_applicable(introduce_named_lifetime, r#"fn my_fun<'a>() -> X<'a$0>"#); + } + + #[test] + fn test_with_type_parameter() { + check_assist( + introduce_named_lifetime, + r#"impl Cursor"#, + r#"impl Cursor"#, + ); + } + + #[test] + fn test_with_existing_lifetime_name_conflict() { + check_assist( + introduce_named_lifetime, + r#"impl<'a, 'b> Cursor<'a, 'b, '_$0>"#, + r#"impl<'a, 'b, 'c> Cursor<'a, 'b, 'c>"#, + ); + } + + #[test] + fn test_function_return_value_anon_lifetime_param() { + check_assist( + introduce_named_lifetime, + r#"fn my_fun() -> X<'_$0>"#, + r#"fn my_fun<'a>() -> X<'a>"#, + ); + } + + #[test] + fn test_function_return_value_anon_reference_lifetime() { + check_assist( + introduce_named_lifetime, + r#"fn my_fun() -> &'_$0 X"#, + r#"fn my_fun<'a>() -> &'a X"#, + ); + } + + #[test] + fn test_function_param_anon_lifetime() { + check_assist( + introduce_named_lifetime, + r#"fn my_fun(x: X<'_$0>)"#, + r#"fn my_fun<'a>(x: X<'a>)"#, + ); + } + + #[test] + fn test_function_add_lifetime_to_params() { + check_assist( + introduce_named_lifetime, + r#"fn my_fun(f: &Foo) -> X<'_$0>"#, + r#"fn my_fun<'a>(f: &'a Foo) -> X<'a>"#, + ); + } + + #[test] + fn test_function_add_lifetime_to_params_in_presence_of_other_lifetime() { + check_assist( + introduce_named_lifetime, + r#"fn my_fun<'other>(f: &Foo, b: &'other Bar) -> X<'_$0>"#, + r#"fn my_fun<'other, 'a>(f: &'a Foo, b: &'other Bar) -> X<'a>"#, + ); + } + + #[test] + fn test_function_not_applicable_without_self_and_multiple_unnamed_param_lifetimes() { + // this is not permitted under lifetime elision rules + check_assist_not_applicable( + introduce_named_lifetime, + r#"fn my_fun(f: &Foo, b: &Bar) -> X<'_$0>"#, + ); + } + + #[test] + fn test_function_add_lifetime_to_self_ref_param() { + check_assist( + introduce_named_lifetime, + r#"fn my_fun<'other>(&self, f: &Foo, b: &'other Bar) -> X<'_$0>"#, + r#"fn my_fun<'other, 'a>(&'a self, f: &Foo, b: &'other Bar) -> X<'a>"#, + ); + } + + #[test] + fn test_function_add_lifetime_to_param_with_non_ref_self() { + check_assist( + introduce_named_lifetime, + r#"fn my_fun<'other>(self, f: &Foo, b: &'other Bar) -> X<'_$0>"#, + r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/invert_if.rs b/crates/ide_assists/src/handlers/invert_if.rs new file mode 100644 index 000000000..5b69dafd4 --- /dev/null +++ b/crates/ide_assists/src/handlers/invert_if.rs @@ -0,0 +1,146 @@ +use syntax::{ + ast::{self, AstNode}, + T, +}; + +use crate::{ + assist_context::{AssistContext, Assists}, + utils::invert_boolean_expression, + AssistId, AssistKind, +}; + +// Assist: invert_if +// +// Apply invert_if +// This transforms if expressions of the form `if !x {A} else {B}` into `if x {B} else {A}` +// This also works with `!=`. This assist can only be applied with the cursor +// on `if`. +// +// ``` +// fn main() { +// if$0 !y { A } else { B } +// } +// ``` +// -> +// ``` +// fn main() { +// if y { B } else { A } +// } +// ``` + +pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let if_keyword = ctx.find_token_syntax_at_offset(T![if])?; + let expr = ast::IfExpr::cast(if_keyword.parent())?; + let if_range = if_keyword.text_range(); + let cursor_in_range = if_range.contains_range(ctx.frange.range); + if !cursor_in_range { + return None; + } + + // This assist should not apply for if-let. + if expr.condition()?.pat().is_some() { + return None; + } + + let cond = expr.condition()?.expr()?; + let then_node = expr.then_branch()?.syntax().clone(); + let else_block = match expr.else_branch()? { + ast::ElseBranch::Block(it) => it, + ast::ElseBranch::IfExpr(_) => return None, + }; + + acc.add(AssistId("invert_if", AssistKind::RefactorRewrite), "Invert if", if_range, |edit| { + let flip_cond = invert_boolean_expression(cond.clone()); + edit.replace_ast(cond, flip_cond); + + let else_node = else_block.syntax(); + let else_range = else_node.text_range(); + let then_range = then_node.text_range(); + + edit.replace(else_range, then_node.text()); + edit.replace(then_range, else_node.text()); + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + #[test] + fn invert_if_composite_condition() { + check_assist( + invert_if, + "fn f() { i$0f x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }", + "fn f() { if !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }", + ) + } + + #[test] + fn invert_if_remove_not_parentheses() { + check_assist( + invert_if, + "fn f() { i$0f !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }", + "fn f() { if x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }", + ) + } + + #[test] + fn invert_if_remove_inequality() { + check_assist( + invert_if, + "fn f() { i$0f x != 3 { 1 } else { 3 + 2 } }", + "fn f() { if x == 3 { 3 + 2 } else { 1 } }", + ) + } + + #[test] + fn invert_if_remove_not() { + check_assist( + invert_if, + "fn f() { $0if !cond { 3 * 2 } else { 1 } }", + "fn f() { if cond { 1 } else { 3 * 2 } }", + ) + } + + #[test] + fn invert_if_general_case() { + check_assist( + invert_if, + "fn f() { i$0f cond { 3 * 2 } else { 1 } }", + "fn f() { if !cond { 1 } else { 3 * 2 } }", + ) + } + + #[test] + fn invert_if_doesnt_apply_with_cursor_not_on_if() { + check_assist_not_applicable(invert_if, "fn f() { if !$0cond { 3 * 2 } else { 1 } }") + } + + #[test] + fn invert_if_doesnt_apply_with_if_let() { + check_assist_not_applicable( + invert_if, + "fn f() { i$0f let Some(_) = Some(1) { 1 } else { 0 } }", + ) + } + + #[test] + fn invert_if_option_case() { + check_assist( + invert_if, + "fn f() { if$0 doc_style.is_some() { Class::DocComment } else { Class::Comment } }", + "fn f() { if doc_style.is_none() { Class::Comment } else { Class::DocComment } }", + ) + } + + #[test] + fn invert_if_result_case() { + check_assist( + invert_if, + "fn f() { i$0f doc_style.is_err() { Class::Err } else { Class::Ok } }", + "fn f() { if doc_style.is_ok() { Class::Ok } else { Class::Err } }", + ) + } +} diff --git a/crates/ide_assists/src/handlers/merge_imports.rs b/crates/ide_assists/src/handlers/merge_imports.rs new file mode 100644 index 000000000..7bd7e1e36 --- /dev/null +++ b/crates/ide_assists/src/handlers/merge_imports.rs @@ -0,0 +1,343 @@ +use ide_db::helpers::insert_use::{try_merge_imports, try_merge_trees, MergeBehavior}; +use syntax::{ + algo::{neighbor, SyntaxRewriter}, + ast, AstNode, +}; + +use crate::{ + assist_context::{AssistContext, Assists}, + utils::next_prev, + AssistId, AssistKind, +}; + +// Assist: merge_imports +// +// Merges two imports with a common prefix. +// +// ``` +// use std::$0fmt::Formatter; +// use std::io; +// ``` +// -> +// ``` +// use std::{fmt::Formatter, io}; +// ``` +pub(crate) fn merge_imports(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let tree: ast::UseTree = ctx.find_node_at_offset()?; + let mut rewriter = SyntaxRewriter::default(); + let mut offset = ctx.offset(); + + if let Some(use_item) = tree.syntax().parent().and_then(ast::Use::cast) { + let (merged, to_delete) = + next_prev().filter_map(|dir| neighbor(&use_item, dir)).find_map(|use_item2| { + try_merge_imports(&use_item, &use_item2, MergeBehavior::Full).zip(Some(use_item2)) + })?; + + rewriter.replace_ast(&use_item, &merged); + rewriter += to_delete.remove(); + + if to_delete.syntax().text_range().end() < offset { + offset -= to_delete.syntax().text_range().len(); + } + } else { + let (merged, to_delete) = + next_prev().filter_map(|dir| neighbor(&tree, dir)).find_map(|use_tree| { + try_merge_trees(&tree, &use_tree, MergeBehavior::Full).zip(Some(use_tree)) + })?; + + rewriter.replace_ast(&tree, &merged); + rewriter += to_delete.remove(); + + if to_delete.syntax().text_range().end() < offset { + offset -= to_delete.syntax().text_range().len(); + } + }; + + let target = tree.syntax().text_range(); + acc.add( + AssistId("merge_imports", AssistKind::RefactorRewrite), + "Merge imports", + target, + |builder| { + builder.rewrite(rewriter); + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn test_merge_equal() { + check_assist( + merge_imports, + r" +use std::fmt$0::{Display, Debug}; +use std::fmt::{Display, Debug}; +", + r" +use std::fmt::{Debug, Display}; +", + ) + } + + #[test] + fn test_merge_first() { + check_assist( + merge_imports, + r" +use std::fmt$0::Debug; +use std::fmt::Display; +", + r" +use std::fmt::{Debug, Display}; +", + ) + } + + #[test] + fn test_merge_second() { + check_assist( + merge_imports, + r" +use std::fmt::Debug; +use std::fmt$0::Display; +", + r" +use std::fmt::{Debug, Display}; +", + ); + } + + #[test] + fn merge_self1() { + check_assist( + merge_imports, + r" +use std::fmt$0; +use std::fmt::Display; +", + r" +use std::fmt::{self, Display}; +", + ); + } + + #[test] + fn merge_self2() { + check_assist( + merge_imports, + r" +use std::{fmt, $0fmt::Display}; +", + r" +use std::{fmt::{self, Display}}; +", + ); + } + + #[test] + fn skip_pub1() { + check_assist_not_applicable( + merge_imports, + r" +pub use std::fmt$0::Debug; +use std::fmt::Display; +", + ); + } + + #[test] + fn skip_pub_last() { + check_assist_not_applicable( + merge_imports, + r" +use std::fmt$0::Debug; +pub use std::fmt::Display; +", + ); + } + + #[test] + fn skip_pub_crate_pub() { + check_assist_not_applicable( + merge_imports, + r" +pub(crate) use std::fmt$0::Debug; +pub use std::fmt::Display; +", + ); + } + + #[test] + fn skip_pub_pub_crate() { + check_assist_not_applicable( + merge_imports, + r" +pub use std::fmt$0::Debug; +pub(crate) use std::fmt::Display; +", + ); + } + + #[test] + fn merge_pub() { + check_assist( + merge_imports, + r" +pub use std::fmt$0::Debug; +pub use std::fmt::Display; +", + r" +pub use std::fmt::{Debug, Display}; +", + ) + } + + #[test] + fn merge_pub_crate() { + check_assist( + merge_imports, + r" +pub(crate) use std::fmt$0::Debug; +pub(crate) use std::fmt::Display; +", + r" +pub(crate) use std::fmt::{Debug, Display}; +", + ) + } + + #[test] + fn test_merge_nested() { + check_assist( + merge_imports, + r" +use std::{fmt$0::Debug, fmt::Display}; +", + r" +use std::{fmt::{Debug, Display}}; +", + ); + } + + #[test] + fn test_merge_nested2() { + check_assist( + merge_imports, + r" +use std::{fmt::Debug, fmt$0::Display}; +", + r" +use std::{fmt::{Debug, Display}}; +", + ); + } + + #[test] + fn test_merge_single_wildcard_diff_prefixes() { + check_assist( + merge_imports, + r" +use std$0::cell::*; +use std::str; +", + r" +use std::{cell::*, str}; +", + ) + } + + #[test] + fn test_merge_both_wildcard_diff_prefixes() { + check_assist( + merge_imports, + r" +use std$0::cell::*; +use std::str::*; +", + r" +use std::{cell::*, str::*}; +", + ) + } + + #[test] + fn removes_just_enough_whitespace() { + check_assist( + merge_imports, + r" +use foo$0::bar; +use foo::baz; + +/// Doc comment +", + r" +use foo::{bar, baz}; + +/// Doc comment +", + ); + } + + #[test] + fn works_with_trailing_comma() { + check_assist( + merge_imports, + r" +use { + foo$0::bar, + foo::baz, +}; +", + r" +use { + foo::{bar, baz}, +}; +", + ); + check_assist( + merge_imports, + r" +use { + foo::baz, + foo$0::bar, +}; +", + r" +use { + foo::{bar, baz}, +}; +", + ); + } + + #[test] + fn test_double_comma() { + check_assist( + merge_imports, + r" +use foo::bar::baz; +use foo::$0{ + FooBar, +}; +", + r" +use foo::{FooBar, bar::baz}; +", + ) + } + + #[test] + fn test_empty_use() { + check_assist_not_applicable( + merge_imports, + r" +use std::$0 +fn main() {}", + ); + } +} diff --git a/crates/ide_assists/src/handlers/merge_match_arms.rs b/crates/ide_assists/src/handlers/merge_match_arms.rs new file mode 100644 index 000000000..9bf076cb9 --- /dev/null +++ b/crates/ide_assists/src/handlers/merge_match_arms.rs @@ -0,0 +1,248 @@ +use std::iter::successors; + +use syntax::{ + algo::neighbor, + ast::{self, AstNode}, + Direction, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists, TextRange}; + +// Assist: merge_match_arms +// +// Merges identical match arms. +// +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// $0Action::Move(..) => foo(), +// Action::Stop => foo(), +// } +// } +// ``` +// -> +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// Action::Move(..) | Action::Stop => foo(), +// } +// } +// ``` +pub(crate) fn merge_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let current_arm = ctx.find_node_at_offset::()?; + // Don't try to handle arms with guards for now - can add support for this later + if current_arm.guard().is_some() { + return None; + } + let current_expr = current_arm.expr()?; + let current_text_range = current_arm.syntax().text_range(); + + // We check if the following match arms match this one. We could, but don't, + // compare to the previous match arm as well. + let arms_to_merge = successors(Some(current_arm), |it| neighbor(it, Direction::Next)) + .take_while(|arm| { + if arm.guard().is_some() { + return false; + } + match arm.expr() { + Some(expr) => expr.syntax().text() == current_expr.syntax().text(), + None => false, + } + }) + .collect::>(); + + if arms_to_merge.len() <= 1 { + return None; + } + + acc.add( + AssistId("merge_match_arms", AssistKind::RefactorRewrite), + "Merge match arms", + current_text_range, + |edit| { + let pats = if arms_to_merge.iter().any(contains_placeholder) { + "_".into() + } else { + arms_to_merge + .iter() + .filter_map(ast::MatchArm::pat) + .map(|x| x.syntax().to_string()) + .collect::>() + .join(" | ") + }; + + let arm = format!("{} => {}", pats, current_expr.syntax().text()); + + let start = arms_to_merge.first().unwrap().syntax().text_range().start(); + let end = arms_to_merge.last().unwrap().syntax().text_range().end(); + + edit.replace(TextRange::new(start, end), arm); + }, + ) +} + +fn contains_placeholder(a: &ast::MatchArm) -> bool { + matches!(a.pat(), Some(ast::Pat::WildcardPat(..))) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn merge_match_arms_single_patterns() { + check_assist( + merge_match_arms, + r#" + #[derive(Debug)] + enum X { A, B, C } + + fn main() { + let x = X::A; + let y = match x { + X::A => { 1i32$0 } + X::B => { 1i32 } + X::C => { 2i32 } + } + } + "#, + r#" + #[derive(Debug)] + enum X { A, B, C } + + fn main() { + let x = X::A; + let y = match x { + X::A | X::B => { 1i32 } + X::C => { 2i32 } + } + } + "#, + ); + } + + #[test] + fn merge_match_arms_multiple_patterns() { + check_assist( + merge_match_arms, + r#" + #[derive(Debug)] + enum X { A, B, C, D, E } + + fn main() { + let x = X::A; + let y = match x { + X::A | X::B => {$0 1i32 }, + X::C | X::D => { 1i32 }, + X::E => { 2i32 }, + } + } + "#, + r#" + #[derive(Debug)] + enum X { A, B, C, D, E } + + fn main() { + let x = X::A; + let y = match x { + X::A | X::B | X::C | X::D => { 1i32 }, + X::E => { 2i32 }, + } + } + "#, + ); + } + + #[test] + fn merge_match_arms_placeholder_pattern() { + check_assist( + merge_match_arms, + r#" + #[derive(Debug)] + enum X { A, B, C, D, E } + + fn main() { + let x = X::A; + let y = match x { + X::A => { 1i32 }, + X::B => { 2i$032 }, + _ => { 2i32 } + } + } + "#, + r#" + #[derive(Debug)] + enum X { A, B, C, D, E } + + fn main() { + let x = X::A; + let y = match x { + X::A => { 1i32 }, + _ => { 2i32 } + } + } + "#, + ); + } + + #[test] + fn merges_all_subsequent_arms() { + check_assist( + merge_match_arms, + r#" + enum X { A, B, C, D, E } + + fn main() { + match X::A { + X::A$0 => 92, + X::B => 92, + X::C => 92, + X::D => 62, + _ => panic!(), + } + } + "#, + r#" + enum X { A, B, C, D, E } + + fn main() { + match X::A { + X::A | X::B | X::C => 92, + X::D => 62, + _ => panic!(), + } + } + "#, + ) + } + + #[test] + fn merge_match_arms_rejects_guards() { + check_assist_not_applicable( + merge_match_arms, + r#" + #[derive(Debug)] + enum X { + A(i32), + B, + C + } + + fn main() { + let x = X::A; + let y = match x { + X::A(a) if a > 5 => { $01i32 }, + X::B => { 1i32 }, + X::C => { 2i32 } + } + } + "#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/move_bounds.rs b/crates/ide_assists/src/handlers/move_bounds.rs new file mode 100644 index 000000000..cf260c6f8 --- /dev/null +++ b/crates/ide_assists/src/handlers/move_bounds.rs @@ -0,0 +1,152 @@ +use syntax::{ + ast::{self, edit::AstNodeEdit, make, AstNode, NameOwner, TypeBoundsOwner}, + match_ast, + SyntaxKind::*, + T, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: move_bounds_to_where_clause +// +// Moves inline type bounds to a where clause. +// +// ``` +// fn apply U>(f: F, x: T) -> U { +// f(x) +// } +// ``` +// -> +// ``` +// fn apply(f: F, x: T) -> U where F: FnOnce(T) -> U { +// f(x) +// } +// ``` +pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let type_param_list = ctx.find_node_at_offset::()?; + + let mut type_params = type_param_list.type_params(); + if type_params.all(|p| p.type_bound_list().is_none()) { + return None; + } + + let parent = type_param_list.syntax().parent()?; + if parent.children_with_tokens().any(|it| it.kind() == WHERE_CLAUSE) { + return None; + } + + let anchor = match_ast! { + match parent { + ast::Fn(it) => it.body()?.syntax().clone().into(), + ast::Trait(it) => it.assoc_item_list()?.syntax().clone().into(), + ast::Impl(it) => it.assoc_item_list()?.syntax().clone().into(), + ast::Enum(it) => it.variant_list()?.syntax().clone().into(), + ast::Struct(it) => { + it.syntax().children_with_tokens() + .find(|it| it.kind() == RECORD_FIELD_LIST || it.kind() == T![;])? + }, + _ => return None + } + }; + + let target = type_param_list.syntax().text_range(); + acc.add( + AssistId("move_bounds_to_where_clause", AssistKind::RefactorRewrite), + "Move to where clause", + target, + |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 = type_param_list.replace_descendants(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 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); + }, + ) +} + +fn build_predicate(param: ast::TypeParam) -> Option { + let path = { + let name_ref = make::name_ref(¶m.name()?.syntax().to_string()); + let segment = make::path_segment(name_ref); + make::path_unqualified(segment) + }; + let predicate = make::where_pred(path, param.type_bound_list()?.bounds()); + Some(predicate) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::check_assist; + + #[test] + fn move_bounds_to_where_clause_fn() { + check_assist( + move_bounds_to_where_clause, + r#" + fn foo T>() {} + "#, + r#" + fn foo() where T: u32, F: FnOnce(T) -> T {} + "#, + ); + } + + #[test] + fn move_bounds_to_where_clause_impl() { + check_assist( + move_bounds_to_where_clause, + r#" + impl A {} + "#, + r#" + impl A where U: u32 {} + "#, + ); + } + + #[test] + fn move_bounds_to_where_clause_struct() { + check_assist( + move_bounds_to_where_clause, + r#" + struct A<$0T: Iterator> {} + "#, + r#" + struct A where T: Iterator {} + "#, + ); + } + + #[test] + fn move_bounds_to_where_clause_tuple_struct() { + check_assist( + move_bounds_to_where_clause, + r#" + struct Pair<$0T: u32>(T, T); + "#, + r#" + struct Pair(T, T) where T: u32; + "#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/move_guard.rs b/crates/ide_assists/src/handlers/move_guard.rs new file mode 100644 index 000000000..3f22302a9 --- /dev/null +++ b/crates/ide_assists/src/handlers/move_guard.rs @@ -0,0 +1,367 @@ +use syntax::{ + ast::{edit::AstNodeEdit, make, AstNode, BlockExpr, Expr, IfExpr, MatchArm}, + SyntaxKind::WHITESPACE, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: move_guard_to_arm_body +// +// Moves match guard into match arm body. +// +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// Action::Move { distance } $0if distance > 10 => foo(), +// _ => (), +// } +// } +// ``` +// -> +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// Action::Move { distance } => if distance > 10 { +// foo() +// }, +// _ => (), +// } +// } +// ``` +pub(crate) fn move_guard_to_arm_body(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let match_arm = ctx.find_node_at_offset::()?; + let guard = match_arm.guard()?; + let space_before_guard = guard.syntax().prev_sibling_or_token(); + + let guard_condition = guard.expr()?; + let arm_expr = match_arm.expr()?; + let if_expr = make::expr_if( + make::condition(guard_condition, None), + make::block_expr(None, Some(arm_expr.clone())), + None, + ) + .indent(arm_expr.indent_level()); + + let target = guard.syntax().text_range(); + acc.add( + AssistId("move_guard_to_arm_body", AssistKind::RefactorRewrite), + "Move guard to arm body", + target, + |edit| { + match space_before_guard { + Some(element) if element.kind() == WHITESPACE => { + edit.delete(element.text_range()); + } + _ => (), + }; + + edit.delete(guard.syntax().text_range()); + edit.replace_ast(arm_expr, if_expr); + }, + ) +} + +// Assist: move_arm_cond_to_match_guard +// +// Moves if expression from match arm body into a guard. +// +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// Action::Move { distance } => $0if distance > 10 { foo() }, +// _ => (), +// } +// } +// ``` +// -> +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// Action::Move { distance } if distance > 10 => foo(), +// _ => (), +// } +// } +// ``` +pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let match_arm: MatchArm = ctx.find_node_at_offset::()?; + let match_pat = match_arm.pat()?; + let arm_body = match_arm.expr()?; + + let mut replace_node = None; + let if_expr: IfExpr = IfExpr::cast(arm_body.syntax().clone()).or_else(|| { + let block_expr = BlockExpr::cast(arm_body.syntax().clone())?; + if let Expr::IfExpr(e) = block_expr.tail_expr()? { + replace_node = Some(block_expr.syntax().clone()); + Some(e) + } else { + None + } + })?; + let replace_node = replace_node.unwrap_or_else(|| if_expr.syntax().clone()); + + let cond = if_expr.condition()?; + let then_block = if_expr.then_branch()?; + + // Not support if with else branch + if if_expr.else_branch().is_some() { + return None; + } + // Not support moving if let to arm guard + if cond.pat().is_some() { + return None; + } + + let buf = format!(" if {}", cond.syntax().text()); + + acc.add( + AssistId("move_arm_cond_to_match_guard", AssistKind::RefactorRewrite), + "Move condition to match guard", + replace_node.text_range(), + |edit| { + let then_only_expr = then_block.statements().next().is_none(); + + match &then_block.tail_expr() { + Some(then_expr) if then_only_expr => { + edit.replace(replace_node.text_range(), then_expr.syntax().text()) + } + _ if replace_node != *if_expr.syntax() => { + // Dedent because if_expr is in a BlockExpr + let replace_with = then_block.dedent(1.into()).syntax().text(); + edit.replace(replace_node.text_range(), replace_with) + } + _ => edit.replace(replace_node.text_range(), then_block.syntax().text()), + } + + edit.insert(match_pat.syntax().text_range().end(), buf); + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + #[test] + fn move_guard_to_arm_body_target() { + check_assist_target( + move_guard_to_arm_body, + r#" +fn main() { + match 92 { + x $0if x > 10 => false, + _ => true + } +} +"#, + r#"if x > 10"#, + ); + } + + #[test] + fn move_guard_to_arm_body_works() { + check_assist( + move_guard_to_arm_body, + r#" +fn main() { + match 92 { + x $0if x > 10 => false, + _ => true + } +} +"#, + r#" +fn main() { + match 92 { + x => if x > 10 { + false + }, + _ => true + } +} +"#, + ); + } + + #[test] + fn move_guard_to_arm_body_works_complex_match() { + check_assist( + move_guard_to_arm_body, + r#" +fn main() { + match 92 { + $0x @ 4 | x @ 5 if x > 5 => true, + _ => false + } +} +"#, + r#" +fn main() { + match 92 { + x @ 4 | x @ 5 => if x > 5 { + true + }, + _ => false + } +} +"#, + ); + } + + #[test] + fn move_arm_cond_to_match_guard_works() { + check_assist( + move_arm_cond_to_match_guard, + r#" +fn main() { + match 92 { + x => if x > 10 { $0false }, + _ => true + } +} +"#, + r#" +fn main() { + match 92 { + x if x > 10 => false, + _ => true + } +} +"#, + ); + } + + #[test] + fn move_arm_cond_in_block_to_match_guard_works() { + check_assist( + move_arm_cond_to_match_guard, + r#" +fn main() { + match 92 { + x => { + $0if x > 10 { + false + } + }, + _ => true + } +} +"#, + r#" +fn main() { + match 92 { + x if x > 10 => false, + _ => true + } +} +"#, + ); + } + + #[test] + fn move_arm_cond_to_match_guard_if_let_not_works() { + check_assist_not_applicable( + move_arm_cond_to_match_guard, + r#" +fn main() { + match 92 { + x => if let 62 = x { $0false }, + _ => true + } +} +"#, + ); + } + + #[test] + fn move_arm_cond_to_match_guard_if_empty_body_works() { + check_assist( + move_arm_cond_to_match_guard, + r#" +fn main() { + match 92 { + x => if x > 10 { $0 }, + _ => true + } +} +"#, + r#" +fn main() { + match 92 { + x if x > 10 => { }, + _ => true + } +} +"#, + ); + } + + #[test] + fn move_arm_cond_to_match_guard_if_multiline_body_works() { + check_assist( + move_arm_cond_to_match_guard, + r#" +fn main() { + match 92 { + x => if x > 10 { + 92;$0 + false + }, + _ => true + } +} +"#, + r#" +fn main() { + match 92 { + x if x > 10 => { + 92; + false + }, + _ => true + } +} +"#, + ); + } + + #[test] + fn move_arm_cond_in_block_to_match_guard_if_multiline_body_works() { + check_assist( + move_arm_cond_to_match_guard, + r#" +fn main() { + match 92 { + x => { + if x > 10 { + 92;$0 + false + } + } + _ => true + } +} +"#, + r#" +fn main() { + match 92 { + x if x > 10 => { + 92; + false + } + _ => true + } +} +"#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/move_module_to_file.rs b/crates/ide_assists/src/handlers/move_module_to_file.rs new file mode 100644 index 000000000..91c395c1b --- /dev/null +++ b/crates/ide_assists/src/handlers/move_module_to_file.rs @@ -0,0 +1,188 @@ +use ast::{edit::IndentLevel, VisibilityOwner}; +use ide_db::base_db::AnchoredPathBuf; +use stdx::format_to; +use syntax::{ + ast::{self, edit::AstNodeEdit, NameOwner}, + AstNode, TextRange, +}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: move_module_to_file +// +// Moves inline module's contents to a separate file. +// +// ``` +// mod $0foo { +// fn t() {} +// } +// ``` +// -> +// ``` +// mod foo; +// ``` +pub(crate) fn move_module_to_file(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let module_ast = ctx.find_node_at_offset::()?; + let module_items = module_ast.item_list()?; + + let l_curly_offset = module_items.syntax().text_range().start(); + if l_curly_offset <= ctx.offset() { + mark::hit!(available_before_curly); + return None; + } + let target = TextRange::new(module_ast.syntax().text_range().start(), l_curly_offset); + + let module_name = module_ast.name()?; + + let module_def = ctx.sema.to_def(&module_ast)?; + let parent_module = module_def.parent(ctx.db())?; + + acc.add( + AssistId("move_module_to_file", AssistKind::RefactorExtract), + "Extract module to file", + target, + |builder| { + let path = { + let dir = match parent_module.name(ctx.db()) { + Some(name) if !parent_module.is_mod_rs(ctx.db()) => format!("{}/", name), + _ => String::new(), + }; + format!("./{}{}.rs", dir, module_name) + }; + let contents = { + let items = module_items.dedent(IndentLevel(1)).to_string(); + let mut items = + items.trim_start_matches('{').trim_end_matches('}').trim().to_string(); + if !items.is_empty() { + items.push('\n'); + } + items + }; + + let mut buf = String::new(); + if let Some(v) = module_ast.visibility() { + format_to!(buf, "{} ", v); + } + format_to!(buf, "mod {};", module_name); + + builder.replace(module_ast.syntax().text_range(), buf); + + let dst = AnchoredPathBuf { anchor: ctx.frange.file_id, path }; + builder.create_file(dst, contents); + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn extract_from_root() { + check_assist( + move_module_to_file, + r#" +mod $0tests { + #[test] fn t() {} +} +"#, + r#" +//- /main.rs +mod tests; +//- /tests.rs +#[test] fn t() {} +"#, + ); + } + + #[test] + fn extract_from_submodule() { + check_assist( + move_module_to_file, + r#" +//- /main.rs +mod submod; +//- /submod.rs +$0mod inner { + fn f() {} +} +fn g() {} +"#, + r#" +//- /submod.rs +mod inner; +fn g() {} +//- /submod/inner.rs +fn f() {} +"#, + ); + } + + #[test] + fn extract_from_mod_rs() { + check_assist( + move_module_to_file, + r#" +//- /main.rs +mod submodule; +//- /submodule/mod.rs +mod inner$0 { + fn f() {} +} +fn g() {} +"#, + r#" +//- /submodule/mod.rs +mod inner; +fn g() {} +//- /submodule/inner.rs +fn f() {} +"#, + ); + } + + #[test] + fn extract_public() { + check_assist( + move_module_to_file, + r#" +pub mod $0tests { + #[test] fn t() {} +} +"#, + r#" +//- /main.rs +pub mod tests; +//- /tests.rs +#[test] fn t() {} +"#, + ); + } + + #[test] + fn extract_public_crate() { + check_assist( + move_module_to_file, + r#" +pub(crate) mod $0tests { + #[test] fn t() {} +} +"#, + r#" +//- /main.rs +pub(crate) mod tests; +//- /tests.rs +#[test] fn t() {} +"#, + ); + } + + #[test] + fn available_before_curly() { + mark::check!(available_before_curly); + check_assist_not_applicable(move_module_to_file, r#"mod m { $0 }"#); + } +} diff --git a/crates/ide_assists/src/handlers/pull_assignment_up.rs b/crates/ide_assists/src/handlers/pull_assignment_up.rs new file mode 100644 index 000000000..13e1cb754 --- /dev/null +++ b/crates/ide_assists/src/handlers/pull_assignment_up.rs @@ -0,0 +1,400 @@ +use syntax::{ + ast::{self, edit::AstNodeEdit, make}, + AstNode, +}; +use test_utils::mark; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, AssistKind, +}; + +// Assist: pull_assignment_up +// +// Extracts variable assignment to outside an if or match statement. +// +// ``` +// fn main() { +// let mut foo = 6; +// +// if true { +// $0foo = 5; +// } else { +// foo = 4; +// } +// } +// ``` +// -> +// ``` +// fn main() { +// let mut foo = 6; +// +// foo = if true { +// 5 +// } else { +// 4 +// }; +// } +// ``` +pub(crate) fn pull_assignment_up(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let assign_expr = ctx.find_node_at_offset::()?; + let name_expr = if assign_expr.op_kind()? == ast::BinOp::Assignment { + assign_expr.lhs()? + } else { + return None; + }; + + let (old_stmt, new_stmt) = if let Some(if_expr) = ctx.find_node_at_offset::() { + ( + ast::Expr::cast(if_expr.syntax().to_owned())?, + exprify_if(&if_expr, &ctx.sema, &name_expr)?.indent(if_expr.indent_level()), + ) + } else if let Some(match_expr) = ctx.find_node_at_offset::() { + ( + ast::Expr::cast(match_expr.syntax().to_owned())?, + exprify_match(&match_expr, &ctx.sema, &name_expr)?, + ) + } else { + return None; + }; + + let expr_stmt = make::expr_stmt(new_stmt); + + acc.add( + AssistId("pull_assignment_up", AssistKind::RefactorExtract), + "Pull assignment up", + old_stmt.syntax().text_range(), + move |edit| { + edit.replace(old_stmt.syntax().text_range(), format!("{} = {};", name_expr, expr_stmt)); + }, + ) +} + +fn exprify_match( + match_expr: &ast::MatchExpr, + sema: &hir::Semantics, + name: &ast::Expr, +) -> Option { + let new_arm_list = match_expr + .match_arm_list()? + .arms() + .map(|arm| { + if let ast::Expr::BlockExpr(block) = arm.expr()? { + let new_block = exprify_block(&block, sema, name)?.indent(block.indent_level()); + Some(arm.replace_descendant(block, new_block)) + } else { + None + } + }) + .collect::>>()?; + let new_arm_list = match_expr + .match_arm_list()? + .replace_descendants(match_expr.match_arm_list()?.arms().zip(new_arm_list)); + Some(make::expr_match(match_expr.expr()?, new_arm_list)) +} + +fn exprify_if( + statement: &ast::IfExpr, + sema: &hir::Semantics, + name: &ast::Expr, +) -> Option { + let then_branch = exprify_block(&statement.then_branch()?, sema, name)?; + let else_branch = match statement.else_branch()? { + ast::ElseBranch::Block(ref block) => { + ast::ElseBranch::Block(exprify_block(block, sema, name)?) + } + ast::ElseBranch::IfExpr(expr) => { + mark::hit!(test_pull_assignment_up_chained_if); + ast::ElseBranch::IfExpr(ast::IfExpr::cast( + exprify_if(&expr, sema, name)?.syntax().to_owned(), + )?) + } + }; + Some(make::expr_if(statement.condition()?, then_branch, Some(else_branch))) +} + +fn exprify_block( + block: &ast::BlockExpr, + sema: &hir::Semantics, + name: &ast::Expr, +) -> Option { + if block.tail_expr().is_some() { + return None; + } + + let mut stmts: Vec<_> = block.statements().collect(); + let stmt = stmts.pop()?; + + if let ast::Stmt::ExprStmt(stmt) = stmt { + if let ast::Expr::BinExpr(expr) = stmt.expr()? { + if expr.op_kind()? == ast::BinOp::Assignment && is_equivalent(sema, &expr.lhs()?, name) + { + // The last statement in the block is an assignment to the name we want + return Some(make::block_expr(stmts, Some(expr.rhs()?))); + } + } + } + None +} + +fn is_equivalent( + sema: &hir::Semantics, + expr0: &ast::Expr, + expr1: &ast::Expr, +) -> bool { + match (expr0, expr1) { + (ast::Expr::FieldExpr(field_expr0), ast::Expr::FieldExpr(field_expr1)) => { + mark::hit!(test_pull_assignment_up_field_assignment); + sema.resolve_field(field_expr0) == sema.resolve_field(field_expr1) + } + (ast::Expr::PathExpr(path0), ast::Expr::PathExpr(path1)) => { + let path0 = path0.path(); + let path1 = path1.path(); + if let (Some(path0), Some(path1)) = (path0, path1) { + sema.resolve_path(&path0) == sema.resolve_path(&path1) + } else { + false + } + } + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + #[test] + fn test_pull_assignment_up_if() { + check_assist( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + if true { + $0a = 2; + } else { + a = 3; + } +}"#, + r#" +fn foo() { + let mut a = 1; + + a = if true { + 2 + } else { + 3 + }; +}"#, + ); + } + + #[test] + fn test_pull_assignment_up_match() { + check_assist( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + match 1 { + 1 => { + $0a = 2; + }, + 2 => { + a = 3; + }, + 3 => { + a = 4; + } + } +}"#, + r#" +fn foo() { + let mut a = 1; + + a = match 1 { + 1 => { + 2 + }, + 2 => { + 3 + }, + 3 => { + 4 + } + }; +}"#, + ); + } + + #[test] + fn test_pull_assignment_up_not_last_not_applicable() { + check_assist_not_applicable( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + if true { + $0a = 2; + b = a; + } else { + a = 3; + } +}"#, + ) + } + + #[test] + fn test_pull_assignment_up_chained_if() { + mark::check!(test_pull_assignment_up_chained_if); + check_assist( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + if true { + $0a = 2; + } else if false { + a = 3; + } else { + a = 4; + } +}"#, + r#" +fn foo() { + let mut a = 1; + + a = if true { + 2 + } else if false { + 3 + } else { + 4 + }; +}"#, + ); + } + + #[test] + fn test_pull_assignment_up_retains_stmts() { + check_assist( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + if true { + let b = 2; + $0a = 2; + } else { + let b = 3; + a = 3; + } +}"#, + r#" +fn foo() { + let mut a = 1; + + a = if true { + let b = 2; + 2 + } else { + let b = 3; + 3 + }; +}"#, + ) + } + + #[test] + fn pull_assignment_up_let_stmt_not_applicable() { + check_assist_not_applicable( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + let b = if true { + $0a = 2 + } else { + a = 3 + }; +}"#, + ) + } + + #[test] + fn pull_assignment_up_if_missing_assigment_not_applicable() { + check_assist_not_applicable( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + if true { + $0a = 2; + } else {} +}"#, + ) + } + + #[test] + fn pull_assignment_up_match_missing_assigment_not_applicable() { + check_assist_not_applicable( + pull_assignment_up, + r#" +fn foo() { + let mut a = 1; + + match 1 { + 1 => { + $0a = 2; + }, + 2 => { + a = 3; + }, + 3 => {}, + } +}"#, + ) + } + + #[test] + fn test_pull_assignment_up_field_assignment() { + mark::check!(test_pull_assignment_up_field_assignment); + check_assist( + pull_assignment_up, + r#" +struct A(usize); + +fn foo() { + let mut a = A(1); + + if true { + $0a.0 = 2; + } else { + a.0 = 3; + } +}"#, + r#" +struct A(usize); + +fn foo() { + let mut a = A(1); + + a.0 = if true { + 2 + } else { + 3 + }; +}"#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/qualify_path.rs b/crates/ide_assists/src/handlers/qualify_path.rs new file mode 100644 index 000000000..b0b0d31b4 --- /dev/null +++ b/crates/ide_assists/src/handlers/qualify_path.rs @@ -0,0 +1,1205 @@ +use std::iter; + +use hir::{AsAssocItem, AsName}; +use ide_db::helpers::{import_assets::ImportCandidate, mod_path_to_ast}; +use ide_db::RootDatabase; +use syntax::{ + ast, + ast::{make, ArgListOwner}, + AstNode, +}; +use test_utils::mark; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, AssistKind, GroupLabel, +}; + +use super::auto_import::find_importable_node; + +// Assist: qualify_path +// +// If the name is unresolved, provides all possible qualified paths for it. +// +// ``` +// fn main() { +// let map = HashMap$0::new(); +// } +// # pub mod std { pub mod collections { pub struct HashMap { } } } +// ``` +// -> +// ``` +// fn main() { +// let map = std::collections::HashMap::new(); +// } +// # pub mod std { pub mod collections { pub struct HashMap { } } } +// ``` +pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; + let proposed_imports = import_assets.search_for_relative_paths(&ctx.sema); + if proposed_imports.is_empty() { + return None; + } + + let candidate = import_assets.import_candidate(); + let range = ctx.sema.original_range(&syntax_under_caret).range; + + let qualify_candidate = match candidate { + ImportCandidate::Path(candidate) => { + if candidate.qualifier.is_some() { + mark::hit!(qualify_path_qualifier_start); + let path = ast::Path::cast(syntax_under_caret)?; + let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?); + QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list()) + } else { + mark::hit!(qualify_path_unqualified_name); + let path = ast::Path::cast(syntax_under_caret)?; + let generics = path.segment()?.generic_arg_list(); + QualifyCandidate::UnqualifiedName(generics) + } + } + ImportCandidate::TraitAssocItem(_) => { + mark::hit!(qualify_path_trait_assoc_item); + let path = ast::Path::cast(syntax_under_caret)?; + let (qualifier, segment) = (path.qualifier()?, path.segment()?); + QualifyCandidate::TraitAssocItem(qualifier, segment) + } + ImportCandidate::TraitMethod(_) => { + mark::hit!(qualify_path_trait_method); + let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?; + QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr) + } + }; + + let group_label = group_label(candidate); + for (import, item) in proposed_imports { + acc.add_group( + &group_label, + AssistId("qualify_path", AssistKind::QuickFix), + label(candidate, &import), + range, + |builder| { + qualify_candidate.qualify( + |replace_with: String| builder.replace(range, replace_with), + import, + item, + ) + }, + ); + } + Some(()) +} + +enum QualifyCandidate<'db> { + QualifierStart(ast::PathSegment, Option), + UnqualifiedName(Option), + TraitAssocItem(ast::Path, ast::PathSegment), + TraitMethod(&'db RootDatabase, ast::MethodCallExpr), +} + +impl QualifyCandidate<'_> { + fn qualify(&self, mut replacer: impl FnMut(String), import: hir::ModPath, item: hir::ItemInNs) { + let import = mod_path_to_ast(&import); + match self { + QualifyCandidate::QualifierStart(segment, generics) => { + let generics = generics.as_ref().map_or_else(String::new, ToString::to_string); + replacer(format!("{}{}::{}", import, generics, segment)); + } + QualifyCandidate::UnqualifiedName(generics) => { + let generics = generics.as_ref().map_or_else(String::new, ToString::to_string); + replacer(format!("{}{}", import.to_string(), generics)); + } + QualifyCandidate::TraitAssocItem(qualifier, segment) => { + replacer(format!("<{} as {}>::{}", qualifier, import, segment)); + } + &QualifyCandidate::TraitMethod(db, ref mcall_expr) => { + Self::qualify_trait_method(db, mcall_expr, replacer, import, item); + } + } + } + + fn qualify_trait_method( + db: &RootDatabase, + mcall_expr: &ast::MethodCallExpr, + mut replacer: impl FnMut(String), + import: ast::Path, + item: hir::ItemInNs, + ) -> Option<()> { + let receiver = mcall_expr.receiver()?; + let trait_method_name = mcall_expr.name_ref()?; + let generics = + mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string); + let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args()); + let trait_ = item_as_trait(db, item)?; + let method = find_trait_method(db, trait_, &trait_method_name)?; + if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) { + let receiver = match self_access { + hir::Access::Shared => make::expr_ref(receiver, false), + hir::Access::Exclusive => make::expr_ref(receiver, true), + hir::Access::Owned => receiver, + }; + replacer(format!( + "{}::{}{}{}", + import, + trait_method_name, + generics, + match arg_list { + Some(args) => make::arg_list(iter::once(receiver).chain(args)), + None => make::arg_list(iter::once(receiver)), + } + )); + } + Some(()) + } +} + +fn find_trait_method( + db: &RootDatabase, + trait_: hir::Trait, + trait_method_name: &ast::NameRef, +) -> Option { + if let Some(hir::AssocItem::Function(method)) = + trait_.items(db).into_iter().find(|item: &hir::AssocItem| { + item.name(db).map(|name| name == trait_method_name.as_name()).unwrap_or(false) + }) + { + Some(method) + } else { + None + } +} + +fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option { + let item_module_def = hir::ModuleDef::from(item.as_module_def_id()?); + + if let hir::ModuleDef::Trait(trait_) = item_module_def { + Some(trait_) + } else { + item_module_def.as_assoc_item(db)?.containing_trait(db) + } +} + +fn group_label(candidate: &ImportCandidate) -> GroupLabel { + let name = match candidate { + ImportCandidate::Path(it) => &it.name, + ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => &it.name, + } + .text(); + GroupLabel(format!("Qualify {}", name)) +} + +fn label(candidate: &ImportCandidate, import: &hir::ModPath) -> String { + match candidate { + ImportCandidate::Path(candidate) => { + if candidate.qualifier.is_some() { + format!("Qualify with `{}`", &import) + } else { + format!("Qualify as `{}`", &import) + } + } + ImportCandidate::TraitAssocItem(_) => format!("Qualify `{}`", &import), + ImportCandidate::TraitMethod(_) => format!("Qualify with cast as `{}`", &import), + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn applicable_when_found_an_import_partial() { + mark::check!(qualify_path_unqualified_name); + check_assist( + qualify_path, + r" + mod std { + pub mod fmt { + pub struct Formatter; + } + } + + use std::fmt; + + $0Formatter + ", + r" + mod std { + pub mod fmt { + pub struct Formatter; + } + } + + use std::fmt; + + fmt::Formatter + ", + ); + } + + #[test] + fn applicable_when_found_an_import() { + check_assist( + qualify_path, + r" + $0PubStruct + + pub mod PubMod { + pub struct PubStruct; + } + ", + r" + PubMod::PubStruct + + pub mod PubMod { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn applicable_in_macros() { + check_assist( + qualify_path, + r" + macro_rules! foo { + ($i:ident) => { fn foo(a: $i) {} } + } + foo!(Pub$0Struct); + + pub mod PubMod { + pub struct PubStruct; + } + ", + r" + macro_rules! foo { + ($i:ident) => { fn foo(a: $i) {} } + } + foo!(PubMod::PubStruct); + + pub mod PubMod { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn applicable_when_found_multiple_imports() { + check_assist( + qualify_path, + r" + PubSt$0ruct + + pub mod PubMod1 { + pub struct PubStruct; + } + pub mod PubMod2 { + pub struct PubStruct; + } + pub mod PubMod3 { + pub struct PubStruct; + } + ", + r" + PubMod3::PubStruct + + pub mod PubMod1 { + pub struct PubStruct; + } + pub mod PubMod2 { + pub struct PubStruct; + } + pub mod PubMod3 { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn not_applicable_for_already_imported_types() { + check_assist_not_applicable( + qualify_path, + r" + use PubMod::PubStruct; + + PubStruct$0 + + pub mod PubMod { + pub struct PubStruct; + } + ", + ); + } + + #[test] + fn not_applicable_for_types_with_private_paths() { + check_assist_not_applicable( + qualify_path, + r" + PrivateStruct$0 + + pub mod PubMod { + struct PrivateStruct; + } + ", + ); + } + + #[test] + fn not_applicable_when_no_imports_found() { + check_assist_not_applicable( + qualify_path, + " + PubStruct$0", + ); + } + + #[test] + fn not_applicable_in_import_statements() { + check_assist_not_applicable( + qualify_path, + r" + use PubStruct$0; + + pub mod PubMod { + pub struct PubStruct; + }", + ); + } + + #[test] + fn qualify_function() { + check_assist( + qualify_path, + r" + test_function$0 + + pub mod PubMod { + pub fn test_function() {}; + } + ", + r" + PubMod::test_function + + pub mod PubMod { + pub fn test_function() {}; + } + ", + ); + } + + #[test] + fn qualify_macro() { + check_assist( + qualify_path, + r" +//- /lib.rs crate:crate_with_macro +#[macro_export] +macro_rules! foo { + () => () +} + +//- /main.rs crate:main deps:crate_with_macro +fn main() { + foo$0 +} +", + r" +fn main() { + crate_with_macro::foo +} +", + ); + } + + #[test] + fn qualify_path_target() { + check_assist_target( + qualify_path, + r" + struct AssistInfo { + group_label: Option<$0GroupLabel>, + } + + mod m { pub struct GroupLabel; } + ", + "GroupLabel", + ) + } + + #[test] + fn not_applicable_when_path_start_is_imported() { + check_assist_not_applicable( + qualify_path, + r" + pub mod mod1 { + pub mod mod2 { + pub mod mod3 { + pub struct TestStruct; + } + } + } + + use mod1::mod2; + fn main() { + mod2::mod3::TestStruct$0 + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_function() { + check_assist_not_applicable( + qualify_path, + r" + pub mod test_mod { + pub fn test_function() {} + } + + use test_mod::test_function; + fn main() { + test_function$0 + } + ", + ); + } + + #[test] + fn associated_struct_function() { + check_assist( + qualify_path, + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + pub fn test_function() {} + } + } + + fn main() { + TestStruct::test_function$0 + } + ", + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + pub fn test_function() {} + } + } + + fn main() { + test_mod::TestStruct::test_function + } + ", + ); + } + + #[test] + fn associated_struct_const() { + mark::check!(qualify_path_qualifier_start); + check_assist( + qualify_path, + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + TestStruct::TEST_CONST$0 + } + ", + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + test_mod::TestStruct::TEST_CONST + } + ", + ); + } + + #[test] + fn associated_trait_function() { + check_assist( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + + fn main() { + test_mod::TestStruct::test_function$0 + } + ", + r" + mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + + fn main() { + ::test_function + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_trait_for_function() { + check_assist_not_applicable( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub trait TestTrait2 { + fn test_function(); + } + pub enum TestEnum { + One, + Two, + } + impl TestTrait2 for TestEnum { + fn test_function() {} + } + impl TestTrait for TestEnum { + fn test_function() {} + } + } + + use test_mod::TestTrait2; + fn main() { + test_mod::TestEnum::test_function$0; + } + ", + ) + } + + #[test] + fn associated_trait_const() { + mark::check!(qualify_path_trait_assoc_item); + check_assist( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + test_mod::TestStruct::TEST_CONST$0 + } + ", + r" + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + ::TEST_CONST + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_trait_for_const() { + check_assist_not_applicable( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub trait TestTrait2 { + const TEST_CONST: f64; + } + pub enum TestEnum { + One, + Two, + } + impl TestTrait2 for TestEnum { + const TEST_CONST: f64 = 42.0; + } + impl TestTrait for TestEnum { + const TEST_CONST: u8 = 42; + } + } + + use test_mod::TestTrait2; + fn main() { + test_mod::TestEnum::TEST_CONST$0; + } + ", + ) + } + + #[test] + fn trait_method() { + mark::check!(qualify_path_trait_method); + check_assist( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_struct.test_meth$0od() + } + ", + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_mod::TestTrait::test_method(&test_struct) + } + ", + ); + } + + #[test] + fn trait_method_multi_params() { + check_assist( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self, test: i32); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self, test: i32) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_struct.test_meth$0od(42) + } + ", + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self, test: i32); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self, test: i32) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_mod::TestTrait::test_method(&test_struct, 42) + } + ", + ); + } + + #[test] + fn trait_method_consume() { + check_assist( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + fn test_method(self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_struct.test_meth$0od() + } + ", + r" + mod test_mod { + pub trait TestTrait { + fn test_method(self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_mod::TestTrait::test_method(test_struct) + } + ", + ); + } + + #[test] + fn trait_method_cross_crate() { + check_assist( + qualify_path, + r" + //- /main.rs crate:main deps:dep + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + test_struct.test_meth$0od() + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + ", + r" + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + dep::test_mod::TestTrait::test_method(&test_struct) + } + ", + ); + } + + #[test] + fn assoc_fn_cross_crate() { + check_assist( + qualify_path, + r" + //- /main.rs crate:main deps:dep + fn main() { + dep::test_mod::TestStruct::test_func$0tion + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + ", + r" + fn main() { + ::test_function + } + ", + ); + } + + #[test] + fn assoc_const_cross_crate() { + check_assist( + qualify_path, + r" + //- /main.rs crate:main deps:dep + fn main() { + dep::test_mod::TestStruct::CONST$0 + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + const CONST: bool; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const CONST: bool = true; + } + } + ", + r" + fn main() { + ::CONST + } + ", + ); + } + + #[test] + fn assoc_fn_as_method_cross_crate() { + check_assist_not_applicable( + qualify_path, + r" + //- /main.rs crate:main deps:dep + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + test_struct.test_func$0tion() + } + //- /dep.rs crate:dep + pub mod test_mod { + pub trait TestTrait { + fn test_function(); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_function() {} + } + } + ", + ); + } + + #[test] + fn private_trait_cross_crate() { + check_assist_not_applicable( + qualify_path, + r" + //- /main.rs crate:main deps:dep + fn main() { + let test_struct = dep::test_mod::TestStruct {}; + test_struct.test_meth$0od() + } + //- /dep.rs crate:dep + pub mod test_mod { + trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + ", + ); + } + + #[test] + fn not_applicable_for_imported_trait_for_method() { + check_assist_not_applicable( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub trait TestTrait2 { + fn test_method(&self); + } + pub enum TestEnum { + One, + Two, + } + impl TestTrait2 for TestEnum { + fn test_method(&self) {} + } + impl TestTrait for TestEnum { + fn test_method(&self) {} + } + } + + use test_mod::TestTrait2; + fn main() { + let one = test_mod::TestEnum::One; + one.test$0_method(); + } + ", + ) + } + + #[test] + fn dep_import() { + check_assist( + qualify_path, + r" +//- /lib.rs crate:dep +pub struct Struct; + +//- /main.rs crate:main deps:dep +fn main() { + Struct$0 +} +", + r" +fn main() { + dep::Struct +} +", + ); + } + + #[test] + fn whole_segment() { + // Tests that only imports whose last segment matches the identifier get suggested. + check_assist( + qualify_path, + r" +//- /lib.rs crate:dep +pub mod fmt { + pub trait Display {} +} + +pub fn panic_fmt() {} + +//- /main.rs crate:main deps:dep +struct S; + +impl f$0mt::Display for S {} +", + r" +struct S; + +impl dep::fmt::Display for S {} +", + ); + } + + #[test] + fn macro_generated() { + // Tests that macro-generated items are suggested from external crates. + check_assist( + qualify_path, + r" +//- /lib.rs crate:dep +macro_rules! mac { + () => { + pub struct Cheese; + }; +} + +mac!(); + +//- /main.rs crate:main deps:dep +fn main() { + Cheese$0; +} +", + r" +fn main() { + dep::Cheese; +} +", + ); + } + + #[test] + fn casing() { + // Tests that differently cased names don't interfere and we only suggest the matching one. + check_assist( + qualify_path, + r" +//- /lib.rs crate:dep +pub struct FMT; +pub struct fmt; + +//- /main.rs crate:main deps:dep +fn main() { + FMT$0; +} +", + r" +fn main() { + dep::FMT; +} +", + ); + } + + #[test] + fn keep_generic_annotations() { + check_assist( + qualify_path, + r" +//- /lib.rs crate:dep +pub mod generic { pub struct Thing<'a, T>(&'a T); } + +//- /main.rs crate:main deps:dep +fn foo() -> Thin$0g<'static, ()> {} + +fn main() {} +", + r" +fn foo() -> dep::generic::Thing<'static, ()> {} + +fn main() {} +", + ); + } + + #[test] + fn keep_generic_annotations_leading_colon() { + check_assist( + qualify_path, + r" +//- /lib.rs crate:dep +pub mod generic { pub struct Thing<'a, T>(&'a T); } + +//- /main.rs crate:main deps:dep +fn foo() -> Thin$0g::<'static, ()> {} + +fn main() {} +", + r" +fn foo() -> dep::generic::Thing::<'static, ()> {} + +fn main() {} +", + ); + } + + #[test] + fn associated_struct_const_generic() { + check_assist( + qualify_path, + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + TestStruct::<()>::TEST_CONST$0 + } + ", + r" + mod test_mod { + pub struct TestStruct {} + impl TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + test_mod::TestStruct::<()>::TEST_CONST + } + ", + ); + } + + #[test] + fn associated_trait_const_generic() { + check_assist( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + test_mod::TestStruct::<()>::TEST_CONST$0 + } + ", + r" + mod test_mod { + pub trait TestTrait { + const TEST_CONST: u8; + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + const TEST_CONST: u8 = 42; + } + } + + fn main() { + as test_mod::TestTrait>::TEST_CONST + } + ", + ); + } + + #[test] + fn trait_method_generic() { + check_assist( + qualify_path, + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_struct.test_meth$0od::<()>() + } + ", + r" + mod test_mod { + pub trait TestTrait { + fn test_method(&self); + } + pub struct TestStruct {} + impl TestTrait for TestStruct { + fn test_method(&self) {} + } + } + + fn main() { + let test_struct = test_mod::TestStruct {}; + test_mod::TestTrait::test_method::<()>(&test_struct) + } + ", + ); + } +} diff --git a/crates/ide_assists/src/handlers/raw_string.rs b/crates/ide_assists/src/handlers/raw_string.rs new file mode 100644 index 000000000..d95267607 --- /dev/null +++ b/crates/ide_assists/src/handlers/raw_string.rs @@ -0,0 +1,512 @@ +use std::borrow::Cow; + +use syntax::{ast, AstToken, TextRange, TextSize}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: make_raw_string +// +// Adds `r#` to a plain string literal. +// +// ``` +// fn main() { +// "Hello,$0 World!"; +// } +// ``` +// -> +// ``` +// fn main() { +// r#"Hello, World!"#; +// } +// ``` +pub(crate) fn make_raw_string(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let token = ctx.find_token_at_offset::()?; + if token.is_raw() { + return None; + } + let value = token.value()?; + let target = token.syntax().text_range(); + acc.add( + AssistId("make_raw_string", AssistKind::RefactorRewrite), + "Rewrite as raw string", + target, + |edit| { + let hashes = "#".repeat(required_hashes(&value).max(1)); + if matches!(value, Cow::Borrowed(_)) { + // Avoid replacing the whole string to better position the cursor. + edit.insert(token.syntax().text_range().start(), format!("r{}", hashes)); + edit.insert(token.syntax().text_range().end(), format!("{}", hashes)); + } else { + edit.replace( + token.syntax().text_range(), + format!("r{}\"{}\"{}", hashes, value, hashes), + ); + } + }, + ) +} + +// Assist: make_usual_string +// +// Turns a raw string into a plain string. +// +// ``` +// fn main() { +// r#"Hello,$0 "World!""#; +// } +// ``` +// -> +// ``` +// fn main() { +// "Hello, \"World!\""; +// } +// ``` +pub(crate) fn make_usual_string(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let token = ctx.find_token_at_offset::()?; + if !token.is_raw() { + return None; + } + let value = token.value()?; + let target = token.syntax().text_range(); + acc.add( + AssistId("make_usual_string", AssistKind::RefactorRewrite), + "Rewrite as regular string", + target, + |edit| { + // parse inside string to escape `"` + let escaped = value.escape_default().to_string(); + if let Some(offsets) = token.quote_offsets() { + if token.text()[offsets.contents - token.syntax().text_range().start()] == escaped { + edit.replace(offsets.quotes.0, "\""); + edit.replace(offsets.quotes.1, "\""); + return; + } + } + + edit.replace(token.syntax().text_range(), format!("\"{}\"", escaped)); + }, + ) +} + +// Assist: add_hash +// +// Adds a hash to a raw string literal. +// +// ``` +// fn main() { +// r#"Hello,$0 World!"#; +// } +// ``` +// -> +// ``` +// fn main() { +// r##"Hello, World!"##; +// } +// ``` +pub(crate) fn add_hash(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let token = ctx.find_token_at_offset::()?; + if !token.is_raw() { + return None; + } + let text_range = token.syntax().text_range(); + let target = text_range; + acc.add(AssistId("add_hash", AssistKind::Refactor), "Add #", target, |edit| { + edit.insert(text_range.start() + TextSize::of('r'), "#"); + edit.insert(text_range.end(), "#"); + }) +} + +// Assist: remove_hash +// +// Removes a hash from a raw string literal. +// +// ``` +// fn main() { +// r#"Hello,$0 World!"#; +// } +// ``` +// -> +// ``` +// fn main() { +// r"Hello, World!"; +// } +// ``` +pub(crate) fn remove_hash(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let token = ctx.find_token_at_offset::()?; + if !token.is_raw() { + return None; + } + + let text = token.text(); + if !text.starts_with("r#") && text.ends_with('#') { + return None; + } + + let existing_hashes = text.chars().skip(1).take_while(|&it| it == '#').count(); + + let text_range = token.syntax().text_range(); + let internal_text = &text[token.text_range_between_quotes()? - text_range.start()]; + + if existing_hashes == required_hashes(internal_text) { + mark::hit!(cant_remove_required_hash); + return None; + } + + acc.add(AssistId("remove_hash", AssistKind::RefactorRewrite), "Remove #", text_range, |edit| { + edit.delete(TextRange::at(text_range.start() + TextSize::of('r'), TextSize::of('#'))); + edit.delete(TextRange::new(text_range.end() - TextSize::of('#'), text_range.end())); + }) +} + +fn required_hashes(s: &str) -> usize { + let mut res = 0usize; + for idx in s.match_indices('"').map(|(i, _)| i) { + let (_, sub) = s.split_at(idx + 1); + let n_hashes = sub.chars().take_while(|c| *c == '#').count(); + res = res.max(n_hashes + 1) + } + res +} + +#[test] +fn test_required_hashes() { + assert_eq!(0, required_hashes("abc")); + assert_eq!(0, required_hashes("###")); + assert_eq!(1, required_hashes("\"")); + assert_eq!(2, required_hashes("\"#abc")); + assert_eq!(0, required_hashes("#abc")); + assert_eq!(3, required_hashes("#ab\"##c")); + assert_eq!(5, required_hashes("#ab\"##\"####c")); +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn make_raw_string_target() { + check_assist_target( + make_raw_string, + r#" + fn f() { + let s = $0"random\nstring"; + } + "#, + r#""random\nstring""#, + ); + } + + #[test] + fn make_raw_string_works() { + check_assist( + make_raw_string, + r#" +fn f() { + let s = $0"random\nstring"; +} +"#, + r##" +fn f() { + let s = r#"random +string"#; +} +"##, + ) + } + + #[test] + fn make_raw_string_works_inside_macros() { + check_assist( + make_raw_string, + r#" + fn f() { + format!($0"x = {}", 92) + } + "#, + r##" + fn f() { + format!(r#"x = {}"#, 92) + } + "##, + ) + } + + #[test] + fn make_raw_string_hashes_inside_works() { + check_assist( + make_raw_string, + r###" +fn f() { + let s = $0"#random##\nstring"; +} +"###, + r####" +fn f() { + let s = r#"#random## +string"#; +} +"####, + ) + } + + #[test] + fn make_raw_string_closing_hashes_inside_works() { + check_assist( + make_raw_string, + r###" +fn f() { + let s = $0"#random\"##\nstring"; +} +"###, + r####" +fn f() { + let s = r###"#random"## +string"###; +} +"####, + ) + } + + #[test] + fn make_raw_string_nothing_to_unescape_works() { + check_assist( + make_raw_string, + r#" + fn f() { + let s = $0"random string"; + } + "#, + r##" + fn f() { + let s = r#"random string"#; + } + "##, + ) + } + + #[test] + fn make_raw_string_not_works_on_partial_string() { + check_assist_not_applicable( + make_raw_string, + r#" + fn f() { + let s = "foo$0 + } + "#, + ) + } + + #[test] + fn make_usual_string_not_works_on_partial_string() { + check_assist_not_applicable( + make_usual_string, + r#" + fn main() { + let s = r#"bar$0 + } + "#, + ) + } + + #[test] + fn add_hash_target() { + check_assist_target( + add_hash, + r#" + fn f() { + let s = $0r"random string"; + } + "#, + r#"r"random string""#, + ); + } + + #[test] + fn add_hash_works() { + check_assist( + add_hash, + r#" + fn f() { + let s = $0r"random string"; + } + "#, + r##" + fn f() { + let s = r#"random string"#; + } + "##, + ) + } + + #[test] + fn add_more_hash_works() { + check_assist( + add_hash, + r##" + fn f() { + let s = $0r#"random"string"#; + } + "##, + r###" + fn f() { + let s = r##"random"string"##; + } + "###, + ) + } + + #[test] + fn add_hash_not_works() { + check_assist_not_applicable( + add_hash, + r#" + fn f() { + let s = $0"random string"; + } + "#, + ); + } + + #[test] + fn remove_hash_target() { + check_assist_target( + remove_hash, + r##" + fn f() { + let s = $0r#"random string"#; + } + "##, + r##"r#"random string"#"##, + ); + } + + #[test] + fn remove_hash_works() { + check_assist( + remove_hash, + r##"fn f() { let s = $0r#"random string"#; }"##, + r#"fn f() { let s = r"random string"; }"#, + ) + } + + #[test] + fn cant_remove_required_hash() { + mark::check!(cant_remove_required_hash); + check_assist_not_applicable( + remove_hash, + r##" + fn f() { + let s = $0r#"random"str"ing"#; + } + "##, + ) + } + + #[test] + fn remove_more_hash_works() { + check_assist( + remove_hash, + r###" + fn f() { + let s = $0r##"random string"##; + } + "###, + r##" + fn f() { + let s = r#"random string"#; + } + "##, + ) + } + + #[test] + fn remove_hash_doesnt_work() { + check_assist_not_applicable(remove_hash, r#"fn f() { let s = $0"random string"; }"#); + } + + #[test] + fn remove_hash_no_hash_doesnt_work() { + check_assist_not_applicable(remove_hash, r#"fn f() { let s = $0r"random string"; }"#); + } + + #[test] + fn make_usual_string_target() { + check_assist_target( + make_usual_string, + r##" + fn f() { + let s = $0r#"random string"#; + } + "##, + r##"r#"random string"#"##, + ); + } + + #[test] + fn make_usual_string_works() { + check_assist( + make_usual_string, + r##" + fn f() { + let s = $0r#"random string"#; + } + "##, + r#" + fn f() { + let s = "random string"; + } + "#, + ) + } + + #[test] + fn make_usual_string_with_quote_works() { + check_assist( + make_usual_string, + r##" + fn f() { + let s = $0r#"random"str"ing"#; + } + "##, + r#" + fn f() { + let s = "random\"str\"ing"; + } + "#, + ) + } + + #[test] + fn make_usual_string_more_hash_works() { + check_assist( + make_usual_string, + r###" + fn f() { + let s = $0r##"random string"##; + } + "###, + r##" + fn f() { + let s = "random string"; + } + "##, + ) + } + + #[test] + fn make_usual_string_not_works() { + check_assist_not_applicable( + make_usual_string, + r#" + fn f() { + let s = $0"random string"; + } + "#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/remove_dbg.rs b/crates/ide_assists/src/handlers/remove_dbg.rs new file mode 100644 index 000000000..6114091f2 --- /dev/null +++ b/crates/ide_assists/src/handlers/remove_dbg.rs @@ -0,0 +1,421 @@ +use syntax::{ + ast::{self, AstNode}, + match_ast, SyntaxElement, TextRange, TextSize, T, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: remove_dbg +// +// Removes `dbg!()` macro call. +// +// ``` +// fn main() { +// $0dbg!(92); +// } +// ``` +// -> +// ``` +// fn main() { +// 92; +// } +// ``` +pub(crate) fn remove_dbg(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let macro_call = ctx.find_node_at_offset::()?; + let new_contents = adjusted_macro_contents(¯o_call)?; + + let macro_text_range = macro_call.syntax().text_range(); + let macro_end = if macro_call.semicolon_token().is_some() { + macro_text_range.end() - TextSize::of(';') + } else { + macro_text_range.end() + }; + + acc.add( + AssistId("remove_dbg", AssistKind::Refactor), + "Remove dbg!()", + macro_text_range, + |builder| { + builder.replace(TextRange::new(macro_text_range.start(), macro_end), new_contents); + }, + ) +} + +fn adjusted_macro_contents(macro_call: &ast::MacroCall) -> Option { + let contents = get_valid_macrocall_contents(¯o_call, "dbg")?; + let macro_text_with_brackets = macro_call.token_tree()?.syntax().text(); + let macro_text_in_brackets = macro_text_with_brackets.slice(TextRange::new( + TextSize::of('('), + macro_text_with_brackets.len() - TextSize::of(')'), + )); + + Some( + if !is_leaf_or_control_flow_expr(macro_call) + && needs_parentheses_around_macro_contents(contents) + { + format!("({})", macro_text_in_brackets) + } else { + macro_text_in_brackets.to_string() + }, + ) +} + +fn is_leaf_or_control_flow_expr(macro_call: &ast::MacroCall) -> bool { + macro_call.syntax().next_sibling().is_none() + || match macro_call.syntax().parent() { + Some(parent) => match_ast! { + match parent { + ast::Condition(_it) => true, + ast::MatchExpr(_it) => true, + _ => false, + } + }, + None => false, + } +} + +/// Verifies that the given macro_call actually matches the given name +/// and contains proper ending tokens, then returns the contents between the ending tokens +fn get_valid_macrocall_contents( + macro_call: &ast::MacroCall, + macro_name: &str, +) -> Option> { + let path = macro_call.path()?; + let name_ref = path.segment()?.name_ref()?; + + // Make sure it is actually a dbg-macro call, dbg followed by ! + let excl = path.syntax().next_sibling_or_token()?; + if name_ref.text() != macro_name || excl.kind() != T![!] { + return None; + } + + let mut children_with_tokens = macro_call.token_tree()?.syntax().children_with_tokens(); + let first_child = children_with_tokens.next()?; + let mut contents_between_brackets = children_with_tokens.collect::>(); + let last_child = contents_between_brackets.pop()?; + + if contents_between_brackets.is_empty() { + None + } else { + match (first_child.kind(), last_child.kind()) { + (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']) => { + Some(contents_between_brackets) + } + _ => None, + } + } +} + +fn needs_parentheses_around_macro_contents(macro_contents: Vec) -> bool { + if macro_contents.len() < 2 { + return false; + } + let mut macro_contents = macro_contents.into_iter().peekable(); + let mut unpaired_brackets_in_contents = Vec::new(); + while let Some(element) = macro_contents.next() { + match element.kind() { + T!['('] | T!['['] | T!['{'] => unpaired_brackets_in_contents.push(element), + T![')'] => { + if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['(']) + { + return true; + } + } + T![']'] => { + if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['[']) + { + return true; + } + } + T!['}'] => { + if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['{']) + { + return true; + } + } + symbol_kind => { + let symbol_not_in_bracket = unpaired_brackets_in_contents.is_empty(); + if symbol_not_in_bracket + && symbol_kind != T![:] // paths + && (symbol_kind != T![.] // field/method access + || macro_contents // range expressions consist of two SyntaxKind::Dot in macro invocations + .peek() + .map(|element| element.kind() == T![.]) + .unwrap_or(false)) + && symbol_kind != T![?] // try operator + && (symbol_kind.is_punct() || symbol_kind == T![as]) + { + return true; + } + } + } + } + !unpaired_brackets_in_contents.is_empty() +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn test_remove_dbg() { + check_assist(remove_dbg, "$0dbg!(1 + 1)", "1 + 1"); + + check_assist(remove_dbg, "dbg!$0((1 + 1))", "(1 + 1)"); + + check_assist(remove_dbg, "dbg!(1 $0+ 1)", "1 + 1"); + + check_assist(remove_dbg, "let _ = $0dbg!(1 + 1)", "let _ = 1 + 1"); + + check_assist( + remove_dbg, + " +fn foo(n: usize) { + if let Some(_) = dbg!(n.$0checked_sub(4)) { + // ... + } +} +", + " +fn foo(n: usize) { + if let Some(_) = n.checked_sub(4) { + // ... + } +} +", + ); + + check_assist(remove_dbg, "$0dbg!(Foo::foo_test()).bar()", "Foo::foo_test().bar()"); + } + + #[test] + fn test_remove_dbg_with_brackets_and_braces() { + check_assist(remove_dbg, "dbg![$01 + 1]", "1 + 1"); + check_assist(remove_dbg, "dbg!{$01 + 1}", "1 + 1"); + } + + #[test] + fn test_remove_dbg_not_applicable() { + check_assist_not_applicable(remove_dbg, "$0vec![1, 2, 3]"); + check_assist_not_applicable(remove_dbg, "$0dbg(5, 6, 7)"); + check_assist_not_applicable(remove_dbg, "$0dbg!(5, 6, 7"); + } + + #[test] + fn test_remove_dbg_target() { + check_assist_target( + remove_dbg, + " +fn foo(n: usize) { + if let Some(_) = dbg!(n.$0checked_sub(4)) { + // ... + } +} +", + "dbg!(n.checked_sub(4))", + ); + } + + #[test] + fn test_remove_dbg_keep_semicolon() { + // https://github.com/rust-analyzer/rust-analyzer/issues/5129#issuecomment-651399779 + // not quite though + // adding a comment at the end of the line makes + // the ast::MacroCall to include the semicolon at the end + check_assist( + remove_dbg, + r#"let res = $0dbg!(1 * 20); // needless comment"#, + r#"let res = 1 * 20; // needless comment"#, + ); + } + + #[test] + fn remove_dbg_from_non_leaf_simple_expression() { + check_assist( + remove_dbg, + " +fn main() { + let mut a = 1; + while dbg!$0(a) < 10000 { + a += 1; + } +} +", + " +fn main() { + let mut a = 1; + while a < 10000 { + a += 1; + } +} +", + ); + } + + #[test] + fn test_remove_dbg_keep_expression() { + check_assist( + remove_dbg, + r#"let res = $0dbg!(a + b).foo();"#, + r#"let res = (a + b).foo();"#, + ); + + check_assist(remove_dbg, r#"let res = $0dbg!(2 + 2) * 5"#, r#"let res = (2 + 2) * 5"#); + check_assist(remove_dbg, r#"let res = $0dbg![2 + 2] * 5"#, r#"let res = (2 + 2) * 5"#); + } + + #[test] + fn test_remove_dbg_method_chaining() { + check_assist( + remove_dbg, + r#"let res = $0dbg!(foo().bar()).baz();"#, + r#"let res = foo().bar().baz();"#, + ); + check_assist( + remove_dbg, + r#"let res = $0dbg!(foo.bar()).baz();"#, + r#"let res = foo.bar().baz();"#, + ); + } + + #[test] + fn test_remove_dbg_field_chaining() { + check_assist(remove_dbg, r#"let res = $0dbg!(foo.bar).baz;"#, r#"let res = foo.bar.baz;"#); + } + + #[test] + fn test_remove_dbg_from_inside_fn() { + check_assist_target( + remove_dbg, + r#" +fn square(x: u32) -> u32 { + x * x +} + +fn main() { + let x = square(dbg$0!(5 + 10)); + println!("{}", x); +}"#, + "dbg!(5 + 10)", + ); + + check_assist( + remove_dbg, + r#" +fn square(x: u32) -> u32 { + x * x +} + +fn main() { + let x = square(dbg$0!(5 + 10)); + println!("{}", x); +}"#, + r#" +fn square(x: u32) -> u32 { + x * x +} + +fn main() { + let x = square(5 + 10); + println!("{}", x); +}"#, + ); + } + + #[test] + fn test_remove_dbg_try_expr() { + check_assist( + remove_dbg, + r#"let res = $0dbg!(result?).foo();"#, + r#"let res = result?.foo();"#, + ); + } + + #[test] + fn test_remove_dbg_await_expr() { + check_assist( + remove_dbg, + r#"let res = $0dbg!(fut.await).foo();"#, + r#"let res = fut.await.foo();"#, + ); + } + + #[test] + fn test_remove_dbg_as_cast() { + check_assist( + remove_dbg, + r#"let res = $0dbg!(3 as usize).foo();"#, + r#"let res = (3 as usize).foo();"#, + ); + } + + #[test] + fn test_remove_dbg_index_expr() { + check_assist( + remove_dbg, + r#"let res = $0dbg!(array[3]).foo();"#, + r#"let res = array[3].foo();"#, + ); + check_assist( + remove_dbg, + r#"let res = $0dbg!(tuple.3).foo();"#, + r#"let res = tuple.3.foo();"#, + ); + } + + #[test] + fn test_remove_dbg_range_expr() { + check_assist( + remove_dbg, + r#"let res = $0dbg!(foo..bar).foo();"#, + r#"let res = (foo..bar).foo();"#, + ); + check_assist( + remove_dbg, + r#"let res = $0dbg!(foo..=bar).foo();"#, + r#"let res = (foo..=bar).foo();"#, + ); + } + + #[test] + fn test_remove_dbg_followed_by_block() { + check_assist( + remove_dbg, + r#"fn foo() { + if $0dbg!(x || y) {} +}"#, + r#"fn foo() { + if x || y {} +}"#, + ); + check_assist( + remove_dbg, + r#"fn foo() { + while let foo = $0dbg!(&x) {} +}"#, + r#"fn foo() { + while let foo = &x {} +}"#, + ); + check_assist( + remove_dbg, + r#"fn foo() { + if let foo = $0dbg!(&x) {} +}"#, + r#"fn foo() { + if let foo = &x {} +}"#, + ); + check_assist( + remove_dbg, + r#"fn foo() { + match $0dbg!(&x) {} +}"#, + r#"fn foo() { + match &x {} +}"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/remove_mut.rs b/crates/ide_assists/src/handlers/remove_mut.rs new file mode 100644 index 000000000..30d36dacd --- /dev/null +++ b/crates/ide_assists/src/handlers/remove_mut.rs @@ -0,0 +1,37 @@ +use syntax::{SyntaxKind, TextRange, T}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: remove_mut +// +// Removes the `mut` keyword. +// +// ``` +// impl Walrus { +// fn feed(&mut$0 self, amount: u32) {} +// } +// ``` +// -> +// ``` +// impl Walrus { +// fn feed(&self, amount: u32) {} +// } +// ``` +pub(crate) fn remove_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let mut_token = ctx.find_token_syntax_at_offset(T![mut])?; + let delete_from = mut_token.text_range().start(); + let delete_to = match mut_token.next_token() { + Some(it) if it.kind() == SyntaxKind::WHITESPACE => it.text_range().end(), + _ => mut_token.text_range().end(), + }; + + let target = mut_token.text_range(); + acc.add( + AssistId("remove_mut", AssistKind::Refactor), + "Remove `mut` keyword", + target, + |builder| { + builder.delete(TextRange::new(delete_from, delete_to)); + }, + ) +} diff --git a/crates/ide_assists/src/handlers/remove_unused_param.rs b/crates/ide_assists/src/handlers/remove_unused_param.rs new file mode 100644 index 000000000..c961680e2 --- /dev/null +++ b/crates/ide_assists/src/handlers/remove_unused_param.rs @@ -0,0 +1,288 @@ +use ide_db::{base_db::FileId, defs::Definition, search::FileReference}; +use syntax::{ + algo::find_node_at_range, + ast::{self, ArgListOwner}, + AstNode, SourceFile, SyntaxKind, SyntaxNode, TextRange, T, +}; +use test_utils::mark; +use SyntaxKind::WHITESPACE; + +use crate::{ + assist_context::AssistBuilder, utils::next_prev, AssistContext, AssistId, AssistKind, Assists, +}; + +// Assist: remove_unused_param +// +// Removes unused function parameter. +// +// ``` +// fn frobnicate(x: i32$0) {} +// +// fn main() { +// frobnicate(92); +// } +// ``` +// -> +// ``` +// fn frobnicate() {} +// +// fn main() { +// frobnicate(); +// } +// ``` +pub(crate) fn remove_unused_param(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let param: ast::Param = ctx.find_node_at_offset()?; + let ident_pat = match param.pat()? { + ast::Pat::IdentPat(it) => it, + _ => return None, + }; + let func = param.syntax().ancestors().find_map(ast::Fn::cast)?; + let param_position = func.param_list()?.params().position(|it| it == param)?; + + let fn_def = { + let func = ctx.sema.to_def(&func)?; + Definition::ModuleDef(func.into()) + }; + + let param_def = { + let local = ctx.sema.to_def(&ident_pat)?; + Definition::Local(local) + }; + if param_def.usages(&ctx.sema).at_least_one() { + mark::hit!(keep_used); + return None; + } + acc.add( + AssistId("remove_unused_param", AssistKind::Refactor), + "Remove unused parameter", + param.syntax().text_range(), + |builder| { + builder.delete(range_to_remove(param.syntax())); + for (file_id, references) in fn_def.usages(&ctx.sema).all() { + process_usages(ctx, builder, file_id, references, param_position); + } + }, + ) +} + +fn process_usages( + ctx: &AssistContext, + builder: &mut AssistBuilder, + file_id: FileId, + references: Vec, + arg_to_remove: usize, +) { + let source_file = ctx.sema.parse(file_id); + builder.edit_file(file_id); + for usage in references { + if let Some(text_range) = process_usage(&source_file, usage, arg_to_remove) { + builder.delete(text_range); + } + } +} + +fn process_usage( + source_file: &SourceFile, + FileReference { range, .. }: FileReference, + arg_to_remove: usize, +) -> Option { + let call_expr: ast::CallExpr = find_node_at_range(source_file.syntax(), range)?; + let call_expr_range = call_expr.expr()?.syntax().text_range(); + if !call_expr_range.contains_range(range) { + return None; + } + let arg = call_expr.arg_list()?.args().nth(arg_to_remove)?; + Some(range_to_remove(arg.syntax())) +} + +fn range_to_remove(node: &SyntaxNode) -> TextRange { + let up_to_comma = next_prev().find_map(|dir| { + node.siblings_with_tokens(dir) + .filter_map(|it| it.into_token()) + .find(|it| it.kind() == T![,]) + .map(|it| (dir, it)) + }); + if let Some((dir, token)) = up_to_comma { + if node.next_sibling().is_some() { + let up_to_space = token + .siblings_with_tokens(dir) + .skip(1) + .take_while(|it| it.kind() == WHITESPACE) + .last() + .and_then(|it| it.into_token()); + return node + .text_range() + .cover(up_to_space.map_or(token.text_range(), |it| it.text_range())); + } + node.text_range().cover(token.text_range()) + } else { + node.text_range() + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn remove_unused() { + check_assist( + remove_unused_param, + r#" +fn a() { foo(9, 2) } +fn foo(x: i32, $0y: i32) { x; } +fn b() { foo(9, 2,) } +"#, + r#" +fn a() { foo(9) } +fn foo(x: i32) { x; } +fn b() { foo(9, ) } +"#, + ); + } + + #[test] + fn remove_unused_first_param() { + check_assist( + remove_unused_param, + r#" +fn foo($0x: i32, y: i32) { y; } +fn a() { foo(1, 2) } +fn b() { foo(1, 2,) } +"#, + r#" +fn foo(y: i32) { y; } +fn a() { foo(2) } +fn b() { foo(2,) } +"#, + ); + } + + #[test] + fn remove_unused_single_param() { + check_assist( + remove_unused_param, + r#" +fn foo($0x: i32) { 0; } +fn a() { foo(1) } +fn b() { foo(1, ) } +"#, + r#" +fn foo() { 0; } +fn a() { foo() } +fn b() { foo( ) } +"#, + ); + } + + #[test] + fn remove_unused_surrounded_by_parms() { + check_assist( + remove_unused_param, + r#" +fn foo(x: i32, $0y: i32, z: i32) { x; } +fn a() { foo(1, 2, 3) } +fn b() { foo(1, 2, 3,) } +"#, + r#" +fn foo(x: i32, z: i32) { x; } +fn a() { foo(1, 3) } +fn b() { foo(1, 3,) } +"#, + ); + } + + #[test] + fn remove_unused_qualified_call() { + check_assist( + remove_unused_param, + r#" +mod bar { pub fn foo(x: i32, $0y: i32) { x; } } +fn b() { bar::foo(9, 2) } +"#, + r#" +mod bar { pub fn foo(x: i32) { x; } } +fn b() { bar::foo(9) } +"#, + ); + } + + #[test] + fn remove_unused_turbofished_func() { + check_assist( + remove_unused_param, + r#" +pub fn foo(x: T, $0y: i32) { x; } +fn b() { foo::(9, 2) } +"#, + r#" +pub fn foo(x: T) { x; } +fn b() { foo::(9) } +"#, + ); + } + + #[test] + fn remove_unused_generic_unused_param_func() { + check_assist( + remove_unused_param, + r#" +pub fn foo(x: i32, $0y: T) { x; } +fn b() { foo::(9, 2) } +fn b2() { foo(9, 2) } +"#, + r#" +pub fn foo(x: i32) { x; } +fn b() { foo::(9) } +fn b2() { foo(9) } +"#, + ); + } + + #[test] + fn keep_used() { + mark::check!(keep_used); + check_assist_not_applicable( + remove_unused_param, + r#" +fn foo(x: i32, $0y: i32) { y; } +fn main() { foo(9, 2) } +"#, + ); + } + + #[test] + fn remove_across_files() { + check_assist( + remove_unused_param, + r#" +//- /main.rs +fn foo(x: i32, $0y: i32) { x; } + +mod foo; + +//- /foo.rs +use super::foo; + +fn bar() { + let _ = foo(1, 2); +} +"#, + r#" +//- /main.rs +fn foo(x: i32) { x; } + +mod foo; + +//- /foo.rs +use super::foo; + +fn bar() { + let _ = foo(1); +} +"#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/reorder_fields.rs b/crates/ide_assists/src/handlers/reorder_fields.rs new file mode 100644 index 000000000..fba7d6ddb --- /dev/null +++ b/crates/ide_assists/src/handlers/reorder_fields.rs @@ -0,0 +1,227 @@ +use itertools::Itertools; +use rustc_hash::FxHashMap; + +use hir::{Adt, ModuleDef, PathResolution, Semantics, Struct}; +use ide_db::RootDatabase; +use syntax::{algo, ast, match_ast, AstNode, SyntaxKind, SyntaxKind::*, SyntaxNode}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: reorder_fields +// +// Reorder the fields of record literals and record patterns in the same order as in +// the definition. +// +// ``` +// struct Foo {foo: i32, bar: i32}; +// const test: Foo = $0Foo {bar: 0, foo: 1} +// ``` +// -> +// ``` +// struct Foo {foo: i32, bar: i32}; +// const test: Foo = Foo {foo: 1, bar: 0} +// ``` +// +pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + reorder::(acc, ctx).or_else(|| reorder::(acc, ctx)) +} + +fn reorder(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let record = ctx.find_node_at_offset::()?; + let path = record.syntax().children().find_map(ast::Path::cast)?; + + let ranks = compute_fields_ranks(&path, &ctx)?; + + let fields = get_fields(&record.syntax()); + let sorted_fields = sorted_by_rank(&fields, |node| { + *ranks.get(&get_field_name(node)).unwrap_or(&usize::max_value()) + }); + + if sorted_fields == fields { + mark::hit!(reorder_sorted_fields); + return None; + } + + let target = record.syntax().text_range(); + acc.add( + AssistId("reorder_fields", AssistKind::RefactorRewrite), + "Reorder record fields", + target, + |edit| { + let mut rewriter = algo::SyntaxRewriter::default(); + for (old, new) in fields.iter().zip(&sorted_fields) { + rewriter.replace(old, new); + } + edit.rewrite(rewriter); + }, + ) +} + +fn get_fields_kind(node: &SyntaxNode) -> Vec { + match node.kind() { + RECORD_EXPR => vec![RECORD_EXPR_FIELD], + RECORD_PAT => vec![RECORD_PAT_FIELD, IDENT_PAT], + _ => vec![], + } +} + +fn get_field_name(node: &SyntaxNode) -> String { + let res = match_ast! { + match node { + ast::RecordExprField(field) => field.field_name().map(|it| it.to_string()), + ast::RecordPatField(field) => field.field_name().map(|it| it.to_string()), + _ => None, + } + }; + res.unwrap_or_default() +} + +fn get_fields(record: &SyntaxNode) -> Vec { + let kinds = get_fields_kind(record); + record.children().flat_map(|n| n.children()).filter(|n| kinds.contains(&n.kind())).collect() +} + +fn sorted_by_rank( + fields: &[SyntaxNode], + get_rank: impl Fn(&SyntaxNode) -> usize, +) -> Vec { + fields.iter().cloned().sorted_by_key(get_rank).collect() +} + +fn struct_definition(path: &ast::Path, sema: &Semantics) -> Option { + match sema.resolve_path(path) { + Some(PathResolution::Def(ModuleDef::Adt(Adt::Struct(s)))) => Some(s), + _ => None, + } +} + +fn compute_fields_ranks(path: &ast::Path, ctx: &AssistContext) -> Option> { + Some( + struct_definition(path, &ctx.sema)? + .fields(ctx.db()) + .iter() + .enumerate() + .map(|(idx, field)| (field.name(ctx.db()).to_string(), idx)) + .collect(), + ) +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn reorder_sorted_fields() { + mark::check!(reorder_sorted_fields); + check_assist_not_applicable( + reorder_fields, + r#" +struct Foo { + foo: i32, + bar: i32, +} + +const test: Foo = $0Foo { foo: 0, bar: 0 }; +"#, + ) + } + + #[test] + fn trivial_empty_fields() { + check_assist_not_applicable( + reorder_fields, + r#" +struct Foo {}; +const test: Foo = $0Foo {} +"#, + ) + } + + #[test] + fn reorder_struct_fields() { + check_assist( + reorder_fields, + r#" +struct Foo {foo: i32, bar: i32}; +const test: Foo = $0Foo {bar: 0, foo: 1} +"#, + r#" +struct Foo {foo: i32, bar: i32}; +const test: Foo = Foo {foo: 1, bar: 0} +"#, + ) + } + + #[test] + fn reorder_struct_pattern() { + check_assist( + reorder_fields, + r#" +struct Foo { foo: i64, bar: i64, baz: i64 } + +fn f(f: Foo) -> { + match f { + $0Foo { baz: 0, ref mut bar, .. } => (), + _ => () + } +} +"#, + r#" +struct Foo { foo: i64, bar: i64, baz: i64 } + +fn f(f: Foo) -> { + match f { + Foo { ref mut bar, baz: 0, .. } => (), + _ => () + } +} +"#, + ) + } + + #[test] + fn reorder_with_extra_field() { + check_assist( + reorder_fields, + r#" +struct Foo { + foo: String, + bar: String, +} + +impl Foo { + fn new() -> Foo { + let foo = String::new(); + $0Foo { + bar: foo.clone(), + extra: "Extra field", + foo, + } + } +} +"#, + r#" +struct Foo { + foo: String, + bar: String, +} + +impl Foo { + fn new() -> Foo { + let foo = String::new(); + Foo { + foo, + bar: foo.clone(), + extra: "Extra field", + } + } +} +"#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/reorder_impl.rs b/crates/ide_assists/src/handlers/reorder_impl.rs new file mode 100644 index 000000000..309f291c8 --- /dev/null +++ b/crates/ide_assists/src/handlers/reorder_impl.rs @@ -0,0 +1,201 @@ +use itertools::Itertools; +use rustc_hash::FxHashMap; + +use hir::{PathResolution, Semantics}; +use ide_db::RootDatabase; +use syntax::{ + algo, + ast::{self, NameOwner}, + AstNode, +}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: reorder_impl +// +// Reorder the methods of an `impl Trait`. The methods will be ordered +// in the same order as in the trait definition. +// +// ``` +// trait Foo { +// fn a() {} +// fn b() {} +// fn c() {} +// } +// +// struct Bar; +// $0impl Foo for Bar { +// fn b() {} +// fn c() {} +// fn a() {} +// } +// ``` +// -> +// ``` +// trait Foo { +// fn a() {} +// fn b() {} +// fn c() {} +// } +// +// struct Bar; +// impl Foo for Bar { +// fn a() {} +// fn b() {} +// fn c() {} +// } +// ``` +// +pub(crate) fn reorder_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let impl_ast = ctx.find_node_at_offset::()?; + let items = impl_ast.assoc_item_list()?; + let methods = get_methods(&items); + + let path = impl_ast + .trait_() + .and_then(|t| match t { + ast::Type::PathType(path) => Some(path), + _ => None, + })? + .path()?; + + let ranks = compute_method_ranks(&path, ctx)?; + let sorted: Vec<_> = methods + .iter() + .cloned() + .sorted_by_key(|f| { + f.name().and_then(|n| ranks.get(&n.to_string()).copied()).unwrap_or(usize::max_value()) + }) + .collect(); + + // Don't edit already sorted methods: + if methods == sorted { + mark::hit!(not_applicable_if_sorted); + return None; + } + + let target = items.syntax().text_range(); + acc.add(AssistId("reorder_impl", AssistKind::RefactorRewrite), "Sort methods", target, |edit| { + let mut rewriter = algo::SyntaxRewriter::default(); + for (old, new) in methods.iter().zip(&sorted) { + rewriter.replace(old.syntax(), new.syntax()); + } + edit.rewrite(rewriter); + }) +} + +fn compute_method_ranks(path: &ast::Path, ctx: &AssistContext) -> Option> { + let td = trait_definition(path, &ctx.sema)?; + + Some( + td.items(ctx.db()) + .iter() + .flat_map(|i| match i { + hir::AssocItem::Function(f) => Some(f), + _ => None, + }) + .enumerate() + .map(|(idx, func)| ((func.name(ctx.db()).to_string(), idx))) + .collect(), + ) +} + +fn trait_definition(path: &ast::Path, sema: &Semantics) -> Option { + match sema.resolve_path(path)? { + PathResolution::Def(hir::ModuleDef::Trait(trait_)) => Some(trait_), + _ => None, + } +} + +fn get_methods(items: &ast::AssocItemList) -> Vec { + items + .assoc_items() + .flat_map(|i| match i { + ast::AssocItem::Fn(f) => Some(f), + _ => None, + }) + .filter(|f| f.name().is_some()) + .collect() +} + +#[cfg(test)] +mod tests { + use test_utils::mark; + + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn not_applicable_if_sorted() { + mark::check!(not_applicable_if_sorted); + check_assist_not_applicable( + reorder_impl, + r#" +trait Bar { + fn a() {} + fn z() {} + fn b() {} +} +struct Foo; +$0impl Bar for Foo { + fn a() {} + fn z() {} + fn b() {} +} + "#, + ) + } + + #[test] + fn not_applicable_if_empty() { + check_assist_not_applicable( + reorder_impl, + r#" +trait Bar {}; +struct Foo; +$0impl Bar for Foo {} + "#, + ) + } + + #[test] + fn reorder_impl_trait_methods() { + check_assist( + reorder_impl, + r#" +trait Bar { + fn a() {} + fn c() {} + fn b() {} + fn d() {} +} + +struct Foo; +$0impl Bar for Foo { + fn d() {} + fn b() {} + fn c() {} + fn a() {} +} + "#, + r#" +trait Bar { + fn a() {} + fn c() {} + fn b() {} + fn d() {} +} + +struct Foo; +impl Bar for Foo { + fn a() {} + fn c() {} + fn b() {} + fn d() {} +} + "#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs b/crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs new file mode 100644 index 000000000..c69bc5cac --- /dev/null +++ b/crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs @@ -0,0 +1,404 @@ +use ide_db::helpers::mod_path_to_ast; +use ide_db::imports_locator; +use itertools::Itertools; +use syntax::{ + ast::{self, make, AstNode, NameOwner}, + SyntaxKind::{IDENT, WHITESPACE}, + TextSize, +}; + +use crate::{ + assist_context::{AssistBuilder, AssistContext, Assists}, + utils::{ + add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text, + render_snippet, Cursor, DefaultMethods, + }, + AssistId, AssistKind, +}; + +// Assist: replace_derive_with_manual_impl +// +// Converts a `derive` impl into a manual one. +// +// ``` +// # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; } +// #[derive(Deb$0ug, Display)] +// struct S; +// ``` +// -> +// ``` +// # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; } +// #[derive(Display)] +// struct S; +// +// impl Debug for S { +// fn fmt(&self, f: &mut Formatter) -> Result<()> { +// ${0:todo!()} +// } +// } +// ``` +pub(crate) fn replace_derive_with_manual_impl( + acc: &mut Assists, + ctx: &AssistContext, +) -> Option<()> { + let attr = ctx.find_node_at_offset::()?; + + let has_derive = attr + .syntax() + .descendants_with_tokens() + .filter(|t| t.kind() == IDENT) + .find_map(syntax::NodeOrToken::into_token) + .filter(|t| t.text() == "derive") + .is_some(); + if !has_derive { + return None; + } + + let trait_token = ctx.token_at_offset().find(|t| t.kind() == IDENT && t.text() != "derive")?; + let trait_path = make::path_unqualified(make::path_segment(make::name_ref(trait_token.text()))); + + let adt = attr.syntax().parent().and_then(ast::Adt::cast)?; + let annotated_name = adt.name()?; + let insert_pos = adt.syntax().text_range().end(); + + let current_module = ctx.sema.scope(annotated_name.syntax()).module()?; + let current_crate = current_module.krate(); + + let found_traits = imports_locator::find_exact_imports( + &ctx.sema, + current_crate, + trait_token.text().to_string(), + ) + .filter_map(|candidate: either::Either| match candidate { + either::Either::Left(hir::ModuleDef::Trait(trait_)) => Some(trait_), + _ => None, + }) + .flat_map(|trait_| { + current_module + .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_)) + .as_ref() + .map(mod_path_to_ast) + .zip(Some(trait_)) + }); + + let mut no_traits_found = true; + for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) { + add_assist(acc, ctx, &attr, &trait_path, Some(trait_), &adt, &annotated_name, insert_pos)?; + } + if no_traits_found { + add_assist(acc, ctx, &attr, &trait_path, None, &adt, &annotated_name, insert_pos)?; + } + Some(()) +} + +fn add_assist( + acc: &mut Assists, + ctx: &AssistContext, + attr: &ast::Attr, + trait_path: &ast::Path, + trait_: Option, + adt: &ast::Adt, + annotated_name: &ast::Name, + insert_pos: TextSize, +) -> Option<()> { + let target = attr.syntax().text_range(); + let input = attr.token_tree()?; + let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name); + let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?; + + acc.add( + AssistId("replace_derive_with_manual_impl", AssistKind::Refactor), + label, + target, + |builder| { + let impl_def_with_items = + impl_def_from_trait(&ctx.sema, annotated_name, trait_, trait_path); + update_attribute(builder, &input, &trait_name, &attr); + let trait_path = format!("{}", trait_path); + match (ctx.config.snippet_cap, impl_def_with_items) { + (None, _) => { + builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, "")) + } + (Some(cap), None) => builder.insert_snippet( + cap, + insert_pos, + generate_trait_impl_text(adt, &trait_path, " $0"), + ), + (Some(cap), Some((impl_def, first_assoc_item))) => { + let mut cursor = Cursor::Before(first_assoc_item.syntax()); + let placeholder; + if let ast::AssocItem::Fn(ref func) = first_assoc_item { + if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) + { + if m.syntax().text() == "todo!()" { + placeholder = m; + cursor = Cursor::Replace(placeholder.syntax()); + } + } + } + + builder.insert_snippet( + cap, + insert_pos, + format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)), + ) + } + }; + }, + ) +} + +fn impl_def_from_trait( + sema: &hir::Semantics, + annotated_name: &ast::Name, + trait_: Option, + trait_path: &ast::Path, +) -> Option<(ast::Impl, ast::AssocItem)> { + let trait_ = trait_?; + let target_scope = sema.scope(annotated_name.syntax()); + let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No); + if trait_items.is_empty() { + return None; + } + let impl_def = make::impl_trait( + trait_path.clone(), + make::path_unqualified(make::path_segment(make::name_ref(annotated_name.text()))), + ); + let (impl_def, first_assoc_item) = + add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope); + Some((impl_def, first_assoc_item)) +} + +fn update_attribute( + builder: &mut AssistBuilder, + input: &ast::TokenTree, + trait_name: &ast::NameRef, + attr: &ast::Attr, +) { + let new_attr_input = input + .syntax() + .descendants_with_tokens() + .filter(|t| t.kind() == IDENT) + .filter_map(|t| t.into_token().map(|t| t.text().to_string())) + .filter(|t| t != trait_name.text()) + .collect::>(); + let has_more_derives = !new_attr_input.is_empty(); + + if has_more_derives { + let new_attr_input = format!("({})", new_attr_input.iter().format(", ")); + builder.replace(input.syntax().text_range(), new_attr_input); + } else { + let attr_range = attr.syntax().text_range(); + builder.delete(attr_range); + + if let Some(line_break_range) = attr + .syntax() + .next_sibling_or_token() + .filter(|t| t.kind() == WHITESPACE) + .map(|t| t.text_range()) + { + builder.delete(line_break_range); + } + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn add_custom_impl_debug() { + check_assist( + replace_derive_with_manual_impl, + " +mod fmt { + pub struct Error; + pub type Result = Result<(), Error>; + pub struct Formatter<'a>; + pub trait Debug { + fn fmt(&self, f: &mut Formatter<'_>) -> Result; + } +} + +#[derive(Debu$0g)] +struct Foo { + bar: String, +} +", + " +mod fmt { + pub struct Error; + pub type Result = Result<(), Error>; + pub struct Formatter<'a>; + pub trait Debug { + fn fmt(&self, f: &mut Formatter<'_>) -> Result; + } +} + +struct Foo { + bar: String, +} + +impl fmt::Debug for Foo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ${0:todo!()} + } +} +", + ) + } + #[test] + fn add_custom_impl_all() { + check_assist( + replace_derive_with_manual_impl, + " +mod foo { + pub trait Bar { + type Qux; + const Baz: usize = 42; + const Fez: usize; + fn foo(); + fn bar() {} + } +} + +#[derive($0Bar)] +struct Foo { + bar: String, +} +", + " +mod foo { + pub trait Bar { + type Qux; + const Baz: usize = 42; + const Fez: usize; + fn foo(); + fn bar() {} + } +} + +struct Foo { + bar: String, +} + +impl foo::Bar for Foo { + $0type Qux; + + const Baz: usize = 42; + + const Fez: usize; + + fn foo() { + todo!() + } +} +", + ) + } + #[test] + fn add_custom_impl_for_unique_input() { + check_assist( + replace_derive_with_manual_impl, + " +#[derive(Debu$0g)] +struct Foo { + bar: String, +} + ", + " +struct Foo { + bar: String, +} + +impl Debug for Foo { + $0 +} + ", + ) + } + + #[test] + fn add_custom_impl_for_with_visibility_modifier() { + check_assist( + replace_derive_with_manual_impl, + " +#[derive(Debug$0)] +pub struct Foo { + bar: String, +} + ", + " +pub struct Foo { + bar: String, +} + +impl Debug for Foo { + $0 +} + ", + ) + } + + #[test] + fn add_custom_impl_when_multiple_inputs() { + check_assist( + replace_derive_with_manual_impl, + " +#[derive(Display, Debug$0, Serialize)] +struct Foo {} + ", + " +#[derive(Display, Serialize)] +struct Foo {} + +impl Debug for Foo { + $0 +} + ", + ) + } + + #[test] + fn test_ignore_derive_macro_without_input() { + check_assist_not_applicable( + replace_derive_with_manual_impl, + " +#[derive($0)] +struct Foo {} + ", + ) + } + + #[test] + fn test_ignore_if_cursor_on_param() { + check_assist_not_applicable( + replace_derive_with_manual_impl, + " +#[derive$0(Debug)] +struct Foo {} + ", + ); + + check_assist_not_applicable( + replace_derive_with_manual_impl, + " +#[derive(Debug)$0] +struct Foo {} + ", + ) + } + + #[test] + fn test_ignore_if_not_derive() { + check_assist_not_applicable( + replace_derive_with_manual_impl, + " +#[allow(non_camel_$0case_types)] +struct Foo {} + ", + ) + } +} diff --git a/crates/ide_assists/src/handlers/replace_if_let_with_match.rs b/crates/ide_assists/src/handlers/replace_if_let_with_match.rs new file mode 100644 index 000000000..aee880625 --- /dev/null +++ b/crates/ide_assists/src/handlers/replace_if_let_with_match.rs @@ -0,0 +1,599 @@ +use std::iter; + +use ide_db::{ty_filter::TryEnum, RootDatabase}; +use syntax::{ + ast::{ + self, + edit::{AstNodeEdit, IndentLevel}, + make, + }, + AstNode, +}; + +use crate::{ + utils::{does_pat_match_variant, unwrap_trivial_block}, + AssistContext, AssistId, AssistKind, Assists, +}; + +// Assist: replace_if_let_with_match +// +// Replaces `if let` with an else branch with a `match` expression. +// +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// $0if let Action::Move { distance } = action { +// foo(distance) +// } else { +// bar() +// } +// } +// ``` +// -> +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// match action { +// Action::Move { distance } => foo(distance), +// _ => bar(), +// } +// } +// ``` +pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let if_expr: ast::IfExpr = ctx.find_node_at_offset()?; + let cond = if_expr.condition()?; + let pat = cond.pat()?; + let expr = cond.expr()?; + let then_block = if_expr.then_branch()?; + let else_block = match if_expr.else_branch()? { + ast::ElseBranch::Block(it) => it, + ast::ElseBranch::IfExpr(_) => return None, + }; + + let target = if_expr.syntax().text_range(); + acc.add( + AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite), + "Replace with match", + target, + move |edit| { + let match_expr = { + let then_arm = { + let then_block = then_block.reset_indent().indent(IndentLevel(1)); + let then_expr = unwrap_trivial_block(then_block); + make::match_arm(vec![pat.clone()], then_expr) + }; + let else_arm = { + let pattern = ctx + .sema + .type_of_pat(&pat) + .and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty)) + .map(|it| { + if does_pat_match_variant(&pat, &it.sad_pattern()) { + it.happy_pattern() + } else { + it.sad_pattern() + } + }) + .unwrap_or_else(|| make::wildcard_pat().into()); + let else_expr = unwrap_trivial_block(else_block); + make::match_arm(vec![pattern], else_expr) + }; + let match_expr = + make::expr_match(expr, make::match_arm_list(vec![then_arm, else_arm])); + match_expr.indent(IndentLevel::from_node(if_expr.syntax())) + }; + + edit.replace_ast::(if_expr.into(), match_expr); + }, + ) +} + +// Assist: replace_match_with_if_let +// +// Replaces a binary `match` with a wildcard pattern and no guards with an `if let` expression. +// +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// $0match action { +// Action::Move { distance } => foo(distance), +// _ => bar(), +// } +// } +// ``` +// -> +// ``` +// enum Action { Move { distance: u32 }, Stop } +// +// fn handle(action: Action) { +// if let Action::Move { distance } = action { +// foo(distance) +// } else { +// bar() +// } +// } +// ``` +pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let match_expr: ast::MatchExpr = ctx.find_node_at_offset()?; + let mut arms = match_expr.match_arm_list()?.arms(); + let first_arm = arms.next()?; + let second_arm = arms.next()?; + if arms.next().is_some() || first_arm.guard().is_some() || second_arm.guard().is_some() { + return None; + } + let condition_expr = match_expr.expr()?; + let (if_let_pat, then_expr, else_expr) = if is_pat_wildcard_or_sad(&ctx.sema, &first_arm.pat()?) + { + (second_arm.pat()?, second_arm.expr()?, first_arm.expr()?) + } else if is_pat_wildcard_or_sad(&ctx.sema, &second_arm.pat()?) { + (first_arm.pat()?, first_arm.expr()?, second_arm.expr()?) + } else { + return None; + }; + + let target = match_expr.syntax().text_range(); + acc.add( + AssistId("replace_match_with_if_let", AssistKind::RefactorRewrite), + "Replace with if let", + target, + move |edit| { + let condition = make::condition(condition_expr, Some(if_let_pat)); + let then_block = match then_expr.reset_indent() { + ast::Expr::BlockExpr(block) => block, + expr => make::block_expr(iter::empty(), Some(expr)), + }; + let else_expr = match else_expr { + ast::Expr::BlockExpr(block) + if block.statements().count() == 0 && block.tail_expr().is_none() => + { + None + } + ast::Expr::TupleExpr(tuple) if tuple.fields().count() == 0 => None, + expr => Some(expr), + }; + let if_let_expr = make::expr_if( + condition, + then_block, + else_expr.map(|else_expr| { + ast::ElseBranch::Block(make::block_expr(iter::empty(), Some(else_expr))) + }), + ) + .indent(IndentLevel::from_node(match_expr.syntax())); + + edit.replace_ast::(match_expr.into(), if_let_expr); + }, + ) +} + +fn is_pat_wildcard_or_sad(sema: &hir::Semantics, pat: &ast::Pat) -> bool { + sema.type_of_pat(&pat) + .and_then(|ty| TryEnum::from_ty(sema, &ty)) + .map(|it| it.sad_pattern().syntax().text() == pat.syntax().text()) + .unwrap_or_else(|| matches!(pat, ast::Pat::WildcardPat(_))) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::{check_assist, check_assist_target}; + + #[test] + fn test_replace_if_let_with_match_unwraps_simple_expressions() { + check_assist( + replace_if_let_with_match, + r#" +impl VariantData { + pub fn is_struct(&self) -> bool { + if $0let VariantData::Struct(..) = *self { + true + } else { + false + } + } +} "#, + r#" +impl VariantData { + pub fn is_struct(&self) -> bool { + match *self { + VariantData::Struct(..) => true, + _ => false, + } + } +} "#, + ) + } + + #[test] + fn test_replace_if_let_with_match_doesnt_unwrap_multiline_expressions() { + check_assist( + replace_if_let_with_match, + r#" +fn foo() { + if $0let VariantData::Struct(..) = a { + bar( + 123 + ) + } else { + false + } +} "#, + r#" +fn foo() { + match a { + VariantData::Struct(..) => { + bar( + 123 + ) + } + _ => false, + } +} "#, + ) + } + + #[test] + fn replace_if_let_with_match_target() { + check_assist_target( + replace_if_let_with_match, + r#" +impl VariantData { + pub fn is_struct(&self) -> bool { + if $0let VariantData::Struct(..) = *self { + true + } else { + false + } + } +} "#, + "if let VariantData::Struct(..) = *self { + true + } else { + false + }", + ); + } + + #[test] + fn special_case_option() { + check_assist( + replace_if_let_with_match, + r#" +enum Option { Some(T), None } +use Option::*; + +fn foo(x: Option) { + $0if let Some(x) = x { + println!("{}", x) + } else { + println!("none") + } +} + "#, + r#" +enum Option { Some(T), None } +use Option::*; + +fn foo(x: Option) { + match x { + Some(x) => println!("{}", x), + None => println!("none"), + } +} + "#, + ); + } + + #[test] + fn special_case_inverted_option() { + check_assist( + replace_if_let_with_match, + r#" +enum Option { Some(T), None } +use Option::*; + +fn foo(x: Option) { + $0if let None = x { + println!("none") + } else { + println!("some") + } +} + "#, + r#" +enum Option { Some(T), None } +use Option::*; + +fn foo(x: Option) { + match x { + None => println!("none"), + Some(_) => println!("some"), + } +} + "#, + ); + } + + #[test] + fn special_case_result() { + check_assist( + replace_if_let_with_match, + r#" +enum Result { Ok(T), Err(E) } +use Result::*; + +fn foo(x: Result) { + $0if let Ok(x) = x { + println!("{}", x) + } else { + println!("none") + } +} + "#, + r#" +enum Result { Ok(T), Err(E) } +use Result::*; + +fn foo(x: Result) { + match x { + Ok(x) => println!("{}", x), + Err(_) => println!("none"), + } +} + "#, + ); + } + + #[test] + fn special_case_inverted_result() { + check_assist( + replace_if_let_with_match, + r#" +enum Result { Ok(T), Err(E) } +use Result::*; + +fn foo(x: Result) { + $0if let Err(x) = x { + println!("{}", x) + } else { + println!("ok") + } +} + "#, + r#" +enum Result { Ok(T), Err(E) } +use Result::*; + +fn foo(x: Result) { + match x { + Err(x) => println!("{}", x), + Ok(_) => println!("ok"), + } +} + "#, + ); + } + + #[test] + fn nested_indent() { + check_assist( + replace_if_let_with_match, + r#" +fn main() { + if true { + $0if let Ok(rel_path) = path.strip_prefix(root_path) { + let rel_path = RelativePathBuf::from_path(rel_path).ok()?; + Some((*id, rel_path)) + } else { + None + } + } +} +"#, + r#" +fn main() { + if true { + match path.strip_prefix(root_path) { + Ok(rel_path) => { + let rel_path = RelativePathBuf::from_path(rel_path).ok()?; + Some((*id, rel_path)) + } + _ => None, + } + } +} +"#, + ) + } + + #[test] + fn test_replace_match_with_if_let_unwraps_simple_expressions() { + check_assist( + replace_match_with_if_let, + r#" +impl VariantData { + pub fn is_struct(&self) -> bool { + $0match *self { + VariantData::Struct(..) => true, + _ => false, + } + } +} "#, + r#" +impl VariantData { + pub fn is_struct(&self) -> bool { + if let VariantData::Struct(..) = *self { + true + } else { + false + } + } +} "#, + ) + } + + #[test] + fn test_replace_match_with_if_let_doesnt_unwrap_multiline_expressions() { + check_assist( + replace_match_with_if_let, + r#" +fn foo() { + $0match a { + VariantData::Struct(..) => { + bar( + 123 + ) + } + _ => false, + } +} "#, + r#" +fn foo() { + if let VariantData::Struct(..) = a { + bar( + 123 + ) + } else { + false + } +} "#, + ) + } + + #[test] + fn replace_match_with_if_let_target() { + check_assist_target( + replace_match_with_if_let, + r#" +impl VariantData { + pub fn is_struct(&self) -> bool { + $0match *self { + VariantData::Struct(..) => true, + _ => false, + } + } +} "#, + r#"match *self { + VariantData::Struct(..) => true, + _ => false, + }"#, + ); + } + + #[test] + fn special_case_option_match_to_if_let() { + check_assist( + replace_match_with_if_let, + r#" +enum Option { Some(T), None } +use Option::*; + +fn foo(x: Option) { + $0match x { + Some(x) => println!("{}", x), + None => println!("none"), + } +} + "#, + r#" +enum Option { Some(T), None } +use Option::*; + +fn foo(x: Option) { + if let Some(x) = x { + println!("{}", x) + } else { + println!("none") + } +} + "#, + ); + } + + #[test] + fn special_case_result_match_to_if_let() { + check_assist( + replace_match_with_if_let, + r#" +enum Result { Ok(T), Err(E) } +use Result::*; + +fn foo(x: Result) { + $0match x { + Ok(x) => println!("{}", x), + Err(_) => println!("none"), + } +} + "#, + r#" +enum Result { Ok(T), Err(E) } +use Result::*; + +fn foo(x: Result) { + if let Ok(x) = x { + println!("{}", x) + } else { + println!("none") + } +} + "#, + ); + } + + #[test] + fn nested_indent_match_to_if_let() { + check_assist( + replace_match_with_if_let, + r#" +fn main() { + if true { + $0match path.strip_prefix(root_path) { + Ok(rel_path) => { + let rel_path = RelativePathBuf::from_path(rel_path).ok()?; + Some((*id, rel_path)) + } + _ => None, + } + } +} +"#, + r#" +fn main() { + if true { + if let Ok(rel_path) = path.strip_prefix(root_path) { + let rel_path = RelativePathBuf::from_path(rel_path).ok()?; + Some((*id, rel_path)) + } else { + None + } + } +} +"#, + ) + } + + #[test] + fn replace_match_with_if_let_empty_wildcard_expr() { + check_assist( + replace_match_with_if_let, + r#" +fn main() { + $0match path.strip_prefix(root_path) { + Ok(rel_path) => println!("{}", rel_path), + _ => (), + } +} +"#, + r#" +fn main() { + if let Ok(rel_path) = path.strip_prefix(root_path) { + println!("{}", rel_path) + } +} +"#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/replace_impl_trait_with_generic.rs b/crates/ide_assists/src/handlers/replace_impl_trait_with_generic.rs new file mode 100644 index 000000000..ff25b61ea --- /dev/null +++ b/crates/ide_assists/src/handlers/replace_impl_trait_with_generic.rs @@ -0,0 +1,168 @@ +use syntax::ast::{self, edit::AstNodeEdit, make, AstNode, GenericParamsOwner}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: replace_impl_trait_with_generic +// +// Replaces `impl Trait` function argument with the named generic. +// +// ``` +// fn foo(bar: $0impl Bar) {} +// ``` +// -> +// ``` +// fn foo(bar: B) {} +// ``` +pub(crate) fn replace_impl_trait_with_generic( + acc: &mut Assists, + ctx: &AssistContext, +) -> Option<()> { + let type_impl_trait = ctx.find_node_at_offset::()?; + let type_param = type_impl_trait.syntax().parent().and_then(ast::Param::cast)?; + let type_fn = type_param.syntax().ancestors().find_map(ast::Fn::cast)?; + + let impl_trait_ty = type_impl_trait.type_bound_list()?; + + let target = type_fn.syntax().text_range(); + acc.add( + AssistId("replace_impl_trait_with_generic", AssistKind::RefactorRewrite), + "Replace impl trait with generic", + target, + |edit| { + let generic_letter = impl_trait_ty.to_string().chars().next().unwrap().to_string(); + + let generic_param_list = type_fn + .generic_param_list() + .unwrap_or_else(|| make::generic_param_list(None)) + .append_param(make::generic_param(generic_letter.clone(), Some(impl_trait_ty))); + + let new_type_fn = type_fn + .replace_descendant::(type_impl_trait.into(), make::ty(&generic_letter)) + .with_generic_param_list(generic_param_list); + + edit.replace_ast(type_fn.clone(), new_type_fn); + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::tests::check_assist; + + #[test] + fn replace_impl_trait_with_generic_params() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo(bar: $0impl Bar) {} + "#, + r#" + fn foo(bar: B) {} + "#, + ); + } + + #[test] + fn replace_impl_trait_without_generic_params() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo(bar: $0impl Bar) {} + "#, + r#" + fn foo(bar: B) {} + "#, + ); + } + + #[test] + fn replace_two_impl_trait_with_generic_params() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo(foo: impl Foo, bar: $0impl Bar) {} + "#, + r#" + fn foo(foo: impl Foo, bar: B) {} + "#, + ); + } + + #[test] + fn replace_impl_trait_with_empty_generic_params() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo<>(bar: $0impl Bar) {} + "#, + r#" + fn foo(bar: B) {} + "#, + ); + } + + #[test] + fn replace_impl_trait_with_empty_multiline_generic_params() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo< + >(bar: $0impl Bar) {} + "#, + r#" + fn foo(bar: B) {} + "#, + ); + } + + #[test] + #[ignore = "This case is very rare but there is no simple solutions to fix it."] + fn replace_impl_trait_with_exist_generic_letter() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo(bar: $0impl Bar) {} + "#, + r#" + fn foo(bar: C) {} + "#, + ); + } + + #[test] + fn replace_impl_trait_with_multiline_generic_params() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo< + G: Foo, + F, + H, + >(bar: $0impl Bar) {} + "#, + r#" + fn foo< + G: Foo, + F, + H, B: Bar + >(bar: B) {} + "#, + ); + } + + #[test] + fn replace_impl_trait_multiple() { + check_assist( + replace_impl_trait_with_generic, + r#" + fn foo(bar: $0impl Foo + Bar) {} + "#, + r#" + fn foo(bar: F) {} + "#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/replace_let_with_if_let.rs b/crates/ide_assists/src/handlers/replace_let_with_if_let.rs new file mode 100644 index 000000000..5a27ada6b --- /dev/null +++ b/crates/ide_assists/src/handlers/replace_let_with_if_let.rs @@ -0,0 +1,101 @@ +use std::iter::once; + +use syntax::{ + ast::{ + self, + edit::{AstNodeEdit, IndentLevel}, + make, + }, + AstNode, T, +}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; +use ide_db::ty_filter::TryEnum; + +// Assist: replace_let_with_if_let +// +// Replaces `let` with an `if-let`. +// +// ``` +// # enum Option { Some(T), None } +// +// fn main(action: Action) { +// $0let x = compute(); +// } +// +// fn compute() -> Option { None } +// ``` +// -> +// ``` +// # enum Option { Some(T), None } +// +// fn main(action: Action) { +// if let Some(x) = compute() { +// } +// } +// +// fn compute() -> Option { None } +// ``` +pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let let_kw = ctx.find_token_syntax_at_offset(T![let])?; + let let_stmt = let_kw.ancestors().find_map(ast::LetStmt::cast)?; + let init = let_stmt.initializer()?; + let original_pat = let_stmt.pat()?; + let ty = ctx.sema.type_of_expr(&init)?; + let happy_variant = TryEnum::from_ty(&ctx.sema, &ty).map(|it| it.happy_case()); + + let target = let_kw.text_range(); + acc.add( + AssistId("replace_let_with_if_let", AssistKind::RefactorRewrite), + "Replace with if-let", + target, + |edit| { + let with_placeholder: ast::Pat = match happy_variant { + None => make::wildcard_pat().into(), + Some(var_name) => make::tuple_struct_pat( + make::path_unqualified(make::path_segment(make::name_ref(var_name))), + once(make::wildcard_pat().into()), + ) + .into(), + }; + let block = + make::block_expr(None, None).indent(IndentLevel::from_node(let_stmt.syntax())); + let if_ = make::expr_if(make::condition(init, Some(with_placeholder)), block, None); + let stmt = make::expr_stmt(if_); + + let placeholder = stmt.syntax().descendants().find_map(ast::WildcardPat::cast).unwrap(); + let stmt = stmt.replace_descendant(placeholder.into(), original_pat); + + edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt)); + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_assist; + + use super::*; + + #[test] + fn replace_let_unknown_enum() { + check_assist( + replace_let_with_if_let, + r" +enum E { X(T), Y(T) } + +fn main() { + $0let x = E::X(92); +} + ", + r" +enum E { X(T), Y(T) } + +fn main() { + if let x = E::X(92) { + } +} + ", + ) + } +} diff --git a/crates/ide_assists/src/handlers/replace_qualified_name_with_use.rs b/crates/ide_assists/src/handlers/replace_qualified_name_with_use.rs new file mode 100644 index 000000000..f3bc6cf39 --- /dev/null +++ b/crates/ide_assists/src/handlers/replace_qualified_name_with_use.rs @@ -0,0 +1,678 @@ +use ide_db::helpers::insert_use::{insert_use, ImportScope}; +use syntax::{algo::SyntaxRewriter, ast, match_ast, AstNode, SyntaxNode}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: replace_qualified_name_with_use +// +// Adds a use statement for a given fully-qualified name. +// +// ``` +// fn process(map: std::collections::$0HashMap) {} +// ``` +// -> +// ``` +// use std::collections::HashMap; +// +// fn process(map: HashMap) {} +// ``` +pub(crate) fn replace_qualified_name_with_use( + acc: &mut Assists, + ctx: &AssistContext, +) -> Option<()> { + 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::Use::cast).is_some() { + return None; + } + if path.qualifier().is_none() { + mark::hit!(dont_import_trivial_paths); + return None; + } + + let target = path.syntax().text_range(); + let scope = ImportScope::find_insert_use_container(path.syntax(), &ctx.sema)?; + let syntax = scope.as_syntax_node(); + acc.add( + AssistId("replace_qualified_name_with_use", AssistKind::RefactorRewrite), + "Replace qualified path with use", + target, + |builder| { + // Now that we've brought the name into scope, re-qualify all paths that could be + // affected (that is, all paths inside the node we added the `use` to). + let mut rewriter = SyntaxRewriter::default(); + shorten_paths(&mut rewriter, syntax.clone(), &path); + if let Some(ref import_scope) = ImportScope::from(syntax.clone()) { + rewriter += insert_use(import_scope, path, ctx.config.insert_use.merge); + builder.rewrite(rewriter); + } + }, + ) +} + +/// Adds replacements to `re` that shorten `path` in all descendants of `node`. +fn shorten_paths(rewriter: &mut SyntaxRewriter<'static>, node: SyntaxNode, path: &ast::Path) { + for child in node.children() { + match_ast! { + match child { + // Don't modify `use` items, as this can break the `use` item when injecting a new + // import into the use tree. + ast::Use(_it) => continue, + // Don't descend into submodules, they don't have the same `use` items in scope. + ast::Module(_it) => continue, + + ast::Path(p) => { + match maybe_replace_path(rewriter, p.clone(), path.clone()) { + Some(()) => {}, + None => shorten_paths(rewriter, p.syntax().clone(), path), + } + }, + _ => shorten_paths(rewriter, child, path), + } + } + } +} + +fn maybe_replace_path( + rewriter: &mut SyntaxRewriter<'static>, + path: ast::Path, + target: ast::Path, +) -> Option<()> { + if !path_eq(path.clone(), target) { + return None; + } + + // Shorten `path`, leaving only its last segment. + if let Some(parent) = path.qualifier() { + rewriter.delete(parent.syntax()); + } + if let Some(double_colon) = path.coloncolon_token() { + rewriter.delete(&double_colon); + } + + Some(()) +} + +fn path_eq(lhs: ast::Path, rhs: ast::Path) -> bool { + let mut lhs_curr = lhs; + let mut rhs_curr = rhs; + loop { + match (lhs_curr.segment(), rhs_curr.segment()) { + (Some(lhs), Some(rhs)) if lhs.syntax().text() == rhs.syntax().text() => (), + _ => return false, + } + + match (lhs_curr.qualifier(), rhs_curr.qualifier()) { + (Some(lhs), Some(rhs)) => { + lhs_curr = lhs; + rhs_curr = rhs; + } + (None, None) => return true, + _ => return false, + } + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn test_replace_already_imported() { + check_assist( + replace_qualified_name_with_use, + r"use std::fs; + +fn main() { + std::f$0s::Path +}", + r"use std::fs; + +fn main() { + fs::Path +}", + ) + } + + #[test] + fn test_replace_add_use_no_anchor() { + check_assist( + replace_qualified_name_with_use, + r" +std::fmt::Debug$0 + ", + r" +use std::fmt::Debug; + +Debug + ", + ); + } + #[test] + fn test_replace_add_use_no_anchor_with_item_below() { + check_assist( + replace_qualified_name_with_use, + r" +std::fmt::Debug$0 + +fn main() { +} + ", + r" +use std::fmt::Debug; + +Debug + +fn main() { +} + ", + ); + } + + #[test] + fn test_replace_add_use_no_anchor_with_item_above() { + check_assist( + replace_qualified_name_with_use, + r" +fn main() { +} + +std::fmt::Debug$0 + ", + r" +use std::fmt::Debug; + +fn main() { +} + +Debug + ", + ); + } + + #[test] + fn test_replace_add_use_no_anchor_2seg() { + check_assist( + replace_qualified_name_with_use, + r" +std::fmt$0::Debug + ", + r" +use std::fmt; + +fmt::Debug + ", + ); + } + + #[test] + fn test_replace_add_use() { + check_assist( + replace_qualified_name_with_use, + r" +use stdx; + +impl std::fmt::Debug$0 for Foo { +} + ", + r" +use std::fmt::Debug; + +use stdx; + +impl Debug for Foo { +} + ", + ); + } + + #[test] + fn test_replace_file_use_other_anchor() { + check_assist( + replace_qualified_name_with_use, + r" +impl std::fmt::Debug$0 for Foo { +} + ", + r" +use std::fmt::Debug; + +impl Debug for Foo { +} + ", + ); + } + + #[test] + fn test_replace_add_use_other_anchor_indent() { + check_assist( + replace_qualified_name_with_use, + r" + impl std::fmt::Debug$0 for Foo { + } + ", + r" + use std::fmt::Debug; + + impl Debug for Foo { + } + ", + ); + } + + #[test] + fn test_replace_split_different() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt; + +impl std::io$0 for Foo { +} + ", + r" +use std::{fmt, io}; + +impl io for Foo { +} + ", + ); + } + + #[test] + fn test_replace_split_self_for_use() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt; + +impl std::fmt::Debug$0 for Foo { +} + ", + r" +use std::fmt::{self, Debug}; + +impl Debug for Foo { +} + ", + ); + } + + #[test] + fn test_replace_split_self_for_target() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt::Debug; + +impl std::fmt$0 for Foo { +} + ", + r" +use std::fmt::{self, Debug}; + +impl fmt for Foo { +} + ", + ); + } + + #[test] + fn test_replace_add_to_nested_self_nested() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt::{Debug, nested::{Display}}; + +impl std::fmt::nested$0 for Foo { +} +", + r" +use std::fmt::{Debug, nested::{self, Display}}; + +impl nested for Foo { +} +", + ); + } + + #[test] + fn test_replace_add_to_nested_self_already_included() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt::{Debug, nested::{self, Display}}; + +impl std::fmt::nested$0 for Foo { +} +", + r" +use std::fmt::{Debug, nested::{self, Display}}; + +impl nested for Foo { +} +", + ); + } + + #[test] + fn test_replace_add_to_nested_nested() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt::{Debug, nested::{Display}}; + +impl std::fmt::nested::Debug$0 for Foo { +} +", + r" +use std::fmt::{Debug, nested::{Debug, Display}}; + +impl Debug for Foo { +} +", + ); + } + + #[test] + fn test_replace_split_common_target_longer() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt::Debug; + +impl std::fmt::nested::Display$0 for Foo { +} +", + r" +use std::fmt::{Debug, nested::Display}; + +impl Display for Foo { +} +", + ); + } + + #[test] + fn test_replace_split_common_use_longer() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt::nested::Debug; + +impl std::fmt::Display$0 for Foo { +} +", + r" +use std::fmt::{Display, nested::Debug}; + +impl Display for Foo { +} +", + ); + } + + #[test] + fn test_replace_use_nested_import() { + check_assist( + replace_qualified_name_with_use, + r" +use crate::{ + ty::{Substs, Ty}, + AssocItem, +}; + +fn foo() { crate::ty::lower$0::trait_env() } +", + r" +use crate::{AssocItem, ty::{Substs, Ty, lower}}; + +fn foo() { lower::trait_env() } +", + ); + } + + #[test] + fn test_replace_alias() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt as foo; + +impl foo::Debug$0 for Foo { +} +", + r" +use std::fmt as foo; + +use foo::Debug; + +impl Debug for Foo { +} +", + ); + } + + #[test] + fn dont_import_trivial_paths() { + mark::check!(dont_import_trivial_paths); + check_assist_not_applicable( + replace_qualified_name_with_use, + r" +impl foo$0 for Foo { +} +", + ); + } + + #[test] + fn test_replace_not_applicable_in_use() { + check_assist_not_applicable( + replace_qualified_name_with_use, + r" +use std::fmt$0; +", + ); + } + + #[test] + fn test_replace_add_use_no_anchor_in_mod_mod() { + check_assist( + replace_qualified_name_with_use, + r" +mod foo { + mod bar { + std::fmt::Debug$0 + } +} + ", + r" +mod foo { + mod bar { + use std::fmt::Debug; + + Debug + } +} + ", + ); + } + + #[test] + fn inserts_imports_after_inner_attributes() { + check_assist( + replace_qualified_name_with_use, + r" +#![allow(dead_code)] + +fn main() { + std::fmt::Debug$0 +} + ", + r" +#![allow(dead_code)] + +use std::fmt::Debug; + +fn main() { + Debug +} + ", + ); + } + + #[test] + fn replaces_all_affected_paths() { + check_assist( + replace_qualified_name_with_use, + r" +fn main() { + std::fmt::Debug$0; + let x: std::fmt::Debug = std::fmt::Debug; +} + ", + r" +use std::fmt::Debug; + +fn main() { + Debug; + let x: Debug = Debug; +} + ", + ); + } + + #[test] + fn replaces_all_affected_paths_mod() { + check_assist( + replace_qualified_name_with_use, + r" +mod m { + fn f() { + std::fmt::Debug$0; + let x: std::fmt::Debug = std::fmt::Debug; + } + fn g() { + std::fmt::Debug; + } +} + +fn f() { + std::fmt::Debug; +} + ", + r" +mod m { + use std::fmt::Debug; + + fn f() { + Debug; + let x: Debug = Debug; + } + fn g() { + Debug; + } +} + +fn f() { + std::fmt::Debug; +} + ", + ); + } + + #[test] + fn does_not_replace_in_submodules() { + check_assist( + replace_qualified_name_with_use, + r" +fn main() { + std::fmt::Debug$0; +} + +mod sub { + fn f() { + std::fmt::Debug; + } +} + ", + r" +use std::fmt::Debug; + +fn main() { + Debug; +} + +mod sub { + fn f() { + std::fmt::Debug; + } +} + ", + ); + } + + #[test] + fn does_not_replace_in_use() { + check_assist( + replace_qualified_name_with_use, + r" +use std::fmt::Display; + +fn main() { + std::fmt$0; +} + ", + r" +use std::fmt::{self, Display}; + +fn main() { + fmt; +} + ", + ); + } + + #[test] + fn does_not_replace_pub_use() { + check_assist( + replace_qualified_name_with_use, + r" +pub use std::fmt; + +impl std::io$0 for Foo { +} + ", + r" +pub use std::fmt; +use std::io; + +impl io for Foo { +} + ", + ); + } + + #[test] + fn does_not_replace_pub_crate_use() { + check_assist( + replace_qualified_name_with_use, + r" +pub(crate) use std::fmt; + +impl std::io$0 for Foo { +} + ", + r" +pub(crate) use std::fmt; +use std::io; + +impl io for Foo { +} + ", + ); + } +} diff --git a/crates/ide_assists/src/handlers/replace_string_with_char.rs b/crates/ide_assists/src/handlers/replace_string_with_char.rs new file mode 100644 index 000000000..317318c24 --- /dev/null +++ b/crates/ide_assists/src/handlers/replace_string_with_char.rs @@ -0,0 +1,137 @@ +use syntax::{ast, AstToken, SyntaxKind::STRING}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: replace_string_with_char +// +// Replace string with char. +// +// ``` +// fn main() { +// find("{$0"); +// } +// ``` +// -> +// ``` +// fn main() { +// find('{'); +// } +// ``` +pub(crate) fn replace_string_with_char(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let token = ctx.find_token_syntax_at_offset(STRING).and_then(ast::String::cast)?; + let value = token.value()?; + let target = token.syntax().text_range(); + + if value.chars().take(2).count() != 1 { + return None; + } + + acc.add( + AssistId("replace_string_with_char", AssistKind::RefactorRewrite), + "Replace string with char", + target, + |edit| { + edit.replace(token.syntax().text_range(), format!("'{}'", value)); + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn replace_string_with_char_target() { + check_assist_target( + replace_string_with_char, + r#" + fn f() { + let s = "$0c"; + } + "#, + r#""c""#, + ); + } + + #[test] + fn replace_string_with_char_assist() { + check_assist( + replace_string_with_char, + r#" + fn f() { + let s = "$0c"; + } + "#, + r##" + fn f() { + let s = 'c'; + } + "##, + ) + } + + #[test] + fn replace_string_with_char_assist_with_emoji() { + check_assist( + replace_string_with_char, + r#" + fn f() { + let s = "$0😀"; + } + "#, + r##" + fn f() { + let s = '😀'; + } + "##, + ) + } + + #[test] + fn replace_string_with_char_assist_not_applicable() { + check_assist_not_applicable( + replace_string_with_char, + r#" + fn f() { + let s = "$0test"; + } + "#, + ) + } + + #[test] + fn replace_string_with_char_works_inside_macros() { + check_assist( + replace_string_with_char, + r#" + fn f() { + format!($0"x", 92) + } + "#, + r##" + fn f() { + format!('x', 92) + } + "##, + ) + } + + #[test] + fn replace_string_with_char_works_func_args() { + check_assist( + replace_string_with_char, + r#" + fn f() { + find($0"x"); + } + "#, + r##" + fn f() { + find('x'); + } + "##, + ) + } +} diff --git a/crates/ide_assists/src/handlers/replace_unwrap_with_match.rs b/crates/ide_assists/src/handlers/replace_unwrap_with_match.rs new file mode 100644 index 000000000..a986a6ae8 --- /dev/null +++ b/crates/ide_assists/src/handlers/replace_unwrap_with_match.rs @@ -0,0 +1,188 @@ +use std::iter; + +use syntax::{ + ast::{ + self, + edit::{AstNodeEdit, IndentLevel}, + make, + }, + AstNode, +}; + +use crate::{ + utils::{render_snippet, Cursor}, + AssistContext, AssistId, AssistKind, Assists, +}; +use ide_db::ty_filter::TryEnum; + +// Assist: replace_unwrap_with_match +// +// Replaces `unwrap` a `match` expression. Works for Result and Option. +// +// ``` +// enum Result { Ok(T), Err(E) } +// fn main() { +// let x: Result = Result::Ok(92); +// let y = x.$0unwrap(); +// } +// ``` +// -> +// ``` +// enum Result { Ok(T), Err(E) } +// fn main() { +// let x: Result = Result::Ok(92); +// let y = match x { +// Ok(a) => a, +// $0_ => unreachable!(), +// }; +// } +// ``` +pub(crate) fn replace_unwrap_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let method_call: ast::MethodCallExpr = ctx.find_node_at_offset()?; + let name = method_call.name_ref()?; + if name.text() != "unwrap" { + return None; + } + let caller = method_call.receiver()?; + let ty = ctx.sema.type_of_expr(&caller)?; + let happy_variant = TryEnum::from_ty(&ctx.sema, &ty)?.happy_case(); + let target = method_call.syntax().text_range(); + acc.add( + AssistId("replace_unwrap_with_match", AssistKind::RefactorRewrite), + "Replace unwrap with match", + target, + |builder| { + let ok_path = make::path_unqualified(make::path_segment(make::name_ref(happy_variant))); + let it = make::ident_pat(make::name("a")).into(); + let ok_tuple = make::tuple_struct_pat(ok_path, iter::once(it)).into(); + + let bind_path = make::path_unqualified(make::path_segment(make::name_ref("a"))); + let ok_arm = make::match_arm(iter::once(ok_tuple), make::expr_path(bind_path)); + + let unreachable_call = make::expr_unreachable(); + let err_arm = + make::match_arm(iter::once(make::wildcard_pat().into()), unreachable_call); + + let match_arm_list = make::match_arm_list(vec![ok_arm, err_arm]); + let match_expr = make::expr_match(caller.clone(), match_arm_list) + .indent(IndentLevel::from_node(method_call.syntax())); + + let range = method_call.syntax().text_range(); + match ctx.config.snippet_cap { + Some(cap) => { + let err_arm = match_expr + .syntax() + .descendants() + .filter_map(ast::MatchArm::cast) + .last() + .unwrap(); + let snippet = + render_snippet(cap, match_expr.syntax(), Cursor::Before(err_arm.syntax())); + builder.replace_snippet(cap, range, snippet) + } + None => builder.replace(range, match_expr.to_string()), + } + }, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_target}; + + use super::*; + + #[test] + fn test_replace_result_unwrap_with_match() { + check_assist( + replace_unwrap_with_match, + r" +enum Result { Ok(T), Err(E) } +fn i(a: T) -> T { a } +fn main() { + let x: Result = Result::Ok(92); + let y = i(x).$0unwrap(); +} + ", + r" +enum Result { Ok(T), Err(E) } +fn i(a: T) -> T { a } +fn main() { + let x: Result = Result::Ok(92); + let y = match i(x) { + Ok(a) => a, + $0_ => unreachable!(), + }; +} + ", + ) + } + + #[test] + fn test_replace_option_unwrap_with_match() { + check_assist( + replace_unwrap_with_match, + r" +enum Option { Some(T), None } +fn i(a: T) -> T { a } +fn main() { + let x = Option::Some(92); + let y = i(x).$0unwrap(); +} + ", + r" +enum Option { Some(T), None } +fn i(a: T) -> T { a } +fn main() { + let x = Option::Some(92); + let y = match i(x) { + Some(a) => a, + $0_ => unreachable!(), + }; +} + ", + ); + } + + #[test] + fn test_replace_result_unwrap_with_match_chaining() { + check_assist( + replace_unwrap_with_match, + r" +enum Result { Ok(T), Err(E) } +fn i(a: T) -> T { a } +fn main() { + let x: Result = Result::Ok(92); + let y = i(x).$0unwrap().count_zeroes(); +} + ", + r" +enum Result { Ok(T), Err(E) } +fn i(a: T) -> T { a } +fn main() { + let x: Result = Result::Ok(92); + let y = match i(x) { + Ok(a) => a, + $0_ => unreachable!(), + }.count_zeroes(); +} + ", + ) + } + + #[test] + fn replace_unwrap_with_match_target() { + check_assist_target( + replace_unwrap_with_match, + r" +enum Option { Some(T), None } +fn i(a: T) -> T { a } +fn main() { + let x = Option::Some(92); + let y = i(x).$0unwrap(); +} + ", + r"i(x).unwrap()", + ); + } +} diff --git a/crates/ide_assists/src/handlers/split_import.rs b/crates/ide_assists/src/handlers/split_import.rs new file mode 100644 index 000000000..9319a4267 --- /dev/null +++ b/crates/ide_assists/src/handlers/split_import.rs @@ -0,0 +1,79 @@ +use std::iter::successors; + +use syntax::{ast, AstNode, T}; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: split_import +// +// Wraps the tail of import into braces. +// +// ``` +// use std::$0collections::HashMap; +// ``` +// -> +// ``` +// use std::{collections::HashMap}; +// ``` +pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let colon_colon = ctx.find_token_syntax_at_offset(T![::])?; + let path = ast::Path::cast(colon_colon.parent())?.qualifier()?; + let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?; + + let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?; + + let new_tree = use_tree.split_prefix(&path); + if new_tree == use_tree { + return None; + } + + let target = colon_colon.text_range(); + acc.add(AssistId("split_import", AssistKind::RefactorRewrite), "Split import", target, |edit| { + edit.replace_ast(use_tree, new_tree); + }) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; + + use super::*; + + #[test] + fn test_split_import() { + check_assist( + split_import, + "use crate::$0db::RootDatabase;", + "use crate::{db::RootDatabase};", + ) + } + + #[test] + fn split_import_works_with_trees() { + check_assist( + split_import, + "use crate:$0:db::{RootDatabase, FileSymbol}", + "use crate::{db::{RootDatabase, FileSymbol}}", + ) + } + + #[test] + fn split_import_target() { + check_assist_target(split_import, "use crate::$0db::{RootDatabase, FileSymbol}", "::"); + } + + #[test] + fn issue4044() { + check_assist_not_applicable(split_import, "use crate::$0:::self;") + } + + #[test] + fn test_empty_use() { + check_assist_not_applicable( + split_import, + r" +use std::$0 +fn main() {}", + ); + } +} diff --git a/crates/ide_assists/src/handlers/toggle_ignore.rs b/crates/ide_assists/src/handlers/toggle_ignore.rs new file mode 100644 index 000000000..33e12a7d0 --- /dev/null +++ b/crates/ide_assists/src/handlers/toggle_ignore.rs @@ -0,0 +1,98 @@ +use syntax::{ + ast::{self, AttrsOwner}, + AstNode, AstToken, +}; + +use crate::{utils::test_related_attribute, AssistContext, AssistId, AssistKind, Assists}; + +// Assist: toggle_ignore +// +// Adds `#[ignore]` attribute to the test. +// +// ``` +// $0#[test] +// fn arithmetics { +// assert_eq!(2 + 2, 5); +// } +// ``` +// -> +// ``` +// #[test] +// #[ignore] +// fn arithmetics { +// assert_eq!(2 + 2, 5); +// } +// ``` +pub(crate) fn toggle_ignore(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let attr: ast::Attr = ctx.find_node_at_offset()?; + let func = attr.syntax().parent().and_then(ast::Fn::cast)?; + let attr = test_related_attribute(&func)?; + + match has_ignore_attribute(&func) { + None => acc.add( + AssistId("toggle_ignore", AssistKind::None), + "Ignore this test", + attr.syntax().text_range(), + |builder| builder.insert(attr.syntax().text_range().end(), &format!("\n#[ignore]")), + ), + Some(ignore_attr) => acc.add( + AssistId("toggle_ignore", AssistKind::None), + "Re-enable this test", + ignore_attr.syntax().text_range(), + |builder| { + builder.delete(ignore_attr.syntax().text_range()); + let whitespace = ignore_attr + .syntax() + .next_sibling_or_token() + .and_then(|x| x.into_token()) + .and_then(ast::Whitespace::cast); + if let Some(whitespace) = whitespace { + builder.delete(whitespace.syntax().text_range()); + } + }, + ), + } +} + +fn has_ignore_attribute(fn_def: &ast::Fn) -> Option { + fn_def.attrs().find(|attr| attr.path().map(|it| it.syntax().text() == "ignore") == Some(true)) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_assist; + + use super::*; + + #[test] + fn test_base_case() { + check_assist( + toggle_ignore, + r#" + #[test$0] + fn test() {} + "#, + r#" + #[test] + #[ignore] + fn test() {} + "#, + ) + } + + #[test] + fn test_unignore() { + check_assist( + toggle_ignore, + r#" + #[test$0] + #[ignore] + fn test() {} + "#, + r#" + #[test] + fn test() {} + "#, + ) + } +} diff --git a/crates/ide_assists/src/handlers/unmerge_use.rs b/crates/ide_assists/src/handlers/unmerge_use.rs new file mode 100644 index 000000000..3dbef8e51 --- /dev/null +++ b/crates/ide_assists/src/handlers/unmerge_use.rs @@ -0,0 +1,231 @@ +use syntax::{ + algo::SyntaxRewriter, + ast::{self, edit::AstNodeEdit, VisibilityOwner}, + AstNode, SyntaxKind, +}; +use test_utils::mark; + +use crate::{ + assist_context::{AssistContext, Assists}, + AssistId, AssistKind, +}; + +// Assist: unmerge_use +// +// Extracts single use item from use list. +// +// ``` +// use std::fmt::{Debug, Display$0}; +// ``` +// -> +// ``` +// use std::fmt::{Debug}; +// use std::fmt::Display; +// ``` +pub(crate) fn unmerge_use(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let tree: ast::UseTree = ctx.find_node_at_offset()?; + + let tree_list = tree.syntax().parent().and_then(ast::UseTreeList::cast)?; + if tree_list.use_trees().count() < 2 { + mark::hit!(skip_single_use_item); + return None; + } + + let use_: ast::Use = tree_list.syntax().ancestors().find_map(ast::Use::cast)?; + let path = resolve_full_path(&tree)?; + + let target = tree.syntax().text_range(); + acc.add( + AssistId("unmerge_use", AssistKind::RefactorRewrite), + "Unmerge use", + target, + |builder| { + let new_use = ast::make::use_( + use_.visibility(), + ast::make::use_tree( + path, + tree.use_tree_list(), + tree.rename(), + tree.star_token().is_some(), + ), + ); + + let mut rewriter = SyntaxRewriter::default(); + rewriter += tree.remove(); + rewriter.insert_after(use_.syntax(), &ast::make::tokens::single_newline()); + if let ident_level @ 1..=usize::MAX = use_.indent_level().0 as usize { + rewriter.insert_after( + use_.syntax(), + &ast::make::tokens::whitespace(&" ".repeat(4 * ident_level)), + ); + } + rewriter.insert_after(use_.syntax(), new_use.syntax()); + + builder.rewrite(rewriter); + }, + ) +} + +fn resolve_full_path(tree: &ast::UseTree) -> Option { + let mut paths = tree + .syntax() + .ancestors() + .take_while(|n| n.kind() != SyntaxKind::USE_KW) + .filter_map(ast::UseTree::cast) + .filter_map(|t| t.path()); + + let mut final_path = paths.next()?; + for path in paths { + final_path = ast::make::path_concat(path, final_path) + } + Some(final_path) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn skip_single_use_item() { + mark::check!(skip_single_use_item); + check_assist_not_applicable( + unmerge_use, + r" +use std::fmt::Debug$0; +", + ); + check_assist_not_applicable( + unmerge_use, + r" +use std::fmt::{Debug$0}; +", + ); + check_assist_not_applicable( + unmerge_use, + r" +use std::fmt::Debug as Dbg$0; +", + ); + } + + #[test] + fn skip_single_glob_import() { + check_assist_not_applicable( + unmerge_use, + r" +use std::fmt::*$0; +", + ); + } + + #[test] + fn unmerge_use_item() { + check_assist( + unmerge_use, + r" +use std::fmt::{Debug, Display$0}; +", + r" +use std::fmt::{Debug}; +use std::fmt::Display; +", + ); + + check_assist( + unmerge_use, + r" +use std::fmt::{Debug, format$0, Display}; +", + r" +use std::fmt::{Debug, Display}; +use std::fmt::format; +", + ); + } + + #[test] + fn unmerge_glob_import() { + check_assist( + unmerge_use, + r" +use std::fmt::{*$0, Display}; +", + r" +use std::fmt::{Display}; +use std::fmt::*; +", + ); + } + + #[test] + fn unmerge_renamed_use_item() { + check_assist( + unmerge_use, + r" +use std::fmt::{Debug, Display as Disp$0}; +", + r" +use std::fmt::{Debug}; +use std::fmt::Display as Disp; +", + ); + } + + #[test] + fn unmerge_indented_use_item() { + check_assist( + unmerge_use, + r" +mod format { + use std::fmt::{Debug, Display$0 as Disp, format}; +} +", + r" +mod format { + use std::fmt::{Debug, format}; + use std::fmt::Display as Disp; +} +", + ); + } + + #[test] + fn unmerge_nested_use_item() { + check_assist( + unmerge_use, + r" +use foo::bar::{baz::{qux$0, foobar}, barbaz}; +", + r" +use foo::bar::{baz::{foobar}, barbaz}; +use foo::bar::baz::qux; +", + ); + check_assist( + unmerge_use, + r" +use foo::bar::{baz$0::{qux, foobar}, barbaz}; +", + r" +use foo::bar::{barbaz}; +use foo::bar::baz::{qux, foobar}; +", + ); + } + + #[test] + fn unmerge_use_item_with_visibility() { + check_assist( + unmerge_use, + r" +pub use std::fmt::{Debug, Display$0}; +", + r" +pub use std::fmt::{Debug}; +pub use std::fmt::Display; +", + ); + } +} diff --git a/crates/ide_assists/src/handlers/unwrap_block.rs b/crates/ide_assists/src/handlers/unwrap_block.rs new file mode 100644 index 000000000..ed6f6177d --- /dev/null +++ b/crates/ide_assists/src/handlers/unwrap_block.rs @@ -0,0 +1,582 @@ +use syntax::{ + ast::{ + self, + edit::{AstNodeEdit, IndentLevel}, + }, + AstNode, SyntaxKind, TextRange, T, +}; + +use crate::{utils::unwrap_trivial_block, AssistContext, AssistId, AssistKind, Assists}; + +// Assist: unwrap_block +// +// This assist removes if...else, for, while and loop control statements to just keep the body. +// +// ``` +// fn foo() { +// if true {$0 +// println!("foo"); +// } +// } +// ``` +// -> +// ``` +// fn foo() { +// println!("foo"); +// } +// ``` +pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let assist_id = AssistId("unwrap_block", AssistKind::RefactorRewrite); + let assist_label = "Unwrap block"; + + let l_curly_token = ctx.find_token_syntax_at_offset(T!['{'])?; + let mut block = ast::BlockExpr::cast(l_curly_token.parent())?; + let target = block.syntax().text_range(); + let mut parent = block.syntax().parent()?; + if ast::MatchArm::can_cast(parent.kind()) { + parent = parent.ancestors().find(|it| ast::MatchExpr::can_cast(it.kind()))? + } + + if matches!(parent.kind(), SyntaxKind::BLOCK_EXPR | SyntaxKind::EXPR_STMT) { + return acc.add(assist_id, assist_label, target, |builder| { + builder.replace( + block.syntax().text_range(), + update_expr_string(block.to_string(), &[' ', '{', '\n']), + ); + }); + } + + let parent = ast::Expr::cast(parent)?; + + match parent.clone() { + ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::LoopExpr(_) => (), + ast::Expr::MatchExpr(_) => block = block.dedent(IndentLevel(1)), + ast::Expr::IfExpr(if_expr) => { + let then_branch = if_expr.then_branch()?; + if then_branch == block { + if let Some(ancestor) = if_expr.syntax().parent().and_then(ast::IfExpr::cast) { + // For `else if` blocks + let ancestor_then_branch = ancestor.then_branch()?; + + return acc.add(assist_id, assist_label, target, |edit| { + let range_to_del_else_if = TextRange::new( + ancestor_then_branch.syntax().text_range().end(), + l_curly_token.text_range().start(), + ); + let range_to_del_rest = TextRange::new( + then_branch.syntax().text_range().end(), + if_expr.syntax().text_range().end(), + ); + + edit.delete(range_to_del_rest); + edit.delete(range_to_del_else_if); + edit.replace( + target, + update_expr_string(then_branch.to_string(), &[' ', '{']), + ); + }); + } + } else { + return acc.add(assist_id, assist_label, target, |edit| { + let range_to_del = TextRange::new( + then_branch.syntax().text_range().end(), + l_curly_token.text_range().start(), + ); + + edit.delete(range_to_del); + edit.replace(target, update_expr_string(block.to_string(), &[' ', '{'])); + }); + } + } + _ => return None, + }; + + let unwrapped = unwrap_trivial_block(block); + acc.add(assist_id, assist_label, target, |builder| { + builder.replace( + parent.syntax().text_range(), + update_expr_string(unwrapped.to_string(), &[' ', '{', '\n']), + ); + }) +} + +fn update_expr_string(expr_str: String, trim_start_pat: &[char]) -> String { + let expr_string = expr_str.trim_start_matches(trim_start_pat); + let mut expr_string_lines: Vec<&str> = expr_string.lines().collect(); + expr_string_lines.pop(); // Delete last line + + expr_string_lines + .into_iter() + .map(|line| line.replacen(" ", "", 1)) // Delete indentation + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn unwrap_tail_expr_block() { + check_assist( + unwrap_block, + r#" +fn main() { + $0{ + 92 + } +} +"#, + r#" +fn main() { + 92 +} +"#, + ) + } + + #[test] + fn unwrap_stmt_expr_block() { + check_assist( + unwrap_block, + r#" +fn main() { + $0{ + 92; + } + () +} +"#, + r#" +fn main() { + 92; + () +} +"#, + ); + // Pedantically, we should add an `;` here... + check_assist( + unwrap_block, + r#" +fn main() { + $0{ + 92 + } + () +} +"#, + r#" +fn main() { + 92 + () +} +"#, + ); + } + + #[test] + fn simple_if() { + check_assist( + unwrap_block, + r#" +fn main() { + bar(); + if true {$0 + foo(); + + //comment + bar(); + } else { + println!("bar"); + } +} +"#, + r#" +fn main() { + bar(); + foo(); + + //comment + bar(); +} +"#, + ); + } + + #[test] + fn simple_if_else() { + check_assist( + unwrap_block, + r#" +fn main() { + bar(); + if true { + foo(); + + //comment + bar(); + } else {$0 + println!("bar"); + } +} +"#, + r#" +fn main() { + bar(); + if true { + foo(); + + //comment + bar(); + } + println!("bar"); +} +"#, + ); + } + + #[test] + fn simple_if_else_if() { + check_assist( + unwrap_block, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } else if false {$0 + println!("bar"); + } else { + println!("foo"); + } +} +"#, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } + println!("bar"); +} +"#, + ); + } + + #[test] + fn simple_if_else_if_nested() { + check_assist( + unwrap_block, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } else if false { + println!("bar"); + } else if true {$0 + println!("foo"); + } +} +"#, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } else if false { + println!("bar"); + } + println!("foo"); +} +"#, + ); + } + + #[test] + fn simple_if_else_if_nested_else() { + check_assist( + unwrap_block, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } else if false { + println!("bar"); + } else if true { + println!("foo"); + } else {$0 + println!("else"); + } +} +"#, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } else if false { + println!("bar"); + } else if true { + println!("foo"); + } + println!("else"); +} +"#, + ); + } + + #[test] + fn simple_if_else_if_nested_middle() { + check_assist( + unwrap_block, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } else if false { + println!("bar"); + } else if true {$0 + println!("foo"); + } else { + println!("else"); + } +} +"#, + r#" +fn main() { + //bar(); + if true { + println!("true"); + + //comment + //bar(); + } else if false { + println!("bar"); + } + println!("foo"); +} +"#, + ); + } + + #[test] + fn simple_if_bad_cursor_position() { + check_assist_not_applicable( + unwrap_block, + r#" +fn main() { + bar();$0 + if true { + foo(); + + //comment + bar(); + } else { + println!("bar"); + } +} +"#, + ); + } + + #[test] + fn simple_for() { + check_assist( + unwrap_block, + r#" +fn main() { + for i in 0..5 {$0 + if true { + foo(); + + //comment + bar(); + } else { + println!("bar"); + } + } +} +"#, + r#" +fn main() { + if true { + foo(); + + //comment + bar(); + } else { + println!("bar"); + } +} +"#, + ); + } + + #[test] + fn simple_if_in_for() { + check_assist( + unwrap_block, + r#" +fn main() { + for i in 0..5 { + if true {$0 + foo(); + + //comment + bar(); + } else { + println!("bar"); + } + } +} +"#, + r#" +fn main() { + for i in 0..5 { + foo(); + + //comment + bar(); + } +} +"#, + ); + } + + #[test] + fn simple_loop() { + check_assist( + unwrap_block, + r#" +fn main() { + loop {$0 + if true { + foo(); + + //comment + bar(); + } else { + println!("bar"); + } + } +} +"#, + r#" +fn main() { + if true { + foo(); + + //comment + bar(); + } else { + println!("bar"); + } +} +"#, + ); + } + + #[test] + fn simple_while() { + check_assist( + unwrap_block, + r#" +fn main() { + while true {$0 + if true { + foo(); + + //comment + bar(); + } else { + println!("bar"); + } + } +} +"#, + r#" +fn main() { + if true { + foo(); + + //comment + bar(); + } else { + println!("bar"); + } +} +"#, + ); + } + + #[test] + fn unwrap_match_arm() { + check_assist( + unwrap_block, + r#" +fn main() { + match rel_path { + Ok(rel_path) => {$0 + let rel_path = RelativePathBuf::from_path(rel_path).ok()?; + Some((*id, rel_path)) + } + Err(_) => None, + } +} +"#, + r#" +fn main() { + let rel_path = RelativePathBuf::from_path(rel_path).ok()?; + Some((*id, rel_path)) +} +"#, + ); + } + + #[test] + fn simple_if_in_while_bad_cursor_position() { + check_assist_not_applicable( + unwrap_block, + r#" +fn main() { + while true { + if true { + foo();$0 + + //comment + bar(); + } else { + println!("bar"); + } + } +} +"#, + ); + } +} diff --git a/crates/ide_assists/src/handlers/wrap_return_type_in_result.rs b/crates/ide_assists/src/handlers/wrap_return_type_in_result.rs new file mode 100644 index 000000000..fec16fc49 --- /dev/null +++ b/crates/ide_assists/src/handlers/wrap_return_type_in_result.rs @@ -0,0 +1,1158 @@ +use std::iter; + +use syntax::{ + ast::{self, make, BlockExpr, Expr, LoopBodyOwner}, + match_ast, AstNode, SyntaxNode, +}; +use test_utils::mark; + +use crate::{AssistContext, AssistId, AssistKind, Assists}; + +// Assist: wrap_return_type_in_result +// +// Wrap the function's return type into Result. +// +// ``` +// fn foo() -> i32$0 { 42i32 } +// ``` +// -> +// ``` +// fn foo() -> Result { Ok(42i32) } +// ``` +pub(crate) fn wrap_return_type_in_result(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { + let ret_type = ctx.find_node_at_offset::()?; + let parent = ret_type.syntax().parent()?; + let block_expr = match_ast! { + match parent { + ast::Fn(func) => func.body()?, + ast::ClosureExpr(closure) => match closure.body()? { + Expr::BlockExpr(block) => block, + // closures require a block when a return type is specified + _ => return None, + }, + _ => return None, + } + }; + + let type_ref = &ret_type.ty()?; + let ret_type_str = type_ref.syntax().text().to_string(); + let first_part_ret_type = ret_type_str.splitn(2, '<').next(); + if let Some(ret_type_first_part) = first_part_ret_type { + if ret_type_first_part.ends_with("Result") { + mark::hit!(wrap_return_type_in_result_simple_return_type_already_result); + return None; + } + } + + acc.add( + AssistId("wrap_return_type_in_result", AssistKind::RefactorRewrite), + "Wrap return type in Result", + type_ref.syntax().text_range(), + |builder| { + let mut tail_return_expr_collector = TailReturnCollector::new(); + tail_return_expr_collector.collect_jump_exprs(&block_expr, false); + tail_return_expr_collector.collect_tail_exprs(&block_expr); + + for ret_expr_arg in tail_return_expr_collector.exprs_to_wrap { + let ok_wrapped = make::expr_call( + make::expr_path(make::path_unqualified(make::path_segment(make::name_ref( + "Ok", + )))), + make::arg_list(iter::once(ret_expr_arg.clone())), + ); + builder.replace_ast(ret_expr_arg, ok_wrapped); + } + + match ctx.config.snippet_cap { + Some(cap) => { + let snippet = format!("Result<{}, ${{0:_}}>", type_ref); + builder.replace_snippet(cap, type_ref.syntax().text_range(), snippet) + } + None => builder + .replace(type_ref.syntax().text_range(), format!("Result<{}, _>", type_ref)), + } + }, + ) +} + +struct TailReturnCollector { + exprs_to_wrap: Vec, +} + +impl TailReturnCollector { + fn new() -> Self { + Self { exprs_to_wrap: vec![] } + } + /// Collect all`return` expression + fn collect_jump_exprs(&mut self, block_expr: &BlockExpr, collect_break: bool) { + let statements = block_expr.statements(); + for stmt in statements { + let expr = match &stmt { + ast::Stmt::ExprStmt(stmt) => stmt.expr(), + ast::Stmt::LetStmt(stmt) => stmt.initializer(), + ast::Stmt::Item(_) => continue, + }; + if let Some(expr) = &expr { + self.handle_exprs(expr, collect_break); + } + } + + // Browse tail expressions for each block + if let Some(expr) = block_expr.tail_expr() { + if let Some(last_exprs) = get_tail_expr_from_block(&expr) { + for last_expr in last_exprs { + let last_expr = match last_expr { + NodeType::Node(expr) => expr, + NodeType::Leaf(expr) => expr.syntax().clone(), + }; + + if let Some(last_expr) = Expr::cast(last_expr.clone()) { + self.handle_exprs(&last_expr, collect_break); + } else if let Some(expr_stmt) = ast::Stmt::cast(last_expr) { + let expr_stmt = match &expr_stmt { + ast::Stmt::ExprStmt(stmt) => stmt.expr(), + ast::Stmt::LetStmt(stmt) => stmt.initializer(), + ast::Stmt::Item(_) => None, + }; + if let Some(expr) = &expr_stmt { + self.handle_exprs(expr, collect_break); + } + } + } + } + } + } + + fn handle_exprs(&mut self, expr: &Expr, collect_break: bool) { + match expr { + Expr::BlockExpr(block_expr) => { + self.collect_jump_exprs(&block_expr, collect_break); + } + Expr::ReturnExpr(ret_expr) => { + if let Some(ret_expr_arg) = &ret_expr.expr() { + self.exprs_to_wrap.push(ret_expr_arg.clone()); + } + } + Expr::BreakExpr(break_expr) if collect_break => { + if let Some(break_expr_arg) = &break_expr.expr() { + self.exprs_to_wrap.push(break_expr_arg.clone()); + } + } + Expr::IfExpr(if_expr) => { + for block in if_expr.blocks() { + self.collect_jump_exprs(&block, collect_break); + } + } + Expr::LoopExpr(loop_expr) => { + if let Some(block_expr) = loop_expr.loop_body() { + self.collect_jump_exprs(&block_expr, collect_break); + } + } + Expr::ForExpr(for_expr) => { + if let Some(block_expr) = for_expr.loop_body() { + self.collect_jump_exprs(&block_expr, collect_break); + } + } + Expr::WhileExpr(while_expr) => { + if let Some(block_expr) = while_expr.loop_body() { + self.collect_jump_exprs(&block_expr, collect_break); + } + } + Expr::MatchExpr(match_expr) => { + if let Some(arm_list) = match_expr.match_arm_list() { + arm_list.arms().filter_map(|match_arm| match_arm.expr()).for_each(|expr| { + self.handle_exprs(&expr, collect_break); + }); + } + } + _ => {} + } + } + + fn collect_tail_exprs(&mut self, block: &BlockExpr) { + if let Some(expr) = block.tail_expr() { + self.handle_exprs(&expr, true); + self.fetch_tail_exprs(&expr); + } + } + + fn fetch_tail_exprs(&mut self, expr: &Expr) { + if let Some(exprs) = get_tail_expr_from_block(expr) { + for node_type in &exprs { + match node_type { + NodeType::Leaf(expr) => { + self.exprs_to_wrap.push(expr.clone()); + } + NodeType::Node(expr) => { + if let Some(last_expr) = Expr::cast(expr.clone()) { + self.fetch_tail_exprs(&last_expr); + } + } + } + } + } + } +} + +#[derive(Debug)] +enum NodeType { + Leaf(ast::Expr), + Node(SyntaxNode), +} + +/// Get a tail expression inside a block +fn get_tail_expr_from_block(expr: &Expr) -> Option> { + match expr { + Expr::IfExpr(if_expr) => { + let mut nodes = vec![]; + for block in if_expr.blocks() { + if let Some(block_expr) = block.tail_expr() { + if let Some(tail_exprs) = get_tail_expr_from_block(&block_expr) { + nodes.extend(tail_exprs); + } + } else if let Some(last_expr) = block.syntax().last_child() { + nodes.push(NodeType::Node(last_expr)); + } else { + nodes.push(NodeType::Node(block.syntax().clone())); + } + } + Some(nodes) + } + Expr::LoopExpr(loop_expr) => { + loop_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) + } + Expr::ForExpr(for_expr) => { + for_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) + } + Expr::WhileExpr(while_expr) => { + while_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) + } + Expr::BlockExpr(block_expr) => { + block_expr.tail_expr().map(|lc| vec![NodeType::Node(lc.syntax().clone())]) + } + Expr::MatchExpr(match_expr) => { + let arm_list = match_expr.match_arm_list()?; + let arms: Vec = arm_list + .arms() + .filter_map(|match_arm| match_arm.expr()) + .map(|expr| match expr { + Expr::ReturnExpr(ret_expr) => NodeType::Node(ret_expr.syntax().clone()), + Expr::BreakExpr(break_expr) => NodeType::Node(break_expr.syntax().clone()), + _ => match expr.syntax().last_child() { + Some(last_expr) => NodeType::Node(last_expr), + None => NodeType::Node(expr.syntax().clone()), + }, + }) + .collect(); + + Some(arms) + } + Expr::BreakExpr(expr) => expr.expr().map(|e| vec![NodeType::Leaf(e)]), + Expr::ReturnExpr(ret_expr) => Some(vec![NodeType::Node(ret_expr.syntax().clone())]), + + Expr::CallExpr(_) + | Expr::Literal(_) + | Expr::TupleExpr(_) + | Expr::ArrayExpr(_) + | Expr::ParenExpr(_) + | Expr::PathExpr(_) + | Expr::RecordExpr(_) + | Expr::IndexExpr(_) + | Expr::MethodCallExpr(_) + | Expr::AwaitExpr(_) + | Expr::CastExpr(_) + | Expr::RefExpr(_) + | Expr::PrefixExpr(_) + | Expr::RangeExpr(_) + | Expr::BinExpr(_) + | Expr::MacroCall(_) + | Expr::BoxExpr(_) => Some(vec![NodeType::Leaf(expr.clone())]), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_assist, check_assist_not_applicable}; + + use super::*; + + #[test] + fn wrap_return_type_in_result_simple() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i3$02 { + let test = "test"; + return 42i32; +} +"#, + r#" +fn foo() -> Result { + let test = "test"; + return Ok(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_closure() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() { + || -> i32$0 { + let test = "test"; + return 42i32; + }; +} +"#, + r#" +fn foo() { + || -> Result { + let test = "test"; + return Ok(42i32); + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_return_type_bad_cursor() { + check_assist_not_applicable( + wrap_return_type_in_result, + r#" +fn foo() -> i32 { + let test = "test";$0 + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_return_type_bad_cursor_closure() { + check_assist_not_applicable( + wrap_return_type_in_result, + r#" +fn foo() { + || -> i32 { + let test = "test";$0 + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_closure_non_block() { + check_assist_not_applicable(wrap_return_type_in_result, r#"fn foo() { || -> i$032 3; }"#); + } + + #[test] + fn wrap_return_type_in_result_simple_return_type_already_result_std() { + check_assist_not_applicable( + wrap_return_type_in_result, + r#" +fn foo() -> std::result::Result { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_return_type_already_result() { + mark::check!(wrap_return_type_in_result_simple_return_type_already_result); + check_assist_not_applicable( + wrap_return_type_in_result, + r#" +fn foo() -> Result { + let test = "test"; + return 42i32; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_return_type_already_result_closure() { + check_assist_not_applicable( + wrap_return_type_in_result, + r#" +fn foo() { + || -> Result { + let test = "test"; + return 42i32; + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_cursor() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> $0i32 { + let test = "test"; + return 42i32; +} +"#, + r#" +fn foo() -> Result { + let test = "test"; + return Ok(42i32); +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() ->$0 i32 { + let test = "test"; + 42i32 +} +"#, + r#" +fn foo() -> Result { + let test = "test"; + Ok(42i32) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail_closure() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() { + || ->$0 i32 { + let test = "test"; + 42i32 + }; +} +"#, + r#" +fn foo() { + || -> Result { + let test = "test"; + Ok(42i32) + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail_only() { + check_assist( + wrap_return_type_in_result, + r#"fn foo() -> i32$0 { 42i32 }"#, + r#"fn foo() -> Result { Ok(42i32) }"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail_block_like() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + if true { + 42i32 + } else { + 24i32 + } +} +"#, + r#" +fn foo() -> Result { + if true { + Ok(42i32) + } else { + Ok(24i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_without_block_closure() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() { + || -> i32$0 { + if true { + 42i32 + } else { + 24i32 + } + }; +} +"#, + r#" +fn foo() { + || -> Result { + if true { + Ok(42i32) + } else { + Ok(24i32) + } + }; +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_nested_if() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + if true { + if false { + 1 + } else { + 2 + } + } else { + 24i32 + } +} +"#, + r#" +fn foo() -> Result { + if true { + if false { + Ok(1) + } else { + Ok(2) + } + } else { + Ok(24i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_await() { + check_assist( + wrap_return_type_in_result, + r#" +async fn foo() -> i$032 { + if true { + if false { + 1.await + } else { + 2.await + } + } else { + 24i32.await + } +} +"#, + r#" +async fn foo() -> Result { + if true { + if false { + Ok(1.await) + } else { + Ok(2.await) + } + } else { + Ok(24i32.await) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_array() { + check_assist( + wrap_return_type_in_result, + r#"fn foo() -> [i32;$0 3] { [1, 2, 3] }"#, + r#"fn foo() -> Result<[i32; 3], ${0:_}> { Ok([1, 2, 3]) }"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_cast() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -$0> i32 { + if true { + if false { + 1 as i32 + } else { + 2 as i32 + } + } else { + 24 as i32 + } +} +"#, + r#" +fn foo() -> Result { + if true { + if false { + Ok(1 as i32) + } else { + Ok(2 as i32) + } + } else { + Ok(24 as i32) + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail_block_like_match() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let my_var = 5; + match my_var { + 5 => 42i32, + _ => 24i32, + } +} +"#, + r#" +fn foo() -> Result { + let my_var = 5; + match my_var { + 5 => Ok(42i32), + _ => Ok(24i32), + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_loop_with_tail() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let my_var = 5; + loop { + println!("test"); + 5 + } + my_var +} +"#, + r#" +fn foo() -> Result { + let my_var = 5; + loop { + println!("test"); + 5 + } + Ok(my_var) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_loop_in_let_stmt() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let my_var = let x = loop { + break 1; + }; + my_var +} +"#, + r#" +fn foo() -> Result { + let my_var = let x = loop { + break 1; + }; + Ok(my_var) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail_block_like_match_return_expr() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return 24i32, + }; + res +} +"#, + r#" +fn foo() -> Result { + let my_var = 5; + let res = match my_var { + 5 => 42i32, + _ => return Ok(24i32), + }; + Ok(res) +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return 24i32; + }; + res +} +"#, + r#" +fn foo() -> Result { + let my_var = 5; + let res = if my_var == 5 { + 42i32 + } else { + return Ok(24i32); + }; + Ok(res) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail_block_like_match_deeper() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let my_var = 5; + match my_var { + 5 => { + if true { + 42i32 + } else { + 25i32 + } + }, + _ => { + let test = "test"; + if test == "test" { + return bar(); + } + 53i32 + }, + } +} +"#, + r#" +fn foo() -> Result { + let my_var = 5; + match my_var { + 5 => { + if true { + Ok(42i32) + } else { + Ok(25i32) + } + }, + _ => { + let test = "test"; + if test == "test" { + return Ok(bar()); + } + Ok(53i32) + }, + } +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_tail_block_like_early_return() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i$032 { + let test = "test"; + if test == "test" { + return 24i32; + } + 53i32 +} +"#, + r#" +fn foo() -> Result { + let test = "test"; + if test == "test" { + return Ok(24i32); + } + Ok(53i32) +} +"#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_closure() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo(the_field: u32) ->$0 u32 { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Result { + let true_closure = || { return true; }; + if the_field < 5 { + let mut i = 0; + if true_closure() { + return Ok(99); + } else { + return Ok(0); + } + } + Ok(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" + fn foo(the_field: u32) -> u32$0 { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return 99; + } else { + return 0; + } + } + let t = None; + + t.unwrap_or_else(|| the_field) + } + "#, + r#" + fn foo(the_field: u32) -> Result { + let true_closure = || { + return true; + }; + if the_field < 5 { + let mut i = 0; + + + if true_closure() { + return Ok(99); + } else { + return Ok(0); + } + } + let t = None; + + Ok(t.unwrap_or_else(|| the_field)) + } + "#, + ); + } + + #[test] + fn wrap_return_type_in_result_simple_with_weird_forms() { + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let test = "test"; + if test == "test" { + return 24i32; + } + let mut i = 0; + loop { + if i == 1 { + break 55; + } + i += 1; + } +} +"#, + r#" +fn foo() -> Result { + let test = "test"; + if test == "test" { + return Ok(24i32); + } + let mut i = 0; + loop { + if i == 1 { + break Ok(55); + } + i += 1; + } +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i32$0 { + let test = "test"; + if test == "test" { + return 24i32; + } + let mut i = 0; + loop { + loop { + if i == 1 { + break 55; + } + i += 1; + } + } +} +"#, + r#" +fn foo() -> Result { + let test = "test"; + if test == "test" { + return Ok(24i32); + } + let mut i = 0; + loop { + loop { + if i == 1 { + break Ok(55); + } + i += 1; + } + } +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" +fn foo() -> i3$02 { + let test = "test"; + let other = 5; + if test == "test" { + let res = match other { + 5 => 43, + _ => return 56, + }; + } + let mut i = 0; + loop { + loop { + if i == 1 { + break 55; + } + i += 1; + } + } +} +"#, + r#" +fn foo() -> Result { + let test = "test"; + let other = 5; + if test == "test" { + let res = match other { + 5 => 43, + _ => return Ok(56), + }; + } + let mut i = 0; + loop { + loop { + if i == 1 { + break Ok(55); + } + i += 1; + } + } +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" +fn foo(the_field: u32) -> u32$0 { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return 55u32; + } + i += 3; + } + match i { + 5 => return 99, + _ => return 0, + }; + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + loop { + if i > 5 { + return Ok(55u32); + } + i += 3; + } + match i { + 5 => return Ok(99), + _ => return Ok(0), + }; + } + Ok(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" +fn foo(the_field: u32) -> u3$02 { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return 99, + _ => return 0, + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + match i { + 5 => return Ok(99), + _ => return Ok(0), + } + } + Ok(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" +fn foo(the_field: u32) -> u32$0 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99 + } else { + return 0 + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Ok(99) + } else { + return Ok(0) + } + } + Ok(the_field) +} +"#, + ); + + check_assist( + wrap_return_type_in_result, + r#" +fn foo(the_field: u32) -> $0u32 { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return 99; + } else { + return 0; + } + } + the_field +} +"#, + r#" +fn foo(the_field: u32) -> Result { + if the_field < 5 { + let mut i = 0; + if i == 5 { + return Ok(99); + } else { + return Ok(0); + } + } + Ok(the_field) +} +"#, + ); + } +} diff --git a/crates/ide_assists/src/lib.rs b/crates/ide_assists/src/lib.rs new file mode 100644 index 000000000..7067cf8b6 --- /dev/null +++ b/crates/ide_assists/src/lib.rs @@ -0,0 +1,246 @@ +//! `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. + +#[allow(unused)] +macro_rules! eprintln { + ($($tt:tt)*) => { stdx::eprintln!($($tt)*) }; +} + +mod assist_config; +mod assist_context; +#[cfg(test)] +mod tests; +pub mod utils; +pub mod ast_transform; + +use hir::Semantics; +use ide_db::base_db::FileRange; +use ide_db::{label::Label, source_change::SourceChange, RootDatabase}; +use syntax::TextRange; + +pub(crate) use crate::assist_context::{AssistContext, Assists}; + +pub use assist_config::AssistConfig; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AssistKind { + None, + QuickFix, + Generate, + Refactor, + RefactorExtract, + RefactorInline, + RefactorRewrite, +} + +impl AssistKind { + pub fn contains(self, other: AssistKind) -> bool { + if self == other { + return true; + } + + match self { + AssistKind::None | AssistKind::Generate => return true, + AssistKind::Refactor => match other { + AssistKind::RefactorExtract + | AssistKind::RefactorInline + | AssistKind::RefactorRewrite => return true, + _ => return false, + }, + _ => return false, + } + } +} + +/// 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, pub AssistKind); + +#[derive(Clone, Debug)] +pub struct GroupLabel(pub String); + +#[derive(Debug, Clone)] +pub struct Assist { + pub id: AssistId, + /// Short description of the assist, as shown in the UI. + pub label: Label, + pub group: Option, + /// Target ranges are used to sort assists: the smaller the target range, + /// the more specific assist is, and so it should be sorted first. + pub target: TextRange, + /// Computing source change sometimes is much more costly then computing the + /// other fields. Additionally, the actual change is not required to show + /// the lightbulb UI, it only is needed when the user tries to apply an + /// assist. So, we compute it lazily: the API allow requesting assists with + /// or without source change. We could (and in fact, used to) distinguish + /// between resolved and unresolved assists at the type level, but this is + /// cumbersome, especially if you want to embed an assist into another data + /// structure, such as a diagnostic. + pub source_change: Option, +} + +impl Assist { + /// Return all the assists applicable at the given position. + pub fn get( + db: &RootDatabase, + config: &AssistConfig, + resolve: bool, + range: FileRange, + ) -> Vec { + let sema = Semantics::new(db); + let ctx = AssistContext::new(sema, config, range); + let mut acc = Assists::new(&ctx, resolve); + handlers::all().iter().for_each(|handler| { + handler(&mut acc, &ctx); + }); + acc.finish() + } +} + +mod handlers { + use crate::{AssistContext, Assists}; + + pub(crate) type Handler = fn(&mut Assists, &AssistContext) -> Option<()>; + + mod add_explicit_type; + mod add_lifetime_to_type; + mod add_missing_impl_members; + mod add_turbo_fish; + mod apply_demorgan; + mod auto_import; + mod change_visibility; + mod convert_integer_literal; + mod early_return; + mod expand_glob_import; + mod extract_function; + mod extract_struct_from_enum_variant; + mod extract_variable; + mod fill_match_arms; + mod fix_visibility; + mod flip_binexpr; + mod flip_comma; + mod flip_trait_bound; + mod generate_default_from_enum_variant; + mod generate_derive; + mod generate_enum_match_method; + mod generate_from_impl_for_enum; + mod generate_function; + mod generate_getter; + mod generate_getter_mut; + mod generate_impl; + mod generate_new; + mod generate_setter; + mod infer_function_return_type; + mod inline_function; + mod inline_local_variable; + mod introduce_named_lifetime; + mod invert_if; + mod merge_imports; + mod merge_match_arms; + mod move_bounds; + mod move_guard; + mod move_module_to_file; + mod pull_assignment_up; + mod qualify_path; + mod raw_string; + mod remove_dbg; + mod remove_mut; + mod remove_unused_param; + mod reorder_fields; + mod reorder_impl; + mod replace_derive_with_manual_impl; + mod replace_if_let_with_match; + mod replace_impl_trait_with_generic; + mod replace_let_with_if_let; + mod replace_qualified_name_with_use; + mod replace_string_with_char; + mod replace_unwrap_with_match; + mod split_import; + mod toggle_ignore; + mod unmerge_use; + mod unwrap_block; + mod wrap_return_type_in_result; + + pub(crate) fn all() -> &'static [Handler] { + &[ + // These are alphabetic for the foolish consistency + add_explicit_type::add_explicit_type, + add_lifetime_to_type::add_lifetime_to_type, + add_turbo_fish::add_turbo_fish, + apply_demorgan::apply_demorgan, + auto_import::auto_import, + change_visibility::change_visibility, + convert_integer_literal::convert_integer_literal, + early_return::convert_to_guarded_return, + expand_glob_import::expand_glob_import, + move_module_to_file::move_module_to_file, + extract_struct_from_enum_variant::extract_struct_from_enum_variant, + fill_match_arms::fill_match_arms, + fix_visibility::fix_visibility, + flip_binexpr::flip_binexpr, + flip_comma::flip_comma, + flip_trait_bound::flip_trait_bound, + generate_default_from_enum_variant::generate_default_from_enum_variant, + generate_derive::generate_derive, + generate_enum_match_method::generate_enum_match_method, + generate_from_impl_for_enum::generate_from_impl_for_enum, + generate_function::generate_function, + generate_getter::generate_getter, + generate_getter_mut::generate_getter_mut, + generate_impl::generate_impl, + generate_new::generate_new, + generate_setter::generate_setter, + infer_function_return_type::infer_function_return_type, + inline_function::inline_function, + inline_local_variable::inline_local_variable, + introduce_named_lifetime::introduce_named_lifetime, + invert_if::invert_if, + merge_imports::merge_imports, + merge_match_arms::merge_match_arms, + move_bounds::move_bounds_to_where_clause, + move_guard::move_arm_cond_to_match_guard, + move_guard::move_guard_to_arm_body, + pull_assignment_up::pull_assignment_up, + qualify_path::qualify_path, + raw_string::add_hash, + raw_string::make_usual_string, + raw_string::remove_hash, + remove_dbg::remove_dbg, + remove_mut::remove_mut, + remove_unused_param::remove_unused_param, + reorder_fields::reorder_fields, + reorder_impl::reorder_impl, + replace_derive_with_manual_impl::replace_derive_with_manual_impl, + replace_if_let_with_match::replace_if_let_with_match, + replace_if_let_with_match::replace_match_with_if_let, + replace_impl_trait_with_generic::replace_impl_trait_with_generic, + replace_let_with_if_let::replace_let_with_if_let, + replace_qualified_name_with_use::replace_qualified_name_with_use, + replace_unwrap_with_match::replace_unwrap_with_match, + split_import::split_import, + toggle_ignore::toggle_ignore, + unmerge_use::unmerge_use, + unwrap_block::unwrap_block, + wrap_return_type_in_result::wrap_return_type_in_result, + // These are manually sorted for better priorities. By default, + // priority is determined by the size of the target range (smaller + // target wins). If the ranges are equal, position in this list is + // used as a tie-breaker. + add_missing_impl_members::add_missing_impl_members, + add_missing_impl_members::add_missing_default_members, + // + replace_string_with_char::replace_string_with_char, + raw_string::make_raw_string, + // + extract_variable::extract_variable, + extract_function::extract_function, + // Are you sure you want to add new assist here, and not to the + // sorted list above? + ] + } +} diff --git a/crates/ide_assists/src/tests.rs b/crates/ide_assists/src/tests.rs new file mode 100644 index 000000000..384eb7eee --- /dev/null +++ b/crates/ide_assists/src/tests.rs @@ -0,0 +1,275 @@ +mod generated; + +use expect_test::expect; +use hir::Semantics; +use ide_db::{ + base_db::{fixture::WithFixture, FileId, FileRange, SourceDatabaseExt}, + helpers::{ + insert_use::{InsertUseConfig, MergeBehavior}, + SnippetCap, + }, + source_change::FileSystemEdit, + RootDatabase, +}; +use stdx::{format_to, trim_indent}; +use syntax::TextRange; +use test_utils::{assert_eq_text, extract_offset}; + +use crate::{handlers::Handler, Assist, AssistConfig, AssistContext, AssistKind, Assists}; + +pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig { + snippet_cap: SnippetCap::new(true), + allowed: None, + insert_use: InsertUseConfig { + merge: Some(MergeBehavior::Full), + prefix_kind: hir::PrefixKind::Plain, + }, +}; + +pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) { + RootDatabase::with_single_file(text) +} + +pub(crate) fn check_assist(assist: Handler, ra_fixture_before: &str, ra_fixture_after: &str) { + let ra_fixture_after = trim_indent(ra_fixture_after); + check(assist, ra_fixture_before, ExpectedResult::After(&ra_fixture_after), None); +} + +// There is no way to choose what assist within a group you want to test against, +// so this is here to allow you choose. +pub(crate) fn check_assist_by_label( + assist: Handler, + ra_fixture_before: &str, + ra_fixture_after: &str, + label: &str, +) { + let ra_fixture_after = trim_indent(ra_fixture_after); + check(assist, ra_fixture_before, ExpectedResult::After(&ra_fixture_after), Some(label)); +} + +// FIXME: instead of having a separate function here, maybe use +// `extract_ranges` and mark the target as ` ` in the +// fixture? +#[track_caller] +pub(crate) fn check_assist_target(assist: Handler, ra_fixture: &str, target: &str) { + check(assist, ra_fixture, ExpectedResult::Target(target), None); +} + +#[track_caller] +pub(crate) fn check_assist_not_applicable(assist: Handler, ra_fixture: &str) { + check(assist, ra_fixture, ExpectedResult::NotApplicable, None); +} + +#[track_caller] +fn check_doc_test(assist_id: &str, before: &str, after: &str) { + let after = trim_indent(after); + let (db, file_id, selection) = RootDatabase::with_range_or_offset(&before); + let before = db.file_text(file_id).to_string(); + let frange = FileRange { file_id, range: selection.into() }; + + let assist = Assist::get(&db, &TEST_CONFIG, true, frange) + .into_iter() + .find(|assist| assist.id.0 == assist_id) + .unwrap_or_else(|| { + panic!( + "\n\nAssist is not applicable: {}\nAvailable assists: {}", + assist_id, + Assist::get(&db, &TEST_CONFIG, false, frange) + .into_iter() + .map(|assist| assist.id.0) + .collect::>() + .join(", ") + ) + }); + + let actual = { + let source_change = assist.source_change.unwrap(); + let mut actual = before; + if let Some(source_file_edit) = source_change.get_source_edit(file_id) { + source_file_edit.apply(&mut actual); + } + actual + }; + assert_eq_text!(&after, &actual); +} + +enum ExpectedResult<'a> { + NotApplicable, + After(&'a str), + Target(&'a str), +} + +#[track_caller] +fn check(handler: Handler, before: &str, expected: ExpectedResult, assist_label: Option<&str>) { + let (db, file_with_caret_id, range_or_offset) = RootDatabase::with_range_or_offset(before); + let text_without_caret = db.file_text(file_with_caret_id).to_string(); + + let frange = FileRange { file_id: file_with_caret_id, range: range_or_offset.into() }; + + let sema = Semantics::new(&db); + let config = TEST_CONFIG; + let ctx = AssistContext::new(sema, &config, frange); + let mut acc = Assists::new(&ctx, true); + handler(&mut acc, &ctx); + let mut res = acc.finish(); + + let assist = match assist_label { + Some(label) => res.into_iter().find(|resolved| resolved.label == label), + None => res.pop(), + }; + + match (assist, expected) { + (Some(assist), ExpectedResult::After(after)) => { + let source_change = assist.source_change.unwrap(); + assert!(!source_change.source_file_edits.is_empty()); + let skip_header = source_change.source_file_edits.len() == 1 + && source_change.file_system_edits.len() == 0; + + let mut buf = String::new(); + for (file_id, edit) in source_change.source_file_edits { + let mut text = db.file_text(file_id).as_ref().to_owned(); + edit.apply(&mut text); + if !skip_header { + let sr = db.file_source_root(file_id); + let sr = db.source_root(sr); + let path = sr.path_for_file(&file_id).unwrap(); + format_to!(buf, "//- {}\n", path) + } + buf.push_str(&text); + } + + for file_system_edit in source_change.file_system_edits { + if let FileSystemEdit::CreateFile { dst, initial_contents } = file_system_edit { + let sr = db.file_source_root(dst.anchor); + let sr = db.source_root(sr); + let mut base = sr.path_for_file(&dst.anchor).unwrap().clone(); + base.pop(); + let created_file_path = format!("{}{}", base.to_string(), &dst.path[1..]); + format_to!(buf, "//- {}\n", created_file_path); + buf.push_str(&initial_contents); + } + } + + assert_eq_text!(after, &buf); + } + (Some(assist), ExpectedResult::Target(target)) => { + let range = assist.target; + assert_eq_text!(&text_without_caret[range], target); + } + (Some(_), ExpectedResult::NotApplicable) => panic!("assist should not be applicable!"), + (None, ExpectedResult::After(_)) | (None, ExpectedResult::Target(_)) => { + panic!("code action is not applicable") + } + (None, ExpectedResult::NotApplicable) => (), + }; +} + +fn labels(assists: &[Assist]) -> String { + let mut labels = assists + .iter() + .map(|assist| { + let mut label = match &assist.group { + Some(g) => g.0.clone(), + None => assist.label.to_string(), + }; + label.push('\n'); + label + }) + .collect::>(); + labels.dedup(); + labels.into_iter().collect::() +} + +#[test] +fn assist_order_field_struct() { + let before = "struct Foo { $0bar: u32 }"; + let (before_cursor_pos, before) = extract_offset(before); + let (db, file_id) = with_single_file(&before); + let frange = FileRange { file_id, range: TextRange::empty(before_cursor_pos) }; + let assists = Assist::get(&db, &TEST_CONFIG, false, frange); + let mut assists = assists.iter(); + + assert_eq!(assists.next().expect("expected assist").label, "Change visibility to pub(crate)"); + assert_eq!(assists.next().expect("expected assist").label, "Generate a getter method"); + assert_eq!(assists.next().expect("expected assist").label, "Generate a mut getter method"); + assert_eq!(assists.next().expect("expected assist").label, "Generate a setter method"); + assert_eq!(assists.next().expect("expected assist").label, "Add `#[derive]`"); +} + +#[test] +fn assist_order_if_expr() { + let (db, frange) = RootDatabase::with_range( + r#" +pub fn test_some_range(a: int) -> bool { + if let 2..6 = $05$0 { + true + } else { + false + } +} +"#, + ); + + let assists = Assist::get(&db, &TEST_CONFIG, false, frange); + let expected = labels(&assists); + + expect![[r#" + Convert integer base + Extract into variable + Extract into function + Replace with match + "#]] + .assert_eq(&expected); +} + +#[test] +fn assist_filter_works() { + let (db, frange) = RootDatabase::with_range( + r#" +pub fn test_some_range(a: int) -> bool { + if let 2..6 = $05$0 { + true + } else { + false + } +} +"#, + ); + { + let mut cfg = TEST_CONFIG; + cfg.allowed = Some(vec![AssistKind::Refactor]); + + let assists = Assist::get(&db, &cfg, false, frange); + let expected = labels(&assists); + + expect![[r#" + Convert integer base + Extract into variable + Extract into function + Replace with match + "#]] + .assert_eq(&expected); + } + + { + let mut cfg = TEST_CONFIG; + cfg.allowed = Some(vec![AssistKind::RefactorExtract]); + let assists = Assist::get(&db, &cfg, false, frange); + let expected = labels(&assists); + + expect![[r#" + Extract into variable + Extract into function + "#]] + .assert_eq(&expected); + } + + { + let mut cfg = TEST_CONFIG; + cfg.allowed = Some(vec![AssistKind::QuickFix]); + let assists = Assist::get(&db, &cfg, false, frange); + let expected = labels(&assists); + + expect![[r#""#]].assert_eq(&expected); + } +} diff --git a/crates/ide_assists/src/tests/generated.rs b/crates/ide_assists/src/tests/generated.rs new file mode 100644 index 000000000..0516deaff --- /dev/null +++ b/crates/ide_assists/src/tests/generated.rs @@ -0,0 +1,1329 @@ +//! Generated file, do not edit by hand, see `xtask/src/codegen` + +use super::check_doc_test; + +#[test] +fn doctest_add_explicit_type() { + check_doc_test( + "add_explicit_type", + r#####" +fn main() { + let x$0 = 92; +} +"#####, + r#####" +fn main() { + let x: i32 = 92; +} +"#####, + ) +} + +#[test] +fn doctest_add_hash() { + check_doc_test( + "add_hash", + r#####" +fn main() { + r#"Hello,$0 World!"#; +} +"#####, + r#####" +fn main() { + r##"Hello, World!"##; +} +"#####, + ) +} + +#[test] +fn doctest_add_impl_default_members() { + check_doc_test( + "add_impl_default_members", + r#####" +trait Trait { + type X; + fn foo(&self); + fn bar(&self) {} +} + +impl Trait for () { + type X = (); + fn foo(&self) {}$0 + +} +"#####, + r#####" +trait Trait { + type X; + fn foo(&self); + fn bar(&self) {} +} + +impl Trait for () { + type X = (); + fn foo(&self) {} + + $0fn bar(&self) {} +} +"#####, + ) +} + +#[test] +fn doctest_add_impl_missing_members() { + check_doc_test( + "add_impl_missing_members", + r#####" +trait Trait { + type X; + fn foo(&self) -> T; + fn bar(&self) {} +} + +impl Trait for () {$0 + +} +"#####, + r#####" +trait Trait { + type X; + fn foo(&self) -> T; + fn bar(&self) {} +} + +impl Trait for () { + $0type X; + + fn foo(&self) -> u32 { + todo!() + } +} +"#####, + ) +} + +#[test] +fn doctest_add_lifetime_to_type() { + check_doc_test( + "add_lifetime_to_type", + r#####" +struct Point { + x: &$0u32, + y: u32, +} +"#####, + r#####" +struct Point<'a> { + x: &'a u32, + y: u32, +} +"#####, + ) +} + +#[test] +fn doctest_add_turbo_fish() { + check_doc_test( + "add_turbo_fish", + r#####" +fn make() -> T { todo!() } +fn main() { + let x = make$0(); +} +"#####, + r#####" +fn make() -> T { todo!() } +fn main() { + let x = make::<${0:_}>(); +} +"#####, + ) +} + +#[test] +fn doctest_apply_demorgan() { + check_doc_test( + "apply_demorgan", + r#####" +fn main() { + if x != 4 ||$0 !y {} +} +"#####, + r#####" +fn main() { + if !(x == 4 && y) {} +} +"#####, + ) +} + +#[test] +fn doctest_auto_import() { + check_doc_test( + "auto_import", + r#####" +fn main() { + let map = HashMap$0::new(); +} +pub mod std { pub mod collections { pub struct HashMap { } } } +"#####, + r#####" +use std::collections::HashMap; + +fn main() { + let map = HashMap::new(); +} +pub mod std { pub mod collections { pub struct HashMap { } } } +"#####, + ) +} + +#[test] +fn doctest_change_visibility() { + check_doc_test( + "change_visibility", + r#####" +$0fn frobnicate() {} +"#####, + r#####" +pub(crate) fn frobnicate() {} +"#####, + ) +} + +#[test] +fn doctest_convert_integer_literal() { + check_doc_test( + "convert_integer_literal", + r#####" +const _: i32 = 10$0; +"#####, + r#####" +const _: i32 = 0b1010; +"#####, + ) +} + +#[test] +fn doctest_convert_to_guarded_return() { + check_doc_test( + "convert_to_guarded_return", + r#####" +fn main() { + $0if cond { + foo(); + bar(); + } +} +"#####, + r#####" +fn main() { + if !cond { + return; + } + foo(); + bar(); +} +"#####, + ) +} + +#[test] +fn doctest_expand_glob_import() { + check_doc_test( + "expand_glob_import", + r#####" +mod foo { + pub struct Bar; + pub struct Baz; +} + +use foo::*$0; + +fn qux(bar: Bar, baz: Baz) {} +"#####, + r#####" +mod foo { + pub struct Bar; + pub struct Baz; +} + +use foo::{Baz, Bar}; + +fn qux(bar: Bar, baz: Baz) {} +"#####, + ) +} + +#[test] +fn doctest_extract_function() { + check_doc_test( + "extract_function", + r#####" +fn main() { + let n = 1; + $0let m = n + 2; + let k = m + n;$0 + let g = 3; +} +"#####, + r#####" +fn main() { + let n = 1; + fun_name(n); + let g = 3; +} + +fn $0fun_name(n: i32) { + let m = n + 2; + let k = m + n; +} +"#####, + ) +} + +#[test] +fn doctest_extract_struct_from_enum_variant() { + check_doc_test( + "extract_struct_from_enum_variant", + r#####" +enum A { $0One(u32, u32) } +"#####, + r#####" +struct One(pub u32, pub u32); + +enum A { One(One) } +"#####, + ) +} + +#[test] +fn doctest_extract_variable() { + check_doc_test( + "extract_variable", + r#####" +fn main() { + $0(1 + 2)$0 * 4; +} +"#####, + r#####" +fn main() { + let $0var_name = (1 + 2); + var_name * 4; +} +"#####, + ) +} + +#[test] +fn doctest_fill_match_arms() { + check_doc_test( + "fill_match_arms", + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + $0 + } +} +"#####, + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + $0Action::Move { distance } => {} + Action::Stop => {} + } +} +"#####, + ) +} + +#[test] +fn doctest_fix_visibility() { + check_doc_test( + "fix_visibility", + r#####" +mod m { + fn frobnicate() {} +} +fn main() { + m::frobnicate$0() {} +} +"#####, + r#####" +mod m { + $0pub(crate) fn frobnicate() {} +} +fn main() { + m::frobnicate() {} +} +"#####, + ) +} + +#[test] +fn doctest_flip_binexpr() { + check_doc_test( + "flip_binexpr", + r#####" +fn main() { + let _ = 90 +$0 2; +} +"#####, + r#####" +fn main() { + let _ = 2 + 90; +} +"#####, + ) +} + +#[test] +fn doctest_flip_comma() { + check_doc_test( + "flip_comma", + r#####" +fn main() { + ((1, 2),$0 (3, 4)); +} +"#####, + r#####" +fn main() { + ((3, 4), (1, 2)); +} +"#####, + ) +} + +#[test] +fn doctest_flip_trait_bound() { + check_doc_test( + "flip_trait_bound", + r#####" +fn foo() { } +"#####, + r#####" +fn foo() { } +"#####, + ) +} + +#[test] +fn doctest_generate_default_from_enum_variant() { + check_doc_test( + "generate_default_from_enum_variant", + r#####" +enum Version { + Undefined, + Minor$0, + Major, +} +"#####, + r#####" +enum Version { + Undefined, + Minor, + Major, +} + +impl Default for Version { + fn default() -> Self { + Self::Minor + } +} +"#####, + ) +} + +#[test] +fn doctest_generate_derive() { + check_doc_test( + "generate_derive", + r#####" +struct Point { + x: u32, + y: u32,$0 +} +"#####, + r#####" +#[derive($0)] +struct Point { + x: u32, + y: u32, +} +"#####, + ) +} + +#[test] +fn doctest_generate_enum_match_method() { + check_doc_test( + "generate_enum_match_method", + r#####" +enum Version { + Undefined, + Minor$0, + Major, +} +"#####, + r#####" +enum Version { + Undefined, + Minor, + Major, +} + +impl Version { + /// Returns `true` if the version is [`Minor`]. + fn is_minor(&self) -> bool { + matches!(self, Self::Minor) + } +} +"#####, + ) +} + +#[test] +fn doctest_generate_from_impl_for_enum() { + check_doc_test( + "generate_from_impl_for_enum", + r#####" +enum A { $0One(u32) } +"#####, + r#####" +enum A { One(u32) } + +impl From for A { + fn from(v: u32) -> Self { + Self::One(v) + } +} +"#####, + ) +} + +#[test] +fn doctest_generate_function() { + check_doc_test( + "generate_function", + r#####" +struct Baz; +fn baz() -> Baz { Baz } +fn foo() { + bar$0("", baz()); +} + +"#####, + r#####" +struct Baz; +fn baz() -> Baz { Baz } +fn foo() { + bar("", baz()); +} + +fn bar(arg: &str, baz: Baz) ${0:-> ()} { + todo!() +} + +"#####, + ) +} + +#[test] +fn doctest_generate_getter() { + check_doc_test( + "generate_getter", + r#####" +struct Person { + nam$0e: String, +} +"#####, + r#####" +struct Person { + name: String, +} + +impl Person { + /// Get a reference to the person's name. + fn name(&self) -> &String { + &self.name + } +} +"#####, + ) +} + +#[test] +fn doctest_generate_getter_mut() { + check_doc_test( + "generate_getter_mut", + r#####" +struct Person { + nam$0e: String, +} +"#####, + r#####" +struct Person { + name: String, +} + +impl Person { + /// Get a mutable reference to the person's name. + fn name_mut(&mut self) -> &mut String { + &mut self.name + } +} +"#####, + ) +} + +#[test] +fn doctest_generate_impl() { + check_doc_test( + "generate_impl", + r#####" +struct Ctx { + data: T,$0 +} +"#####, + r#####" +struct Ctx { + data: T, +} + +impl Ctx { + $0 +} +"#####, + ) +} + +#[test] +fn doctest_generate_new() { + check_doc_test( + "generate_new", + r#####" +struct Ctx { + data: T,$0 +} +"#####, + r#####" +struct Ctx { + data: T, +} + +impl Ctx { + fn $0new(data: T) -> Self { Self { data } } +} +"#####, + ) +} + +#[test] +fn doctest_generate_setter() { + check_doc_test( + "generate_setter", + r#####" +struct Person { + nam$0e: String, +} +"#####, + r#####" +struct Person { + name: String, +} + +impl Person { + /// Set the person's name. + fn set_name(&mut self, name: String) { + self.name = name; + } +} +"#####, + ) +} + +#[test] +fn doctest_infer_function_return_type() { + check_doc_test( + "infer_function_return_type", + r#####" +fn foo() { 4$02i32 } +"#####, + r#####" +fn foo() -> i32 { 42i32 } +"#####, + ) +} + +#[test] +fn doctest_inline_function() { + check_doc_test( + "inline_function", + r#####" +fn add(a: u32, b: u32) -> u32 { a + b } +fn main() { + let x = add$0(1, 2); +} +"#####, + r#####" +fn add(a: u32, b: u32) -> u32 { a + b } +fn main() { + let x = { + let a = 1; + let b = 2; + a + b + }; +} +"#####, + ) +} + +#[test] +fn doctest_inline_local_variable() { + check_doc_test( + "inline_local_variable", + r#####" +fn main() { + let x$0 = 1 + 2; + x * 4; +} +"#####, + r#####" +fn main() { + (1 + 2) * 4; +} +"#####, + ) +} + +#[test] +fn doctest_introduce_named_lifetime() { + check_doc_test( + "introduce_named_lifetime", + r#####" +impl Cursor<'_$0> { + fn node(self) -> &SyntaxNode { + match self { + Cursor::Replace(node) | Cursor::Before(node) => node, + } + } +} +"#####, + r#####" +impl<'a> Cursor<'a> { + fn node(self) -> &SyntaxNode { + match self { + Cursor::Replace(node) | Cursor::Before(node) => node, + } + } +} +"#####, + ) +} + +#[test] +fn doctest_invert_if() { + check_doc_test( + "invert_if", + r#####" +fn main() { + if$0 !y { A } else { B } +} +"#####, + r#####" +fn main() { + if y { B } else { A } +} +"#####, + ) +} + +#[test] +fn doctest_make_raw_string() { + check_doc_test( + "make_raw_string", + r#####" +fn main() { + "Hello,$0 World!"; +} +"#####, + r#####" +fn main() { + r#"Hello, World!"#; +} +"#####, + ) +} + +#[test] +fn doctest_make_usual_string() { + check_doc_test( + "make_usual_string", + r#####" +fn main() { + r#"Hello,$0 "World!""#; +} +"#####, + r#####" +fn main() { + "Hello, \"World!\""; +} +"#####, + ) +} + +#[test] +fn doctest_merge_imports() { + check_doc_test( + "merge_imports", + r#####" +use std::$0fmt::Formatter; +use std::io; +"#####, + r#####" +use std::{fmt::Formatter, io}; +"#####, + ) +} + +#[test] +fn doctest_merge_match_arms() { + check_doc_test( + "merge_match_arms", + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + $0Action::Move(..) => foo(), + Action::Stop => foo(), + } +} +"#####, + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + Action::Move(..) | Action::Stop => foo(), + } +} +"#####, + ) +} + +#[test] +fn doctest_move_arm_cond_to_match_guard() { + check_doc_test( + "move_arm_cond_to_match_guard", + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + Action::Move { distance } => $0if distance > 10 { foo() }, + _ => (), + } +} +"#####, + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + Action::Move { distance } if distance > 10 => foo(), + _ => (), + } +} +"#####, + ) +} + +#[test] +fn doctest_move_bounds_to_where_clause() { + check_doc_test( + "move_bounds_to_where_clause", + r#####" +fn apply U>(f: F, x: T) -> U { + f(x) +} +"#####, + r#####" +fn apply(f: F, x: T) -> U where F: FnOnce(T) -> U { + f(x) +} +"#####, + ) +} + +#[test] +fn doctest_move_guard_to_arm_body() { + check_doc_test( + "move_guard_to_arm_body", + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + Action::Move { distance } $0if distance > 10 => foo(), + _ => (), + } +} +"#####, + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + Action::Move { distance } => if distance > 10 { + foo() + }, + _ => (), + } +} +"#####, + ) +} + +#[test] +fn doctest_move_module_to_file() { + check_doc_test( + "move_module_to_file", + r#####" +mod $0foo { + fn t() {} +} +"#####, + r#####" +mod foo; +"#####, + ) +} + +#[test] +fn doctest_pull_assignment_up() { + check_doc_test( + "pull_assignment_up", + r#####" +fn main() { + let mut foo = 6; + + if true { + $0foo = 5; + } else { + foo = 4; + } +} +"#####, + r#####" +fn main() { + let mut foo = 6; + + foo = if true { + 5 + } else { + 4 + }; +} +"#####, + ) +} + +#[test] +fn doctest_qualify_path() { + check_doc_test( + "qualify_path", + r#####" +fn main() { + let map = HashMap$0::new(); +} +pub mod std { pub mod collections { pub struct HashMap { } } } +"#####, + r#####" +fn main() { + let map = std::collections::HashMap::new(); +} +pub mod std { pub mod collections { pub struct HashMap { } } } +"#####, + ) +} + +#[test] +fn doctest_remove_dbg() { + check_doc_test( + "remove_dbg", + r#####" +fn main() { + $0dbg!(92); +} +"#####, + r#####" +fn main() { + 92; +} +"#####, + ) +} + +#[test] +fn doctest_remove_hash() { + check_doc_test( + "remove_hash", + r#####" +fn main() { + r#"Hello,$0 World!"#; +} +"#####, + r#####" +fn main() { + r"Hello, World!"; +} +"#####, + ) +} + +#[test] +fn doctest_remove_mut() { + check_doc_test( + "remove_mut", + r#####" +impl Walrus { + fn feed(&mut$0 self, amount: u32) {} +} +"#####, + r#####" +impl Walrus { + fn feed(&self, amount: u32) {} +} +"#####, + ) +} + +#[test] +fn doctest_remove_unused_param() { + check_doc_test( + "remove_unused_param", + r#####" +fn frobnicate(x: i32$0) {} + +fn main() { + frobnicate(92); +} +"#####, + r#####" +fn frobnicate() {} + +fn main() { + frobnicate(); +} +"#####, + ) +} + +#[test] +fn doctest_reorder_fields() { + check_doc_test( + "reorder_fields", + r#####" +struct Foo {foo: i32, bar: i32}; +const test: Foo = $0Foo {bar: 0, foo: 1} +"#####, + r#####" +struct Foo {foo: i32, bar: i32}; +const test: Foo = Foo {foo: 1, bar: 0} +"#####, + ) +} + +#[test] +fn doctest_reorder_impl() { + check_doc_test( + "reorder_impl", + r#####" +trait Foo { + fn a() {} + fn b() {} + fn c() {} +} + +struct Bar; +$0impl Foo for Bar { + fn b() {} + fn c() {} + fn a() {} +} +"#####, + r#####" +trait Foo { + fn a() {} + fn b() {} + fn c() {} +} + +struct Bar; +impl Foo for Bar { + fn a() {} + fn b() {} + fn c() {} +} +"#####, + ) +} + +#[test] +fn doctest_replace_derive_with_manual_impl() { + check_doc_test( + "replace_derive_with_manual_impl", + r#####" +trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; } +#[derive(Deb$0ug, Display)] +struct S; +"#####, + r#####" +trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; } +#[derive(Display)] +struct S; + +impl Debug for S { + fn fmt(&self, f: &mut Formatter) -> Result<()> { + ${0:todo!()} + } +} +"#####, + ) +} + +#[test] +fn doctest_replace_if_let_with_match() { + check_doc_test( + "replace_if_let_with_match", + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + $0if let Action::Move { distance } = action { + foo(distance) + } else { + bar() + } +} +"#####, + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + match action { + Action::Move { distance } => foo(distance), + _ => bar(), + } +} +"#####, + ) +} + +#[test] +fn doctest_replace_impl_trait_with_generic() { + check_doc_test( + "replace_impl_trait_with_generic", + r#####" +fn foo(bar: $0impl Bar) {} +"#####, + r#####" +fn foo(bar: B) {} +"#####, + ) +} + +#[test] +fn doctest_replace_let_with_if_let() { + check_doc_test( + "replace_let_with_if_let", + r#####" +enum Option { Some(T), None } + +fn main(action: Action) { + $0let x = compute(); +} + +fn compute() -> Option { None } +"#####, + r#####" +enum Option { Some(T), None } + +fn main(action: Action) { + if let Some(x) = compute() { + } +} + +fn compute() -> Option { None } +"#####, + ) +} + +#[test] +fn doctest_replace_match_with_if_let() { + check_doc_test( + "replace_match_with_if_let", + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + $0match action { + Action::Move { distance } => foo(distance), + _ => bar(), + } +} +"#####, + r#####" +enum Action { Move { distance: u32 }, Stop } + +fn handle(action: Action) { + if let Action::Move { distance } = action { + foo(distance) + } else { + bar() + } +} +"#####, + ) +} + +#[test] +fn doctest_replace_qualified_name_with_use() { + check_doc_test( + "replace_qualified_name_with_use", + r#####" +fn process(map: std::collections::$0HashMap) {} +"#####, + r#####" +use std::collections::HashMap; + +fn process(map: HashMap) {} +"#####, + ) +} + +#[test] +fn doctest_replace_string_with_char() { + check_doc_test( + "replace_string_with_char", + r#####" +fn main() { + find("{$0"); +} +"#####, + r#####" +fn main() { + find('{'); +} +"#####, + ) +} + +#[test] +fn doctest_replace_unwrap_with_match() { + check_doc_test( + "replace_unwrap_with_match", + r#####" +enum Result { Ok(T), Err(E) } +fn main() { + let x: Result = Result::Ok(92); + let y = x.$0unwrap(); +} +"#####, + r#####" +enum Result { Ok(T), Err(E) } +fn main() { + let x: Result = Result::Ok(92); + let y = match x { + Ok(a) => a, + $0_ => unreachable!(), + }; +} +"#####, + ) +} + +#[test] +fn doctest_split_import() { + check_doc_test( + "split_import", + r#####" +use std::$0collections::HashMap; +"#####, + r#####" +use std::{collections::HashMap}; +"#####, + ) +} + +#[test] +fn doctest_toggle_ignore() { + check_doc_test( + "toggle_ignore", + r#####" +$0#[test] +fn arithmetics { + assert_eq!(2 + 2, 5); +} +"#####, + r#####" +#[test] +#[ignore] +fn arithmetics { + assert_eq!(2 + 2, 5); +} +"#####, + ) +} + +#[test] +fn doctest_unmerge_use() { + check_doc_test( + "unmerge_use", + r#####" +use std::fmt::{Debug, Display$0}; +"#####, + r#####" +use std::fmt::{Debug}; +use std::fmt::Display; +"#####, + ) +} + +#[test] +fn doctest_unwrap_block() { + check_doc_test( + "unwrap_block", + r#####" +fn foo() { + if true {$0 + println!("foo"); + } +} +"#####, + r#####" +fn foo() { + println!("foo"); +} +"#####, + ) +} + +#[test] +fn doctest_wrap_return_type_in_result() { + check_doc_test( + "wrap_return_type_in_result", + r#####" +fn foo() -> i32$0 { 42i32 } +"#####, + r#####" +fn foo() -> Result { Ok(42i32) } +"#####, + ) +} diff --git a/crates/ide_assists/src/utils.rs b/crates/ide_assists/src/utils.rs new file mode 100644 index 000000000..0074da741 --- /dev/null +++ b/crates/ide_assists/src/utils.rs @@ -0,0 +1,434 @@ +//! Assorted functions shared by several assists. + +use std::ops; + +use ast::TypeBoundsOwner; +use hir::{Adt, HasSource}; +use ide_db::{helpers::SnippetCap, RootDatabase}; +use itertools::Itertools; +use stdx::format_to; +use syntax::{ + ast::edit::AstNodeEdit, + ast::AttrsOwner, + ast::NameOwner, + ast::{self, edit, make, ArgListOwner, GenericParamsOwner}, + AstNode, Direction, SmolStr, + SyntaxKind::*, + SyntaxNode, TextSize, T, +}; + +use crate::{ + assist_context::AssistContext, + ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams}, +}; + +pub(crate) fn unwrap_trivial_block(block: ast::BlockExpr) -> ast::Expr { + extract_trivial_expression(&block) + .filter(|expr| !expr.syntax().text().contains_char('\n')) + .unwrap_or_else(|| block.into()) +} + +pub fn extract_trivial_expression(block: &ast::BlockExpr) -> Option { + let has_anything_else = |thing: &SyntaxNode| -> bool { + let mut non_trivial_children = + block.syntax().children_with_tokens().filter(|it| match it.kind() { + WHITESPACE | T!['{'] | T!['}'] => false, + _ => it.as_node() != Some(thing), + }); + non_trivial_children.next().is_some() + }; + + if let Some(expr) = block.tail_expr() { + if has_anything_else(expr.syntax()) { + return None; + } + return Some(expr); + } + // Unwrap `{ continue; }` + let (stmt,) = block.statements().next_tuple()?; + if let ast::Stmt::ExprStmt(expr_stmt) = stmt { + if has_anything_else(expr_stmt.syntax()) { + return None; + } + let expr = expr_stmt.expr()?; + match expr.syntax().kind() { + CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR => return Some(expr), + _ => (), + } + } + None +} + +/// This is a method with a heuristics to support test methods annotated with custom test annotations, such as +/// `#[test_case(...)]`, `#[tokio::test]` and similar. +/// Also a regular `#[test]` annotation is supported. +/// +/// It may produce false positives, for example, `#[wasm_bindgen_test]` requires a different command to run the test, +/// but it's better than not to have the runnables for the tests at all. +pub fn test_related_attribute(fn_def: &ast::Fn) -> Option { + fn_def.attrs().find_map(|attr| { + let path = attr.path()?; + if path.syntax().text().to_string().contains("test") { + Some(attr) + } else { + None + } + }) +} + +#[derive(Copy, Clone, PartialEq)] +pub enum DefaultMethods { + Only, + No, +} + +pub fn filter_assoc_items( + db: &RootDatabase, + items: &[hir::AssocItem], + default_methods: DefaultMethods, +) -> Vec { + fn has_def_name(item: &ast::AssocItem) -> bool { + match item { + ast::AssocItem::Fn(def) => def.name(), + ast::AssocItem::TypeAlias(def) => def.name(), + ast::AssocItem::Const(def) => def.name(), + ast::AssocItem::MacroCall(_) => None, + } + .is_some() + } + + items + .iter() + // Note: This throws away items with no source. + .filter_map(|i| { + let item = match i { + hir::AssocItem::Function(i) => ast::AssocItem::Fn(i.source(db)?.value), + hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(i.source(db)?.value), + hir::AssocItem::Const(i) => ast::AssocItem::Const(i.source(db)?.value), + }; + Some(item) + }) + .filter(has_def_name) + .filter(|it| match it { + ast::AssocItem::Fn(def) => matches!( + (default_methods, def.body()), + (DefaultMethods::Only, Some(_)) | (DefaultMethods::No, None) + ), + _ => default_methods == DefaultMethods::No, + }) + .collect::>() +} + +pub fn add_trait_assoc_items_to_impl( + sema: &hir::Semantics, + items: Vec, + trait_: hir::Trait, + impl_def: ast::Impl, + target_scope: hir::SemanticsScope, +) -> (ast::Impl, ast::AssocItem) { + let impl_item_list = impl_def.assoc_item_list().unwrap_or_else(make::assoc_item_list); + + let n_existing_items = impl_item_list.assoc_items().count(); + let source_scope = sema.scope_for_def(trait_); + let ast_transform = QualifyPaths::new(&target_scope, &source_scope) + .or(SubstituteTypeParams::for_trait_impl(&source_scope, trait_, impl_def.clone())); + + let items = items + .into_iter() + .map(|it| ast_transform::apply(&*ast_transform, it)) + .map(|it| match it { + ast::AssocItem::Fn(def) => ast::AssocItem::Fn(add_body(def)), + ast::AssocItem::TypeAlias(def) => ast::AssocItem::TypeAlias(def.remove_bounds()), + _ => it, + }) + .map(|it| edit::remove_attrs_and_docs(&it)); + + let new_impl_item_list = impl_item_list.append_items(items); + let new_impl_def = impl_def.with_assoc_item_list(new_impl_item_list); + let first_new_item = + new_impl_def.assoc_item_list().unwrap().assoc_items().nth(n_existing_items).unwrap(); + return (new_impl_def, first_new_item); + + fn add_body(fn_def: ast::Fn) -> ast::Fn { + match fn_def.body() { + Some(_) => fn_def, + None => { + let body = + make::block_expr(None, Some(make::expr_todo())).indent(edit::IndentLevel(1)); + fn_def.with_body(body) + } + } + } +} + +#[derive(Clone, Copy, Debug)] +pub(crate) enum Cursor<'a> { + Replace(&'a SyntaxNode), + Before(&'a SyntaxNode), +} + +impl<'a> Cursor<'a> { + fn node(self) -> &'a SyntaxNode { + match self { + Cursor::Replace(node) | Cursor::Before(node) => node, + } + } +} + +pub(crate) fn render_snippet(_cap: SnippetCap, node: &SyntaxNode, cursor: Cursor) -> String { + assert!(cursor.node().ancestors().any(|it| it == *node)); + let range = cursor.node().text_range() - node.text_range().start(); + let range: ops::Range = range.into(); + + let mut placeholder = cursor.node().to_string(); + escape(&mut placeholder); + let tab_stop = match cursor { + Cursor::Replace(placeholder) => format!("${{0:{}}}", placeholder), + Cursor::Before(placeholder) => format!("$0{}", placeholder), + }; + + let mut buf = node.to_string(); + buf.replace_range(range, &tab_stop); + return buf; + + fn escape(buf: &mut String) { + stdx::replace(buf, '{', r"\{"); + stdx::replace(buf, '}', r"\}"); + stdx::replace(buf, '$', r"\$"); + } +} + +pub(crate) fn vis_offset(node: &SyntaxNode) -> TextSize { + node.children_with_tokens() + .find(|it| !matches!(it.kind(), WHITESPACE | COMMENT | ATTR)) + .map(|it| it.text_range().start()) + .unwrap_or_else(|| node.text_range().start()) +} + +pub(crate) fn invert_boolean_expression(expr: ast::Expr) -> ast::Expr { + if let Some(expr) = invert_special_case(&expr) { + return expr; + } + make::expr_prefix(T![!], expr) +} + +fn invert_special_case(expr: &ast::Expr) -> Option { + match expr { + ast::Expr::BinExpr(bin) => match bin.op_kind()? { + ast::BinOp::NegatedEqualityTest => bin.replace_op(T![==]).map(|it| it.into()), + ast::BinOp::EqualityTest => bin.replace_op(T![!=]).map(|it| it.into()), + // Parenthesize composite boolean expressions before prefixing `!` + ast::BinOp::BooleanAnd | ast::BinOp::BooleanOr => { + Some(make::expr_prefix(T![!], make::expr_paren(expr.clone()))) + } + _ => None, + }, + ast::Expr::MethodCallExpr(mce) => { + let receiver = mce.receiver()?; + let method = mce.name_ref()?; + let arg_list = mce.arg_list()?; + + let method = match method.text() { + "is_some" => "is_none", + "is_none" => "is_some", + "is_ok" => "is_err", + "is_err" => "is_ok", + _ => return None, + }; + Some(make::expr_method_call(receiver, method, arg_list)) + } + ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::PrefixOp::Not => { + if let ast::Expr::ParenExpr(parexpr) = pe.expr()? { + parexpr.expr() + } else { + pe.expr() + } + } + // FIXME: + // ast::Expr::Literal(true | false ) + _ => None, + } +} + +pub(crate) fn next_prev() -> impl Iterator { + [Direction::Next, Direction::Prev].iter().copied() +} + +pub(crate) fn does_pat_match_variant(pat: &ast::Pat, var: &ast::Pat) -> bool { + let first_node_text = |pat: &ast::Pat| pat.syntax().first_child().map(|node| node.text()); + + let pat_head = match pat { + ast::Pat::IdentPat(bind_pat) => { + if let Some(p) = bind_pat.pat() { + first_node_text(&p) + } else { + return pat.syntax().text() == var.syntax().text(); + } + } + pat => first_node_text(pat), + }; + + let var_head = first_node_text(var); + + pat_head == var_head +} + +// Uses a syntax-driven approach to find any impl blocks for the struct that +// exist within the module/file +// +// Returns `None` if we've found an existing fn +// +// FIXME: change the new fn checking to a more semantic approach when that's more +// viable (e.g. we process proc macros, etc) +// FIXME: this partially overlaps with `find_impl_block_*` +pub(crate) fn find_struct_impl( + ctx: &AssistContext, + strukt: &ast::Adt, + name: &str, +) -> Option> { + let db = ctx.db(); + let module = strukt.syntax().ancestors().find(|node| { + ast::Module::can_cast(node.kind()) || ast::SourceFile::can_cast(node.kind()) + })?; + + let struct_def = match strukt { + ast::Adt::Enum(e) => Adt::Enum(ctx.sema.to_def(e)?), + ast::Adt::Struct(s) => Adt::Struct(ctx.sema.to_def(s)?), + ast::Adt::Union(u) => Adt::Union(ctx.sema.to_def(u)?), + }; + + let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| { + let blk = ctx.sema.to_def(&impl_blk)?; + + // FIXME: handle e.g. `struct S; impl S {}` + // (we currently use the wrong type parameter) + // also we wouldn't want to use e.g. `impl S` + + let same_ty = match blk.target_ty(db).as_adt() { + Some(def) => def == struct_def, + None => false, + }; + let not_trait_impl = blk.target_trait(db).is_none(); + + if !(same_ty && not_trait_impl) { + None + } else { + Some(impl_blk) + } + }); + + if let Some(ref impl_blk) = block { + if has_fn(impl_blk, name) { + return None; + } + } + + Some(block) +} + +fn has_fn(imp: &ast::Impl, rhs_name: &str) -> bool { + if let Some(il) = imp.assoc_item_list() { + for item in il.assoc_items() { + if let ast::AssocItem::Fn(f) = item { + if let Some(name) = f.name() { + if name.text().eq_ignore_ascii_case(rhs_name) { + return true; + } + } + } + } + } + + false +} + +/// Find the start of the `impl` block for the given `ast::Impl`. +// +// FIXME: this partially overlaps with `find_struct_impl` +pub(crate) fn find_impl_block_start(impl_def: ast::Impl, buf: &mut String) -> Option { + buf.push('\n'); + let start = impl_def.assoc_item_list().and_then(|it| it.l_curly_token())?.text_range().end(); + Some(start) +} + +/// Find the end of the `impl` block for the given `ast::Impl`. +// +// FIXME: this partially overlaps with `find_struct_impl` +pub(crate) fn find_impl_block_end(impl_def: ast::Impl, buf: &mut String) -> Option { + buf.push('\n'); + let end = impl_def + .assoc_item_list() + .and_then(|it| it.r_curly_token())? + .prev_sibling_or_token()? + .text_range() + .end(); + Some(end) +} + +// Generates the surrounding `impl Type { }` including type and lifetime +// parameters +pub(crate) fn generate_impl_text(adt: &ast::Adt, code: &str) -> String { + generate_impl_text_inner(adt, None, code) +} + +// Generates the surrounding `impl for Type { }` including type +// and lifetime parameters +pub(crate) fn generate_trait_impl_text(adt: &ast::Adt, trait_text: &str, code: &str) -> String { + generate_impl_text_inner(adt, Some(trait_text), code) +} + +fn generate_impl_text_inner(adt: &ast::Adt, trait_text: Option<&str>, code: &str) -> String { + let generic_params = adt.generic_param_list(); + let mut buf = String::with_capacity(code.len()); + buf.push_str("\n\n"); + adt.attrs() + .filter(|attr| attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false)) + .for_each(|attr| buf.push_str(format!("{}\n", attr.to_string()).as_str())); + buf.push_str("impl"); + if let Some(generic_params) = &generic_params { + let lifetimes = generic_params.lifetime_params().map(|lt| format!("{}", lt.syntax())); + let type_params = generic_params.type_params().map(|type_param| { + let mut buf = String::new(); + if let Some(it) = type_param.name() { + format_to!(buf, "{}", it.syntax()); + } + if let Some(it) = type_param.colon_token() { + format_to!(buf, "{} ", it); + } + if let Some(it) = type_param.type_bound_list() { + format_to!(buf, "{}", it.syntax()); + } + buf + }); + let generics = lifetimes.chain(type_params).format(", "); + format_to!(buf, "<{}>", generics); + } + buf.push(' '); + if let Some(trait_text) = trait_text { + buf.push_str(trait_text); + buf.push_str(" for "); + } + buf.push_str(adt.name().unwrap().text()); + if let Some(generic_params) = generic_params { + let lifetime_params = generic_params + .lifetime_params() + .filter_map(|it| it.lifetime()) + .map(|it| SmolStr::from(it.text())); + let type_params = generic_params + .type_params() + .filter_map(|it| it.name()) + .map(|it| SmolStr::from(it.text())); + format_to!(buf, "<{}>", lifetime_params.chain(type_params).format(", ")) + } + + match adt.where_clause() { + Some(where_clause) => { + format_to!(buf, "\n{}\n{{\n{}\n}}", where_clause, code); + } + None => { + format_to!(buf, " {{\n{}\n}}", code); + } + } + + buf +} -- cgit v1.2.3