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