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