aufbau 0.1.0

Type-aware constrained decoding for LLMs using context-dependent grammars with typing rules
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
//! Testing utilities for P7
//!
//! This module provides common testing utilities to reduce code duplication
//! across test modules. It includes grammar loading, parsing assertions,
//! type checking assertions, and tree comparison utilities.
//!
//! # Equality Checking Strategy
//!
//! ## Full Equality
//!
//! Since serializations are injective (one-to-one), we use hashes of serializations
//! for efficient equality checking. This eliminates redundant tree traversal code.
//!
//! ## Structural Equality
//!
//! When we only want to check for equality of structure,
//! and not take into account extra info like continuations/derivatives,
//! we use the `serialize_structure` method to get a structure-only serialization
//! and compare hashes of those.

use crate::logic::grammar::Grammar;
use crate::logic::partial::parse::Parser;
use crate::logic::partial::structure::{Node, NonTerminal, Terminal};
use std::path::Path;

// ============================================================================
// Grammar Loading Utilities
// ============================================================================

/// Load a grammar from the examples directory
///
/// # Example
/// ```ignore
/// let g = load_example_grammar("stlc");
/// ```

pub fn load_example_grammar(name: &str) -> Grammar {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let path = Path::new(manifest_dir)
        .join("examples")
        .join(format!("{}.auf", name));
    let content = std::fs::read_to_string(&path)
        .unwrap_or_else(|e| panic!("Failed to read {}: {}", path.display(), e));
    Grammar::load(&content).unwrap_or_else(|e| panic!("Failed to load grammar '{}': {}", name, e))
}

/// Load grammar from inline specification
///
/// # Example
/// ```ignore
/// let g = load_inline_grammar(r#"
///     expr ::= "x" | "y"
///     start ::= expr
/// "#);
/// ```
pub fn load_inline_grammar(spec: &str) -> Grammar {
    Grammar::load(spec).expect("Failed to load inline grammar")
}

/// Common test grammars as lazy statics
pub mod grammars {
    use super::*;
    use std::sync::OnceLock;

    static STLC: OnceLock<Grammar> = OnceLock::new();
    static CLIKE: OnceLock<Grammar> = OnceLock::new();
    static IMP: OnceLock<Grammar> = OnceLock::new();
    static FUN: OnceLock<Grammar> = OnceLock::new();

    pub fn stlc() -> &'static Grammar {
        STLC.get_or_init(|| load_example_grammar("stlc"))
    }

    pub fn clike() -> &'static Grammar {
        CLIKE.get_or_init(|| load_example_grammar("clike"))
    }

    pub fn imp() -> &'static Grammar {
        IMP.get_or_init(|| load_example_grammar("imp"))
    }

    pub fn fun() -> &'static Grammar {
        FUN.get_or_init(|| load_example_grammar("fun"))
    }
}

// ============================================================================
// Parsing Assertions
// ============================================================================

/// Assert that input parses successfully and produces a complete AST
pub fn assert_parses(grammar: &Grammar, input: &str) {
    let mut p = Parser::new(grammar.clone());
    let ast = p
        .parse(input)
        .unwrap_or_else(|e| panic!("Failed to parse '{}': {:?}", input, e));
    assert!(
        ast.is_complete(),
        "AST should be complete for input: {}",
        input
    );
}

/// Assert that input parses successfully and produces a complete AST with the given root name
pub fn assert_parses_as(grammar: &Grammar, input: &str, expected_root: &str) {
    let mut p = Parser::new(grammar.clone());
    let ast = p
        .parse(input)
        .unwrap_or_else(|e| panic!("Failed to parse '{}': {:?}", input, e));
    assert!(
        ast.is_complete(),
        "AST should be complete for input: {}",
        input
    );
    assert!(!ast.roots().is_empty(), "AST should have at least one root");
    assert_eq!(
        ast.roots()[0].name,
        expected_root,
        "Expected root '{}', got '{}'",
        expected_root,
        ast.roots()[0].name
    );
}

