rust/crates/hir-def/src/body.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

429 lines
14 KiB
Rust
Raw Normal View History

2019-11-24 11:39:48 -06:00
//! Defines `Body`: a lowered representation of bodies of functions, statics and
//! consts.
2019-11-12 06:09:25 -06:00
mod lower;
2024-01-26 13:08:10 -06:00
mod pretty;
pub mod scope;
2020-10-23 12:27:04 -05:00
#[cfg(test)]
mod tests;
2019-11-12 09:46:57 -06:00
2023-05-02 09:12:22 -05:00
use std::ops::Index;
2019-11-12 09:46:57 -06:00
2020-08-13 09:25:38 -05:00
use base_db::CrateId;
use cfg::{CfgExpr, CfgOptions};
use either::Either;
use hir_expand::{name::Name, HirFileId, InFile};
use la_arena::{Arena, ArenaMap};
2019-11-12 09:46:57 -06:00
use rustc_hash::FxHashMap;
use syntax::{ast, AstPtr, SyntaxNodePtr};
2023-05-02 09:12:22 -05:00
use triomphe::Arc;
2019-11-12 09:46:57 -06:00
use crate::{
2019-11-23 05:44:43 -06:00
db::DefDatabase,
expander::Expander,
hir::{
dummy_expr_id, Binding, BindingId, Expr, ExprId, Label, LabelId, Pat, PatId, RecordFieldPat,
},
2021-01-18 13:18:05 -06:00
nameres::DefMap,
2019-12-18 10:41:33 -06:00
path::{ModPath, Path},
src::HasSource,
BlockId, DefWithBodyId, HasModule, Lookup,
2019-11-12 09:46:57 -06:00
};
2019-11-12 09:46:57 -06:00
/// The body of an item (function, const etc.).
2022-07-17 10:22:11 -05:00
#[derive(Debug, Eq, PartialEq)]
2019-11-12 09:46:57 -06:00
pub struct Body {
2020-03-19 10:00:11 -05:00
pub exprs: Arena<Expr>,
pub pats: Arena<Pat>,
2023-02-18 14:32:55 -06:00
pub bindings: Arena<Binding>,
2020-12-23 09:34:30 -06:00
pub labels: Arena<Label>,
/// Id of the closure/coroutine that owns the corresponding binding. If a binding is owned by the
2023-06-18 05:03:04 -05:00
/// top level expression, it will not be listed in here.
pub binding_owners: FxHashMap<BindingId, ExprId>,
2019-11-12 09:46:57 -06:00
/// The patterns for the function's parameters. While the parameter types are
/// part of the function signature, the patterns are not (they don't change
/// the external type of the function).
///
/// If this `Body` is for the body of a constant, this will just be
/// empty.
2019-11-24 09:48:29 -06:00
pub params: Vec<PatId>,
2019-11-12 09:46:57 -06:00
/// The `ExprId` of the actual body expression.
2019-11-24 09:48:29 -06:00
pub body_expr: ExprId,
2021-03-05 07:08:23 -06:00
/// Block expressions in this body that may contain inner items.
block_scopes: Vec<BlockId>,
2019-11-12 09:46:57 -06:00
}
2020-04-11 12:25:33 -05:00
pub type ExprPtr = AstPtr<ast::Expr>;
2019-11-28 03:50:26 -06:00
pub type ExprSource = InFile<ExprPtr>;
2019-11-12 09:46:57 -06:00
pub type PatPtr = AstPtr<Either<ast::Pat, ast::SelfParam>>;
2019-11-28 03:50:26 -06:00
pub type PatSource = InFile<PatPtr>;
2019-11-12 09:46:57 -06:00
2020-12-23 09:34:30 -06:00
pub type LabelPtr = AstPtr<ast::Label>;
pub type LabelSource = InFile<LabelPtr>;
pub type FieldPtr = AstPtr<ast::RecordExprField>;
pub type FieldSource = InFile<FieldPtr>;
pub type PatFieldPtr = AstPtr<ast::RecordPatField>;
pub type PatFieldSource = InFile<PatFieldPtr>;
2019-11-12 09:46:57 -06:00
/// An item body together with the mapping from syntax nodes to HIR expression
/// IDs. This is needed to go from e.g. a position in a file to the HIR
/// expression containing it; but for type inference etc., we want to operate on
/// a structure that is agnostic to the actual positions of expressions in the
/// file, so that we don't recompute types whenever some whitespace is typed.
///
/// One complication here is that, due to macro expansion, a single `Body` might
/// be spread across several files. So, for each ExprId and PatId, we record
/// both the HirFileId and the position inside the file. However, we only store
/// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
/// this properly for macros.
#[derive(Default, Debug, Eq, PartialEq)]
pub struct BodySourceMap {
expr_map: FxHashMap<ExprSource, ExprId>,
expr_map_back: ArenaMap<ExprId, ExprSource>,
2021-03-15 07:38:50 -05:00
pat_map: FxHashMap<PatSource, PatId>,
pat_map_back: ArenaMap<PatId, PatSource>,
2021-03-15 07:38:50 -05:00
2020-12-23 09:34:30 -06:00
label_map: FxHashMap<LabelSource, LabelId>,
label_map_back: ArenaMap<LabelId, LabelSource>,
2021-03-15 07:38:50 -05:00
/// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
/// Instead, we use id of expression (`92`) to identify the field.
field_map_back: FxHashMap<ExprId, FieldSource>,
pat_field_map_back: FxHashMap<PatId, PatFieldSource>,
2021-03-15 07:38:50 -05:00
2023-12-05 08:42:39 -06:00
format_args_template_map: FxHashMap<ExprId, Vec<(syntax::TextRange, Name)>>,
2019-12-23 07:47:11 -06:00
expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
2020-10-23 12:27:04 -05:00
/// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
/// the source map (since they're just as volatile).
diagnostics: Vec<BodyDiagnostic>,
2019-11-12 09:46:57 -06:00
}
2020-03-06 08:11:05 -06:00
#[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
2020-03-06 07:44:44 -06:00
pub struct SyntheticSyntax;
#[derive(Debug, Eq, PartialEq)]
pub enum BodyDiagnostic {
InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>>, krate: CrateId },
UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
UnreachableLabel { node: InFile<AstPtr<ast::Lifetime>>, name: Name },
UndeclaredLabel { node: InFile<AstPtr<ast::Lifetime>>, name: Name },
}
2019-11-12 09:46:57 -06:00
impl Body {
2019-11-14 08:37:22 -06:00
pub(crate) fn body_with_source_map_query(
db: &dyn DefDatabase,
2019-11-14 08:37:22 -06:00
def: DefWithBodyId,
) -> (Arc<Body>, Arc<BodySourceMap>) {
let _p = tracing::span!(tracing::Level::INFO, "body_with_source_map_query").entered();
2019-11-14 08:37:22 -06:00
let mut params = None;
let mut is_async_fn = false;
let InFile { file_id, value: body } = {
match def {
DefWithBodyId::FunctionId(f) => {
let data = db.function_data(f);
let f = f.lookup(db);
let src = f.source(db);
params = src.value.param_list().map(|param_list| {
let item_tree = f.id.item_tree(db);
let func = &item_tree[f.id.value];
let krate = f.container.module(db).krate;
let crate_graph = db.crate_graph();
(
param_list,
func.params.clone().map(move |param| {
item_tree
.attrs(db, krate, param.into())
.is_cfg_enabled(&crate_graph[krate].cfg_options)
}),
)
});
is_async_fn = data.has_async_kw();
src.map(|it| it.body().map(ast::Expr::from))
}
DefWithBodyId::ConstId(c) => {
let c = c.lookup(db);
let src = c.source(db);
src.map(|it| it.body())
}
DefWithBodyId::StaticId(s) => {
let s = s.lookup(db);
let src = s.source(db);
src.map(|it| it.body())
}
DefWithBodyId::VariantId(v) => {
let s = v.lookup(db);
let src = s.source(db);
src.map(|it| it.expr())
}
DefWithBodyId::InTypeConstId(c) => c.lookup(db).id.map(|_| c.source(db).expr()),
2022-08-06 11:50:21 -05:00
}
2019-11-14 08:37:22 -06:00
};
2023-06-05 06:27:19 -05:00
let module = def.module(db);
2019-11-14 08:37:22 -06:00
let expander = Expander::new(db, file_id, module);
2023-09-09 07:40:56 -05:00
let (mut body, mut source_map) =
2023-05-12 09:47:15 -05:00
Body::new(db, def, expander, params, body, module.krate, is_async_fn);
2021-04-03 20:26:16 -05:00
body.shrink_to_fit();
2023-09-09 07:40:56 -05:00
source_map.shrink_to_fit();
2019-11-14 08:37:22 -06:00
(Arc::new(body), Arc::new(source_map))
}
pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
2019-11-14 08:37:22 -06:00
db.body_with_source_map(def).0
}
/// Returns an iterator over all block expressions in this body that define inner items.
pub fn blocks<'a>(
&'a self,
db: &'a dyn DefDatabase,
) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
self.block_scopes.iter().map(move |&block| (block, db.block_def_map(block)))
}
2022-08-15 06:51:45 -05:00
pub fn pretty_print(&self, db: &dyn DefDatabase, owner: DefWithBodyId) -> String {
pretty::print_body_hir(db, self, owner)
}
pub fn pretty_print_expr(
&self,
db: &dyn DefDatabase,
owner: DefWithBodyId,
expr: ExprId,
) -> String {
pretty::print_expr_hir(db, self, owner, expr)
}
2019-11-14 08:37:22 -06:00
fn new(
db: &dyn DefDatabase,
2023-05-12 09:47:15 -05:00
owner: DefWithBodyId,
2019-11-14 00:38:25 -06:00
expander: Expander,
params: Option<(ast::ParamList, impl Iterator<Item = bool>)>,
2019-11-12 09:46:57 -06:00
body: Option<ast::Expr>,
2023-03-08 11:28:52 -06:00
krate: CrateId,
2023-04-04 14:37:38 -05:00
is_async_fn: bool,
2019-11-12 09:46:57 -06:00
) -> (Body, BodySourceMap) {
2023-05-12 09:47:15 -05:00
lower::lower(db, owner, expander, params, body, krate, is_async_fn)
2019-11-12 09:46:57 -06:00
}
2021-04-03 20:26:16 -05:00
fn shrink_to_fit(&mut self) {
2023-06-18 05:03:04 -05:00
let Self {
body_expr: _,
block_scopes,
exprs,
labels,
params,
pats,
bindings,
binding_owners,
} = self;
2021-04-03 20:26:16 -05:00
block_scopes.shrink_to_fit();
exprs.shrink_to_fit();
labels.shrink_to_fit();
params.shrink_to_fit();
pats.shrink_to_fit();
2023-02-18 14:32:55 -06:00
bindings.shrink_to_fit();
2023-06-18 05:03:04 -05:00
binding_owners.shrink_to_fit();
2021-04-03 20:26:16 -05:00
}
pub fn walk_bindings_in_pat(&self, pat_id: PatId, mut f: impl FnMut(BindingId)) {
self.walk_pats(pat_id, &mut |pat| {
if let Pat::Bind { id, .. } = &self[pat] {
f(*id);
}
});
}
pub fn walk_pats_shallow(&self, pat_id: PatId, mut f: impl FnMut(PatId)) {
let pat = &self[pat_id];
match pat {
Pat::Range { .. }
| Pat::Lit(..)
| Pat::Path(..)
| Pat::ConstBlock(..)
| Pat::Wild
| Pat::Missing => {}
&Pat::Bind { subpat, .. } => {
if let Some(subpat) = subpat {
f(subpat);
}
}
Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => {
2024-01-19 09:37:08 -06:00
args.iter().copied().for_each(f);
}
Pat::Ref { pat, .. } => f(*pat),
Pat::Slice { prefix, slice, suffix } => {
let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter());
2024-01-19 09:37:08 -06:00
total_iter.copied().for_each(f);
}
Pat::Record { args, .. } => {
args.iter().for_each(|RecordFieldPat { pat, .. }| f(*pat));
}
Pat::Box { inner } => f(*inner),
}
}
pub fn walk_pats(&self, pat_id: PatId, f: &mut impl FnMut(PatId)) {
f(pat_id);
self.walk_pats_shallow(pat_id, |p| self.walk_pats(p, f));
}
2023-06-18 05:03:04 -05:00
pub fn is_binding_upvar(&self, binding: BindingId, relative_to: ExprId) -> bool {
match self.binding_owners.get(&binding) {
2023-07-06 09:03:17 -05:00
Some(it) => {
2023-06-18 05:03:04 -05:00
// We assign expression ids in a way that outer closures will receive
// a lower id
2023-07-06 09:03:17 -05:00
it.into_raw() < relative_to.into_raw()
2023-06-18 05:03:04 -05:00
}
None => true,
}
}
2019-11-12 09:46:57 -06:00
}
2022-07-17 10:22:11 -05:00
impl Default for Body {
fn default() -> Self {
Self {
body_expr: dummy_expr_id(),
exprs: Default::default(),
pats: Default::default(),
2023-02-18 14:32:55 -06:00
bindings: Default::default(),
2022-07-17 10:22:11 -05:00
labels: Default::default(),
params: Default::default(),
block_scopes: Default::default(),
2023-06-18 05:03:04 -05:00
binding_owners: Default::default(),
2022-07-17 10:22:11 -05:00
}
}
}
2019-11-12 09:46:57 -06:00
impl Index<ExprId> for Body {
type Output = Expr;
fn index(&self, expr: ExprId) -> &Expr {
&self.exprs[expr]
}
}
impl Index<PatId> for Body {
type Output = Pat;
fn index(&self, pat: PatId) -> &Pat {
&self.pats[pat]
}
}
2020-12-23 09:34:30 -06:00
impl Index<LabelId> for Body {
type Output = Label;
fn index(&self, label: LabelId) -> &Label {
&self.labels[label]
}
}
2023-02-18 14:32:55 -06:00
impl Index<BindingId> for Body {
type Output = Binding;
fn index(&self, b: BindingId) -> &Binding {
&self.bindings[b]
}
}
2021-03-15 07:38:50 -05:00
// FIXME: Change `node_` prefix to something more reasonable.
// Perhaps `expr_syntax` and `expr_id`?
2019-11-12 09:46:57 -06:00
impl BodySourceMap {
2020-03-06 07:44:44 -06:00
pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
self.expr_map_back.get(expr).cloned().ok_or(SyntheticSyntax)
2019-11-12 09:46:57 -06:00
}
2019-11-28 03:50:26 -06:00
pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
2022-03-12 06:35:31 -06:00
let src = node.map(AstPtr::new);
self.expr_map.get(&src).cloned()
2019-11-12 09:46:57 -06:00
}
2019-12-23 07:47:11 -06:00
pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
2022-03-12 06:35:31 -06:00
let src = node.map(AstPtr::new);
2019-12-23 07:47:11 -06:00
self.expansions.get(&src).cloned()
}
2020-03-06 07:44:44 -06:00
pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
self.pat_map_back.get(pat).cloned().ok_or(SyntheticSyntax)
2019-11-12 09:46:57 -06:00
}
2019-11-28 03:50:26 -06:00
pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
let src = node.map(|it| AstPtr::new(it).wrap_left());
self.pat_map.get(&src).cloned()
2019-11-12 09:46:57 -06:00
}
2020-07-10 07:08:35 -05:00
pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
let src = node.map(|it| AstPtr::new(it).wrap_right());
2020-07-10 07:08:35 -05:00
self.pat_map.get(&src).cloned()
}
2020-12-23 09:34:30 -06:00
pub fn label_syntax(&self, label: LabelId) -> LabelSource {
2024-01-19 07:15:00 -06:00
self.label_map_back[label]
2020-12-23 09:34:30 -06:00
}
pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
2022-03-12 06:35:31 -06:00
let src = node.map(AstPtr::new);
2020-12-23 09:34:30 -06:00
self.label_map.get(&src).cloned()
}
pub fn field_syntax(&self, expr: ExprId) -> FieldSource {
2024-01-19 07:15:00 -06:00
self.field_map_back[&expr]
2021-03-15 07:38:50 -05:00
}
pub fn pat_field_syntax(&self, pat: PatId) -> PatFieldSource {
2024-01-19 07:15:00 -06:00
self.pat_field_map_back[&pat]
2019-11-12 09:46:57 -06:00
}
pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroExpr>) -> Option<ExprId> {
let src = node.map(AstPtr::new).map(AstPtr::upcast::<ast::MacroExpr>).map(AstPtr::upcast);
self.expr_map.get(&src).copied()
}
2023-12-05 08:42:39 -06:00
pub fn implicit_format_args(
&self,
node: InFile<&ast::FormatArgsExpr>,
) -> Option<&[(syntax::TextRange, Name)]> {
let src = node.map(AstPtr::new).map(AstPtr::upcast::<ast::Expr>);
self.format_args_template_map.get(self.expr_map.get(&src)?).map(std::ops::Deref::deref)
}
/// Get a reference to the body source map's diagnostics.
pub fn diagnostics(&self) -> &[BodyDiagnostic] {
&self.diagnostics
}
2023-09-09 07:40:56 -05:00
fn shrink_to_fit(&mut self) {
let Self {
expr_map,
expr_map_back,
pat_map,
pat_map_back,
label_map,
label_map_back,
field_map_back,
pat_field_map_back,
expansions,
2023-12-05 08:42:39 -06:00
format_args_template_map,
2023-09-09 07:40:56 -05:00
diagnostics,
} = self;
2023-12-05 08:42:39 -06:00
format_args_template_map.shrink_to_fit();
2023-09-09 07:40:56 -05:00
expr_map.shrink_to_fit();
expr_map_back.shrink_to_fit();
pat_map.shrink_to_fit();
pat_map_back.shrink_to_fit();
label_map.shrink_to_fit();
label_map_back.shrink_to_fit();
field_map_back.shrink_to_fit();
pat_field_map_back.shrink_to_fit();
expansions.shrink_to_fit();
diagnostics.shrink_to_fit();
}
}