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
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
use crate::logic::grammar::Production;
use crate::logic::segment::SegmentRange;
use crate::regex::Regex as DerivativeRegex;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

pub type SppfNodeId = usize;

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum SppfChild {
    Node(SppfNodeId),
    Terminal(Terminal),
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct PackedAlternative {
    pub alternative_index: usize,
    pub production: Arc<Production>,
    pub children: Vec<SppfChild>,
}

#[derive(Clone, Debug)]
pub struct SppfNode {
    pub name: String,
    pub binding: Option<String>,
    pub abs_pos: usize,
    pub consumed_segments: usize,
    pub alternatives: Vec<PackedAlternative>,
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct SppfNodeKey {
    pub name: String,
    pub binding: Option<String>,
    pub abs_pos: usize,
    pub consumed_segments: usize,
}

#[derive(Clone, Debug, Default)]
pub struct SppfForest {
    nodes: Vec<SppfNode>,
    node_lookup: HashMap<SppfNodeKey, SppfNodeId>,
}

impl SppfForest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn intern_node(&mut self, key: SppfNodeKey) -> SppfNodeId {
        if let Some(existing) = self.node_lookup.get(&key) {
            return *existing;
        }

        let id = self.nodes.len();
        self.nodes.push(SppfNode {
            name: key.name.clone(),
            binding: key.binding.clone(),
            abs_pos: key.abs_pos,
            consumed_segments: key.consumed_segments,
            alternatives: Vec::new(),
        });
        self.node_lookup.insert(key, id);
        id
    }

    pub fn add_alternative(&mut self, node_id: SppfNodeId, alt: PackedAlternative) {
        if let Some(node) = self.nodes.get_mut(node_id) {
            if !node.alternatives.contains(&alt) {
                node.alternatives.push(alt);
            }
        }
    }

    pub fn consumed_segments(&self, node_id: SppfNodeId) -> usize {
        self.nodes
            .get(node_id)
            .map(|n| n.consumed_segments)
            .unwrap_or(0)
    }

    pub fn node_is_complete(&self, node_id: SppfNodeId) -> bool {
        fn rec(
            forest: &SppfForest,
            id: SppfNodeId,
            memo: &mut HashMap<SppfNodeId, bool>,
            seen: &mut HashSet<SppfNodeId>,
        ) -> bool {
            if let Some(v) = memo.get(&id) {
                return *v;
            }
            if !seen.insert(id) {
                return false;
            }

            let complete = forest.nodes.get(id).is_some_and(|node| {
                node.alternatives.iter().any(|alt| {
                    alt.children.iter().all(|c| match c {
                        SppfChild::Terminal(Terminal::Complete { .. }) => true,
                        SppfChild::Terminal(Terminal::Partial { .. }) => false,
                        SppfChild::Node(child_id) => rec(forest, *child_id, memo, seen),
                    })
                })
            });

            seen.remove(&id);
            memo.insert(id, complete);
            complete
        }

        rec(self, node_id, &mut HashMap::new(), &mut HashSet::new())
    }

    pub fn merge_from(&mut self, other: &SppfForest) -> Vec<SppfNodeId> {
        let mut id_map = vec![0; other.nodes.len()];

        for (old_id, node) in other.nodes.iter().enumerate() {
            let key = SppfNodeKey {
                name: node.name.clone(),
                binding: node.binding.clone(),
                abs_pos: node.abs_pos,
                consumed_segments: node.consumed_segments,
            };
            id_map[old_id] = self.intern_node(key);
        }

        for (old_id, node) in other.nodes.iter().enumerate() {
            let new_id = id_map[old_id];
            for alt in &node.alternatives {
                let children = alt
                    .children
                    .iter()
                    .map(|c| match c {
                        SppfChild::Terminal(t) => SppfChild::Terminal(t.clone()),
                        SppfChild::Node(cid) => SppfChild::Node(id_map[*cid]),
                    })
                    .collect();
                self.add_alternative(
                    new_id,
                    PackedAlternative {
                        alternative_index: alt.alternative_index,
                        production: Arc::clone(&alt.production),
                        children,
                    },
                );
            }
        }

        id_map
    }

    pub fn materialize_roots(&self, root_ids: &[SppfNodeId]) -> Vec<NonTerminal> {
        let mut memo: HashMap<SppfNodeId, Vec<NonTerminal>> = HashMap::new();
        let mut seen: HashSet<SppfNodeId> = HashSet::new();
        let mut out = Vec::new();
        for root_id in root_ids {
            out.extend(self.materialize_node(*root_id, &mut memo, &mut seen));
        }
        out
    }

    pub fn materialize_root(&self, root_id: SppfNodeId) -> Vec<NonTerminal> {
        let mut memo: HashMap<SppfNodeId, Vec<NonTerminal>> = HashMap::new();
        let mut seen: HashSet<SppfNodeId> = HashSet::new();
        self.materialize_node(root_id, &mut memo, &mut seen)
    }

    fn materialize_node(
        &self,
        node_id: SppfNodeId,
        memo: &mut HashMap<SppfNodeId, Vec<NonTerminal>>,
        seen: &mut HashSet<SppfNodeId>,
    ) -> Vec<NonTerminal> {
        if let Some(v) = memo.get(&node_id) {
            return v.clone();
        }
        if !seen.insert(node_id) {
            return Vec::new();
        }

        let Some(node) = self.nodes.get(node_id) else {
            seen.remove(&node_id);
            return Vec::new();
        };

        let mut trees = Vec::new();
        for packed in &node.alternatives {
            let child_sequences = self.materialize_children(&packed.children, memo, seen);
            for children in child_sequences {
                trees.push(NonTerminal::new(
                    node.name.clone(),
                    Arc::clone(&packed.production),
                    packed.alternative_index,
                    children,
                    node.binding.clone(),
                    node.consumed_segments,
                ));
            }
        }

        seen.remove(&node_id);
        memo.insert(node_id, trees.clone());
        trees
    }

    fn materialize_children(
        &self,
        children: &[SppfChild],
        memo: &mut HashMap<SppfNodeId, Vec<NonTerminal>>,
        seen: &mut HashSet<SppfNodeId>,
    ) -> Vec<Vec<Node>> {
        let mut sequences: Vec<Vec<Node>> = vec![Vec::new()];

        for child in children {
            let choices: Vec<Node> = match child {
                SppfChild::Terminal(t) => vec![Node::Terminal(t.clone())],
                SppfChild::Node(id) => self
                    .materialize_node(*id, memo, seen)
                    .into_iter()
                    .map(Node::NonTerminal)
                    .collect(),
            };

            if choices.is_empty() {
                return Vec::new();
            }

            let mut next = Vec::new();
            for base in &sequences {
                for choice in &choices {
                    let mut seq = base.clone();
                    seq.push(choice.clone());
                    next.push(seq);
                }
            }
            sequences = next;
        }

        sequences
    }
}

#[derive(Clone, Debug)]
pub struct Sppf {
    forest: Arc<SppfForest>,
    root_ids: Vec<SppfNodeId>,
    pub input: String,
}

pub type PartialAST = Sppf;

impl Sppf {
    pub(crate) fn from_trees(roots: Vec<NonTerminal>, input: String) -> Self {
        let mut forest = SppfForest::new();
        let mut root_ids = Vec::new();

        for root in roots {
            root_ids.push(Self::insert_nt(&mut forest, root, 0));
        }

        Self {
            forest: Arc::new(forest),
            root_ids,
            input,
        }
    }

    pub fn from_forest(forest: SppfForest, root_ids: Vec<SppfNodeId>, input: String) -> Self {
        Self {
            forest: Arc::new(forest),
            root_ids,
            input,
        }
    }

    fn insert_nt(forest: &mut SppfForest, nt: NonTerminal, abs_pos: usize) -> SppfNodeId {
        let key = SppfNodeKey {
            name: nt.name.clone(),
            binding: nt.binding.clone(),
            abs_pos,
            consumed_segments: nt.consumed_segments,
        };
        let node_id = forest.intern_node(key);

        let mut offset = abs_pos;
        let mut packed_children = Vec::with_capacity(nt.children.len());
        for child in nt.children {
            match child {
                Node::Terminal(t) => {
                    if matches!(t, Terminal::Complete { .. } | Terminal::Partial { .. }) {
                        offset += 1;
                    }
                    packed_children.push(SppfChild::Terminal(t));
                }
                Node::NonTerminal(child_nt) => {
                    let consumed = child_nt.consumed_segments;
                    let child_id = Self::insert_nt(forest, child_nt, offset);
                    offset += consumed;
                    packed_children.push(SppfChild::Node(child_id));
                }
            }
        }

        forest.add_alternative(
            node_id,
            PackedAlternative {
                alternative_index: nt.alternative_index,
                production: Arc::clone(&nt.production),
                children: packed_children,
            },
        );

        node_id
    }

    pub fn roots(&self) -> Vec<NonTerminal> {
        self.forest.materialize_roots(self.root_ids.as_slice())
    }

    pub fn forest(&self) -> &SppfForest {
        self.forest.as_ref()
    }

    pub fn root_ids(&self) -> &[SppfNodeId] {
        self.root_ids.as_slice()
    }

    pub fn root_count(&self) -> usize {
        self.root_ids.len()
    }

    pub fn is_empty(&self) -> bool {
        self.root_ids.is_empty()
    }

    pub fn input(&self) -> &str {
        &self.input
    }

    pub fn complete(&self) -> Option<NonTerminal> {
        self.roots().into_iter().find(|root| root.is_complete())
    }

    pub fn completes(&self) -> Vec<NonTerminal> {
        self.roots()
            .into_iter()
            .filter(|root| root.is_complete())
            .collect()
    }

    pub fn is_complete(&self) -> bool {
        self.root_ids
            .iter()
            .any(|root_id| self.forest.node_is_complete(*root_id))
    }
}

/// A nonterminal node representing a specific choice of production
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct NonTerminal {
    /// Name of the nonterminal (e.g., "Expr", "start")
    pub name: String,
    /// The production rule used for this node
    pub production: Arc<Production>,
    /// The index of the alternative chosen
    pub alternative_index: usize,
    /// The children nodes
    pub children: Vec<Node>,
    /// Optional binding from grammar
    pub binding: Option<String>,
    /// Number of segments consumed by this node
    pub consumed_segments: usize,
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum Terminal {
    Complete {
        value: String,
        binding: Option<String>,
        extension: Option<DerivativeRegex>,
    },
    Partial {
        value: String,
        binding: Option<String>,
        remainder: Option<DerivativeRegex>,
    },
}

impl Terminal {
    pub fn len(&self) -> usize {
        match self {
            Terminal::Complete { value, .. } => value.len(),
            Terminal::Partial { value, .. } => value.len(),
        }
    }

    pub fn value(&self) -> &str {
        match self {
            Terminal::Complete { value, .. } => value,
            Terminal::Partial { value, .. } => value,
        }
    }
}

impl NonTerminal {
    pub fn new(
        name: String,
        production: impl Into<Arc<Production>>,
        alternative_index: usize,
        children: Vec<Node>,
        binding: Option<String>,
        consumed_segments: usize,
    ) -> Self {
        Self {
            name,
            production: production.into(),
            alternative_index,
            children,
            binding,
            consumed_segments,
        }
    }

    pub fn is_complete(&self) -> bool {
        if self.production.rhs.is_empty() {
            return true;
        }
        if self.children.len() != self.production.rhs.len() {
            return false;
        }
        self.children.iter().all(|child| child.is_complete())
    }

    pub fn is_extensible(&self) -> bool {
        if !self.is_complete() {
            return true;
        }
        match self.children.last() {
            Some(Node::NonTerminal(nt)) => nt.is_extensible(),
            Some(Node::Terminal(Terminal::Complete { extension: e, .. })) => e.is_some(),
            Some(Node::Terminal(Terminal::Partial { .. })) => true,
            None => false,
        }
    }

    pub fn frontier(&self) -> Option<usize> {
        if self.is_complete() {
            None
        } else {
            Some(self.children.len())
        }
    }

    pub fn size(&self) -> usize {
        self.children.iter().map(|c| c.size()).sum::<usize>() + 1
    }

    pub fn consumed_segments(&self) -> usize {
        self.consumed_segments
    }

    pub fn complete_len(
        &self,
        segments: &[crate::logic::grammar::Segment],
    ) -> Option<SegmentRange> {
        if !self.is_complete() {
            return None;
        }

        let mut min_seg: Option<usize> = None;
        let mut max_seg: Option<usize> = None;

        for child in &self.children {
            match child {
                Node::Terminal(Terminal::Complete { value, .. }) => {
                    for seg in segments {
                        if seg.text() == *value {
                            let seg_idx = seg.index;
                            min_seg = Some(min_seg.map_or(seg_idx, |m| m.min(seg_idx)));
                            max_seg = Some(max_seg.map_or(seg_idx, |m| m.max(seg_idx)));
                            break;
                        }
                    }
                }
                Node::Terminal(Terminal::Partial { .. }) => return None,
                Node::NonTerminal(nt) => {
                    if let Some(range) = nt.complete_len(segments) {
                        min_seg = Some(min_seg.map_or(range.start, |m| m.min(range.start)));
                        max_seg = Some(max_seg.map_or(range.end, |m| m.max(range.end)));
                    } else {
                        return None;
                    }
                }
            }
        }

        match (min_seg, max_seg) {
            (Some(start), Some(end)) => Some(SegmentRange::new(start, end)),
            _ => None,
        }
    }

    pub fn is_frontier(&self, index: usize) -> bool {
        self.frontier_child_index() == Some(index)
    }

    pub fn frontier_child_index(&self) -> Option<usize> {
        if self.is_complete() {
            return None;
        }

        if self.children.len() < self.production.rhs.len() {
            return Some(self.children.len());
        }

        self.children.iter().rposition(|child| !child.is_complete())
    }

    pub fn get(&self, index: usize) -> Result<Option<&Node>, String> {
        if index >= self.production.rhs.len() {
            return Err("Index out of bounds".to_string());
        }
        Ok(self.children.get(index))
    }

    pub fn get_path(&self, path: &[usize]) -> Option<Node> {
        if path.is_empty() {
            return Some(Node::NonTerminal(self.clone()));
        }
        self.children
            .get(path[0])
            .and_then(|child| child.get_path(&path[1..]))
    }

    pub fn get_path_as_nt(&self, path: &[usize]) -> Option<&NonTerminal> {
        if path.is_empty() {
            return Some(self);
        }
        self.children
            .get(path[0])
            .and_then(|child| child.get_path_as_nt(&path[1..]))
    }

    pub fn is_path_nt(&self, path: &[usize]) -> bool {
        self.get_path_as_nt(path).is_some()
    }

    pub fn path_exists(&self, path: &[usize]) -> bool {
        if path.is_empty() {
            return true;
        }
        self.children
            .get(path[0])
            .map(|child| child.path_exists(&path[1..]))
            .unwrap_or(false)
    }

    pub fn text(&self) -> Option<String> {
        self.children.iter().map(|child| child.text()).collect()
    }

    pub fn node_text_path(&self, path: &[usize]) -> Option<String> {
        if path.is_empty() {
            return self.text();
        }
        self.children.get(path[0]).and_then(|child| match child {
            Node::NonTerminal(nt) => nt.node_text_path(&path[1..]),
            Node::Terminal(t) => {
                if path.len() == 1 {
                    Some(t.value().to_string())
                } else {
                    None
                }
            }
        })
    }
}

impl PartialOrd for NonTerminal {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.size().cmp(&other.size()))
    }
}

