quantalang 1.0.0

The QuantaLang compiler — an effects-oriented systems language with multi-backend codegen (C, HLSL, GLSL, SPIR-V, LLVM IR, WebAssembly, x86-64, ARM64)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// ===============================================================================
// QUANTALANG AST - EXPRESSIONS
// ===============================================================================
// Copyright (c) 2022-2026 Zain Dana Harper. MIT License.
// ===============================================================================

//! Expression AST nodes.
//!
//! Expressions are the core of QuantaLang - everything that produces a value.

use super::{
    AssignOp, Attribute, BinOp, Block, Ident, Mutability, NodeId, Path, Pattern, Type, UnaryOp,
};
use crate::lexer::Span;

/// An expression node.
#[derive(Debug, Clone, PartialEq)]
pub struct Expr {
    /// The kind of expression.
    pub kind: ExprKind,
    /// The span of this expression.
    pub span: Span,
    /// Node ID for this expression.
    pub id: NodeId,
    /// Attributes on this expression.
    pub attrs: Vec<Attribute>,
}

impl Expr {
    /// Create a new expression.
    pub fn new(kind: ExprKind, span: Span) -> Self {
        Self {
            kind,
            span,
            id: NodeId::DUMMY,
            attrs: Vec::new(),
        }
    }

    /// Create with attributes.
    pub fn with_attrs(kind: ExprKind, span: Span, attrs: Vec<Attribute>) -> Self {
        Self {
            kind,
            span,
            id: NodeId::DUMMY,
            attrs,
        }
    }

    /// Check if this expression is a place expression (can be assigned to).
    pub fn is_place(&self) -> bool {
        matches!(
            self.kind,
            ExprKind::Ident(_)
                | ExprKind::Field { .. }
                | ExprKind::TupleField { .. }
                | ExprKind::Index { .. }
                | ExprKind::Deref(_)
                | ExprKind::Path(_)
        )
    }

    /// Check if this expression requires a semicolon when used as a statement.
    pub fn requires_semi(&self) -> bool {
        !matches!(
            self.kind,
            ExprKind::If { .. }
                | ExprKind::Match { .. }
                | ExprKind::Loop { .. }
                | ExprKind::While { .. }
                | ExprKind::For { .. }
                | ExprKind::Block(_)
                | ExprKind::Unsafe(_)
                | ExprKind::Async { .. }
                | ExprKind::Handle { .. }
        )
    }
}

/// The kind of expression.
#[derive(Debug, Clone, PartialEq)]
pub enum ExprKind {
    // =========================================================================
    // LITERALS
    // =========================================================================
    /// A literal value.
    Literal(Literal),

    // =========================================================================
    // IDENTIFIERS AND PATHS
    // =========================================================================
    /// An identifier: `x`, `foo`
    Ident(Ident),

    /// A path: `std::io::Read`
    Path(Path),

    // =========================================================================
    // COMPOUND EXPRESSIONS
    // =========================================================================
    /// An array literal: `[1, 2, 3]`
    Array(Vec<Expr>),

    /// An array with repeated element: `[0; 10]`
    ArrayRepeat {
        element: Box<Expr>,
        count: Box<Expr>,
    },

    /// A tuple: `(a, b, c)`
    Tuple(Vec<Expr>),

    /// A struct literal: `Point { x: 1, y: 2 }`
    Struct {
        path: Path,
        fields: Vec<FieldExpr>,
        rest: Option<Box<Expr>>,
    },

    // =========================================================================
    // OPERATORS
    // =========================================================================
    /// A unary operation: `-x`, `!b`, `*ptr`
    Unary { op: UnaryOp, expr: Box<Expr> },

    /// A binary operation: `a + b`, `x && y`
    Binary {
        op: BinOp,
        left: Box<Expr>,
        right: Box<Expr>,
    },

    /// An assignment: `x = 1`, `x += 1`
    Assign {
        op: AssignOp,
        target: Box<Expr>,
        value: Box<Expr>,
    },

    // =========================================================================
    // ACCESS
    // =========================================================================
    /// Field access: `point.x`
    Field { expr: Box<Expr>, field: Ident },

    /// Tuple field access: `tuple.0`
    TupleField {
        expr: Box<Expr>,
        index: u32,
        span: Span,
    },

    /// Index access: `array[0]`
    Index { expr: Box<Expr>, index: Box<Expr> },

    /// Dereference: `*ptr`
    Deref(Box<Expr>),

    /// Reference: `&x`, `&mut x`
    Ref {
        mutability: Mutability,
        expr: Box<Expr>,
    },

