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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
// ===============================================================================
// QUANTALANG MACRO EXPANSION - PATTERN MATCHING
// ===============================================================================
// Copyright (c) 2022-2026 Zain Dana Harper. MIT License.
// ===============================================================================

//! Macro pattern matching and binding.
//!
//! This module implements the pattern matching algorithm for macro_rules! macros.

use std::collections::HashMap;
use std::sync::Arc;

use crate::lexer::{Delimiter, Keyword, TokenKind};

use super::{
    MacroError, MacroPattern, MacroResult, MetaVarKind, PatternElement, RepetitionKind, TokenTree,
};

// =============================================================================
// MACRO BINDINGS
// =============================================================================

/// A bound value from pattern matching.
#[derive(Debug, Clone)]
pub enum Binding {
    /// A single value.
    Single(BindingValue),
    /// Multiple values from a repetition.
    Repeated(Vec<Binding>),
}

/// A single bound value.
#[derive(Debug, Clone)]
pub enum BindingValue {
    /// A token tree.
    TokenTree(TokenTree),
    /// Multiple token trees.
    TokenTrees(Vec<TokenTree>),
}

impl Binding {
    /// Get as a single value.
    pub fn as_single(&self) -> Option<&BindingValue> {
        match self {
            Binding::Single(v) => Some(v),
            _ => None,
        }
    }

    /// Get as repeated values.
    pub fn as_repeated(&self) -> Option<&[Binding]> {
        match self {
            Binding::Repeated(v) => Some(v),
            _ => None,
        }
    }

    /// Get the number of repetitions (1 for single values).
    pub fn count(&self) -> usize {
        match self {
            Binding::Single(_) => 1,
            Binding::Repeated(v) => v.len(),
        }
    }
}

/// Collection of bindings from pattern matching.
#[derive(Debug, Clone, Default)]
pub struct Bindings {
    pub(crate) bindings: HashMap<Arc<str>, Binding>,
}

impl Bindings {
    /// Create empty bindings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a binding.
    pub fn insert(&mut self, name: Arc<str>, binding: Binding) {
        self.bindings.insert(name, binding);
    }

    /// Get a binding.
    pub fn get(&self, name: &str) -> Option<&Binding> {
        self.bindings.get(name)
    }

    /// Merge another set of bindings into this one.
    pub fn merge(&mut self, other: Bindings) {
        self.bindings.extend(other.bindings);
    }
}

// =============================================================================
// PATTERN MATCHER
// =============================================================================

/// The macro pattern matcher.
pub struct PatternMatcher<'a> {
    /// The input token trees.
    input: &'a [TokenTree],
    /// Current position in the input.
    pos: usize,
}

impl<'a> PatternMatcher<'a> {
    /// Create a new pattern matcher.
    pub fn new(input: &'a [TokenTree]) -> Self {
        Self { input, pos: 0 }
    }

    /// Match a pattern against the input.
    pub fn match_pattern(&mut self, pattern: &MacroPattern) -> MacroResult<Bindings> {
        let mut bindings = Bindings::new();

        for element in &pattern.elements {
            self.match_element(element, &mut bindings)?;
        }

        // Check that all input was consumed
        if self.pos < self.input.len() {
            return Err(MacroError::UnexpectedToken {
                expected: "end of macro input".to_string(),
                found: self.current_kind().clone(),
            });
        }

        Ok(bindings)
    }

    /// Match a single pattern element.
    fn match_element(
        &mut self,
        element: &PatternElement,
        bindings: &mut Bindings,
    ) -> MacroResult<()> {
        match element {
            PatternElement::Token(kind) => {
                self.expect_token(kind)?;
            }
            PatternElement::MetaVar { name, kind } => {
                let value = self.match_metavar(*kind)?;
                bindings.insert(name.clone(), Binding::Single(value));
            }
            PatternElement::Repetition {
                elements,
                separator,
                repetition,
            } => {
                self.match_repetition(elements, separator.as_ref(), *repetition, bindings)?;
            }
            PatternElement::Delimited {
                delimiter,
                elements,
            } => {
                self.match_delimited(*delimiter, elements, bindings)?;
            }
        }
        Ok(())
    }