impl Ord for NonTerminal {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.size().cmp(&other.size())
    }
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum Node {
    NonTerminal(NonTerminal),
    Terminal(Terminal),
}

impl Node {
    pub fn is_complete(&self) -> bool {
        match self {
            Node::NonTerminal(nt) => nt.is_complete(),
            Node::Terminal(Terminal::Complete { .. }) => true,
            Node::Terminal(Terminal::Partial { .. }) => false,
        }
    }

    pub fn size(&self) -> usize {
        match self {
            Node::NonTerminal(nt) => nt.size(),
            Node::Terminal(_) => 1,
        }
    }

    pub fn get_path(&self, path: &[usize]) -> Option<Node> {
        if path.is_empty() {
            return Some(self.clone());
        }

        match self {
            Node::NonTerminal(nt) => nt.get_path(path),
            Node::Terminal(_) => None,
        }
    }

    pub fn get_path_as_nt(&self, path: &[usize]) -> Option<&NonTerminal> {
        match self {
            Node::NonTerminal(nt) => nt.get_path_as_nt(path),
            Node::Terminal(_) => None,
        }
    }

    pub fn path_exists(&self, path: &[usize]) -> bool {
        if path.is_empty() {
            return true;
        }
        match self {
            Node::NonTerminal(nt) => nt.path_exists(path),
            Node::Terminal(_) => false,
        }
    }

    pub fn text(&self) -> Option<String> {
        match self {
            Node::NonTerminal(nt) => nt.text(),
            Node::Terminal(Terminal::Complete { value, .. }) => Some(value.clone()),
            Node::Terminal(Terminal::Partial { value, .. }) => Some(value.clone()),
        }
    }
}

impl PartialOrd for Node {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.size().cmp(&other.size()))
    }
}

impl Ord for Node {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.size().cmp(&other.size())
    }
}