]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/lib.rs
Merge #7677
[rust.git] / crates / ide_assists / src / lib.rs
1 //! `assists` crate provides a bunch of code assists, also known as code
2 //! actions (in LSP) or intentions (in IntelliJ).
3 //!
4 //! An assist is a micro-refactoring, which is automatically activated in
5 //! certain context. For example, if the cursor is over `,`, a "swap `,`" assist
6 //! becomes available.
7
8 #[allow(unused)]
9 macro_rules! eprintln {
10     ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
11 }
12
13 mod assist_config;
14 mod assist_context;
15 #[cfg(test)]
16 mod tests;
17 pub mod utils;
18 pub mod ast_transform;
19
20 use hir::Semantics;
21 use ide_db::base_db::FileRange;
22 use ide_db::{label::Label, source_change::SourceChange, RootDatabase};
23 use syntax::TextRange;
24
25 pub(crate) use crate::assist_context::{AssistContext, Assists};
26
27 pub use assist_config::AssistConfig;
28
29 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
30 pub enum AssistKind {
31     None,
32     QuickFix,
33     Generate,
34     Refactor,
35     RefactorExtract,
36     RefactorInline,
37     RefactorRewrite,
38 }
39
40 impl AssistKind {
41     pub fn contains(self, other: AssistKind) -> bool {
42         if self == other {
43             return true;
44         }
45
46         match self {
47             AssistKind::None | AssistKind::Generate => return true,
48             AssistKind::Refactor => match other {
49                 AssistKind::RefactorExtract
50                 | AssistKind::RefactorInline
51                 | AssistKind::RefactorRewrite => return true,
52                 _ => return false,
53             },
54             _ => return false,
55         }
56     }
57 }
58
59 /// Unique identifier of the assist, should not be shown to the user
60 /// directly.
61 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
62 pub struct AssistId(pub &'static str, pub AssistKind);
63
64 #[derive(Clone, Debug)]
65 pub struct GroupLabel(pub String);
66
67 #[derive(Debug, Clone)]
68 pub struct Assist {
69     pub id: AssistId,
70     /// Short description of the assist, as shown in the UI.
71     pub label: Label,
72     pub group: Option<GroupLabel>,
73     /// Target ranges are used to sort assists: the smaller the target range,
74     /// the more specific assist is, and so it should be sorted first.
75     pub target: TextRange,
76     /// Computing source change sometimes is much more costly then computing the
77     /// other fields. Additionally, the actual change is not required to show
78     /// the lightbulb UI, it only is needed when the user tries to apply an
79     /// assist. So, we compute it lazily: the API allow requesting assists with
80     /// or without source change. We could (and in fact, used to) distinguish
81     /// between resolved and unresolved assists at the type level, but this is
82     /// cumbersome, especially if you want to embed an assist into another data
83     /// structure, such as a diagnostic.
84     pub source_change: Option<SourceChange>,
85 }
86
87 impl Assist {
88     /// Return all the assists applicable at the given position.
89     pub fn get(
90         db: &RootDatabase,
91         config: &AssistConfig,
92         resolve: bool,
93         range: FileRange,
94     ) -> Vec<Assist> {
95         let sema = Semantics::new(db);
96         let ctx = AssistContext::new(sema, config, range);
97         let mut acc = Assists::new(&ctx, resolve);
98         handlers::all().iter().for_each(|handler| {
99             handler(&mut acc, &ctx);
100         });
101         acc.finish()
102     }
103 }
104
105 mod handlers {
106     use crate::{AssistContext, Assists};
107
108     pub(crate) type Handler = fn(&mut Assists, &AssistContext) -> Option<()>;
109
110     mod add_explicit_type;
111     mod add_lifetime_to_type;
112     mod add_missing_impl_members;
113     mod add_turbo_fish;
114     mod apply_demorgan;
115     mod auto_import;
116     mod change_visibility;
117     mod convert_for_to_iter_for_each;
118     mod convert_integer_literal;
119     mod early_return;
120     mod expand_glob_import;
121     mod extract_function;
122     mod extract_struct_from_enum_variant;
123     mod extract_variable;
124     mod fill_match_arms;
125     mod fix_visibility;
126     mod flip_binexpr;
127     mod flip_comma;
128     mod flip_trait_bound;
129     mod generate_default_from_enum_variant;
130     mod generate_derive;
131     mod generate_enum_is_method;
132     mod generate_enum_projection_method;
133     mod generate_from_impl_for_enum;
134     mod generate_function;
135     mod generate_getter;
136     mod generate_getter_mut;
137     mod generate_impl;
138     mod generate_new;
139     mod generate_setter;
140     mod infer_function_return_type;
141     mod inline_function;
142     mod inline_local_variable;
143     mod introduce_named_lifetime;
144     mod invert_if;
145     mod merge_imports;
146     mod merge_match_arms;
147     mod move_bounds;
148     mod move_guard;
149     mod move_module_to_file;
150     mod pull_assignment_up;
151     mod qualify_path;
152     mod raw_string;
153     mod remove_dbg;
154     mod remove_mut;
155     mod remove_unused_param;
156     mod reorder_fields;
157     mod reorder_impl;
158     mod replace_derive_with_manual_impl;
159     mod replace_if_let_with_match;
160     mod replace_impl_trait_with_generic;
161     mod replace_let_with_if_let;
162     mod replace_qualified_name_with_use;
163     mod replace_string_with_char;
164     mod replace_unwrap_with_match;
165     mod split_import;
166     mod toggle_ignore;
167     mod unmerge_use;
168     mod unwrap_block;
169     mod wrap_return_type_in_result;
170
171     pub(crate) fn all() -> &'static [Handler] {
172         &[
173             // These are alphabetic for the foolish consistency
174             add_explicit_type::add_explicit_type,
175             add_lifetime_to_type::add_lifetime_to_type,
176             add_turbo_fish::add_turbo_fish,
177             apply_demorgan::apply_demorgan,
178             auto_import::auto_import,
179             change_visibility::change_visibility,
180             convert_for_to_iter_for_each::convert_for_to_iter_for_each,
181             convert_integer_literal::convert_integer_literal,
182             early_return::convert_to_guarded_return,
183             expand_glob_import::expand_glob_import,
184             move_module_to_file::move_module_to_file,
185             extract_struct_from_enum_variant::extract_struct_from_enum_variant,
186             fill_match_arms::fill_match_arms,
187             fix_visibility::fix_visibility,
188             flip_binexpr::flip_binexpr,
189             flip_comma::flip_comma,
190             flip_trait_bound::flip_trait_bound,
191             generate_default_from_enum_variant::generate_default_from_enum_variant,
192             generate_derive::generate_derive,
193             generate_enum_is_method::generate_enum_is_method,
194             generate_enum_projection_method::generate_enum_try_into_method,
195             generate_enum_projection_method::generate_enum_as_method,
196             generate_from_impl_for_enum::generate_from_impl_for_enum,
197             generate_function::generate_function,
198             generate_getter::generate_getter,
199             generate_getter_mut::generate_getter_mut,
200             generate_impl::generate_impl,
201             generate_new::generate_new,
202             generate_setter::generate_setter,
203             infer_function_return_type::infer_function_return_type,
204             inline_function::inline_function,
205             inline_local_variable::inline_local_variable,
206             introduce_named_lifetime::introduce_named_lifetime,
207             invert_if::invert_if,
208             merge_imports::merge_imports,
209             merge_match_arms::merge_match_arms,
210             move_bounds::move_bounds_to_where_clause,
211             move_guard::move_arm_cond_to_match_guard,
212             move_guard::move_guard_to_arm_body,
213             pull_assignment_up::pull_assignment_up,
214             qualify_path::qualify_path,
215             raw_string::add_hash,
216             raw_string::make_usual_string,
217             raw_string::remove_hash,
218             remove_dbg::remove_dbg,
219             remove_mut::remove_mut,
220             remove_unused_param::remove_unused_param,
221             reorder_fields::reorder_fields,
222             reorder_impl::reorder_impl,
223             replace_derive_with_manual_impl::replace_derive_with_manual_impl,
224             replace_if_let_with_match::replace_if_let_with_match,
225             replace_if_let_with_match::replace_match_with_if_let,
226             replace_impl_trait_with_generic::replace_impl_trait_with_generic,
227             replace_let_with_if_let::replace_let_with_if_let,
228             replace_qualified_name_with_use::replace_qualified_name_with_use,
229             replace_unwrap_with_match::replace_unwrap_with_match,
230             split_import::split_import,
231             toggle_ignore::toggle_ignore,
232             unmerge_use::unmerge_use,
233             unwrap_block::unwrap_block,
234             wrap_return_type_in_result::wrap_return_type_in_result,
235             // These are manually sorted for better priorities. By default,
236             // priority is determined by the size of the target range (smaller
237             // target wins). If the ranges are equal, position in this list is
238             // used as a tie-breaker.
239             add_missing_impl_members::add_missing_impl_members,
240             add_missing_impl_members::add_missing_default_members,
241             //
242             replace_string_with_char::replace_string_with_char,
243             raw_string::make_raw_string,
244             //
245             extract_variable::extract_variable,
246             extract_function::extract_function,
247             // Are you sure you want to add new assist here, and not to the
248             // sorted list above?
249         ]
250     }
251 }