aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/source_analyzer.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir/src/source_analyzer.rs')
-rw-r--r--crates/ra_hir/src/source_analyzer.rs546
1 files changed, 546 insertions, 0 deletions
diff --git a/crates/ra_hir/src/source_analyzer.rs b/crates/ra_hir/src/source_analyzer.rs
new file mode 100644
index 000000000..3df48842d
--- /dev/null
+++ b/crates/ra_hir/src/source_analyzer.rs
@@ -0,0 +1,546 @@
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::sync::Arc;
9
10use either::Either;
11use hir_def::{
12 body::{
13 scope::{ExprScopes, ScopeId},
14 BodySourceMap,
15 },
16 expr::{ExprId, PatId},
17 nameres::ModuleSource,
18 resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs},
19 AssocItemId, DefWithBodyId,
20};
21use hir_expand::{
22 hygiene::Hygiene, name::AsName, AstId, HirFileId, InFile, MacroCallId, MacroCallKind,
23};
24use hir_ty::{method_resolution, Canonical, InEnvironment, InferenceResult, TraitEnvironment, Ty};
25use ra_prof::profile;
26use ra_syntax::{
27 ast::{self, AstNode},
28 match_ast, AstPtr,
29 SyntaxKind::*,
30 SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextUnit,
31};
32
33use crate::{
34 db::HirDatabase, Adt, AssocItem, Const, DefWithBody, Enum, EnumVariant, FromSource, Function,
35 ImplBlock, Local, MacroDef, Name, Path, ScopeDef, Static, Struct, Trait, Type, TypeAlias,
36 TypeParam,
37};
38
39/// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
40/// original source files. It should not be used inside the HIR itself.
41#[derive(Debug)]
42pub struct SourceAnalyzer {
43 file_id: HirFileId,
44 resolver: Resolver,
45 body_owner: Option<DefWithBody>,
46 body_source_map: Option<Arc<BodySourceMap>>,
47 infer: Option<Arc<InferenceResult>>,
48 scopes: Option<Arc<ExprScopes>>,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum PathResolution {
53 /// An item
54 Def(crate::ModuleDef),
55 /// A local binding (only value namespace)
56 Local(Local),
57 /// A generic parameter
58 TypeParam(TypeParam),
59 SelfType(crate::ImplBlock),
60 Macro(MacroDef),
61 AssocItem(crate::AssocItem),
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct ScopeEntryWithSyntax {
66 pub(crate) name: Name,
67 pub(crate) ptr: Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>,
68}
69
70impl ScopeEntryWithSyntax {
71 pub fn name(&self) -> &Name {
72 &self.name
73 }
74
75 pub fn ptr(&self) -> Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>> {
76 self.ptr
77 }
78}
79
80#[derive(Debug)]
81pub struct ReferenceDescriptor {
82 pub range: TextRange,
83 pub name: String,
84}
85
86#[derive(Debug)]
87pub struct Expansion {
88 macro_call_id: MacroCallId,
89}
90
91impl Expansion {
92 pub fn map_token_down(
93 &self,
94 db: &impl HirDatabase,
95 token: InFile<&SyntaxToken>,
96 ) -> Option<InFile<SyntaxToken>> {
97 let exp_info = self.file_id().expansion_info(db)?;
98 exp_info.map_token_down(token)
99 }
100
101 pub fn file_id(&self) -> HirFileId {
102 self.macro_call_id.as_file()
103 }
104}
105
106impl SourceAnalyzer {
107 pub fn new(
108 db: &impl HirDatabase,
109 node: InFile<&SyntaxNode>,
110 offset: Option<TextUnit>,
111 ) -> SourceAnalyzer {
112 let _p = profile("SourceAnalyzer::new");
113 let def_with_body = def_with_body_from_child_node(db, node);
114 if let Some(def) = def_with_body {
115 let (_body, source_map) = db.body_with_source_map(def.into());
116 let scopes = db.expr_scopes(def.into());
117 let scope = match offset {
118 None => scope_for(&scopes, &source_map, node),
119 Some(offset) => scope_for_offset(&scopes, &source_map, node.with_value(offset)),
120 };
121 let resolver = resolver_for_scope(db, def.into(), scope);
122 SourceAnalyzer {
123 resolver,
124 body_owner: Some(def),
125 body_source_map: Some(source_map),
126 infer: Some(db.infer(def.into())),
127 scopes: Some(scopes),
128 file_id: node.file_id,
129 }
130 } else {
131 SourceAnalyzer {
132 resolver: node
133 .value
134 .ancestors()
135 .find_map(|it| try_get_resolver_for_node(db, node.with_value(&it)))
136 .unwrap_or_default(),
137 body_owner: None,
138 body_source_map: None,
139 infer: None,
140 scopes: None,
141 file_id: node.file_id,
142 }
143 }
144 }
145
146 pub fn module(&self) -> Option<crate::code_model::Module> {
147 Some(crate::code_model::Module { id: self.resolver.module()? })
148 }
149
150 fn expr_id(&self, expr: &ast::Expr) -> Option<ExprId> {
151 let src = InFile { file_id: self.file_id, value: expr };
152 self.body_source_map.as_ref()?.node_expr(src)
153 }
154
155 fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
156 let src = InFile { file_id: self.file_id, value: pat };
157 self.body_source_map.as_ref()?.node_pat(src)
158 }
159
160 fn expand_expr(
161 &self,
162 db: &impl HirDatabase,
163 expr: InFile<&ast::Expr>,
164 ) -> Option<InFile<ast::Expr>> {
165 let macro_call = ast::MacroCall::cast(expr.value.syntax().clone())?;
166 let macro_file =
167 self.body_source_map.as_ref()?.node_macro_file(expr.with_value(&macro_call))?;
168 let expanded = db.parse_or_expand(macro_file)?;
169 let kind = expanded.kind();
170 let expr = InFile::new(macro_file, ast::Expr::cast(expanded)?);
171
172 if ast::MacroCall::can_cast(kind) {
173 self.expand_expr(db, expr.as_ref())
174 } else {
175 Some(expr)
176 }
177 }
178
179 pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> {
180 let expr_id = if let Some(expr) = self.expand_expr(db, InFile::new(self.file_id, expr)) {
181 self.body_source_map.as_ref()?.node_expr(expr.as_ref())?
182 } else {
183 self.expr_id(expr)?
184 };
185
186 let ty = self.infer.as_ref()?[expr_id].clone();
187 let environment = TraitEnvironment::lower(db, &self.resolver);
188 Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
189 }
190
191 pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> {
192 let pat_id = self.pat_id(pat)?;
193 let ty = self.infer.as_ref()?[pat_id].clone();
194 let environment = TraitEnvironment::lower(db, &self.resolver);
195 Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
196 }
197
198 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
199 let expr_id = self.expr_id(&call.clone().into())?;
200 self.infer.as_ref()?.method_resolution(expr_id).map(Function::from)
201 }
202
203 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> {
204 let expr_id = self.expr_id(&field.clone().into())?;
205 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
206 }
207
208 pub fn resolve_record_field(&self, field: &ast::RecordField) -> Option<crate::StructField> {
209 let expr_id = match field.expr() {
210 Some(it) => self.expr_id(&it)?,
211 None => {
212 let src = InFile { file_id: self.file_id, value: field };
213 self.body_source_map.as_ref()?.field_init_shorthand_expr(src)?
214 }
215 };
216 self.infer.as_ref()?.record_field_resolution(expr_id).map(|it| it.into())
217 }
218
219 pub fn resolve_record_literal(&self, record_lit: &ast::RecordLit) -> Option<crate::VariantDef> {
220 let expr_id = self.expr_id(&record_lit.clone().into())?;
221 self.infer.as_ref()?.variant_resolution_for_expr(expr_id).map(|it| it.into())
222 }
223
224 pub fn resolve_record_pattern(&self, record_pat: &ast::RecordPat) -> Option<crate::VariantDef> {
225 let pat_id = self.pat_id(&record_pat.clone().into())?;
226 self.infer.as_ref()?.variant_resolution_for_pat(pat_id).map(|it| it.into())
227 }
228
229 pub fn resolve_macro_call(
230 &self,
231 db: &impl HirDatabase,
232 macro_call: InFile<&ast::MacroCall>,
233 ) -> Option<MacroDef> {
234 let hygiene = Hygiene::new(db, macro_call.file_id);
235 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
236 self.resolver.resolve_path_as_macro(db, path.mod_path()).map(|it| it.into())
237 }
238
239 pub fn resolve_hir_path(
240 &self,
241 db: &impl HirDatabase,
242 path: &crate::Path,
243 ) -> Option<PathResolution> {
244 let types =
245 self.resolver.resolve_path_in_type_ns_fully(db, path.mod_path()).map(|ty| match ty {
246 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
247 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
248 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
249 PathResolution::Def(Adt::from(it).into())
250 }
251 TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
252 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
253 TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
254 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
255 });
256 let values =
257 self.resolver.resolve_path_in_value_ns_fully(db, path.mod_path()).and_then(|val| {
258 let res = match val {
259 ValueNs::LocalBinding(pat_id) => {
260 let var = Local { parent: self.body_owner?, pat_id };
261 PathResolution::Local(var)
262 }
263 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
264 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
265 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
266 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
267 ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
268 };
269 Some(res)
270 });
271
272 let items = self
273 .resolver
274 .resolve_module_path_in_items(db, path.mod_path())
275 .take_types()
276 .map(|it| PathResolution::Def(it.into()));
277 types.or(values).or(items).or_else(|| {
278 self.resolver
279 .resolve_path_as_macro(db, path.mod_path())
280 .map(|def| PathResolution::Macro(def.into()))
281 })
282 }
283
284 pub fn resolve_path(&self, db: &impl HirDatabase, path: &ast::Path) -> Option<PathResolution> {
285 if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
286 let expr_id = self.expr_id(&path_expr.into())?;
287 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) {
288 return Some(PathResolution::AssocItem(assoc.into()));
289 }
290 }
291 if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) {
292 let pat_id = self.pat_id(&path_pat.into())?;
293 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
294 return Some(PathResolution::AssocItem(assoc.into()));
295 }
296 }
297 // This must be a normal source file rather than macro file.
298 let hir_path = crate::Path::from_ast(path.clone())?;
299 self.resolve_hir_path(db, &hir_path)
300 }
301
302 fn resolve_local_name(&self, name_ref: &ast::NameRef) -> Option<ScopeEntryWithSyntax> {
303 let name = name_ref.as_name();
304 let source_map = self.body_source_map.as_ref()?;
305 let scopes = self.scopes.as_ref()?;
306 let scope = scope_for(scopes, source_map, InFile::new(self.file_id, name_ref.syntax()))?;
307 let entry = scopes.resolve_name_in_scope(scope, &name)?;
308 Some(ScopeEntryWithSyntax {
309 name: entry.name().clone(),
310 ptr: source_map.pat_syntax(entry.pat())?.value,
311 })
312 }
313
314 pub fn process_all_names(&self, db: &impl HirDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
315 self.resolver.process_all_names(db, &mut |name, def| {
316 let def = match def {
317 resolver::ScopeDef::PerNs(it) => it.into(),
318 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
319 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
320 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
321 resolver::ScopeDef::Local(pat_id) => {
322 let parent = self.resolver.body_owner().unwrap().into();
323 ScopeDef::Local(Local { parent, pat_id })
324 }
325 };
326 f(name, def)
327 })
328 }
329
330 // FIXME: we only use this in `inline_local_variable` assist, ideally, we
331 // should switch to general reference search infra there.
332 pub fn find_all_refs(&self, pat: &ast::BindPat) -> Vec<ReferenceDescriptor> {
333 let fn_def = pat.syntax().ancestors().find_map(ast::FnDef::cast).unwrap();
334 let ptr = Either::Left(AstPtr::new(&ast::Pat::from(pat.clone())));
335 fn_def
336 .syntax()
337 .descendants()
338 .filter_map(ast::NameRef::cast)
339 .filter(|name_ref| match self.resolve_local_name(&name_ref) {
340 None => false,
341 Some(entry) => entry.ptr() == ptr,
342 })
343 .map(|name_ref| ReferenceDescriptor {
344 name: name_ref.text().to_string(),
345 range: name_ref.syntax().text_range(),
346 })
347 .collect()
348 }
349
350 pub fn iterate_method_candidates<T>(
351 &self,
352 db: &impl HirDatabase,
353 ty: &Type,
354 name: Option<&Name>,
355 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
356 ) -> Option<T> {
357 // There should be no inference vars in types passed here
358 // FIXME check that?
359 // FIXME replace Unknown by bound vars here
360 let canonical = Canonical { value: ty.ty.value.clone(), num_vars: 0 };
361 method_resolution::iterate_method_candidates(
362 &canonical,
363 db,
364 &self.resolver,
365 name,
366 method_resolution::LookupMode::MethodCall,
367 |ty, it| match it {
368 AssocItemId::FunctionId(f) => callback(ty, f.into()),
369 _ => None,
370 },
371 )
372 }
373
374 pub fn iterate_path_candidates<T>(
375 &self,
376 db: &impl HirDatabase,
377 ty: &Type,
378 name: Option<&Name>,
379 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
380 ) -> Option<T> {
381 // There should be no inference vars in types passed here
382 // FIXME check that?
383 // FIXME replace Unknown by bound vars here
384 let canonical = Canonical { value: ty.ty.value.clone(), num_vars: 0 };
385 method_resolution::iterate_method_candidates(
386 &canonical,
387 db,
388 &self.resolver,
389 name,
390 method_resolution::LookupMode::Path,
391 |ty, it| callback(ty, it.into()),
392 )
393 }
394
395 pub fn expand(
396 &self,
397 db: &impl HirDatabase,
398 macro_call: InFile<&ast::MacroCall>,
399 ) -> Option<Expansion> {
400 let def = self.resolve_macro_call(db, macro_call)?.id;
401 let ast_id = AstId::new(
402 macro_call.file_id,
403 db.ast_id_map(macro_call.file_id).ast_id(macro_call.value),
404 );
405 Some(Expansion { macro_call_id: def.as_call_id(db, MacroCallKind::FnLike(ast_id)) })
406 }
407}
408
409fn try_get_resolver_for_node(db: &impl HirDatabase, node: InFile<&SyntaxNode>) -> Option<Resolver> {
410 match_ast! {
411 match (node.value) {
412 ast::Module(it) => {
413 let src = node.with_value(it);
414 Some(crate::Module::from_declaration(db, src)?.id.resolver(db))
415 },
416 ast::SourceFile(it) => {
417 let src = node.with_value(ModuleSource::SourceFile(it));
418 Some(crate::Module::from_definition(db, src)?.id.resolver(db))
419 },
420 ast::StructDef(it) => {
421 let src = node.with_value(it);
422 Some(Struct::from_source(db, src)?.id.resolver(db))
423 },
424 ast::EnumDef(it) => {
425 let src = node.with_value(it);
426 Some(Enum::from_source(db, src)?.id.resolver(db))
427 },
428 ast::ImplBlock(it) => {
429 let src = node.with_value(it);
430 Some(ImplBlock::from_source(db, src)?.id.resolver(db))
431 },
432 ast::TraitDef(it) => {
433 let src = node.with_value(it);
434 Some(Trait::from_source(db, src)?.id.resolver(db))
435 },
436 _ => match node.value.kind() {
437 FN_DEF | CONST_DEF | STATIC_DEF => {
438 let def = def_with_body_from_child_node(db, node)?;
439 let def = DefWithBodyId::from(def);
440 Some(def.resolver(db))
441 }
442 // FIXME add missing cases
443 _ => None
444 }
445 }
446 }
447}
448
449fn def_with_body_from_child_node(
450 db: &impl HirDatabase,
451 child: InFile<&SyntaxNode>,
452) -> Option<DefWithBody> {
453 let _p = profile("def_with_body_from_child_node");
454 child.cloned().ancestors_with_macros(db).find_map(|node| {
455 let n = &node.value;
456 match_ast! {
457 match n {
458 ast::FnDef(def) => { return Function::from_source(db, node.with_value(def)).map(DefWithBody::from); },
459 ast::ConstDef(def) => { return Const::from_source(db, node.with_value(def)).map(DefWithBody::from); },
460 ast::StaticDef(def) => { return Static::from_source(db, node.with_value(def)).map(DefWithBody::from); },
461 _ => { None },
462 }
463 }
464 })
465}
466
467fn scope_for(
468 scopes: &ExprScopes,
469 source_map: &BodySourceMap,
470 node: InFile<&SyntaxNode>,
471) -> Option<ScopeId> {
472 node.value
473 .ancestors()
474 .filter_map(ast::Expr::cast)
475 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
476 .find_map(|it| scopes.scope_for(it))
477}
478
479fn scope_for_offset(
480 scopes: &ExprScopes,
481 source_map: &BodySourceMap,
482 offset: InFile<TextUnit>,
483) -> Option<ScopeId> {
484 scopes
485 .scope_by_expr()
486 .iter()
487 .filter_map(|(id, scope)| {
488 let source = source_map.expr_syntax(*id)?;
489 // FIXME: correctly handle macro expansion
490 if source.file_id != offset.file_id {
491 return None;
492 }
493 let syntax_node_ptr =
494 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
495 Some((syntax_node_ptr, scope))
496 })
497 // find containing scope
498 .min_by_key(|(ptr, _scope)| {
499 (
500 !(ptr.range().start() <= offset.value && offset.value <= ptr.range().end()),
501 ptr.range().len(),
502 )
503 })
504 .map(|(ptr, scope)| {
505 adjust(scopes, source_map, ptr, offset.file_id, offset.value).unwrap_or(*scope)
506 })
507}
508
509// XXX: during completion, cursor might be outside of any particular
510// expression. Try to figure out the correct scope...
511fn adjust(
512 scopes: &ExprScopes,
513 source_map: &BodySourceMap,
514 ptr: SyntaxNodePtr,
515 file_id: HirFileId,
516 offset: TextUnit,
517) -> Option<ScopeId> {
518 let r = ptr.range();
519 let child_scopes = scopes
520 .scope_by_expr()
521 .iter()
522 .filter_map(|(id, scope)| {
523 let source = source_map.expr_syntax(*id)?;
524 // FIXME: correctly handle macro expansion
525 if source.file_id != file_id {
526 return None;
527 }
528 let syntax_node_ptr =
529 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
530 Some((syntax_node_ptr, scope))
531 })
532 .map(|(ptr, scope)| (ptr.range(), scope))
533 .filter(|(range, _)| range.start() <= offset && range.is_subrange(&r) && *range != r);
534
535 child_scopes
536 .max_by(|(r1, _), (r2, _)| {
537 if r2.is_subrange(&r1) {
538 std::cmp::Ordering::Greater
539 } else if r1.is_subrange(&r2) {
540 std::cmp::Ordering::Less
541 } else {
542 r1.start().cmp(&r2.start())
543 }
544 })
545 .map(|(_ptr, scope)| *scope)
546}