1 //! Path expression resolution.
5 use chalk_ir::cast::Cast;
7 path::{Path, PathSegment},
8 resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs},
9 AdtId, AssocItemId, EnumVariantId, ItemContainerId, Lookup,
11 use hir_expand::name::Name;
14 method_resolution, Interner, Substitution, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
18 use super::{ExprOrPatId, InferenceContext, TraitRef};
20 impl<'a> InferenceContext<'a> {
21 pub(super) fn infer_path(
27 let ty = self.resolve_value_path(resolver, path, id)?;
28 let ty = self.insert_type_vars(ty);
29 let ty = self.normalize_associated_types_in(ty);
33 fn resolve_value_path(
39 let (value, self_subst) = if let Some(type_ref) = path.type_anchor() {
40 if path.segments().is_empty() {
41 // This can't actually happen syntax-wise
44 let ty = self.make_ty(type_ref);
45 let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1);
46 let ctx = crate::lower::TyLoweringContext::new(self.db, resolver);
47 let (ty, _) = ctx.lower_ty_relative_path(ty, None, remaining_segments_for_ty);
48 self.resolve_ty_assoc_item(
50 path.segments().last().expect("path had at least one segment").name,
54 let value_or_partial =
55 resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path())?;
57 match value_or_partial {
58 ResolveValueResult::ValueNs(it) => (it, None),
59 ResolveValueResult::Partial(def, remaining_index) => {
60 self.resolve_assoc_item(def, path, remaining_index, id)?
65 let typable: ValueTyDefId = match value {
66 ValueNs::LocalBinding(pat) => {
67 let ty = self.result.type_of_pat.get(pat)?.clone();
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.as_slice(&Interner)[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.canonicalize(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.table.trait_env.clone(),
230 self.resolver.module(),
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 ItemContainerId::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 ItemContainerId::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 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
265 self.write_assoc_resolution(id, item);
271 fn resolve_enum_variant_on_ty(
276 ) -> Option<(ValueNs, Option<Substitution>)> {
277 let ty = self.resolve_ty_shallow(ty);
278 let (enum_id, subst) = match ty.as_adt() {
279 Some((AdtId::EnumId(e), subst)) => (e, subst),
282 let enum_data = self.db.enum_data(enum_id);
283 let local_id = enum_data.variant(name)?;
284 let variant = EnumVariantId { parent: enum_id, local_id };
285 self.write_variant_resolution(id, variant.into());
286 Some((ValueNs::EnumVariantId(variant), Some(subst.clone())))