]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/source_analyzer.rs
Merge #11065
[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         }
294
295         if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
296             let pat_id = self.pat_id(&path_pat.into())?;
297             if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
298                 return Some(PathResolution::AssocItem(assoc.into()));
299             }
300             if let Some(VariantId::EnumVariantId(variant)) =
301                 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
302             {
303                 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
304             }
305         }
306
307         if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
308             let expr_id = self.expr_id(db, &rec_lit.into())?;
309             if let Some(VariantId::EnumVariantId(variant)) =
310                 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
311             {
312                 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
313             }
314         }
315
316         let record_pat = parent().and_then(ast::RecordPat::cast).map(ast::Pat::from);
317         let tuple_struct_pat = || parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from);
318         if let Some(pat) = record_pat.or_else(tuple_struct_pat) {
319             let pat_id = self.pat_id(&pat)?;
320             let variant_res_for_pat = self.infer.as_ref()?.variant_resolution_for_pat(pat_id);
321             if let Some(VariantId::EnumVariantId(variant)) = variant_res_for_pat {
322                 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
323             }
324         }
325
326         // This must be a normal source file rather than macro file.
327         let hygiene = Hygiene::new(db.upcast(), self.file_id);
328         let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
329         let hir_path = Path::from_src(path.clone(), &ctx)?;
330
331         // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
332         // trying to resolve foo::bar.
333         if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
334             if let Some(qualifier) = use_tree.path() {
335                 if path == &qualifier && use_tree.coloncolon_token().is_some() {
336                     return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
337                 }
338             }
339         }
340
341         let is_path_of_attr = path
342             .top_path()
343             .syntax()
344             .ancestors()
345             .nth(2) // Path -> Meta -> Attr
346             .map_or(false, |it| ast::Attr::can_cast(it.kind()));
347
348         // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
349         // trying to resolve foo::bar.
350         if let Some(outer_path) = path.parent_path() {
351             if let Some(qualifier) = outer_path.qualifier() {
352                 if path == &qualifier {
353                     return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
354                 }
355             }
356         } else if is_path_of_attr {
357             // Case where we are resolving the final path segment of a path in an attribute
358             // in this case we have to check for inert/builtin attributes and tools and prioritize
359             // resolution of attributes over other namesapces
360             let name_ref = path.as_single_name_ref();
361             let builtin =
362                 name_ref.as_ref().map(ast::NameRef::text).as_deref().and_then(BuiltinAttr::by_name);
363             if let builtin @ Some(_) = builtin {
364                 return builtin.map(PathResolution::BuiltinAttr);
365             }
366             return match resolve_hir_path_as_macro(db, &self.resolver, &hir_path) {
367                 res @ Some(m) if m.is_attr() => res.map(PathResolution::Macro),
368                 _ => name_ref.and_then(|name_ref| {
369                     ToolModule::by_name(&name_ref.text()).map(PathResolution::ToolModule)
370                 }),
371             };
372         }
373
374         let res = if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
375             resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
376         } else {
377             resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
378         };
379         match res {
380             Some(_) => res,
381             // this labels any path that starts with a tool module as the tool itself, this is technically wrong
382             // but there is no benefit in differentiating these two cases for the time being
383             None if is_path_of_attr => path
384                 .first_segment()
385                 .and_then(|seg| seg.name_ref())
386                 .and_then(|name_ref| ToolModule::by_name(&name_ref.text()))
387                 .map(PathResolution::ToolModule),
388             None => None,
389         }
390     }
391
392     pub(crate) fn record_literal_missing_fields(
393         &self,
394         db: &dyn HirDatabase,
395         literal: &ast::RecordExpr,
396     ) -> Option<Vec<(Field, Type)>> {
397         let krate = self.resolver.krate()?;
398         let body = self.body.as_ref()?;
399         let infer = self.infer.as_ref()?;
400
401         let expr_id = self.expr_id(db, &literal.clone().into())?;
402         let substs = infer.type_of_expr[expr_id].as_adt()?.1;
403
404         let (variant, missing_fields, _exhaustive) =
405             record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
406         let res = self.missing_fields(db, krate, substs, variant, missing_fields);
407         Some(res)
408     }
409
410     pub(crate) fn record_pattern_missing_fields(
411         &self,
412         db: &dyn HirDatabase,
413         pattern: &ast::RecordPat,
414     ) -> Option<Vec<(Field, Type)>> {
415         let krate = self.resolver.krate()?;
416         let body = self.body.as_ref()?;
417         let infer = self.infer.as_ref()?;
418
419         let pat_id = self.pat_id(&pattern.clone().into())?;
420         let substs = infer.type_of_pat[pat_id].as_adt()?.1;
421
422         let (variant, missing_fields, _exhaustive) =
423             record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
424         let res = self.missing_fields(db, krate, substs, variant, missing_fields);
425         Some(res)
426     }
427
428     fn missing_fields(
429         &self,
430         db: &dyn HirDatabase,
431         krate: CrateId,
432         substs: &Substitution,
433         variant: VariantId,
434         missing_fields: Vec<LocalFieldId>,
435     ) -> Vec<(Field, Type)> {
436         let field_types = db.field_types(variant);
437
438         missing_fields
439             .into_iter()
440             .map(|local_id| {
441                 let field = FieldId { parent: variant, local_id };
442                 let ty = field_types[local_id].clone().substitute(Interner, substs);
443                 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
444             })
445             .collect()
446     }
447
448     pub(crate) fn expand(
449         &self,
450         db: &dyn HirDatabase,
451         macro_call: InFile<&ast::MacroCall>,
452     ) -> Option<HirFileId> {
453         let krate = self.resolver.krate()?;
454         let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
455             self.resolver.resolve_path_as_macro(db.upcast(), &path)
456         })?;
457         Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
458     }
459
460     pub(crate) fn resolve_variant(
461         &self,
462         db: &dyn HirDatabase,
463         record_lit: ast::RecordExpr,
464     ) -> Option<VariantId> {
465         let infer = self.infer.as_ref()?;
466         let expr_id = self.expr_id(db, &record_lit.into())?;
467         infer.variant_resolution_for_expr(expr_id)
468     }
469 }
470
471 fn scope_for(
472     scopes: &ExprScopes,
473     source_map: &BodySourceMap,
474     node: InFile<&SyntaxNode>,
475 ) -> Option<ScopeId> {
476     node.value
477         .ancestors()
478         .filter_map(ast::Expr::cast)
479         .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
480         .find_map(|it| scopes.scope_for(it))
481 }
482
483 fn scope_for_offset(
484     db: &dyn HirDatabase,
485     scopes: &ExprScopes,
486     source_map: &BodySourceMap,
487     offset: InFile<TextSize>,
488 ) -> Option<ScopeId> {
489     scopes
490         .scope_by_expr()
491         .iter()
492         .filter_map(|(id, scope)| {
493             let source = source_map.expr_syntax(*id).ok()?;
494             // FIXME: correctly handle macro expansion
495             if source.file_id != offset.file_id {
496                 return None;
497             }
498             let root = source.file_syntax(db.upcast());
499             let node = source.value.to_node(&root);
500             Some((node.syntax().text_range(), scope))
501         })
502         // find containing scope
503         .min_by_key(|(expr_range, _scope)| {
504             (
505                 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
506                 expr_range.len(),
507             )
508         })
509         .map(|(expr_range, scope)| {
510             adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
511         })
512 }
513
514 // XXX: during completion, cursor might be outside of any particular
515 // expression. Try to figure out the correct scope...
516 fn adjust(
517     db: &dyn HirDatabase,
518     scopes: &ExprScopes,
519     source_map: &BodySourceMap,
520     expr_range: TextRange,
521     offset: InFile<TextSize>,
522 ) -> Option<ScopeId> {
523     let child_scopes = scopes
524         .scope_by_expr()
525         .iter()
526         .filter_map(|(id, scope)| {
527             let source = source_map.expr_syntax(*id).ok()?;
528             // FIXME: correctly handle macro expansion
529             if source.file_id != offset.file_id {
530                 return None;
531             }
532             let root = source.file_syntax(db.upcast());
533             let node = source.value.to_node(&root);
534             Some((node.syntax().text_range(), scope))
535         })
536         .filter(|&(range, _)| {
537             range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
538         });
539
540     child_scopes
541         .max_by(|&(r1, _), &(r2, _)| {
542             if r1.contains_range(r2) {
543                 std::cmp::Ordering::Greater
544             } else if r2.contains_range(r1) {
545                 std::cmp::Ordering::Less
546             } else {
547                 r1.start().cmp(&r2.start())
548             }
549         })
550         .map(|(_ptr, scope)| *scope)
551 }
552
553 #[inline]
554 pub(crate) fn resolve_hir_path(
555     db: &dyn HirDatabase,
556     resolver: &Resolver,
557     path: &Path,
558 ) -> Option<PathResolution> {
559     resolve_hir_path_(db, resolver, path, false)
560 }
561
562 #[inline]
563 pub(crate) fn resolve_hir_path_as_macro(
564     db: &dyn HirDatabase,
565     resolver: &Resolver,
566     path: &Path,
567 ) -> Option<MacroDef> {
568     resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(Into::into)
569 }
570
571 fn resolve_hir_path_(
572     db: &dyn HirDatabase,
573     resolver: &Resolver,
574     path: &Path,
575     prefer_value_ns: bool,
576 ) -> Option<PathResolution> {
577     let types = || {
578         let (ty, unresolved) = match path.type_anchor() {
579             Some(type_ref) => {
580                 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
581                 res.map(|ty_ns| (ty_ns, path.segments().first()))
582             }
583             None => {
584                 let (ty, remaining) =
585                     resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
586                 match remaining {
587                     Some(remaining) if remaining > 1 => None,
588                     _ => Some((ty, path.segments().get(1))),
589                 }
590             }
591         }?;
592
593         // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
594         // within the trait's associated types.
595         if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
596             if let Some(type_alias_id) =
597                 db.trait_data(trait_id).associated_type_by_name(&unresolved.name)
598             {
599                 return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
600             }
601         }
602
603         let res = match ty {
604             TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
605             TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
606             TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
607                 PathResolution::Def(Adt::from(it).into())
608             }
609             TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
610             TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
611             TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
612             TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
613         };
614         match unresolved {
615             Some(unresolved) => res
616                 .assoc_type_shorthand_candidates(db, |name, alias| {
617                     (name == unresolved.name).then(|| alias)
618                 })
619                 .map(TypeAlias::from)
620                 .map(Into::into)
621                 .map(PathResolution::Def),
622             None => Some(res),
623         }
624     };
625
626     let body_owner = resolver.body_owner();
627     let values = || {
628         resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
629             let res = match val {
630                 ValueNs::LocalBinding(pat_id) => {
631                     let var = Local { parent: body_owner?, pat_id };
632                     PathResolution::Local(var)
633                 }
634                 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
635                 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
636                 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
637                 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
638                 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
639                 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
640                 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
641             };
642             Some(res)
643         })
644     };
645
646     let items = || {
647         resolver
648             .resolve_module_path_in_items(db.upcast(), path.mod_path())
649             .take_types()
650             .map(|it| PathResolution::Def(it.into()))
651     };
652
653     let macros = || {
654         resolver
655             .resolve_path_as_macro(db.upcast(), path.mod_path())
656             .map(|def| PathResolution::Macro(def.into()))
657     };
658
659     if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
660         .or_else(items)
661         .or_else(macros)
662 }
663
664 /// Resolves a path where we know it is a qualifier of another path.
665 ///
666 /// For example, if we have:
667 /// ```
668 /// mod my {
669 ///     pub mod foo {
670 ///         struct Bar;
671 ///     }
672 ///
673 ///     pub fn foo() {}
674 /// }
675 /// ```
676 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
677 fn resolve_hir_path_qualifier(
678     db: &dyn HirDatabase,
679     resolver: &Resolver,
680     path: &Path,
681 ) -> Option<PathResolution> {
682     let items = resolver
683         .resolve_module_path_in_items(db.upcast(), path.mod_path())
684         .take_types()
685         .map(|it| PathResolution::Def(it.into()));
686
687     if items.is_some() {
688         return items;
689     }
690
691     resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
692         TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
693         TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
694         TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
695         TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
696         TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
697         TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
698         TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
699     })
700 }