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