diff options
Diffstat (limited to 'crates')
74 files changed, 1659 insertions, 864 deletions
diff --git a/crates/assists/src/handlers/auto_import.rs b/crates/assists/src/handlers/auto_import.rs index 4e2a4fcd9..e93901cb3 100644 --- a/crates/assists/src/handlers/auto_import.rs +++ b/crates/assists/src/handlers/auto_import.rs | |||
@@ -3,7 +3,7 @@ use ide_db::helpers::{ | |||
3 | insert_use::{insert_use, ImportScope}, | 3 | insert_use::{insert_use, ImportScope}, |
4 | mod_path_to_ast, | 4 | mod_path_to_ast, |
5 | }; | 5 | }; |
6 | use syntax::ast; | 6 | use syntax::{ast, AstNode, SyntaxNode}; |
7 | 7 | ||
8 | use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; | 8 | use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; |
9 | 9 | ||
@@ -82,25 +82,16 @@ use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; | |||
82 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | 82 | // # pub mod std { pub mod collections { pub struct HashMap { } } } |
83 | // ``` | 83 | // ``` |
84 | pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | 84 | pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { |
85 | let import_assets = | 85 | let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; |
86 | if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() { | 86 | let proposed_imports = |
87 | ImportAssets::for_regular_path(path_under_caret, &ctx.sema) | 87 | import_assets.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind); |
88 | } else if let Some(method_under_caret) = | ||
89 | ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>() | ||
90 | { | ||
91 | ImportAssets::for_method_call(method_under_caret, &ctx.sema) | ||
92 | } else { | ||
93 | None | ||
94 | }?; | ||
95 | let proposed_imports = import_assets.search_for_imports(&ctx.sema, &ctx.config.insert_use); | ||
96 | if proposed_imports.is_empty() { | 88 | if proposed_imports.is_empty() { |
97 | return None; | 89 | return None; |
98 | } | 90 | } |
99 | 91 | ||
100 | let range = ctx.sema.original_range(import_assets.syntax_under_caret()).range; | 92 | let range = ctx.sema.original_range(&syntax_under_caret).range; |
101 | let group = import_group_message(import_assets.import_candidate()); | 93 | let group = import_group_message(import_assets.import_candidate()); |
102 | let scope = | 94 | let scope = ImportScope::find_insert_use_container(&syntax_under_caret, &ctx.sema)?; |
103 | ImportScope::find_insert_use_container(import_assets.syntax_under_caret(), &ctx.sema)?; | ||
104 | for (import, _) in proposed_imports { | 95 | for (import, _) in proposed_imports { |
105 | acc.add_group( | 96 | acc.add_group( |
106 | &group, | 97 | &group, |
@@ -117,14 +108,28 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> | |||
117 | Some(()) | 108 | Some(()) |
118 | } | 109 | } |
119 | 110 | ||
111 | pub(super) fn find_importable_node(ctx: &AssistContext) -> Option<(ImportAssets, SyntaxNode)> { | ||
112 | if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() { | ||
113 | ImportAssets::for_exact_path(&path_under_caret, &ctx.sema) | ||
114 | .zip(Some(path_under_caret.syntax().clone())) | ||
115 | } else if let Some(method_under_caret) = | ||
116 | ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>() | ||
117 | { | ||
118 | ImportAssets::for_method_call(&method_under_caret, &ctx.sema) | ||
119 | .zip(Some(method_under_caret.syntax().clone())) | ||
120 | } else { | ||
121 | None | ||
122 | } | ||
123 | } | ||
124 | |||
120 | fn import_group_message(import_candidate: &ImportCandidate) -> GroupLabel { | 125 | fn import_group_message(import_candidate: &ImportCandidate) -> GroupLabel { |
121 | let name = match import_candidate { | 126 | let name = match import_candidate { |
122 | ImportCandidate::Path(candidate) => format!("Import {}", &candidate.name), | 127 | ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()), |
123 | ImportCandidate::TraitAssocItem(candidate) => { | 128 | ImportCandidate::TraitAssocItem(candidate) => { |
124 | format!("Import a trait for item {}", &candidate.name) | 129 | format!("Import a trait for item {}", candidate.name.text()) |
125 | } | 130 | } |
126 | ImportCandidate::TraitMethod(candidate) => { | 131 | ImportCandidate::TraitMethod(candidate) => { |
127 | format!("Import a trait for method {}", &candidate.name) | 132 | format!("Import a trait for method {}", candidate.name.text()) |
128 | } | 133 | } |
129 | }; | 134 | }; |
130 | GroupLabel(name) | 135 | GroupLabel(name) |
diff --git a/crates/assists/src/handlers/introduce_named_lifetime.rs b/crates/assists/src/handlers/introduce_named_lifetime.rs index 3f5f44d69..02782eb6d 100644 --- a/crates/assists/src/handlers/introduce_named_lifetime.rs +++ b/crates/assists/src/handlers/introduce_named_lifetime.rs | |||
@@ -61,7 +61,7 @@ fn generate_fn_def_assist( | |||
61 | // compute the location which implicitly has the same lifetime as the anonymous lifetime | 61 | // compute the location which implicitly has the same lifetime as the anonymous lifetime |
62 | let loc_needing_lifetime = if let Some(self_param) = self_param { | 62 | let loc_needing_lifetime = if let Some(self_param) = self_param { |
63 | // if we have a self reference, use that | 63 | // if we have a self reference, use that |
64 | Some(self_param.self_token()?.text_range().start()) | 64 | Some(self_param.name()?.syntax().text_range().start()) |
65 | } else { | 65 | } else { |
66 | // otherwise, if there's a single reference parameter without a named liftime, use that | 66 | // otherwise, if there's a single reference parameter without a named liftime, use that |
67 | let fn_params_without_lifetime: Vec<_> = param_list | 67 | let fn_params_without_lifetime: Vec<_> = param_list |
diff --git a/crates/assists/src/handlers/qualify_path.rs b/crates/assists/src/handlers/qualify_path.rs index a7d9fd4dc..af8a11d03 100644 --- a/crates/assists/src/handlers/qualify_path.rs +++ b/crates/assists/src/handlers/qualify_path.rs | |||
@@ -1,10 +1,7 @@ | |||
1 | use std::iter; | 1 | use std::iter; |
2 | 2 | ||
3 | use hir::AsName; | 3 | use hir::AsName; |
4 | use ide_db::helpers::{ | 4 | use ide_db::helpers::{import_assets::ImportCandidate, mod_path_to_ast}; |
5 | import_assets::{ImportAssets, ImportCandidate}, | ||
6 | mod_path_to_ast, | ||
7 | }; | ||
8 | use ide_db::RootDatabase; | 5 | use ide_db::RootDatabase; |
9 | use syntax::{ | 6 | use syntax::{ |
10 | ast, | 7 | ast, |
@@ -18,6 +15,8 @@ use crate::{ | |||
18 | AssistId, AssistKind, GroupLabel, | 15 | AssistId, AssistKind, GroupLabel, |
19 | }; | 16 | }; |
20 | 17 | ||
18 | use super::auto_import::find_importable_node; | ||
19 | |||
21 | // Assist: qualify_path | 20 | // Assist: qualify_path |
22 | // | 21 | // |
23 | // If the name is unresolved, provides all possible qualified paths for it. | 22 | // If the name is unresolved, provides all possible qualified paths for it. |
@@ -36,47 +35,38 @@ use crate::{ | |||
36 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | 35 | // # pub mod std { pub mod collections { pub struct HashMap { } } } |
37 | // ``` | 36 | // ``` |
38 | pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | 37 | pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { |
39 | let import_assets = | 38 | let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; |
40 | if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() { | ||
41 | ImportAssets::for_regular_path(path_under_caret, &ctx.sema) | ||
42 | } else if let Some(method_under_caret) = | ||
43 | ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>() | ||
44 | { | ||
45 | ImportAssets::for_method_call(method_under_caret, &ctx.sema) | ||
46 | } else { | ||
47 | None | ||
48 | }?; | ||
49 | let proposed_imports = import_assets.search_for_relative_paths(&ctx.sema); | 39 | let proposed_imports = import_assets.search_for_relative_paths(&ctx.sema); |
50 | if proposed_imports.is_empty() { | 40 | if proposed_imports.is_empty() { |
51 | return None; | 41 | return None; |
52 | } | 42 | } |
53 | 43 | ||
54 | let candidate = import_assets.import_candidate(); | 44 | let candidate = import_assets.import_candidate(); |
55 | let range = ctx.sema.original_range(import_assets.syntax_under_caret()).range; | 45 | let range = ctx.sema.original_range(&syntax_under_caret).range; |
56 | 46 | ||
57 | let qualify_candidate = match candidate { | 47 | let qualify_candidate = match candidate { |
58 | ImportCandidate::Path(candidate) => { | 48 | ImportCandidate::Path(candidate) => { |
59 | if candidate.qualifier.is_some() { | 49 | if candidate.qualifier.is_some() { |
60 | mark::hit!(qualify_path_qualifier_start); | 50 | mark::hit!(qualify_path_qualifier_start); |
61 | let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?; | 51 | let path = ast::Path::cast(syntax_under_caret)?; |
62 | let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?); | 52 | let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?); |
63 | QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list()) | 53 | QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list()) |
64 | } else { | 54 | } else { |
65 | mark::hit!(qualify_path_unqualified_name); | 55 | mark::hit!(qualify_path_unqualified_name); |
66 | let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?; | 56 | let path = ast::Path::cast(syntax_under_caret)?; |
67 | let generics = path.segment()?.generic_arg_list(); | 57 | let generics = path.segment()?.generic_arg_list(); |
68 | QualifyCandidate::UnqualifiedName(generics) | 58 | QualifyCandidate::UnqualifiedName(generics) |
69 | } | 59 | } |
70 | } | 60 | } |
71 | ImportCandidate::TraitAssocItem(_) => { | 61 | ImportCandidate::TraitAssocItem(_) => { |
72 | mark::hit!(qualify_path_trait_assoc_item); | 62 | mark::hit!(qualify_path_trait_assoc_item); |
73 | let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?; | 63 | let path = ast::Path::cast(syntax_under_caret)?; |
74 | let (qualifier, segment) = (path.qualifier()?, path.segment()?); | 64 | let (qualifier, segment) = (path.qualifier()?, path.segment()?); |
75 | QualifyCandidate::TraitAssocItem(qualifier, segment) | 65 | QualifyCandidate::TraitAssocItem(qualifier, segment) |
76 | } | 66 | } |
77 | ImportCandidate::TraitMethod(_) => { | 67 | ImportCandidate::TraitMethod(_) => { |
78 | mark::hit!(qualify_path_trait_method); | 68 | mark::hit!(qualify_path_trait_method); |
79 | let mcall_expr = ast::MethodCallExpr::cast(import_assets.syntax_under_caret().clone())?; | 69 | let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?; |
80 | QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr) | 70 | QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr) |
81 | } | 71 | } |
82 | }; | 72 | }; |
@@ -140,7 +130,7 @@ impl QualifyCandidate<'_> { | |||
140 | let generics = | 130 | let generics = |
141 | mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string); | 131 | mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string); |
142 | let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args()); | 132 | let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args()); |
143 | let trait_ = item_as_trait(item)?; | 133 | let trait_ = item_as_trait(db, item)?; |
144 | let method = find_trait_method(db, trait_, &trait_method_name)?; | 134 | let method = find_trait_method(db, trait_, &trait_method_name)?; |
145 | if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) { | 135 | if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) { |
146 | let receiver = match self_access { | 136 | let receiver = match self_access { |
@@ -179,11 +169,13 @@ fn find_trait_method( | |||
179 | } | 169 | } |
180 | } | 170 | } |
181 | 171 | ||
182 | fn item_as_trait(item: hir::ItemInNs) -> Option<hir::Trait> { | 172 | fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> { |
183 | if let hir::ModuleDef::Trait(trait_) = hir::ModuleDef::from(item.as_module_def_id()?) { | 173 | let item_module_def = hir::ModuleDef::from(item.as_module_def_id()?); |
174 | |||
175 | if let hir::ModuleDef::Trait(trait_) = item_module_def { | ||
184 | Some(trait_) | 176 | Some(trait_) |
185 | } else { | 177 | } else { |
186 | None | 178 | item_module_def.as_assoc_item(db)?.containing_trait(db) |
187 | } | 179 | } |
188 | } | 180 | } |
189 | 181 | ||
@@ -191,7 +183,8 @@ fn group_label(candidate: &ImportCandidate) -> GroupLabel { | |||
191 | let name = match candidate { | 183 | let name = match candidate { |
192 | ImportCandidate::Path(it) => &it.name, | 184 | ImportCandidate::Path(it) => &it.name, |
193 | ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => &it.name, | 185 | ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => &it.name, |
194 | }; | 186 | } |
187 | .text(); | ||
195 | GroupLabel(format!("Qualify {}", name)) | 188 | GroupLabel(format!("Qualify {}", name)) |
196 | } | 189 | } |
197 | 190 | ||
diff --git a/crates/completion/src/completions/flyimport.rs b/crates/completion/src/completions/flyimport.rs index 222809638..47e797ac8 100644 --- a/crates/completion/src/completions/flyimport.rs +++ b/crates/completion/src/completions/flyimport.rs | |||
@@ -20,11 +20,14 @@ | |||
20 | //! # pub mod std { pub mod marker { pub struct PhantomData { } } } | 20 | //! # pub mod std { pub mod marker { pub struct PhantomData { } } } |
21 | //! ``` | 21 | //! ``` |
22 | //! | 22 | //! |
23 | //! Also completes associated items, that require trait imports. | ||
24 | //! | ||
23 | //! .Fuzzy search details | 25 | //! .Fuzzy search details |
24 | //! | 26 | //! |
25 | //! To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only | 27 | //! To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only |
26 | //! (i.e. in `HashMap` in the `std::collections::HashMap` path). | 28 | //! (i.e. in `HashMap` in the `std::collections::HashMap` path). |
27 | //! For the same reasons, avoids searching for any imports for inputs with their length less that 2 symbols. | 29 | //! For the same reasons, avoids searching for any path imports for inputs with their length less that 2 symbols |
30 | //! (but shows all associated items for any input length). | ||
28 | //! | 31 | //! |
29 | //! .Import configuration | 32 | //! .Import configuration |
30 | //! | 33 | //! |
@@ -45,10 +48,12 @@ | |||
45 | //! Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corredponding | 48 | //! Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corredponding |
46 | //! capability enabled. | 49 | //! capability enabled. |
47 | 50 | ||
48 | use either::Either; | ||
49 | use hir::{ModPath, ScopeDef}; | 51 | use hir::{ModPath, ScopeDef}; |
50 | use ide_db::{helpers::insert_use::ImportScope, imports_locator}; | 52 | use ide_db::helpers::{ |
51 | use syntax::AstNode; | 53 | import_assets::{ImportAssets, ImportCandidate}, |
54 | insert_use::ImportScope, | ||
55 | }; | ||
56 | use syntax::{AstNode, SyntaxNode, T}; | ||
52 | use test_utils::mark; | 57 | use test_utils::mark; |
53 | 58 | ||
54 | use crate::{ | 59 | use crate::{ |
@@ -60,58 +65,108 @@ use crate::{ | |||
60 | use super::Completions; | 65 | use super::Completions; |
61 | 66 | ||
62 | pub(crate) fn import_on_the_fly(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { | 67 | pub(crate) fn import_on_the_fly(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { |
63 | if !ctx.config.enable_autoimport_completions { | 68 | if !ctx.config.enable_imports_on_the_fly { |
64 | return None; | 69 | return None; |
65 | } | 70 | } |
66 | if ctx.attribute_under_caret.is_some() || ctx.mod_declaration_under_caret.is_some() { | 71 | if ctx.attribute_under_caret.is_some() || ctx.mod_declaration_under_caret.is_some() { |
67 | return None; | 72 | return None; |
68 | } | 73 | } |
69 | let potential_import_name = ctx.token.to_string(); | 74 | let potential_import_name = { |
70 | if potential_import_name.len() < 2 { | 75 | let token_kind = ctx.token.kind(); |
71 | return None; | 76 | if matches!(token_kind, T![.] | T![::]) { |
72 | } | 77 | String::new() |
73 | let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string()); | 78 | } else { |
79 | ctx.token.to_string() | ||
80 | } | ||
81 | }; | ||
74 | 82 | ||
75 | let current_module = ctx.scope.module()?; | 83 | let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string()); |
76 | let anchor = ctx.name_ref_syntax.as_ref()?; | ||
77 | let import_scope = ImportScope::find_insert_use_container(anchor.syntax(), &ctx.sema)?; | ||
78 | 84 | ||
79 | let user_input_lowercased = potential_import_name.to_lowercase(); | 85 | let user_input_lowercased = potential_import_name.to_lowercase(); |
80 | let mut all_mod_paths = imports_locator::find_similar_imports( | 86 | let import_assets = import_assets(ctx, potential_import_name)?; |
87 | let import_scope = ImportScope::find_insert_use_container( | ||
88 | position_for_import(ctx, Some(import_assets.import_candidate()))?, | ||
81 | &ctx.sema, | 89 | &ctx.sema, |
82 | ctx.krate?, | 90 | )?; |
83 | Some(40), | 91 | let mut all_mod_paths = import_assets |
84 | potential_import_name, | 92 | .search_for_relative_paths(&ctx.sema) |
85 | true, | 93 | .into_iter() |
86 | true, | 94 | .map(|(mod_path, item_in_ns)| { |
87 | ) | 95 | let scope_item = match item_in_ns { |
88 | .filter_map(|import_candidate| { | 96 | hir::ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()), |
89 | Some(match import_candidate { | 97 | hir::ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()), |
90 | Either::Left(module_def) => { | 98 | hir::ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()), |
91 | (current_module.find_use_path(ctx.db, module_def)?, ScopeDef::ModuleDef(module_def)) | 99 | }; |
92 | } | 100 | (mod_path, scope_item) |
93 | Either::Right(macro_def) => { | ||
94 | (current_module.find_use_path(ctx.db, macro_def)?, ScopeDef::MacroDef(macro_def)) | ||
95 | } | ||
96 | }) | 101 | }) |
97 | }) | 102 | .collect::<Vec<_>>(); |
98 | .filter(|(mod_path, _)| mod_path.len() > 1) | ||
99 | .collect::<Vec<_>>(); | ||
100 | |||
101 | all_mod_paths.sort_by_cached_key(|(mod_path, _)| { | 103 | all_mod_paths.sort_by_cached_key(|(mod_path, _)| { |
102 | compute_fuzzy_completion_order_key(mod_path, &user_input_lowercased) | 104 | compute_fuzzy_completion_order_key(mod_path, &user_input_lowercased) |
103 | }); | 105 | }); |
104 | 106 | ||
105 | acc.add_all(all_mod_paths.into_iter().filter_map(|(import_path, definition)| { | 107 | acc.add_all(all_mod_paths.into_iter().filter_map(|(import_path, definition)| { |
106 | render_resolution_with_import( | 108 | let import_for_trait_assoc_item = match definition { |
107 | RenderContext::new(ctx), | 109 | ScopeDef::ModuleDef(module_def) => module_def |
108 | ImportEdit { import_path, import_scope: import_scope.clone() }, | 110 | .as_assoc_item(ctx.db) |
109 | &definition, | 111 | .and_then(|assoc| assoc.containing_trait(ctx.db)) |
110 | ) | 112 | .is_some(), |
113 | _ => false, | ||
114 | }; | ||
115 | let import_edit = ImportEdit { | ||
116 | import_path, | ||
117 | import_scope: import_scope.clone(), | ||
118 | import_for_trait_assoc_item, | ||
119 | }; | ||
120 | render_resolution_with_import(RenderContext::new(ctx), import_edit, &definition) | ||
111 | })); | 121 | })); |
112 | Some(()) | 122 | Some(()) |
113 | } | 123 | } |
114 | 124 | ||
125 | pub(crate) fn position_for_import<'a>( | ||
126 | ctx: &'a CompletionContext, | ||
127 | import_candidate: Option<&ImportCandidate>, | ||
128 | ) -> Option<&'a SyntaxNode> { | ||
129 | Some(match import_candidate { | ||
130 | Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(), | ||
131 | Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual.as_ref()?.syntax(), | ||
132 | Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver.as_ref()?.syntax(), | ||
133 | None => ctx | ||
134 | .name_ref_syntax | ||
135 | .as_ref() | ||
136 | .map(|name_ref| name_ref.syntax()) | ||
137 | .or_else(|| ctx.path_qual.as_ref().map(|path| path.syntax())) | ||
138 | .or_else(|| ctx.dot_receiver.as_ref().map(|expr| expr.syntax()))?, | ||
139 | }) | ||
140 | } | ||
141 | |||
142 | fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> { | ||
143 | let current_module = ctx.scope.module()?; | ||
144 | if let Some(dot_receiver) = &ctx.dot_receiver { | ||
145 | ImportAssets::for_fuzzy_method_call( | ||
146 | current_module, | ||
147 | ctx.sema.type_of_expr(dot_receiver)?, | ||
148 | fuzzy_name, | ||
149 | ) | ||
150 | } else { | ||
151 | let fuzzy_name_length = fuzzy_name.len(); | ||
152 | let assets_for_path = ImportAssets::for_fuzzy_path( | ||
153 | current_module, | ||
154 | ctx.path_qual.clone(), | ||
155 | fuzzy_name, | ||
156 | &ctx.sema, | ||
157 | ); | ||
158 | |||
159 | if matches!(assets_for_path.as_ref()?.import_candidate(), ImportCandidate::Path(_)) | ||
160 | && fuzzy_name_length < 2 | ||
161 | { | ||
162 | mark::hit!(ignore_short_input_for_path); | ||
163 | None | ||
164 | } else { | ||
165 | assets_for_path | ||
166 | } | ||
167 | } | ||
168 | } | ||
169 | |||
115 | fn compute_fuzzy_completion_order_key( | 170 | fn compute_fuzzy_completion_order_key( |
116 | proposed_mod_path: &ModPath, | 171 | proposed_mod_path: &ModPath, |
117 | user_input_lowercased: &str, | 172 | user_input_lowercased: &str, |
@@ -224,6 +279,30 @@ fn main() { | |||
224 | } | 279 | } |
225 | 280 | ||
226 | #[test] | 281 | #[test] |
282 | fn short_paths_are_ignored() { | ||
283 | mark::check!(ignore_short_input_for_path); | ||
284 | |||
285 | check( | ||
286 | r#" | ||
287 | //- /lib.rs crate:dep | ||
288 | pub struct FirstStruct; | ||
289 | pub mod some_module { | ||
290 | pub struct SecondStruct; | ||
291 | pub struct ThirdStruct; | ||
292 | } | ||
293 | |||
294 | //- /main.rs crate:main deps:dep | ||
295 | use dep::{FirstStruct, some_module::SecondStruct}; | ||
296 | |||
297 | fn main() { | ||
298 | t$0 | ||
299 | } | ||
300 | "#, | ||
301 | expect![[r#""#]], | ||
302 | ); | ||
303 | } | ||
304 | |||
305 | #[test] | ||
227 | fn fuzzy_completions_come_in_specific_order() { | 306 | fn fuzzy_completions_come_in_specific_order() { |
228 | mark::check!(certain_fuzzy_order_test); | 307 | mark::check!(certain_fuzzy_order_test); |
229 | check( | 308 | check( |
@@ -259,6 +338,176 @@ fn main() { | |||
259 | } | 338 | } |
260 | 339 | ||
261 | #[test] | 340 | #[test] |
341 | fn trait_function_fuzzy_completion() { | ||
342 | let fixture = r#" | ||
343 | //- /lib.rs crate:dep | ||
344 | pub mod test_mod { | ||
345 | pub trait TestTrait { | ||
346 | const SPECIAL_CONST: u8; | ||
347 | type HumbleType; | ||
348 | fn weird_function(); | ||
349 | fn random_method(&self); | ||
350 | } | ||
351 | pub struct TestStruct {} | ||
352 | impl TestTrait for TestStruct { | ||
353 | const SPECIAL_CONST: u8 = 42; | ||
354 | type HumbleType = (); | ||
355 | fn weird_function() {} | ||
356 | fn random_method(&self) {} | ||
357 | } | ||
358 | } | ||
359 | |||
360 | //- /main.rs crate:main deps:dep | ||
361 | fn main() { | ||
362 | dep::test_mod::TestStruct::wei$0 | ||
363 | } | ||
364 | "#; | ||
365 | |||
366 | check( | ||
367 | fixture, | ||
368 | expect![[r#" | ||
369 | fn weird_function() (dep::test_mod::TestTrait) fn weird_function() | ||
370 | "#]], | ||
371 | ); | ||
372 | |||
373 | check_edit( | ||
374 | "weird_function", | ||
375 | fixture, | ||
376 | r#" | ||
377 | use dep::test_mod::TestTrait; | ||
378 | |||
379 | fn main() { | ||
380 | dep::test_mod::TestStruct::weird_function()$0 | ||
381 | } | ||
382 | "#, | ||
383 | ); | ||
384 | } | ||
385 | |||
386 | #[test] | ||
387 | fn trait_const_fuzzy_completion() { | ||
388 | let fixture = r#" | ||
389 | //- /lib.rs crate:dep | ||
390 | pub mod test_mod { | ||
391 | pub trait TestTrait { | ||
392 | const SPECIAL_CONST: u8; | ||
393 | type HumbleType; | ||
394 | fn weird_function(); | ||
395 | fn random_method(&self); | ||
396 | } | ||
397 | pub struct TestStruct {} | ||
398 | impl TestTrait for TestStruct { | ||
399 | const SPECIAL_CONST: u8 = 42; | ||
400 | type HumbleType = (); | ||
401 | fn weird_function() {} | ||
402 | fn random_method(&self) {} | ||
403 | } | ||
404 | } | ||
405 | |||
406 | //- /main.rs crate:main deps:dep | ||
407 | fn main() { | ||
408 | dep::test_mod::TestStruct::spe$0 | ||
409 | } | ||
410 | "#; | ||
411 | |||
412 | check( | ||
413 | fixture, | ||
414 | expect![[r#" | ||
415 | ct SPECIAL_CONST (dep::test_mod::TestTrait) | ||
416 | "#]], | ||
417 | ); | ||
418 | |||
419 | check_edit( | ||
420 | "SPECIAL_CONST", | ||
421 | fixture, | ||
422 | r#" | ||
423 | use dep::test_mod::TestTrait; | ||
424 | |||
425 | fn main() { | ||
426 | dep::test_mod::TestStruct::SPECIAL_CONST | ||
427 | } | ||
428 | "#, | ||
429 | ); | ||
430 | } | ||
431 | |||
432 | #[test] | ||
433 | fn trait_method_fuzzy_completion() { | ||
434 | let fixture = r#" | ||
435 | //- /lib.rs crate:dep | ||
436 | pub mod test_mod { | ||
437 | pub trait TestTrait { | ||
438 | const SPECIAL_CONST: u8; | ||
439 | type HumbleType; | ||
440 | fn weird_function(); | ||
441 | fn random_method(&self); | ||
442 | } | ||
443 | pub struct TestStruct {} | ||
444 | impl TestTrait for TestStruct { | ||
445 | const SPECIAL_CONST: u8 = 42; | ||
446 | type HumbleType = (); | ||
447 | fn weird_function() {} | ||
448 | fn random_method(&self) {} | ||
449 | } | ||
450 | } | ||
451 | |||
452 | //- /main.rs crate:main deps:dep | ||
453 | fn main() { | ||
454 | let test_struct = dep::test_mod::TestStruct {}; | ||
455 | test_struct.ran$0 | ||
456 | } | ||
457 | "#; | ||
458 | |||
459 | check( | ||
460 | fixture, | ||
461 | expect![[r#" | ||
462 | me random_method() (dep::test_mod::TestTrait) fn random_method(&self) | ||
463 | "#]], | ||
464 | ); | ||
465 | |||
466 | check_edit( | ||
467 | "random_method", | ||
468 | fixture, | ||
469 | r#" | ||
470 | use dep::test_mod::TestTrait; | ||
471 | |||
472 | fn main() { | ||
473 | let test_struct = dep::test_mod::TestStruct {}; | ||
474 | test_struct.random_method()$0 | ||
475 | } | ||
476 | "#, | ||
477 | ); | ||
478 | } | ||
479 | |||
480 | #[test] | ||
481 | fn no_trait_type_fuzzy_completion() { | ||
482 | check( | ||
483 | r#" | ||
484 | //- /lib.rs crate:dep | ||
485 | pub mod test_mod { | ||
486 | pub trait TestTrait { | ||
487 | const SPECIAL_CONST: u8; | ||
488 | type HumbleType; | ||
489 | fn weird_function(); | ||
490 | fn random_method(&self); | ||
491 | } | ||
492 | pub struct TestStruct {} | ||
493 | impl TestTrait for TestStruct { | ||
494 | const SPECIAL_CONST: u8 = 42; | ||
495 | type HumbleType = (); | ||
496 | fn weird_function() {} | ||
497 | fn random_method(&self) {} | ||
498 | } | ||
499 | } | ||
500 | |||
501 | //- /main.rs crate:main deps:dep | ||
502 | fn main() { | ||
503 | dep::test_mod::TestStruct::hum$0 | ||
504 | } | ||
505 | "#, | ||
506 | expect![[r#""#]], | ||
507 | ); | ||
508 | } | ||
509 | |||
510 | #[test] | ||
262 | fn does_not_propose_names_in_scope() { | 511 | fn does_not_propose_names_in_scope() { |
263 | check( | 512 | check( |
264 | r#" | 513 | r#" |
@@ -288,4 +537,129 @@ fn main() { | |||
288 | expect![[r#""#]], | 537 | expect![[r#""#]], |
289 | ); | 538 | ); |
290 | } | 539 | } |
540 | |||
541 | #[test] | ||
542 | fn does_not_propose_traits_in_scope() { | ||
543 | check( | ||
544 | r#" | ||
545 | //- /lib.rs crate:dep | ||
546 | pub mod test_mod { | ||
547 | pub trait TestTrait { | ||
548 | const SPECIAL_CONST: u8; | ||
549 | type HumbleType; | ||
550 | fn weird_function(); | ||
551 | fn random_method(&self); | ||
552 | } | ||
553 | pub struct TestStruct {} | ||
554 | impl TestTrait for TestStruct { | ||
555 | const SPECIAL_CONST: u8 = 42; | ||
556 | type HumbleType = (); | ||
557 | fn weird_function() {} | ||
558 | fn random_method(&self) {} | ||
559 | } | ||
560 | } | ||
561 | |||
562 | //- /main.rs crate:main deps:dep | ||
563 | use dep::test_mod::{TestStruct, TestTrait}; | ||
564 | fn main() { | ||
565 | dep::test_mod::TestStruct::hum$0 | ||
566 | } | ||
567 | "#, | ||
568 | expect![[r#""#]], | ||
569 | ); | ||
570 | } | ||
571 | |||
572 | #[test] | ||
573 | fn blanket_trait_impl_import() { | ||
574 | check_edit( | ||
575 | "another_function", | ||
576 | r#" | ||
577 | //- /lib.rs crate:dep | ||
578 | pub mod test_mod { | ||
579 | pub struct TestStruct {} | ||
580 | pub trait TestTrait { | ||
581 | fn another_function(); | ||
582 | } | ||
583 | impl<T> TestTrait for T { | ||
584 | fn another_function() {} | ||
585 | } | ||
586 | } | ||
587 | |||
588 | //- /main.rs crate:main deps:dep | ||
589 | fn main() { | ||
590 | dep::test_mod::TestStruct::ano$0 | ||
591 | } | ||
592 | "#, | ||
593 | r#" | ||
594 | use dep::test_mod::TestTrait; | ||
595 | |||
596 | fn main() { | ||
597 | dep::test_mod::TestStruct::another_function()$0 | ||
598 | } | ||
599 | "#, | ||
600 | ); | ||
601 | } | ||
602 | |||
603 | #[test] | ||
604 | fn zero_input_assoc_item_completion() { | ||
605 | check( | ||
606 | r#" | ||
607 | //- /lib.rs crate:dep | ||
608 | pub mod test_mod { | ||
609 | pub trait TestTrait { | ||
610 | const SPECIAL_CONST: u8; | ||
611 | type HumbleType; | ||
612 | fn weird_function(); | ||
613 | fn random_method(&self); | ||
614 | } | ||
615 | pub struct TestStruct {} | ||
616 | impl TestTrait for TestStruct { | ||
617 | const SPECIAL_CONST: u8 = 42; | ||
618 | type HumbleType = (); | ||
619 | fn weird_function() {} | ||
620 | fn random_method(&self) {} | ||
621 | } | ||
622 | } | ||
623 | |||
624 | //- /main.rs crate:main deps:dep | ||
625 | fn main() { | ||
626 | let test_struct = dep::test_mod::TestStruct {}; | ||
627 | test_struct.$0 | ||
628 | } | ||
629 | "#, | ||
630 | expect![[r#" | ||
631 | me random_method() (dep::test_mod::TestTrait) fn random_method(&self) | ||
632 | "#]], | ||
633 | ); | ||
634 | |||
635 | check( | ||
636 | r#" | ||
637 | //- /lib.rs crate:dep | ||
638 | pub mod test_mod { | ||
639 | pub trait TestTrait { | ||
640 | const SPECIAL_CONST: u8; | ||
641 | type HumbleType; | ||
642 | fn weird_function(); | ||
643 | fn random_method(&self); | ||
644 | } | ||
645 | pub struct TestStruct {} | ||
646 | impl TestTrait for TestStruct { | ||
647 | const SPECIAL_CONST: u8 = 42; | ||
648 | type HumbleType = (); | ||
649 | fn weird_function() {} | ||
650 | fn random_method(&self) {} | ||
651 | } | ||
652 | } | ||
653 | |||
654 | //- /main.rs crate:main deps:dep | ||
655 | fn main() { | ||
656 | dep::test_mod::TestStruct::$0 | ||
657 | } | ||
658 | "#, | ||
659 | expect![[r#" | ||
660 | ct SPECIAL_CONST (dep::test_mod::TestTrait) | ||
661 | fn weird_function() (dep::test_mod::TestTrait) fn weird_function() | ||
662 | "#]], | ||
663 | ); | ||
664 | } | ||
291 | } | 665 | } |
diff --git a/crates/completion/src/config.rs b/crates/completion/src/config.rs index 58fc700f3..d70ed6c1c 100644 --- a/crates/completion/src/config.rs +++ b/crates/completion/src/config.rs | |||
@@ -9,7 +9,7 @@ use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap}; | |||
9 | #[derive(Clone, Debug, PartialEq, Eq)] | 9 | #[derive(Clone, Debug, PartialEq, Eq)] |
10 | pub struct CompletionConfig { | 10 | pub struct CompletionConfig { |
11 | pub enable_postfix_completions: bool, | 11 | pub enable_postfix_completions: bool, |
12 | pub enable_autoimport_completions: bool, | 12 | pub enable_imports_on_the_fly: bool, |
13 | pub add_call_parenthesis: bool, | 13 | pub add_call_parenthesis: bool, |
14 | pub add_call_argument_snippets: bool, | 14 | pub add_call_argument_snippets: bool, |
15 | pub snippet_cap: Option<SnippetCap>, | 15 | pub snippet_cap: Option<SnippetCap>, |
diff --git a/crates/completion/src/item.rs b/crates/completion/src/item.rs index 0134ff219..4147853e7 100644 --- a/crates/completion/src/item.rs +++ b/crates/completion/src/item.rs | |||
@@ -270,6 +270,7 @@ impl CompletionItem { | |||
270 | pub struct ImportEdit { | 270 | pub struct ImportEdit { |
271 | pub import_path: ModPath, | 271 | pub import_path: ModPath, |
272 | pub import_scope: ImportScope, | 272 | pub import_scope: ImportScope, |
273 | pub import_for_trait_assoc_item: bool, | ||
273 | } | 274 | } |
274 | 275 | ||
275 | impl ImportEdit { | 276 | impl ImportEdit { |
@@ -321,17 +322,19 @@ impl Builder { | |||
321 | let mut insert_text = self.insert_text; | 322 | let mut insert_text = self.insert_text; |
322 | 323 | ||
323 | if let Some(import_to_add) = self.import_to_add.as_ref() { | 324 | if let Some(import_to_add) = self.import_to_add.as_ref() { |
324 | let mut import_path_without_last_segment = import_to_add.import_path.to_owned(); | 325 | if import_to_add.import_for_trait_assoc_item { |
325 | let _ = import_path_without_last_segment.segments.pop(); | 326 | lookup = lookup.or_else(|| Some(label.clone())); |
326 | 327 | insert_text = insert_text.or_else(|| Some(label.clone())); | |
327 | if !import_path_without_last_segment.segments.is_empty() { | 328 | label = format!("{} ({})", label, import_to_add.import_path); |
328 | if lookup.is_none() { | 329 | } else { |
329 | lookup = Some(label.clone()); | 330 | let mut import_path_without_last_segment = import_to_add.import_path.to_owned(); |
330 | } | 331 | let _ = import_path_without_last_segment.segments.pop(); |
331 | if insert_text.is_none() { | 332 | |
332 | insert_text = Some(label.clone()); | 333 | if !import_path_without_last_segment.segments.is_empty() { |
334 | lookup = lookup.or_else(|| Some(label.clone())); | ||
335 | insert_text = insert_text.or_else(|| Some(label.clone())); | ||
336 | label = format!("{}::{}", import_path_without_last_segment, label); | ||
333 | } | 337 | } |
334 | label = format!("{}::{}", import_path_without_last_segment, label); | ||
335 | } | 338 | } |
336 | } | 339 | } |
337 | 340 | ||
@@ -398,7 +401,9 @@ impl Builder { | |||
398 | pub(crate) fn set_detail(mut self, detail: Option<impl Into<String>>) -> Builder { | 401 | pub(crate) fn set_detail(mut self, detail: Option<impl Into<String>>) -> Builder { |
399 | self.detail = detail.map(Into::into); | 402 | self.detail = detail.map(Into::into); |
400 | if let Some(detail) = &self.detail { | 403 | if let Some(detail) = &self.detail { |
401 | assert_never!(detail.contains('\n'), "multiline detail: {}", detail); | 404 | if assert_never!(detail.contains('\n'), "multiline detail: {}", detail) { |
405 | self.detail = Some(detail.splitn(2, '\n').next().unwrap().to_string()); | ||
406 | } | ||
402 | } | 407 | } |
403 | self | 408 | self |
404 | } | 409 | } |
diff --git a/crates/completion/src/lib.rs b/crates/completion/src/lib.rs index ee1b822e7..2c4e54524 100644 --- a/crates/completion/src/lib.rs +++ b/crates/completion/src/lib.rs | |||
@@ -11,10 +11,10 @@ mod render; | |||
11 | 11 | ||
12 | mod completions; | 12 | mod completions; |
13 | 13 | ||
14 | use completions::flyimport::position_for_import; | ||
14 | use ide_db::{ | 15 | use ide_db::{ |
15 | base_db::FilePosition, helpers::insert_use::ImportScope, imports_locator, RootDatabase, | 16 | base_db::FilePosition, helpers::insert_use::ImportScope, imports_locator, RootDatabase, |
16 | }; | 17 | }; |
17 | use syntax::AstNode; | ||
18 | use text_edit::TextEdit; | 18 | use text_edit::TextEdit; |
19 | 19 | ||
20 | use crate::{completions::Completions, context::CompletionContext, item::CompletionKind}; | 20 | use crate::{completions::Completions, context::CompletionContext, item::CompletionKind}; |
@@ -139,12 +139,13 @@ pub fn resolve_completion_edits( | |||
139 | position: FilePosition, | 139 | position: FilePosition, |
140 | full_import_path: &str, | 140 | full_import_path: &str, |
141 | imported_name: String, | 141 | imported_name: String, |
142 | import_for_trait_assoc_item: bool, | ||
142 | ) -> Option<Vec<TextEdit>> { | 143 | ) -> Option<Vec<TextEdit>> { |
143 | let ctx = CompletionContext::new(db, position, config)?; | 144 | let ctx = CompletionContext::new(db, position, config)?; |
144 | let anchor = ctx.name_ref_syntax.as_ref()?; | 145 | let position_for_import = position_for_import(&ctx, None)?; |
145 | let import_scope = ImportScope::find_insert_use_container(anchor.syntax(), &ctx.sema)?; | 146 | let import_scope = ImportScope::find_insert_use_container(position_for_import, &ctx.sema)?; |
146 | 147 | ||
147 | let current_module = ctx.sema.scope(anchor.syntax()).module()?; | 148 | let current_module = ctx.sema.scope(position_for_import).module()?; |
148 | let current_crate = current_module.krate(); | 149 | let current_crate = current_module.krate(); |
149 | 150 | ||
150 | let import_path = imports_locator::find_exact_imports(&ctx.sema, current_crate, imported_name) | 151 | let import_path = imports_locator::find_exact_imports(&ctx.sema, current_crate, imported_name) |
@@ -154,7 +155,7 @@ pub fn resolve_completion_edits( | |||
154 | }) | 155 | }) |
155 | .find(|mod_path| mod_path.to_string() == full_import_path)?; | 156 | .find(|mod_path| mod_path.to_string() == full_import_path)?; |
156 | 157 | ||
157 | ImportEdit { import_path, import_scope } | 158 | ImportEdit { import_path, import_scope, import_for_trait_assoc_item } |
158 | .to_text_edit(config.insert_use.merge) | 159 | .to_text_edit(config.insert_use.merge) |
159 | .map(|edit| vec![edit]) | 160 | .map(|edit| vec![edit]) |
160 | } | 161 | } |
diff --git a/crates/completion/src/render.rs b/crates/completion/src/render.rs index 820dd01d1..4b3c9702a 100644 --- a/crates/completion/src/render.rs +++ b/crates/completion/src/render.rs | |||
@@ -10,7 +10,7 @@ pub(crate) mod type_alias; | |||
10 | 10 | ||
11 | mod builder_ext; | 11 | mod builder_ext; |
12 | 12 | ||
13 | use hir::{Documentation, HasAttrs, HirDisplay, Mutability, ScopeDef, Type}; | 13 | use hir::{Documentation, HasAttrs, HirDisplay, ModuleDef, Mutability, ScopeDef, Type}; |
14 | use ide_db::{helpers::SnippetCap, RootDatabase}; | 14 | use ide_db::{helpers::SnippetCap, RootDatabase}; |
15 | use syntax::TextRange; | 15 | use syntax::TextRange; |
16 | use test_utils::mark; | 16 | use test_utils::mark; |
@@ -51,16 +51,16 @@ pub(crate) fn render_resolution_with_import<'a>( | |||
51 | import_edit: ImportEdit, | 51 | import_edit: ImportEdit, |
52 | resolution: &ScopeDef, | 52 | resolution: &ScopeDef, |
53 | ) -> Option<CompletionItem> { | 53 | ) -> Option<CompletionItem> { |
54 | Render::new(ctx) | 54 | let local_name = match resolution { |
55 | .render_resolution( | 55 | ScopeDef::ModuleDef(ModuleDef::Function(f)) => f.name(ctx.completion.db).to_string(), |
56 | import_edit.import_path.segments.last()?.to_string(), | 56 | ScopeDef::ModuleDef(ModuleDef::Const(c)) => c.name(ctx.completion.db)?.to_string(), |
57 | Some(import_edit), | 57 | ScopeDef::ModuleDef(ModuleDef::TypeAlias(t)) => t.name(ctx.completion.db).to_string(), |
58 | resolution, | 58 | _ => import_edit.import_path.segments.last()?.to_string(), |
59 | ) | 59 | }; |
60 | .map(|mut item| { | 60 | Render::new(ctx).render_resolution(local_name, Some(import_edit), resolution).map(|mut item| { |
61 | item.completion_kind = CompletionKind::Magic; | 61 | item.completion_kind = CompletionKind::Magic; |
62 | item | 62 | item |
63 | }) | 63 | }) |
64 | } | 64 | } |
65 | 65 | ||
66 | /// Interface for data and methods required for items rendering. | 66 | /// Interface for data and methods required for items rendering. |
diff --git a/crates/completion/src/test_utils.rs b/crates/completion/src/test_utils.rs index 6ea6da989..3faf861b9 100644 --- a/crates/completion/src/test_utils.rs +++ b/crates/completion/src/test_utils.rs | |||
@@ -18,7 +18,7 @@ use crate::{item::CompletionKind, CompletionConfig, CompletionItem}; | |||
18 | 18 | ||
19 | pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig { | 19 | pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig { |
20 | enable_postfix_completions: true, | 20 | enable_postfix_completions: true, |
21 | enable_autoimport_completions: true, | 21 | enable_imports_on_the_fly: true, |
22 | add_call_parenthesis: true, | 22 | add_call_parenthesis: true, |
23 | add_call_argument_snippets: true, | 23 | add_call_argument_snippets: true, |
24 | snippet_cap: SnippetCap::new(true), | 24 | snippet_cap: SnippetCap::new(true), |
diff --git a/crates/hir/src/code_model.rs b/crates/hir/src/code_model.rs index 6cbf5cecf..2950f08b8 100644 --- a/crates/hir/src/code_model.rs +++ b/crates/hir/src/code_model.rs | |||
@@ -272,6 +272,15 @@ impl ModuleDef { | |||
272 | 272 | ||
273 | hir_ty::diagnostics::validate_module_item(db, module.id.krate, id, sink) | 273 | hir_ty::diagnostics::validate_module_item(db, module.id.krate, id, sink) |
274 | } | 274 | } |
275 | |||
276 | pub fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> { | ||
277 | match self { | ||
278 | ModuleDef::Function(f) => f.as_assoc_item(db), | ||
279 | ModuleDef::Const(c) => c.as_assoc_item(db), | ||
280 | ModuleDef::TypeAlias(t) => t.as_assoc_item(db), | ||
281 | _ => None, | ||
282 | } | ||
283 | } | ||
275 | } | 284 | } |
276 | 285 | ||
277 | impl Module { | 286 | impl Module { |
@@ -1091,6 +1100,13 @@ impl AssocItem { | |||
1091 | AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"), | 1100 | AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"), |
1092 | } | 1101 | } |
1093 | } | 1102 | } |
1103 | |||
1104 | pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> { | ||
1105 | match self.container(db) { | ||
1106 | AssocItemContainer::Trait(t) => Some(t), | ||
1107 | _ => None, | ||
1108 | } | ||
1109 | } | ||
1094 | } | 1110 | } |
1095 | 1111 | ||
1096 | impl HasVisibility for AssocItem { | 1112 | impl HasVisibility for AssocItem { |
diff --git a/crates/hir_def/src/import_map.rs b/crates/hir_def/src/import_map.rs index e5368b293..fac0de90c 100644 --- a/crates/hir_def/src/import_map.rs +++ b/crates/hir_def/src/import_map.rs | |||
@@ -263,6 +263,7 @@ pub enum ImportKind { | |||
263 | Trait, | 263 | Trait, |
264 | TypeAlias, | 264 | TypeAlias, |
265 | BuiltinType, | 265 | BuiltinType, |
266 | AssociatedItem, | ||
266 | } | 267 | } |
267 | 268 | ||
268 | /// A way to match import map contents against the search query. | 269 | /// A way to match import map contents against the search query. |
@@ -282,6 +283,7 @@ pub struct Query { | |||
282 | query: String, | 283 | query: String, |
283 | lowercased: String, | 284 | lowercased: String, |
284 | name_only: bool, | 285 | name_only: bool, |
286 | assoc_items_only: bool, | ||
285 | search_mode: SearchMode, | 287 | search_mode: SearchMode, |
286 | case_sensitive: bool, | 288 | case_sensitive: bool, |
287 | limit: usize, | 289 | limit: usize, |
@@ -295,6 +297,7 @@ impl Query { | |||
295 | query, | 297 | query, |
296 | lowercased, | 298 | lowercased, |
297 | name_only: false, | 299 | name_only: false, |
300 | assoc_items_only: false, | ||
298 | search_mode: SearchMode::Contains, | 301 | search_mode: SearchMode::Contains, |
299 | case_sensitive: false, | 302 | case_sensitive: false, |
300 | limit: usize::max_value(), | 303 | limit: usize::max_value(), |
@@ -309,6 +312,11 @@ impl Query { | |||
309 | Self { name_only: true, ..self } | 312 | Self { name_only: true, ..self } |
310 | } | 313 | } |
311 | 314 | ||
315 | /// Matches only the entries that are associated items, ignoring the rest. | ||
316 | pub fn assoc_items_only(self) -> Self { | ||
317 | Self { assoc_items_only: true, ..self } | ||
318 | } | ||
319 | |||
312 | /// Specifies the way to search for the entries using the query. | 320 | /// Specifies the way to search for the entries using the query. |
313 | pub fn search_mode(self, search_mode: SearchMode) -> Self { | 321 | pub fn search_mode(self, search_mode: SearchMode) -> Self { |
314 | Self { search_mode, ..self } | 322 | Self { search_mode, ..self } |
@@ -331,6 +339,14 @@ impl Query { | |||
331 | } | 339 | } |
332 | 340 | ||
333 | fn import_matches(&self, import: &ImportInfo, enforce_lowercase: bool) -> bool { | 341 | fn import_matches(&self, import: &ImportInfo, enforce_lowercase: bool) -> bool { |
342 | if import.is_trait_assoc_item { | ||
343 | if self.exclude_import_kinds.contains(&ImportKind::AssociatedItem) { | ||
344 | return false; | ||
345 | } | ||
346 | } else if self.assoc_items_only { | ||
347 | return false; | ||
348 | } | ||
349 | |||
334 | let mut input = if import.is_trait_assoc_item || self.name_only { | 350 | let mut input = if import.is_trait_assoc_item || self.name_only { |
335 | import.path.segments.last().unwrap().to_string() | 351 | import.path.segments.last().unwrap().to_string() |
336 | } else { | 352 | } else { |
@@ -814,6 +830,56 @@ mod tests { | |||
814 | } | 830 | } |
815 | 831 | ||
816 | #[test] | 832 | #[test] |
833 | fn assoc_items_filtering() { | ||
834 | let ra_fixture = r#" | ||
835 | //- /main.rs crate:main deps:dep | ||
836 | //- /dep.rs crate:dep | ||
837 | pub mod fmt { | ||
838 | pub trait Display { | ||
839 | type FmtTypeAlias; | ||
840 | const FMT_CONST: bool; | ||
841 | |||
842 | fn format_function(); | ||
843 | fn format_method(&self); | ||
844 | } | ||
845 | } | ||
846 | "#; | ||
847 | |||
848 | check_search( | ||
849 | ra_fixture, | ||
850 | "main", | ||
851 | Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy).assoc_items_only(), | ||
852 | expect![[r#" | ||
853 | dep::fmt::Display::FMT_CONST (a) | ||
854 | dep::fmt::Display::format_function (a) | ||
855 | dep::fmt::Display::format_method (a) | ||
856 | "#]], | ||
857 | ); | ||
858 | |||
859 | check_search( | ||
860 | ra_fixture, | ||
861 | "main", | ||
862 | Query::new("fmt".to_string()) | ||
863 | .search_mode(SearchMode::Fuzzy) | ||
864 | .exclude_import_kind(ImportKind::AssociatedItem), | ||
865 | expect![[r#" | ||
866 | dep::fmt (t) | ||
867 | dep::fmt::Display (t) | ||
868 | "#]], | ||
869 | ); | ||
870 | |||
871 | check_search( | ||
872 | ra_fixture, | ||
873 | "main", | ||
874 | Query::new("fmt".to_string()) | ||
875 | .search_mode(SearchMode::Fuzzy) | ||
876 | .assoc_items_only() | ||
877 | .exclude_import_kind(ImportKind::AssociatedItem), | ||
878 | expect![[r#""#]], | ||
879 | ); | ||
880 | } | ||
881 | |||
882 | #[test] | ||
817 | fn search_mode() { | 883 | fn search_mode() { |
818 | let ra_fixture = r#" | 884 | let ra_fixture = r#" |
819 | //- /main.rs crate:main deps:dep | 885 | //- /main.rs crate:main deps:dep |
diff --git a/crates/hir_def/src/item_tree.rs b/crates/hir_def/src/item_tree.rs index 9a433b61c..ff62928df 100644 --- a/crates/hir_def/src/item_tree.rs +++ b/crates/hir_def/src/item_tree.rs | |||
@@ -145,7 +145,6 @@ impl ItemTree { | |||
145 | macro_calls, | 145 | macro_calls, |
146 | macro_rules, | 146 | macro_rules, |
147 | macro_defs, | 147 | macro_defs, |
148 | exprs, | ||
149 | vis, | 148 | vis, |
150 | generics, | 149 | generics, |
151 | } = &mut **data; | 150 | } = &mut **data; |
@@ -167,7 +166,6 @@ impl ItemTree { | |||
167 | macro_calls.shrink_to_fit(); | 166 | macro_calls.shrink_to_fit(); |
168 | macro_rules.shrink_to_fit(); | 167 | macro_rules.shrink_to_fit(); |
169 | macro_defs.shrink_to_fit(); | 168 | macro_defs.shrink_to_fit(); |
170 | exprs.shrink_to_fit(); | ||
171 | 169 | ||
172 | vis.arena.shrink_to_fit(); | 170 | vis.arena.shrink_to_fit(); |
173 | generics.arena.shrink_to_fit(); | 171 | generics.arena.shrink_to_fit(); |
@@ -296,7 +294,6 @@ struct ItemTreeData { | |||
296 | macro_calls: Arena<MacroCall>, | 294 | macro_calls: Arena<MacroCall>, |
297 | macro_rules: Arena<MacroRules>, | 295 | macro_rules: Arena<MacroRules>, |
298 | macro_defs: Arena<MacroDef>, | 296 | macro_defs: Arena<MacroDef>, |
299 | exprs: Arena<Expr>, | ||
300 | 297 | ||
301 | vis: ItemVisibilities, | 298 | vis: ItemVisibilities, |
302 | generics: GenericParamsStorage, | 299 | generics: GenericParamsStorage, |
@@ -461,7 +458,7 @@ macro_rules! impl_index { | |||
461 | }; | 458 | }; |
462 | } | 459 | } |
463 | 460 | ||
464 | impl_index!(fields: Field, variants: Variant, exprs: Expr); | 461 | impl_index!(fields: Field, variants: Variant); |
465 | 462 | ||
466 | impl Index<RawVisibilityId> for ItemTree { | 463 | impl Index<RawVisibilityId> for ItemTree { |
467 | type Output = RawVisibility; | 464 | type Output = RawVisibility; |
@@ -664,11 +661,6 @@ pub struct MacroDef { | |||
664 | pub ast_id: FileAstId<ast::MacroDef>, | 661 | pub ast_id: FileAstId<ast::MacroDef>, |
665 | } | 662 | } |
666 | 663 | ||
667 | // NB: There's no `FileAstId` for `Expr`. The only case where this would be useful is for array | ||
668 | // lengths, but we don't do much with them yet. | ||
669 | #[derive(Debug, Clone, Eq, PartialEq)] | ||
670 | pub struct Expr; | ||
671 | |||
672 | macro_rules! impl_froms { | 664 | macro_rules! impl_froms { |
673 | ($e:ident { $($v:ident ($t:ty)),* $(,)? }) => { | 665 | ($e:ident { $($v:ident ($t:ty)),* $(,)? }) => { |
674 | $( | 666 | $( |
diff --git a/crates/hir_def/src/path.rs b/crates/hir_def/src/path.rs index 3dd7c3cbb..e34cd7f2f 100644 --- a/crates/hir_def/src/path.rs +++ b/crates/hir_def/src/path.rs | |||
@@ -87,7 +87,7 @@ impl ModPath { | |||
87 | 87 | ||
88 | /// If this path is a single identifier, like `foo`, return its name. | 88 | /// If this path is a single identifier, like `foo`, return its name. |
89 | pub fn as_ident(&self) -> Option<&Name> { | 89 | pub fn as_ident(&self) -> Option<&Name> { |
90 | if self.kind != PathKind::Plain || self.segments.len() > 1 { | 90 | if !self.is_ident() { |
91 | return None; | 91 | return None; |
92 | } | 92 | } |
93 | self.segments.first() | 93 | self.segments.first() |
diff --git a/crates/hir_def/src/type_ref.rs b/crates/hir_def/src/type_ref.rs index ae93d0d10..049b2e462 100644 --- a/crates/hir_def/src/type_ref.rs +++ b/crates/hir_def/src/type_ref.rs | |||
@@ -159,6 +159,8 @@ impl TypeRef { | |||
159 | ast::Type::DynTraitType(inner) => { | 159 | ast::Type::DynTraitType(inner) => { |
160 | TypeRef::DynTrait(type_bounds_from_ast(ctx, inner.type_bound_list())) | 160 | TypeRef::DynTrait(type_bounds_from_ast(ctx, inner.type_bound_list())) |
161 | } | 161 | } |
162 | // FIXME: Macros in type position are not yet supported. | ||
163 | ast::Type::MacroType(_) => TypeRef::Error, | ||
162 | } | 164 | } |
163 | } | 165 | } |
164 | 166 | ||
diff --git a/crates/hir_expand/src/hygiene.rs b/crates/hir_expand/src/hygiene.rs index 8db581b77..c8ea81210 100644 --- a/crates/hir_expand/src/hygiene.rs +++ b/crates/hir_expand/src/hygiene.rs | |||
@@ -76,6 +76,8 @@ pub struct HygieneFrame { | |||
76 | 76 | ||
77 | impl HygieneFrames { | 77 | impl HygieneFrames { |
78 | fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Self { | 78 | fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Self { |
79 | // Note that this intentionally avoids the `hygiene_frame` query to avoid blowing up memory | ||
80 | // usage. The query is only helpful for nested `HygieneFrame`s as it avoids redundant work. | ||
79 | HygieneFrames(Arc::new(HygieneFrame::new(db, file_id))) | 81 | HygieneFrames(Arc::new(HygieneFrame::new(db, file_id))) |
80 | } | 82 | } |
81 | 83 | ||
diff --git a/crates/hir_expand/src/proc_macro.rs b/crates/hir_expand/src/proc_macro.rs index 1923daca5..75e950816 100644 --- a/crates/hir_expand/src/proc_macro.rs +++ b/crates/hir_expand/src/proc_macro.rs | |||
@@ -135,7 +135,6 @@ mod tests { | |||
135 | let result = format!("{:#?}", remove_derive_attrs(&tt).unwrap()); | 135 | let result = format!("{:#?}", remove_derive_attrs(&tt).unwrap()); |
136 | 136 | ||
137 | assert_eq_text!( | 137 | assert_eq_text!( |
138 | &result, | ||
139 | r#" | 138 | r#" |
140 | SUBTREE $ | 139 | SUBTREE $ |
141 | PUNCH # [alone] 0 | 140 | PUNCH # [alone] 0 |
@@ -150,7 +149,8 @@ SUBTREE $ | |||
150 | PUNCH : [alone] 19 | 149 | PUNCH : [alone] 19 |
151 | IDENT u32 20 | 150 | IDENT u32 20 |
152 | "# | 151 | "# |
153 | .trim() | 152 | .trim(), |
153 | &result | ||
154 | ); | 154 | ); |
155 | } | 155 | } |
156 | } | 156 | } |
diff --git a/crates/hir_ty/src/tests.rs b/crates/hir_ty/src/tests.rs index 3b1675f0b..5ff755321 100644 --- a/crates/hir_ty/src/tests.rs +++ b/crates/hir_ty/src/tests.rs | |||
@@ -26,7 +26,7 @@ use once_cell::race::OnceBool; | |||
26 | use stdx::format_to; | 26 | use stdx::format_to; |
27 | use syntax::{ | 27 | use syntax::{ |
28 | algo, | 28 | algo, |
29 | ast::{self, AstNode}, | 29 | ast::{self, AstNode, NameOwner}, |
30 | SyntaxNode, | 30 | SyntaxNode, |
31 | }; | 31 | }; |
32 | use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry}; | 32 | use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry}; |
@@ -153,7 +153,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { | |||
153 | }); | 153 | }); |
154 | for (node, ty) in &types { | 154 | for (node, ty) in &types { |
155 | let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) { | 155 | let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) { |
156 | (self_param.self_token().unwrap().text_range(), "self".to_string()) | 156 | (self_param.name().unwrap().syntax().text_range(), "self".to_string()) |
157 | } else { | 157 | } else { |
158 | (node.value.text_range(), node.value.text().to_string().replace("\n", " ")) | 158 | (node.value.text_range(), node.value.text().to_string().replace("\n", " ")) |
159 | }; | 159 | }; |
diff --git a/crates/ide/src/diagnostics/fixes.rs b/crates/ide/src/diagnostics/fixes.rs index e4335119b..579d5a308 100644 --- a/crates/ide/src/diagnostics/fixes.rs +++ b/crates/ide/src/diagnostics/fixes.rs | |||
@@ -140,7 +140,7 @@ impl DiagnosticWithFix for IncorrectCase { | |||
140 | rename_with_semantics(sema, file_position, &self.suggested_text).ok()?; | 140 | rename_with_semantics(sema, file_position, &self.suggested_text).ok()?; |
141 | 141 | ||
142 | let label = format!("Rename to {}", self.suggested_text); | 142 | let label = format!("Rename to {}", self.suggested_text); |
143 | Some(Fix::new(&label, rename_changes.info, rename_changes.range)) | 143 | Some(Fix::new(&label, rename_changes, frange.range)) |
144 | } | 144 | } |
145 | } | 145 | } |
146 | 146 | ||
diff --git a/crates/ide/src/display/navigation_target.rs b/crates/ide/src/display/navigation_target.rs index 685052e7f..00e601244 100644 --- a/crates/ide/src/display/navigation_target.rs +++ b/crates/ide/src/display/navigation_target.rs | |||
@@ -400,15 +400,13 @@ impl TryToNav for hir::GenericParam { | |||
400 | impl ToNav for hir::Local { | 400 | impl ToNav for hir::Local { |
401 | fn to_nav(&self, db: &RootDatabase) -> NavigationTarget { | 401 | fn to_nav(&self, db: &RootDatabase) -> NavigationTarget { |
402 | let src = self.source(db); | 402 | let src = self.source(db); |
403 | let (node, focus_range) = match &src.value { | 403 | let (node, name) = match &src.value { |
404 | Either::Left(bind_pat) => ( | 404 | Either::Left(bind_pat) => (bind_pat.syntax().clone(), bind_pat.name()), |
405 | bind_pat.syntax().clone(), | 405 | Either::Right(it) => (it.syntax().clone(), it.name()), |
406 | bind_pat | ||
407 | .name() | ||
408 | .map(|it| src.with_value(&it.syntax().clone()).original_file_range(db).range), | ||
409 | ), | ||
410 | Either::Right(it) => (it.syntax().clone(), it.self_token().map(|it| it.text_range())), | ||
411 | }; | 406 | }; |
407 | let focus_range = | ||
408 | name.map(|it| src.with_value(&it.syntax().clone()).original_file_range(db).range); | ||
409 | |||
412 | let full_range = src.with_value(&node).original_file_range(db); | 410 | let full_range = src.with_value(&node).original_file_range(db); |
413 | let name = match self.name(db) { | 411 | let name = match self.name(db) { |
414 | Some(it) => it.to_string().into(), | 412 | Some(it) => it.to_string().into(), |
diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index de10406bc..1f08d7810 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs | |||
@@ -438,10 +438,10 @@ fn get_symbol_fragment(db: &dyn HirDatabase, field_or_assoc: &FieldOrAssocItem) | |||
438 | FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), | 438 | FieldOrAssocItem::Field(field) => format!("#structfield.{}", field.name(db)), |
439 | FieldOrAssocItem::AssocItem(assoc) => match assoc { | 439 | FieldOrAssocItem::AssocItem(assoc) => match assoc { |
440 | AssocItem::Function(function) => { | 440 | AssocItem::Function(function) => { |
441 | let is_trait_method = matches!( | 441 | let is_trait_method = function |
442 | function.as_assoc_item(db).map(|assoc| assoc.container(db)), | 442 | .as_assoc_item(db) |
443 | Some(AssocItemContainer::Trait(..)) | 443 | .and_then(|assoc| assoc.containing_trait(db)) |
444 | ); | 444 | .is_some(); |
445 | // This distinction may get more complicated when specialization is available. | 445 | // This distinction may get more complicated when specialization is available. |
446 | // Rustdoc makes this decision based on whether a method 'has defaultness'. | 446 | // Rustdoc makes this decision based on whether a method 'has defaultness'. |
447 | // Currently this is only the case for provided trait methods. | 447 | // Currently this is only the case for provided trait methods. |
diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs index 988a5668f..a1d2bce1d 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs | |||
@@ -55,11 +55,6 @@ pub(crate) fn goto_definition( | |||
55 | } else { | 55 | } else { |
56 | reference_definition(&sema, Either::Left(<)).to_vec() | 56 | reference_definition(&sema, Either::Left(<)).to_vec() |
57 | }, | 57 | }, |
58 | ast::SelfParam(self_param) => { | ||
59 | let def = NameClass::classify_self_param(&sema, &self_param)?.referenced_or_defined(sema.db); | ||
60 | let nav = def.try_to_nav(sema.db)?; | ||
61 | vec![nav] | ||
62 | }, | ||
63 | _ => return None, | 58 | _ => return None, |
64 | } | 59 | } |
65 | }; | 60 | }; |
diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index 6022bd275..2024acd94 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs | |||
@@ -98,7 +98,6 @@ pub(crate) fn hover( | |||
98 | ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|d| d.referenced(sema.db)), | 98 | ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|d| d.referenced(sema.db)), |
99 | ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime) | 99 | ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime) |
100 | .map_or_else(|| NameRefClass::classify_lifetime(&sema, &lifetime).map(|d| d.referenced(sema.db)), |d| d.defined(sema.db)), | 100 | .map_or_else(|| NameRefClass::classify_lifetime(&sema, &lifetime).map(|d| d.referenced(sema.db)), |d| d.defined(sema.db)), |
101 | ast::SelfParam(self_param) => NameClass::classify_self_param(&sema, &self_param).and_then(|d| d.defined(sema.db)), | ||
102 | _ => None, | 101 | _ => None, |
103 | } | 102 | } |
104 | }; | 103 | }; |
@@ -3223,7 +3222,7 @@ impl Foo { | |||
3223 | } | 3222 | } |
3224 | "#, | 3223 | "#, |
3225 | expect![[r#" | 3224 | expect![[r#" |
3226 | *&self* | 3225 | *self* |
3227 | 3226 | ||
3228 | ```rust | 3227 | ```rust |
3229 | &Foo | 3228 | &Foo |
@@ -3243,7 +3242,7 @@ impl Foo { | |||
3243 | } | 3242 | } |
3244 | "#, | 3243 | "#, |
3245 | expect![[r#" | 3244 | expect![[r#" |
3246 | *self: Arc<Foo>* | 3245 | *self* |
3247 | 3246 | ||
3248 | ```rust | 3247 | ```rust |
3249 | Arc<Foo> | 3248 | Arc<Foo> |
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index f8d69382e..3abbb14c6 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs | |||
@@ -86,18 +86,15 @@ pub use completion::{ | |||
86 | InsertTextFormat, | 86 | InsertTextFormat, |
87 | }; | 87 | }; |
88 | pub use hir::{Documentation, Semantics}; | 88 | pub use hir::{Documentation, Semantics}; |
89 | pub use ide_db::base_db::{ | ||
90 | Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRoot, | ||
91 | SourceRootId, | ||
92 | }; | ||
93 | pub use ide_db::{ | 89 | pub use ide_db::{ |
90 | base_db::{ | ||
91 | Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, | ||
92 | SourceRoot, SourceRootId, | ||
93 | }, | ||
94 | call_info::CallInfo, | 94 | call_info::CallInfo, |
95 | search::{FileReference, ReferenceAccess, ReferenceKind}, | ||
96 | }; | ||
97 | pub use ide_db::{ | ||
98 | label::Label, | 95 | label::Label, |
99 | line_index::{LineCol, LineIndex}, | 96 | line_index::{LineCol, LineIndex}, |
100 | search::SearchScope, | 97 | search::{FileReference, ReferenceAccess, ReferenceKind, SearchScope}, |
101 | source_change::{FileSystemEdit, SourceChange}, | 98 | source_change::{FileSystemEdit, SourceChange}, |
102 | symbol_index::Query, | 99 | symbol_index::Query, |
103 | RootDatabase, | 100 | RootDatabase, |
@@ -481,6 +478,7 @@ impl Analysis { | |||
481 | position: FilePosition, | 478 | position: FilePosition, |
482 | full_import_path: &str, | 479 | full_import_path: &str, |
483 | imported_name: String, | 480 | imported_name: String, |
481 | import_for_trait_assoc_item: bool, | ||
484 | ) -> Cancelable<Vec<TextEdit>> { | 482 | ) -> Cancelable<Vec<TextEdit>> { |
485 | Ok(self | 483 | Ok(self |
486 | .with_db(|db| { | 484 | .with_db(|db| { |
@@ -490,6 +488,7 @@ impl Analysis { | |||
490 | position, | 488 | position, |
491 | full_import_path, | 489 | full_import_path, |
492 | imported_name, | 490 | imported_name, |
491 | import_for_trait_assoc_item, | ||
493 | ) | 492 | ) |
494 | })? | 493 | })? |
495 | .unwrap_or_default()) | 494 | .unwrap_or_default()) |
@@ -523,7 +522,7 @@ impl Analysis { | |||
523 | &self, | 522 | &self, |
524 | position: FilePosition, | 523 | position: FilePosition, |
525 | new_name: &str, | 524 | new_name: &str, |
526 | ) -> Cancelable<Result<RangeInfo<SourceChange>, RenameError>> { | 525 | ) -> Cancelable<Result<SourceChange, RenameError>> { |
527 | self.with_db(|db| references::rename::rename(db, position, new_name)) | 526 | self.with_db(|db| references::rename::rename(db, position, new_name)) |
528 | } | 527 | } |
529 | 528 | ||
diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 51a2f4327..df9c31aef 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs | |||
@@ -930,6 +930,26 @@ impl Foo { | |||
930 | ); | 930 | ); |
931 | } | 931 | } |
932 | 932 | ||
933 | #[test] | ||
934 | fn test_find_self_refs_decl() { | ||
935 | check( | ||
936 | r#" | ||
937 | struct Foo { bar: i32 } | ||
938 | |||
939 | impl Foo { | ||
940 | fn foo(self$0) { | ||
941 | self; | ||
942 | } | ||
943 | } | ||
944 | "#, | ||
945 | expect![[r#" | ||
946 | self SelfParam FileId(0) 47..51 47..51 SelfParam | ||
947 | |||
948 | FileId(0) 63..67 Other Read | ||
949 | "#]], | ||
950 | ); | ||
951 | } | ||
952 | |||
933 | fn check(ra_fixture: &str, expect: Expect) { | 953 | fn check(ra_fixture: &str, expect: Expect) { |
934 | check_with_scope(ra_fixture, None, expect) | 954 | check_with_scope(ra_fixture, None, expect) |
935 | } | 955 | } |
diff --git a/crates/ide/src/references/rename.rs b/crates/ide/src/references/rename.rs index 9ac4af026..c25bcce50 100644 --- a/crates/ide/src/references/rename.rs +++ b/crates/ide/src/references/rename.rs | |||
@@ -1,27 +1,25 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | use std::{ | 2 | use std::fmt::{self, Display}; |
3 | convert::TryInto, | ||
4 | fmt::{self, Display}, | ||
5 | }; | ||
6 | 3 | ||
7 | use hir::{Module, ModuleDef, ModuleSource, Semantics}; | 4 | use either::Either; |
5 | use hir::{HasSource, InFile, Module, ModuleDef, ModuleSource, Semantics}; | ||
8 | use ide_db::{ | 6 | use ide_db::{ |
9 | base_db::{AnchoredPathBuf, FileId, FileRange, SourceDatabaseExt}, | 7 | base_db::{AnchoredPathBuf, FileId, FileRange}, |
10 | defs::{Definition, NameClass, NameRefClass}, | 8 | defs::{Definition, NameClass, NameRefClass}, |
11 | search::FileReference, | 9 | search::FileReference, |
12 | RootDatabase, | 10 | RootDatabase, |
13 | }; | 11 | }; |
12 | use stdx::assert_never; | ||
14 | use syntax::{ | 13 | use syntax::{ |
15 | algo::find_node_at_offset, | ||
16 | ast::{self, NameOwner}, | 14 | ast::{self, NameOwner}, |
17 | lex_single_syntax_kind, match_ast, AstNode, SyntaxKind, SyntaxNode, SyntaxToken, T, | 15 | lex_single_syntax_kind, AstNode, SyntaxKind, SyntaxNode, T, |
18 | }; | 16 | }; |
19 | use test_utils::mark; | 17 | use test_utils::mark; |
20 | use text_edit::TextEdit; | 18 | use text_edit::TextEdit; |
21 | 19 | ||
22 | use crate::{ | 20 | use crate::{ |
23 | FilePosition, FileSystemEdit, RangeInfo, ReferenceKind, ReferenceSearchResult, SourceChange, | 21 | display::TryToNav, FilePosition, FileSystemEdit, RangeInfo, ReferenceKind, SourceChange, |
24 | TextRange, TextSize, | 22 | TextRange, |
25 | }; | 23 | }; |
26 | 24 | ||
27 | type RenameResult<T> = Result<T, RenameError>; | 25 | type RenameResult<T> = Result<T, RenameError>; |
@@ -50,24 +48,22 @@ pub(crate) fn prepare_rename( | |||
50 | let sema = Semantics::new(db); | 48 | let sema = Semantics::new(db); |
51 | let source_file = sema.parse(position.file_id); | 49 | let source_file = sema.parse(position.file_id); |
52 | let syntax = source_file.syntax(); | 50 | let syntax = source_file.syntax(); |
53 | if let Some(module) = find_module_at_offset(&sema, position, syntax) { | 51 | let range = match &find_name_like(&sema, &syntax, position) |
54 | rename_mod(&sema, position, module, "dummy") | 52 | .ok_or_else(|| format_err!("No references found at position"))? |
55 | } else if let Some(self_token) = | ||
56 | syntax.token_at_offset(position.offset).find(|t| t.kind() == T![self]) | ||
57 | { | 53 | { |
58 | rename_self_to_param(&sema, position, self_token, "dummy") | 54 | NameLike::Name(it) => it.syntax(), |
59 | } else { | 55 | NameLike::NameRef(it) => it.syntax(), |
60 | let RangeInfo { range, .. } = find_all_refs(&sema, position)?; | 56 | NameLike::Lifetime(it) => it.syntax(), |
61 | Ok(RangeInfo::new(range, SourceChange::default())) | ||
62 | } | 57 | } |
63 | .map(|info| RangeInfo::new(info.range, ())) | 58 | .text_range(); |
59 | Ok(RangeInfo::new(range, ())) | ||
64 | } | 60 | } |
65 | 61 | ||
66 | pub(crate) fn rename( | 62 | pub(crate) fn rename( |
67 | db: &RootDatabase, | 63 | db: &RootDatabase, |
68 | position: FilePosition, | 64 | position: FilePosition, |
69 | new_name: &str, | 65 | new_name: &str, |
70 | ) -> RenameResult<RangeInfo<SourceChange>> { | 66 | ) -> RenameResult<SourceChange> { |
71 | let sema = Semantics::new(db); | 67 | let sema = Semantics::new(db); |
72 | rename_with_semantics(&sema, position, new_name) | 68 | rename_with_semantics(&sema, position, new_name) |
73 | } | 69 | } |
@@ -76,18 +72,15 @@ pub(crate) fn rename_with_semantics( | |||
76 | sema: &Semantics<RootDatabase>, | 72 | sema: &Semantics<RootDatabase>, |
77 | position: FilePosition, | 73 | position: FilePosition, |
78 | new_name: &str, | 74 | new_name: &str, |
79 | ) -> RenameResult<RangeInfo<SourceChange>> { | 75 | ) -> RenameResult<SourceChange> { |
80 | let source_file = sema.parse(position.file_id); | 76 | let source_file = sema.parse(position.file_id); |
81 | let syntax = source_file.syntax(); | 77 | let syntax = source_file.syntax(); |
82 | 78 | ||
83 | if let Some(module) = find_module_at_offset(&sema, position, syntax) { | 79 | let def = find_definition(sema, syntax, position) |
84 | rename_mod(&sema, position, module, new_name) | 80 | .ok_or_else(|| format_err!("No references found at position"))?; |
85 | } else if let Some(self_token) = | 81 | match def { |
86 | syntax.token_at_offset(position.offset).find(|t| t.kind() == T![self]) | 82 | Definition::ModuleDef(ModuleDef::Module(module)) => rename_mod(&sema, module, new_name), |
87 | { | 83 | def => rename_reference(sema, def, new_name), |
88 | rename_self_to_param(&sema, position, self_token, new_name) | ||
89 | } else { | ||
90 | rename_reference(&sema, position, new_name) | ||
91 | } | 84 | } |
92 | } | 85 | } |
93 | 86 | ||
@@ -98,17 +91,12 @@ pub(crate) fn will_rename_file( | |||
98 | ) -> Option<SourceChange> { | 91 | ) -> Option<SourceChange> { |
99 | let sema = Semantics::new(db); | 92 | let sema = Semantics::new(db); |
100 | let module = sema.to_module_def(file_id)?; | 93 | let module = sema.to_module_def(file_id)?; |
101 | 94 | let mut change = rename_mod(&sema, module, new_name_stem).ok()?; | |
102 | let decl = module.declaration_source(db)?; | ||
103 | let range = decl.value.name()?.syntax().text_range(); | ||
104 | |||
105 | let position = FilePosition { file_id: decl.file_id.original_file(db), offset: range.start() }; | ||
106 | let mut change = rename_mod(&sema, position, module, new_name_stem).ok()?.info; | ||
107 | change.file_system_edits.clear(); | 95 | change.file_system_edits.clear(); |
108 | Some(change) | 96 | Some(change) |
109 | } | 97 | } |
110 | 98 | ||
111 | #[derive(Debug, PartialEq)] | 99 | #[derive(Copy, Clone, Debug, PartialEq)] |
112 | enum IdentifierKind { | 100 | enum IdentifierKind { |
113 | Ident, | 101 | Ident, |
114 | Lifetime, | 102 | Lifetime, |
@@ -135,40 +123,51 @@ fn check_identifier(new_name: &str) -> RenameResult<IdentifierKind> { | |||
135 | } | 123 | } |
136 | } | 124 | } |
137 | 125 | ||
138 | fn find_module_at_offset( | 126 | enum NameLike { |
127 | Name(ast::Name), | ||
128 | NameRef(ast::NameRef), | ||
129 | Lifetime(ast::Lifetime), | ||
130 | } | ||
131 | |||
132 | fn find_name_like( | ||
139 | sema: &Semantics<RootDatabase>, | 133 | sema: &Semantics<RootDatabase>, |
140 | position: FilePosition, | ||
141 | syntax: &SyntaxNode, | 134 | syntax: &SyntaxNode, |
142 | ) -> Option<Module> { | 135 | position: FilePosition, |
143 | let ident = syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::IDENT)?; | 136 | ) -> Option<NameLike> { |
144 | 137 | let namelike = if let Some(name_ref) = | |
145 | let module = match_ast! { | 138 | sema.find_node_at_offset_with_descend::<ast::NameRef>(syntax, position.offset) |
146 | match (ident.parent()) { | 139 | { |
147 | ast::NameRef(name_ref) => { | 140 | NameLike::NameRef(name_ref) |
148 | match NameRefClass::classify(sema, &name_ref)? { | 141 | } else if let Some(name) = |
149 | NameRefClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module, | 142 | sema.find_node_at_offset_with_descend::<ast::Name>(syntax, position.offset) |
150 | _ => return None, | 143 | { |
151 | } | 144 | NameLike::Name(name) |
152 | }, | 145 | } else if let Some(lifetime) = |
153 | ast::Name(name) => { | 146 | sema.find_node_at_offset_with_descend::<ast::Lifetime>(syntax, position.offset) |
154 | match NameClass::classify(&sema, &name)? { | 147 | { |
155 | NameClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module, | 148 | NameLike::Lifetime(lifetime) |
156 | _ => return None, | 149 | } else { |
157 | } | 150 | return None; |
158 | }, | ||
159 | _ => return None, | ||
160 | } | ||
161 | }; | 151 | }; |
162 | 152 | Some(namelike) | |
163 | Some(module) | ||
164 | } | 153 | } |
165 | 154 | ||
166 | fn find_all_refs( | 155 | fn find_definition( |
167 | sema: &Semantics<RootDatabase>, | 156 | sema: &Semantics<RootDatabase>, |
157 | syntax: &SyntaxNode, | ||
168 | position: FilePosition, | 158 | position: FilePosition, |
169 | ) -> RenameResult<RangeInfo<ReferenceSearchResult>> { | 159 | ) -> Option<Definition> { |
170 | crate::references::find_all_refs(sema, position, None) | 160 | let def = match find_name_like(sema, syntax, position)? { |
171 | .ok_or_else(|| format_err!("No references found at position")) | 161 | NameLike::Name(name) => NameClass::classify(sema, &name)?.referenced_or_defined(sema.db), |
162 | NameLike::NameRef(name_ref) => NameRefClass::classify(sema, &name_ref)?.referenced(sema.db), | ||
163 | NameLike::Lifetime(lifetime) => NameRefClass::classify_lifetime(sema, &lifetime) | ||
164 | .map(|class| NameRefClass::referenced(class, sema.db)) | ||
165 | .or_else(|| { | ||
166 | NameClass::classify_lifetime(sema, &lifetime) | ||
167 | .map(|it| it.referenced_or_defined(sema.db)) | ||
168 | })?, | ||
169 | }; | ||
170 | Some(def) | ||
172 | } | 171 | } |
173 | 172 | ||
174 | fn source_edit_from_references( | 173 | fn source_edit_from_references( |
@@ -242,72 +241,84 @@ fn edit_text_range_for_record_field_expr_or_pat( | |||
242 | 241 | ||
243 | fn rename_mod( | 242 | fn rename_mod( |
244 | sema: &Semantics<RootDatabase>, | 243 | sema: &Semantics<RootDatabase>, |
245 | position: FilePosition, | ||
246 | module: Module, | 244 | module: Module, |
247 | new_name: &str, | 245 | new_name: &str, |
248 | ) -> RenameResult<RangeInfo<SourceChange>> { | 246 | ) -> RenameResult<SourceChange> { |
249 | if IdentifierKind::Ident != check_identifier(new_name)? { | 247 | if IdentifierKind::Ident != check_identifier(new_name)? { |
250 | bail!("Invalid name `{0}`: cannot rename module to {0}", new_name); | 248 | bail!("Invalid name `{0}`: cannot rename module to {0}", new_name); |
251 | } | 249 | } |
252 | 250 | ||
253 | let mut source_change = SourceChange::default(); | 251 | let mut source_change = SourceChange::default(); |
254 | 252 | ||
255 | let src = module.definition_source(sema.db); | 253 | let InFile { file_id, value: def_source } = module.definition_source(sema.db); |
256 | let file_id = src.file_id.original_file(sema.db); | 254 | let file_id = file_id.original_file(sema.db); |
257 | match src.value { | 255 | if let ModuleSource::SourceFile(..) = def_source { |
258 | ModuleSource::SourceFile(..) => { | 256 | // mod is defined in path/to/dir/mod.rs |
259 | // mod is defined in path/to/dir/mod.rs | 257 | let path = if module.is_mod_rs(sema.db) { |
260 | let path = if module.is_mod_rs(sema.db) { | 258 | format!("../{}/mod.rs", new_name) |
261 | format!("../{}/mod.rs", new_name) | 259 | } else { |
262 | } else { | 260 | format!("{}.rs", new_name) |
263 | format!("{}.rs", new_name) | 261 | }; |
264 | }; | 262 | let dst = AnchoredPathBuf { anchor: file_id, path }; |
265 | let dst = AnchoredPathBuf { anchor: file_id, path }; | 263 | let move_file = FileSystemEdit::MoveFile { src: file_id, dst }; |
266 | let move_file = FileSystemEdit::MoveFile { src: file_id, dst }; | 264 | source_change.push_file_system_edit(move_file); |
267 | source_change.push_file_system_edit(move_file); | 265 | } |
268 | } | 266 | |
269 | ModuleSource::Module(..) => {} | 267 | if let Some(InFile { file_id, value: decl_source }) = module.declaration_source(sema.db) { |
270 | } | 268 | let file_id = file_id.original_file(sema.db); |
271 | 269 | match decl_source.name() { | |
272 | if let Some(src) = module.declaration_source(sema.db) { | 270 | Some(name) => source_change.insert_source_edit( |
273 | let file_id = src.file_id.original_file(sema.db); | 271 | file_id, |
274 | let name = src.value.name().unwrap(); | 272 | TextEdit::replace(name.syntax().text_range(), new_name.to_string()), |
275 | source_change.insert_source_edit( | 273 | ), |
276 | file_id, | 274 | _ => unreachable!(), |
277 | TextEdit::replace(name.syntax().text_range(), new_name.into()), | 275 | }; |
278 | ); | ||
279 | } | 276 | } |
280 | 277 | let def = Definition::ModuleDef(ModuleDef::Module(module)); | |
281 | let RangeInfo { range, info: refs } = find_all_refs(sema, position)?; | 278 | let usages = def.usages(sema).all(); |
282 | let ref_edits = refs.references().iter().map(|(&file_id, references)| { | 279 | let ref_edits = usages.iter().map(|(&file_id, references)| { |
283 | source_edit_from_references(sema, file_id, references, new_name) | 280 | source_edit_from_references(sema, file_id, references, new_name) |
284 | }); | 281 | }); |
285 | source_change.extend(ref_edits); | 282 | source_change.extend(ref_edits); |
286 | 283 | ||
287 | Ok(RangeInfo::new(range, source_change)) | 284 | Ok(source_change) |
288 | } | 285 | } |
289 | 286 | ||
290 | fn rename_to_self( | 287 | fn rename_to_self(sema: &Semantics<RootDatabase>, local: hir::Local) -> RenameResult<SourceChange> { |
291 | sema: &Semantics<RootDatabase>, | 288 | if assert_never!(local.is_self(sema.db)) { |
292 | position: FilePosition, | 289 | bail!("rename_to_self invoked on self"); |
293 | ) -> Result<RangeInfo<SourceChange>, RenameError> { | 290 | } |
294 | let source_file = sema.parse(position.file_id); | 291 | |
295 | let syn = source_file.syntax(); | 292 | let fn_def = match local.parent(sema.db) { |
293 | hir::DefWithBody::Function(func) => func, | ||
294 | _ => bail!("Cannot rename non-param local to self"), | ||
295 | }; | ||
296 | |||
297 | // FIXME: reimplement this on the hir instead | ||
298 | // as of the time of this writing params in hir don't keep their names | ||
299 | let fn_ast = | ||
300 | fn_def.source(sema.db).ok_or(format_err!("Cannot rename non-param local to self"))?.value; | ||
296 | 301 | ||
297 | let (fn_def, fn_ast) = find_node_at_offset::<ast::Fn>(syn, position.offset) | 302 | let first_param_range = fn_ast |
298 | .and_then(|fn_ast| sema.to_def(&fn_ast).zip(Some(fn_ast))) | ||
299 | .ok_or_else(|| format_err!("No surrounding method declaration found"))?; | ||
300 | let param_range = fn_ast | ||
301 | .param_list() | 303 | .param_list() |
302 | .and_then(|p| p.params().next()) | 304 | .and_then(|p| p.params().next()) |
303 | .ok_or_else(|| format_err!("Method has no parameters"))? | 305 | .ok_or_else(|| format_err!("Method has no parameters"))? |
304 | .syntax() | 306 | .syntax() |
305 | .text_range(); | 307 | .text_range(); |
306 | if !param_range.contains(position.offset) { | 308 | let InFile { file_id, value: local_source } = local.source(sema.db); |
307 | bail!("Only the first parameter can be self"); | 309 | match local_source { |
310 | either::Either::Left(pat) | ||
311 | if !first_param_range.contains_range(pat.syntax().text_range()) => | ||
312 | { | ||
313 | bail!("Only the first parameter can be self"); | ||
314 | } | ||
315 | _ => (), | ||
308 | } | 316 | } |
309 | 317 | ||
310 | let impl_block = find_node_at_offset::<ast::Impl>(syn, position.offset) | 318 | let impl_block = fn_ast |
319 | .syntax() | ||
320 | .ancestors() | ||
321 | .find_map(|node| ast::Impl::cast(node)) | ||
311 | .and_then(|def| sema.to_def(&def)) | 322 | .and_then(|def| sema.to_def(&def)) |
312 | .ok_or_else(|| format_err!("No impl block found for function"))?; | 323 | .ok_or_else(|| format_err!("No impl block found for function"))?; |
313 | if fn_def.self_param(sema.db).is_some() { | 324 | if fn_def.self_param(sema.db).is_some() { |
@@ -331,25 +342,21 @@ fn rename_to_self( | |||
331 | bail!("Parameter type differs from impl block type"); | 342 | bail!("Parameter type differs from impl block type"); |
332 | } | 343 | } |
333 | 344 | ||
334 | let RangeInfo { range, info: refs } = find_all_refs(sema, position)?; | 345 | let def = Definition::Local(local); |
335 | 346 | let usages = def.usages(sema).all(); | |
336 | let mut source_change = SourceChange::default(); | 347 | let mut source_change = SourceChange::default(); |
337 | source_change.extend(refs.references().iter().map(|(&file_id, references)| { | 348 | source_change.extend(usages.iter().map(|(&file_id, references)| { |
338 | source_edit_from_references(sema, file_id, references, "self") | 349 | source_edit_from_references(sema, file_id, references, "self") |
339 | })); | 350 | })); |
340 | source_change.insert_source_edit( | 351 | source_change.insert_source_edit( |
341 | position.file_id, | 352 | file_id.original_file(sema.db), |
342 | TextEdit::replace(param_range, String::from(self_param)), | 353 | TextEdit::replace(first_param_range, String::from(self_param)), |
343 | ); | 354 | ); |
344 | 355 | ||
345 | Ok(RangeInfo::new(range, source_change)) | 356 | Ok(source_change) |
346 | } | 357 | } |
347 | 358 | ||
348 | fn text_edit_from_self_param( | 359 | fn text_edit_from_self_param(self_param: &ast::SelfParam, new_name: &str) -> Option<TextEdit> { |
349 | syn: &SyntaxNode, | ||
350 | self_param: &ast::SelfParam, | ||
351 | new_name: &str, | ||
352 | ) -> Option<TextEdit> { | ||
353 | fn target_type_name(impl_def: &ast::Impl) -> Option<String> { | 360 | fn target_type_name(impl_def: &ast::Impl) -> Option<String> { |
354 | if let Some(ast::Type::PathType(p)) = impl_def.self_ty() { | 361 | if let Some(ast::Type::PathType(p)) = impl_def.self_ty() { |
355 | return Some(p.path()?.segment()?.name_ref()?.text().to_string()); | 362 | return Some(p.path()?.segment()?.name_ref()?.text().to_string()); |
@@ -357,7 +364,7 @@ fn text_edit_from_self_param( | |||
357 | None | 364 | None |
358 | } | 365 | } |
359 | 366 | ||
360 | let impl_def = find_node_at_offset::<ast::Impl>(syn, self_param.syntax().text_range().start())?; | 367 | let impl_def = self_param.syntax().ancestors().find_map(|it| ast::Impl::cast(it))?; |
361 | let type_name = target_type_name(&impl_def)?; | 368 | let type_name = target_type_name(&impl_def)?; |
362 | 369 | ||
363 | let mut replacement_text = String::from(new_name); | 370 | let mut replacement_text = String::from(new_name); |
@@ -374,96 +381,119 @@ fn text_edit_from_self_param( | |||
374 | 381 | ||
375 | fn rename_self_to_param( | 382 | fn rename_self_to_param( |
376 | sema: &Semantics<RootDatabase>, | 383 | sema: &Semantics<RootDatabase>, |
377 | position: FilePosition, | 384 | local: hir::Local, |
378 | self_token: SyntaxToken, | ||
379 | new_name: &str, | 385 | new_name: &str, |
380 | ) -> Result<RangeInfo<SourceChange>, RenameError> { | 386 | identifier_kind: IdentifierKind, |
381 | let ident_kind = check_identifier(new_name)?; | 387 | ) -> RenameResult<SourceChange> { |
382 | match ident_kind { | 388 | let (file_id, self_param) = match local.source(sema.db) { |
383 | IdentifierKind::Lifetime => bail!("Invalid name `{}`: not an identifier", new_name), | 389 | InFile { file_id, value: Either::Right(self_param) } => (file_id, self_param), |
384 | IdentifierKind::ToSelf => { | 390 | _ => { |
385 | // no-op | 391 | assert_never!(true, "rename_self_to_param invoked on a non-self local"); |
386 | mark::hit!(rename_self_to_self); | 392 | bail!("rename_self_to_param invoked on a non-self local"); |
387 | return Ok(RangeInfo::new(self_token.text_range(), SourceChange::default())); | ||
388 | } | ||
389 | _ => (), | ||
390 | } | ||
391 | let source_file = sema.parse(position.file_id); | ||
392 | let syn = source_file.syntax(); | ||
393 | |||
394 | let text = sema.db.file_text(position.file_id); | ||
395 | let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset) | ||
396 | .ok_or_else(|| format_err!("No surrounding method declaration found"))?; | ||
397 | let search_range = fn_def.syntax().text_range(); | ||
398 | |||
399 | let mut source_change = SourceChange::default(); | ||
400 | |||
401 | for (idx, _) in text.match_indices("self") { | ||
402 | let offset: TextSize = idx.try_into().unwrap(); | ||
403 | if !search_range.contains_inclusive(offset) { | ||
404 | continue; | ||
405 | } | 393 | } |
406 | if let Some(ref usage) = syn.token_at_offset(offset).find(|t| t.kind() == T![self]) { | 394 | }; |
407 | let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) { | ||
408 | text_edit_from_self_param(syn, self_param, new_name) | ||
409 | .ok_or_else(|| format_err!("No target type found"))? | ||
410 | } else { | ||
411 | TextEdit::replace(usage.text_range(), String::from(new_name)) | ||
412 | }; | ||
413 | source_change.insert_source_edit(position.file_id, edit); | ||
414 | } | ||
415 | } | ||
416 | 395 | ||
417 | if source_change.source_file_edits.len() > 1 && ident_kind == IdentifierKind::Underscore { | 396 | let def = Definition::Local(local); |
397 | let usages = def.usages(sema).all(); | ||
398 | let edit = text_edit_from_self_param(&self_param, new_name) | ||
399 | .ok_or_else(|| format_err!("No target type found"))?; | ||
400 | if usages.len() > 1 && identifier_kind == IdentifierKind::Underscore { | ||
418 | bail!("Cannot rename reference to `_` as it is being referenced multiple times"); | 401 | bail!("Cannot rename reference to `_` as it is being referenced multiple times"); |
419 | } | 402 | } |
420 | 403 | let mut source_change = SourceChange::default(); | |
421 | let range = ast::SelfParam::cast(self_token.parent()) | 404 | source_change.insert_source_edit(file_id.original_file(sema.db), edit); |
422 | .map_or(self_token.text_range(), |p| p.syntax().text_range()); | 405 | source_change.extend(usages.iter().map(|(&file_id, references)| { |
423 | 406 | source_edit_from_references(sema, file_id, &references, new_name) | |
424 | Ok(RangeInfo::new(range, source_change)) | 407 | })); |
408 | Ok(source_change) | ||
425 | } | 409 | } |
426 | 410 | ||
427 | fn rename_reference( | 411 | fn rename_reference( |
428 | sema: &Semantics<RootDatabase>, | 412 | sema: &Semantics<RootDatabase>, |
429 | position: FilePosition, | 413 | def: Definition, |
430 | new_name: &str, | 414 | new_name: &str, |
431 | ) -> Result<RangeInfo<SourceChange>, RenameError> { | 415 | ) -> RenameResult<SourceChange> { |
432 | let ident_kind = check_identifier(new_name)?; | 416 | let ident_kind = check_identifier(new_name)?; |
433 | let RangeInfo { range, info: refs } = find_all_refs(sema, position)?; | ||
434 | 417 | ||
435 | match (ident_kind, &refs.declaration.kind) { | 418 | let def_is_lbl_or_lt = matches!(def, |
436 | (IdentifierKind::ToSelf, ReferenceKind::Lifetime) | 419 | Definition::GenericParam(hir::GenericParam::LifetimeParam(_)) |
437 | | (IdentifierKind::Underscore, ReferenceKind::Lifetime) | 420 | | Definition::Label(_) |
438 | | (IdentifierKind::Ident, ReferenceKind::Lifetime) => { | 421 | ); |
422 | match (ident_kind, def) { | ||
423 | (IdentifierKind::ToSelf, _) | ||
424 | | (IdentifierKind::Underscore, _) | ||
425 | | (IdentifierKind::Ident, _) | ||
426 | if def_is_lbl_or_lt => | ||
427 | { | ||
439 | mark::hit!(rename_not_a_lifetime_ident_ref); | 428 | mark::hit!(rename_not_a_lifetime_ident_ref); |
440 | bail!("Invalid name `{}`: not a lifetime identifier", new_name) | 429 | bail!("Invalid name `{}`: not a lifetime identifier", new_name) |
441 | } | 430 | } |
442 | (IdentifierKind::Lifetime, ReferenceKind::Lifetime) => mark::hit!(rename_lifetime), | 431 | (IdentifierKind::Lifetime, _) if def_is_lbl_or_lt => mark::hit!(rename_lifetime), |
443 | (IdentifierKind::Lifetime, _) => { | 432 | (IdentifierKind::Lifetime, _) => { |
444 | mark::hit!(rename_not_an_ident_ref); | 433 | mark::hit!(rename_not_an_ident_ref); |
445 | bail!("Invalid name `{}`: not an identifier", new_name) | 434 | bail!("Invalid name `{}`: not an identifier", new_name) |
446 | } | 435 | } |
447 | (IdentifierKind::ToSelf, ReferenceKind::SelfParam) => { | 436 | (IdentifierKind::ToSelf, Definition::Local(local)) if local.is_self(sema.db) => { |
448 | unreachable!("rename_self_to_param should've been called instead") | 437 | // no-op |
438 | mark::hit!(rename_self_to_self); | ||
439 | return Ok(SourceChange::default()); | ||
449 | } | 440 | } |
450 | (IdentifierKind::ToSelf, _) => { | 441 | (ident_kind, Definition::Local(local)) if local.is_self(sema.db) => { |
451 | mark::hit!(rename_to_self); | 442 | mark::hit!(rename_self_to_param); |
452 | return rename_to_self(sema, position); | 443 | return rename_self_to_param(sema, local, new_name, ident_kind); |
453 | } | 444 | } |
454 | (IdentifierKind::Underscore, _) if !refs.references.is_empty() => { | 445 | (IdentifierKind::ToSelf, Definition::Local(local)) => { |
455 | mark::hit!(rename_underscore_multiple); | 446 | mark::hit!(rename_to_self); |
456 | bail!("Cannot rename reference to `_` as it is being referenced multiple times") | 447 | return rename_to_self(sema, local); |
457 | } | 448 | } |
449 | (IdentifierKind::ToSelf, _) => bail!("Invalid name `{}`: not an identifier", new_name), | ||
458 | (IdentifierKind::Ident, _) | (IdentifierKind::Underscore, _) => mark::hit!(rename_ident), | 450 | (IdentifierKind::Ident, _) | (IdentifierKind::Underscore, _) => mark::hit!(rename_ident), |
459 | } | 451 | } |
460 | 452 | ||
453 | let usages = def.usages(sema).all(); | ||
454 | if !usages.is_empty() && ident_kind == IdentifierKind::Underscore { | ||
455 | mark::hit!(rename_underscore_multiple); | ||
456 | bail!("Cannot rename reference to `_` as it is being referenced multiple times"); | ||
457 | } | ||
461 | let mut source_change = SourceChange::default(); | 458 | let mut source_change = SourceChange::default(); |
462 | source_change.extend(refs.into_iter().map(|(file_id, references)| { | 459 | source_change.extend(usages.iter().map(|(&file_id, references)| { |
463 | source_edit_from_references(sema, file_id, &references, new_name) | 460 | source_edit_from_references(sema, file_id, &references, new_name) |
464 | })); | 461 | })); |
465 | 462 | ||
466 | Ok(RangeInfo::new(range, source_change)) | 463 | let (file_id, edit) = source_edit_from_def(sema, def, new_name)?; |
464 | source_change.insert_source_edit(file_id, edit); | ||
465 | Ok(source_change) | ||
466 | } | ||
467 | |||
468 | fn source_edit_from_def( | ||
469 | sema: &Semantics<RootDatabase>, | ||
470 | def: Definition, | ||
471 | new_name: &str, | ||
472 | ) -> RenameResult<(FileId, TextEdit)> { | ||
473 | let nav = def.try_to_nav(sema.db).unwrap(); | ||
474 | |||
475 | let mut replacement_text = String::new(); | ||
476 | let mut repl_range = nav.focus_or_full_range(); | ||
477 | if let Definition::Local(local) = def { | ||
478 | if let Either::Left(pat) = local.source(sema.db).value { | ||
479 | if matches!( | ||
480 | pat.syntax().parent().and_then(ast::RecordPatField::cast), | ||
481 | Some(pat_field) if pat_field.name_ref().is_none() | ||
482 | ) { | ||
483 | replacement_text.push_str(": "); | ||
484 | replacement_text.push_str(new_name); | ||
485 | repl_range = TextRange::new( | ||
486 | pat.syntax().text_range().end(), | ||
487 | pat.syntax().text_range().end(), | ||
488 | ); | ||
489 | } | ||
490 | } | ||
491 | } | ||
492 | if replacement_text.is_empty() { | ||
493 | replacement_text.push_str(new_name); | ||
494 | } | ||
495 | let edit = TextEdit::replace(repl_range, replacement_text); | ||
496 | Ok((nav.file_id, edit)) | ||
467 | } | 497 | } |
468 | 498 | ||
469 | #[cfg(test)] | 499 | #[cfg(test)] |
@@ -485,7 +515,7 @@ mod tests { | |||
485 | Ok(source_change) => { | 515 | Ok(source_change) => { |
486 | let mut text_edit_builder = TextEdit::builder(); | 516 | let mut text_edit_builder = TextEdit::builder(); |
487 | let mut file_id: Option<FileId> = None; | 517 | let mut file_id: Option<FileId> = None; |
488 | for edit in source_change.info.source_file_edits { | 518 | for edit in source_change.source_file_edits { |
489 | file_id = Some(edit.0); | 519 | file_id = Some(edit.0); |
490 | for indel in edit.1.into_iter() { | 520 | for indel in edit.1.into_iter() { |
491 | text_edit_builder.replace(indel.delete, indel.insert); | 521 | text_edit_builder.replace(indel.delete, indel.insert); |
@@ -884,36 +914,33 @@ mod foo$0; | |||
884 | // empty | 914 | // empty |
885 | "#, | 915 | "#, |
886 | expect![[r#" | 916 | expect![[r#" |
887 | RangeInfo { | 917 | SourceChange { |
888 | range: 4..7, | 918 | source_file_edits: { |
889 | info: SourceChange { | 919 | FileId( |
890 | source_file_edits: { | 920 | 1, |
891 | FileId( | 921 | ): TextEdit { |
892 | 1, | 922 | indels: [ |
893 | ): TextEdit { | 923 | Indel { |
894 | indels: [ | 924 | insert: "foo2", |
895 | Indel { | 925 | delete: 4..7, |
896 | insert: "foo2", | 926 | }, |
897 | delete: 4..7, | 927 | ], |
898 | }, | ||
899 | ], | ||
900 | }, | ||
901 | }, | 928 | }, |
902 | file_system_edits: [ | 929 | }, |
903 | MoveFile { | 930 | file_system_edits: [ |
904 | src: FileId( | 931 | MoveFile { |
932 | src: FileId( | ||
933 | 2, | ||
934 | ), | ||
935 | dst: AnchoredPathBuf { | ||
936 | anchor: FileId( | ||
905 | 2, | 937 | 2, |
906 | ), | 938 | ), |
907 | dst: AnchoredPathBuf { | 939 | path: "foo2.rs", |
908 | anchor: FileId( | ||
909 | 2, | ||
910 | ), | ||
911 | path: "foo2.rs", | ||
912 | }, | ||
913 | }, | 940 | }, |
914 | ], | 941 | }, |
915 | is_snippet: false, | 942 | ], |
916 | }, | 943 | is_snippet: false, |
917 | } | 944 | } |
918 | "#]], | 945 | "#]], |
919 | ); | 946 | ); |
@@ -936,46 +963,43 @@ pub struct FooContent; | |||
936 | use crate::foo$0::FooContent; | 963 | use crate::foo$0::FooContent; |
937 | "#, | 964 | "#, |
938 | expect![[r#" | 965 | expect![[r#" |
939 | RangeInfo { | 966 | SourceChange { |
940 | range: 11..14, | 967 | source_file_edits: { |
941 | info: SourceChange { | 968 | FileId( |
942 | source_file_edits: { | 969 | 0, |
943 | FileId( | 970 | ): TextEdit { |
944 | 0, | 971 | indels: [ |
945 | ): TextEdit { | 972 | Indel { |
946 | indels: [ | 973 | insert: "quux", |
947 | Indel { | 974 | delete: 8..11, |
948 | insert: "quux", | 975 | }, |
949 | delete: 8..11, | 976 | ], |
950 | }, | 977 | }, |
951 | ], | 978 | FileId( |
952 | }, | 979 | 2, |
953 | FileId( | 980 | ): TextEdit { |
954 | 2, | 981 | indels: [ |
955 | ): TextEdit { | 982 | Indel { |
956 | indels: [ | 983 | insert: "quux", |
957 | Indel { | 984 | delete: 11..14, |
958 | insert: "quux", | 985 | }, |
959 | delete: 11..14, | 986 | ], |
960 | }, | ||
961 | ], | ||
962 | }, | ||
963 | }, | 987 | }, |
964 | file_system_edits: [ | 988 | }, |
965 | MoveFile { | 989 | file_system_edits: [ |
966 | src: FileId( | 990 | MoveFile { |
991 | src: FileId( | ||
992 | 1, | ||
993 | ), | ||
994 | dst: AnchoredPathBuf { | ||
995 | anchor: FileId( | ||
967 | 1, | 996 | 1, |
968 | ), | 997 | ), |
969 | dst: AnchoredPathBuf { | 998 | path: "quux.rs", |
970 | anchor: FileId( | ||
971 | 1, | ||
972 | ), | ||
973 | path: "quux.rs", | ||
974 | }, | ||
975 | }, | 999 | }, |
976 | ], | 1000 | }, |
977 | is_snippet: false, | 1001 | ], |
978 | }, | 1002 | is_snippet: false, |
979 | } | 1003 | } |
980 | "#]], | 1004 | "#]], |
981 | ); | 1005 | ); |
@@ -992,36 +1016,33 @@ mod fo$0o; | |||
992 | // empty | 1016 | // empty |
993 | "#, | 1017 | "#, |
994 | expect![[r#" | 1018 | expect![[r#" |
995 | RangeInfo { | 1019 | SourceChange { |
996 | range: 4..7, | 1020 | source_file_edits: { |
997 | info: SourceChange { | 1021 | FileId( |
998 | source_file_edits: { | 1022 | 0, |
999 | FileId( | 1023 | ): TextEdit { |
1000 | 0, | 1024 | indels: [ |
1001 | ): TextEdit { | 1025 | Indel { |
1002 | indels: [ | 1026 | insert: "foo2", |
1003 | Indel { | 1027 | delete: 4..7, |
1004 | insert: "foo2", | 1028 | }, |
1005 | delete: 4..7, | 1029 | ], |
1006 | }, | ||
1007 | ], | ||
1008 | }, | ||
1009 | }, | 1030 | }, |
1010 | file_system_edits: [ | 1031 | }, |
1011 | MoveFile { | 1032 | file_system_edits: [ |
1012 | src: FileId( | 1033 | MoveFile { |
1034 | src: FileId( | ||
1035 | 1, | ||
1036 | ), | ||
1037 | dst: AnchoredPathBuf { | ||
1038 | anchor: FileId( | ||
1013 | 1, | 1039 | 1, |
1014 | ), | 1040 | ), |
1015 | dst: AnchoredPathBuf { | 1041 | path: "../foo2/mod.rs", |
1016 | anchor: FileId( | ||
1017 | 1, | ||
1018 | ), | ||
1019 | path: "../foo2/mod.rs", | ||
1020 | }, | ||
1021 | }, | 1042 | }, |
1022 | ], | 1043 | }, |
1023 | is_snippet: false, | 1044 | ], |
1024 | }, | 1045 | is_snippet: false, |
1025 | } | 1046 | } |
1026 | "#]], | 1047 | "#]], |
1027 | ); | 1048 | ); |
@@ -1039,36 +1060,33 @@ mod outer { mod fo$0o; } | |||
1039 | // empty | 1060 | // empty |
1040 | "#, | 1061 | "#, |
1041 | expect![[r#" | 1062 | expect![[r#" |
1042 | RangeInfo { | 1063 | SourceChange { |
1043 | range: 16..19, | 1064 | source_file_edits: { |
1044 | info: SourceChange { | 1065 | FileId( |
1045 | source_file_edits: { | 1066 | 0, |
1046 | FileId( | 1067 | ): TextEdit { |
1047 | 0, | 1068 | indels: [ |
1048 | ): TextEdit { | 1069 | Indel { |
1049 | indels: [ | 1070 | insert: "bar", |
1050 | Indel { | 1071 | delete: 16..19, |
1051 | insert: "bar", | 1072 | }, |
1052 | delete: 16..19, | 1073 | ], |
1053 | }, | ||
1054 | ], | ||
1055 | }, | ||
1056 | }, | 1074 | }, |
1057 | file_system_edits: [ | 1075 | }, |
1058 | MoveFile { | 1076 | file_system_edits: [ |
1059 | src: FileId( | 1077 | MoveFile { |
1078 | src: FileId( | ||
1079 | 1, | ||
1080 | ), | ||
1081 | dst: AnchoredPathBuf { | ||
1082 | anchor: FileId( | ||
1060 | 1, | 1083 | 1, |
1061 | ), | 1084 | ), |
1062 | dst: AnchoredPathBuf { | 1085 | path: "bar.rs", |
1063 | anchor: FileId( | ||
1064 | 1, | ||
1065 | ), | ||
1066 | path: "bar.rs", | ||
1067 | }, | ||
1068 | }, | 1086 | }, |
1069 | ], | 1087 | }, |
1070 | is_snippet: false, | 1088 | ], |
1071 | }, | 1089 | is_snippet: false, |
1072 | } | 1090 | } |
1073 | "#]], | 1091 | "#]], |
1074 | ); | 1092 | ); |
@@ -1109,46 +1127,43 @@ pub mod foo$0; | |||
1109 | // pub fn fun() {} | 1127 | // pub fn fun() {} |
1110 | "#, | 1128 | "#, |
1111 | expect![[r#" | 1129 | expect![[r#" |
1112 | RangeInfo { | 1130 | SourceChange { |
1113 | range: 8..11, | 1131 | source_file_edits: { |
1114 | info: SourceChange { | 1132 | FileId( |
1115 | source_file_edits: { | 1133 | 0, |
1116 | FileId( | 1134 | ): TextEdit { |
1117 | 0, | 1135 | indels: [ |
1118 | ): TextEdit { | 1136 | Indel { |
1119 | indels: [ | 1137 | insert: "foo2", |
1120 | Indel { | 1138 | delete: 27..30, |
1121 | insert: "foo2", | 1139 | }, |
1122 | delete: 27..30, | 1140 | ], |
1123 | }, | ||
1124 | ], | ||
1125 | }, | ||
1126 | FileId( | ||
1127 | 1, | ||
1128 | ): TextEdit { | ||
1129 | indels: [ | ||
1130 | Indel { | ||
1131 | insert: "foo2", | ||
1132 | delete: 8..11, | ||
1133 | }, | ||
1134 | ], | ||
1135 | }, | ||
1136 | }, | 1141 | }, |
1137 | file_system_edits: [ | 1142 | FileId( |
1138 | MoveFile { | 1143 | 1, |
1139 | src: FileId( | 1144 | ): TextEdit { |
1145 | indels: [ | ||
1146 | Indel { | ||
1147 | insert: "foo2", | ||
1148 | delete: 8..11, | ||
1149 | }, | ||
1150 | ], | ||
1151 | }, | ||
1152 | }, | ||
1153 | file_system_edits: [ | ||
1154 | MoveFile { | ||
1155 | src: FileId( | ||
1156 | 2, | ||
1157 | ), | ||
1158 | dst: AnchoredPathBuf { | ||
1159 | anchor: FileId( | ||
1140 | 2, | 1160 | 2, |
1141 | ), | 1161 | ), |
1142 | dst: AnchoredPathBuf { | 1162 | path: "foo2.rs", |
1143 | anchor: FileId( | ||
1144 | 2, | ||
1145 | ), | ||
1146 | path: "foo2.rs", | ||
1147 | }, | ||
1148 | }, | 1163 | }, |
1149 | ], | 1164 | }, |
1150 | is_snippet: false, | 1165 | ], |
1151 | }, | 1166 | is_snippet: false, |
1152 | } | 1167 | } |
1153 | "#]], | 1168 | "#]], |
1154 | ); | 1169 | ); |
@@ -1350,6 +1365,7 @@ impl Foo { | |||
1350 | 1365 | ||
1351 | #[test] | 1366 | #[test] |
1352 | fn test_owned_self_to_parameter() { | 1367 | fn test_owned_self_to_parameter() { |
1368 | mark::check!(rename_self_to_param); | ||
1353 | check( | 1369 | check( |
1354 | "foo", | 1370 | "foo", |
1355 | r#" | 1371 | r#" |
diff --git a/crates/ide/src/syntax_highlighting/highlight.rs b/crates/ide/src/syntax_highlighting/highlight.rs index 87578e70a..8625ef5df 100644 --- a/crates/ide/src/syntax_highlighting/highlight.rs +++ b/crates/ide/src/syntax_highlighting/highlight.rs | |||
@@ -68,7 +68,8 @@ pub(super) fn element( | |||
68 | NAME_REF => { | 68 | NAME_REF => { |
69 | let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap(); | 69 | let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap(); |
70 | highlight_func_by_name_ref(sema, &name_ref).unwrap_or_else(|| { | 70 | highlight_func_by_name_ref(sema, &name_ref).unwrap_or_else(|| { |
71 | match NameRefClass::classify(sema, &name_ref) { | 71 | let is_self = name_ref.self_token().is_some(); |
72 | let h = match NameRefClass::classify(sema, &name_ref) { | ||
72 | Some(name_kind) => match name_kind { | 73 | Some(name_kind) => match name_kind { |
73 | NameRefClass::ExternCrate(_) => HlTag::Symbol(SymbolKind::Module).into(), | 74 | NameRefClass::ExternCrate(_) => HlTag::Symbol(SymbolKind::Module).into(), |
74 | NameRefClass::Definition(def) => { | 75 | NameRefClass::Definition(def) => { |
@@ -108,6 +109,11 @@ pub(super) fn element( | |||
108 | highlight_name_ref_by_syntax(name_ref, sema) | 109 | highlight_name_ref_by_syntax(name_ref, sema) |
109 | } | 110 | } |
110 | None => HlTag::UnresolvedReference.into(), | 111 | None => HlTag::UnresolvedReference.into(), |
112 | }; | ||
113 | if h.tag == HlTag::Symbol(SymbolKind::Module) && is_self { | ||
114 | HlTag::Symbol(SymbolKind::SelfParam).into() | ||
115 | } else { | ||
116 | h | ||
111 | } | 117 | } |
112 | }) | 118 | }) |
113 | } | 119 | } |
@@ -225,18 +231,8 @@ pub(super) fn element( | |||
225 | T![for] if !is_child_of_impl(&element) => h | HlMod::ControlFlow, | 231 | T![for] if !is_child_of_impl(&element) => h | HlMod::ControlFlow, |
226 | T![unsafe] => h | HlMod::Unsafe, | 232 | T![unsafe] => h | HlMod::Unsafe, |
227 | T![true] | T![false] => HlTag::BoolLiteral.into(), | 233 | T![true] | T![false] => HlTag::BoolLiteral.into(), |
228 | T![self] => { | 234 | // self is handled as either a Name or NameRef already |
229 | let self_param = element.parent().and_then(ast::SelfParam::cast); | 235 | T![self] => return None, |
230 | if let Some(NameClass::Definition(def)) = self_param | ||
231 | .and_then(|self_param| NameClass::classify_self_param(sema, &self_param)) | ||
232 | { | ||
233 | highlight_def(db, def) | HlMod::Definition | ||
234 | } else if element.ancestors().any(|it| it.kind() == USE_TREE) { | ||
235 | HlTag::Symbol(SymbolKind::SelfParam).into() | ||
236 | } else { | ||
237 | return None; | ||
238 | } | ||
239 | } | ||
240 | T![ref] => element | 236 | T![ref] => element |
241 | .parent() | 237 | .parent() |
242 | .and_then(ast::IdentPat::cast) | 238 | .and_then(ast::IdentPat::cast) |
diff --git a/crates/ide/src/syntax_tree.rs b/crates/ide/src/syntax_tree.rs index 1d4bac7ad..4c63d3023 100644 --- a/crates/ide/src/syntax_tree.rs +++ b/crates/ide/src/syntax_tree.rs | |||
@@ -111,7 +111,6 @@ mod tests { | |||
111 | let syn = analysis.syntax_tree(file_id, None).unwrap(); | 111 | let syn = analysis.syntax_tree(file_id, None).unwrap(); |
112 | 112 | ||
113 | assert_eq_text!( | 113 | assert_eq_text!( |
114 | syn.trim(), | ||
115 | r#" | 114 | r#" |
116 | [email protected] | 115 | [email protected] |
117 | [email protected] | 116 | [email protected] |
@@ -127,7 +126,8 @@ [email protected] | |||
127 | [email protected] "{" | 126 | [email protected] "{" |
128 | [email protected] "}" | 127 | [email protected] "}" |
129 | "# | 128 | "# |
130 | .trim() | 129 | .trim(), |
130 | syn.trim() | ||
131 | ); | 131 | ); |
132 | 132 | ||
133 | let (analysis, file_id) = fixture::file( | 133 | let (analysis, file_id) = fixture::file( |
@@ -143,7 +143,6 @@ fn test() { | |||
143 | let syn = analysis.syntax_tree(file_id, None).unwrap(); | 143 | let syn = analysis.syntax_tree(file_id, None).unwrap(); |
144 | 144 | ||
145 | assert_eq_text!( | 145 | assert_eq_text!( |
146 | syn.trim(), | ||
147 | r#" | 146 | r#" |
148 | [email protected] | 147 | [email protected] |
149 | [email protected] | 148 | [email protected] |
@@ -176,7 +175,8 @@ [email protected] | |||
176 | [email protected] "\n" | 175 | [email protected] "\n" |
177 | [email protected] "}" | 176 | [email protected] "}" |
178 | "# | 177 | "# |
179 | .trim() | 178 | .trim(), |
179 | syn.trim() | ||
180 | ); | 180 | ); |
181 | } | 181 | } |
182 | 182 | ||
@@ -186,7 +186,6 @@ [email protected] | |||
186 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); | 186 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); |
187 | 187 | ||
188 | assert_eq_text!( | 188 | assert_eq_text!( |
189 | syn.trim(), | ||
190 | r#" | 189 | r#" |
191 | [email protected] | 190 | [email protected] |
192 | [email protected] "fn" | 191 | [email protected] "fn" |
@@ -201,7 +200,8 @@ [email protected] | |||
201 | [email protected] "{" | 200 | [email protected] "{" |
202 | [email protected] "}" | 201 | [email protected] "}" |
203 | "# | 202 | "# |
204 | .trim() | 203 | .trim(), |
204 | syn.trim() | ||
205 | ); | 205 | ); |
206 | 206 | ||
207 | let (analysis, range) = fixture::range( | 207 | let (analysis, range) = fixture::range( |
@@ -216,7 +216,6 @@ [email protected] | |||
216 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); | 216 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); |
217 | 217 | ||
218 | assert_eq_text!( | 218 | assert_eq_text!( |
219 | syn.trim(), | ||
220 | r#" | 219 | r#" |
221 | [email protected] | 220 | [email protected] |
222 | [email protected] | 221 | [email protected] |
@@ -234,7 +233,8 @@ [email protected] | |||
234 | [email protected] ")" | 233 | [email protected] ")" |
235 | [email protected] ";" | 234 | [email protected] ";" |
236 | "# | 235 | "# |
237 | .trim() | 236 | .trim(), |
237 | syn.trim() | ||
238 | ); | 238 | ); |
239 | } | 239 | } |
240 | 240 | ||
@@ -253,7 +253,6 @@ fn bar() { | |||
253 | ); | 253 | ); |
254 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); | 254 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); |
255 | assert_eq_text!( | 255 | assert_eq_text!( |
256 | syn.trim(), | ||
257 | r#" | 256 | r#" |
258 | [email protected] | 257 | [email protected] |
259 | [email protected] | 258 | [email protected] |
@@ -270,7 +269,8 @@ [email protected] | |||
270 | [email protected] "\n" | 269 | [email protected] "\n" |
271 | [email protected] "}" | 270 | [email protected] "}" |
272 | "# | 271 | "# |
273 | .trim() | 272 | .trim(), |
273 | syn.trim() | ||
274 | ); | 274 | ); |
275 | 275 | ||
276 | // With a raw string | 276 | // With a raw string |
@@ -287,7 +287,6 @@ fn bar() { | |||
287 | ); | 287 | ); |
288 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); | 288 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); |
289 | assert_eq_text!( | 289 | assert_eq_text!( |
290 | syn.trim(), | ||
291 | r#" | 290 | r#" |
292 | [email protected] | 291 | [email protected] |
293 | [email protected] | 292 | [email protected] |
@@ -304,7 +303,8 @@ [email protected] | |||
304 | [email protected] "\n" | 303 | [email protected] "\n" |
305 | [email protected] "}" | 304 | [email protected] "}" |
306 | "# | 305 | "# |
307 | .trim() | 306 | .trim(), |
307 | syn.trim() | ||
308 | ); | 308 | ); |
309 | 309 | ||
310 | // With a raw string | 310 | // With a raw string |
@@ -320,7 +320,6 @@ fn bar() { | |||
320 | ); | 320 | ); |
321 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); | 321 | let syn = analysis.syntax_tree(range.file_id, Some(range.range)).unwrap(); |
322 | assert_eq_text!( | 322 | assert_eq_text!( |
323 | syn.trim(), | ||
324 | r#" | 323 | r#" |
325 | [email protected] | 324 | [email protected] |
326 | [email protected] | 325 | [email protected] |
@@ -351,7 +350,8 @@ [email protected] | |||
351 | [email protected] "\n" | 350 | [email protected] "\n" |
352 | [email protected] "}" | 351 | [email protected] "}" |
353 | "# | 352 | "# |
354 | .trim() | 353 | .trim(), |
354 | syn.trim() | ||
355 | ); | 355 | ); |
356 | } | 356 | } |
357 | } | 357 | } |
diff --git a/crates/ide_db/src/defs.rs b/crates/ide_db/src/defs.rs index 231e886a9..d9875ffef 100644 --- a/crates/ide_db/src/defs.rs +++ b/crates/ide_db/src/defs.rs | |||
@@ -117,13 +117,6 @@ impl NameClass { | |||
117 | } | 117 | } |
118 | } | 118 | } |
119 | 119 | ||
120 | pub fn classify_self_param( | ||
121 | sema: &Semantics<RootDatabase>, | ||
122 | self_param: &ast::SelfParam, | ||
123 | ) -> Option<NameClass> { | ||
124 | sema.to_def(self_param).map(Definition::Local).map(NameClass::Definition) | ||
125 | } | ||
126 | |||
127 | pub fn classify(sema: &Semantics<RootDatabase>, name: &ast::Name) -> Option<NameClass> { | 120 | pub fn classify(sema: &Semantics<RootDatabase>, name: &ast::Name) -> Option<NameClass> { |
128 | let _p = profile::span("classify_name"); | 121 | let _p = profile::span("classify_name"); |
129 | 122 | ||
@@ -186,6 +179,10 @@ impl NameClass { | |||
186 | 179 | ||
187 | Some(NameClass::Definition(Definition::Local(local))) | 180 | Some(NameClass::Definition(Definition::Local(local))) |
188 | }, | 181 | }, |
182 | ast::SelfParam(it) => { | ||
183 | let def = sema.to_def(&it)?; | ||
184 | Some(NameClass::Definition(Definition::Local(def.into()))) | ||
185 | }, | ||
189 | ast::RecordField(it) => { | 186 | ast::RecordField(it) => { |
190 | let field: hir::Field = sema.to_def(&it)?; | 187 | let field: hir::Field = sema.to_def(&it)?; |
191 | Some(NameClass::Definition(Definition::Field(field))) | 188 | Some(NameClass::Definition(Definition::Field(field))) |
diff --git a/crates/ide_db/src/helpers/import_assets.rs b/crates/ide_db/src/helpers/import_assets.rs index edc3da318..517abbb4b 100644 --- a/crates/ide_db/src/helpers/import_assets.rs +++ b/crates/ide_db/src/helpers/import_assets.rs | |||
@@ -1,12 +1,13 @@ | |||
1 | //! Look up accessible paths for items. | 1 | //! Look up accessible paths for items. |
2 | use either::Either; | 2 | use either::Either; |
3 | use hir::{AsAssocItem, AssocItemContainer, ModuleDef, Semantics}; | 3 | use hir::{AsAssocItem, AssocItem, Crate, MacroDef, Module, ModuleDef, PrefixKind, Semantics}; |
4 | use rustc_hash::FxHashSet; | 4 | use rustc_hash::FxHashSet; |
5 | use syntax::{ast, AstNode, SyntaxNode}; | 5 | use syntax::{ast, AstNode}; |
6 | 6 | ||
7 | use crate::{imports_locator, RootDatabase}; | 7 | use crate::{ |
8 | 8 | imports_locator::{self, AssocItemSearch, DEFAULT_QUERY_SEARCH_LIMIT}, | |
9 | use super::insert_use::InsertUseConfig; | 9 | RootDatabase, |
10 | }; | ||
10 | 11 | ||
11 | #[derive(Debug)] | 12 | #[derive(Debug)] |
12 | pub enum ImportCandidate { | 13 | pub enum ImportCandidate { |
@@ -24,86 +25,141 @@ pub enum ImportCandidate { | |||
24 | 25 | ||
25 | #[derive(Debug)] | 26 | #[derive(Debug)] |
26 | pub struct TraitImportCandidate { | 27 | pub struct TraitImportCandidate { |
27 | pub ty: hir::Type, | 28 | pub receiver_ty: hir::Type, |
28 | pub name: ast::NameRef, | 29 | pub name: NameToImport, |
29 | } | 30 | } |
30 | 31 | ||
31 | #[derive(Debug)] | 32 | #[derive(Debug)] |
32 | pub struct PathImportCandidate { | 33 | pub struct PathImportCandidate { |
33 | pub qualifier: Option<ast::Path>, | 34 | pub qualifier: Option<ast::Path>, |
34 | pub name: ast::NameRef, | 35 | pub name: NameToImport, |
36 | } | ||
37 | |||
38 | #[derive(Debug)] | ||
39 | pub enum NameToImport { | ||
40 | Exact(String), | ||
41 | Fuzzy(String), | ||
42 | } | ||
43 | |||
44 | impl NameToImport { | ||
45 | pub fn text(&self) -> &str { | ||
46 | match self { | ||
47 | NameToImport::Exact(text) => text.as_str(), | ||
48 | NameToImport::Fuzzy(text) => text.as_str(), | ||
49 | } | ||
50 | } | ||
35 | } | 51 | } |
36 | 52 | ||
37 | #[derive(Debug)] | 53 | #[derive(Debug)] |
38 | pub struct ImportAssets { | 54 | pub struct ImportAssets { |
39 | import_candidate: ImportCandidate, | 55 | import_candidate: ImportCandidate, |
40 | module_with_name_to_import: hir::Module, | 56 | module_with_candidate: hir::Module, |
41 | syntax_under_caret: SyntaxNode, | ||
42 | } | 57 | } |
43 | 58 | ||
44 | impl ImportAssets { | 59 | impl ImportAssets { |
45 | pub fn for_method_call( | 60 | pub fn for_method_call( |
46 | method_call: ast::MethodCallExpr, | 61 | method_call: &ast::MethodCallExpr, |
47 | sema: &Semantics<RootDatabase>, | 62 | sema: &Semantics<RootDatabase>, |
48 | ) -> Option<Self> { | 63 | ) -> Option<Self> { |
49 | let syntax_under_caret = method_call.syntax().to_owned(); | ||
50 | let module_with_name_to_import = sema.scope(&syntax_under_caret).module()?; | ||
51 | Some(Self { | 64 | Some(Self { |
52 | import_candidate: ImportCandidate::for_method_call(sema, &method_call)?, | 65 | import_candidate: ImportCandidate::for_method_call(sema, method_call)?, |
53 | module_with_name_to_import, | 66 | module_with_candidate: sema.scope(method_call.syntax()).module()?, |
54 | syntax_under_caret, | ||
55 | }) | 67 | }) |
56 | } | 68 | } |
57 | 69 | ||
58 | pub fn for_regular_path( | 70 | pub fn for_exact_path( |
59 | path_under_caret: ast::Path, | 71 | fully_qualified_path: &ast::Path, |
60 | sema: &Semantics<RootDatabase>, | 72 | sema: &Semantics<RootDatabase>, |
61 | ) -> Option<Self> { | 73 | ) -> Option<Self> { |
62 | let syntax_under_caret = path_under_caret.syntax().to_owned(); | 74 | let syntax_under_caret = fully_qualified_path.syntax(); |
63 | if syntax_under_caret.ancestors().find_map(ast::Use::cast).is_some() { | 75 | if syntax_under_caret.ancestors().find_map(ast::Use::cast).is_some() { |
64 | return None; | 76 | return None; |
65 | } | 77 | } |
66 | |||
67 | let module_with_name_to_import = sema.scope(&syntax_under_caret).module()?; | ||
68 | Some(Self { | 78 | Some(Self { |
69 | import_candidate: ImportCandidate::for_regular_path(sema, &path_under_caret)?, | 79 | import_candidate: ImportCandidate::for_regular_path(sema, fully_qualified_path)?, |
70 | module_with_name_to_import, | 80 | module_with_candidate: sema.scope(syntax_under_caret).module()?, |
71 | syntax_under_caret, | ||
72 | }) | 81 | }) |
73 | } | 82 | } |
74 | 83 | ||
75 | pub fn syntax_under_caret(&self) -> &SyntaxNode { | 84 | pub fn for_fuzzy_path( |
76 | &self.syntax_under_caret | 85 | module_with_path: Module, |
86 | qualifier: Option<ast::Path>, | ||
87 | fuzzy_name: String, | ||
88 | sema: &Semantics<RootDatabase>, | ||
89 | ) -> Option<Self> { | ||
90 | Some(match qualifier { | ||
91 | Some(qualifier) => { | ||
92 | let qualifier_resolution = sema.resolve_path(&qualifier)?; | ||
93 | match qualifier_resolution { | ||
94 | hir::PathResolution::Def(hir::ModuleDef::Adt(assoc_item_path)) => Self { | ||
95 | import_candidate: ImportCandidate::TraitAssocItem(TraitImportCandidate { | ||
96 | receiver_ty: assoc_item_path.ty(sema.db), | ||
97 | name: NameToImport::Fuzzy(fuzzy_name), | ||
98 | }), | ||
99 | module_with_candidate: module_with_path, | ||
100 | }, | ||
101 | _ => Self { | ||
102 | import_candidate: ImportCandidate::Path(PathImportCandidate { | ||
103 | qualifier: Some(qualifier), | ||
104 | name: NameToImport::Fuzzy(fuzzy_name), | ||
105 | }), | ||
106 | module_with_candidate: module_with_path, | ||
107 | }, | ||
108 | } | ||
109 | } | ||
110 | None => Self { | ||
111 | import_candidate: ImportCandidate::Path(PathImportCandidate { | ||
112 | qualifier: None, | ||
113 | name: NameToImport::Fuzzy(fuzzy_name), | ||
114 | }), | ||
115 | module_with_candidate: module_with_path, | ||
116 | }, | ||
117 | }) | ||
77 | } | 118 | } |
78 | 119 | ||
120 | pub fn for_fuzzy_method_call( | ||
121 | module_with_method_call: Module, | ||
122 | receiver_ty: hir::Type, | ||
123 | fuzzy_method_name: String, | ||
124 | ) -> Option<Self> { | ||
125 | Some(Self { | ||
126 | import_candidate: ImportCandidate::TraitMethod(TraitImportCandidate { | ||
127 | receiver_ty, | ||
128 | name: NameToImport::Fuzzy(fuzzy_method_name), | ||
129 | }), | ||
130 | module_with_candidate: module_with_method_call, | ||
131 | }) | ||
132 | } | ||
133 | } | ||
134 | |||
135 | impl ImportAssets { | ||
79 | pub fn import_candidate(&self) -> &ImportCandidate { | 136 | pub fn import_candidate(&self) -> &ImportCandidate { |
80 | &self.import_candidate | 137 | &self.import_candidate |
81 | } | 138 | } |
82 | 139 | ||
83 | fn get_search_query(&self) -> &str { | 140 | fn name_to_import(&self) -> &NameToImport { |
84 | match &self.import_candidate { | 141 | match &self.import_candidate { |
85 | ImportCandidate::Path(candidate) => candidate.name.text(), | 142 | ImportCandidate::Path(candidate) => &candidate.name, |
86 | ImportCandidate::TraitAssocItem(candidate) | 143 | ImportCandidate::TraitAssocItem(candidate) |
87 | | ImportCandidate::TraitMethod(candidate) => candidate.name.text(), | 144 | | ImportCandidate::TraitMethod(candidate) => &candidate.name, |
88 | } | 145 | } |
89 | } | 146 | } |
90 | 147 | ||
91 | pub fn search_for_imports( | 148 | pub fn search_for_imports( |
92 | &self, | 149 | &self, |
93 | sema: &Semantics<RootDatabase>, | 150 | sema: &Semantics<RootDatabase>, |
94 | config: &InsertUseConfig, | 151 | prefix_kind: PrefixKind, |
95 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { | 152 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { |
96 | let _p = profile::span("import_assists::search_for_imports"); | 153 | let _p = profile::span("import_assets::search_for_imports"); |
97 | self.search_for(sema, Some(config.prefix_kind)) | 154 | self.search_for(sema, Some(prefix_kind)) |
98 | } | 155 | } |
99 | 156 | ||
100 | /// This may return non-absolute paths if a part of the returned path is already imported into scope. | 157 | /// This may return non-absolute paths if a part of the returned path is already imported into scope. |
101 | #[allow(dead_code)] | ||
102 | pub fn search_for_relative_paths( | 158 | pub fn search_for_relative_paths( |
103 | &self, | 159 | &self, |
104 | sema: &Semantics<RootDatabase>, | 160 | sema: &Semantics<RootDatabase>, |
105 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { | 161 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { |
106 | let _p = profile::span("import_assists::search_for_relative_paths"); | 162 | let _p = profile::span("import_assets::search_for_relative_paths"); |
107 | self.search_for(sema, None) | 163 | self.search_for(sema, None) |
108 | } | 164 | } |
109 | 165 | ||
@@ -112,99 +168,142 @@ impl ImportAssets { | |||
112 | sema: &Semantics<RootDatabase>, | 168 | sema: &Semantics<RootDatabase>, |
113 | prefixed: Option<hir::PrefixKind>, | 169 | prefixed: Option<hir::PrefixKind>, |
114 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { | 170 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { |
115 | let db = sema.db; | 171 | let current_crate = self.module_with_candidate.krate(); |
116 | let mut trait_candidates = FxHashSet::default(); | ||
117 | let current_crate = self.module_with_name_to_import.krate(); | ||
118 | 172 | ||
119 | let filter = |candidate: Either<hir::ModuleDef, hir::MacroDef>| { | 173 | let unfiltered_imports = match self.name_to_import() { |
120 | trait_candidates.clear(); | 174 | NameToImport::Exact(exact_name) => { |
121 | match &self.import_candidate { | 175 | imports_locator::find_exact_imports(sema, current_crate, exact_name.clone()) |
122 | ImportCandidate::TraitAssocItem(trait_candidate) => { | 176 | } |
123 | let located_assoc_item = match candidate { | 177 | // FIXME: ideally, we should avoid using `fst` for seacrhing trait imports for assoc items: |
124 | Either::Left(ModuleDef::Function(located_function)) => { | 178 | // instead, we need to look up all trait impls for a certain struct and search through them only |
125 | located_function.as_assoc_item(db) | 179 | // see https://github.com/rust-analyzer/rust-analyzer/pull/7293#issuecomment-761585032 |
126 | } | 180 | // and https://rust-lang.zulipchat.com/#narrow/stream/185405-t-compiler.2Fwg-rls-2.2E0/topic/Blanket.20trait.20impls.20lookup |
127 | Either::Left(ModuleDef::Const(located_const)) => { | 181 | // for the details |
128 | located_const.as_assoc_item(db) | 182 | NameToImport::Fuzzy(fuzzy_name) => { |
129 | } | 183 | let (assoc_item_search, limit) = match self.import_candidate { |
130 | _ => None, | 184 | ImportCandidate::TraitAssocItem(_) | ImportCandidate::TraitMethod(_) => { |
185 | (AssocItemSearch::AssocItemsOnly, None) | ||
131 | } | 186 | } |
132 | .map(|assoc| assoc.container(db)) | 187 | _ => (AssocItemSearch::Exclude, Some(DEFAULT_QUERY_SEARCH_LIMIT)), |
133 | .and_then(Self::assoc_to_trait)?; | 188 | }; |
134 | 189 | imports_locator::find_similar_imports( | |
135 | trait_candidates.insert(located_assoc_item.into()); | 190 | sema, |
191 | current_crate, | ||
192 | fuzzy_name.clone(), | ||
193 | assoc_item_search, | ||
194 | limit, | ||
195 | ) | ||
196 | } | ||
197 | }; | ||
136 | 198 | ||
137 | trait_candidate | 199 | let db = sema.db; |
138 | .ty | 200 | let mut res = |
139 | .iterate_path_candidates( | 201 | applicable_defs(self.import_candidate(), current_crate, db, unfiltered_imports) |
140 | db, | 202 | .filter_map(|candidate| { |
141 | current_crate, | 203 | let item: hir::ItemInNs = candidate.clone().either(Into::into, Into::into); |
142 | &trait_candidates, | ||
143 | None, | ||
144 | |_, assoc| Self::assoc_to_trait(assoc.container(db)), | ||
145 | ) | ||
146 | .map(ModuleDef::from) | ||
147 | .map(Either::Left) | ||
148 | } | ||
149 | ImportCandidate::TraitMethod(trait_candidate) => { | ||
150 | let located_assoc_item = | ||
151 | if let Either::Left(ModuleDef::Function(located_function)) = candidate { | ||
152 | located_function | ||
153 | .as_assoc_item(db) | ||
154 | .map(|assoc| assoc.container(db)) | ||
155 | .and_then(Self::assoc_to_trait) | ||
156 | } else { | ||
157 | None | ||
158 | }?; | ||
159 | 204 | ||
160 | trait_candidates.insert(located_assoc_item.into()); | 205 | let item_to_search = match self.import_candidate { |
206 | ImportCandidate::TraitAssocItem(_) | ImportCandidate::TraitMethod(_) => { | ||
207 | let canidate_trait = match candidate { | ||
208 | Either::Left(module_def) => { | ||
209 | module_def.as_assoc_item(db)?.containing_trait(db) | ||
210 | } | ||
211 | _ => None, | ||
212 | }?; | ||
213 | ModuleDef::from(canidate_trait).into() | ||
214 | } | ||
215 | _ => item, | ||
216 | }; | ||
161 | 217 | ||
162 | trait_candidate | 218 | if let Some(prefix_kind) = prefixed { |
163 | .ty | 219 | self.module_with_candidate.find_use_path_prefixed( |
164 | .iterate_method_candidates( | ||
165 | db, | 220 | db, |
166 | current_crate, | 221 | item_to_search, |
167 | &trait_candidates, | 222 | prefix_kind, |
168 | None, | ||
169 | |_, function| { | ||
170 | Self::assoc_to_trait(function.as_assoc_item(db)?.container(db)) | ||
171 | }, | ||
172 | ) | 223 | ) |
173 | .map(ModuleDef::from) | 224 | } else { |
174 | .map(Either::Left) | 225 | self.module_with_candidate.find_use_path(db, item_to_search) |
175 | } | 226 | } |
176 | _ => Some(candidate), | 227 | .map(|path| (path, item)) |
177 | } | 228 | }) |
178 | }; | 229 | .filter(|(use_path, _)| use_path.len() > 1) |
179 | 230 | .collect::<Vec<_>>(); | |
180 | let mut res = imports_locator::find_exact_imports( | 231 | res.sort_by_cached_key(|(path, _)| path.clone()); |
181 | sema, | ||
182 | current_crate, | ||
183 | self.get_search_query().to_string(), | ||
184 | ) | ||
185 | .filter_map(filter) | ||
186 | .filter_map(|candidate| { | ||
187 | let item: hir::ItemInNs = candidate.either(Into::into, Into::into); | ||
188 | if let Some(prefix_kind) = prefixed { | ||
189 | self.module_with_name_to_import.find_use_path_prefixed(db, item, prefix_kind) | ||
190 | } else { | ||
191 | self.module_with_name_to_import.find_use_path(db, item) | ||
192 | } | ||
193 | .map(|path| (path, item)) | ||
194 | }) | ||
195 | .filter(|(use_path, _)| use_path.len() > 1) | ||
196 | .take(20) | ||
197 | .collect::<Vec<_>>(); | ||
198 | res.sort_by_key(|(path, _)| path.clone()); | ||
199 | res | 232 | res |
200 | } | 233 | } |
234 | } | ||
201 | 235 | ||
202 | fn assoc_to_trait(assoc: AssocItemContainer) -> Option<hir::Trait> { | 236 | fn applicable_defs<'a>( |
203 | if let AssocItemContainer::Trait(extracted_trait) = assoc { | 237 | import_candidate: &ImportCandidate, |
204 | Some(extracted_trait) | 238 | current_crate: Crate, |
205 | } else { | 239 | db: &RootDatabase, |
206 | None | 240 | unfiltered_imports: Box<dyn Iterator<Item = Either<ModuleDef, MacroDef>> + 'a>, |
241 | ) -> Box<dyn Iterator<Item = Either<ModuleDef, MacroDef>> + 'a> { | ||
242 | let receiver_ty = match import_candidate { | ||
243 | ImportCandidate::Path(_) => return unfiltered_imports, | ||
244 | ImportCandidate::TraitAssocItem(candidate) | ImportCandidate::TraitMethod(candidate) => { | ||
245 | &candidate.receiver_ty | ||
207 | } | 246 | } |
247 | }; | ||
248 | |||
249 | let mut required_assoc_items = FxHashSet::default(); | ||
250 | |||
251 | let trait_candidates = unfiltered_imports | ||
252 | .filter_map(|input| match input { | ||
253 | Either::Left(module_def) => module_def.as_assoc_item(db), | ||
254 | _ => None, | ||
255 | }) | ||
256 | .filter_map(|assoc| { | ||
257 | let assoc_item_trait = assoc.containing_trait(db)?; | ||
258 | required_assoc_items.insert(assoc); | ||
259 | Some(assoc_item_trait.into()) | ||
260 | }) | ||
261 | .collect(); | ||
262 | |||
263 | let mut applicable_defs = FxHashSet::default(); | ||
264 | |||
265 | match import_candidate { | ||
266 | ImportCandidate::Path(_) => unreachable!(), | ||
267 | ImportCandidate::TraitAssocItem(_) => receiver_ty.iterate_path_candidates( | ||
268 | db, | ||
269 | current_crate, | ||
270 | &trait_candidates, | ||
271 | None, | ||
272 | |_, assoc| { | ||
273 | if required_assoc_items.contains(&assoc) { | ||
274 | if let AssocItem::Function(f) = assoc { | ||
275 | if f.self_param(db).is_some() { | ||
276 | return None; | ||
277 | } | ||
278 | } | ||
279 | applicable_defs.insert(Either::Left(assoc_to_module_def(assoc))); | ||
280 | } | ||
281 | None::<()> | ||
282 | }, | ||
283 | ), | ||
284 | ImportCandidate::TraitMethod(_) => receiver_ty.iterate_method_candidates( | ||
285 | db, | ||
286 | current_crate, | ||
287 | &trait_candidates, | ||
288 | None, | ||
289 | |_, function| { | ||
290 | let assoc = function.as_assoc_item(db)?; | ||
291 | if required_assoc_items.contains(&assoc) { | ||
292 | applicable_defs.insert(Either::Left(assoc_to_module_def(assoc))); | ||
293 | } | ||
294 | None::<()> | ||
295 | }, | ||
296 | ), | ||
297 | }; | ||
298 | |||
299 | Box::new(applicable_defs.into_iter()) | ||
300 | } | ||
301 | |||
302 | fn assoc_to_module_def(assoc: AssocItem) -> ModuleDef { | ||
303 | match assoc { | ||
304 | AssocItem::Function(f) => f.into(), | ||
305 | AssocItem::Const(c) => c.into(), | ||
306 | AssocItem::TypeAlias(t) => t.into(), | ||
208 | } | 307 | } |
209 | } | 308 | } |
210 | 309 | ||
@@ -216,22 +315,19 @@ impl ImportCandidate { | |||
216 | match sema.resolve_method_call(method_call) { | 315 | match sema.resolve_method_call(method_call) { |
217 | Some(_) => None, | 316 | Some(_) => None, |
218 | None => Some(Self::TraitMethod(TraitImportCandidate { | 317 | None => Some(Self::TraitMethod(TraitImportCandidate { |
219 | ty: sema.type_of_expr(&method_call.receiver()?)?, | 318 | receiver_ty: sema.type_of_expr(&method_call.receiver()?)?, |
220 | name: method_call.name_ref()?, | 319 | name: NameToImport::Exact(method_call.name_ref()?.to_string()), |
221 | })), | 320 | })), |
222 | } | 321 | } |
223 | } | 322 | } |
224 | 323 | ||
225 | fn for_regular_path( | 324 | fn for_regular_path(sema: &Semantics<RootDatabase>, path: &ast::Path) -> Option<Self> { |
226 | sema: &Semantics<RootDatabase>, | 325 | if sema.resolve_path(path).is_some() { |
227 | path_under_caret: &ast::Path, | ||
228 | ) -> Option<Self> { | ||
229 | if sema.resolve_path(path_under_caret).is_some() { | ||
230 | return None; | 326 | return None; |
231 | } | 327 | } |
232 | 328 | ||
233 | let segment = path_under_caret.segment()?; | 329 | let segment = path.segment()?; |
234 | let candidate = if let Some(qualifier) = path_under_caret.qualifier() { | 330 | let candidate = if let Some(qualifier) = path.qualifier() { |
235 | let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?; | 331 | let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?; |
236 | let qualifier_start_path = | 332 | let qualifier_start_path = |
237 | qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?; | 333 | qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?; |
@@ -244,8 +340,8 @@ impl ImportCandidate { | |||
244 | match qualifier_resolution { | 340 | match qualifier_resolution { |
245 | hir::PathResolution::Def(hir::ModuleDef::Adt(assoc_item_path)) => { | 341 | hir::PathResolution::Def(hir::ModuleDef::Adt(assoc_item_path)) => { |
246 | ImportCandidate::TraitAssocItem(TraitImportCandidate { | 342 | ImportCandidate::TraitAssocItem(TraitImportCandidate { |
247 | ty: assoc_item_path.ty(sema.db), | 343 | receiver_ty: assoc_item_path.ty(sema.db), |
248 | name: segment.name_ref()?, | 344 | name: NameToImport::Exact(segment.name_ref()?.to_string()), |
249 | }) | 345 | }) |
250 | } | 346 | } |
251 | _ => return None, | 347 | _ => return None, |
@@ -253,13 +349,15 @@ impl ImportCandidate { | |||
253 | } else { | 349 | } else { |
254 | ImportCandidate::Path(PathImportCandidate { | 350 | ImportCandidate::Path(PathImportCandidate { |
255 | qualifier: Some(qualifier), | 351 | qualifier: Some(qualifier), |
256 | name: qualifier_start, | 352 | name: NameToImport::Exact(qualifier_start.to_string()), |
257 | }) | 353 | }) |
258 | } | 354 | } |
259 | } else { | 355 | } else { |
260 | ImportCandidate::Path(PathImportCandidate { | 356 | ImportCandidate::Path(PathImportCandidate { |
261 | qualifier: None, | 357 | qualifier: None, |
262 | name: segment.syntax().descendants().find_map(ast::NameRef::cast)?, | 358 | name: NameToImport::Exact( |
359 | segment.syntax().descendants().find_map(ast::NameRef::cast)?.to_string(), | ||
360 | ), | ||
263 | }) | 361 | }) |
264 | }; | 362 | }; |
265 | Some(candidate) | 363 | Some(candidate) |
diff --git a/crates/ide_db/src/helpers/insert_use/tests.rs b/crates/ide_db/src/helpers/insert_use/tests.rs index a603fe87f..4bbe66f1f 100644 --- a/crates/ide_db/src/helpers/insert_use/tests.rs +++ b/crates/ide_db/src/helpers/insert_use/tests.rs | |||
@@ -599,7 +599,7 @@ fn check( | |||
599 | 599 | ||
600 | let rewriter = insert_use(&file, path, mb); | 600 | let rewriter = insert_use(&file, path, mb); |
601 | let result = rewriter.rewrite(file.as_syntax_node()).to_string(); | 601 | let result = rewriter.rewrite(file.as_syntax_node()).to_string(); |
602 | assert_eq_text!(&result, ra_fixture_after); | 602 | assert_eq_text!(ra_fixture_after, &result); |
603 | } | 603 | } |
604 | 604 | ||
605 | fn check_full(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { | 605 | fn check_full(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { |
diff --git a/crates/ide_db/src/imports_locator.rs b/crates/ide_db/src/imports_locator.rs index d111fba92..502e8281a 100644 --- a/crates/ide_db/src/imports_locator.rs +++ b/crates/ide_db/src/imports_locator.rs | |||
@@ -1,7 +1,10 @@ | |||
1 | //! This module contains an import search functionality that is provided to the assists module. | 1 | //! This module contains an import search functionality that is provided to the assists module. |
2 | //! Later, this should be moved away to a separate crate that is accessible from the assists module. | 2 | //! Later, this should be moved away to a separate crate that is accessible from the assists module. |
3 | 3 | ||
4 | use hir::{import_map, AsAssocItem, Crate, MacroDef, ModuleDef, Semantics}; | 4 | use hir::{ |
5 | import_map::{self, ImportKind}, | ||
6 | AsAssocItem, Crate, MacroDef, ModuleDef, Semantics, | ||
7 | }; | ||
5 | use syntax::{ast, AstNode, SyntaxKind::NAME}; | 8 | use syntax::{ast, AstNode, SyntaxKind::NAME}; |
6 | 9 | ||
7 | use crate::{ | 10 | use crate::{ |
@@ -12,69 +15,84 @@ use crate::{ | |||
12 | use either::Either; | 15 | use either::Either; |
13 | use rustc_hash::FxHashSet; | 16 | use rustc_hash::FxHashSet; |
14 | 17 | ||
15 | const QUERY_SEARCH_LIMIT: usize = 40; | 18 | pub(crate) const DEFAULT_QUERY_SEARCH_LIMIT: usize = 40; |
16 | 19 | ||
17 | pub fn find_exact_imports<'a>( | 20 | pub fn find_exact_imports<'a>( |
18 | sema: &Semantics<'a, RootDatabase>, | 21 | sema: &Semantics<'a, RootDatabase>, |
19 | krate: Crate, | 22 | krate: Crate, |
20 | name_to_import: String, | 23 | name_to_import: String, |
21 | ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> { | 24 | ) -> Box<dyn Iterator<Item = Either<ModuleDef, MacroDef>>> { |
22 | let _p = profile::span("find_exact_imports"); | 25 | let _p = profile::span("find_exact_imports"); |
23 | find_imports( | 26 | Box::new(find_imports( |
24 | sema, | 27 | sema, |
25 | krate, | 28 | krate, |
26 | { | 29 | { |
27 | let mut local_query = symbol_index::Query::new(name_to_import.clone()); | 30 | let mut local_query = symbol_index::Query::new(name_to_import.clone()); |
28 | local_query.exact(); | 31 | local_query.exact(); |
29 | local_query.limit(QUERY_SEARCH_LIMIT); | 32 | local_query.limit(DEFAULT_QUERY_SEARCH_LIMIT); |
30 | local_query | 33 | local_query |
31 | }, | 34 | }, |
32 | import_map::Query::new(name_to_import) | 35 | import_map::Query::new(name_to_import) |
33 | .limit(QUERY_SEARCH_LIMIT) | 36 | .limit(DEFAULT_QUERY_SEARCH_LIMIT) |
34 | .name_only() | 37 | .name_only() |
35 | .search_mode(import_map::SearchMode::Equals) | 38 | .search_mode(import_map::SearchMode::Equals) |
36 | .case_sensitive(), | 39 | .case_sensitive(), |
37 | ) | 40 | )) |
41 | } | ||
42 | |||
43 | pub enum AssocItemSearch { | ||
44 | Include, | ||
45 | Exclude, | ||
46 | AssocItemsOnly, | ||
38 | } | 47 | } |
39 | 48 | ||
40 | pub fn find_similar_imports<'a>( | 49 | pub fn find_similar_imports<'a>( |
41 | sema: &Semantics<'a, RootDatabase>, | 50 | sema: &Semantics<'a, RootDatabase>, |
42 | krate: Crate, | 51 | krate: Crate, |
43 | limit: Option<usize>, | ||
44 | fuzzy_search_string: String, | 52 | fuzzy_search_string: String, |
45 | ignore_assoc_items: bool, | 53 | assoc_item_search: AssocItemSearch, |
46 | name_only: bool, | 54 | limit: Option<usize>, |
47 | ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> + 'a { | 55 | ) -> Box<dyn Iterator<Item = Either<ModuleDef, MacroDef>> + 'a> { |
48 | let _p = profile::span("find_similar_imports"); | 56 | let _p = profile::span("find_similar_imports"); |
49 | 57 | ||
50 | let mut external_query = import_map::Query::new(fuzzy_search_string.clone()) | 58 | let mut external_query = import_map::Query::new(fuzzy_search_string.clone()) |
51 | .search_mode(import_map::SearchMode::Fuzzy); | 59 | .search_mode(import_map::SearchMode::Fuzzy) |
52 | if name_only { | 60 | .name_only(); |
53 | external_query = external_query.name_only(); | 61 | |
62 | match assoc_item_search { | ||
63 | AssocItemSearch::Include => {} | ||
64 | AssocItemSearch::Exclude => { | ||
65 | external_query = external_query.exclude_import_kind(ImportKind::AssociatedItem); | ||
66 | } | ||
67 | AssocItemSearch::AssocItemsOnly => { | ||
68 | external_query = external_query.assoc_items_only(); | ||
69 | } | ||
54 | } | 70 | } |
55 | 71 | ||
56 | let mut local_query = symbol_index::Query::new(fuzzy_search_string); | 72 | let mut local_query = symbol_index::Query::new(fuzzy_search_string); |
57 | 73 | ||
58 | if let Some(limit) = limit { | 74 | if let Some(limit) = limit { |
59 | local_query.limit(limit); | ||
60 | external_query = external_query.limit(limit); | 75 | external_query = external_query.limit(limit); |
76 | local_query.limit(limit); | ||
61 | } | 77 | } |
62 | 78 | ||
63 | let db = sema.db; | 79 | let db = sema.db; |
64 | find_imports(sema, krate, local_query, external_query).filter(move |import_candidate| { | 80 | Box::new(find_imports(sema, krate, local_query, external_query).filter( |
65 | if ignore_assoc_items { | 81 | move |import_candidate| match assoc_item_search { |
66 | match import_candidate { | 82 | AssocItemSearch::Include => true, |
67 | Either::Left(ModuleDef::Function(function)) => function.as_assoc_item(db).is_none(), | 83 | AssocItemSearch::Exclude => !is_assoc_item(import_candidate, db), |
68 | Either::Left(ModuleDef::Const(const_)) => const_.as_assoc_item(db).is_none(), | 84 | AssocItemSearch::AssocItemsOnly => is_assoc_item(import_candidate, db), |
69 | Either::Left(ModuleDef::TypeAlias(type_alias)) => { | 85 | }, |
70 | type_alias.as_assoc_item(db).is_none() | 86 | )) |
71 | } | 87 | } |
72 | _ => true, | 88 | |
73 | } | 89 | fn is_assoc_item(import_candidate: &Either<ModuleDef, MacroDef>, db: &RootDatabase) -> bool { |
74 | } else { | 90 | match import_candidate { |
75 | true | 91 | Either::Left(ModuleDef::Function(function)) => function.as_assoc_item(db).is_some(), |
76 | } | 92 | Either::Left(ModuleDef::Const(const_)) => const_.as_assoc_item(db).is_some(), |
77 | }) | 93 | Either::Left(ModuleDef::TypeAlias(type_alias)) => type_alias.as_assoc_item(db).is_some(), |
94 | _ => false, | ||
95 | } | ||
78 | } | 96 | } |
79 | 97 | ||
80 | fn find_imports<'a>( | 98 | fn find_imports<'a>( |
diff --git a/crates/mbe/src/syntax_bridge.rs b/crates/mbe/src/syntax_bridge.rs index e648519f9..2a41d8167 100644 --- a/crates/mbe/src/syntax_bridge.rs +++ b/crates/mbe/src/syntax_bridge.rs | |||
@@ -51,6 +51,7 @@ pub fn syntax_node_to_token_tree(node: &SyntaxNode) -> Option<(tt::Subtree, Toke | |||
51 | let global_offset = node.text_range().start(); | 51 | let global_offset = node.text_range().start(); |
52 | let mut c = Convertor::new(node, global_offset); | 52 | let mut c = Convertor::new(node, global_offset); |
53 | let subtree = c.go()?; | 53 | let subtree = c.go()?; |
54 | c.id_alloc.map.entries.shrink_to_fit(); | ||
54 | Some((subtree, c.id_alloc.map)) | 55 | Some((subtree, c.id_alloc.map)) |
55 | } | 56 | } |
56 | 57 | ||
@@ -593,7 +594,8 @@ impl<'a> TtTreeSink<'a> { | |||
593 | } | 594 | } |
594 | } | 595 | } |
595 | 596 | ||
596 | fn finish(self) -> (Parse<SyntaxNode>, TokenMap) { | 597 | fn finish(mut self) -> (Parse<SyntaxNode>, TokenMap) { |
598 | self.token_map.entries.shrink_to_fit(); | ||
597 | (self.inner.finish(), self.token_map) | 599 | (self.inner.finish(), self.token_map) |
598 | } | 600 | } |
599 | } | 601 | } |
diff --git a/crates/mbe/src/tests.rs b/crates/mbe/src/tests.rs index 9ff901e97..bd2977ebd 100644 --- a/crates/mbe/src/tests.rs +++ b/crates/mbe/src/tests.rs | |||
@@ -261,7 +261,6 @@ fn test_expr_order() { | |||
261 | 261 | ||
262 | let dump = format!("{:#?}", expanded); | 262 | let dump = format!("{:#?}", expanded); |
263 | assert_eq_text!( | 263 | assert_eq_text!( |
264 | dump.trim(), | ||
265 | r#"[email protected] | 264 | r#"[email protected] |
266 | [email protected] | 265 | [email protected] |
267 | [email protected] "fn" | 266 | [email protected] "fn" |
@@ -285,6 +284,7 @@ fn test_expr_order() { | |||
285 | [email protected] "2" | 284 | [email protected] "2" |
286 | [email protected] ";" | 285 | [email protected] ";" |
287 | [email protected] "}""#, | 286 | [email protected] "}""#, |
287 | dump.trim() | ||
288 | ); | 288 | ); |
289 | } | 289 | } |
290 | 290 | ||
@@ -989,7 +989,6 @@ fn test_tt_composite2() { | |||
989 | 989 | ||
990 | let res = format!("{:#?}", &node); | 990 | let res = format!("{:#?}", &node); |
991 | assert_eq_text!( | 991 | assert_eq_text!( |
992 | res.trim(), | ||
993 | r###"[email protected] | 992 | r###"[email protected] |
994 | [email protected] | 993 | [email protected] |
995 | [email protected] | 994 | [email protected] |
@@ -1003,7 +1002,8 @@ fn test_tt_composite2() { | |||
1003 | [email protected] ">" | 1002 | [email protected] ">" |
1004 | [email protected] " " | 1003 | [email protected] " " |
1005 | [email protected] "#" | 1004 | [email protected] "#" |
1006 | [email protected] ")""### | 1005 | [email protected] ")""###, |
1006 | res.trim() | ||
1007 | ); | 1007 | ); |
1008 | } | 1008 | } |
1009 | 1009 | ||
@@ -1742,7 +1742,7 @@ impl MacroFixture { | |||
1742 | fn assert_expand(&self, invocation: &str, expected: &str) { | 1742 | fn assert_expand(&self, invocation: &str, expected: &str) { |
1743 | let expansion = self.expand_tt(invocation); | 1743 | let expansion = self.expand_tt(invocation); |
1744 | let actual = format!("{:?}", expansion); | 1744 | let actual = format!("{:?}", expansion); |
1745 | test_utils::assert_eq_text!(&actual.trim(), &expected.trim()); | 1745 | test_utils::assert_eq_text!(&expected.trim(), &actual.trim()); |
1746 | } | 1746 | } |
1747 | 1747 | ||
1748 | fn assert_expand_items(&self, invocation: &str, expected: &str) -> &MacroFixture { | 1748 | fn assert_expand_items(&self, invocation: &str, expected: &str) -> &MacroFixture { |
@@ -1941,7 +1941,6 @@ fn test_no_space_after_semi_colon() { | |||
1941 | 1941 | ||
1942 | let dump = format!("{:#?}", expanded); | 1942 | let dump = format!("{:#?}", expanded); |
1943 | assert_eq_text!( | 1943 | assert_eq_text!( |
1944 | dump.trim(), | ||
1945 | r###"[email protected] | 1944 | r###"[email protected] |
1946 | [email protected] | 1945 | [email protected] |
1947 | [email protected] | 1946 | [email protected] |
@@ -1981,6 +1980,7 @@ fn test_no_space_after_semi_colon() { | |||
1981 | [email protected] | 1980 | [email protected] |
1982 | [email protected] "f" | 1981 | [email protected] "f" |
1983 | [email protected] ";""###, | 1982 | [email protected] ";""###, |
1983 | dump.trim() | ||
1984 | ); | 1984 | ); |
1985 | } | 1985 | } |
1986 | 1986 | ||
diff --git a/crates/parser/src/grammar.rs b/crates/parser/src/grammar.rs index bb9ffea8b..6913e9ec2 100644 --- a/crates/parser/src/grammar.rs +++ b/crates/parser/src/grammar.rs | |||
@@ -190,17 +190,25 @@ fn opt_visibility(p: &mut Parser) -> bool { | |||
190 | // test crate_visibility | 190 | // test crate_visibility |
191 | // pub(crate) struct S; | 191 | // pub(crate) struct S; |
192 | // pub(self) struct S; | 192 | // pub(self) struct S; |
193 | // pub(self) struct S; | 193 | // pub(super) struct S; |
194 | // pub(self) struct S; | ||
195 | 194 | ||
196 | // test pub_parens_typepath | 195 | // test pub_parens_typepath |
197 | // struct B(pub (super::A)); | 196 | // struct B(pub (super::A)); |
198 | // struct B(pub (crate::A,)); | 197 | // struct B(pub (crate::A,)); |
199 | T![crate] | T![self] | T![super] if p.nth(2) != T![:] => { | 198 | T![crate] | T![self] | T![super] if p.nth(2) != T![:] => { |
200 | p.bump_any(); | 199 | p.bump_any(); |
200 | let path_m = p.start(); | ||
201 | let path_segment_m = p.start(); | ||
202 | let name_ref_m = p.start(); | ||
201 | p.bump_any(); | 203 | p.bump_any(); |
204 | name_ref_m.complete(p, NAME_REF); | ||
205 | path_segment_m.complete(p, PATH_SEGMENT); | ||
206 | path_m.complete(p, PATH); | ||
202 | p.expect(T![')']); | 207 | p.expect(T![')']); |
203 | } | 208 | } |
209 | // test crate_visibility_in | ||
210 | // pub(in super::A) struct S; | ||
211 | // pub(in crate) struct S; | ||
204 | T![in] => { | 212 | T![in] => { |
205 | p.bump_any(); | 213 | p.bump_any(); |
206 | p.bump_any(); | 214 | p.bump_any(); |
diff --git a/crates/parser/src/grammar/items.rs b/crates/parser/src/grammar/items.rs index 2070ce163..1d894e907 100644 --- a/crates/parser/src/grammar/items.rs +++ b/crates/parser/src/grammar/items.rs | |||
@@ -270,7 +270,9 @@ fn extern_crate(p: &mut Parser, m: Marker) { | |||
270 | p.bump(T![crate]); | 270 | p.bump(T![crate]); |
271 | 271 | ||
272 | if p.at(T![self]) { | 272 | if p.at(T![self]) { |
273 | let m = p.start(); | ||
273 | p.bump(T![self]); | 274 | p.bump(T![self]); |
275 | m.complete(p, NAME_REF); | ||
274 | } else { | 276 | } else { |
275 | name_ref(p); | 277 | name_ref(p); |
276 | } | 278 | } |
diff --git a/crates/parser/src/grammar/items/traits.rs b/crates/parser/src/grammar/items/traits.rs index d076974ed..d3327271c 100644 --- a/crates/parser/src/grammar/items/traits.rs +++ b/crates/parser/src/grammar/items/traits.rs | |||
@@ -40,6 +40,10 @@ pub(super) fn impl_(p: &mut Parser) { | |||
40 | type_params::opt_generic_param_list(p); | 40 | type_params::opt_generic_param_list(p); |
41 | } | 41 | } |
42 | 42 | ||
43 | // test impl_def_const | ||
44 | // impl const Send for X {} | ||
45 | p.eat(T![const]); | ||
46 | |||
43 | // FIXME: never type | 47 | // FIXME: never type |
44 | // impl ! {} | 48 | // impl ! {} |
45 | 49 | ||
diff --git a/crates/parser/src/grammar/params.rs b/crates/parser/src/grammar/params.rs index 2d006a1d5..6a98d7368 100644 --- a/crates/parser/src/grammar/params.rs +++ b/crates/parser/src/grammar/params.rs | |||
@@ -156,7 +156,7 @@ fn variadic_param(p: &mut Parser) -> bool { | |||
156 | fn opt_self_param(p: &mut Parser, m: Marker) { | 156 | fn opt_self_param(p: &mut Parser, m: Marker) { |
157 | if p.at(T![self]) || p.at(T![mut]) && p.nth(1) == T![self] { | 157 | if p.at(T![self]) || p.at(T![mut]) && p.nth(1) == T![self] { |
158 | p.eat(T![mut]); | 158 | p.eat(T![mut]); |
159 | p.eat(T![self]); | 159 | self_as_name(p); |
160 | // test arb_self_types | 160 | // test arb_self_types |
161 | // impl S { | 161 | // impl S { |
162 | // fn a(self: &Self) {} | 162 | // fn a(self: &Self) {} |
@@ -169,24 +169,29 @@ fn opt_self_param(p: &mut Parser, m: Marker) { | |||
169 | let la1 = p.nth(1); | 169 | let la1 = p.nth(1); |
170 | let la2 = p.nth(2); | 170 | let la2 = p.nth(2); |
171 | let la3 = p.nth(3); | 171 | let la3 = p.nth(3); |
172 | let mut n_toks = match (p.current(), la1, la2, la3) { | 172 | if !matches!((p.current(), la1, la2, la3), |
173 | (T![&], T![self], _, _) => 2, | 173 | (T![&], T![self], _, _) |
174 | (T![&], T![mut], T![self], _) => 3, | 174 | | (T![&], T![mut], T![self], _) |
175 | (T![&], LIFETIME_IDENT, T![self], _) => 3, | 175 | | (T![&], LIFETIME_IDENT, T![self], _) |
176 | (T![&], LIFETIME_IDENT, T![mut], T![self]) => 4, | 176 | | (T![&], LIFETIME_IDENT, T![mut], T![self]) |
177 | _ => return m.abandon(p), | 177 | ) { |
178 | }; | 178 | return m.abandon(p); |
179 | p.bump_any(); | 179 | } |
180 | p.bump(T![&]); | ||
180 | if p.at(LIFETIME_IDENT) { | 181 | if p.at(LIFETIME_IDENT) { |
181 | lifetime(p); | 182 | lifetime(p); |
182 | n_toks -= 1; | ||
183 | } | ||
184 | for _ in 1..n_toks { | ||
185 | p.bump_any(); | ||
186 | } | 183 | } |
184 | p.eat(T![mut]); | ||
185 | self_as_name(p); | ||
187 | } | 186 | } |
188 | m.complete(p, SELF_PARAM); | 187 | m.complete(p, SELF_PARAM); |
189 | if !p.at(T![')']) { | 188 | if !p.at(T![')']) { |
190 | p.expect(T![,]); | 189 | p.expect(T![,]); |
191 | } | 190 | } |
192 | } | 191 | } |
192 | |||
193 | fn self_as_name(p: &mut Parser) { | ||
194 | let m = p.start(); | ||
195 | p.bump(T![self]); | ||
196 | m.complete(p, NAME); | ||
197 | } | ||
diff --git a/crates/parser/src/syntax_kind.rs b/crates/parser/src/syntax_kind.rs index 63204436c..9ea0e4f9b 100644 --- a/crates/parser/src/syntax_kind.rs +++ b/crates/parser/src/syntax_kind.rs | |||
@@ -6,6 +6,7 @@ mod generated; | |||
6 | pub use self::generated::SyntaxKind; | 6 | pub use self::generated::SyntaxKind; |
7 | 7 | ||
8 | impl From<u16> for SyntaxKind { | 8 | impl From<u16> for SyntaxKind { |
9 | #[inline] | ||
9 | fn from(d: u16) -> SyntaxKind { | 10 | fn from(d: u16) -> SyntaxKind { |
10 | assert!(d <= (SyntaxKind::__LAST as u16)); | 11 | assert!(d <= (SyntaxKind::__LAST as u16)); |
11 | unsafe { std::mem::transmute::<u16, SyntaxKind>(d) } | 12 | unsafe { std::mem::transmute::<u16, SyntaxKind>(d) } |
@@ -13,12 +14,14 @@ impl From<u16> for SyntaxKind { | |||
13 | } | 14 | } |
14 | 15 | ||
15 | impl From<SyntaxKind> for u16 { | 16 | impl From<SyntaxKind> for u16 { |
17 | #[inline] | ||
16 | fn from(k: SyntaxKind) -> u16 { | 18 | fn from(k: SyntaxKind) -> u16 { |
17 | k as u16 | 19 | k as u16 |
18 | } | 20 | } |
19 | } | 21 | } |
20 | 22 | ||
21 | impl SyntaxKind { | 23 | impl SyntaxKind { |
24 | #[inline] | ||
22 | pub fn is_trivia(self) -> bool { | 25 | pub fn is_trivia(self) -> bool { |
23 | matches!(self, SyntaxKind::WHITESPACE | SyntaxKind::COMMENT) | 26 | matches!(self, SyntaxKind::WHITESPACE | SyntaxKind::COMMENT) |
24 | } | 27 | } |
diff --git a/crates/parser/src/syntax_kind/generated.rs b/crates/parser/src/syntax_kind/generated.rs index 7d53cc4cd..bcefd183a 100644 --- a/crates/parser/src/syntax_kind/generated.rs +++ b/crates/parser/src/syntax_kind/generated.rs | |||
@@ -143,6 +143,7 @@ pub enum SyntaxKind { | |||
143 | MACRO_DEF, | 143 | MACRO_DEF, |
144 | PAREN_TYPE, | 144 | PAREN_TYPE, |
145 | TUPLE_TYPE, | 145 | TUPLE_TYPE, |
146 | MACRO_TYPE, | ||
146 | NEVER_TYPE, | 147 | NEVER_TYPE, |
147 | PATH_TYPE, | 148 | PATH_TYPE, |
148 | PTR_TYPE, | 149 | PTR_TYPE, |
diff --git a/crates/proc_macro_api/Cargo.toml b/crates/proc_macro_api/Cargo.toml index 1af2bbca7..078568cb2 100644 --- a/crates/proc_macro_api/Cargo.toml +++ b/crates/proc_macro_api/Cargo.toml | |||
@@ -11,7 +11,7 @@ doctest = false | |||
11 | 11 | ||
12 | [dependencies] | 12 | [dependencies] |
13 | serde = { version = "1.0", features = ["derive"] } | 13 | serde = { version = "1.0", features = ["derive"] } |
14 | serde_json = "1.0" | 14 | serde_json = { version = "1.0", features = ["unbounded_depth"] } |
15 | log = "0.4.8" | 15 | log = "0.4.8" |
16 | crossbeam-channel = "0.5.0" | 16 | crossbeam-channel = "0.5.0" |
17 | jod-thread = "0.1.1" | 17 | jod-thread = "0.1.1" |
diff --git a/crates/proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt b/crates/proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt index e6fd21610..ea34e688f 100644 --- a/crates/proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt +++ b/crates/proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt | |||
@@ -59,7 +59,7 @@ SUBTREE $ | |||
59 | IDENT _serde 4294967295 | 59 | IDENT _serde 4294967295 |
60 | PUNCH : [joint] 4294967295 | 60 | PUNCH : [joint] 4294967295 |
61 | PUNCH : [alone] 4294967295 | 61 | PUNCH : [alone] 4294967295 |
62 | IDENT export 4294967295 | 62 | IDENT __private 4294967295 |
63 | PUNCH : [joint] 4294967295 | 63 | PUNCH : [joint] 4294967295 |
64 | PUNCH : [alone] 4294967295 | 64 | PUNCH : [alone] 4294967295 |
65 | IDENT Ok 4294967295 | 65 | IDENT Ok 4294967295 |
@@ -72,7 +72,7 @@ SUBTREE $ | |||
72 | IDENT _serde 4294967295 | 72 | IDENT _serde 4294967295 |
73 | PUNCH : [joint] 4294967295 | 73 | PUNCH : [joint] 4294967295 |
74 | PUNCH : [alone] 4294967295 | 74 | PUNCH : [alone] 4294967295 |
75 | IDENT export 4294967295 | 75 | IDENT __private 4294967295 |
76 | PUNCH : [joint] 4294967295 | 76 | PUNCH : [joint] 4294967295 |
77 | PUNCH : [alone] 4294967295 | 77 | PUNCH : [alone] 4294967295 |
78 | IDENT Err 4294967295 | 78 | IDENT Err 4294967295 |
@@ -85,7 +85,7 @@ SUBTREE $ | |||
85 | IDENT _serde 4294967295 | 85 | IDENT _serde 4294967295 |
86 | PUNCH : [joint] 4294967295 | 86 | PUNCH : [joint] 4294967295 |
87 | PUNCH : [alone] 4294967295 | 87 | PUNCH : [alone] 4294967295 |
88 | IDENT export 4294967295 | 88 | IDENT __private 4294967295 |
89 | PUNCH : [joint] 4294967295 | 89 | PUNCH : [joint] 4294967295 |
90 | PUNCH : [alone] 4294967295 | 90 | PUNCH : [alone] 4294967295 |
91 | IDENT Err 4294967295 | 91 | IDENT Err 4294967295 |
@@ -120,7 +120,7 @@ SUBTREE $ | |||
120 | IDENT _serde 4294967295 | 120 | IDENT _serde 4294967295 |
121 | PUNCH : [joint] 4294967295 | 121 | PUNCH : [joint] 4294967295 |
122 | PUNCH : [alone] 4294967295 | 122 | PUNCH : [alone] 4294967295 |
123 | IDENT export 4294967295 | 123 | IDENT __private 4294967295 |
124 | PUNCH : [joint] 4294967295 | 124 | PUNCH : [joint] 4294967295 |
125 | PUNCH : [alone] 4294967295 | 125 | PUNCH : [alone] 4294967295 |
126 | IDENT Result 4294967295 | 126 | IDENT Result 4294967295 |
diff --git a/crates/proc_macro_srv/src/tests/mod.rs b/crates/proc_macro_srv/src/tests/mod.rs index 1a827cbd7..fd54f8dfd 100644 --- a/crates/proc_macro_srv/src/tests/mod.rs +++ b/crates/proc_macro_srv/src/tests/mod.rs | |||
@@ -38,9 +38,9 @@ fn test_derive_proc_macro_list() { | |||
38 | let res = list("serde_derive", "1").join("\n"); | 38 | let res = list("serde_derive", "1").join("\n"); |
39 | 39 | ||
40 | assert_eq_text!( | 40 | assert_eq_text!( |
41 | &res, | ||
42 | r#"Serialize [CustomDerive] | 41 | r#"Serialize [CustomDerive] |
43 | Deserialize [CustomDerive]"# | 42 | Deserialize [CustomDerive]"#, |
43 | &res | ||
44 | ); | 44 | ); |
45 | } | 45 | } |
46 | 46 | ||
@@ -50,9 +50,9 @@ fn list_test_macros() { | |||
50 | let res = list("proc_macro_test", "0.0.0").join("\n"); | 50 | let res = list("proc_macro_test", "0.0.0").join("\n"); |
51 | 51 | ||
52 | assert_eq_text!( | 52 | assert_eq_text!( |
53 | &res, | ||
54 | r#"function_like_macro [FuncLike] | 53 | r#"function_like_macro [FuncLike] |
55 | attribute_macro [Attr] | 54 | attribute_macro [Attr] |
56 | DummyTrait [CustomDerive]"# | 55 | DummyTrait [CustomDerive]"#, |
56 | &res | ||
57 | ); | 57 | ); |
58 | } | 58 | } |
diff --git a/crates/proc_macro_srv/src/tests/utils.rs b/crates/proc_macro_srv/src/tests/utils.rs index 36942147d..196abb8fc 100644 --- a/crates/proc_macro_srv/src/tests/utils.rs +++ b/crates/proc_macro_srv/src/tests/utils.rs | |||
@@ -52,7 +52,7 @@ pub fn assert_expand( | |||
52 | let fixture = parse_string(ra_fixture).unwrap(); | 52 | let fixture = parse_string(ra_fixture).unwrap(); |
53 | 53 | ||
54 | let res = expander.expand(macro_name, &fixture.subtree, None).unwrap(); | 54 | let res = expander.expand(macro_name, &fixture.subtree, None).unwrap(); |
55 | assert_eq_text!(&format!("{:?}", res), &expect.trim()); | 55 | assert_eq_text!(&expect.trim(), &format!("{:?}", res)); |
56 | } | 56 | } |
57 | 57 | ||
58 | pub fn list(crate_name: &str, version: &str) -> Vec<String> { | 58 | pub fn list(crate_name: &str, version: &str) -> Vec<String> { |
diff --git a/crates/profile/Cargo.toml b/crates/profile/Cargo.toml index 9c7ce26be..f7231c2b8 100644 --- a/crates/profile/Cargo.toml +++ b/crates/profile/Cargo.toml | |||
@@ -14,12 +14,14 @@ once_cell = "1.3.1" | |||
14 | cfg-if = "1" | 14 | cfg-if = "1" |
15 | libc = "0.2.73" | 15 | libc = "0.2.73" |
16 | la-arena = { version = "0.2.0", path = "../../lib/arena" } | 16 | la-arena = { version = "0.2.0", path = "../../lib/arena" } |
17 | jemalloc-ctl = { version = "0.3.3", optional = true } | ||
17 | 18 | ||
18 | [target.'cfg(target_os = "linux")'.dependencies] | 19 | [target.'cfg(target_os = "linux")'.dependencies] |
19 | perf-event = "0.4" | 20 | perf-event = "0.4" |
20 | 21 | ||
21 | [features] | 22 | [features] |
22 | cpu_profiler = [] | 23 | cpu_profiler = [] |
24 | jemalloc = ["jemalloc-ctl"] | ||
23 | 25 | ||
24 | # Uncomment to enable for the whole crate graph | 26 | # Uncomment to enable for the whole crate graph |
25 | # default = [ "cpu_profiler" ] | 27 | # default = [ "cpu_profiler" ] |
diff --git a/crates/profile/src/memory_usage.rs b/crates/profile/src/memory_usage.rs index 83390212a..cb4e54447 100644 --- a/crates/profile/src/memory_usage.rs +++ b/crates/profile/src/memory_usage.rs | |||
@@ -24,7 +24,12 @@ impl std::ops::Sub for MemoryUsage { | |||
24 | impl MemoryUsage { | 24 | impl MemoryUsage { |
25 | pub fn current() -> MemoryUsage { | 25 | pub fn current() -> MemoryUsage { |
26 | cfg_if! { | 26 | cfg_if! { |
27 | if #[cfg(all(target_os = "linux", target_env = "gnu"))] { | 27 | if #[cfg(all(feature = "jemalloc", not(target_env = "msvc")))] { |
28 | jemalloc_ctl::epoch::advance().unwrap(); | ||
29 | MemoryUsage { | ||
30 | allocated: Bytes(jemalloc_ctl::stats::allocated::read().unwrap() as isize), | ||
31 | } | ||
32 | } else if #[cfg(all(target_os = "linux", target_env = "gnu"))] { | ||
28 | // Note: This is incredibly slow. | 33 | // Note: This is incredibly slow. |
29 | let alloc = unsafe { libc::mallinfo() }.uordblks as isize; | 34 | let alloc = unsafe { libc::mallinfo() }.uordblks as isize; |
30 | MemoryUsage { allocated: Bytes(alloc) } | 35 | MemoryUsage { allocated: Bytes(alloc) } |
diff --git a/crates/project_model/Cargo.toml b/crates/project_model/Cargo.toml index 436eff16b..293cb5bfe 100644 --- a/crates/project_model/Cargo.toml +++ b/crates/project_model/Cargo.toml | |||
@@ -25,3 +25,4 @@ toolchain = { path = "../toolchain", version = "0.0.0" } | |||
25 | proc_macro_api = { path = "../proc_macro_api", version = "0.0.0" } | 25 | proc_macro_api = { path = "../proc_macro_api", version = "0.0.0" } |
26 | paths = { path = "../paths", version = "0.0.0" } | 26 | paths = { path = "../paths", version = "0.0.0" } |
27 | stdx = { path = "../stdx", version = "0.0.0" } | 27 | stdx = { path = "../stdx", version = "0.0.0" } |
28 | profile = { path = "../profile", version = "0.0.0" } | ||
diff --git a/crates/project_model/src/lib.rs b/crates/project_model/src/lib.rs index aabb7a47d..970a7e140 100644 --- a/crates/project_model/src/lib.rs +++ b/crates/project_model/src/lib.rs | |||
@@ -5,6 +5,7 @@ mod cfg_flag; | |||
5 | mod project_json; | 5 | mod project_json; |
6 | mod sysroot; | 6 | mod sysroot; |
7 | mod workspace; | 7 | mod workspace; |
8 | mod rustc_cfg; | ||
8 | 9 | ||
9 | use std::{ | 10 | use std::{ |
10 | fs::{read_dir, ReadDir}, | 11 | fs::{read_dir, ReadDir}, |
diff --git a/crates/project_model/src/rustc_cfg.rs b/crates/project_model/src/rustc_cfg.rs new file mode 100644 index 000000000..4a7bd8ae3 --- /dev/null +++ b/crates/project_model/src/rustc_cfg.rs | |||
@@ -0,0 +1,34 @@ | |||
1 | //! Runs `rustc --print cfg` to get built-in cfg flags. | ||
2 | |||
3 | use std::process::Command; | ||
4 | |||
5 | use crate::{cfg_flag::CfgFlag, utf8_stdout}; | ||
6 | |||
7 | pub(crate) fn get(target: Option<&str>) -> Vec<CfgFlag> { | ||
8 | let _p = profile::span("rustc_cfg::get"); | ||
9 | let mut res = Vec::new(); | ||
10 | |||
11 | // Some nightly-only cfgs, which are required for stdlib | ||
12 | res.push(CfgFlag::Atom("target_thread_local".into())); | ||
13 | for &ty in ["8", "16", "32", "64", "cas", "ptr"].iter() { | ||
14 | for &key in ["target_has_atomic", "target_has_atomic_load_store"].iter() { | ||
15 | res.push(CfgFlag::KeyValue { key: key.to_string(), value: ty.into() }); | ||
16 | } | ||
17 | } | ||
18 | |||
19 | let rustc_cfgs = { | ||
20 | let mut cmd = Command::new(toolchain::rustc()); | ||
21 | cmd.args(&["--print", "cfg", "-O"]); | ||
22 | if let Some(target) = target { | ||
23 | cmd.args(&["--target", target]); | ||
24 | } | ||
25 | utf8_stdout(cmd) | ||
26 | }; | ||
27 | |||
28 | match rustc_cfgs { | ||
29 | Ok(rustc_cfgs) => res.extend(rustc_cfgs.lines().map(|it| it.parse().unwrap())), | ||
30 | Err(e) => log::error!("failed to get rustc cfgs: {:#}", e), | ||
31 | } | ||
32 | |||
33 | res | ||
34 | } | ||
diff --git a/crates/project_model/src/workspace.rs b/crates/project_model/src/workspace.rs index 06a0be284..8e0481ae9 100644 --- a/crates/project_model/src/workspace.rs +++ b/crates/project_model/src/workspace.rs | |||
@@ -16,7 +16,7 @@ use proc_macro_api::ProcMacroClient; | |||
16 | use rustc_hash::{FxHashMap, FxHashSet}; | 16 | use rustc_hash::{FxHashMap, FxHashSet}; |
17 | 17 | ||
18 | use crate::{ | 18 | use crate::{ |
19 | cargo_workspace, cfg_flag::CfgFlag, sysroot::SysrootCrate, utf8_stdout, CargoConfig, | 19 | cargo_workspace, cfg_flag::CfgFlag, rustc_cfg, sysroot::SysrootCrate, utf8_stdout, CargoConfig, |
20 | CargoWorkspace, ProjectJson, ProjectManifest, Sysroot, TargetKind, | 20 | CargoWorkspace, ProjectJson, ProjectManifest, Sysroot, TargetKind, |
21 | }; | 21 | }; |
22 | 22 | ||
@@ -34,15 +34,25 @@ pub struct PackageRoot { | |||
34 | #[derive(Clone, Eq, PartialEq)] | 34 | #[derive(Clone, Eq, PartialEq)] |
35 | pub enum ProjectWorkspace { | 35 | pub enum ProjectWorkspace { |
36 | /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`. | 36 | /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`. |
37 | Cargo { cargo: CargoWorkspace, sysroot: Sysroot, rustc: Option<CargoWorkspace> }, | 37 | Cargo { |
38 | cargo: CargoWorkspace, | ||
39 | sysroot: Sysroot, | ||
40 | rustc: Option<CargoWorkspace>, | ||
41 | /// Holds cfg flags for the current target. We get those by running | ||
42 | /// `rustc --print cfg`. | ||
43 | /// | ||
44 | /// FIXME: make this a per-crate map, as, eg, build.rs might have a | ||
45 | /// different target. | ||
46 | rustc_cfg: Vec<CfgFlag>, | ||
47 | }, | ||
38 | /// Project workspace was manually specified using a `rust-project.json` file. | 48 | /// Project workspace was manually specified using a `rust-project.json` file. |
39 | Json { project: ProjectJson, sysroot: Option<Sysroot> }, | 49 | Json { project: ProjectJson, sysroot: Option<Sysroot>, rustc_cfg: Vec<CfgFlag> }, |
40 | } | 50 | } |
41 | 51 | ||
42 | impl fmt::Debug for ProjectWorkspace { | 52 | impl fmt::Debug for ProjectWorkspace { |
43 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | 53 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
44 | match self { | 54 | match self { |
45 | ProjectWorkspace::Cargo { cargo, sysroot, rustc } => f | 55 | ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } => f |
46 | .debug_struct("Cargo") | 56 | .debug_struct("Cargo") |
47 | .field("n_packages", &cargo.packages().len()) | 57 | .field("n_packages", &cargo.packages().len()) |
48 | .field("n_sysroot_crates", &sysroot.crates().len()) | 58 | .field("n_sysroot_crates", &sysroot.crates().len()) |
@@ -50,13 +60,15 @@ impl fmt::Debug for ProjectWorkspace { | |||
50 | "n_rustc_compiler_crates", | 60 | "n_rustc_compiler_crates", |
51 | &rustc.as_ref().map_or(0, |rc| rc.packages().len()), | 61 | &rustc.as_ref().map_or(0, |rc| rc.packages().len()), |
52 | ) | 62 | ) |
63 | .field("rustc_cfg", rustc_cfg) | ||
53 | .finish(), | 64 | .finish(), |
54 | ProjectWorkspace::Json { project, sysroot } => { | 65 | ProjectWorkspace::Json { project, sysroot, rustc_cfg } => { |
55 | let mut debug_struct = f.debug_struct("Json"); | 66 | let mut debug_struct = f.debug_struct("Json"); |
56 | debug_struct.field("n_crates", &project.n_crates()); | 67 | debug_struct.field("n_crates", &project.n_crates()); |
57 | if let Some(sysroot) = sysroot { | 68 | if let Some(sysroot) = sysroot { |
58 | debug_struct.field("n_sysroot_crates", &sysroot.crates().len()); | 69 | debug_struct.field("n_sysroot_crates", &sysroot.crates().len()); |
59 | } | 70 | } |
71 | debug_struct.field("rustc_cfg", rustc_cfg); | ||
60 | debug_struct.finish() | 72 | debug_struct.finish() |
61 | } | 73 | } |
62 | } | 74 | } |
@@ -79,7 +91,7 @@ impl ProjectWorkspace { | |||
79 | })?; | 91 | })?; |
80 | let project_location = project_json.parent().unwrap().to_path_buf(); | 92 | let project_location = project_json.parent().unwrap().to_path_buf(); |
81 | let project_json = ProjectJson::new(&project_location, data); | 93 | let project_json = ProjectJson::new(&project_location, data); |
82 | ProjectWorkspace::load_inline(project_json)? | 94 | ProjectWorkspace::load_inline(project_json, config.target.as_deref())? |
83 | } | 95 | } |
84 | ProjectManifest::CargoToml(cargo_toml) => { | 96 | ProjectManifest::CargoToml(cargo_toml) => { |
85 | let cargo_version = utf8_stdout({ | 97 | let cargo_version = utf8_stdout({ |
@@ -117,21 +129,24 @@ impl ProjectWorkspace { | |||
117 | } else { | 129 | } else { |
118 | None | 130 | None |
119 | }; | 131 | }; |
120 | 132 | let rustc_cfg = rustc_cfg::get(config.target.as_deref()); | |
121 | ProjectWorkspace::Cargo { cargo, sysroot, rustc } | 133 | ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } |
122 | } | 134 | } |
123 | }; | 135 | }; |
124 | 136 | ||
125 | Ok(res) | 137 | Ok(res) |
126 | } | 138 | } |
127 | 139 | ||
128 | pub fn load_inline(project_json: ProjectJson) -> Result<ProjectWorkspace> { | 140 | pub fn load_inline( |
141 | project_json: ProjectJson, | ||
142 | target: Option<&str>, | ||
143 | ) -> Result<ProjectWorkspace> { | ||
129 | let sysroot = match &project_json.sysroot_src { | 144 | let sysroot = match &project_json.sysroot_src { |
130 | Some(path) => Some(Sysroot::load(path)?), | 145 | Some(path) => Some(Sysroot::load(path)?), |
131 | None => None, | 146 | None => None, |
132 | }; | 147 | }; |
133 | 148 | let rustc_cfg = rustc_cfg::get(target); | |
134 | Ok(ProjectWorkspace::Json { project: project_json, sysroot }) | 149 | Ok(ProjectWorkspace::Json { project: project_json, sysroot, rustc_cfg }) |
135 | } | 150 | } |
136 | 151 | ||
137 | /// Returns the roots for the current `ProjectWorkspace` | 152 | /// Returns the roots for the current `ProjectWorkspace` |
@@ -139,7 +154,7 @@ impl ProjectWorkspace { | |||
139 | /// the root is a member of the current workspace | 154 | /// the root is a member of the current workspace |
140 | pub fn to_roots(&self) -> Vec<PackageRoot> { | 155 | pub fn to_roots(&self) -> Vec<PackageRoot> { |
141 | match self { | 156 | match self { |
142 | ProjectWorkspace::Json { project, sysroot } => project | 157 | ProjectWorkspace::Json { project, sysroot, rustc_cfg: _ } => project |
143 | .crates() | 158 | .crates() |
144 | .map(|(_, krate)| PackageRoot { | 159 | .map(|(_, krate)| PackageRoot { |
145 | is_member: krate.is_workspace_member, | 160 | is_member: krate.is_workspace_member, |
@@ -156,7 +171,7 @@ impl ProjectWorkspace { | |||
156 | }) | 171 | }) |
157 | })) | 172 | })) |
158 | .collect::<Vec<_>>(), | 173 | .collect::<Vec<_>>(), |
159 | ProjectWorkspace::Cargo { cargo, sysroot, rustc } => cargo | 174 | ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg: _ } => cargo |
160 | .packages() | 175 | .packages() |
161 | .map(|pkg| { | 176 | .map(|pkg| { |
162 | let is_member = cargo[pkg].is_member; | 177 | let is_member = cargo[pkg].is_member; |
@@ -194,7 +209,7 @@ impl ProjectWorkspace { | |||
194 | pub fn n_packages(&self) -> usize { | 209 | pub fn n_packages(&self) -> usize { |
195 | match self { | 210 | match self { |
196 | ProjectWorkspace::Json { project, .. } => project.n_crates(), | 211 | ProjectWorkspace::Json { project, .. } => project.n_crates(), |
197 | ProjectWorkspace::Cargo { cargo, sysroot, rustc } => { | 212 | ProjectWorkspace::Cargo { cargo, sysroot, rustc, .. } => { |
198 | let rustc_package_len = rustc.as_ref().map_or(0, |rc| rc.packages().len()); | 213 | let rustc_package_len = rustc.as_ref().map_or(0, |rc| rc.packages().len()); |
199 | cargo.packages().len() + sysroot.crates().len() + rustc_package_len | 214 | cargo.packages().len() + sysroot.crates().len() + rustc_package_len |
200 | } | 215 | } |
@@ -203,22 +218,31 @@ impl ProjectWorkspace { | |||
203 | 218 | ||
204 | pub fn to_crate_graph( | 219 | pub fn to_crate_graph( |
205 | &self, | 220 | &self, |
206 | target: Option<&str>, | ||
207 | proc_macro_client: Option<&ProcMacroClient>, | 221 | proc_macro_client: Option<&ProcMacroClient>, |
208 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, | 222 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, |
209 | ) -> CrateGraph { | 223 | ) -> CrateGraph { |
224 | let _p = profile::span("ProjectWorkspace::to_crate_graph"); | ||
210 | let proc_macro_loader = |path: &Path| match proc_macro_client { | 225 | let proc_macro_loader = |path: &Path| match proc_macro_client { |
211 | Some(client) => client.by_dylib_path(path), | 226 | Some(client) => client.by_dylib_path(path), |
212 | None => Vec::new(), | 227 | None => Vec::new(), |
213 | }; | 228 | }; |
214 | 229 | ||
215 | let mut crate_graph = match self { | 230 | let mut crate_graph = match self { |
216 | ProjectWorkspace::Json { project, sysroot } => { | 231 | ProjectWorkspace::Json { project, sysroot, rustc_cfg } => project_json_to_crate_graph( |
217 | project_json_to_crate_graph(target, &proc_macro_loader, load, project, sysroot) | 232 | rustc_cfg.clone(), |
218 | } | 233 | &proc_macro_loader, |
219 | ProjectWorkspace::Cargo { cargo, sysroot, rustc } => { | 234 | load, |
220 | cargo_to_crate_graph(target, &proc_macro_loader, load, cargo, sysroot, rustc) | 235 | project, |
221 | } | 236 | sysroot, |
237 | ), | ||
238 | ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } => cargo_to_crate_graph( | ||
239 | rustc_cfg.clone(), | ||
240 | &proc_macro_loader, | ||
241 | load, | ||
242 | cargo, | ||
243 | sysroot, | ||
244 | rustc, | ||
245 | ), | ||
222 | }; | 246 | }; |
223 | if crate_graph.patch_cfg_if() { | 247 | if crate_graph.patch_cfg_if() { |
224 | log::debug!("Patched std to depend on cfg-if") | 248 | log::debug!("Patched std to depend on cfg-if") |
@@ -230,7 +254,7 @@ impl ProjectWorkspace { | |||
230 | } | 254 | } |
231 | 255 | ||
232 | fn project_json_to_crate_graph( | 256 | fn project_json_to_crate_graph( |
233 | target: Option<&str>, | 257 | rustc_cfg: Vec<CfgFlag>, |
234 | proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>, | 258 | proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>, |
235 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, | 259 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, |
236 | project: &ProjectJson, | 260 | project: &ProjectJson, |
@@ -239,9 +263,9 @@ fn project_json_to_crate_graph( | |||
239 | let mut crate_graph = CrateGraph::default(); | 263 | let mut crate_graph = CrateGraph::default(); |
240 | let sysroot_deps = sysroot | 264 | let sysroot_deps = sysroot |
241 | .as_ref() | 265 | .as_ref() |
242 | .map(|sysroot| sysroot_to_crate_graph(&mut crate_graph, sysroot, target, load)); | 266 | .map(|sysroot| sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load)); |
243 | 267 | ||
244 | let mut cfg_cache: FxHashMap<Option<&str>, Vec<CfgFlag>> = FxHashMap::default(); | 268 | let mut cfg_cache: FxHashMap<&str, Vec<CfgFlag>> = FxHashMap::default(); |
245 | let crates: FxHashMap<CrateId, CrateId> = project | 269 | let crates: FxHashMap<CrateId, CrateId> = project |
246 | .crates() | 270 | .crates() |
247 | .filter_map(|(crate_id, krate)| { | 271 | .filter_map(|(crate_id, krate)| { |
@@ -253,9 +277,12 @@ fn project_json_to_crate_graph( | |||
253 | let env = krate.env.clone().into_iter().collect(); | 277 | let env = krate.env.clone().into_iter().collect(); |
254 | let proc_macro = krate.proc_macro_dylib_path.clone().map(|it| proc_macro_loader(&it)); | 278 | let proc_macro = krate.proc_macro_dylib_path.clone().map(|it| proc_macro_loader(&it)); |
255 | 279 | ||
256 | let target = krate.target.as_deref().or(target); | 280 | let target_cfgs = match krate.target.as_deref() { |
257 | let target_cfgs = | 281 | Some(target) => { |
258 | cfg_cache.entry(target).or_insert_with(|| get_rustc_cfg_options(target)); | 282 | cfg_cache.entry(target).or_insert_with(|| rustc_cfg::get(Some(target))) |
283 | } | ||
284 | None => &rustc_cfg, | ||
285 | }; | ||
259 | 286 | ||
260 | let mut cfg_options = CfgOptions::default(); | 287 | let mut cfg_options = CfgOptions::default(); |
261 | cfg_options.extend(target_cfgs.iter().chain(krate.cfg.iter()).cloned()); | 288 | cfg_options.extend(target_cfgs.iter().chain(krate.cfg.iter()).cloned()); |
@@ -292,19 +319,20 @@ fn project_json_to_crate_graph( | |||
292 | } | 319 | } |
293 | 320 | ||
294 | fn cargo_to_crate_graph( | 321 | fn cargo_to_crate_graph( |
295 | target: Option<&str>, | 322 | rustc_cfg: Vec<CfgFlag>, |
296 | proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>, | 323 | proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>, |
297 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, | 324 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, |
298 | cargo: &CargoWorkspace, | 325 | cargo: &CargoWorkspace, |
299 | sysroot: &Sysroot, | 326 | sysroot: &Sysroot, |
300 | rustc: &Option<CargoWorkspace>, | 327 | rustc: &Option<CargoWorkspace>, |
301 | ) -> CrateGraph { | 328 | ) -> CrateGraph { |
329 | let _p = profile::span("cargo_to_crate_graph"); | ||
302 | let mut crate_graph = CrateGraph::default(); | 330 | let mut crate_graph = CrateGraph::default(); |
303 | let (public_deps, libproc_macro) = | 331 | let (public_deps, libproc_macro) = |
304 | sysroot_to_crate_graph(&mut crate_graph, sysroot, target, load); | 332 | sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load); |
305 | 333 | ||
306 | let mut cfg_options = CfgOptions::default(); | 334 | let mut cfg_options = CfgOptions::default(); |
307 | cfg_options.extend(get_rustc_cfg_options(target)); | 335 | cfg_options.extend(rustc_cfg); |
308 | 336 | ||
309 | let mut pkg_to_lib_crate = FxHashMap::default(); | 337 | let mut pkg_to_lib_crate = FxHashMap::default(); |
310 | 338 | ||
@@ -490,11 +518,12 @@ fn add_target_crate_root( | |||
490 | fn sysroot_to_crate_graph( | 518 | fn sysroot_to_crate_graph( |
491 | crate_graph: &mut CrateGraph, | 519 | crate_graph: &mut CrateGraph, |
492 | sysroot: &Sysroot, | 520 | sysroot: &Sysroot, |
493 | target: Option<&str>, | 521 | rustc_cfg: Vec<CfgFlag>, |
494 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, | 522 | load: &mut dyn FnMut(&AbsPath) -> Option<FileId>, |
495 | ) -> (Vec<(CrateName, CrateId)>, Option<CrateId>) { | 523 | ) -> (Vec<(CrateName, CrateId)>, Option<CrateId>) { |
524 | let _p = profile::span("sysroot_to_crate_graph"); | ||
496 | let mut cfg_options = CfgOptions::default(); | 525 | let mut cfg_options = CfgOptions::default(); |
497 | cfg_options.extend(get_rustc_cfg_options(target)); | 526 | cfg_options.extend(rustc_cfg); |
498 | let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = sysroot | 527 | let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = sysroot |
499 | .crates() | 528 | .crates() |
500 | .filter_map(|krate| { | 529 | .filter_map(|krate| { |
@@ -533,34 +562,6 @@ fn sysroot_to_crate_graph( | |||
533 | (public_deps, libproc_macro) | 562 | (public_deps, libproc_macro) |
534 | } | 563 | } |
535 | 564 | ||
536 | fn get_rustc_cfg_options(target: Option<&str>) -> Vec<CfgFlag> { | ||
537 | let mut res = Vec::new(); | ||
538 | |||
539 | // Some nightly-only cfgs, which are required for stdlib | ||
540 | res.push(CfgFlag::Atom("target_thread_local".into())); | ||
541 | for &ty in ["8", "16", "32", "64", "cas", "ptr"].iter() { | ||
542 | for &key in ["target_has_atomic", "target_has_atomic_load_store"].iter() { | ||
543 | res.push(CfgFlag::KeyValue { key: key.to_string(), value: ty.into() }); | ||
544 | } | ||
545 | } | ||
546 | |||
547 | let rustc_cfgs = { | ||
548 | let mut cmd = Command::new(toolchain::rustc()); | ||
549 | cmd.args(&["--print", "cfg", "-O"]); | ||
550 | if let Some(target) = target { | ||
551 | cmd.args(&["--target", target]); | ||
552 | } | ||
553 | utf8_stdout(cmd) | ||
554 | }; | ||
555 | |||
556 | match rustc_cfgs { | ||
557 | Ok(rustc_cfgs) => res.extend(rustc_cfgs.lines().map(|it| it.parse().unwrap())), | ||
558 | Err(e) => log::error!("failed to get rustc cfgs: {:#}", e), | ||
559 | } | ||
560 | |||
561 | res | ||
562 | } | ||
563 | |||
564 | fn add_dep(graph: &mut CrateGraph, from: CrateId, name: CrateName, to: CrateId) { | 565 | fn add_dep(graph: &mut CrateGraph, from: CrateId, name: CrateName, to: CrateId) { |
565 | if let Err(err) = graph.add_dep(from, name, to) { | 566 | if let Err(err) = graph.add_dep(from, name, to) { |
566 | log::error!("{}", err) | 567 | log::error!("{}", err) |
diff --git a/crates/rust-analyzer/Cargo.toml b/crates/rust-analyzer/Cargo.toml index af7b86ead..3cb45b030 100644 --- a/crates/rust-analyzer/Cargo.toml +++ b/crates/rust-analyzer/Cargo.toml | |||
@@ -61,8 +61,14 @@ proc_macro_srv = { path = "../proc_macro_srv", version = "0.0.0" } | |||
61 | [target.'cfg(windows)'.dependencies] | 61 | [target.'cfg(windows)'.dependencies] |
62 | winapi = "0.3.8" | 62 | winapi = "0.3.8" |
63 | 63 | ||
64 | [target.'cfg(not(target_env = "msvc"))'.dependencies] | ||
65 | jemallocator = { version = "0.3.2", optional = true } | ||
66 | |||
64 | [dev-dependencies] | 67 | [dev-dependencies] |
65 | expect-test = "1.1" | 68 | expect-test = "1.1" |
66 | test_utils = { path = "../test_utils" } | 69 | test_utils = { path = "../test_utils" } |
67 | mbe = { path = "../mbe" } | 70 | mbe = { path = "../mbe" } |
68 | tt = { path = "../tt" } | 71 | tt = { path = "../tt" } |
72 | |||
73 | [features] | ||
74 | jemalloc = ["jemallocator", "profile/jemalloc"] | ||
diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index bf42654a8..2f7f94a39 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs | |||
@@ -15,6 +15,10 @@ use vfs::AbsPathBuf; | |||
15 | #[global_allocator] | 15 | #[global_allocator] |
16 | static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; | 16 | static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; |
17 | 17 | ||
18 | #[cfg(all(feature = "jemalloc", not(target_env = "msvc")))] | ||
19 | #[global_allocator] | ||
20 | static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; | ||
21 | |||
18 | fn main() { | 22 | fn main() { |
19 | if let Err(err) = try_main() { | 23 | if let Err(err) = try_main() { |
20 | eprintln!("{}", err); | 24 | eprintln!("{}", err); |
diff --git a/crates/rust-analyzer/src/cli/analysis_bench.rs b/crates/rust-analyzer/src/cli/analysis_bench.rs index a02c8327f..a01b49822 100644 --- a/crates/rust-analyzer/src/cli/analysis_bench.rs +++ b/crates/rust-analyzer/src/cli/analysis_bench.rs | |||
@@ -93,7 +93,7 @@ impl BenchCmd { | |||
93 | if is_completion { | 93 | if is_completion { |
94 | let options = CompletionConfig { | 94 | let options = CompletionConfig { |
95 | enable_postfix_completions: true, | 95 | enable_postfix_completions: true, |
96 | enable_autoimport_completions: true, | 96 | enable_imports_on_the_fly: true, |
97 | add_call_parenthesis: true, | 97 | add_call_parenthesis: true, |
98 | add_call_argument_snippets: true, | 98 | add_call_argument_snippets: true, |
99 | snippet_cap: SnippetCap::new(true), | 99 | snippet_cap: SnippetCap::new(true), |
diff --git a/crates/rust-analyzer/src/cli/load_cargo.rs b/crates/rust-analyzer/src/cli/load_cargo.rs index 31a16ca46..16ccab781 100644 --- a/crates/rust-analyzer/src/cli/load_cargo.rs +++ b/crates/rust-analyzer/src/cli/load_cargo.rs | |||
@@ -39,7 +39,7 @@ pub fn load_cargo( | |||
39 | None | 39 | None |
40 | }; | 40 | }; |
41 | 41 | ||
42 | let crate_graph = ws.to_crate_graph(None, proc_macro_client.as_ref(), &mut |path: &AbsPath| { | 42 | let crate_graph = ws.to_crate_graph(proc_macro_client.as_ref(), &mut |path: &AbsPath| { |
43 | let contents = loader.load_sync(path); | 43 | let contents = loader.load_sync(path); |
44 | let path = vfs::VfsPath::from(path.to_path_buf()); | 44 | let path = vfs::VfsPath::from(path.to_path_buf()); |
45 | vfs.set_file_contents(path.clone(), contents); | 45 | vfs.set_file_contents(path.clone(), contents); |
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index ce9655818..3ddb9e19a 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs | |||
@@ -559,7 +559,7 @@ impl Config { | |||
559 | pub fn completion(&self) -> CompletionConfig { | 559 | pub fn completion(&self) -> CompletionConfig { |
560 | CompletionConfig { | 560 | CompletionConfig { |
561 | enable_postfix_completions: self.data.completion_postfix_enable, | 561 | enable_postfix_completions: self.data.completion_postfix_enable, |
562 | enable_autoimport_completions: self.data.completion_autoimport_enable | 562 | enable_imports_on_the_fly: self.data.completion_autoimport_enable |
563 | && completion_item_edit_resolve(&self.caps), | 563 | && completion_item_edit_resolve(&self.caps), |
564 | add_call_parenthesis: self.data.completion_addCallParenthesis, | 564 | add_call_parenthesis: self.data.completion_addCallParenthesis, |
565 | add_call_argument_snippets: self.data.completion_addCallArgumentSnippets, | 565 | add_call_argument_snippets: self.data.completion_addCallArgumentSnippets, |
@@ -581,18 +581,7 @@ impl Config { | |||
581 | AssistConfig { | 581 | AssistConfig { |
582 | snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")), | 582 | snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")), |
583 | allowed: None, | 583 | allowed: None, |
584 | insert_use: InsertUseConfig { | 584 | insert_use: self.insert_use_config(), |
585 | merge: match self.data.assist_importMergeBehavior { | ||
586 | MergeBehaviorDef::None => None, | ||
587 | MergeBehaviorDef::Full => Some(MergeBehavior::Full), | ||
588 | MergeBehaviorDef::Last => Some(MergeBehavior::Last), | ||
589 | }, | ||
590 | prefix_kind: match self.data.assist_importPrefix { | ||
591 | ImportPrefixDef::Plain => PrefixKind::Plain, | ||
592 | ImportPrefixDef::ByCrate => PrefixKind::ByCrate, | ||
593 | ImportPrefixDef::BySelf => PrefixKind::BySelf, | ||
594 | }, | ||
595 | }, | ||
596 | } | 585 | } |
597 | } | 586 | } |
598 | pub fn call_info_full(&self) -> bool { | 587 | pub fn call_info_full(&self) -> bool { |
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index 1a4e0dd32..001f3a37d 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs | |||
@@ -653,7 +653,7 @@ pub(crate) fn handle_completion( | |||
653 | let mut new_completion_items = | 653 | let mut new_completion_items = |
654 | to_proto::completion_item(&line_index, line_endings, item.clone()); | 654 | to_proto::completion_item(&line_index, line_endings, item.clone()); |
655 | 655 | ||
656 | if completion_config.enable_autoimport_completions { | 656 | if completion_config.enable_imports_on_the_fly { |
657 | for new_item in &mut new_completion_items { | 657 | for new_item in &mut new_completion_items { |
658 | fill_resolve_data(&mut new_item.data, &item, &text_document_position); | 658 | fill_resolve_data(&mut new_item.data, &item, &text_document_position); |
659 | } | 659 | } |
@@ -703,6 +703,7 @@ pub(crate) fn handle_completion_resolve( | |||
703 | FilePosition { file_id, offset }, | 703 | FilePosition { file_id, offset }, |
704 | &resolve_data.full_import_path, | 704 | &resolve_data.full_import_path, |
705 | resolve_data.imported_name, | 705 | resolve_data.imported_name, |
706 | resolve_data.import_for_trait_assoc_item, | ||
706 | )? | 707 | )? |
707 | .into_iter() | 708 | .into_iter() |
708 | .flat_map(|edit| { | 709 | .flat_map(|edit| { |
@@ -809,7 +810,7 @@ pub(crate) fn handle_rename( | |||
809 | 810 | ||
810 | let change = | 811 | let change = |
811 | snap.analysis.rename(position, &*params.new_name)?.map_err(to_proto::rename_error)?; | 812 | snap.analysis.rename(position, &*params.new_name)?.map_err(to_proto::rename_error)?; |
812 | let workspace_edit = to_proto::workspace_edit(&snap, change.info)?; | 813 | let workspace_edit = to_proto::workspace_edit(&snap, change)?; |
813 | Ok(Some(workspace_edit)) | 814 | Ok(Some(workspace_edit)) |
814 | } | 815 | } |
815 | 816 | ||
@@ -1694,6 +1695,7 @@ struct CompletionResolveData { | |||
1694 | position: lsp_types::TextDocumentPositionParams, | 1695 | position: lsp_types::TextDocumentPositionParams, |
1695 | full_import_path: String, | 1696 | full_import_path: String, |
1696 | imported_name: String, | 1697 | imported_name: String, |
1698 | import_for_trait_assoc_item: bool, | ||
1697 | } | 1699 | } |
1698 | 1700 | ||
1699 | fn fill_resolve_data( | 1701 | fn fill_resolve_data( |
@@ -1710,6 +1712,7 @@ fn fill_resolve_data( | |||
1710 | position: position.to_owned(), | 1712 | position: position.to_owned(), |
1711 | full_import_path, | 1713 | full_import_path, |
1712 | imported_name, | 1714 | imported_name, |
1715 | import_for_trait_assoc_item: import_edit.import_for_trait_assoc_item, | ||
1713 | }) | 1716 | }) |
1714 | .unwrap(), | 1717 | .unwrap(), |
1715 | ); | 1718 | ); |
diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index 97e20362f..dabfb4241 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs | |||
@@ -135,7 +135,10 @@ impl GlobalState { | |||
135 | ) | 135 | ) |
136 | } | 136 | } |
137 | LinkedProject::InlineJsonProject(it) => { | 137 | LinkedProject::InlineJsonProject(it) => { |
138 | project_model::ProjectWorkspace::load_inline(it.clone()) | 138 | project_model::ProjectWorkspace::load_inline( |
139 | it.clone(), | ||
140 | cargo_config.target.as_deref(), | ||
141 | ) | ||
139 | } | 142 | } |
140 | }) | 143 | }) |
141 | .collect::<Vec<_>>(); | 144 | .collect::<Vec<_>>(); |
@@ -253,11 +256,7 @@ impl GlobalState { | |||
253 | res | 256 | res |
254 | }; | 257 | }; |
255 | for ws in workspaces.iter() { | 258 | for ws in workspaces.iter() { |
256 | crate_graph.extend(ws.to_crate_graph( | 259 | crate_graph.extend(ws.to_crate_graph(self.proc_macro_client.as_ref(), &mut load)); |
257 | self.config.cargo().target.as_deref(), | ||
258 | self.proc_macro_client.as_ref(), | ||
259 | &mut load, | ||
260 | )); | ||
261 | } | 260 | } |
262 | 261 | ||
263 | crate_graph | 262 | crate_graph |
@@ -274,6 +273,7 @@ impl GlobalState { | |||
274 | } | 273 | } |
275 | 274 | ||
276 | fn reload_flycheck(&mut self) { | 275 | fn reload_flycheck(&mut self) { |
276 | let _p = profile::span("GlobalState::reload_flycheck"); | ||
277 | let config = match self.config.flycheck() { | 277 | let config = match self.config.flycheck() { |
278 | Some(it) => it, | 278 | Some(it) => it, |
279 | None => { | 279 | None => { |
@@ -288,9 +288,7 @@ impl GlobalState { | |||
288 | .iter() | 288 | .iter() |
289 | .enumerate() | 289 | .enumerate() |
290 | .filter_map(|(id, w)| match w { | 290 | .filter_map(|(id, w)| match w { |
291 | ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => { | 291 | ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())), |
292 | Some((id, cargo.workspace_root())) | ||
293 | } | ||
294 | ProjectWorkspace::Json { project, .. } => { | 292 | ProjectWorkspace::Json { project, .. } => { |
295 | // Enable flychecks for json projects if a custom flycheck command was supplied | 293 | // Enable flychecks for json projects if a custom flycheck command was supplied |
296 | // in the workspace configuration. | 294 | // in the workspace configuration. |
diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs index 1ff2d3fea..0e3550002 100644 --- a/crates/rust-analyzer/src/to_proto.rs +++ b/crates/rust-analyzer/src/to_proto.rs | |||
@@ -884,7 +884,7 @@ mod tests { | |||
884 | .completions( | 884 | .completions( |
885 | &ide::CompletionConfig { | 885 | &ide::CompletionConfig { |
886 | enable_postfix_completions: true, | 886 | enable_postfix_completions: true, |
887 | enable_autoimport_completions: true, | 887 | enable_imports_on_the_fly: true, |
888 | add_call_parenthesis: true, | 888 | add_call_parenthesis: true, |
889 | add_call_argument_snippets: true, | 889 | add_call_argument_snippets: true, |
890 | snippet_cap: SnippetCap::new(true), | 890 | snippet_cap: SnippetCap::new(true), |
diff --git a/crates/syntax/src/ast/generated/nodes.rs b/crates/syntax/src/ast/generated/nodes.rs index 1d722db3c..5baa54a3f 100644 --- a/crates/syntax/src/ast/generated/nodes.rs +++ b/crates/syntax/src/ast/generated/nodes.rs | |||
@@ -11,6 +11,7 @@ pub struct Name { | |||
11 | } | 11 | } |
12 | impl Name { | 12 | impl Name { |
13 | pub fn ident_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![ident]) } | 13 | pub fn ident_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![ident]) } |
14 | pub fn self_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![self]) } | ||
14 | } | 15 | } |
15 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | 16 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
16 | pub struct NameRef { | 17 | pub struct NameRef { |
@@ -238,7 +239,6 @@ impl ExternCrate { | |||
238 | pub fn extern_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![extern]) } | 239 | pub fn extern_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![extern]) } |
239 | pub fn crate_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![crate]) } | 240 | pub fn crate_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![crate]) } |
240 | pub fn name_ref(&self) -> Option<NameRef> { support::child(&self.syntax) } | 241 | pub fn name_ref(&self) -> Option<NameRef> { support::child(&self.syntax) } |
241 | pub fn self_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![self]) } | ||
242 | pub fn rename(&self) -> Option<Rename> { support::child(&self.syntax) } | 242 | pub fn rename(&self) -> Option<Rename> { support::child(&self.syntax) } |
243 | pub fn semicolon_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![;]) } | 243 | pub fn semicolon_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![;]) } |
244 | } | 244 | } |
@@ -406,9 +406,6 @@ pub struct Visibility { | |||
406 | impl Visibility { | 406 | impl Visibility { |
407 | pub fn pub_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![pub]) } | 407 | pub fn pub_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![pub]) } |
408 | pub fn l_paren_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T!['(']) } | 408 | pub fn l_paren_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T!['(']) } |
409 | pub fn super_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![super]) } | ||
410 | pub fn self_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![self]) } | ||
411 | pub fn crate_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![crate]) } | ||
412 | pub fn in_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![in]) } | 409 | pub fn in_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![in]) } |
413 | pub fn path(&self) -> Option<Path> { support::child(&self.syntax) } | 410 | pub fn path(&self) -> Option<Path> { support::child(&self.syntax) } |
414 | pub fn r_paren_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![')']) } | 411 | pub fn r_paren_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![')']) } |
@@ -492,11 +489,11 @@ pub struct SelfParam { | |||
492 | pub(crate) syntax: SyntaxNode, | 489 | pub(crate) syntax: SyntaxNode, |
493 | } | 490 | } |
494 | impl ast::AttrsOwner for SelfParam {} | 491 | impl ast::AttrsOwner for SelfParam {} |
492 | impl ast::NameOwner for SelfParam {} | ||
495 | impl SelfParam { | 493 | impl SelfParam { |
496 | pub fn amp_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![&]) } | 494 | pub fn amp_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![&]) } |
497 | pub fn lifetime(&self) -> Option<Lifetime> { support::child(&self.syntax) } | 495 | pub fn lifetime(&self) -> Option<Lifetime> { support::child(&self.syntax) } |
498 | pub fn mut_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![mut]) } | 496 | pub fn mut_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![mut]) } |
499 | pub fn self_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![self]) } | ||
500 | pub fn colon_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![:]) } | 497 | pub fn colon_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![:]) } |
501 | pub fn ty(&self) -> Option<Type> { support::child(&self.syntax) } | 498 | pub fn ty(&self) -> Option<Type> { support::child(&self.syntax) } |
502 | } | 499 | } |
@@ -1075,6 +1072,13 @@ impl InferType { | |||
1075 | pub fn underscore_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![_]) } | 1072 | pub fn underscore_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![_]) } |
1076 | } | 1073 | } |
1077 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | 1074 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
1075 | pub struct MacroType { | ||
1076 | pub(crate) syntax: SyntaxNode, | ||
1077 | } | ||
1078 | impl MacroType { | ||
1079 | pub fn macro_call(&self) -> Option<MacroCall> { support::child(&self.syntax) } | ||
1080 | } | ||
1081 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
1078 | pub struct NeverType { | 1082 | pub struct NeverType { |
1079 | pub(crate) syntax: SyntaxNode, | 1083 | pub(crate) syntax: SyntaxNode, |
1080 | } | 1084 | } |
@@ -1303,6 +1307,7 @@ pub enum Type { | |||
1303 | ForType(ForType), | 1307 | ForType(ForType), |
1304 | ImplTraitType(ImplTraitType), | 1308 | ImplTraitType(ImplTraitType), |
1305 | InferType(InferType), | 1309 | InferType(InferType), |
1310 | MacroType(MacroType), | ||
1306 | NeverType(NeverType), | 1311 | NeverType(NeverType), |
1307 | ParenType(ParenType), | 1312 | ParenType(ParenType), |
1308 | PathType(PathType), | 1313 | PathType(PathType), |
@@ -2561,6 +2566,17 @@ impl AstNode for InferType { | |||
2561 | } | 2566 | } |
2562 | fn syntax(&self) -> &SyntaxNode { &self.syntax } | 2567 | fn syntax(&self) -> &SyntaxNode { &self.syntax } |
2563 | } | 2568 | } |
2569 | impl AstNode for MacroType { | ||
2570 | fn can_cast(kind: SyntaxKind) -> bool { kind == MACRO_TYPE } | ||
2571 | fn cast(syntax: SyntaxNode) -> Option<Self> { | ||
2572 | if Self::can_cast(syntax.kind()) { | ||
2573 | Some(Self { syntax }) | ||
2574 | } else { | ||
2575 | None | ||
2576 | } | ||
2577 | } | ||
2578 | fn syntax(&self) -> &SyntaxNode { &self.syntax } | ||
2579 | } | ||
2564 | impl AstNode for NeverType { | 2580 | impl AstNode for NeverType { |
2565 | fn can_cast(kind: SyntaxKind) -> bool { kind == NEVER_TYPE } | 2581 | fn can_cast(kind: SyntaxKind) -> bool { kind == NEVER_TYPE } |
2566 | fn cast(syntax: SyntaxNode) -> Option<Self> { | 2582 | fn cast(syntax: SyntaxNode) -> Option<Self> { |
@@ -2892,6 +2908,9 @@ impl From<ImplTraitType> for Type { | |||
2892 | impl From<InferType> for Type { | 2908 | impl From<InferType> for Type { |
2893 | fn from(node: InferType) -> Type { Type::InferType(node) } | 2909 | fn from(node: InferType) -> Type { Type::InferType(node) } |
2894 | } | 2910 | } |
2911 | impl From<MacroType> for Type { | ||
2912 | fn from(node: MacroType) -> Type { Type::MacroType(node) } | ||
2913 | } | ||
2895 | impl From<NeverType> for Type { | 2914 | impl From<NeverType> for Type { |
2896 | fn from(node: NeverType) -> Type { Type::NeverType(node) } | 2915 | fn from(node: NeverType) -> Type { Type::NeverType(node) } |
2897 | } | 2916 | } |
@@ -2917,8 +2936,8 @@ impl AstNode for Type { | |||
2917 | fn can_cast(kind: SyntaxKind) -> bool { | 2936 | fn can_cast(kind: SyntaxKind) -> bool { |
2918 | match kind { | 2937 | match kind { |
2919 | ARRAY_TYPE | DYN_TRAIT_TYPE | FN_PTR_TYPE | FOR_TYPE | IMPL_TRAIT_TYPE | INFER_TYPE | 2938 | ARRAY_TYPE | DYN_TRAIT_TYPE | FN_PTR_TYPE | FOR_TYPE | IMPL_TRAIT_TYPE | INFER_TYPE |
2920 | | NEVER_TYPE | PAREN_TYPE | PATH_TYPE | PTR_TYPE | REF_TYPE | SLICE_TYPE | 2939 | | MACRO_TYPE | NEVER_TYPE | PAREN_TYPE | PATH_TYPE | PTR_TYPE | REF_TYPE |
2921 | | TUPLE_TYPE => true, | 2940 | | SLICE_TYPE | TUPLE_TYPE => true, |
2922 | _ => false, | 2941 | _ => false, |
2923 | } | 2942 | } |
2924 | } | 2943 | } |
@@ -2930,6 +2949,7 @@ impl AstNode for Type { | |||
2930 | FOR_TYPE => Type::ForType(ForType { syntax }), | 2949 | FOR_TYPE => Type::ForType(ForType { syntax }), |
2931 | IMPL_TRAIT_TYPE => Type::ImplTraitType(ImplTraitType { syntax }), | 2950 | IMPL_TRAIT_TYPE => Type::ImplTraitType(ImplTraitType { syntax }), |
2932 | INFER_TYPE => Type::InferType(InferType { syntax }), | 2951 | INFER_TYPE => Type::InferType(InferType { syntax }), |
2952 | MACRO_TYPE => Type::MacroType(MacroType { syntax }), | ||
2933 | NEVER_TYPE => Type::NeverType(NeverType { syntax }), | 2953 | NEVER_TYPE => Type::NeverType(NeverType { syntax }), |
2934 | PAREN_TYPE => Type::ParenType(ParenType { syntax }), | 2954 | PAREN_TYPE => Type::ParenType(ParenType { syntax }), |
2935 | PATH_TYPE => Type::PathType(PathType { syntax }), | 2955 | PATH_TYPE => Type::PathType(PathType { syntax }), |
@@ -2949,6 +2969,7 @@ impl AstNode for Type { | |||
2949 | Type::ForType(it) => &it.syntax, | 2969 | Type::ForType(it) => &it.syntax, |
2950 | Type::ImplTraitType(it) => &it.syntax, | 2970 | Type::ImplTraitType(it) => &it.syntax, |
2951 | Type::InferType(it) => &it.syntax, | 2971 | Type::InferType(it) => &it.syntax, |
2972 | Type::MacroType(it) => &it.syntax, | ||
2952 | Type::NeverType(it) => &it.syntax, | 2973 | Type::NeverType(it) => &it.syntax, |
2953 | Type::ParenType(it) => &it.syntax, | 2974 | Type::ParenType(it) => &it.syntax, |
2954 | Type::PathType(it) => &it.syntax, | 2975 | Type::PathType(it) => &it.syntax, |
@@ -4085,6 +4106,11 @@ impl std::fmt::Display for InferType { | |||
4085 | std::fmt::Display::fmt(self.syntax(), f) | 4106 | std::fmt::Display::fmt(self.syntax(), f) |
4086 | } | 4107 | } |
4087 | } | 4108 | } |
4109 | impl std::fmt::Display for MacroType { | ||
4110 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
4111 | std::fmt::Display::fmt(self.syntax(), f) | ||
4112 | } | ||
4113 | } | ||
4088 | impl std::fmt::Display for NeverType { | 4114 | impl std::fmt::Display for NeverType { |
4089 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | 4115 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
4090 | std::fmt::Display::fmt(self.syntax(), f) | 4116 | std::fmt::Display::fmt(self.syntax(), f) |
diff --git a/crates/syntax/src/ast/node_ext.rs b/crates/syntax/src/ast/node_ext.rs index b8ce71d27..738c92a5b 100644 --- a/crates/syntax/src/ast/node_ext.rs +++ b/crates/syntax/src/ast/node_ext.rs | |||
@@ -198,6 +198,13 @@ impl ast::Path { | |||
198 | pub fn parent_path(&self) -> Option<ast::Path> { | 198 | pub fn parent_path(&self) -> Option<ast::Path> { |
199 | self.syntax().parent().and_then(ast::Path::cast) | 199 | self.syntax().parent().and_then(ast::Path::cast) |
200 | } | 200 | } |
201 | |||
202 | pub fn as_single_segment(&self) -> Option<ast::PathSegment> { | ||
203 | match self.qualifier() { | ||
204 | Some(_) => None, | ||
205 | None => self.segment(), | ||
206 | } | ||
207 | } | ||
201 | } | 208 | } |
202 | 209 | ||
203 | impl ast::UseTreeList { | 210 | impl ast::UseTreeList { |
@@ -448,16 +455,22 @@ pub enum VisibilityKind { | |||
448 | 455 | ||
449 | impl ast::Visibility { | 456 | impl ast::Visibility { |
450 | pub fn kind(&self) -> VisibilityKind { | 457 | pub fn kind(&self) -> VisibilityKind { |
451 | if let Some(path) = support::children(self.syntax()).next() { | 458 | match self.path() { |
452 | VisibilityKind::In(path) | 459 | Some(path) => { |
453 | } else if self.crate_token().is_some() { | 460 | if let Some(segment) = |
454 | VisibilityKind::PubCrate | 461 | path.as_single_segment().filter(|it| it.coloncolon_token().is_none()) |
455 | } else if self.super_token().is_some() { | 462 | { |
456 | VisibilityKind::PubSuper | 463 | if segment.crate_token().is_some() { |
457 | } else if self.self_token().is_some() { | 464 | return VisibilityKind::PubCrate; |
458 | VisibilityKind::PubSelf | 465 | } else if segment.super_token().is_some() { |
459 | } else { | 466 | return VisibilityKind::PubSuper; |
460 | VisibilityKind::Pub | 467 | } else if segment.self_token().is_some() { |
468 | return VisibilityKind::PubSelf; | ||
469 | } | ||
470 | } | ||
471 | VisibilityKind::In(path) | ||
472 | } | ||
473 | None => VisibilityKind::Pub, | ||
461 | } | 474 | } |
462 | } | 475 | } |
463 | } | 476 | } |
diff --git a/crates/syntax/test_data/parser/err/0037_visibility_in_traits.rast b/crates/syntax/test_data/parser/err/0037_visibility_in_traits.rast index faf87d6e5..ae4dd2f3b 100644 --- a/crates/syntax/test_data/parser/err/0037_visibility_in_traits.rast +++ b/crates/syntax/test_data/parser/err/0037_visibility_in_traits.rast | |||
@@ -50,7 +50,10 @@ [email protected] | |||
50 | [email protected] | 50 | [email protected] |
51 | [email protected] "pub" | 51 | [email protected] "pub" |
52 | [email protected] "(" | 52 | [email protected] "(" |
53 | [email protected] "crate" | 53 | [email protected] |
54 | [email protected] | ||
55 | [email protected] | ||
56 | [email protected] "crate" | ||
54 | [email protected] ")" | 57 | [email protected] ")" |
55 | [email protected] " " | 58 | [email protected] " " |
56 | [email protected] "type" | 59 | [email protected] "type" |
@@ -69,7 +72,10 @@ [email protected] | |||
69 | [email protected] | 72 | [email protected] |
70 | [email protected] "pub" | 73 | [email protected] "pub" |
71 | [email protected] "(" | 74 | [email protected] "(" |
72 | [email protected] "crate" | 75 | [email protected] |
76 | [email protected] | ||
77 | [email protected] | ||
78 | [email protected] "crate" | ||
73 | [email protected] ")" | 79 | [email protected] ")" |
74 | [email protected] " " | 80 | [email protected] " " |
75 | [email protected] "const" | 81 | [email protected] "const" |
diff --git a/crates/syntax/test_data/parser/inline/ok/0006_self_param.rast b/crates/syntax/test_data/parser/inline/ok/0006_self_param.rast index 8048f5fad..f0d152d33 100644 --- a/crates/syntax/test_data/parser/inline/ok/0006_self_param.rast +++ b/crates/syntax/test_data/parser/inline/ok/0006_self_param.rast | |||
@@ -19,7 +19,8 @@ [email protected] | |||
19 | [email protected] | 19 | [email protected] |
20 | [email protected] "(" | 20 | [email protected] "(" |
21 | [email protected] | 21 | [email protected] |
22 | [email protected] "self" | 22 | [email protected] |
23 | [email protected] "self" | ||
23 | [email protected] ")" | 24 | [email protected] ")" |
24 | [email protected] " " | 25 | [email protected] " " |
25 | [email protected] | 26 | [email protected] |
@@ -35,7 +36,8 @@ [email protected] | |||
35 | [email protected] "(" | 36 | [email protected] "(" |
36 | [email protected] | 37 | [email protected] |
37 | [email protected] "&" | 38 | [email protected] "&" |
38 | [email protected] "self" | 39 | [email protected] |
40 | [email protected] "self" | ||
39 | [email protected] "," | 41 | [email protected] "," |
40 | [email protected] ")" | 42 | [email protected] ")" |
41 | [email protected] " " | 43 | [email protected] " " |
@@ -55,7 +57,8 @@ [email protected] | |||
55 | [email protected] | 57 | [email protected] |
56 | [email protected] "\'a" | 58 | [email protected] "\'a" |
57 | [email protected] " " | 59 | [email protected] " " |
58 | [email protected] "self" | 60 | [email protected] |
61 | [email protected] "self" | ||
59 | [email protected] "," | 62 | [email protected] "," |
60 | [email protected] ")" | 63 | [email protected] ")" |
61 | [email protected] " " | 64 | [email protected] " " |
@@ -77,7 +80,8 @@ [email protected] | |||
77 | [email protected] " " | 80 | [email protected] " " |
78 | [email protected] "mut" | 81 | [email protected] "mut" |
79 | [email protected] " " | 82 | [email protected] " " |
80 | [email protected] "self" | 83 | [email protected] |
84 | [email protected] "self" | ||
81 | [email protected] "," | 85 | [email protected] "," |
82 | [email protected] " " | 86 | [email protected] " " |
83 | [email protected] | 87 | [email protected] |
@@ -107,7 +111,8 @@ [email protected] | |||
107 | [email protected] | 111 | [email protected] |
108 | [email protected] "mut" | 112 | [email protected] "mut" |
109 | [email protected] " " | 113 | [email protected] " " |
110 | [email protected] "self" | 114 | [email protected] |
115 | [email protected] "self" | ||
111 | [email protected] ")" | 116 | [email protected] ")" |
112 | [email protected] " " | 117 | [email protected] " " |
113 | [email protected] | 118 | [email protected] |
diff --git a/crates/syntax/test_data/parser/inline/ok/0018_arb_self_types.rast b/crates/syntax/test_data/parser/inline/ok/0018_arb_self_types.rast index ddbd66588..df59f37a2 100644 --- a/crates/syntax/test_data/parser/inline/ok/0018_arb_self_types.rast +++ b/crates/syntax/test_data/parser/inline/ok/0018_arb_self_types.rast | |||
@@ -19,7 +19,8 @@ [email protected] | |||
19 | [email protected] | 19 | [email protected] |
20 | [email protected] "(" | 20 | [email protected] "(" |
21 | [email protected] | 21 | [email protected] |
22 | [email protected] "self" | 22 | [email protected] |
23 | [email protected] "self" | ||
23 | [email protected] ":" | 24 | [email protected] ":" |
24 | [email protected] " " | 25 | [email protected] " " |
25 | [email protected] | 26 | [email protected] |
@@ -45,7 +46,8 @@ [email protected] | |||
45 | [email protected] | 46 | [email protected] |
46 | [email protected] "mut" | 47 | [email protected] "mut" |
47 | [email protected] " " | 48 | [email protected] " " |
48 | [email protected] "self" | 49 | [email protected] |
50 | [email protected] "self" | ||
49 | [email protected] ":" | 51 | [email protected] ":" |
50 | [email protected] " " | 52 | [email protected] " " |
51 | [email protected] | 53 | [email protected] |
diff --git a/crates/syntax/test_data/parser/inline/ok/0021_impl_item_list.rast b/crates/syntax/test_data/parser/inline/ok/0021_impl_item_list.rast index ca0702aba..dc7f6295b 100644 --- a/crates/syntax/test_data/parser/inline/ok/0021_impl_item_list.rast +++ b/crates/syntax/test_data/parser/inline/ok/0021_impl_item_list.rast | |||
@@ -67,7 +67,8 @@ [email protected] | |||
67 | [email protected] "(" | 67 | [email protected] "(" |
68 | [email protected] | 68 | [email protected] |
69 | [email protected] "&" | 69 | [email protected] "&" |
70 | [email protected] "self" | 70 | [email protected] |
71 | [email protected] "self" | ||
71 | [email protected] ")" | 72 | [email protected] ")" |
72 | [email protected] " " | 73 | [email protected] " " |
73 | [email protected] | 74 | [email protected] |
diff --git a/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rast b/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rast index 50742cbcf..f2ead8a62 100644 --- a/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rast +++ b/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rast | |||
@@ -1,9 +1,12 @@ | |||
1 | SOURCE_FILE@0..81 | 1 | SOURCE_FILE@0..62 |
2 | [email protected] | 2 | [email protected] |
3 | [email protected] | 3 | [email protected] |
4 | [email protected] "pub" | 4 | [email protected] "pub" |
5 | [email protected] "(" | 5 | [email protected] "(" |
6 | [email protected] "crate" | 6 | [email protected] |
7 | [email protected] | ||
8 | [email protected] | ||
9 | [email protected] "crate" | ||
7 | [email protected] ")" | 10 | [email protected] ")" |
8 | [email protected] " " | 11 | [email protected] " " |
9 | [email protected] "struct" | 12 | [email protected] "struct" |
@@ -16,7 +19,10 @@ [email protected] | |||
16 | [email protected] | 19 | [email protected] |
17 | [email protected] "pub" | 20 | [email protected] "pub" |
18 | [email protected] "(" | 21 | [email protected] "(" |
19 | [email protected] "self" | 22 | [email protected] |
23 | [email protected] | ||
24 | [email protected] | ||
25 | [email protected] "self" | ||
20 | [email protected] ")" | 26 | [email protected] ")" |
21 | [email protected] " " | 27 | [email protected] " " |
22 | [email protected] "struct" | 28 | [email protected] "struct" |
@@ -25,29 +31,19 @@ [email protected] | |||
25 | [email protected] "S" | 31 | [email protected] "S" |
26 | [email protected] ";" | 32 | [email protected] ";" |
27 | [email protected] "\n" | 33 | [email protected] "\n" |
28 | [email protected]0 | 34 | [email protected]1 |
29 | [email protected]0 | 35 | [email protected]1 |
30 | [email protected] "pub" | 36 | [email protected] "pub" |
31 | [email protected] "(" | 37 | [email protected] "(" |
32 | [email protected] "self" | 38 | [email protected] |
33 | [email protected] ")" | 39 | [email protected] |
34 | [email protected] " " | 40 | [email protected] |
35 | [email protected] "struct" | 41 | [email protected] "super" |
36 | [email protected] " " | 42 | [email protected] ")" |
37 | [email protected] | 43 | [email protected] " " |
38 | [email protected] "S" | 44 | [email protected] "struct" |
39 | [email protected] ";" | 45 | [email protected] " " |
40 | [email protected] "\n" | 46 | [email protected] |
41 | [email protected] | 47 | [email protected] "S" |
42 | [email protected] | 48 | [email protected] ";" |
43 | [email protected] "pub" | 49 | [email protected] "\n" |
44 | [email protected] "(" | ||
45 | [email protected] "self" | ||
46 | [email protected] ")" | ||
47 | [email protected] " " | ||
48 | [email protected] "struct" | ||
49 | [email protected] " " | ||
50 | [email protected] | ||
51 | [email protected] "S" | ||
52 | [email protected] ";" | ||
53 | [email protected] "\n" | ||
diff --git a/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rs b/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rs index faeefde94..a790a485f 100644 --- a/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rs +++ b/crates/syntax/test_data/parser/inline/ok/0022_crate_visibility.rs | |||
@@ -1,4 +1,3 @@ | |||
1 | pub(crate) struct S; | 1 | pub(crate) struct S; |
2 | pub(self) struct S; | 2 | pub(self) struct S; |
3 | pub(self) struct S; | 3 | pub(super) struct S; |
4 | pub(self) struct S; | ||
diff --git a/crates/syntax/test_data/parser/inline/ok/0138_self_param_outer_attr.rast b/crates/syntax/test_data/parser/inline/ok/0138_self_param_outer_attr.rast index d3219f0b2..c54e64e3f 100644 --- a/crates/syntax/test_data/parser/inline/ok/0138_self_param_outer_attr.rast +++ b/crates/syntax/test_data/parser/inline/ok/0138_self_param_outer_attr.rast | |||
@@ -16,7 +16,8 @@ [email protected] | |||
16 | [email protected] "must_use" | 16 | [email protected] "must_use" |
17 | [email protected] "]" | 17 | [email protected] "]" |
18 | [email protected] " " | 18 | [email protected] " " |
19 | [email protected] "self" | 19 | [email protected] |
20 | [email protected] "self" | ||
20 | [email protected] ")" | 21 | [email protected] ")" |
21 | [email protected] " " | 22 | [email protected] " " |
22 | [email protected] | 23 | [email protected] |
diff --git a/crates/syntax/test_data/parser/inline/ok/0160_crate_visibility_in.rast b/crates/syntax/test_data/parser/inline/ok/0160_crate_visibility_in.rast new file mode 100644 index 000000000..3d855fc6b --- /dev/null +++ b/crates/syntax/test_data/parser/inline/ok/0160_crate_visibility_in.rast | |||
@@ -0,0 +1,42 @@ | |||
1 | [email protected] | ||
2 | [email protected] | ||
3 | [email protected] | ||
4 | [email protected] "pub" | ||
5 | [email protected] "(" | ||
6 | [email protected] "in" | ||
7 | [email protected] " " | ||
8 | [email protected] | ||
9 | [email protected] | ||
10 | [email protected] | ||
11 | [email protected] | ||
12 | [email protected] "super" | ||
13 | [email protected] "::" | ||
14 | [email protected] | ||
15 | [email protected] | ||
16 | [email protected] "A" | ||
17 | [email protected] ")" | ||
18 | [email protected] " " | ||
19 | [email protected] "struct" | ||
20 | [email protected] " " | ||
21 | [email protected] | ||
22 | [email protected] "S" | ||
23 | [email protected] ";" | ||
24 | [email protected] "\n" | ||
25 | [email protected] | ||
26 | [email protected] | ||
27 | [email protected] "pub" | ||
28 | [email protected] "(" | ||
29 | [email protected] "in" | ||
30 | [email protected] " " | ||
31 | [email protected] | ||
32 | [email protected] | ||
33 | [email protected] | ||
34 | [email protected] "crate" | ||
35 | [email protected] ")" | ||
36 | [email protected] " " | ||
37 | [email protected] "struct" | ||
38 | [email protected] " " | ||
39 | [email protected] | ||
40 | [email protected] "S" | ||
41 | [email protected] ";" | ||
42 | [email protected] "\n" | ||
diff --git a/crates/syntax/test_data/parser/inline/ok/0160_crate_visibility_in.rs b/crates/syntax/test_data/parser/inline/ok/0160_crate_visibility_in.rs new file mode 100644 index 000000000..2856dbd84 --- /dev/null +++ b/crates/syntax/test_data/parser/inline/ok/0160_crate_visibility_in.rs | |||
@@ -0,0 +1,2 @@ | |||
1 | pub(in super::A) struct S; | ||
2 | pub(in crate) struct S; | ||
diff --git a/crates/syntax/test_data/parser/inline/ok/0161_impl_def_const.rast b/crates/syntax/test_data/parser/inline/ok/0161_impl_def_const.rast new file mode 100644 index 000000000..dcd39535b --- /dev/null +++ b/crates/syntax/test_data/parser/inline/ok/0161_impl_def_const.rast | |||
@@ -0,0 +1,24 @@ | |||
1 | [email protected] | ||
2 | [email protected] | ||
3 | [email protected] "impl" | ||
4 | [email protected] " " | ||
5 | [email protected] "const" | ||
6 | [email protected] " " | ||
7 | [email protected] | ||
8 | [email protected] | ||
9 | [email protected] | ||
10 | [email protected] | ||
11 | [email protected] "Send" | ||
12 | [email protected] " " | ||
13 | [email protected] "for" | ||
14 | [email protected] " " | ||
15 | [email protected] | ||
16 | [email protected] | ||
17 | [email protected] | ||
18 | [email protected] | ||
19 | [email protected] "X" | ||
20 | [email protected] " " | ||
21 | [email protected] | ||
22 | [email protected] "{" | ||
23 | [email protected] "}" | ||
24 | [email protected] "\n" | ||
diff --git a/crates/syntax/test_data/parser/inline/ok/0161_impl_def_const.rs b/crates/syntax/test_data/parser/inline/ok/0161_impl_def_const.rs new file mode 100644 index 000000000..8d6886469 --- /dev/null +++ b/crates/syntax/test_data/parser/inline/ok/0161_impl_def_const.rs | |||
@@ -0,0 +1 @@ | |||
impl const Send for X {} | |||
diff --git a/crates/syntax/test_data/parser/ok/0007_extern_crate.rast b/crates/syntax/test_data/parser/ok/0007_extern_crate.rast index 594c2f8f2..4babdba92 100644 --- a/crates/syntax/test_data/parser/ok/0007_extern_crate.rast +++ b/crates/syntax/test_data/parser/ok/0007_extern_crate.rast | |||
@@ -28,7 +28,8 @@ [email protected] | |||
28 | [email protected] " " | 28 | [email protected] " " |
29 | [email protected] "crate" | 29 | [email protected] "crate" |
30 | [email protected] " " | 30 | [email protected] " " |
31 | [email protected] "self" | 31 | [email protected] |
32 | [email protected] "self" | ||
32 | [email protected] " " | 33 | [email protected] " " |
33 | [email protected] | 34 | [email protected] |
34 | [email protected] "as" | 35 | [email protected] "as" |
diff --git a/crates/syntax/test_data/parser/ok/0012_visibility.rast b/crates/syntax/test_data/parser/ok/0012_visibility.rast index 83a93b5a9..c5dbfb702 100644 --- a/crates/syntax/test_data/parser/ok/0012_visibility.rast +++ b/crates/syntax/test_data/parser/ok/0012_visibility.rast | |||
@@ -32,7 +32,10 @@ [email protected] | |||
32 | [email protected] | 32 | [email protected] |
33 | [email protected] "pub" | 33 | [email protected] "pub" |
34 | [email protected] "(" | 34 | [email protected] "(" |
35 | [email protected] "crate" | 35 | [email protected] |
36 | [email protected] | ||
37 | [email protected] | ||
38 | [email protected] "crate" | ||
36 | [email protected] ")" | 39 | [email protected] ")" |
37 | [email protected] " " | 40 | [email protected] " " |
38 | [email protected] "fn" | 41 | [email protected] "fn" |
@@ -51,7 +54,10 @@ [email protected] | |||
51 | [email protected] | 54 | [email protected] |
52 | [email protected] "pub" | 55 | [email protected] "pub" |
53 | [email protected] "(" | 56 | [email protected] "(" |
54 | [email protected] "super" | 57 | [email protected] |
58 | [email protected] | ||
59 | [email protected] | ||
60 | [email protected] "super" | ||
55 | [email protected] ")" | 61 | [email protected] ")" |
56 | [email protected] " " | 62 | [email protected] " " |
57 | [email protected] "fn" | 63 | [email protected] "fn" |
diff --git a/crates/syntax/test_data/parser/ok/0045_block_inner_attrs.rast b/crates/syntax/test_data/parser/ok/0045_block_inner_attrs.rast index 0ac56df6d..6afed5f05 100644 --- a/crates/syntax/test_data/parser/ok/0045_block_inner_attrs.rast +++ b/crates/syntax/test_data/parser/ok/0045_block_inner_attrs.rast | |||
@@ -110,7 +110,8 @@ [email protected] | |||
110 | [email protected] "(" | 110 | [email protected] "(" |
111 | [email protected] | 111 | [email protected] |
112 | [email protected] "&" | 112 | [email protected] "&" |
113 | [email protected] "self" | 113 | [email protected] |
114 | [email protected] "self" | ||
114 | [email protected] "," | 115 | [email protected] "," |
115 | [email protected] " " | 116 | [email protected] " " |
116 | [email protected] | 117 | [email protected] |
diff --git a/crates/syntax/test_data/parser/ok/0051_parameter_attrs.rast b/crates/syntax/test_data/parser/ok/0051_parameter_attrs.rast index 3fed11838..e10521d85 100644 --- a/crates/syntax/test_data/parser/ok/0051_parameter_attrs.rast +++ b/crates/syntax/test_data/parser/ok/0051_parameter_attrs.rast | |||
@@ -281,7 +281,8 @@ [email protected] | |||
281 | [email protected] "must_use" | 281 | [email protected] "must_use" |
282 | [email protected] "]" | 282 | [email protected] "]" |
283 | [email protected] " " | 283 | [email protected] " " |
284 | [email protected] "self" | 284 | [email protected] |
285 | [email protected] "self" | ||
285 | [email protected] ")" | 286 | [email protected] ")" |
286 | [email protected] " " | 287 | [email protected] " " |
287 | [email protected] | 288 | [email protected] |
@@ -305,7 +306,8 @@ [email protected] | |||
305 | [email protected] "attr" | 306 | [email protected] "attr" |
306 | [email protected] "]" | 307 | [email protected] "]" |
307 | [email protected] " " | 308 | [email protected] " " |
308 | [email protected] "self" | 309 | [email protected] |
310 | [email protected] "self" | ||
309 | [email protected] ")" | 311 | [email protected] ")" |
310 | [email protected] " " | 312 | [email protected] " " |
311 | [email protected] | 313 | [email protected] |
@@ -330,7 +332,8 @@ [email protected] | |||
330 | [email protected] "]" | 332 | [email protected] "]" |
331 | [email protected] " " | 333 | [email protected] " " |
332 | [email protected] "&" | 334 | [email protected] "&" |
333 | [email protected] "self" | 335 | [email protected] |
336 | [email protected] "self" | ||
334 | [email protected] ")" | 337 | [email protected] ")" |
335 | [email protected] " " | 338 | [email protected] " " |
336 | [email protected] | 339 | [email protected] |
@@ -363,7 +366,8 @@ [email protected] | |||
363 | [email protected] "&" | 366 | [email protected] "&" |
364 | [email protected] "mut" | 367 | [email protected] "mut" |
365 | [email protected] " " | 368 | [email protected] " " |
366 | [email protected] "self" | 369 | [email protected] |
370 | [email protected] "self" | ||
367 | [email protected] ")" | 371 | [email protected] ")" |
368 | [email protected] " " | 372 | [email protected] " " |
369 | [email protected] | 373 | [email protected] |
@@ -397,7 +401,8 @@ [email protected] | |||
397 | [email protected] | 401 | [email protected] |
398 | [email protected] "\'a" | 402 | [email protected] "\'a" |
399 | [email protected] " " | 403 | [email protected] " " |
400 | [email protected] "self" | 404 | [email protected] |
405 | [email protected] "self" | ||
401 | [email protected] ")" | 406 | [email protected] ")" |
402 | [email protected] " " | 407 | [email protected] " " |
403 | [email protected] | 408 | [email protected] |
@@ -433,7 +438,8 @@ [email protected] | |||
433 | [email protected] " " | 438 | [email protected] " " |
434 | [email protected] "mut" | 439 | [email protected] "mut" |
435 | [email protected] " " | 440 | [email protected] " " |
436 | [email protected] "self" | 441 | [email protected] |
442 | [email protected] "self" | ||
437 | [email protected] ")" | 443 | [email protected] ")" |
438 | [email protected] " " | 444 | [email protected] " " |
439 | [email protected] | 445 | [email protected] |
@@ -457,7 +463,8 @@ [email protected] | |||
457 | [email protected] "attr" | 463 | [email protected] "attr" |
458 | [email protected] "]" | 464 | [email protected] "]" |
459 | [email protected] " " | 465 | [email protected] " " |
460 | [email protected] "self" | 466 | [email protected] |
467 | [email protected] "self" | ||
461 | [email protected] ":" | 468 | [email protected] ":" |
462 | [email protected] " " | 469 | [email protected] " " |
463 | [email protected] | 470 | [email protected] |
@@ -488,7 +495,8 @@ [email protected] | |||
488 | [email protected] "attr" | 495 | [email protected] "attr" |
489 | [email protected] "]" | 496 | [email protected] "]" |
490 | [email protected] " " | 497 | [email protected] " " |
491 | [email protected] "self" | 498 | [email protected] |
499 | [email protected] "self" | ||
492 | [email protected] ":" | 500 | [email protected] ":" |
493 | [email protected] " " | 501 | [email protected] " " |
494 | [email protected] | 502 | [email protected] |