Skip to main content

t_ree/
expression.rs

1use crate::declaration::Parameter;
2use crate::operator::{ArithmeticOperator, BinaryOperator, UnaryOperator};
3use crate::types::Type;
4
5/// Source location in the input.
6#[derive(Copy, Clone, Debug, Default)]
7pub struct Span {
8    /// Line number (1-based, 0 = unknown).
9    pub line: u32,
10    /// Column number (1-based, 0 = unknown).
11    pub column: u32,
12}
13
14impl std::fmt::Display for Span {
15    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        write!(formatter, "{}:{}", self.line, self.column)
17    }
18}
19
20/// Variable binding mode.
21#[derive(Copy, Clone, Debug, PartialEq, Eq)]
22pub enum Binding {
23    /// Immutable value (moved or copied).
24    Value,
25    /// Immutable reference.
26    Reference,
27    /// Mutable variable reference.
28    Variable,
29}
30
31/// Literal values.
32#[derive(Clone, Debug, PartialEq)]
33pub enum Literal {
34    /// Boolean literal.
35    Bool(bool),
36    /// Integer literal.
37    Integer(u128),
38    /// Floating-point literal.
39    Float(f64),
40    /// Byte string literal.
41    String(Vec<u8>),
42    /// Null pointer literal.
43    Null,
44}
45
46/// A typed expression node.
47#[derive(Clone, Debug)]
48pub struct Expression {
49    /// The expression variant.
50    pub kind: ExpressionKind,
51    /// The resolved type of this expression (`None` until resolution).
52    pub resolved_type: Option<Type>,
53    /// Source location.
54    pub span: Span,
55}
56
57impl Expression {
58    /// Creates a new expression with the given kind and type.
59    pub fn new(kind: ExpressionKind, resolved_type: Option<Type>) -> Self {
60        Self {
61            kind,
62            resolved_type,
63            span: Span::default(),
64        }
65    }
66
67    /// Creates a new expression with the given kind, type, and source location.
68    pub fn with_span(kind: ExpressionKind, resolved_type: Option<Type>, span: Span) -> Self {
69        Self {
70            kind,
71            resolved_type,
72            span,
73        }
74    }
75}
76
77/// A sequence of statements with an optional trailing expression.
78#[derive(Clone, Debug)]
79pub struct Block {
80    /// Statements in the block.
81    pub statements: Vec<Statement>,
82    /// Optional result expression.
83    pub result: Option<Box<Expression>>,
84}
85
86impl Block {
87    /// Creates an empty block with no statements or result.
88    pub fn empty() -> Self {
89        Self {
90            statements: Vec::new(),
91            result: None,
92        }
93    }
94
95    /// Creates a block containing only a result expression.
96    pub fn expression(expression: Expression) -> Self {
97        Self {
98            statements: Vec::new(),
99            result: Some(Box::new(expression)),
100        }
101    }
102}
103
104/// A single arm in a match expression.
105#[derive(Clone, Debug)]
106pub struct MatchArm {
107    /// The pattern to match against.
108    pub pattern: MatchPattern,
109    /// The body to execute if the pattern matches.
110    pub body: Block,
111}
112
113/// Pattern for match arms.
114#[derive(Clone, Debug)]
115pub enum MatchPattern {
116    /// Match a specific integer value.
117    Integer(u128),
118    /// Bind the matched value to a variable.
119    Variable(String),
120    /// Match anything (wildcard `_`).
121    Wildcard,
122    /// Match an enum variant by type name, binding the inner value.
123    Variant(String, String),
124}
125
126/// Statement nodes within a block.
127#[derive(Clone, Debug)]
128pub enum Statement {
129    /// Expression evaluated for side effects.
130    Expression(Expression),
131    /// Local variable declaration.
132    Let {
133        /// Variable name.
134        name: String,
135        /// Binding mode.
136        binding: Binding,
137        /// Optional explicit type annotation.
138        declared_type: Option<Type>,
139        /// Initializer expression.
140        value: Expression,
141    },
142    /// Assignment to a place expression.
143    Assign(Expression, Expression),
144    /// Return from the current function.
145    Return(Option<Expression>),
146    /// Label definition (jump target with parameters).
147    Label {
148        /// Label name.
149        name: String,
150        /// Label parameters.
151        parameters: Vec<Parameter>,
152        /// Initial arguments passed when entering the label.
153        initial_arguments: Vec<Expression>,
154    },
155    /// Jump to a label with arguments.
156    Jump {
157        /// Target label name.
158        label: String,
159        /// Arguments passed to the label.
160        arguments: Vec<Expression>,
161    },
162    /// Simultaneous multi-replacement with optional old-value capture.
163    MultiReplace {
164        /// Optional new bindings for old values.
165        bindings: Vec<Option<(String, Binding)>>,
166        /// Place expressions to assign to.
167        targets: Vec<Expression>,
168        /// New values (evaluated before any assignment).
169        values: Vec<Expression>,
170    },
171    /// Deferred statement, executed at the end of the enclosing block (LIFO).
172    Defer(Box<Self>),
173}
174
175/// Expression variants.
176#[derive(Clone, Debug)]
177pub enum ExpressionKind {
178    /// Literal value.
179    Literal(Literal),
180    /// Variable reference.
181    Variable(String),
182
183    /// Binary operation (e.g. `a + b`).
184    BinaryOperation(BinaryOperator, Box<Expression>, Box<Expression>),
185    /// Unary operation (e.g. `-x`).
186    UnaryOperation(UnaryOperator, Box<Expression>),
187
188    /// Function call with arguments.
189    Call(Box<Expression>, Vec<Expression>),
190    /// Field access (e.g. `x.field`).
191    Field(Box<Expression>, String),
192    /// Index access (e.g. `a[i]`).
193    Index(Box<Expression>, Box<Expression>),
194
195    /// Pointer dereference.
196    Dereference(Box<Expression>),
197
198    /// Newtype conversion (`Type: value`, `value.Type`). Safe, type-checked.
199    Convert(Box<Expression>, Type),
200    /// Unsafe pointer transmute (`value as Type`). Pointer ↔ integer/pointer only.
201    Transmute(Box<Expression>, Type),
202    /// Size of a type.
203    SizeOf(Type),
204
205    /// Newtype construction with named fields (e.g. `point: (x: 1.0, y: 2.0)`).
206    TypeConstruction(String, Vec<(String, Expression)>),
207    /// Array literal.
208    ArrayLiteral(Vec<Expression>),
209    /// Tuple literal.
210    TupleLiteral(Vec<Expression>),
211
212    /// Block expression.
213    Block(Block),
214    /// Conditional expression.
215    If {
216        /// Condition.
217        condition: Box<Expression>,
218        /// Then branch.
219        then_branch: Block,
220        /// Optional else branch.
221        else_branch: Option<Block>,
222    },
223    /// Match expression.
224    Match {
225        /// Value being matched.
226        value: Box<Expression>,
227        /// Match arms.
228        arms: Vec<MatchArm>,
229    },
230
231    /// Replace: assigns new value, returns old value (like `std::mem::replace`).
232    Replace(Box<Expression>, Box<Expression>),
233    /// Compound assignment (`+=`, `-=`, `*=`, `/=`).
234    OpAssign(ArithmeticOperator, Box<Expression>, Box<Expression>),
235
236    /// Slice operation: converts array to slice.
237    /// Full slice (no bounds) or sub-slice (start, end).
238    Slice(
239        Box<Expression>,
240        Option<Box<Expression>>,
241        Option<Box<Expression>>,
242    ),
243
244    /// Debug print (temporary intrinsic).
245    Print(Vec<Expression>),
246}