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

//! # Abstract Syntax Tree
//!
//! This module defines the AST node types for QuantaLang. The AST is produced
//! by the parser and consumed by later stages (type checking, code generation).
//!
//! ## Design Principles
//!
//! - Every node carries a `Span` for error reporting
//! - Nodes are designed for both analysis and transformation
//! - Expression nodes support the full Pratt parsing operator set
//! - Pattern nodes mirror expression structure where applicable

mod expr;
mod item;
mod operators;
mod pattern;
mod stmt;
mod ty;

pub use expr::*;
pub use item::*;
pub use operators::*;
pub use pattern::*;
pub use stmt::*;
pub use ty::*;

pub use crate::lexer::Span;
use std::sync::Arc;

/// A unique identifier for AST nodes (for later passes).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeId(pub u32);

impl NodeId {
    /// A dummy node ID for synthetic nodes.
    pub const DUMMY: Self = Self(u32::MAX);

    /// Create a new node ID.
    pub const fn new(id: u32) -> Self {
        Self(id)
    }
}

impl Default for NodeId {
    fn default() -> Self {
        Self::DUMMY
    }
}

/// An interned identifier (variable name, function name, etc.).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Ident {
    /// The name of the identifier.
    pub name: Arc<str>,
    /// The span where this identifier appears.
    pub span: Span,
}

impl Ident {
    /// Create a new identifier.
    pub fn new(name: impl Into<Arc<str>>, span: Span) -> Self {
        Self {
            name: name.into(),
            span,
        }
    }

    /// Create a dummy identifier (for synthetic nodes).
    pub fn dummy(name: impl Into<Arc<str>>) -> Self {
        Self {
            name: name.into(),
            span: Span::dummy(),
        }
    }

    /// Get the name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.name
    }
}

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

impl AsRef<str> for Ident {
    fn as_ref(&self) -> &str {
        &self.name
    }
}

/// A path like `std::collections::HashMap`.
#[derive(Debug, Clone, PartialEq)]
pub struct Path {
    /// The segments of the path.
    pub segments: Vec<PathSegment>,
    /// The span of the entire path.
    pub span: Span,
}

impl Path {
    /// Create a new path.
    pub fn new(segments: Vec<PathSegment>, span: Span) -> Self {
        Self { segments, span }
    }

    /// Create a single-segment path from an identifier.
    pub fn from_ident(ident: Ident) -> Self {
        let span = ident.span;
        Self {
            segments: vec![PathSegment::from_ident(ident)],
            span,
        }
    }

    /// Check if this path has a single segment.
    pub fn is_simple(&self) -> bool {
        self.segments.len() == 1 && self.segments[0].generics.is_empty()
    }

    /// Get the last segment's identifier.
    pub fn last_ident(&self) -> Option<&Ident> {
        self.segments.last().map(|s| &s.ident)
    }

    /// Get the last segment's generic arguments.
    pub fn last_generics(&self) -> Option<&[GenericArg]> {
        self.segments.last().map(|s| s.generics.as_slice())
    }
}

/// A segment in a path (e.g., `HashMap<K, V>`).
#[derive(Debug, Clone, PartialEq)]
pub struct PathSegment {
    /// The identifier.
    pub ident: Ident,
    /// Generic arguments (if any).
    pub generics: Vec<GenericArg>,
}

impl PathSegment {
    /// Create a segment from an identifier.
    pub fn from_ident(ident: Ident) -> Self {
        Self {
            ident,
            generics: Vec::new(),
        }
    }

    /// Create a simple segment (alias for from_ident).
    pub fn simple(ident: Ident) -> Self {
        Self::from_ident(ident)
    }

    /// Create a segment with generic arguments.
    pub fn with_generics(ident: Ident, generics: Vec<GenericArg>) -> Self {
        Self { ident, generics }
    }
}

/// A generic argument in a path.
#[derive(Debug, Clone, PartialEq)]
pub enum GenericArg {
    /// A type argument.
    Type(Box<Type>),
    /// A lifetime argument.
    Lifetime(Lifetime),
    /// A const argument.
    Const(Box<Expr>),
}

/// A lifetime like `'a` or `'static`.
#[derive(Debug, Clone, PartialEq)]
pub struct Lifetime {
    /// The name (without the leading `'`).
    pub name: Ident,
    /// The span including the `'`.
    pub span: Span,
}

impl Lifetime {
    /// Create a new lifetime.
    pub fn new(name: Ident, span: Span) -> Self {
        Self { name, span }
    }

    /// Check if this is the static lifetime.
    pub fn is_static(&self) -> bool {
        self.name.as_str() == "static"
    }

    /// Check if this is the anonymous lifetime `'_`.
    pub fn is_anonymous(&self) -> bool {
        self.name.as_str() == "_"
    }
}

/// Visibility of an item.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Visibility {
    /// Private (default).
    #[default]
    Private,
    /// Public to all.
    Public(Span),
    /// Public within the crate.
    Crate(Span),
    /// Public to the parent module.
    Super(Span),
    /// Public to a specific path.
    Restricted { path: Path, span: Span },
}

impl Visibility {
    /// Check if this is public.
    pub fn is_public(&self) -> bool {
        matches!(self, Visibility::Public(_))
    }