    // =========================================================================
    // CALLS
    // =========================================================================
    /// Function call: `foo(1, 2)`
    Call { func: Box<Expr>, args: Vec<Expr> },

    /// Method call: `x.foo(1, 2)`
    MethodCall {
        receiver: Box<Expr>,
        method: Ident,
        generics: Vec<super::GenericArg>,
        args: Vec<Expr>,
    },

    // =========================================================================
    // CONTROL FLOW
    // =========================================================================
    /// If expression: `if cond { ... } else { ... }`
    If {
        condition: Box<Expr>,
        then_branch: Box<Block>,
        else_branch: Option<Box<Expr>>,
    },

    /// If let expression: `if let Pat = expr { ... } else { ... }`
    IfLet {
        pattern: Box<Pattern>,
        expr: Box<Expr>,
        then_branch: Box<Block>,
        else_branch: Option<Box<Expr>>,
    },

    /// Match expression: `match x { ... }`
    Match {
        scrutinee: Box<Expr>,
        arms: Vec<MatchArm>,
    },

    /// Infinite loop: `loop { ... }`
    Loop {
        body: Box<Block>,
        label: Option<Ident>,
    },

    /// While loop: `while cond { ... }`
    While {
        condition: Box<Expr>,
        body: Box<Block>,
        label: Option<Ident>,
    },

    /// While let loop: `while let Pat = expr { ... }`
    WhileLet {
        pattern: Box<Pattern>,
        expr: Box<Expr>,
        body: Box<Block>,
        label: Option<Ident>,
    },

    /// For loop: `for x in iter { ... }`
    For {
        pattern: Box<Pattern>,
        iter: Box<Expr>,
        body: Box<Block>,
        label: Option<Ident>,
    },

    // =========================================================================
    // JUMPS
    // =========================================================================
    /// Return: `return`, `return x`
    Return(Option<Box<Expr>>),

    /// Break: `break`, `break x`, `break 'label x`
    Break {
        label: Option<Ident>,
        value: Option<Box<Expr>>,
    },

    /// Continue: `continue`, `continue 'label`
    Continue { label: Option<Ident> },

    // =========================================================================
    // CLOSURES
    // =========================================================================
    /// Closure: `|x, y| x + y`, `move |x| x * 2`
    Closure {
        is_move: bool,
        is_async: bool,
        params: Vec<ClosureParam>,
        return_type: Option<Box<Type>>,
        body: Box<Expr>,
    },

    // =========================================================================
    // BLOCKS
    // =========================================================================
    /// Block expression: `{ ... }`
    Block(Box<Block>),

    /// Unsafe block: `unsafe { ... }`
    Unsafe(Box<Block>),

    /// Async block: `async { ... }`, `async move { ... }`
    Async { is_move: bool, body: Box<Block> },

    // =========================================================================
    // TYPE OPERATIONS
    // =========================================================================
    /// Type cast: `x as i32`
    Cast { expr: Box<Expr>, ty: Box<Type> },

    /// Type ascription: `x: i32`
    TypeAscription { expr: Box<Expr>, ty: Box<Type> },

    // =========================================================================
    // ERROR HANDLING
    // =========================================================================
    /// Try operator: `x?`
    Try(Box<Expr>),

    // =========================================================================
    // ASYNC
    // =========================================================================
    /// Await: `x.await`
    Await(Box<Expr>),

    // =========================================================================
    // RANGES
    // =========================================================================
    /// Range: `..`, `a..`, `..b`, `a..b`
    Range {
        start: Option<Box<Expr>>,
        end: Option<Box<Expr>>,
        inclusive: bool,
    },

    // =========================================================================
    // MACROS
    // =========================================================================
    /// Macro invocation: `println!(...)`
    Macro {
        path: Path,
        delimiter: crate::lexer::Delimiter,
        tokens: Vec<super::TokenTree>,
    },

    // =========================================================================
    // QUANTALANG EXTENSIONS
    // =========================================================================
    /// AI query: `@ai("prompt")`
    AIQuery {
        prompt: Box<Expr>,
        options: Vec<(Ident, Expr)>,
    },

    /// AI inference: `expr @infer Type`
    AIInfer { expr: Box<Expr>, ty: Box<Type> },

    /// Effect handler: `handle effect { ... }`
    Handle {
        effect: Path,
        handlers: Vec<EffectHandler>,
        body: Box<Block>,
    },

    /// Resume from effect: `resume value`
    Resume(Option<Box<Expr>>),

