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, 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, BuiltinType, Const, Field, Function, Local,
33 MacroDef, ModuleDef, Static, Struct, Trait, Type, TypeAlias, TypeParam, Variant,
37 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
38 /// original source files. It should not be used inside the HIR itself.
40 pub(crate) struct SourceAnalyzer {
41 pub(crate) file_id: HirFileId,
42 pub(crate) resolver: Resolver,
43 body: Option<Arc<Body>>,
44 body_source_map: Option<Arc<BodySourceMap>>,
45 infer: Option<Arc<InferenceResult>>,
46 scopes: Option<Arc<ExprScopes>>,
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)),
69 file_id: node.file_id,
73 pub(crate) fn new_for_resolver(
75 node: InFile<&SyntaxNode>,
80 body_source_map: None,
83 file_id: node.file_id,
87 fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
88 let src = match expr {
89 ast::Expr::MacroCall(call) => {
90 self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
92 _ => InFile::new(self.file_id, expr.clone()),
94 let sm = self.body_source_map.as_ref()?;
95 sm.node_expr(src.as_ref())
98 fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
99 // FIXME: macros, see `expr_id`
100 let src = InFile { file_id: self.file_id, value: pat };
101 self.body_source_map.as_ref()?.node_pat(src)
106 db: &dyn HirDatabase,
107 expr: InFile<ast::MacroCall>,
108 ) -> Option<InFile<ast::Expr>> {
109 let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
110 let expanded = db.parse_or_expand(macro_file)?;
112 let res = match ast::MacroCall::cast(expanded.clone()) {
113 Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
114 _ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
119 pub(crate) fn type_of_expr(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<Type> {
120 let expr_id = self.expr_id(db, expr)?;
121 let ty = self.infer.as_ref()?[expr_id].clone();
122 Type::new_with_resolver(db, &self.resolver, ty)
125 pub(crate) fn type_of_expr_with_coercion(
127 db: &dyn HirDatabase,
130 let expr_id = self.expr_id(db, expr)?;
131 let infer = self.infer.as_ref()?;
135 .and_then(|adjusts| adjusts.last().map(|adjust| &adjust.target))
136 .unwrap_or_else(|| &infer[expr_id]);
137 Type::new_with_resolver(db, &self.resolver, ty.clone())
140 pub(crate) fn type_of_pat(&self, db: &dyn HirDatabase, pat: &ast::Pat) -> Option<Type> {
141 let pat_id = self.pat_id(pat)?;
142 let ty = self.infer.as_ref()?[pat_id].clone();
143 Type::new_with_resolver(db, &self.resolver, ty)
146 pub(crate) fn type_of_self(
148 db: &dyn HirDatabase,
149 param: &ast::SelfParam,
151 let src = InFile { file_id: self.file_id, value: param };
152 let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
153 let ty = self.infer.as_ref()?[pat_id].clone();
154 Type::new_with_resolver(db, &self.resolver, ty)
157 pub(crate) fn resolve_method_call(
159 db: &dyn HirDatabase,
160 call: &ast::MethodCallExpr,
161 ) -> Option<(FunctionId, Substitution)> {
162 let expr_id = self.expr_id(db, &call.clone().into())?;
163 self.infer.as_ref()?.method_resolution(expr_id)
166 pub(crate) fn resolve_field(
168 db: &dyn HirDatabase,
169 field: &ast::FieldExpr,
171 let expr_id = self.expr_id(db, &field.clone().into())?;
172 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
175 pub(crate) fn resolve_record_field(
177 db: &dyn HirDatabase,
178 field: &ast::RecordExprField,
179 ) -> Option<(Field, Option<Local>, Type)> {
180 let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
181 let expr = ast::Expr::from(record_expr);
182 let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
184 let local_name = field.field_name()?.as_name();
185 let local = if field.name_ref().is_some() {
188 let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
189 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
190 Some(ValueNs::LocalBinding(pat_id)) => {
191 Some(Local { pat_id, parent: self.resolver.body_owner()? })
196 let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
197 let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
198 let variant_data = variant.variant_data(db.upcast());
199 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
201 db.field_types(variant).get(field.local_id)?.clone().substitute(&Interner, subst);
202 Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
205 pub(crate) fn resolve_record_pat_field(
207 db: &dyn HirDatabase,
208 field: &ast::RecordPatField,
210 let field_name = field.field_name()?.as_name();
211 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
212 let pat_id = self.pat_id(&record_pat.into())?;
213 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
214 let variant_data = variant.variant_data(db.upcast());
215 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
219 pub(crate) fn resolve_macro_call(
221 db: &dyn HirDatabase,
222 macro_call: InFile<&ast::MacroCall>,
223 ) -> Option<MacroDef> {
224 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
225 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
226 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
229 pub(crate) fn resolve_bind_pat_to_const(
231 db: &dyn HirDatabase,
233 ) -> Option<ModuleDef> {
234 let pat_id = self.pat_id(&pat.clone().into())?;
235 let body = self.body.as_ref()?;
236 let path = match &body[pat_id] {
237 Pat::Path(path) => path,
240 let res = resolve_hir_path(db, &self.resolver, path)?;
242 PathResolution::Def(def) => Some(def),
247 pub(crate) fn resolve_path(
249 db: &dyn HirDatabase,
251 ) -> Option<PathResolution> {
252 let parent = || path.syntax().parent();
253 let mut prefer_value_ns = false;
254 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
255 let expr_id = self.expr_id(db, &path_expr.into())?;
256 let infer = self.infer.as_ref()?;
257 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
258 return Some(PathResolution::AssocItem(assoc.into()));
260 if let Some(VariantId::EnumVariantId(variant)) =
261 infer.variant_resolution_for_expr(expr_id)
263 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
265 prefer_value_ns = true;
268 if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
269 let pat_id = self.pat_id(&path_pat.into())?;
270 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
271 return Some(PathResolution::AssocItem(assoc.into()));
273 if let Some(VariantId::EnumVariantId(variant)) =
274 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
276 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
280 if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
281 let expr_id = self.expr_id(db, &rec_lit.into())?;
282 if let Some(VariantId::EnumVariantId(variant)) =
283 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
285 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
289 if let Some(pat) = parent()
290 .and_then(ast::RecordPat::cast)
292 .or_else(|| parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from))
294 let pat_id = self.pat_id(&pat)?;
295 if let Some(VariantId::EnumVariantId(variant)) =
296 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
298 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
302 // This must be a normal source file rather than macro file.
303 let hygiene = Hygiene::new(db.upcast(), self.file_id);
304 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
305 let hir_path = Path::from_src(path.clone(), &ctx)?;
307 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
308 // trying to resolve foo::bar.
309 if let Some(outer_path) = parent().and_then(ast::Path::cast) {
310 if let Some(qualifier) = outer_path.qualifier() {
311 if path == &qualifier {
312 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
316 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
317 // trying to resolve foo::bar.
318 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
319 if let Some(qualifier) = use_tree.path() {
320 if path == &qualifier && use_tree.coloncolon_token().is_some() {
321 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
326 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
327 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
329 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
333 pub(crate) fn record_literal_missing_fields(
335 db: &dyn HirDatabase,
336 literal: &ast::RecordExpr,
337 ) -> Option<Vec<(Field, Type)>> {
338 let krate = self.resolver.krate()?;
339 let body = self.body.as_ref()?;
340 let infer = self.infer.as_ref()?;
342 let expr_id = self.expr_id(db, &literal.clone().into())?;
343 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
345 let (variant, missing_fields, _exhaustive) =
346 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
347 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
351 pub(crate) fn record_pattern_missing_fields(
353 db: &dyn HirDatabase,
354 pattern: &ast::RecordPat,
355 ) -> Option<Vec<(Field, Type)>> {
356 let krate = self.resolver.krate()?;
357 let body = self.body.as_ref()?;
358 let infer = self.infer.as_ref()?;
360 let pat_id = self.pat_id(&pattern.clone().into())?;
361 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
363 let (variant, missing_fields, _exhaustive) =
364 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
365 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
371 db: &dyn HirDatabase,
373 substs: &Substitution,
375 missing_fields: Vec<LocalFieldId>,
376 ) -> Vec<(Field, Type)> {
377 let field_types = db.field_types(variant);
382 let field = FieldId { parent: variant, local_id };
383 let ty = field_types[local_id].clone().substitute(&Interner, substs);
384 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
389 pub(crate) fn expand(
391 db: &dyn HirDatabase,
392 macro_call: InFile<&ast::MacroCall>,
393 ) -> Option<HirFileId> {
394 let krate = self.resolver.krate()?;
395 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
396 self.resolver.resolve_path_as_macro(db.upcast(), &path)
398 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
401 pub(crate) fn resolve_variant(
403 db: &dyn HirDatabase,
404 record_lit: ast::RecordExpr,
405 ) -> Option<VariantId> {
406 let infer = self.infer.as_ref()?;
407 let expr_id = self.expr_id(db, &record_lit.into())?;
408 infer.variant_resolution_for_expr(expr_id)
414 source_map: &BodySourceMap,
415 node: InFile<&SyntaxNode>,
416 ) -> Option<ScopeId> {
419 .filter_map(ast::Expr::cast)
420 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
421 .find_map(|it| scopes.scope_for(it))
425 db: &dyn HirDatabase,
427 source_map: &BodySourceMap,
428 offset: InFile<TextSize>,
429 ) -> Option<ScopeId> {
433 .filter_map(|(id, scope)| {
434 let source = source_map.expr_syntax(*id).ok()?;
435 // FIXME: correctly handle macro expansion
436 if source.file_id != offset.file_id {
439 let root = source.file_syntax(db.upcast());
440 let node = source.value.to_node(&root);
441 Some((node.syntax().text_range(), scope))
443 // find containing scope
444 .min_by_key(|(expr_range, _scope)| {
446 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
450 .map(|(expr_range, scope)| {
451 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
455 // XXX: during completion, cursor might be outside of any particular
456 // expression. Try to figure out the correct scope...
458 db: &dyn HirDatabase,
460 source_map: &BodySourceMap,
461 expr_range: TextRange,
462 offset: InFile<TextSize>,
463 ) -> Option<ScopeId> {
464 let child_scopes = scopes
467 .filter_map(|(id, scope)| {
468 let source = source_map.expr_syntax(*id).ok()?;
469 // FIXME: correctly handle macro expansion
470 if source.file_id != offset.file_id {
473 let root = source.file_syntax(db.upcast());
474 let node = source.value.to_node(&root);
475 Some((node.syntax().text_range(), scope))
477 .filter(|&(range, _)| {
478 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
482 .max_by(|&(r1, _), &(r2, _)| {
483 if r1.contains_range(r2) {
484 std::cmp::Ordering::Greater
485 } else if r2.contains_range(r1) {
486 std::cmp::Ordering::Less
488 r1.start().cmp(&r2.start())
491 .map(|(_ptr, scope)| *scope)
495 pub(crate) fn resolve_hir_path(
496 db: &dyn HirDatabase,
499 ) -> Option<PathResolution> {
500 resolve_hir_path_(db, resolver, path, false)
503 fn resolve_hir_path_(
504 db: &dyn HirDatabase,
507 prefer_value_ns: bool,
508 ) -> Option<PathResolution> {
510 let (ty, unresolved) = match path.type_anchor() {
512 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
513 res.map(|ty_ns| (ty_ns, path.segments().first()))
516 let (ty, remaining) =
517 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
519 Some(remaining) if remaining > 1 => None,
520 _ => Some((ty, path.segments().get(1))),
525 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
526 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
527 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
528 PathResolution::Def(Adt::from(it).into())
530 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
531 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
532 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
533 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
536 Some(unresolved) => res
537 .assoc_type_shorthand_candidates(db, |name, alias| {
538 (name == unresolved.name).then(|| alias)
540 .map(TypeAlias::from)
542 .map(PathResolution::Def),
547 let body_owner = resolver.body_owner();
549 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
550 let res = match val {
551 ValueNs::LocalBinding(pat_id) => {
552 let var = Local { parent: body_owner?, pat_id };
553 PathResolution::Local(var)
555 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
556 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
557 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
558 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
559 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
560 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
561 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
569 .resolve_module_path_in_items(db.upcast(), path.mod_path())
571 .map(|it| PathResolution::Def(it.into()))
576 .resolve_path_as_macro(db.upcast(), path.mod_path())
577 .map(|def| PathResolution::Macro(def.into()))
580 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
585 /// Resolves a path where we know it is a qualifier of another path.
587 /// For example, if we have:
597 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
598 fn resolve_hir_path_qualifier(
599 db: &dyn HirDatabase,
602 ) -> Option<PathResolution> {
604 .resolve_module_path_in_items(db.upcast(), path.mod_path())
606 .map(|it| PathResolution::Def(it.into()));
612 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
613 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
614 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
615 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
616 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
617 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
618 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
619 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),