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, to_chalk_trait_id, Interner, Substitution, Ty, 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 = Substitution::type_params_for_generics(self.db, &generics);
86 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
87 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() {
88 let ty = self.db.value_ty(struct_id.into()).subst(&substs);
91 // FIXME: diagnostic, invalid Self reference
95 ValueNs::GenericParam(it) => return Some(self.db.const_param_ty(it)),
98 let ty = self.db.value_ty(typable);
99 // self_subst is just for the parent
100 let parent_substs = self_subst.unwrap_or_else(Substitution::empty);
101 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
102 let substs = ctx.substs_from_path(path, typable, true);
103 let full_substs = Substitution::builder(substs.len())
104 .use_parent_substs(&parent_substs)
105 .fill(substs.0[parent_substs.len()..].iter().cloned())
107 let ty = ty.subst(&full_substs);
111 fn resolve_assoc_item(
115 remaining_index: usize,
117 ) -> Option<(ValueNs, Option<Substitution>)> {
118 assert!(remaining_index < path.segments().len());
119 // there may be more intermediate segments between the resolved one and
120 // the end. Only the last segment needs to be resolved to a value; from
121 // the segments before that, we need to get either a type or a trait ref.
123 let resolved_segment = path.segments().get(remaining_index - 1).unwrap();
124 let remaining_segments = path.segments().skip(remaining_index);
125 let is_before_last = remaining_segments.len() == 1;
127 match (def, is_before_last) {
128 (TypeNs::TraitId(trait_), true) => {
130 remaining_segments.last().expect("there should be at least one segment here");
131 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
133 ctx.lower_trait_ref_from_resolved_path(trait_, resolved_segment, None);
134 self.resolve_trait_assoc_item(trait_ref, segment, id)
137 // Either we already have a type (e.g. `Vec::new`), or we have a
138 // trait but it's not the last segment, so the next segment
139 // should resolve to an associated type of that trait (e.g. `<T
140 // as Iterator>::Item::default`)
141 let remaining_segments_for_ty =
142 remaining_segments.take(remaining_segments.len() - 1);
143 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
144 let (ty, _) = ctx.lower_partly_resolved_path(
147 remaining_segments_for_ty,
150 if let TyKind::Unknown = ty.interned(&Interner) {
154 let ty = self.insert_type_vars(ty);
155 let ty = self.normalize_associated_types_in(ty);
158 remaining_segments.last().expect("there should be at least one segment here");
160 self.resolve_ty_assoc_item(ty, &segment.name, id)
165 fn resolve_trait_assoc_item(
168 segment: PathSegment<'_>,
170 ) -> Option<(ValueNs, Option<Substitution>)> {
171 let trait_ = trait_ref.hir_trait_id();
173 self.db.trait_data(trait_).items.iter().map(|(_name, id)| (*id)).find_map(|item| {
175 AssocItemId::FunctionId(func) => {
176 if segment.name == &self.db.function_data(func).name {
177 Some(AssocItemId::FunctionId(func))
183 AssocItemId::ConstId(konst) => {
189 .map_or(false, |n| n == segment.name)
191 Some(AssocItemId::ConstId(konst))
196 AssocItemId::TypeAliasId(_) => None,
199 let def = match item {
200 AssocItemId::FunctionId(f) => ValueNs::FunctionId(f),
201 AssocItemId::ConstId(c) => ValueNs::ConstId(c),
202 AssocItemId::TypeAliasId(_) => unreachable!(),
205 self.write_assoc_resolution(id, item);
206 Some((def, Some(trait_ref.substitution)))
209 fn resolve_ty_assoc_item(
214 ) -> Option<(ValueNs, Option<Substitution>)> {
215 if let TyKind::Unknown = ty.interned(&Interner) {
219 if let Some(result) = self.resolve_enum_variant_on_ty(&ty, name, id) {
223 let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone());
224 let krate = self.resolver.krate()?;
225 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
227 method_resolution::iterate_method_candidates(
230 self.trait_env.clone(),
235 method_resolution::LookupMode::Path,
237 let (def, container) = match item {
238 AssocItemId::FunctionId(f) => {
239 (ValueNs::FunctionId(f), f.lookup(self.db.upcast()).container)
241 AssocItemId::ConstId(c) => {
242 (ValueNs::ConstId(c), c.lookup(self.db.upcast()).container)
244 AssocItemId::TypeAliasId(_) => unreachable!(),
246 let substs = match container {
247 AssocContainerId::ImplId(impl_id) => {
248 let impl_substs = Substitution::build_for_def(self.db, impl_id)
249 .fill(iter::repeat_with(|| self.table.new_type_var()))
251 let impl_self_ty = self.db.impl_self_ty(impl_id).subst(&impl_substs);
252 self.unify(&impl_self_ty, &ty);
255 AssocContainerId::TraitId(trait_) => {
256 // we're picking this method
257 let trait_substs = Substitution::build_for_def(self.db, trait_)
259 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
261 self.push_obligation(
263 trait_id: to_chalk_trait_id(trait_),
264 substitution: trait_substs.clone(),
270 AssocContainerId::ModuleId(_) => None,
273 self.write_assoc_resolution(id, item);
279 fn resolve_enum_variant_on_ty(
284 ) -> Option<(ValueNs, Option<Substitution>)> {
285 let (enum_id, subst) = match ty.as_adt() {
286 Some((AdtId::EnumId(e), subst)) => (e, subst),
289 let enum_data = self.db.enum_data(enum_id);
290 let local_id = enum_data.variant(name)?;
291 let variant = EnumVariantId { parent: enum_id, local_id };
292 self.write_variant_resolution(id, variant.into());
293 Some((ValueNs::EnumVariantId(variant), Some(subst.clone())))