1 //! The type system. We currently use this to infer types for completion, hover
2 //! information and various assists.
3 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
4
5 #[allow(unused)]
6 macro_rules! eprintln {
7 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
8 }
9
10 mod builder;
11 mod chalk_db;
12 mod chalk_ext;
13 mod infer;
14 mod inhabitedness;
15 mod interner;
16 mod lower;
17 mod mapping;
18 mod tls;
19 mod utils;
20
21 pub mod autoderef;
22 pub mod consteval;
23 pub mod db;
24 pub mod diagnostics;
25 pub mod display;
26 pub mod lang_items;
27 pub mod layout;
28 pub mod method_resolution;
29 pub mod mir;
30 pub mod primitive;
31 pub mod traits;
32
33 #[cfg(test)]
34 mod tests;
35 #[cfg(test)]
36 mod test_db;
37
38 use std::{
39 collections::{hash_map::Entry, HashMap},
40 hash::Hash,
41 };
42
43 use chalk_ir::{
44 fold::{Shift, TypeFoldable},
45 interner::HasInterner,
46 visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor},
47 NoSolution, TyData,
48 };
49 use either::Either;
50 use hir_def::{hir::ExprId, type_ref::Rawness, GeneralConstId, TypeOrConstParamId};
51 use hir_expand::name;
52 use la_arena::{Arena, Idx};
53 use mir::{MirEvalError, VTableMap};
54 use rustc_hash::FxHashSet;
55 use traits::FnTrait;
56 use triomphe::Arc;
57 use utils::Generics;
58
59 use crate::{
60 consteval::unknown_const, db::HirDatabase, infer::unify::InferenceTable, utils::generics,
61 };
62
63 pub use autoderef::autoderef;
64 pub use builder::{ParamKind, TyBuilder};
65 pub use chalk_ext::*;
66 pub use infer::{
67 closure::{CaptureKind, CapturedItem},
68 could_coerce, could_unify, Adjust, Adjustment, AutoBorrow, BindingMode, InferenceDiagnostic,
69 InferenceResult, OverloadedDeref, PointerCast,
70 };
71 pub use interner::Interner;
72 pub use lower::{
73 associated_type_shorthand_candidates, CallableDefId, ImplTraitLoweringMode, TyDefId,
74 TyLoweringContext, ValueTyDefId,
75 };
76 pub use mapping::{
77 from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id, from_placeholder_idx,
78 lt_from_placeholder_idx, to_assoc_type_id, to_chalk_trait_id, to_foreign_def_id,
79 to_placeholder_idx,
80 };
81 pub use traits::TraitEnvironment;
82 pub use utils::{all_super_traits, is_fn_unsafe_to_call};
83
84 pub use chalk_ir::{
85 cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
86 };
87
88 pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
89 pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
90 pub type FnDefId = chalk_ir::FnDefId<Interner>;
91 pub type ClosureId = chalk_ir::ClosureId<Interner>;
92 pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
93 pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
94
95 pub type VariableKind = chalk_ir::VariableKind<Interner>;
96 pub type VariableKinds = chalk_ir::VariableKinds<Interner>;
97 pub type CanonicalVarKinds = chalk_ir::CanonicalVarKinds<Interner>;
98 /// Represents generic parameters and an item bound by them. When the item has parent, the binders
99 /// also contain the generic parameters for its parent. See chalk's documentation for details.
100 ///
101 /// One thing to keep in mind when working with `Binders` (and `Substitution`s, which represent
102 /// generic arguments) in rust-analyzer is that the ordering within *is* significant - the generic
103 /// parameters/arguments for an item MUST come before those for its parent. This is to facilitate
104 /// the integration with chalk-solve, which mildly puts constraints as such. See #13335 for its
105 /// motivation in detail.
106 pub type Binders<T> = chalk_ir::Binders<T>;
107 /// Interned list of generic arguments for an item. When an item has parent, the `Substitution` for
108 /// it contains generic arguments for both its parent and itself. See chalk's documentation for
109 /// details.
110 ///
111 /// See `Binders` for the constraint on the ordering.
112 pub type Substitution = chalk_ir::Substitution<Interner>;
113 pub type GenericArg = chalk_ir::GenericArg<Interner>;
114 pub type GenericArgData = chalk_ir::GenericArgData<Interner>;
115
116 pub type Ty = chalk_ir::Ty<Interner>;
117 pub type TyKind = chalk_ir::TyKind<Interner>;
118 pub type TypeFlags = chalk_ir::TypeFlags;
119 pub type DynTy = chalk_ir::DynTy<Interner>;
120 pub type FnPointer = chalk_ir::FnPointer<Interner>;
121 // pub type FnSubst = chalk_ir::FnSubst<Interner>;
122 pub use chalk_ir::FnSubst;
123 pub type ProjectionTy = chalk_ir::ProjectionTy<Interner>;
124 pub type AliasTy = chalk_ir::AliasTy<Interner>;
125 pub type OpaqueTy = chalk_ir::OpaqueTy<Interner>;
126 pub type InferenceVar = chalk_ir::InferenceVar;
127
128 pub type Lifetime = chalk_ir::Lifetime<Interner>;
129 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
130 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
131
132 pub type Const = chalk_ir::Const<Interner>;
133 pub type ConstData = chalk_ir::ConstData<Interner>;
134 pub type ConstValue = chalk_ir::ConstValue<Interner>;
135 pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>;
136
137 pub type ChalkTraitId = chalk_ir::TraitId<Interner>;
138 pub type TraitRef = chalk_ir::TraitRef<Interner>;
139 pub type QuantifiedWhereClause = Binders<WhereClause>;
140 pub type QuantifiedWhereClauses = chalk_ir::QuantifiedWhereClauses<Interner>;
141 pub type Canonical<T> = chalk_ir::Canonical<T>;
142
143 pub type FnSig = chalk_ir::FnSig<Interner>;
144
145 pub type InEnvironment<T> = chalk_ir::InEnvironment<T>;
146 pub type Environment = chalk_ir::Environment<Interner>;
147 pub type DomainGoal = chalk_ir::DomainGoal<Interner>;
148 pub type Goal = chalk_ir::Goal<Interner>;
149 pub type AliasEq = chalk_ir::AliasEq<Interner>;
150 pub type Solution = chalk_solve::Solution<Interner>;
151 pub type ConstrainedSubst = chalk_ir::ConstrainedSubst<Interner>;
152 pub type Guidance = chalk_solve::Guidance<Interner>;
153 pub type WhereClause = chalk_ir::WhereClause<Interner>;
154
155 /// A constant can have reference to other things. Memory map job is holding
156 /// the necessary bits of memory of the const eval session to keep the constant
157 /// meaningful.
158 #[derive(Debug, Default, Clone, PartialEq, Eq)]
159 pub struct MemoryMap {
160 pub memory: HashMap<usize, Vec<u8>>,
161 pub vtable: VTableMap,
162 }
163
164 impl MemoryMap {
insert(&mut self, addr: usize, x: Vec<u8>)165 fn insert(&mut self, addr: usize, x: Vec<u8>) {
166 match self.memory.entry(addr) {
167 Entry::Occupied(mut e) => {
168 if e.get().len() < x.len() {
169 e.insert(x);
170 }
171 }
172 Entry::Vacant(e) => {
173 e.insert(x);
174 }
175 }
176 }
177
178 /// This functions convert each address by a function `f` which gets the byte intervals and assign an address
179 /// to them. It is useful when you want to load a constant with a memory map in a new memory. You can pass an
180 /// allocator function as `f` and it will return a mapping of old addresses to new addresses.
transform_addresses( &self, mut f: impl FnMut(&[u8]) -> Result<usize, MirEvalError>, ) -> Result<HashMap<usize, usize>, MirEvalError>181 fn transform_addresses(
182 &self,
183 mut f: impl FnMut(&[u8]) -> Result<usize, MirEvalError>,
184 ) -> Result<HashMap<usize, usize>, MirEvalError> {
185 self.memory.iter().map(|x| Ok((*x.0, f(x.1)?))).collect()
186 }
187
get<'a>(&'a self, addr: usize, size: usize) -> Option<&'a [u8]>188 fn get<'a>(&'a self, addr: usize, size: usize) -> Option<&'a [u8]> {
189 if size == 0 {
190 Some(&[])
191 } else {
192 self.memory.get(&addr)?.get(0..size)
193 }
194 }
195 }
196
197 /// A concrete constant value
198 #[derive(Debug, Clone, PartialEq, Eq)]
199 pub enum ConstScalar {
200 Bytes(Vec<u8>, MemoryMap),
201 // FIXME: this is a hack to get around chalk not being able to represent unevaluatable
202 // constants
203 UnevaluatedConst(GeneralConstId, Substitution),
204 /// Case of an unknown value that rustc might know but we don't
205 // FIXME: this is a hack to get around chalk not being able to represent unevaluatable
206 // constants
207 // https://github.com/rust-lang/rust-analyzer/pull/8813#issuecomment-840679177
208 // https://rust-lang.zulipchat.com/#narrow/stream/144729-wg-traits/topic/Handling.20non.20evaluatable.20constants'.20equality/near/238386348
209 Unknown,
210 }
211
212 impl Hash for ConstScalar {
hash<H: std::hash::Hasher>(&self, state: &mut H)213 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
214 core::mem::discriminant(self).hash(state);
215 if let ConstScalar::Bytes(b, _) = self {
216 b.hash(state)
217 }
218 }
219 }
220
221 /// Return an index of a parameter in the generic type parameter list by it's id.
param_idx(db: &dyn HirDatabase, id: TypeOrConstParamId) -> Option<usize>222 pub fn param_idx(db: &dyn HirDatabase, id: TypeOrConstParamId) -> Option<usize> {
223 generics(db.upcast(), id.parent).param_idx(id)
224 }
225
wrap_empty_binders<T>(value: T) -> Binders<T> where T: TypeFoldable<Interner> + HasInterner<Interner = Interner>,226 pub(crate) fn wrap_empty_binders<T>(value: T) -> Binders<T>
227 where
228 T: TypeFoldable<Interner> + HasInterner<Interner = Interner>,
229 {
230 Binders::empty(Interner, value.shifted_in_from(Interner, DebruijnIndex::ONE))
231 }
232
make_type_and_const_binders<T: HasInterner<Interner = Interner>>( which_is_const: impl Iterator<Item = Option<Ty>>, value: T, ) -> Binders<T>233 pub(crate) fn make_type_and_const_binders<T: HasInterner<Interner = Interner>>(
234 which_is_const: impl Iterator<Item = Option<Ty>>,
235 value: T,
236 ) -> Binders<T> {
237 Binders::new(
238 VariableKinds::from_iter(
239 Interner,
240 which_is_const.map(|x| {
241 if let Some(ty) = x {
242 chalk_ir::VariableKind::Const(ty)
243 } else {
244 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General)
245 }
246 }),
247 ),
248 value,
249 )
250 }
251
make_single_type_binders<T: HasInterner<Interner = Interner>>( value: T, ) -> Binders<T>252 pub(crate) fn make_single_type_binders<T: HasInterner<Interner = Interner>>(
253 value: T,
254 ) -> Binders<T> {
255 Binders::new(
256 VariableKinds::from_iter(
257 Interner,
258 std::iter::once(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General)),
259 ),
260 value,
261 )
262 }
263
make_binders_with_count<T: HasInterner<Interner = Interner>>( db: &dyn HirDatabase, count: usize, generics: &Generics, value: T, ) -> Binders<T>264 pub(crate) fn make_binders_with_count<T: HasInterner<Interner = Interner>>(
265 db: &dyn HirDatabase,
266 count: usize,
267 generics: &Generics,
268 value: T,
269 ) -> Binders<T> {
270 let it = generics.iter_id().take(count).map(|id| match id {
271 Either::Left(_) => None,
272 Either::Right(id) => Some(db.const_param_ty(id)),
273 });
274 crate::make_type_and_const_binders(it, value)
275 }
276
make_binders<T: HasInterner<Interner = Interner>>( db: &dyn HirDatabase, generics: &Generics, value: T, ) -> Binders<T>277 pub(crate) fn make_binders<T: HasInterner<Interner = Interner>>(
278 db: &dyn HirDatabase,
279 generics: &Generics,
280 value: T,
281 ) -> Binders<T> {
282 make_binders_with_count(db, usize::MAX, generics, value)
283 }
284
285 // FIXME: get rid of this, just replace it by FnPointer
286 /// A function signature as seen by type inference: Several parameter types and
287 /// one return type.
288 #[derive(Clone, PartialEq, Eq, Debug)]
289 pub struct CallableSig {
290 params_and_return: Arc<[Ty]>,
291 is_varargs: bool,
292 safety: Safety,
293 }
294
295 has_interner!(CallableSig);
296
297 /// A polymorphic function signature.
298 pub type PolyFnSig = Binders<CallableSig>;
299
300 impl CallableSig {
from_params_and_return( mut params: Vec<Ty>, ret: Ty, is_varargs: bool, safety: Safety, ) -> CallableSig301 pub fn from_params_and_return(
302 mut params: Vec<Ty>,
303 ret: Ty,
304 is_varargs: bool,
305 safety: Safety,
306 ) -> CallableSig {
307 params.push(ret);
308 CallableSig { params_and_return: params.into(), is_varargs, safety }
309 }
310
from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig311 pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
312 CallableSig {
313 // FIXME: what to do about lifetime params? -> return PolyFnSig
314 // FIXME: use `Arc::from_iter` when it becomes available
315 params_and_return: Arc::from(
316 fn_ptr
317 .substitution
318 .clone()
319 .shifted_out_to(Interner, DebruijnIndex::ONE)
320 .expect("unexpected lifetime vars in fn ptr")
321 .0
322 .as_slice(Interner)
323 .iter()
324 .map(|arg| arg.assert_ty_ref(Interner).clone())
325 .collect::<Vec<_>>(),
326 ),
327 is_varargs: fn_ptr.sig.variadic,
328 safety: fn_ptr.sig.safety,
329 }
330 }
331
to_fn_ptr(&self) -> FnPointer332 pub fn to_fn_ptr(&self) -> FnPointer {
333 FnPointer {
334 num_binders: 0,
335 sig: FnSig { abi: (), safety: self.safety, variadic: self.is_varargs },
336 substitution: FnSubst(Substitution::from_iter(
337 Interner,
338 self.params_and_return.iter().cloned(),
339 )),
340 }
341 }
342
params(&self) -> &[Ty]343 pub fn params(&self) -> &[Ty] {
344 &self.params_and_return[0..self.params_and_return.len() - 1]
345 }
346
ret(&self) -> &Ty347 pub fn ret(&self) -> &Ty {
348 &self.params_and_return[self.params_and_return.len() - 1]
349 }
350 }
351
352 impl TypeFoldable<Interner> for CallableSig {
try_fold_with<E>( self, folder: &mut dyn chalk_ir::fold::FallibleTypeFolder<Interner, Error = E>, outer_binder: DebruijnIndex, ) -> Result<Self, E>353 fn try_fold_with<E>(
354 self,
355 folder: &mut dyn chalk_ir::fold::FallibleTypeFolder<Interner, Error = E>,
356 outer_binder: DebruijnIndex,
357 ) -> Result<Self, E> {
358 let vec = self.params_and_return.to_vec();
359 let folded = vec.try_fold_with(folder, outer_binder)?;
360 Ok(CallableSig {
361 params_and_return: folded.into(),
362 is_varargs: self.is_varargs,
363 safety: self.safety,
364 })
365 }
366 }
367
368 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
369 pub enum ImplTraitId {
370 ReturnTypeImplTrait(hir_def::FunctionId, RpitId),
371 AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
372 }
373
374 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
375 pub struct ReturnTypeImplTraits {
376 pub(crate) impl_traits: Arena<ReturnTypeImplTrait>,
377 }
378
379 has_interner!(ReturnTypeImplTraits);
380
381 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
382 pub struct ReturnTypeImplTrait {
383 pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
384 }
385
386 pub type RpitId = Idx<ReturnTypeImplTrait>;
387
static_lifetime() -> Lifetime388 pub fn static_lifetime() -> Lifetime {
389 LifetimeData::Static.intern(Interner)
390 }
391
fold_free_vars<T: HasInterner<Interner = Interner> + TypeFoldable<Interner>>( t: T, for_ty: impl FnMut(BoundVar, DebruijnIndex) -> Ty, for_const: impl FnMut(Ty, BoundVar, DebruijnIndex) -> Const, ) -> T392 pub(crate) fn fold_free_vars<T: HasInterner<Interner = Interner> + TypeFoldable<Interner>>(
393 t: T,
394 for_ty: impl FnMut(BoundVar, DebruijnIndex) -> Ty,
395 for_const: impl FnMut(Ty, BoundVar, DebruijnIndex) -> Const,
396 ) -> T {
397 use chalk_ir::fold::TypeFolder;
398
399 #[derive(chalk_derive::FallibleTypeFolder)]
400 #[has_interner(Interner)]
401 struct FreeVarFolder<
402 F1: FnMut(BoundVar, DebruijnIndex) -> Ty,
403 F2: FnMut(Ty, BoundVar, DebruijnIndex) -> Const,
404 >(F1, F2);
405 impl<
406 F1: FnMut(BoundVar, DebruijnIndex) -> Ty,
407 F2: FnMut(Ty, BoundVar, DebruijnIndex) -> Const,
408 > TypeFolder<Interner> for FreeVarFolder<F1, F2>
409 {
410 fn as_dyn(&mut self) -> &mut dyn TypeFolder<Interner, Error = Self::Error> {
411 self
412 }
413
414 fn interner(&self) -> Interner {
415 Interner
416 }
417
418 fn fold_free_var_ty(&mut self, bound_var: BoundVar, outer_binder: DebruijnIndex) -> Ty {
419 self.0(bound_var, outer_binder)
420 }
421
422 fn fold_free_var_const(
423 &mut self,
424 ty: Ty,
425 bound_var: BoundVar,
426 outer_binder: DebruijnIndex,
427 ) -> Const {
428 self.1(ty, bound_var, outer_binder)
429 }
430 }
431 t.fold_with(&mut FreeVarFolder(for_ty, for_const), DebruijnIndex::INNERMOST)
432 }
433
fold_tys<T: HasInterner<Interner = Interner> + TypeFoldable<Interner>>( t: T, mut for_ty: impl FnMut(Ty, DebruijnIndex) -> Ty, binders: DebruijnIndex, ) -> T434 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + TypeFoldable<Interner>>(
435 t: T,
436 mut for_ty: impl FnMut(Ty, DebruijnIndex) -> Ty,
437 binders: DebruijnIndex,
438 ) -> T {
439 fold_tys_and_consts(
440 t,
441 |x, d| match x {
442 Either::Left(x) => Either::Left(for_ty(x, d)),
443 Either::Right(x) => Either::Right(x),
444 },
445 binders,
446 )
447 }
448
fold_tys_and_consts<T: HasInterner<Interner = Interner> + TypeFoldable<Interner>>( t: T, f: impl FnMut(Either<Ty, Const>, DebruijnIndex) -> Either<Ty, Const>, binders: DebruijnIndex, ) -> T449 pub(crate) fn fold_tys_and_consts<T: HasInterner<Interner = Interner> + TypeFoldable<Interner>>(
450 t: T,
451 f: impl FnMut(Either<Ty, Const>, DebruijnIndex) -> Either<Ty, Const>,
452 binders: DebruijnIndex,
453 ) -> T {
454 use chalk_ir::fold::{TypeFolder, TypeSuperFoldable};
455 #[derive(chalk_derive::FallibleTypeFolder)]
456 #[has_interner(Interner)]
457 struct TyFolder<F: FnMut(Either<Ty, Const>, DebruijnIndex) -> Either<Ty, Const>>(F);
458 impl<F: FnMut(Either<Ty, Const>, DebruijnIndex) -> Either<Ty, Const>> TypeFolder<Interner>
459 for TyFolder<F>
460 {
461 fn as_dyn(&mut self) -> &mut dyn TypeFolder<Interner, Error = Self::Error> {
462 self
463 }
464
465 fn interner(&self) -> Interner {
466 Interner
467 }
468
469 fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Ty {
470 let ty = ty.super_fold_with(self.as_dyn(), outer_binder);
471 self.0(Either::Left(ty), outer_binder).left().unwrap()
472 }
473
474 fn fold_const(&mut self, c: Const, outer_binder: DebruijnIndex) -> Const {
475 self.0(Either::Right(c), outer_binder).right().unwrap()
476 }
477 }
478 t.fold_with(&mut TyFolder(f), binders)
479 }
480
481 /// 'Canonicalizes' the `t` by replacing any errors with new variables. Also
482 /// ensures there are no unbound variables or inference variables anywhere in
483 /// the `t`.
replace_errors_with_variables<T>(t: &T) -> Canonical<T> where T: HasInterner<Interner = Interner> + TypeFoldable<Interner> + Clone,484 pub fn replace_errors_with_variables<T>(t: &T) -> Canonical<T>
485 where
486 T: HasInterner<Interner = Interner> + TypeFoldable<Interner> + Clone,
487 {
488 use chalk_ir::{
489 fold::{FallibleTypeFolder, TypeSuperFoldable},
490 Fallible,
491 };
492 struct ErrorReplacer {
493 vars: usize,
494 }
495 impl FallibleTypeFolder<Interner> for ErrorReplacer {
496 type Error = NoSolution;
497
498 fn as_dyn(&mut self) -> &mut dyn FallibleTypeFolder<Interner, Error = Self::Error> {
499 self
500 }
501
502 fn interner(&self) -> Interner {
503 Interner
504 }
505
506 fn try_fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
507 if let TyKind::Error = ty.kind(Interner) {
508 let index = self.vars;
509 self.vars += 1;
510 Ok(TyKind::BoundVar(BoundVar::new(outer_binder, index)).intern(Interner))
511 } else {
512 ty.try_super_fold_with(self.as_dyn(), outer_binder)
513 }
514 }
515
516 fn try_fold_inference_ty(
517 &mut self,
518 _var: InferenceVar,
519 _kind: TyVariableKind,
520 _outer_binder: DebruijnIndex,
521 ) -> Fallible<Ty> {
522 if cfg!(debug_assertions) {
523 // we don't want to just panic here, because then the error message
524 // won't contain the whole thing, which would not be very helpful
525 Err(NoSolution)
526 } else {
527 Ok(TyKind::Error.intern(Interner))
528 }
529 }
530
531 fn try_fold_free_var_ty(
532 &mut self,
533 _bound_var: BoundVar,
534 _outer_binder: DebruijnIndex,
535 ) -> Fallible<Ty> {
536 if cfg!(debug_assertions) {
537 // we don't want to just panic here, because then the error message
538 // won't contain the whole thing, which would not be very helpful
539 Err(NoSolution)
540 } else {
541 Ok(TyKind::Error.intern(Interner))
542 }
543 }
544
545 fn try_fold_inference_const(
546 &mut self,
547 ty: Ty,
548 _var: InferenceVar,
549 _outer_binder: DebruijnIndex,
550 ) -> Fallible<Const> {
551 if cfg!(debug_assertions) {
552 Err(NoSolution)
553 } else {
554 Ok(unknown_const(ty))
555 }
556 }
557
558 fn try_fold_free_var_const(
559 &mut self,
560 ty: Ty,
561 _bound_var: BoundVar,
562 _outer_binder: DebruijnIndex,
563 ) -> Fallible<Const> {
564 if cfg!(debug_assertions) {
565 Err(NoSolution)
566 } else {
567 Ok(unknown_const(ty))
568 }
569 }
570
571 fn try_fold_inference_lifetime(
572 &mut self,
573 _var: InferenceVar,
574 _outer_binder: DebruijnIndex,
575 ) -> Fallible<Lifetime> {
576 if cfg!(debug_assertions) {
577 Err(NoSolution)
578 } else {
579 Ok(static_lifetime())
580 }
581 }
582
583 fn try_fold_free_var_lifetime(
584 &mut self,
585 _bound_var: BoundVar,
586 _outer_binder: DebruijnIndex,
587 ) -> Fallible<Lifetime> {
588 if cfg!(debug_assertions) {
589 Err(NoSolution)
590 } else {
591 Ok(static_lifetime())
592 }
593 }
594 }
595 let mut error_replacer = ErrorReplacer { vars: 0 };
596 let value = match t.clone().try_fold_with(&mut error_replacer, DebruijnIndex::INNERMOST) {
597 Ok(t) => t,
598 Err(_) => panic!("Encountered unbound or inference vars in {t:?}"),
599 };
600 let kinds = (0..error_replacer.vars).map(|_| {
601 chalk_ir::CanonicalVarKind::new(
602 chalk_ir::VariableKind::Ty(TyVariableKind::General),
603 chalk_ir::UniverseIndex::ROOT,
604 )
605 });
606 Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(Interner, kinds) }
607 }
608
callable_sig_from_fnonce( mut self_ty: &Ty, env: Arc<TraitEnvironment>, db: &dyn HirDatabase, ) -> Option<CallableSig>609 pub fn callable_sig_from_fnonce(
610 mut self_ty: &Ty,
611 env: Arc<TraitEnvironment>,
612 db: &dyn HirDatabase,
613 ) -> Option<CallableSig> {
614 if let Some((ty, _, _)) = self_ty.as_reference() {
615 // This will happen when it implements fn or fn mut, since we add a autoborrow adjustment
616 self_ty = ty;
617 }
618 let krate = env.krate;
619 let fn_once_trait = FnTrait::FnOnce.get_id(db, krate)?;
620 let output_assoc_type = db.trait_data(fn_once_trait).associated_type_by_name(&name![Output])?;
621
622 let mut table = InferenceTable::new(db, env);
623 let b = TyBuilder::trait_ref(db, fn_once_trait);
624 if b.remaining() != 2 {
625 return None;
626 }
627
628 // Register two obligations:
629 // - Self: FnOnce<?args_ty>
630 // - <Self as FnOnce<?args_ty>>::Output == ?ret_ty
631 let args_ty = table.new_type_var();
632 let trait_ref = b.push(self_ty.clone()).push(args_ty.clone()).build();
633 let projection = TyBuilder::assoc_type_projection(
634 db,
635 output_assoc_type,
636 Some(trait_ref.substitution.clone()),
637 )
638 .build();
639 table.register_obligation(trait_ref.cast(Interner));
640 let ret_ty = table.normalize_projection_ty(projection);
641
642 let ret_ty = table.resolve_completely(ret_ty);
643 let args_ty = table.resolve_completely(args_ty);
644
645 let params =
646 args_ty.as_tuple()?.iter(Interner).map(|it| it.assert_ty_ref(Interner)).cloned().collect();
647
648 Some(CallableSig::from_params_and_return(params, ret_ty, false, Safety::Safe))
649 }
650
651 struct PlaceholderCollector<'db> {
652 db: &'db dyn HirDatabase,
653 placeholders: FxHashSet<TypeOrConstParamId>,
654 }
655
656 impl PlaceholderCollector<'_> {
collect(&mut self, idx: PlaceholderIndex)657 fn collect(&mut self, idx: PlaceholderIndex) {
658 let id = from_placeholder_idx(self.db, idx);
659 self.placeholders.insert(id);
660 }
661 }
662
663 impl TypeVisitor<Interner> for PlaceholderCollector<'_> {
664 type BreakTy = ();
665
as_dyn(&mut self) -> &mut dyn TypeVisitor<Interner, BreakTy = Self::BreakTy>666 fn as_dyn(&mut self) -> &mut dyn TypeVisitor<Interner, BreakTy = Self::BreakTy> {
667 self
668 }
669
interner(&self) -> Interner670 fn interner(&self) -> Interner {
671 Interner
672 }
673
visit_ty( &mut self, ty: &Ty, outer_binder: DebruijnIndex, ) -> std::ops::ControlFlow<Self::BreakTy>674 fn visit_ty(
675 &mut self,
676 ty: &Ty,
677 outer_binder: DebruijnIndex,
678 ) -> std::ops::ControlFlow<Self::BreakTy> {
679 let has_placeholder_bits = TypeFlags::HAS_TY_PLACEHOLDER | TypeFlags::HAS_CT_PLACEHOLDER;
680 let TyData { kind, flags } = ty.data(Interner);
681
682 if let TyKind::Placeholder(idx) = kind {
683 self.collect(*idx);
684 } else if flags.intersects(has_placeholder_bits) {
685 return ty.super_visit_with(self, outer_binder);
686 } else {
687 // Fast path: don't visit inner types (e.g. generic arguments) when `flags` indicate
688 // that there are no placeholders.
689 }
690
691 std::ops::ControlFlow::Continue(())
692 }
693
visit_const( &mut self, constant: &chalk_ir::Const<Interner>, _outer_binder: DebruijnIndex, ) -> std::ops::ControlFlow<Self::BreakTy>694 fn visit_const(
695 &mut self,
696 constant: &chalk_ir::Const<Interner>,
697 _outer_binder: DebruijnIndex,
698 ) -> std::ops::ControlFlow<Self::BreakTy> {
699 if let chalk_ir::ConstValue::Placeholder(idx) = constant.data(Interner).value {
700 self.collect(idx);
701 }
702 std::ops::ControlFlow::Continue(())
703 }
704 }
705
706 /// Returns unique placeholders for types and consts contained in `value`.
collect_placeholders<T>(value: &T, db: &dyn HirDatabase) -> Vec<TypeOrConstParamId> where T: ?Sized + TypeVisitable<Interner>,707 pub fn collect_placeholders<T>(value: &T, db: &dyn HirDatabase) -> Vec<TypeOrConstParamId>
708 where
709 T: ?Sized + TypeVisitable<Interner>,
710 {
711 let mut collector = PlaceholderCollector { db, placeholders: FxHashSet::default() };
712 value.visit_with(&mut collector, DebruijnIndex::INNERMOST);
713 collector.placeholders.into_iter().collect()
714 }
715