use crate::{
builtins::function::FunctionFlags,
environment::lexical_environment::VariableScope,
exec::Executable,
gc::{Finalize, Trace},
syntax::ast::node::{join_nodes, FormalParameter, Node, StatementList},
BoaProfiler, Context, Result, Value,
};
use std::fmt;
#[cfg(feature = "deser")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct FunctionDecl {
name: Box<str>,
parameters: Box<[FormalParameter]>,
body: StatementList,
}
impl FunctionDecl {
pub(in crate::syntax) fn new<N, P, B>(name: N, parameters: P, body: B) -> Self
where
N: Into<Box<str>>,
P: Into<Box<[FormalParameter]>>,
B: Into<StatementList>,
{
Self {
name: name.into(),
parameters: parameters.into(),
body: body.into(),
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn parameters(&self) -> &[FormalParameter] {
&self.parameters
}
pub fn body(&self) -> &[Node] {
self.body.items()
}
pub(in crate::syntax::ast::node) fn display(
&self,
f: &mut fmt::Formatter<'_>,
indentation: usize,
) -> fmt::Result {
write!(f, "function {}(", self.name)?;
join_nodes(f, &self.parameters)?;
f.write_str(") {{")?;
self.body.display(f, indentation + 1)?;
writeln!(f, "}}")
}
}
impl Executable for FunctionDecl {
fn run(&self, context: &mut Context) -> Result<Value> {
let _timer = BoaProfiler::global().start_event("FunctionDecl", "exec");
let val = context.create_function(
self.parameters().to_vec(),
self.body().to_vec(),
FunctionFlags::CALLABLE | FunctionFlags::CONSTRUCTABLE,
)?;
val.set_field("name", self.name(), context)?;
let environment = &mut context.realm_mut().environment;
if environment.has_binding(self.name()) {
environment
.set_mutable_binding(self.name(), val, true)
.map_err(|e| e.to_error(context))?;
} else {
environment
.create_mutable_binding(self.name().to_owned(), false, VariableScope::Function)
.map_err(|e| e.to_error(context))?;
context
.realm_mut()
.environment
.initialize_binding(self.name(), val)
.map_err(|e| e.to_error(context))?;
}
Ok(Value::undefined())
}
}
impl From<FunctionDecl> for Node {
fn from(decl: FunctionDecl) -> Self {
Self::FunctionDecl(decl)
}
}
impl fmt::Display for FunctionDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}