Skip to main content

boa_ast/expression/
new.rs

1use crate::expression::Call;
2use crate::visitor::{VisitWith, Visitor, VisitorMut};
3use crate::{Span, Spanned};
4use boa_interner::{Interner, ToInternedString};
5use core::ops::ControlFlow;
6
7use super::Expression;
8
9/// The `new` operator lets developers create an instance of a user-defined object type or of
10/// one of the built-in object types that has a constructor function.
11///
12/// The new keyword does the following things:
13///  - Creates a blank, plain JavaScript object;
14///  - Links (sets the constructor of) this object to another object;
15///  - Passes the newly created object from Step 1 as the this context;
16///  - Returns this if the function doesn't return its own object.
17///
18/// More information:
19///  - [ECMAScript reference][spec]
20///  - [MDN documentation][mdn]
21///
22/// [spec]: https://tc39.es/ecma262/#prod-NewExpression
23/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
26#[derive(Clone, Debug, PartialEq)]
27pub struct New {
28    call: Call,
29}
30
31impl New {
32    /// Gets the constructor of the new expression.
33    #[inline]
34    #[must_use]
35    pub const fn constructor(&self) -> &Expression {
36        self.call.function()
37    }
38
39    /// Retrieves the arguments passed to the constructor.
40    #[inline]
41    #[must_use]
42    pub const fn arguments(&self) -> &[Expression] {
43        self.call.args()
44    }
45
46    /// Returns the inner call expression.
47    #[must_use]
48    pub const fn call(&self) -> &Call {
49        &self.call
50    }
51}
52
53impl From<Call> for New {
54    #[inline]
55    fn from(call: Call) -> Self {
56        Self { call }
57    }
58}
59
60impl Spanned for New {
61    #[inline]
62    fn span(&self) -> Span {
63        self.call.span()
64    }
65}
66
67impl ToInternedString for New {
68    #[inline]
69    fn to_interned_string(&self, interner: &Interner) -> String {
70        format!("new {}", self.call.to_interned_string(interner))
71    }
72}
73
74impl From<New> for Expression {
75    #[inline]
76    fn from(new: New) -> Self {
77        Self::New(new)
78    }
79}
80
81impl VisitWith for New {
82    fn visit_with<'a, V>(&'a self, visitor: &mut V) -> ControlFlow<V::BreakTy>
83    where
84        V: Visitor<'a>,
85    {
86        visitor.visit_call(&self.call)
87    }
88
89    fn visit_with_mut<'a, V>(&'a mut self, visitor: &mut V) -> ControlFlow<V::BreakTy>
90    where
91        V: VisitorMut<'a>,
92    {
93        visitor.visit_call_mut(&mut self.call)
94    }
95}