1#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
5#![allow(rustdoc::private_intra_doc_links)]
7
8extern crate ra_ap_rustc_abi as rustc_abi;
15extern crate ra_ap_rustc_ast_ir as rustc_ast_ir;
16extern crate ra_ap_rustc_index as rustc_index;
17extern crate ra_ap_rustc_next_trait_solver as rustc_next_trait_solver;
18extern crate ra_ap_rustc_type_ir as rustc_type_ir;
19
20extern crate self as hir_ty;
21
22pub mod builtin_derive;
23pub mod generics;
24mod infer;
25pub mod inhabitedness;
26mod lower;
27pub mod next_solver;
28mod opaques;
29mod representability;
30mod specialization;
31mod target_feature;
32pub mod utils;
33mod variance;
34
35pub mod autoderef;
36pub mod consteval;
37pub mod db;
38pub mod drop;
39pub mod dyn_compatibility;
40pub mod lang_items;
41pub mod layout;
42pub mod method_resolution;
43pub mod mir;
44pub mod primitive;
45pub mod solver_errors;
46pub mod traits;
47
48use std::{hash::Hash, ops::ControlFlow};
49
50use base_db::SourceDatabase;
51use hir_def::{
52 CallableDefId, ConstId, DefWithBodyId, EnumVariantId, ExpressionStoreOwnerId, FunctionId,
53 GenericDefId, HasModule, LifetimeParamId, ModuleId, StaticId, TypeAliasId, TypeOrConstParamId,
54 TypeParamId,
55 expr_store::{Body, ExpressionStore},
56 hir::{BindingId, ExprId, ExprOrPatId, ExprOrPatIdPacked, PatId},
57 resolver::{HasResolver, Resolver, TypeNs},
58 type_ref::{Rawness, TypeRefId},
59};
60use hir_expand::name::Name;
61use indexmap::{IndexMap, map::Entry};
62use macros::GenericTypeVisitable;
63use mir::{MirEvalError, VTableMap};
64use rustc_abi::ExternAbi;
65use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
66use rustc_type_ir::{
67 BoundVarIndexKind, TypeSuperVisitable, TypeVisitableExt,
68 inherent::{IntoKind, Ty as _},
69};
70use salsa::SalsaValue;
71use stdx::impl_from;
72use traits::FnTrait;
73
74use crate::{
75 db::{AnonConstId, HirDatabase},
76 lower::SupertraitsInfo,
77 next_solver::{
78 AliasTy, Binder, BoundConst, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, Canonical,
79 CanonicalVarKind, CanonicalVarKinds, ClauseKind, Const, ConstKind, DbInterner, GenericArgs,
80 PolyFnSig, Region, RegionKind, TraitRef, Ty, TyKind, TypingMode,
81 abi::Safety,
82 infer::{
83 DbInternerInferExt,
84 traits::{Obligation, ObligationCause},
85 },
86 obligation_ctxt::ObligationCtxt,
87 },
88};
89
90pub use autoderef::autoderef;
91pub use infer::{
92 Adjust, Adjustment, AutoBorrow, BindingMode, ByRef, ExplicitDropMethodUseKind,
93 InferenceDiagnostic, InferenceResult, OverloadedDeref, PointerCast, ReturnKind,
94 cast::CastError, could_coerce, could_unify, could_unify_deeply, infer_query_with_inspect,
95};
96pub use lower::{
97 FieldType, GenericDefaults, GenericDefaultsRef, GenericPredicates, LifetimeElisionKind,
98 LifetimeLoweringMode, LoweringMode, TyDefId, TyLoweringContext, TyLoweringInferVarsCtx,
99 TyLoweringResult, ValueTyDefId, diagnostics::*,
100};
101pub use next_solver::interner::{attach_db, attach_db_allow_change, with_attached_db};
102pub use target_feature::TargetFeatures;
103pub use traits::{ParamEnvAndCrate, check_orphan_rules};
104pub use utils::{
105 TargetFeatureIsSafeInTarget, Unsafety, all_super_traits, direct_super_traits,
106 is_fn_unsafe_to_call, target_feature_is_safe_in_target,
107};
108
109pub mod closure_analysis {
110 pub use crate::infer::{
111 CaptureInfo, CaptureSourceStack, CapturedPlace, ClosureData, UpvarCapture,
112 closure::analysis::{
113 BorrowKind,
114 expr_use_visitor::{FakeReadCause, Place, PlaceBase, Projection, ProjectionKind},
115 },
116 };
117}
118
119#[derive(Debug, Default, Clone, PartialEq, Eq, GenericTypeVisitable)]
123pub enum MemoryMap<'db> {
124 #[default]
125 Empty,
126 Simple(Box<[u8]>),
127 Complex(Box<ComplexMemoryMap<'db>>),
128}
129
130#[derive(Debug, Default, Clone, PartialEq, Eq, GenericTypeVisitable)]
131pub struct ComplexMemoryMap<'db> {
132 memory: IndexMap<usize, Box<[u8]>, FxBuildHasher>,
133 vtable: VTableMap<'db>,
134}
135
136impl ComplexMemoryMap<'_> {
137 fn insert(&mut self, addr: usize, val: Box<[u8]>) {
138 match self.memory.entry(addr) {
139 Entry::Occupied(mut e) => {
140 if e.get().len() < val.len() {
141 e.insert(val);
142 }
143 }
144 Entry::Vacant(e) => {
145 e.insert(val);
146 }
147 }
148 }
149}
150
151impl<'db> MemoryMap<'db> {
152 pub fn vtable_ty(&self, id: usize) -> Result<Ty<'db>, MirEvalError<'db>> {
153 match self {
154 MemoryMap::Empty | MemoryMap::Simple(_) => Err(MirEvalError::InvalidVTableId(id)),
155 MemoryMap::Complex(cm) => cm.vtable.ty(id),
156 }
157 }
158
159 fn simple(v: Box<[u8]>) -> Self {
160 MemoryMap::Simple(v)
161 }
162
163 fn transform_addresses(
167 &self,
168 mut f: impl FnMut(&[u8], usize) -> Result<usize, MirEvalError<'db>>,
169 ) -> Result<FxHashMap<usize, usize>, MirEvalError<'db>> {
170 let mut transform = |(addr, val): (&usize, &[u8])| {
171 let addr = *addr;
172 let align = if addr == 0 { 64 } else { (addr - (addr & (addr - 1))).min(64) };
173 f(val, align).map(|it| (addr, it))
174 };
175 match self {
176 MemoryMap::Empty => Ok(Default::default()),
177 MemoryMap::Simple(m) => transform((&0, m)).map(|(addr, val)| {
178 let mut map = FxHashMap::with_capacity_and_hasher(1, rustc_hash::FxBuildHasher);
179 map.insert(addr, val);
180 map
181 }),
182 MemoryMap::Complex(cm) => {
183 cm.memory.iter().map(|(addr, val)| transform((addr, val))).collect()
184 }
185 }
186 }
187
188 pub fn get(&self, addr: usize, size: usize) -> Option<&[u8]> {
189 if size == 0 {
190 Some(&[])
191 } else {
192 match self {
193 MemoryMap::Empty => Some(&[]),
194 MemoryMap::Simple(m) if addr == 0 => m.get(0..size),
195 MemoryMap::Simple(_) => None,
196 MemoryMap::Complex(cm) => cm.memory.get(&addr)?.get(0..size),
197 }
198 }
199 }
200}
201
202pub fn type_or_const_param_idx(db: &dyn HirDatabase, id: TypeOrConstParamId) -> u32 {
204 generics::generics(db, id.parent).type_or_const_param_idx(id)
205}
206
207pub fn lifetime_param_idx(db: &dyn HirDatabase, id: LifetimeParamId) -> u32 {
208 generics::generics(db, id.parent).lifetime_param_idx(id, false).0
209}
210
211#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
212pub enum ImplTraitId {
213 ReturnTypeImplTrait(hir_def::FunctionId, next_solver::ImplTraitIdx),
214 TypeAliasImplTrait(hir_def::TypeAliasId, next_solver::ImplTraitIdx),
215}
216
217pub fn replace_errors_with_variables<'db, T>(interner: DbInterner<'db>, t: &T) -> Canonical<'db, T>
221where
222 T: rustc_type_ir::TypeFoldable<DbInterner<'db>> + Clone,
223{
224 use rustc_type_ir::{FallibleTypeFolder, TypeSuperFoldable};
225 struct ErrorReplacer<'db> {
226 interner: DbInterner<'db>,
227 vars: Vec<CanonicalVarKind<'db>>,
228 binder: rustc_type_ir::DebruijnIndex,
229 }
230 impl<'db> FallibleTypeFolder<DbInterner<'db>> for ErrorReplacer<'db> {
231 #[cfg(debug_assertions)]
232 type Error = ();
233 #[cfg(not(debug_assertions))]
234 type Error = std::convert::Infallible;
235
236 fn cx(&self) -> DbInterner<'db> {
237 self.interner
238 }
239
240 fn try_fold_binder<T>(&mut self, t: Binder<'db, T>) -> Result<Binder<'db, T>, Self::Error>
241 where
242 T: rustc_type_ir::TypeFoldable<DbInterner<'db>>,
243 {
244 self.binder.shift_in(1);
245 let result = t.try_super_fold_with(self);
246 self.binder.shift_out(1);
247 result
248 }
249
250 fn try_fold_ty(&mut self, t: Ty<'db>) -> Result<Ty<'db>, Self::Error> {
251 if !t.has_type_flags(
252 rustc_type_ir::TypeFlags::HAS_ERROR
253 | rustc_type_ir::TypeFlags::HAS_TY_INFER
254 | rustc_type_ir::TypeFlags::HAS_CT_INFER
255 | rustc_type_ir::TypeFlags::HAS_RE_INFER,
256 ) {
257 return Ok(t);
258 }
259
260 #[cfg(debug_assertions)]
261 let error = || Err(());
262 #[cfg(not(debug_assertions))]
263 let error = || Ok(Ty::new_error(self.interner, crate::next_solver::ErrorGuaranteed));
264
265 match t.kind() {
266 TyKind::Error(_) => {
267 let var = rustc_type_ir::BoundVar::from_usize(self.vars.len());
268 self.vars.push(CanonicalVarKind::Ty {
269 ui: rustc_type_ir::UniverseIndex::ZERO,
270 sub_root: var,
271 });
272 Ok(Ty::new_bound(
273 self.interner,
274 self.binder,
275 BoundTy { var, kind: BoundTyKind::Anon },
276 ))
277 }
278 TyKind::Infer(_) => error(),
279 TyKind::Bound(BoundVarIndexKind::Bound(index), _) if index > self.binder => error(),
280 _ => t.try_super_fold_with(self),
281 }
282 }
283
284 fn try_fold_const(&mut self, ct: Const<'db>) -> Result<Const<'db>, Self::Error> {
285 if !ct.has_type_flags(
286 rustc_type_ir::TypeFlags::HAS_ERROR
287 | rustc_type_ir::TypeFlags::HAS_TY_INFER
288 | rustc_type_ir::TypeFlags::HAS_CT_INFER
289 | rustc_type_ir::TypeFlags::HAS_RE_INFER,
290 ) {
291 return Ok(ct);
292 }
293
294 #[cfg(debug_assertions)]
295 let error = || Err(());
296 #[cfg(not(debug_assertions))]
297 let error = || Ok(Const::error(self.interner));
298
299 match ct.kind() {
300 ConstKind::Error(_) => {
301 let var = rustc_type_ir::BoundVar::from_usize(self.vars.len());
302 self.vars.push(CanonicalVarKind::Const(rustc_type_ir::UniverseIndex::ZERO));
303 Ok(Const::new_bound(self.interner, self.binder, BoundConst::new(var)))
304 }
305 ConstKind::Infer(_) => error(),
306 ConstKind::Bound(BoundVarIndexKind::Bound(index), _) if index > self.binder => {
307 error()
308 }
309 _ => ct.try_super_fold_with(self),
310 }
311 }
312
313 fn try_fold_region(&mut self, region: Region<'db>) -> Result<Region<'db>, Self::Error> {
314 #[cfg(debug_assertions)]
315 let error = || Err(());
316 #[cfg(not(debug_assertions))]
317 let error = || Ok(Region::error(self.interner));
318
319 match region.kind() {
320 RegionKind::ReError(_) => {
321 let var = rustc_type_ir::BoundVar::from_usize(self.vars.len());
322 self.vars.push(CanonicalVarKind::Region(rustc_type_ir::UniverseIndex::ZERO));
323 Ok(Region::new_bound(
324 self.interner,
325 self.binder,
326 BoundRegion { var, kind: BoundRegionKind::Anon },
327 ))
328 }
329 RegionKind::ReVar(_) => error(),
330 RegionKind::ReBound(BoundVarIndexKind::Bound(index), _) if index > self.binder => {
331 error()
332 }
333 _ => Ok(region),
334 }
335 }
336 }
337
338 let mut error_replacer =
339 ErrorReplacer { vars: Vec::new(), binder: rustc_type_ir::DebruijnIndex::ZERO, interner };
340 let value = match t.clone().try_fold_with(&mut error_replacer) {
341 Ok(t) => t,
342 Err(_) => panic!("Encountered unbound or inference vars in {t:?}"),
343 };
344 Canonical {
345 value,
346 max_universe: rustc_type_ir::UniverseIndex::ZERO,
347 var_kinds: CanonicalVarKinds::new_from_slice(&error_replacer.vars),
348 }
349}
350
351pub fn associated_type_shorthand_candidates(
353 db: &dyn HirDatabase,
354 def: GenericDefId,
355 res: TypeNs,
356 mut cb: impl FnMut(&Name, TypeAliasId) -> bool,
357) -> Option<TypeAliasId> {
358 let interner = DbInterner::new_no_crate(db);
359 let (def, param) = match res {
360 TypeNs::GenericParam(param) => (def, param),
361 TypeNs::SelfType(impl_) => {
362 let impl_trait = db.impl_trait(impl_)?.skip_binder().def_id.0;
363 let param = TypeParamId::trait_self(impl_trait);
364 (impl_trait.into(), param)
365 }
366 _ => return None,
367 };
368
369 let mut dedup_map = FxHashSet::default();
370 let param_ty = Ty::new_param(interner, param, type_or_const_param_idx(db, param.into()));
371 let param_env = db.trait_environment(def);
373 for clause in param_env.clauses {
374 let ClauseKind::Trait(trait_clause) = clause.kind().skip_binder() else { continue };
375 if trait_clause.self_ty() != param_ty {
376 continue;
377 }
378 let trait_id = trait_clause.def_id().0;
379 dedup_map.extend(
380 SupertraitsInfo::query(db, trait_id)
381 .defined_assoc_types
382 .iter()
383 .map(|(name, id)| (name, *id)),
384 );
385 }
386
387 dedup_map
388 .into_iter()
389 .try_for_each(
390 |(name, id)| {
391 if cb(name, id) { ControlFlow::Break(id) } else { ControlFlow::Continue(()) }
392 },
393 )
394 .break_value()
395}
396
397pub fn callable_sig_from_fn_trait<'db>(
399 self_ty: Ty<'db>,
400 param_env: ParamEnvAndCrate<'db>,
401 db: &'db dyn HirDatabase,
402) -> Option<(FnTrait, PolyFnSig<'db>)> {
403 let ParamEnvAndCrate { param_env, krate } = param_env;
404 let interner = DbInterner::new_with(db, krate);
405 let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
406 let lang_items = interner.lang_items();
407 let cause = ObligationCause::dummy();
408
409 let impls_trait = |trait_: FnTrait| {
410 let mut ocx = ObligationCtxt::new(&infcx);
411 let tupled_args = infcx.next_ty_var(Span::Dummy);
412 let args = GenericArgs::new_from_slice(&[self_ty.into(), tupled_args.into()]);
413 let trait_id = trait_.get_id(lang_items)?;
414 let trait_ref = TraitRef::new_from_args(interner, trait_id.into(), args);
415 let obligation = Obligation::new(interner, cause, param_env, trait_ref);
416 ocx.register_obligation(obligation);
417 if !ocx.try_evaluate_obligations().is_empty() {
418 return None;
419 }
420 let tupled_args =
421 infcx.resolve_vars_if_possible(tupled_args).replace_infer_with_error(interner);
422 if tupled_args.is_tuple() { Some(tupled_args) } else { None }
423 };
424
425 let (trait_, args) = 'find_trait: {
426 for trait_ in [FnTrait::Fn, FnTrait::FnMut, FnTrait::FnOnce] {
427 if let Some(args) = impls_trait(trait_) {
428 break 'find_trait (trait_, args);
429 }
430 }
431 return None;
432 };
433
434 let output_assoc_type = lang_items.FnOnceOutput?;
435 let output_projection = Ty::new_alias(
436 interner,
437 AliasTy::new(
438 interner,
439 rustc_type_ir::Projection { def_id: output_assoc_type.into() },
440 [self_ty, args],
441 ),
442 );
443 let mut ocx = ObligationCtxt::new(&infcx);
444 let ret = ocx.structurally_normalize_ty(&cause, param_env, output_projection).ok()?;
445 let ret = ret.replace_infer_with_error(interner);
446
447 let sig = Binder::dummy(interner.mk_fn_sig(
448 args.tuple_fields(),
449 ret,
450 false,
451 Safety::Safe,
453 ExternAbi::Rust,
454 ));
455 Some((trait_, sig))
456}
457
458struct ParamCollector {
459 params: FxHashSet<TypeOrConstParamId>,
460}
461
462impl<'db> rustc_type_ir::TypeVisitor<DbInterner<'db>> for ParamCollector {
463 type Result = ();
464
465 fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
466 if let TyKind::Param(param) = ty.kind() {
467 self.params.insert(param.id.into());
468 }
469
470 ty.super_visit_with(self);
471 }
472
473 fn visit_const(&mut self, konst: Const<'db>) -> Self::Result {
474 if let ConstKind::Param(param) = konst.kind() {
475 self.params.insert(param.id.into());
476 }
477
478 konst.super_visit_with(self);
479 }
480}
481
482pub fn collect_params<'db, T>(value: &T) -> Vec<TypeOrConstParamId>
484where
485 T: ?Sized + rustc_type_ir::TypeVisitable<DbInterner<'db>>,
486{
487 let mut collector = ParamCollector { params: FxHashSet::default() };
488 value.visit_with(&mut collector);
489 Vec::from_iter(collector.params)
490}
491
492#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
498pub enum Span {
499 ExprId(ExprId),
500 PatId(PatId),
501 BindingId(BindingId),
502 TypeRefId(TypeRefId),
503 Dummy,
505}
506impl_from!(ExprId, PatId, BindingId, TypeRefId for Span);
507
508impl From<ExprOrPatIdPacked> for Span {
509 fn from(value: ExprOrPatIdPacked) -> Self {
510 match value.unpack() {
511 ExprOrPatId::ExprId(idx) => idx.into(),
512 ExprOrPatId::PatId(idx) => idx.into(),
513 }
514 }
515}
516
517impl Span {
518 pub(crate) fn pick_best(a: Span, b: Span) -> Span {
519 if b.is_dummy() { b } else { a }
521 }
522
523 #[inline]
524 pub fn is_dummy(&self) -> bool {
525 matches!(self, Self::Dummy)
526 }
527}
528
529#[derive(
531 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, salsa::Supertype, SalsaValue,
532)]
533pub enum InferBodyId<'db> {
534 DefWithBodyId(DefWithBodyId),
535 AnonConstId(AnonConstId<'db>),
536}
537impl_from!(
538 impl<'db>
539 DefWithBodyId(FunctionId, ConstId, StaticId),
540 AnonConstId<'db>
541 for InferBodyId<'db>
542);
543impl<'db> From<EnumVariantId> for InferBodyId<'db> {
544 fn from(id: EnumVariantId) -> Self {
545 InferBodyId::DefWithBodyId(DefWithBodyId::VariantId(id))
546 }
547}
548
549impl HasModule for InferBodyId<'_> {
550 fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
551 match self {
552 InferBodyId::DefWithBodyId(id) => id.module(db),
553 InferBodyId::AnonConstId(id) => id.module(db),
554 }
555 }
556}
557
558impl HasResolver for InferBodyId<'_> {
559 fn resolver(self, db: &dyn SourceDatabase) -> Resolver<'_> {
560 match self {
561 InferBodyId::DefWithBodyId(id) => id.resolver(db),
562 InferBodyId::AnonConstId(id) => id.resolver(db),
563 }
564 }
565}
566
567impl InferBodyId<'_> {
568 pub fn expression_store_owner(self, db: &dyn HirDatabase) -> ExpressionStoreOwnerId {
569 match self {
570 InferBodyId::DefWithBodyId(id) => id.into(),
571 InferBodyId::AnonConstId(id) => id.loc(db).owner,
572 }
573 }
574
575 pub fn generic_def(self, db: &dyn HirDatabase) -> GenericDefId {
576 match self {
577 InferBodyId::DefWithBodyId(id) => id.generic_def(db),
578 InferBodyId::AnonConstId(id) => id.loc(db).owner.generic_def(db),
579 }
580 }
581
582 #[inline]
583 pub fn as_function(self) -> Option<FunctionId> {
584 match self {
585 InferBodyId::DefWithBodyId(DefWithBodyId::FunctionId(it)) => Some(it),
586 _ => None,
587 }
588 }
589
590 #[inline]
591 pub fn as_variant(self) -> Option<EnumVariantId> {
592 match self {
593 InferBodyId::DefWithBodyId(DefWithBodyId::VariantId(it)) => Some(it),
594 _ => None,
595 }
596 }
597
598 pub fn store_and_root_expr(self, db: &dyn HirDatabase) -> (&ExpressionStore, ExprId) {
599 match self {
600 InferBodyId::DefWithBodyId(id) => {
601 let body = Body::of(db, id);
602 (body, body.root_expr())
603 }
604 InferBodyId::AnonConstId(id) => {
605 let loc = id.loc(db);
606 let store = ExpressionStore::of(db, loc.owner);
607 (store, loc.expr)
608 }
609 }
610 }
611}
612
613pub fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
614 use std::env;
615 use tracing_subscriber::{Registry, layer::SubscriberExt};
616 use tracing_tree::HierarchicalLayer;
617
618 let filter: tracing_subscriber::filter::Targets =
619 env::var("SOLVER_DEBUG").ok().and_then(|it| it.parse().ok()).unwrap_or_default();
620 let layer = HierarchicalLayer::default()
621 .with_indent_lines(true)
622 .with_ansi(false)
623 .with_indent_amount(2)
624 .with_writer(std::io::stderr);
625 let subscriber = Registry::default().with(filter).with(layer);
626 Some(tracing::subscriber::set_default(subscriber))
627}