use crate::syntax::ast::node::{join_nodes, FormalParameterList, Node, StatementList};
use boa_interner::{Interner, Sym, ToInternedString};
#[cfg(feature = "deser")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionDecl {
name: Sym,
parameters: FormalParameterList,
body: StatementList,
}
impl FunctionDecl {
pub(in crate::syntax) fn new<P, B>(name: Sym, parameters: P, body: B) -> Self
where
P: Into<FormalParameterList>,
B: Into<StatementList>,
{
Self {
name,
parameters: parameters.into(),
body: body.into(),
}
}
pub fn name(&self) -> Sym {
self.name
}
pub fn parameters(&self) -> &FormalParameterList {
&self.parameters
}
pub fn body(&self) -> &StatementList {
&self.body
}
pub(in crate::syntax::ast::node) fn to_indented_string(
&self,
interner: &Interner,
indentation: usize,
) -> String {
let mut buf = format!(
"function {}({}",
interner.resolve_expect(self.name),
join_nodes(interner, &self.parameters.parameters)
);
if self.body().items().is_empty() {
buf.push_str(") {}");
} else {
buf.push_str(&format!(
") {{\n{}{}}}",
self.body.to_indented_string(interner, indentation + 1),
" ".repeat(indentation)
));
}
buf
}
}
impl From<FunctionDecl> for Node {
fn from(decl: FunctionDecl) -> Self {
Self::FunctionDecl(decl)
}
}
impl ToInternedString for FunctionDecl {
fn to_interned_string(&self, interner: &Interner) -> String {
self.to_indented_string(interner, 0)
}
}