/// Assert that input fails to parse
pub fn assert_parse_fails(grammar: &Grammar, input: &str) {
    let mut p = Parser::new(grammar.clone());
    let result = p.parse(input);
    assert!(
        result.is_err(),
        "Expected parsing to fail for input: {}",
        input
    );
}

/// Assert that parsing produces the expected serialized AST structure
///
/// This deserializes the expected string and compares the trees structurally
/// rather than comparing serialized strings.
pub fn assert_parse_matches(grammar: &Grammar, input: &str, expected_serialized: &str) {
    let mut p = Parser::new(grammar.clone());

    let ast = p
        .parse(input)
        .unwrap_or_else(|e| panic!("Failed to parse '{}': {:?}", input, e));

    assert!(
        ast.is_complete(),
        "AST should be complete for input: {}",
        input
    );
    assert!(!ast.roots().is_empty(), "AST should have at least one root");

    // Deserialize the expected tree
    let expected = NonTerminal::deserialize(expected_serialized, grammar)
        .unwrap_or_else(|e| panic!("Failed to deserialize expected tree: {}", e));

    // Compare trees
    let actual = &ast.roots()[0];
    assert_trees_equal(actual, &expected, input);
}

/// Assert that parsing produces a complete tree matching the expected serialization
pub fn assert_complete_matches(grammar: &Grammar, input: &str, expected_serialized: &str) {
    assert_parse_matches(grammar, input, expected_serialized);
}

/// Assert that parsing produces a partial tree that contains the expected structure
///
///  This checks that the parse succeeds and produces at least
/// one tree matching the expected structure, but doesn't require the parse to be complete.
pub fn assert_partial_matches(grammar: &Grammar, input: &str, expected_serialized: &str) {
    let mut p = Parser::new(grammar.clone());

    let ast = p
        .parse(input)
        .unwrap_or_else(|e| panic!("Failed to parse '{}': {:?}", input, e));

    assert!(!ast.roots().is_empty(), "AST should have at least one root");

    // Deserialize the expected tree
    let expected = NonTerminal::deserialize(expected_serialized, grammar)
        .unwrap_or_else(|e| panic!("Failed to deserialize expected tree: {}", e));

    // Find a matching tree in the roots
    let found = ast.roots().iter().any(|root| trees_equal(root, &expected));

    assert!(
        found,
        "No tree matching expected structure found in parse forest for input: '{}'",
        input
    );
}

// ============================================================================
// Tree Equality Checking (Hash-based)
// ============================================================================

/// Compute hash of a serialized structure for equality comparison.
/// Since serializations are injective, equal hashes imply equal structures.
fn compute_hash(serialized: &str) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    serialized.hash(&mut hasher);
    hasher.finish()
}

/// Check if two trees are equal by comparing serialization hashes.
/// Serializations are injective, so this is a reliable equality check.
fn trees_equal(actual: &NonTerminal, expected: &NonTerminal) -> bool {
    compute_hash(&actual.serialize()) == compute_hash(&expected.serialize())
}

/// Check if two nodes are equal by comparing serialization hashes
fn nodes_equal(actual: &Node, expected: &Node) -> bool {
    compute_hash(&actual.serialize()) == compute_hash(&expected.serialize())
}

/// Check if two terminals are equal by comparing serialization hashes
fn terminals_equal(actual: &Terminal, expected: &Terminal) -> bool {
    compute_hash(&actual.serialize()) == compute_hash(&expected.serialize())
}

/// Assert two NonTerminal trees are equal using hash-based comparison
pub fn assert_trees_equal(actual: &NonTerminal, expected: &NonTerminal, context: &str) {
    if !trees_equal(actual, expected) {
        panic!(
            "Tree mismatch at '{}'\nExpected:\n{}\n\nActual:\n{}\n",
            context,
            expected.serialize(),
            actual.serialize()
        );
    }
}

