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};
12 scope::{ExprScopes, ScopeId},
15 expr::{ExprId, Pat, PatId},
16 resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs},
17 AsMacroCall, DefWithBodyId, FieldId, LocalFieldId, VariantId,
19 use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
21 expr::{record_literal_missing_fields, record_pattern_missing_fields},
22 InferenceResult, Substs, Ty,
26 SyntaxNode, TextRange, TextSize,
30 db::HirDatabase, semantics::PathResolution, Adt, Const, EnumVariant, Field, Function, Local,
31 MacroDef, ModPath, ModuleDef, Path, PathKind, Static, Struct, Trait, Type, TypeAlias,
36 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
37 /// original source files. It should not be used inside the HIR itself.
39 pub(crate) struct SourceAnalyzer {
41 pub(crate) resolver: Resolver,
42 body: Option<Arc<Body>>,
43 body_source_map: Option<Arc<BodySourceMap>>,
44 infer: Option<Arc<InferenceResult>>,
45 scopes: Option<Arc<ExprScopes>>,
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)),
68 file_id: node.file_id,
72 pub(crate) fn new_for_resolver(
74 node: InFile<&SyntaxNode>,
79 body_source_map: None,
82 file_id: node.file_id,
86 fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
87 let src = match expr {
88 ast::Expr::MacroCall(call) => {
89 self.expand_expr(db, InFile::new(self.file_id, call.clone()))?
91 _ => InFile::new(self.file_id, expr.clone()),
93 let sm = self.body_source_map.as_ref()?;
94 sm.node_expr(src.as_ref())
97 fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
98 // FIXME: macros, see `expr_id`
99 let src = InFile { file_id: self.file_id, value: pat };
100 self.body_source_map.as_ref()?.node_pat(src)
105 db: &dyn HirDatabase,
106 expr: InFile<ast::MacroCall>,
107 ) -> Option<InFile<ast::Expr>> {
108 let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
109 let expanded = db.parse_or_expand(macro_file)?;
111 let res = match ast::MacroCall::cast(expanded.clone()) {
112 Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?,
113 _ => InFile::new(macro_file, ast::Expr::cast(expanded)?),
118 pub(crate) fn type_of(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<Type> {
119 let expr_id = self.expr_id(db, expr)?;
120 let ty = self.infer.as_ref()?[expr_id].clone();
121 Type::new_with_resolver(db, &self.resolver, ty)
124 pub(crate) fn type_of_pat(&self, db: &dyn HirDatabase, pat: &ast::Pat) -> Option<Type> {
125 let pat_id = self.pat_id(pat)?;
126 let ty = self.infer.as_ref()?[pat_id].clone();
127 Type::new_with_resolver(db, &self.resolver, ty)
130 pub(crate) fn resolve_method_call(
132 db: &dyn HirDatabase,
133 call: &ast::MethodCallExpr,
134 ) -> Option<Function> {
135 let expr_id = self.expr_id(db, &call.clone().into())?;
136 self.infer.as_ref()?.method_resolution(expr_id).map(Function::from)
139 pub(crate) fn resolve_field(
141 db: &dyn HirDatabase,
142 field: &ast::FieldExpr,
144 let expr_id = self.expr_id(db, &field.clone().into())?;
145 self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
148 pub(crate) fn resolve_record_field(
150 db: &dyn HirDatabase,
151 field: &ast::RecordField,
152 ) -> Option<(Field, Option<Local>)> {
153 let expr = field.expr()?;
154 let expr_id = self.expr_id(db, &expr)?;
155 let local = if field.name_ref().is_some() {
158 let local_name = field.field_name()?.as_name();
159 let path = ModPath::from_segments(PathKind::Plain, once(local_name));
160 match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
161 Some(ValueNs::LocalBinding(pat_id)) => {
162 Some(Local { pat_id, parent: self.resolver.body_owner()? })
167 let struct_field = self.infer.as_ref()?.record_field_resolution(expr_id)?;
168 Some((struct_field.into(), local))
171 pub(crate) fn resolve_record_field_pat(
173 _db: &dyn HirDatabase,
174 field: &ast::RecordFieldPat,
176 let pat_id = self.pat_id(&field.pat()?)?;
177 let struct_field = self.infer.as_ref()?.record_field_pat_resolution(pat_id)?;
178 Some(struct_field.into())
181 pub(crate) fn resolve_macro_call(
183 db: &dyn HirDatabase,
184 macro_call: InFile<&ast::MacroCall>,
185 ) -> Option<MacroDef> {
186 let hygiene = Hygiene::new(db.upcast(), macro_call.file_id);
187 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
188 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
191 pub(crate) fn resolve_bind_pat_to_const(
193 db: &dyn HirDatabase,
195 ) -> Option<ModuleDef> {
196 let pat_id = self.pat_id(&pat.clone().into())?;
197 let body = self.body.as_ref()?;
198 let path = match &body[pat_id] {
199 Pat::Path(path) => path,
202 let res = resolve_hir_path(db, &self.resolver, &path)?;
204 PathResolution::Def(def) => Some(def),
209 pub(crate) fn resolve_path(
211 db: &dyn HirDatabase,
213 ) -> Option<PathResolution> {
214 if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
215 let expr_id = self.expr_id(db, &path_expr.into())?;
216 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) {
217 return Some(PathResolution::AssocItem(assoc.into()));
220 if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) {
221 let pat_id = self.pat_id(&path_pat.into())?;
222 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
223 return Some(PathResolution::AssocItem(assoc.into()));
226 // This must be a normal source file rather than macro file.
228 crate::Path::from_src(path.clone(), &Hygiene::new(db.upcast(), self.file_id))?;
230 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we
231 // trying to resolve foo::bar.
232 if let Some(outer_path) = path.syntax().parent().and_then(ast::Path::cast) {
233 if let Some(qualifier) = outer_path.qualifier() {
234 if path == &qualifier {
235 return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
240 resolve_hir_path(db, &self.resolver, &hir_path)
243 pub(crate) fn record_literal_missing_fields(
245 db: &dyn HirDatabase,
246 literal: &ast::RecordLit,
247 ) -> Option<Vec<(Field, Type)>> {
248 let krate = self.resolver.krate()?;
249 let body = self.body.as_ref()?;
250 let infer = self.infer.as_ref()?;
252 let expr_id = self.expr_id(db, &literal.clone().into())?;
253 let substs = match &infer.type_of_expr[expr_id] {
254 Ty::Apply(a_ty) => &a_ty.parameters,
258 let (variant, missing_fields, _exhaustive) =
259 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
260 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
264 pub(crate) fn record_pattern_missing_fields(
266 db: &dyn HirDatabase,
267 pattern: &ast::RecordPat,
268 ) -> Option<Vec<(Field, Type)>> {
269 let krate = self.resolver.krate()?;
270 let body = self.body.as_ref()?;
271 let infer = self.infer.as_ref()?;
273 let pat_id = self.pat_id(&pattern.clone().into())?;
274 let substs = match &infer.type_of_pat[pat_id] {
275 Ty::Apply(a_ty) => &a_ty.parameters,
279 let (variant, missing_fields, _exhaustive) =
280 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
281 let res = self.missing_fields(db, krate, substs, variant, missing_fields);
287 db: &dyn HirDatabase,
291 missing_fields: Vec<LocalFieldId>,
292 ) -> Vec<(Field, Type)> {
293 let field_types = db.field_types(variant);
298 let field = FieldId { parent: variant, local_id };
299 let ty = field_types[local_id].clone().subst(substs);
300 (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty))
305 pub(crate) fn expand(
307 db: &dyn HirDatabase,
308 macro_call: InFile<&ast::MacroCall>,
309 ) -> Option<HirFileId> {
310 let macro_call_id = macro_call.as_call_id(db.upcast(), |path| {
311 self.resolver.resolve_path_as_macro(db.upcast(), &path)
313 Some(macro_call_id.as_file())
319 source_map: &BodySourceMap,
320 node: InFile<&SyntaxNode>,
321 ) -> Option<ScopeId> {
324 .filter_map(ast::Expr::cast)
325 .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
326 .find_map(|it| scopes.scope_for(it))
330 db: &dyn HirDatabase,
332 source_map: &BodySourceMap,
333 offset: InFile<TextSize>,
334 ) -> Option<ScopeId> {
338 .filter_map(|(id, scope)| {
339 let source = source_map.expr_syntax(*id).ok()?;
340 // FIXME: correctly handle macro expansion
341 if source.file_id != offset.file_id {
344 let root = source.file_syntax(db.upcast());
345 let node = source.value.to_node(&root);
346 Some((node.syntax().text_range(), scope))
348 // find containing scope
349 .min_by_key(|(expr_range, _scope)| {
351 !(expr_range.start() <= offset.value && offset.value <= expr_range.end()),
355 .map(|(expr_range, scope)| {
356 adjust(db, scopes, source_map, expr_range, offset.file_id, offset.value)
361 // XXX: during completion, cursor might be outside of any particular
362 // expression. Try to figure out the correct scope...
364 db: &dyn HirDatabase,
366 source_map: &BodySourceMap,
367 expr_range: TextRange,
370 ) -> Option<ScopeId> {
371 let child_scopes = scopes
374 .filter_map(|(id, scope)| {
375 let source = source_map.expr_syntax(*id).ok()?;
376 // FIXME: correctly handle macro expansion
377 if source.file_id != file_id {
380 let root = source.file_syntax(db.upcast());
381 let node = source.value.to_node(&root);
382 Some((node.syntax().text_range(), scope))
384 .filter(|&(range, _)| {
385 range.start() <= offset && expr_range.contains_range(range) && range != expr_range
389 .max_by(|&(r1, _), &(r2, _)| {
390 if r1.contains_range(r2) {
391 std::cmp::Ordering::Greater
392 } else if r2.contains_range(r1) {
393 std::cmp::Ordering::Less
395 r1.start().cmp(&r2.start())
398 .map(|(_ptr, scope)| *scope)
401 pub(crate) fn resolve_hir_path(
402 db: &dyn HirDatabase,
405 ) -> Option<PathResolution> {
407 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
408 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
409 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
410 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
411 PathResolution::Def(Adt::from(it).into())
413 TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
414 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
415 TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
416 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
419 let body_owner = resolver.body_owner();
421 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
422 let res = match val {
423 ValueNs::LocalBinding(pat_id) => {
424 let var = Local { parent: body_owner?.into(), pat_id };
425 PathResolution::Local(var)
427 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
428 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
429 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
430 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
431 ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
432 ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
438 .resolve_module_path_in_items(db.upcast(), path.mod_path())
440 .map(|it| PathResolution::Def(it.into()));
442 types.or(values).or(items).or_else(|| {
444 .resolve_path_as_macro(db.upcast(), path.mod_path())
445 .map(|def| PathResolution::Macro(def.into()))
449 /// Resolves a path where we know it is a qualifier of another path.
451 /// For example, if we have:
461 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
462 pub(crate) fn resolve_hir_path_qualifier(
463 db: &dyn HirDatabase,
466 ) -> Option<PathResolution> {
468 .resolve_module_path_in_items(db.upcast(), path.mod_path())
470 .map(|it| PathResolution::Def(it.into()));
476 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
477 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
478 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
479 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()),
480 TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
481 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
482 TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
483 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),