boa/syntax/ast/node/throw/
mod.rs

1use crate::{
2    exec::Executable,
3    gc::{Finalize, Trace},
4    syntax::ast::node::Node,
5    Context, JsResult, JsValue,
6};
7use std::fmt;
8
9#[cfg(feature = "deser")]
10use serde::{Deserialize, Serialize};
11
12#[cfg(test)]
13mod tests;
14
15/// The `throw` statement throws a user-defined exception.
16///
17/// Syntax: `throw expression;`
18///
19/// Execution of the current function will stop (the statements after throw won't be executed),
20/// and control will be passed to the first catch block in the call stack. If no catch block
21/// exists among caller functions, the program will terminate.
22///
23/// More information:
24///  - [ECMAScript reference][spec]
25///  - [MDN documentation][mdn]
26///
27/// [spec]: https://tc39.es/ecma262/#prod-ThrowStatement
28/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
29#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
30#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
31pub struct Throw {
32    expr: Box<Node>,
33}
34
35impl Throw {
36    pub fn expr(&self) -> &Node {
37        &self.expr
38    }
39
40    /// Creates a `Throw` AST node.
41    pub fn new<V>(val: V) -> Self
42    where
43        V: Into<Node>,
44    {
45        Self {
46            expr: Box::new(val.into()),
47        }
48    }
49}
50
51impl Executable for Throw {
52    #[inline]
53    fn run(&self, context: &mut Context) -> JsResult<JsValue> {
54        Err(self.expr().run(context)?)
55    }
56}
57
58impl fmt::Display for Throw {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        write!(f, "throw {}", self.expr)
61    }
62}
63
64impl From<Throw> for Node {
65    fn from(trw: Throw) -> Node {
66        Self::Throw(trw)
67    }
68}