use crate::{
exec::Executable,
gc::{Finalize, Trace},
syntax::ast::node::Node,
Context, JsResult, JsValue,
};
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 GetConstField {
obj: Box<Node>,
field: Box<str>,
}
impl GetConstField {
pub fn new<V, L>(value: V, label: L) -> Self
where
V: Into<Node>,
L: Into<Box<str>>,
{
Self {
obj: Box::new(value.into()),
field: label.into(),
}
}
pub fn obj(&self) -> &Node {
&self.obj
}
pub fn field(&self) -> &str {
&self.field
}
}
impl Executable for GetConstField {
fn run(&self, context: &mut Context) -> JsResult<JsValue> {
let mut obj = self.obj().run(context)?;
if !obj.is_object() {
obj = JsValue::Object(obj.to_object(context)?);
}
obj.get_field(self.field(), context)
}
}
impl fmt::Display for GetConstField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.obj(), self.field())
}
}
impl From<GetConstField> for Node {
fn from(get_const_field: GetConstField) -> Self {
Self::GetConstField(get_const_field)
}
}