1 //! Path expression resolution.
6 path::{Path, PathSegment},
7 resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs},
8 AdtId, AssocContainerId, AssocItemId, EnumVariantId, Lookup,
10 use hir_expand::name::Name;
12 use crate::{method_resolution, Interner, Substs, Ty, TyKind, ValueTyDefId};
14 use super::{ExprOrPatId, InferenceContext, TraitRef};
16 impl<'a> InferenceContext<'a> {
17 pub(super) fn infer_path(
23 let ty = self.resolve_value_path(resolver, path, id)?;
24 let ty = self.insert_type_vars(ty);
25 let ty = self.normalize_associated_types_in(ty);
29 fn resolve_value_path(
35 let (value, self_subst) = if let Some(type_ref) = path.type_anchor() {
36 if path.segments().is_empty() {
37 // This can't actually happen syntax-wise
40 let ty = self.make_ty(type_ref);
41 let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1);
42 let ctx = crate::lower::TyLoweringContext::new(self.db, &resolver);
43 let (ty, _) = ctx.lower_ty_relative_path(ty, None, remaining_segments_for_ty);
44 self.resolve_ty_assoc_item(
46 &path.segments().last().expect("path had at least one segment").name,
50 let value_or_partial =
51 resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path())?;
53 match value_or_partial {
54 ResolveValueResult::ValueNs(it) => (it, None),
55 ResolveValueResult::Partial(def, remaining_index) => {
56 self.resolve_assoc_item(def, path, remaining_index, id)?
61 let typable: ValueTyDefId = match value {
62 ValueNs::LocalBinding(pat) => {
63 let ty = self.result.type_of_pat.get(pat)?.clone();
64 let ty = self.resolve_ty_as_possible(ty);
67 ValueNs::FunctionId(it) => it.into(),
68 ValueNs::ConstId(it) => it.into(),
69 ValueNs::StaticId(it) => it.into(),
70 ValueNs::StructId(it) => {
71 self.write_variant_resolution(id, it.into());
75 ValueNs::EnumVariantId(it) => {
76 self.write_variant_resolution(id, it.into());
80 ValueNs::ImplSelf(impl_id) => {
81 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
82 let substs = Substs::type_params_for_generics(self.db, &generics);
83 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
84 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() {
85 let ty = self.db.value_ty(struct_id.into()).subst(&substs);
88 // FIXME: diagnostic, invalid Self reference
92 ValueNs::GenericParam(it) => return Some(self.db.const_param_ty(it)),
95 let ty = self.db.value_ty(typable);
96 // self_subst is just for the parent
97 let parent_substs = self_subst.unwrap_or_else(Substs::empty);
98 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
99 let substs = ctx.substs_from_path(path, typable, true);
100 let full_substs = Substs::builder(substs.len())
101 .use_parent_substs(&parent_substs)
102 .fill(substs.0[parent_substs.len()..].iter().cloned())
104 let ty = ty.subst(&full_substs);
108 fn resolve_assoc_item(
112 remaining_index: usize,
114 ) -> Option<(ValueNs, Option<Substs>)> {
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::Unknown = ty.interned(&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<Substs>)> {
168 let trait_ = trait_ref.trait_;
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.substs)))
206 fn resolve_ty_assoc_item(
211 ) -> Option<(ValueNs, Option<Substs>)> {
212 if let TyKind::Unknown = ty.interned(&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(),
231 method_resolution::LookupMode::Path,
233 let (def, container) = match item {
234 AssocItemId::FunctionId(f) => {
235 (ValueNs::FunctionId(f), f.lookup(self.db.upcast()).container)
237 AssocItemId::ConstId(c) => {
238 (ValueNs::ConstId(c), c.lookup(self.db.upcast()).container)
240 AssocItemId::TypeAliasId(_) => unreachable!(),
242 let substs = match container {
243 AssocContainerId::ImplId(impl_id) => {
244 let impl_substs = Substs::build_for_def(self.db, impl_id)
245 .fill(iter::repeat_with(|| self.table.new_type_var()))
247 let impl_self_ty = self.db.impl_self_ty(impl_id).subst(&impl_substs);
248 self.unify(&impl_self_ty, &ty);
251 AssocContainerId::TraitId(trait_) => {
252 // we're picking this method
253 let trait_substs = Substs::build_for_def(self.db, trait_)
255 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
257 self.obligations.push(super::Obligation::Trait(TraitRef {
259 substs: trait_substs.clone(),
263 AssocContainerId::ModuleId(_) => None,
266 self.write_assoc_resolution(id, item);
272 fn resolve_enum_variant_on_ty(
277 ) -> Option<(ValueNs, Option<Substs>)> {
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())))