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>>,
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(
251 db: &dyn HirDatabase,
253 ) -> Option<PathResolution> {
254 let parent = || path.syntax().parent();
255 let mut prefer_value_ns = false;
256 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
257 let expr_id = self.expr_id(db, &path_expr.into())?;
258 let infer = self.infer.as_ref()?;
259 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
260 return Some(PathResolution::AssocItem(assoc.into()));
262 if let Some(VariantId::EnumVariantId(variant)) =
263 infer.variant_resolution_for_expr(expr_id)
265 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
267 prefer_value_ns = true;
270 if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
271 let pat_id = self.pat_id(&path_pat.into())?;
272 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
273 return Some(PathResolution::AssocItem(assoc.into()));
275 if let Some(VariantId::EnumVariantId(variant)) =
276 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
278 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
282 if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
283 let expr_id = self.expr_id(db, &rec_lit.into())?;
284 if let Some(VariantId::EnumVariantId(variant)) =
285 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
287 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
291 if let Some(pat) = parent()
292 .and_then(ast::RecordPat::cast)
294 .or_else(|| parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from))
296 let pat_id = self.pat_id(&pat)?;
297 if let Some(VariantId::EnumVariantId(variant)) =
298 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
300 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
304 // This must be a normal source file rather than macro file.
305 let hygiene = Hygiene::new(db.upcast(), self.file_id);
306 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
307 let hir_path = Path::from_src(path.clone(), &ctx)?;
309 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
310 // trying to resolve foo::bar.
311 if let Some(outer_path) = parent().and_then(ast::Path::cast) {
312 if let Some(qualifier) = outer_path.qualifier() {
313 if path == &qualifier {
314 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
318 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
319 // trying to resolve foo::bar.
320 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
321 if let Some(qualifier) = use_tree.path() {
322 if path == &qualifier && use_tree.coloncolon_token().is_some() {
323 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
328 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
329 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
331 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
335 pub(crate) fn record_literal_missing_fields(
337 db: &dyn HirDatabase,
338 literal: &ast::RecordExpr,
339 ) -> Option<Vec<(Field, Type)>> {
340 let krate = self.resolver.krate()?;
341 let body = self.body.as_ref()?;
342 let infer = self.infer.as_ref()?;
344 let expr_id = self.expr_id(db, &literal.clone().into())?;
345 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
347 let (variant, missing_fields, _exhaustive) =
348 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
349 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
353 pub(crate) fn record_pattern_missing_fields(
355 db: &dyn HirDatabase,
356 pattern: &ast::RecordPat,
357 ) -> Option<Vec<(Field, Type)>> {
358 let krate = self.resolver.krate()?;
359 let body = self.body.as_ref()?;
360 let infer = self.infer.as_ref()?;
362 let pat_id = self.pat_id(&pattern.clone().into())?;
363 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
365 let (variant, missing_fields, _exhaustive) =
366 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
367 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
373 db: &dyn HirDatabase,
375 substs: &Substitution,
377 missing_fields: Vec<LocalFieldId>,
378 ) -> Vec<(Field, Type)> {
379 let field_types = db.field_types(variant);
384 let field = FieldId { parent: variant, local_id };
385 let ty = field_types[local_id].clone().substitute(&Interner, substs);
386 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
391 pub(crate) fn expand(
393 db: &dyn HirDatabase,
394 macro_call: InFile<&ast::MacroCall>,
395 ) -> Option<HirFileId> {
396 let krate = self.resolver.krate()?;
397 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
398 self.resolver.resolve_path_as_macro(db.upcast(), &path)
400 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
403 pub(crate) fn resolve_variant(
405 db: &dyn HirDatabase,
406 record_lit: ast::RecordExpr,
407 ) -> Option<VariantId> {
408 let infer = self.infer.as_ref()?;
409 let expr_id = self.expr_id(db, &record_lit.into())?;
410 infer.variant_resolution_for_expr(expr_id)
416 source_map: &BodySourceMap,
417 node: InFile<&SyntaxNode>,
418 ) -> Option<ScopeId> {
421 .filter_map(ast::Expr::cast)
422 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
423 .find_map(|it| scopes.scope_for(it))
427 db: &dyn HirDatabase,
429 source_map: &BodySourceMap,
430 offset: InFile<TextSize>,
431 ) -> Option<ScopeId> {
435 .filter_map(|(id, scope)| {
436 let source = source_map.expr_syntax(*id).ok()?;
437 // FIXME: correctly handle macro expansion
438 if source.file_id != offset.file_id {
441 let root = source.file_syntax(db.upcast());
442 let node = source.value.to_node(&root);
443 Some((node.syntax().text_range(), scope))
445 // find containing scope
446 .min_by_key(|(expr_range, _scope)| {
448 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
452 .map(|(expr_range, scope)| {
453 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
457 // XXX: during completion, cursor might be outside of any particular
458 // expression. Try to figure out the correct scope...
460 db: &dyn HirDatabase,
462 source_map: &BodySourceMap,
463 expr_range: TextRange,
464 offset: InFile<TextSize>,
465 ) -> Option<ScopeId> {
466 let child_scopes = scopes
469 .filter_map(|(id, scope)| {
470 let source = source_map.expr_syntax(*id).ok()?;
471 // FIXME: correctly handle macro expansion
472 if source.file_id != offset.file_id {
475 let root = source.file_syntax(db.upcast());
476 let node = source.value.to_node(&root);
477 Some((node.syntax().text_range(), scope))
479 .filter(|&(range, _)| {
480 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
484 .max_by(|&(r1, _), &(r2, _)| {
485 if r1.contains_range(r2) {
486 std::cmp::Ordering::Greater
487 } else if r2.contains_range(r1) {
488 std::cmp::Ordering::Less
490 r1.start().cmp(&r2.start())
493 .map(|(_ptr, scope)| *scope)
497 pub(crate) fn resolve_hir_path(
498 db: &dyn HirDatabase,
501 ) -> Option<PathResolution> {
502 resolve_hir_path_(db, resolver, path, false)
505 fn resolve_hir_path_(
506 db: &dyn HirDatabase,
509 prefer_value_ns: bool,
510 ) -> Option<PathResolution> {
512 let (ty, unresolved) = match path.type_anchor() {
514 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
515 res.map(|ty_ns| (ty_ns, path.segments().first()))
518 let (ty, remaining) =
519 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
521 Some(remaining) if remaining > 1 => None,
522 _ => Some((ty, path.segments().get(1))),
527 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
528 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
529 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
530 PathResolution::Def(Adt::from(it).into())
532 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
533 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
534 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
535 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
538 Some(unresolved) => res
539 .assoc_type_shorthand_candidates(db, |name, alias| {
540 (name == unresolved.name).then(|| alias)
542 .map(TypeAlias::from)
544 .map(PathResolution::Def),
549 let body_owner = resolver.body_owner();
551 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
552 let res = match val {
553 ValueNs::LocalBinding(pat_id) => {
554 let var = Local { parent: body_owner?, pat_id };
555 PathResolution::Local(var)
557 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
558 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
559 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
560 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
561 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
562 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
563 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
571 .resolve_module_path_in_items(db.upcast(), path.mod_path())
573 .map(|it| PathResolution::Def(it.into()))
578 .resolve_path_as_macro(db.upcast(), path.mod_path())
579 .map(|def| PathResolution::Macro(def.into()))
582 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
587 /// Resolves a path where we know it is a qualifier of another path.
589 /// For example, if we have:
599 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
600 fn resolve_hir_path_qualifier(
601 db: &dyn HirDatabase,
604 ) -> Option<PathResolution> {
606 .resolve_module_path_in_items(db.upcast(), path.mod_path())
608 .map(|it| PathResolution::Def(it.into()));
614 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
615 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
616 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
617 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
618 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
619 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
620 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
621 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),