X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=crates%2Fhir_ty%2Fsrc%2Flower.rs;h=9e69785ac29c4b4ecae51b574784be3cdc551c2d;hb=b301b040f5781a9083348936369a01c37138756f;hp=7373c9eb8b4b84c143f25cabd295c0abe91b9137;hpb=40159150aa89b11965fcbebb007d83d76d2f3db3;p=rust.git diff --git a/crates/hir_ty/src/lower.rs b/crates/hir_ty/src/lower.rs index 7373c9eb8b4..9e69785ac29 100644 --- a/crates/hir_ty/src/lower.rs +++ b/crates/hir_ty/src/lower.rs @@ -9,8 +9,11 @@ use std::{iter, sync::Arc}; use base_db::CrateId; -use chalk_ir::{cast::Cast, fold::Shift, interner::HasInterner, Mutability, Safety}; +use chalk_ir::{cast::Cast, fold::Shift, Mutability, Safety}; +use hir_def::generics::TypeOrConstParamData; use hir_def::intern::Interned; +use hir_def::path::{ModPath, PathKind}; +use hir_def::type_ref::ConstScalarOrPath; use hir_def::{ adt::StructKind, body::{Expander, LowerCtx}, @@ -19,26 +22,29 @@ path::{GenericArg, Path, PathSegment, PathSegments}, resolver::{HasResolver, Resolver, TypeNs}, type_ref::{TraitBoundModifier, TraitRef as HirTraitRef, TypeBound, TypeRef}, - AdtId, AssocItemId, ConstId, ConstParamId, EnumId, EnumVariantId, FunctionId, GenericDefId, - HasModule, ImplId, ItemContainerId, LocalFieldId, Lookup, StaticId, StructId, TraitId, - TypeAliasId, TypeParamId, UnionId, VariantId, + AdtId, AssocItemId, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, + ImplId, ItemContainerId, LocalFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, + UnionId, VariantId, }; +use hir_def::{ConstParamId, TypeOrConstParamId, TypeParamId}; use hir_expand::{name::Name, ExpandResult}; +use itertools::Either; use la_arena::ArenaMap; use rustc_hash::FxHashSet; use smallvec::SmallVec; -use stdx::impl_from; +use stdx::{impl_from, never}; use syntax::{ast, SmolStr}; -use crate::all_super_traits; +use crate::consteval::{path_to_const, unknown_const_as_generic, unknown_const_usize, usize_const}; +use crate::method_resolution::fallback_bound_vars; +use crate::utils::Generics; +use crate::{all_super_traits, make_binders, Const, GenericArgData, ParamKind}; use crate::{ consteval, db::HirDatabase, mapping::ToChalk, static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx, - utils::{ - all_super_trait_refs, associated_type_by_name_including_super_traits, generics, Generics, - }, + utils::{all_super_trait_refs, associated_type_by_name_including_super_traits, generics}, AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig, FnSubst, ImplTraitId, Interner, PolyFnSig, ProjectionTy, QuantifiedWhereClause, QuantifiedWhereClauses, ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution, @@ -54,7 +60,7 @@ pub struct TyLoweringContext<'a> { /// some type params should be represented as placeholders, and others /// should be converted to variables. I think in practice, this isn't /// possible currently, so this should be fine for now. - pub type_param_mode: TypeParamLoweringMode, + pub type_param_mode: ParamLoweringMode, pub impl_trait_mode: ImplTraitLoweringMode, impl_trait_counter: Cell, /// When turning `impl Trait` into opaque types, we have to collect the @@ -75,7 +81,7 @@ impl<'a> TyLoweringContext<'a> { pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self { let impl_trait_counter = Cell::new(0); let impl_trait_mode = ImplTraitLoweringMode::Disallowed; - let type_param_mode = TypeParamLoweringMode::Placeholder; + let type_param_mode = ParamLoweringMode::Placeholder; let in_binders = DebruijnIndex::INNERMOST; let opaque_type_data = RefCell::new(Vec::new()); Self { @@ -127,7 +133,7 @@ pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Sel Self { impl_trait_mode, ..self } } - pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self { + pub fn with_type_param_mode(self, type_param_mode: ParamLoweringMode) -> Self { Self { type_param_mode, ..self } } } @@ -153,7 +159,7 @@ pub enum ImplTraitLoweringMode { } #[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum TypeParamLoweringMode { +pub enum ParamLoweringMode { Placeholder, Variable, } @@ -163,14 +169,23 @@ pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty { self.lower_ty_ext(type_ref).0 } + fn generics(&self) -> Generics { + generics( + self.db.upcast(), + self.resolver + .generic_def() + .expect("there should be generics if there's a generic param"), + ) + } + pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { let mut res = None; let ty = match type_ref { - TypeRef::Never => TyKind::Never.intern(&Interner), + TypeRef::Never => TyKind::Never.intern(Interner), TypeRef::Tuple(inner) => { let inner_tys = inner.iter().map(|tr| self.lower_ty(tr)); - TyKind::Tuple(inner_tys.len(), Substitution::from_iter(&Interner, inner_tys)) - .intern(&Interner) + TyKind::Tuple(inner_tys.len(), Substitution::from_iter(Interner, inner_tys)) + .intern(Interner) } TypeRef::Path(path) => { let (ty, res_) = self.lower_path(path); @@ -179,48 +194,54 @@ pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { } TypeRef::RawPtr(inner, mutability) => { let inner_ty = self.lower_ty(inner); - TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner) + TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(Interner) } TypeRef::Array(inner, len) => { let inner_ty = self.lower_ty(inner); + let const_len = const_or_path_to_chalk( + self.db, + self.resolver, + len, + self.type_param_mode, + || self.generics(), + DebruijnIndex::INNERMOST, + ); - let const_len = consteval::usize_const(len.as_usize()); - - TyKind::Array(inner_ty, const_len).intern(&Interner) + TyKind::Array(inner_ty, const_len).intern(Interner) } TypeRef::Slice(inner) => { let inner_ty = self.lower_ty(inner); - TyKind::Slice(inner_ty).intern(&Interner) + TyKind::Slice(inner_ty).intern(Interner) } TypeRef::Reference(inner, _, mutability) => { let inner_ty = self.lower_ty(inner); let lifetime = static_lifetime(); TyKind::Ref(lower_to_chalk_mutability(*mutability), lifetime, inner_ty) - .intern(&Interner) + .intern(Interner) } - TypeRef::Placeholder => TyKind::Error.intern(&Interner), + TypeRef::Placeholder => TyKind::Error.intern(Interner), TypeRef::Fn(params, is_varargs) => { let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { - Substitution::from_iter(&Interner, params.iter().map(|tr| ctx.lower_ty(tr))) + Substitution::from_iter(Interner, params.iter().map(|(_, tr)| ctx.lower_ty(tr))) }); TyKind::Function(FnPointer { num_binders: 0, // FIXME lower `for<'a> fn()` correctly sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs }, substitution: FnSubst(substs), }) - .intern(&Interner) + .intern(Interner) } TypeRef::DynTrait(bounds) => { let self_ty = - TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner); + TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(Interner); let bounds = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { QuantifiedWhereClauses::from_iter( - &Interner, + Interner, bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)), ) }); - let bounds = crate::make_only_type_binders(1, bounds); - TyKind::Dyn(DynTy { bounds, lifetime: static_lifetime() }).intern(&Interner) + let bounds = crate::make_single_type_binders(bounds); + TyKind::Dyn(DynTy { bounds, lifetime: static_lifetime() }).intern(Interner) } TypeRef::ImplTrait(bounds) => { match self.impl_trait_mode { @@ -237,7 +258,7 @@ pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { // place even if we encounter more opaque types while // lowering the bounds self.opaque_type_data.borrow_mut().push(ReturnTypeImplTrait { - bounds: crate::make_only_type_binders(1, Vec::new()), + bounds: crate::make_single_type_binders(Vec::new()), }); // We don't want to lower the bounds inside the binders // we're currently in, because they don't end up inside @@ -257,8 +278,8 @@ pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx); let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into(); let generics = generics(self.db.upcast(), func.into()); - let parameters = generics.bound_vars_subst(self.in_binders); - TyKind::OpaqueType(opaque_ty_id, parameters).intern(&Interner) + let parameters = generics.bound_vars_subst(self.db, self.in_binders); + TyKind::OpaqueType(opaque_ty_id, parameters).intern(Interner) } ImplTraitLoweringMode::Param => { let idx = self.impl_trait_counter.get(); @@ -267,7 +288,7 @@ pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { if let Some(def) = self.resolver.generic_def() { let generics = generics(self.db.upcast(), def); let param = generics - .iter() + .type_iter() .filter(|(_, data)| { data.provenance == TypeParamProvenance::ArgumentImplTrait }) @@ -275,31 +296,36 @@ pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { .map_or(TyKind::Error, |(id, _)| { TyKind::Placeholder(to_placeholder_idx(self.db, id)) }); - param.intern(&Interner) + param.intern(Interner) } else { - TyKind::Error.intern(&Interner) + TyKind::Error.intern(Interner) } } ImplTraitLoweringMode::Variable => { let idx = self.impl_trait_counter.get(); // FIXME we're probably doing something wrong here self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16); - let (parent_params, self_params, list_params, _impl_trait_params) = - if let Some(def) = self.resolver.generic_def() { - let generics = generics(self.db.upcast(), def); - generics.provenance_split() - } else { - (0, 0, 0, 0) - }; + let ( + parent_params, + self_params, + list_params, + const_params, + _impl_trait_params, + ) = if let Some(def) = self.resolver.generic_def() { + let generics = generics(self.db.upcast(), def); + generics.provenance_split() + } else { + (0, 0, 0, 0, 0) + }; TyKind::BoundVar(BoundVar::new( self.in_binders, - idx as usize + parent_params + self_params + list_params, + idx as usize + parent_params + self_params + list_params + const_params, )) - .intern(&Interner) + .intern(Interner) } ImplTraitLoweringMode::Disallowed => { // FIXME: report error - TyKind::Error.intern(&Interner) + TyKind::Error.intern(Interner) } } } @@ -343,9 +369,9 @@ pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { if recursion_start { *self.expander.borrow_mut() = None; } - ty.unwrap_or_else(|| TyKind::Error.intern(&Interner)) + ty.unwrap_or_else(|| TyKind::Error.intern(Interner)) } - TypeRef::Error => TyKind::Error.intern(&Interner), + TypeRef::Error => TyKind::Error.intern(Interner), }; (ty, res) } @@ -353,7 +379,7 @@ pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option) { /// This is only for `generic_predicates_for_param`, where we can't just /// lower the self types of the predicates since that could lead to cycles. /// So we just check here if the `type_ref` resolves to a generic param, and which. - fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option { + fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option { let path = match type_ref { TypeRef::Path(path) => path, _ => return None, @@ -370,7 +396,7 @@ fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option { _ => return None, }; match resolution { - TypeNs::GenericParam(param_id) => Some(param_id), + TypeNs::GenericParam(param_id) => Some(param_id.into()), _ => None, } } @@ -391,7 +417,7 @@ pub(crate) fn lower_ty_relative_path( } _ => { // FIXME report error (ambiguous associated type) - (TyKind::Error.intern(&Interner), None) + (TyKind::Error.intern(Interner), None) } } } @@ -421,18 +447,18 @@ pub(crate) fn lower_partly_resolved_path( associated_ty_id: to_assoc_type_id(associated_ty), substitution: trait_ref.substitution, })) - .intern(&Interner) + .intern(Interner) } None => { // FIXME: report error (associated type not found) - TyKind::Error.intern(&Interner) + TyKind::Error.intern(Interner) } } } 0 => { let self_ty = Some( TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)) - .intern(&Interner), + .intern(Interner), ); let trait_ref = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { ctx.lower_trait_ref_from_resolved_path( @@ -442,10 +468,9 @@ pub(crate) fn lower_partly_resolved_path( ) }); let dyn_ty = DynTy { - bounds: crate::make_only_type_binders( - 1, + bounds: crate::make_single_type_binders( QuantifiedWhereClauses::from_iter( - &Interner, + Interner, Some(crate::wrap_empty_binders(WhereClause::Implemented( trait_ref, ))), @@ -453,11 +478,11 @@ pub(crate) fn lower_partly_resolved_path( ), lifetime: static_lifetime(), }; - TyKind::Dyn(dyn_ty).intern(&Interner) + TyKind::Dyn(dyn_ty).intern(Interner) } _ => { // FIXME report error (ambiguous associated type) - TyKind::Error.intern(&Interner) + TyKind::Error.intern(Interner) } }; return (ty, None); @@ -468,31 +493,35 @@ pub(crate) fn lower_partly_resolved_path( self.resolver.generic_def().expect("generics in scope"), ); match self.type_param_mode { - TypeParamLoweringMode::Placeholder => { - TyKind::Placeholder(to_placeholder_idx(self.db, param_id)) + ParamLoweringMode::Placeholder => { + TyKind::Placeholder(to_placeholder_idx(self.db, param_id.into())) } - TypeParamLoweringMode::Variable => { - let idx = generics.param_idx(param_id).expect("matching generics"); + ParamLoweringMode::Variable => { + let idx = generics.param_idx(param_id.into()).expect("matching generics"); TyKind::BoundVar(BoundVar::new(self.in_binders, idx)) } } - .intern(&Interner) + .intern(Interner) } TypeNs::SelfType(impl_id) => { let generics = generics(self.db.upcast(), impl_id.into()); let substs = match self.type_param_mode { - TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db), - TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders), + ParamLoweringMode::Placeholder => generics.placeholder_subst(self.db), + ParamLoweringMode::Variable => { + generics.bound_vars_subst(self.db, self.in_binders) + } }; - self.db.impl_self_ty(impl_id).substitute(&Interner, &substs) + self.db.impl_self_ty(impl_id).substitute(Interner, &substs) } TypeNs::AdtSelfType(adt) => { let generics = generics(self.db.upcast(), adt.into()); let substs = match self.type_param_mode { - TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db), - TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders), + ParamLoweringMode::Placeholder => generics.placeholder_subst(self.db), + ParamLoweringMode::Variable => { + generics.bound_vars_subst(self.db, self.in_binders) + } }; - self.db.ty(adt.into()).substitute(&Interner, &substs) + self.db.ty(adt.into()).substitute(Interner, &substs) } TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args), @@ -503,7 +532,7 @@ pub(crate) fn lower_partly_resolved_path( self.lower_path_inner(resolved_segment, it.into(), infer_args) } // FIXME: report error - TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(&Interner), None), + TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(Interner), None), }; self.lower_ty_relative_path(ty, Some(resolution), remaining_segments) } @@ -517,7 +546,7 @@ pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option) { let (resolution, remaining_index) = match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) { Some(it) => it, - None => return (TyKind::Error.intern(&Interner), None), + None => return (TyKind::Error.intern(Interner), None), }; let (resolved_segment, remaining_segments) = match remaining_index { None => ( @@ -530,49 +559,50 @@ pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option) { } fn select_associated_type(&self, res: Option, segment: PathSegment<'_>) -> Ty { - if let Some(res) = res { - let ty = named_associated_type_shorthand_candidates( - self.db, - res, - Some(segment.name.clone()), - move |name, t, associated_ty| { - if name == segment.name { - let substs = match self.type_param_mode { - TypeParamLoweringMode::Placeholder => { - // if we're lowering to placeholders, we have to put - // them in now - let generics = generics( - self.db.upcast(), - self.resolver.generic_def().expect( - "there should be generics if there's a generic param", - ), - ); - let s = generics.type_params_subst(self.db); - s.apply(t.substitution.clone(), &Interner) - } - TypeParamLoweringMode::Variable => t.substitution.clone(), - }; - // We need to shift in the bound vars, since - // associated_type_shorthand_candidates does not do that - let substs = substs.shifted_in_from(&Interner, self.in_binders); - // FIXME handle type parameters on the segment - Some( - TyKind::Alias(AliasTy::Projection(ProjectionTy { - associated_ty_id: to_assoc_type_id(associated_ty), - substitution: substs, - })) - .intern(&Interner), - ) - } else { - None - } - }, - ); + let (def, res) = match (self.resolver.generic_def(), res) { + (Some(def), Some(res)) => (def, res), + _ => return TyKind::Error.intern(Interner), + }; + let ty = named_associated_type_shorthand_candidates( + self.db, + def, + res, + Some(segment.name.clone()), + move |name, t, associated_ty| { + if name == segment.name { + let substs = match self.type_param_mode { + ParamLoweringMode::Placeholder => { + // if we're lowering to placeholders, we have to put + // them in now + let generics = generics( + self.db.upcast(), + self.resolver + .generic_def() + .expect("there should be generics if there's a generic param"), + ); + let s = generics.placeholder_subst(self.db); + s.apply(t.substitution.clone(), Interner) + } + ParamLoweringMode::Variable => t.substitution.clone(), + }; + // We need to shift in the bound vars, since + // associated_type_shorthand_candidates does not do that + let substs = substs.shifted_in_from(Interner, self.in_binders); + // FIXME handle type parameters on the segment + Some( + TyKind::Alias(AliasTy::Projection(ProjectionTy { + associated_ty_id: to_assoc_type_id(associated_ty), + substitution: substs, + })) + .intern(Interner), + ) + } else { + None + } + }, + ); - ty.unwrap_or_else(|| TyKind::Error.intern(&Interner)) - } else { - TyKind::Error.intern(&Interner) - } + ty.unwrap_or_else(|| TyKind::Error.intern(Interner)) } fn lower_path_inner( @@ -587,7 +617,7 @@ fn lower_path_inner( TyDefId::TypeAliasId(it) => Some(it.into()), }; let substs = self.substs_from_path_segment(segment, generic_def, infer_args, None); - self.db.ty(typeable).substitute(&Interner, &substs) + self.db.ty(typeable).substitute(Interner, &substs) } /// Collect generic arguments from a path into a `Substs`. See also @@ -634,46 +664,75 @@ fn substs_from_path_segment( explicit_self_ty: Option, ) -> Substitution { let mut substs = Vec::new(); - let def_generics = def_generic.map(|def| generics(self.db.upcast(), def)); - - let (parent_params, self_params, type_params, impl_trait_params) = - def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split()); - let total_len = parent_params + self_params + type_params + impl_trait_params; - - substs.extend(iter::repeat(TyKind::Error.intern(&Interner)).take(parent_params)); + let def_generics = if let Some(def) = def_generic { + generics(self.db.upcast(), def) + } else { + return Substitution::empty(Interner); + }; + let (parent_params, self_params, type_params, const_params, impl_trait_params) = + def_generics.provenance_split(); + let total_len = + parent_params + self_params + type_params + const_params + impl_trait_params; + + let ty_error = GenericArgData::Ty(TyKind::Error.intern(Interner)).intern(Interner); + let const_error = GenericArgData::Const(consteval::usize_const(None)).intern(Interner); + + for (_, data) in def_generics.iter().take(parent_params) { + match data { + TypeOrConstParamData::TypeParamData(_) => substs.push(ty_error.clone()), + TypeOrConstParamData::ConstParamData(_) => substs.push(const_error.clone()), + } + } let fill_self_params = || { substs.extend( explicit_self_ty .into_iter() - .chain(iter::repeat(TyKind::Error.intern(&Interner))) + .map(|x| GenericArgData::Ty(x).intern(Interner)) + .chain(iter::repeat(ty_error.clone())) .take(self_params), ) }; - let mut had_explicit_type_args = false; + let mut had_explicit_args = false; if let Some(generic_args) = &segment.args_and_bindings { if !generic_args.has_self_type { fill_self_params(); } - let expected_num = - if generic_args.has_self_type { self_params + type_params } else { type_params }; + let expected_num = if generic_args.has_self_type { + self_params + type_params + const_params + } else { + type_params + const_params + }; let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 }; // if args are provided, it should be all of them, but we can't rely on that - for arg in generic_args + for (arg, id) in generic_args .args .iter() - .filter(|arg| matches!(arg, GenericArg::Type(_))) + .filter(|arg| !matches!(arg, GenericArg::Lifetime(_))) .skip(skip) .take(expected_num) + .zip(def_generics.iter_id().skip(skip)) { - match arg { - GenericArg::Type(type_ref) => { - had_explicit_type_args = true; - let ty = self.lower_ty(type_ref); - substs.push(ty); - } - GenericArg::Lifetime(_) => {} + if let Some(x) = generic_arg_to_chalk( + self.db, + id, + arg, + &mut (), + |_, type_ref| self.lower_ty(type_ref), + |_, c| { + const_or_path_to_chalk( + self.db, + &self.resolver, + c, + self.type_param_mode, + || self.generics(), + DebruijnIndex::INNERMOST, + ) + }, + ) { + had_explicit_args = true; + substs.push(x); } } } else { @@ -683,27 +742,30 @@ fn substs_from_path_segment( // handle defaults. In expression or pattern path segments without // explicitly specified type arguments, missing type arguments are inferred // (i.e. defaults aren't used). - if !infer_args || had_explicit_type_args { + if !infer_args || had_explicit_args { if let Some(def_generic) = def_generic { let defaults = self.db.generic_defaults(def_generic); assert_eq!(total_len, defaults.len()); for default_ty in defaults.iter().skip(substs.len()) { // each default can depend on the previous parameters - let substs_so_far = Substitution::from_iter(&Interner, substs.clone()); - substs.push(default_ty.clone().substitute(&Interner, &substs_so_far)); + let substs_so_far = Substitution::from_iter(Interner, substs.clone()); + substs.push(default_ty.clone().substitute(Interner, &substs_so_far)); } } } // add placeholders for args that were not provided // FIXME: emit diagnostics in contexts where this is not allowed - for _ in substs.len()..total_len { - substs.push(TyKind::Error.intern(&Interner)); + for (_, data) in def_generics.iter().skip(substs.len()) { + match data { + TypeOrConstParamData::TypeParamData(_) => substs.push(ty_error.clone()), + TypeOrConstParamData::ConstParamData(_) => substs.push(const_error.clone()), + } } assert_eq!(substs.len(), total_len); - Substitution::from_iter(&Interner, substs) + Substitution::from_iter(Interner, substs) } fn lower_trait_ref_from_path( @@ -757,20 +819,22 @@ pub(crate) fn lower_where_predicate( | WherePredicate::TypeBound { target, bound } => { let self_ty = match target { WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref), - WherePredicateTypeTarget::TypeParam(param_id) => { + WherePredicateTypeTarget::TypeOrConstParam(param_id) => { let generic_def = self.resolver.generic_def().expect("generics in scope"); let generics = generics(self.db.upcast(), generic_def); - let param_id = - hir_def::TypeParamId { parent: generic_def, local_id: *param_id }; + let param_id = hir_def::TypeOrConstParamId { + parent: generic_def, + local_id: *param_id, + }; let placeholder = to_placeholder_idx(self.db, param_id); match self.type_param_mode { - TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder), - TypeParamLoweringMode::Variable => { + ParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder), + ParamLoweringMode::Variable => { let idx = generics.param_idx(param_id).expect("matching generics"); TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx)) } } - .intern(&Interner) + .intern(Interner) } }; self.lower_type_bound(bound, self_ty, ignore_bindings) @@ -869,7 +933,7 @@ fn assoc_type_bindings_from_type_bound( for bound in &binding.bounds { preds.extend(self.lower_type_bound( bound, - TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner), + TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(Interner), false, )); } @@ -883,8 +947,7 @@ fn lower_impl_trait( func: FunctionId, ) -> ReturnTypeImplTrait { cov_mark::hit!(lower_rpit); - let self_ty = - TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner); + let self_ty = TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(Interner); let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { let mut predicates: Vec<_> = bounds .iter() @@ -900,7 +963,7 @@ fn lower_impl_trait( let sized_clause = sized_trait.map(|trait_id| { let clause = WhereClause::Implemented(TraitRef { trait_id, - substitution: Substitution::from1(&Interner, self_ty.clone()), + substitution: Substitution::from1(Interner, self_ty.clone()), }); crate::wrap_empty_binders(clause) }); @@ -909,8 +972,7 @@ fn lower_impl_trait( } predicates }); - - ReturnTypeImplTrait { bounds: crate::make_only_type_binders(1, predicates) } + ReturnTypeImplTrait { bounds: crate::make_single_type_binders(predicates) } } } @@ -935,14 +997,18 @@ pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig pub fn associated_type_shorthand_candidates( db: &dyn HirDatabase, + def: GenericDefId, res: TypeNs, cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option, ) -> Option { - named_associated_type_shorthand_candidates(db, res, None, cb) + named_associated_type_shorthand_candidates(db, def, res, None, cb) } fn named_associated_type_shorthand_candidates( db: &dyn HirDatabase, + // If the type parameter is defined in an impl and we're in a method, there + // might be additional where clauses to consider + def: GenericDefId, res: TypeNs, assoc_name: Option, mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option, @@ -969,12 +1035,12 @@ fn named_associated_type_shorthand_candidates( db.impl_trait(impl_id)?.into_value_and_skipped_binders().0, ), TypeNs::GenericParam(param_id) => { - let predicates = db.generic_predicates_for_param(param_id, assoc_name); + let predicates = db.generic_predicates_for_param(def, param_id.into(), assoc_name); let res = predicates.iter().find_map(|pred| match pred.skip_binders().skip_binders() { // FIXME: how to correctly handle higher-ranked bounds here? WhereClause::Implemented(tr) => search( tr.clone() - .shifted_out_to(&Interner, DebruijnIndex::ONE) + .shifted_out_to(Interner, DebruijnIndex::ONE) .expect("FIXME unexpected higher-ranked trait bound"), ), _ => None, @@ -983,11 +1049,9 @@ fn named_associated_type_shorthand_candidates( return res; } // Handle `Self::Type` referring to own associated type in trait definitions - if let GenericDefId::TraitId(trait_id) = param_id.parent { + if let GenericDefId::TraitId(trait_id) = param_id.parent() { let generics = generics(db.upcast(), trait_id.into()); - if generics.params.types[param_id.local_id].provenance - == TypeParamProvenance::TraitSelf - { + if generics.params.type_or_consts[param_id.local_id()].is_trait_self() { let trait_ref = TyBuilder::trait_ref(db, trait_id) .fill_with_bound_vars(DebruijnIndex::INNERMOST, 0) .build(); @@ -1014,9 +1078,9 @@ pub(crate) fn field_types_query( let generics = generics(db.upcast(), def); let mut res = ArenaMap::default(); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); for (field_id, field_data) in var_data.fields().iter() { - res.insert(field_id, make_binders(&generics, ctx.lower_ty(&field_data.type_ref))) + res.insert(field_id, make_binders(db, &generics, ctx.lower_ty(&field_data.type_ref))) } Arc::new(res) } @@ -1031,13 +1095,14 @@ pub(crate) fn field_types_query( /// these are fine: `T: Foo, U: Foo<()>`. pub(crate) fn generic_predicates_for_param_query( db: &dyn HirDatabase, - param_id: TypeParamId, + def: GenericDefId, + param_id: TypeOrConstParamId, assoc_name: Option, ) -> Arc<[Binders]> { - let resolver = param_id.parent.resolver(db.upcast()); + let resolver = def.resolver(db.upcast()); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); - let generics = generics(db.upcast(), param_id.parent); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); + let generics = generics(db.upcast(), def); let mut predicates: Vec<_> = resolver .where_predicates_in_scope() // we have to filter out all other predicates *first*, before attempting to lower them @@ -1050,7 +1115,7 @@ pub(crate) fn generic_predicates_for_param_query( return false; } } - WherePredicateTypeTarget::TypeParam(local_id) => { + WherePredicateTypeTarget::TypeOrConstParam(local_id) => { if *local_id != param_id.local_id { return false; } @@ -1084,14 +1149,16 @@ pub(crate) fn generic_predicates_for_param_query( } WherePredicate::Lifetime { .. } => false, }) - .flat_map(|pred| ctx.lower_where_predicate(pred, true).map(|p| make_binders(&generics, p))) + .flat_map(|pred| { + ctx.lower_where_predicate(pred, true).map(|p| make_binders(db, &generics, p)) + }) .collect(); - let subst = generics.bound_vars_subst(DebruijnIndex::INNERMOST); + let subst = generics.bound_vars_subst(db, DebruijnIndex::INNERMOST); let explicitly_unsized_tys = ctx.unsized_types.into_inner(); let implicitly_sized_predicates = implicitly_sized_clauses(db, param_id.parent, &explicitly_unsized_tys, &subst, &resolver) - .map(|p| make_binders(&generics, crate::wrap_empty_binders(p))); + .map(|p| make_binders(db, &generics, crate::wrap_empty_binders(p))); predicates.extend(implicitly_sized_predicates); predicates.into() } @@ -1099,7 +1166,8 @@ pub(crate) fn generic_predicates_for_param_query( pub(crate) fn generic_predicates_for_param_recover( _db: &dyn HirDatabase, _cycle: &[String], - _param_id: &TypeParamId, + _def: &GenericDefId, + _param_id: &TypeOrConstParamId, _assoc_name: &Option, ) -> Arc<[Binders]> { Arc::new([]) @@ -1110,18 +1178,17 @@ pub(crate) fn trait_environment_query( def: GenericDefId, ) -> Arc { let resolver = def.resolver(db.upcast()); - let ctx = TyLoweringContext::new(db, &resolver) - .with_type_param_mode(TypeParamLoweringMode::Placeholder); + let ctx = + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Placeholder); let mut traits_in_scope = Vec::new(); let mut clauses = Vec::new(); for pred in resolver.where_predicates_in_scope() { for pred in ctx.lower_where_predicate(pred, false) { if let WhereClause::Implemented(tr) = &pred.skip_binders() { - traits_in_scope - .push((tr.self_type_parameter(&Interner).clone(), tr.hir_trait_id())); + traits_in_scope.push((tr.self_type_parameter(Interner).clone(), tr.hir_trait_id())); } - let program_clause: chalk_ir::ProgramClause = pred.cast(&Interner); - clauses.push(program_clause.into_from_env_clause(&Interner)); + let program_clause: chalk_ir::ProgramClause = pred.cast(Interner); + clauses.push(program_clause.into_from_env_clause(Interner)); } } @@ -1140,25 +1207,25 @@ pub(crate) fn trait_environment_query( // function default implementations (and speculative code // inside consts or type aliases) cov_mark::hit!(trait_self_implements_self); - let substs = TyBuilder::type_params_subst(db, trait_id); + let substs = TyBuilder::placeholder_subst(db, trait_id); let trait_ref = TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution: substs }; let pred = WhereClause::Implemented(trait_ref); - let program_clause: chalk_ir::ProgramClause = pred.cast(&Interner); - clauses.push(program_clause.into_from_env_clause(&Interner)); + let program_clause: chalk_ir::ProgramClause = pred.cast(Interner); + clauses.push(program_clause.into_from_env_clause(Interner)); } - let subst = generics(db.upcast(), def).type_params_subst(db); + let subst = generics(db.upcast(), def).placeholder_subst(db); let explicitly_unsized_tys = ctx.unsized_types.into_inner(); let implicitly_sized_clauses = implicitly_sized_clauses(db, def, &explicitly_unsized_tys, &subst, &resolver).map(|pred| { - let program_clause: chalk_ir::ProgramClause = pred.cast(&Interner); - program_clause.into_from_env_clause(&Interner) + let program_clause: chalk_ir::ProgramClause = pred.cast(Interner); + program_clause.into_from_env_clause(Interner) }); clauses.extend(implicitly_sized_clauses); let krate = def.module(db.upcast()).krate(); - let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses); + let env = chalk_ir::Environment::new(Interner).add_clauses(Interner, clauses); Arc::new(TraitEnvironment { krate, traits_from_clauses: traits_in_scope, env }) } @@ -1170,19 +1237,21 @@ pub(crate) fn generic_predicates_query( ) -> Arc<[Binders]> { let resolver = def.resolver(db.upcast()); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); let generics = generics(db.upcast(), def); let mut predicates = resolver .where_predicates_in_scope() - .flat_map(|pred| ctx.lower_where_predicate(pred, false).map(|p| make_binders(&generics, p))) + .flat_map(|pred| { + ctx.lower_where_predicate(pred, false).map(|p| make_binders(db, &generics, p)) + }) .collect::>(); - let subst = generics.bound_vars_subst(DebruijnIndex::INNERMOST); + let subst = generics.bound_vars_subst(db, DebruijnIndex::INNERMOST); let explicitly_unsized_tys = ctx.unsized_types.into_inner(); let implicitly_sized_predicates = implicitly_sized_clauses(db, def, &explicitly_unsized_tys, &subst, &resolver) - .map(|p| make_binders(&generics, crate::wrap_empty_binders(p))); + .map(|p| make_binders(db, &generics, crate::wrap_empty_binders(p))); predicates.extend(implicitly_sized_predicates); predicates.into() } @@ -1197,7 +1266,7 @@ fn implicitly_sized_clauses<'a>( resolver: &Resolver, ) -> impl Iterator + 'a { let is_trait_def = matches!(def, GenericDefId::TraitId(..)); - let generic_args = &substitution.as_slice(&Interner)[is_trait_def as usize..]; + let generic_args = &substitution.as_slice(Interner)[is_trait_def as usize..]; let sized_trait = resolver .krate() .and_then(|krate| db.lang_item(krate, SmolStr::new_inline("sized"))) @@ -1206,12 +1275,12 @@ fn implicitly_sized_clauses<'a>( sized_trait.into_iter().flat_map(move |sized_trait| { let implicitly_sized_tys = generic_args .iter() - .filter_map(|generic_arg| generic_arg.ty(&Interner)) + .filter_map(|generic_arg| generic_arg.ty(Interner)) .filter(move |&self_ty| !explicitly_unsized_tys.contains(self_ty)); implicitly_sized_tys.map(move |self_ty| { WhereClause::Implemented(TraitRef { trait_id: sized_trait, - substitution: Substitution::from1(&Interner, self_ty.clone()), + substitution: Substitution::from1(Interner, self_ty.clone()), }) }) }) @@ -1221,32 +1290,36 @@ fn implicitly_sized_clauses<'a>( pub(crate) fn generic_defaults_query( db: &dyn HirDatabase, def: GenericDefId, -) -> Arc<[Binders]> { +) -> Arc<[Binders>]> { let resolver = def.resolver(db.upcast()); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); let generic_params = generics(db.upcast(), def); let defaults = generic_params .iter() .enumerate() - .map(|(idx, (_, p))| { + .map(|(idx, (id, p))| { + let p = match p { + TypeOrConstParamData::TypeParamData(p) => p, + TypeOrConstParamData::ConstParamData(_) => { + // FIXME: implement const generic defaults + let val = unknown_const_as_generic( + db.const_param_ty(ConstParamId::from_unchecked(id)), + ); + return crate::make_binders_with_count(db, idx, &generic_params, val); + } + }; let mut ty = - p.default.as_ref().map_or(TyKind::Error.intern(&Interner), |t| ctx.lower_ty(t)); + p.default.as_ref().map_or(TyKind::Error.intern(Interner), |t| ctx.lower_ty(t)); // Each default can only refer to previous parameters. - ty = crate::fold_free_vars(ty, |bound, binders| { - if bound.index >= idx && bound.debruijn == DebruijnIndex::INNERMOST { - // type variable default referring to parameter coming - // after it. This is forbidden (FIXME: report - // diagnostic) - TyKind::Error.intern(&Interner) - } else { - bound.shifted_in_from(binders).to_ty(&Interner) - } - }); - - crate::make_only_type_binders(idx, ty) + // type variable default referring to parameter coming + // after it. This is forbidden (FIXME: report + // diagnostic) + ty = fallback_bound_vars(ty, idx); + let val = GenericArgData::Ty(ty).intern(Interner); + crate::make_binders_with_count(db, idx, &generic_params, val) }) .collect(); @@ -1257,17 +1330,21 @@ pub(crate) fn generic_defaults_recover( db: &dyn HirDatabase, _cycle: &[String], def: &GenericDefId, -) -> Arc<[Binders]> { +) -> Arc<[Binders]> { let generic_params = generics(db.upcast(), *def); - + // FIXME: this code is not covered in tests. // we still need one default per parameter let defaults = generic_params - .iter() + .iter_id() .enumerate() - .map(|(idx, _)| { - let ty = TyKind::Error.intern(&Interner); - - crate::make_only_type_binders(idx, ty) + .map(|(count, id)| { + let val = match id { + itertools::Either::Left(_) => { + GenericArgData::Ty(TyKind::Error.intern(Interner)).intern(Interner) + } + itertools::Either::Right(id) => unknown_const_as_generic(db.const_param_ty(id)), + }; + crate::make_binders_with_count(db, count, &generic_params, val) }) .collect(); @@ -1279,24 +1356,29 @@ fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig { let resolver = def.resolver(db.upcast()); let ctx_params = TyLoweringContext::new(db, &resolver) .with_impl_trait_mode(ImplTraitLoweringMode::Variable) - .with_type_param_mode(TypeParamLoweringMode::Variable); - let params = data.params.iter().map(|tr| ctx_params.lower_ty(tr)).collect::>(); + .with_type_param_mode(ParamLoweringMode::Variable); + let params = data.params.iter().map(|(_, tr)| ctx_params.lower_ty(tr)).collect::>(); let ctx_ret = TyLoweringContext::new(db, &resolver) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) - .with_type_param_mode(TypeParamLoweringMode::Variable); + .with_type_param_mode(ParamLoweringMode::Variable); let ret = ctx_ret.lower_ty(&data.ret_type); let generics = generics(db.upcast(), def.into()); - make_binders(&generics, CallableSig::from_params_and_return(params, ret, data.is_varargs())) + let mut sig = CallableSig::from_params_and_return(params, ret, data.is_varargs()); + if !data.legacy_const_generics_indices.is_empty() { + sig.set_legacy_const_generics_indices(&data.legacy_const_generics_indices); + } + make_binders(db, &generics, sig) } /// Build the declared type of a function. This should not need to look at the /// function body. fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders { let generics = generics(db.upcast(), def.into()); - let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST); + let substs = generics.bound_vars_subst(db, DebruijnIndex::INNERMOST); make_binders( + db, &generics, - TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner), + TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(Interner), ) } @@ -1306,9 +1388,9 @@ fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders { let generics = generics(db.upcast(), def.into()); let resolver = def.resolver(db.upcast()); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); - make_binders(&generics, ctx.lower_ty(&data.type_ref)) + make_binders(db, &generics, ctx.lower_ty(&data.type_ref)) } /// Build the declared type of a static. @@ -1317,7 +1399,7 @@ fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders { let resolver = def.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver); - Binders::empty(&Interner, ctx.lower_ty(&data.type_ref)) + Binders::empty(Interner, ctx.lower_ty(&data.type_ref)) } fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig { @@ -1325,7 +1407,7 @@ fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnS let fields = struct_data.variant_data.fields(); let resolver = def.resolver(db.upcast()); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::>(); let (ret, binders) = type_for_adt(db, def.into()).into_value_and_skipped_binders(); Binders::new(binders, CallableSig::from_params_and_return(params, ret, false)) @@ -1338,10 +1420,11 @@ fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders>(); let (ret, binders) = type_for_adt(db, def.parent.into()).into_value_and_skipped_binders(); Binders::new(binders, CallableSig::from_params_and_return(params, ret, false)) @@ -1365,31 +1448,32 @@ fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) - return type_for_adt(db, def.parent.into()); } let generics = generics(db.upcast(), def.parent.into()); - let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST); + let substs = generics.bound_vars_subst(db, DebruijnIndex::INNERMOST); make_binders( + db, &generics, - TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner), + TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(Interner), ) } fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders { let generics = generics(db.upcast(), adt.into()); - let b = TyBuilder::adt(db, adt); - let ty = b.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0).build(); - make_binders(&generics, ty) + let subst = generics.bound_vars_subst(db, DebruijnIndex::INNERMOST); + let ty = TyKind::Adt(crate::AdtId(adt), subst).intern(Interner); + make_binders(db, &generics, ty) } fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders { let generics = generics(db.upcast(), t.into()); let resolver = t.resolver(db.upcast()); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); if db.type_alias_data(t).is_extern { - Binders::empty(&Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(&Interner)) + Binders::empty(Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(Interner)) } else { let type_ref = &db.type_alias_data(t).type_ref; let inner = ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error)); - make_binders(&generics, inner) + make_binders(db, &generics, inner) } } @@ -1448,7 +1532,7 @@ pub enum ValueTyDefId { /// namespace. pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders { match def { - TyDefId::BuiltinType(it) => Binders::empty(&Interner, TyBuilder::builtin(it)), + TyDefId::BuiltinType(it) => Binders::empty(Interner, TyBuilder::builtin(it)), TyDefId::AdtId(it) => type_for_adt(db, it), TyDefId::TypeAliasId(it) => type_for_type_alias(db, it), } @@ -1456,13 +1540,11 @@ pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders { pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders { let generics = match *def { - TyDefId::BuiltinType(_) => { - return Binders::empty(&Interner, TyKind::Error.intern(&Interner)) - } + TyDefId::BuiltinType(_) => return Binders::empty(Interner, TyKind::Error.intern(Interner)), TyDefId::AdtId(it) => generics(db.upcast(), it.into()), TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()), }; - make_binders(&generics, TyKind::Error.intern(&Interner)) + make_binders(db, &generics, TyKind::Error.intern(Interner)) } pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders { @@ -1486,17 +1568,23 @@ pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binde )); let generics = generics(db.upcast(), impl_id.into()); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); - make_binders(&generics, ctx.lower_ty(&impl_data.self_ty)) + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); + make_binders(db, &generics, ctx.lower_ty(&impl_data.self_ty)) } +// returns None if def is a type arg pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty { - let parent_data = db.generic_params(def.parent); - let data = &parent_data.consts[def.local_id]; - let resolver = def.parent.resolver(db.upcast()); + let parent_data = db.generic_params(def.parent()); + let data = &parent_data.type_or_consts[def.local_id()]; + let resolver = def.parent().resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver); - - ctx.lower_ty(&data.ty) + match data { + TypeOrConstParamData::TypeParamData(_) => { + never!(); + Ty::new(Interner, TyKind::Error) + } + TypeOrConstParamData::ConstParamData(d) => ctx.lower_ty(&d.ty), + } } pub(crate) fn impl_self_ty_recover( @@ -1505,7 +1593,7 @@ pub(crate) fn impl_self_ty_recover( impl_id: &ImplId, ) -> Binders { let generics = generics(db.upcast(), (*impl_id).into()); - make_binders(&generics, TyKind::Error.intern(&Interner)) + make_binders(db, &generics, TyKind::Error.intern(Interner)) } pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option> { @@ -1517,7 +1605,7 @@ pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option< impl_id, impl_loc, impl_data )); let ctx = - TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); + TyLoweringContext::new(db, &resolver).with_type_param_mode(ParamLoweringMode::Variable); let (self_ty, binders) = db.impl_self_ty(impl_id).into_value_and_skipped_binders(); let target_trait = impl_data.target_trait.as_ref()?; Some(Binders::new(binders, ctx.lower_trait_ref(target_trait, Some(self_ty))?)) @@ -1532,7 +1620,7 @@ pub(crate) fn return_type_impl_traits( let resolver = def.resolver(db.upcast()); let ctx_ret = TyLoweringContext::new(db, &resolver) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) - .with_type_param_mode(TypeParamLoweringMode::Variable); + .with_type_param_mode(ParamLoweringMode::Variable); let _ret = (&ctx_ret).lower_ty(&data.ret_type); let generics = generics(db.upcast(), def.into()); let return_type_impl_traits = @@ -1540,7 +1628,7 @@ pub(crate) fn return_type_impl_traits( if return_type_impl_traits.impl_traits.is_empty() { None } else { - Some(Arc::new(make_binders(&generics, return_type_impl_traits))) + Some(Arc::new(make_binders(db, &generics, return_type_impl_traits))) } } @@ -1551,6 +1639,65 @@ pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mut } } -fn make_binders>(generics: &Generics, value: T) -> Binders { - crate::make_only_type_binders(generics.len(), value) +pub(crate) fn generic_arg_to_chalk<'a, T>( + db: &dyn HirDatabase, + kind_id: Either, + arg: &'a GenericArg, + this: &mut T, + for_type: impl FnOnce(&mut T, &TypeRef) -> Ty + 'a, + for_const: impl FnOnce(&mut T, &ConstScalarOrPath) -> Const + 'a, +) -> Option { + let kind = match kind_id { + Either::Left(_) => ParamKind::Type, + Either::Right(id) => { + let ty = db.const_param_ty(id); + ParamKind::Const(ty) + } + }; + Some(match (arg, kind) { + (GenericArg::Type(type_ref), ParamKind::Type) => { + let ty = for_type(this, type_ref); + GenericArgData::Ty(ty).intern(Interner) + } + (GenericArg::Const(c), ParamKind::Const(_)) => { + GenericArgData::Const(for_const(this, c)).intern(Interner) + } + (GenericArg::Const(_), ParamKind::Type) => { + GenericArgData::Ty(TyKind::Error.intern(Interner)).intern(Interner) + } + (GenericArg::Type(t), ParamKind::Const(ty)) => { + // We want to recover simple idents, which parser detects them + // as types. Maybe here is not the best place to do it, but + // it works. + if let TypeRef::Path(p) = t { + let p = p.mod_path(); + if p.kind == PathKind::Plain { + if let [n] = p.segments() { + let c = ConstScalarOrPath::Path(n.clone()); + return Some(GenericArgData::Const(for_const(this, &c)).intern(Interner)); + } + } + } + unknown_const_as_generic(ty) + } + (GenericArg::Lifetime(_), _) => return None, + }) +} + +pub(crate) fn const_or_path_to_chalk( + db: &dyn HirDatabase, + resolver: &Resolver, + value: &ConstScalarOrPath, + mode: ParamLoweringMode, + args: impl FnOnce() -> Generics, + debruijn: DebruijnIndex, +) -> Const { + match value { + ConstScalarOrPath::Scalar(s) => usize_const(s.as_usize()), + ConstScalarOrPath::Path(n) => { + let path = ModPath::from_segments(PathKind::Plain, Some(n.clone())); + path_to_const(db, resolver, &path, mode, args, debruijn) + .unwrap_or_else(|| unknown_const_usize()) + } + } }