1use std::cell::RefCell;
11use std::fmt;
12use std::rc::Rc;
13use std::sync::Arc;
14
15use indexmap::IndexMap;
16use serde_json::{json, Map, Value};
17use tabnas::{Context, GrammarError, Rule, Tabnas};
18
19use crate::ir::{diag_name, NodeKind};
20
21pub type ActionFn =
24 Arc<dyn Fn(&mut Rule, &mut Context) -> Result<(), tabnas::ActionError> + Send + Sync>;
25
26pub type ActionsMap = Vec<(String, Vec<ActionFn>)>;
29
30#[derive(Clone)]
35pub enum RefAction {
36 Node {
39 init: bool,
40 rule: String,
41 kind: NodeKind,
42 nterms: usize,
43 },
44 Capture { rule: String, kind: NodeKind },
46 Bubble,
48 Fold { c_n: usize },
50 ProbeInit,
52 ProbeDecide { disambiguator: String },
54 ProbePhase(u8),
56 User(ActionFn),
58 Phase(Vec<ActionFn>),
60}
61
62impl fmt::Debug for RefAction {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 RefAction::Node {
66 init,
67 rule,
68 kind,
69 nterms,
70 } => write!(f, "Node({init}, {rule}, {}, {nterms})", kind.as_str()),
71 RefAction::Capture { rule, kind } => write!(f, "Capture({rule}, {})", kind.as_str()),
72 RefAction::Bubble => write!(f, "Bubble"),
73 RefAction::Fold { c_n } => write!(f, "Fold({c_n})"),
74 RefAction::ProbeInit => write!(f, "ProbeInit"),
75 RefAction::ProbeDecide { disambiguator } => write!(f, "ProbeDecide({disambiguator})"),
76 RefAction::ProbePhase(n) => write!(f, "ProbePhase({n})"),
77 RefAction::User(_) => write!(f, "User(fn)"),
78 RefAction::Phase(fns) => write!(f, "Phase({} fns)", fns.len()),
79 }
80 }
81}
82
83#[derive(Debug, Clone, Default, PartialEq)]
93pub struct AltSpec {
94 fields: Map<String, Value>,
95 pub m: Option<String>,
96}
97
98impl AltSpec {
99 pub fn new() -> Self {
100 Self::default()
101 }
102
103 pub fn with_tag(tag: &str) -> Self {
105 let mut alt = Self::default();
106 alt.set("g", tag);
107 alt
108 }
109
110 pub fn set(&mut self, key: &str, value: impl Into<Value>) -> &mut Self {
113 self.fields.insert(key.to_string(), value.into());
114 self
115 }
116
117 pub fn remove(&mut self, key: &str) -> Option<Value> {
118 self.fields.shift_remove(key)
119 }
120
121 pub fn get(&self, key: &str) -> Option<&Value> {
122 self.fields.get(key)
123 }
124
125 pub fn contains(&self, key: &str) -> bool {
126 self.fields.contains_key(key)
127 }
128
129 pub fn assign_from(&mut self, other: &AltSpec) -> &mut Self {
132 for (key, value) in &other.fields {
133 self.fields.insert(key.clone(), value.clone());
134 }
135 self
136 }
137
138 fn str_field(&self, key: &str) -> Option<&str> {
139 self.fields.get(key).and_then(Value::as_str)
140 }
141
142 pub fn s(&self) -> Option<&str> {
144 self.str_field("s")
145 }
146
147 pub fn p(&self) -> Option<&str> {
149 self.str_field("p")
150 }
151
152 pub fn r(&self) -> Option<&str> {
154 self.str_field("r")
155 }
156
157 pub fn g(&self) -> Option<&str> {
159 self.str_field("g")
160 }
161
162 pub fn b(&self) -> Option<u64> {
164 self.fields.get("b").and_then(Value::as_u64)
165 }
166
167 pub fn actions(&self) -> Vec<String> {
169 match self.fields.get("a") {
170 Some(Value::String(a)) => vec![a.clone()],
171 Some(Value::Array(list)) => list
172 .iter()
173 .filter_map(|v| v.as_str().map(str::to_string))
174 .collect(),
175 _ => Vec::new(),
176 }
177 }
178
179 pub fn set_actions(&mut self, actions: &[&str]) {
182 match actions {
183 [] => {
184 self.remove("a");
185 }
186 [one] => {
187 self.set("a", *one);
188 }
189 many => {
190 self.set("a", Value::Array(many.iter().map(|s| json!(s)).collect()));
191 }
192 }
193 }
194
195 pub fn append_action(&mut self, added: &str) {
198 let next = match self.fields.get("a") {
199 None | Some(Value::Null) => json!(added),
200 Some(Value::Array(list)) => {
201 let mut out = list.clone();
202 out.push(json!(added));
203 Value::Array(out)
204 }
205 Some(existing) => Value::Array(vec![existing.clone(), json!(added)]),
206 };
207 self.set("a", next);
208 }
209
210 pub fn k(&self) -> Option<&Map<String, Value>> {
212 self.fields.get("k").and_then(Value::as_object)
213 }
214
215 pub fn k_mut(&mut self) -> Option<&mut Map<String, Value>> {
216 self.fields.get_mut("k").and_then(Value::as_object_mut)
217 }
218
219 pub fn to_value(&self) -> Value {
221 Value::Object(self.fields.clone())
222 }
223}
224
225#[derive(Debug, Clone, Default, PartialEq)]
228pub struct RuleSpec {
229 pub open: Vec<AltSpec>,
230 pub close: Option<Vec<AltSpec>>,
231}
232
233impl RuleSpec {
234 pub fn to_value(&self) -> Value {
235 let mut m = Map::new();
236 m.insert(
237 "open".into(),
238 Value::Array(self.open.iter().map(AltSpec::to_value).collect()),
239 );
240 if let Some(close) = &self.close {
241 m.insert(
242 "close".into(),
243 Value::Array(close.iter().map(AltSpec::to_value).collect()),
244 );
245 }
246 Value::Object(m)
247 }
248
249 pub(crate) fn alts_mut(&mut self, phase: &str) -> &mut Vec<AltSpec> {
250 if phase == "open" {
251 &mut self.open
252 } else {
253 self.close.get_or_insert_with(Vec::new)
254 }
255 }
256
257 pub(crate) fn alts(&self, phase: &str) -> &[AltSpec] {
258 if phase == "open" {
259 &self.open
260 } else {
261 self.close.as_deref().unwrap_or(&[])
262 }
263 }
264}
265
266#[derive(Debug, Clone, Default)]
276pub struct GrammarSpec {
277 pub refs: IndexMap<String, RefAction>,
278 pub options: Map<String, Value>,
279 pub rule: IndexMap<String, Option<RuleSpec>>,
280 pub meta: Option<Value>,
282 pub clear: bool,
284}
285
286impl GrammarSpec {
287 fn rules_value(&self) -> Value {
289 let mut m = Map::new();
290 for (name, rule) in &self.rule {
291 m.insert(
292 name.clone(),
293 match rule {
294 Some(r) => r.to_value(),
295 None => Value::Null,
296 },
297 );
298 }
299 Value::Object(m)
300 }
301
302 pub fn to_value(&self) -> Value {
306 let mut m = Map::new();
307 m.insert("options".into(), Value::Object(self.options.clone()));
308 m.insert("rule".into(), self.rules_value());
309 if let Some(meta) = &self.meta {
310 m.insert("meta".into(), meta.clone());
311 }
312 if self.clear {
313 m.insert("clear".into(), json!(true));
314 }
315 Value::Object(m)
316 }
317
318 pub fn to_engine(&self) -> Result<tabnas::GrammarSpec, GrammarError> {
320 tabnas::GrammarSpec::from_value(self.to_value())
321 }
322
323 pub fn has_closures(&self) -> bool {
326 !self.refs.is_empty()
327 }
328
329 pub fn bind(&self, parser: &mut Tabnas) {
333 for (name, action) in &self.refs {
334 bind_ref(parser, name, action);
335 }
336 }
337
338 pub fn install(&self, parser: &mut Tabnas) -> Result<(), GrammarError> {
340 self.bind(parser);
341 let engine = self.to_engine()?;
342 parser.grammar(&engine)?;
343 Ok(())
344 }
345}
346
347fn ast_node(rule: &str, kind: NodeKind) -> tabnas::Value {
348 let mut node = IndexMap::new();
349 if kind == NodeKind::User {
350 node.insert("rule".to_string(), tabnas::Value::String(rule.to_string()));
351 }
352 node.insert("src".to_string(), tabnas::Value::String(String::new()));
353 node.insert("kids".to_string(), tabnas::Value::array(Vec::new()));
354 tabnas::Value::object(node)
355}
356
357fn append_src(node: &mut IndexMap<String, tabnas::Value>, source: &str) {
358 if let Some(tabnas::Value::String(current)) = node.get_mut("src") {
359 current.push_str(source);
360 }
361}
362
363fn append_kid(node: &mut IndexMap<String, tabnas::Value>, child: tabnas::Value) {
364 if let Some(kids) = node.get_mut("kids").and_then(tabnas::Value::as_array_mut) {
365 kids.push(child);
366 }
367}
368
369fn capture_child(node: &mut IndexMap<String, tabnas::Value>, child: tabnas::Value) {
373 if let tabnas::Value::Object(child_map) = &child {
374 if let Some(tabnas::Value::String(source)) = child_map.get("src") {
375 append_src(node, source);
376 if child_map
377 .get("rule")
378 .is_some_and(|v| !matches!(v, tabnas::Value::String(r) if r.is_empty()))
379 {
380 append_kid(node, child);
381 } else if let Some(tabnas::Value::Array(children)) = child_map.get("kids") {
382 for nested in children.iter() {
383 append_kid(node, nested.clone());
384 }
385 }
386 return;
387 }
388 }
389 append_kid(node, child);
391}
392
393fn phase_of(rule: &Rule) -> u8 {
394 match rule.k.get("pd_phase") {
395 Some(tabnas::Value::Number(n)) => *n as u8,
396 _ => 0,
397 }
398}
399
400fn bind_ref(parser: &mut Tabnas, name: &str, action: &RefAction) {
404 match action.clone() {
405 RefAction::Node {
406 init,
407 rule,
408 kind,
409 nterms,
410 } => {
411 parser.action(name, move |r: &mut Rule| {
412 if init {
413 r.node = Rc::new(RefCell::new(ast_node(&rule, kind)));
414 }
415 let sources: Vec<String> =
416 r.o.iter().take(nterms).map(|t| t.src.to_string()).collect();
417 if let Some(node) = r.node.borrow_mut().as_object_mut() {
418 for src in &sources {
419 append_src(node, src);
420 }
421 }
422 });
423 }
424 RefAction::Capture { rule, kind } => {
425 parser.action(name, move |r: &mut Rule| {
426 if r.node.borrow().is_undefined() {
427 r.node = Rc::new(RefCell::new(ast_node(&rule, kind)));
428 }
429 if r.child_node.is_undefined() {
430 return;
431 }
432 let child = r.child_node.clone();
433 if let Some(node) = r.node.borrow_mut().as_object_mut() {
434 capture_child(node, child);
435 }
436 });
437 }
438 RefAction::Bubble => {
439 parser.action(name, |r: &mut Rule| {
440 if !r.child_node.is_undefined() {
441 r.node = Rc::new(RefCell::new(r.child_node.clone()));
442 }
443 });
444 }
445 RefAction::Fold { c_n } => {
446 parser.action(name, move |r: &mut Rule| {
447 if let Some(parent_node) = r.parent_node.clone() {
448 let same_node = Rc::ptr_eq(&parent_node, &r.node);
449 let own = r.node.borrow().clone();
450 let closes: Vec<String> =
451 r.c.iter().take(c_n).map(|t| t.src.to_string()).collect();
452 if let Some(parent) = parent_node.borrow_mut().as_object_mut() {
453 if parent.contains_key("src") {
454 if !same_node {
455 if let tabnas::Value::Object(own_map) = &own {
456 if own_map.contains_key("src") {
457 capture_child(parent, own);
458 }
459 }
460 }
461 for src in &closes {
462 append_src(parent, src);
463 }
464 }
465 }
466 }
467 r.node = Rc::new(RefCell::new(tabnas::Value::Undefined));
468 });
469 }
470 RefAction::ProbeInit => {
471 parser.action_with_context(name, |r: &mut Rule, ctx: &mut Context| {
472 r.k_mut()
473 .insert("pd_phase".into(), tabnas::Value::Number(0.0));
474 let mark = tabnas::Value::Number(ctx.mark() as f64);
475 r.k_mut().insert("pd_mark".into(), mark);
476 ctx.probe_open(r);
480 Ok(())
481 });
482 }
483 RefAction::ProbeDecide { disambiguator } => {
484 parser.action_with_context(name, move |r: &mut Rule, ctx: &mut Context| {
485 let peek = ctx.t0().map(|t| t.name.to_string());
488 let mark = match r.k.get("pd_mark") {
489 Some(tabnas::Value::Number(m)) => *m as usize,
490 _ => ctx.mark(),
491 };
492 ctx.rewind(mark)?;
493 let matched = peek.as_deref() == Some(disambiguator.as_str());
494 r.k_mut().insert(
495 "pd_phase".into(),
496 tabnas::Value::Number(if matched { 1.0 } else { 2.0 }),
497 );
498 ctx.probe_close();
502 Ok(())
503 });
504 }
505 RefAction::ProbePhase(phase) => {
506 parser.alt_condition(name, move |r: &mut Rule, _ctx: &mut Context| {
507 phase_of(r) == phase
508 });
509 }
510 RefAction::User(f) => {
511 parser.action_with_context(name, move |r: &mut Rule, ctx: &mut Context| f(r, ctx));
512 }
513 RefAction::Phase(fns) => {
514 parser.state_action_ref(name, move |r: &mut Rule, ctx: &mut Context| {
515 for f in &fns {
516 f(r, ctx)?;
517 }
518 Ok(())
519 });
520 }
521 }
522}
523
524#[derive(Debug, Clone, PartialEq, Eq)]
526pub struct CompileError {
527 pub message: String,
528 pub rules: Vec<String>,
529}
530
531impl fmt::Display for CompileError {
532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533 f.write_str(&self.message)
534 }
535}
536
537impl std::error::Error for CompileError {}
538
539const REF_FIELDS: [&str; 3] = ["a", "bo", "bc"];
542
543const TREE_BUILTINS: [&str; 11] = [
548 "@node$",
549 "@capture$",
550 "@bubble$",
551 "@fold$",
552 "@object$",
553 "@array$",
554 "@reset$",
555 "@key$",
556 "@setval$",
557 "@push$",
558 "@value$",
559];
560const TREE_CONFIG_KEYS: [&str; 9] = [
561 "node$", "capture$", "fold$", "object$", "array$", "key$", "setval$", "push$", "value$",
562];
563
564fn clone_recognition(v: &Value, is_dropped: &dyn Fn(&str) -> bool) -> Value {
568 match v {
569 Value::Array(items) => Value::Array(
570 items
571 .iter()
572 .map(|x| clone_recognition(x, is_dropped))
573 .collect(),
574 ),
575 Value::Object(map) => {
576 let mut o = Map::new();
577 for (k, x) in map {
578 if REF_FIELDS.contains(&k.as_str()) {
579 match x {
580 Value::String(s) => {
581 if is_dropped(s) {
582 continue;
583 }
584 }
585 Value::Array(list) => {
586 let kept: Vec<Value> = list
590 .iter()
591 .filter(|e| !matches!(e, Value::String(s) if is_dropped(s)))
592 .cloned()
593 .collect();
594 if kept.is_empty() {
595 continue;
596 }
597 o.insert(
598 k.clone(),
599 if kept.len() == 1 {
600 kept[0].clone()
601 } else {
602 Value::Array(kept)
603 },
604 );
605 continue;
606 }
607 _ => {}
608 }
609 }
610 if k == "k" {
611 if let Value::Object(_) = x {
612 let kc = clone_recognition(x, is_dropped);
613 let Value::Object(mut kc) = kc else {
614 unreachable!()
615 };
616 for tk in TREE_CONFIG_KEYS {
617 kc.remove(tk);
618 }
619 if kc.is_empty() {
620 continue;
621 }
622 o.insert(k.clone(), Value::Object(kc));
623 continue;
624 }
625 }
626 o.insert(k.clone(), clone_recognition(x, is_dropped));
627 }
628 Value::Object(o)
629 }
630 _ => v.clone(),
631 }
632}
633
634fn control_ref_rules(rules: &Value, is_ref: &dyn Fn(&str) -> bool) -> Vec<String> {
639 fn scan(o: &Value, rule: &str, is_ref: &dyn Fn(&str) -> bool, offenders: &mut Vec<String>) {
640 match o {
641 Value::Array(items) => {
642 for x in items {
643 scan(x, rule, is_ref, offenders);
644 }
645 }
646 Value::Object(map) => {
647 for (k, x) in map {
648 match x {
649 Value::String(s) if !REF_FIELDS.contains(&k.as_str()) && is_ref(s) => {
650 if !offenders.iter().any(|r| r == rule) {
651 offenders.push(rule.to_string());
652 }
653 }
654 _ => scan(x, rule, is_ref, offenders),
655 }
656 }
657 }
658 _ => {}
659 }
660 }
661 let mut offenders: Vec<String> = Vec::new();
662 if let Value::Object(rules) = rules {
663 for (name, spec) in rules {
664 scan(spec, name, is_ref, &mut offenders);
665 }
666 }
667 offenders.sort_by_key(|s| s.encode_utf16().collect::<Vec<u16>>());
668 offenders
669}
670
671fn carry_meta(from: &GrammarSpec, to: &mut Map<String, Value>) {
672 if let Some(meta) = &from.meta {
673 to.insert("meta".into(), meta.clone());
674 }
675}
676
677pub fn to_recognition_spec(spec: &GrammarSpec) -> Result<Value, CompileError> {
682 let is_ref = |s: &str| spec.refs.contains_key(s);
683 let rules = spec.rules_value();
684 let offenders = control_ref_rules(&rules, &is_ref);
685 if !offenders.is_empty() {
686 return Err(CompileError {
687 message: format!(
688 "{}: grammar needs control functions (probe / unbounded lookahead) and \
689 cannot be emitted as a pure recognition grammar; recompile with \
690 `builtins: true`. Offending rule(s): {}",
691 diag_name(),
692 offenders.join(", ")
693 ),
694 rules: offenders,
695 });
696 }
697 let is_dropped = |s: &str| is_ref(s) || TREE_BUILTINS.contains(&s);
698 let mut doc = Map::new();
699 doc.insert("options".into(), Value::Object(spec.options.clone()));
700 doc.insert("rule".into(), rules);
701 let out = clone_recognition(&Value::Object(doc), &is_dropped);
702 let Value::Object(mut out) = out else {
703 unreachable!()
704 };
705 out.insert("v".into(), json!(tabnas::grammar::BUILTIN_SCHEMA_VERSION));
708 carry_meta(spec, &mut out);
709 Ok(Value::Object(out))
710}
711
712pub fn to_pure_spec(spec: &GrammarSpec) -> Result<Value, CompileError> {
716 if !spec.refs.is_empty() {
717 let closures: Vec<&str> = spec.refs.keys().map(String::as_str).take(3).collect();
718 return Err(CompileError {
719 message: format!(
720 "{}: spec still contains closures; convert with `builtins: true` for \
721 pure-data output. Stray ref(s): {}",
722 diag_name(),
723 closures.join(", ")
724 ),
725 rules: Vec::new(),
726 });
727 }
728 let mut out = Map::new();
729 out.insert("options".into(), Value::Object(spec.options.clone()));
730 out.insert("rule".into(), spec.rules_value());
731 out.insert("v".into(), json!(tabnas::grammar::BUILTIN_SCHEMA_VERSION));
732 carry_meta(spec, &mut out);
733 Ok(Value::Object(out))
734}
735
736#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
738pub struct JsonicOptions {
739 pub strict: bool,
742 pub indent: Option<usize>,
744}
745
746fn is_ident(k: &str) -> bool {
747 let mut chars = k.chars();
748 match chars.next() {
749 Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
750 _ => return false,
751 }
752 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
753}
754
755const JS_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
758
759fn js_number(f: f64) -> String {
773 if f.is_nan() {
774 return "NaN".to_string();
775 }
776 if f.is_infinite() {
777 return if f > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
778 }
779 if f == 0.0 {
781 return "0".to_string();
782 }
783 let magnitude = f.abs();
784 let (digits, exponent) = (0..17u32)
793 .map(|p| format!("{magnitude:.*e}", p as usize))
794 .find(|text| text.parse::<f64>() == Ok(magnitude))
795 .map(|text| {
796 let (mantissa, exponent) = text.split_once('e').expect("{:e} emits an exponent");
797 (
798 mantissa.chars().filter(|c| *c != '.').collect::<String>(),
799 exponent
800 .parse::<i32>()
801 .expect("{:e} emits an integer exponent"),
802 )
803 })
804 .expect("17 significant digits round-trip every finite f64");
805 let k = digits.len() as i32;
806 let n = exponent + 1;
807
808 let body = if k <= n && n <= 21 {
809 format!("{}{}", digits, "0".repeat((n - k) as usize))
811 } else if 0 < n && n <= 21 {
812 format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
814 } else if -6 < n && n <= 0 {
815 format!("0.{}{}", "0".repeat(-n as usize), digits)
817 } else {
818 let e = n - 1;
820 let head = if k == 1 {
821 digits.clone()
822 } else {
823 format!("{}.{}", &digits[..1], &digits[1..])
824 };
825 format!("{}e{}{}", head, if e < 0 { '-' } else { '+' }, e.abs())
826 };
827 if f < 0.0 {
828 format!("-{body}")
829 } else {
830 body
831 }
832}
833
834pub fn to_jsonic(value: &Value, opts: JsonicOptions) -> String {
837 let strict = opts.strict;
838 let ind = opts.indent.unwrap_or(2);
839 let sep = if strict { ",\n" } else { "\n" };
840 let pad = |n: usize| " ".repeat(ind * n);
841
842 fn quote(s: &str, ch: char) -> String {
845 let mut out = String::with_capacity(s.len() + 2);
846 out.push(ch);
847 for c in s.chars() {
848 match c {
849 '\\' => out.push_str("\\\\"),
850 c if c == ch => {
851 out.push('\\');
852 out.push(ch);
853 }
854 '\u{8}' => out.push_str("\\b"),
855 '\t' => out.push_str("\\t"),
856 '\n' => out.push_str("\\n"),
857 '\u{c}' => out.push_str("\\f"),
858 '\r' => out.push_str("\\r"),
859 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
860 c => out.push(c),
861 }
862 }
863 out.push(ch);
864 out
865 }
866 let str_ = |s: &str| {
867 if strict {
868 quote(s, '"')
869 } else {
870 quote(s, '\'')
871 }
872 };
873 let key = |k: &str| {
874 if !strict && is_ident(k) {
875 k.to_string()
876 } else {
877 quote(k, '"')
878 }
879 };
880
881 fn number(n: &serde_json::Number) -> String {
882 if let Some(i) = n.as_i64() {
887 if i.unsigned_abs() <= JS_SAFE_INTEGER {
888 return i.to_string();
889 }
890 return js_number(i as f64);
891 }
892 if let Some(u) = n.as_u64() {
893 if u <= JS_SAFE_INTEGER {
894 return u.to_string();
895 }
896 return js_number(u as f64);
897 }
898 js_number(n.as_f64().unwrap_or(0.0))
899 }
900
901 fn ser(
902 v: &Value,
903 depth: usize,
904 sep: &str,
905 pad: &dyn Fn(usize) -> String,
906 str_: &dyn Fn(&str) -> String,
907 key: &dyn Fn(&str) -> String,
908 ) -> String {
909 match v {
910 Value::Null => "null".into(),
911 Value::Bool(b) => b.to_string(),
912 Value::Number(n) => number(n),
913 Value::String(s) => str_(s),
914 Value::Array(items) => {
915 if items.is_empty() {
916 return "[]".into();
917 }
918 let lines: Vec<String> = items
919 .iter()
920 .map(|x| {
921 format!(
922 "{}{}",
923 pad(depth + 1),
924 ser(x, depth + 1, sep, pad, str_, key)
925 )
926 })
927 .collect();
928 format!("[\n{}\n{}]", lines.join(sep), pad(depth))
929 }
930 Value::Object(map) => {
931 if map.is_empty() {
932 return "{}".into();
933 }
934 let lines: Vec<String> = map
935 .iter()
936 .map(|(k, x)| {
937 format!(
938 "{}{}: {}",
939 pad(depth + 1),
940 key(k),
941 ser(x, depth + 1, sep, pad, str_, key)
942 )
943 })
944 .collect();
945 format!("{{\n{}\n{}}}", lines.join(sep), pad(depth))
946 }
947 }
948 }
949
950 ser(value, 0, sep, &pad, &str_, &key)
951}
952
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
955pub struct CompileOptions {
956 pub recognition: bool,
960 pub strict: bool,
961 pub indent: Option<usize>,
962}
963
964impl Default for CompileOptions {
965 fn default() -> Self {
966 Self {
967 recognition: true,
968 strict: false,
969 indent: None,
970 }
971 }
972}
973
974pub fn compile_spec(spec: &GrammarSpec, opts: CompileOptions) -> Result<String, CompileError> {
978 let out = if opts.recognition {
979 to_recognition_spec(spec)?
980 } else {
981 to_pure_spec(spec)?
982 };
983 Ok(to_jsonic(
984 &out,
985 JsonicOptions {
986 strict: opts.strict,
987 indent: opts.indent,
988 },
989 ))
990}
991
992#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct ActionError {
995 pub message: String,
996}
997
998impl fmt::Display for ActionError {
999 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1000 f.write_str(&self.message)
1001 }
1002}
1003
1004impl std::error::Error for ActionError {}
1005
1006enum Target {
1007 Phase(String),
1008 Alts { phase: String, indices: Vec<usize> },
1009}
1010
1011const PHASES: [&str; 4] = ["bo", "ao", "bc", "ac"];
1012
1013fn resolve_target(spec: &GrammarSpec, key: &str) -> Result<(String, Target), ActionError> {
1016 if key.contains('$') {
1019 return Err(ActionError {
1020 message: format!(
1021 "{}: '$' is reserved for engine builtins; user action ref '{}' may not contain '$'",
1022 diag_name(),
1023 key
1024 ),
1025 });
1026 }
1027 let malformed = || ActionError {
1028 message: format!(
1029 "{}: malformed action ref '{}' (expected @rule:phase or @rule:o|c:mark)",
1030 diag_name(),
1031 key
1032 ),
1033 };
1034 let body = key.strip_prefix('@').ok_or_else(malformed)?;
1035 let (rule, sel) = body.split_once(':').ok_or_else(malformed)?;
1036 if rule.is_empty() || sel.is_empty() {
1037 return Err(malformed());
1038 }
1039 let Some(Some(rs)) = spec.rule.get(rule) else {
1040 return Err(ActionError {
1041 message: format!(
1042 "{}: action ref '{}' targets unknown rule '{}'",
1043 diag_name(),
1044 key,
1045 rule
1046 ),
1047 });
1048 };
1049 if PHASES.contains(&sel) {
1050 return Ok((rule.to_string(), Target::Phase(sel.to_string())));
1051 }
1052 let (oc, mark) = match sel.split_once(':') {
1053 Some((oc @ ("o" | "c"), mark)) if !mark.is_empty() => (oc, mark),
1054 _ => {
1055 return Err(ActionError {
1056 message: format!("{}: malformed action ref '{}'", diag_name(), key),
1057 })
1058 }
1059 };
1060 let phase = if oc == "o" { "open" } else { "close" };
1061 let indices: Vec<usize> = rs
1062 .alts(phase)
1063 .iter()
1064 .enumerate()
1065 .filter(|(_, a)| a.m.as_deref() == Some(mark))
1066 .map(|(i, _)| i)
1067 .collect();
1068 if indices.is_empty() {
1069 return Err(ActionError {
1070 message: format!(
1071 "{}: action ref '{}' matches no {} alt with mark '{}' in rule '{}'",
1072 diag_name(),
1073 key,
1074 phase,
1075 mark,
1076 rule
1077 ),
1078 });
1079 }
1080 Ok((
1081 rule.to_string(),
1082 Target::Alts {
1083 phase: phase.to_string(),
1084 indices,
1085 },
1086 ))
1087}
1088
1089pub fn attach_actions(spec: &mut GrammarSpec, actions: ActionsMap) -> Result<(), ActionError> {
1095 let mut counter = 0;
1098 while spec.refs.contains_key(&format!("@bnf_user{counter}")) {
1099 counter += 1;
1100 }
1101
1102 for (key, fns) in actions {
1103 let (rule, target) = resolve_target(spec, &key)?;
1104 match target {
1105 Target::Phase(phase) => {
1106 let fkey = format!("@{rule}-{phase}");
1109 match spec.refs.get_mut(&fkey) {
1110 Some(RefAction::Phase(existing)) => existing.extend(fns),
1111 _ => {
1112 spec.refs.insert(fkey, RefAction::Phase(fns));
1113 }
1114 }
1115 }
1116 Target::Alts { phase, indices } => {
1117 let fns_arc: Vec<ActionFn> = fns;
1118 let seq: ActionFn = if fns_arc.len() == 1 {
1119 fns_arc[0].clone()
1120 } else {
1121 Arc::new(move |r: &mut Rule, ctx: &mut Context| {
1122 for f in &fns_arc {
1123 f(r, ctx)?;
1124 }
1125 Ok(())
1126 })
1127 };
1128 for i in indices {
1129 let user_ref = format!("@bnf_user{counter}");
1130 counter += 1;
1131 spec.refs
1132 .insert(user_ref.clone(), RefAction::User(seq.clone()));
1133 let rs = spec
1134 .rule
1135 .get_mut(&rule)
1136 .and_then(Option::as_mut)
1137 .expect("resolved above");
1138 rs.alts_mut(&phase)[i].append_action(&user_ref);
1139 }
1140 }
1141 }
1142 }
1143 Ok(())
1144}
1145
1146pub fn attach_action_slots(spec: &mut GrammarSpec, ref_names: &[&str]) -> Result<(), ActionError> {
1152 for name in ref_names {
1153 let (rule, target) = resolve_target(spec, name)?;
1154 match target {
1155 Target::Phase(_) => {
1156 return Err(ActionError {
1157 message: format!(
1158 "{}: slot '{}' is a rule-phase ref; slots are for @rule:o|c:mark alt actions",
1159 diag_name(),
1160 name
1161 ),
1162 })
1163 }
1164 Target::Alts { phase, indices } => {
1165 let rs = spec
1166 .rule
1167 .get_mut(&rule)
1168 .and_then(Option::as_mut)
1169 .expect("resolved above");
1170 for i in indices {
1171 rs.alts_mut(&phase)[i].append_action(name);
1172 }
1173 }
1174 }
1175 }
1176 Ok(())
1177}
1178
1179pub fn mark_listing(spec: &GrammarSpec) -> String {
1182 let mut lines: Vec<String> = Vec::new();
1183 for (rule, entry) in &spec.rule {
1184 let Some(entry) = entry else { continue };
1186 for (phase, sym) in [("open", "o"), ("close", "c")] {
1187 for a in entry.alts(phase) {
1188 let Some(m) = &a.m else { continue };
1189 let what = match (a.s(), a.p()) {
1190 (Some(s), _) if !s.is_empty() => format!("s:{s}"),
1191 (_, Some(p)) if !p.is_empty() => format!("p:{p}"),
1192 _ => "(empty)".to_string(),
1193 };
1194 lines.push(format!("{rule} {sym}:{m} {what}"));
1195 }
1196 }
1197 }
1198 lines.join("\n")
1199}