    /// Match a metavariable.
    fn match_metavar(&mut self, kind: MetaVarKind) -> MacroResult<BindingValue> {
        if self.pos >= self.input.len() {
            return Err(MacroError::UnexpectedToken {
                expected: format!("{:?}", kind),
                found: TokenKind::Eof,
            });
        }

        match kind {
            MetaVarKind::TokenTree => {
                let tt = self.input[self.pos].clone();
                self.pos += 1;
                Ok(BindingValue::TokenTree(tt))
            }
            MetaVarKind::Ident => {
                self.expect_ident()?;
                let tt = self.input[self.pos - 1].clone();
                Ok(BindingValue::TokenTree(tt))
            }
            MetaVarKind::Literal => {
                self.expect_literal()?;
                let tt = self.input[self.pos - 1].clone();
                Ok(BindingValue::TokenTree(tt))
            }
            MetaVarKind::Lifetime => {
                self.expect_lifetime()?;
                let tt = self.input[self.pos - 1].clone();
                Ok(BindingValue::TokenTree(tt))
            }
            MetaVarKind::Expr
            | MetaVarKind::Type
            | MetaVarKind::Path
            | MetaVarKind::Pat
            | MetaVarKind::Stmt
            | MetaVarKind::Block
            | MetaVarKind::Item
            | MetaVarKind::Meta
            | MetaVarKind::Vis => {
                // For complex fragments, collect tokens until a delimiter or end
                let trees = self.collect_fragment(kind)?;
                Ok(BindingValue::TokenTrees(trees))
            }
        }
    }

    /// Match a repetition pattern.
    fn match_repetition(
        &mut self,
        elements: &[PatternElement],
        separator: Option<&TokenKind>,
        repetition: RepetitionKind,
        bindings: &mut Bindings,
    ) -> MacroResult<()> {
        let mut all_bindings: HashMap<Arc<str>, Vec<Binding>> = HashMap::new();
        let mut count = 0;

        loop {
            // Check if we should stop
            let can_match = self.can_match_elements(elements);
            if !can_match {
                break;
            }

            // Match the elements
            let mut iter_bindings = Bindings::new();
            let start_pos = self.pos;

            let matched = self.try_match_elements(elements, &mut iter_bindings);
            if !matched {
                self.pos = start_pos;
                break;
            }

            // Collect bindings
            for (name, binding) in iter_bindings.bindings {
                all_bindings.entry(name).or_default().push(binding);
            }

            count += 1;

            // Handle separator
            if let Some(sep) = separator {
                if self.check_token(sep) {
                    self.pos += 1;
                } else {
                    break;
                }
            }
        }

        // Check repetition requirements
        match repetition {
            RepetitionKind::ZeroOrMore => {}
            RepetitionKind::OneOrMore => {
                if count == 0 {
                    return Err(MacroError::UnexpectedToken {
                        expected: "at least one repetition".to_string(),
                        found: self.current_kind().clone(),
                    });
                }
            }
            RepetitionKind::ZeroOrOne => {
                if count > 1 {
                    return Err(MacroError::UnexpectedToken {
                        expected: "at most one repetition".to_string(),
                        found: self.current_kind().clone(),
                    });
                }
            }
        }

        // Add collected bindings
        for (name, values) in all_bindings {
            bindings.insert(name, Binding::Repeated(values));
        }

        Ok(())
    }

    /// Match a delimited group.
    fn match_delimited(
        &mut self,
        delimiter: Delimiter,
        elements: &[PatternElement],
        bindings: &mut Bindings,
    ) -> MacroResult<()> {
        if self.pos >= self.input.len() {
            return Err(MacroError::UnexpectedToken {
                expected: format!("{:?}", delimiter),
                found: TokenKind::Eof,
            });
        }

        match &self.input[self.pos] {
            TokenTree::Delimited {
                delimiter: d,
                tokens,
                ..
            } if *d == delimiter => {
                self.pos += 1;

                // Match inner elements
                let mut inner_matcher = PatternMatcher::new(tokens);
                for element in elements {
                    inner_matcher.match_element(element, bindings)?;
                }

                Ok(())
            }
            _ => Err(MacroError::UnexpectedToken {
                expected: format!("{:?}", delimiter),
                found: self.current_kind().clone(),
            }),
        }
    }

