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