Skip to main content

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_dot_deref;
109    mod add_explicit_enum_discriminant;
110    mod add_explicit_type;
111    mod add_label_to_loop;
112    mod add_lifetime_to_type;
113    mod add_missing_impl_members;
114    mod add_missing_match_arms;
115    mod add_return_type;
116    mod add_turbo_fish;
117    mod apply_demorgan;
118    mod auto_import;
119    mod bind_unused_param;
120    mod change_visibility;
121    mod convert_bool_then;
122    mod convert_bool_to_enum;
123    mod convert_char_literal;
124    mod convert_closure_to_fn;
125    mod convert_comment_block;
126    mod convert_comment_from_or_to_doc;
127    mod convert_for_to_while_let;
128    mod convert_from_to_tryfrom;
129    mod convert_integer_literal;
130    mod convert_into_to_from;
131    mod convert_iter_for_each_to_for;
132    mod convert_let_else_to_match;
133    mod convert_match_to_let_else;
134    mod convert_named_struct_to_tuple_struct;
135    mod convert_nested_function_to_closure;
136    mod convert_range_for_to_while;
137    mod convert_to_guarded_return;
138    mod convert_tuple_return_type_to_struct;
139    mod convert_tuple_struct_to_named_struct;
140    mod convert_two_arm_bool_match_to_matches_macro;
141    mod convert_while_to_loop;
142    mod destructure_struct_binding;
143    mod destructure_tuple_binding;
144    mod desugar_doc_comment;
145    mod desugar_try_expr;
146    mod expand_glob_import;
147    mod expand_rest_pattern;
148    mod extract_expressions_from_format_string;
149    mod extract_function;
150    mod extract_module;
151    mod extract_struct_from_enum_variant;
152    mod extract_type_alias;
153    mod extract_variable;
154    mod fix_visibility;
155    mod flip_binexpr;
156    mod flip_comma;
157    mod flip_or_pattern;
158    mod flip_trait_bound;
159    mod generate_blanket_trait_impl;
160    mod generate_constant;
161    mod generate_default_from_enum_variant;
162    mod generate_default_from_new;
163    mod generate_delegate_methods;
164    mod generate_delegate_trait;
165    mod generate_deref;
166    mod generate_derive;
167    mod generate_documentation_template;
168    mod generate_enum_is_method;
169    mod generate_enum_projection_method;
170    mod generate_enum_variant;
171    mod generate_fn_type_alias;
172    mod generate_from_impl_for_enum;
173    mod generate_function;
174    mod generate_getter_or_setter;
175    mod generate_impl;
176    mod generate_is_empty_from_len;
177    mod generate_mut_trait_impl;
178    mod generate_new;
179    mod generate_single_field_struct_from;
180    mod generate_trait_from_impl;
181    mod inline_call;
182    mod inline_const_as_literal;
183    mod inline_local_variable;
184    mod inline_macro;
185    mod inline_type_alias;
186    mod into_to_qualified_from;
187    mod introduce_named_lifetime;
188    mod introduce_named_type_parameter;
189    mod invert_if;
190    mod merge_imports;
191    mod merge_match_arms;
192    mod merge_nested_if;
193    mod move_bounds;
194    mod move_const_to_impl;
195    mod move_from_mod_rs;
196    mod move_guard;
197    mod move_module_to_file;
198    mod move_to_mod_rs;
199    mod normalize_import;
200    mod number_representation;
201    mod promote_local_to_const;
202    mod pull_assignment_up;
203    mod qualify_method_call;
204    mod qualify_path;
205    mod raw_string;
206    mod remove_dbg;
207    mod remove_else_branches;
208    mod remove_mut;
209    mod remove_parentheses;
210    mod remove_underscore;
211    mod remove_unused_imports;
212    mod remove_unused_param;
213    mod reorder_fields;
214    mod reorder_impl_items;
215    mod replace_arith_op;
216    mod replace_derive_with_manual_impl;
217    mod replace_if_let_with_match;
218    mod replace_is_method_with_if_let_method;
219    mod replace_let_with_if_let;
220    mod replace_method_eager_lazy;
221    mod replace_named_generic_with_impl;
222    mod replace_qualified_name_with_use;
223    mod replace_string_with_char;
224    mod replace_turbofish_with_explicit_type;
225    mod sort_items;
226    mod split_import;
227    mod term_search;
228    mod toggle_async_sugar;
229    mod toggle_ignore;
230    mod toggle_macro_delimiter;
231    mod unmerge_imports;
232    mod unmerge_match_arm;
233    mod unnecessary_async;
234    mod unqualify_method_call;
235    mod unwrap_branch;
236    mod unwrap_return_type;
237    mod unwrap_tuple;
238    mod unwrap_type_to_generic_arg;
239    mod wrap_return_type;
240    mod wrap_unwrap_cfg_attr;
241
242    pub(crate) fn all() -> &'static [Handler] {
243        &[
244            // These are alphabetic for the foolish consistency
245            add_braces::add_braces,
246            add_explicit_dot_deref::add_explicit_method_call_deref,
247            add_explicit_enum_discriminant::add_explicit_enum_discriminant,
248            add_explicit_type::add_explicit_type,
249            add_label_to_loop::add_label_to_loop,
250            add_lifetime_to_type::add_lifetime_to_type,
251            add_missing_match_arms::add_missing_match_arms,
252            add_turbo_fish::add_turbo_fish,
253            apply_demorgan::apply_demorgan_iterator,
254            apply_demorgan::apply_demorgan,
255            auto_import::auto_import,
256            bind_unused_param::bind_unused_param,
257            change_visibility::change_visibility,
258            convert_bool_then::convert_bool_then_to_if,
259            convert_bool_then::convert_if_to_bool_then,
260            convert_bool_to_enum::convert_bool_to_enum,
261            convert_char_literal::convert_char_literal,
262            convert_closure_to_fn::convert_closure_to_fn,
263            convert_comment_block::convert_comment_block,
264            convert_comment_from_or_to_doc::convert_comment_from_or_to_doc,
265            convert_for_to_while_let::convert_for_loop_to_while_let,
266            convert_from_to_tryfrom::convert_from_to_tryfrom,
267            convert_integer_literal::convert_integer_literal,
268            convert_into_to_from::convert_into_to_from,
269            convert_iter_for_each_to_for::convert_for_loop_with_for_each,
270            convert_iter_for_each_to_for::convert_iter_for_each_to_for,
271            convert_let_else_to_match::convert_let_else_to_match,
272            convert_match_to_let_else::convert_match_to_let_else,
273            convert_named_struct_to_tuple_struct::convert_named_struct_to_tuple_struct,
274            convert_nested_function_to_closure::convert_nested_function_to_closure,
275            convert_range_for_to_while::convert_range_for_to_while,
276            convert_to_guarded_return::convert_to_guarded_return,
277            convert_tuple_return_type_to_struct::convert_tuple_return_type_to_struct,
278            convert_tuple_struct_to_named_struct::convert_tuple_struct_to_named_struct,
279            convert_two_arm_bool_match_to_matches_macro::convert_two_arm_bool_match_to_matches_macro,
280            convert_while_to_loop::convert_while_to_loop,
281            destructure_struct_binding::destructure_struct_binding,
282            destructure_tuple_binding::destructure_tuple_binding,
283            desugar_doc_comment::desugar_doc_comment,
284            desugar_try_expr::desugar_try_expr,
285            expand_glob_import::expand_glob_import,
286            expand_glob_import::expand_glob_reexport,
287            expand_rest_pattern::expand_rest_pattern,
288            extract_expressions_from_format_string::extract_expressions_from_format_string,
289            extract_struct_from_enum_variant::extract_struct_from_enum_variant,
290            extract_type_alias::extract_type_alias,
291            fix_visibility::fix_visibility,
292            flip_binexpr::flip_binexpr,
293            flip_binexpr::flip_range_expr,
294            flip_comma::flip_comma,
295            flip_or_pattern::flip_or_pattern,
296            flip_trait_bound::flip_trait_bound,
297            generate_constant::generate_constant,
298            generate_default_from_enum_variant::generate_default_from_enum_variant,
299            generate_default_from_new::generate_default_from_new,
300            generate_delegate_trait::generate_delegate_trait,
301            generate_derive::generate_derive,
302            generate_documentation_template::generate_doc_example,
303            generate_documentation_template::generate_documentation_template,
304            generate_enum_is_method::generate_enum_is_method,
305            generate_enum_projection_method::generate_enum_as_method,
306            generate_enum_projection_method::generate_enum_try_into_method,
307            generate_enum_variant::generate_enum_variant,
308            generate_fn_type_alias::generate_fn_type_alias,
309            generate_from_impl_for_enum::generate_from_impl_for_enum,
310            generate_function::generate_function,
311            generate_impl::generate_impl,
312            generate_impl::generate_trait_impl,
313            generate_impl::generate_impl_trait,
314            generate_is_empty_from_len::generate_is_empty_from_len,
315            generate_mut_trait_impl::generate_mut_trait_impl,
316            generate_new::generate_new,
317            generate_trait_from_impl::generate_trait_from_impl,
318            generate_single_field_struct_from::generate_single_field_struct_from,
319            generate_blanket_trait_impl::generate_blanket_trait_impl,
320            inline_call::inline_call,
321            inline_call::inline_into_callers,
322            inline_const_as_literal::inline_const_as_literal,
323            inline_local_variable::inline_local_variable,
324            inline_macro::inline_macro,
325            inline_type_alias::inline_type_alias_uses,
326            inline_type_alias::inline_type_alias,
327            into_to_qualified_from::into_to_qualified_from,
328            introduce_named_lifetime::introduce_named_lifetime,
329            introduce_named_type_parameter::introduce_named_type_parameter,
330            invert_if::invert_if,
331            merge_imports::merge_imports,
332            merge_match_arms::merge_match_arms,
333            merge_nested_if::merge_nested_if,
334            move_bounds::move_bounds_to_where_clause,
335            move_const_to_impl::move_const_to_impl,
336            move_from_mod_rs::move_from_mod_rs,
337            move_guard::move_arm_cond_to_match_guard,
338            move_guard::move_guard_to_arm_body,
339            move_module_to_file::move_module_to_file,
340            move_to_mod_rs::move_to_mod_rs,
341            normalize_import::normalize_import,
342            number_representation::reformat_number_literal,
343            promote_local_to_const::promote_local_to_const,
344            pull_assignment_up::pull_assignment_up,
345            qualify_method_call::qualify_method_call,
346            qualify_path::qualify_path,
347            raw_string::add_hash,
348            raw_string::make_usual_string,
349            raw_string::remove_hash,
350            remove_dbg::remove_dbg,
351            remove_mut::remove_mut,
352            remove_else_branches::remove_else_branches,
353            remove_parentheses::remove_parentheses,
354            remove_underscore::remove_underscore,
355            remove_unused_imports::remove_unused_imports,
356            remove_unused_param::remove_unused_param,
357            reorder_fields::reorder_fields,
358            reorder_impl_items::reorder_impl_items,
359            replace_arith_op::replace_arith_with_checked,
360            replace_arith_op::replace_arith_with_saturating,
361            replace_arith_op::replace_arith_with_wrapping,
362            replace_derive_with_manual_impl::replace_derive_with_manual_impl,
363            replace_if_let_with_match::replace_if_let_with_match,
364            replace_if_let_with_match::replace_match_with_if_let,
365            replace_is_method_with_if_let_method::replace_is_method_with_if_let_method,
366            replace_let_with_if_let::replace_let_with_if_let,
367            replace_method_eager_lazy::replace_with_eager_method,
368            replace_method_eager_lazy::replace_with_lazy_method,
369            replace_named_generic_with_impl::replace_named_generic_with_impl,
370            replace_qualified_name_with_use::replace_qualified_name_with_use,
371            replace_turbofish_with_explicit_type::replace_turbofish_with_explicit_type,
372            sort_items::sort_items,
373            split_import::split_import,
374            term_search::term_search,
375            toggle_async_sugar::desugar_async_into_impl_future,
376            toggle_async_sugar::sugar_impl_future_into_async,
377            toggle_ignore::toggle_ignore,
378            toggle_macro_delimiter::toggle_macro_delimiter,
379            unmerge_match_arm::unmerge_match_arm,
380            unmerge_imports::unmerge_imports,
381            unnecessary_async::unnecessary_async,
382            unqualify_method_call::unqualify_method_call,
383            unwrap_branch::unwrap_block,
384            unwrap_branch::unwrap_branch,
385            unwrap_return_type::unwrap_return_type,
386            unwrap_tuple::unwrap_tuple,
387            unwrap_type_to_generic_arg::unwrap_type_to_generic_arg,
388            wrap_return_type::wrap_return_type,
389            wrap_unwrap_cfg_attr::wrap_unwrap_cfg_attr,
390
391            // These are manually sorted for better priorities. By default,
392            // priority is determined by the size of the target range (smaller
393            // target wins). If the ranges are equal, position in this list is
394            // used as a tie-breaker.
395            add_missing_impl_members::add_missing_impl_members,
396            add_missing_impl_members::add_missing_default_members,
397            add_return_type::add_return_type,
398            //
399            replace_string_with_char::replace_string_with_char,
400            replace_string_with_char::replace_char_with_string,
401            raw_string::make_raw_string,
402            //
403            extract_variable::extract_variable,
404            extract_function::extract_function,
405            extract_module::extract_module,
406            //
407            generate_getter_or_setter::generate_getter,
408            generate_getter_or_setter::generate_getter_mut,
409            generate_getter_or_setter::generate_setter,
410            generate_delegate_methods::generate_delegate_methods,
411            generate_deref::generate_deref,
412            // Are you sure you want to add new assist here, and not to the
413            // sorted list above?
414        ]
415    }
416}