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".
8 use std::{iter::once, sync::Arc};
13 scope::{ExprScopes, ScopeId},
16 expr::{ExprId, Pat, PatId},
17 path::{ModPath, Path, PathKind},
18 resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs},
19 AsMacroCall, DefWithBodyId, FieldId, FunctionId, LocalFieldId, ModuleDefId, VariantId,
21 use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
23 diagnostics::{record_literal_missing_fields, record_pattern_missing_fields},
24 InferenceResult, Interner, Substitution, TyExt, TyLoweringContext,
28 SyntaxNode, TextRange, TextSize,
32 db::HirDatabase, semantics::PathResolution, Adt, BuiltinAttr, BuiltinType, Const, Field,
33 Function, Local, MacroDef, ModuleDef, Static, Struct, ToolModule, Trait, Type, TypeAlias,
38 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
39 /// original source files. It should not be used inside the HIR itself.
41 pub(crate) struct SourceAnalyzer {
42 pub(crate) file_id: HirFileId,
43 pub(crate) resolver: Resolver,
44 body: Option<Arc<Body>>,
45 body_source_map: Option<Arc<BodySourceMap>>,
46 infer: Option<Arc<InferenceResult>>,
50 pub(crate) fn new_for_body(
53 node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
54 offset: Option<TextSize>,
56 let (body, source_map) = db.body_with_source_map(def);
57 let scopes = db.expr_scopes(def);
58 let scope = match offset {
59 None => scope_for(&scopes, &source_map, node),
60 Some(offset) => scope_for_offset(db, &scopes, &source_map, node.with_value(offset)),
62 let resolver = resolver_for_scope(db.upcast(), def, scope);
66 body_source_map: Some(source_map),
67 infer: Some(db.infer(def)),
72 pub(crate) fn new_for_body_no_infer(
75 node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
76 offset: Option<TextSize>,
78 let (body, source_map) = db.body_with_source_map(def);
79 let scopes = db.expr_scopes(def);
80 let scope = match offset {
81 None => scope_for(&scopes, &source_map, node),
82 Some(offset) => scope_for_offset(db, &scopes, &source_map, node.with_value(offset)),
84 let resolver = resolver_for_scope(db.upcast(), def, scope);
88 body_source_map: Some(source_map),
94 pub(crate) fn new_for_resolver(
96 node: InFile<&SyntaxNode>,
101 body_source_map: None,
103 file_id: node.file_id,
107 fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
108 let src = match expr {
109 ast::Expr::MacroCall(call) => {
110 self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
112 _ => InFile::new(self.file_id, expr.clone()),
114 let sm = self.body_source_map.as_ref()?;
115 sm.node_expr(src.as_ref())
118 fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
119 // FIXME: macros, see `expr_id`
120 let src = InFile { file_id: self.file_id, value: pat };
121 self.body_source_map.as_ref()?.node_pat(src)
126 db: &dyn HirDatabase,
127 expr: InFile<ast::MacroCall>,
128 ) -> Option<InFile<ast::Expr>> {
129 let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
130 let expanded = db.parse_or_expand(macro_file)?;
132 let res = match ast::MacroCall::cast(expanded.clone()) {
133 Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
134 _ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
139 pub(crate) fn type_of_expr(
141 db: &dyn HirDatabase,
143 ) -> Option<(Type, Option<Type>)> {
144 let expr_id = self.expr_id(db, expr)?;
145 let infer = self.infer.as_ref()?;
149 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
150 let ty = infer[expr_id].clone();
151 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
152 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
155 pub(crate) fn type_of_pat(
157 db: &dyn HirDatabase,
159 ) -> Option<(Type, Option<Type>)> {
160 let pat_id = self.pat_id(pat)?;
161 let infer = self.infer.as_ref()?;
165 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
166 let ty = infer[pat_id].clone();
167 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
168 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
171 pub(crate) fn type_of_self(
173 db: &dyn HirDatabase,
174 param: &ast::SelfParam,
176 let src = InFile { file_id: self.file_id, value: param };
177 let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
178 let ty = self.infer.as_ref()?[pat_id].clone();
179 Type::new_with_resolver(db, &self.resolver, ty)
182 pub(crate) fn resolve_method_call(
184 db: &dyn HirDatabase,
185 call: &ast::MethodCallExpr,
186 ) -> Option<(FunctionId, Substitution)> {
187 let expr_id = self.expr_id(db, &call.clone().into())?;
188 self.infer.as_ref()?.method_resolution(expr_id)
191 pub(crate) fn resolve_field(
193 db: &dyn HirDatabase,
194 field: &ast::FieldExpr,
196 let expr_id = self.expr_id(db, &field.clone().into())?;
197 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
200 pub(crate) fn resolve_record_field(
202 db: &dyn HirDatabase,
203 field: &ast::RecordExprField,
204 ) -> Option<(Field, Option<Local>, Type)> {
205 let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
206 let expr = ast::Expr::from(record_expr);
207 let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
209 let local_name = field.field_name()?.as_name();
210 let local = if field.name_ref().is_some() {
213 let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
214 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
215 Some(ValueNs::LocalBinding(pat_id)) => {
216 Some(Local { pat_id, parent: self.resolver.body_owner()? })
221 let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
222 let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
223 let variant_data = variant.variant_data(db.upcast());
224 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
226 db.field_types(variant).get(field.local_id)?.clone().substitute(Interner, subst);
227 Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
230 pub(crate) fn resolve_record_pat_field(
232 db: &dyn HirDatabase,
233 field: &ast::RecordPatField,
235 let field_name = field.field_name()?.as_name();
236 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
237 let pat_id = self.pat_id(&record_pat.into())?;
238 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
239 let variant_data = variant.variant_data(db.upcast());
240 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
244 pub(crate) fn resolve_macro_call(
246 db: &dyn HirDatabase,
247 macro_call: InFile<&ast::MacroCall>,
248 ) -> Option<MacroDef> {
249 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
250 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
251 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
254 pub(crate) fn resolve_bind_pat_to_const(
256 db: &dyn HirDatabase,
258 ) -> Option<ModuleDef> {
259 let pat_id = self.pat_id(&pat.clone().into())?;
260 let body = self.body.as_ref()?;
261 let path = match &body[pat_id] {
262 Pat::Path(path) => path,
265 let res = resolve_hir_path(db, &self.resolver, path)?;
267 PathResolution::Def(def) => Some(def),
272 pub(crate) fn resolve_path(
274 db: &dyn HirDatabase,
276 ) -> Option<PathResolution> {
277 let parent = path.syntax().parent();
278 let parent = || parent.clone();
280 let mut prefer_value_ns = false;
281 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
282 let expr_id = self.expr_id(db, &path_expr.into())?;
283 let infer = self.infer.as_ref()?;
284 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
285 return Some(PathResolution::AssocItem(assoc.into()));
287 if let Some(VariantId::EnumVariantId(variant)) =
288 infer.variant_resolution_for_expr(expr_id)
290 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
292 prefer_value_ns = true;
293 } else if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
294 let pat_id = self.pat_id(&path_pat.into())?;
295 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
296 return Some(PathResolution::AssocItem(assoc.into()));
298 if let Some(VariantId::EnumVariantId(variant)) =
299 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
301 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
303 } else if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
304 let expr_id = self.expr_id(db, &rec_lit.into())?;
305 if let Some(VariantId::EnumVariantId(variant)) =
306 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
308 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
312 let record_pat = parent().and_then(ast::RecordPat::cast).map(ast::Pat::from);
313 let tuple_struct_pat = || parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from);
314 if let Some(pat) = record_pat.or_else(tuple_struct_pat) {
315 let pat_id = self.pat_id(&pat)?;
316 let variant_res_for_pat = self.infer.as_ref()?.variant_resolution_for_pat(pat_id);
317 if let Some(VariantId::EnumVariantId(variant)) = variant_res_for_pat {
318 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
322 // This must be a normal source file rather than macro file.
323 let hygiene = Hygiene::new(db.upcast(), self.file_id);
324 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
325 let hir_path = Path::from_src(path.clone(), &ctx)?;
327 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
328 // trying to resolve foo::bar.
329 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
330 if use_tree.coloncolon_token().is_some() {
331 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
335 let is_path_of_attr = path
339 .take_while(|&kind| ast::Path::can_cast(kind) || ast::Meta::can_cast(kind))
341 .map_or(false, ast::Meta::can_cast);
343 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
344 // trying to resolve foo::bar.
345 if path.parent_path().is_some() {
346 return match resolve_hir_path_qualifier(db, &self.resolver, &hir_path) {
347 None if is_path_of_attr => {
348 path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| {
349 ToolModule::by_name(&name_ref.text()).map(PathResolution::ToolModule)
354 } else if is_path_of_attr {
355 // Case where we are resolving the final path segment of a path in an attribute
356 // in this case we have to check for inert/builtin attributes and tools and prioritize
357 // resolution of attributes over other namespaces
358 let name_ref = path.as_single_name_ref();
360 name_ref.as_ref().map(ast::NameRef::text).as_deref().and_then(BuiltinAttr::by_name);
361 if let builtin @ Some(_) = builtin {
362 return builtin.map(PathResolution::BuiltinAttr);
364 return match resolve_hir_path_as_macro(db, &self.resolver, &hir_path) {
365 res @ Some(m) if m.is_attr() => res.map(PathResolution::Macro),
366 // this labels any path that starts with a tool module as the tool itself, this is technically wrong
367 // but there is no benefit in differentiating these two cases for the time being
368 _ => path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| {
369 ToolModule::by_name(&name_ref.text()).map(PathResolution::ToolModule)
373 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
374 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
376 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
380 pub(crate) fn record_literal_missing_fields(
382 db: &dyn HirDatabase,
383 literal: &ast::RecordExpr,
384 ) -> Option<Vec<(Field, Type)>> {
385 let krate = self.resolver.krate()?;
386 let body = self.body.as_ref()?;
387 let infer = self.infer.as_ref()?;
389 let expr_id = self.expr_id(db, &literal.clone().into())?;
390 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
392 let (variant, missing_fields, _exhaustive) =
393 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
394 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
398 pub(crate) fn record_pattern_missing_fields(
400 db: &dyn HirDatabase,
401 pattern: &ast::RecordPat,
402 ) -> Option<Vec<(Field, Type)>> {
403 let krate = self.resolver.krate()?;
404 let body = self.body.as_ref()?;
405 let infer = self.infer.as_ref()?;
407 let pat_id = self.pat_id(&pattern.clone().into())?;
408 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
410 let (variant, missing_fields, _exhaustive) =
411 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
412 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
418 db: &dyn HirDatabase,
420 substs: &Substitution,
422 missing_fields: Vec<LocalFieldId>,
423 ) -> Vec<(Field, Type)> {
424 let field_types = db.field_types(variant);
429 let field = FieldId { parent: variant, local_id };
430 let ty = field_types[local_id].clone().substitute(Interner, substs);
431 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
436 pub(crate) fn expand(
438 db: &dyn HirDatabase,
439 macro_call: InFile<&ast::MacroCall>,
440 ) -> Option<HirFileId> {
441 let krate = self.resolver.krate()?;
442 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
443 self.resolver.resolve_path_as_macro(db.upcast(), &path)
445 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
448 pub(crate) fn resolve_variant(
450 db: &dyn HirDatabase,
451 record_lit: ast::RecordExpr,
452 ) -> Option<VariantId> {
453 let infer = self.infer.as_ref()?;
454 let expr_id = self.expr_id(db, &record_lit.into())?;
455 infer.variant_resolution_for_expr(expr_id)
461 source_map: &BodySourceMap,
462 node: InFile<&SyntaxNode>,
463 ) -> Option<ScopeId> {
466 .filter_map(ast::Expr::cast)
467 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
468 .find_map(|it| scopes.scope_for(it))
472 db: &dyn HirDatabase,
474 source_map: &BodySourceMap,
475 offset: InFile<TextSize>,
476 ) -> Option<ScopeId> {
480 .filter_map(|(id, scope)| {
481 let source = source_map.expr_syntax(*id).ok()?;
482 // FIXME: correctly handle macro expansion
483 if source.file_id != offset.file_id {
486 let root = source.file_syntax(db.upcast());
487 let node = source.value.to_node(&root);
488 Some((node.syntax().text_range(), scope))
490 // find containing scope
491 .min_by_key(|(expr_range, _scope)| {
493 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
497 .map(|(expr_range, scope)| {
498 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
502 // XXX: during completion, cursor might be outside of any particular
503 // expression. Try to figure out the correct scope...
505 db: &dyn HirDatabase,
507 source_map: &BodySourceMap,
508 expr_range: TextRange,
509 offset: InFile<TextSize>,
510 ) -> Option<ScopeId> {
511 let child_scopes = scopes
514 .filter_map(|(id, scope)| {
515 let source = source_map.expr_syntax(*id).ok()?;
516 // FIXME: correctly handle macro expansion
517 if source.file_id != offset.file_id {
520 let root = source.file_syntax(db.upcast());
521 let node = source.value.to_node(&root);
522 Some((node.syntax().text_range(), scope))
524 .filter(|&(range, _)| {
525 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
529 .max_by(|&(r1, _), &(r2, _)| {
530 if r1.contains_range(r2) {
531 std::cmp::Ordering::Greater
532 } else if r2.contains_range(r1) {
533 std::cmp::Ordering::Less
535 r1.start().cmp(&r2.start())
538 .map(|(_ptr, scope)| *scope)
542 pub(crate) fn resolve_hir_path(
543 db: &dyn HirDatabase,
546 ) -> Option<PathResolution> {
547 resolve_hir_path_(db, resolver, path, false)
551 pub(crate) fn resolve_hir_path_as_macro(
552 db: &dyn HirDatabase,
555 ) -> Option<MacroDef> {
556 resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(Into::into)
559 fn resolve_hir_path_(
560 db: &dyn HirDatabase,
563 prefer_value_ns: bool,
564 ) -> Option<PathResolution> {
566 let (ty, unresolved) = match path.type_anchor() {
568 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
569 res.map(|ty_ns| (ty_ns, path.segments().first()))
572 let (ty, remaining) =
573 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
575 Some(remaining) if remaining > 1 => None,
576 _ => Some((ty, path.segments().get(1))),
581 // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
582 // within the trait's associated types.
583 if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
584 if let Some(type_alias_id) =
585 db.trait_data(trait_id).associated_type_by_name(&unresolved.name)
587 return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
592 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
593 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
594 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
595 PathResolution::Def(Adt::from(it).into())
597 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
598 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
599 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
600 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
603 Some(unresolved) => res
604 .assoc_type_shorthand_candidates(db, |name, alias| {
605 (name == unresolved.name).then(|| alias)
607 .map(TypeAlias::from)
609 .map(PathResolution::Def),
614 let body_owner = resolver.body_owner();
616 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
617 let res = match val {
618 ValueNs::LocalBinding(pat_id) => {
619 let var = Local { parent: body_owner?, pat_id };
620 PathResolution::Local(var)
622 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
623 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
624 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
625 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
626 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
627 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
628 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
636 .resolve_module_path_in_items(db.upcast(), path.mod_path())
638 .map(|it| PathResolution::Def(it.into()))
643 .resolve_path_as_macro(db.upcast(), path.mod_path())
644 .map(|def| PathResolution::Macro(def.into()))
647 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
652 /// Resolves a path where we know it is a qualifier of another path.
654 /// For example, if we have:
664 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
665 fn resolve_hir_path_qualifier(
666 db: &dyn HirDatabase,
669 ) -> Option<PathResolution> {
671 .resolve_module_path_in_items(db.upcast(), path.mod_path())
673 .map(|it| PathResolution::Def(it.into()));
679 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
680 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
681 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
682 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
683 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
684 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
685 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
686 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),