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>)> {
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 variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
182 let variant_data = variant.variant_data(db.upcast());
183 let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
184 Some((field.into(), local))
187 pub(crate) fn resolve_record_pat_field(
189 db: &dyn HirDatabase,
190 field: &ast::RecordPatField,
192 let field_name = field.field_name()?.as_name();
193 let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
194 let pat_id = self.pat_id(&record_pat.into())?;
195 let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
196 let variant_data = variant.variant_data(db.upcast());
197 let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
201 pub(crate) fn resolve_macro_call(
203 db: &dyn HirDatabase,
204 macro_call: InFile<&ast::MacroCall>,
205 ) -> Option<MacroDef> {
206 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
207 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
208 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
211 pub(crate) fn resolve_bind_pat_to_const(
213 db: &dyn HirDatabase,
215 ) -> Option<ModuleDef> {
216 let pat_id = self.pat_id(&pat.clone().into())?;
217 let body = self.body.as_ref()?;
218 let path = match &body[pat_id] {
219 Pat::Path(path) => path,
222 let res = resolve_hir_path(db, &self.resolver, &path)?;
224 PathResolution::Def(def) => Some(def),
229 pub(crate) fn resolve_path(
231 db: &dyn HirDatabase,
233 ) -> Option<PathResolution> {
234 let parent = || path.syntax().parent();
235 let mut prefer_value_ns = false;
236 if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
237 let expr_id = self.expr_id(db, &path_expr.into())?;
238 let infer = self.infer.as_ref()?;
239 if let Some(assoc) = infer.assoc_resolutions_for_expr(expr_id) {
240 return Some(PathResolution::AssocItem(assoc.into()));
242 if let Some(VariantId::EnumVariantId(variant)) =
243 infer.variant_resolution_for_expr(expr_id)
245 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
247 prefer_value_ns = true;
250 if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
251 let pat_id = self.pat_id(&path_pat.into())?;
252 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
253 return Some(PathResolution::AssocItem(assoc.into()));
255 if let Some(VariantId::EnumVariantId(variant)) =
256 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
258 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
262 if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
263 let expr_id = self.expr_id(db, &rec_lit.into())?;
264 if let Some(VariantId::EnumVariantId(variant)) =
265 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
267 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
271 if let Some(pat) = parent()
272 .and_then(ast::RecordPat::cast)
274 .or_else(|| parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from))
276 let pat_id = self.pat_id(&pat)?;
277 if let Some(VariantId::EnumVariantId(variant)) =
278 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
280 return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
284 // This must be a normal source file rather than macro file.
285 let hygiene = Hygiene::new(db.upcast(), self.file_id);
286 let ctx = body::LowerCtx::with_hygiene(db.upcast(), &hygiene);
287 let hir_path = Path::from_src(path.clone(), &ctx)?;
289 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we
290 // trying to resolve foo::bar.
291 if let Some(outer_path) = parent().and_then(ast::Path::cast) {
292 if let Some(qualifier) = outer_path.qualifier() {
293 if path == &qualifier {
294 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
299 resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
302 pub(crate) fn record_literal_missing_fields(
304 db: &dyn HirDatabase,
305 literal: &ast::RecordExpr,
306 ) -> Option<Vec<(Field, Type)>> {
307 let krate = self.resolver.krate()?;
308 let body = self.body.as_ref()?;
309 let infer = self.infer.as_ref()?;
311 let expr_id = self.expr_id(db, &literal.clone().into())?;
312 let substs = infer.type_of_expr[expr_id].as_adt()?.1;
314 let (variant, missing_fields, _exhaustive) =
315 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
316 let res = self.missing_fields(db, krate, &substs, variant, missing_fields);
320 pub(crate) fn record_pattern_missing_fields(
322 db: &dyn HirDatabase,
323 pattern: &ast::RecordPat,
324 ) -> Option<Vec<(Field, Type)>> {
325 let krate = self.resolver.krate()?;
326 let body = self.body.as_ref()?;
327 let infer = self.infer.as_ref()?;
329 let pat_id = self.pat_id(&pattern.clone().into())?;
330 let substs = infer.type_of_pat[pat_id].as_adt()?.1;
332 let (variant, missing_fields, _exhaustive) =
333 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
334 let res = self.missing_fields(db, krate, &substs, variant, missing_fields);
340 db: &dyn HirDatabase,
342 substs: &Substitution,
344 missing_fields: Vec<LocalFieldId>,
345 ) -> Vec<(Field, Type)> {
346 let field_types = db.field_types(variant);
351 let field = FieldId { parent: variant, local_id };
352 let ty = field_types[local_id].clone().substitute(&Interner, substs);
353 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
358 pub(crate) fn expand(
360 db: &dyn HirDatabase,
361 macro_call: InFile<&ast::MacroCall>,
362 ) -> Option<HirFileId> {
363 let krate = self.resolver.krate()?;
364 let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
365 self.resolver.resolve_path_as_macro(db.upcast(), &path)
367 Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
370 pub(crate) fn resolve_variant(
372 db: &dyn HirDatabase,
373 record_lit: ast::RecordExpr,
374 ) -> Option<VariantId> {
375 let infer = self.infer.as_ref()?;
376 let expr_id = self.expr_id(db, &record_lit.into())?;
377 infer.variant_resolution_for_expr(expr_id)
383 source_map: &BodySourceMap,
384 node: InFile<&SyntaxNode>,
385 ) -> Option<ScopeId> {
388 .filter_map(ast::Expr::cast)
389 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
390 .find_map(|it| scopes.scope_for(it))
394 db: &dyn HirDatabase,
396 source_map: &BodySourceMap,
397 offset: InFile<TextSize>,
398 ) -> Option<ScopeId> {
402 .filter_map(|(id, scope)| {
403 let source = source_map.expr_syntax(*id).ok()?;
404 // FIXME: correctly handle macro expansion
405 if source.file_id != offset.file_id {
408 let root = source.file_syntax(db.upcast());
409 let node = source.value.to_node(&root);
410 Some((node.syntax().text_range(), scope))
412 // find containing scope
413 .min_by_key(|(expr_range, _scope)| {
415 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
419 .map(|(expr_range, scope)| {
420 adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope)
424 // XXX: during completion, cursor might be outside of any particular
425 // expression. Try to figure out the correct scope...
427 db: &dyn HirDatabase,
429 source_map: &BodySourceMap,
430 expr_range: TextRange,
431 offset: InFile<TextSize>,
432 ) -> Option<ScopeId> {
433 let child_scopes = scopes
436 .filter_map(|(id, scope)| {
437 let source = source_map.expr_syntax(*id).ok()?;
438 // FIXME: correctly handle macro expansion
439 if source.file_id != offset.file_id {
442 let root = source.file_syntax(db.upcast());
443 let node = source.value.to_node(&root);
444 Some((node.syntax().text_range(), scope))
446 .filter(|&(range, _)| {
447 range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range
451 .max_by(|&(r1, _), &(r2, _)| {
452 if r1.contains_range(r2) {
453 std::cmp::Ordering::Greater
454 } else if r2.contains_range(r1) {
455 std::cmp::Ordering::Less
457 r1.start().cmp(&r2.start())
460 .map(|(_ptr, scope)| *scope)
464 pub(crate) fn resolve_hir_path(
465 db: &dyn HirDatabase,
468 ) -> Option<PathResolution> {
469 resolve_hir_path_(db, resolver, path, false)
472 fn resolve_hir_path_(
473 db: &dyn HirDatabase,
476 prefer_value_ns: bool,
477 ) -> Option<PathResolution> {
479 let (ty, unresolved) = match path.type_anchor() {
481 let (_, res) = TyLoweringContext::new(db, resolver).lower_ty_ext(type_ref);
482 res.map(|ty_ns| (ty_ns, path.segments().first()))
485 let (ty, remaining) =
486 resolver.resolve_path_in_type_ns(db.upcast(), path.mod_path())?;
488 Some(remaining) if remaining > 1 => None,
489 _ => Some((ty, path.segments().get(1))),
494 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
495 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
496 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
497 PathResolution::Def(Adt::from(it).into())
499 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
500 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
501 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
502 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
505 Some(unresolved) => res
506 .assoc_type_shorthand_candidates(db, |name, alias| {
507 (name == unresolved.name).then(|| alias)
509 .map(TypeAlias::from)
511 .map(PathResolution::Def),
516 let body_owner = resolver.body_owner();
518 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
519 let res = match val {
520 ValueNs::LocalBinding(pat_id) => {
521 let var = Local { parent: body_owner?, pat_id };
522 PathResolution::Local(var)
524 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
525 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
526 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
527 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
528 ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
529 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
530 ValueNs::GenericParam(it) => PathResolution::ConstParam(it.into()),
538 .resolve_module_path_in_items(db.upcast(), path.mod_path())
540 .map(|it| PathResolution::Def(it.into()))
545 .resolve_path_as_macro(db.upcast(), path.mod_path())
546 .map(|def| PathResolution::Macro(def.into()))
549 if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
554 /// Resolves a path where we know it is a qualifier of another path.
556 /// For example, if we have:
566 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
567 fn resolve_hir_path_qualifier(
568 db: &dyn HirDatabase,
571 ) -> Option<PathResolution> {
573 .resolve_module_path_in_items(db.upcast(), path.mod_path())
575 .map(|it| PathResolution::Def(it.into()));
581 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
582 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
583 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
584 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
585 TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
586 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
587 TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
588 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),