1use std::fmt;
27
28#[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
56pub const MAX_STACK_TRIPLES: usize = 8;
59pub const MAX_PARSE_BRACE_DEPTH: usize = 16;
62pub 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 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#[derive(Debug, Clone, PartialEq)]
86pub struct Formula<'a> {
87 pub triples: Vec<Triple<'a>>,
88}
89
90#[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 #[inline]
100 pub fn new() -> Self {
101 Self {
102 triples: [empty_triple(); MAX_STACK_TRIPLES],
103 len: 0,
104 }
105 }
106 #[inline]
108 pub fn as_slice(&self) -> &[Triple<'a>] {
109 &self.triples[..self.len]
110 }
111}
112
113impl Default for StackFormula<'_> {
114 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#[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#[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#[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#[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 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#[inline]
182fn empty_triple<'a>() -> Triple<'a> {
183 Triple {
184 subject: Term::Uri(""),
185 predicate: Term::Uri(""),
186 object: Term::Uri(""),
187 }
188}
189
190pub 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 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 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
229pub 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
239struct TripleTokenizer<'a> {
247 s: &'a str,
248 b: &'a [u8],
249 i: usize,
250}
251
252impl<'a> TripleTokenizer<'a> {
253 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 fn next(&mut self) -> Option<&'a str> {
272 let len = self.b.len();
273 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 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 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; }
329 return Some(&self.s[start..self.i]);
330 }
331
332 if c == b';' || c == b',' || c == b'.' {
334 self.i += 1;
335 return Some(&self.s[start..self.i]);
336 }
337
338 while self.i < len {
340 let d = self.b[self.i];
341 if d == b'.' {
342 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 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
367fn 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; }
394 "," => {
395 }
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 }
416 }
417 }
418 }
419 Ok(())
420}
421
422pub struct N3Parser<'a> {
424 text: &'a str,
425}
426
427impl<'a> N3Parser<'a> {
428 pub fn new(text: &'a str) -> Self {
431 N3Parser { text }
432 }
433
434 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 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 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 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 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 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 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 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 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 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 fn parse_term(s: &'a str) -> Term<'a> {
658 let s = s.trim();
659 if s.is_empty() {
660 return Term::Uri("");
661 }
662 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 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
689fn looks_like_rule(s: &str) -> bool {
691 s.contains("=>") || s.contains("~>") || s.contains("^>") || s.contains(" -o ")
692}
693
694fn 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
733fn 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
748enum BlockKind {
751 Asp,
752 Diffuse,
753}
754
755fn 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
771fn 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
787fn 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
810fn 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 #[test]
849 fn keyword_a_is_the_engine_type_token() {
850 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 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 #[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 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 #[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 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 #[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 #[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 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}