wright/ast/expr.rs
1//! AST models for expressions in wright source code.
2
3use super::{AstNode, identifier::Identifier, literal::Literal, path::Path, stmt::Block, ty::Type};
4use crate::source_tracking::fragment::Fragment;
5
6/// An expression in wright source code.
7#[derive(Debug, Clone, PartialEq)]
8pub struct Expr {
9 /// The source code of the whole expression.
10 pub matching_source: Fragment,
11
12 /// What kind of expression this is.
13 pub kind: ExprKind,
14}
15
16impl Expr {
17 /// Is this an [ExprKind::Error]?
18 pub fn is_error(&self) -> bool {
19 matches!(self.kind, ExprKind::Error)
20 }
21
22 /// Is this a "block-like" expression -- one that ends with a block (`{ ... }`) and so does not need a
23 /// semicolon after it when used as a statement?
24 pub fn is_block_like(&self) -> bool {
25 matches!(
26 self.kind,
27 ExprKind::Block(_)
28 | ExprKind::If(_)
29 | ExprKind::While(_)
30 | ExprKind::Loop(_)
31 | ExprKind::For(_)
32 )
33 }
34
35 /// Is this a "place" expression -- one that refers to a location in memory that can be assigned to?
36 /// These are paths, field accesses, index expressions, dereferences, and parenthesized place expressions.
37 pub fn is_place(&self) -> bool {
38 match &self.kind {
39 ExprKind::Path(_) | ExprKind::Field(_) | ExprKind::Index(_) => true,
40 ExprKind::Unary(unary) => unary.op == UnaryOperation::Dereference,
41 ExprKind::Paren(inner) => inner.is_place(),
42 // Don't report errors on top of errors.
43 ExprKind::Error => true,
44 _ => false,
45 }
46 }
47}
48
49impl AstNode for Expr {
50 fn matching_source(&self) -> &Fragment {
51 &self.matching_source
52 }
53}
54
55/// The different kinds of [Expr]s.
56#[derive(Debug, Clone, PartialEq)]
57pub enum ExprKind {
58 /// A literal value, such as `1`, `"hi"`, or `true`.
59 Literal(Literal),
60 /// A path to a variable or item, such as `x` or `std::io::println`.
61 Path(Path),
62 /// A record literal, such as `Point { x: 1, y: 2 }`.
63 Record(RecordLiteral),
64 /// An array literal, such as `[1, 2, 3]` or `[0; 16]`.
65 Array(ArrayLiteral),
66 /// A parenthesized expression, such as `(a + b)`.
67 Paren(Box<Expr>),
68 /// A block expression, such as `{ let x = 1; x + 1 }`.
69 Block(Block),
70 /// An `if` expression, possibly with `else` branches.
71 If(IfExpr),
72 /// A `while` loop.
73 While(WhileExpr),
74 /// An infinite `loop`.
75 Loop(LoopExpr),
76 /// A `for` loop.
77 For(ForExpr),
78 /// A function call, such as `f(1, 2)`.
79 Call(CallExpr),
80 /// An index expression, such as `a[i]`.
81 Index(IndexExpr),
82 /// A field access, such as `point.x`.
83 Field(FieldExpr),
84 /// A unary operation, such as `-x` or `!done`.
85 Unary(UnaryExpr),
86 /// A binary operation, such as `a + b` or `x && y`.
87 Binary(BinaryExpr),
88 /// A type cast, such as `x as u64`.
89 Cast(CastExpr),
90 /// A range, such as `0..10` or `1..=100`.
91 Range(RangeExpr),
92 /// An expression that could not be parsed. The parser will have emitted an error for it.
93 Error,
94}
95
96/// A record literal, such as `Point { x: 1, y: 2 }`.
97#[derive(Debug, Clone, PartialEq)]
98pub struct RecordLiteral {
99 /// The name of the record type being constructed.
100 pub name: Path,
101
102 /// The field initializers, in source order.
103 pub fields: Vec<FieldInit>,
104}
105
106/// A field initializer in a [RecordLiteral], such as the `x: 1` in `Point { x: 1 }`.
107#[derive(Debug, Clone, PartialEq)]
108pub struct FieldInit {
109 /// The source of this field initializer.
110 pub matching_source: Fragment,
111
112 /// The name of the field.
113 pub name: Identifier,
114
115 /// The value of the field. For shorthand initializers (`Point { x }`) this is a path expression referring to the
116 /// variable with the same name as the field.
117 pub value: Expr,
118
119 /// Was this written using the shorthand `Point { x }` syntax?
120 pub shorthand: bool,
121}
122
123impl AstNode for FieldInit {
124 fn matching_source(&self) -> &Fragment {
125 &self.matching_source
126 }
127}
128
129/// An array literal.
130#[derive(Debug, Clone, PartialEq)]
131pub enum ArrayLiteral {
132 /// A list of elements, such as `[1, 2, 3]`.
133 List(Vec<Expr>),
134
135 /// A value repeated some number of times, such as `[0; 16]`.
136 Repeat {
137 /// The value to repeat.
138 value: Box<Expr>,
139 /// The number of times to repeat it.
140 count: Box<Expr>,
141 },
142}
143
144/// An `if` expression.
145#[derive(Debug, Clone, PartialEq)]
146pub struct IfExpr {
147 /// The condition being tested.
148 pub condition: Box<Expr>,
149
150 /// The block run when the condition is true.
151 pub then_block: Block,
152
153 /// The `else` branch, if there is one. This is always an [ExprKind::If] (for `else if`), an [ExprKind::Block],
154 /// or an [ExprKind::Error].
155 pub else_branch: Option<Box<Expr>>,
156}
157
158/// A `while` loop.
159#[derive(Debug, Clone, PartialEq)]
160pub struct WhileExpr {
161 /// The condition checked before every iteration.
162 pub condition: Box<Expr>,
163
164 /// The body of the loop.
165 pub body: Block,
166}
167
168/// An infinite `loop`.
169#[derive(Debug, Clone, PartialEq)]
170pub struct LoopExpr {
171 /// The body of the loop.
172 pub body: Block,
173}
174
175/// A `for` loop, such as `for i in 0..10 { ... }`.
176#[derive(Debug, Clone, PartialEq)]
177pub struct ForExpr {
178 /// The binding each element is assigned to.
179 pub binding: Binding,
180
181 /// The expression being iterated over.
182 pub iterable: Box<Expr>,
183
184 /// The body of the loop.
185 pub body: Block,
186}
187
188/// A name being bound in a `let`/`var` statement or `for` loop.
189#[derive(Debug, Clone, PartialEq)]
190pub enum Binding {
191 /// A named binding, such as `x`.
192 Named(Identifier),
193
194 /// A wildcard (`_`) that discards the value.
195 Wildcard(Fragment),
196}
197
198impl AstNode for Binding {
199 fn matching_source(&self) -> &Fragment {
200 match self {
201 Binding::Named(identifier) => &identifier.fragment,
202 Binding::Wildcard(fragment) => fragment,
203 }
204 }
205}
206
207/// A function call, such as `f(1, 2)`.
208#[derive(Debug, Clone, PartialEq)]
209pub struct CallExpr {
210 /// The function being called.
211 pub callee: Box<Expr>,
212
213 /// The arguments, in order.
214 pub args: Vec<Expr>,
215}
216
217/// An index expression, such as `a[i]`.
218#[derive(Debug, Clone, PartialEq)]
219pub struct IndexExpr {
220 /// The expression being indexed.
221 pub base: Box<Expr>,
222
223 /// The index.
224 pub index: Box<Expr>,
225}
226
227/// A field access, such as `point.x`.
228#[derive(Debug, Clone, PartialEq)]
229pub struct FieldExpr {
230 /// The expression whose field is being accessed.
231 pub base: Box<Expr>,
232
233 /// The name of the field.
234 pub field: Identifier,
235}
236
237/// A unary operation, such as `-x`.
238#[derive(Debug, Clone, PartialEq)]
239pub struct UnaryExpr {
240 /// The operation being applied.
241 pub op: UnaryOperation,
242
243 /// The source of the operator token.
244 pub op_source: Fragment,
245
246 /// The operand.
247 pub operand: Box<Expr>,
248}
249
250/// The different unary operations.
251#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
252pub enum UnaryOperation {
253 /// `@x` -- take a reference to `x`.
254 Reference,
255 /// `*x` -- dereference `x`.
256 Dereference,
257 /// `-x` -- arithmetic negation.
258 Negate,
259 /// `!x` -- boolean not.
260 BooleanNot,
261 /// `~x` -- bitwise not.
262 BitwiseNot,
263}
264
265impl UnaryOperation {
266 /// Get the symbol used for this operation in source code.
267 pub const fn symbol(self) -> &'static str {
268 match self {
269 UnaryOperation::Reference => "@",
270 UnaryOperation::Dereference => "*",
271 UnaryOperation::Negate => "-",
272 UnaryOperation::BooleanNot => "!",
273 UnaryOperation::BitwiseNot => "~",
274 }
275 }
276}
277
278/// A binary operation, such as `a + b`.
279#[derive(Debug, Clone, PartialEq)]
280pub struct BinaryExpr {
281 /// The operation being applied.
282 pub op: BinaryOperation,
283
284 /// The source of the operator token.
285 pub op_source: Fragment,
286
287 /// The left hand side.
288 pub lhs: Box<Expr>,
289
290 /// The right hand side.
291 pub rhs: Box<Expr>,
292}
293
294/// The different binary operations.
295#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
296#[allow(missing_docs)]
297pub enum BinaryOperation {
298 Multiply,
299 Divide,
300 Remainder,
301 Add,
302 Subtract,
303 ShiftLeft,
304 ShiftRight,
305 BitwiseAnd,
306 BitwiseXor,
307 BitwiseOr,
308 Equal,
309 NotEqual,
310 Less,
311 LessOrEqual,
312 Greater,
313 GreaterOrEqual,
314 BooleanAnd,
315 BooleanOr,
316}
317
318impl BinaryOperation {
319 /// Get the symbol used for this operation in source code.
320 pub const fn symbol(self) -> &'static str {
321 use BinaryOperation::*;
322
323 match self {
324 Multiply => "*",
325 Divide => "/",
326 Remainder => "%",
327 Add => "+",
328 Subtract => "-",
329 ShiftLeft => "<<",
330 ShiftRight => ">>",
331 BitwiseAnd => "&",
332 BitwiseXor => "^",
333 BitwiseOr => "|",
334 Equal => "==",
335 NotEqual => "!=",
336 Less => "<",
337 LessOrEqual => "<=",
338 Greater => ">",
339 GreaterOrEqual => ">=",
340 BooleanAnd => "&&",
341 BooleanOr => "||",
342 }
343 }
344
345 /// Is this a comparison operation (`==`, `!=`, `<`, `<=`, `>`, `>=`)?
346 pub const fn is_comparison(self) -> bool {
347 use BinaryOperation::*;
348
349 matches!(self, Equal | NotEqual | Less | LessOrEqual | Greater | GreaterOrEqual)
350 }
351}
352
353/// A type cast, such as `x as u64`.
354#[derive(Debug, Clone, PartialEq)]
355pub struct CastExpr {
356 /// The expression being cast.
357 pub expr: Box<Expr>,
358
359 /// The type it's being cast to.
360 pub ty: Type,
361}
362
363/// A range, such as `0..10` or `1..=100`.
364#[derive(Debug, Clone, PartialEq)]
365pub struct RangeExpr {
366 /// The start of the range.
367 pub start: Box<Expr>,
368
369 /// The end of the range.
370 pub end: Box<Expr>,
371
372 /// Does the range include its end (`..=`)?
373 pub inclusive: bool,
374}