Skip to main content

wright/ast/
stmt.rs

1//! AST models for statements and blocks.
2
3use super::{
4    AstNode,
5    expr::{BinaryOperation, Binding, Expr},
6    ty::Type,
7};
8use crate::source_tracking::fragment::Fragment;
9
10/// A block of statements, optionally ending in a tail expression that gives the block its value.
11///
12/// i.e. `{ let x = 1; x + 1 }`
13#[derive(Debug, Clone, PartialEq)]
14pub struct Block {
15    /// The source of the whole block, including the braces.
16    pub matching_source: Fragment,
17
18    /// The statements in the block, in order.
19    pub stmts: Vec<Stmt>,
20
21    /// The final expression of the block (without a trailing semicolon), which is the value of the block.
22    pub tail: Option<Box<Expr>>,
23}
24
25impl AstNode for Block {
26    fn matching_source(&self) -> &Fragment {
27        &self.matching_source
28    }
29}
30
31/// A statement inside a [Block].
32#[derive(Debug, Clone, PartialEq)]
33pub struct Stmt {
34    /// The source of the statement, including any trailing semicolon.
35    pub matching_source: Fragment,
36
37    /// What kind of statement this is.
38    pub kind: StmtKind,
39}
40
41impl AstNode for Stmt {
42    fn matching_source(&self) -> &Fragment {
43        &self.matching_source
44    }
45}
46
47/// The different kinds of [Stmt]s.
48#[derive(Debug, Clone, PartialEq)]
49pub enum StmtKind {
50    /// A `let` or `var` variable declaration.
51    Let(LetStmt),
52    /// An assignment, such as `x = 1` or `x += 1`.
53    Assign(AssignStmt),
54    /// An expression evaluated for its side effects, such as `f();` or `if c { ... }`.
55    Expr(Expr),
56    /// A `return` statement, with an optional value.
57    Return(Option<Expr>),
58    /// A `break` statement.
59    Break,
60    /// A `continue` statement.
61    Continue,
62}
63
64/// A `let` (immutable) or `var` (mutable) variable declaration.
65///
66/// i.e. `let x: u8 = 1;`
67#[derive(Debug, Clone, PartialEq)]
68pub struct LetStmt {
69    /// Was this declared with `var` (mutable) rather than `let` (immutable)?
70    pub mutable: bool,
71
72    /// The name being bound.
73    pub binding: Binding,
74
75    /// The declared type, if any.
76    pub ty: Option<Type>,
77
78    /// The initial value, if any.
79    pub value: Option<Expr>,
80}
81
82/// An assignment, such as `x = 1` or `x += 1`.
83#[derive(Debug, Clone, PartialEq)]
84pub struct AssignStmt {
85    /// The place being assigned to.
86    pub target: Expr,
87
88    /// For compound assignments (such as `+=`), the operation applied. [None] for plain `=` assignments.
89    pub op: Option<BinaryOperation>,
90
91    /// The source of the assignment operator.
92    pub op_source: Fragment,
93
94    /// The value being assigned.
95    pub value: Expr,
96}