boa/syntax/ast/node/operator/assign/
mod.rs1use crate::{
2 environment::lexical_environment::VariableScope,
3 exec::Executable,
4 gc::{Finalize, Trace},
5 syntax::ast::node::Node,
6 BoaProfiler, Context, JsResult, JsValue,
7};
8use std::fmt;
9
10#[cfg(feature = "deser")]
11use serde::{Deserialize, Serialize};
12
13#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
25#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
26pub struct Assign {
27 lhs: Box<Node>,
28 rhs: Box<Node>,
29}
30
31impl Assign {
32 pub(in crate::syntax) fn new<L, R>(lhs: L, rhs: R) -> Self
34 where
35 L: Into<Node>,
36 R: Into<Node>,
37 {
38 Self {
39 lhs: Box::new(lhs.into()),
40 rhs: Box::new(rhs.into()),
41 }
42 }
43
44 pub fn lhs(&self) -> &Node {
46 &self.lhs
47 }
48
49 pub fn rhs(&self) -> &Node {
51 &self.rhs
52 }
53}
54
55impl Executable for Assign {
56 fn run(&self, context: &mut Context) -> JsResult<JsValue> {
57 let _timer = BoaProfiler::global().start_event("Assign", "exec");
58 let val = self.rhs().run(context)?;
59 match self.lhs() {
60 Node::Identifier(ref name) => {
61 if context.has_binding(name.as_ref())? {
62 context.set_mutable_binding(name.as_ref(), val.clone(), context.strict())?;
64 } else {
65 context.create_mutable_binding(name.as_ref(), true, VariableScope::Function)?;
66 context.initialize_binding(name.as_ref(), val.clone())?;
67 }
68 }
69 Node::GetConstField(ref get_const_field) => {
70 let val_obj = get_const_field.obj().run(context)?;
71 val_obj.set_field(get_const_field.field(), val.clone(), false, context)?;
72 }
73 Node::GetField(ref get_field) => {
74 let object = get_field.obj().run(context)?;
75 let field = get_field.field().run(context)?;
76 let key = field.to_property_key(context)?;
77 object.set_field(key, val.clone(), false, context)?;
78 }
79 _ => (),
80 }
81 Ok(val)
82 }
83}
84
85impl fmt::Display for Assign {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 write!(f, "{} = {}", self.lhs, self.rhs)
88 }
89}
90
91impl From<Assign> for Node {
92 fn from(op: Assign) -> Self {
93 Self::Assign(op)
94 }
95}