    /// Perform an effect operation: `perform IO.read("/etc/hosts")`
    Perform {
        /// The effect name (e.g., `IO`).
        effect: Ident,
        /// The operation name (e.g., `read`).
        operation: Ident,
        /// Arguments to the operation.
        args: Vec<Expr>,
    },

    // =========================================================================
    // SPECIAL
    // =========================================================================
    /// Parenthesized expression (for span tracking)
    Paren(Box<Expr>),

    /// Placeholder for error recovery
    Error,
}

/// A literal value.
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    /// Integer literal.
    Int {
        value: u128,
        suffix: Option<IntSuffix>,
        base: super::super::lexer::IntBase,
    },
    /// Float literal.
    Float {
        value: f64,
        suffix: Option<FloatSuffix>,
    },
    /// String literal.
    Str { value: String, is_raw: bool },
    /// Byte string literal.
    ByteStr { value: Vec<u8>, is_raw: bool },
    /// Character literal.
    Char(char),
    /// Byte literal.
    Byte(u8),
    /// Boolean literal.
    Bool(bool),
}

/// Integer suffix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntSuffix {
    I8,
    I16,
    I32,
    I64,
    I128,
    Isize,
    U8,
    U16,
    U32,
    U64,
    U128,
    Usize,
}

impl IntSuffix {
    /// Parse from a string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "i8" => Some(IntSuffix::I8),
            "i16" => Some(IntSuffix::I16),
            "i32" => Some(IntSuffix::I32),
            "i64" => Some(IntSuffix::I64),
            "i128" => Some(IntSuffix::I128),
            "isize" => Some(IntSuffix::Isize),
            "u8" => Some(IntSuffix::U8),
            "u16" => Some(IntSuffix::U16),
            "u32" => Some(IntSuffix::U32),
            "u64" => Some(IntSuffix::U64),
            "u128" => Some(IntSuffix::U128),
            "usize" => Some(IntSuffix::Usize),
            _ => None,
        }
    }
}

/// Float suffix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatSuffix {
    F16,
    F32,
    F64,
}

impl FloatSuffix {
    /// Parse from a string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "f16" => Some(FloatSuffix::F16),
            "f32" => Some(FloatSuffix::F32),
            "f64" => Some(FloatSuffix::F64),
            _ => None,
        }
    }
}

/// A struct field expression: `x: 1` or `x` (shorthand).
#[derive(Debug, Clone, PartialEq)]
pub struct FieldExpr {
    /// The field name.
    pub name: Ident,
    /// The field value (None for shorthand).
    pub value: Option<Box<Expr>>,
    /// Attributes.
    pub attrs: Vec<Attribute>,
    /// Span.
    pub span: Span,
}

/// A match arm: `Pattern if guard => expr`
#[derive(Debug, Clone, PartialEq)]
pub struct MatchArm {
    /// Attributes on this arm.
    pub attrs: Vec<Attribute>,
    /// The pattern to match.
    pub pattern: Pattern,
    /// Optional guard expression.
    pub guard: Option<Box<Expr>>,
    /// The body expression.
    pub body: Box<Expr>,
    /// Span.
    pub span: Span,
}

/// A closure parameter.
#[derive(Debug, Clone, PartialEq)]
pub struct ClosureParam {
    /// The pattern.
    pub pattern: Pattern,
    /// Optional type annotation.
    pub ty: Option<Box<Type>>,
    /// Span.
    pub span: Span,
}

/// An effect handler.
#[derive(Debug, Clone, PartialEq)]
pub struct EffectHandler {
    /// The effect operation being handled.
    pub operation: Ident,
    /// Parameters for the operation.
    pub params: Vec<ClosureParam>,
    /// Handler body.
    pub body: Box<Expr>,
    /// Span.
    pub span: Span,
}

/// Expression precedence for parsing.
impl Expr {
    /// Get the precedence of this expression for disambiguation.
    pub fn precedence(&self) -> u8 {
        match &self.kind {
            ExprKind::Closure { .. } => 0,
            ExprKind::Assign { .. } => 1,
            ExprKind::Range { .. } => 2,
            ExprKind::Binary { op, .. } => op.precedence(),
            ExprKind::Unary { .. } => 25,
            ExprKind::Cast { .. } | ExprKind::TypeAscription { .. } => 26,
            ExprKind::Call { .. }
            | ExprKind::MethodCall { .. }
            | ExprKind::Field { .. }
            | ExprKind::TupleField { .. }
            | ExprKind::Index { .. }
            | ExprKind::Try(_)
            | ExprKind::Await(_) => 27,
            _ => 28, // Atoms have highest precedence
        }
    }
}