    /// Try to match elements, returning false if it fails.
    fn try_match_elements(&mut self, elements: &[PatternElement], bindings: &mut Bindings) -> bool {
        for element in elements {
            if self.match_element(element, bindings).is_err() {
                return false;
            }
        }
        true
    }

    /// Check if we can potentially match the elements.
    fn can_match_elements(&self, elements: &[PatternElement]) -> bool {
        if self.pos >= self.input.len() {
            return false;
        }

        if let Some(first) = elements.first() {
            self.can_match_element(first)
        } else {
            true
        }
    }

    /// Check if we can potentially match an element.
    fn can_match_element(&self, element: &PatternElement) -> bool {
        if self.pos >= self.input.len() {
            return false;
        }

        match element {
            PatternElement::Token(kind) => self.check_token(kind),
            PatternElement::MetaVar { kind, .. } => self.can_match_metavar(*kind),
            PatternElement::Repetition { .. } => true,
            PatternElement::Delimited { delimiter, .. } => {
                matches!(&self.input[self.pos], TokenTree::Delimited { delimiter: d, .. } if *d == *delimiter)
            }
        }
    }

    /// Check if we can match a metavariable kind.
    fn can_match_metavar(&self, kind: MetaVarKind) -> bool {
        if self.pos >= self.input.len() {
            return false;
        }

        match kind {
            MetaVarKind::TokenTree => true,
            MetaVarKind::Ident => matches!(
                self.current_kind(),
                TokenKind::Ident | TokenKind::RawIdent | TokenKind::Keyword(_)
            ),
            MetaVarKind::Literal => matches!(self.current_kind(), TokenKind::Literal { .. }),
            MetaVarKind::Lifetime => matches!(self.current_kind(), TokenKind::Lifetime),
            _ => true, // Complex fragments can start with many tokens
        }
    }

    /// Collect tokens for a complex fragment.
    fn collect_fragment(&mut self, kind: MetaVarKind) -> MacroResult<Vec<TokenTree>> {
        let mut trees = Vec::new();

        // Collect until we hit something that definitely ends the fragment
        while self.pos < self.input.len() {
            if self.at_fragment_end(kind) {
                break;
            }
            trees.push(self.input[self.pos].clone());
            self.pos += 1;
        }

        if trees.is_empty() {
            return Err(MacroError::UnexpectedToken {
                expected: format!("{:?}", kind),
                found: self.current_kind().clone(),
            });
        }

        Ok(trees)
    }

    /// Check if we're at the end of a fragment.
    fn at_fragment_end(&self, kind: MetaVarKind) -> bool {
        if self.pos >= self.input.len() {
            return true;
        }

        let token = self.current_kind();

        match kind {
            MetaVarKind::Expr | MetaVarKind::Stmt => {
                // Expressions/statements end at ; , => and closing delimiters
                matches!(
                    token,
                    TokenKind::Semi
                        | TokenKind::Comma
                        | TokenKind::FatArrow
                        | TokenKind::CloseDelim(_)
                )
            }
            MetaVarKind::Type | MetaVarKind::Path => {
                // Types/paths end at , ; = > and closing delimiters
                matches!(
                    token,
                    TokenKind::Comma
                        | TokenKind::Semi
                        | TokenKind::Eq
                        | TokenKind::Gt
                        | TokenKind::CloseDelim(_)
                )
            }
            MetaVarKind::Pat => {
                // Patterns end at = | if and closing delimiters
                matches!(
                    token,
                    TokenKind::Eq | TokenKind::Or | TokenKind::CloseDelim(_)
                ) || matches!(token, TokenKind::Keyword(Keyword::If))
            }
            _ => {
                // Default: end at common delimiters
                matches!(
                    token,
                    TokenKind::Semi | TokenKind::Comma | TokenKind::CloseDelim(_)
                )
            }
        }
    }

