1 //! Path expression resolution.
5 use chalk_ir::cast::Cast;
7 path::{Path, PathSegment},
8 resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs},
9 AdtId, AssocContainerId, AssocItemId, EnumVariantId, Lookup,
11 use hir_expand::name::Name;
14 method_resolution, Interner, Substitution, Ty, TyBuilder, TyExt, TyKind, ValueTyDefId,
17 use super::{ExprOrPatId, InferenceContext, TraitRef};
19 impl<'a> InferenceContext<'a> {
20 pub(super) fn infer_path(
26 let ty = self.resolve_value_path(resolver, path, id)?;
27 let ty = self.insert_type_vars(ty);
28 let ty = self.normalize_associated_types_in(ty);
32 fn resolve_value_path(
38 let (value, self_subst) = if let Some(type_ref) = path.type_anchor() {
39 if path.segments().is_empty() {
40 // This can't actually happen syntax-wise
43 let ty = self.make_ty(type_ref);
44 let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1);
45 let ctx = crate::lower::TyLoweringContext::new(self.db, &resolver);
46 let (ty, _) = ctx.lower_ty_relative_path(ty, None, remaining_segments_for_ty);
47 self.resolve_ty_assoc_item(
49 &path.segments().last().expect("path had at least one segment").name,
53 let value_or_partial =
54 resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path())?;
56 match value_or_partial {
57 ResolveValueResult::ValueNs(it) => (it, None),
58 ResolveValueResult::Partial(def, remaining_index) => {
59 self.resolve_assoc_item(def, path, remaining_index, id)?
64 let typable: ValueTyDefId = match value {
65 ValueNs::LocalBinding(pat) => {
66 let ty = self.result.type_of_pat.get(pat)?.clone();
67 let ty = self.resolve_ty_as_possible(ty);
70 ValueNs::FunctionId(it) => it.into(),
71 ValueNs::ConstId(it) => it.into(),
72 ValueNs::StaticId(it) => it.into(),
73 ValueNs::StructId(it) => {
74 self.write_variant_resolution(id, it.into());
78 ValueNs::EnumVariantId(it) => {
79 self.write_variant_resolution(id, it.into());
83 ValueNs::ImplSelf(impl_id) => {
84 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
85 let substs = generics.type_params_subst(self.db);
86 let ty = self.db.impl_self_ty(impl_id).substitute(&Interner, &substs);
87 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() {
88 let ty = self.db.value_ty(struct_id.into()).substitute(&Interner, &substs);
91 // FIXME: diagnostic, invalid Self reference
95 ValueNs::GenericParam(it) => return Some(self.db.const_param_ty(it)),
98 let parent_substs = self_subst.unwrap_or_else(|| Substitution::empty(&Interner));
99 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
100 let substs = ctx.substs_from_path(path, typable, true);
101 let ty = TyBuilder::value_ty(self.db, typable)
102 .use_parent_substs(&parent_substs)
103 .fill(substs.interned()[parent_substs.len(&Interner)..].iter().cloned())
108 fn resolve_assoc_item(
112 remaining_index: usize,
114 ) -> Option<(ValueNs, Option<Substitution>)> {
115 assert!(remaining_index < path.segments().len());
116 // there may be more intermediate segments between the resolved one and
117 // the end. Only the last segment needs to be resolved to a value; from
118 // the segments before that, we need to get either a type or a trait ref.
120 let resolved_segment = path.segments().get(remaining_index - 1).unwrap();
121 let remaining_segments = path.segments().skip(remaining_index);
122 let is_before_last = remaining_segments.len() == 1;
124 match (def, is_before_last) {
125 (TypeNs::TraitId(trait_), true) => {
127 remaining_segments.last().expect("there should be at least one segment here");
128 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
130 ctx.lower_trait_ref_from_resolved_path(trait_, resolved_segment, None);
131 self.resolve_trait_assoc_item(trait_ref, segment, id)
134 // Either we already have a type (e.g. `Vec::new`), or we have a
135 // trait but it's not the last segment, so the next segment
136 // should resolve to an associated type of that trait (e.g. `<T
137 // as Iterator>::Item::default`)
138 let remaining_segments_for_ty =
139 remaining_segments.take(remaining_segments.len() - 1);
140 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
141 let (ty, _) = ctx.lower_partly_resolved_path(
144 remaining_segments_for_ty,
147 if let TyKind::Error = ty.kind(&Interner) {
151 let ty = self.insert_type_vars(ty);
152 let ty = self.normalize_associated_types_in(ty);
155 remaining_segments.last().expect("there should be at least one segment here");
157 self.resolve_ty_assoc_item(ty, &segment.name, id)
162 fn resolve_trait_assoc_item(
165 segment: PathSegment<'_>,
167 ) -> Option<(ValueNs, Option<Substitution>)> {
168 let trait_ = trait_ref.hir_trait_id();
170 self.db.trait_data(trait_).items.iter().map(|(_name, id)| (*id)).find_map(|item| {
172 AssocItemId::FunctionId(func) => {
173 if segment.name == &self.db.function_data(func).name {
174 Some(AssocItemId::FunctionId(func))
180 AssocItemId::ConstId(konst) => {
186 .map_or(false, |n| n == segment.name)
188 Some(AssocItemId::ConstId(konst))
193 AssocItemId::TypeAliasId(_) => None,
196 let def = match item {
197 AssocItemId::FunctionId(f) => ValueNs::FunctionId(f),
198 AssocItemId::ConstId(c) => ValueNs::ConstId(c),
199 AssocItemId::TypeAliasId(_) => unreachable!(),
202 self.write_assoc_resolution(id, item);
203 Some((def, Some(trait_ref.substitution)))
206 fn resolve_ty_assoc_item(
211 ) -> Option<(ValueNs, Option<Substitution>)> {
212 if let TyKind::Error = ty.kind(&Interner) {
216 if let Some(result) = self.resolve_enum_variant_on_ty(&ty, name, id) {
220 let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone());
221 let krate = self.resolver.krate()?;
222 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
224 method_resolution::iterate_method_candidates(
227 self.trait_env.clone(),
232 method_resolution::LookupMode::Path,
234 let (def, container) = match item {
235 AssocItemId::FunctionId(f) => {
236 (ValueNs::FunctionId(f), f.lookup(self.db.upcast()).container)
238 AssocItemId::ConstId(c) => {
239 (ValueNs::ConstId(c), c.lookup(self.db.upcast()).container)
241 AssocItemId::TypeAliasId(_) => unreachable!(),
243 let substs = match container {
244 AssocContainerId::ImplId(impl_id) => {
245 let impl_substs = TyBuilder::subst_for_def(self.db, impl_id)
246 .fill(iter::repeat_with(|| self.table.new_type_var()))
249 self.db.impl_self_ty(impl_id).substitute(&Interner, &impl_substs);
250 self.unify(&impl_self_ty, &ty);
253 AssocContainerId::TraitId(trait_) => {
254 // we're picking this method
255 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
257 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
259 self.push_obligation(trait_ref.clone().cast(&Interner));
260 Some(trait_ref.substitution)
262 AssocContainerId::ModuleId(_) => None,
265 self.write_assoc_resolution(id, item);
271 fn resolve_enum_variant_on_ty(
276 ) -> Option<(ValueNs, Option<Substitution>)> {
277 let (enum_id, subst) = match ty.as_adt() {
278 Some((AdtId::EnumId(e), subst)) => (e, subst),
281 let enum_data = self.db.enum_data(enum_id);
282 let local_id = enum_data.variant(name)?;
283 let variant = EnumVariantId { parent: enum_id, local_id };
284 self.write_variant_resolution(id, variant.into());
285 Some((ValueNs::EnumVariantId(variant), Some(subst.clone())))