]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/source_analyzer.rs
Merge #11173
[rust.git] / crates / hir / src / source_analyzer.rs
1 //! Lookup hir elements using positions in the source code. This is a lossy
2 //! transformation: in general, a single source might correspond to several
3 //! modules, functions, etc, due to macros, cfgs and `#[path=]` attributes on
4 //! modules.
5 //!
6 //! So, this modules should not be used during hir construction, it exists
7 //! purely for "IDE needs".
8 use std::{iter::once, sync::Arc};
9
10 use hir_def::{
11     body::{
12         self,
13         scope::{ExprScopes, ScopeId},
14         Body, BodySourceMap,
15     },
16     expr::{ExprId, Pat, PatId},
17     path::{ModPath, Path, PathKind},
18     resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs},
19     AsMacroCall, DefWithBodyId, FieldId, FunctionId, LocalFieldId, ModuleDefId, VariantId,
20 };
21 use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
22 use hir_ty::{
23     diagnostics::{record_literal_missing_fields, record_pattern_missing_fields},
24     InferenceResult, Interner, Substitution, TyExt, TyLoweringContext,
25 };
26 use syntax::{
27     ast::{self, AstNode},
28     SyntaxNode, TextRange, TextSize,
29 };
30
31 use crate::{
32     db::HirDatabase, semantics::PathResolution, Adt, BuiltinAttr, BuiltinType, Const, Field,
33     Function, Local, MacroDef, ModuleDef, Static, Struct, ToolModule, Trait, Type, TypeAlias,
34     TypeParam, Variant,
35 };
36 use base_db::CrateId;
37
38 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
39 /// original source files. It should not be used inside the HIR itself.
40 #[derive(Debug)]
41 pub(crate) struct SourceAnalyzer {
42     pub(crate) file_id: HirFileId,
43     pub(crate) resolver: Resolver,
44     body: Option<Arc<Body>>,
45     body_source_map: Option<Arc<BodySourceMap>>,
46     infer: Option<Arc<InferenceResult>>,
47 }
48
49 impl SourceAnalyzer {
50     pub(crate) fn new_for_body(
51         db: &dyn HirDatabase,
52         def: DefWithBodyId,
53         node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
54         offset: Option<TextSize>,
55     ) -> SourceAnalyzer {
56         let (body, source_map) = db.body_with_source_map(def);
57         let scopes = db.expr_scopes(def);
58         let scope = match offset {
59             None => scope_for(&scopes, &source_map, node),
60             Some(offset) => scope_for_offset(db, &scopes, &source_map, node.with_value(offset)),
61         };
62         let resolver = resolver_for_scope(db.upcast(), def, scope);
63         SourceAnalyzer {
64             resolver,
65             body: Some(body),
66             body_source_map: Some(source_map),
67             infer: Some(db.infer(def)),
68             file_id,
69         }
70     }
71
72     pub(crate) fn new_for_body_no_infer(
73         db: &dyn HirDatabase,
74         def: DefWithBodyId,
75         node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
76         offset: Option<TextSize>,
77     ) -> SourceAnalyzer {
78         let (body, source_map) = db.body_with_source_map(def);
79         let scopes = db.expr_scopes(def);
80         let scope = match offset {
81             None => scope_for(&scopes, &source_map, node),
82             Some(offset) => scope_for_offset(db, &scopes, &source_map, node.with_value(offset)),
83         };
84         let resolver = resolver_for_scope(db.upcast(), def, scope);
85         SourceAnalyzer {
86             resolver,
87             body: Some(body),
88             body_source_map: Some(source_map),
89             infer: None,
90             file_id,
91         }
92     }
93
94     pub(crate) fn new_for_resolver(
95         resolver: Resolver,
96         node: InFile<&SyntaxNode>,
97     ) -> SourceAnalyzer {
98         SourceAnalyzer {
99             resolver,
100             body: None,
101             body_source_map: None,
102             infer: None,
103             file_id: node.file_id,
104         }
105     }
106
107     fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
108         let src = match expr {
109             ast::Expr::MacroCall(call) => {
110                 self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
111             }
112             _ => InFile::new(self.file_id, expr.clone()),
113         };
114         let sm = self.body_source_map.as_ref()?;
115         sm.node_expr(src.as_ref())
116     }
117
118     fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
119         // FIXME: macros, see `expr_id`
120         let src = InFile { file_id: self.file_id, value: pat };
121         self.body_source_map.as_ref()?.node_pat(src)
122     }
123
124     fn expand_expr(
125         &self,
126         db: &dyn HirDatabase,
127         expr: InFile<ast::MacroCall>,
128     ) -> Option<InFile<ast::Expr>> {
129         let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
130         let expanded = db.parse_or_expand(macro_file)?;
131
132         let res = match ast::MacroCall::cast(expanded.clone()) {
133             Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
134             _ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
135         };
136         Some(res)
137     }
138
139     pub(crate) fn type_of_expr(
140         &self,
141         db: &dyn HirDatabase,
142         expr: &ast::Expr,
143     ) -> Option<(Type, Option<Type>)> {
144         let expr_id = self.expr_id(db, expr)?;
145         let infer = self.infer.as_ref()?;
146         let coerced = infer
147             .expr_adjustments
148             .get(&expr_id)
149             .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
150         let ty = infer[expr_id].clone();
151         let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
152         mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
153     }
154
155     pub(crate) fn type_of_pat(
156         &self,
157         db: &dyn HirDatabase,
158         pat: &ast::Pat,
159     ) -> Option<(Type, Option<Type>)> {
160         let pat_id = self.pat_id(pat)?;
161         let infer = self.infer.as_ref()?;
162         let coerced = infer
163             .pat_adjustments
164             .get(&pat_id)
165             .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
166         let ty = infer[pat_id].clone();
167         let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
168         mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
169     }
170
171     pub(crate) fn type_of_self(
172         &self,
173         db: &dyn HirDatabase,
174         param: &ast::SelfParam,
175     ) -> Option<Type> {
176         let src = InFile { file_id: self.file_id, value: param };
177         let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
178         let ty = self.infer.as_ref()?[pat_id].clone();
179         Type::new_with_resolver(db, &self.resolver, ty)
180     }
181
182     pub(crate) fn resolve_method_call(
183         &self,
184         db: &dyn HirDatabase,
185         call: &ast::MethodCallExpr,
186     ) -> Option<(FunctionId, Substitution)> {
187         let expr_id = self.expr_id(db, &call.clone().into())?;
188         self.infer.as_ref()?.method_resolution(expr_id)
189     }
190
191     pub(crate) fn resolve_field(
192         &self,
193         db: &dyn HirDatabase,
194         field: &ast::FieldExpr,
195     ) -> Option<Field> {
196         let expr_id = self.expr_id(db, &field.clone().into())?;
197         self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
198     }
199
200     pub(crate) fn resolve_record_field(
201         &self,
202         db: &dyn HirDatabase,
203         field: &ast::RecordExprField,
204     ) -> Option<(Field, Option<Local>, Type)> {
205         let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
206         let expr = ast::Expr::from(record_expr);
207         let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
208
209         let local_name = field.field_name()?.as_name();
210         let local = if field.name_ref().is_some() {
211             None
212         } else {
213             let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
214             match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
215                 Some(ValueNs::LocalBinding(pat_id)) => {
216                     Some(Local { pat_id, parent: self.resolver.body_owner()? })
217                 }
218                 _ => None,
219             }
220         };
221         let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
222         let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
223         let variant_data = variant.variant_data(db.upcast());
224         let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
225         let field_ty =
226             db.field_types(variant).get(field.local_id)?.clone().substitute(Interner, subst);
227         Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
228     }
229
230     pub(crate) fn resolve_record_pat_field(
231         &self,
232         db: &dyn HirDatabase,
233         field: &ast::RecordPatField,
234     ) -> Option<Field> {
235         let field_name = field.field_name()?.as_name();
236         let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
237         let pat_id = self.pat_id(&record_pat.into())?;
238         let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
239         let variant_data = variant.variant_data(db.upcast());
240         let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
241         Some(field.into())
242     }
243
244     pub(crate) fn resolve_macro_call(
245         &self,
246         db: &dyn HirDatabase,
247         macro_call: InFile<&ast::MacroCall>,
248     ) -> Option<MacroDef> {
249         let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
250         let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
251         self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
252     }
253
254     pub(crate) fn resolve_bind_pat_to_const(
255         &self,
256         db: &dyn HirDatabase,
257         pat: &ast::IdentPat,
258     ) -> Option<ModuleDef> {
259         let pat_id = self.pat_id(&pat.clone().into())?;
260         let body = self.body.as_ref()?;
261         let path = match &body[pat_id] {
262             Pat::Path(path) => path,
263             _ => return None,
264         };
265         let res = resolve_hir_path(db, &self.resolver, path)?;
266         match res {
267             PathResolution::Def(def) => Some(def),
268             _ => None,
269         }
270     }
271
272     pub(crate) fn resolve_path(
273         &self,
274         db: &dyn HirDatabase,
275         path: &ast::Path,
276     ) -> Option<PathResolution> {
277         let parent = path.syntax().parent();
278         let parent = || parent.clone();
279
280         let mut prefer_value_ns = false;
281         if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
282             let expr_id = self.expr_id(db, &path_expr.into())?;
283             let infer = self.infer.as_ref()?;
284             if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
285                 return Some(PathResolution::AssocItem(assoc.into()));
286             }
287             if let Some(VariantId::EnumVariantId(variant)) =
288                 infer.variant_resolution_for_expr(expr_id)
289             {
290                 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
291             }
292             prefer_value_ns = true;
293         } else if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
294             let pat_id = self.pat_id(&path_pat.into())?;
295             if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
296                 return Some(PathResolution::AssocItem(assoc.into()));
297             }
298             if let Some(VariantId::EnumVariantId(variant)) =
299                 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
300             {
301                 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
302             }
303         } else if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
304             let expr_id = self.expr_id(db, &rec_lit.into())?;
305             if let Some(VariantId::EnumVariantId(variant)) =
306                 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
307             {
308                 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
309             }
310         }
311
312         let record_pat = parent().and_then(ast::RecordPat::cast).map(ast::Pat::from);
313         let tuple_struct_pat = || parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from);
314         if let Some(pat) = record_pat.or_else(tuple_struct_pat) {
315             let pat_id = self.pat_id(&pat)?;
316             let variant_res_for_pat = self.infer.as_ref()?.variant_resolution_for_pat(pat_id);
317             if let Some(VariantId::EnumVariantId(variant)) = variant_res_for_pat {
318                 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
319             }
320         }
321
322         // This must be a normal source file rather than macro file.
323         let hygiene = Hygiene::new(db.upcast(), self.file_id);
324         let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
325         let hir_path = Path::from_src(path.clone(), &ctx)?;
326
327         // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
328         // trying to resolve foo::bar.
329         if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
330             if use_tree.coloncolon_token().is_some() {
331                 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
332             }
333         }
334
335         let is_path_of_attr = path
336             .syntax()
337             .ancestors()
338             .map(|it| it.kind())
339             .take_while(|&kind| ast::Path::can_cast(kind) || ast::Meta::can_cast(kind))
340             .last()
341             .map_or(false, ast::Meta::can_cast);
342
343         // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
344         // trying to resolve foo::bar.
345         if path.parent_path().is_some() {
346             return match resolve_hir_path_qualifier(db, &self.resolver, &hir_path) {
347                 None if is_path_of_attr => {
348                     path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| {
349                         ToolModule::by_name(&name_ref.text()).map(PathResolution::ToolModule)
350                     })
351                 }
352                 res => res,
353             };
354         } else if is_path_of_attr {
355             // Case where we are resolving the final path segment of a path in an attribute
356             // in this case we have to check for inert/builtin attributes and tools and prioritize
357             // resolution of attributes over other namespaces
358             let name_ref = path.as_single_name_ref();
359             let builtin =
360                 name_ref.as_ref().map(ast::NameRef::text).as_deref().and_then(BuiltinAttr::by_name);
361             if let builtin @ Some(_) = builtin {
362                 return builtin.map(PathResolution::BuiltinAttr);
363             }
364             return match resolve_hir_path_as_macro(db, &self.resolver, &hir_path) {
365                 res @ Some(m) if m.is_attr() => res.map(PathResolution::Macro),
366                 // this labels any path that starts with a tool module as the tool itself, this is technically wrong
367                 // but there is no benefit in differentiating these two cases for the time being
368                 _ => path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| {
369                     ToolModule::by_name(&name_ref.text()).map(PathResolution::ToolModule)
370                 }),
371             };
372         }
373         if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
374             resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
375         } else {
376             resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
377         }
378     }
379
380     pub(crate) fn record_literal_missing_fields(
381         &self,
382         db: &dyn HirDatabase,
383         literal: &ast::RecordExpr,
384     ) -> Option<Vec<(Field, Type)>> {
385         let krate = self.resolver.krate()?;
386         let body = self.body.as_ref()?;
387         let infer = self.infer.as_ref()?;
388
389         let expr_id = self.expr_id(db, &literal.clone().into())?;
390         let substs = infer.type_of_expr[expr_id].as_adt()?.1;
391
392         let (variant, missing_fields, _exhaustive) =
393             record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
394         let res = self.missing_fields(db, krate, substs, variant, missing_fields);
395         Some(res)
396     }
397
398     pub(crate) fn record_pattern_missing_fields(
399         &self,
400         db: &dyn HirDatabase,
401         pattern: &ast::RecordPat,
402     ) -> Option<Vec<(Field, Type)>> {
403         let krate = self.resolver.krate()?;
404         let body = self.body.as_ref()?;
405         let infer = self.infer.as_ref()?;
406
407         let pat_id = self.pat_id(&pattern.clone().into())?;
408         let substs = infer.type_of_pat[pat_id].as_adt()?.1;
409
410         let (variant, missing_fields, _exhaustive) =
411             record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
412         let res = self.missing_fields(db, krate, substs, variant, missing_fields);
413         Some(res)
414     }
415
416     fn missing_fields(
417         &self,
418         db: &dyn HirDatabase,
419         krate: CrateId,
420         substs: &Substitution,
421         variant: VariantId,
422         missing_fields: Vec<LocalFieldId>,
423     ) -> Vec<(Field, Type)> {
424         let field_types = db.field_types(variant);
425
426         missing_fields
427             .into_iter()
428             .map(|local_id| {
429                 let field = FieldId { parent: variant, local_id };
430                 let ty = field_types[local_id].clone().substitute(Interner, substs);
431                 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
432             })
433             .collect()
434     }
435
436     pub(crate) fn expand(
437         &self,
438         db: &dyn HirDatabase,
439         macro_call: InFile<&ast::MacroCall>,
440     ) -> Option<HirFileId> {
441         let krate = self.resolver.krate()?;
442         let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
443             self.resolver.resolve_path_as_macro(db.upcast(), &path)
444         })?;
445         Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
446     }
447
448     pub(crate) fn resolve_variant(
449         &self,
450         db: &dyn HirDatabase,
451         record_lit: ast::RecordExpr,
452     ) -> Option<VariantId> {
453         let infer = self.infer.as_ref()?;
454         let expr_id = self.expr_id(db, &record_lit.into())?;
455         infer.variant_resolution_for_expr(expr_id)
456     }
457 }
458
459 fn scope_for(
460     scopes: &ExprScopes,
461     source_map: &BodySourceMap,
462     node: InFile<&SyntaxNode>,
463 ) -> Option<ScopeId> {
464     node.value
465         .ancestors()
466         .filter_map(ast::Expr::cast)
467         .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
468         .find_map(|it| scopes.scope_for(it))
469 }
470
471 fn scope_for_offset(
472     db: &dyn HirDatabase,
473     scopes: &ExprScopes,
474     source_map: &BodySourceMap,
475     offset: InFile<TextSize>,
476 ) -> Option<ScopeId> {
477     scopes
478         .scope_by_expr()
479         .iter()
480         .filter_map(|(id, scope)| {
481             let source = source_map.expr_syntax(*id).ok()?;
482             // FIXME: correctly handle macro expansion
483             if source.file_id != offset.file_id {
484                 return None;
485             }
486             let root = source.file_syntax(db.upcast());
487             let node = source.value.to_node(&root);
488             Some((node.syntax().text_range(), scope))
489         })
490         // find containing scope
491         .min_by_key(|(expr_range, _scope)| {
492             (
493                 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
494                 expr_range.len(),
495             )
496         })
497         .map(|(expr_range, scope)| {
498             adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
499         })
500 }
501
502 // XXX: during completion, cursor might be outside of any particular
503 // expression. Try to figure out the correct scope...
504 fn adjust(
505     db: &dyn HirDatabase,
506     scopes: &ExprScopes,
507     source_map: &BodySourceMap,
508     expr_range: TextRange,
509     offset: InFile<TextSize>,
510 ) -> Option<ScopeId> {
511     let child_scopes = scopes
512         .scope_by_expr()
513         .iter()
514         .filter_map(|(id, scope)| {
515             let source = source_map.expr_syntax(*id).ok()?;
516             // FIXME: correctly handle macro expansion
517             if source.file_id != offset.file_id {
518                 return None;
519             }
520             let root = source.file_syntax(db.upcast());
521             let node = source.value.to_node(&root);
522             Some((node.syntax().text_range(), scope))
523         })
524         .filter(|&(range, _)| {
525             range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
526         });
527
528     child_scopes
529         .max_by(|&(r1, _), &(r2, _)| {
530             if r1.contains_range(r2) {
531                 std::cmp::Ordering::Greater
532             } else if r2.contains_range(r1) {
533                 std::cmp::Ordering::Less
534             } else {
535                 r1.start().cmp(&r2.start())
536             }
537         })
538         .map(|(_ptr, scope)| *scope)
539 }
540
541 #[inline]
542 pub(crate) fn resolve_hir_path(
543     db: &dyn HirDatabase,
544     resolver: &Resolver,
545     path: &Path,
546 ) -> Option<PathResolution> {
547     resolve_hir_path_(db, resolver, path, false)
548 }
549
550 #[inline]
551 pub(crate) fn resolve_hir_path_as_macro(
552     db: &dyn HirDatabase,
553     resolver: &Resolver,
554     path: &Path,
555 ) -> Option<MacroDef> {
556     resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(Into::into)
557 }
558
559 fn resolve_hir_path_(
560     db: &dyn HirDatabase,
561     resolver: &Resolver,
562     path: &Path,
563     prefer_value_ns: bool,
564 ) -> Option<PathResolution> {
565     let types = || {
566         let (ty, unresolved) = match path.type_anchor() {
567             Some(type_ref) => {
568                 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
569                 res.map(|ty_ns| (ty_ns, path.segments().first()))
570             }
571             None => {
572                 let (ty, remaining) =
573                     resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
574                 match remaining {
575                     Some(remaining) if remaining > 1 => None,
576                     _ => Some((ty, path.segments().get(1))),
577                 }
578             }
579         }?;
580
581         // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
582         // within the trait's associated types.
583         if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
584             if let Some(type_alias_id) =
585                 db.trait_data(trait_id).associated_type_by_name(&unresolved.name)
586             {
587                 return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
588             }
589         }
590
591         let res = match ty {
592             TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
593             TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
594             TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
595                 PathResolution::Def(Adt::from(it).into())
596             }
597             TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
598             TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
599             TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
600             TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
601         };
602         match unresolved {
603             Some(unresolved) => res
604                 .assoc_type_shorthand_candidates(db, |name, alias| {
605                     (name == unresolved.name).then(|| alias)
606                 })
607                 .map(TypeAlias::from)
608                 .map(Into::into)
609                 .map(PathResolution::Def),
610             None => Some(res),
611         }
612     };
613
614     let body_owner = resolver.body_owner();
615     let values = || {
616         resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
617             let res = match val {
618                 ValueNs::LocalBinding(pat_id) => {
619                     let var = Local { parent: body_owner?, pat_id };
620                     PathResolution::Local(var)
621                 }
622                 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
623                 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
624                 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
625                 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
626                 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
627                 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
628                 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
629             };
630             Some(res)
631         })
632     };
633
634     let items = || {
635         resolver
636             .resolve_module_path_in_items(db.upcast(), path.mod_path())
637             .take_types()
638             .map(|it| PathResolution::Def(it.into()))
639     };
640
641     let macros = || {
642         resolver
643             .resolve_path_as_macro(db.upcast(), path.mod_path())
644             .map(|def| PathResolution::Macro(def.into()))
645     };
646
647     if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
648         .or_else(items)
649         .or_else(macros)
650 }
651
652 /// Resolves a path where we know it is a qualifier of another path.
653 ///
654 /// For example, if we have:
655 /// ```
656 /// mod my {
657 ///     pub mod foo {
658 ///         struct Bar;
659 ///     }
660 ///
661 ///     pub fn foo() {}
662 /// }
663 /// ```
664 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
665 fn resolve_hir_path_qualifier(
666     db: &dyn HirDatabase,
667     resolver: &Resolver,
668     path: &Path,
669 ) -> Option<PathResolution> {
670     let items = resolver
671         .resolve_module_path_in_items(db.upcast(), path.mod_path())
672         .take_types()
673         .map(|it| PathResolution::Def(it.into()));
674
675     if items.is_some() {
676         return items;
677     }
678
679     resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
680         TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
681         TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
682         TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
683         TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
684         TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
685         TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
686         TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
687     })
688 }