Skip to content

Commit 9c9c245

Browse files
authored
Merge pull request #21169 from Veykril/push-psyltyvxtpoz
internal: New style salsa infer query
2 parents 645e490 + e78e835 commit 9c9c245

File tree

27 files changed

+168
-126
lines changed

27 files changed

+168
-126
lines changed

src/tools/rust-analyzer/crates/hir-def/src/hir.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ pub type PatId = Idx<Pat>;
4545

4646
// FIXME: Encode this as a single u32, we won't ever reach all 32 bits especially given these counts
4747
// are local to the body.
48-
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
48+
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, salsa::Update)]
4949
pub enum ExprOrPatId {
5050
ExprId(ExprId),
5151
PatId(PatId),

src/tools/rust-analyzer/crates/hir-def/src/lib.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -600,17 +600,17 @@ impl HasModule for ModuleId {
600600
/// An ID of a module, **local** to a `DefMap`.
601601
pub type LocalModuleId = Idx<nameres::ModuleData>;
602602

603-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
603+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Update)]
604604
pub struct FieldId {
605605
// FIXME: Store this as an erased `salsa::Id` to save space
606606
pub parent: VariantId,
607607
pub local_id: LocalFieldId,
608608
}
609609

610-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
610+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Update)]
611611
pub struct TupleId(pub u32);
612612

613-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
613+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Update)]
614614
pub struct TupleFieldId {
615615
pub tuple: TupleId,
616616
pub index: u32,
@@ -1014,7 +1014,7 @@ impl From<VariantId> for AttrDefId {
10141014
}
10151015
}
10161016