/// Assert two Node trees are equal using hash-based comparison
#[allow(dead_code)]
fn assert_nodes_equal(actual: &Node, expected: &Node, context: &str) {
    if !nodes_equal(actual, expected) {
        panic!(
            "Node mismatch at '{}'\nExpected:\n{}\n\nActual:\n{}\n",
            context,
            expected.serialize(),
            actual.serialize()
        );
    }
}

/// Assert two Terminals are equal using hash-based comparison
#[allow(dead_code)]
fn assert_terminals_equal(actual: &Terminal, expected: &Terminal, context: &str) {
    if !terminals_equal(actual, expected) {
        panic!(
            "Terminal mismatch at '{}'\nExpected:\n{}\n\nActual:\n{}\n",
            context,
            expected.serialize(),
            actual.serialize()
        );
    }
}

// ============================================================================
// Structural Matching (ignoring derivatives)
// ============================================================================

/// Check if two NonTerminals structurally match by comparing structure-only serializations.
/// This ignores extensions/remainders but checks everything else.
/// Uses the serialize_structure method from the serialization module.
pub fn trees_match(actual: &NonTerminal, expected: &NonTerminal) -> bool {
    let actual_structure = actual.serialize_structure();
    let expected_structure = expected.serialize_structure();
    compute_hash(&actual_structure) == compute_hash(&expected_structure)
}

/// Check if two nodes structurally match
fn nodes_match(actual: &Node, expected: &Node) -> bool {
    match (actual, expected) {
        (Node::NonTerminal(a), Node::NonTerminal(e)) => trees_match(a, e),
        (
            Node::Terminal(Terminal::Complete {
                value: av,
                binding: ab,
                ..
            }),
            Node::Terminal(Terminal::Complete {
                value: ev,
                binding: eb,
                ..
            }),
        ) => av == ev && ab == eb,
        (
            Node::Terminal(Terminal::Partial {
                value: av,
                binding: ab,
                ..
            }),
            Node::Terminal(Terminal::Partial {
                value: ev,
                binding: eb,
                ..
            }),
        ) => av == ev && ab == eb,
        _ => false,
    }
}

/// Assert that two trees structurally match (ignoring extensions/remainders)
pub fn assert_trees_match(actual: &NonTerminal, expected: &NonTerminal, context: &str) {
    if !trees_match(actual, expected) {
        panic!(
            "Tree structure mismatch at '{}'\nExpected structure:\n{}\n\nActual structure:\n{}\n",
            context,
            expected.serialize_structure(),
            actual.serialize_structure()
        );
    }
}

/// Assert that two nodes structurally match
#[allow(dead_code)]
fn assert_nodes_match(actual: &Node, expected: &Node, context: &str) {
    if !nodes_match(actual, expected) {
        panic!(
            "Node structure mismatch at '{}'\nExpected:\n{}\n\nActual:\n{}\n",
            context,
            expected.serialize(),
            actual.serialize()
        );
    }
}

/// Assert that parsing produces a tree that structurally matches (ignoring derivatives)
pub fn assert_parse_structurally_matches(
    grammar: &Grammar,
    input: &str,
    expected_serialized: &str,
) {
    let mut parser = Parser::new(grammar.clone());
    let ast = parser
        .parse(input)
        .unwrap_or_else(|e| panic!("Failed to parse '{}': {:?}", input, e));

    assert!(
        ast.is_complete(),
        "AST should be complete for input: {}",
        input
    );
    assert!(!ast.roots().is_empty(), "AST should have at least one root");

    // Deserialize the expected tree
    let expected = NonTerminal::deserialize(expected_serialized, grammar)
        .unwrap_or_else(|e| panic!("Failed to deserialize expected tree: {}", e));

    // Compare trees structurally (ignoring extensions/remainders). With an SPPF-backed
    // parser, root enumeration order is not semantically meaningful, so we accept any
    // complete root that matches the expected structure.
    let roots = ast.roots();
    let found_match = roots.iter().any(|root| trees_match(root, &expected));

    assert!(
        found_match,
        "No complete root in AST matches expected tree for input '{}'\nExpected:\n{}\nActual roots:\n{}",
        input,
        expected.serialize(),
        roots
            .iter()
            .enumerate()
            .map(|(i, r)| format!("Root {}:\n{}", i, r.serialize()))
            .collect::<Vec<_>>()
            .join("\n")
    );
}

