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_pat(&self, db: &dyn HirDatabase, pat: &ast::Pat) -> Option<Type> {
126 let pat_id = self.pat_id(pat)?;
127 let ty = self.infer.as_ref()?[pat_id].clone();
128 Type::new_with_resolver(db, &self.resolver, ty)
131 pub(crate) fn type_of_self(
133 db: &dyn HirDatabase,
134 param: &ast::SelfParam,
136 let src = InFile { file_id: self.file_id, value: param };
137 let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?;
138 let ty = self.infer.as_ref()?[pat_id].clone();
139 Type::new_with_resolver(db, &self.resolver, ty)
142 pub(crate) fn resolve_method_call(
144 db: &dyn HirDatabase,
145 call: &ast::MethodCallExpr,
146 ) -> Option<(FunctionId, Substitution)> {
147 let expr_id = self.expr_id(db, &call.clone().into())?;
148 self.infer.as_ref()?.method_resolution(expr_id)
151 pub(crate) fn resolve_field(
153 db: &dyn HirDatabase,
154 field: &ast::FieldExpr,
156 let expr_id = self.expr_id(db, &field.clone().into())?;
157 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
160 pub(crate) fn resolve_record_field(
162 db: &dyn HirDatabase,
163 field: &ast::RecordExprField,
164 ) -> Option<(Field, Option<Local>, Type)> {
165 let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
166 let expr = ast::Expr::from(record_expr);
167 let expr_id = self.body_source_map.as_ref()?.node_expr(InFile::new(self.file_id, &expr))?;
169 let local_name = field.field_name()?.as_name();
170 let local = if field.name_ref().is_some() {
173 let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
174 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
175 Some(ValueNs::LocalBinding(pat_id)) => {
176 Some(Local { pat_id, parent: self.resolver.body_owner()? })
181 let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
182 let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
183 let variant_data = variant.variant_data(db.upcast());
184 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
186 db.field_types(variant).get(field.local_id)?.clone().substitute(&Interner, subst);
187 Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)?))
190 pub(crate) fn resolve_record_pat_field(
192 db: &dyn HirDatabase,
193 field: &ast::RecordPatField,
195 let field_name = field.field_name()?.as_name();
196 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
197 let pat_id = self.pat_id(&record_pat.into())?;
198 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
199 let variant_data = variant.variant_data(db.upcast());
200 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
204 pub(crate) fn resolve_macro_call(
206 db: &dyn HirDatabase,
207 macro_call: InFile<&ast::MacroCall>,
208 ) -> Option<MacroDef> {
209 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
210 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
211 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
214 pub(crate) fn resolve_bind_pat_to_const(
216 db: &dyn HirDatabase,
218 ) -> Option<ModuleDef> {
219 let pat_id = self.pat_id(&pat.clone().into())?;
220 let body = self.body.as_ref()?;
221 let path = match &body[pat_id] {
222 Pat::Path(path) => path,
225 let res = resolve_hir_path(db, &self.resolver, path)?;
227 PathResolution::Def(def) => Some(def),
232 pub(crate) fn resolve_path(
234 db: &dyn HirDatabase,
236 ) -> Option<PathResolution> {
237 let parent = || path.syntax().parent();
238 let mut prefer_value_ns = false;
239 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
240 let expr_id = self.expr_id(db, &path_expr.into())?;
241 let infer = self.infer.as_ref()?;
242 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
243 return Some(PathResolution::AssocItem(assoc.into()));
245 if let Some(VariantId::EnumVariantId(variant)) =
246 infer.variant_resolution_for_expr(expr_id)
248 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
250 prefer_value_ns = true;
253 if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
254 let pat_id = self.pat_id(&path_pat.into())?;
255 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
256 return Some(PathResolution::AssocItem(assoc.into()));
258 if let Some(VariantId::EnumVariantId(variant)) =
259 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
261 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
265 if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
266 let expr_id = self.expr_id(db, &rec_lit.into())?;
267 if let Some(VariantId::EnumVariantId(variant)) =
268 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
270 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
274 if let Some(pat) = parent()
275 .and_then(ast::RecordPat::cast)
277 .or_else(|| parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from))
279 let pat_id = self.pat_id(&pat)?;
280 if let Some(VariantId::EnumVariantId(variant)) =
281 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
283 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
287 // This must be a normal source file rather than macro file.
288 let hygiene = Hygiene::new(db.upcast(), self.file_id);
289 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
290 let hir_path = Path::from_src(path.clone(), &ctx)?;
292 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
293 // trying to resolve foo::bar.
294 if let Some(outer_path) = parent().and_then(ast::Path::cast) {
295 if let Some(qualifier) = outer_path.qualifier() {
296 if path == &qualifier {
297 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
301 // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
302 // trying to resolve foo::bar.
303 if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
304 if let Some(qualifier) = use_tree.path() {
305 if path == &qualifier && use_tree.coloncolon_token().is_some() {
306 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
311 if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
312 resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
314 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
318 pub(crate) fn record_literal_missing_fields(
320 db: &dyn HirDatabase,
321 literal: &ast::RecordExpr,
322 ) -> Option<Vec<(Field, Type)>> {
323 let krate = self.resolver.krate()?;
324 let body = self.body.as_ref()?;
325 let infer = self.infer.as_ref()?;
327 let expr_id = self.expr_id(db, &literal.clone().into())?;
328 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
330 let (variant, missing_fields, _exhaustive) =
331 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
332 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
336 pub(crate) fn record_pattern_missing_fields(
338 db: &dyn HirDatabase,
339 pattern: &ast::RecordPat,
340 ) -> Option<Vec<(Field, Type)>> {
341 let krate = self.resolver.krate()?;
342 let body = self.body.as_ref()?;
343 let infer = self.infer.as_ref()?;
345 let pat_id = self.pat_id(&pattern.clone().into())?;
346 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
348 let (variant, missing_fields, _exhaustive) =
349 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
350 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
356 db: &dyn HirDatabase,
358 substs: &Substitution,
360 missing_fields: Vec<LocalFieldId>,
361 ) -> Vec<(Field, Type)> {
362 let field_types = db.field_types(variant);
367 let field = FieldId { parent: variant, local_id };
368 let ty = field_types[local_id].clone().substitute(&Interner, substs);
369 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
374 pub(crate) fn expand(
376 db: &dyn HirDatabase,
377 macro_call: InFile<&ast::MacroCall>,
378 ) -> Option<HirFileId> {
379 let krate = self.resolver.krate()?;
380 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
381 self.resolver.resolve_path_as_macro(db.upcast(), &path)
383 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
386 pub(crate) fn resolve_variant(
388 db: &dyn HirDatabase,
389 record_lit: ast::RecordExpr,
390 ) -> Option<VariantId> {
391 let infer = self.infer.as_ref()?;
392 let expr_id = self.expr_id(db, &record_lit.into())?;
393 infer.variant_resolution_for_expr(expr_id)
399 source_map: &BodySourceMap,
400 node: InFile<&SyntaxNode>,
401 ) -> Option<ScopeId> {
404 .filter_map(ast::Expr::cast)
405 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
406 .find_map(|it| scopes.scope_for(it))
410 db: &dyn HirDatabase,
412 source_map: &BodySourceMap,
413 offset: InFile<TextSize>,
414 ) -> Option<ScopeId> {
418 .filter_map(|(id, scope)| {
419 let source = source_map.expr_syntax(*id).ok()?;
420 // FIXME: correctly handle macro expansion
421 if source.file_id != offset.file_id {
424 let root = source.file_syntax(db.upcast());
425 let node = source.value.to_node(&root);
426 Some((node.syntax().text_range(), scope))
428 // find containing scope
429 .min_by_key(|(expr_range, _scope)| {
431 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
435 .map(|(expr_range, scope)| {
436 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
440 // XXX: during completion, cursor might be outside of any particular
441 // expression. Try to figure out the correct scope...
443 db: &dyn HirDatabase,
445 source_map: &BodySourceMap,
446 expr_range: TextRange,
447 offset: InFile<TextSize>,
448 ) -> Option<ScopeId> {
449 let child_scopes = scopes
452 .filter_map(|(id, scope)| {
453 let source = source_map.expr_syntax(*id).ok()?;
454 // FIXME: correctly handle macro expansion
455 if source.file_id != offset.file_id {
458 let root = source.file_syntax(db.upcast());
459 let node = source.value.to_node(&root);
460 Some((node.syntax().text_range(), scope))
462 .filter(|&(range, _)| {
463 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
467 .max_by(|&(r1, _), &(r2, _)| {
468 if r1.contains_range(r2) {
469 std::cmp::Ordering::Greater
470 } else if r2.contains_range(r1) {
471 std::cmp::Ordering::Less
473 r1.start().cmp(&r2.start())
476 .map(|(_ptr, scope)| *scope)
480 pub(crate) fn resolve_hir_path(
481 db: &dyn HirDatabase,
484 ) -> Option<PathResolution> {
485 resolve_hir_path_(db, resolver, path, false)
488 fn resolve_hir_path_(
489 db: &dyn HirDatabase,
492 prefer_value_ns: bool,
493 ) -> Option<PathResolution> {
495 let (ty, unresolved) = match path.type_anchor() {
497 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
498 res.map(|ty_ns| (ty_ns, path.segments().first()))
501 let (ty, remaining) =
502 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
504 Some(remaining) if remaining > 1 => None,
505 _ => Some((ty, path.segments().get(1))),
510 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
511 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
512 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
513 PathResolution::Def(Adt::from(it).into())
515 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
516 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
517 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
518 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
521 Some(unresolved) => res
522 .assoc_type_shorthand_candidates(db, |name, alias| {
523 (name == unresolved.name).then(|| alias)
525 .map(TypeAlias::from)
527 .map(PathResolution::Def),
532 let body_owner = resolver.body_owner();
534 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
535 let res = match val {
536 ValueNs::LocalBinding(pat_id) => {
537 let var = Local { parent: body_owner?, pat_id };
538 PathResolution::Local(var)
540 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
541 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
542 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
543 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
544 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
545 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
546 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
554 .resolve_module_path_in_items(db.upcast(), path.mod_path())
556 .map(|it| PathResolution::Def(it.into()))
561 .resolve_path_as_macro(db.upcast(), path.mod_path())
562 .map(|def| PathResolution::Macro(def.into()))
565 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
570 /// Resolves a path where we know it is a qualifier of another path.
572 /// For example, if we have:
582 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
583 fn resolve_hir_path_qualifier(
584 db: &dyn HirDatabase,
587 ) -> Option<PathResolution> {
589 .resolve_module_path_in_items(db.upcast(), path.mod_path())
591 .map(|it| PathResolution::Def(it.into()));
597 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
598 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
599 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
600 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
601 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
602 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
603 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
604 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),