1017-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa_macros::Supertype)]
1017+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa_macros::Supertype, salsa::Update)]
10181018
pub enum VariantId {
10191019
EnumVariantId(EnumVariantId),
10201020
StructId(StructId),

src/tools/rust-analyzer/crates/hir-ty/src/db.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use salsa::plumbing::AsId;
1212
use triomphe::Arc;
1313

1414
use crate::{
15-
ImplTraitId, InferenceResult, TraitEnvironment, TyDefId, ValueTyDefId,
15+
ImplTraitId, TraitEnvironment, TyDefId, ValueTyDefId,
1616
consteval::ConstEvalError,
1717
dyn_compatibility::DynCompatibilityViolation,
1818
layout::{Layout, LayoutError},
@@ -23,10 +23,6 @@ use crate::{
2323

2424
#[query_group::query_group]
2525
pub trait HirDatabase: DefDatabase + std::fmt::Debug {
26-
#[salsa::invoke(crate::infer::infer_query)]
27-
#[salsa::cycle(cycle_result = crate::infer::infer_cycle_result)]
28-
fn infer<'db>(&'db self, def: DefWithBodyId) -> Arc<InferenceResult<'db>>;
29-
3026
// region:mir
3127

3228
// FXME: Collapse `mir_body_for_closure` into `mir_body`

src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ impl BodyValidationDiagnostic {
7676
validate_lints: bool,
7777
) -> Vec<BodyValidationDiagnostic> {
7878
let _p = tracing::info_span!("BodyValidationDiagnostic::collect").entered();
79-
let infer = db.infer(owner);
79+
let infer = InferenceResult::for_body(db, owner);
8080
let body = db.body(owner);
8181
let env = db.trait_environment_for_body(owner);
8282
let interner = DbInterner::new_with(db, env.krate, env.block);
@@ -99,7 +99,7 @@ impl BodyValidationDiagnostic {
9999
struct ExprValidator<'db> {
100100
owner: DefWithBodyId,
101101
body: Arc<Body>,
102-
infer: Arc<InferenceResult<'db>>,
102+
infer: &'db InferenceResult<'db>,
103103
env: Arc<TraitEnvironment<'db>>,
104104
diagnostics: Vec<BodyValidationDiagnostic>,
105105
validate_lints: bool,
@@ -124,7 +124,7 @@ impl<'db> ExprValidator<'db> {
124124

125125
for (id, expr) in body.exprs() {
126126
if let Some((variant, missed_fields, true)) =
127-
record_literal_missing_fields(db, &self.infer, id, expr)
127+
record_literal_missing_fields(db, self.infer, id, expr)
128128
{
129129
self.diagnostics.push(BodyValidationDiagnostic::RecordMissingFields {
130130
record: Either::Left(id),
@@ -155,7 +155,7 @@ impl<'db> ExprValidator<'db> {
155155

156156
for (id, pat) in body.pats() {
157157
if let Some((variant, missed_fields, true)) =
158-
record_pattern_missing_fields(db, &self.infer, id, pat)
158+
record_pattern_missing_fields(db, self.infer, id, pat)
159159
{
160160
self.diagnostics.push(BodyValidationDiagnostic::RecordMissingFields {
161161
record: Either::Right(id),
@@ -240,7 +240,7 @@ impl<'db> ExprValidator<'db> {
240240
.as_reference()
241241
.map(|(match_expr_ty, ..)| match_expr_ty == pat_ty)
242242
.unwrap_or(false))
243-
&& types_of_subpatterns_do_match(arm.pat, &self.body, &self.infer)
243+
&& types_of_subpatterns_do_match(arm.pat, &self.body, self.infer)
244244
{
245245
// If we had a NotUsefulMatchArm diagnostic, we could
246246
// check the usefulness of each pattern as we added it
@@ -388,7 +388,7 @@ impl<'db> ExprValidator<'db> {
388388
pat: PatId,
389389
have_errors: &mut bool,
390390
) -> DeconstructedPat<'a, 'db> {
391-
let mut patcx = match_check::PatCtxt::new(self.db(), &self.infer, &self.body);
391+
let mut patcx = match_check::PatCtxt::new(self.db(), self.infer, &self.body);
392392
let pattern = patcx.lower_pattern(pat);
393393
let pattern = cx.lower_pat(&pattern);
394394
if !patcx.errors.is_empty() {

src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ pub fn missing_unsafe(db: &dyn HirDatabase, def: DefWithBodyId) -> MissingUnsafe
4242

4343
let mut res = MissingUnsafeResult { fn_is_unsafe: is_unsafe, ..MissingUnsafeResult::default() };
4444
let body = db.body(def);
45-
let infer = db.infer(def);
45+
let infer = InferenceResult::for_body(db, def);
4646
let mut callback = |diag| match diag {
4747
UnsafeDiagnostic::UnsafeOperation { node, inside_unsafe_block, reason } => {
4848
if inside_unsafe_block == InsideUnsafeBlock::No {
@@ -55,7 +55,7 @@ pub fn missing_unsafe(db: &dyn HirDatabase, def: DefWithBodyId) -> MissingUnsafe
5555
}
5656
}
5757
};
58-
let mut visitor = UnsafeVisitor::new(db, &infer, &body, def, &mut callback);
58+
let mut visitor = UnsafeVisitor::new(db, infer, &body, def, &mut callback);
5959
visitor.walk_expr(body.body_expr);
6060

6161
if !is_unsafe {

src/tools/rust-analyzer/crates/hir-ty/src/display.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ use stdx::never;
4747
use triomphe::Arc;
4848

4949
use crate::{
50-
CallableDefId, FnAbi, ImplTraitId, MemoryMap, TraitEnvironment, consteval,
50+
CallableDefId, FnAbi, ImplTraitId, InferenceResult, MemoryMap, TraitEnvironment, consteval,
5151
db::{HirDatabase, InternedClosure, InternedCoroutine},
5252
generics::generics,
5353
layout::Layout,
@@ -1398,7 +1398,7 @@ impl<'db> HirDisplay<'db> for Ty<'db> {
13981398
if let Some(sig) = sig {
13991399
let sig = sig.skip_binder();
14001400
let InternedClosure(def, _) = db.lookup_intern_closure(id);
1401-
let infer = db.infer(def);
1401+
let infer = InferenceResult::for_body(db, def);
14021402
let (_, kind) = infer.closure_info(id);
14031403
match f.closure_style {
14041404
ClosureStyle::ImplFn => write!(f, "impl {kind:?}(")?,

src/tools/rust-analyzer/crates/hir-ty/src/drop.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use stdx::never;
77
use triomphe::Arc;
88

99
use crate::{
10-
TraitEnvironment, consteval,
10+
InferenceResult, TraitEnvironment, consteval,
1111
method_resolution::TraitImpls,
1212
next_solver::{
1313
DbInterner, SimplifiedType, Ty, TyKind,
@@ -137,7 +137,7 @@ fn has_drop_glue_impl<'db>(
137137
TyKind::Slice(ty) => has_drop_glue_impl(infcx, ty, env, visited),
138138
TyKind::Closure(closure_id, subst) => {
139139
let owner = db.lookup_intern_closure(closure_id.0).0;
140-
let infer = db.infer(owner);
140+
let infer = InferenceResult::for_body(db, owner);
141141
let (captures, _) = infer.closure_info(closure_id.0);
142142
let env = db.trait_environment_for_body(owner);
143143
captures

src/tools/rust-analyzer/crates/hir-ty/src/infer.rs

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,10 @@ use rustc_type_ir::{
5454
AliasTyKind, TypeFoldable,
5555
inherent::{AdtDef, IntoKind, Region as _, SliceLike, Ty as _},
5656
};
57+
use salsa::Update;
5758
use span::Edition;
5859
use stdx::never;
5960
use thin_vec::ThinVec;
60-
use triomphe::Arc;
6161

6262
use crate::{
6363
ImplTraitId, IncorrectGenericsLenKind, PathLoweringDiagnostic, TargetFeatures,
@@ -95,7 +95,7 @@ use cast::{CastCheck, CastError};
9595
pub(crate) use closure::analysis::{CaptureKind, CapturedItem, CapturedItemWithoutTy};
9696

9797
/// The entry point of type inference.
98-
pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult<'_>> {
98+
fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> InferenceResult<'_> {
9999
let _p = tracing::info_span!("infer_query").entered();
100100
let resolver = def.resolver(db);
101101
let body = db.body(def);
@@ -159,17 +159,14 @@ pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<Infer
159159

160160
ctx.handle_opaque_type_uses();
161161

162-
Arc::new(ctx.resolve_all())
162+
ctx.resolve_all()
163163
}
164164

165-
pub(crate) fn infer_cycle_result(
166-
db: &dyn HirDatabase,
167-
_: DefWithBodyId,
168-
) -> Arc<InferenceResult<'_>> {
169-
Arc::new(InferenceResult {
165+
fn infer_cycle_result(db: &dyn HirDatabase, _: DefWithBodyId) -> InferenceResult<'_> {
166+
InferenceResult {
170167
has_errors: true,
171168
..InferenceResult::new(Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed))
172-
})
169+
}
173170
}
174171

175172
/// Binding modes inferred for patterns.
@@ -199,7 +196,7 @@ pub enum InferenceTyDiagnosticSource {
199196
Signature,
200197
}
201198

202-
#[derive(Debug, PartialEq, Eq, Clone)]
199+
#[derive(Debug, PartialEq, Eq, Clone, Update)]
203200
pub enum InferenceDiagnostic<'db> {
204201
NoSuchField {
205202
field: ExprOrPatId,
@@ -293,7 +290,7 @@ pub enum InferenceDiagnostic<'db> {
293290
}
294291

295292
/// A mismatch between an expected and an inferred type.
296-
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
293+
#[derive(Clone, PartialEq, Eq, Debug, Hash, Update)]
297294
pub struct TypeMismatch<'db> {
298295
pub expected: Ty<'db>,
299296
pub actual: Ty<'db>,
@@ -339,7 +336,7 @@ pub struct TypeMismatch<'db> {
339336
/// At some point, of course, `Box` should move out of the compiler, in which
340337
/// case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
341338
/// Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
342-
#[derive(Clone, Debug, PartialEq, Eq, Hash, TypeVisitable, TypeFoldable)]
339+
#[derive(Clone, Debug, PartialEq, Eq, Hash, TypeVisitable, TypeFoldable, Update)]
343340
pub struct Adjustment<'db> {
344341
#[type_visitable(ignore)]
345342
#[type_foldable(identity)]
@@ -476,9 +473,10 @@ pub enum PointerCast {
476473
/// When you add a field that stores types (including `Substitution` and the like), don't forget
477474
/// `resolve_completely()`'ing them in `InferenceContext::resolve_all()`. Inference variables must
478475
/// not appear in the final inference result.
479-
#[derive(Clone, PartialEq, Eq, Debug)]
476+
#[derive(Clone, PartialEq, Eq, Debug, Update)]
480477
pub struct InferenceResult<'db> {
481478
/// For each method call expr, records the function it resolves to.
479+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* expr id is technically update */)))]
482480
method_resolutions: FxHashMap<ExprId, (FunctionId, GenericArgs<'db>)>,
483481
/// For each field access expr, records the field it resolves to.
484482
field_resolutions: FxHashMap<ExprId, Either<FieldId, TupleFieldId>>,
@@ -489,15 +487,20 @@ pub struct InferenceResult<'db> {
489487
/// Whenever a tuple field expression access a tuple field, we allocate a tuple id in
490488
/// [`InferenceContext`] and store the tuples substitution there. This map is the reverse of
491489
/// that which allows us to resolve a [`TupleFieldId`]s type.
492-
tuple_field_access_types: FxHashMap<TupleId, Tys<'db>>,
490+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* thinvec is technically update */)))]
491+
tuple_field_access_types: ThinVec<Tys<'db>>,
493492

493+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* expr id is technically update */)))]
494494
pub(crate) type_of_expr: ArenaMap<ExprId, Ty<'db>>,
495495
/// For each pattern record the type it resolves to.
496496
///
497497
/// **Note**: When a pattern type is resolved it may still contain
498498
/// unresolved or missing subpatterns or subpatterns of mismatched types.
499+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* pat id is technically update */)))]
499500
pub(crate) type_of_pat: ArenaMap<PatId, Ty<'db>>,
501+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* binding id is technically update */)))]
500502
pub(crate) type_of_binding: ArenaMap<BindingId, Ty<'db>>,
503+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* type ref id is technically update */)))]
501504
pub(crate) type_of_type_placeholder: FxHashMap<TypeRefId, Ty<'db>>,
502505
pub(crate) type_of_opaque: FxHashMap<InternedOpaqueTyId, Ty<'db>>,
503506

@@ -508,14 +511,17 @@ pub struct InferenceResult<'db> {
508511
// Which will then mark this field.
509512
pub(crate) has_errors: bool,
510513
/// During inference this field is empty and [`InferenceContext::diagnostics`] is filled instead.
514+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* thinvec is technically update */)))]
511515
diagnostics: ThinVec<InferenceDiagnostic<'db>>,
512516

