prism-inference 0.1.18

Bounded Rust CPU inference and tokenization for Prism-compatible GGUF models
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
//! Deterministic GBNF lowering, including Aho-Corasick delimiter grammars.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fmt::Write as _;

use super::{Arena, Parser, Result, invalid};
fn schema_delegates(schema: &serde_json::Value, raw: bool) -> bool {
    if schema.is_null() {
        return true;
    }
    if !raw {
        return false;
    }
    if let Some(kind) = schema.get("type") {
        if kind == "string" {
            return true;
        }
        if let Some(types) = kind.as_array() {
            return types
                .iter()
                .find(|kind| kind.as_str().is_some_and(|value| value != "null"))
                .is_some_and(|kind| kind == "string");
        }
        false
    } else {
        schema.get("enum").is_some()
    }
}

fn literal(value: &str) -> String {
    let mut result = String::from("\"");
    for value in value.chars() {
        match value {
            '\r' => result.push_str("\\r"),
            '\n' => result.push_str("\\n"),
            '"' => result.push_str("\\\""),
            '\\' => result.push_str("\\\\"),
            _ => result.push(value),
        }
    }
    result.push('"');
    result
}
fn repeated(value: &str, minimum: i32, maximum: i32) -> String {
    match (minimum, maximum) {
        (0, 1) => format!("{value}?"),
        (0, -1) => format!("{value}*"),
        (1, -1) => format!("{value}+"),
        (_, -1) => format!("{value}{{{minimum},}}"),
        (1, 1) => value.to_owned(),
        _ if minimum == maximum => format!("{value}{{{minimum}}}"),
        _ => format!("{value}{{{minimum},{maximum}}}"),
    }
}

#[derive(Default)]
struct State {
    children: BTreeMap<u32, usize>,
    terminal: bool,
    fail: usize,
}
fn character(value: u32) -> String {
    match value {
        45 | 91 | 93 | 92 => format!("\\{}", char::from_u32(value).unwrap_or('\0')),
        10 => "\\n".into(),
        9 => "\\t".into(),
        13 => "\\r".into(),
        32..=126 => char::from_u32(value).unwrap_or('\0').to_string(),
        0..=255 => format!("\\x{value:02X}"),
        256..=65535 => format!("\\u{value:04X}"),
        _ => format!("\\U{value:08X}"),
    }
}
fn class(values: &[u32], negated: bool) -> String {
    let mut result = if negated {
        String::from("[^")
    } else {
        String::from("[")
    };
    for &value in values {
        result.push_str(&character(value));
    }
    result.push(']');
    result
}
#[allow(
    clippy::too_many_lines,
    reason = "Keep trie construction, suffix links and deterministic DFA grammar emission together"
)]
fn automaton(
    strings: &[String],
    prefix: &str,
    including: bool,
    rules: &mut BTreeMap<String, String>,
) -> Result<String> {
    let mut states = vec![State::default()];
    let mut alphabet = BTreeSet::new();
    for string in strings {
        let mut current = 0;
        for value in string.chars().map(u32::from) {
            alphabet.insert(value);
            current = if let Some(&next) = states[current].children.get(&value) {
                next
            } else {
                let next = states.len();
                states.push(State::default());
                states[current].children.insert(value, next);
                next
            };
        }
        states[current].terminal = true;
    }
    if states.len() > 65536 {
        return Err(invalid("PEG delimiter automaton state bound exceeded"));
    }
    let mut queue = VecDeque::from([0]);
    let mut order = Vec::new();
    while let Some(current) = queue.pop_front() {
        order.push(current);
        let children: Vec<_> = states[current]
            .children
            .iter()
            .map(|(&value, &next)| (value, next))
            .collect();
        for (value, next) in children {
            if current != 0 {
                let mut fail = states[current].fail;
                while fail != 0 && !states[fail].children.contains_key(&value) {
                    fail = states[fail].fail;
                }
                states[next].fail = states[fail]
                    .children
                    .get(&value)
                    .copied()
                    .filter(|&id| id != next)
                    .unwrap_or(0);
            }
            queue.push_back(next);
        }
    }
    for current in order {
        if current != 0 {
            states[current].terminal |= states[states[current].fail].terminal;
        }
    }
    let state_name = |state| {
        if state == 0 {
            prefix.to_owned()
        } else {
            format!("{prefix}-{state:02}")
        }
    };
    for current in 0..states.len() {
        if states[current].terminal {
            continue;
        }
        let mut buckets: BTreeMap<usize, Vec<u32>> = BTreeMap::new();
        let mut completing = Vec::new();
        let mut specific = Vec::new();
        for &value in &alphabet {
            let mut state = current;
            while state != 0 && !states[state].children.contains_key(&value) {
                state = states[state].fail;
            }
            let next = states[state].children.get(&value).copied().unwrap_or(0);
            if states[next].terminal {
                completing.push(value);
                specific.push(value);
            } else if next != 0 {
                buckets.entry(next).or_default().push(value);
                specific.push(value);
            }
        }
        let rule = if including {
            let mut choices = Vec::new();
            if !completing.is_empty() {
                choices.push(class(&completing, false));
            }
            for (next, values) in buckets {
                choices.push(format!("{} {}", class(&values, false), state_name(next)));
            }
            choices.push(format!("{} {}", class(&specific, true), state_name(0)));
            choices.join(" | ")
        } else {
            let mut rule = String::from("|");
            for (next, values) in buckets {
                write!(rule, " {} {} |", class(&values, false), state_name(next))?;
            }
            write!(rule, " {} {}", class(&specific, true), state_name(0))?;
            rule
        };
        rules.insert(state_name(current), rule);
    }
    if states[0].terminal {
        rules.insert(prefix.to_owned(), "|".into());
    }
    Ok(prefix.to_owned())
}

