boa/syntax/ast/node/operator/assign/
mod.rs

1use 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/// An assignment operator assigns a value to its left operand based on the value of its right
14/// operand.
15///
16/// Assignment operator (`=`), assigns the value of its right operand to its left operand.
17///
18/// More information:
19///  - [ECMAScript reference][spec]
20///  - [MDN documentation][mdn]
21///
22/// [spec]: https://tc39.es/ecma262/#prod-AssignmentExpression
23/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators
24#[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    /// Creates an `Assign` AST node.
33    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    /// Gets the left hand side of the assignment operation.
45    pub fn lhs(&self) -> &Node {
46        &self.lhs
47    }
48
49    /// Gets the right hand side of the assignment operation.
50    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                    // Binding already exists
63                    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}