use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use std::sync::Arc;
use indexmap::IndexMap;
use serde_json::{json, Map, Value};
use tabnas::{Context, GrammarError, Rule, Tabnas};
use crate::ir::{diag_name, NodeKind};
pub type ActionFn =
Arc<dyn Fn(&mut Rule, &mut Context) -> Result<(), tabnas::ActionError> + Send + Sync>;
pub type ActionsMap = Vec<(String, Vec<ActionFn>)>;
#[derive(Clone)]
pub enum RefAction {
Node {
init: bool,
rule: String,
kind: NodeKind,
nterms: usize,
},
Capture { rule: String, kind: NodeKind },
Bubble,
Fold { c_n: usize },
ProbeInit,
ProbeDecide { disambiguator: String },
ProbePhase(u8),
User(ActionFn),
Phase(Vec<ActionFn>),
}
impl fmt::Debug for RefAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RefAction::Node {
init,
rule,
kind,
nterms,
} => write!(f, "Node({init}, {rule}, {}, {nterms})", kind.as_str()),
RefAction::Capture { rule, kind } => write!(f, "Capture({rule}, {})", kind.as_str()),
RefAction::Bubble => write!(f, "Bubble"),
RefAction::Fold { c_n } => write!(f, "Fold({c_n})"),
RefAction::ProbeInit => write!(f, "ProbeInit"),
RefAction::ProbeDecide { disambiguator } => write!(f, "ProbeDecide({disambiguator})"),
RefAction::ProbePhase(n) => write!(f, "ProbePhase({n})"),
RefAction::User(_) => write!(f, "User(fn)"),
RefAction::Phase(fns) => write!(f, "Phase({} fns)", fns.len()),
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AltSpec {
fields: Map<String, Value>,
pub m: Option<String>,
}
impl AltSpec {
pub fn new() -> Self {
Self::default()
}
pub fn with_tag(tag: &str) -> Self {
let mut alt = Self::default();
alt.set("g", tag);
alt
}
pub fn set(&mut self, key: &str, value: impl Into<Value>) -> &mut Self {
self.fields.insert(key.to_string(), value.into());
self
}
pub fn remove(&mut self, key: &str) -> Option<Value> {
self.fields.shift_remove(key)
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.fields.get(key)
}
pub fn contains(&self, key: &str) -> bool {
self.fields.contains_key(key)
}
pub fn assign_from(&mut self, other: &AltSpec) -> &mut Self {
for (key, value) in &other.fields {
self.fields.insert(key.clone(), value.clone());
}
self
}
fn str_field(&self, key: &str) -> Option<&str> {
self.fields.get(key).and_then(Value::as_str)
}
pub fn s(&self) -> Option<&str> {
self.str_field("s")
}
pub fn p(&self) -> Option<&str> {
self.str_field("p")
}
pub fn r(&self) -> Option<&str> {
self.str_field("r")
}
pub fn g(&self) -> Option<&str> {
self.str_field("g")
}
pub fn b(&self) -> Option<u64> {
self.fields.get("b").and_then(Value::as_u64)
}
pub fn actions(&self) -> Vec<String> {
match self.fields.get("a") {
Some(Value::String(a)) => vec![a.clone()],
Some(Value::Array(list)) => list
.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect(),
_ => Vec::new(),
}
}
pub fn set_actions(&mut self, actions: &[&str]) {
match actions {
[] => {
self.remove("a");
}
[one] => {
self.set("a", *one);
}
many => {
self.set("a", Value::Array(many.iter().map(|s| json!(s)).collect()));
}
}
}
pub fn append_action(&mut self, added: &str) {
let next = match self.fields.get("a") {
None | Some(Value::Null) => json!(added),
Some(Value::Array(list)) => {
let mut out = list.clone();
out.push(json!(added));
Value::Array(out)
}
Some(existing) => Value::Array(vec![existing.clone(), json!(added)]),
};
self.set("a", next);
}
pub fn k(&self) -> Option<&Map<String, Value>> {
self.fields.get("k").and_then(Value::as_object)
}
pub fn k_mut(&mut self) -> Option<&mut Map<String, Value>> {
self.fields.get_mut("k").and_then(Value::as_object_mut)
}
pub fn to_value(&self) -> Value {
Value::Object(self.fields.clone())
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RuleSpec {
pub open: Vec<AltSpec>,
pub close: Option<Vec<AltSpec>>,
}
impl RuleSpec {
pub fn to_value(&self) -> Value {
let mut m = Map::new();
m.insert(
"open".into(),
Value::Array(self.open.iter().map(AltSpec::to_value).collect()),
);
if let Some(close) = &self.close {
m.insert(
"close".into(),
Value::Array(close.iter().map(AltSpec::to_value).collect()),
);
}
Value::Object(m)
}
pub(crate) fn alts_mut(&mut self, phase: &str) -> &mut Vec<AltSpec> {
if phase == "open" {
&mut self.open
} else {
self.close.get_or_insert_with(Vec::new)
}
}
pub(crate) fn alts(&self, phase: &str) -> &[AltSpec] {
if phase == "open" {
&self.open
} else {
self.close.as_deref().unwrap_or(&[])
}
}
}
#[derive(Debug, Clone, Default)]
pub struct GrammarSpec {
pub refs: IndexMap<String, RefAction>,
pub options: Map<String, Value>,
pub rule: IndexMap<String, Option<RuleSpec>>,
pub meta: Option<Value>,
pub clear: bool,
}
impl GrammarSpec {
fn rules_value(&self) -> Value {
let mut m = Map::new();
for (name, rule) in &self.rule {
m.insert(
name.clone(),
match rule {
Some(r) => r.to_value(),
None => Value::Null,
},
);
}
Value::Object(m)
}
pub fn to_value(&self) -> Value {
let mut m = Map::new();
m.insert("options".into(), Value::Object(self.options.clone()));
m.insert("rule".into(), self.rules_value());
if let Some(meta) = &self.meta {
m.insert("meta".into(), meta.clone());
}
if self.clear {
m.insert("clear".into(), json!(true));
}
Value::Object(m)
}
pub fn to_engine(&self) -> Result<tabnas::GrammarSpec, GrammarError> {
tabnas::GrammarSpec::from_value(self.to_value())
}
pub fn has_closures(&self) -> bool {
!self.refs.is_empty()
}
pub fn bind(&self, parser: &mut Tabnas) {
for (name, action) in &self.refs {
bind_ref(parser, name, action);
}
}
pub fn install(&self, parser: &mut Tabnas) -> Result<(), GrammarError> {
self.bind(parser);
let engine = self.to_engine()?;
parser.grammar(&engine)?;
Ok(())
}
}
fn ast_node(rule: &str, kind: NodeKind) -> tabnas::Value {
let mut node = IndexMap::new();
if kind == NodeKind::User {
node.insert("rule".to_string(), tabnas::Value::String(rule.to_string()));
}
node.insert("src".to_string(), tabnas::Value::String(String::new()));
node.insert("kids".to_string(), tabnas::Value::array(Vec::new()));
tabnas::Value::object(node)
}
fn append_src(node: &mut IndexMap<String, tabnas::Value>, source: &str) {
if let Some(tabnas::Value::String(current)) = node.get_mut("src") {
current.push_str(source);
}
}
fn append_kid(node: &mut IndexMap<String, tabnas::Value>, child: tabnas::Value) {
if let Some(kids) = node.get_mut("kids").and_then(tabnas::Value::as_array_mut) {
kids.push(child);
}
}
fn capture_child(node: &mut IndexMap<String, tabnas::Value>, child: tabnas::Value) {
if let tabnas::Value::Object(child_map) = &child {
if let Some(tabnas::Value::String(source)) = child_map.get("src") {
append_src(node, source);
if child_map
.get("rule")
.is_some_and(|v| !matches!(v, tabnas::Value::String(r) if r.is_empty()))
{
append_kid(node, child);
} else if let Some(tabnas::Value::Array(children)) = child_map.get("kids") {
for nested in children.iter() {
append_kid(node, nested.clone());
}
}
return;
}
}
append_kid(node, child);
}
fn phase_of(rule: &Rule) -> u8 {
match rule.k.get("pd_phase") {
Some(tabnas::Value::Number(n)) => *n as u8,
_ => 0,
}
}
fn bind_ref(parser: &mut Tabnas, name: &str, action: &RefAction) {
match action.clone() {
RefAction::Node {
init,
rule,
kind,
nterms,
} => {
parser.action(name, move |r: &mut Rule| {
if init {
r.node = Rc::new(RefCell::new(ast_node(&rule, kind)));
}
let sources: Vec<String> =
r.o.iter().take(nterms).map(|t| t.src.to_string()).collect();
if let Some(node) = r.node.borrow_mut().as_object_mut() {
for src in &sources {
append_src(node, src);
}
}
});
}
RefAction::Capture { rule, kind } => {
parser.action(name, move |r: &mut Rule| {
if r.node.borrow().is_undefined() {
r.node = Rc::new(RefCell::new(ast_node(&rule, kind)));
}
if r.child_node.is_undefined() {
return;
}
let child = r.child_node.clone();
if let Some(node) = r.node.borrow_mut().as_object_mut() {
capture_child(node, child);
}
});
}
RefAction::Bubble => {
parser.action(name, |r: &mut Rule| {
if !r.child_node.is_undefined() {
r.node = Rc::new(RefCell::new(r.child_node.clone()));
}
});
}
RefAction::Fold { c_n } => {
parser.action(name, move |r: &mut Rule| {
if let Some(parent_node) = r.parent_node.clone() {
let same_node = Rc::ptr_eq(&parent_node, &r.node);
let own = r.node.borrow().clone();
let closes: Vec<String> =
r.c.iter().take(c_n).map(|t| t.src.to_string()).collect();
if let Some(parent) = parent_node.borrow_mut().as_object_mut() {
if parent.contains_key("src") {
if !same_node {
if let tabnas::Value::Object(own_map) = &own {
if own_map.contains_key("src") {
capture_child(parent, own);
}
}
}
for src in &closes {
append_src(parent, src);
}
}
}
}
r.node = Rc::new(RefCell::new(tabnas::Value::Undefined));
});
}
RefAction::ProbeInit => {
parser.action_with_context(name, |r: &mut Rule, ctx: &mut Context| {
r.k_mut()
.insert("pd_phase".into(), tabnas::Value::Number(0.0));
let mark = tabnas::Value::Number(ctx.mark() as f64);
r.k_mut().insert("pd_mark".into(), mark);
ctx.probe_open(r);
Ok(())
});
}
RefAction::ProbeDecide { disambiguator } => {
parser.action_with_context(name, move |r: &mut Rule, ctx: &mut Context| {
let peek = ctx.t0().map(|t| t.name.to_string());
let mark = match r.k.get("pd_mark") {
Some(tabnas::Value::Number(m)) => *m as usize,
_ => ctx.mark(),
};
ctx.rewind(mark)?;
let matched = peek.as_deref() == Some(disambiguator.as_str());
r.k_mut().insert(
"pd_phase".into(),
tabnas::Value::Number(if matched { 1.0 } else { 2.0 }),
);
ctx.probe_close();
Ok(())
});
}
RefAction::ProbePhase(phase) => {
parser.alt_condition(name, move |r: &mut Rule, _ctx: &mut Context| {
phase_of(r) == phase
});
}
RefAction::User(f) => {
parser.action_with_context(name, move |r: &mut Rule, ctx: &mut Context| f(r, ctx));
}
RefAction::Phase(fns) => {
parser.state_action_ref(name, move |r: &mut Rule, ctx: &mut Context| {
for f in &fns {
f(r, ctx)?;
}
Ok(())
});
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileError {
pub message: String,
pub rules: Vec<String>,
}
impl fmt::Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for CompileError {}
const REF_FIELDS: [&str; 3] = ["a", "bo", "bc"];
const TREE_BUILTINS: [&str; 11] = [
"@node$",
"@capture$",
"@bubble$",
"@fold$",
"@object$",
"@array$",
"@reset$",
"@key$",
"@setval$",
"@push$",
"@value$",
];
const TREE_CONFIG_KEYS: [&str; 9] = [
"node$", "capture$", "fold$", "object$", "array$", "key$", "setval$", "push$", "value$",
];
fn clone_recognition(v: &Value, is_dropped: &dyn Fn(&str) -> bool) -> Value {
match v {
Value::Array(items) => Value::Array(
items
.iter()
.map(|x| clone_recognition(x, is_dropped))
.collect(),
),
Value::Object(map) => {
let mut o = Map::new();
for (k, x) in map {
if REF_FIELDS.contains(&k.as_str()) {
match x {
Value::String(s) => {
if is_dropped(s) {
continue;
}
}
Value::Array(list) => {
let kept: Vec<Value> = list
.iter()
.filter(|e| !matches!(e, Value::String(s) if is_dropped(s)))
.cloned()
.collect();
if kept.is_empty() {
continue;
}
o.insert(
k.clone(),
if kept.len() == 1 {
kept[0].clone()
} else {
Value::Array(kept)
},
);
continue;
}
_ => {}
}
}
if k == "k" {
if let Value::Object(_) = x {
let kc = clone_recognition(x, is_dropped);
let Value::Object(mut kc) = kc else {
unreachable!()
};
for tk in TREE_CONFIG_KEYS {
kc.remove(tk);
}
if kc.is_empty() {
continue;
}
o.insert(k.clone(), Value::Object(kc));
continue;
}
}
o.insert(k.clone(), clone_recognition(x, is_dropped));
}
Value::Object(o)
}
_ => v.clone(),
}
}
fn control_ref_rules(rules: &Value, is_ref: &dyn Fn(&str) -> bool) -> Vec<String> {
fn scan(o: &Value, rule: &str, is_ref: &dyn Fn(&str) -> bool, offenders: &mut Vec<String>) {
match o {
Value::Array(items) => {
for x in items {
scan(x, rule, is_ref, offenders);
}
}
Value::Object(map) => {
for (k, x) in map {
match x {
Value::String(s) if !REF_FIELDS.contains(&k.as_str()) && is_ref(s) => {
if !offenders.iter().any(|r| r == rule) {
offenders.push(rule.to_string());
}
}
_ => scan(x, rule, is_ref, offenders),
}
}
}
_ => {}
}
}
let mut offenders: Vec<String> = Vec::new();
if let Value::Object(rules) = rules {
for (name, spec) in rules {
scan(spec, name, is_ref, &mut offenders);
}
}
offenders.sort_by_key(|s| s.encode_utf16().collect::<Vec<u16>>());
offenders
}
fn carry_meta(from: &GrammarSpec, to: &mut Map<String, Value>) {
if let Some(meta) = &from.meta {
to.insert("meta".into(), meta.clone());
}
}
pub fn to_recognition_spec(spec: &GrammarSpec) -> Result<Value, CompileError> {
let is_ref = |s: &str| spec.refs.contains_key(s);
let rules = spec.rules_value();
let offenders = control_ref_rules(&rules, &is_ref);
if !offenders.is_empty() {
return Err(CompileError {
message: format!(
"{}: grammar needs control functions (probe / unbounded lookahead) and \
cannot be emitted as a pure recognition grammar; recompile with \
`builtins: true`. Offending rule(s): {}",
diag_name(),
offenders.join(", ")
),
rules: offenders,
});
}
let is_dropped = |s: &str| is_ref(s) || TREE_BUILTINS.contains(&s);
let mut doc = Map::new();
doc.insert("options".into(), Value::Object(spec.options.clone()));
doc.insert("rule".into(), rules);
let out = clone_recognition(&Value::Object(doc), &is_dropped);
let Value::Object(mut out) = out else {
unreachable!()
};
out.insert("v".into(), json!(tabnas::grammar::BUILTIN_SCHEMA_VERSION));
carry_meta(spec, &mut out);
Ok(Value::Object(out))
}
pub fn to_pure_spec(spec: &GrammarSpec) -> Result<Value, CompileError> {
if !spec.refs.is_empty() {
let closures: Vec<&str> = spec.refs.keys().map(String::as_str).take(3).collect();
return Err(CompileError {
message: format!(
"{}: spec still contains closures; convert with `builtins: true` for \
pure-data output. Stray ref(s): {}",
diag_name(),
closures.join(", ")
),
rules: Vec::new(),
});
}
let mut out = Map::new();
out.insert("options".into(), Value::Object(spec.options.clone()));
out.insert("rule".into(), spec.rules_value());
out.insert("v".into(), json!(tabnas::grammar::BUILTIN_SCHEMA_VERSION));
carry_meta(spec, &mut out);
Ok(Value::Object(out))
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct JsonicOptions {
pub strict: bool,
pub indent: Option<usize>,
}
fn is_ident(k: &str) -> bool {
let mut chars = k.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
_ => return false,
}
chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}
const JS_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
fn js_number(f: f64) -> String {
if f.is_nan() {
return "NaN".to_string();
}
if f.is_infinite() {
return if f > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
}
if f == 0.0 {
return "0".to_string();
}
let magnitude = f.abs();
let (digits, exponent) = (0..17u32)
.map(|p| format!("{magnitude:.*e}", p as usize))
.find(|text| text.parse::<f64>() == Ok(magnitude))
.map(|text| {
let (mantissa, exponent) = text.split_once('e').expect("{:e} emits an exponent");
(
mantissa.chars().filter(|c| *c != '.').collect::<String>(),
exponent
.parse::<i32>()
.expect("{:e} emits an integer exponent"),
)
})
.expect("17 significant digits round-trip every finite f64");
let k = digits.len() as i32;
let n = exponent + 1;
let body = if k <= n && n <= 21 {
format!("{}{}", digits, "0".repeat((n - k) as usize))
} else if 0 < n && n <= 21 {
format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
} else if -6 < n && n <= 0 {
format!("0.{}{}", "0".repeat(-n as usize), digits)
} else {
let e = n - 1;
let head = if k == 1 {
digits.clone()
} else {
format!("{}.{}", &digits[..1], &digits[1..])
};
format!("{}e{}{}", head, if e < 0 { '-' } else { '+' }, e.abs())
};
if f < 0.0 {
format!("-{body}")
} else {
body
}
}
pub fn to_jsonic(value: &Value, opts: JsonicOptions) -> String {
let strict = opts.strict;
let ind = opts.indent.unwrap_or(2);
let sep = if strict { ",\n" } else { "\n" };
let pad = |n: usize| " ".repeat(ind * n);
fn quote(s: &str, ch: char) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push(ch);
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
c if c == ch => {
out.push('\\');
out.push(ch);
}
'\u{8}' => out.push_str("\\b"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\u{c}' => out.push_str("\\f"),
'\r' => out.push_str("\\r"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push(ch);
out
}
let str_ = |s: &str| {
if strict {
quote(s, '"')
} else {
quote(s, '\'')
}
};
let key = |k: &str| {
if !strict && is_ident(k) {
k.to_string()
} else {
quote(k, '"')
}
};
fn number(n: &serde_json::Number) -> String {
if let Some(i) = n.as_i64() {
if i.unsigned_abs() <= JS_SAFE_INTEGER {
return i.to_string();
}
return js_number(i as f64);
}
if let Some(u) = n.as_u64() {
if u <= JS_SAFE_INTEGER {
return u.to_string();
}
return js_number(u as f64);
}
js_number(n.as_f64().unwrap_or(0.0))
}
fn ser(
v: &Value,
depth: usize,
sep: &str,
pad: &dyn Fn(usize) -> String,
str_: &dyn Fn(&str) -> String,
key: &dyn Fn(&str) -> String,
) -> String {
match v {
Value::Null => "null".into(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => number(n),
Value::String(s) => str_(s),
Value::Array(items) => {
if items.is_empty() {
return "[]".into();
}
let lines: Vec<String> = items
.iter()
.map(|x| {
format!(
"{}{}",
pad(depth + 1),
ser(x, depth + 1, sep, pad, str_, key)
)
})
.collect();
format!("[\n{}\n{}]", lines.join(sep), pad(depth))
}
Value::Object(map) => {
if map.is_empty() {
return "{}".into();
}
let lines: Vec<String> = map
.iter()
.map(|(k, x)| {
format!(
"{}{}: {}",
pad(depth + 1),
key(k),
ser(x, depth + 1, sep, pad, str_, key)
)
})
.collect();
format!("{{\n{}\n{}}}", lines.join(sep), pad(depth))
}
}
}
ser(value, 0, sep, &pad, &str_, &key)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CompileOptions {
pub recognition: bool,
pub strict: bool,
pub indent: Option<usize>,
}
impl Default for CompileOptions {
fn default() -> Self {
Self {
recognition: true,
strict: false,
indent: None,
}
}
}
pub fn compile_spec(spec: &GrammarSpec, opts: CompileOptions) -> Result<String, CompileError> {
let out = if opts.recognition {
to_recognition_spec(spec)?
} else {
to_pure_spec(spec)?
};
Ok(to_jsonic(
&out,
JsonicOptions {
strict: opts.strict,
indent: opts.indent,
},
))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActionError {
pub message: String,
}
impl fmt::Display for ActionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ActionError {}
enum Target {
Phase(String),
Alts { phase: String, indices: Vec<usize> },
}
const PHASES: [&str; 4] = ["bo", "ao", "bc", "ac"];
fn resolve_target(spec: &GrammarSpec, key: &str) -> Result<(String, Target), ActionError> {
if key.contains('$') {
return Err(ActionError {
message: format!(
"{}: '$' is reserved for engine builtins; user action ref '{}' may not contain '$'",
diag_name(),
key
),
});
}
let malformed = || ActionError {
message: format!(
"{}: malformed action ref '{}' (expected @rule:phase or @rule:o|c:mark)",
diag_name(),
key
),
};
let body = key.strip_prefix('@').ok_or_else(malformed)?;
let (rule, sel) = body.split_once(':').ok_or_else(malformed)?;
if rule.is_empty() || sel.is_empty() {
return Err(malformed());
}
let Some(Some(rs)) = spec.rule.get(rule) else {
return Err(ActionError {
message: format!(
"{}: action ref '{}' targets unknown rule '{}'",
diag_name(),
key,
rule
),
});
};
if PHASES.contains(&sel) {
return Ok((rule.to_string(), Target::Phase(sel.to_string())));
}
let (oc, mark) = match sel.split_once(':') {
Some((oc @ ("o" | "c"), mark)) if !mark.is_empty() => (oc, mark),
_ => {
return Err(ActionError {
message: format!("{}: malformed action ref '{}'", diag_name(), key),
})
}
};
let phase = if oc == "o" { "open" } else { "close" };
let indices: Vec<usize> = rs
.alts(phase)
.iter()
.enumerate()
.filter(|(_, a)| a.m.as_deref() == Some(mark))
.map(|(i, _)| i)
.collect();
if indices.is_empty() {
return Err(ActionError {
message: format!(
"{}: action ref '{}' matches no {} alt with mark '{}' in rule '{}'",
diag_name(),
key,
phase,
mark,
rule
),
});
}
Ok((
rule.to_string(),
Target::Alts {
phase: phase.to_string(),
indices,
},
))
}
pub fn attach_actions(spec: &mut GrammarSpec, actions: ActionsMap) -> Result<(), ActionError> {
let mut counter = 0;
while spec.refs.contains_key(&format!("@bnf_user{counter}")) {
counter += 1;
}
for (key, fns) in actions {
let (rule, target) = resolve_target(spec, &key)?;
match target {
Target::Phase(phase) => {
let fkey = format!("@{rule}-{phase}");
match spec.refs.get_mut(&fkey) {
Some(RefAction::Phase(existing)) => existing.extend(fns),
_ => {
spec.refs.insert(fkey, RefAction::Phase(fns));
}
}
}
Target::Alts { phase, indices } => {
let fns_arc: Vec<ActionFn> = fns;
let seq: ActionFn = if fns_arc.len() == 1 {
fns_arc[0].clone()
} else {
Arc::new(move |r: &mut Rule, ctx: &mut Context| {
for f in &fns_arc {
f(r, ctx)?;
}
Ok(())
})
};
for i in indices {
let user_ref = format!("@bnf_user{counter}");
counter += 1;
spec.refs
.insert(user_ref.clone(), RefAction::User(seq.clone()));
let rs = spec
.rule
.get_mut(&rule)
.and_then(Option::as_mut)
.expect("resolved above");
rs.alts_mut(&phase)[i].append_action(&user_ref);
}
}
}
}
Ok(())
}
pub fn attach_action_slots(spec: &mut GrammarSpec, ref_names: &[&str]) -> Result<(), ActionError> {
for name in ref_names {
let (rule, target) = resolve_target(spec, name)?;
match target {
Target::Phase(_) => {
return Err(ActionError {
message: format!(
"{}: slot '{}' is a rule-phase ref; slots are for @rule:o|c:mark alt actions",
diag_name(),
name
),
})
}
Target::Alts { phase, indices } => {
let rs = spec
.rule
.get_mut(&rule)
.and_then(Option::as_mut)
.expect("resolved above");
for i in indices {
rs.alts_mut(&phase)[i].append_action(name);
}
}
}
}
Ok(())
}
pub fn mark_listing(spec: &GrammarSpec) -> String {
let mut lines: Vec<String> = Vec::new();
for (rule, entry) in &spec.rule {
let Some(entry) = entry else { continue };
for (phase, sym) in [("open", "o"), ("close", "c")] {
for a in entry.alts(phase) {
let Some(m) = &a.m else { continue };
let what = match (a.s(), a.p()) {
(Some(s), _) if !s.is_empty() => format!("s:{s}"),
(_, Some(p)) if !p.is_empty() => format!("p:{p}"),
_ => "(empty)".to_string(),
};
lines.push(format!("{rule} {sym}:{m} {what}"));
}
}
}
lines.join("\n")
}