aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_def/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/hir_def/src')
-rw-r--r--crates/hir_def/src/attr.rs45
-rw-r--r--crates/hir_def/src/body.rs26
-rw-r--r--crates/hir_def/src/body/lower.rs76
-rw-r--r--crates/hir_def/src/body/tests.rs10
-rw-r--r--crates/hir_def/src/body/tests/block.rs24
-rw-r--r--crates/hir_def/src/child_by_source.rs4
-rw-r--r--crates/hir_def/src/diagnostics.rs5
-rw-r--r--crates/hir_def/src/find_path.rs695
-rw-r--r--crates/hir_def/src/item_tree.rs17
-rw-r--r--crates/hir_def/src/item_tree/lower.rs2
-rw-r--r--crates/hir_def/src/lib.rs53
-rw-r--r--crates/hir_def/src/nameres.rs55
-rw-r--r--crates/hir_def/src/nameres/collector.rs34
-rw-r--r--crates/hir_def/src/nameres/path_resolution.rs59
-rw-r--r--crates/hir_def/src/nameres/tests/diagnostics.rs4
-rw-r--r--crates/hir_def/src/path.rs7
-rw-r--r--crates/hir_def/src/path/lower.rs17
-rw-r--r--crates/hir_def/src/test_db.rs51
-rw-r--r--crates/hir_def/src/type_ref.rs18
-rw-r--r--crates/hir_def/src/visibility.rs10
20 files changed, 808 insertions, 404 deletions
diff --git a/crates/hir_def/src/attr.rs b/crates/hir_def/src/attr.rs
index d9df7564d..d9294d93a 100644
--- a/crates/hir_def/src/attr.rs
+++ b/crates/hir_def/src/attr.rs
@@ -9,7 +9,7 @@ use std::{
9use base_db::CrateId; 9use base_db::CrateId;
10use cfg::{CfgExpr, CfgOptions}; 10use cfg::{CfgExpr, CfgOptions};
11use either::Either; 11use either::Either;
12use hir_expand::{hygiene::Hygiene, name::AsName, AstId, InFile}; 12use hir_expand::{hygiene::Hygiene, name::AsName, AstId, AttrId, InFile};
13use itertools::Itertools; 13use itertools::Itertools;
14use la_arena::ArenaMap; 14use la_arena::ArenaMap;
15use mbe::ast_to_token_tree; 15use mbe::ast_to_token_tree;
@@ -98,13 +98,16 @@ impl RawAttrs {
98 pub(crate) fn new(owner: &dyn ast::AttrsOwner, hygiene: &Hygiene) -> Self { 98 pub(crate) fn new(owner: &dyn ast::AttrsOwner, hygiene: &Hygiene) -> Self {
99 let entries = collect_attrs(owner) 99 let entries = collect_attrs(owner)
100 .enumerate() 100 .enumerate()
101 .flat_map(|(i, attr)| match attr { 101 .flat_map(|(i, attr)| {
102 Either::Left(attr) => Attr::from_src(attr, hygiene, i as u32), 102 let index = AttrId(i as u32);
103 Either::Right(comment) => comment.doc_comment().map(|doc| Attr { 103 match attr {
104 index: i as u32, 104 Either::Left(attr) => Attr::from_src(attr, hygiene, index),
105 input: Some(AttrInput::Literal(SmolStr::new(doc))), 105 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
106 path: Interned::new(ModPath::from(hir_expand::name!(doc))), 106 id: index,
107 }), 107 input: Some(AttrInput::Literal(SmolStr::new(doc))),
108 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
109 }),
110 }
108 }) 111 })
109 .collect::<Arc<_>>(); 112 .collect::<Arc<_>>();
110 113
@@ -161,7 +164,7 @@ impl RawAttrs {
161 let cfg = parts.next().unwrap(); 164 let cfg = parts.next().unwrap();
162 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() }; 165 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
163 let cfg = CfgExpr::parse(&cfg); 166 let cfg = CfgExpr::parse(&cfg);
164 let index = attr.index; 167 let index = attr.id;
165 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| { 168 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
166 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() }; 169 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
167 let attr = ast::Attr::parse(&format!("#[{}]", tree)).ok()?; 170 let attr = ast::Attr::parse(&format!("#[{}]", tree)).ok()?;
@@ -468,7 +471,7 @@ impl AttrsWithOwner {
468 ) -> Option<(Documentation, DocsRangeMap)> { 471 ) -> Option<(Documentation, DocsRangeMap)> {
469 // FIXME: code duplication in `docs` above 472 // FIXME: code duplication in `docs` above
470 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_ref()? { 473 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_ref()? {
471 AttrInput::Literal(s) => Some((s, attr.index)), 474 AttrInput::Literal(s) => Some((s, attr.id)),
472 AttrInput::TokenTree(_) => None, 475 AttrInput::TokenTree(_) => None,
473 }); 476 });
474 let indent = docs 477 let indent = docs
@@ -542,7 +545,7 @@ fn inner_attributes(
542 _ => return None, 545 _ => return None,
543 } 546 }
544 }; 547 };
545 let attrs = attrs.filter(|attr| attr.excl_token().is_some()); 548 let attrs = attrs.filter(|attr| attr.kind().is_inner());
546 let docs = docs.filter(|doc| doc.is_inner()); 549 let docs = docs.filter(|doc| doc.is_inner());
547 Some((attrs, docs)) 550 Some((attrs, docs))
548} 551}
@@ -560,8 +563,8 @@ impl AttrSourceMap {
560 /// the attribute represented by `Attr`. 563 /// the attribute represented by `Attr`.
561 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> { 564 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
562 self.attrs 565 self.attrs
563 .get(attr.index as usize) 566 .get(attr.id.0 as usize)
564 .unwrap_or_else(|| panic!("cannot find `Attr` at index {}", attr.index)) 567 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", attr.id))
565 .as_ref() 568 .as_ref()
566 } 569 }
567} 570}
@@ -572,7 +575,7 @@ pub struct DocsRangeMap {
572 // (docstring-line-range, attr_index, attr-string-range) 575 // (docstring-line-range, attr_index, attr-string-range)
573 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and 576 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
574 // the original (untrimmed) syntax doc line 577 // the original (untrimmed) syntax doc line
575 mapping: Vec<(TextRange, u32, TextRange)>, 578 mapping: Vec<(TextRange, AttrId, TextRange)>,
576} 579}
577 580
578impl DocsRangeMap { 581impl DocsRangeMap {
@@ -585,7 +588,7 @@ impl DocsRangeMap {
585 588
586 let relative_range = range - line_docs_range.start(); 589 let relative_range = range - line_docs_range.start();
587 590
588 let &InFile { file_id, value: ref source } = &self.source[idx as usize]; 591 let &InFile { file_id, value: ref source } = &self.source[idx.0 as usize];
589 match source { 592 match source {
590 Either::Left(_) => None, // FIXME, figure out a nice way to handle doc attributes here 593 Either::Left(_) => None, // FIXME, figure out a nice way to handle doc attributes here
591 // as well as for whats done in syntax highlight doc injection 594 // as well as for whats done in syntax highlight doc injection
@@ -606,7 +609,7 @@ impl DocsRangeMap {
606 609
607#[derive(Debug, Clone, PartialEq, Eq)] 610#[derive(Debug, Clone, PartialEq, Eq)]
608pub struct Attr { 611pub struct Attr {
609 index: u32, 612 pub(crate) id: AttrId,
610 pub(crate) path: Interned<ModPath>, 613 pub(crate) path: Interned<ModPath>,
611 pub(crate) input: Option<AttrInput>, 614 pub(crate) input: Option<AttrInput>,
612} 615}
@@ -620,7 +623,7 @@ pub enum AttrInput {
620} 623}
621 624
622impl Attr { 625impl Attr {
623 fn from_src(ast: ast::Attr, hygiene: &Hygiene, index: u32) -> Option<Attr> { 626 fn from_src(ast: ast::Attr, hygiene: &Hygiene, id: AttrId) -> Option<Attr> {
624 let path = Interned::new(ModPath::from_src(ast.path()?, hygiene)?); 627 let path = Interned::new(ModPath::from_src(ast.path()?, hygiene)?);
625 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() { 628 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
626 let value = match lit.kind() { 629 let value = match lit.kind() {
@@ -633,7 +636,7 @@ impl Attr {
633 } else { 636 } else {
634 None 637 None
635 }; 638 };
636 Some(Attr { index, path, input }) 639 Some(Attr { id, path, input })
637 } 640 }
638 641
639 /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths 642 /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths
@@ -737,7 +740,7 @@ fn collect_attrs(
737 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax()) 740 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
738 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs))); 741 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
739 742
740 let outer_attrs = owner.attrs().filter(|attr| attr.excl_token().is_none()); 743 let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
741 let attrs = outer_attrs 744 let attrs = outer_attrs
742 .chain(inner_attrs.into_iter().flatten()) 745 .chain(inner_attrs.into_iter().flatten())
743 .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr))); 746 .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr)));
@@ -748,9 +751,7 @@ fn collect_attrs(
748 .chain(inner_docs.into_iter().flatten()) 751 .chain(inner_docs.into_iter().flatten())
749 .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text))); 752 .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text)));
750 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved 753 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
751 let attrs: Vec<_> = docs.chain(attrs).sorted_by_key(|&(offset, _)| offset).collect(); 754 docs.chain(attrs).sorted_by_key(|&(offset, _)| offset).map(|(_, attr)| attr)
752
753 attrs.into_iter().map(|(_, attr)| attr)
754} 755}
755 756
756pub(crate) fn variants_attrs_source_map( 757pub(crate) fn variants_attrs_source_map(
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;
21use rustc_hash::FxHashMap; 21use rustc_hash::FxHashMap;
22use syntax::{ast, AstNode, AstPtr}; 22use syntax::{ast, AstNode, AstPtr};
23 23
24pub(crate) use lower::LowerCtx; 24pub use lower::LowerCtx;
25 25
26use crate::{ 26use 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)]
40pub(crate) struct CfgExpander { 41pub(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
46pub(crate) struct Expander { 47#[derive(Debug)]
48pub 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
82impl Expander { 84impl 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
207pub(crate) struct Mark { 210#[derive(Debug)]
211pub 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 bfb75a8a5..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
4use std::mem; 4use std::{mem, sync::Arc};
5 5
6use either::Either; 6use either::Either;
7use hir_expand::{ 7use 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
40use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource}; 41use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
41 42
42pub(crate) struct LowerCtx { 43pub 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
46impl LowerCtx { 49impl 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 }
49 } 56 }
50 pub(crate) fn with_hygiene(hygiene: &Hygiene) -> Self { 57
51 LowerCtx { hygiene: hygiene.clone() } 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
64 }
65
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
@@ -531,8 +551,9 @@ impl ExprCollector<'_> {
531 } 551 }
532 } 552 }
533 ast::Expr::MacroCall(e) => { 553 ast::Expr::MacroCall(e) => {
554 let macro_ptr = AstPtr::new(&e);
534 let mut ids = vec![]; 555 let mut ids = vec![];
535 self.collect_macro_call(e, syntax_ptr.clone(), true, |this, expansion| { 556 self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
536 ids.push(match expansion { 557 ids.push(match expansion {
537 Some(it) => this.collect_expr(it), 558 Some(it) => this.collect_expr(it),
538 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()), 559 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
@@ -555,7 +576,7 @@ impl ExprCollector<'_> {
555 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>( 576 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
556 &mut self, 577 &mut self,
557 e: ast::MacroCall, 578 e: ast::MacroCall,
558 syntax_ptr: AstPtr<ast::Expr>, 579 syntax_ptr: AstPtr<ast::MacroCall>,
559 is_error_recoverable: bool, 580 is_error_recoverable: bool,
560 mut collector: F, 581 mut collector: F,
561 ) { 582 ) {
@@ -567,9 +588,13 @@ impl ExprCollector<'_> {
567 588
568 let res = match res { 589 let res = match res {
569 Ok(res) => res, 590 Ok(res) => res,
570 Err(UnresolvedMacro) => { 591 Err(UnresolvedMacro { path }) => {
571 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall( 592 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall(
572 UnresolvedMacroCall { file: outer_file, node: syntax_ptr.cast().unwrap() }, 593 UnresolvedMacroCall {
594 file: outer_file,
595 node: syntax_ptr.cast().unwrap(),
596 path,
597 },
573 )); 598 ));
574 collector(self, None); 599 collector(self, None);
575 return; 600 return;
@@ -643,10 +668,14 @@ impl ExprCollector<'_> {
643 668
644 // Note that macro could be expended to multiple statements 669 // Note that macro could be expended to multiple statements
645 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() { 670 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
671 let macro_ptr = AstPtr::new(&m);
646 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap()); 672 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
647 673
648 self.collect_macro_call(m, syntax_ptr.clone(), false, |this, expansion| { 674 self.collect_macro_call(
649 match expansion { 675 m,
676 macro_ptr,
677 false,
678 |this, expansion| match expansion {
650 Some(expansion) => { 679 Some(expansion) => {
651 let statements: ast::MacroStmts = expansion; 680 let statements: ast::MacroStmts = expansion;
652 681
@@ -660,8 +689,8 @@ impl ExprCollector<'_> {
660 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone()); 689 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
661 this.statements_in_scope.push(Statement::Expr(expr)); 690 this.statements_in_scope.push(Statement::Expr(expr));
662 } 691 }
663 } 692 },
664 }); 693 );
665 } else { 694 } else {
666 let expr = self.collect_expr_opt(stmt.expr()); 695 let expr = self.collect_expr_opt(stmt.expr());
667 self.statements_in_scope.push(Statement::Expr(expr)); 696 self.statements_in_scope.push(Statement::Expr(expr));
@@ -848,8 +877,23 @@ impl ExprCollector<'_> {
848 Pat::Missing 877 Pat::Missing
849 } 878 }
850 } 879 }
880 ast::Pat::MacroPat(mac) => match mac.macro_call() {
881 Some(call) => {
882 let macro_ptr = AstPtr::new(&call);
883 let mut pat = None;
884 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
885 pat = Some(this.collect_pat_opt(expanded_pat));
886 });
887
888 match pat {
889 Some(pat) => return pat,
890 None => Pat::Missing,
891 }
892 }
893 None => Pat::Missing,
894 },
851 // FIXME: implement 895 // FIXME: implement
852 ast::Pat::RangePat(_) | ast::Pat::MacroPat(_) => Pat::Missing, 896 ast::Pat::RangePat(_) => Pat::Missing,
853 }; 897 };
854 let ptr = AstPtr::new(&pat); 898 let ptr = AstPtr::new(&pat);
855 self.alloc_pat(pattern, Either::Left(ptr)) 899 self.alloc_pat(pattern, Either::Left(ptr))
diff --git a/crates/hir_def/src/body/tests.rs b/crates/hir_def/src/body/tests.rs
index c1d3e998f..3e8f16306 100644
--- a/crates/hir_def/src/body/tests.rs
+++ b/crates/hir_def/src/body/tests.rs
@@ -40,6 +40,14 @@ fn block_def_map_at(ra_fixture: &str) -> String {
40 module.def_map(&db).dump(&db) 40 module.def_map(&db).dump(&db)
41} 41}
42 42
43fn check_block_scopes_at(ra_fixture: &str, expect: Expect) {
44 let (db, position) = crate::test_db::TestDB::with_position(ra_fixture);
45
46 let module = db.module_at_position(position);
47 let actual = module.def_map(&db).dump_block_scopes(&db);
48 expect.assert_eq(&actual);
49}
50
43fn check_at(ra_fixture: &str, expect: Expect) { 51fn check_at(ra_fixture: &str, expect: Expect) {
44 let actual = block_def_map_at(ra_fixture); 52 let actual = block_def_map_at(ra_fixture);
45 expect.assert_eq(&actual); 53 expect.assert_eq(&actual);
@@ -180,7 +188,7 @@ fn unresolved_macro_diag() {
180 r#" 188 r#"
181fn f() { 189fn f() {
182 m!(); 190 m!();
183 //^^^^ unresolved macro call 191 //^^^^ unresolved macro `m!`
184} 192}
185 "#, 193 "#,
186 ); 194 );
diff --git a/crates/hir_def/src/body/tests/block.rs b/crates/hir_def/src/body/tests/block.rs
index 3b6ba4cde..bc3d0f138 100644
--- a/crates/hir_def/src/body/tests/block.rs
+++ b/crates/hir_def/src/body/tests/block.rs
@@ -134,6 +134,30 @@ struct Struct {}
134} 134}
135 135
136#[test] 136#[test]
137fn nested_module_scoping() {
138 check_block_scopes_at(
139 r#"
140fn f() {
141 mod module {
142 struct Struct {}
143 fn f() {
144 use self::Struct;
145 $0
146 }
147 }
148}
149 "#,
150 expect![[r#"
151 BlockId(1) in ModuleId { krate: CrateId(0), block: Some(BlockId(0)), local_id: Idx::<ModuleData>(0) }
152 BlockId(0) in ModuleId { krate: CrateId(0), block: None, local_id: Idx::<ModuleData>(0) }
153 crate scope
154 "#]],
155 );
156 // FIXME: The module nesting here is wrong!
157 // The first block map should be located in module #1 (`mod module`), not #0 (BlockId(0) root module)
158}
159
160#[test]
137fn legacy_macro_items() { 161fn legacy_macro_items() {
138 // Checks that legacy-scoped `macro_rules!` from parent namespaces are resolved and expanded 162 // Checks that legacy-scoped `macro_rules!` from parent namespaces are resolved and expanded
139 // correctly. 163 // correctly.
diff --git a/crates/hir_def/src/child_by_source.rs b/crates/hir_def/src/child_by_source.rs
index f40a7f80d..f2e809ca9 100644
--- a/crates/hir_def/src/child_by_source.rs
+++ b/crates/hir_def/src/child_by_source.rs
@@ -80,6 +80,10 @@ impl ChildBySource for ModuleId {
80impl ChildBySource for ItemScope { 80impl ChildBySource for ItemScope {
81 fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap) { 81 fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap) {
82 self.declarations().for_each(|item| add_module_def(db, res, item)); 82 self.declarations().for_each(|item| add_module_def(db, res, item));
83 self.unnamed_consts().for_each(|konst| {
84 let src = konst.lookup(db).source(db);
85 res[keys::CONST].insert(src, konst);
86 });
83 self.impls().for_each(|imp| add_impl(db, res, imp)); 87 self.impls().for_each(|imp| add_impl(db, res, imp));
84 88
85 fn add_module_def(db: &dyn DefDatabase, map: &mut DynMap, item: ModuleDefId) { 89 fn add_module_def(db: &dyn DefDatabase, map: &mut DynMap, item: ModuleDefId) {
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};
8use hir_expand::{HirFileId, InFile}; 8use hir_expand::{HirFileId, InFile};
9use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange}; 9use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange};
10 10
11use crate::{db::DefDatabase, DefWithBodyId}; 11use crate::{db::DefDatabase, path::ModPath, DefWithBodyId};
12 12
13pub fn validate_body(db: &dyn DefDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) { 13pub 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 {
103pub struct UnresolvedMacroCall { 103pub 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
108impl Diagnostic for UnresolvedMacroCall { 109impl 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..c06a37294 100644
--- a/crates/hir_def/src/find_path.rs
+++ b/crates/hir_def/src/find_path.rs
@@ -119,8 +119,7 @@ fn find_path_inner(
119 119
120 // - if the item is the crate root, return `crate` 120 // - if the item is the crate root, return `crate`
121 let root = def_map.crate_root(db); 121 let root = def_map.crate_root(db);
122 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) && def_map.block_id().is_none() { 122 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) {
123 // FIXME: the `block_id()` check should be unnecessary, but affects the result
124 return Some(ModPath::from_segments(PathKind::Crate, Vec::new())); 123 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
125 } 124 }
126 125
@@ -131,7 +130,8 @@ fn find_path_inner(
131 } 130 }
132 131
133 // - if the item is the crate root of a dependency crate, return the name from the extern prelude 132 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
134 for (name, def_id) in def_map.extern_prelude() { 133 let root_def_map = root.def_map(db);
134 for (name, def_id) in root_def_map.extern_prelude() {
135 if item == ItemInNs::Types(*def_id) { 135 if item == ItemInNs::Types(*def_id) {
136 let name = scope_name.unwrap_or_else(|| name.clone()); 136 let name = scope_name.unwrap_or_else(|| name.clone());
137 return Some(ModPath::from_segments(PathKind::Plain, vec![name])); 137 return Some(ModPath::from_segments(PathKind::Plain, vec![name]));
@@ -139,7 +139,8 @@ fn find_path_inner(
139 } 139 }
140 140
141 // - if the item is in the prelude, return the name from there 141 // - if the item is in the prelude, return the name from there
142 if let Some(prelude_module) = def_map.prelude() { 142 if let Some(prelude_module) = root_def_map.prelude() {
143 // Preludes in block DefMaps are ignored, only the crate DefMap is searched
143 let prelude_def_map = prelude_module.def_map(db); 144 let prelude_def_map = prelude_module.def_map(db);
144 let prelude_scope: &crate::item_scope::ItemScope = 145 let prelude_scope: &crate::item_scope::ItemScope =
145 &prelude_def_map[prelude_module.local_id].scope; 146 &prelude_def_map[prelude_module.local_id].scope;
@@ -298,6 +299,7 @@ fn find_local_import_locations(
298 let data = &def_map[from.local_id]; 299 let data = &def_map[from.local_id];
299 let mut worklist = 300 let mut worklist =
300 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>(); 301 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
302 // FIXME: do we need to traverse out of block expressions here?
301 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) { 303 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
302 worklist.push(ancestor); 304 worklist.push(ancestor);
303 } 305 }
@@ -425,106 +427,142 @@ mod tests {
425 427
426 #[test] 428 #[test]
427 fn same_module() { 429 fn same_module() {
428 let code = r#" 430 check_found_path(
429 //- /main.rs 431 r#"
430 struct S; 432struct S;
431 $0 433$0
432 "#; 434 "#,
433 check_found_path(code, "S", "S", "crate::S", "self::S"); 435 "S",
436 "S",
437 "crate::S",
438 "self::S",
439 );
434 } 440 }
435 441
436 #[test] 442 #[test]
437 fn enum_variant() { 443 fn enum_variant() {
438 let code = r#" 444 check_found_path(
439 //- /main.rs 445 r#"
440 enum E { A } 446enum E { A }
441 $0 447$0
442 "#; 448 "#,
443 check_found_path(code, "E::A", "E::A", "E::A", "E::A"); 449 "E::A",
450 "E::A",
451 "E::A",
452 "E::A",
453 );
444 } 454 }
445 455
446 #[test] 456 #[test]
447 fn sub_module() { 457 fn sub_module() {
448 let code = r#" 458 check_found_path(
449 //- /main.rs 459 r#"
450 mod foo { 460mod foo {
451 pub struct S; 461 pub struct S;
452 } 462}
453 $0 463$0
454 "#; 464 "#,
455 check_found_path(code, "foo::S", "foo::S", "crate::foo::S", "self::foo::S"); 465 "foo::S",
466 "foo::S",
467 "crate::foo::S",
468 "self::foo::S",
469 );
456 } 470 }
457 471
458 #[test] 472 #[test]
459 fn super_module() { 473 fn super_module() {
460 let code = r#" 474 check_found_path(
461 //- /main.rs 475 r#"
462 mod foo; 476//- /main.rs
463 //- /foo.rs 477mod foo;
464 mod bar; 478//- /foo.rs
465 struct S; 479mod bar;
466 //- /foo/bar.rs 480struct S;
467 $0 481//- /foo/bar.rs
468 "#; 482$0
469 check_found_path(code, "super::S", "super::S", "crate::foo::S", "super::S"); 483 "#,
484 "super::S",
485 "super::S",
486 "crate::foo::S",
487 "super::S",
488 );
470 } 489 }
471 490
472 #[test] 491 #[test]
473 fn self_module() { 492 fn self_module() {
474 let code = r#" 493 check_found_path(
475 //- /main.rs 494 r#"
476 mod foo; 495//- /main.rs
477 //- /foo.rs 496mod foo;
478 $0 497//- /foo.rs
479 "#; 498$0
480 check_found_path(code, "self", "self", "crate::foo", "self"); 499 "#,
500 "self",
501 "self",
502 "crate::foo",
503 "self",
504 );
481 } 505 }
482 506
483 #[test] 507 #[test]
484 fn crate_root() { 508 fn crate_root() {
485 let code = r#" 509 check_found_path(
486 //- /main.rs 510 r#"
487 mod foo; 511//- /main.rs
488 //- /foo.rs 512mod foo;
489 $0 513//- /foo.rs
490 "#; 514$0
491 check_found_path(code, "crate", "crate", "crate", "crate"); 515 "#,
516 "crate",
517 "crate",
518 "crate",
519 "crate",
520 );
492 } 521 }
493 522
494 #[test] 523 #[test]
495 fn same_crate() { 524 fn same_crate() {
496 let code = r#" 525 check_found_path(
497 //- /main.rs 526 r#"
498 mod foo; 527//- /main.rs
499 struct S; 528mod foo;
500 //- /foo.rs 529struct S;
501 $0 530//- /foo.rs
502 "#; 531$0
503 check_found_path(code, "crate::S", "crate::S", "crate::S", "crate::S"); 532 "#,
533 "crate::S",
534 "crate::S",
535 "crate::S",
536 "crate::S",
537 );
504 } 538 }
505 539
506 #[test] 540 #[test]
507 fn different_crate() { 541 fn different_crate() {
508 let code = r#" 542 check_found_path(
509 //- /main.rs crate:main deps:std 543 r#"
510 $0 544//- /main.rs crate:main deps:std
511 //- /std.rs crate:std 545$0
512 pub struct S; 546//- /std.rs crate:std
513 "#; 547pub struct S;
514 check_found_path(code, "std::S", "std::S", "std::S", "std::S"); 548 "#,
549 "std::S",
550 "std::S",
551 "std::S",
552 "std::S",
553 );
515 } 554 }
516 555
517 #[test] 556 #[test]
518 fn different_crate_renamed() { 557 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( 558 check_found_path(
527 code, 559 r#"
560//- /main.rs crate:main deps:std
561extern crate std as std_renamed;
562$0
563//- /std.rs crate:std
564pub struct S;
565 "#,
528 "std_renamed::S", 566 "std_renamed::S",
529 "std_renamed::S", 567 "std_renamed::S",
530 "std_renamed::S", 568 "std_renamed::S",
@@ -537,41 +575,38 @@ mod tests {
537 cov_mark::check!(partially_imported); 575 cov_mark::check!(partially_imported);
538 // Tests that short paths are used even for external items, when parts of the path are 576 // Tests that short paths are used even for external items, when parts of the path are
539 // already in scope. 577 // already in scope.
540 let code = r#" 578 check_found_path(
541 //- /main.rs crate:main deps:syntax 579 r#"
580//- /main.rs crate:main deps:syntax
542 581
543 use syntax::ast; 582use syntax::ast;
544 $0 583$0
545 584
546 //- /lib.rs crate:syntax 585//- /lib.rs crate:syntax
547 pub mod ast { 586pub mod ast {
548 pub enum ModuleItem { 587 pub enum ModuleItem {
549 A, B, C, 588 A, B, C,
550 } 589 }
551 } 590}
552 "#; 591 "#,
553 check_found_path(
554 code,
555 "ast::ModuleItem", 592 "ast::ModuleItem",
556 "syntax::ast::ModuleItem", 593 "syntax::ast::ModuleItem",
557 "syntax::ast::ModuleItem", 594 "syntax::ast::ModuleItem",
558 "syntax::ast::ModuleItem", 595 "syntax::ast::ModuleItem",
559 ); 596 );
560 597
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( 598 check_found_path(
574 code, 599 r#"
600//- /main.rs crate:main deps:syntax
601$0
602
603//- /lib.rs crate:syntax
604pub mod ast {
605 pub enum ModuleItem {
606 A, B, C,
607 }
608}
609 "#,
575 "syntax::ast::ModuleItem", 610 "syntax::ast::ModuleItem",
576 "syntax::ast::ModuleItem", 611 "syntax::ast::ModuleItem",
577 "syntax::ast::ModuleItem", 612 "syntax::ast::ModuleItem",
@@ -581,68 +616,86 @@ mod tests {
581 616
582 #[test] 617 #[test]
583 fn same_crate_reexport() { 618 fn same_crate_reexport() {
584 let code = r#" 619 check_found_path(
585 //- /main.rs 620 r#"
586 mod bar { 621mod bar {
587 mod foo { pub(super) struct S; } 622 mod foo { pub(super) struct S; }
588 pub(crate) use foo::*; 623 pub(crate) use foo::*;
589 } 624}
590 $0 625$0
591 "#; 626 "#,
592 check_found_path(code, "bar::S", "bar::S", "crate::bar::S", "self::bar::S"); 627 "bar::S",
628 "bar::S",
629 "crate::bar::S",
630 "self::bar::S",
631 );
593 } 632 }
594 633
595 #[test] 634 #[test]
596 fn same_crate_reexport_rename() { 635 fn same_crate_reexport_rename() {
597 let code = r#" 636 check_found_path(
598 //- /main.rs 637 r#"
599 mod bar { 638mod bar {
600 mod foo { pub(super) struct S; } 639 mod foo { pub(super) struct S; }
601 pub(crate) use foo::S as U; 640 pub(crate) use foo::S as U;
602 } 641}
603 $0 642$0
604 "#; 643 "#,
605 check_found_path(code, "bar::U", "bar::U", "crate::bar::U", "self::bar::U"); 644 "bar::U",
645 "bar::U",
646 "crate::bar::U",
647 "self::bar::U",
648 );
606 } 649 }
607 650
608 #[test] 651 #[test]
609 fn different_crate_reexport() { 652 fn different_crate_reexport() {
610 let code = r#" 653 check_found_path(
611 //- /main.rs crate:main deps:std 654 r#"
612 $0 655//- /main.rs crate:main deps:std
613 //- /std.rs crate:std deps:core 656$0
614 pub use core::S; 657//- /std.rs crate:std deps:core
615 //- /core.rs crate:core 658pub use core::S;
616 pub struct S; 659//- /core.rs crate:core
617 "#; 660pub struct S;
618 check_found_path(code, "std::S", "std::S", "std::S", "std::S"); 661 "#,
662 "std::S",
663 "std::S",
664 "std::S",
665 "std::S",
666 );
619 } 667 }
620 668
621 #[test] 669 #[test]
622 fn prelude() { 670 fn prelude() {
623 let code = r#" 671 check_found_path(
624 //- /main.rs crate:main deps:std 672 r#"
625 $0 673//- /main.rs crate:main deps:std
626 //- /std.rs crate:std 674$0
627 pub mod prelude { pub struct S; } 675//- /std.rs crate:std
628 #[prelude_import] 676pub mod prelude { pub struct S; }
629 pub use prelude::*; 677#[prelude_import]
630 "#; 678pub use prelude::*;
631 check_found_path(code, "S", "S", "S", "S"); 679 "#,
680 "S",
681 "S",
682 "S",
683 "S",
684 );
632 } 685 }
633 686
634 #[test] 687 #[test]
635 fn enum_variant_from_prelude() { 688 fn enum_variant_from_prelude() {
636 let code = r#" 689 let code = r#"
637 //- /main.rs crate:main deps:std 690//- /main.rs crate:main deps:std
638 $0 691$0
639 //- /std.rs crate:std 692//- /std.rs crate:std
640 pub mod prelude { 693pub mod prelude {
641 pub enum Option<T> { Some(T), None } 694 pub enum Option<T> { Some(T), None }
642 pub use Option::*; 695 pub use Option::*;
643 } 696}
644 #[prelude_import] 697#[prelude_import]
645 pub use prelude::*; 698pub use prelude::*;
646 "#; 699 "#;
647 check_found_path(code, "None", "None", "None", "None"); 700 check_found_path(code, "None", "None", "None", "None");
648 check_found_path(code, "Some", "Some", "Some", "Some"); 701 check_found_path(code, "Some", "Some", "Some", "Some");
@@ -650,71 +703,85 @@ mod tests {
650 703
651 #[test] 704 #[test]
652 fn shortest_path() { 705 fn shortest_path() {
653 let code = r#" 706 check_found_path(
654 //- /main.rs 707 r#"
655 pub mod foo; 708//- /main.rs
656 pub mod baz; 709pub mod foo;
657 struct S; 710pub mod baz;
658 $0 711struct S;
659 //- /foo.rs 712$0
660 pub mod bar { pub struct S; } 713//- /foo.rs
661 //- /baz.rs 714pub mod bar { pub struct S; }
662 pub use crate::foo::bar::S; 715//- /baz.rs
663 "#; 716pub use crate::foo::bar::S;
664 check_found_path(code, "baz::S", "baz::S", "crate::baz::S", "self::baz::S"); 717 "#,
718 "baz::S",
719 "baz::S",
720 "crate::baz::S",
721 "self::baz::S",
722 );
665 } 723 }
666 724
667 #[test] 725 #[test]
668 fn discount_private_imports() { 726 fn discount_private_imports() {
669 let code = r#" 727 check_found_path(
670 //- /main.rs 728 r#"
671 mod foo; 729//- /main.rs
672 pub mod bar { pub struct S; } 730mod foo;
673 use bar::S; 731pub mod bar { pub struct S; }
674 //- /foo.rs 732use bar::S;
675 $0 733//- /foo.rs
676 "#; 734$0
677 // crate::S would be shorter, but using private imports seems wrong 735 "#,
678 check_found_path(code, "crate::bar::S", "crate::bar::S", "crate::bar::S", "crate::bar::S"); 736 // crate::S would be shorter, but using private imports seems wrong
737 "crate::bar::S",
738 "crate::bar::S",
739 "crate::bar::S",
740 "crate::bar::S",
741 );
679 } 742 }
680 743
681 #[test] 744 #[test]
682 fn import_cycle() { 745 fn import_cycle() {
683 let code = r#" 746 check_found_path(
684 //- /main.rs 747 r#"
685 pub mod foo; 748//- /main.rs
686 pub mod bar; 749pub mod foo;
687 pub mod baz; 750pub mod bar;
688 //- /bar.rs 751pub mod baz;
689 $0 752//- /bar.rs
690 //- /foo.rs 753$0
691 pub use super::baz; 754//- /foo.rs
692 pub struct S; 755pub use super::baz;
693 //- /baz.rs 756pub struct S;
694 pub use super::foo; 757//- /baz.rs
695 "#; 758pub use super::foo;
696 check_found_path(code, "crate::foo::S", "crate::foo::S", "crate::foo::S", "crate::foo::S"); 759 "#,
760 "crate::foo::S",
761 "crate::foo::S",
762 "crate::foo::S",
763 "crate::foo::S",
764 );
697 } 765 }
698 766
699 #[test] 767 #[test]
700 fn prefer_std_paths_over_alloc() { 768 fn prefer_std_paths_over_alloc() {
701 cov_mark::check!(prefer_std_paths); 769 cov_mark::check!(prefer_std_paths);
702 let code = r#" 770 check_found_path(
703 //- /main.rs crate:main deps:alloc,std 771 r#"
704 $0 772//- /main.rs crate:main deps:alloc,std
773$0
705 774
706 //- /std.rs crate:std deps:alloc 775//- /std.rs crate:std deps:alloc
707 pub mod sync { 776pub mod sync {
708 pub use alloc::sync::Arc; 777 pub use alloc::sync::Arc;
709 } 778}
710 779
711 //- /zzz.rs crate:alloc 780//- /zzz.rs crate:alloc
712 pub mod sync { 781pub mod sync {
713 pub struct Arc; 782 pub struct Arc;
714 } 783}
715 "#; 784 "#,
716 check_found_path(
717 code,
718 "std::sync::Arc", 785 "std::sync::Arc",
719 "std::sync::Arc", 786 "std::sync::Arc",
720 "std::sync::Arc", 787 "std::sync::Arc",
@@ -725,26 +792,25 @@ mod tests {
725 #[test] 792 #[test]
726 fn prefer_core_paths_over_std() { 793 fn prefer_core_paths_over_std() {
727 cov_mark::check!(prefer_no_std_paths); 794 cov_mark::check!(prefer_no_std_paths);
728 let code = r#" 795 check_found_path(
729 //- /main.rs crate:main deps:core,std 796 r#"
730 #![no_std] 797//- /main.rs crate:main deps:core,std
798#![no_std]
731 799
732 $0 800$0
733 801
734 //- /std.rs crate:std deps:core 802//- /std.rs crate:std deps:core
735 803
736 pub mod fmt { 804pub mod fmt {
737 pub use core::fmt::Error; 805 pub use core::fmt::Error;
738 } 806}
739 807
740 //- /zzz.rs crate:core 808//- /zzz.rs crate:core
741 809
742 pub mod fmt { 810pub mod fmt {
743 pub struct Error; 811 pub struct Error;
744 } 812}
745 "#; 813 "#,
746 check_found_path(
747 code,
748 "core::fmt::Error", 814 "core::fmt::Error",
749 "core::fmt::Error", 815 "core::fmt::Error",
750 "core::fmt::Error", 816 "core::fmt::Error",
@@ -754,26 +820,25 @@ mod tests {
754 820
755 #[test] 821 #[test]
756 fn prefer_alloc_paths_over_std() { 822 fn prefer_alloc_paths_over_std() {
757 let code = r#" 823 check_found_path(
758 //- /main.rs crate:main deps:alloc,std 824 r#"
759 #![no_std] 825//- /main.rs crate:main deps:alloc,std
826#![no_std]
760 827
761 $0 828$0
762 829
763 //- /std.rs crate:std deps:alloc 830//- /std.rs crate:std deps:alloc
764 831
765 pub mod sync { 832pub mod sync {
766 pub use alloc::sync::Arc; 833 pub use alloc::sync::Arc;
767 } 834}
768 835
769 //- /zzz.rs crate:alloc 836//- /zzz.rs crate:alloc
770 837
771 pub mod sync { 838pub mod sync {
772 pub struct Arc; 839 pub struct Arc;
773 } 840}
774 "#; 841 "#,
775 check_found_path(
776 code,
777 "alloc::sync::Arc", 842 "alloc::sync::Arc",
778 "alloc::sync::Arc", 843 "alloc::sync::Arc",
779 "alloc::sync::Arc", 844 "alloc::sync::Arc",
@@ -783,20 +848,19 @@ mod tests {
783 848
784 #[test] 849 #[test]
785 fn prefer_shorter_paths_if_not_alloc() { 850 fn prefer_shorter_paths_if_not_alloc() {
786 let code = r#" 851 check_found_path(
787 //- /main.rs crate:main deps:megaalloc,std 852 r#"
788 $0 853//- /main.rs crate:main deps:megaalloc,std
854$0
789 855
790 //- /std.rs crate:std deps:megaalloc 856//- /std.rs crate:std deps:megaalloc
791 pub mod sync { 857pub mod sync {
792 pub use megaalloc::sync::Arc; 858 pub use megaalloc::sync::Arc;
793 } 859}
794 860
795 //- /zzz.rs crate:megaalloc 861//- /zzz.rs crate:megaalloc
796 pub struct Arc; 862pub struct Arc;
797 "#; 863 "#,
798 check_found_path(
799 code,
800 "megaalloc::Arc", 864 "megaalloc::Arc",
801 "megaalloc::Arc", 865 "megaalloc::Arc",
802 "megaalloc::Arc", 866 "megaalloc::Arc",
@@ -807,12 +871,11 @@ mod tests {
807 #[test] 871 #[test]
808 fn builtins_are_in_scope() { 872 fn builtins_are_in_scope() {
809 let code = r#" 873 let code = r#"
810 //- /main.rs 874$0
811 $0
812 875
813 pub mod primitive { 876pub mod primitive {
814 pub use u8; 877 pub use u8;
815 } 878}
816 "#; 879 "#;
817 check_found_path(code, "u8", "u8", "u8", "u8"); 880 check_found_path(code, "u8", "u8", "u8", "u8");
818 check_found_path(code, "u16", "u16", "u16", "u16"); 881 check_found_path(code, "u16", "u16", "u16", "u16");
@@ -822,10 +885,10 @@ mod tests {
822 fn inner_items() { 885 fn inner_items() {
823 check_found_path( 886 check_found_path(
824 r#" 887 r#"
825 fn main() { 888fn main() {
826 struct Inner {} 889 struct Inner {}
827 $0 890 $0
828 } 891}
829 "#, 892 "#,
830 "Inner", 893 "Inner",
831 "Inner", 894 "Inner",
@@ -838,12 +901,12 @@ mod tests {
838 fn inner_items_from_outer_scope() { 901 fn inner_items_from_outer_scope() {
839 check_found_path( 902 check_found_path(
840 r#" 903 r#"
841 fn main() { 904fn main() {
842 struct Struct {} 905 struct Struct {}
843 { 906 {
844 $0 907 $0
845 } 908 }
846 } 909}
847 "#, 910 "#,
848 "Struct", 911 "Struct",
849 "Struct", 912 "Struct",
@@ -857,14 +920,14 @@ mod tests {
857 cov_mark::check!(prefixed_in_block_expression); 920 cov_mark::check!(prefixed_in_block_expression);
858 check_found_path( 921 check_found_path(
859 r#" 922 r#"
860 fn main() { 923fn main() {
861 mod module { 924 mod module {
862 struct Struct {} 925 struct Struct {}
863 } 926 }
864 { 927 {
865 $0 928 $0
866 } 929 }
867 } 930}
868 "#, 931 "#,
869 "module::Struct", 932 "module::Struct",
870 "module::Struct", 933 "module::Struct",
@@ -877,19 +940,65 @@ mod tests {
877 fn outer_items_with_inner_items_present() { 940 fn outer_items_with_inner_items_present() {
878 check_found_path( 941 check_found_path(
879 r#" 942 r#"
880 mod module { 943mod module {
881 pub struct CompleteMe; 944 pub struct CompleteMe;
882 } 945}
883 946
884 fn main() { 947fn main() {
885 fn inner() {} 948 fn inner() {}
886 $0 949 $0
887 } 950}
888 "#, 951 "#,
952 // FIXME: these could use fewer/better prefixes
889 "module::CompleteMe", 953 "module::CompleteMe",
890 "module::CompleteMe",
891 "crate::module::CompleteMe", 954 "crate::module::CompleteMe",
892 "self::module::CompleteMe", 955 "crate::module::CompleteMe",
956 "crate::module::CompleteMe",
957 )
958 }
959
960 #[test]
961 fn from_inside_module() {
962 // This worked correctly, but the test suite logic was broken.
963 cov_mark::check!(submodule_in_testdb);
964 check_found_path(
965 r#"
966mod baz {
967 pub struct Foo {}
968}
969
970mod bar {
971 fn bar() {
972 $0
973 }
974}
975 "#,
976 "crate::baz::Foo",
977 "crate::baz::Foo",
978 "crate::baz::Foo",
979 "crate::baz::Foo",
980 )
981 }
982
983 #[test]
984 fn from_inside_module_with_inner_items() {
985 check_found_path(
986 r#"
987mod baz {
988 pub struct Foo {}
989}
990
991mod bar {
992 fn bar() {
993 fn inner() {}
994 $0
995 }
996}
997 "#,
998 "crate::baz::Foo",
999 "crate::baz::Foo",
1000 "crate::baz::Foo",
1001 "crate::baz::Foo",
893 ) 1002 )
894 } 1003 }
895 1004
@@ -920,4 +1029,58 @@ pub mod name {
920 "self::name::AsName", 1029 "self::name::AsName",
921 ); 1030 );
922 } 1031 }
1032
1033 #[test]
1034 fn extern_crate() {
1035 check_found_path(
1036 r#"
1037//- /main.rs crate:main deps:dep
1038$0
1039//- /dep.rs crate:dep
1040"#,
1041 "dep",
1042 "dep",
1043 "dep",
1044 "dep",
1045 );
1046
1047 check_found_path(
1048 r#"
1049//- /main.rs crate:main deps:dep
1050fn f() {
1051 fn inner() {}
1052 $0
1053}
1054//- /dep.rs crate:dep
1055"#,
1056 "dep",
1057 "dep",
1058 "dep",
1059 "dep",
1060 );
1061 }
1062
1063 #[test]
1064 fn prelude_with_inner_items() {
1065 check_found_path(
1066 r#"
1067//- /main.rs crate:main deps:std
1068fn f() {
1069 fn inner() {}
1070 $0
1071}
1072//- /std.rs crate:std
1073pub mod prelude {
1074 pub enum Option { None }
1075 pub use Option::*;
1076}
1077#[prelude_import]
1078pub use prelude::*;
1079 "#,
1080 "None",
1081 "None",
1082 "None",
1083 "None",
1084 );
1085 }
923} 1086}
diff --git a/crates/hir_def/src/item_tree.rs b/crates/hir_def/src/item_tree.rs
index 240662486..eaeca01bd 100644
--- a/crates/hir_def/src/item_tree.rs
+++ b/crates/hir_def/src/item_tree.rs
@@ -99,6 +99,16 @@ impl ItemTree {
99 // items. 99 // items.
100 ctx.lower_macro_stmts(stmts) 100 ctx.lower_macro_stmts(stmts)
101 }, 101 },
102 ast::Pat(_pat) => {
103 // FIXME: This occurs because macros in pattern position are treated as inner
104 // items and expanded during block DefMap computation
105 return Default::default();
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 },
102 ast::Expr(e) => { 112 ast::Expr(e) => {
103 // 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
104 // still need to collect inner items. 114 // still need to collect inner items.
@@ -186,13 +196,6 @@ impl ItemTree {
186 self.raw_attrs(of).clone().filter(db, krate) 196 self.raw_attrs(of).clone().filter(db, krate)
187 } 197 }
188 198
189 pub fn all_inner_items(&self) -> impl Iterator<Item = ModItem> + '_ {
190 match &self.data {
191 Some(data) => Some(data.inner_items.values().flatten().copied()).into_iter().flatten(),
192 None => None.into_iter().flatten(),
193 }
194 }
195
196 pub fn inner_items_of_block(&self, block: FileAstId<ast::BlockExpr>) -> &[ModItem] { 199 pub fn inner_items_of_block(&self, block: FileAstId<ast::BlockExpr>) -> &[ModItem] {
197 match &self.data { 200 match &self.data {
198 Some(data) => data.inner_items.get(&block).map(|it| &**it).unwrap_or(&[]), 201 Some(data) => data.inner_items.get(&block).map(|it| &**it).unwrap_or(&[]),
diff --git a/crates/hir_def/src/item_tree/lower.rs b/crates/hir_def/src/item_tree/lower.rs
index c5629af24..45b099cf3 100644
--- a/crates/hir_def/src/item_tree/lower.rs
+++ b/crates/hir_def/src/item_tree/lower.rs
@@ -189,7 +189,7 @@ impl Ctx {
189 block_stack.push(self.source_ast_id_map.ast_id(&block)); 189 block_stack.push(self.source_ast_id_map.ast_id(&block));
190 }, 190 },
191 ast::Item(item) => { 191 ast::Item(item) => {
192 // FIXME: This triggers for macro calls in expression position 192 // FIXME: This triggers for macro calls in expression/pattern/type position
193 let mod_items = self.lower_mod_item(&item, true); 193 let mod_items = self.lower_mod_item(&item, true);
194 let current_block = block_stack.last(); 194 let current_block = block_stack.last();
195 if let (Some(mod_items), Some(block)) = (mod_items, current_block) { 195 if let (Some(mod_items), Some(block)) = (mod_items, current_block) {
diff --git a/crates/hir_def/src/lib.rs b/crates/hir_def/src/lib.rs
index e2af0e514..25694f037 100644
--- a/crates/hir_def/src/lib.rs
+++ b/crates/hir_def/src/lib.rs
@@ -62,10 +62,11 @@ use hir_expand::{
62 ast_id_map::FileAstId, 62 ast_id_map::FileAstId,
63 eager::{expand_eager_macro, ErrorEmitted, ErrorSink}, 63 eager::{expand_eager_macro, ErrorEmitted, ErrorSink},
64 hygiene::Hygiene, 64 hygiene::Hygiene,
65 AstId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind, 65 AstId, AttrId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
66}; 66};
67use la_arena::Idx; 67use la_arena::Idx;
68use nameres::DefMap; 68use nameres::DefMap;
69use path::ModPath;
69use syntax::ast; 70use syntax::ast;
70 71
71use crate::builtin_type::BuiltinType; 72use 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
451impl 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)]
439pub enum VariantId { 462pub enum VariantId {
440 EnumVariantId(EnumVariantId), 463 EnumVariantId(EnumVariantId),
@@ -665,7 +688,10 @@ impl<T: ast::AstNode> AstIdWithPath<T> {
665 } 688 }
666} 689}
667 690
668pub struct UnresolvedMacro; 691#[derive(Debug)]
692pub struct UnresolvedMacro {
693 pub path: ModPath,
694}
669 695
670fn macro_call_as_call_id( 696fn 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()));
@@ -690,24 +717,36 @@ fn macro_call_as_call_id(
690 ) 717 )
691 .map(MacroCallId::from) 718 .map(MacroCallId::from)
692 } else { 719 } else {
693 Ok(def.as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike(call.ast_id)).into()) 720 Ok(def
721 .as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike { ast_id: call.ast_id })
722 .into())
694 }; 723 };
695 Ok(res) 724 Ok(res)
696} 725}
697 726
698fn derive_macro_as_call_id( 727fn derive_macro_as_call_id(
699 item_attr: &AstIdWithPath<ast::Item>, 728 item_attr: &AstIdWithPath<ast::Item>,
729 derive_attr: AttrId,
700 db: &dyn db::DefDatabase, 730 db: &dyn db::DefDatabase,
701 krate: CrateId, 731 krate: CrateId,
702 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, 732 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
703) -> Result<MacroCallId, UnresolvedMacro> { 733) -> Result<MacroCallId, UnresolvedMacro> {
704 let def: MacroDefId = resolver(item_attr.path.clone()).ok_or(UnresolvedMacro)?; 734 let def: MacroDefId = resolver(item_attr.path.clone())
705 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() })?;
706 let res = def 741 let res = def
707 .as_lazy_macro( 742 .as_lazy_macro(
708 db.upcast(), 743 db.upcast(),
709 krate, 744 krate,
710 MacroCallKind::Derive(item_attr.ast_id, last_segment.to_string()), 745 MacroCallKind::Derive {
746 ast_id: item_attr.ast_id,
747 derive_name: last_segment.to_string(),
748 derive_attr,
749 },
711 ) 750 )
712 .into(); 751 .into();
713 Ok(res) 752 Ok(res)
diff --git a/crates/hir_def/src/nameres.rs b/crates/hir_def/src/nameres.rs
index 7dd68219f..ba027c44a 100644
--- a/crates/hir_def/src/nameres.rs
+++ b/crates/hir_def/src/nameres.rs
@@ -410,6 +410,20 @@ impl DefMap {
410 } 410 }
411 } 411 }
412 412
413 pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
414 let mut buf = String::new();
415 let mut arc;
416 let mut current_map = self;
417 while let Some(block) = &current_map.block {
418 format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
419 arc = block.parent.def_map(db);
420 current_map = &*arc;
421 }
422
423 format_to!(buf, "crate scope\n");
424 buf
425 }
426
413 fn shrink_to_fit(&mut self) { 427 fn shrink_to_fit(&mut self) {
414 // Exhaustive match to require handling new fields. 428 // Exhaustive match to require handling new fields.
415 let Self { 429 let Self {
@@ -481,7 +495,7 @@ mod diagnostics {
481 495
482 UnresolvedProcMacro { ast: MacroCallKind }, 496 UnresolvedProcMacro { ast: MacroCallKind },
483 497
484 UnresolvedMacroCall { ast: AstId<ast::MacroCall> }, 498 UnresolvedMacroCall { ast: AstId<ast::MacroCall>, path: ModPath },
485 499
486 MacroError { ast: MacroCallKind, message: String }, 500 MacroError { ast: MacroCallKind, message: String },
487 } 501 }
@@ -546,8 +560,9 @@ mod diagnostics {
546 pub(super) fn unresolved_macro_call( 560 pub(super) fn unresolved_macro_call(
547 container: LocalModuleId, 561 container: LocalModuleId,
548 ast: AstId<ast::MacroCall>, 562 ast: AstId<ast::MacroCall>,
563 path: ModPath,
549 ) -> Self { 564 ) -> Self {
550 Self { in_module: container, kind: DiagnosticKind::UnresolvedMacroCall { ast } } 565 Self { in_module: container, kind: DiagnosticKind::UnresolvedMacroCall { ast, path } }
551 } 566 }
552 567
553 pub(super) fn add_to( 568 pub(super) fn add_to(
@@ -613,12 +628,12 @@ mod diagnostics {
613 DiagnosticKind::UnresolvedProcMacro { ast } => { 628 DiagnosticKind::UnresolvedProcMacro { ast } => {
614 let mut precise_location = None; 629 let mut precise_location = None;
615 let (file, ast, name) = match ast { 630 let (file, ast, name) = match ast {
616 MacroCallKind::FnLike(ast) => { 631 MacroCallKind::FnLike { ast_id } => {
617 let node = ast.to_node(db.upcast()); 632 let node = ast_id.to_node(db.upcast());
618 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node)), None) 633 (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node)), None)
619 } 634 }
620 MacroCallKind::Derive(ast, name) => { 635 MacroCallKind::Derive { ast_id, derive_name, .. } => {
621 let node = ast.to_node(db.upcast()); 636 let node = ast_id.to_node(db.upcast());
622 637
623 // Compute the precise location of the macro name's token in the derive 638 // Compute the precise location of the macro name's token in the derive
624 // list. 639 // list.
@@ -639,7 +654,7 @@ mod diagnostics {
639 }); 654 });
640 for token in tokens { 655 for token in tokens {
641 if token.kind() == SyntaxKind::IDENT 656 if token.kind() == SyntaxKind::IDENT
642 && token.text() == name.as_str() 657 && token.text() == derive_name.as_str()
643 { 658 {
644 precise_location = Some(token.text_range()); 659 precise_location = Some(token.text_range());
645 break 'outer; 660 break 'outer;
@@ -648,9 +663,9 @@ mod diagnostics {
648 } 663 }
649 664
650 ( 665 (
651 ast.file_id, 666 ast_id.file_id,
652 SyntaxNodePtr::from(AstPtr::new(&node)), 667 SyntaxNodePtr::from(AstPtr::new(&node)),
653 Some(name.clone()), 668 Some(derive_name.clone()),
654 ) 669 )
655 } 670 }
656 }; 671 };
@@ -662,20 +677,24 @@ mod diagnostics {
662 }); 677 });
663 } 678 }
664 679
665 DiagnosticKind::UnresolvedMacroCall { ast } => { 680 DiagnosticKind::UnresolvedMacroCall { ast, path } => {
666 let node = ast.to_node(db.upcast()); 681 let node = ast.to_node(db.upcast());
667 sink.push(UnresolvedMacroCall { file: ast.file_id, node: AstPtr::new(&node) }); 682 sink.push(UnresolvedMacroCall {
683 file: ast.file_id,
684 node: AstPtr::new(&node),
685 path: path.clone(),
686 });
668 } 687 }
669 688
670 DiagnosticKind::MacroError { ast, message } => { 689 DiagnosticKind::MacroError { ast, message } => {
671 let (file, ast) = match ast { 690 let (file, ast) = match ast {
672 MacroCallKind::FnLike(ast) => { 691 MacroCallKind::FnLike { ast_id, .. } => {
673 let node = ast.to_node(db.upcast()); 692 let node = ast_id.to_node(db.upcast());
674 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node))) 693 (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node)))
675 } 694 }
676 MacroCallKind::Derive(ast, _) => { 695 MacroCallKind::Derive { ast_id, .. } => {
677 let node = ast.to_node(db.upcast()); 696 let node = ast_id.to_node(db.upcast());
678 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node))) 697 (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node)))
679 } 698 }
680 }; 699 };
681 sink.push(MacroError { file, node: ast, message: message.clone() }); 700 sink.push(MacroError { file, node: ast, message: message.clone() });
diff --git a/crates/hir_def/src/nameres/collector.rs b/crates/hir_def/src/nameres/collector.rs
index 492d8c71f..05ceb1efb 100644
--- a/crates/hir_def/src/nameres/collector.rs
+++ b/crates/hir_def/src/nameres/collector.rs
@@ -13,7 +13,7 @@ use hir_expand::{
13 builtin_macro::find_builtin_macro, 13 builtin_macro::find_builtin_macro,
14 name::{AsName, Name}, 14 name::{AsName, Name},
15 proc_macro::ProcMacroExpander, 15 proc_macro::ProcMacroExpander,
16 HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind, 16 AttrId, HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
17}; 17};
18use hir_expand::{InFile, MacroCallLoc}; 18use hir_expand::{InFile, MacroCallLoc};
19use rustc_hash::{FxHashMap, FxHashSet}; 19use rustc_hash::{FxHashMap, FxHashSet};
@@ -216,7 +216,7 @@ struct MacroDirective {
216#[derive(Clone, Debug, Eq, PartialEq)] 216#[derive(Clone, Debug, Eq, PartialEq)]
217enum MacroDirectiveKind { 217enum MacroDirectiveKind {
218 FnLike { ast_id: AstIdWithPath<ast::MacroCall> }, 218 FnLike { ast_id: AstIdWithPath<ast::MacroCall> },
219 Derive { ast_id: AstIdWithPath<ast::Item> }, 219 Derive { ast_id: AstIdWithPath<ast::Item>, derive_attr: AttrId },
220} 220}
221 221
222struct DefData<'a> { 222struct DefData<'a> {
@@ -478,7 +478,7 @@ impl DefCollector<'_> {
478 self.def_map.edition, 478 self.def_map.edition,
479 ); 479 );
480 480
481 let res = self.def_map.resolve_name_in_extern_prelude(&extern_crate.name); 481 let res = self.def_map.resolve_name_in_extern_prelude(self.db, &extern_crate.name);
482 482
483 if let Some(ModuleDefId::ModuleId(m)) = res.take_types() { 483 if let Some(ModuleDefId::ModuleId(m)) = res.take_types() {
484 cov_mark::hit!(macro_rules_from_other_crates_are_visible_with_macro_use); 484 cov_mark::hit!(macro_rules_from_other_crates_are_visible_with_macro_use);
@@ -534,6 +534,7 @@ impl DefCollector<'_> {
534 log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition); 534 log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
535 if import.is_extern_crate { 535 if import.is_extern_crate {
536 let res = self.def_map.resolve_name_in_extern_prelude( 536 let res = self.def_map.resolve_name_in_extern_prelude(
537 self.db,
537 &import 538 &import
538 .path 539 .path
539 .as_ident() 540 .as_ident()
@@ -828,19 +829,23 @@ impl DefCollector<'_> {
828 res = ReachedFixedPoint::No; 829 res = ReachedFixedPoint::No;
829 return false; 830 return false;
830 } 831 }
831 Err(UnresolvedMacro) | Ok(Err(_)) => {} 832 Err(UnresolvedMacro { .. }) | Ok(Err(_)) => {}
832 } 833 }
833 } 834 }
834 MacroDirectiveKind::Derive { ast_id } => { 835 MacroDirectiveKind::Derive { ast_id, derive_attr } => {
835 match derive_macro_as_call_id(ast_id, self.db, self.def_map.krate, |path| { 836 match derive_macro_as_call_id(
836 self.resolve_derive_macro(directive.module_id, &path) 837 ast_id,
837 }) { 838 *derive_attr,
839 self.db,
840 self.def_map.krate,
841 |path| self.resolve_derive_macro(directive.module_id, &path),
842 ) {
838 Ok(call_id) => { 843 Ok(call_id) => {
839 resolved.push((directive.module_id, call_id, 0)); 844 resolved.push((directive.module_id, call_id, directive.depth));
840 res = ReachedFixedPoint::No; 845 res = ReachedFixedPoint::No;
841 return false; 846 return false;
842 } 847 }
843 Err(UnresolvedMacro) => (), 848 Err(UnresolvedMacro { .. }) => (),
844 } 849 }
845 } 850 }
846 } 851 }
@@ -938,10 +943,11 @@ impl DefCollector<'_> {
938 &mut |_| (), 943 &mut |_| (),
939 ) { 944 ) {
940 Ok(_) => (), 945 Ok(_) => (),
941 Err(UnresolvedMacro) => { 946 Err(UnresolvedMacro { path }) => {
942 self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call( 947 self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call(
943 directive.module_id, 948 directive.module_id,
944 ast_id.ast_id, 949 ast_id.ast_id,
950 path,
945 )); 951 ));
946 } 952 }
947 }, 953 },
@@ -1368,7 +1374,7 @@ impl ModCollector<'_, '_> {
1368 self.def_collector.unexpanded_macros.push(MacroDirective { 1374 self.def_collector.unexpanded_macros.push(MacroDirective {
1369 module_id: self.module_id, 1375 module_id: self.module_id,
1370 depth: self.macro_depth + 1, 1376 depth: self.macro_depth + 1,
1371 kind: MacroDirectiveKind::Derive { ast_id }, 1377 kind: MacroDirectiveKind::Derive { ast_id, derive_attr: derive.id },
1372 }); 1378 });
1373 } 1379 }
1374 } 1380 }
@@ -1520,12 +1526,12 @@ impl ModCollector<'_, '_> {
1520 // Built-in macro failed eager expansion. 1526 // Built-in macro failed eager expansion.
1521 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error( 1527 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
1522 self.module_id, 1528 self.module_id,
1523 MacroCallKind::FnLike(ast_id.ast_id), 1529 MacroCallKind::FnLike { ast_id: ast_id.ast_id },
1524 error.unwrap().to_string(), 1530 error.unwrap().to_string(),
1525 )); 1531 ));
1526 return; 1532 return;
1527 } 1533 }
1528 Err(UnresolvedMacro) => (), 1534 Err(UnresolvedMacro { .. }) => (),
1529 } 1535 }
1530 1536
1531 // 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 60471937c..c984148c3 100644
--- a/crates/hir_def/src/nameres/path_resolution.rs
+++ b/crates/hir_def/src/nameres/path_resolution.rs
@@ -60,12 +60,26 @@ impl ResolvePathResult {
60} 60}
61 61
62impl DefMap { 62impl DefMap {
63 pub(super) fn resolve_name_in_extern_prelude(&self, name: &Name) -> PerNs { 63 pub(super) fn resolve_name_in_extern_prelude(
64 &self,
65 db: &dyn DefDatabase,
66 name: &Name,
67 ) -> PerNs {
64 if name == &name!(self) { 68 if name == &name!(self) {
65 cov_mark::hit!(extern_crate_self_as); 69 cov_mark::hit!(extern_crate_self_as);
66 return PerNs::types(self.module_id(self.root).into(), Visibility::Public); 70 return PerNs::types(self.module_id(self.root).into(), Visibility::Public);
67 } 71 }
68 self.extern_prelude 72
73 let arc;
74 let root = match self.block {
75 Some(_) => {
76 arc = self.crate_root(db).def_map(db);
77 &*arc
78 }
79 None => self,
80 };
81
82 root.extern_prelude
69 .get(name) 83 .get(name)
70 .map_or(PerNs::none(), |&it| PerNs::types(it, Visibility::Public)) 84 .map_or(PerNs::none(), |&it| PerNs::types(it, Visibility::Public))
71 } 85 }
@@ -191,7 +205,7 @@ impl DefMap {
191 None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), 205 None => return ResolvePathResult::empty(ReachedFixedPoint::Yes),
192 }; 206 };
193 log::debug!("resolving {:?} in crate root (+ extern prelude)", segment); 207 log::debug!("resolving {:?} in crate root (+ extern prelude)", segment);
194 self.resolve_name_in_crate_root_or_extern_prelude(&segment) 208 self.resolve_name_in_crate_root_or_extern_prelude(db, &segment)
195 } 209 }
196 PathKind::Plain => { 210 PathKind::Plain => {
197 let (_, segment) = match segments.next() { 211 let (_, segment) = match segments.next() {
@@ -373,7 +387,13 @@ impl DefMap {
373 .get_legacy_macro(name) 387 .get_legacy_macro(name)
374 .map_or_else(PerNs::none, |m| PerNs::macros(m, Visibility::Public)); 388 .map_or_else(PerNs::none, |m| PerNs::macros(m, Visibility::Public));
375 let from_scope = self[module].scope.get(name); 389 let from_scope = self[module].scope.get(name);
376 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 };
377 let from_scope_or_builtin = match shadow { 397 let from_scope_or_builtin = match shadow {
378 BuiltinShadowMode::Module => from_scope.or(from_builtin), 398 BuiltinShadowMode::Module => from_scope.or(from_builtin),
379 BuiltinShadowMode::Other => { 399 BuiltinShadowMode::Other => {
@@ -384,24 +404,31 @@ impl DefMap {
384 } 404 }
385 } 405 }
386 }; 406 };
387 // Give precedence to names in outer `DefMap`s over the extern prelude; only check prelude 407 let from_extern_prelude = self
388 // from the crate DefMap. 408 .extern_prelude
389 let from_extern_prelude = match self.block { 409 .get(name)
390 Some(_) => PerNs::none(), 410 .map_or(PerNs::none(), |&it| PerNs::types(it, Visibility::Public));
391 None => self
392 .extern_prelude
393 .get(name)
394 .map_or(PerNs::none(), |&it| PerNs::types(it, Visibility::Public)),
395 };
396 411
397 let from_prelude = self.resolve_in_prelude(db, name); 412 let from_prelude = self.resolve_in_prelude(db, name);
398 413
399 from_legacy_macro.or(from_scope_or_builtin).or(from_extern_prelude).or(from_prelude) 414 from_legacy_macro.or(from_scope_or_builtin).or(from_extern_prelude).or(from_prelude)
400 } 415 }
401 416
402 fn resolve_name_in_crate_root_or_extern_prelude(&self, name: &Name) -> PerNs { 417 fn resolve_name_in_crate_root_or_extern_prelude(
403 let from_crate_root = self[self.root].scope.get(name); 418 &self,
404 let from_extern_prelude = self.resolve_name_in_extern_prelude(name); 419 db: &dyn DefDatabase,
420 name: &Name,
421 ) -> PerNs {
422 let arc;
423 let crate_def_map = match self.block {
424 Some(_) => {
425 arc = self.crate_root(db).def_map(db);
426 &arc
427 }
428 None => self,
429 };
430 let from_crate_root = crate_def_map[crate_def_map.root].scope.get(name);
431 let from_extern_prelude = self.resolve_name_in_extern_prelude(db, name);
405 432
406 from_crate_root.or(from_extern_prelude) 433 from_crate_root.or(from_extern_prelude)
407 } 434 }
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
49impl ModPath { 49impl 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 {
167impl Path { 168impl 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;
6use std::sync::Arc; 6use std::sync::Arc;
7 7
8use either::Either; 8use either::Either;
9use hir_expand::{ 9use hir_expand::name::{name, AsName};
10 hygiene::Hygiene,
11 name::{name, AsName},
12};
13use syntax::ast::{self, AstNode, TypeBoundsOwner}; 10use syntax::ast::{self, AstNode, TypeBoundsOwner};
14 11
15use super::AssociatedTypeBinding; 12use 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.
26pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> { 23pub(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;
15use syntax::{algo, ast, AstNode, TextRange, TextSize}; 15use syntax::{algo, ast, AstNode, TextRange, TextSize};
16use test_utils::extract_annotations; 16use test_utils::extract_annotations;
17 17
18use crate::{db::DefDatabase, nameres::DefMap, src::HasSource, Lookup, ModuleDefId, ModuleId}; 18use 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.
3use hir_expand::name::Name; 3
4use hir_expand::{name::Name, AstId, InFile};
4use syntax::ast; 5use syntax::ast;
5 6
6use crate::{body::LowerCtx, path::Path}; 7use 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)]
73pub enum TypeRef { 75pub 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
117impl TypeRef { 120impl 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;