513517
/// Interned `Error` type to return references to.
514518
// FIXME: Remove this.
515519
error_ty: Ty<'db>,
516520

521+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* expr id is technically update */)))]
517522
pub(crate) expr_adjustments: FxHashMap<ExprId, Box<[Adjustment<'db>]>>,
518523
/// Stores the types which were implicitly dereferenced in pattern binding modes.
524+
#[update(unsafe(with(crate::utils::unsafe_update_eq /* pat id is technically update */)))]
519525
pub(crate) pat_adjustments: FxHashMap<PatId, Vec<Ty<'db>>>,
520526
/// Stores the binding mode (`ref` in `let ref x = 2`) of bindings.
521527
///
@@ -539,6 +545,14 @@ pub struct InferenceResult<'db> {
539545
pub(crate) coercion_casts: FxHashSet<ExprId>,
540546
}
541547

548+
#[salsa::tracked]
549+
impl<'db> InferenceResult<'db> {
550+
#[salsa::tracked(returns(ref), cycle_result = infer_cycle_result)]
551+
pub fn for_body(db: &'db dyn HirDatabase, def: DefWithBodyId) -> InferenceResult<'db> {
552+
infer_query(db, def)
553+
}
554+
}
555+
542556
impl<'db> InferenceResult<'db> {
543557
fn new(error_ty: Ty<'db>) -> Self {
544558
Self {
@@ -672,7 +686,7 @@ impl<'db> InferenceResult<'db> {
672686
}
673687

674688
pub fn tuple_field_access_type(&self, id: TupleId) -> Tys<'db> {
675-
self.tuple_field_access_types[&id]
689+
self.tuple_field_access_types[id.0 as usize]
676690
}
677691

678692
pub fn pat_adjustment(&self, id: PatId) -> Option<&[Ty<'db>]> {
@@ -1135,9 +1149,8 @@ impl<'body, 'db> InferenceContext<'body, 'db> {
11351149
pat_adjustments.shrink_to_fit();
11361150
result.tuple_field_access_types = tuple_field_accesses_rev
11371151
.into_iter()
1138-
.enumerate()
1139-
.map(|(idx, subst)| (TupleId(idx as u32), table.resolve_completely(subst)))
1140-
.inspect(|(_, subst)| {
1152+
.map(|subst| table.resolve_completely(subst))
1153+
.inspect(|subst| {
11411154
*has_errors = *has_errors || subst.iter().any(|ty| ty.references_non_lt_error());
11421155
})
11431156
.collect();

src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,10 @@ use crate::{
3131

3232
// The below functions handle capture and closure kind (Fn, FnMut, ..)
3333

34-
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
34+
#[derive(Debug, Clone, PartialEq, Eq, Hash, salsa::Update)]
3535
pub(crate) struct HirPlace<'db> {
3636
pub(crate) local: BindingId,
37-
pub(crate) projections: Vec<ProjectionElem<Infallible, Ty<'db>>>,
37+
pub(crate) projections: Vec<ProjectionElem<'db, Infallible>>,
3838
}
3939

4040
impl<'db> HirPlace<'db> {
@@ -76,7 +76,7 @@ pub enum CaptureKind {
7676
ByValue,
7777
}
7878

79-
#[derive(Debug, Clone, PartialEq, Eq)]
79+
#[derive(Debug, Clone, PartialEq, Eq, salsa::Update)]
8080
pub struct CapturedItem<'db> {
8181
pub(crate) place: HirPlace<'db>,
8282
pub(crate) kind: CaptureKind,
@@ -87,6 +87,7 @@ pub struct CapturedItem<'db> {
8787
/// copy all captures of the inner closure to the outer closure, and then we may
8888
/// truncate them, and we want the correct span to be reported.
8989
span_stacks: SmallVec<[SmallVec<[MirSpan; 3]>; 3]>,
90+
#[update(unsafe(with(crate::utils::unsafe_update_eq)))]
9091
pub(crate) ty: EarlyBinder<'db, Ty<'db>>,
9192
}
9293

src/tools/rust-analyzer/crates/hir-ty/src/layout.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use rustc_type_ir::{
2121
use triomphe::Arc;
2222

2323
use crate::{
24-
TraitEnvironment,
24+
InferenceResult, TraitEnvironment,
2525
consteval::try_const_usize,
2626
db::HirDatabase,
2727
next_solver::{
@@ -322,7 +322,7 @@ pub fn layout_of_ty_query<'db>(
322322
}
323323
TyKind::Closure(id, args) => {
324324
let def = db.lookup_intern_closure(id.0);
325-
let infer = db.infer(def.0);
325+
let infer = InferenceResult::for_body(db, def.0);
326326
let (captures, _) = infer.closure_info(id.0);
327327
let fields = captures
328328
.iter()

0 commit comments

Comments
 (0)