]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir/src/source_analyzer.rs
4b509f07c6b73303c0d3a53161f33ae147b1df0e
[rust.git] / crates / ra_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         scope::{ExprScopes, ScopeId},
13         Body, BodySourceMap,
14     },
15     expr::{ExprId, Pat, PatId},
16     resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs},
17     AsMacroCall, DefWithBodyId, FieldId, LocalFieldId, VariantId,
18 };
19 use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
20 use hir_ty::{
21     expr::{record_literal_missing_fields, record_pattern_missing_fields},
22     InferenceResult, Substs, Ty,
23 };
24 use ra_syntax::{
25     ast::{self, AstNode},
26     SyntaxNode, TextRange, TextSize,
27 };
28
29 use crate::{
30     db::HirDatabase, semantics::PathResolution, Adt, Const, EnumVariant, Field, Function, Local,
31     MacroDef, ModPath, ModuleDef, Path, PathKind, Static, Struct, Trait, Type, TypeAlias,
32     TypeParam,
33 };
34 use ra_db::CrateId;
35
36 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
37 /// original source files. It should not be used inside the HIR itself.
38 #[derive(Debug)]
39 pub(crate) struct SourceAnalyzer {
40     file_id: HirFileId,
41     pub(crate) resolver: Resolver,
42     body: Option<Arc<Body>>,
43     body_source_map: Option<Arc<BodySourceMap>>,
44     infer: Option<Arc<InferenceResult>>,
45     scopes: Option<Arc<ExprScopes>>,
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             scopes: Some(scopes),
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             scopes: None,
82             file_id: node.file_id,
83         }
84     }
85
86     fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
87         let src = match expr {
88             ast::Expr::MacroCall(call) => {
89                 self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
90             }
91             _ => InFile::new(self.file_id, expr.clone()),
92         };
93         let sm = self.body_source_map.as_ref()?;
94         sm.node_expr(src.as_ref())
95     }
96
97     fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
98         // FIXME: macros, see `expr_id`
99         let src = InFile { file_id: self.file_id, value: pat };
100         self.body_source_map.as_ref()?.node_pat(src)
101     }
102
103     fn expand_expr(
104         &self,
105         db: &dyn HirDatabase,
106         expr: InFile<ast::MacroCall>,
107     ) -> Option<InFile<ast::Expr>> {
108         let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
109         let expanded = db.parse_or_expand(macro_file)?;
110
111         let res = match ast::MacroCall::cast(expanded.clone()) {
112             Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
113             _ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
114         };
115         Some(res)
116     }
117
118     pub(crate) fn type_of(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<Type> {
119         let expr_id = self.expr_id(db, expr)?;
120         let ty = self.infer.as_ref()?[expr_id].clone();
121         Type::new_with_resolver(db, &self.resolver, ty)
122     }
123
124     pub(crate) fn type_of_pat(&self, db: &dyn HirDatabase, pat: &ast::Pat) -> Option<Type> {
125         let pat_id = self.pat_id(pat)?;
126         let ty = self.infer.as_ref()?[pat_id].clone();
127         Type::new_with_resolver(db, &self.resolver, ty)
128     }
129
130     pub(crate) fn resolve_method_call(
131         &self,
132         db: &dyn HirDatabase,
133         call: &ast::MethodCallExpr,
134     ) -> Option<Function> {
135         let expr_id = self.expr_id(db, &call.clone().into())?;
136         self.infer.as_ref()?.method_resolution(expr_id).map(Function::from)
137     }
138
139     pub(crate) fn resolve_field(
140         &self,
141         db: &dyn HirDatabase,
142         field: &ast::FieldExpr,
143     ) -> Option<Field> {
144         let expr_id = self.expr_id(db, &field.clone().into())?;
145         self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
146     }
147
148     pub(crate) fn resolve_record_field(
149         &self,
150         db: &dyn HirDatabase,
151         field: &ast::RecordField,
152     ) -> Option<(Field, Option<Local>)> {
153         let expr = field.expr()?;
154         let expr_id = self.expr_id(db, &expr)?;
155         let local = if field.name_ref().is_some() {
156             None
157         } else {
158             let local_name = field.field_name()?.as_name();
159             let path = ModPath::from_segments(PathKind::Plain, once(local_name));
160             match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
161                 Some(ValueNs::LocalBinding(pat_id)) => {
162                     Some(Local { pat_id, parent: self.resolver.body_owner()? })
163                 }
164                 _ => None,
165             }
166         };
167         let struct_field = self.infer.as_ref()?.record_field_resolution(expr_id)?;
168         Some((struct_field.into(), local))
169     }
170
171     pub(crate) fn resolve_record_field_pat(
172         &self,
173         _db: &dyn HirDatabase,
174         field: &ast::RecordFieldPat,
175     ) -> Option<Field> {
176         let pat_id = self.pat_id(&field.pat()?)?;
177         let struct_field = self.infer.as_ref()?.record_field_pat_resolution(pat_id)?;
178         Some(struct_field.into())
179     }
180
181     pub(crate) fn resolve_macro_call(
182         &self,
183         db: &dyn HirDatabase,
184         macro_call: InFile<&ast::MacroCall>,
185     ) -> Option<MacroDef> {
186         let hygiene = Hygiene::new(db.upcast(), macro_call.file_id);
187         let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
188         self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
189     }
190
191     pub(crate) fn resolve_bind_pat_to_const(
192         &self,
193         db: &dyn HirDatabase,
194         pat: &ast::BindPat,
195     ) -> Option<ModuleDef> {
196         let pat_id = self.pat_id(&pat.clone().into())?;
197         let body = self.body.as_ref()?;
198         let path = match &body[pat_id] {
199             Pat::Path(path) => path,
200             _ => return None,
201         };
202         let res = resolve_hir_path(db, &self.resolver, &path)?;
203         match res {
204             PathResolution::Def(def) => Some(def),
205             _ => None,
206         }
207     }
208
209     pub(crate) fn resolve_path(
210         &self,
211         db: &dyn HirDatabase,
212         path: &ast::Path,
213     ) -> Option<PathResolution> {
214         if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
215             let expr_id = self.expr_id(db, &path_expr.into())?;
216             if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) {
217                 return Some(PathResolution::AssocItem(assoc.into()));
218             }
219         }
220         if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) {
221             let pat_id = self.pat_id(&path_pat.into())?;
222             if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
223                 return Some(PathResolution::AssocItem(assoc.into()));
224             }
225         }
226         // This must be a normal source file rather than macro file.
227         let hir_path =
228             crate::Path::from_src(path.clone(), &Hygiene::new(db.upcast(), self.file_id))?;
229
230         // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we
231         // trying to resolve foo::bar.
232         if let Some(outer_path) = path.syntax().parent().and_then(ast::Path::cast) {
233             if let Some(qualifier) = outer_path.qualifier() {
234                 if path == &qualifier {
235                     return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
236                 }
237             }
238         }
239
240         resolve_hir_path(db, &self.resolver, &hir_path)
241     }
242
243     pub(crate) fn record_literal_missing_fields(
244         &self,
245         db: &dyn HirDatabase,
246         literal: &ast::RecordLit,
247     ) -> Option<Vec<(Field, Type)>> {
248         let krate = self.resolver.krate()?;
249         let body = self.body.as_ref()?;
250         let infer = self.infer.as_ref()?;
251
252         let expr_id = self.expr_id(db, &literal.clone().into())?;
253         let substs = match &infer.type_of_expr[expr_id] {
254             Ty::Apply(a_ty) => &a_ty.parameters,
255             _ => return None,
256         };
257
258         let (variant, missing_fields, _exhaustive) =
259             record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
260         let res = self.missing_fields(db, krate, substs, variant, missing_fields);
261         Some(res)
262     }
263
264     pub(crate) fn record_pattern_missing_fields(
265         &self,
266         db: &dyn HirDatabase,
267         pattern: &ast::RecordPat,
268     ) -> Option<Vec<(Field, Type)>> {
269         let krate = self.resolver.krate()?;
270         let body = self.body.as_ref()?;
271         let infer = self.infer.as_ref()?;
272
273         let pat_id = self.pat_id(&pattern.clone().into())?;
274         let substs = match &infer.type_of_pat[pat_id] {
275             Ty::Apply(a_ty) => &a_ty.parameters,
276             _ => return None,
277         };
278
279         let (variant, missing_fields, _exhaustive) =
280             record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
281         let res = self.missing_fields(db, krate, substs, variant, missing_fields);
282         Some(res)
283     }
284
285     fn missing_fields(
286         &self,
287         db: &dyn HirDatabase,
288         krate: CrateId,
289         substs: &Substs,
290         variant: VariantId,
291         missing_fields: Vec<LocalFieldId>,
292     ) -> Vec<(Field, Type)> {
293         let field_types = db.field_types(variant);
294
295         missing_fields
296             .into_iter()
297             .map(|local_id| {
298                 let field = FieldId { parent: variant, local_id };
299                 let ty = field_types[local_id].clone().subst(substs);
300                 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
301             })
302             .collect()
303     }
304
305     pub(crate) fn expand(
306         &self,
307         db: &dyn HirDatabase,
308         macro_call: InFile<&ast::MacroCall>,
309     ) -> Option<HirFileId> {
310         let macro_call_id = macro_call.as_call_id(db.upcast(), |path| {
311             self.resolver.resolve_path_as_macro(db.upcast(), &path)
312         })?;
313         Some(macro_call_id.as_file())
314     }
315 }
316
317 fn scope_for(
318     scopes: &ExprScopes,
319     source_map: &BodySourceMap,
320     node: InFile<&SyntaxNode>,
321 ) -> Option<ScopeId> {
322     node.value
323         .ancestors()
324         .filter_map(ast::Expr::cast)
325         .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
326         .find_map(|it| scopes.scope_for(it))
327 }
328
329 fn scope_for_offset(
330     db: &dyn HirDatabase,
331     scopes: &ExprScopes,
332     source_map: &BodySourceMap,
333     offset: InFile<TextSize>,
334 ) -> Option<ScopeId> {
335     scopes
336         .scope_by_expr()
337         .iter()
338         .filter_map(|(id, scope)| {
339             let source = source_map.expr_syntax(*id).ok()?;
340             // FIXME: correctly handle macro expansion
341             if source.file_id != offset.file_id {
342                 return None;
343             }
344             let root = source.file_syntax(db.upcast());
345             let node = source.value.to_node(&root);
346             Some((node.syntax().text_range(), scope))
347         })
348         // find containing scope
349         .min_by_key(|(expr_range, _scope)| {
350             (
351                 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
352                 expr_range.len(),
353             )
354         })
355         .map(|(expr_range, scope)| {
356             adjust(db, scopes, source_map, expr_range, offset.file_id, offset.value)
357                 .unwrap_or(*scope)
358         })
359 }
360
361 // XXX: during completion, cursor might be outside of any particular
362 // expression. Try to figure out the correct scope...
363 fn adjust(
364     db: &dyn HirDatabase,
365     scopes: &ExprScopes,
366     source_map: &BodySourceMap,
367     expr_range: TextRange,
368     file_id: HirFileId,
369     offset: TextSize,
370 ) -> Option<ScopeId> {
371     let child_scopes = scopes
372         .scope_by_expr()
373         .iter()
374         .filter_map(|(id, scope)| {
375             let source = source_map.expr_syntax(*id).ok()?;
376             // FIXME: correctly handle macro expansion
377             if source.file_id != file_id {
378                 return None;
379             }
380             let root = source.file_syntax(db.upcast());
381             let node = source.value.to_node(&root);
382             Some((node.syntax().text_range(), scope))
383         })
384         .filter(|&(range, _)| {
385             range.start() <= offset && expr_range.contains_range(range) && range != expr_range
386         });
387
388     child_scopes
389         .max_by(|&(r1, _), &(r2, _)| {
390             if r1.contains_range(r2) {
391                 std::cmp::Ordering::Greater
392             } else if r2.contains_range(r1) {
393                 std::cmp::Ordering::Less
394             } else {
395                 r1.start().cmp(&r2.start())
396             }
397         })
398         .map(|(_ptr, scope)| *scope)
399 }
400
401 pub(crate) fn resolve_hir_path(
402     db: &dyn HirDatabase,
403     resolver: &Resolver,
404     path: &crate::Path,
405 ) -> Option<PathResolution> {
406     let types =
407         resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
408             TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
409             TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
410             TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
411                 PathResolution::Def(Adt::from(it).into())
412             }
413             TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
414             TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
415             TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
416             TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
417         });
418
419     let body_owner = resolver.body_owner();
420     let values =
421         resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
422             let res = match val {
423                 ValueNs::LocalBinding(pat_id) => {
424                     let var = Local { parent: body_owner?.into(), pat_id };
425                     PathResolution::Local(var)
426                 }
427                 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
428                 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
429                 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
430                 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
431                 ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
432                 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
433             };
434             Some(res)
435         });
436
437     let items = resolver
438         .resolve_module_path_in_items(db.upcast(), path.mod_path())
439         .take_types()
440         .map(|it| PathResolution::Def(it.into()));
441
442     types.or(values).or(items).or_else(|| {
443         resolver
444             .resolve_path_as_macro(db.upcast(), path.mod_path())
445             .map(|def| PathResolution::Macro(def.into()))
446     })
447 }
448
449 /// Resolves a path where we know it is a qualifier of another path.
450 ///
451 /// For example, if we have:
452 /// ```
453 /// mod my {
454 ///     pub mod foo {
455 ///         struct Bar;
456 ///     }
457 ///
458 ///     pub fn foo() {}
459 /// }
460 /// ```
461 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
462 pub(crate) fn resolve_hir_path_qualifier(
463     db: &dyn HirDatabase,
464     resolver: &Resolver,
465     path: &crate::Path,
466 ) -> Option<PathResolution> {
467     let items = resolver
468         .resolve_module_path_in_items(db.upcast(), path.mod_path())
469         .take_types()
470         .map(|it| PathResolution::Def(it.into()));
471
472     if items.is_some() {
473         return items;
474     }
475
476     resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
477         TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
478         TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
479         TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
480         TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
481         TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
482         TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
483         TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
484     })
485 }