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, Ty, 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,
129 ) -> Option<(Type, Option<Type>)> {
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 let mk_ty = |ty: &Ty| Type::new_with_resolver(db, &self.resolver, ty.clone());
137 mk_ty(&infer[expr_id]).map(|ty| (ty, coerced.and_then(mk_ty)))
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_pat_with_coercion(
148 db: &dyn HirDatabase,
150 ) -> Option<(Type, Option<Type>)> {
151 let pat_id = self.pat_id(pat)?;
152 let infer = self.infer.as_ref()?;
156 .and_then(|adjusts| adjusts.last().map(|adjust| &adjust.target));
157 let mk_ty = |ty: &Ty| Type::new_with_resolver(db, &self.resolver, ty.clone());
158 mk_ty(&infer[pat_id]).map(|ty| (ty, coerced.and_then(mk_ty)))
161 pub(crate) fn type_of_self(
163 db: &dyn HirDatabase,
164 param: &ast::SelfParam,
166 let src = InFile { file_id: self.file_id, value: param };
167 let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
168 let ty = self.infer.as_ref()?[pat_id].clone();
169 Type::new_with_resolver(db, &self.resolver, ty)
172 pub(crate) fn resolve_method_call(
174 db: &dyn HirDatabase,
175 call: &ast::MethodCallExpr,
176 ) -> Option<(FunctionId, Substitution)> {
177 let expr_id = self.expr_id(db, &call.clone().into())?;
178 self.infer.as_ref()?.method_resolution(expr_id)
181 pub(crate) fn resolve_field(
183 db: &dyn HirDatabase,
184 field: &ast::FieldExpr,
186 let expr_id = self.expr_id(db, &field.clone().into())?;
187 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
190 pub(crate) fn resolve_record_field(
192 db: &dyn HirDatabase,
193 field: &ast::RecordExprField,
194 ) -> Option<(Field, Option<Local>, Type)> {
195 let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
196 let expr = ast::Expr::from(record_expr);
197 let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
199 let local_name = field.field_name()?.as_name();
200 let local = if field.name_ref().is_some() {
203 let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
204 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
205 Some(ValueNs::LocalBinding(pat_id)) => {
206 Some(Local { pat_id, parent: self.resolver.body_owner()? })
211 let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
212 let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
213 let variant_data = variant.variant_data(db.upcast());
214 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
216 db.field_types(variant).get(field.local_id)?.clone().substitute(&Interner, subst);
217 Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
220 pub(crate) fn resolve_record_pat_field(
222 db: &dyn HirDatabase,
223 field: &ast::RecordPatField,
225 let field_name = field.field_name()?.as_name();
226 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
227 let pat_id = self.pat_id(&record_pat.into())?;
228 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
229 let variant_data = variant.variant_data(db.upcast());
230 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
234 pub(crate) fn resolve_macro_call(
236 db: &dyn HirDatabase,
237 macro_call: InFile<&ast::MacroCall>,
238 ) -> Option<MacroDef> {
239 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
240 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
241 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
244 pub(crate) fn resolve_bind_pat_to_const(
246 db: &dyn HirDatabase,
248 ) -> Option<ModuleDef> {
249 let pat_id = self.pat_id(&pat.clone().into())?;
250 let body = self.body.as_ref()?;
251 let path = match &body[pat_id] {
252 Pat::Path(path) => path,
255 let res = resolve_hir_path(db, &self.resolver, path)?;
257 PathResolution::Def(def) => Some(def),
262 pub(crate) fn resolve_path(
264 db: &dyn HirDatabase,
266 ) -> Option<PathResolution> {
267 let parent = || path.syntax().parent();
268 let mut prefer_value_ns = false;
269 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
270 let expr_id = self.expr_id(db, &path_expr.into())?;
271 let infer = self.infer.as_ref()?;
272 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
273 return Some(PathResolution::AssocItem(assoc.into()));
275 if let Some(VariantId::EnumVariantId(variant)) =
276 infer.variant_resolution_for_expr(expr_id)
278 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
280 prefer_value_ns = true;
283 if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
284 let pat_id = self.pat_id(&path_pat.into())?;
285 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
286 return Some(PathResolution::AssocItem(assoc.into()));
288 if let Some(VariantId::EnumVariantId(variant)) =
289 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
291 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
295 if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
296 let expr_id = self.expr_id(db, &rec_lit.into())?;
297 if let Some(VariantId::EnumVariantId(variant)) =
298 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
300 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
304 if let Some(pat) = parent()
305 .and_then(ast::RecordPat::cast)
307 .or_else(|| parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from))
309 let pat_id = self.pat_id(&pat)?;
310 if let Some(VariantId::EnumVariantId(variant)) =
311 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
313 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
317 // This must be a normal source file rather than macro file.
318 let hygiene = Hygiene::new(db.upcast(), self.file_id);
319 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
320 let hir_path = Path::from_src(path.clone(), &ctx)?;
322 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
323 // trying to resolve foo::bar.
324 if let Some(outer_path) = parent().and_then(ast::Path::cast) {
325 if let Some(qualifier) = outer_path.qualifier() {
326 if path == &qualifier {
327 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
331 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
332 // trying to resolve foo::bar.
333 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
334 if let Some(qualifier) = use_tree.path() {
335 if path == &qualifier && use_tree.coloncolon_token().is_some() {
336 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
341 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
342 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
344 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
348 pub(crate) fn record_literal_missing_fields(
350 db: &dyn HirDatabase,
351 literal: &ast::RecordExpr,
352 ) -> Option<Vec<(Field, Type)>> {
353 let krate = self.resolver.krate()?;
354 let body = self.body.as_ref()?;
355 let infer = self.infer.as_ref()?;
357 let expr_id = self.expr_id(db, &literal.clone().into())?;
358 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
360 let (variant, missing_fields, _exhaustive) =
361 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
362 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
366 pub(crate) fn record_pattern_missing_fields(
368 db: &dyn HirDatabase,
369 pattern: &ast::RecordPat,
370 ) -> Option<Vec<(Field, Type)>> {
371 let krate = self.resolver.krate()?;
372 let body = self.body.as_ref()?;
373 let infer = self.infer.as_ref()?;
375 let pat_id = self.pat_id(&pattern.clone().into())?;
376 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
378 let (variant, missing_fields, _exhaustive) =
379 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
380 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
386 db: &dyn HirDatabase,
388 substs: &Substitution,
390 missing_fields: Vec<LocalFieldId>,
391 ) -> Vec<(Field, Type)> {
392 let field_types = db.field_types(variant);
397 let field = FieldId { parent: variant, local_id };
398 let ty = field_types[local_id].clone().substitute(&Interner, substs);
399 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
404 pub(crate) fn expand(
406 db: &dyn HirDatabase,
407 macro_call: InFile<&ast::MacroCall>,
408 ) -> Option<HirFileId> {
409 let krate = self.resolver.krate()?;
410 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
411 self.resolver.resolve_path_as_macro(db.upcast(), &path)
413 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
416 pub(crate) fn resolve_variant(
418 db: &dyn HirDatabase,
419 record_lit: ast::RecordExpr,
420 ) -> Option<VariantId> {
421 let infer = self.infer.as_ref()?;
422 let expr_id = self.expr_id(db, &record_lit.into())?;
423 infer.variant_resolution_for_expr(expr_id)
429 source_map: &BodySourceMap,
430 node: InFile<&SyntaxNode>,
431 ) -> Option<ScopeId> {
434 .filter_map(ast::Expr::cast)
435 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
436 .find_map(|it| scopes.scope_for(it))
440 db: &dyn HirDatabase,
442 source_map: &BodySourceMap,
443 offset: InFile<TextSize>,
444 ) -> Option<ScopeId> {
448 .filter_map(|(id, scope)| {
449 let source = source_map.expr_syntax(*id).ok()?;
450 // FIXME: correctly handle macro expansion
451 if source.file_id != offset.file_id {
454 let root = source.file_syntax(db.upcast());
455 let node = source.value.to_node(&root);
456 Some((node.syntax().text_range(), scope))
458 // find containing scope
459 .min_by_key(|(expr_range, _scope)| {
461 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
465 .map(|(expr_range, scope)| {
466 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
470 // XXX: during completion, cursor might be outside of any particular
471 // expression. Try to figure out the correct scope...
473 db: &dyn HirDatabase,
475 source_map: &BodySourceMap,
476 expr_range: TextRange,
477 offset: InFile<TextSize>,
478 ) -> Option<ScopeId> {
479 let child_scopes = scopes
482 .filter_map(|(id, scope)| {
483 let source = source_map.expr_syntax(*id).ok()?;
484 // FIXME: correctly handle macro expansion
485 if source.file_id != offset.file_id {
488 let root = source.file_syntax(db.upcast());
489 let node = source.value.to_node(&root);
490 Some((node.syntax().text_range(), scope))
492 .filter(|&(range, _)| {
493 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
497 .max_by(|&(r1, _), &(r2, _)| {
498 if r1.contains_range(r2) {
499 std::cmp::Ordering::Greater
500 } else if r2.contains_range(r1) {
501 std::cmp::Ordering::Less
503 r1.start().cmp(&r2.start())
506 .map(|(_ptr, scope)| *scope)
510 pub(crate) fn resolve_hir_path(
511 db: &dyn HirDatabase,
514 ) -> Option<PathResolution> {
515 resolve_hir_path_(db, resolver, path, false)
518 fn resolve_hir_path_(
519 db: &dyn HirDatabase,
522 prefer_value_ns: bool,
523 ) -> Option<PathResolution> {
525 let (ty, unresolved) = match path.type_anchor() {
527 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
528 res.map(|ty_ns| (ty_ns, path.segments().first()))
531 let (ty, remaining) =
532 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
534 Some(remaining) if remaining > 1 => None,
535 _ => Some((ty, path.segments().get(1))),
540 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
541 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
542 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
543 PathResolution::Def(Adt::from(it).into())
545 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
546 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
547 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
548 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
551 Some(unresolved) => res
552 .assoc_type_shorthand_candidates(db, |name, alias| {
553 (name == unresolved.name).then(|| alias)
555 .map(TypeAlias::from)
557 .map(PathResolution::Def),
562 let body_owner = resolver.body_owner();
564 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
565 let res = match val {
566 ValueNs::LocalBinding(pat_id) => {
567 let var = Local { parent: body_owner?, pat_id };
568 PathResolution::Local(var)
570 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
571 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
572 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
573 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
574 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
575 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
576 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
584 .resolve_module_path_in_items(db.upcast(), path.mod_path())
586 .map(|it| PathResolution::Def(it.into()))
591 .resolve_path_as_macro(db.upcast(), path.mod_path())
592 .map(|def| PathResolution::Macro(def.into()))
595 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
600 /// Resolves a path where we know it is a qualifier of another path.
602 /// For example, if we have:
612 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
613 fn resolve_hir_path_qualifier(
614 db: &dyn HirDatabase,
617 ) -> Option<PathResolution> {
619 .resolve_module_path_in_items(db.upcast(), path.mod_path())
621 .map(|it| PathResolution::Def(it.into()));
627 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
628 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
629 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
630 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
631 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
632 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
633 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
634 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),