Skip to main content

qualia_core_db/modalities/logic/
n3_parser.rs

1//! Native, zero-copy N3 (Notation3) parser.
2//!
3//! Two complementary front-ends over the same tokenizer:
4//!
5//! * **Borrowing AST** ([`Formula`]/[`Rule`], `Vec`-backed) — the convenient
6//!   cold-path form consumed by [`crate::modalities::logic::n3_compiler`], which
7//!   immediately lowers it to a zero-heap `CompiledRule`.
8//! * **Zero-allocation AST** ([`StackFormula`]/[`StackRule`], fixed arrays) +
9//!   [`N3Parser::parse_all_zero_heap`] — parses N3 with **no heap allocation**
10//!   at all (proven by a `dhat` test), for edge hardware and the hot path.
11//!
12//! Supported N3 surface: triples with `;` (predicate lists) and `,` (object
13//! lists); the `a` (rdf:type) keyword, kept as the engine's bare `a` token;
14//! implication rules
15//! (`=>` strict, `~>` defeasible, `^>` defeater, ` -o ` linear) with optional
16//! `[id]` and `(weight)` annotations; `{ … }` **formula quoting / reification**
17//! (a quoted graph used as a term, identified by the canonical hash of its
18//! text); `#asp { … }` and `qualia:diffuse { … }` blocks; `#` comments.
19//!
20//! Resource caps (anti-DoS): brace nesting is bounded by
21//! [`MAX_PARSE_BRACE_DEPTH`] and statement count by [`MAX_PARSE_STATEMENTS`];
22//! a quoted/parsed formula yields at most [`MAX_STACK_TRIPLES`] triples. The
23//! *evaluation* caps (forward-chaining fixpoint rounds, premise depth) live in
24//! [`crate::webizen`] (`fire_guard_rules`).
25
26use std::fmt;
27
28/// Decode one UTF-8 character at byte offset `i` in `bytes`, returning
29/// `(char, byte_width)`. Falls back to the raw byte for invalid UTF-8
30/// (never panics). Used for Unicode-aware whitespace detection.
31#[inline]
32fn decode_utf8_char(bytes: &[u8], i: usize) -> (char, usize) {
33    let b = bytes[i];
34    if b < 0x80 {
35        return (b as char, 1);
36    }
37    let remaining = &bytes[i..];
38    match std::str::from_utf8(remaining) {
39        Ok(s) => {
40            let c = s.chars().next().unwrap_or(b as char);
41            (c, c.len_utf8())
42        }
43        Err(e) => {
44            let valid_len = e.valid_up_to();
45            if valid_len > 0 {
46                let s = std::str::from_utf8(&remaining[..valid_len]).unwrap();
47                let c = s.chars().next().unwrap();
48                (c, c.len_utf8())
49            } else {
50                (b as char, 1)
51            }
52        }
53    }
54}
55
56/// Max triples in a zero-allocation [`StackFormula`] (matches the compiler's
57/// `CompiledFormula` capacity).
58pub const MAX_STACK_TRIPLES: usize = 8;
59/// Max `{` nesting depth accepted by [`N3Parser::parse_all`] before failing
60/// closed — prevents pathological-input parser state explosion.
61pub const MAX_PARSE_BRACE_DEPTH: usize = 16;
62/// Max top-level statements accepted in a single parse — anti-DoS bound.
63pub const MAX_PARSE_STATEMENTS: usize = 65_536;
64
65#[derive(Debug, Clone, Copy, PartialEq)]
66pub enum Term<'a> {
67    Uri(&'a str),
68    Variable(&'a str),
69    Literal(&'a str),
70    /// A quoted N3 formula `{ … }` used as a term (graph quoting / reification).
71    /// Holds the trimmed inner text; its identity is [`q_hash_formula`] of that
72    /// text, so an nquin can refer to (reason about) another statement.
73    Formula(&'a str),
74}
75
76#[derive(Debug, Clone, Copy, PartialEq)]
77pub struct Triple<'a> {
78    pub subject: Term<'a>,
79    pub predicate: Term<'a>,
80    pub object: Term<'a>,
81}
82
83/// Heap-backed formula (cold-path convenience; the compiler lowers it to a
84/// fixed-size `CompiledFormula`).
85#[derive(Debug, Clone, PartialEq)]
86pub struct Formula<'a> {
87    pub triples: Vec<Triple<'a>>,
88}
89
90/// Zero-allocation formula: borrowed triples in a fixed stack array.
91#[derive(Debug, Clone, Copy, PartialEq)]
92pub struct StackFormula<'a> {
93    pub triples: [Triple<'a>; MAX_STACK_TRIPLES],
94    pub len: usize,
95}
96
97impl<'a> StackFormula<'a> {
98    /// An empty formula: `MAX_STACK_TRIPLES` zeroed slots, `len` 0.
99    #[inline]
100    pub fn new() -> Self {
101        Self {
102            triples: [empty_triple(); MAX_STACK_TRIPLES],
103            len: 0,
104        }
105    }
106    /// The populated prefix.
107    #[inline]
108    pub fn as_slice(&self) -> &[Triple<'a>] {
109        &self.triples[..self.len]
110    }
111}
112
113impl Default for StackFormula<'_> {
114    /// Equivalent to [`StackFormula::new`].
115    fn default() -> Self {
116        Self::new()
117    }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum RuleType {
122    Strict,
123    Defeasible,
124    Defeater,
125    Linear,
126}
127
128/// Heap-backed rule (cold-path convenience).
129#[derive(Debug, Clone, PartialEq)]
130pub struct Rule<'a> {
131    pub id: Option<&'a str>,
132    pub rule_type: RuleType,
133    pub weight: Option<f32>,
134    pub premise: Formula<'a>,
135    pub conclusion: Formula<'a>,
136}
137
138/// Zero-allocation rule.
139#[derive(Debug, Clone, Copy, PartialEq)]
140pub struct StackRule<'a> {
141    pub id: Option<&'a str>,
142    pub rule_type: RuleType,
143    pub weight: Option<f32>,
144    pub premise: StackFormula<'a>,
145    pub conclusion: StackFormula<'a>,
146}
147
148/// Streamed event from the heap front-end ([`N3Parser::parse_all`]).
149#[derive(Debug)]
150pub enum N3Event<'a> {
151    StaticTriple(Triple<'a>),
152    LogicRule(Rule<'a>),
153    AspBlock(&'a str),
154    DiffuseBlock(&'a str),
155}
156
157/// Streamed event from the zero-allocation front-end
158/// ([`N3Parser::parse_all_zero_heap`]). `Copy`, no heap.
159#[derive(Debug, Clone, Copy)]
160pub enum StackEvent<'a> {
161    StaticTriple(Triple<'a>),
162    LogicRule(StackRule<'a>),
163    AspBlock(&'a str),
164    DiffuseBlock(&'a str),
165}
166
167#[derive(Debug, Clone)]
168pub struct N3ParserError(pub &'static str);
169
170impl fmt::Display for N3ParserError {
171    /// Renders the static error message.
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        write!(f, "{}", self.0)
174    }
175}
176
177impl std::error::Error for N3ParserError {}
178
179/// Sentinel triple of three empty-URI terms — fills unused
180/// `StackFormula` slots.
181#[inline]
182fn empty_triple<'a>() -> Triple<'a> {
183    Triple {
184        subject: Term::Uri(""),
185        predicate: Term::Uri(""),
186        object: Term::Uri(""),
187    }
188}
189
190/// Canonical 64-bit FNV-1a hash of a quoted-formula's text, with runs of
191/// Unicode whitespace collapsed to a single space (and leading/trailing
192/// whitespace dropped). This gives a **stable identity** for a quoted statement
193/// so that `{ :a :b :c }` and `{  :a  :b  :c  }` denote the same node — the
194/// handle other nquins use to reason about that statement (reification).
195/// Zero-allocation.
196///
197/// Unicode-aware: handles CJK ideographic space (U+3000), non-breaking space
198/// (U+00A0), and all other `char::is_whitespace` code points, not just ASCII.
199pub fn q_hash_formula(text: &str) -> u64 {
200    const OFFSET: u64 = 0xcbf29ce484222325;
201    const PRIME: u64 = 0x0000_0100_0000_01B3;
202    let mut h = OFFSET;
203    // Defer the separator space until a following token confirms it, so leading
204    // AND trailing whitespace are both dropped (only interior runs collapse).
205    let mut pending_space = false;
206    let mut started = false;
207    for c in text.chars() {
208        if c.is_whitespace() {
209            if started {
210                pending_space = true;
211            }
212        } else {
213            if pending_space {
214                h ^= 0x20;
215                h = h.wrapping_mul(PRIME);
216                pending_space = false;
217            }
218            // Hash the UTF-8 bytes of the character, not just the low byte.
219            for &b in c.encode_utf8(&mut [0u8; 4]).as_bytes() {
220                h ^= b as u64;
221                h = h.wrapping_mul(PRIME);
222            }
223            started = true;
224        }
225    }
226    h
227}
228
229/// Map a parsed N3 [`Term`] to its 64-bit quin hash (variables return `None`).
230pub fn term_uri_hash(term: &Term<'_>) -> Option<u64> {
231    match term {
232        Term::Uri(uri) => Some(crate::q_hash(uri)),
233        Term::Literal(lit) => Some(crate::q_hash(lit)),
234        Term::Formula(s) => Some(q_hash_formula(s)),
235        Term::Variable(_) => None,
236    }
237}
238
239/// Tokenizer over one N3 statement-block. Yields, in order:
240/// * a `{ … }` quoted formula (balanced braces) as a single token (incl. braces),
241/// * a `"…"` string literal as a single token (incl. quotes),
242/// * the punctuation tokens `;`, `,`, `.` (one char each),
243/// * otherwise a run up to the next whitespace / punctuation / `{` / `"`.
244///
245/// A `.` between two digits (a decimal, e.g. `3.14`) is kept inside the token.
246struct TripleTokenizer<'a> {
247    s: &'a str,
248    b: &'a [u8],
249    i: usize,
250}
251
252impl<'a> TripleTokenizer<'a> {
253    /// Tokenizer over `s` — iterates zero-copy `&str` tokens.
254    fn new(s: &'a str) -> Self {
255        Self {
256            s,
257            b: s.as_bytes(),
258            i: 0,
259        }
260    }
261}
262
263impl<'a> Iterator for TripleTokenizer<'a> {
264    type Item = &'a str;
265
266    /// Next N3 token: skips whitespace (Unicode-aware) and `#` comments,
267    /// yields `{…}` quoted formulas as one balanced token, `"…"` string
268    /// literals, single-char `;`/`,`/`.` punctuation, or a general token
269    /// (a `.` between digits stays inside decimals). `None` at EOF or
270    /// unbalanced braces.
271    fn next(&mut self) -> Option<&'a str> {
272        let len = self.b.len();
273        // Skip whitespace and `#...\n` comments (a comment is only a comment when
274        // it starts a token - a `#` inside a `<...>` URI or string literal is
275        // consumed as part of that token below). Unicode-aware: handles CJK
276        // ideographic space (U+3000), non-breaking space (U+00A0), etc.
277        loop {
278            while self.i < len {
279                let (c, w) = decode_utf8_char(self.b, self.i);
280                if c.is_whitespace() {
281                    self.i += w;
282                } else {
283                    break;
284                }
285            }
286            if self.i < len && self.b[self.i] == b'#' {
287                while self.i < len && self.b[self.i] != b'\n' {
288                    self.i += 1;
289                }
290                continue;
291            }
292            break;
293        }
294        if self.i >= len {
295            return None;
296        }
297        let start = self.i;
298        let c = self.b[self.i];
299
300        // Quoted formula: balanced braces.
301        if c == b'{' {
302            let mut depth = 0i32;
303            while self.i < len {
304                match self.b[self.i] {
305                    b'{' => depth += 1,
306                    b'}' => {
307                        depth -= 1;
308                        if depth == 0 {
309                            self.i += 1;
310                            break;
311                        }
312                    }
313                    _ => {}
314                }
315                self.i += 1;
316            }
317            return Some(&self.s[start..self.i]);
318        }
319
320        // String literal.
321        if c == b'"' {
322            self.i += 1;
323            while self.i < len && self.b[self.i] != b'"' {
324                self.i += 1;
325            }
326            if self.i < len {
327                self.i += 1; // include closing quote
328            }
329            return Some(&self.s[start..self.i]);
330        }
331
332        // Single-char punctuation.
333        if c == b';' || c == b',' || c == b'.' {
334            self.i += 1;
335            return Some(&self.s[start..self.i]);
336        }
337
338        // General token.
339        while self.i < len {
340            let d = self.b[self.i];
341            if d == b'.' {
342                // Keep a decimal point (digit '.' digit) inside the token.
343                let prev_digit = self.i > start && self.b[self.i - 1].is_ascii_digit();
344                let next_digit = self.i + 1 < len && self.b[self.i + 1].is_ascii_digit();
345                if prev_digit && next_digit {
346                    self.i += 1;
347                    continue;
348                }
349                break;
350            }
351            if d.is_ascii_whitespace() || d == b';' || d == b',' || d == b'{' || d == b'"' {
352                break;
353            }
354            // Also break on Unicode whitespace (e.g. U+3000 ideographic space).
355            if (d & 0x80) != 0 {
356                let (ch, _) = decode_utf8_char(self.b, self.i);
357                if ch.is_whitespace() {
358                    break;
359                }
360            }
361            self.i += 1;
362        }
363        Some(&self.s[start..self.i])
364    }
365}
366
367/// Parse the triples of one block, emitting each via `emit`. The block may be a
368/// bare formula body or a `{ … }`-wrapped one; multiple `.`-separated statements
369/// are handled, as are `;` (predicate) and `,` (object) lists. Zero-allocation.
370///
371/// `emit` returns `Ok(true)` to continue, `Ok(false)` to stop early (e.g. a
372/// caller buffer filled), or `Err` to abort.
373fn for_each_triple<'a>(
374    block: &'a str,
375    mut emit: impl FnMut(Triple<'a>) -> Result<bool, N3ParserError>,
376) -> Result<(), N3ParserError> {
377    let mut s = block.trim();
378    if s.starts_with('{') && s.ends_with('}') {
379        s = s[1..s.len() - 1].trim();
380    }
381
382    let mut subject: Option<Term<'a>> = None;
383    let mut predicate: Option<Term<'a>> = None;
384
385    for tok in TripleTokenizer::new(s) {
386        match tok {
387            "." => {
388                subject = None;
389                predicate = None;
390            }
391            ";" => {
392                predicate = None; // same subject, new predicate
393            }
394            "," => {
395                // same subject + predicate, new object: state already correct.
396            }
397            node => {
398                let term = N3Parser::parse_term(node);
399                if subject.is_none() {
400                    subject = Some(term);
401                } else if predicate.is_none() {
402                    predicate = Some(term);
403                } else {
404                    let triple = Triple {
405                        subject: subject.unwrap(),
406                        predicate: predicate.unwrap(),
407                        object: term,
408                    };
409                    if !emit(triple)? {
410                        return Ok(());
411                    }
412                    // Stay ready for `,` (another object) / `;` (new predicate) /
413                    // `.` (new statement); a bare following node is treated as a
414                    // comma-implied object.
415                }
416            }
417        }
418    }
419    Ok(())
420}
421
422/// A highly capable, native N3 parser over a borrowed `&str` (zero-copy terms).
423pub struct N3Parser<'a> {
424    text: &'a str,
425}
426
427impl<'a> N3Parser<'a> {
428    /// Parser over borrowed `text` — all emitted terms are zero-copy
429    /// slices of it.
430    pub fn new(text: &'a str) -> Self {
431        N3Parser { text }
432    }
433
434    // ── Heap front-end (cold-path convenience) ──────────────────────────────
435
436    /// Heap-backed streaming parse (cold-path convenience): emits
437    /// [`N3Event`]s — `StaticTriple`, `LogicRule`, `AspBlock`,
438    /// `DiffuseBlock` — one per statement/block, in source order.
439    /// Callback errors propagate immediately.
440    pub fn parse_all<F>(&mut self, callback: F) -> Result<(), N3ParserError>
441    where
442        F: FnMut(N3Event<'a>) -> Result<(), N3ParserError>,
443    {
444        self.scan(callback, dispatch_statement_heap, emit_block_heap)
445    }
446
447    /// Zero-allocation streaming parse: emits [`StackEvent`]s with no heap use.
448    pub fn parse_all_zero_heap<F>(&mut self, callback: F) -> Result<(), N3ParserError>
449    where
450        F: FnMut(StackEvent<'a>) -> Result<(), N3ParserError>,
451    {
452        self.scan(callback, dispatch_statement_stack, emit_block_stack)
453    }
454
455    /// Shared statement-splitter for both front-ends. Tracks comments, the two
456    /// special `{ … }` blocks, brace depth (capped), and `.`-termination at
457    /// brace depth 0, dispatching each statement via `dispatch` and each special
458    /// block via `emit_block`. `F` (the caller's event type) is opaque here —
459    /// only the per-front-end function pointers know how to build events.
460    fn scan<F>(
461        &mut self,
462        mut callback: F,
463        dispatch: fn(&'a str, &mut F) -> Result<(), N3ParserError>,
464        emit_block: fn(BlockKind, &'a str, &mut F) -> Result<(), N3ParserError>,
465    ) -> Result<(), N3ParserError> {
466        let bytes = self.text.as_bytes();
467        let len = bytes.len();
468
469        let mut i = 0;
470        let mut stmt_start = 0;
471        let mut brace_depth: i32 = 0;
472        let mut in_comment = false;
473        let mut in_string = false;
474        let mut statements = 0usize;
475
476        while i < len {
477            let c = bytes[i] as char;
478
479            if in_comment {
480                if c == '\n' {
481                    in_comment = false;
482                }
483                i += 1;
484                continue;
485            }
486
487            // Inside a `"…"` string literal, structural characters (`.`, `#`, `{`,
488            // `}`) are data, not delimiters — e.g. `"alice@example.org"` must not
489            // be split at the dot. (Comments are handled above; a `"` in a comment
490            // never reaches here.)
491            if in_string {
492                if c == '"' {
493                    in_string = false;
494                }
495                i += 1;
496                continue;
497            }
498            if c == '"' {
499                in_string = true;
500                i += 1;
501                continue;
502            }
503
504            if c == '#' {
505                if self.text[i..].starts_with("#asp {") {
506                    let end = self.text[i..].find('}').unwrap_or(self.text[i..].len());
507                    emit_block(
508                        BlockKind::Asp,
509                        self.text[i + 6..i + end].trim(),
510                        &mut callback,
511                    )?;
512                    i += end + 1;
513                    stmt_start = i;
514                    continue;
515                } else {
516                    in_comment = true;
517                    i += 1;
518                    continue;
519                }
520            }
521
522            // Gate on the ASCII lead byte 'q' so `self.text[i..]` is only sliced
523            // on a UTF-8 char boundary (continuation bytes of multi-byte chars
524            // in URIs/strings/comments must never reach a `str` slice).
525            if c == 'q' && self.text[i..].starts_with("qualia:diffuse {") {
526                let end = self.text[i..].find('}').unwrap_or(self.text[i..].len());
527                emit_block(
528                    BlockKind::Diffuse,
529                    self.text[i + 16..i + end].trim(),
530                    &mut callback,
531                )?;
532                i += end + 1;
533                stmt_start = i;
534                continue;
535            }
536
537            if c == '{' {
538                brace_depth += 1;
539                if brace_depth as usize > MAX_PARSE_BRACE_DEPTH {
540                    return Err(N3ParserError(
541                        "N3 brace nesting exceeds MAX_PARSE_BRACE_DEPTH",
542                    ));
543                }
544            }
545            if c == '}' {
546                brace_depth -= 1;
547                if brace_depth < 0 {
548                    return Err(N3ParserError("unbalanced '}' in N3 input"));
549                }
550            }
551
552            if c == '.' && brace_depth <= 0 {
553                // Do not treat a decimal point between two digits as a statement terminator (e.g. 0.85).
554                let prev_digit = i > stmt_start && bytes[i - 1].is_ascii_digit();
555                let next_digit = i + 1 < len && bytes[i + 1].is_ascii_digit();
556                if prev_digit && next_digit {
557                    i += 1;
558                    continue;
559                }
560
561                let stmt = self.text[stmt_start..=i].trim();
562                statements += 1;
563                if statements > MAX_PARSE_STATEMENTS {
564                    return Err(N3ParserError(
565                        "N3 statement count exceeds MAX_PARSE_STATEMENTS",
566                    ));
567                }
568                dispatch(stmt, &mut callback)?;
569                stmt_start = i + 1;
570            }
571
572            i += 1;
573        }
574
575        if brace_depth != 0 {
576            return Err(N3ParserError("unbalanced '{' in N3 input"));
577        }
578
579        let rem = self.text[stmt_start..].trim();
580        if !rem.is_empty() && !rem.starts_with('@') && !rem.starts_with('#') {
581            dispatch(rem, &mut callback)?;
582        }
583
584        Ok(())
585    }
586
587    // ── Zero-allocation helpers ─────────────────────────────────────────────
588
589    /// Parse a block's triples into a caller-provided buffer; returns the count
590    /// written (capped at `out.len()`). Zero-allocation.
591    pub fn parse_triples_into(block: &'a str, out: &mut [Triple<'a>]) -> usize {
592        let mut n = 0usize;
593        let _ = for_each_triple(block, |t| {
594            if n < out.len() {
595                out[n] = t;
596                n += 1;
597                Ok(n < out.len())
598            } else {
599                Ok(false)
600            }
601        });
602        n
603    }
604
605    /// Parse one rule line into a zero-allocation [`StackRule`].
606    pub fn parse_rule_zero_heap(line: &'a str) -> Option<StackRule<'a>> {
607        let (id, weight, rule_type, premise_str, conclusion_str) = split_rule(line)?;
608        let mut premise = StackFormula::new();
609        premise.len = Self::parse_triples_into(premise_str, &mut premise.triples);
610        let mut conclusion = StackFormula::new();
611        conclusion.len = Self::parse_triples_into(conclusion_str, &mut conclusion.triples);
612        Some(StackRule {
613            id,
614            rule_type,
615            weight,
616            premise,
617            conclusion,
618        })
619    }
620
621    // ── Heap helpers (kept for existing consumers) ──────────────────────────
622
623    /// Parse one rule statement into a heap `Rule` — `None` when no
624    /// implication arrow is present (callers only invoke this after
625    /// `looks_like_rule`).
626    fn parse_rule(line: &'a str) -> Option<Rule<'a>> {
627        let (id, weight, rule_type, premise_str, conclusion_str) = split_rule(line)?;
628        Some(Rule {
629            id,
630            rule_type,
631            weight,
632            premise: Formula {
633                triples: Self::parse_formula_triples(premise_str),
634            },
635            conclusion: Formula {
636                triples: Self::parse_formula_triples(conclusion_str),
637            },
638        })
639    }
640
641    /// Tokenize a formula body into a `Vec` of triples via the shared
642    /// `for_each_triple` walker; malformed tails are dropped.
643    fn parse_formula_triples(block: &'a str) -> Vec<Triple<'a>> {
644        let mut triples = Vec::new();
645        let _ = for_each_triple(block, |t| {
646            triples.push(t);
647            Ok(true)
648        });
649        triples
650    }
651
652    /// Classify one token: `?…` → `Variable`, `{…}` → `Formula` (braces
653    /// stripped), `"…"` or numeric → `Literal` (quotes stripped for
654    /// numerics), otherwise `Uri`. The N3 `a` keyword stays the bare
655    /// token `a` — expanding it to `rdf:type` would desync rules from
656    /// facts hashed under `q_hash("a")`.
657    fn parse_term(s: &'a str) -> Term<'a> {
658        let s = s.trim();
659        if s.is_empty() {
660            return Term::Uri("");
661        }
662        // NOTE: the N3 `a` keyword (rdf:type) is left as the bare token `a`,
663        // which is the engine's established type predicate (`q_hash("a")`, used
664        // uniformly by the agency/values guards and fact ingestion). It is *not*
665        // expanded to `rdf:type` here — doing so would desync rules from facts.
666        if let Some(rest) = s.strip_prefix('?') {
667            let _ = rest;
668            return Term::Variable(s);
669        }
670        if s.starts_with('{') {
671            let inner = s
672                .strip_prefix('{')
673                .and_then(|x| x.strip_suffix('}'))
674                .unwrap_or(s)
675                .trim();
676            return Term::Formula(inner);
677        }
678        if s.starts_with('"') {
679            // Strip quotes so literal VALUES are comparable / numerically parseable.
680            return Term::Literal(s.trim_matches('"'));
681        }
682        if s.parse::<f64>().is_ok() {
683            return Term::Literal(s);
684        }
685        Term::Uri(s)
686    }
687}
688
689/// True if a statement looks like an implication rule.
690fn looks_like_rule(s: &str) -> bool {
691    s.contains("=>") || s.contains("~>") || s.contains("^>") || s.contains(" -o ")
692}
693
694/// Split a rule line into `(id, weight, type, premise_str, conclusion_str)`,
695/// all zero-copy slices. Returns `None` if no arrow is present.
696fn split_rule(line: &str) -> Option<(Option<&str>, Option<f32>, RuleType, &str, &str)> {
697    let mut clean = line.trim();
698    let mut id = None;
699    let mut weight = None;
700
701    if clean.starts_with('[') {
702        if let Some(end) = clean.find(']') {
703            id = Some(clean[1..end].trim());
704            clean = clean[end + 1..].trim();
705        }
706    }
707    if clean.starts_with('(') {
708        if let Some(end) = clean.find(')') {
709            if let Ok(w) = clean[1..end].trim().parse::<f32>() {
710                weight = Some(w);
711            }
712            clean = clean[end + 1..].trim();
713        }
714    }
715
716    let (rule_type, arrow_len, arrow_idx) = if let Some(idx) = clean.find("=>") {
717        (RuleType::Strict, 2, idx)
718    } else if let Some(idx) = clean.find("~>") {
719        (RuleType::Defeasible, 2, idx)
720    } else if let Some(idx) = clean.find("^>") {
721        (RuleType::Defeater, 2, idx)
722    } else if let Some(idx) = clean.find(" -o ") {
723        (RuleType::Linear, 4, idx)
724    } else {
725        return None;
726    };
727
728    let premise = clean[..arrow_idx].trim();
729    let conclusion = clean[arrow_idx + arrow_len..].trim().trim_end_matches('.');
730    Some((id, weight, rule_type, premise, conclusion))
731}
732
733/// Strip leading whitespace and full-line `#` comments from a
734/// statement slice; returns `""` when only comments remain.
735fn trim_leading_comment_lines(mut s: &str) -> &str {
736    loop {
737        let trimmed = s.trim_start();
738        let Some(rest) = trimmed.strip_prefix('#') else {
739            return trimmed;
740        };
741        let Some(newline) = rest.find('\n') else {
742            return "";
743        };
744        s = &rest[newline + 1..];
745    }
746}
747
748// ── Statement dispatchers (one per front-end) ───────────────────────────────
749
750enum BlockKind {
751    Asp,
752    Diffuse,
753}
754
755/// Emit an `#asp {}`/`qualia:diffuse {}` block body as the heap-front-end
756/// `N3Event` variant matching `kind`.
757fn emit_block_heap<'a, F>(
758    kind: BlockKind,
759    body: &'a str,
760    callback: &mut F,
761) -> Result<(), N3ParserError>
762where
763    F: FnMut(N3Event<'a>) -> Result<(), N3ParserError>,
764{
765    match kind {
766        BlockKind::Asp => callback(N3Event::AspBlock(body)),
767        BlockKind::Diffuse => callback(N3Event::DiffuseBlock(body)),
768    }
769}
770
771/// Emit an `#asp {}`/`qualia:diffuse {}` block body as the
772/// zero-heap-front-end `StackEvent` variant matching `kind`.
773fn emit_block_stack<'a, F>(
774    kind: BlockKind,
775    body: &'a str,
776    callback: &mut F,
777) -> Result<(), N3ParserError>
778where
779    F: FnMut(StackEvent<'a>) -> Result<(), N3ParserError>,
780{
781    match kind {
782        BlockKind::Asp => callback(StackEvent::AspBlock(body)),
783        BlockKind::Diffuse => callback(StackEvent::DiffuseBlock(body)),
784    }
785}
786
787/// Heap-front-end statement dispatch: comment-only statements are
788/// skipped; arrow-bearing statements emit `LogicRule`; everything else
789/// is a `.`-terminated triple block emitted as `StaticTriple` events.
790fn dispatch_statement_heap<'a, F>(stmt: &'a str, callback: &mut F) -> Result<(), N3ParserError>
791where
792    F: FnMut(N3Event<'a>) -> Result<(), N3ParserError>,
793{
794    let s = trim_leading_comment_lines(stmt);
795    if s.is_empty() {
796        return Ok(());
797    }
798    if looks_like_rule(s) {
799        if let Some(rule) = N3Parser::parse_rule(s) {
800            return callback(N3Event::LogicRule(rule));
801        }
802    }
803    let triples = N3Parser::parse_formula_triples(s.trim_end_matches('.'));
804    for triple in triples {
805        callback(N3Event::StaticTriple(triple))?;
806    }
807    Ok(())
808}
809
810/// Zero-heap-front-end statement dispatch — same semantics as
811/// [`dispatch_statement_heap`] but emitting `StackEvent`s via the
812/// stack-formula rule/triple paths; the first callback error wins.
813fn dispatch_statement_stack<'a, F>(stmt: &'a str, callback: &mut F) -> Result<(), N3ParserError>
814where
815    F: FnMut(StackEvent<'a>) -> Result<(), N3ParserError>,
816{
817    let s = trim_leading_comment_lines(stmt);
818    if s.is_empty() {
819        return Ok(());
820    }
821    if looks_like_rule(s) {
822        if let Some(rule) = N3Parser::parse_rule_zero_heap(s) {
823            return callback(StackEvent::LogicRule(rule));
824        }
825    }
826    let mut err: Option<N3ParserError> = None;
827    for_each_triple(s.trim_end_matches('.'), |t| {
828        match callback(StackEvent::StaticTriple(t)) {
829            Ok(()) => Ok(true),
830            Err(e) => {
831                err = Some(e);
832                Ok(false)
833            }
834        }
835    })?;
836    if let Some(e) = err {
837        return Err(e);
838    }
839    Ok(())
840}
841
842#[cfg(test)]
843mod tests {
844    use super::*;
845
846    // ── Faithful parsing (item 2) ───────────────────────────────────────────
847
848    #[test]
849    fn keyword_a_is_the_engine_type_token() {
850        // The N3 `a` keyword is kept as the bare token the engine uses uniformly
851        // for rdf:type (`q_hash("a")`) — NOT expanded to `rdf:type`, which would
852        // desync parsed rules from facts asserted with `vh("a")`.
853        let mut buf = [empty_triple(); MAX_STACK_TRIPLES];
854        let n = N3Parser::parse_triples_into(":x a :Y .", &mut buf);
855        assert_eq!(n, 1);
856        assert_eq!(buf[0].predicate, Term::Uri("a"));
857        assert_eq!(buf[0].subject, Term::Uri(":x"));
858        assert_eq!(buf[0].object, Term::Uri(":Y"));
859    }
860
861    #[test]
862    fn object_lists_and_predicate_lists() {
863        let mut buf = [empty_triple(); MAX_STACK_TRIPLES];
864        // comma = object list, semicolon = predicate list
865        let n = N3Parser::parse_triples_into(":x :p :a, :b ; :q :c .", &mut buf);
866        assert_eq!(n, 3);
867        assert_eq!(
868            buf[0],
869            Triple {
870                subject: Term::Uri(":x"),
871                predicate: Term::Uri(":p"),
872                object: Term::Uri(":a")
873            }
874        );
875        assert_eq!(
876            buf[1],
877            Triple {
878                subject: Term::Uri(":x"),
879                predicate: Term::Uri(":p"),
880                object: Term::Uri(":b")
881            }
882        );
883        assert_eq!(
884            buf[2],
885            Triple {
886                subject: Term::Uri(":x"),
887                predicate: Term::Uri(":q"),
888                object: Term::Uri(":c")
889            }
890        );
891    }
892
893    #[test]
894    fn leading_comment_before_rule_preserves_premise() {
895        let text = r#"
896# (G1) Corporate-capture guard.
897{ ?c a values:CorporatePerson ; values:claims ?r .
898  ?r a values:Right ; values:heldBy values:NaturalPerson
899} => { ?c values:flag values:PersonhoodCategoryError } .
900"#;
901        let mut rules = Vec::new();
902        let mut parser = N3Parser::new(text);
903        parser
904            .parse_all(|ev| {
905                if let N3Event::LogicRule(rule) = ev {
906                    rules.push(rule);
907                }
908                Ok(())
909            })
910            .unwrap();
911
912        assert_eq!(rules.len(), 1);
913        assert_eq!(rules[0].premise.triples.len(), 4);
914        assert_eq!(rules[0].conclusion.triples.len(), 1);
915        assert_eq!(rules[0].premise.triples[0].subject, Term::Variable("?c"));
916        assert_eq!(rules[0].premise.triples[0].predicate, Term::Uri("a"));
917        assert_eq!(
918            rules[0].premise.triples[0].object,
919            Term::Uri("values:CorporatePerson")
920        );
921    }
922
923    #[test]
924    fn decimal_literal_is_one_token() {
925        let mut buf = [empty_triple(); MAX_STACK_TRIPLES];
926        let n = N3Parser::parse_triples_into(":x :p 3.14 .", &mut buf);
927        assert_eq!(n, 1);
928        assert_eq!(buf[0].object, Term::Literal("3.14"));
929    }
930
931    #[test]
932    fn parses_implication_rule_zero_heap() {
933        let rule = N3Parser::parse_rule_zero_heap("{ ?x a ?y } => { ?y a ?z } .").unwrap();
934        assert_eq!(rule.rule_type, RuleType::Strict);
935        assert_eq!(rule.premise.len, 1);
936        assert_eq!(rule.conclusion.len, 1);
937        let p = rule.premise.triples[0];
938        assert_eq!(p.subject, Term::Variable("?x"));
939        assert_eq!(p.predicate, Term::Uri("a"));
940        assert_eq!(p.object, Term::Variable("?y"));
941    }
942
943    // ── Quoting / reification (item 3) ──────────────────────────────────────
944
945    #[test]
946    fn quoted_formula_term_is_captured() {
947        let mut buf = [empty_triple(); MAX_STACK_TRIPLES];
948        let n = N3Parser::parse_triples_into("{ :alice :says :x } :trustedBy :bob .", &mut buf);
949        assert_eq!(n, 1);
950        match buf[0].subject {
951            Term::Formula(body) => assert!(body.contains(":alice :says :x")),
952            other => panic!("expected a quoted formula subject, got {other:?}"),
953        }
954        assert_eq!(buf[0].predicate, Term::Uri(":trustedBy"));
955        assert_eq!(buf[0].object, Term::Uri(":bob"));
956    }
957
958    #[test]
959    fn formula_with_internal_period_is_one_term() {
960        let mut buf = [empty_triple(); MAX_STACK_TRIPLES];
961        let n = N3Parser::parse_triples_into("{ :a :b :c . :d :e :f } :g :h .", &mut buf);
962        assert_eq!(n, 1);
963        assert!(matches!(buf[0].subject, Term::Formula(_)));
964        assert_eq!(buf[0].object, Term::Uri(":h"));
965    }
966
967    #[test]
968    fn reification_handle_is_whitespace_canonical() {
969        // The same statement with different spacing denotes the same node.
970        assert_eq!(q_hash_formula(":a :b :c"), q_hash_formula("  :a   :b  :c "));
971        assert_ne!(q_hash_formula(":a :b :c"), q_hash_formula(":a :b :d"));
972    }
973
974    // ── Resource caps (item 4, parser level) ────────────────────────────────
975
976    #[test]
977    fn rejects_excessive_brace_nesting() {
978        let deep = "{".repeat(MAX_PARSE_BRACE_DEPTH + 2);
979        let mut parser = N3Parser::new(&deep);
980        let r = parser.parse_all(|_| Ok(()));
981        assert!(r.is_err());
982    }
983
984    #[test]
985    fn rejects_unbalanced_braces() {
986        let mut parser = N3Parser::new("} :a :b :c .");
987        assert!(parser.parse_all(|_| Ok(())).is_err());
988    }
989
990    #[test]
991    fn parses_multibyte_utf8_without_panicking() {
992        // Multi-byte UTF-8 outside comments (literals, URIs) must not cause a
993        // mid-character `str` slice panic in the byte-scanning loop.
994        let doc = ":x :label \"café — déjà ➜ vu\" .\n\
995                   <http://例え.example/Ω> :note \":naïve\" .\n";
996        let mut parser = N3Parser::new(doc);
997        let mut n = 0usize;
998        parser
999            .parse_all(|ev| {
1000                if let N3Event::StaticTriple(_) = ev {
1001                    n += 1;
1002                }
1003                Ok(())
1004            })
1005            .unwrap();
1006        assert!(n >= 2, "expected both UTF-8 triples, got {n}");
1007    }
1008
1009    // ── Zero-allocation guarantee (item 1) ──────────────────────────────────
1010
1011    #[test]
1012    fn parse_all_zero_heap_allocates_nothing() {
1013        let doc = "\
1014            :alice a :Person .\n\
1015            :alice :knows :bob, :carol .\n\
1016            { ?x a :Person } => { ?x a :Agent } .\n\
1017            { :alice :says :hi } :assertedBy :alice .\n";
1018        let _profiler = dhat::Profiler::builder().testing().build();
1019
1020        let mut parser = N3Parser::new(doc);
1021        let mut triples = 0usize;
1022        let mut rules = 0usize;
1023        parser
1024            .parse_all_zero_heap(|ev| {
1025                match ev {
1026                    StackEvent::StaticTriple(_) => triples += 1,
1027                    StackEvent::LogicRule(_) => rules += 1,
1028                    _ => {}
1029                }
1030                Ok(())
1031            })
1032            .unwrap();
1033
1034        let stats = dhat::HeapStats::get();
1035        assert_eq!(
1036            stats.curr_blocks, 0,
1037            "parse_all_zero_heap must not allocate"
1038        );
1039        assert_eq!(stats.curr_bytes, 0);
1040        assert!(triples >= 4, "expected the static + object-list triples");
1041        assert_eq!(rules, 1);
1042    }
1043
1044    // ── End-to-end: parse → compile → bytecode (item 2) ─────────────────────
1045
1046    #[test]
1047    fn implication_compiles_to_sentinel_bytecode() {
1048        use crate::modalities::logic::n3_compiler::{
1049            compile_rule_to_opcodes, compile_rule_to_zero_heap, MAX_COMPILED_OPCODES,
1050        };
1051        use crate::webizen::SlgOpcode;
1052
1053        // Parse via the heap front-end (the compiler consumes `Rule`).
1054        let mut parser = N3Parser::new("{ ?x a ?y } => { ?y a ?z } .");
1055        let mut compiled_ok = false;
1056        parser
1057            .parse_all(|ev| {
1058                if let N3Event::LogicRule(rule) = ev {
1059                    let compiled = compile_rule_to_zero_heap(&rule);
1060                    let mut ops = [SlgOpcode::Call; MAX_COMPILED_OPCODES];
1061                    let n = compile_rule_to_opcodes(&compiled, &mut ops).unwrap();
1062                    assert!(n >= 3);
1063                    assert_eq!(ops[0], SlgOpcode::Unify);
1064                    compiled_ok = true;
1065                }
1066                Ok(())
1067            })
1068            .unwrap();
1069        assert!(
1070            compiled_ok,
1071            "the implication rule did not reach the compiler"
1072        );
1073    }
1074}