Skip to main content

boa_ast/statement/iteration/
while_loop.rs

1use crate::{
2    expression::Expression,
3    statement::Statement,
4    visitor::{VisitWith, Visitor, VisitorMut},
5};
6use boa_interner::{Interner, ToIndentedString, ToInternedString};
7use core::ops::ControlFlow;
8
9/// The `while` statement creates a loop that executes a specified statement as long as the
10/// test condition evaluates to `true`.
11///
12/// The condition is evaluated before executing the statement.
13///
14/// More information:
15///  - [ECMAScript reference][spec]
16///  - [MDN documentation][mdn]
17///
18/// [spec]: https://tc39.es/ecma262/#prod-grammar-notation-WhileStatement
19/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
22#[derive(Clone, Debug, PartialEq)]
23pub struct WhileLoop {
24    condition: Expression,
25    body: Box<Statement>,
26}
27
28impl WhileLoop {
29    /// Creates a `WhileLoop` AST node.
30    #[inline]
31    #[must_use]
32    pub fn new(condition: Expression, body: Statement) -> Self {
33        Self {
34            condition,
35            body: body.into(),
36        }
37    }
38
39    /// Gets the condition of the while loop.
40    #[inline]
41    #[must_use]
42    pub const fn condition(&self) -> &Expression {
43        &self.condition
44    }
45
46    /// Gets the body of the while loop.
47    #[inline]
48    #[must_use]
49    pub const fn body(&self) -> &Statement {
50        &self.body
51    }
52}
53
54impl ToIndentedString for WhileLoop {
55    fn to_indented_string(&self, interner: &Interner, indentation: usize) -> String {
56        format!(
57            "while ({}) {}",
58            self.condition().to_interned_string(interner),
59            self.body().to_indented_string(interner, indentation)
60        )
61    }
62}
63
64impl From<WhileLoop> for Statement {
65    #[inline]
66    fn from(while_loop: WhileLoop) -> Self {
67        Self::WhileLoop(while_loop)
68    }
69}
70
71impl VisitWith for WhileLoop {
72    fn visit_with<'a, V>(&'a self, visitor: &mut V) -> ControlFlow<V::BreakTy>
73    where
74        V: Visitor<'a>,
75    {
76        visitor.visit_expression(&self.condition)?;
77        visitor.visit_statement(&self.body)
78    }
79
80    fn visit_with_mut<'a, V>(&'a mut self, visitor: &mut V) -> ControlFlow<V::BreakTy>
81    where
82        V: VisitorMut<'a>,
83    {
84        visitor.visit_expression_mut(&mut self.condition)?;
85        visitor.visit_statement_mut(&mut self.body)
86    }
87}