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<&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)),
68 file_id: node.file_id,
72 pub(crate) fn new_for_resolver(
74 node: InFile<&SyntaxNode>,
79 body_source_map: None,
81 file_id: node.file_id,
85 fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
86 let src = match expr {
87 ast::Expr::MacroCall(call) => {
88 self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
90 _ => InFile::new(self.file_id, expr.clone()),
92 let sm = self.body_source_map.as_ref()?;
93 sm.node_expr(src.as_ref())
96 fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
97 // FIXME: macros, see `expr_id`
98 let src = InFile { file_id: self.file_id, value: pat };
99 self.body_source_map.as_ref()?.node_pat(src)
104 db: &dyn HirDatabase,
105 expr: InFile<ast::MacroCall>,
106 ) -> Option<InFile<ast::Expr>> {
107 let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
108 let expanded = db.parse_or_expand(macro_file)?;
110 let res = match ast::MacroCall::cast(expanded.clone()) {
111 Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
112 _ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
117 pub(crate) fn type_of_expr(
119 db: &dyn HirDatabase,
121 ) -> Option<(Type, Option<Type>)> {
122 let expr_id = self.expr_id(db, expr)?;
123 let infer = self.infer.as_ref()?;
127 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
128 let ty = infer[expr_id].clone();
129 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
130 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
133 pub(crate) fn type_of_pat(
135 db: &dyn HirDatabase,
137 ) -> Option<(Type, Option<Type>)> {
138 let pat_id = self.pat_id(pat)?;
139 let infer = self.infer.as_ref()?;
143 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
144 let ty = infer[pat_id].clone();
145 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
146 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
149 pub(crate) fn type_of_self(
151 db: &dyn HirDatabase,
152 param: &ast::SelfParam,
154 let src = InFile { file_id: self.file_id, value: param };
155 let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
156 let ty = self.infer.as_ref()?[pat_id].clone();
157 Type::new_with_resolver(db, &self.resolver, ty)
160 pub(crate) fn resolve_method_call(
162 db: &dyn HirDatabase,
163 call: &ast::MethodCallExpr,
164 ) -> Option<(FunctionId, Substitution)> {
165 let expr_id = self.expr_id(db, &call.clone().into())?;
166 self.infer.as_ref()?.method_resolution(expr_id)
169 pub(crate) fn resolve_field(
171 db: &dyn HirDatabase,
172 field: &ast::FieldExpr,
174 let expr_id = self.expr_id(db, &field.clone().into())?;
175 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
178 pub(crate) fn resolve_record_field(
180 db: &dyn HirDatabase,
181 field: &ast::RecordExprField,
182 ) -> Option<(Field, Option<Local>, Type)> {
183 let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
184 let expr = ast::Expr::from(record_expr);
185 let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
187 let local_name = field.field_name()?.as_name();
188 let local = if field.name_ref().is_some() {
191 let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
192 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
193 Some(ValueNs::LocalBinding(pat_id)) => {
194 Some(Local { pat_id, parent: self.resolver.body_owner()? })
199 let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
200 let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
201 let variant_data = variant.variant_data(db.upcast());
202 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
204 db.field_types(variant).get(field.local_id)?.clone().substitute(&Interner, subst);
205 Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
208 pub(crate) fn resolve_record_pat_field(
210 db: &dyn HirDatabase,
211 field: &ast::RecordPatField,
213 let field_name = field.field_name()?.as_name();
214 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
215 let pat_id = self.pat_id(&record_pat.into())?;
216 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
217 let variant_data = variant.variant_data(db.upcast());
218 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
222 pub(crate) fn resolve_macro_call(
224 db: &dyn HirDatabase,
225 macro_call: InFile<&ast::MacroCall>,
226 ) -> Option<MacroDef> {
227 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
228 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
229 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
232 pub(crate) fn resolve_bind_pat_to_const(
234 db: &dyn HirDatabase,
236 ) -> Option<ModuleDef> {
237 let pat_id = self.pat_id(&pat.clone().into())?;
238 let body = self.body.as_ref()?;
239 let path = match &body[pat_id] {
240 Pat::Path(path) => path,
243 let res = resolve_hir_path(db, &self.resolver, path)?;
245 PathResolution::Def(def) => Some(def),
250 pub(crate) fn resolve_path(
252 db: &dyn HirDatabase,
254 ) -> Option<PathResolution> {
255 let parent = path.syntax().parent();
256 let parent = || parent.clone();
258 let mut prefer_value_ns = false;
259 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
260 let expr_id = self.expr_id(db, &path_expr.into())?;
261 let infer = self.infer.as_ref()?;
262 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
263 return Some(PathResolution::AssocItem(assoc.into()));
265 if let Some(VariantId::EnumVariantId(variant)) =
266 infer.variant_resolution_for_expr(expr_id)
268 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
270 prefer_value_ns = true;
273 if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
274 let pat_id = self.pat_id(&path_pat.into())?;
275 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
276 return Some(PathResolution::AssocItem(assoc.into()));
278 if let Some(VariantId::EnumVariantId(variant)) =
279 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
281 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
285 if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
286 let expr_id = self.expr_id(db, &rec_lit.into())?;
287 if let Some(VariantId::EnumVariantId(variant)) =
288 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
290 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
294 let record_pat = parent().and_then(ast::RecordPat::cast).map(ast::Pat::from);
295 let tuple_struct_pat = || parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from);
296 if let Some(pat) = record_pat.or_else(tuple_struct_pat) {
297 let pat_id = self.pat_id(&pat)?;
298 let variant_res_for_pat = self.infer.as_ref()?.variant_resolution_for_pat(pat_id);
299 if let Some(VariantId::EnumVariantId(variant)) = variant_res_for_pat {
300 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
304 // This must be a normal source file rather than macro file.
305 let hygiene = Hygiene::new(db.upcast(), self.file_id);
306 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
307 let hir_path = Path::from_src(path.clone(), &ctx)?;
309 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
310 // trying to resolve foo::bar.
311 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
312 if let Some(qualifier) = use_tree.path() {
313 if path == &qualifier && use_tree.coloncolon_token().is_some() {
314 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
319 let is_path_of_attr = path
323 .nth(2) // Path -> Meta -> Attr
324 .map_or(false, |it| ast::Attr::can_cast(it.kind()));
326 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
327 // trying to resolve foo::bar.
328 if let Some(outer_path) = path.parent_path() {
329 if let Some(qualifier) = outer_path.qualifier() {
330 if path == &qualifier {
331 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
334 } else if is_path_of_attr {
335 // Case where we are resolving the final path segment of a path in an attribute
336 // in this case we have to check for inert/builtin attributes and tools and prioritize
337 // resolution of attributes over other namesapces
338 let name_ref = path.as_single_name_ref();
340 name_ref.as_ref().map(ast::NameRef::text).as_deref().and_then(BuiltinAttr::by_name);
341 if let builtin @ Some(_) = builtin {
342 return builtin.map(PathResolution::BuiltinAttr);
344 return match resolve_hir_path_as_macro(db, &self.resolver, &hir_path) {
345 res @ Some(m) if m.is_attr() => res.map(PathResolution::Macro),
346 _ => name_ref.and_then(|name_ref| {
347 ToolModule::by_name(&name_ref.text()).map(PathResolution::ToolModule)
352 let res = if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
353 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
355 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
359 // this labels any path that starts with a tool module as the tool itself, this is technically wrong
360 // but there is no benefit in differentiating these two cases for the time being
361 None if is_path_of_attr => path
363 .and_then(|seg| seg.name_ref())
364 .and_then(|name_ref| ToolModule::by_name(&name_ref.text()))
365 .map(PathResolution::ToolModule),
370 pub(crate) fn record_literal_missing_fields(
372 db: &dyn HirDatabase,
373 literal: &ast::RecordExpr,
374 ) -> Option<Vec<(Field, Type)>> {
375 let krate = self.resolver.krate()?;
376 let body = self.body.as_ref()?;
377 let infer = self.infer.as_ref()?;
379 let expr_id = self.expr_id(db, &literal.clone().into())?;
380 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
382 let (variant, missing_fields, _exhaustive) =
383 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
384 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
388 pub(crate) fn record_pattern_missing_fields(
390 db: &dyn HirDatabase,
391 pattern: &ast::RecordPat,
392 ) -> Option<Vec<(Field, Type)>> {
393 let krate = self.resolver.krate()?;
394 let body = self.body.as_ref()?;
395 let infer = self.infer.as_ref()?;
397 let pat_id = self.pat_id(&pattern.clone().into())?;
398 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
400 let (variant, missing_fields, _exhaustive) =
401 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
402 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
408 db: &dyn HirDatabase,
410 substs: &Substitution,
412 missing_fields: Vec<LocalFieldId>,
413 ) -> Vec<(Field, Type)> {
414 let field_types = db.field_types(variant);
419 let field = FieldId { parent: variant, local_id };
420 let ty = field_types[local_id].clone().substitute(&Interner, substs);
421 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
426 pub(crate) fn expand(
428 db: &dyn HirDatabase,
429 macro_call: InFile<&ast::MacroCall>,
430 ) -> Option<HirFileId> {
431 let krate = self.resolver.krate()?;
432 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
433 self.resolver.resolve_path_as_macro(db.upcast(), &path)
435 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
438 pub(crate) fn resolve_variant(
440 db: &dyn HirDatabase,
441 record_lit: ast::RecordExpr,
442 ) -> Option<VariantId> {
443 let infer = self.infer.as_ref()?;
444 let expr_id = self.expr_id(db, &record_lit.into())?;
445 infer.variant_resolution_for_expr(expr_id)
451 source_map: &BodySourceMap,
452 node: InFile<&SyntaxNode>,
453 ) -> Option<ScopeId> {
456 .filter_map(ast::Expr::cast)
457 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
458 .find_map(|it| scopes.scope_for(it))
462 db: &dyn HirDatabase,
464 source_map: &BodySourceMap,
465 offset: InFile<TextSize>,
466 ) -> Option<ScopeId> {
470 .filter_map(|(id, scope)| {
471 let source = source_map.expr_syntax(*id).ok()?;
472 // FIXME: correctly handle macro expansion
473 if source.file_id != offset.file_id {
476 let root = source.file_syntax(db.upcast());
477 let node = source.value.to_node(&root);
478 Some((node.syntax().text_range(), scope))
480 // find containing scope
481 .min_by_key(|(expr_range, _scope)| {
483 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
487 .map(|(expr_range, scope)| {
488 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
492 // XXX: during completion, cursor might be outside of any particular
493 // expression. Try to figure out the correct scope...
495 db: &dyn HirDatabase,
497 source_map: &BodySourceMap,
498 expr_range: TextRange,
499 offset: InFile<TextSize>,
500 ) -> Option<ScopeId> {
501 let child_scopes = scopes
504 .filter_map(|(id, scope)| {
505 let source = source_map.expr_syntax(*id).ok()?;
506 // FIXME: correctly handle macro expansion
507 if source.file_id != offset.file_id {
510 let root = source.file_syntax(db.upcast());
511 let node = source.value.to_node(&root);
512 Some((node.syntax().text_range(), scope))
514 .filter(|&(range, _)| {
515 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
519 .max_by(|&(r1, _), &(r2, _)| {
520 if r1.contains_range(r2) {
521 std::cmp::Ordering::Greater
522 } else if r2.contains_range(r1) {
523 std::cmp::Ordering::Less
525 r1.start().cmp(&r2.start())
528 .map(|(_ptr, scope)| *scope)
532 pub(crate) fn resolve_hir_path(
533 db: &dyn HirDatabase,
536 ) -> Option<PathResolution> {
537 resolve_hir_path_(db, resolver, path, false)
541 pub(crate) fn resolve_hir_path_as_macro(
542 db: &dyn HirDatabase,
545 ) -> Option<MacroDef> {
546 resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(Into::into)
549 fn resolve_hir_path_(
550 db: &dyn HirDatabase,
553 prefer_value_ns: bool,
554 ) -> Option<PathResolution> {
556 let (ty, unresolved) = match path.type_anchor() {
558 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
559 res.map(|ty_ns| (ty_ns, path.segments().first()))
562 let (ty, remaining) =
563 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
565 Some(remaining) if remaining > 1 => None,
566 _ => Some((ty, path.segments().get(1))),
571 // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
572 // within the trait's associated types.
573 if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
574 if let Some(type_alias_id) =
575 db.trait_data(trait_id).associated_type_by_name(&unresolved.name)
577 return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
582 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
583 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
584 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
585 PathResolution::Def(Adt::from(it).into())
587 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
588 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
589 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
590 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
593 Some(unresolved) => res
594 .assoc_type_shorthand_candidates(db, |name, alias| {
595 (name == unresolved.name).then(|| alias)
597 .map(TypeAlias::from)
599 .map(PathResolution::Def),
604 let body_owner = resolver.body_owner();
606 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
607 let res = match val {
608 ValueNs::LocalBinding(pat_id) => {
609 let var = Local { parent: body_owner?, pat_id };
610 PathResolution::Local(var)
612 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
613 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
614 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
615 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
616 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
617 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
618 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
626 .resolve_module_path_in_items(db.upcast(), path.mod_path())
628 .map(|it| PathResolution::Def(it.into()))
633 .resolve_path_as_macro(db.upcast(), path.mod_path())
634 .map(|def| PathResolution::Macro(def.into()))
637 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
642 /// Resolves a path where we know it is a qualifier of another path.
644 /// For example, if we have:
654 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
655 fn resolve_hir_path_qualifier(
656 db: &dyn HirDatabase,
659 ) -> Option<PathResolution> {
661 .resolve_module_path_in_items(db.upcast(), path.mod_path())
663 .map(|it| PathResolution::Def(it.into()));
669 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
670 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
671 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
672 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
673 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
674 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
675 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
676 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),