diff options
101 files changed, 2783 insertions, 1035 deletions
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index b5160eaa3..060a05d41 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md | |||
@@ -14,8 +14,9 @@ Forum for questions: https://users.rust-lang.org/c/ide/14 | |||
14 | Before submitting, please make sure that you're not running into one of these known issues: | 14 | Before submitting, please make sure that you're not running into one of these known issues: |
15 | 15 | ||
16 | 1. on-the-fly diagnostics are mostly unimplemented (`cargo check` diagnostics will be shown when saving a file) | 16 | 1. on-the-fly diagnostics are mostly unimplemented (`cargo check` diagnostics will be shown when saving a file) |
17 | 2. some settings are required for procedural macro and build script support (`rust-analyzer.cargo.loadOutDirsFromCheck`, `rust-analyzer.procMacro.enable`): #6448 | 17 | 2. some platform-specific imports are not resolved: #6038 |
18 | 3. some platform-specific imports are not resolved: #6038 | 18 | 3. attribute proc macros are not supported: #6029 |
19 | 4. the version string is misleading (includes the previous week): #8571 | ||
19 | 20 | ||
20 | Otherwise please try to provide information which will help us to fix the issue faster. Minimal reproducible examples with few dependencies are especially lovely <3. | 21 | Otherwise please try to provide information which will help us to fix the issue faster. Minimal reproducible examples with few dependencies are especially lovely <3. |
21 | --> | 22 | --> |
diff --git a/Cargo.lock b/Cargo.lock index d7e6d3ac8..1bb66c66e 100644 --- a/Cargo.lock +++ b/Cargo.lock | |||
@@ -259,9 +259,9 @@ dependencies = [ | |||
259 | 259 | ||
260 | [[package]] | 260 | [[package]] |
261 | name = "crossbeam-channel" | 261 | name = "crossbeam-channel" |
262 | version = "0.5.0" | 262 | version = "0.5.1" |
263 | source = "registry+https://github.com/rust-lang/crates.io-index" | 263 | source = "registry+https://github.com/rust-lang/crates.io-index" |
264 | checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775" | 264 | checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" |
265 | dependencies = [ | 265 | dependencies = [ |
266 | "cfg-if", | 266 | "cfg-if", |
267 | "crossbeam-utils", | 267 | "crossbeam-utils", |
@@ -971,9 +971,9 @@ dependencies = [ | |||
971 | 971 | ||
972 | [[package]] | 972 | [[package]] |
973 | name = "notify" | 973 | name = "notify" |
974 | version = "5.0.0-pre.6" | 974 | version = "5.0.0-pre.7" |
975 | source = "registry+https://github.com/rust-lang/crates.io-index" | 975 | source = "registry+https://github.com/rust-lang/crates.io-index" |
976 | checksum = "e5fd82b93434edb9c00ae65ee741e0e081cdc8c63346ab9f687935a629aaf4c3" | 976 | checksum = "1ebe7699a0f8c5759450716ee03d231685c22b4fe8f406c42c22e0ad94d40ce7" |
977 | dependencies = [ | 977 | dependencies = [ |
978 | "anymap", | 978 | "anymap", |
979 | "bitflags", | 979 | "bitflags", |
diff --git a/crates/base_db/src/fixture.rs b/crates/base_db/src/fixture.rs index 04e2be390..0132565e4 100644 --- a/crates/base_db/src/fixture.rs +++ b/crates/base_db/src/fixture.rs | |||
@@ -35,7 +35,7 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static { | |||
35 | fn with_position(ra_fixture: &str) -> (Self, FilePosition) { | 35 | fn with_position(ra_fixture: &str) -> (Self, FilePosition) { |
36 | let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture); | 36 | let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture); |
37 | let offset = match range_or_offset { | 37 | let offset = match range_or_offset { |
38 | RangeOrOffset::Range(_) => panic!(), | 38 | RangeOrOffset::Range(_) => panic!("Expected a cursor position, got a range instead"), |
39 | RangeOrOffset::Offset(it) => it, | 39 | RangeOrOffset::Offset(it) => it, |
40 | }; | 40 | }; |
41 | (db, FilePosition { file_id, offset }) | 41 | (db, FilePosition { file_id, offset }) |
@@ -45,7 +45,7 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static { | |||
45 | let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture); | 45 | let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture); |
46 | let range = match range_or_offset { | 46 | let range = match range_or_offset { |
47 | RangeOrOffset::Range(it) => it, | 47 | RangeOrOffset::Range(it) => it, |
48 | RangeOrOffset::Offset(_) => panic!(), | 48 | RangeOrOffset::Offset(_) => panic!("Expected a cursor range, got a position instead"), |
49 | }; | 49 | }; |
50 | (db, FileRange { file_id, range }) | 50 | (db, FileRange { file_id, range }) |
51 | } | 51 | } |
@@ -54,7 +54,9 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static { | |||
54 | let fixture = ChangeFixture::parse(ra_fixture); | 54 | let fixture = ChangeFixture::parse(ra_fixture); |
55 | let mut db = Self::default(); | 55 | let mut db = Self::default(); |
56 | fixture.change.apply(&mut db); | 56 | fixture.change.apply(&mut db); |
57 | let (file_id, range_or_offset) = fixture.file_position.unwrap(); | 57 | let (file_id, range_or_offset) = fixture |
58 | .file_position | ||
59 | .expect("Could not find file position in fixture. Did you forget to add an `$0`?"); | ||
58 | (db, file_id, range_or_offset) | 60 | (db, file_id, range_or_offset) |
59 | } | 61 | } |
60 | 62 | ||
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index eba46a056..0acfa582a 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs | |||
@@ -2066,6 +2066,18 @@ impl Type { | |||
2066 | self.ty.dyn_trait().map(Into::into) | 2066 | self.ty.dyn_trait().map(Into::into) |
2067 | } | 2067 | } |
2068 | 2068 | ||
2069 | /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type, | ||
2070 | /// or an empty iterator otherwise. | ||
2071 | pub fn applicable_inherent_traits<'a>( | ||
2072 | &'a self, | ||
2073 | db: &'a dyn HirDatabase, | ||
2074 | ) -> impl Iterator<Item = Trait> + 'a { | ||
2075 | self.autoderef(db) | ||
2076 | .filter_map(|derefed_type| derefed_type.ty.dyn_trait()) | ||
2077 | .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id)) | ||
2078 | .map(Trait::from) | ||
2079 | } | ||
2080 | |||
2069 | pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> { | 2081 | pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> { |
2070 | self.ty.impl_trait_bounds(db).map(|it| { | 2082 | self.ty.impl_trait_bounds(db).map(|it| { |
2071 | it.into_iter() | 2083 | it.into_iter() |
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs index 7955bf0b5..62500602a 100644 --- a/crates/hir/src/semantics.rs +++ b/crates/hir/src/semantics.rs | |||
@@ -6,10 +6,11 @@ use std::{cell::RefCell, fmt, iter::successors}; | |||
6 | 6 | ||
7 | use base_db::{FileId, FileRange}; | 7 | use base_db::{FileId, FileRange}; |
8 | use hir_def::{ | 8 | use hir_def::{ |
9 | body, | ||
9 | resolver::{self, HasResolver, Resolver, TypeNs}, | 10 | resolver::{self, HasResolver, Resolver, TypeNs}, |
10 | AsMacroCall, FunctionId, TraitId, VariantId, | 11 | AsMacroCall, FunctionId, TraitId, VariantId, |
11 | }; | 12 | }; |
12 | use hir_expand::{hygiene::Hygiene, name::AsName, ExpansionInfo}; | 13 | use hir_expand::{name::AsName, ExpansionInfo}; |
13 | use hir_ty::associated_type_shorthand_candidates; | 14 | use hir_ty::associated_type_shorthand_candidates; |
14 | use itertools::Itertools; | 15 | use itertools::Itertools; |
15 | use rustc_hash::{FxHashMap, FxHashSet}; | 16 | use rustc_hash::{FxHashMap, FxHashSet}; |
@@ -853,8 +854,8 @@ impl<'a> SemanticsScope<'a> { | |||
853 | /// Resolve a path as-if it was written at the given scope. This is | 854 | /// Resolve a path as-if it was written at the given scope. This is |
854 | /// necessary a heuristic, as it doesn't take hygiene into account. | 855 | /// necessary a heuristic, as it doesn't take hygiene into account. |
855 | pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> { | 856 | pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> { |
856 | let hygiene = Hygiene::new(self.db.upcast(), self.file_id); | 857 | let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id); |
857 | let path = Path::from_src(path.clone(), &hygiene)?; | 858 | let path = Path::from_src(path.clone(), &ctx)?; |
858 | resolve_hir_path(self.db, &self.resolver, &path) | 859 | resolve_hir_path(self.db, &self.resolver, &path) |
859 | } | 860 | } |
860 | } | 861 | } |
diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs index 847d2537d..0895bd6f1 100644 --- a/crates/hir/src/source_analyzer.rs +++ b/crates/hir/src/source_analyzer.rs | |||
@@ -9,6 +9,7 @@ use std::{iter::once, sync::Arc}; | |||
9 | 9 | ||
10 | use hir_def::{ | 10 | use hir_def::{ |
11 | body::{ | 11 | body::{ |
12 | self, | ||
12 | scope::{ExprScopes, ScopeId}, | 13 | scope::{ExprScopes, ScopeId}, |
13 | Body, BodySourceMap, | 14 | Body, BodySourceMap, |
14 | }, | 15 | }, |
@@ -202,8 +203,8 @@ impl SourceAnalyzer { | |||
202 | db: &dyn HirDatabase, | 203 | db: &dyn HirDatabase, |
203 | macro_call: InFile<&ast::MacroCall>, | 204 | macro_call: InFile<&ast::MacroCall>, |
204 | ) -> Option<MacroDef> { | 205 | ) -> Option<MacroDef> { |
205 | let hygiene = Hygiene::new(db.upcast(), macro_call.file_id); | 206 | let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id); |
206 | let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?; | 207 | let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?; |
207 | self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into()) | 208 | self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into()) |
208 | } | 209 | } |
209 | 210 | ||
@@ -281,7 +282,9 @@ impl SourceAnalyzer { | |||
281 | } | 282 | } |
282 | 283 | ||
283 | // This must be a normal source file rather than macro file. | 284 | // This must be a normal source file rather than macro file. |
284 | let hir_path = Path::from_src(path.clone(), &Hygiene::new(db.upcast(), self.file_id))?; | 285 | let hygiene = Hygiene::new(db.upcast(), self.file_id); |
286 | let ctx = body::LowerCtx::with_hygiene(&hygiene); | ||
287 | let hir_path = Path::from_src(path.clone(), &ctx)?; | ||
285 | 288 | ||
286 | // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we | 289 | // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we |
287 | // trying to resolve foo::bar. | 290 | // trying to resolve foo::bar. |
diff --git a/crates/hir_def/src/body.rs b/crates/hir_def/src/body.rs index 96b959967..131f424cc 100644 --- a/crates/hir_def/src/body.rs +++ b/crates/hir_def/src/body.rs | |||
@@ -21,7 +21,7 @@ use profile::Count; | |||
21 | use rustc_hash::FxHashMap; | 21 | use rustc_hash::FxHashMap; |
22 | use syntax::{ast, AstNode, AstPtr}; | 22 | use syntax::{ast, AstNode, AstPtr}; |
23 | 23 | ||
24 | pub(crate) use lower::LowerCtx; | 24 | pub use lower::LowerCtx; |
25 | 25 | ||
26 | use crate::{ | 26 | use crate::{ |
27 | attr::{Attrs, RawAttrs}, | 27 | attr::{Attrs, RawAttrs}, |
@@ -37,13 +37,15 @@ use crate::{ | |||
37 | 37 | ||
38 | /// A subset of Expander that only deals with cfg attributes. We only need it to | 38 | /// A subset of Expander that only deals with cfg attributes. We only need it to |
39 | /// avoid cyclic queries in crate def map during enum processing. | 39 | /// avoid cyclic queries in crate def map during enum processing. |
40 | #[derive(Debug)] | ||
40 | pub(crate) struct CfgExpander { | 41 | pub(crate) struct CfgExpander { |
41 | cfg_options: CfgOptions, | 42 | cfg_options: CfgOptions, |
42 | hygiene: Hygiene, | 43 | hygiene: Hygiene, |
43 | krate: CrateId, | 44 | krate: CrateId, |
44 | } | 45 | } |
45 | 46 | ||
46 | pub(crate) struct Expander { | 47 | #[derive(Debug)] |
48 | pub struct Expander { | ||
47 | cfg_expander: CfgExpander, | 49 | cfg_expander: CfgExpander, |
48 | def_map: Arc<DefMap>, | 50 | def_map: Arc<DefMap>, |
49 | current_file_id: HirFileId, | 51 | current_file_id: HirFileId, |
@@ -80,11 +82,7 @@ impl CfgExpander { | |||
80 | } | 82 | } |
81 | 83 | ||
82 | impl Expander { | 84 | impl Expander { |
83 | pub(crate) fn new( | 85 | pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander { |
84 | db: &dyn DefDatabase, | ||
85 | current_file_id: HirFileId, | ||
86 | module: ModuleId, | ||
87 | ) -> Expander { | ||
88 | let cfg_expander = CfgExpander::new(db, current_file_id, module.krate); | 86 | let cfg_expander = CfgExpander::new(db, current_file_id, module.krate); |
89 | let def_map = module.def_map(db); | 87 | let def_map = module.def_map(db); |
90 | let ast_id_map = db.ast_id_map(current_file_id); | 88 | let ast_id_map = db.ast_id_map(current_file_id); |
@@ -98,7 +96,7 @@ impl Expander { | |||
98 | } | 96 | } |
99 | } | 97 | } |
100 | 98 | ||
101 | pub(crate) fn enter_expand<T: ast::AstNode>( | 99 | pub fn enter_expand<T: ast::AstNode>( |
102 | &mut self, | 100 | &mut self, |
103 | db: &dyn DefDatabase, | 101 | db: &dyn DefDatabase, |
104 | macro_call: ast::MacroCall, | 102 | macro_call: ast::MacroCall, |
@@ -170,7 +168,7 @@ impl Expander { | |||
170 | Ok(ExpandResult { value: Some((mark, node)), err }) | 168 | Ok(ExpandResult { value: Some((mark, node)), err }) |
171 | } | 169 | } |
172 | 170 | ||
173 | pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) { | 171 | pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) { |
174 | self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id); | 172 | self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id); |
175 | self.current_file_id = mark.file_id; | 173 | self.current_file_id = mark.file_id; |
176 | self.ast_id_map = mem::take(&mut mark.ast_id_map); | 174 | self.ast_id_map = mem::take(&mut mark.ast_id_map); |
@@ -190,8 +188,13 @@ impl Expander { | |||
190 | &self.cfg_expander.cfg_options | 188 | &self.cfg_expander.cfg_options |
191 | } | 189 | } |
192 | 190 | ||
191 | pub fn current_file_id(&self) -> HirFileId { | ||
192 | self.current_file_id | ||
193 | } | ||
194 | |||
193 | fn parse_path(&mut self, path: ast::Path) -> Option<Path> { | 195 | fn parse_path(&mut self, path: ast::Path) -> Option<Path> { |
194 | Path::from_src(path, &self.cfg_expander.hygiene) | 196 | let ctx = LowerCtx::with_hygiene(&self.cfg_expander.hygiene); |
197 | Path::from_src(path, &ctx) | ||
195 | } | 198 | } |
196 | 199 | ||
197 | fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> { | 200 | fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> { |
@@ -204,7 +207,8 @@ impl Expander { | |||
204 | } | 207 | } |
205 | } | 208 | } |
206 | 209 | ||
207 | pub(crate) struct Mark { | 210 | #[derive(Debug)] |
211 | pub struct Mark { | ||
208 | file_id: HirFileId, | 212 | file_id: HirFileId, |
209 | ast_id_map: Arc<AstIdMap>, | 213 | ast_id_map: Arc<AstIdMap>, |
210 | bomb: DropBomb, | 214 | bomb: DropBomb, |
diff --git a/crates/hir_def/src/body/lower.rs b/crates/hir_def/src/body/lower.rs index ed07d6928..c11da30d2 100644 --- a/crates/hir_def/src/body/lower.rs +++ b/crates/hir_def/src/body/lower.rs | |||
@@ -1,10 +1,11 @@ | |||
1 | //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr` | 1 | //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr` |
2 | //! representation. | 2 | //! representation. |
3 | 3 | ||
4 | use std::mem; | 4 | use std::{mem, sync::Arc}; |
5 | 5 | ||
6 | use either::Either; | 6 | use either::Either; |
7 | use hir_expand::{ | 7 | use hir_expand::{ |
8 | ast_id_map::{AstIdMap, FileAstId}, | ||
8 | hygiene::Hygiene, | 9 | hygiene::Hygiene, |
9 | name::{name, AsName, Name}, | 10 | name::{name, AsName, Name}, |
10 | ExpandError, HirFileId, | 11 | ExpandError, HirFileId, |
@@ -39,20 +40,39 @@ use crate::{ | |||
39 | 40 | ||
40 | use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource}; | 41 | use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource}; |
41 | 42 | ||
42 | pub(crate) struct LowerCtx { | 43 | pub struct LowerCtx { |
43 | hygiene: Hygiene, | 44 | hygiene: Hygiene, |
45 | file_id: Option<HirFileId>, | ||
46 | source_ast_id_map: Option<Arc<AstIdMap>>, | ||
44 | } | 47 | } |
45 | 48 | ||
46 | impl LowerCtx { | 49 | impl LowerCtx { |
47 | pub(crate) fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self { | 50 | pub fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self { |
48 | LowerCtx { hygiene: Hygiene::new(db.upcast(), file_id) } | 51 | LowerCtx { |
52 | hygiene: Hygiene::new(db.upcast(), file_id), | ||
53 | file_id: Some(file_id), | ||
54 | source_ast_id_map: Some(db.ast_id_map(file_id)), | ||
55 | } | ||
56 | } | ||
57 | |||
58 | pub fn with_hygiene(hygiene: &Hygiene) -> Self { | ||
59 | LowerCtx { hygiene: hygiene.clone(), file_id: None, source_ast_id_map: None } | ||
60 | } | ||
61 | |||
62 | pub(crate) fn hygiene(&self) -> &Hygiene { | ||
63 | &self.hygiene | ||
49 | } | 64 | } |
50 | pub(crate) fn with_hygiene(hygiene: &Hygiene) -> Self { | 65 | |
51 | LowerCtx { hygiene: hygiene.clone() } | 66 | pub(crate) fn file_id(&self) -> HirFileId { |
67 | self.file_id.unwrap() | ||
52 | } | 68 | } |
53 | 69 | ||
54 | pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> { | 70 | pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> { |
55 | Path::from_src(ast, &self.hygiene) | 71 | Path::from_src(ast, self) |
72 | } | ||
73 | |||
74 | pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> Option<FileAstId<N>> { | ||
75 | self.source_ast_id_map.as_ref().map(|ast_id_map| ast_id_map.ast_id(item)) | ||
56 | } | 76 | } |
57 | } | 77 | } |
58 | 78 | ||
@@ -568,9 +588,13 @@ impl ExprCollector<'_> { | |||
568 | 588 | ||
569 | let res = match res { | 589 | let res = match res { |
570 | Ok(res) => res, | 590 | Ok(res) => res, |
571 | Err(UnresolvedMacro) => { | 591 | Err(UnresolvedMacro { path }) => { |
572 | self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall( | 592 | self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall( |
573 | UnresolvedMacroCall { file: outer_file, node: syntax_ptr.cast().unwrap() }, | 593 | UnresolvedMacroCall { |
594 | file: outer_file, | ||
595 | node: syntax_ptr.cast().unwrap(), | ||
596 | path, | ||
597 | }, | ||
574 | )); | 598 | )); |
575 | collector(self, None); | 599 | collector(self, None); |
576 | return; | 600 | return; |
diff --git a/crates/hir_def/src/body/tests.rs b/crates/hir_def/src/body/tests.rs index c1d3e998f..63f5fe88d 100644 --- a/crates/hir_def/src/body/tests.rs +++ b/crates/hir_def/src/body/tests.rs | |||
@@ -180,7 +180,7 @@ fn unresolved_macro_diag() { | |||
180 | r#" | 180 | r#" |
181 | fn f() { | 181 | fn f() { |
182 | m!(); | 182 | m!(); |
183 | //^^^^ unresolved macro call | 183 | //^^^^ unresolved macro `m!` |
184 | } | 184 | } |
185 | "#, | 185 | "#, |
186 | ); | 186 | ); |
diff --git a/crates/hir_def/src/diagnostics.rs b/crates/hir_def/src/diagnostics.rs index 97abf8653..a71ae2668 100644 --- a/crates/hir_def/src/diagnostics.rs +++ b/crates/hir_def/src/diagnostics.rs | |||
@@ -8,7 +8,7 @@ use hir_expand::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticSink}; | |||
8 | use hir_expand::{HirFileId, InFile}; | 8 | use hir_expand::{HirFileId, InFile}; |
9 | use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange}; | 9 | use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange}; |
10 | 10 | ||
11 | use crate::{db::DefDatabase, DefWithBodyId}; | 11 | use crate::{db::DefDatabase, path::ModPath, DefWithBodyId}; |
12 | 12 | ||
13 | pub fn validate_body(db: &dyn DefDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) { | 13 | pub fn validate_body(db: &dyn DefDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) { |
14 | let source_map = db.body_with_source_map(owner).1; | 14 | let source_map = db.body_with_source_map(owner).1; |
@@ -103,6 +103,7 @@ impl Diagnostic for UnresolvedImport { | |||
103 | pub struct UnresolvedMacroCall { | 103 | pub struct UnresolvedMacroCall { |
104 | pub file: HirFileId, | 104 | pub file: HirFileId, |
105 | pub node: AstPtr<ast::MacroCall>, | 105 | pub node: AstPtr<ast::MacroCall>, |
106 | pub path: ModPath, | ||
106 | } | 107 | } |
107 | 108 | ||
108 | impl Diagnostic for UnresolvedMacroCall { | 109 | impl Diagnostic for UnresolvedMacroCall { |
@@ -110,7 +111,7 @@ impl Diagnostic for UnresolvedMacroCall { | |||
110 | DiagnosticCode("unresolved-macro-call") | 111 | DiagnosticCode("unresolved-macro-call") |
111 | } | 112 | } |
112 | fn message(&self) -> String { | 113 | fn message(&self) -> String { |
113 | "unresolved macro call".to_string() | 114 | format!("unresolved macro `{}!`", self.path) |
114 | } | 115 | } |
115 | fn display_source(&self) -> InFile<SyntaxNodePtr> { | 116 | fn display_source(&self) -> InFile<SyntaxNodePtr> { |
116 | InFile::new(self.file, self.node.clone().into()) | 117 | InFile::new(self.file, self.node.clone().into()) |
diff --git a/crates/hir_def/src/find_path.rs b/crates/hir_def/src/find_path.rs index 109d3552f..2c4bbe585 100644 --- a/crates/hir_def/src/find_path.rs +++ b/crates/hir_def/src/find_path.rs | |||
@@ -425,106 +425,142 @@ mod tests { | |||
425 | 425 | ||
426 | #[test] | 426 | #[test] |
427 | fn same_module() { | 427 | fn same_module() { |
428 | let code = r#" | 428 | check_found_path( |
429 | //- /main.rs | 429 | r#" |
430 | struct S; | 430 | struct S; |
431 | $0 | 431 | $0 |
432 | "#; | 432 | "#, |
433 | check_found_path(code, "S", "S", "crate::S", "self::S"); | 433 | "S", |
434 | "S", | ||
435 | "crate::S", | ||
436 | "self::S", | ||
437 | ); | ||
434 | } | 438 | } |
435 | 439 | ||
436 | #[test] | 440 | #[test] |
437 | fn enum_variant() { | 441 | fn enum_variant() { |
438 | let code = r#" | 442 | check_found_path( |
439 | //- /main.rs | 443 | r#" |
440 | enum E { A } | 444 | enum E { A } |
441 | $0 | 445 | $0 |
442 | "#; | 446 | "#, |
443 | check_found_path(code, "E::A", "E::A", "E::A", "E::A"); | 447 | "E::A", |
448 | "E::A", | ||
449 | "E::A", | ||
450 | "E::A", | ||
451 | ); | ||
444 | } | 452 | } |
445 | 453 | ||
446 | #[test] | 454 | #[test] |
447 | fn sub_module() { | 455 | fn sub_module() { |
448 | let code = r#" | 456 | check_found_path( |
449 | //- /main.rs | 457 | r#" |
450 | mod foo { | 458 | mod foo { |
451 | pub struct S; | 459 | pub struct S; |
452 | } | 460 | } |
453 | $0 | 461 | $0 |
454 | "#; | 462 | "#, |
455 | check_found_path(code, "foo::S", "foo::S", "crate::foo::S", "self::foo::S"); | 463 | "foo::S", |
464 | "foo::S", | ||
465 | "crate::foo::S", | ||
466 | "self::foo::S", | ||
467 | ); | ||
456 | } | 468 | } |
457 | 469 | ||
458 | #[test] | 470 | #[test] |
459 | fn super_module() { | 471 | fn super_module() { |
460 | let code = r#" | 472 | check_found_path( |
461 | //- /main.rs | 473 | r#" |
462 | mod foo; | 474 | //- /main.rs |
463 | //- /foo.rs | 475 | mod foo; |
464 | mod bar; | 476 | //- /foo.rs |
465 | struct S; | 477 | mod bar; |
466 | //- /foo/bar.rs | 478 | struct S; |
467 | $0 | 479 | //- /foo/bar.rs |
468 | "#; | 480 | $0 |
469 | check_found_path(code, "super::S", "super::S", "crate::foo::S", "super::S"); | 481 | "#, |
482 | "super::S", | ||
483 | "super::S", | ||
484 | "crate::foo::S", | ||
485 | "super::S", | ||
486 | ); | ||
470 | } | 487 | } |
471 | 488 | ||
472 | #[test] | 489 | #[test] |
473 | fn self_module() { | 490 | fn self_module() { |
474 | let code = r#" | 491 | check_found_path( |
475 | //- /main.rs | 492 | r#" |
476 | mod foo; | 493 | //- /main.rs |
477 | //- /foo.rs | 494 | mod foo; |
478 | $0 | 495 | //- /foo.rs |
479 | "#; | 496 | $0 |
480 | check_found_path(code, "self", "self", "crate::foo", "self"); | 497 | "#, |
498 | "self", | ||
499 | "self", | ||
500 | "crate::foo", | ||
501 | "self", | ||
502 | ); | ||
481 | } | 503 | } |
482 | 504 | ||
483 | #[test] | 505 | #[test] |
484 | fn crate_root() { | 506 | fn crate_root() { |
485 | let code = r#" | 507 | check_found_path( |
486 | //- /main.rs | 508 | r#" |
487 | mod foo; | 509 | //- /main.rs |
488 | //- /foo.rs | 510 | mod foo; |
489 | $0 | 511 | //- /foo.rs |
490 | "#; | 512 | $0 |
491 | check_found_path(code, "crate", "crate", "crate", "crate"); | 513 | "#, |
514 | "crate", | ||
515 | "crate", | ||
516 | "crate", | ||
517 | "crate", | ||
518 | ); | ||
492 | } | 519 | } |
493 | 520 | ||
494 | #[test] | 521 | #[test] |
495 | fn same_crate() { | 522 | fn same_crate() { |
496 | let code = r#" | 523 | check_found_path( |
497 | //- /main.rs | 524 | r#" |
498 | mod foo; | 525 | //- /main.rs |
499 | struct S; | 526 | mod foo; |
500 | //- /foo.rs | 527 | struct S; |
501 | $0 | 528 | //- /foo.rs |
502 | "#; | 529 | $0 |
503 | check_found_path(code, "crate::S", "crate::S", "crate::S", "crate::S"); | 530 | "#, |
531 | "crate::S", | ||
532 | "crate::S", | ||
533 | "crate::S", | ||
534 | "crate::S", | ||
535 | ); | ||
504 | } | 536 | } |
505 | 537 | ||
506 | #[test] | 538 | #[test] |
507 | fn different_crate() { | 539 | fn different_crate() { |
508 | let code = r#" | 540 | check_found_path( |
509 | //- /main.rs crate:main deps:std | 541 | r#" |
510 | $0 | 542 | //- /main.rs crate:main deps:std |
511 | //- /std.rs crate:std | 543 | $0 |
512 | pub struct S; | 544 | //- /std.rs crate:std |
513 | "#; | 545 | pub struct S; |
514 | check_found_path(code, "std::S", "std::S", "std::S", "std::S"); | 546 | "#, |
547 | "std::S", | ||
548 | "std::S", | ||
549 | "std::S", | ||
550 | "std::S", | ||
551 | ); | ||
515 | } | 552 | } |
516 | 553 | ||
517 | #[test] | 554 | #[test] |
518 | fn different_crate_renamed() { | 555 | fn different_crate_renamed() { |
519 | let code = r#" | ||
520 | //- /main.rs crate:main deps:std | ||
521 | extern crate std as std_renamed; | ||
522 | $0 | ||
523 | //- /std.rs crate:std | ||
524 | pub struct S; | ||
525 | "#; | ||
526 | check_found_path( | 556 | check_found_path( |
527 | code, | 557 | r#" |
558 | //- /main.rs crate:main deps:std | ||
559 | extern crate std as std_renamed; | ||
560 | $0 | ||
561 | //- /std.rs crate:std | ||
562 | pub struct S; | ||
563 | "#, | ||
528 | "std_renamed::S", | 564 | "std_renamed::S", |
529 | "std_renamed::S", | 565 | "std_renamed::S", |
530 | "std_renamed::S", | 566 | "std_renamed::S", |
@@ -537,41 +573,38 @@ mod tests { | |||
537 | cov_mark::check!(partially_imported); | 573 | cov_mark::check!(partially_imported); |
538 | // Tests that short paths are used even for external items, when parts of the path are | 574 | // Tests that short paths are used even for external items, when parts of the path are |
539 | // already in scope. | 575 | // already in scope. |
540 | let code = r#" | 576 | check_found_path( |
541 | //- /main.rs crate:main deps:syntax | 577 | r#" |
578 | //- /main.rs crate:main deps:syntax | ||
542 | 579 | ||
543 | use syntax::ast; | 580 | use syntax::ast; |
544 | $0 | 581 | $0 |
545 | 582 | ||
546 | //- /lib.rs crate:syntax | 583 | //- /lib.rs crate:syntax |
547 | pub mod ast { | 584 | pub mod ast { |
548 | pub enum ModuleItem { | 585 | pub enum ModuleItem { |
549 | A, B, C, | 586 | A, B, C, |
550 | } | 587 | } |
551 | } | 588 | } |
552 | "#; | 589 | "#, |
553 | check_found_path( | ||
554 | code, | ||
555 | "ast::ModuleItem", | 590 | "ast::ModuleItem", |
556 | "syntax::ast::ModuleItem", | 591 | "syntax::ast::ModuleItem", |
557 | "syntax::ast::ModuleItem", | 592 | "syntax::ast::ModuleItem", |
558 | "syntax::ast::ModuleItem", | 593 | "syntax::ast::ModuleItem", |
559 | ); | 594 | ); |
560 | 595 | ||
561 | let code = r#" | ||
562 | //- /main.rs crate:main deps:syntax | ||
563 | |||
564 | $0 | ||
565 | |||
566 | //- /lib.rs crate:syntax | ||
567 | pub mod ast { | ||
568 | pub enum ModuleItem { | ||
569 | A, B, C, | ||
570 | } | ||
571 | } | ||
572 | "#; | ||
573 | check_found_path( | 596 | check_found_path( |
574 | code, | 597 | r#" |
598 | //- /main.rs crate:main deps:syntax | ||
599 | $0 | ||
600 | |||
601 | //- /lib.rs crate:syntax | ||
602 | pub mod ast { | ||
603 | pub enum ModuleItem { | ||
604 | A, B, C, | ||
605 | } | ||
606 | } | ||
607 | "#, | ||
575 | "syntax::ast::ModuleItem", | 608 | "syntax::ast::ModuleItem", |
576 | "syntax::ast::ModuleItem", | 609 | "syntax::ast::ModuleItem", |
577 | "syntax::ast::ModuleItem", | 610 | "syntax::ast::ModuleItem", |
@@ -581,68 +614,86 @@ mod tests { | |||
581 | 614 | ||
582 | #[test] | 615 | #[test] |
583 | fn same_crate_reexport() { | 616 | fn same_crate_reexport() { |
584 | let code = r#" | 617 | check_found_path( |
585 | //- /main.rs | 618 | r#" |
586 | mod bar { | 619 | mod bar { |
587 | mod foo { pub(super) struct S; } | 620 | mod foo { pub(super) struct S; } |
588 | pub(crate) use foo::*; | 621 | pub(crate) use foo::*; |
589 | } | 622 | } |
590 | $0 | 623 | $0 |
591 | "#; | 624 | "#, |
592 | check_found_path(code, "bar::S", "bar::S", "crate::bar::S", "self::bar::S"); | 625 | "bar::S", |
626 | "bar::S", | ||
627 | "crate::bar::S", | ||
628 | "self::bar::S", | ||
629 | ); | ||
593 | } | 630 | } |
594 | 631 | ||
595 | #[test] | 632 | #[test] |
596 | fn same_crate_reexport_rename() { | 633 | fn same_crate_reexport_rename() { |
597 | let code = r#" | 634 | check_found_path( |
598 | //- /main.rs | 635 | r#" |
599 | mod bar { | 636 | mod bar { |
600 | mod foo { pub(super) struct S; } | 637 | mod foo { pub(super) struct S; } |
601 | pub(crate) use foo::S as U; | 638 | pub(crate) use foo::S as U; |
602 | } | 639 | } |
603 | $0 | 640 | $0 |
604 | "#; | 641 | "#, |
605 | check_found_path(code, "bar::U", "bar::U", "crate::bar::U", "self::bar::U"); | 642 | "bar::U", |
643 | "bar::U", | ||
644 | "crate::bar::U", | ||
645 | "self::bar::U", | ||
646 | ); | ||
606 | } | 647 | } |
607 | 648 | ||
608 | #[test] | 649 | #[test] |
609 | fn different_crate_reexport() { | 650 | fn different_crate_reexport() { |
610 | let code = r#" | 651 | check_found_path( |
611 | //- /main.rs crate:main deps:std | 652 | r#" |
612 | $0 | 653 | //- /main.rs crate:main deps:std |
613 | //- /std.rs crate:std deps:core | 654 | $0 |
614 | pub use core::S; | 655 | //- /std.rs crate:std deps:core |
615 | //- /core.rs crate:core | 656 | pub use core::S; |
616 | pub struct S; | 657 | //- /core.rs crate:core |
617 | "#; | 658 | pub struct S; |
618 | check_found_path(code, "std::S", "std::S", "std::S", "std::S"); | 659 | "#, |
660 | "std::S", | ||
661 | "std::S", | ||
662 | "std::S", | ||
663 | "std::S", | ||
664 | ); | ||
619 | } | 665 | } |
620 | 666 | ||
621 | #[test] | 667 | #[test] |
622 | fn prelude() { | 668 | fn prelude() { |
623 | let code = r#" | 669 | check_found_path( |
624 | //- /main.rs crate:main deps:std | 670 | r#" |
625 | $0 | 671 | //- /main.rs crate:main deps:std |
626 | //- /std.rs crate:std | 672 | $0 |
627 | pub mod prelude { pub struct S; } | 673 | //- /std.rs crate:std |
628 | #[prelude_import] | 674 | pub mod prelude { pub struct S; } |
629 | pub use prelude::*; | 675 | #[prelude_import] |
630 | "#; | 676 | pub use prelude::*; |
631 | check_found_path(code, "S", "S", "S", "S"); | 677 | "#, |
678 | "S", | ||
679 | "S", | ||
680 | "S", | ||
681 | "S", | ||
682 | ); | ||
632 | } | 683 | } |
633 | 684 | ||
634 | #[test] | 685 | #[test] |
635 | fn enum_variant_from_prelude() { | 686 | fn enum_variant_from_prelude() { |
636 | let code = r#" | 687 | let code = r#" |
637 | //- /main.rs crate:main deps:std | 688 | //- /main.rs crate:main deps:std |
638 | $0 | 689 | $0 |
639 | //- /std.rs crate:std | 690 | //- /std.rs crate:std |
640 | pub mod prelude { | 691 | pub mod prelude { |
641 | pub enum Option<T> { Some(T), None } | 692 | pub enum Option<T> { Some(T), None } |
642 | pub use Option::*; | 693 | pub use Option::*; |
643 | } | 694 | } |
644 | #[prelude_import] | 695 | #[prelude_import] |
645 | pub use prelude::*; | 696 | pub use prelude::*; |
646 | "#; | 697 | "#; |
647 | check_found_path(code, "None", "None", "None", "None"); | 698 | check_found_path(code, "None", "None", "None", "None"); |
648 | check_found_path(code, "Some", "Some", "Some", "Some"); | 699 | check_found_path(code, "Some", "Some", "Some", "Some"); |
@@ -650,71 +701,85 @@ mod tests { | |||
650 | 701 | ||
651 | #[test] | 702 | #[test] |
652 | fn shortest_path() { | 703 | fn shortest_path() { |
653 | let code = r#" | 704 | check_found_path( |
654 | //- /main.rs | 705 | r#" |
655 | pub mod foo; | 706 | //- /main.rs |
656 | pub mod baz; | 707 | pub mod foo; |
657 | struct S; | 708 | pub mod baz; |
658 | $0 | 709 | struct S; |
659 | //- /foo.rs | 710 | $0 |
660 | pub mod bar { pub struct S; } | 711 | //- /foo.rs |
661 | //- /baz.rs | 712 | pub mod bar { pub struct S; } |
662 | pub use crate::foo::bar::S; | 713 | //- /baz.rs |
663 | "#; | 714 | pub use crate::foo::bar::S; |
664 | check_found_path(code, "baz::S", "baz::S", "crate::baz::S", "self::baz::S"); | 715 | "#, |
716 | "baz::S", | ||
717 | "baz::S", | ||
718 | "crate::baz::S", | ||
719 | "self::baz::S", | ||
720 | ); | ||
665 | } | 721 | } |
666 | 722 | ||
667 | #[test] | 723 | #[test] |
668 | fn discount_private_imports() { | 724 | fn discount_private_imports() { |
669 | let code = r#" | 725 | check_found_path( |
670 | //- /main.rs | 726 | r#" |
671 | mod foo; | 727 | //- /main.rs |
672 | pub mod bar { pub struct S; } | 728 | mod foo; |
673 | use bar::S; | 729 | pub mod bar { pub struct S; } |
674 | //- /foo.rs | 730 | use bar::S; |
675 | $0 | 731 | //- /foo.rs |
676 | "#; | 732 | $0 |
677 | // crate::S would be shorter, but using private imports seems wrong | 733 | "#, |
678 | check_found_path(code, "crate::bar::S", "crate::bar::S", "crate::bar::S", "crate::bar::S"); | 734 | // crate::S would be shorter, but using private imports seems wrong |
735 | "crate::bar::S", | ||
736 | "crate::bar::S", | ||
737 | "crate::bar::S", | ||
738 | "crate::bar::S", | ||
739 | ); | ||
679 | } | 740 | } |
680 | 741 | ||
681 | #[test] | 742 | #[test] |
682 | fn import_cycle() { | 743 | fn import_cycle() { |
683 | let code = r#" | 744 | check_found_path( |
684 | //- /main.rs | 745 | r#" |
685 | pub mod foo; | 746 | //- /main.rs |
686 | pub mod bar; | 747 | pub mod foo; |
687 | pub mod baz; | 748 | pub mod bar; |
688 | //- /bar.rs | 749 | pub mod baz; |
689 | $0 | 750 | //- /bar.rs |
690 | //- /foo.rs | 751 | $0 |
691 | pub use super::baz; | 752 | //- /foo.rs |
692 | pub struct S; | 753 | pub use super::baz; |
693 | //- /baz.rs | 754 | pub struct S; |
694 | pub use super::foo; | 755 | //- /baz.rs |
695 | "#; | 756 | pub use super::foo; |
696 | check_found_path(code, "crate::foo::S", "crate::foo::S", "crate::foo::S", "crate::foo::S"); | 757 | "#, |
758 | "crate::foo::S", | ||
759 | "crate::foo::S", | ||
760 | "crate::foo::S", | ||
761 | "crate::foo::S", | ||
762 | ); | ||
697 | } | 763 | } |
698 | 764 | ||
699 | #[test] | 765 | #[test] |
700 | fn prefer_std_paths_over_alloc() { | 766 | fn prefer_std_paths_over_alloc() { |
701 | cov_mark::check!(prefer_std_paths); | 767 | cov_mark::check!(prefer_std_paths); |
702 | let code = r#" | 768 | check_found_path( |
703 | //- /main.rs crate:main deps:alloc,std | 769 | r#" |
704 | $0 | 770 | //- /main.rs crate:main deps:alloc,std |
771 | $0 | ||
705 | 772 | ||
706 | //- /std.rs crate:std deps:alloc | 773 | //- /std.rs crate:std deps:alloc |
707 | pub mod sync { | 774 | pub mod sync { |
708 | pub use alloc::sync::Arc; | 775 | pub use alloc::sync::Arc; |
709 | } | 776 | } |
710 | 777 | ||
711 | //- /zzz.rs crate:alloc | 778 | //- /zzz.rs crate:alloc |
712 | pub mod sync { | 779 | pub mod sync { |
713 | pub struct Arc; | 780 | pub struct Arc; |
714 | } | 781 | } |
715 | "#; | 782 | "#, |
716 | check_found_path( | ||
717 | code, | ||
718 | "std::sync::Arc", | 783 | "std::sync::Arc", |
719 | "std::sync::Arc", | 784 | "std::sync::Arc", |
720 | "std::sync::Arc", | 785 | "std::sync::Arc", |
@@ -725,26 +790,25 @@ mod tests { | |||
725 | #[test] | 790 | #[test] |
726 | fn prefer_core_paths_over_std() { | 791 | fn prefer_core_paths_over_std() { |
727 | cov_mark::check!(prefer_no_std_paths); | 792 | cov_mark::check!(prefer_no_std_paths); |
728 | let code = r#" | 793 | check_found_path( |
729 | //- /main.rs crate:main deps:core,std | 794 | r#" |
730 | #![no_std] | 795 | //- /main.rs crate:main deps:core,std |
796 | #![no_std] | ||
731 | 797 | ||
732 | $0 | 798 | $0 |
733 | 799 | ||
734 | //- /std.rs crate:std deps:core | 800 | //- /std.rs crate:std deps:core |
735 | 801 | ||
736 | pub mod fmt { | 802 | pub mod fmt { |
737 | pub use core::fmt::Error; | 803 | pub use core::fmt::Error; |
738 | } | 804 | } |
739 | 805 | ||
740 | //- /zzz.rs crate:core | 806 | //- /zzz.rs crate:core |
741 | 807 | ||
742 | pub mod fmt { | 808 | pub mod fmt { |
743 | pub struct Error; | 809 | pub struct Error; |
744 | } | 810 | } |
745 | "#; | 811 | "#, |
746 | check_found_path( | ||
747 | code, | ||
748 | "core::fmt::Error", | 812 | "core::fmt::Error", |
749 | "core::fmt::Error", | 813 | "core::fmt::Error", |
750 | "core::fmt::Error", | 814 | "core::fmt::Error", |
@@ -754,26 +818,25 @@ mod tests { | |||
754 | 818 | ||
755 | #[test] | 819 | #[test] |
756 | fn prefer_alloc_paths_over_std() { | 820 | fn prefer_alloc_paths_over_std() { |
757 | let code = r#" | 821 | check_found_path( |
758 | //- /main.rs crate:main deps:alloc,std | 822 | r#" |
759 | #![no_std] | 823 | //- /main.rs crate:main deps:alloc,std |
824 | #![no_std] | ||
760 | 825 | ||
761 | $0 | 826 | $0 |
762 | 827 | ||
763 | //- /std.rs crate:std deps:alloc | 828 | //- /std.rs crate:std deps:alloc |
764 | 829 | ||
765 | pub mod sync { | 830 | pub mod sync { |
766 | pub use alloc::sync::Arc; | 831 | pub use alloc::sync::Arc; |
767 | } | 832 | } |
768 | 833 | ||
769 | //- /zzz.rs crate:alloc | 834 | //- /zzz.rs crate:alloc |
770 | 835 | ||
771 | pub mod sync { | 836 | pub mod sync { |
772 | pub struct Arc; | 837 | pub struct Arc; |
773 | } | 838 | } |
774 | "#; | 839 | "#, |
775 | check_found_path( | ||
776 | code, | ||
777 | "alloc::sync::Arc", | 840 | "alloc::sync::Arc", |
778 | "alloc::sync::Arc", | 841 | "alloc::sync::Arc", |
779 | "alloc::sync::Arc", | 842 | "alloc::sync::Arc", |
@@ -783,20 +846,19 @@ mod tests { | |||
783 | 846 | ||
784 | #[test] | 847 | #[test] |
785 | fn prefer_shorter_paths_if_not_alloc() { | 848 | fn prefer_shorter_paths_if_not_alloc() { |
786 | let code = r#" | 849 | check_found_path( |
787 | //- /main.rs crate:main deps:megaalloc,std | 850 | r#" |
788 | $0 | 851 | //- /main.rs crate:main deps:megaalloc,std |
852 | $0 | ||
789 | 853 | ||
790 | //- /std.rs crate:std deps:megaalloc | 854 | //- /std.rs crate:std deps:megaalloc |
791 | pub mod sync { | 855 | pub mod sync { |
792 | pub use megaalloc::sync::Arc; | 856 | pub use megaalloc::sync::Arc; |
793 | } | 857 | } |
794 | 858 | ||
795 | //- /zzz.rs crate:megaalloc | 859 | //- /zzz.rs crate:megaalloc |
796 | pub struct Arc; | 860 | pub struct Arc; |
797 | "#; | 861 | "#, |
798 | check_found_path( | ||
799 | code, | ||
800 | "megaalloc::Arc", | 862 | "megaalloc::Arc", |
801 | "megaalloc::Arc", | 863 | "megaalloc::Arc", |
802 | "megaalloc::Arc", | 864 | "megaalloc::Arc", |
@@ -807,12 +869,11 @@ mod tests { | |||
807 | #[test] | 869 | #[test] |
808 | fn builtins_are_in_scope() { | 870 | fn builtins_are_in_scope() { |
809 | let code = r#" | 871 | let code = r#" |
810 | //- /main.rs | 872 | $0 |
811 | $0 | ||
812 | 873 | ||
813 | pub mod primitive { | 874 | pub mod primitive { |
814 | pub use u8; | 875 | pub use u8; |
815 | } | 876 | } |
816 | "#; | 877 | "#; |
817 | check_found_path(code, "u8", "u8", "u8", "u8"); | 878 | check_found_path(code, "u8", "u8", "u8", "u8"); |
818 | check_found_path(code, "u16", "u16", "u16", "u16"); | 879 | check_found_path(code, "u16", "u16", "u16", "u16"); |
@@ -822,10 +883,10 @@ mod tests { | |||
822 | fn inner_items() { | 883 | fn inner_items() { |
823 | check_found_path( | 884 | check_found_path( |
824 | r#" | 885 | r#" |
825 | fn main() { | 886 | fn main() { |
826 | struct Inner {} | 887 | struct Inner {} |
827 | $0 | 888 | $0 |
828 | } | 889 | } |
829 | "#, | 890 | "#, |
830 | "Inner", | 891 | "Inner", |
831 | "Inner", | 892 | "Inner", |
@@ -838,12 +899,12 @@ mod tests { | |||
838 | fn inner_items_from_outer_scope() { | 899 | fn inner_items_from_outer_scope() { |
839 | check_found_path( | 900 | check_found_path( |
840 | r#" | 901 | r#" |
841 | fn main() { | 902 | fn main() { |
842 | struct Struct {} | 903 | struct Struct {} |
843 | { | 904 | { |
844 | $0 | 905 | $0 |
845 | } | 906 | } |
846 | } | 907 | } |
847 | "#, | 908 | "#, |
848 | "Struct", | 909 | "Struct", |
849 | "Struct", | 910 | "Struct", |
@@ -857,14 +918,14 @@ mod tests { | |||
857 | cov_mark::check!(prefixed_in_block_expression); | 918 | cov_mark::check!(prefixed_in_block_expression); |
858 | check_found_path( | 919 | check_found_path( |
859 | r#" | 920 | r#" |
860 | fn main() { | 921 | fn main() { |
861 | mod module { | 922 | mod module { |
862 | struct Struct {} | 923 | struct Struct {} |
863 | } | 924 | } |
864 | { | 925 | { |
865 | $0 | 926 | $0 |
866 | } | 927 | } |
867 | } | 928 | } |
868 | "#, | 929 | "#, |
869 | "module::Struct", | 930 | "module::Struct", |
870 | "module::Struct", | 931 | "module::Struct", |
@@ -877,14 +938,14 @@ mod tests { | |||
877 | fn outer_items_with_inner_items_present() { | 938 | fn outer_items_with_inner_items_present() { |
878 | check_found_path( | 939 | check_found_path( |
879 | r#" | 940 | r#" |
880 | mod module { | 941 | mod module { |
881 | pub struct CompleteMe; | 942 | pub struct CompleteMe; |
882 | } | 943 | } |
883 | 944 | ||
884 | fn main() { | 945 | fn main() { |
885 | fn inner() {} | 946 | fn inner() {} |
886 | $0 | 947 | $0 |
887 | } | 948 | } |
888 | "#, | 949 | "#, |
889 | "module::CompleteMe", | 950 | "module::CompleteMe", |
890 | "module::CompleteMe", | 951 | "module::CompleteMe", |
@@ -894,6 +955,29 @@ mod tests { | |||
894 | } | 955 | } |
895 | 956 | ||
896 | #[test] | 957 | #[test] |
958 | fn from_inside_module() { | ||
959 | // This worked correctly, but the test suite logic was broken. | ||
960 | cov_mark::check!(submodule_in_testdb); | ||
961 | check_found_path( | ||
962 | r#" | ||
963 | mod baz { | ||
964 | pub struct Foo {} | ||
965 | } | ||
966 | |||
967 | mod bar { | ||
968 | fn bar() { | ||
969 | $0 | ||
970 | } | ||
971 | } | ||
972 | "#, | ||
973 | "crate::baz::Foo", | ||
974 | "crate::baz::Foo", | ||
975 | "crate::baz::Foo", | ||
976 | "crate::baz::Foo", | ||
977 | ) | ||
978 | } | ||
979 | |||
980 | #[test] | ||
897 | fn recursive_pub_mod_reexport() { | 981 | fn recursive_pub_mod_reexport() { |
898 | cov_mark::check!(recursive_imports); | 982 | cov_mark::check!(recursive_imports); |
899 | check_found_path( | 983 | check_found_path( |
diff --git a/crates/hir_def/src/item_tree.rs b/crates/hir_def/src/item_tree.rs index 94e08f835..16a94a058 100644 --- a/crates/hir_def/src/item_tree.rs +++ b/crates/hir_def/src/item_tree.rs | |||
@@ -104,6 +104,11 @@ impl ItemTree { | |||
104 | // items and expanded during block DefMap computation | 104 | // items and expanded during block DefMap computation |
105 | return Default::default(); | 105 | return Default::default(); |
106 | }, | 106 | }, |
107 | ast::Type(ty) => { | ||
108 | // Types can contain inner items. We return an empty item tree in this case, but | ||
109 | // still need to collect inner items. | ||
110 | ctx.lower_inner_items(ty.syntax()) | ||
111 | }, | ||
107 | ast::Expr(e) => { | 112 | ast::Expr(e) => { |
108 | // Macros can expand to expressions. We return an empty item tree in this case, but | 113 | // Macros can expand to expressions. We return an empty item tree in this case, but |
109 | // still need to collect inner items. | 114 | // still need to collect inner items. |
diff --git a/crates/hir_def/src/lib.rs b/crates/hir_def/src/lib.rs index d69116d51..25694f037 100644 --- a/crates/hir_def/src/lib.rs +++ b/crates/hir_def/src/lib.rs | |||
@@ -66,6 +66,7 @@ use hir_expand::{ | |||
66 | }; | 66 | }; |
67 | use la_arena::Idx; | 67 | use la_arena::Idx; |
68 | use nameres::DefMap; | 68 | use nameres::DefMap; |
69 | use path::ModPath; | ||
69 | use syntax::ast; | 70 | use syntax::ast; |
70 | 71 | ||
71 | use crate::builtin_type::BuiltinType; | 72 | use crate::builtin_type::BuiltinType; |
@@ -107,6 +108,18 @@ impl ModuleId { | |||
107 | pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> { | 108 | pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> { |
108 | self.def_map(db).containing_module(self.local_id) | 109 | self.def_map(db).containing_module(self.local_id) |
109 | } | 110 | } |
111 | |||
112 | /// Returns `true` if this module represents a block expression. | ||
113 | /// | ||
114 | /// Returns `false` if this module is a submodule *inside* a block expression | ||
115 | /// (eg. `m` in `{ mod m {} }`). | ||
116 | pub fn is_block_root(&self, db: &dyn db::DefDatabase) -> bool { | ||
117 | if self.block.is_none() { | ||
118 | return false; | ||
119 | } | ||
120 | |||
121 | self.def_map(db)[self.local_id].parent.is_none() | ||
122 | } | ||
110 | } | 123 | } |
111 | 124 | ||
112 | /// An ID of a module, **local** to a specific crate | 125 | /// An ID of a module, **local** to a specific crate |
@@ -435,6 +448,16 @@ impl_from!( | |||
435 | for AttrDefId | 448 | for AttrDefId |
436 | ); | 449 | ); |
437 | 450 | ||
451 | impl From<AssocContainerId> for AttrDefId { | ||
452 | fn from(acid: AssocContainerId) -> Self { | ||
453 | match acid { | ||
454 | AssocContainerId::ModuleId(mid) => AttrDefId::ModuleId(mid), | ||
455 | AssocContainerId::ImplId(iid) => AttrDefId::ImplId(iid), | ||
456 | AssocContainerId::TraitId(tid) => AttrDefId::TraitId(tid), | ||
457 | } | ||
458 | } | ||
459 | } | ||
460 | |||
438 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | 461 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
439 | pub enum VariantId { | 462 | pub enum VariantId { |
440 | EnumVariantId(EnumVariantId), | 463 | EnumVariantId(EnumVariantId), |
@@ -665,7 +688,10 @@ impl<T: ast::AstNode> AstIdWithPath<T> { | |||
665 | } | 688 | } |
666 | } | 689 | } |
667 | 690 | ||
668 | pub struct UnresolvedMacro; | 691 | #[derive(Debug)] |
692 | pub struct UnresolvedMacro { | ||
693 | pub path: ModPath, | ||
694 | } | ||
669 | 695 | ||
670 | fn macro_call_as_call_id( | 696 | fn macro_call_as_call_id( |
671 | call: &AstIdWithPath<ast::MacroCall>, | 697 | call: &AstIdWithPath<ast::MacroCall>, |
@@ -674,7 +700,8 @@ fn macro_call_as_call_id( | |||
674 | resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, | 700 | resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, |
675 | error_sink: &mut dyn FnMut(mbe::ExpandError), | 701 | error_sink: &mut dyn FnMut(mbe::ExpandError), |
676 | ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> { | 702 | ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> { |
677 | let def: MacroDefId = resolver(call.path.clone()).ok_or(UnresolvedMacro)?; | 703 | let def: MacroDefId = |
704 | resolver(call.path.clone()).ok_or_else(|| UnresolvedMacro { path: call.path.clone() })?; | ||
678 | 705 | ||
679 | let res = if let MacroDefKind::BuiltInEager(..) = def.kind { | 706 | let res = if let MacroDefKind::BuiltInEager(..) = def.kind { |
680 | let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast())); | 707 | let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast())); |
@@ -704,8 +731,13 @@ fn derive_macro_as_call_id( | |||
704 | krate: CrateId, | 731 | krate: CrateId, |
705 | resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, | 732 | resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, |
706 | ) -> Result<MacroCallId, UnresolvedMacro> { | 733 | ) -> Result<MacroCallId, UnresolvedMacro> { |
707 | let def: MacroDefId = resolver(item_attr.path.clone()).ok_or(UnresolvedMacro)?; | 734 | let def: MacroDefId = resolver(item_attr.path.clone()) |
708 | let last_segment = item_attr.path.segments().last().ok_or(UnresolvedMacro)?; | 735 | .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?; |
736 | let last_segment = item_attr | ||
737 | .path | ||
738 | .segments() | ||
739 | .last() | ||
740 | .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?; | ||
709 | let res = def | 741 | let res = def |
710 | .as_lazy_macro( | 742 | .as_lazy_macro( |
711 | db.upcast(), | 743 | db.upcast(), |
diff --git a/crates/hir_def/src/nameres.rs b/crates/hir_def/src/nameres.rs index 9e181751c..542f190a1 100644 --- a/crates/hir_def/src/nameres.rs +++ b/crates/hir_def/src/nameres.rs | |||
@@ -481,7 +481,7 @@ mod diagnostics { | |||
481 | 481 | ||
482 | UnresolvedProcMacro { ast: MacroCallKind }, | 482 | UnresolvedProcMacro { ast: MacroCallKind }, |
483 | 483 | ||
484 | UnresolvedMacroCall { ast: AstId<ast::MacroCall> }, | 484 | UnresolvedMacroCall { ast: AstId<ast::MacroCall>, path: ModPath }, |
485 | 485 | ||
486 | MacroError { ast: MacroCallKind, message: String }, | 486 | MacroError { ast: MacroCallKind, message: String }, |
487 | } | 487 | } |
@@ -546,8 +546,9 @@ mod diagnostics { | |||
546 | pub(super) fn unresolved_macro_call( | 546 | pub(super) fn unresolved_macro_call( |
547 | container: LocalModuleId, | 547 | container: LocalModuleId, |
548 | ast: AstId<ast::MacroCall>, | 548 | ast: AstId<ast::MacroCall>, |
549 | path: ModPath, | ||
549 | ) -> Self { | 550 | ) -> Self { |
550 | Self { in_module: container, kind: DiagnosticKind::UnresolvedMacroCall { ast } } | 551 | Self { in_module: container, kind: DiagnosticKind::UnresolvedMacroCall { ast, path } } |
551 | } | 552 | } |
552 | 553 | ||
553 | pub(super) fn add_to( | 554 | pub(super) fn add_to( |
@@ -662,9 +663,13 @@ mod diagnostics { | |||
662 | }); | 663 | }); |
663 | } | 664 | } |
664 | 665 | ||
665 | DiagnosticKind::UnresolvedMacroCall { ast } => { | 666 | DiagnosticKind::UnresolvedMacroCall { ast, path } => { |
666 | let node = ast.to_node(db.upcast()); | 667 | let node = ast.to_node(db.upcast()); |
667 | sink.push(UnresolvedMacroCall { file: ast.file_id, node: AstPtr::new(&node) }); | 668 | sink.push(UnresolvedMacroCall { |
669 | file: ast.file_id, | ||
670 | node: AstPtr::new(&node), | ||
671 | path: path.clone(), | ||
672 | }); | ||
668 | } | 673 | } |
669 | 674 | ||
670 | DiagnosticKind::MacroError { ast, message } => { | 675 | DiagnosticKind::MacroError { ast, message } => { |
diff --git a/crates/hir_def/src/nameres/collector.rs b/crates/hir_def/src/nameres/collector.rs index fb4ddff5e..05ceb1efb 100644 --- a/crates/hir_def/src/nameres/collector.rs +++ b/crates/hir_def/src/nameres/collector.rs | |||
@@ -829,7 +829,7 @@ impl DefCollector<'_> { | |||
829 | res = ReachedFixedPoint::No; | 829 | res = ReachedFixedPoint::No; |
830 | return false; | 830 | return false; |
831 | } | 831 | } |
832 | Err(UnresolvedMacro) | Ok(Err(_)) => {} | 832 | Err(UnresolvedMacro { .. }) | Ok(Err(_)) => {} |
833 | } | 833 | } |
834 | } | 834 | } |
835 | MacroDirectiveKind::Derive { ast_id, derive_attr } => { | 835 | MacroDirectiveKind::Derive { ast_id, derive_attr } => { |
@@ -845,7 +845,7 @@ impl DefCollector<'_> { | |||
845 | res = ReachedFixedPoint::No; | 845 | res = ReachedFixedPoint::No; |
846 | return false; | 846 | return false; |
847 | } | 847 | } |
848 | Err(UnresolvedMacro) => (), | 848 | Err(UnresolvedMacro { .. }) => (), |
849 | } | 849 | } |
850 | } | 850 | } |
851 | } | 851 | } |
@@ -943,10 +943,11 @@ impl DefCollector<'_> { | |||
943 | &mut |_| (), | 943 | &mut |_| (), |
944 | ) { | 944 | ) { |
945 | Ok(_) => (), | 945 | Ok(_) => (), |
946 | Err(UnresolvedMacro) => { | 946 | Err(UnresolvedMacro { path }) => { |
947 | self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call( | 947 | self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call( |
948 | directive.module_id, | 948 | directive.module_id, |
949 | ast_id.ast_id, | 949 | ast_id.ast_id, |
950 | path, | ||
950 | )); | 951 | )); |
951 | } | 952 | } |
952 | }, | 953 | }, |
@@ -1530,7 +1531,7 @@ impl ModCollector<'_, '_> { | |||
1530 | )); | 1531 | )); |
1531 | return; | 1532 | return; |
1532 | } | 1533 | } |
1533 | Err(UnresolvedMacro) => (), | 1534 | Err(UnresolvedMacro { .. }) => (), |
1534 | } | 1535 | } |
1535 | 1536 | ||
1536 | // Case 2: resolve in module scope, expand during name resolution. | 1537 | // Case 2: resolve in module scope, expand during name resolution. |
diff --git a/crates/hir_def/src/nameres/path_resolution.rs b/crates/hir_def/src/nameres/path_resolution.rs index ccc9f22eb..c984148c3 100644 --- a/crates/hir_def/src/nameres/path_resolution.rs +++ b/crates/hir_def/src/nameres/path_resolution.rs | |||
@@ -387,7 +387,13 @@ impl DefMap { | |||
387 | .get_legacy_macro(name) | 387 | .get_legacy_macro(name) |
388 | .map_or_else(PerNs::none, |m| PerNs::macros(m, Visibility::Public)); | 388 | .map_or_else(PerNs::none, |m| PerNs::macros(m, Visibility::Public)); |
389 | let from_scope = self[module].scope.get(name); | 389 | let from_scope = self[module].scope.get(name); |
390 | let from_builtin = BUILTIN_SCOPE.get(name).copied().unwrap_or_else(PerNs::none); | 390 | let from_builtin = match self.block { |
391 | Some(_) => { | ||
392 | // Only resolve to builtins in the root `DefMap`. | ||
393 | PerNs::none() | ||
394 | } | ||
395 | None => BUILTIN_SCOPE.get(name).copied().unwrap_or_else(PerNs::none), | ||
396 | }; | ||
391 | let from_scope_or_builtin = match shadow { | 397 | let from_scope_or_builtin = match shadow { |
392 | BuiltinShadowMode::Module => from_scope.or(from_builtin), | 398 | BuiltinShadowMode::Module => from_scope.or(from_builtin), |
393 | BuiltinShadowMode::Other => { | 399 | BuiltinShadowMode::Other => { |
diff --git a/crates/hir_def/src/nameres/tests/diagnostics.rs b/crates/hir_def/src/nameres/tests/diagnostics.rs index 1ac88fc89..543975e07 100644 --- a/crates/hir_def/src/nameres/tests/diagnostics.rs +++ b/crates/hir_def/src/nameres/tests/diagnostics.rs | |||
@@ -170,7 +170,7 @@ fn unresolved_legacy_scope_macro() { | |||
170 | 170 | ||
171 | m!(); | 171 | m!(); |
172 | m2!(); | 172 | m2!(); |
173 | //^^^^^^ unresolved macro call | 173 | //^^^^^^ unresolved macro `self::m2!` |
174 | "#, | 174 | "#, |
175 | ); | 175 | ); |
176 | } | 176 | } |
@@ -187,7 +187,7 @@ fn unresolved_module_scope_macro() { | |||
187 | 187 | ||
188 | self::m!(); | 188 | self::m!(); |
189 | self::m2!(); | 189 | self::m2!(); |
190 | //^^^^^^^^^^^^ unresolved macro call | 190 | //^^^^^^^^^^^^ unresolved macro `self::m2!` |
191 | "#, | 191 | "#, |
192 | ); | 192 | ); |
193 | } | 193 | } |
diff --git a/crates/hir_def/src/path.rs b/crates/hir_def/src/path.rs index b528ff8ba..509f77850 100644 --- a/crates/hir_def/src/path.rs +++ b/crates/hir_def/src/path.rs | |||
@@ -48,7 +48,8 @@ pub enum ImportAlias { | |||
48 | 48 | ||
49 | impl ModPath { | 49 | impl ModPath { |
50 | pub fn from_src(path: ast::Path, hygiene: &Hygiene) -> Option<ModPath> { | 50 | pub fn from_src(path: ast::Path, hygiene: &Hygiene) -> Option<ModPath> { |
51 | lower::lower_path(path, hygiene).map(|it| (*it.mod_path).clone()) | 51 | let ctx = LowerCtx::with_hygiene(hygiene); |
52 | lower::lower_path(path, &ctx).map(|it| (*it.mod_path).clone()) | ||
52 | } | 53 | } |
53 | 54 | ||
54 | pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath { | 55 | pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath { |
@@ -167,8 +168,8 @@ pub enum GenericArg { | |||
167 | impl Path { | 168 | impl Path { |
168 | /// Converts an `ast::Path` to `Path`. Works with use trees. | 169 | /// Converts an `ast::Path` to `Path`. Works with use trees. |
169 | /// It correctly handles `$crate` based path from macro call. | 170 | /// It correctly handles `$crate` based path from macro call. |
170 | pub fn from_src(path: ast::Path, hygiene: &Hygiene) -> Option<Path> { | 171 | pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> { |
171 | lower::lower_path(path, hygiene) | 172 | lower::lower_path(path, ctx) |
172 | } | 173 | } |
173 | 174 | ||
174 | /// Converts a known mod path to `Path`. | 175 | /// Converts a known mod path to `Path`. |
diff --git a/crates/hir_def/src/path/lower.rs b/crates/hir_def/src/path/lower.rs index 7b29d9d4f..1df6db525 100644 --- a/crates/hir_def/src/path/lower.rs +++ b/crates/hir_def/src/path/lower.rs | |||
@@ -6,10 +6,7 @@ use crate::intern::Interned; | |||
6 | use std::sync::Arc; | 6 | use std::sync::Arc; |
7 | 7 | ||
8 | use either::Either; | 8 | use either::Either; |
9 | use hir_expand::{ | 9 | use hir_expand::name::{name, AsName}; |
10 | hygiene::Hygiene, | ||
11 | name::{name, AsName}, | ||
12 | }; | ||
13 | use syntax::ast::{self, AstNode, TypeBoundsOwner}; | 10 | use syntax::ast::{self, AstNode, TypeBoundsOwner}; |
14 | 11 | ||
15 | use super::AssociatedTypeBinding; | 12 | use super::AssociatedTypeBinding; |
@@ -23,12 +20,12 @@ pub(super) use lower_use::lower_use_tree; | |||
23 | 20 | ||
24 | /// Converts an `ast::Path` to `Path`. Works with use trees. | 21 | /// Converts an `ast::Path` to `Path`. Works with use trees. |
25 | /// It correctly handles `$crate` based path from macro call. | 22 | /// It correctly handles `$crate` based path from macro call. |
26 | pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> { | 23 | pub(super) fn lower_path(mut path: ast::Path, ctx: &LowerCtx) -> Option<Path> { |
27 | let mut kind = PathKind::Plain; | 24 | let mut kind = PathKind::Plain; |
28 | let mut type_anchor = None; | 25 | let mut type_anchor = None; |
29 | let mut segments = Vec::new(); | 26 | let mut segments = Vec::new(); |
30 | let mut generic_args = Vec::new(); | 27 | let mut generic_args = Vec::new(); |
31 | let ctx = LowerCtx::with_hygiene(hygiene); | 28 | let hygiene = ctx.hygiene(); |
32 | loop { | 29 | loop { |
33 | let segment = path.segment()?; | 30 | let segment = path.segment()?; |
34 | 31 | ||
@@ -43,10 +40,10 @@ pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> | |||
43 | Either::Left(name) => { | 40 | Either::Left(name) => { |
44 | let args = segment | 41 | let args = segment |
45 | .generic_arg_list() | 42 | .generic_arg_list() |
46 | .and_then(|it| lower_generic_args(&ctx, it)) | 43 | .and_then(|it| lower_generic_args(ctx, it)) |
47 | .or_else(|| { | 44 | .or_else(|| { |
48 | lower_generic_args_from_fn_path( | 45 | lower_generic_args_from_fn_path( |
49 | &ctx, | 46 | ctx, |
50 | segment.param_list(), | 47 | segment.param_list(), |
51 | segment.ret_type(), | 48 | segment.ret_type(), |
52 | ) | 49 | ) |
@@ -64,7 +61,7 @@ pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> | |||
64 | ast::PathSegmentKind::Type { type_ref, trait_ref } => { | 61 | ast::PathSegmentKind::Type { type_ref, trait_ref } => { |
65 | assert!(path.qualifier().is_none()); // this can only occur at the first segment | 62 | assert!(path.qualifier().is_none()); // this can only occur at the first segment |
66 | 63 | ||
67 | let self_type = TypeRef::from_ast(&ctx, type_ref?); | 64 | let self_type = TypeRef::from_ast(ctx, type_ref?); |
68 | 65 | ||
69 | match trait_ref { | 66 | match trait_ref { |
70 | // <T>::foo | 67 | // <T>::foo |
@@ -74,7 +71,7 @@ pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> | |||
74 | } | 71 | } |
75 | // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo | 72 | // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo |
76 | Some(trait_ref) => { | 73 | Some(trait_ref) => { |
77 | let path = Path::from_src(trait_ref.path()?, hygiene)?; | 74 | let path = Path::from_src(trait_ref.path()?, ctx)?; |
78 | let mod_path = (*path.mod_path).clone(); | 75 | let mod_path = (*path.mod_path).clone(); |
79 | let num_segments = path.mod_path.segments.len(); | 76 | let num_segments = path.mod_path.segments.len(); |
80 | kind = mod_path.kind; | 77 | kind = mod_path.kind; |
diff --git a/crates/hir_def/src/test_db.rs b/crates/hir_def/src/test_db.rs index dd36106f8..8fa703a57 100644 --- a/crates/hir_def/src/test_db.rs +++ b/crates/hir_def/src/test_db.rs | |||
@@ -15,7 +15,12 @@ use rustc_hash::FxHashSet; | |||
15 | use syntax::{algo, ast, AstNode, TextRange, TextSize}; | 15 | use syntax::{algo, ast, AstNode, TextRange, TextSize}; |
16 | use test_utils::extract_annotations; | 16 | use test_utils::extract_annotations; |
17 | 17 | ||
18 | use crate::{db::DefDatabase, nameres::DefMap, src::HasSource, Lookup, ModuleDefId, ModuleId}; | 18 | use crate::{ |
19 | db::DefDatabase, | ||
20 | nameres::{DefMap, ModuleSource}, | ||
21 | src::HasSource, | ||
22 | LocalModuleId, Lookup, ModuleDefId, ModuleId, | ||
23 | }; | ||
19 | 24 | ||
20 | #[salsa::database( | 25 | #[salsa::database( |
21 | base_db::SourceDatabaseExtStorage, | 26 | base_db::SourceDatabaseExtStorage, |
@@ -87,10 +92,11 @@ impl TestDB { | |||
87 | pub(crate) fn module_at_position(&self, position: FilePosition) -> ModuleId { | 92 | pub(crate) fn module_at_position(&self, position: FilePosition) -> ModuleId { |
88 | let file_module = self.module_for_file(position.file_id); | 93 | let file_module = self.module_for_file(position.file_id); |
89 | let mut def_map = file_module.def_map(self); | 94 | let mut def_map = file_module.def_map(self); |
95 | let module = self.mod_at_position(&def_map, position); | ||
90 | 96 | ||
91 | def_map = match self.block_at_position(&def_map, position) { | 97 | def_map = match self.block_at_position(&def_map, position) { |
92 | Some(it) => it, | 98 | Some(it) => it, |
93 | None => return file_module, | 99 | None => return def_map.module_id(module), |
94 | }; | 100 | }; |
95 | loop { | 101 | loop { |
96 | let new_map = self.block_at_position(&def_map, position); | 102 | let new_map = self.block_at_position(&def_map, position); |
@@ -106,6 +112,47 @@ impl TestDB { | |||
106 | } | 112 | } |
107 | } | 113 | } |
108 | 114 | ||
115 | /// Finds the smallest/innermost module in `def_map` containing `position`. | ||
116 | fn mod_at_position(&self, def_map: &DefMap, position: FilePosition) -> LocalModuleId { | ||
117 | let mut size = None; | ||
118 | let mut res = def_map.root(); | ||
119 | for (module, data) in def_map.modules() { | ||
120 | let src = data.definition_source(self); | ||
121 | if src.file_id != position.file_id.into() { | ||
122 | continue; | ||
123 | } | ||
124 | |||
125 | let range = match src.value { | ||
126 | ModuleSource::SourceFile(it) => it.syntax().text_range(), | ||
127 | ModuleSource::Module(it) => it.syntax().text_range(), | ||
128 | ModuleSource::BlockExpr(it) => it.syntax().text_range(), | ||
129 | }; | ||
130 | |||
131 | if !range.contains(position.offset) { | ||
132 | continue; | ||
133 | } | ||
134 | |||
135 | let new_size = match size { | ||
136 | None => range.len(), | ||
137 | Some(size) => { | ||
138 | if range.len() < size { | ||
139 | range.len() | ||
140 | } else { | ||
141 | size | ||
142 | } | ||
143 | } | ||
144 | }; | ||
145 | |||
146 | if size != Some(new_size) { | ||
147 | cov_mark::hit!(submodule_in_testdb); | ||
148 | size = Some(new_size); | ||
149 | res = module; | ||
150 | } | ||
151 | } | ||
152 | |||
153 | res | ||
154 | } | ||
155 | |||
109 | fn block_at_position(&self, def_map: &DefMap, position: FilePosition) -> Option<Arc<DefMap>> { | 156 | fn block_at_position(&self, def_map: &DefMap, position: FilePosition) -> Option<Arc<DefMap>> { |
110 | // Find the smallest (innermost) function in `def_map` containing the cursor. | 157 | // Find the smallest (innermost) function in `def_map` containing the cursor. |
111 | let mut size = None; | 158 | let mut size = None; |
diff --git a/crates/hir_def/src/type_ref.rs b/crates/hir_def/src/type_ref.rs index 4c24aae94..ea29da5da 100644 --- a/crates/hir_def/src/type_ref.rs +++ b/crates/hir_def/src/type_ref.rs | |||
@@ -1,6 +1,7 @@ | |||
1 | //! HIR for references to types. Paths in these are not yet resolved. They can | 1 | //! HIR for references to types. Paths in these are not yet resolved. They can |
2 | //! be directly created from an ast::TypeRef, without further queries. | 2 | //! be directly created from an ast::TypeRef, without further queries. |
3 | use hir_expand::name::Name; | 3 | |
4 | use hir_expand::{name::Name, AstId, InFile}; | ||
4 | use syntax::ast; | 5 | use syntax::ast; |
5 | 6 | ||
6 | use crate::{body::LowerCtx, path::Path}; | 7 | use crate::{body::LowerCtx, path::Path}; |
@@ -68,6 +69,7 @@ impl TraitRef { | |||
68 | } | 69 | } |
69 | } | 70 | } |
70 | } | 71 | } |
72 | |||
71 | /// Compare ty::Ty | 73 | /// Compare ty::Ty |
72 | #[derive(Clone, PartialEq, Eq, Hash, Debug)] | 74 | #[derive(Clone, PartialEq, Eq, Hash, Debug)] |
73 | pub enum TypeRef { | 75 | pub enum TypeRef { |
@@ -84,6 +86,7 @@ pub enum TypeRef { | |||
84 | // For | 86 | // For |
85 | ImplTrait(Vec<TypeBound>), | 87 | ImplTrait(Vec<TypeBound>), |
86 | DynTrait(Vec<TypeBound>), | 88 | DynTrait(Vec<TypeBound>), |
89 | Macro(AstId<ast::MacroCall>), | ||
87 | Error, | 90 | Error, |
88 | } | 91 | } |
89 | 92 | ||
@@ -116,7 +119,7 @@ pub enum TypeBound { | |||
116 | 119 | ||
117 | impl TypeRef { | 120 | impl TypeRef { |
118 | /// Converts an `ast::TypeRef` to a `hir::TypeRef`. | 121 | /// Converts an `ast::TypeRef` to a `hir::TypeRef`. |
119 | pub(crate) fn from_ast(ctx: &LowerCtx, node: ast::Type) -> Self { | 122 | pub fn from_ast(ctx: &LowerCtx, node: ast::Type) -> Self { |
120 | match node { | 123 | match node { |
121 | ast::Type::ParenType(inner) => TypeRef::from_ast_opt(&ctx, inner.ty()), | 124 | ast::Type::ParenType(inner) => TypeRef::from_ast_opt(&ctx, inner.ty()), |
122 | ast::Type::TupleType(inner) => { | 125 | ast::Type::TupleType(inner) => { |
@@ -176,8 +179,13 @@ impl TypeRef { | |||
176 | ast::Type::DynTraitType(inner) => { | 179 | ast::Type::DynTraitType(inner) => { |
177 | TypeRef::DynTrait(type_bounds_from_ast(ctx, inner.type_bound_list())) | 180 | TypeRef::DynTrait(type_bounds_from_ast(ctx, inner.type_bound_list())) |
178 | } | 181 | } |
179 | // FIXME: Macros in type position are not yet supported. | 182 | ast::Type::MacroType(mt) => match mt.macro_call() { |
180 | ast::Type::MacroType(_) => TypeRef::Error, | 183 | Some(mc) => ctx |
184 | .ast_id(&mc) | ||
185 | .map(|mc| TypeRef::Macro(InFile::new(ctx.file_id(), mc))) | ||
186 | .unwrap_or(TypeRef::Error), | ||
187 | None => TypeRef::Error, | ||
188 | }, | ||
181 | } | 189 | } |
182 | } | 190 | } |
183 | 191 | ||
@@ -215,7 +223,7 @@ impl TypeRef { | |||
215 | } | 223 | } |
216 | } | 224 | } |
217 | TypeRef::Path(path) => go_path(path, f), | 225 | TypeRef::Path(path) => go_path(path, f), |
218 | TypeRef::Never | TypeRef::Placeholder | TypeRef::Error => {} | 226 | TypeRef::Never | TypeRef::Placeholder | TypeRef::Macro(_) | TypeRef::Error => {} |
219 | }; | 227 | }; |
220 | } | 228 | } |
221 | 229 | ||
diff --git a/crates/hir_def/src/visibility.rs b/crates/hir_def/src/visibility.rs index 9908cd926..d4b7c9970 100644 --- a/crates/hir_def/src/visibility.rs +++ b/crates/hir_def/src/visibility.rs | |||
@@ -123,11 +123,19 @@ impl Visibility { | |||
123 | def_map: &DefMap, | 123 | def_map: &DefMap, |
124 | mut from_module: crate::LocalModuleId, | 124 | mut from_module: crate::LocalModuleId, |
125 | ) -> bool { | 125 | ) -> bool { |
126 | let to_module = match self { | 126 | let mut to_module = match self { |
127 | Visibility::Module(m) => m, | 127 | Visibility::Module(m) => m, |
128 | Visibility::Public => return true, | 128 | Visibility::Public => return true, |
129 | }; | 129 | }; |
130 | 130 | ||
131 | // `to_module` might be the root module of a block expression. Those have the same | ||
132 | // visibility as the containing module (even though no items are directly nameable from | ||
133 | // there, getting this right is important for method resolution). | ||
134 | // In that case, we adjust the visibility of `to_module` to point to the containing module. | ||
135 | if to_module.is_block_root(db) { | ||
136 | to_module = to_module.containing_module(db).unwrap(); | ||
137 | } | ||
138 | |||
131 | // from_module needs to be a descendant of to_module | 139 | // from_module needs to be a descendant of to_module |
132 | let mut def_map = def_map; | 140 | let mut def_map = def_map; |
133 | let mut parent_arc; | 141 | let mut parent_arc; |
diff --git a/crates/hir_expand/src/builtin_macro.rs b/crates/hir_expand/src/builtin_macro.rs index 80365fc16..179de61f9 100644 --- a/crates/hir_expand/src/builtin_macro.rs +++ b/crates/hir_expand/src/builtin_macro.rs | |||
@@ -110,6 +110,7 @@ register_builtin! { | |||
110 | (format_args_nl, FormatArgsNl) => format_args_expand, | 110 | (format_args_nl, FormatArgsNl) => format_args_expand, |
111 | (llvm_asm, LlvmAsm) => asm_expand, | 111 | (llvm_asm, LlvmAsm) => asm_expand, |
112 | (asm, Asm) => asm_expand, | 112 | (asm, Asm) => asm_expand, |
113 | (global_asm, GlobalAsm) => global_asm_expand, | ||
113 | (cfg, Cfg) => cfg_expand, | 114 | (cfg, Cfg) => cfg_expand, |
114 | (core_panic, CorePanic) => panic_expand, | 115 | (core_panic, CorePanic) => panic_expand, |
115 | (std_panic, StdPanic) => panic_expand, | 116 | (std_panic, StdPanic) => panic_expand, |
@@ -274,6 +275,15 @@ fn asm_expand( | |||
274 | ExpandResult::ok(expanded) | 275 | ExpandResult::ok(expanded) |
275 | } | 276 | } |
276 | 277 | ||
278 | fn global_asm_expand( | ||
279 | _db: &dyn AstDatabase, | ||
280 | _id: LazyMacroId, | ||
281 | _tt: &tt::Subtree, | ||
282 | ) -> ExpandResult<tt::Subtree> { | ||
283 | // Expand to nothing (at item-level) | ||
284 | ExpandResult::ok(quote! {}) | ||
285 | } | ||
286 | |||
277 | fn cfg_expand( | 287 | fn cfg_expand( |
278 | db: &dyn AstDatabase, | 288 | db: &dyn AstDatabase, |
279 | id: LazyMacroId, | 289 | id: LazyMacroId, |
diff --git a/crates/hir_expand/src/db.rs b/crates/hir_expand/src/db.rs index ca705ee9d..1e4b0cc19 100644 --- a/crates/hir_expand/src/db.rs +++ b/crates/hir_expand/src/db.rs | |||
@@ -440,6 +440,7 @@ fn to_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind { | |||
440 | MACRO_ITEMS | SOURCE_FILE => FragmentKind::Items, | 440 | MACRO_ITEMS | SOURCE_FILE => FragmentKind::Items, |
441 | MACRO_STMTS => FragmentKind::Statements, | 441 | MACRO_STMTS => FragmentKind::Statements, |
442 | MACRO_PAT => FragmentKind::Pattern, | 442 | MACRO_PAT => FragmentKind::Pattern, |
443 | MACRO_TYPE => FragmentKind::Type, | ||
443 | ITEM_LIST => FragmentKind::Items, | 444 | ITEM_LIST => FragmentKind::Items, |
444 | LET_STMT => { | 445 | LET_STMT => { |
445 | // FIXME: Handle LHS Pattern | 446 | // FIXME: Handle LHS Pattern |
diff --git a/crates/hir_expand/src/eager.rs b/crates/hir_expand/src/eager.rs index ef126e4ad..a5ac32d3c 100644 --- a/crates/hir_expand/src/eager.rs +++ b/crates/hir_expand/src/eager.rs | |||
@@ -31,6 +31,7 @@ use parser::FragmentKind; | |||
31 | use std::sync::Arc; | 31 | use std::sync::Arc; |
32 | use syntax::{algo::SyntaxRewriter, SyntaxNode}; | 32 | use syntax::{algo::SyntaxRewriter, SyntaxNode}; |
33 | 33 | ||
34 | #[derive(Debug)] | ||
34 | pub struct ErrorEmitted { | 35 | pub struct ErrorEmitted { |
35 | _private: (), | 36 | _private: (), |
36 | } | 37 | } |
diff --git a/crates/hir_expand/src/name.rs b/crates/hir_expand/src/name.rs index a0f8766b0..bcfd3e524 100644 --- a/crates/hir_expand/src/name.rs +++ b/crates/hir_expand/src/name.rs | |||
@@ -221,6 +221,7 @@ pub mod known { | |||
221 | option_env, | 221 | option_env, |
222 | llvm_asm, | 222 | llvm_asm, |
223 | asm, | 223 | asm, |
224 | global_asm, | ||
224 | // Builtin derives | 225 | // Builtin derives |
225 | Copy, | 226 | Copy, |
226 | Clone, | 227 | Clone, |
diff --git a/crates/hir_ty/src/autoderef.rs b/crates/hir_ty/src/autoderef.rs index 71bc436e6..2c07494a9 100644 --- a/crates/hir_ty/src/autoderef.rs +++ b/crates/hir_ty/src/autoderef.rs | |||
@@ -36,6 +36,7 @@ pub(crate) fn deref( | |||
36 | krate: CrateId, | 36 | krate: CrateId, |
37 | ty: InEnvironment<&Canonical<Ty>>, | 37 | ty: InEnvironment<&Canonical<Ty>>, |
38 | ) -> Option<Canonical<Ty>> { | 38 | ) -> Option<Canonical<Ty>> { |
39 | let _p = profile::span("deref"); | ||
39 | if let Some(derefed) = builtin_deref(&ty.goal.value) { | 40 | if let Some(derefed) = builtin_deref(&ty.goal.value) { |
40 | Some(Canonical { value: derefed, binders: ty.goal.binders.clone() }) | 41 | Some(Canonical { value: derefed, binders: ty.goal.binders.clone() }) |
41 | } else { | 42 | } else { |
@@ -56,6 +57,7 @@ fn deref_by_trait( | |||
56 | krate: CrateId, | 57 | krate: CrateId, |
57 | ty: InEnvironment<&Canonical<Ty>>, | 58 | ty: InEnvironment<&Canonical<Ty>>, |
58 | ) -> Option<Canonical<Ty>> { | 59 | ) -> Option<Canonical<Ty>> { |
60 | let _p = profile::span("deref_by_trait"); | ||
59 | let deref_trait = match db.lang_item(krate, "deref".into())? { | 61 | let deref_trait = match db.lang_item(krate, "deref".into())? { |
60 | LangItemTarget::TraitId(it) => it, | 62 | LangItemTarget::TraitId(it) => it, |
61 | _ => return None, | 63 | _ => return None, |
diff --git a/crates/hir_ty/src/db.rs b/crates/hir_ty/src/db.rs index 1690926ad..cf67d4266 100644 --- a/crates/hir_ty/src/db.rs +++ b/crates/hir_ty/src/db.rs | |||
@@ -128,13 +128,21 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> { | |||
128 | id: chalk_db::AssociatedTyValueId, | 128 | id: chalk_db::AssociatedTyValueId, |
129 | ) -> Arc<chalk_db::AssociatedTyValue>; | 129 | ) -> Arc<chalk_db::AssociatedTyValue>; |
130 | 130 | ||
131 | #[salsa::invoke(crate::traits::trait_solve_query)] | 131 | #[salsa::invoke(trait_solve_wait)] |
132 | #[salsa::transparent] | ||
132 | fn trait_solve( | 133 | fn trait_solve( |
133 | &self, | 134 | &self, |
134 | krate: CrateId, | 135 | krate: CrateId, |
135 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, | 136 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, |
136 | ) -> Option<crate::Solution>; | 137 | ) -> Option<crate::Solution>; |
137 | 138 | ||
139 | #[salsa::invoke(crate::traits::trait_solve_query)] | ||
140 | fn trait_solve_query( | ||
141 | &self, | ||
142 | krate: CrateId, | ||
143 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, | ||
144 | ) -> Option<crate::Solution>; | ||
145 | |||
138 | #[salsa::invoke(chalk_db::program_clauses_for_chalk_env_query)] | 146 | #[salsa::invoke(chalk_db::program_clauses_for_chalk_env_query)] |
139 | fn program_clauses_for_chalk_env( | 147 | fn program_clauses_for_chalk_env( |
140 | &self, | 148 | &self, |
@@ -156,6 +164,15 @@ fn infer_wait(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> | |||
156 | db.infer_query(def) | 164 | db.infer_query(def) |
157 | } | 165 | } |
158 | 166 | ||
167 | fn trait_solve_wait( | ||
168 | db: &dyn HirDatabase, | ||
169 | krate: CrateId, | ||
170 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, | ||
171 | ) -> Option<crate::Solution> { | ||
172 | let _p = profile::span("trait_solve::wait"); | ||
173 | db.trait_solve_query(krate, goal) | ||
174 | } | ||
175 | |||
159 | #[test] | 176 | #[test] |
160 | fn hir_database_is_object_safe() { | 177 | fn hir_database_is_object_safe() { |
161 | fn _assert_object_safe(_: &dyn HirDatabase) {} | 178 | fn _assert_object_safe(_: &dyn HirDatabase) {} |
diff --git a/crates/hir_ty/src/diagnostics/decl_check.rs b/crates/hir_ty/src/diagnostics/decl_check.rs index 1c9f9ede7..075dc4131 100644 --- a/crates/hir_ty/src/diagnostics/decl_check.rs +++ b/crates/hir_ty/src/diagnostics/decl_check.rs | |||
@@ -35,6 +35,8 @@ use crate::{ | |||
35 | }; | 35 | }; |
36 | 36 | ||
37 | mod allow { | 37 | mod allow { |
38 | pub(super) const BAD_STYLE: &str = "bad_style"; | ||
39 | pub(super) const NONSTANDARD_STYLE: &str = "nonstandard_style"; | ||
38 | pub(super) const NON_SNAKE_CASE: &str = "non_snake_case"; | 40 | pub(super) const NON_SNAKE_CASE: &str = "non_snake_case"; |
39 | pub(super) const NON_UPPER_CASE_GLOBAL: &str = "non_upper_case_globals"; | 41 | pub(super) const NON_UPPER_CASE_GLOBAL: &str = "non_upper_case_globals"; |
40 | pub(super) const NON_CAMEL_CASE_TYPES: &str = "non_camel_case_types"; | 42 | pub(super) const NON_CAMEL_CASE_TYPES: &str = "non_camel_case_types"; |
@@ -83,10 +85,39 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
83 | } | 85 | } |
84 | 86 | ||
85 | /// Checks whether not following the convention is allowed for this item. | 87 | /// Checks whether not following the convention is allowed for this item. |
86 | /// | 88 | fn allowed(&self, id: AttrDefId, allow_name: &str, recursing: bool) -> bool { |
87 | /// Currently this method doesn't check parent attributes. | 89 | let is_allowed = |def_id| { |
88 | fn allowed(&self, id: AttrDefId, allow_name: &str) -> bool { | 90 | let attrs = self.db.attrs(def_id); |
89 | self.db.attrs(id).by_key("allow").tt_values().any(|tt| tt.to_string().contains(allow_name)) | 91 | // don't bug the user about directly no_mangle annotated stuff, they can't do anything about it |
92 | (!recursing && attrs.by_key("no_mangle").exists()) | ||
93 | || attrs.by_key("allow").tt_values().any(|tt| { | ||
94 | let allows = tt.to_string(); | ||
95 | allows.contains(allow_name) | ||
96 | || allows.contains(allow::BAD_STYLE) | ||
97 | || allows.contains(allow::NONSTANDARD_STYLE) | ||
98 | }) | ||
99 | }; | ||
100 | |||
101 | is_allowed(id) | ||
102 | // go upwards one step or give up | ||
103 | || match id { | ||
104 | AttrDefId::ModuleId(m) => m.containing_module(self.db.upcast()).map(|v| v.into()), | ||
105 | AttrDefId::FunctionId(f) => Some(f.lookup(self.db.upcast()).container.into()), | ||
106 | AttrDefId::StaticId(sid) => Some(sid.lookup(self.db.upcast()).container.into()), | ||
107 | AttrDefId::ConstId(cid) => Some(cid.lookup(self.db.upcast()).container.into()), | ||
108 | AttrDefId::TraitId(tid) => Some(tid.lookup(self.db.upcast()).container.into()), | ||
109 | AttrDefId::ImplId(iid) => Some(iid.lookup(self.db.upcast()).container.into()), | ||
110 | // These warnings should not explore macro definitions at all | ||
111 | AttrDefId::MacroDefId(_) => None, | ||
112 | // Will never occur under an enum/struct/union/type alias | ||
113 | AttrDefId::AdtId(_) => None, | ||
114 | AttrDefId::FieldId(_) => None, | ||
115 | AttrDefId::EnumVariantId(_) => None, | ||
116 | AttrDefId::TypeAliasId(_) => None, | ||
117 | AttrDefId::GenericParamId(_) => None, | ||
118 | } | ||
119 | .map(|mid| self.allowed(mid, allow_name, true)) | ||
120 | .unwrap_or(false) | ||
90 | } | 121 | } |
91 | 122 | ||
92 | fn validate_func(&mut self, func: FunctionId) { | 123 | fn validate_func(&mut self, func: FunctionId) { |
@@ -109,7 +140,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
109 | } | 140 | } |
110 | 141 | ||
111 | // Check whether non-snake case identifiers are allowed for this function. | 142 | // Check whether non-snake case identifiers are allowed for this function. |
112 | if self.allowed(func.into(), allow::NON_SNAKE_CASE) { | 143 | if self.allowed(func.into(), allow::NON_SNAKE_CASE, false) { |
113 | return; | 144 | return; |
114 | } | 145 | } |
115 | 146 | ||
@@ -328,8 +359,9 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
328 | fn validate_struct(&mut self, struct_id: StructId) { | 359 | fn validate_struct(&mut self, struct_id: StructId) { |
329 | let data = self.db.struct_data(struct_id); | 360 | let data = self.db.struct_data(struct_id); |
330 | 361 | ||
331 | let non_camel_case_allowed = self.allowed(struct_id.into(), allow::NON_CAMEL_CASE_TYPES); | 362 | let non_camel_case_allowed = |
332 | let non_snake_case_allowed = self.allowed(struct_id.into(), allow::NON_SNAKE_CASE); | 363 | self.allowed(struct_id.into(), allow::NON_CAMEL_CASE_TYPES, false); |
364 | let non_snake_case_allowed = self.allowed(struct_id.into(), allow::NON_SNAKE_CASE, false); | ||
333 | 365 | ||
334 | // Check the structure name. | 366 | // Check the structure name. |
335 | let struct_name = data.name.to_string(); | 367 | let struct_name = data.name.to_string(); |
@@ -461,7 +493,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
461 | let data = self.db.enum_data(enum_id); | 493 | let data = self.db.enum_data(enum_id); |
462 | 494 | ||
463 | // Check whether non-camel case names are allowed for this enum. | 495 | // Check whether non-camel case names are allowed for this enum. |
464 | if self.allowed(enum_id.into(), allow::NON_CAMEL_CASE_TYPES) { | 496 | if self.allowed(enum_id.into(), allow::NON_CAMEL_CASE_TYPES, false) { |
465 | return; | 497 | return; |
466 | } | 498 | } |
467 | 499 | ||
@@ -584,7 +616,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
584 | fn validate_const(&mut self, const_id: ConstId) { | 616 | fn validate_const(&mut self, const_id: ConstId) { |
585 | let data = self.db.const_data(const_id); | 617 | let data = self.db.const_data(const_id); |
586 | 618 | ||
587 | if self.allowed(const_id.into(), allow::NON_UPPER_CASE_GLOBAL) { | 619 | if self.allowed(const_id.into(), allow::NON_UPPER_CASE_GLOBAL, false) { |
588 | return; | 620 | return; |
589 | } | 621 | } |
590 | 622 | ||
@@ -632,7 +664,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
632 | return; | 664 | return; |
633 | } | 665 | } |
634 | 666 | ||
635 | if self.allowed(static_id.into(), allow::NON_UPPER_CASE_GLOBAL) { | 667 | if self.allowed(static_id.into(), allow::NON_UPPER_CASE_GLOBAL, false) { |
636 | return; | 668 | return; |
637 | } | 669 | } |
638 | 670 | ||
@@ -867,23 +899,116 @@ fn main() { | |||
867 | fn allow_attributes() { | 899 | fn allow_attributes() { |
868 | check_diagnostics( | 900 | check_diagnostics( |
869 | r#" | 901 | r#" |
870 | #[allow(non_snake_case)] | 902 | #[allow(non_snake_case)] |
871 | fn NonSnakeCaseName(SOME_VAR: u8) -> u8{ | 903 | fn NonSnakeCaseName(SOME_VAR: u8) -> u8{ |
872 | let OtherVar = SOME_VAR + 1; | 904 | // cov_flags generated output from elsewhere in this file |
873 | OtherVar | 905 | extern "C" { |
906 | #[no_mangle] | ||
907 | static lower_case: u8; | ||
874 | } | 908 | } |
875 | 909 | ||
876 | #[allow(non_snake_case, non_camel_case_types)] | 910 | let OtherVar = SOME_VAR + 1; |
877 | pub struct some_type { | 911 | OtherVar |
878 | SOME_FIELD: u8, | 912 | } |
879 | SomeField: u16, | 913 | |
914 | #[allow(nonstandard_style)] | ||
915 | mod CheckNonstandardStyle { | ||
916 | fn HiImABadFnName() {} | ||
917 | } | ||
918 | |||
919 | #[allow(bad_style)] | ||
920 | mod CheckBadStyle { | ||
921 | fn HiImABadFnName() {} | ||
922 | } | ||
923 | |||
924 | mod F { | ||
925 | #![allow(non_snake_case)] | ||
926 | fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {} | ||
927 | } | ||
928 | |||
929 | #[allow(non_snake_case, non_camel_case_types)] | ||
930 | pub struct some_type { | ||
931 | SOME_FIELD: u8, | ||
932 | SomeField: u16, | ||
933 | } | ||
934 | |||
935 | #[allow(non_upper_case_globals)] | ||
936 | pub const some_const: u8 = 10; | ||
937 | |||
938 | #[allow(non_upper_case_globals)] | ||
939 | pub static SomeStatic: u8 = 10; | ||
940 | "#, | ||
941 | ); | ||
880 | } | 942 | } |
881 | 943 | ||
882 | #[allow(non_upper_case_globals)] | 944 | #[test] |
883 | pub const some_const: u8 = 10; | 945 | fn allow_attributes_crate_attr() { |
946 | check_diagnostics( | ||
947 | r#" | ||
948 | #![allow(non_snake_case)] | ||
884 | 949 | ||
885 | #[allow(non_upper_case_globals)] | 950 | mod F { |
886 | pub static SomeStatic: u8 = 10; | 951 | fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {} |
952 | } | ||
953 | "#, | ||
954 | ); | ||
955 | } | ||
956 | |||
957 | #[test] | ||
958 | #[ignore] | ||
959 | fn bug_trait_inside_fn() { | ||
960 | // FIXME: | ||
961 | // This is broken, and in fact, should not even be looked at by this | ||
962 | // lint in the first place. There's weird stuff going on in the | ||
963 | // collection phase. | ||
964 | // It's currently being brought in by: | ||
965 | // * validate_func on `a` recursing into modules | ||
966 | // * then it finds the trait and then the function while iterating | ||
967 | // through modules | ||
968 | // * then validate_func is called on Dirty | ||
969 | // * ... which then proceeds to look at some unknown module taking no | ||
970 | // attrs from either the impl or the fn a, and then finally to the root | ||
971 | // module | ||
972 | // | ||
973 | // It should find the attribute on the trait, but it *doesn't even see | ||
974 | // the trait* as far as I can tell. | ||
975 | |||
976 | check_diagnostics( | ||
977 | r#" | ||
978 | trait T { fn a(); } | ||
979 | struct U {} | ||
980 | impl T for U { | ||
981 | fn a() { | ||
982 | // this comes out of bitflags, mostly | ||
983 | #[allow(non_snake_case)] | ||
984 | trait __BitFlags { | ||
985 | const HiImAlsoBad: u8 = 2; | ||
986 | #[inline] | ||
987 | fn Dirty(&self) -> bool { | ||
988 | false | ||
989 | } | ||
990 | } | ||
991 | |||
992 | } | ||
993 | } | ||
994 | "#, | ||
995 | ); | ||
996 | } | ||
997 | |||
998 | #[test] | ||
999 | #[ignore] | ||
1000 | fn bug_traits_arent_checked() { | ||
1001 | // FIXME: Traits and functions in traits aren't currently checked by | ||
1002 | // r-a, even though rustc will complain about them. | ||
1003 | check_diagnostics( | ||
1004 | r#" | ||
1005 | trait BAD_TRAIT { | ||
1006 | // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait` | ||
1007 | fn BAD_FUNCTION(); | ||
1008 | // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function` | ||
1009 | fn BadFunction(); | ||
1010 | // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function` | ||
1011 | } | ||
887 | "#, | 1012 | "#, |
888 | ); | 1013 | ); |
889 | } | 1014 | } |
diff --git a/crates/hir_ty/src/display.rs b/crates/hir_ty/src/display.rs index e7c9dabc2..4fb7d9cf2 100644 --- a/crates/hir_ty/src/display.rs +++ b/crates/hir_ty/src/display.rs | |||
@@ -9,6 +9,7 @@ use std::{ | |||
9 | 9 | ||
10 | use chalk_ir::BoundVar; | 10 | use chalk_ir::BoundVar; |
11 | use hir_def::{ | 11 | use hir_def::{ |
12 | body, | ||
12 | db::DefDatabase, | 13 | db::DefDatabase, |
13 | find_path, | 14 | find_path, |
14 | generics::TypeParamProvenance, | 15 | generics::TypeParamProvenance, |
@@ -18,7 +19,7 @@ use hir_def::{ | |||
18 | visibility::Visibility, | 19 | visibility::Visibility, |
19 | AssocContainerId, Lookup, ModuleId, TraitId, | 20 | AssocContainerId, Lookup, ModuleId, TraitId, |
20 | }; | 21 | }; |
21 | use hir_expand::name::Name; | 22 | use hir_expand::{hygiene::Hygiene, name::Name}; |
22 | 23 | ||
23 | use crate::{ | 24 | use crate::{ |
24 | const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id, | 25 | const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id, |
@@ -997,6 +998,18 @@ impl HirDisplay for TypeRef { | |||
997 | write!(f, "dyn ")?; | 998 | write!(f, "dyn ")?; |
998 | f.write_joined(bounds, " + ")?; | 999 | f.write_joined(bounds, " + ")?; |
999 | } | 1000 | } |
1001 | TypeRef::Macro(macro_call) => { | ||
1002 | let macro_call = macro_call.to_node(f.db.upcast()); | ||
1003 | let ctx = body::LowerCtx::with_hygiene(&Hygiene::new_unhygienic()); | ||
1004 | match macro_call.path() { | ||
1005 | Some(path) => match Path::from_src(path, &ctx) { | ||
1006 | Some(path) => path.hir_fmt(f)?, | ||
1007 | None => write!(f, "{{macro}}")?, | ||
1008 | }, | ||
1009 | None => write!(f, "{{macro}}")?, | ||
1010 | } | ||
1011 | write!(f, "!(..)")?; | ||
1012 | } | ||
1000 | TypeRef::Error => write!(f, "{{error}}")?, | 1013 | TypeRef::Error => write!(f, "{{error}}")?, |
1001 | } | 1014 | } |
1002 | Ok(()) | 1015 | Ok(()) |
diff --git a/crates/hir_ty/src/lib.rs b/crates/hir_ty/src/lib.rs index 113234fa4..0505fa4ae 100644 --- a/crates/hir_ty/src/lib.rs +++ b/crates/hir_ty/src/lib.rs | |||
@@ -56,6 +56,7 @@ pub use mapping::{ | |||
56 | to_foreign_def_id, to_placeholder_idx, | 56 | to_foreign_def_id, to_placeholder_idx, |
57 | }; | 57 | }; |
58 | pub use traits::TraitEnvironment; | 58 | pub use traits::TraitEnvironment; |
59 | pub use utils::all_super_traits; | ||
59 | pub use walk::TypeWalk; | 60 | pub use walk::TypeWalk; |
60 | 61 | ||
61 | pub use chalk_ir::{ | 62 | pub use chalk_ir::{ |
diff --git a/crates/hir_ty/src/lower.rs b/crates/hir_ty/src/lower.rs index a035686bc..7fd46becd 100644 --- a/crates/hir_ty/src/lower.rs +++ b/crates/hir_ty/src/lower.rs | |||
@@ -5,12 +5,14 @@ | |||
5 | //! - Building the type for an item: This happens through the `type_for_def` query. | 5 | //! - Building the type for an item: This happens through the `type_for_def` query. |
6 | //! | 6 | //! |
7 | //! This usually involves resolving names, collecting generic arguments etc. | 7 | //! This usually involves resolving names, collecting generic arguments etc. |
8 | use std::cell::{Cell, RefCell}; | ||
8 | use std::{iter, sync::Arc}; | 9 | use std::{iter, sync::Arc}; |
9 | 10 | ||
10 | use base_db::CrateId; | 11 | use base_db::CrateId; |
11 | use chalk_ir::{cast::Cast, fold::Shift, interner::HasInterner, Mutability, Safety}; | 12 | use chalk_ir::{cast::Cast, fold::Shift, interner::HasInterner, Mutability, Safety}; |
12 | use hir_def::{ | 13 | use hir_def::{ |
13 | adt::StructKind, | 14 | adt::StructKind, |
15 | body::{Expander, LowerCtx}, | ||
14 | builtin_type::BuiltinType, | 16 | builtin_type::BuiltinType, |
15 | generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget}, | 17 | generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget}, |
16 | path::{GenericArg, Path, PathSegment, PathSegments}, | 18 | path::{GenericArg, Path, PathSegment, PathSegments}, |
@@ -20,10 +22,11 @@ use hir_def::{ | |||
20 | GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId, | 22 | GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId, |
21 | TypeAliasId, TypeParamId, UnionId, VariantId, | 23 | TypeAliasId, TypeParamId, UnionId, VariantId, |
22 | }; | 24 | }; |
23 | use hir_expand::name::Name; | 25 | use hir_expand::{name::Name, ExpandResult}; |
24 | use la_arena::ArenaMap; | 26 | use la_arena::ArenaMap; |
25 | use smallvec::SmallVec; | 27 | use smallvec::SmallVec; |
26 | use stdx::impl_from; | 28 | use stdx::impl_from; |
29 | use syntax::ast; | ||
27 | 30 | ||
28 | use crate::{ | 31 | use crate::{ |
29 | db::HirDatabase, | 32 | db::HirDatabase, |
@@ -50,7 +53,7 @@ pub struct TyLoweringContext<'a> { | |||
50 | /// possible currently, so this should be fine for now. | 53 | /// possible currently, so this should be fine for now. |
51 | pub type_param_mode: TypeParamLoweringMode, | 54 | pub type_param_mode: TypeParamLoweringMode, |
52 | pub impl_trait_mode: ImplTraitLoweringMode, | 55 | pub impl_trait_mode: ImplTraitLoweringMode, |
53 | impl_trait_counter: std::cell::Cell<u16>, | 56 | impl_trait_counter: Cell<u16>, |
54 | /// When turning `impl Trait` into opaque types, we have to collect the | 57 | /// When turning `impl Trait` into opaque types, we have to collect the |
55 | /// bounds at the same time to get the IDs correct (without becoming too | 58 | /// bounds at the same time to get the IDs correct (without becoming too |
56 | /// complicated). I don't like using interior mutability (as for the | 59 | /// complicated). I don't like using interior mutability (as for the |
@@ -59,16 +62,17 @@ pub struct TyLoweringContext<'a> { | |||
59 | /// we're grouping the mutable data (the counter and this field) together | 62 | /// we're grouping the mutable data (the counter and this field) together |
60 | /// with the immutable context (the references to the DB and resolver). | 63 | /// with the immutable context (the references to the DB and resolver). |
61 | /// Splitting this up would be a possible fix. | 64 | /// Splitting this up would be a possible fix. |
62 | opaque_type_data: std::cell::RefCell<Vec<ReturnTypeImplTrait>>, | 65 | opaque_type_data: RefCell<Vec<ReturnTypeImplTrait>>, |
66 | expander: RefCell<Option<Expander>>, | ||
63 | } | 67 | } |
64 | 68 | ||
65 | impl<'a> TyLoweringContext<'a> { | 69 | impl<'a> TyLoweringContext<'a> { |
66 | pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self { | 70 | pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self { |
67 | let impl_trait_counter = std::cell::Cell::new(0); | 71 | let impl_trait_counter = Cell::new(0); |
68 | let impl_trait_mode = ImplTraitLoweringMode::Disallowed; | 72 | let impl_trait_mode = ImplTraitLoweringMode::Disallowed; |
69 | let type_param_mode = TypeParamLoweringMode::Placeholder; | 73 | let type_param_mode = TypeParamLoweringMode::Placeholder; |
70 | let in_binders = DebruijnIndex::INNERMOST; | 74 | let in_binders = DebruijnIndex::INNERMOST; |
71 | let opaque_type_data = std::cell::RefCell::new(Vec::new()); | 75 | let opaque_type_data = RefCell::new(Vec::new()); |
72 | Self { | 76 | Self { |
73 | db, | 77 | db, |
74 | resolver, | 78 | resolver, |
@@ -77,6 +81,7 @@ impl<'a> TyLoweringContext<'a> { | |||
77 | impl_trait_counter, | 81 | impl_trait_counter, |
78 | type_param_mode, | 82 | type_param_mode, |
79 | opaque_type_data, | 83 | opaque_type_data, |
84 | expander: RefCell::new(None), | ||
80 | } | 85 | } |
81 | } | 86 | } |
82 | 87 | ||
@@ -86,15 +91,18 @@ impl<'a> TyLoweringContext<'a> { | |||
86 | f: impl FnOnce(&TyLoweringContext) -> T, | 91 | f: impl FnOnce(&TyLoweringContext) -> T, |
87 | ) -> T { | 92 | ) -> T { |
88 | let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new()); | 93 | let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new()); |
94 | let expander = self.expander.replace(None); | ||
89 | let new_ctx = Self { | 95 | let new_ctx = Self { |
90 | in_binders: debruijn, | 96 | in_binders: debruijn, |
91 | impl_trait_counter: std::cell::Cell::new(self.impl_trait_counter.get()), | 97 | impl_trait_counter: Cell::new(self.impl_trait_counter.get()), |
92 | opaque_type_data: std::cell::RefCell::new(opaque_ty_data_vec), | 98 | opaque_type_data: RefCell::new(opaque_ty_data_vec), |
99 | expander: RefCell::new(expander), | ||
93 | ..*self | 100 | ..*self |
94 | }; | 101 | }; |
95 | let result = f(&new_ctx); | 102 | let result = f(&new_ctx); |
96 | self.impl_trait_counter.set(new_ctx.impl_trait_counter.get()); | 103 | self.impl_trait_counter.set(new_ctx.impl_trait_counter.get()); |
97 | self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner()); | 104 | self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner()); |
105 | self.expander.replace(new_ctx.expander.into_inner()); | ||
98 | result | 106 | result |
99 | } | 107 | } |
100 | 108 | ||
@@ -287,6 +295,53 @@ impl<'a> TyLoweringContext<'a> { | |||
287 | } | 295 | } |
288 | } | 296 | } |
289 | } | 297 | } |
298 | TypeRef::Macro(macro_call) => { | ||
299 | let (expander, recursion_start) = { | ||
300 | let mut expander = self.expander.borrow_mut(); | ||
301 | if expander.is_some() { | ||
302 | (Some(expander), false) | ||
303 | } else { | ||
304 | if let Some(module_id) = self.resolver.module() { | ||
305 | *expander = Some(Expander::new( | ||
306 | self.db.upcast(), | ||
307 | macro_call.file_id, | ||
308 | module_id, | ||
309 | )); | ||
310 | (Some(expander), true) | ||
311 | } else { | ||
312 | (None, false) | ||
313 | } | ||
314 | } | ||
315 | }; | ||
316 | let ty = if let Some(mut expander) = expander { | ||
317 | let expander_mut = expander.as_mut().unwrap(); | ||
318 | let macro_call = macro_call.to_node(self.db.upcast()); | ||
319 | match expander_mut.enter_expand::<ast::Type>(self.db.upcast(), macro_call) { | ||
320 | Ok(ExpandResult { value: Some((mark, expanded)), .. }) => { | ||
321 | let ctx = | ||
322 | LowerCtx::new(self.db.upcast(), expander_mut.current_file_id()); | ||
323 | let type_ref = TypeRef::from_ast(&ctx, expanded); | ||
324 | |||
325 | drop(expander); | ||
326 | let ty = self.lower_ty(&type_ref); | ||
327 | |||
328 | self.expander | ||
329 | .borrow_mut() | ||
330 | .as_mut() | ||
331 | .unwrap() | ||
332 | .exit(self.db.upcast(), mark); | ||
333 | Some(ty) | ||
334 | } | ||
335 | _ => None, | ||
336 | } | ||
337 | } else { | ||
338 | None | ||
339 | }; | ||
340 | if recursion_start { | ||
341 | *self.expander.borrow_mut() = None; | ||
342 | } | ||
343 | ty.unwrap_or_else(|| TyKind::Error.intern(&Interner)) | ||
344 | } | ||
290 | TypeRef::Error => TyKind::Error.intern(&Interner), | 345 | TypeRef::Error => TyKind::Error.intern(&Interner), |
291 | }; | 346 | }; |
292 | (ty, res) | 347 | (ty, res) |
diff --git a/crates/hir_ty/src/method_resolution.rs b/crates/hir_ty/src/method_resolution.rs index 3693e3284..48bbcfd9f 100644 --- a/crates/hir_ty/src/method_resolution.rs +++ b/crates/hir_ty/src/method_resolution.rs | |||
@@ -246,29 +246,39 @@ pub struct InherentImpls { | |||
246 | 246 | ||
247 | impl InherentImpls { | 247 | impl InherentImpls { |
248 | pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> { | 248 | pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> { |
249 | let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default(); | 249 | let mut impls = Self { map: FxHashMap::default() }; |
250 | 250 | ||
251 | let crate_def_map = db.crate_def_map(krate); | 251 | let crate_def_map = db.crate_def_map(krate); |
252 | for (_module_id, module_data) in crate_def_map.modules() { | 252 | collect_def_map(db, &crate_def_map, &mut impls); |
253 | for impl_id in module_data.scope.impls() { | 253 | |
254 | let data = db.impl_data(impl_id); | 254 | return Arc::new(impls); |
255 | if data.target_trait.is_some() { | 255 | |
256 | continue; | 256 | fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut InherentImpls) { |
257 | for (_module_id, module_data) in def_map.modules() { | ||
258 | for impl_id in module_data.scope.impls() { | ||
259 | let data = db.impl_data(impl_id); | ||
260 | if data.target_trait.is_some() { | ||
261 | continue; | ||
262 | } | ||
263 | |||
264 | let self_ty = db.impl_self_ty(impl_id); | ||
265 | let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders()); | ||
266 | if let Some(fp) = fp { | ||
267 | impls.map.entry(fp).or_default().push(impl_id); | ||
268 | } | ||
269 | // `fp` should only be `None` in error cases (either erroneous code or incomplete name resolution) | ||
257 | } | 270 | } |
258 | 271 | ||
259 | let self_ty = db.impl_self_ty(impl_id); | 272 | // To better support custom derives, collect impls in all unnamed const items. |
260 | let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders()); | 273 | // const _: () = { ... }; |
261 | if let Some(fp) = fp { | 274 | for konst in module_data.scope.unnamed_consts() { |
262 | map.entry(fp).or_default().push(impl_id); | 275 | let body = db.body(konst.into()); |
276 | for (_, block_def_map) in body.blocks(db.upcast()) { | ||
277 | collect_def_map(db, &block_def_map, impls); | ||
278 | } | ||
263 | } | 279 | } |
264 | // `fp` should only be `None` in error cases (either erroneous code or incomplete name resolution) | ||
265 | } | 280 | } |
266 | } | 281 | } |
267 | |||
268 | // NOTE: We're not collecting inherent impls from unnamed consts here, we intentionally only | ||
269 | // support trait impls there. | ||
270 | |||
271 | Arc::new(Self { map }) | ||
272 | } | 282 | } |
273 | 283 | ||
274 | pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] { | 284 | pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] { |
diff --git a/crates/hir_ty/src/tests/macros.rs b/crates/hir_ty/src/tests/macros.rs index b8e373ed8..6588aa46c 100644 --- a/crates/hir_ty/src/tests/macros.rs +++ b/crates/hir_ty/src/tests/macros.rs | |||
@@ -1074,3 +1074,202 @@ fn macro_in_arm() { | |||
1074 | "#]], | 1074 | "#]], |
1075 | ); | 1075 | ); |
1076 | } | 1076 | } |
1077 | |||
1078 | #[test] | ||
1079 | fn macro_in_type_alias_position() { | ||
1080 | check_infer( | ||
1081 | r#" | ||
1082 | macro_rules! U32 { | ||
1083 | () => { u32 }; | ||
1084 | } | ||
1085 | |||
1086 | trait Foo { | ||
1087 | type Ty; | ||
1088 | } | ||
1089 | |||
1090 | impl<T> Foo for T { | ||
1091 | type Ty = U32!(); | ||
1092 | } | ||
1093 | |||
1094 | type TayTo = U32!(); | ||
1095 | |||
1096 | fn testy() { | ||
1097 | let a: <() as Foo>::Ty; | ||
1098 | let b: TayTo; | ||
1099 | } | ||
1100 | "#, | ||
1101 | expect![[r#" | ||
1102 | 147..196 '{ ...yTo; }': () | ||
1103 | 157..158 'a': u32 | ||
1104 | 185..186 'b': u32 | ||
1105 | "#]], | ||
1106 | ); | ||
1107 | } | ||
1108 | |||
1109 | #[test] | ||
1110 | fn nested_macro_in_type_alias_position() { | ||
1111 | check_infer( | ||
1112 | r#" | ||
1113 | macro_rules! U32Inner2 { | ||
1114 | () => { u32 }; | ||
1115 | } | ||
1116 | |||
1117 | macro_rules! U32Inner1 { | ||
1118 | () => { U32Inner2!() }; | ||
1119 | } | ||
1120 | |||
1121 | macro_rules! U32 { | ||
1122 | () => { U32Inner1!() }; | ||
1123 | } | ||
1124 | |||
1125 | trait Foo { | ||
1126 | type Ty; | ||
1127 | } | ||
1128 | |||
1129 | impl<T> Foo for T { | ||
1130 | type Ty = U32!(); | ||
1131 | } | ||
1132 | |||
1133 | type TayTo = U32!(); | ||
1134 | |||
1135 | fn testy() { | ||
1136 | let a: <() as Foo>::Ty; | ||
1137 | let b: TayTo; | ||
1138 | } | ||
1139 | "#, | ||
1140 | expect![[r#" | ||
1141 | 259..308 '{ ...yTo; }': () | ||
1142 | 269..270 'a': u32 | ||
1143 | 297..298 'b': u32 | ||
1144 | "#]], | ||
1145 | ); | ||
1146 | } | ||
1147 | |||
1148 | #[test] | ||
1149 | fn macros_in_type_alias_position_generics() { | ||
1150 | check_infer( | ||
1151 | r#" | ||
1152 | struct Foo<A, B>(A, B); | ||
1153 | |||
1154 | macro_rules! U32 { | ||
1155 | () => { u32 }; | ||
1156 | } | ||
1157 | |||
1158 | macro_rules! Bar { | ||
1159 | () => { Foo<U32!(), U32!()> }; | ||
1160 | } | ||
1161 | |||
1162 | trait Moo { | ||
1163 | type Ty; | ||
1164 | } | ||
1165 | |||
1166 | impl<T> Moo for T { | ||
1167 | type Ty = Bar!(); | ||
1168 | } | ||
1169 | |||
1170 | type TayTo = Bar!(); | ||
1171 | |||
1172 | fn main() { | ||
1173 | let a: <() as Moo>::Ty; | ||
1174 | let b: TayTo; | ||
1175 | } | ||
1176 | "#, | ||
1177 | expect![[r#" | ||
1178 | 228..277 '{ ...yTo; }': () | ||
1179 | 238..239 'a': Foo<u32, u32> | ||
1180 | 266..267 'b': Foo<u32, u32> | ||
1181 | "#]], | ||
1182 | ); | ||
1183 | } | ||
1184 | |||
1185 | #[test] | ||
1186 | fn macros_in_type_position() { | ||
1187 | check_infer( | ||
1188 | r#" | ||
1189 | struct Foo<A, B>(A, B); | ||
1190 | |||
1191 | macro_rules! U32 { | ||
1192 | () => { u32 }; | ||
1193 | } | ||
1194 | |||
1195 | macro_rules! Bar { | ||
1196 | () => { Foo<U32!(), U32!()> }; | ||
1197 | } | ||
1198 | |||
1199 | fn main() { | ||
1200 | let a: Bar!(); | ||
1201 | } | ||
1202 | "#, | ||
1203 | expect![[r#" | ||
1204 | 133..155 '{ ...!(); }': () | ||
1205 | 143..144 'a': Foo<u32, u32> | ||
1206 | "#]], | ||
1207 | ); | ||
1208 | } | ||
1209 | |||
1210 | #[test] | ||
1211 | fn macros_in_type_generics() { | ||
1212 | check_infer( | ||
1213 | r#" | ||
1214 | struct Foo<A, B>(A, B); | ||
1215 | |||
1216 | macro_rules! U32 { | ||
1217 | () => { u32 }; | ||
1218 | } | ||
1219 | |||
1220 | macro_rules! Bar { | ||
1221 | () => { Foo<U32!(), U32!()> }; | ||
1222 | } | ||
1223 | |||
1224 | trait Moo { | ||
1225 | type Ty; | ||
1226 | } | ||
1227 | |||
1228 | impl<T> Moo for T { | ||
1229 | type Ty = Foo<Bar!(), Bar!()>; | ||
1230 | } | ||
1231 | |||
1232 | type TayTo = Foo<Bar!(), U32!()>; | ||
1233 | |||
1234 | fn main() { | ||
1235 | let a: <() as Moo>::Ty; | ||
1236 | let b: TayTo; | ||
1237 | } | ||
1238 | "#, | ||
1239 | expect![[r#" | ||
1240 | 254..303 '{ ...yTo; }': () | ||
1241 | 264..265 'a': Foo<Foo<u32, u32>, Foo<u32, u32>> | ||
1242 | 292..293 'b': Foo<Foo<u32, u32>, u32> | ||
1243 | "#]], | ||
1244 | ); | ||
1245 | } | ||
1246 | |||
1247 | #[test] | ||
1248 | fn infinitely_recursive_macro_type() { | ||
1249 | check_infer( | ||
1250 | r#" | ||
1251 | struct Bar<T, X>(T, X); | ||
1252 | |||
1253 | macro_rules! Foo { | ||
1254 | () => { Foo!() } | ||
1255 | } | ||
1256 | |||
1257 | macro_rules! U32 { | ||
1258 | () => { u32 } | ||
1259 | } | ||
1260 | |||
1261 | type A = Foo!(); | ||
1262 | type B = Bar<Foo!(), U32!()>; | ||
1263 | |||
1264 | fn main() { | ||
1265 | let a: A; | ||
1266 | let b: B; | ||
1267 | } | ||
1268 | "#, | ||
1269 | expect![[r#" | ||
1270 | 166..197 '{ ...: B; }': () | ||
1271 | 176..177 'a': {unknown} | ||
1272 | 190..191 'b': Bar<{unknown}, u32> | ||
1273 | "#]], | ||
1274 | ); | ||
1275 | } | ||
diff --git a/crates/hir_ty/src/tests/method_resolution.rs b/crates/hir_ty/src/tests/method_resolution.rs index 4b2c82b41..a4c132bc5 100644 --- a/crates/hir_ty/src/tests/method_resolution.rs +++ b/crates/hir_ty/src/tests/method_resolution.rs | |||
@@ -1294,7 +1294,7 @@ mod b { | |||
1294 | } | 1294 | } |
1295 | 1295 | ||
1296 | #[test] | 1296 | #[test] |
1297 | fn impl_in_unnamed_const() { | 1297 | fn trait_impl_in_unnamed_const() { |
1298 | check_types( | 1298 | check_types( |
1299 | r#" | 1299 | r#" |
1300 | struct S; | 1300 | struct S; |
@@ -1314,3 +1314,38 @@ fn f() { | |||
1314 | "#, | 1314 | "#, |
1315 | ); | 1315 | ); |
1316 | } | 1316 | } |
1317 | |||
1318 | #[test] | ||
1319 | fn inherent_impl_in_unnamed_const() { | ||
1320 | check_types( | ||
1321 | r#" | ||
1322 | struct S; | ||
1323 | |||
1324 | const _: () = { | ||
1325 | impl S { | ||
1326 | fn method(&self) -> u16 { 0 } | ||
1327 | |||
1328 | pub(super) fn super_method(&self) -> u16 { 0 } | ||
1329 | |||
1330 | pub(crate) fn crate_method(&self) -> u16 { 0 } | ||
1331 | |||
1332 | pub fn pub_method(&self) -> u16 { 0 } | ||
1333 | } | ||
1334 | }; | ||
1335 | |||
1336 | fn f() { | ||
1337 | S.method(); | ||
1338 | //^^^^^^^^^^ u16 | ||
1339 | |||
1340 | S.super_method(); | ||
1341 | //^^^^^^^^^^^^^^^^ u16 | ||
1342 | |||
1343 | S.crate_method(); | ||
1344 | //^^^^^^^^^^^^^^^^ u16 | ||
1345 | |||
1346 | S.pub_method(); | ||
1347 | //^^^^^^^^^^^^^^ u16 | ||
1348 | } | ||
1349 | "#, | ||
1350 | ); | ||
1351 | } | ||
diff --git a/crates/hir_ty/src/tests/simple.rs b/crates/hir_ty/src/tests/simple.rs index 84c5c05fd..5948d0bc2 100644 --- a/crates/hir_ty/src/tests/simple.rs +++ b/crates/hir_ty/src/tests/simple.rs | |||
@@ -1765,6 +1765,24 @@ fn main() { | |||
1765 | } | 1765 | } |
1766 | 1766 | ||
1767 | #[test] | 1767 | #[test] |
1768 | fn shadowing_primitive_with_inner_items() { | ||
1769 | check_types( | ||
1770 | r#" | ||
1771 | struct i32; | ||
1772 | struct Foo; | ||
1773 | |||
1774 | impl i32 { fn foo(&self) -> Foo { Foo } } | ||
1775 | |||
1776 | fn main() { | ||
1777 | fn inner() {} | ||
1778 | let x: i32 = i32; | ||
1779 | x.foo(); | ||
1780 | //^ Foo | ||
1781 | }"#, | ||
1782 | ); | ||
1783 | } | ||
1784 | |||
1785 | #[test] | ||
1768 | fn not_shadowing_primitive_by_module() { | 1786 | fn not_shadowing_primitive_by_module() { |
1769 | check_types( | 1787 | check_types( |
1770 | r#" | 1788 | r#" |
diff --git a/crates/hir_ty/src/utils.rs b/crates/hir_ty/src/utils.rs index 5f6cb052a..2f04ee57a 100644 --- a/crates/hir_ty/src/utils.rs +++ b/crates/hir_ty/src/utils.rs | |||
@@ -78,7 +78,7 @@ fn direct_super_trait_refs(db: &dyn HirDatabase, trait_ref: &TraitRef) -> Vec<Tr | |||
78 | 78 | ||
79 | /// Returns an iterator over the whole super trait hierarchy (including the | 79 | /// Returns an iterator over the whole super trait hierarchy (including the |
80 | /// trait itself). | 80 | /// trait itself). |
81 | pub(super) fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> Vec<TraitId> { | 81 | pub fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> Vec<TraitId> { |
82 | // we need to take care a bit here to avoid infinite loops in case of cycles | 82 | // we need to take care a bit here to avoid infinite loops in case of cycles |
83 | // (i.e. if we have `trait A: B; trait B: A;`) | 83 | // (i.e. if we have `trait A: B; trait B: A;`) |
84 | let mut result = vec![trait_]; | 84 | let mut result = vec![trait_]; |
diff --git a/crates/ide/src/diagnostics.rs b/crates/ide/src/diagnostics.rs index 4f0b4a62e..1c911a8b2 100644 --- a/crates/ide/src/diagnostics.rs +++ b/crates/ide/src/diagnostics.rs | |||
@@ -84,6 +84,7 @@ pub struct DiagnosticsConfig { | |||
84 | pub(crate) fn diagnostics( | 84 | pub(crate) fn diagnostics( |
85 | db: &RootDatabase, | 85 | db: &RootDatabase, |
86 | config: &DiagnosticsConfig, | 86 | config: &DiagnosticsConfig, |
87 | resolve: bool, | ||
87 | file_id: FileId, | 88 | file_id: FileId, |
88 | ) -> Vec<Diagnostic> { | 89 | ) -> Vec<Diagnostic> { |
89 | let _p = profile::span("diagnostics"); | 90 | let _p = profile::span("diagnostics"); |
@@ -107,25 +108,25 @@ pub(crate) fn diagnostics( | |||
107 | let res = RefCell::new(res); | 108 | let res = RefCell::new(res); |
108 | let sink_builder = DiagnosticSinkBuilder::new() | 109 | let sink_builder = DiagnosticSinkBuilder::new() |
109 | .on::<hir::diagnostics::UnresolvedModule, _>(|d| { | 110 | .on::<hir::diagnostics::UnresolvedModule, _>(|d| { |
110 | res.borrow_mut().push(diagnostic_with_fix(d, &sema)); | 111 | res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve)); |
111 | }) | 112 | }) |
112 | .on::<hir::diagnostics::MissingFields, _>(|d| { | 113 | .on::<hir::diagnostics::MissingFields, _>(|d| { |
113 | res.borrow_mut().push(diagnostic_with_fix(d, &sema)); | 114 | res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve)); |
114 | }) | 115 | }) |
115 | .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| { | 116 | .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| { |
116 | res.borrow_mut().push(diagnostic_with_fix(d, &sema)); | 117 | res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve)); |
117 | }) | 118 | }) |
118 | .on::<hir::diagnostics::NoSuchField, _>(|d| { | 119 | .on::<hir::diagnostics::NoSuchField, _>(|d| { |
119 | res.borrow_mut().push(diagnostic_with_fix(d, &sema)); | 120 | res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve)); |
120 | }) | 121 | }) |
121 | .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| { | 122 | .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| { |
122 | res.borrow_mut().push(diagnostic_with_fix(d, &sema)); | 123 | res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve)); |
123 | }) | 124 | }) |
124 | .on::<hir::diagnostics::IncorrectCase, _>(|d| { | 125 | .on::<hir::diagnostics::IncorrectCase, _>(|d| { |
125 | res.borrow_mut().push(warning_with_fix(d, &sema)); | 126 | res.borrow_mut().push(warning_with_fix(d, &sema, resolve)); |
126 | }) | 127 | }) |
127 | .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| { | 128 | .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| { |
128 | res.borrow_mut().push(warning_with_fix(d, &sema)); | 129 | res.borrow_mut().push(warning_with_fix(d, &sema, resolve)); |
129 | }) | 130 | }) |
130 | .on::<hir::diagnostics::InactiveCode, _>(|d| { | 131 | .on::<hir::diagnostics::InactiveCode, _>(|d| { |
131 | // If there's inactive code somewhere in a macro, don't propagate to the call-site. | 132 | // If there's inactive code somewhere in a macro, don't propagate to the call-site. |
@@ -152,7 +153,7 @@ pub(crate) fn diagnostics( | |||
152 | // Override severity and mark as unused. | 153 | // Override severity and mark as unused. |
153 | res.borrow_mut().push( | 154 | res.borrow_mut().push( |
154 | Diagnostic::hint(range, d.message()) | 155 | Diagnostic::hint(range, d.message()) |
155 | .with_fix(d.fix(&sema)) | 156 | .with_fix(d.fix(&sema, resolve)) |
156 | .with_code(Some(d.code())), | 157 | .with_code(Some(d.code())), |
157 | ); | 158 | ); |
158 | }) | 159 | }) |
@@ -208,15 +209,23 @@ pub(crate) fn diagnostics( | |||
208 | res.into_inner() | 209 | res.into_inner() |
209 | } | 210 | } |
210 | 211 | ||
211 | fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { | 212 | fn diagnostic_with_fix<D: DiagnosticWithFix>( |
213 | d: &D, | ||
214 | sema: &Semantics<RootDatabase>, | ||
215 | resolve: bool, | ||
216 | ) -> Diagnostic { | ||
212 | Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message()) | 217 | Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message()) |
213 | .with_fix(d.fix(&sema)) | 218 | .with_fix(d.fix(&sema, resolve)) |
214 | .with_code(Some(d.code())) | 219 | .with_code(Some(d.code())) |
215 | } | 220 | } |
216 | 221 | ||
217 | fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { | 222 | fn warning_with_fix<D: DiagnosticWithFix>( |
223 | d: &D, | ||
224 | sema: &Semantics<RootDatabase>, | ||
225 | resolve: bool, | ||
226 | ) -> Diagnostic { | ||
218 | Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message()) | 227 | Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message()) |
219 | .with_fix(d.fix(&sema)) | 228 | .with_fix(d.fix(&sema, resolve)) |
220 | .with_code(Some(d.code())) | 229 | .with_code(Some(d.code())) |
221 | } | 230 | } |
222 | 231 | ||
@@ -271,13 +280,19 @@ fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement( | |||
271 | } | 280 | } |
272 | 281 | ||
273 | fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist { | 282 | fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist { |
283 | let mut res = unresolved_fix(id, label, target); | ||
284 | res.source_change = Some(source_change); | ||
285 | res | ||
286 | } | ||
287 | |||
288 | fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist { | ||
274 | assert!(!id.contains(' ')); | 289 | assert!(!id.contains(' ')); |
275 | Assist { | 290 | Assist { |
276 | id: AssistId(id, AssistKind::QuickFix), | 291 | id: AssistId(id, AssistKind::QuickFix), |
277 | label: Label::new(label), | 292 | label: Label::new(label), |
278 | group: None, | 293 | group: None, |
279 | target, | 294 | target, |
280 | source_change: Some(source_change), | 295 | source_change: None, |
281 | } | 296 | } |
282 | } | 297 | } |
283 | 298 | ||
@@ -299,7 +314,7 @@ mod tests { | |||
299 | 314 | ||
300 | let (analysis, file_position) = fixture::position(ra_fixture_before); | 315 | let (analysis, file_position) = fixture::position(ra_fixture_before); |
301 | let diagnostic = analysis | 316 | let diagnostic = analysis |
302 | .diagnostics(&DiagnosticsConfig::default(), file_position.file_id) | 317 | .diagnostics(&DiagnosticsConfig::default(), true, file_position.file_id) |
303 | .unwrap() | 318 | .unwrap() |
304 | .pop() | 319 | .pop() |
305 | .unwrap(); | 320 | .unwrap(); |
@@ -328,7 +343,7 @@ mod tests { | |||
328 | fn check_no_fix(ra_fixture: &str) { | 343 | fn check_no_fix(ra_fixture: &str) { |
329 | let (analysis, file_position) = fixture::position(ra_fixture); | 344 | let (analysis, file_position) = fixture::position(ra_fixture); |
330 | let diagnostic = analysis | 345 | let diagnostic = analysis |
331 | .diagnostics(&DiagnosticsConfig::default(), file_position.file_id) | 346 | .diagnostics(&DiagnosticsConfig::default(), true, file_position.file_id) |
332 | .unwrap() | 347 | .unwrap() |
333 | .pop() | 348 | .pop() |
334 | .unwrap(); | 349 | .unwrap(); |
@@ -342,7 +357,7 @@ mod tests { | |||
342 | let diagnostics = files | 357 | let diagnostics = files |
343 | .into_iter() | 358 | .into_iter() |
344 | .flat_map(|file_id| { | 359 | .flat_map(|file_id| { |
345 | analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap() | 360 | analysis.diagnostics(&DiagnosticsConfig::default(), true, file_id).unwrap() |
346 | }) | 361 | }) |
347 | .collect::<Vec<_>>(); | 362 | .collect::<Vec<_>>(); |
348 | assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics); | 363 | assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics); |
@@ -350,7 +365,8 @@ mod tests { | |||
350 | 365 | ||
351 | fn check_expect(ra_fixture: &str, expect: Expect) { | 366 | fn check_expect(ra_fixture: &str, expect: Expect) { |
352 | let (analysis, file_id) = fixture::file(ra_fixture); | 367 | let (analysis, file_id) = fixture::file(ra_fixture); |
353 | let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap(); | 368 | let diagnostics = |
369 | analysis.diagnostics(&DiagnosticsConfig::default(), true, file_id).unwrap(); | ||
354 | expect.assert_debug_eq(&diagnostics) | 370 | expect.assert_debug_eq(&diagnostics) |
355 | } | 371 | } |
356 | 372 | ||
@@ -709,7 +725,7 @@ fn test_fn() { | |||
709 | expect![[r#" | 725 | expect![[r#" |
710 | [ | 726 | [ |
711 | Diagnostic { | 727 | Diagnostic { |
712 | message: "unresolved macro call", | 728 | message: "unresolved macro `foo::bar!`", |
713 | range: 5..8, | 729 | range: 5..8, |
714 | severity: Error, | 730 | severity: Error, |
715 | fix: None, | 731 | fix: None, |
@@ -895,10 +911,11 @@ struct Foo { | |||
895 | 911 | ||
896 | let (analysis, file_id) = fixture::file(r#"mod foo;"#); | 912 | let (analysis, file_id) = fixture::file(r#"mod foo;"#); |
897 | 913 | ||
898 | let diagnostics = analysis.diagnostics(&config, file_id).unwrap(); | 914 | let diagnostics = analysis.diagnostics(&config, true, file_id).unwrap(); |
899 | assert!(diagnostics.is_empty()); | 915 | assert!(diagnostics.is_empty()); |
900 | 916 | ||
901 | let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap(); | 917 | let diagnostics = |
918 | analysis.diagnostics(&DiagnosticsConfig::default(), true, file_id).unwrap(); | ||
902 | assert!(!diagnostics.is_empty()); | 919 | assert!(!diagnostics.is_empty()); |
903 | } | 920 | } |
904 | 921 | ||
@@ -1004,8 +1021,9 @@ impl TestStruct { | |||
1004 | let expected = r#"fn foo() {}"#; | 1021 | let expected = r#"fn foo() {}"#; |
1005 | 1022 | ||
1006 | let (analysis, file_position) = fixture::position(input); | 1023 | let (analysis, file_position) = fixture::position(input); |
1007 | let diagnostics = | 1024 | let diagnostics = analysis |
1008 | analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap(); | 1025 | .diagnostics(&DiagnosticsConfig::default(), true, file_position.file_id) |
1026 | .unwrap(); | ||
1009 | assert_eq!(diagnostics.len(), 1); | 1027 | assert_eq!(diagnostics.len(), 1); |
1010 | 1028 | ||
1011 | check_fix(input, expected); | 1029 | check_fix(input, expected); |
diff --git a/crates/ide/src/diagnostics/fixes.rs b/crates/ide/src/diagnostics/fixes.rs index 69cf5288c..7be8b3459 100644 --- a/crates/ide/src/diagnostics/fixes.rs +++ b/crates/ide/src/diagnostics/fixes.rs | |||
@@ -20,17 +20,26 @@ use syntax::{ | |||
20 | }; | 20 | }; |
21 | use text_edit::TextEdit; | 21 | use text_edit::TextEdit; |
22 | 22 | ||
23 | use crate::{diagnostics::fix, references::rename::rename_with_semantics, Assist, FilePosition}; | 23 | use crate::{ |
24 | diagnostics::{fix, unresolved_fix}, | ||
25 | references::rename::rename_with_semantics, | ||
26 | Assist, FilePosition, | ||
27 | }; | ||
24 | 28 | ||
25 | /// A [Diagnostic] that potentially has a fix available. | 29 | /// A [Diagnostic] that potentially has a fix available. |
26 | /// | 30 | /// |
27 | /// [Diagnostic]: hir::diagnostics::Diagnostic | 31 | /// [Diagnostic]: hir::diagnostics::Diagnostic |
28 | pub(crate) trait DiagnosticWithFix: Diagnostic { | 32 | pub(crate) trait DiagnosticWithFix: Diagnostic { |
29 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist>; | 33 | /// `resolve` determines if the diagnostic should fill in the `edit` field |
34 | /// of the assist. | ||
35 | /// | ||
36 | /// If `resolve` is false, the edit will be computed later, on demand, and | ||
37 | /// can be omitted. | ||
38 | fn fix(&self, sema: &Semantics<RootDatabase>, _resolve: bool) -> Option<Assist>; | ||
30 | } | 39 | } |
31 | 40 | ||
32 | impl DiagnosticWithFix for UnresolvedModule { | 41 | impl DiagnosticWithFix for UnresolvedModule { |
33 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist> { | 42 | fn fix(&self, sema: &Semantics<RootDatabase>, _resolve: bool) -> Option<Assist> { |
34 | let root = sema.db.parse_or_expand(self.file)?; | 43 | let root = sema.db.parse_or_expand(self.file)?; |
35 | let unresolved_module = self.decl.to_node(&root); | 44 | let unresolved_module = self.decl.to_node(&root); |
36 | Some(fix( | 45 | Some(fix( |
@@ -50,7 +59,7 @@ impl DiagnosticWithFix for UnresolvedModule { | |||
50 | } | 59 | } |
51 | 60 | ||
52 | impl DiagnosticWithFix for NoSuchField { | 61 | impl DiagnosticWithFix for NoSuchField { |
53 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist> { | 62 | fn fix(&self, sema: &Semantics<RootDatabase>, _resolve: bool) -> Option<Assist> { |
54 | let root = sema.db.parse_or_expand(self.file)?; | 63 | let root = sema.db.parse_or_expand(self.file)?; |
55 | missing_record_expr_field_fix( | 64 | missing_record_expr_field_fix( |
56 | &sema, | 65 | &sema, |
@@ -61,7 +70,7 @@ impl DiagnosticWithFix for NoSuchField { | |||
61 | } | 70 | } |
62 | 71 | ||
63 | impl DiagnosticWithFix for MissingFields { | 72 | impl DiagnosticWithFix for MissingFields { |
64 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist> { | 73 | fn fix(&self, sema: &Semantics<RootDatabase>, _resolve: bool) -> Option<Assist> { |
65 | // Note that although we could add a diagnostics to | 74 | // Note that although we could add a diagnostics to |
66 | // fill the missing tuple field, e.g : | 75 | // fill the missing tuple field, e.g : |
67 | // `struct A(usize);` | 76 | // `struct A(usize);` |
@@ -97,7 +106,7 @@ impl DiagnosticWithFix for MissingFields { | |||
97 | } | 106 | } |
98 | 107 | ||
99 | impl DiagnosticWithFix for MissingOkOrSomeInTailExpr { | 108 | impl DiagnosticWithFix for MissingOkOrSomeInTailExpr { |
100 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist> { | 109 | fn fix(&self, sema: &Semantics<RootDatabase>, _resolve: bool) -> Option<Assist> { |
101 | let root = sema.db.parse_or_expand(self.file)?; | 110 | let root = sema.db.parse_or_expand(self.file)?; |
102 | let tail_expr = self.expr.to_node(&root); | 111 | let tail_expr = self.expr.to_node(&root); |
103 | let tail_expr_range = tail_expr.syntax().text_range(); | 112 | let tail_expr_range = tail_expr.syntax().text_range(); |
@@ -110,7 +119,7 @@ impl DiagnosticWithFix for MissingOkOrSomeInTailExpr { | |||
110 | } | 119 | } |
111 | 120 | ||
112 | impl DiagnosticWithFix for RemoveThisSemicolon { | 121 | impl DiagnosticWithFix for RemoveThisSemicolon { |
113 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist> { | 122 | fn fix(&self, sema: &Semantics<RootDatabase>, _resolve: bool) -> Option<Assist> { |
114 | let root = sema.db.parse_or_expand(self.file)?; | 123 | let root = sema.db.parse_or_expand(self.file)?; |
115 | 124 | ||
116 | let semicolon = self | 125 | let semicolon = self |
@@ -130,7 +139,7 @@ impl DiagnosticWithFix for RemoveThisSemicolon { | |||
130 | } | 139 | } |
131 | 140 | ||
132 | impl DiagnosticWithFix for IncorrectCase { | 141 | impl DiagnosticWithFix for IncorrectCase { |
133 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist> { | 142 | fn fix(&self, sema: &Semantics<RootDatabase>, resolve: bool) -> Option<Assist> { |
134 | let root = sema.db.parse_or_expand(self.file)?; | 143 | let root = sema.db.parse_or_expand(self.file)?; |
135 | let name_node = self.ident.to_node(&root); | 144 | let name_node = self.ident.to_node(&root); |
136 | 145 | ||
@@ -138,16 +147,19 @@ impl DiagnosticWithFix for IncorrectCase { | |||
138 | let frange = name_node.original_file_range(sema.db); | 147 | let frange = name_node.original_file_range(sema.db); |
139 | let file_position = FilePosition { file_id: frange.file_id, offset: frange.range.start() }; | 148 | let file_position = FilePosition { file_id: frange.file_id, offset: frange.range.start() }; |
140 | 149 | ||
141 | let rename_changes = | ||
142 | rename_with_semantics(sema, file_position, &self.suggested_text).ok()?; | ||
143 | |||
144 | let label = format!("Rename to {}", self.suggested_text); | 150 | let label = format!("Rename to {}", self.suggested_text); |
145 | Some(fix("change_case", &label, rename_changes, frange.range)) | 151 | let mut res = unresolved_fix("change_case", &label, frange.range); |
152 | if resolve { | ||
153 | let source_change = rename_with_semantics(sema, file_position, &self.suggested_text); | ||
154 | res.source_change = Some(source_change.ok().unwrap_or_default()); | ||
155 | } | ||
156 | |||
157 | Some(res) | ||
146 | } | 158 | } |
147 | } | 159 | } |
148 | 160 | ||
149 | impl DiagnosticWithFix for ReplaceFilterMapNextWithFindMap { | 161 | impl DiagnosticWithFix for ReplaceFilterMapNextWithFindMap { |
150 | fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Assist> { | 162 | fn fix(&self, sema: &Semantics<RootDatabase>, _resolve: bool) -> Option<Assist> { |
151 | let root = sema.db.parse_or_expand(self.file)?; | 163 | let root = sema.db.parse_or_expand(self.file)?; |
152 | let next_expr = self.next_expr.to_node(&root); | 164 | let next_expr = self.next_expr.to_node(&root); |
153 | let next_call = ast::MethodCallExpr::cast(next_expr.syntax().clone())?; | 165 | let next_call = ast::MethodCallExpr::cast(next_expr.syntax().clone())?; |
diff --git a/crates/ide/src/diagnostics/unlinked_file.rs b/crates/ide/src/diagnostics/unlinked_file.rs index 5482b7287..7d39f4fbe 100644 --- a/crates/ide/src/diagnostics/unlinked_file.rs +++ b/crates/ide/src/diagnostics/unlinked_file.rs | |||
@@ -50,7 +50,7 @@ impl Diagnostic for UnlinkedFile { | |||
50 | } | 50 | } |
51 | 51 | ||
52 | impl DiagnosticWithFix for UnlinkedFile { | 52 | impl DiagnosticWithFix for UnlinkedFile { |
53 | fn fix(&self, sema: &hir::Semantics<RootDatabase>) -> Option<Assist> { | 53 | fn fix(&self, sema: &hir::Semantics<RootDatabase>, _resolve: bool) -> Option<Assist> { |
54 | // If there's an existing module that could add a `mod` item to include the unlinked file, | 54 | // If there's an existing module that could add a `mod` item to include the unlinked file, |
55 | // suggest that as a fix. | 55 | // suggest that as a fix. |
56 | 56 | ||
diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs index d057d5402..a04333e63 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs | |||
@@ -110,6 +110,13 @@ mod tests { | |||
110 | assert_eq!(expected, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() }); | 110 | assert_eq!(expected, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() }); |
111 | } | 111 | } |
112 | 112 | ||
113 | fn check_unresolved(ra_fixture: &str) { | ||
114 | let (analysis, position) = fixture::position(ra_fixture); | ||
115 | let navs = analysis.goto_definition(position).unwrap().expect("no definition found").info; | ||
116 | |||
117 | assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {:?}", navs) | ||
118 | } | ||
119 | |||
113 | #[test] | 120 | #[test] |
114 | fn goto_def_for_extern_crate() { | 121 | fn goto_def_for_extern_crate() { |
115 | check( | 122 | check( |
@@ -927,17 +934,12 @@ fn f() -> impl Iterator<Item$0 = u8> {} | |||
927 | } | 934 | } |
928 | 935 | ||
929 | #[test] | 936 | #[test] |
930 | #[should_panic = "unresolved reference"] | ||
931 | fn unknown_assoc_ty() { | 937 | fn unknown_assoc_ty() { |
932 | check( | 938 | check_unresolved( |
933 | r#" | 939 | r#" |
934 | trait Iterator { | 940 | trait Iterator { type Item; } |
935 | type Item; | ||
936 | //^^^^ | ||
937 | } | ||
938 | |||
939 | fn f() -> impl Iterator<Invalid$0 = u8> {} | 941 | fn f() -> impl Iterator<Invalid$0 = u8> {} |
940 | "#, | 942 | "#, |
941 | ) | 943 | ) |
942 | } | 944 | } |
943 | 945 | ||
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index 0615b26d3..99e45633e 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs | |||
@@ -82,7 +82,7 @@ pub use crate::{ | |||
82 | references::{rename::RenameError, ReferenceSearchResult}, | 82 | references::{rename::RenameError, ReferenceSearchResult}, |
83 | runnables::{Runnable, RunnableKind, TestId}, | 83 | runnables::{Runnable, RunnableKind, TestId}, |
84 | syntax_highlighting::{ | 84 | syntax_highlighting::{ |
85 | tags::{Highlight, HlMod, HlMods, HlPunct, HlTag}, | 85 | tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag}, |
86 | HlRange, | 86 | HlRange, |
87 | }, | 87 | }, |
88 | }; | 88 | }; |
@@ -244,6 +244,12 @@ impl Analysis { | |||
244 | self.with_db(|db| db.parse(file_id).tree()) | 244 | self.with_db(|db| db.parse(file_id).tree()) |
245 | } | 245 | } |
246 | 246 | ||
247 | /// Returns true if this file belongs to an immutable library. | ||
248 | pub fn is_library_file(&self, file_id: FileId) -> Cancelable<bool> { | ||
249 | use ide_db::base_db::SourceDatabaseExt; | ||
250 | self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library) | ||
251 | } | ||
252 | |||
247 | /// Gets the file's `LineIndex`: data structure to convert between absolute | 253 | /// Gets the file's `LineIndex`: data structure to convert between absolute |
248 | /// offsets and line/column representation. | 254 | /// offsets and line/column representation. |
249 | pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> { | 255 | pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> { |
@@ -526,9 +532,39 @@ impl Analysis { | |||
526 | pub fn diagnostics( | 532 | pub fn diagnostics( |
527 | &self, | 533 | &self, |
528 | config: &DiagnosticsConfig, | 534 | config: &DiagnosticsConfig, |
535 | resolve: bool, | ||
529 | file_id: FileId, | 536 | file_id: FileId, |
530 | ) -> Cancelable<Vec<Diagnostic>> { | 537 | ) -> Cancelable<Vec<Diagnostic>> { |
531 | self.with_db(|db| diagnostics::diagnostics(db, config, file_id)) | 538 | self.with_db(|db| diagnostics::diagnostics(db, config, resolve, file_id)) |
539 | } | ||
540 | |||
541 | /// Convenience function to return assists + quick fixes for diagnostics | ||
542 | pub fn assists_with_fixes( | ||
543 | &self, | ||
544 | assist_config: &AssistConfig, | ||
545 | diagnostics_config: &DiagnosticsConfig, | ||
546 | resolve: bool, | ||
547 | frange: FileRange, | ||
548 | ) -> Cancelable<Vec<Assist>> { | ||
549 | let include_fixes = match &assist_config.allowed { | ||
550 | Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix), | ||
551 | None => true, | ||
552 | }; | ||
553 | |||
554 | self.with_db(|db| { | ||
555 | let mut res = Assist::get(db, assist_config, resolve, frange); | ||
556 | ssr::add_ssr_assist(db, &mut res, resolve, frange); | ||
557 | |||
558 | if include_fixes { | ||
559 | res.extend( | ||
560 | diagnostics::diagnostics(db, diagnostics_config, resolve, frange.file_id) | ||
561 | .into_iter() | ||
562 | .filter_map(|it| it.fix) | ||
563 | .filter(|it| it.target.intersect(frange.range).is_some()), | ||
564 | ); | ||
565 | } | ||
566 | res | ||
567 | }) | ||
532 | } | 568 | } |
533 | 569 | ||
534 | /// Returns the edit required to rename reference at the position to the new | 570 | /// Returns the edit required to rename reference at the position to the new |
diff --git a/crates/ide/src/move_item.rs b/crates/ide/src/move_item.rs index 8d37f4f92..246f10a0a 100644 --- a/crates/ide/src/move_item.rs +++ b/crates/ide/src/move_item.rs | |||
@@ -1,4 +1,4 @@ | |||
1 | use std::iter::once; | 1 | use std::{iter::once, mem}; |
2 | 2 | ||
3 | use hir::Semantics; | 3 | use hir::Semantics; |
4 | use ide_db::{base_db::FileRange, RootDatabase}; | 4 | use ide_db::{base_db::FileRange, RootDatabase}; |
@@ -102,7 +102,7 @@ fn move_in_direction( | |||
102 | ast::GenericArgList(it) => swap_sibling_in_list(node, it.generic_args(), range, direction), | 102 | ast::GenericArgList(it) => swap_sibling_in_list(node, it.generic_args(), range, direction), |
103 | ast::VariantList(it) => swap_sibling_in_list(node, it.variants(), range, direction), | 103 | ast::VariantList(it) => swap_sibling_in_list(node, it.variants(), range, direction), |
104 | ast::TypeBoundList(it) => swap_sibling_in_list(node, it.bounds(), range, direction), | 104 | ast::TypeBoundList(it) => swap_sibling_in_list(node, it.bounds(), range, direction), |
105 | _ => Some(replace_nodes(node, &match direction { | 105 | _ => Some(replace_nodes(range, node, &match direction { |
106 | Direction::Up => node.prev_sibling(), | 106 | Direction::Up => node.prev_sibling(), |
107 | Direction::Down => node.next_sibling(), | 107 | Direction::Down => node.next_sibling(), |
108 | }?)) | 108 | }?)) |
@@ -125,7 +125,7 @@ fn swap_sibling_in_list<A: AstNode + Clone, I: Iterator<Item = A>>( | |||
125 | .next(); | 125 | .next(); |
126 | 126 | ||
127 | if let Some((l, r)) = list_lookup { | 127 | if let Some((l, r)) = list_lookup { |
128 | Some(replace_nodes(l.syntax(), r.syntax())) | 128 | Some(replace_nodes(range, l.syntax(), r.syntax())) |
129 | } else { | 129 | } else { |
130 | // Cursor is beyond any movable list item (for example, on curly brace in enum). | 130 | // Cursor is beyond any movable list item (for example, on curly brace in enum). |
131 | // It's not necessary, that parent of list is movable (arg list's parent is not, for example), | 131 | // It's not necessary, that parent of list is movable (arg list's parent is not, for example), |
@@ -134,11 +134,38 @@ fn swap_sibling_in_list<A: AstNode + Clone, I: Iterator<Item = A>>( | |||
134 | } | 134 | } |
135 | } | 135 | } |
136 | 136 | ||
137 | fn replace_nodes(first: &SyntaxNode, second: &SyntaxNode) -> TextEdit { | 137 | fn replace_nodes<'a>( |
138 | range: TextRange, | ||
139 | mut first: &'a SyntaxNode, | ||
140 | mut second: &'a SyntaxNode, | ||
141 | ) -> TextEdit { | ||
142 | let cursor_offset = if range.is_empty() { | ||
143 | // FIXME: `applySnippetTextEdits` does not support non-empty selection ranges | ||
144 | if first.text_range().contains_range(range) { | ||
145 | Some(range.start() - first.text_range().start()) | ||
146 | } else if second.text_range().contains_range(range) { | ||
147 | mem::swap(&mut first, &mut second); | ||
148 | Some(range.start() - first.text_range().start()) | ||
149 | } else { | ||
150 | None | ||
151 | } | ||
152 | } else { | ||
153 | None | ||
154 | }; | ||
155 | |||
156 | let first_with_cursor = match cursor_offset { | ||
157 | Some(offset) => { | ||
158 | let mut item_text = first.text().to_string(); | ||
159 | item_text.insert_str(offset.into(), "$0"); | ||
160 | item_text | ||
161 | } | ||
162 | None => first.text().to_string(), | ||