ide_assists/
lib.rs

1//! `assists` crate provides a bunch of code assists, also known as code actions
2//! (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//! ## Assists Guidelines
9//!
10//! Assists are the main mechanism to deliver advanced IDE features to the user,
11//! so we should pay extra attention to the UX.
12//!
13//! The power of assists comes from their context-awareness. The main problem
14//! with IDE features is that there are a lot of them, and it's hard to teach
15//! the user what's available. Assists solve this problem nicely: 💡 signifies
16//! that *something* is possible, and clicking on it reveals a *short* list of
17//! actions. Contrast it with Emacs `M-x`, which just spits an infinite list of
18//! all the features.
19//!
20//! Here are some considerations when creating a new assist:
21//!
22//! * It's good to preserve semantics, and it's good to keep the code compiling,
23//!   but it isn't necessary. Example: "flip binary operation" might change
24//!   semantics.
25//! * Assist shouldn't necessary make the code "better". A lot of assist come in
26//!   pairs: "if let <-> match".
27//! * Assists should have as narrow scope as possible. Each new assists greatly
28//!   improves UX for cases where the user actually invokes it, but it makes UX
29//!   worse for every case where the user clicks 💡 to invoke some *other*
30//!   assist. So, a rarely useful assist which is always applicable can be a net
31//!   negative.
32//! * Rarely useful actions are tricky. Sometimes there are features which are
33//!   clearly useful to some users, but are just noise most of the time. We
34//!   don't have a good solution here, our current approach is to make this
35//!   functionality available only if assist is applicable to the whole
36//!   selection. Example: `sort_items` sorts items alphabetically. Naively, it
37//!   should be available more or less everywhere, which isn't useful. So
38//!   instead we only show it if the user *selects* the items they want to sort.
39//! * Consider grouping related assists together (see [`Assists::add_group`]).
40//! * Make assists robust. If the assist depends on results of type-inference too
41//!   much, it might only fire in fully-correct code. This makes assist less
42//!   useful and (worse) less predictable. The user should have a clear
43//!   intuition when each particular assist is available.
44//! * Make small assists, which compose. Example: rather than auto-importing
45//!   enums in `add_missing_match_arms`, we use fully-qualified names. There's a
46//!   separate assist to shorten a fully-qualified name.
47//! * Distinguish between assists and fixits for diagnostics. Internally, fixits
48//!   and assists are equivalent. They have the same "show a list + invoke a
49//!   single element" workflow, and both use [`Assist`] data structure. The main
50//!   difference is in the UX: while 💡 looks only at the cursor position,
51//!   diagnostics squigglies and fixits are calculated for the whole file and
52//!   are presented to the user eagerly. So, diagnostics should be fixable
53//!   errors, while assists can be just suggestions for an alternative way to do
54//!   something. If something *could* be a diagnostic, it should be a
55//!   diagnostic. Conversely, it might be valuable to turn a diagnostic with a
56//!   lot of false errors into an assist.
57//!
58//! See also this post:
59//! <https://rust-analyzer.github.io/blog/2020/09/28/how-to-make-a-light-bulb.html>
60
61#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
62// It's useful to refer to code that is private in doc comments.
63#![allow(rustdoc::private_intra_doc_links)]
64
65mod assist_config;
66mod assist_context;
67#[cfg(test)]
68mod tests;
69pub mod utils;
70
71use hir::Semantics;
72use ide_db::RootDatabase;
73use syntax::TextRange;
74
75pub(crate) use crate::assist_context::{AssistContext, Assists};
76
77pub use assist_config::AssistConfig;
78pub use ide_db::assists::{
79    Assist, AssistId, AssistKind, AssistResolveStrategy, GroupLabel, SingleResolve,
80};
81
82/// Return all the assists applicable at the given position.
83///
84// NOTE: We don't have a `Feature: ` section for assists, they are special-cased
85// in the manual.
86pub fn assists(
87    db: &RootDatabase,
88    config: &AssistConfig,
89    resolve: AssistResolveStrategy,
90    range: ide_db::FileRange,
91) -> Vec<Assist> {
92    let sema = Semantics::new(db);
93    let file_id = sema.attach_first_edition(range.file_id);
94    let ctx = AssistContext::new(sema, config, hir::FileRange { file_id, range: range.range });
95    let mut acc = Assists::new(&ctx, resolve);
96    handlers::all().iter().for_each(|handler| {
97        handler(&mut acc, &ctx);
98    });
99    acc.finish()
100}
101
102mod handlers {
103    use crate::{AssistContext, Assists};
104
105    pub(crate) type Handler = fn(&mut Assists, &AssistContext<'_>) -> Option<()>;
106
107    mod add_braces;
108    mod add_explicit_enum_discriminant;
109    mod add_explicit_type;
110    mod add_label_to_loop;
111    mod add_lifetime_to_type;
112    mod add_missing_impl_members;
113    mod add_missing_match_arms;
114    mod add_return_type;
115    mod add_turbo_fish;
116    mod apply_demorgan;
117    mod auto_import;
118    mod bind_unused_param;
119    mod change_visibility;
120    mod convert_bool_then;
121    mod convert_bool_to_enum;
122    mod convert_char_literal;
123    mod convert_closure_to_fn;
124    mod convert_comment_block;
125    mod convert_comment_from_or_to_doc;
126    mod convert_for_to_while_let;
127    mod convert_from_to_tryfrom;
128    mod convert_integer_literal;
129    mod convert_into_to_from;
130    mod convert_iter_for_each_to_for;
131    mod convert_let_else_to_match;
132    mod convert_match_to_let_else;
133    mod convert_named_struct_to_tuple_struct;
134    mod convert_nested_function_to_closure;
135    mod convert_range_for_to_while;
136    mod convert_to_guarded_return;
137    mod convert_tuple_return_type_to_struct;
138    mod convert_tuple_struct_to_named_struct;
139    mod convert_two_arm_bool_match_to_matches_macro;
140    mod convert_while_to_loop;
141    mod destructure_struct_binding;
142    mod destructure_tuple_binding;
143    mod desugar_doc_comment;
144    mod desugar_try_expr;
145    mod expand_glob_import;
146    mod expand_rest_pattern;
147    mod extract_expressions_from_format_string;
148    mod extract_function;
149    mod extract_module;
150    mod extract_struct_from_enum_variant;
151    mod extract_type_alias;
152    mod extract_variable;
153    mod fix_visibility;
154    mod flip_binexpr;
155    mod flip_comma;
156    mod flip_or_pattern;
157    mod flip_trait_bound;
158    mod generate_blanket_trait_impl;
159    mod generate_constant;
160    mod generate_default_from_enum_variant;
161    mod generate_default_from_new;
162    mod generate_delegate_methods;
163    mod generate_delegate_trait;
164    mod generate_deref;
165    mod generate_derive;
166    mod generate_documentation_template;
167    mod generate_enum_is_method;
168    mod generate_enum_projection_method;
169    mod generate_enum_variant;
170    mod generate_fn_type_alias;
171    mod generate_from_impl_for_enum;
172    mod generate_function;
173    mod generate_getter_or_setter;
174    mod generate_impl;
175    mod generate_is_empty_from_len;
176    mod generate_mut_trait_impl;
177    mod generate_new;
178    mod generate_single_field_struct_from;
179    mod generate_trait_from_impl;
180    mod inline_call;
181    mod inline_const_as_literal;
182    mod inline_local_variable;
183    mod inline_macro;
184    mod inline_type_alias;
185    mod into_to_qualified_from;
186    mod introduce_named_lifetime;
187    mod introduce_named_type_parameter;
188    mod invert_if;
189    mod merge_imports;
190    mod merge_match_arms;
191    mod merge_nested_if;
192    mod move_bounds;
193    mod move_const_to_impl;
194    mod move_from_mod_rs;
195    mod move_guard;
196    mod move_module_to_file;
197    mod move_to_mod_rs;
198    mod normalize_import;
199    mod number_representation;
200    mod promote_local_to_const;
201    mod pull_assignment_up;
202    mod qualify_method_call;
203    mod qualify_path;
204    mod raw_string;
205    mod remove_dbg;
206    mod remove_else_branches;
207    mod remove_mut;
208    mod remove_parentheses;
209    mod remove_underscore;
210    mod remove_unused_imports;
211    mod remove_unused_param;
212    mod reorder_fields;
213    mod reorder_impl_items;
214    mod replace_arith_op;
215    mod replace_derive_with_manual_impl;
216    mod replace_if_let_with_match;
217    mod replace_is_method_with_if_let_method;
218    mod replace_let_with_if_let;
219    mod replace_method_eager_lazy;
220    mod replace_named_generic_with_impl;
221    mod replace_qualified_name_with_use;
222    mod replace_string_with_char;
223    mod replace_turbofish_with_explicit_type;
224    mod sort_items;
225    mod split_import;
226    mod term_search;
227    mod toggle_async_sugar;
228    mod toggle_ignore;
229    mod toggle_macro_delimiter;
230    mod unmerge_imports;
231    mod unmerge_match_arm;
232    mod unnecessary_async;
233    mod unqualify_method_call;
234    mod unwrap_block;
235    mod unwrap_return_type;
236    mod unwrap_tuple;
237    mod unwrap_type_to_generic_arg;
238    mod wrap_return_type;
239    mod wrap_unwrap_cfg_attr;
240
241    pub(crate) fn all() -> &'static [Handler] {
242        &[
243            // These are alphabetic for the foolish consistency
244            add_braces::add_braces,
245            add_explicit_enum_discriminant::add_explicit_enum_discriminant,
246            add_explicit_type::add_explicit_type,
247            add_label_to_loop::add_label_to_loop,
248            add_lifetime_to_type::add_lifetime_to_type,
249            add_missing_match_arms::add_missing_match_arms,
250            add_turbo_fish::add_turbo_fish,
251            apply_demorgan::apply_demorgan_iterator,
252            apply_demorgan::apply_demorgan,
253            auto_import::auto_import,
254            bind_unused_param::bind_unused_param,
255            change_visibility::change_visibility,
256            convert_bool_then::convert_bool_then_to_if,
257            convert_bool_then::convert_if_to_bool_then,
258            convert_bool_to_enum::convert_bool_to_enum,
259            convert_char_literal::convert_char_literal,
260            convert_closure_to_fn::convert_closure_to_fn,
261            convert_comment_block::convert_comment_block,
262            convert_comment_from_or_to_doc::convert_comment_from_or_to_doc,
263            convert_for_to_while_let::convert_for_loop_to_while_let,
264            convert_from_to_tryfrom::convert_from_to_tryfrom,
265            convert_integer_literal::convert_integer_literal,
266            convert_into_to_from::convert_into_to_from,
267            convert_iter_for_each_to_for::convert_for_loop_with_for_each,
268            convert_iter_for_each_to_for::convert_iter_for_each_to_for,
269            convert_let_else_to_match::convert_let_else_to_match,
270            convert_match_to_let_else::convert_match_to_let_else,
271            convert_named_struct_to_tuple_struct::convert_named_struct_to_tuple_struct,
272            convert_nested_function_to_closure::convert_nested_function_to_closure,
273            convert_range_for_to_while::convert_range_for_to_while,
274            convert_to_guarded_return::convert_to_guarded_return,
275            convert_tuple_return_type_to_struct::convert_tuple_return_type_to_struct,
276            convert_tuple_struct_to_named_struct::convert_tuple_struct_to_named_struct,
277            convert_two_arm_bool_match_to_matches_macro::convert_two_arm_bool_match_to_matches_macro,
278            convert_while_to_loop::convert_while_to_loop,
279            destructure_struct_binding::destructure_struct_binding,
280            destructure_tuple_binding::destructure_tuple_binding,
281            desugar_doc_comment::desugar_doc_comment,
282            desugar_try_expr::desugar_try_expr,
283            expand_glob_import::expand_glob_import,
284            expand_glob_import::expand_glob_reexport,
285            expand_rest_pattern::expand_rest_pattern,
286            extract_expressions_from_format_string::extract_expressions_from_format_string,
287            extract_struct_from_enum_variant::extract_struct_from_enum_variant,
288            extract_type_alias::extract_type_alias,
289            fix_visibility::fix_visibility,
290            flip_binexpr::flip_binexpr,
291            flip_binexpr::flip_range_expr,
292            flip_comma::flip_comma,
293            flip_or_pattern::flip_or_pattern,
294            flip_trait_bound::flip_trait_bound,
295            generate_constant::generate_constant,
296            generate_default_from_enum_variant::generate_default_from_enum_variant,
297            generate_default_from_new::generate_default_from_new,
298            generate_delegate_trait::generate_delegate_trait,
299            generate_derive::generate_derive,
300            generate_documentation_template::generate_doc_example,
301            generate_documentation_template::generate_documentation_template,
302            generate_enum_is_method::generate_enum_is_method,
303            generate_enum_projection_method::generate_enum_as_method,
304            generate_enum_projection_method::generate_enum_try_into_method,
305            generate_enum_variant::generate_enum_variant,
306            generate_fn_type_alias::generate_fn_type_alias,
307            generate_from_impl_for_enum::generate_from_impl_for_enum,
308            generate_function::generate_function,
309            generate_impl::generate_impl,
310            generate_impl::generate_trait_impl,
311            generate_impl::generate_impl_trait,
312            generate_is_empty_from_len::generate_is_empty_from_len,
313            generate_mut_trait_impl::generate_mut_trait_impl,
314            generate_new::generate_new,
315            generate_trait_from_impl::generate_trait_from_impl,
316            generate_single_field_struct_from::generate_single_field_struct_from,
317            generate_blanket_trait_impl::generate_blanket_trait_impl,
318            inline_call::inline_call,
319            inline_call::inline_into_callers,
320            inline_const_as_literal::inline_const_as_literal,
321            inline_local_variable::inline_local_variable,
322            inline_macro::inline_macro,
323            inline_type_alias::inline_type_alias_uses,
324            inline_type_alias::inline_type_alias,
325            into_to_qualified_from::into_to_qualified_from,
326            introduce_named_lifetime::introduce_named_lifetime,
327            introduce_named_type_parameter::introduce_named_type_parameter,
328            invert_if::invert_if,
329            merge_imports::merge_imports,
330            merge_match_arms::merge_match_arms,
331            merge_nested_if::merge_nested_if,
332            move_bounds::move_bounds_to_where_clause,
333            move_const_to_impl::move_const_to_impl,
334            move_from_mod_rs::move_from_mod_rs,
335            move_guard::move_arm_cond_to_match_guard,
336            move_guard::move_guard_to_arm_body,
337            move_module_to_file::move_module_to_file,
338            move_to_mod_rs::move_to_mod_rs,
339            normalize_import::normalize_import,
340            number_representation::reformat_number_literal,
341            promote_local_to_const::promote_local_to_const,
342            pull_assignment_up::pull_assignment_up,
343            qualify_method_call::qualify_method_call,
344            qualify_path::qualify_path,
345            raw_string::add_hash,
346            raw_string::make_usual_string,
347            raw_string::remove_hash,
348            remove_dbg::remove_dbg,
349            remove_mut::remove_mut,
350            remove_else_branches::remove_else_branches,
351            remove_parentheses::remove_parentheses,
352            remove_underscore::remove_underscore,
353            remove_unused_imports::remove_unused_imports,
354            remove_unused_param::remove_unused_param,
355            reorder_fields::reorder_fields,
356            reorder_impl_items::reorder_impl_items,
357            replace_arith_op::replace_arith_with_checked,
358            replace_arith_op::replace_arith_with_saturating,
359            replace_arith_op::replace_arith_with_wrapping,
360            replace_derive_with_manual_impl::replace_derive_with_manual_impl,
361            replace_if_let_with_match::replace_if_let_with_match,
362            replace_if_let_with_match::replace_match_with_if_let,
363            replace_is_method_with_if_let_method::replace_is_method_with_if_let_method,
364            replace_let_with_if_let::replace_let_with_if_let,
365            replace_method_eager_lazy::replace_with_eager_method,
366            replace_method_eager_lazy::replace_with_lazy_method,
367            replace_named_generic_with_impl::replace_named_generic_with_impl,
368            replace_qualified_name_with_use::replace_qualified_name_with_use,
369            replace_turbofish_with_explicit_type::replace_turbofish_with_explicit_type,
370            sort_items::sort_items,
371            split_import::split_import,
372            term_search::term_search,
373            toggle_async_sugar::desugar_async_into_impl_future,
374            toggle_async_sugar::sugar_impl_future_into_async,
375            toggle_ignore::toggle_ignore,
376            toggle_macro_delimiter::toggle_macro_delimiter,
377            unmerge_match_arm::unmerge_match_arm,
378            unmerge_imports::unmerge_imports,
379            unnecessary_async::unnecessary_async,
380            unqualify_method_call::unqualify_method_call,
381            unwrap_block::unwrap_block,
382            unwrap_return_type::unwrap_return_type,
383            unwrap_tuple::unwrap_tuple,
384            unwrap_type_to_generic_arg::unwrap_type_to_generic_arg,
385            wrap_return_type::wrap_return_type,
386            wrap_unwrap_cfg_attr::wrap_unwrap_cfg_attr,
387
388            // These are manually sorted for better priorities. By default,
389            // priority is determined by the size of the target range (smaller
390            // target wins). If the ranges are equal, position in this list is
391            // used as a tie-breaker.
392            add_missing_impl_members::add_missing_impl_members,
393            add_missing_impl_members::add_missing_default_members,
394            add_return_type::add_return_type,
395            //
396            replace_string_with_char::replace_string_with_char,
397            replace_string_with_char::replace_char_with_string,
398            raw_string::make_raw_string,
399            //
400            extract_variable::extract_variable,
401            extract_function::extract_function,
402            extract_module::extract_module,
403            //
404            generate_getter_or_setter::generate_getter,
405            generate_getter_or_setter::generate_getter_mut,
406            generate_getter_or_setter::generate_setter,
407            generate_delegate_methods::generate_delegate_methods,
408            generate_deref::generate_deref,
409            // Are you sure you want to add new assist here, and not to the
410            // sorted list above?
411        ]
412    }
413}