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