impl Arena {
    fn effective(&self, mut id: usize) -> Result<&Parser> {
        for _ in 0..256 {
            match &self.parsers[id] {
                Parser::Tag { child, .. } | Parser::Atomic { child } => id = *child,
                Parser::Schema {
                    child, schema, raw, ..
                } if schema_delegates(schema, *raw) => id = *child,
                _ => return Ok(&self.parsers[id]),
            }
        }
        Err(invalid("PEG effective parser cycle"))
    }
    fn reachable(&self, id: usize, visited: &mut BTreeSet<String>, depth: usize) -> Result<()> {
        if depth > 256 {
            return Err(invalid("PEG rule graph depth exceeded"));
        }
        match &self.parsers[id] {
            Parser::Sequence { children } | Parser::Choice { children } => {
                for &child in children {
                    self.reachable(child, visited, depth + 1)?;
                }
            }
            Parser::Rule { name, child, .. } => {
                if visited.insert(name.clone()) {
                    self.reachable(*child, visited, depth + 1)?;
                }
            }
            Parser::Ref { name } => self.reachable(
                *self
                    .rules
                    .get(name)
                    .ok_or_else(|| invalid("PEG rule missing"))?,
                visited,
                depth + 1,
            )?,
            Parser::Repetition { child, .. }
            | Parser::And { child }
            | Parser::Not { child }
            | Parser::Tag { child, .. }
            | Parser::Atomic { child }
            | Parser::Gbnf { child, .. }
            | Parser::Ac { child, .. }
            | Parser::Schema { child, .. } => self.reachable(*child, visited, depth + 1)?,
            _ => {}
        }
        Ok(())
    }
    #[allow(
        clippy::too_many_lines,
        reason = "One exhaustive lowering match preserves all PEG variant grouping and quantifier rules"
    )]
    fn gbnf(
        &self,
        id: usize,
        rules: &mut BTreeMap<String, String>,
        schemas: &mut crate::schema::RuleBuilder,
        depth: usize,
    ) -> Result<String> {
        if depth > 256 {
            return Err(invalid("PEG grammar expansion depth exceeded"));
        }
        let result = match &self.parsers[id] {
            Parser::Epsilon
            | Parser::Start
            | Parser::End
            | Parser::And { .. }
            | Parser::Not { .. } => String::new(),
            Parser::Any => ".".into(),
            Parser::Space => "space".into(),
            Parser::Literal { literal: value } => literal(value),
            Parser::Sequence { children } => {
                let mut values = Vec::new();
                let mut bytes = 0;
                for &child in children {
                    let value = self.gbnf(child, rules, schemas, depth + 1)?;
                    bytes += value.len() + 3;
                    if bytes > 4 * 1024 * 1024 {
                        return Err(invalid("PEG grammar expansion exceeds byte bound"));
                    }
                    if value.is_empty() {
                        continue;
                    }
                    values.push(
                        if matches!(
                            self.effective(child)?,
                            Parser::Sequence { .. } | Parser::Choice { .. }
                        ) {
                            format!("({value})")
                        } else {
                            value
                        },
                    );
                }
                values.join(" ")
            }
            Parser::Choice { children } => {
                let mut result = String::new();
                for &child in children {
                    if !result.is_empty() {
                        result.push_str(" | ");
                    }
                    let value = self.gbnf(child, rules, schemas, depth + 1)?;
                    if matches!(self.effective(child)?, Parser::Choice { .. }) {
                        write!(result, "({value})")?;
                    } else {
                        result.push_str(&value);
                    }
                    if result.len() > 4 * 1024 * 1024 {
                        return Err(invalid("PEG grammar expansion exceeds byte bound"));
                    }
                }
                result
            }
            Parser::Repetition {
                child,
                min_count,
                max_count,
            } => {
                let value = self.gbnf(*child, rules, schemas, depth + 1)?;
                repeated(
                    &if matches!(
                        self.effective(*child)?,
                        Parser::Sequence { .. } | Parser::Choice { .. }
                    ) {
                        format!("({value})")
                    } else {
                        value
                    },
                    *min_count,
                    *max_count,
                )
            }
            Parser::Chars {
                pattern,
                min_count,
                max_count,
                ..
            } => repeated(pattern, *min_count, *max_count),
            Parser::String { delimiter } => format!(
                r#"( [^{delimiter}\\] | "\\" ( [{delimiter}\\/ bfnrt] | "u" [0-9a-fA-F]{{4}} ) )*"#
            ),
            Parser::Until { delimiters } => {
                if delimiters.is_empty() {
                    ".*".into()
                } else {
                    automaton(delimiters, &format!("until-{id}"), false, rules)?
                }
            }
            Parser::Ac { delimiters, .. } => {
                automaton(delimiters, &format!("ac-{id}"), true, rules)?
            }
            Parser::Rule { name, .. } | Parser::Ref { name } => name.clone(),
            Parser::Tag { child, .. } | Parser::Atomic { child } => {
                self.gbnf(*child, rules, schemas, depth + 1)?
            }
            Parser::Gbnf { grammar, .. } => grammar.clone(),
            Parser::Schema {
                child,
                name,
                schema,
                schema_source,
                raw,
            } => {
                if schema_delegates(schema, *raw) {
                    self.gbnf(*child, rules, schemas, depth + 1)?
                } else {
                    let source = schema_source.as_ref().map_or_else(
                        || serde_json::to_string(schema),
                        |source| Ok(source.clone()),
                    )?;
                    schemas.add(name, &source)?
                }
            }
        };
        if result.len() > 4 * 1024 * 1024 {
            return Err(invalid("PEG grammar expansion exceeds byte bound"));
        }
        Ok(result)
    }
    /// Generates deterministic GBNF from reachable rules or lazy trigger rules.
    /// # Errors
    /// Rejects cyclic expansion, missing rules and grammar resource limits.
    pub fn grammar(&self, lazy: bool) -> Result<String> {
        self.grammar_with_refs(lazy, &[])
    }
    /// Generates a composed grammar after resolving shared source schema documents.
    ///
    /// # Errors
    /// Rejects malformed references, unsupported schemas and grammar resource limits.
    pub fn grammar_with_refs(&self, lazy: bool, references: &[String]) -> Result<String> {
        let mut schemas = crate::schema::RuleBuilder::new();
        if references.len() > 128 {
            return Err(invalid("PEG schema reference count bound exceeded"));
        }
        for reference in references {
            schemas.resolve(reference)?;
        }
        let mut reachable = BTreeSet::new();
        let mut triggers = Vec::new();
        for (name, &id) in &self.rules {
            if matches!(&self.parsers[id], Parser::Rule { trigger: true, .. }) {
                triggers.push(name.clone());
                if lazy {
                    self.reachable(id, &mut reachable, 0)?;
                }
            }
        }
        if !lazy {
            self.reachable(self.root, &mut reachable, 0)?;
        }
        let mut rules = BTreeMap::from([(
            "space".to_owned(),
            "| \" \" | \"\\n\"{1,2} [ \\t]{0,20}".to_owned(),
        )]);
        for (name, &id) in &self.rules {
            if !reachable.contains(name) {
                continue;
            }
            if let Parser::Rule { child, .. } = &self.parsers[id] {
                let rule = self.gbnf(*child, &mut rules, &mut schemas, 0)?;
                rules.insert(name.clone(), rule);
            }
        }
        let root = if lazy {
            triggers.join(" | ")
        } else {
            self.gbnf(self.root, &mut rules, &mut schemas, 0)?
        };
        rules.insert("root".into(), root);
        for (name, rule) in schemas.into_rules() {
            rules.entry(name).or_insert(rule);
        }
        let mut result = String::new();
        for (name, rule) in rules {
            writeln!(result, "{name} ::= {rule}")?;
            if result.len() > 4 * 1024 * 1024 {
                return Err(invalid("PEG grammar output limit exceeded"));
            }
        }
        Ok(result)
    }
}