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, 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();
68 let ty = self.resolve_ty_as_possible(ty);
71 ValueNs::FunctionId(it) => it.into(),
72 ValueNs::ConstId(it) => it.into(),
73 ValueNs::StaticId(it) => it.into(),
74 ValueNs::StructId(it) => {
75 self.write_variant_resolution(id, it.into());
79 ValueNs::EnumVariantId(it) => {
80 self.write_variant_resolution(id, it.into());
84 ValueNs::ImplSelf(impl_id) => {
85 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
86 let substs = generics.type_params_subst(self.db);
87 let ty = self.db.impl_self_ty(impl_id).substitute(&Interner, &substs);
88 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() {
89 let ty = self.db.value_ty(struct_id.into()).substitute(&Interner, &substs);
92 // FIXME: diagnostic, invalid Self reference
96 ValueNs::GenericParam(it) => return Some(self.db.const_param_ty(it)),
99 let parent_substs = self_subst.unwrap_or_else(|| Substitution::empty(&Interner));
100 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
101 let substs = ctx.substs_from_path(path, typable, true);
102 let ty = TyBuilder::value_ty(self.db, typable)
103 .use_parent_substs(&parent_substs)
104 .fill(substs.as_slice(&Interner)[parent_substs.len(&Interner)..].iter().cloned())
109 fn resolve_assoc_item(
113 remaining_index: usize,
115 ) -> Option<(ValueNs, Option<Substitution>)> {
116 assert!(remaining_index < path.segments().len());
117 // there may be more intermediate segments between the resolved one and
118 // the end. Only the last segment needs to be resolved to a value; from
119 // the segments before that, we need to get either a type or a trait ref.
121 let resolved_segment = path.segments().get(remaining_index - 1).unwrap();
122 let remaining_segments = path.segments().skip(remaining_index);
123 let is_before_last = remaining_segments.len() == 1;
125 match (def, is_before_last) {
126 (TypeNs::TraitId(trait_), true) => {
128 remaining_segments.last().expect("there should be at least one segment here");
129 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
131 ctx.lower_trait_ref_from_resolved_path(trait_, resolved_segment, None);
132 self.resolve_trait_assoc_item(trait_ref, segment, id)
135 // Either we already have a type (e.g. `Vec::new`), or we have a
136 // trait but it's not the last segment, so the next segment
137 // should resolve to an associated type of that trait (e.g. `<T
138 // as Iterator>::Item::default`)
139 let remaining_segments_for_ty =
140 remaining_segments.take(remaining_segments.len() - 1);
141 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
142 let (ty, _) = ctx.lower_partly_resolved_path(
145 remaining_segments_for_ty,
148 if let TyKind::Error = ty.kind(&Interner) {
152 let ty = self.insert_type_vars(ty);
153 let ty = self.normalize_associated_types_in(ty);
156 remaining_segments.last().expect("there should be at least one segment here");
158 self.resolve_ty_assoc_item(ty, &segment.name, id)
163 fn resolve_trait_assoc_item(
166 segment: PathSegment<'_>,
168 ) -> Option<(ValueNs, Option<Substitution>)> {
169 let trait_ = trait_ref.hir_trait_id();
171 self.db.trait_data(trait_).items.iter().map(|(_name, id)| (*id)).find_map(|item| {
173 AssocItemId::FunctionId(func) => {
174 if segment.name == &self.db.function_data(func).name {
175 Some(AssocItemId::FunctionId(func))
181 AssocItemId::ConstId(konst) => {
187 .map_or(false, |n| n == segment.name)
189 Some(AssocItemId::ConstId(konst))
194 AssocItemId::TypeAliasId(_) => None,
197 let def = match item {
198 AssocItemId::FunctionId(f) => ValueNs::FunctionId(f),
199 AssocItemId::ConstId(c) => ValueNs::ConstId(c),
200 AssocItemId::TypeAliasId(_) => unreachable!(),
203 self.write_assoc_resolution(id, item);
204 Some((def, Some(trait_ref.substitution)))
207 fn resolve_ty_assoc_item(
212 ) -> Option<(ValueNs, Option<Substitution>)> {
213 if let TyKind::Error = ty.kind(&Interner) {
217 if let Some(result) = self.resolve_enum_variant_on_ty(&ty, name, id) {
221 let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone());
222 let krate = self.resolver.krate()?;
223 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
225 method_resolution::iterate_method_candidates(
228 self.trait_env.clone(),
233 method_resolution::LookupMode::Path,
235 let (def, container) = match item {
236 AssocItemId::FunctionId(f) => {
237 (ValueNs::FunctionId(f), f.lookup(self.db.upcast()).container)
239 AssocItemId::ConstId(c) => {
240 (ValueNs::ConstId(c), c.lookup(self.db.upcast()).container)
242 AssocItemId::TypeAliasId(_) => unreachable!(),
244 let substs = match container {
245 AssocContainerId::ImplId(impl_id) => {
246 let impl_substs = TyBuilder::subst_for_def(self.db, impl_id)
247 .fill(iter::repeat_with(|| self.table.new_type_var()))
250 self.db.impl_self_ty(impl_id).substitute(&Interner, &impl_substs);
251 self.unify(&impl_self_ty, &ty);
254 AssocContainerId::TraitId(trait_) => {
255 // we're picking this method
256 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
258 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
260 self.push_obligation(trait_ref.clone().cast(&Interner));
261 Some(trait_ref.substitution)
263 AssocContainerId::ModuleId(_) => None,
266 self.write_assoc_resolution(id, item);
272 fn resolve_enum_variant_on_ty(
277 ) -> Option<(ValueNs, Option<Substitution>)> {
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())))