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