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
// ===============================================================================
// QUANTALANG AST - OPERATORS
// ===============================================================================
// Copyright (c) 2022-2026 Zain Dana Harper. MIT License.
// ===============================================================================

//! Operator definitions and precedence for QuantaLang.
//!
//! Precedence levels follow Rust conventions with QuantaLang extensions:
//! - Higher numbers = tighter binding
//! - Associativity determines left-to-right vs right-to-left parsing

use std::fmt;

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BinOp {
    // =========================================================================
    // ARITHMETIC OPERATORS
    // =========================================================================
    /// Addition: `+`
    Add,
    /// Subtraction: `-`
    Sub,
    /// Multiplication: `*`
    Mul,
    /// Division: `/`
    Div,
    /// Remainder/Modulo: `%`
    Rem,
    /// Power: `**` (QuantaLang extension)
    Pow,

    // =========================================================================
    // BITWISE OPERATORS
    // =========================================================================
    /// Bitwise AND: `&`
    BitAnd,
    /// Bitwise OR: `|`
    BitOr,
    /// Bitwise XOR: `^`
    BitXor,
    /// Left shift: `<<`
    Shl,
    /// Right shift: `>>`
    Shr,

    // =========================================================================
    // LOGICAL OPERATORS
    // =========================================================================
    /// Logical AND: `&&`
    And,
    /// Logical OR: `||`
    Or,

    // =========================================================================
    // COMPARISON OPERATORS
    // =========================================================================
    /// Equality: `==`
    Eq,
    /// Inequality: `!=`
    Ne,
    /// Less than: `<`
    Lt,
    /// Less than or equal: `<=`
    Le,
    /// Greater than: `>`
    Gt,
    /// Greater than or equal: `>=`
    Ge,

    // =========================================================================
    // RANGE OPERATORS
    // =========================================================================
    /// Exclusive range: `..`
    Range,
    /// Inclusive range: `..=`
    RangeInclusive,

    // =========================================================================
    // SPECIAL OPERATORS (QuantaLang extensions)
    // =========================================================================
    /// Pipe operator: `|>` (function application)
    Pipe,
    /// Compose operator: `>>` (function composition)
    Compose,
}

impl BinOp {
    /// Get the precedence of this operator.
    /// Higher values bind tighter.
    pub fn precedence(&self) -> u8 {
        match self {
            // Lowest precedence
            BinOp::Range | BinOp::RangeInclusive => 1,

            // Logical OR
            BinOp::Or => 2,

            // Logical AND
            BinOp::And => 3,

            // Comparison
            BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => 4,

            // Bitwise OR
            BinOp::BitOr => 5,

            // Bitwise XOR
            BinOp::BitXor => 6,

            // Bitwise AND
            BinOp::BitAnd => 7,

            // Shift
            BinOp::Shl | BinOp::Shr => 8,

            // Pipe and compose (special operators)
            BinOp::Pipe | BinOp::Compose => 9,

            // Addition and subtraction
            BinOp::Add | BinOp::Sub => 10,

            // Multiplication, division, remainder
            BinOp::Mul | BinOp::Div | BinOp::Rem => 11,

            // Power (highest arithmetic precedence)
            BinOp::Pow => 12,
        }
    }

    /// Get the associativity of this operator.
    pub fn associativity(&self) -> Associativity {
        match self {
            // Right-associative operators
            BinOp::Pow => Associativity::Right,
            BinOp::Pipe | BinOp::Compose => Associativity::Left,

            // Most operators are left-associative
            _ => Associativity::Left,
        }
    }

    /// Get the binding power for Pratt parsing.
    /// Returns (left_bp, right_bp) where higher = tighter binding.
    pub fn binding_power(&self) -> (u8, u8) {
        let prec = self.precedence() * 2;
        match self.associativity() {
            Associativity::Left => (prec, prec + 1),
            Associativity::Right => (prec + 1, prec),
            Associativity::None => (prec, prec),
        }
    }

