Skip to content

Commit ca4baa6

Browse files
committed
Use FileAstId<ast::Adt> in nameres where appropriate instead
1 parent 08adce6 commit ca4baa6

23 files changed

+98
-65
lines changed

crates/hir/src/lib.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -649,8 +649,12 @@ impl Module {
649649
let node = ast_id.to_node(db.upcast());
650650
ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
651651
}
652-
MacroCallKind::Derive { ast_id, .. }
653-
| MacroCallKind::Attr { ast_id, .. } => {
652+
MacroCallKind::Derive { ast_id, .. } => {
653+
// FIXME: point to the attribute instead, this creates very large diagnostics
654+
let node = ast_id.to_node(db.upcast());
655+
ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
656+
}
657+
MacroCallKind::Attr { ast_id, .. } => {
654658
// FIXME: point to the attribute instead, this creates very large diagnostics
655659
let node = ast_id.to_node(db.upcast());
656660
ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))

crates/hir/src/semantics.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
1818
use smallvec::{smallvec, SmallVec};
1919
use syntax::{
2020
algo::skip_trivia_token,
21-
ast::{self, HasAttrs, HasGenericParams, HasLoopBody},
21+
ast::{self, HasAttrs as _, HasGenericParams, HasLoopBody},
2222
match_ast, AstNode, AstToken, Direction, SyntaxElement, SyntaxNode, SyntaxNodePtr, SyntaxToken,
2323
TextSize, T,
2424
};
@@ -27,9 +27,9 @@ use crate::{
2727
db::HirDatabase,
2828
semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
2929
source_analyzer::{resolve_hir_path, SourceAnalyzer},
30-
Access, AssocItem, BuiltinAttr, Callable, ConstParam, Crate, Field, Function, HasSource,
31-
HirFileId, Impl, InFile, Label, LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path,
32-
ScopeDef, ToolModule, Trait, Type, TypeAlias, TypeParam, VariantDef,
30+
Access, AssocItem, BuiltinAttr, Callable, ConstParam, Crate, Field, Function, HasAttrs as _,
31+
HasSource, HirFileId, Impl, InFile, Label, LifetimeParam, Local, MacroDef, Module, ModuleDef,
32+
Name, Path, ScopeDef, ToolModule, Trait, Type, TypeAlias, TypeParam, VariantDef,
3333
};
3434

