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(
121 db: &dyn HirDatabase,
123 ) -> Option<(Type, Option<Type>)> {
124 let expr_id = self.expr_id(db, expr)?;
125 let infer = self.infer.as_ref()?;
129 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
130 let ty = infer[expr_id].clone();
131 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
132 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
135 pub(crate) fn type_of_pat(
137 db: &dyn HirDatabase,
139 ) -> Option<(Type, Option<Type>)> {
140 let pat_id = self.pat_id(pat)?;
141 let infer = self.infer.as_ref()?;
145 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
146 let ty = infer[pat_id].clone();
147 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
148 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
151 pub(crate) fn type_of_self(
153 db: &dyn HirDatabase,
154 param: &ast::SelfParam,
156 let src = InFile { file_id: self.file_id, value: param };
157 let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
158 let ty = self.infer.as_ref()?[pat_id].clone();
159 Type::new_with_resolver(db, &self.resolver, ty)
162 pub(crate) fn resolve_method_call(
164 db: &dyn HirDatabase,
165 call: &ast::MethodCallExpr,
166 ) -> Option<(FunctionId, Substitution)> {
167 let expr_id = self.expr_id(db, &call.clone().into())?;
168 self.infer.as_ref()?.method_resolution(expr_id)
171 pub(crate) fn resolve_field(
173 db: &dyn HirDatabase,
174 field: &ast::FieldExpr,
176 let expr_id = self.expr_id(db, &field.clone().into())?;
177 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
180 pub(crate) fn resolve_record_field(
182 db: &dyn HirDatabase,
183 field: &ast::RecordExprField,
184 ) -> Option<(Field, Option<Local>, Type)> {
185 let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
186 let expr = ast::Expr::from(record_expr);
187 let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
189 let local_name = field.field_name()?.as_name();
190 let local = if field.name_ref().is_some() {
193 let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
194 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
195 Some(ValueNs::LocalBinding(pat_id)) => {
196 Some(Local { pat_id, parent: self.resolver.body_owner()? })
201 let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
202 let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
203 let variant_data = variant.variant_data(db.upcast());
204 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
206 db.field_types(variant).get(field.local_id)?.clone().substitute(&Interner, subst);
207 Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
210 pub(crate) fn resolve_record_pat_field(
212 db: &dyn HirDatabase,
213 field: &ast::RecordPatField,
215 let field_name = field.field_name()?.as_name();
216 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
217 let pat_id = self.pat_id(&record_pat.into())?;
218 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
219 let variant_data = variant.variant_data(db.upcast());
220 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
224 pub(crate) fn resolve_macro_call(
226 db: &dyn HirDatabase,
227 macro_call: InFile<&ast::MacroCall>,
228 ) -> Option<MacroDef> {
229 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
230 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
231 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
234 pub(crate) fn resolve_bind_pat_to_const(
236 db: &dyn HirDatabase,
238 ) -> Option<ModuleDef> {
239 let pat_id = self.pat_id(&pat.clone().into())?;
240 let body = self.body.as_ref()?;
241 let path = match &body[pat_id] {
242 Pat::Path(path) => path,
245 let res = resolve_hir_path(db, &self.resolver, path)?;
247 PathResolution::Def(def) => Some(def),
252 pub(crate) fn resolve_path(
254 db: &dyn HirDatabase,
256 ) -> Option<PathResolution> {
257 let parent = || path.syntax().parent();
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 if let Some(pat) = parent()
295 .and_then(ast::RecordPat::cast)
297 .or_else(|| parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from))
299 let pat_id = self.pat_id(&pat)?;
300 if let Some(VariantId::EnumVariantId(variant)) =
301 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
303 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
307 // This must be a normal source file rather than macro file.
308 let hygiene = Hygiene::new(db.upcast(), self.file_id);
309 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
310 let hir_path = Path::from_src(path.clone(), &ctx)?;
312 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
313 // trying to resolve foo::bar.
314 if let Some(outer_path) = parent().and_then(ast::Path::cast) {
315 if let Some(qualifier) = outer_path.qualifier() {
316 if path == &qualifier {
317 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
321 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
322 // trying to resolve foo::bar.
323 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
324 if let Some(qualifier) = use_tree.path() {
325 if path == &qualifier && use_tree.coloncolon_token().is_some() {
326 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
331 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
332 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
334 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
338 pub(crate) fn record_literal_missing_fields(
340 db: &dyn HirDatabase,
341 literal: &ast::RecordExpr,
342 ) -> Option<Vec<(Field, Type)>> {
343 let krate = self.resolver.krate()?;
344 let body = self.body.as_ref()?;
345 let infer = self.infer.as_ref()?;
347 let expr_id = self.expr_id(db, &literal.clone().into())?;
348 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
350 let (variant, missing_fields, _exhaustive) =
351 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
352 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
356 pub(crate) fn record_pattern_missing_fields(
358 db: &dyn HirDatabase,
359 pattern: &ast::RecordPat,
360 ) -> Option<Vec<(Field, Type)>> {
361 let krate = self.resolver.krate()?;
362 let body = self.body.as_ref()?;
363 let infer = self.infer.as_ref()?;
365 let pat_id = self.pat_id(&pattern.clone().into())?;
366 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
368 let (variant, missing_fields, _exhaustive) =
369 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
370 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
376 db: &dyn HirDatabase,
378 substs: &Substitution,
380 missing_fields: Vec<LocalFieldId>,
381 ) -> Vec<(Field, Type)> {
382 let field_types = db.field_types(variant);
387 let field = FieldId { parent: variant, local_id };
388 let ty = field_types[local_id].clone().substitute(&Interner, substs);
389 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
394 pub(crate) fn expand(
396 db: &dyn HirDatabase,
397 macro_call: InFile<&ast::MacroCall>,
398 ) -> Option<HirFileId> {
399 let krate = self.resolver.krate()?;
400 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
401 self.resolver.resolve_path_as_macro(db.upcast(), &path)
403 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
406 pub(crate) fn resolve_variant(
408 db: &dyn HirDatabase,
409 record_lit: ast::RecordExpr,
410 ) -> Option<VariantId> {
411 let infer = self.infer.as_ref()?;
412 let expr_id = self.expr_id(db, &record_lit.into())?;
413 infer.variant_resolution_for_expr(expr_id)
419 source_map: &BodySourceMap,
420 node: InFile<&SyntaxNode>,
421 ) -> Option<ScopeId> {
424 .filter_map(ast::Expr::cast)
425 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
426 .find_map(|it| scopes.scope_for(it))
430 db: &dyn HirDatabase,
432 source_map: &BodySourceMap,
433 offset: InFile<TextSize>,
434 ) -> Option<ScopeId> {
438 .filter_map(|(id, scope)| {
439 let source = source_map.expr_syntax(*id).ok()?;
440 // FIXME: correctly handle macro expansion
441 if source.file_id != offset.file_id {
444 let root = source.file_syntax(db.upcast());
445 let node = source.value.to_node(&root);
446 Some((node.syntax().text_range(), scope))
448 // find containing scope
449 .min_by_key(|(expr_range, _scope)| {
451 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
455 .map(|(expr_range, scope)| {
456 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
460 // XXX: during completion, cursor might be outside of any particular
461 // expression. Try to figure out the correct scope...
463 db: &dyn HirDatabase,
465 source_map: &BodySourceMap,
466 expr_range: TextRange,
467 offset: InFile<TextSize>,
468 ) -> Option<ScopeId> {
469 let child_scopes = scopes
472 .filter_map(|(id, scope)| {
473 let source = source_map.expr_syntax(*id).ok()?;
474 // FIXME: correctly handle macro expansion
475 if source.file_id != offset.file_id {
478 let root = source.file_syntax(db.upcast());
479 let node = source.value.to_node(&root);
480 Some((node.syntax().text_range(), scope))
482 .filter(|&(range, _)| {
483 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
487 .max_by(|&(r1, _), &(r2, _)| {
488 if r1.contains_range(r2) {
489 std::cmp::Ordering::Greater
490 } else if r2.contains_range(r1) {
491 std::cmp::Ordering::Less
493 r1.start().cmp(&r2.start())
496 .map(|(_ptr, scope)| *scope)
500 pub(crate) fn resolve_hir_path(
501 db: &dyn HirDatabase,
504 ) -> Option<PathResolution> {
505 resolve_hir_path_(db, resolver, path, false)
508 fn resolve_hir_path_(
509 db: &dyn HirDatabase,
512 prefer_value_ns: bool,
513 ) -> Option<PathResolution> {
515 let (ty, unresolved) = match path.type_anchor() {
517 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
518 res.map(|ty_ns| (ty_ns, path.segments().first()))
521 let (ty, remaining) =
522 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
524 Some(remaining) if remaining > 1 => None,
525 _ => Some((ty, path.segments().get(1))),
530 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
531 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
532 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
533 PathResolution::Def(Adt::from(it).into())
535 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
536 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
537 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
538 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
541 Some(unresolved) => res
542 .assoc_type_shorthand_candidates(db, |name, alias| {
543 (name == unresolved.name).then(|| alias)
545 .map(TypeAlias::from)
547 .map(PathResolution::Def),
552 let body_owner = resolver.body_owner();
554 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
555 let res = match val {
556 ValueNs::LocalBinding(pat_id) => {
557 let var = Local { parent: body_owner?, pat_id };
558 PathResolution::Local(var)
560 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
561 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
562 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
563 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
564 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
565 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
566 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
574 .resolve_module_path_in_items(db.upcast(), path.mod_path())
576 .map(|it| PathResolution::Def(it.into()))
581 .resolve_path_as_macro(db.upcast(), path.mod_path())
582 .map(|def| PathResolution::Macro(def.into()))
585 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
590 /// Resolves a path where we know it is a qualifier of another path.
592 /// For example, if we have:
602 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
603 fn resolve_hir_path_qualifier(
604 db: &dyn HirDatabase,
607 ) -> Option<PathResolution> {
609 .resolve_module_path_in_items(db.upcast(), path.mod_path())
611 .map(|it| PathResolution::Def(it.into()));
617 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
618 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
619 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
620 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
621 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
622 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
623 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
624 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),