    /// Get the operator symbol.
    pub fn as_str(&self) -> &'static str {
        match self {
            BinOp::Add => "+",
            BinOp::Sub => "-",
            BinOp::Mul => "*",
            BinOp::Div => "/",
            BinOp::Rem => "%",
            BinOp::Pow => "**",
            BinOp::BitAnd => "&",
            BinOp::BitOr => "|",
            BinOp::BitXor => "^",
            BinOp::Shl => "<<",
            BinOp::Shr => ">>",
            BinOp::And => "&&",
            BinOp::Or => "||",
            BinOp::Eq => "==",
            BinOp::Ne => "!=",
            BinOp::Lt => "<",
            BinOp::Le => "<=",
            BinOp::Gt => ">",
            BinOp::Ge => ">=",
            BinOp::Range => "..",
            BinOp::RangeInclusive => "..=",
            BinOp::Pipe => "|>",
            BinOp::Compose => ">>",
        }
    }

    /// Check if this is a comparison operator.
    pub fn is_comparison(&self) -> bool {
        matches!(
            self,
            BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge
        )
    }

    /// Check if this is a logical operator.
    pub fn is_logical(&self) -> bool {
        matches!(self, BinOp::And | BinOp::Or)
    }

    /// Check if this is an arithmetic operator.
    pub fn is_arithmetic(&self) -> bool {
        matches!(
            self,
            BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Rem | BinOp::Pow
        )
    }

    /// Check if this is a bitwise operator.
    pub fn is_bitwise(&self) -> bool {
        matches!(
            self,
            BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor | BinOp::Shl | BinOp::Shr
        )
    }
}

impl fmt::Display for BinOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Compound assignment operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AssignOp {
    /// `=`
    Assign,
    /// `+=`
    AddAssign,
    /// `-=`
    SubAssign,
    /// `*=`
    MulAssign,
    /// `/=`
    DivAssign,
    /// `%=`
    RemAssign,
    /// `&=`
    BitAndAssign,
    /// `|=`
    BitOrAssign,
    /// `^=`
    BitXorAssign,
    /// `<<=`
    ShlAssign,
    /// `>>=`
    ShrAssign,
}

impl AssignOp {
    /// Get the corresponding binary operator (if any).
    pub fn to_bin_op(&self) -> Option<BinOp> {
        match self {
            AssignOp::Assign => None,
            AssignOp::AddAssign => Some(BinOp::Add),
            AssignOp::SubAssign => Some(BinOp::Sub),
            AssignOp::MulAssign => Some(BinOp::Mul),
            AssignOp::DivAssign => Some(BinOp::Div),
            AssignOp::RemAssign => Some(BinOp::Rem),
            AssignOp::BitAndAssign => Some(BinOp::BitAnd),
            AssignOp::BitOrAssign => Some(BinOp::BitOr),
            AssignOp::BitXorAssign => Some(BinOp::BitXor),
            AssignOp::ShlAssign => Some(BinOp::Shl),
            AssignOp::ShrAssign => Some(BinOp::Shr),
        }
    }

    /// Get the operator symbol.
    pub fn as_str(&self) -> &'static str {
        match self {
            AssignOp::Assign => "=",
            AssignOp::AddAssign => "+=",
            AssignOp::SubAssign => "-=",
            AssignOp::MulAssign => "*=",
            AssignOp::DivAssign => "/=",
            AssignOp::RemAssign => "%=",
            AssignOp::BitAndAssign => "&=",
            AssignOp::BitOrAssign => "|=",
            AssignOp::BitXorAssign => "^=",
            AssignOp::ShlAssign => "<<=",
            AssignOp::ShrAssign => ">>=",
        }
    }
}

