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
6 //! So, this modules should not be used during hir construction, it exists
7 //! purely for "IDE needs".
13 scope::{ExprScopes, ScopeId},
16 expr::{ExprId, PatId},
18 resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs},
19 AssocItemId, DefWithBodyId,
22 hygiene::Hygiene, name::AsName, AstId, HirFileId, InFile, MacroCallId, MacroFileKind,
28 SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextUnit,
34 method_resolution::{self, implements_trait},
35 InEnvironment, TraitEnvironment, Ty,
37 Adt, AssocItem, Const, DefWithBody, Enum, EnumVariant, FromSource, Function, GenericParam,
38 Local, MacroDef, Name, Path, ScopeDef, Static, Struct, Trait, Type, TypeAlias,
41 fn try_get_resolver_for_node(db: &impl HirDatabase, node: InFile<&SyntaxNode>) -> Option<Resolver> {
45 let src = node.with_value(it);
46 Some(crate::Module::from_declaration(db, src)?.id.resolver(db))
48 ast::SourceFile(it) => {
49 let src = node.with_value(crate::ModuleSource::SourceFile(it));
50 Some(crate::Module::from_definition(db, src)?.id.resolver(db))
52 ast::StructDef(it) => {
53 let src = node.with_value(it);
54 Some(Struct::from_source(db, src)?.id.resolver(db))
57 let src = node.with_value(it);
58 Some(Enum::from_source(db, src)?.id.resolver(db))
60 _ => match node.value.kind() {
61 FN_DEF | CONST_DEF | STATIC_DEF => {
62 let def = def_with_body_from_child_node(db, node)?;
63 let def = DefWithBodyId::from(def);
64 Some(def.resolver(db))
66 // FIXME add missing cases
73 fn def_with_body_from_child_node(
74 db: &impl HirDatabase,
75 child: InFile<&SyntaxNode>,
76 ) -> Option<DefWithBody> {
77 child.value.ancestors().find_map(|node| {
80 ast::FnDef(def) => { return Function::from_source(db, child.with_value(def)).map(DefWithBody::from); },
81 ast::ConstDef(def) => { return Const::from_source(db, child.with_value(def)).map(DefWithBody::from); },
82 ast::StaticDef(def) => { return Static::from_source(db, child.with_value(def)).map(DefWithBody::from); },
89 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
90 /// original source files. It should not be used inside the HIR itself.
92 pub struct SourceAnalyzer {
95 body_owner: Option<DefWithBody>,
96 body_source_map: Option<Arc<BodySourceMap>>,
97 infer: Option<Arc<crate::ty::InferenceResult>>,
98 scopes: Option<Arc<ExprScopes>>,
101 #[derive(Debug, Clone, PartialEq, Eq)]
102 pub enum PathResolution {
104 Def(crate::ModuleDef),
105 /// A local binding (only value namespace)
107 /// A generic parameter
108 GenericParam(GenericParam),
109 SelfType(crate::ImplBlock),
111 AssocItem(crate::AssocItem),
114 #[derive(Debug, Clone, PartialEq, Eq)]
115 pub struct ScopeEntryWithSyntax {
116 pub(crate) name: Name,
117 pub(crate) ptr: Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>,
120 impl ScopeEntryWithSyntax {
121 pub fn name(&self) -> &Name {
125 pub fn ptr(&self) -> Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>> {
131 pub struct ReferenceDescriptor {
132 pub range: TextRange,
136 pub struct Expansion {
137 macro_file_kind: MacroFileKind,
138 macro_call_id: MacroCallId,
142 pub fn map_token_down(
144 db: &impl HirDatabase,
145 token: InFile<&SyntaxToken>,
146 ) -> Option<InFile<SyntaxToken>> {
147 let exp_info = self.file_id().expansion_info(db)?;
148 exp_info.map_token_down(token)
151 pub fn file_id(&self) -> HirFileId {
152 self.macro_call_id.as_file(self.macro_file_kind)
156 impl SourceAnalyzer {
158 db: &impl HirDatabase,
159 node: InFile<&SyntaxNode>,
160 offset: Option<TextUnit>,
161 ) -> SourceAnalyzer {
162 let def_with_body = def_with_body_from_child_node(db, node);
163 if let Some(def) = def_with_body {
164 let (_body, source_map) = db.body_with_source_map(def.into());
165 let scopes = db.expr_scopes(def.into());
166 let scope = match offset {
167 None => scope_for(&scopes, &source_map, node),
168 Some(offset) => scope_for_offset(&scopes, &source_map, node.with_value(offset)),
170 let resolver = resolver_for_scope(db, def.into(), scope);
173 body_owner: Some(def),
174 body_source_map: Some(source_map),
175 infer: Some(db.infer(def.into())),
176 scopes: Some(scopes),
177 file_id: node.file_id,
184 .find_map(|it| try_get_resolver_for_node(db, node.with_value(&it)))
185 .unwrap_or_default(),
187 body_source_map: None,
190 file_id: node.file_id,
195 fn expr_id(&self, expr: &ast::Expr) -> Option<ExprId> {
196 let src = InFile { file_id: self.file_id, value: expr };
197 self.body_source_map.as_ref()?.node_expr(src)
200 fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
201 let src = InFile { file_id: self.file_id, value: pat };
202 self.body_source_map.as_ref()?.node_pat(src)
205 pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> {
206 let expr_id = self.expr_id(expr)?;
207 let ty = self.infer.as_ref()?[expr_id].clone();
208 let environment = TraitEnvironment::lower(db, &self.resolver);
209 Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
212 pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> {
213 let pat_id = self.pat_id(pat)?;
214 let ty = self.infer.as_ref()?[pat_id].clone();
215 let environment = TraitEnvironment::lower(db, &self.resolver);
216 Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
219 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
220 let expr_id = self.expr_id(&call.clone().into())?;
221 self.infer.as_ref()?.method_resolution(expr_id).map(Function::from)
224 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> {
225 let expr_id = self.expr_id(&field.clone().into())?;
226 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
229 pub fn resolve_record_field(&self, field: &ast::RecordField) -> Option<crate::StructField> {
230 let expr_id = self.expr_id(&field.expr()?)?;
231 self.infer.as_ref()?.record_field_resolution(expr_id).map(|it| it.into())
234 pub fn resolve_record_literal(&self, record_lit: &ast::RecordLit) -> Option<crate::VariantDef> {
235 let expr_id = self.expr_id(&record_lit.clone().into())?;
236 self.infer.as_ref()?.variant_resolution_for_expr(expr_id).map(|it| it.into())
239 pub fn resolve_record_pattern(&self, record_pat: &ast::RecordPat) -> Option<crate::VariantDef> {
240 let pat_id = self.pat_id(&record_pat.clone().into())?;
241 self.infer.as_ref()?.variant_resolution_for_pat(pat_id).map(|it| it.into())
244 pub fn resolve_macro_call(
246 db: &impl HirDatabase,
247 macro_call: InFile<&ast::MacroCall>,
248 ) -> Option<MacroDef> {
249 let hygiene = Hygiene::new(db, macro_call.file_id);
250 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
251 self.resolver.resolve_path_as_macro(db, &path).map(|it| it.into())
254 pub fn resolve_hir_path(
256 db: &impl HirDatabase,
258 ) -> Option<PathResolution> {
259 let types = self.resolver.resolve_path_in_type_ns_fully(db, &path).map(|ty| match ty {
260 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
261 TypeNs::GenericParam(idx) => PathResolution::GenericParam(GenericParam {
262 parent: self.resolver.generic_def().unwrap(),
265 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
266 PathResolution::Def(Adt::from(it).into())
268 TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
269 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
270 TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
271 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
273 let values = self.resolver.resolve_path_in_value_ns_fully(db, &path).and_then(|val| {
274 let res = match val {
275 ValueNs::LocalBinding(pat_id) => {
276 let var = Local { parent: self.body_owner?, pat_id };
277 PathResolution::Local(var)
279 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
280 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
281 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
282 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
283 ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
290 .resolve_module_path_in_items(db, &path)
292 .map(|it| PathResolution::Def(it.into()));
293 types.or(values).or(items).or_else(|| {
295 .resolve_path_as_macro(db, &path)
296 .map(|def| PathResolution::Macro(def.into()))
300 pub fn resolve_path(&self, db: &impl HirDatabase, path: &ast::Path) -> Option<PathResolution> {
301 if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
302 let expr_id = self.expr_id(&path_expr.into())?;
303 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) {
304 return Some(PathResolution::AssocItem(assoc.into()));
307 if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) {
308 let pat_id = self.pat_id(&path_pat.into())?;
309 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
310 return Some(PathResolution::AssocItem(assoc.into()));
313 // This must be a normal source file rather than macro file.
314 let hir_path = crate::Path::from_ast(path.clone())?;
315 self.resolve_hir_path(db, &hir_path)
318 fn resolve_local_name(&self, name_ref: &ast::NameRef) -> Option<ScopeEntryWithSyntax> {
319 let name = name_ref.as_name();
320 let source_map = self.body_source_map.as_ref()?;
321 let scopes = self.scopes.as_ref()?;
322 let scope = scope_for(scopes, source_map, InFile::new(self.file_id, name_ref.syntax()))?;
323 let entry = scopes.resolve_name_in_scope(scope, &name)?;
324 Some(ScopeEntryWithSyntax {
325 name: entry.name().clone(),
326 ptr: source_map.pat_syntax(entry.pat())?.value,
330 pub fn process_all_names(&self, db: &impl HirDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
331 self.resolver.process_all_names(db, &mut |name, def| {
332 let def = match def {
333 resolver::ScopeDef::PerNs(it) => it.into(),
334 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
335 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
336 resolver::ScopeDef::GenericParam(idx) => {
337 let parent = self.resolver.generic_def().unwrap();
338 ScopeDef::GenericParam(GenericParam { parent, idx })
340 resolver::ScopeDef::Local(pat_id) => {
341 let parent = self.resolver.body_owner().unwrap().into();
342 ScopeDef::Local(Local { parent, pat_id })
349 // FIXME: we only use this in `inline_local_variable` assist, ideally, we
350 // should switch to general reference search infra there.
351 pub fn find_all_refs(&self, pat: &ast::BindPat) -> Vec<ReferenceDescriptor> {
352 let fn_def = pat.syntax().ancestors().find_map(ast::FnDef::cast).unwrap();
353 let ptr = Either::Left(AstPtr::new(&ast::Pat::from(pat.clone())));
357 .filter_map(ast::NameRef::cast)
358 .filter(|name_ref| match self.resolve_local_name(&name_ref) {
360 Some(entry) => entry.ptr() == ptr,
362 .map(|name_ref| ReferenceDescriptor {
363 name: name_ref.text().to_string(),
364 range: name_ref.syntax().text_range(),
369 pub fn iterate_method_candidates<T>(
371 db: &impl HirDatabase,
374 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
376 // There should be no inference vars in types passed here
378 // FIXME replace Unknown by bound vars here
379 let canonical = crate::ty::Canonical { value: ty.ty.value.clone(), num_vars: 0 };
380 method_resolution::iterate_method_candidates(
385 method_resolution::LookupMode::MethodCall,
387 AssocItemId::FunctionId(f) => callback(ty, f.into()),
393 pub fn iterate_path_candidates<T>(
395 db: &impl HirDatabase,
398 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
400 // There should be no inference vars in types passed here
402 // FIXME replace Unknown by bound vars here
403 let canonical = crate::ty::Canonical { value: ty.ty.value.clone(), num_vars: 0 };
404 method_resolution::iterate_method_candidates(
409 method_resolution::LookupMode::Path,
410 |ty, it| callback(ty, it.into()),
414 // pub fn autoderef<'a>(
416 // db: &'a impl HirDatabase,
418 // ) -> impl Iterator<Item = Ty> + 'a {
419 // // There should be no inference vars in types passed here
420 // // FIXME check that?
421 // let canonical = crate::ty::Canonical { value: ty, num_vars: 0 };
422 // let krate = self.resolver.krate();
423 // let environment = TraitEnvironment::lower(db, &self.resolver);
424 // let ty = crate::ty::InEnvironment { value: canonical, environment };
425 // crate::ty::autoderef(db, krate, ty).map(|canonical| canonical.value)
428 /// Checks that particular type `ty` implements `std::future::Future`.
429 /// This function is used in `.await` syntax completion.
430 pub fn impls_future(&self, db: &impl HirDatabase, ty: Ty) -> bool {
431 let std_future_path = known::std_future_future();
433 let std_future_trait = match self.resolver.resolve_known_trait(db, &std_future_path) {
434 Some(it) => it.into(),
438 let krate = match self.resolver.krate() {
439 Some(krate) => krate,
443 let canonical_ty = crate::ty::Canonical { value: ty, num_vars: 0 };
444 implements_trait(&canonical_ty, db, &self.resolver, krate.into(), std_future_trait)
449 db: &impl HirDatabase,
450 macro_call: InFile<&ast::MacroCall>,
451 ) -> Option<Expansion> {
452 let def = self.resolve_macro_call(db, macro_call)?.id;
453 let ast_id = AstId::new(
455 db.ast_id_map(macro_call.file_id).ast_id(macro_call.value),
458 macro_call_id: def.as_call_id(db, ast_id),
459 macro_file_kind: to_macro_file_kind(macro_call.value),
466 source_map: &BodySourceMap,
467 node: InFile<&SyntaxNode>,
468 ) -> Option<ScopeId> {
471 .filter_map(ast::Expr::cast)
472 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
473 .find_map(|it| scopes.scope_for(it))
478 source_map: &BodySourceMap,
479 offset: InFile<TextUnit>,
480 ) -> Option<ScopeId> {
484 .filter_map(|(id, scope)| {
485 let source = source_map.expr_syntax(*id)?;
486 // FIXME: correctly handle macro expansion
487 if source.file_id != offset.file_id {
490 let syntax_node_ptr =
491 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
492 Some((syntax_node_ptr, scope))
494 // find containing scope
495 .min_by_key(|(ptr, _scope)| {
497 !(ptr.range().start() <= offset.value && offset.value <= ptr.range().end()),
501 .map(|(ptr, scope)| {
502 adjust(scopes, source_map, ptr, offset.file_id, offset.value).unwrap_or(*scope)
506 // XXX: during completion, cursor might be outside of any particular
507 // expression. Try to figure out the correct scope...
510 source_map: &BodySourceMap,
514 ) -> Option<ScopeId> {
516 let child_scopes = scopes
519 .filter_map(|(id, scope)| {
520 let source = source_map.expr_syntax(*id)?;
521 // FIXME: correctly handle macro expansion
522 if source.file_id != file_id {
525 let syntax_node_ptr =
526 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
527 Some((syntax_node_ptr, scope))
529 .map(|(ptr, scope)| (ptr.range(), scope))
530 .filter(|(range, _)| range.start() <= offset && range.is_subrange(&r) && *range != r);
533 .max_by(|(r1, _), (r2, _)| {
534 if r2.is_subrange(&r1) {
535 std::cmp::Ordering::Greater
536 } else if r1.is_subrange(&r2) {
537 std::cmp::Ordering::Less
539 r1.start().cmp(&r2.start())
542 .map(|(_ptr, scope)| *scope)
545 /// Given a `ast::MacroCall`, return what `MacroKindFile` it belongs to.
546 /// FIXME: Not completed
547 fn to_macro_file_kind(macro_call: &ast::MacroCall) -> MacroFileKind {
548 let syn = macro_call.syntax();
549 let parent = match syn.parent() {
553 // If it is root, which means the parent HirFile
554 // MacroKindFile must be non-items
556 return MacroFileKind::Expr;
560 match parent.kind() {
561 MACRO_ITEMS | SOURCE_FILE => MacroFileKind::Items,
563 // FIXME: Handle Pattern
566 EXPR_STMT => MacroFileKind::Statements,
567 BLOCK => MacroFileKind::Statements,
568 ARG_LIST => MacroFileKind::Expr,
569 TRY_EXPR => MacroFileKind::Expr,
571 // Unknown , Just guess it is `Items`