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, HasResolver, 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>>,
49 pub(crate) fn new_for_body(
52 node: InFile<&SyntaxNode>,
53 offset: Option<TextSize>,
55 let (body, source_map) = db.body_with_source_map(def);
56 let scopes = db.expr_scopes(def);
57 let scope = match offset {
58 None => scope_for(&scopes, &source_map, node),
59 Some(offset) => scope_for_offset(db, &scopes, &source_map, node.with_value(offset)),
61 let resolver = resolver_for_scope(db.upcast(), def, scope);
65 body_source_map: Some(source_map),
66 infer: Some(db.infer(def)),
67 file_id: node.file_id,
71 pub(crate) fn new_for_resolver(
73 node: InFile<&SyntaxNode>,
78 body_source_map: None,
80 file_id: node.file_id,
84 fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
85 let src = match expr {
86 ast::Expr::MacroCall(call) => {
87 self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
89 _ => InFile::new(self.file_id, expr.clone()),
91 let sm = self.body_source_map.as_ref()?;
92 sm.node_expr(src.as_ref())
95 fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
96 // FIXME: macros, see `expr_id`
97 let src = InFile { file_id: self.file_id, value: pat };
98 self.body_source_map.as_ref()?.node_pat(src)
103 db: &dyn HirDatabase,
104 expr: InFile<ast::MacroCall>,
105 ) -> Option<InFile<ast::Expr>> {
106 let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
107 let expanded = db.parse_or_expand(macro_file)?;
109 let res = match ast::MacroCall::cast(expanded.clone()) {
110 Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
111 _ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
116 pub(crate) fn type_of_expr(
118 db: &dyn HirDatabase,
120 ) -> Option<(Type, Option<Type>)> {
121 let expr_id = self.expr_id(db, expr)?;
122 let infer = self.infer.as_ref()?;
126 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
127 let ty = infer[expr_id].clone();
128 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
129 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
132 pub(crate) fn type_of_pat(
134 db: &dyn HirDatabase,
136 ) -> Option<(Type, Option<Type>)> {
137 let pat_id = self.pat_id(pat)?;
138 let infer = self.infer.as_ref()?;
142 .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
143 let ty = infer[pat_id].clone();
144 let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
145 mk_ty(ty).zip(Some(coerced.and_then(mk_ty)))
148 pub(crate) fn type_of_self(
150 db: &dyn HirDatabase,
151 param: &ast::SelfParam,
153 let src = InFile { file_id: self.file_id, value: param };
154 let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
155 let ty = self.infer.as_ref()?[pat_id].clone();
156 Type::new_with_resolver(db, &self.resolver, ty)
159 pub(crate) fn resolve_method_call(
161 db: &dyn HirDatabase,
162 call: &ast::MethodCallExpr,
163 ) -> Option<(FunctionId, Substitution)> {
164 let expr_id = self.expr_id(db, &call.clone().into())?;
165 self.infer.as_ref()?.method_resolution(expr_id)
168 pub(crate) fn resolve_field(
170 db: &dyn HirDatabase,
171 field: &ast::FieldExpr,
173 let expr_id = self.expr_id(db, &field.clone().into())?;
174 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
177 pub(crate) fn resolve_record_field(
179 db: &dyn HirDatabase,
180 field: &ast::RecordExprField,
181 ) -> Option<(Field, Option<Local>, Type)> {
182 let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
183 let expr = ast::Expr::from(record_expr);
184 let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
186 let local_name = field.field_name()?.as_name();
187 let local = if field.name_ref().is_some() {
190 let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
191 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
192 Some(ValueNs::LocalBinding(pat_id)) => {
193 Some(Local { pat_id, parent: self.resolver.body_owner()? })
198 let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
199 let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
200 let variant_data = variant.variant_data(db.upcast());
201 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
203 db.field_types(variant).get(field.local_id)?.clone().substitute(&Interner, subst);
204 Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
207 pub(crate) fn resolve_record_pat_field(
209 db: &dyn HirDatabase,
210 field: &ast::RecordPatField,
212 let field_name = field.field_name()?.as_name();
213 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
214 let pat_id = self.pat_id(&record_pat.into())?;
215 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
216 let variant_data = variant.variant_data(db.upcast());
217 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
221 pub(crate) fn resolve_macro_call(
223 db: &dyn HirDatabase,
224 macro_call: InFile<&ast::MacroCall>,
225 ) -> Option<MacroDef> {
226 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
227 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
228 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
231 pub(crate) fn resolve_bind_pat_to_const(
233 db: &dyn HirDatabase,
235 ) -> Option<ModuleDef> {
236 let pat_id = self.pat_id(&pat.clone().into())?;
237 let body = self.body.as_ref()?;
238 let path = match &body[pat_id] {
239 Pat::Path(path) => path,
242 let res = resolve_hir_path(db, &self.resolver, path)?;
244 PathResolution::Def(def) => Some(def),
249 pub(crate) fn resolve_path_as_macro(
251 db: &dyn HirDatabase,
253 ) -> Option<MacroDef> {
254 // This must be a normal source file rather than macro file.
255 let hygiene = Hygiene::new(db.upcast(), self.file_id);
256 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
257 let hir_path = Path::from_src(path.clone(), &ctx)?;
258 resolve_hir_path_as_macro(db, &self.resolver, &hir_path)
261 pub(crate) fn resolve_path(
263 db: &dyn HirDatabase,
265 ) -> Option<PathResolution> {
266 let parent = || path.syntax().parent();
267 let mut prefer_value_ns = false;
268 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
269 let expr_id = self.expr_id(db, &path_expr.into())?;
270 let infer = self.infer.as_ref()?;
271 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
272 return Some(PathResolution::AssocItem(assoc.into()));
274 if let Some(VariantId::EnumVariantId(variant)) =
275 infer.variant_resolution_for_expr(expr_id)
277 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
279 prefer_value_ns = true;
282 if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
283 let pat_id = self.pat_id(&path_pat.into())?;
284 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
285 return Some(PathResolution::AssocItem(assoc.into()));
287 if let Some(VariantId::EnumVariantId(variant)) =
288 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
290 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
294 if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
295 let expr_id = self.expr_id(db, &rec_lit.into())?;
296 if let Some(VariantId::EnumVariantId(variant)) =
297 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
299 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
303 if let Some(pat) = parent()
304 .and_then(ast::RecordPat::cast)
306 .or_else(|| parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from))
308 let pat_id = self.pat_id(&pat)?;
309 if let Some(VariantId::EnumVariantId(variant)) =
310 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
312 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
316 // This must be a normal source file rather than macro file.
317 let hygiene = Hygiene::new(db.upcast(), self.file_id);
318 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
319 let hir_path = Path::from_src(path.clone(), &ctx)?;
321 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
322 // trying to resolve foo::bar.
323 if let Some(outer_path) = parent().and_then(ast::Path::cast) {
324 if let Some(qualifier) = outer_path.qualifier() {
325 if path == &qualifier {
326 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
330 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
331 // trying to resolve foo::bar.
332 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
333 if let Some(qualifier) = use_tree.path() {
334 if path == &qualifier && use_tree.coloncolon_token().is_some() {
335 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
340 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
341 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
343 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
347 pub(crate) fn record_literal_missing_fields(
349 db: &dyn HirDatabase,
350 literal: &ast::RecordExpr,
351 ) -> Option<Vec<(Field, Type)>> {
352 let krate = self.resolver.krate()?;
353 let body = self.body.as_ref()?;
354 let infer = self.infer.as_ref()?;
356 let expr_id = self.expr_id(db, &literal.clone().into())?;
357 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
359 let (variant, missing_fields, _exhaustive) =
360 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
361 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
365 pub(crate) fn record_pattern_missing_fields(
367 db: &dyn HirDatabase,
368 pattern: &ast::RecordPat,
369 ) -> Option<Vec<(Field, Type)>> {
370 let krate = self.resolver.krate()?;
371 let body = self.body.as_ref()?;
372 let infer = self.infer.as_ref()?;
374 let pat_id = self.pat_id(&pattern.clone().into())?;
375 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
377 let (variant, missing_fields, _exhaustive) =
378 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
379 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
385 db: &dyn HirDatabase,
387 substs: &Substitution,
389 missing_fields: Vec<LocalFieldId>,
390 ) -> Vec<(Field, Type)> {
391 let field_types = db.field_types(variant);
396 let field = FieldId { parent: variant, local_id };
397 let ty = field_types[local_id].clone().substitute(&Interner, substs);
398 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
403 pub(crate) fn expand(
405 db: &dyn HirDatabase,
406 macro_call: InFile<&ast::MacroCall>,
407 ) -> Option<HirFileId> {
408 let krate = self.resolver.krate()?;
409 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
410 self.resolver.resolve_path_as_macro(db.upcast(), &path)
412 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
415 pub(crate) fn resolve_variant(
417 db: &dyn HirDatabase,
418 record_lit: ast::RecordExpr,
419 ) -> Option<VariantId> {
420 let infer = self.infer.as_ref()?;
421 let expr_id = self.expr_id(db, &record_lit.into())?;
422 infer.variant_resolution_for_expr(expr_id)
428 source_map: &BodySourceMap,
429 node: InFile<&SyntaxNode>,
430 ) -> Option<ScopeId> {
433 .filter_map(ast::Expr::cast)
434 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
435 .find_map(|it| scopes.scope_for(it))
439 db: &dyn HirDatabase,
441 source_map: &BodySourceMap,
442 offset: InFile<TextSize>,
443 ) -> Option<ScopeId> {
447 .filter_map(|(id, scope)| {
448 let source = source_map.expr_syntax(*id).ok()?;
449 // FIXME: correctly handle macro expansion
450 if source.file_id != offset.file_id {
453 let root = source.file_syntax(db.upcast());
454 let node = source.value.to_node(&root);
455 Some((node.syntax().text_range(), scope))
457 // find containing scope
458 .min_by_key(|(expr_range, _scope)| {
460 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
464 .map(|(expr_range, scope)| {
465 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
469 // XXX: during completion, cursor might be outside of any particular
470 // expression. Try to figure out the correct scope...
472 db: &dyn HirDatabase,
474 source_map: &BodySourceMap,
475 expr_range: TextRange,
476 offset: InFile<TextSize>,
477 ) -> Option<ScopeId> {
478 let child_scopes = scopes
481 .filter_map(|(id, scope)| {
482 let source = source_map.expr_syntax(*id).ok()?;
483 // FIXME: correctly handle macro expansion
484 if source.file_id != offset.file_id {
487 let root = source.file_syntax(db.upcast());
488 let node = source.value.to_node(&root);
489 Some((node.syntax().text_range(), scope))
491 .filter(|&(range, _)| {
492 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
496 .max_by(|&(r1, _), &(r2, _)| {
497 if r1.contains_range(r2) {
498 std::cmp::Ordering::Greater
499 } else if r2.contains_range(r1) {
500 std::cmp::Ordering::Less
502 r1.start().cmp(&r2.start())
505 .map(|(_ptr, scope)| *scope)
509 pub(crate) fn resolve_hir_path(
510 db: &dyn HirDatabase,
513 ) -> Option<PathResolution> {
514 resolve_hir_path_(db, resolver, path, false)
518 pub(crate) fn resolve_hir_path_as_macro(
519 db: &dyn HirDatabase,
522 ) -> Option<MacroDef> {
523 resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(Into::into)
526 fn resolve_hir_path_(
527 db: &dyn HirDatabase,
530 prefer_value_ns: bool,
531 ) -> Option<PathResolution> {
533 let (ty, unresolved) = match path.type_anchor() {
535 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
536 res.map(|ty_ns| (ty_ns, path.segments().first()))
539 let (ty, remaining) =
540 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
542 Some(remaining) if remaining > 1 => None,
543 _ => Some((ty, path.segments().get(1))),
548 if let (Some(_), TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
549 let resolver = trait_id.resolver(db.upcast());
550 if let Some(module_def_id) = resolver
551 .resolve_module_path_in_trait_assoc_items(db.upcast(), path.mod_path())
552 .and_then(|ns| ns.take_types())
554 return Some(PathResolution::Def(module_def_id.into()));
559 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
560 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
561 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
562 PathResolution::Def(Adt::from(it).into())
564 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
565 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
566 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
567 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
570 Some(unresolved) => res
571 .assoc_type_shorthand_candidates(db, |name, alias| {
572 (name == unresolved.name).then(|| alias)
574 .map(TypeAlias::from)
576 .map(PathResolution::Def),
581 let body_owner = resolver.body_owner();
583 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
584 let res = match val {
585 ValueNs::LocalBinding(pat_id) => {
586 let var = Local { parent: body_owner?, pat_id };
587 PathResolution::Local(var)
589 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
590 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
591 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
592 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
593 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
594 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
595 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
603 .resolve_module_path_in_items(db.upcast(), path.mod_path())
605 .map(|it| PathResolution::Def(it.into()))
610 .resolve_path_as_macro(db.upcast(), path.mod_path())
611 .map(|def| PathResolution::Macro(def.into()))
614 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
619 /// Resolves a path where we know it is a qualifier of another path.
621 /// For example, if we have:
631 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
632 fn resolve_hir_path_qualifier(
633 db: &dyn HirDatabase,
636 ) -> Option<PathResolution> {
638 .resolve_module_path_in_items(db.upcast(), path.mod_path())
640 .map(|it| PathResolution::Def(it.into()));
646 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
647 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
648 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
649 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
650 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
651 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
652 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
653 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),