/// Assert that parsing produces a partial tree with at least one root that structurally matches
pub fn assert_partial_structurally_matches(
    grammar: &Grammar,
    input: &str,
    expected_serialized: &str,
) {
    let mut parser = Parser::new(grammar.clone());
    let ast = parser
        .partial(input)
        .into_result()
        .unwrap_or_else(|e| panic!("Failed to parse '{}': {:?}", input, e));

    assert!(!ast.roots().is_empty(), "AST should have at least one root");

    // Deserialize the expected tree
    let expected = NonTerminal::deserialize(expected_serialized, grammar)
        .unwrap_or_else(|e| panic!("Failed to deserialize expected tree: {}", e));

    // Check if any root structurally matches
    let roots = ast.roots();
    let found_match = roots.iter().any(|root| trees_match(root, &expected));

    assert!(
        found_match,
        "No root in AST matches expected tree for input '{}'\nExpected:\n{}\nActual roots:\n{}",
        input,
        expected.serialize(),
        roots
            .iter()
            .enumerate()
            .map(|(i, r)| format!("Root {}:\n{}", i, r.serialize()))
            .collect::<Vec<_>>()
            .join("\n")
    );
}

// ============================================================================
// Tree Inspection Utilities
// ============================================================================

/// Count the total number of nodes in a tree
pub fn count_nodes(root: &NonTerminal) -> usize {
    1 + root
        .children
        .iter()
        .map(|child| match child {
            Node::NonTerminal(nt) => count_nodes(nt),
            Node::Terminal(_) => 1,
        })
        .sum::<usize>()
}

/// Get all terminal values in the tree (in order)
pub fn collect_terminal_values(root: &NonTerminal) -> Vec<String> {
    let mut values = Vec::new();
    collect_terminals_rec(root, &mut values);
    values
}

fn collect_terminals_rec(nt: &NonTerminal, values: &mut Vec<String>) {
    for child in &nt.children {
        match child {
            Node::NonTerminal(nt) => collect_terminals_rec(nt, values),
            Node::Terminal(Terminal::Complete { value, .. }) => values.push(value.clone()),
            Node::Terminal(Terminal::Partial { value, .. }) => values.push(value.clone()),
        }
    }
}

/// Get all bindings in the tree
pub fn collect_bindings(root: &NonTerminal) -> Vec<(String, String)> {
    let mut bindings = Vec::new();
    collect_bindings_rec(root, &mut bindings);
    bindings
}

fn collect_bindings_rec(nt: &NonTerminal, bindings: &mut Vec<(String, String)>) {
    if let Some(ref binding) = nt.binding {
        bindings.push((nt.name.clone(), binding.clone()));
    }

    for child in &nt.children {
        match child {
            Node::NonTerminal(nt) => collect_bindings_rec(nt, bindings),
            Node::Terminal(Terminal::Complete {
                binding: Some(b), ..
            })
            | Node::Terminal(Terminal::Partial {
                binding: Some(b), ..
            }) => {
                bindings.push(("Terminal".to_string(), b.clone()));
            }
            _ => {}
        }
    }
}

// ============================================================================
// Convenience Macros
// ============================================================================

/// Parse input with a grammar and panic with a nice error message on failure
#[macro_export]
macro_rules! parse {
    ($grammar:expr, $input:expr) => {{
        let mut p = $crate::logic::partial::parse::Parser::new(($grammar).clone());
        p.parse($input)
            .unwrap_or_else(|e| panic!("Failed to parse '{}': {:?}", $input, e))
    }};
}

/// Assert that two values are equal with a custom message
#[macro_export]
macro_rules! assert_eq_msg {
    ($left:expr, $right:expr, $msg:expr) => {
        assert_eq!($left, $right, "{}", $msg)
    };
}