Skip to content

Commit e4f7f1e

Browse files
bors[bot]cynecx
andauthored
Merge #8462
8462: Expand macros at type position r=jonas-schievink a=cynecx Co-authored-by: cynecx <me@cynecx.net>
2 parents 3f1a220 + f0507ab commit e4f7f1e

File tree

16 files changed

+391
-76
lines changed

16 files changed

+391
-76
lines changed

crates/hir/src/semantics.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@ use std::{cell::RefCell, fmt, iter::successors};
66

77
use base_db::{FileId, FileRange};
88
use hir_def::{
9+
body,
910
resolver::{self, HasResolver, Resolver, TypeNs},
1011
AsMacroCall, FunctionId, TraitId, VariantId,
1112
};
12-
use hir_expand::{hygiene::Hygiene, name::AsName, ExpansionInfo};
13+
use hir_expand::{name::AsName, ExpansionInfo};
1314
use hir_ty::associated_type_shorthand_candidates;
1415
use itertools::Itertools;
1516
use rustc_hash::{FxHashMap, FxHashSet};
@@ -853,8 +854,8 @@ impl<'a> SemanticsScope<'a> {
853854
/// Resolve a path as-if it was written at the given scope. This is
854855
/// necessary a heuristic, as it doesn't take hygiene into account.
855856
pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
856-
let hygiene = Hygiene::new(self.db.upcast(), self.file_id);
857-
let path = Path::from_src(path.clone(), &hygiene)?;
857+
let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
858+
let path = Path::from_src(path.clone(), &ctx)?;
858859
resolve_hir_path(self.db, &self.resolver, &path)
859860
}
860861
}

crates/hir/src/source_analyzer.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::{iter::once, sync::Arc};
99

