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 GetField {
obj: Box<Node>,
field: Box<Node>,
}
impl GetField {
pub fn obj(&self) -> &Node {
&self.obj
}
pub fn field(&self) -> &Node {
&self.field
}
pub fn new<V, F>(value: V, field: F) -> Self
where
V: Into<Node>,
F: Into<Node>,
{
Self {
obj: Box::new(value.into()),
field: Box::new(field.into()),
}
}
}
impl Executable for GetField {
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)?);
}
let field = self.field().run(context)?;
obj.get_field(field.to_property_key(context)?, context)
}
}
impl fmt::Display for GetField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}[{}]", self.obj(), self.field())
}
}
impl From<GetField> for Node {
fn from(get_field: GetField) -> Self {
Self::GetField(get_field)
}
}