3535
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -486,7 +486,7 @@ impl<'db> SemanticsImpl<'db> {
486486
let adt = InFile::new(file_id, &adt);
487487
let src = InFile::new(file_id, attr.clone());
488488
self.with_ctx(|ctx| {
489-
let res = ctx.attr_to_derive_macro_call(adt, src)?;
489+
let (_, res) = ctx.attr_to_derive_macro_call(adt, src)?;
490490
Some(res.to_vec())
491491
})
492492
}
@@ -917,15 +917,14 @@ impl<'db> SemanticsImpl<'db> {
917917
let tt = derive.token_tree()?;
918918
let file = self.find_file(derive.syntax());
919919
let adt = derive.syntax().parent().and_then(ast::Adt::cast)?;
920-
920+
let adt_def = ToDef::to_def(self, file.with_value(adt.clone()))?;
921921
let res = self.with_ctx(|ctx| {
922-
let attr_def = ctx.attr_to_def(file.with_value(derive.clone()))?;
923-
let derives = ctx.attr_to_derive_macro_call(
922+
let (attr_id, derives) = ctx.attr_to_derive_macro_call(
924923
file.with_value(&adt),
925924
file.with_value(derive.clone()),
926925
)?;
927-
928-
let mut derive_paths = attr_def.parse_path_comma_token_tree()?;
926+
let attrs = adt_def.attrs(self.db);
927+
let mut derive_paths = attrs[attr_id].parse_path_comma_token_tree()?;
929928

930929
let derive_idx = tt
931930
.syntax()
@@ -1225,7 +1224,6 @@ to_def_impls![
12251224
(crate::Local, ast::SelfParam, self_param_to_def),
12261225
(crate::Label, ast::Label, label_to_def),
12271226
(crate::Adt, ast::Adt, adt_to_def),
1228-
(crate::Attr, ast::Attr, attr_to_def),
12291227
];
12301228

12311229
fn find_root(node: &SyntaxNode) -> SyntaxNode {

crates/hir/src/semantics/source_to_def.rs

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@
8787
8888
use base_db::FileId;
8989
use hir_def::{
90+
attr::AttrId,
9091
child_by_source::ChildBySource,
9192
dyn_map::DynMap,
9293
expr::{LabelId, PatId},
@@ -210,19 +211,6 @@ impl SourceToDefCtx<'_, '_> {
210211
ast::Adt::Union(it) => self.union_to_def(InFile::new(file_id, it)).map(AdtId::UnionId),
211212
}
212213
}
213-
pub(super) fn attr_to_def(
214-
&mut self,
215-
InFile { file_id, value }: InFile<ast::Attr>,
216-
) -> Option<crate::Attr> {
217-
// FIXME: Use dynmap?
218-
let adt = value.syntax().parent().and_then(ast::Adt::cast)?;
219-
let attr_pos = ast::HasAttrs::attrs(&adt).position(|it| it == value)?;
220-
let attrs = {
221-
let def = self.adt_to_def(InFile::new(file_id, adt))?;
222-
self.db.attrs(def.into())
223-
};
224-
attrs.get(attr_pos).cloned()
225-
}
226214
pub(super) fn bind_pat_to_def(
227215
&mut self,
228216
src: InFile<ast::IdentPat>,
@@ -254,16 +242,16 @@ impl SourceToDefCtx<'_, '_> {
254242

255243
pub(super) fn item_to_macro_call(&mut self, src: InFile<ast::Item>) -> Option<MacroCallId> {
256244
let map = self.dyn_map(src.as_ref())?;
257-
map[keys::ATTR_MACRO].get(&src).copied()
245+
map[keys::ATTR_MACRO_CALL].get(&src).copied()
258246
}
259247

260248
pub(super) fn attr_to_derive_macro_call(
261249
&mut self,
262250
item: InFile<&ast::Adt>,
263251
src: InFile<ast::Attr>,
264-
) -> Option<&[Option<MacroCallId>]> {
252+
) -> Option<(AttrId, &[Option<MacroCallId>])> {
265253
let map = self.dyn_map(item)?;
266-
map[keys::DERIVE_MACRO].get(&src).map(AsRef::as_ref)
254+
map[keys::DERIVE_MACRO_CALL].get(&src).map(|(id, ids)| (*id, &**ids))
267255
}
268256

269257
fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
@@ -328,7 +316,8 @@ impl SourceToDefCtx<'_, '_> {
328316
}
329317

330318
pub(super) fn macro_to_def(&mut self, src: InFile<ast::Macro>) -> Option<MacroDefId> {
331-
let makro = self.dyn_map(src.as_ref()).and_then(|it| it[keys::MACRO].get(&src).copied());
319+
let makro =
320+
self.dyn_map(src.as_ref()).and_then(|it| it[keys::MACRO_CALL].get(&src).copied());
332321
if let res @ Some(_) = makro {
333322
return res;
334323
}

crates/hir_def/src/child_by_source.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
77
use either::Either;
88
use hir_expand::HirFileId;
9-
use syntax::ast::HasAttrs;
9+
use syntax::ast::HasDocComments;
1010

1111
use crate::{
1212
db::DefDatabase,
@@ -110,7 +110,7 @@ impl ChildBySource for ItemScope {
110110
// FIXME: Do we need to add proc-macros into a PROCMACRO dynmap here?
111111
Either::Right(_fn) => return,
112112
};
113-
res[keys::MACRO].insert(src, makro);
113+
res[keys::MACRO_CALL].insert(src, makro);
114114
}
115115
});
116116
self.unnamed_consts().for_each(|konst| {
@@ -120,13 +120,16 @@ impl ChildBySource for ItemScope {
120120
self.impls().for_each(|imp| add_impl(db, file_id, res, imp));
121121
self.attr_macro_invocs().for_each(|(ast_id, call_id)| {
122122
let item = ast_id.with_value(ast_id.to_node(db.upcast()));
123-
res[keys::ATTR_MACRO].insert(item, call_id);
123+
res[keys::ATTR_MACRO_CALL].insert(item, call_id);
124124
});
125125
self.derive_macro_invocs().for_each(|(ast_id, calls)| {
126-
let item = ast_id.to_node(db.upcast());
126+
let adt = ast_id.to_node(db.upcast());
127127
for (attr_id, calls) in calls {
128-
if let Some(attr) = item.attrs().nth(attr_id.ast_index as usize) {
129-
res[keys::DERIVE_MACRO].insert(ast_id.with_value(attr), calls.into());
128+
if let Some(Either::Right(attr)) =
129+
adt.doc_comments_and_attrs().nth(attr_id.ast_index as usize)
130+
{
131+
res[keys::DERIVE_MACRO_CALL]
132+
.insert(ast_id.with_value(attr), (attr_id, calls.into()));
130133
}
131134
}
132135
});

crates/hir_def/src/item_scope.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ pub struct ItemScope {
6767
/// The derive macro invocations in this scope, keyed by the owner item over the actual derive attributes
6868
/// paired with the derive macro invocations for the specific attribute.
6969
derive_macros:
70-
FxHashMap<AstId<ast::Item>, SmallVec<[(AttrId, SmallVec<[Option<MacroCallId>; 1]>); 1]>>,
70+
FxHashMap<AstId<ast::Adt>, SmallVec<[(AttrId, SmallVec<[Option<MacroCallId>; 1]>); 1]>>,
7171
}
7272

7373
pub(crate) static BUILTIN_SCOPE: Lazy<FxHashMap<Name, PerNs>> = Lazy::new(|| {
@@ -204,12 +204,12 @@ impl ItemScope {
204204

205205
pub(crate) fn set_derive_macro_invoc(
206206
&mut self,
207-
item: AstId<ast::Item>,
207+
adt: AstId<ast::Adt>,
208208
call: MacroCallId,
209209
attr_id: AttrId,
210210
idx: usize,
211211
) {
212-
if let Some(derives) = self.derive_macros.get_mut(&item) {
212+
if let Some(derives) = self.derive_macros.get_mut(&adt) {
213213
if let Some((_, invocs)) = derives.iter_mut().find(|&&mut (id, _)| id == attr_id) {
214214
invocs[idx] = Some(call);
215215
}
@@ -221,17 +221,17 @@ impl ItemScope {
221221
/// independent of their indices.
222222
pub(crate) fn init_derive_attribute(
223223
&mut self,
224-
item: AstId<ast::Item>,
224+
adt: AstId<ast::Adt>,
225225
attr_id: AttrId,
226226
len: usize,
227227
) {
228-
self.derive_macros.entry(item).or_default().push((attr_id, smallvec![None; len]));
228+
self.derive_macros.entry(adt).or_default().push((attr_id, smallvec![None; len]));
229229
}
230230

231231
pub(crate) fn derive_macro_invocs(
232232
&self,
233233
) -> impl Iterator<
234-
Item = (AstId<ast::Item>, impl Iterator<Item = (AttrId, &[Option<MacroCallId>])>),
234+
Item = (AstId<ast::Adt>, impl Iterator<Item = (AttrId, &[Option<MacroCallId>])>),
235235
> + '_ {
236236
self.derive_macros
237237
.iter()

crates/hir_def/src/keys.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use rustc_hash::FxHashMap;
77
use syntax::{ast, AstNode, AstPtr};
88

99
use crate::{
10+
attr::AttrId,
1011
dyn_map::{DynMap, Policy},
1112
ConstId, ConstParamId, EnumId, EnumVariantId, FieldId, FunctionId, ImplId, LifetimeParamId,
1213
StaticId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId,
@@ -31,9 +32,9 @@ pub const TYPE_PARAM: Key<ast::TypeParam, TypeParamId> = Key::new();
3132
pub const LIFETIME_PARAM: Key<ast::LifetimeParam, LifetimeParamId> = Key::new();
3233
pub const CONST_PARAM: Key<ast::ConstParam, ConstParamId> = Key::new();
3334

34-
pub const MACRO: Key<ast::Macro, MacroDefId> = Key::new();
35-
pub const ATTR_MACRO: Key<ast::Item, MacroCallId> = Key::new();
36-
pub const DERIVE_MACRO: Key<ast::Attr, Box<[Option<MacroCallId>]>> = Key::new();
35+
pub const MACRO_CALL: Key<ast::Macro, MacroDefId> = Key::new();
36+
pub const ATTR_MACRO_CALL: Key<ast::Item, MacroCallId> = Key::new();
37+
pub const DERIVE_MACRO_CALL: Key<ast::Attr, (AttrId, Box<[Option<MacroCallId>]>)> = Key::new();
3738

3839
/// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are
3940
/// equal if they point to exactly the same object.

crates/hir_def/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -751,7 +751,7 @@ fn macro_call_as_call_id(
751751
}
752752

753753
fn derive_macro_as_call_id(
754-
item_attr: &AstIdWithPath<ast::Item>,
754+
item_attr: &AstIdWithPath<ast::Adt>,
755755
derive_attr: AttrId,
756756
db: &dyn db::DefDatabase,
757757
krate: CrateId,

crates/hir_def/src/nameres/collector.rs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::iter;
88
use base_db::{CrateId, Edition, FileId, ProcMacroId};
99
use cfg::{CfgExpr, CfgOptions};
1010
use hir_expand::{
11+
ast_id_map::FileAstId,
1112
builtin_attr_macro::find_builtin_attr,
1213
builtin_derive_macro::find_builtin_derive,
1314
builtin_fn_macro::find_builtin_macro,
@@ -30,8 +31,8 @@ use crate::{
3031
intern::Interned,
3132
item_scope::{ImportType, PerNsGlobImports},
3233
item_tree::{
33-
self, Fields, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, MacroCall, MacroDef,
34-
MacroRules, Mod, ModItem, ModKind, TreeId,
34+
self, Fields, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, ItemTreeNode, MacroCall,
35+
MacroDef, MacroRules, Mod, ModItem, ModKind, TreeId,
3536
},
3637
macro_call_as_call_id,
3738
nameres::{
@@ -217,7 +218,7 @@ struct MacroDirective {
217218
#[derive(Clone, Debug, Eq, PartialEq)]
218219
enum MacroDirectiveKind {
219220
FnLike { ast_id: AstIdWithPath<ast::MacroCall>, expand_to: ExpandTo },
220-
Derive { ast_id: AstIdWithPath<ast::Item>, derive_attr: AttrId, derive_pos: usize },
221+
Derive { ast_id: AstIdWithPath<ast::Adt>, derive_attr: AttrId, derive_pos: usize },
221222
Attr { ast_id: AstIdWithPath<ast::Item>, attr: Attr, mod_item: ModItem, tree: TreeId },
222223
}
223224

@@ -1129,8 +1130,11 @@ impl DefCollector<'_> {
11291130
) {
11301131
// Resolved to `#[derive]`
11311132

1132-
match mod_item {
1133-
ModItem::Struct(_) | ModItem::Union(_) | ModItem::Enum(_) => (),
1133+
let item_tree = tree.item_tree(self.db);
1134+
let ast_adt_id: FileAstId<ast::Adt> = match *mod_item {
1135+
ModItem::Struct(strukt) => item_tree[strukt].ast_id().upcast(),
1136+
ModItem::Union(union) => item_tree[union].ast_id().upcast(),
1137+
ModItem::Enum(enum_) => item_tree[enum_].ast_id().upcast(),
11341138
_ => {
11351139
let diag = DefDiagnostic::invalid_derive_target(
11361140
directive.module_id,
@@ -1140,7 +1144,8 @@ impl DefCollector<'_> {
11401144
self.def_map.diagnostics.push(diag);
11411145
return recollect_without(self);
11421146
}
1143-
}
1147+
};
1148+
let ast_id = ast_id.with_value(ast_adt_id);
11441149

11451150
match attr.parse_path_comma_token_tree() {
11461151
Some(derive_macros) => {
@@ -1274,7 +1279,7 @@ impl DefCollector<'_> {
12741279
if let Some(def) = def_map.exported_proc_macros.get(&loc.def) {
12751280
if let ProcMacroKind::CustomDerive { helpers } = &def.kind {
12761281
self.derive_helpers_in_scope
1277-
.entry(*ast_id)
1282+
.entry(ast_id.map(|it| it.upcast()))
12781283
.or_default()
12791284
.extend(helpers.iter().cloned());
12801285
}

crates/hir_def/src/nameres/diagnostics.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ pub enum DefDiagnosticKind {
3333

3434
InvalidDeriveTarget { ast: AstId<ast::Item>, id: u32 },
3535

36-
MalformedDerive { ast: AstId<ast::Item>, id: u32 },
36+
MalformedDerive { ast: AstId<ast::Adt>, id: u32 },
3737
}
3838

3939
#[derive(Debug, PartialEq, Eq)]
@@ -121,7 +121,7 @@ impl DefDiagnostic {
121121

122122
pub(super) fn malformed_derive(
123123
container: LocalModuleId,
124-
ast: AstId<ast::Item>,
124+
ast: AstId<ast::Adt>,
125125
id: AttrId,
126126
) -> Self {
127127
Self {

crates/hir_expand/src/lib.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ pub enum MacroCallKind {
121121
expand_to: ExpandTo,
122122
},
123123
Derive {
124-
ast_id: AstId<ast::Item>,
124+
ast_id: AstId<ast::Adt>,
125125
derive_name: Box<str>,
126126
/// Syntactical index of the invoking `#[derive]` attribute.
127127
///
@@ -328,11 +328,10 @@ impl MacroDefId {
328328
impl MacroCallKind {
329329
/// Returns the file containing the macro invocation.
330330
fn file_id(&self) -> HirFileId {
331-
match self {
332-
MacroCallKind::FnLike { ast_id, .. } => ast_id.file_id,
333-
MacroCallKind::Derive { ast_id, .. } | MacroCallKind::Attr { ast_id, .. } => {
334-
ast_id.file_id
335-
}
331+
match *self {
332+
MacroCallKind::FnLike { ast_id: InFile { file_id, .. }, .. }
333+
| MacroCallKind::Derive { ast_id: InFile { file_id, .. }, .. }
334+
| MacroCallKind::Attr { ast_id: InFile { file_id, .. }, .. } => file_id,
336335
}
337336
}
338337

@@ -341,7 +340,10 @@ impl MacroCallKind {
341340
MacroCallKind::FnLike { ast_id, .. } => {
342341
ast_id.with_value(ast_id.to_node(db).syntax().clone())
343342
}
344-
MacroCallKind::Derive { ast_id, .. } | MacroCallKind::Attr { ast_id, .. } => {
343+
MacroCallKind::Derive { ast_id, .. } => {
344+
ast_id.with_value(ast_id.to_node(db).syntax().clone())
345+
}
346+
MacroCallKind::Attr { ast_id, .. } => {
345347
ast_id.with_value(ast_id.to_node(db).syntax().clone())
346348
}
347349
}
@@ -352,9 +354,8 @@ impl MacroCallKind {
352354
MacroCallKind::FnLike { ast_id, .. } => {
353355
Some(ast_id.to_node(db).token_tree()?.syntax().clone())
354356
}
355-
MacroCallKind::Derive { ast_id, .. } | MacroCallKind::Attr { ast_id, .. } => {
356-
Some(ast_id.to_node(db).syntax().clone())
357-
}
357+
MacroCallKind::Derive { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
358+
MacroCallKind::Attr { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
358359
}
359360
}
360361

0 commit comments

Comments
 (0)