Skip to content

Commit a776419

Browse files
committed
Auto merge of rust-lang#16123 - Veykril:simplify, r=Veykril
internal: Remove `ModuleId` from `TypeOwnerId` It only exists due to the IDE layer, but we can encode this temporary hack more cleanly
2 parents 34d572e + 9083017 commit a776419

File tree

11 files changed

+112
-45
lines changed

11 files changed

+112
-45
lines changed

crates/hir-def/src/generics.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -222,11 +222,10 @@ impl GenericParams {
222222
let module = loc.container.module(db);
223223
let func_data = db.function_data(id);
224224

225-
// Don't create an `Expander` nor call `loc.source(db)` if not needed since this
226-
// causes a reparse after the `ItemTree` has been created.
227-
let mut expander = Lazy::new(|| {
228-
(module.def_map(db), Expander::new(db, loc.source(db).file_id, module))
229-
});
225+
// Don't create an `Expander` if not needed since this
226+
// could cause a reparse after the `ItemTree` has been created due to the spanmap.
227+
let mut expander =
228+
Lazy::new(|| (module.def_map(db), Expander::new(db, loc.id.file_id(), module)));
230229
for param in func_data.params.iter() {
231230
generic_params.fill_implicit_impl_trait_args(db, &mut expander, param);
232231
}

crates/hir-def/src/item_tree.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,6 @@ impl ItemTree {
106106
pub(crate) fn file_item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<ItemTree> {
107107
let _p = profile::span("file_item_tree_query").detail(|| format!("{file_id:?}"));
108108
let syntax = db.parse_or_expand(file_id);
109-
if never!(syntax.kind() == SyntaxKind::ERROR, "{:?} from {:?} {}", file_id, syntax, syntax)
110-
{
111-
// FIXME: not 100% sure why these crop up, but return an empty tree to avoid a panic
112-
return Default::default();
113-
}
114109

115110
let ctx = lower::Ctx::new(db, file_id);
116111
let mut top_attrs = None;
@@ -129,6 +124,9 @@ impl ItemTree {
129124
ctx.lower_macro_stmts(stmts)
130125
},
131126
_ => {
127+
if never!(syntax.kind() == SyntaxKind::ERROR, "{:?} from {:?} {}", file_id, syntax, syntax) {
128+
return Default::default();
129+
}
132130
panic!("cannot create item tree for file {file_id:?} from {syntax:?} {syntax}");
133131
},
134132
}

crates/hir-def/src/lib.rs

+9-11
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,8 @@ pub struct ConstBlockLoc {
569569
pub root: hir::ExprId,
570570
}
571571

572+
/// Something that holds types, required for the current const arg lowering implementation as they
573+
/// need to be able to query where they are defined.
572574
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
573575
pub enum TypeOwnerId {
574576
FunctionId(FunctionId),
@@ -581,9 +583,6 @@ pub enum TypeOwnerId {
581583
TypeAliasId(TypeAliasId),
582584
ImplId(ImplId),
583585
EnumVariantId(EnumVariantId),
584-
// FIXME(const-generic-body): ModuleId should not be a type owner. This needs to be fixed to make `TypeOwnerId` actually
585-
// useful for assigning ids to in type consts.
586-
ModuleId(ModuleId),
587586
}
588587

589588
impl TypeOwnerId {
@@ -597,9 +596,7 @@ impl TypeOwnerId {
597596
TypeOwnerId::TypeAliasId(it) => GenericDefId::TypeAliasId(it),
598597
TypeOwnerId::ImplId(it) => GenericDefId::ImplId(it),
599598
TypeOwnerId::EnumVariantId(it) => GenericDefId::EnumVariantId(it),
600-
TypeOwnerId::InTypeConstId(_) | TypeOwnerId::ModuleId(_) | TypeOwnerId::StaticId(_) => {
601-
return None
602-
}
599+
TypeOwnerId::InTypeConstId(_) | TypeOwnerId::StaticId(_) => return None,
603600
})
604601
}
605602
}
@@ -614,8 +611,7 @@ impl_from!(
614611
TraitAliasId,
615612
TypeAliasId,
616613
ImplId,
617-
EnumVariantId,
618-
ModuleId
614+
EnumVariantId
619615
for TypeOwnerId
620616
);
621617

@@ -713,12 +709,15 @@ pub struct InTypeConstLoc {
713709
pub id: AstId<ast::ConstArg>,
714710
/// The thing this const arg appears in
715711
pub owner: TypeOwnerId,
716-
pub thing: Box<dyn OpaqueInternableThing>,
712+
// FIXME(const-generic-body): The expected type should not be
713+
pub expected_ty: Box<dyn OpaqueInternableThing>,
717714
}
718715

719716
impl PartialEq for InTypeConstLoc {
720717
fn eq(&self, other: &Self) -> bool {
721-
self.id == other.id && self.owner == other.owner && &*self.thing == &*other.thing
718+
self.id == other.id
719+
&& self.owner == other.owner
720+
&& &*self.expected_ty == &*other.expected_ty
722721
}
723722
}
724723

@@ -1041,7 +1040,6 @@ impl HasModule for TypeOwnerId {
10411040
TypeOwnerId::TypeAliasId(it) => it.lookup(db).module(db),
10421041
TypeOwnerId::ImplId(it) => it.lookup(db).container,
10431042
TypeOwnerId::EnumVariantId(it) => it.parent.lookup(db).container,
1044-
TypeOwnerId::ModuleId(it) => *it,
10451043
}
10461044
}
10471045
}