1010
use hir_def::{
1111
body::{
12+
self,
1213
scope::{ExprScopes, ScopeId},
1314
Body, BodySourceMap,
1415
},
@@ -202,8 +203,8 @@ impl SourceAnalyzer {
202203
db: &dyn HirDatabase,
203204
macro_call: InFile<&ast::MacroCall>,
204205
) -> Option<MacroDef> {
205-
let hygiene = Hygiene::new(db.upcast(), macro_call.file_id);
206-
let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
206+
let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
207+
let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
207208
self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
208209
}
209210

@@ -281,7 +282,9 @@ impl SourceAnalyzer {
281282
}
282283

283284
// 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)?;
285288

286289
// Case where path is a qualifier of another path, e.g. foo::bar::Baz where we
287290
// trying to resolve foo::bar.

crates/hir_def/src/body.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use profile::Count;
2121
use rustc_hash::FxHashMap;
2222
use syntax::{ast, AstNode, AstPtr};
2323

24-
pub(crate) use lower::LowerCtx;
24+
pub use lower::LowerCtx;
2525

2626
use crate::{
2727
attr::{Attrs, RawAttrs},
@@ -37,13 +37,15 @@ use crate::{
3737

3838
/// A subset of Expander that only deals with cfg attributes. We only need it to
3939
/// avoid cyclic queries in crate def map during enum processing.
40+
#[derive(Debug)]
4041
pub(crate) struct CfgExpander {
4142
cfg_options: CfgOptions,
4243
hygiene: Hygiene,
4344
krate: CrateId,
4445
}
4546

46-
pub(crate) struct Expander {
47+
#[derive(Debug)]
48+
pub struct Expander {
4749
cfg_expander: CfgExpander,
4850
def_map: Arc<DefMap>,
4951
current_file_id: HirFileId,
@@ -80,11 +82,7 @@ impl CfgExpander {
8082
}
8183

8284
impl Expander {
83-
pub(crate) fn new(
84-
db: &dyn DefDatabase,
85-
current_file_id: HirFileId,
86-
module: ModuleId,
87-
) -> Expander {
85+
pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
8886
let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
8987
let def_map = module.def_map(db);
9088
let ast_id_map = db.ast_id_map(current_file_id);
@@ -98,7 +96,7 @@ impl Expander {
9896
}
9997
}
10098

101-
pub(crate) fn enter_expand<T: ast::AstNode>(
99+
pub fn enter_expand<T: ast::AstNode>(
102100
&mut self,
103101
db: &dyn DefDatabase,
104102
macro_call: ast::MacroCall,
@@ -170,7 +168,7 @@ impl Expander {
170168
Ok(ExpandResult { value: Some((mark, node)), err })
171169
}
172170

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) {
174172
self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
175173
self.current_file_id = mark.file_id;
176174
self.ast_id_map = mem::take(&mut mark.ast_id_map);
@@ -190,8 +188,13 @@ impl Expander {
190188
&self.cfg_expander.cfg_options
191189
}
192190

191+
pub fn current_file_id(&self) -> HirFileId {
192+
self.current_file_id
193+
}
194+
193195
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)
195198
}
196199

197200
fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
@@ -204,7 +207,8 @@ impl Expander {
204207
}
205208
}
206209

207-
pub(crate) struct Mark {
210+
#[derive(Debug)]
211+
pub struct Mark {
208212
file_id: HirFileId,
209213
ast_id_map: Arc<AstIdMap>,
210214
bomb: DropBomb,

crates/hir_def/src/body/lower.rs

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
//! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
22
//! representation.
33
4-
use std::mem;
4+
use std::{mem, sync::Arc};
55

66
use either::Either;
77
use hir_expand::{
8+
ast_id_map::{AstIdMap, FileAstId},
89
hygiene::Hygiene,
910
name::{name, AsName, Name},
1011
ExpandError, HirFileId,
@@ -39,20 +40,39 @@ use crate::{
3940

4041
use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
4142

42-
pub(crate) struct LowerCtx {
43+
pub struct LowerCtx {
4344
hygiene: Hygiene,
45+
file_id: Option<HirFileId>,
46+
source_ast_id_map: Option<Arc<AstIdMap>>,
4447
}
4548

4649
impl LowerCtx {
47-
pub(crate) fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self {
48-
LowerCtx { hygiene: Hygiene::new(db.upcast(), file_id) }
50+
pub fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self {
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
4964
}
50-
pub(crate) fn with_hygiene(hygiene: &Hygiene) -> Self {
51-
LowerCtx { hygiene: hygiene.clone() }
65+
66+
pub(crate) fn file_id(&self) -> HirFileId {
67+
self.file_id.unwrap()
5268
}
5369

5470
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))
5676
}
5777
}
5878

crates/hir_def/src/item_tree.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,11 @@ impl ItemTree {
104104
// items and expanded during block DefMap computation
105105
return Default::default();
106106
},
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+
},
107112
ast::Expr(e) => {
108113
// Macros can expand to expressions. We return an empty item tree in this case, but
109114
// still need to collect inner items.

crates/hir_def/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,7 @@ impl<T: ast::AstNode> AstIdWithPath<T> {
688688
}
689689
}
690690

691+
#[derive(Debug)]
691692
pub struct UnresolvedMacro {
692693
pub path: ModPath,
693694
}

crates/hir_def/src/path.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ pub enum ImportAlias {
4848

4949
impl ModPath {
5050
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())
5253
}
5354

5455
pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath {
@@ -167,8 +168,8 @@ pub enum GenericArg {
167168
impl Path {
168169
/// Converts an `ast::Path` to `Path`. Works with use trees.
169170
/// It correctly handles `$crate` based path from macro call.
170-
pub fn from_src(path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
171-
lower::lower_path(path, hygiene)
171+
pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
172+
lower::lower_path(path, ctx)
172173
}
173174

174175
/// Converts a known mod path to `Path`.

crates/hir_def/src/path/lower.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@ use crate::intern::Interned;
66
use std::sync::Arc;
77

88
use either::Either;
9-
use hir_expand::{
10-
hygiene::Hygiene,
11-
name::{name, AsName},
12-
};
9+
use hir_expand::name::{name, AsName};
1310
use syntax::ast::{self, AstNode, TypeBoundsOwner};
1411

1512
use super::AssociatedTypeBinding;
@@ -23,12 +20,12 @@ pub(super) use lower_use::lower_use_tree;
2320

2421
/// Converts an `ast::Path` to `Path`. Works with use trees.
2522
/// 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> {
2724
let mut kind = PathKind::Plain;
2825
let mut type_anchor = None;
2926
let mut segments = Vec::new();
3027
let mut generic_args = Vec::new();
31-
let ctx = LowerCtx::with_hygiene(hygiene);
28+
let hygiene = ctx.hygiene();
3229
loop {
3330
let segment = path.segment()?;
3431

@@ -43,10 +40,10 @@ pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path>
4340
Either::Left(name) => {
4441
let args = segment
4542
.generic_arg_list()
46-
.and_then(|it| lower_generic_args(&ctx, it))
43+
.and_then(|it| lower_generic_args(ctx, it))
4744
.or_else(|| {
4845
lower_generic_args_from_fn_path(
49-
&ctx,
46+
ctx,
5047
segment.param_list(),
5148
segment.ret_type(),
5249
)
@@ -64,7 +61,7 @@ pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path>
6461
ast::PathSegmentKind::Type { type_ref, trait_ref } => {
6562
assert!(path.qualifier().is_none()); // this can only occur at the first segment
6663

67-
let self_type = TypeRef::from_ast(&ctx, type_ref?);
64+
let self_type = TypeRef::from_ast(ctx, type_ref?);
6865

6966
match trait_ref {
7067
// <T>::foo
@@ -74,7 +71,7 @@ pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path>
7471
}
7572
// <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo
7673
Some(trait_ref) => {
77-
let path = Path::from_src(trait_ref.path()?, hygiene)?;
74+
let path = Path::from_src(trait_ref.path()?, ctx)?;
7875
let mod_path = (*path.mod_path).clone();
7976
let num_segments = path.mod_path.segments.len();
8077
kind = mod_path.kind;

crates/hir_def/src/type_ref.rs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! HIR for references to types. Paths in these are not yet resolved. They can
22
//! 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};
45
use syntax::ast;
56

67
use crate::{body::LowerCtx, path::Path};
@@ -68,6 +69,7 @@ impl TraitRef {
6869
}
6970
}
7071
}
72+
7173
/// Compare ty::Ty
7274
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
7375
pub enum TypeRef {
@@ -84,6 +86,7 @@ pub enum TypeRef {
8486
// For
8587
ImplTrait(Vec<TypeBound>),
8688
DynTrait(Vec<TypeBound>),
89+
Macro(AstId<ast::MacroCall>),
8790
Error,
8891
}
8992

@@ -116,7 +119,7 @@ pub enum TypeBound {
116119

117120
impl TypeRef {
118121
/// 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 {
120123
match node {
121124
ast::Type::ParenType(inner) => TypeRef::from_ast_opt(&ctx, inner.ty()),
122125
ast::Type::TupleType(inner) => {
@@ -176,8 +179,13 @@ impl TypeRef {
176179
ast::Type::DynTraitType(inner) => {
177180
TypeRef::DynTrait(type_bounds_from_ast(ctx, inner.type_bound_list()))
178181
}
179-
// FIXME: Macros in type position are not yet supported.
180-
ast::Type::MacroType(_) => TypeRef::Error,
182+
ast::Type::MacroType(mt) => match mt.macro_call() {
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+
},
181189
}
182190
}
183191

@@ -215,7 +223,7 @@ impl TypeRef {
215223
}
216224
}
217225
TypeRef::Path(path) => go_path(path, f),
218-
TypeRef::Never | TypeRef::Placeholder | TypeRef::Error => {}
226+
TypeRef::Never | TypeRef::Placeholder | TypeRef::Macro(_) | TypeRef::Error => {}
219227
};
220228
}
221229

crates/hir_expand/src/db.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,7 @@ fn to_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind {
440440
MACRO_ITEMS | SOURCE_FILE => FragmentKind::Items,
441441
MACRO_STMTS => FragmentKind::Statements,
442442
MACRO_PAT => FragmentKind::Pattern,
443+
MACRO_TYPE => FragmentKind::Type,
443444
ITEM_LIST => FragmentKind::Items,
444445
LET_STMT => {
445446
// FIXME: Handle LHS Pattern

0 commit comments

Comments
 (0)