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.rs506
1 files changed, 506 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..76e0bff34
--- /dev/null
+++ b/crates/ra_hir/src/source_analyzer.rs
@@ -0,0 +1,506 @@
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 DefWithBodyId, TraitId,
20};
21use hir_expand::{
22 hygiene::Hygiene, name::AsName, AstId, HirFileId, InFile, MacroCallId, MacroCallKind,
23};
24use hir_ty::{InEnvironment, InferenceResult, TraitEnvironment};
25use ra_prof::profile;
26use ra_syntax::{
27 ast::{self, AstNode},
28 match_ast, AstPtr,
29 SyntaxKind::*,
30 SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextUnit,
31};
32use rustc_hash::FxHashSet;
33
34use crate::{
35 db::HirDatabase, Adt, Const, DefWithBody, Enum, EnumVariant, FromSource, Function, ImplBlock,
36 Local, MacroDef, Name, Path, ScopeDef, Static, Struct, Trait, Type, TypeAlias, 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 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
351 pub fn traits_in_scope(&self, db: &impl HirDatabase) -> FxHashSet<TraitId> {
352 self.resolver.traits_in_scope(db)
353 }
354
355 pub fn expand(
356 &self,
357 db: &impl HirDatabase,
358 macro_call: InFile<&ast::MacroCall>,
359 ) -> Option<Expansion> {
360 let def = self.resolve_macro_call(db, macro_call)?.id;
361 let ast_id = AstId::new(
362 macro_call.file_id,
363 db.ast_id_map(macro_call.file_id).ast_id(macro_call.value),
364 );
365 Some(Expansion { macro_call_id: def.as_call_id(db, MacroCallKind::FnLike(ast_id)) })
366 }
367}
368
369fn try_get_resolver_for_node(db: &impl HirDatabase, node: InFile<&SyntaxNode>) -> Option<Resolver> {
370 match_ast! {
371 match (node.value) {
372 ast::Module(it) => {
373 let src = node.with_value(it);
374 Some(crate::Module::from_declaration(db, src)?.id.resolver(db))
375 },
376 ast::SourceFile(it) => {
377 let src = node.with_value(ModuleSource::SourceFile(it));
378 Some(crate::Module::from_definition(db, src)?.id.resolver(db))
379 },
380 ast::StructDef(it) => {
381 let src = node.with_value(it);
382 Some(Struct::from_source(db, src)?.id.resolver(db))
383 },
384 ast::EnumDef(it) => {
385 let src = node.with_value(it);
386 Some(Enum::from_source(db, src)?.id.resolver(db))
387 },
388 ast::ImplBlock(it) => {
389 let src = node.with_value(it);
390 Some(ImplBlock::from_source(db, src)?.id.resolver(db))
391 },
392 ast::TraitDef(it) => {
393 let src = node.with_value(it);
394 Some(Trait::from_source(db, src)?.id.resolver(db))
395 },
396 _ => match node.value.kind() {
397 FN_DEF | CONST_DEF | STATIC_DEF => {
398 let def = def_with_body_from_child_node(db, node)?;
399 let def = DefWithBodyId::from(def);
400 Some(def.resolver(db))
401 }
402 // FIXME add missing cases
403 _ => None
404 }
405 }
406 }
407}
408
409fn def_with_body_from_child_node(
410 db: &impl HirDatabase,
411 child: InFile<&SyntaxNode>,
412) -> Option<DefWithBody> {
413 let _p = profile("def_with_body_from_child_node");
414 child.cloned().ancestors_with_macros(db).find_map(|node| {
415 let n = &node.value;
416 match_ast! {
417 match n {
418 ast::FnDef(def) => { return Function::from_source(db, node.with_value(def)).map(DefWithBody::from); },
419 ast::ConstDef(def) => { return Const::from_source(db, node.with_value(def)).map(DefWithBody::from); },
420 ast::StaticDef(def) => { return Static::from_source(db, node.with_value(def)).map(DefWithBody::from); },
421 _ => { None },
422 }
423 }
424 })
425}
426
427fn scope_for(
428 scopes: &ExprScopes,
429 source_map: &BodySourceMap,
430 node: InFile<&SyntaxNode>,
431) -> Option<ScopeId> {
432 node.value
433 .ancestors()
434 .filter_map(ast::Expr::cast)
435 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
436 .find_map(|it| scopes.scope_for(it))
437}
438
439fn scope_for_offset(
440 scopes: &ExprScopes,
441 source_map: &BodySourceMap,
442 offset: InFile<TextUnit>,
443) -> Option<ScopeId> {
444 scopes
445 .scope_by_expr()
446 .iter()
447 .filter_map(|(id, scope)| {
448 let source = source_map.expr_syntax(*id)?;
449 // FIXME: correctly handle macro expansion
450 if source.file_id != offset.file_id {
451 return None;
452 }
453 let syntax_node_ptr =
454 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
455 Some((syntax_node_ptr, scope))
456 })
457 // find containing scope
458 .min_by_key(|(ptr, _scope)| {
459 (
460 !(ptr.range().start() <= offset.value && offset.value <= ptr.range().end()),
461 ptr.range().len(),
462 )
463 })
464 .map(|(ptr, scope)| {
465 adjust(scopes, source_map, ptr, offset.file_id, offset.value).unwrap_or(*scope)
466 })
467}
468
469// XXX: during completion, cursor might be outside of any particular
470// expression. Try to figure out the correct scope...
471fn adjust(
472 scopes: &ExprScopes,
473 source_map: &BodySourceMap,
474 ptr: SyntaxNodePtr,
475 file_id: HirFileId,
476 offset: TextUnit,
477) -> Option<ScopeId> {
478 let r = ptr.range();
479 let child_scopes = scopes
480 .scope_by_expr()
481 .iter()
482 .filter_map(|(id, scope)| {
483 let source = source_map.expr_syntax(*id)?;
484 // FIXME: correctly handle macro expansion
485 if source.file_id != file_id {
486 return None;
487 }
488 let syntax_node_ptr =
489 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
490 Some((syntax_node_ptr, scope))
491 })
492 .map(|(ptr, scope)| (ptr.range(), scope))
493 .filter(|(range, _)| range.start() <= offset && range.is_subrange(&r) && *range != r);
494
495 child_scopes
496 .max_by(|(r1, _), (r2, _)| {
497 if r2.is_subrange(&r1) {
498 std::cmp::Ordering::Greater
499 } else if r1.is_subrange(&r2) {
500 std::cmp::Ordering::Less
501 } else {
502 r1.start().cmp(&r2.start())
503 }
504 })
505 .map(|(_ptr, scope)| *scope)
506}