use crate::expression::{Expression, PropertyKey};
use crate::function::Function;
use crate::identifier::Identifier;
use crate::statement::Statement;
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::struct_field_names)] pub struct Class {
id: Option<Identifier>,
super_class: Option<Box<Expression>>,
body: Vec<ClassMember>,
}
impl Class {
#[must_use]
pub fn new(
id: Option<Identifier>,
super_class: Option<Expression>,
body: Vec<ClassMember>,
) -> Self {
Self {
id,
super_class: super_class.map(Box::new),
body,
}
}
#[must_use]
pub fn id(&self) -> Option<&Identifier> {
self.id.as_ref()
}
#[must_use]
pub fn super_class(&self) -> Option<&Expression> {
self.super_class.as_deref()
}
#[must_use]
pub fn body(&self) -> &[ClassMember] {
&self.body
}
}
impl std::fmt::Display for Class {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("class")?;
if let Some(name) = &self.id {
write!(f, " {name}")?;
}
if let Some(super_expr) = &self.super_class {
write!(f, " extends {super_expr}")?;
}
f.write_str(" { ... }")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClassMember {
Method {
key: PropertyKey,
value: Function,
kind: MethodKind,
is_static: bool,
computed: bool,
},
Property {
key: PropertyKey,
value: Option<Expression>,
is_static: bool,
computed: bool,
},
StaticBlock {
body: Vec<Statement>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MethodKind {
Constructor,
Method,
Get,
Set,
}
impl std::fmt::Display for MethodKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Constructor => "constructor",
Self::Method => "method",
Self::Get => "get",
Self::Set => "set",
})
}
}