    /// Get the span of the visibility modifier.
    pub fn span(&self) -> Option<Span> {
        match self {
            Visibility::Private => None,
            Visibility::Public(span) => Some(*span),
            Visibility::Crate(span) => Some(*span),
            Visibility::Super(span) => Some(*span),
            Visibility::Restricted { span, .. } => Some(*span),
        }
    }
}

/// Mutability marker.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Mutability {
    /// Immutable (default).
    #[default]
    Immutable,
    /// Mutable.
    Mutable,
}

impl Mutability {
    /// Check if mutable.
    pub fn is_mut(&self) -> bool {
        matches!(self, Mutability::Mutable)
    }
}

/// An attribute like `#[derive(Debug)]` or `#![no_std]`.
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute {
    /// The path of the attribute.
    pub path: Path,
    /// The arguments/body of the attribute.
    pub args: AttrArgs,
    /// Whether this is an inner attribute (`#!`).
    pub is_inner: bool,
    /// The span of the entire attribute.
    pub span: Span,
}

/// Attribute arguments.
#[derive(Debug, Clone, PartialEq)]
pub enum AttrArgs {
    /// No arguments: `#[test]`
    Empty,
    /// Parenthesized tokens: `#[derive(Debug, Clone)]`
    Delimited(Vec<TokenTree>),
    /// Equals sign and expression: `#[path = "foo.rs"]`
    Eq(Box<Expr>),
}

/// A token tree for macro/attribute arguments.
#[derive(Debug, Clone, PartialEq)]
pub enum TokenTree {
    /// A single token.
    Token(crate::lexer::Token),
    /// A delimited group.
    Delimited {
        delimiter: crate::lexer::Delimiter,
        tokens: Vec<TokenTree>,
        span: Span,
    },
}

/// A parsed module (source file AST).
#[derive(Debug, Clone, PartialEq)]
pub struct Module {
    /// Inner attributes.
    pub attrs: Vec<Attribute>,
    /// Top-level items.
    pub items: Vec<Item>,
    /// The span of the entire file.
    pub span: Span,
}

impl Module {
    /// Create a new module.
    pub fn new(attrs: Vec<Attribute>, items: Vec<Item>, span: Span) -> Self {
        Self { attrs, items, span }
    }
}

/// A block of statements.
#[derive(Debug, Clone, PartialEq)]
pub struct Block {
    /// The statements in the block.
    /// The final statement may be an expression statement without semicolon,
    /// which serves as the block's return value.
    pub stmts: Vec<Stmt>,
    /// The span of the block including braces.
    pub span: Span,
    /// Node ID for this block.
    pub id: NodeId,
}

impl Block {
    /// Create a new block.
    pub fn new(stmts: Vec<Stmt>, span: Span) -> Self {
        Self {
            stmts,
            span,
            id: NodeId::DUMMY,
        }
    }

    /// Check if the block is empty.
    pub fn is_empty(&self) -> bool {
        self.stmts.is_empty()
    }

    /// Get the trailing expression (the block's value) if any.
    pub fn tail_expr(&self) -> Option<&Expr> {
        match self.stmts.last() {
            Some(stmt) => match &stmt.kind {
                StmtKind::Expr(expr) => Some(expr),
                _ => None,
            },
            None => None,
        }
    }
}

/// Generic parameter definition.
#[derive(Debug, Clone, PartialEq)]
pub struct GenericParam {
    /// The parameter identifier.
    pub ident: Ident,
    /// The kind of generic parameter.
    pub kind: GenericParamKind,
    /// Attributes on this parameter.
    pub attrs: Vec<Attribute>,
    /// The span.
    pub span: Span,
}

/// Kind of generic parameter.
#[derive(Debug, Clone, PartialEq)]
pub enum GenericParamKind {
    /// A type parameter: `T` or `T: Trait`.
    Type {
        bounds: Vec<TypeBound>,
        default: Option<Box<Type>>,
    },
    /// A lifetime parameter: `'a` or `'a: 'b`.
    Lifetime { bounds: Vec<Lifetime> },
    /// A const parameter: `const N: usize`.
    Const {
        ty: Box<Type>,
        default: Option<Box<Expr>>,
    },
}

/// A bound on a type like `T: Clone + Debug`.
#[derive(Debug, Clone, PartialEq)]
pub struct TypeBound {
    /// The trait path.
    pub path: Path,
    /// Whether this is a `?Sized` style bound.
    pub is_maybe: bool,
    /// The span.
    pub span: Span,
}

/// Where clause.
#[derive(Debug, Clone, PartialEq)]
pub struct WhereClause {
    /// The predicates.
    pub predicates: Vec<WherePredicate>,
    /// The span.
    pub span: Span,
}

/// A predicate in a where clause.
#[derive(Debug, Clone, PartialEq)]
pub struct WherePredicate {
    /// The type being constrained.
    pub ty: Box<Type>,
    /// The bounds.
    pub bounds: Vec<TypeBound>,
    /// The span.
    pub span: Span,
}

/// Generics on an item.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Generics {
    /// Generic parameters.
    pub params: Vec<GenericParam>,
    /// Where clause.
    pub where_clause: Option<WhereClause>,
    /// The span of the `<...>` part.
    pub span: Span,
}

impl Generics {
    /// Create empty generics.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Check if there are no generic parameters.
    pub fn is_empty(&self) -> bool {
        self.params.is_empty() && self.where_clause.is_none()
    }
}