impl fmt::Display for AssignOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UnaryOp {
    /// Negation: `-`
    Neg,
    /// Logical NOT: `!`
    Not,
    /// Bitwise NOT: `~`
    BitNot,
    /// Dereference: `*`
    Deref,
    /// Reference: `&`
    Ref,
    /// Mutable reference: `&mut`
    RefMut,
}

impl UnaryOp {
    /// Get the binding power for prefix operators.
    pub fn prefix_binding_power(&self) -> u8 {
        // All prefix operators have the same (high) precedence
        25
    }

    /// Get the operator symbol.
    pub fn as_str(&self) -> &'static str {
        match self {
            UnaryOp::Neg => "-",
            UnaryOp::Not => "!",
            UnaryOp::BitNot => "~",
            UnaryOp::Deref => "*",
            UnaryOp::Ref => "&",
            UnaryOp::RefMut => "&mut",
        }
    }
}

impl fmt::Display for UnaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Associativity of an operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Associativity {
    /// Left-to-right: `a + b + c` = `(a + b) + c`
    Left,
    /// Right-to-left: `a ** b ** c` = `a ** (b ** c)`
    Right,
    /// Non-associative (comparison chaining)
    None,
}

/// Postfix operators and their binding power.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PostfixOp {
    /// Function call: `f(args)`
    Call,
    /// Method call: `x.method(args)`
    MethodCall,
    /// Field access: `x.field`
    Field,
    /// Index: `x[index]`
    Index,
    /// Try operator: `x?`
    Try,
    /// Await: `x.await`
    Await,
}

impl PostfixOp {
    /// Get the binding power for postfix operators.
    /// All postfix operators bind very tightly.
    pub fn binding_power(&self) -> u8 {
        27 // Higher than any prefix or infix operator
    }
}

/// Operator precedence levels (for reference).
/// These are the actual values used in the Pratt parser.
pub mod precedence {
    /// Assignment (lowest)
    pub const ASSIGN: u8 = 0;
    /// Range operators
    pub const RANGE: u8 = 2;
    /// Logical OR
    pub const OR: u8 = 4;
    /// Logical AND
    pub const AND: u8 = 6;
    /// Comparison
    pub const COMPARE: u8 = 8;
    /// Bitwise OR
    pub const BIT_OR: u8 = 10;
    /// Bitwise XOR
    pub const BIT_XOR: u8 = 12;
    /// Bitwise AND
    pub const BIT_AND: u8 = 14;
    /// Shift
    pub const SHIFT: u8 = 16;
    /// Pipe operator
    pub const PIPE: u8 = 18;
    /// Addition/Subtraction
    pub const SUM: u8 = 20;
    /// Multiplication/Division
    pub const PRODUCT: u8 = 22;
    /// Power
    pub const POWER: u8 = 24;
    /// Prefix operators
    pub const PREFIX: u8 = 25;
    /// Postfix operators (highest)
    pub const POSTFIX: u8 = 27;
    /// Type ascription
    pub const AS: u8 = 26;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_precedence_ordering() {
        // Multiplication binds tighter than addition
        assert!(BinOp::Mul.precedence() > BinOp::Add.precedence());

        // Logical AND binds tighter than OR
        assert!(BinOp::And.precedence() > BinOp::Or.precedence());

        // Comparison is between logical operators and arithmetic
        assert!(BinOp::Eq.precedence() > BinOp::Or.precedence());
        assert!(BinOp::Eq.precedence() < BinOp::Add.precedence());
    }

    #[test]
    fn test_binding_power() {
        // Left-associative: left < right
        let (l, r) = BinOp::Add.binding_power();
        assert!(l < r);

        // Right-associative: left > right
        let (l, r) = BinOp::Pow.binding_power();
        assert!(l > r);
    }

    #[test]
    fn test_assign_op_conversion() {
        assert_eq!(AssignOp::AddAssign.to_bin_op(), Some(BinOp::Add));
        assert_eq!(AssignOp::Assign.to_bin_op(), None);
    }
}