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 match self.resolver.krate() {
350 Some(krate) => ToolModule::by_name(db, krate.into(), &name_ref.text()),
351 None => ToolModule::builtin(&name_ref.text()),
353 .map(PathResolution::ToolModule)
358 } else if is_path_of_attr {
359 // Case where we are resolving the final path segment of a path in an attribute
360 // in this case we have to check for inert/builtin attributes and tools and prioritize
361 // resolution of attributes over other namespaces
362 let name_ref = path.as_single_name_ref();
363 let builtin = name_ref.as_ref().and_then(|name_ref| match self.resolver.krate() {
364 Some(krate) => BuiltinAttr::by_name(db, krate.into(), &name_ref.text()),
365 None => BuiltinAttr::builtin(&name_ref.text()),
367 if let builtin @ Some(_) = builtin {
368 return builtin.map(PathResolution::BuiltinAttr);
370 return match resolve_hir_path_as_macro(db, &self.resolver, &hir_path) {
371 res @ Some(m) if m.is_attr() => res.map(PathResolution::Macro),
372 // this labels any path that starts with a tool module as the tool itself, this is technically wrong
373 // but there is no benefit in differentiating these two cases for the time being
374 _ => path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| {
375 match self.resolver.krate() {
376 Some(krate) => ToolModule::by_name(db, krate.into(), &name_ref.text()),
377 None => ToolModule::builtin(&name_ref.text()),
379 .map(PathResolution::ToolModule)
383 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
384 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
386 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
390 pub(crate) fn record_literal_missing_fields(
392 db: &dyn HirDatabase,
393 literal: &ast::RecordExpr,
394 ) -> Option<Vec<(Field, Type)>> {
395 let krate = self.resolver.krate()?;
396 let body = self.body.as_ref()?;
397 let infer = self.infer.as_ref()?;
399 let expr_id = self.expr_id(db, &literal.clone().into())?;
400 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
402 let (variant, missing_fields, _exhaustive) =
403 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
404 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
408 pub(crate) fn record_pattern_missing_fields(
410 db: &dyn HirDatabase,
411 pattern: &ast::RecordPat,
412 ) -> Option<Vec<(Field, Type)>> {
413 let krate = self.resolver.krate()?;
414 let body = self.body.as_ref()?;
415 let infer = self.infer.as_ref()?;
417 let pat_id = self.pat_id(&pattern.clone().into())?;
418 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
420 let (variant, missing_fields, _exhaustive) =
421 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
422 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
428 db: &dyn HirDatabase,
430 substs: &Substitution,
432 missing_fields: Vec<LocalFieldId>,
433 ) -> Vec<(Field, Type)> {
434 let field_types = db.field_types(variant);
439 let field = FieldId { parent: variant, local_id };
440 let ty = field_types[local_id].clone().substitute(Interner, substs);
441 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
446 pub(crate) fn expand(
448 db: &dyn HirDatabase,
449 macro_call: InFile<&ast::MacroCall>,
450 ) -> Option<HirFileId> {
451 let krate = self.resolver.krate()?;
452 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
453 self.resolver.resolve_path_as_macro(db.upcast(), &path)
455 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
458 pub(crate) fn resolve_variant(
460 db: &dyn HirDatabase,
461 record_lit: ast::RecordExpr,
462 ) -> Option<VariantId> {
463 let infer = self.infer.as_ref()?;
464 let expr_id = self.expr_id(db, &record_lit.into())?;
465 infer.variant_resolution_for_expr(expr_id)
471 source_map: &BodySourceMap,
472 node: InFile<&SyntaxNode>,
473 ) -> Option<ScopeId> {
476 .filter_map(ast::Expr::cast)
477 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
478 .find_map(|it| scopes.scope_for(it))
482 db: &dyn HirDatabase,
484 source_map: &BodySourceMap,
485 offset: InFile<TextSize>,
486 ) -> Option<ScopeId> {
490 .filter_map(|(id, scope)| {
491 let source = source_map.expr_syntax(*id).ok()?;
492 // FIXME: correctly handle macro expansion
493 if source.file_id != offset.file_id {
496 let root = source.file_syntax(db.upcast());
497 let node = source.value.to_node(&root);
498 Some((node.syntax().text_range(), scope))
500 // find containing scope
501 .min_by_key(|(expr_range, _scope)| {
503 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
507 .map(|(expr_range, scope)| {
508 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
512 // XXX: during completion, cursor might be outside of any particular
513 // expression. Try to figure out the correct scope...
515 db: &dyn HirDatabase,
517 source_map: &BodySourceMap,
518 expr_range: TextRange,
519 offset: InFile<TextSize>,
520 ) -> Option<ScopeId> {
521 let child_scopes = scopes
524 .filter_map(|(id, scope)| {
525 let source = source_map.expr_syntax(*id).ok()?;
526 // FIXME: correctly handle macro expansion
527 if source.file_id != offset.file_id {
530 let root = source.file_syntax(db.upcast());
531 let node = source.value.to_node(&root);
532 Some((node.syntax().text_range(), scope))
534 .filter(|&(range, _)| {
535 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
539 .max_by(|&(r1, _), &(r2, _)| {
540 if r1.contains_range(r2) {
541 std::cmp::Ordering::Greater
542 } else if r2.contains_range(r1) {
543 std::cmp::Ordering::Less
545 r1.start().cmp(&r2.start())
548 .map(|(_ptr, scope)| *scope)
552 pub(crate) fn resolve_hir_path(
553 db: &dyn HirDatabase,
556 ) -> Option<PathResolution> {
557 resolve_hir_path_(db, resolver, path, false)
561 pub(crate) fn resolve_hir_path_as_macro(
562 db: &dyn HirDatabase,
565 ) -> Option<MacroDef> {
566 resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(Into::into)
569 fn resolve_hir_path_(
570 db: &dyn HirDatabase,
573 prefer_value_ns: bool,
574 ) -> Option<PathResolution> {
576 let (ty, unresolved) = match path.type_anchor() {
578 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
579 res.map(|ty_ns| (ty_ns, path.segments().first()))
582 let (ty, remaining) =
583 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
585 Some(remaining) if remaining > 1 => None,
586 _ => Some((ty, path.segments().get(1))),
591 // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
592 // within the trait's associated types.
593 if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
594 if let Some(type_alias_id) =
595 db.trait_data(trait_id).associated_type_by_name(&unresolved.name)
597 return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
602 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
603 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
604 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
605 PathResolution::Def(Adt::from(it).into())
607 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
608 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
609 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
610 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
613 Some(unresolved) => res
614 .assoc_type_shorthand_candidates(db, |name, alias| {
615 (name == unresolved.name).then(|| alias)
617 .map(TypeAlias::from)
619 .map(PathResolution::Def),
624 let body_owner = resolver.body_owner();
626 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
627 let res = match val {
628 ValueNs::LocalBinding(pat_id) => {
629 let var = Local { parent: body_owner?, pat_id };
630 PathResolution::Local(var)
632 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
633 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
634 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
635 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
636 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
637 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
638 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
646 .resolve_module_path_in_items(db.upcast(), path.mod_path())
648 .map(|it| PathResolution::Def(it.into()))
653 .resolve_path_as_macro(db.upcast(), path.mod_path())
654 .map(|def| PathResolution::Macro(def.into()))
657 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
662 /// Resolves a path where we know it is a qualifier of another path.
664 /// For example, if we have:
674 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
675 fn resolve_hir_path_qualifier(
676 db: &dyn HirDatabase,
679 ) -> Option<PathResolution> {
681 .resolve_module_path_in_items(db.upcast(), path.mod_path())
683 .map(|it| PathResolution::Def(it.into()));
689 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
690 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
691 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
692 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
693 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
694 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
695 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
696 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),