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