    /// Expect a specific token.
    fn expect_token(&mut self, expected: &TokenKind) -> MacroResult<()> {
        if !self.check_token(expected) {
            return Err(MacroError::UnexpectedToken {
                expected: format!("{:?}", expected),
                found: self.current_kind().clone(),
            });
        }
        self.pos += 1;
        Ok(())
    }

    /// Expect an identifier.
    fn expect_ident(&mut self) -> MacroResult<()> {
        match self.current_kind() {
            TokenKind::Ident | TokenKind::RawIdent => {
                self.pos += 1;
                Ok(())
            }
            _ => Err(MacroError::UnexpectedToken {
                expected: "identifier".to_string(),
                found: self.current_kind().clone(),
            }),
        }
    }

    /// Expect a literal.
    fn expect_literal(&mut self) -> MacroResult<()> {
        match self.current_kind() {
            TokenKind::Literal { .. } => {
                self.pos += 1;
                Ok(())
            }
            _ => Err(MacroError::UnexpectedToken {
                expected: "literal".to_string(),
                found: self.current_kind().clone(),
            }),
        }
    }

    /// Expect a lifetime.
    fn expect_lifetime(&mut self) -> MacroResult<()> {
        match self.current_kind() {
            TokenKind::Lifetime => {
                self.pos += 1;
                Ok(())
            }
            _ => Err(MacroError::UnexpectedToken {
                expected: "lifetime".to_string(),
                found: self.current_kind().clone(),
            }),
        }
    }

    /// Check if the current token matches.
    fn check_token(&self, expected: &TokenKind) -> bool {
        if self.pos >= self.input.len() {
            return false;
        }
        match &self.input[self.pos] {
            TokenTree::Token(t) => &t.kind == expected,
            _ => false,
        }
    }

    /// Get the current token kind.
    fn current_kind(&self) -> TokenKind {
        if self.pos >= self.input.len() {
            TokenKind::Eof
        } else {
            match &self.input[self.pos] {
                TokenTree::Token(t) => t.kind.clone(),
                TokenTree::Delimited { delimiter, .. } => TokenKind::OpenDelim(*delimiter),
            }
        }
    }
}

/// Match a pattern against token trees.
pub fn match_macro_pattern(pattern: &MacroPattern, input: &[TokenTree]) -> MacroResult<Bindings> {
    let mut matcher = PatternMatcher::new(input);
    matcher.match_pattern(pattern)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lexer::{Lexer, SourceFile, Token};
    use crate::macro_expand::tokens_to_tree;

    fn lex(source: &str) -> Vec<Token> {
        let file = SourceFile::anonymous(source);
        let mut lexer = Lexer::new(&file);
        lexer.tokenize().unwrap()
    }

    fn make_pattern(elements: Vec<PatternElement>) -> MacroPattern {
        MacroPattern { elements }
    }

    #[test]
    fn test_match_literal_token() {
        let tokens = lex("foo");
        let trees = tokens_to_tree(&tokens);

        let pattern = make_pattern(vec![PatternElement::Token(TokenKind::Ident)]);

        let bindings = match_macro_pattern(&pattern, &trees).unwrap();
        assert!(bindings.bindings.is_empty());
    }

    #[test]
    fn test_match_metavar_ident() {
        let tokens = lex("foo");
        let trees = tokens_to_tree(&tokens);

        let pattern = make_pattern(vec![PatternElement::MetaVar {
            name: "x".into(),
            kind: MetaVarKind::Ident,
        }]);

        let bindings = match_macro_pattern(&pattern, &trees).unwrap();
        assert!(bindings.get("x").is_some());
    }

    #[test]
    fn test_match_metavar_tt() {
        let tokens = lex("(1 + 2)");
        let trees = tokens_to_tree(&tokens);

        let pattern = make_pattern(vec![PatternElement::MetaVar {
            name: "e".into(),
            kind: MetaVarKind::TokenTree,
        }]);

        let bindings = match_macro_pattern(&pattern, &trees).unwrap();
        assert!(bindings.get("e").is_some());
    }
}