use super::{Node, StatementList};
use crate::{
environment::declarative_environment_record::DeclarativeEnvironmentRecord,
exec::Executable,
exec::InterpreterState,
gc::{Finalize, Trace},
BoaProfiler, Context, JsResult, JsValue,
};
use std::fmt;
#[cfg(feature = "deser")]
use serde::{Deserialize, Serialize};
#[cfg(test)]
mod tests;
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "deser", serde(transparent))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct Block {
#[cfg_attr(feature = "deser", serde(flatten))]
statements: StatementList,
}
impl Block {
pub(crate) fn items(&self) -> &[Node] {
self.statements.items()
}
pub(super) fn display(&self, f: &mut fmt::Formatter<'_>, indentation: usize) -> fmt::Result {
writeln!(f, "{{")?;
self.statements.display(f, indentation + 1)?;
write!(f, "{}}}", " ".repeat(indentation))
}
}
impl Executable for Block {
fn run(&self, context: &mut Context) -> JsResult<JsValue> {
let _timer = BoaProfiler::global().start_event("Block", "exec");
{
let env = context.get_current_environment();
context.push_environment(DeclarativeEnvironmentRecord::new(Some(env)));
}
let mut obj = JsValue::default();
for statement in self.items() {
obj = statement.run(context).map_err(|e| {
context.pop_environment();
e
})?;
match context.executor().get_current_state() {
InterpreterState::Return => {
break;
}
InterpreterState::Break(_label) => {
break;
}
InterpreterState::Continue(_label) => {
break;
}
InterpreterState::Executing => {
}
}
}
let _ = context.pop_environment();
Ok(obj)
}
}
impl<T> From<T> for Block
where
T: Into<StatementList>,
{
fn from(list: T) -> Self {
Self {
statements: list.into(),
}
}
}
impl fmt::Display for Block {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}
impl From<Block> for Node {
fn from(block: Block) -> Self {
Self::Block(block)
}
}