crates/hir-def/src/resolver.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,16 @@ impl Resolver {
589589
})
590590
}
591591

592+
pub fn type_owner(&self) -> Option<TypeOwnerId> {
593+
self.scopes().find_map(|scope| match scope {
594+
Scope::BlockScope(_) => None,
595+
&Scope::GenericParams { def, .. } => Some(def.into()),
596+
&Scope::ImplDefScope(id) => Some(id.into()),
597+
&Scope::AdtScope(adt) => Some(adt.into()),
598+
Scope::ExprScope(it) => Some(it.owner.into()),
599+
})
600+
}
601+
592602
pub fn impl_def(&self) -> Option<ImplId> {
593603
self.scopes().find_map(|scope| match scope {
594604
Scope::ImplDefScope(def) => Some(*def),
@@ -1079,7 +1089,6 @@ impl HasResolver for TypeOwnerId {
10791089
TypeOwnerId::TypeAliasId(it) => it.resolver(db),
10801090
TypeOwnerId::ImplId(it) => it.resolver(db),
10811091
TypeOwnerId::EnumVariantId(it) => it.resolver(db),
1082-
TypeOwnerId::ModuleId(it) => it.resolver(db),
10831092
}
10841093
}
10851094
}

crates/hir-expand/src/eager.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ pub fn expand_eager_macro_input(
8888
let loc = MacroCallLoc {
8989
def,
9090
krate,
91-
eager: Some(Box::new(EagerCallInfo { arg: Arc::new(subtree), arg_id, error: err.clone() })),
91+
eager: Some(Arc::new(EagerCallInfo { arg: Arc::new(subtree), arg_id, error: err.clone() })),
9292
kind: MacroCallKind::FnLike { ast_id: call_id, expand_to },
9393
call_site,
9494
};

crates/hir-expand/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ pub struct MacroCallLoc {
117117
pub krate: CrateId,
118118
/// Some if this is a macro call for an eager macro. Note that this is `None`
119119
/// for the eager input macro file.
120-
eager: Option<Box<EagerCallInfo>>,
120+
eager: Option<Arc<EagerCallInfo>>,
121121
pub kind: MacroCallKind,
122122
pub call_site: SyntaxContextId,
123123
}

crates/hir-ty/src/infer.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<Infer
113113
// FIXME(const-generic-body): We should not get the return type in this way.
114114
ctx.return_ty = c
115115
.lookup(db.upcast())
116-
.thing
116+
.expected_ty
117117
.box_any()
118118
.downcast::<InTypeConstIdMetadata>()
119119
.unwrap()

crates/hir-ty/src/lower.rs

+17-5
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ pub struct TyLoweringContext<'a> {
113113
pub db: &'a dyn HirDatabase,
114114
resolver: &'a Resolver,
115115
in_binders: DebruijnIndex,
116-
owner: TypeOwnerId,
116+
// FIXME: Should not be an `Option` but `Resolver` currently does not return owners in all cases
117+
// where expected
118+
owner: Option<TypeOwnerId>,
117119
/// Note: Conceptually, it's thinkable that we could be in a location where
118120
/// some type params should be represented as placeholders, and others
119121
/// should be converted to variables. I think in practice, this isn't
@@ -127,6 +129,14 @@ pub struct TyLoweringContext<'a> {
127129

128130
impl<'a> TyLoweringContext<'a> {
129131
pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver, owner: TypeOwnerId) -> Self {
132+
Self::new_maybe_unowned(db, resolver, Some(owner))
133+
}
134+
135+
pub fn new_maybe_unowned(
136+
db: &'a dyn HirDatabase,
137+
resolver: &'a Resolver,
138+
owner: Option<TypeOwnerId>,
139+
) -> Self {
130140
let impl_trait_mode = ImplTraitLoweringState::Disallowed;
131141
let type_param_mode = ParamLoweringMode::Placeholder;
132142
let in_binders = DebruijnIndex::INNERMOST;
@@ -213,10 +223,11 @@ impl<'a> TyLoweringContext<'a> {
213223
}
214224

215225
pub fn lower_const(&self, const_ref: &ConstRef, const_type: Ty) -> Const {
226+
let Some(owner) = self.owner else { return unknown_const(const_type) };
216227
const_or_path_to_chalk(
217228
self.db,
218229
self.resolver,
219-
self.owner,
230+
owner,
220231
const_type,
221232
const_ref,
222233
self.type_param_mode,
@@ -1768,10 +1779,11 @@ fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
17681779
let resolver = t.resolver(db.upcast());
17691780
let ctx = TyLoweringContext::new(db, &resolver, t.into())
17701781
.with_type_param_mode(ParamLoweringMode::Variable);
1771-
if db.type_alias_data(t).is_extern {
1782+
let type_alias_data = db.type_alias_data(t);
1783+
if type_alias_data.is_extern {
17721784
Binders::empty(Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(Interner))
17731785
} else {
1774-
let type_ref = &db.type_alias_data(t).type_ref;
1786+
let type_ref = &type_alias_data.type_ref;
17751787
let inner = ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error));
17761788
make_binders(db, &generics, inner)
17771789
}
@@ -2042,7 +2054,7 @@ pub(crate) fn const_or_path_to_chalk(
20422054
.intern_in_type_const(InTypeConstLoc {
20432055
id: it,
20442056
owner,
2045-
thing: Box::new(InTypeConstIdMetadata(expected_ty.clone())),
2057+
expected_ty: Box::new(InTypeConstIdMetadata(expected_ty.clone())),
20462058
})
20472059
.into();
20482060
intern_const_scalar(

crates/hir-ty/src/tests/incremental.rs

+61-11
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,10 @@ use super::visit_module;
99
fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
1010
let (mut db, pos) = TestDB::with_position(
1111
"
12-
//- /lib.rs
13-
fn foo() -> i32 {
14-
$01 + 1
15-
}
16-
",
12+
//- /lib.rs
13+
fn foo() -> i32 {
14+
$01 + 1
15+
}",
1716
);
1817
{
1918
let events = db.log_executed(|| {
@@ -27,12 +26,11 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
2726
}
2827

2928
let new_text = "
30-
fn foo() -> i32 {
31-
1
32-
+
33-
1
34-
}
35-
";
29+
fn foo() -> i32 {
30+
1
31+
+
32+
1
33+
}";
3634

3735
db.set_file_text(pos.file_id, Arc::from(new_text));
3836

@@ -47,3 +45,55 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
4745
assert!(!format!("{events:?}").contains("infer"), "{events:#?}")
4846
}
4947
}
48+
49+
#[test]
50+
fn typing_inside_a_function_should_not_invalidate_types_in_another() {
51+
let (mut db, pos) = TestDB::with_position(
52+
"
53+
//- /lib.rs
54+
fn foo() -> f32 {
55+
1.0 + 2.0
56+
}
57+
fn bar() -> i32 {
58+
$01 + 1
59+
}
60+
fn baz() -> i32 {
61+
1 + 1
62+
}",
63+
);
64+
{
65+
let events = db.log_executed(|| {
66+
let module = db.module_for_file(pos.file_id);
67+
let crate_def_map = module.def_map(&db);
68+
visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
69+
db.infer(def);
70+
});
71+
});
72+
assert!(format!("{events:?}").contains("infer"))
73+
}
74+
75+
let new_text = "
76+
fn foo() -> f32 {
77+
1.0 + 2.0
78+
}
79+
fn bar() -> i32 {
80+
53
81+
}
82+
fn baz() -> i32 {
83+
1 + 1
84+
}
85+
";
86+
87+
db.set_file_text(pos.file_id, Arc::from(new_text));
88+
89+
{
90+
let events = db.log_executed(|| {
91+
let module = db.module_for_file(pos.file_id);
92+
let crate_def_map = module.def_map(&db);
93+
visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
94+
db.infer(def);
95+
});
96+
});
97+
assert!(format!("{events:?}").matches("infer").count() == 1, "{events:#?}")
98+
}
99+
}

crates/hir/src/semantics.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -948,10 +948,10 @@ impl<'db> SemanticsImpl<'db> {
948948
pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
949949
let analyze = self.analyze(ty.syntax())?;
950950
let ctx = LowerCtx::with_file_id(self.db.upcast(), analyze.file_id);
951-
let ty = hir_ty::TyLoweringContext::new(
951+
let ty = hir_ty::TyLoweringContext::new_maybe_unowned(
952952
self.db,
953953
&analyze.resolver,
954-
analyze.resolver.module().into(),
954+
analyze.resolver.type_owner(),
955955
)
956956
.lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
957957
Some(Type::new_with_resolver(self.db, &analyze.resolver, ty))

crates/hir/src/source_analyzer.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1040,8 +1040,9 @@ fn resolve_hir_path_(
10401040
let types = || {
10411041
let (ty, unresolved) = match path.type_anchor() {
10421042
Some(type_ref) => {
1043-
let (_, res) = TyLoweringContext::new(db, resolver, resolver.module().into())
1044-
.lower_ty_ext(type_ref);
1043+
let (_, res) =
1044+
TyLoweringContext::new_maybe_unowned(db, resolver, resolver.type_owner())
1045+
.lower_ty_ext(type_ref);
10451046
res.map(|ty_ns| (ty_ns, path.segments().first()))
10461047
}
10471048
None => {

0 commit comments

Comments
 (0)