use std::rc::Rc;
use indexmap::{IndexMap, IndexSet};
use crate::budget::{EmitBudget, STEP_FIRST, STEP_FOLLOW, STEP_PAIRS};
use crate::ir::{diag_name, regex_key, term_key_of, Element, EmitError, Kind};
use crate::shared::{origin_of, refs_in, tokens_in, Grammar, Production, Sequence};
#[derive(Debug, Default)]
pub(crate) struct Tokens {
pub literals: IndexMap<String, String>,
pub regex_tokens: IndexMap<String, String>,
}
impl Tokens {
pub fn of(&self, el: &Element) -> Option<String> {
match &el.kind {
Kind::Term { .. } => self.literals.get(&term_key_of(el)).cloned(),
Kind::Regex { pattern, flags } => {
self.regex_tokens.get(®ex_key(pattern, flags)).cloned()
}
Kind::Token { name } => Some(name.clone()),
_ => None,
}
}
pub fn name(&self, el: &Element) -> String {
self.of(el).unwrap_or_default()
}
}
pub(crate) type FirstSets = IndexMap<String, IndexSet<String>>;
pub(crate) type Nullable = IndexSet<String>;
pub(crate) type FollowSets = IndexMap<String, IndexSet<String>>;
pub(crate) type FollowPairs = IndexMap<String, IndexMap<String, IndexSet<String>>>;
pub(crate) fn compute_first_sets(
grammar: &Grammar,
tokens: &Tokens,
class_sets: &IndexMap<String, String>,
budget: &EmitBudget,
) -> Result<(FirstSets, Nullable), EmitError> {
let mut first_sets: FirstSets = IndexMap::new();
for p in &grammar.productions {
let mut first = IndexSet::new();
if let Some(set) = class_sets.get(&p.name) {
budget.begin_rule(origin_of(p), p.sp, &STEP_FIRST);
budget.charge(1)?;
first.insert(set.clone());
}
first_sets.insert(p.name.clone(), first);
}
let mut nullable: Nullable = IndexSet::new();
let mut changed = true;
while changed {
changed = false;
for prod in &grammar.productions {
if class_sets.contains_key(&prod.name) {
continue;
}
budget.begin_rule(origin_of(prod), prod.sp, &STEP_FIRST);
for alt in &prod.alts {
let mut alt_nullable = true;
for el in alt {
match &el.kind {
Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } => {
let tok = tokens.name(el);
if !first_sets[&prod.name].contains(&tok) {
budget.charge(1)?;
first_sets[&prod.name].insert(tok);
changed = true;
}
alt_nullable = false;
break;
}
Kind::Ref { name, .. } => {
let ref_first: Vec<String> = first_sets
.get(name)
.map(|s| s.iter().cloned().collect())
.unwrap_or_default();
for tok in ref_first {
if !first_sets[&prod.name].contains(&tok) {
budget.charge(1)?;
first_sets[&prod.name].insert(tok);
changed = true;
}
}
if !nullable.contains(name) {
alt_nullable = false;
break;
}
}
_ => panic!(
"{}: internal — unexpected kind in FIRST: {}",
diag_name(),
kind_name(el)
),
}
}
if alt_nullable && nullable.insert(prod.name.clone()) {
changed = true;
}
}
}
}
Ok((first_sets, nullable))
}
pub(crate) fn kind_name(el: &Element) -> &'static str {
match el.kind {
Kind::Term { .. } => "term",
Kind::Ref { .. } => "ref",
Kind::Token { .. } => "token",
Kind::Prose { .. } => "prose",
Kind::Regex { .. } => "regex",
Kind::Opt { .. } => "opt",
Kind::Star { .. } => "star",
Kind::Plus { .. } => "plus",
Kind::Rep { .. } => "rep",
Kind::Group { .. } => "group",
}
}
pub(crate) fn first_of_alt(
alt: &[Rc<Element>],
tokens: &Tokens,
first_sets: &FirstSets,
nullable: &Nullable,
) -> Option<IndexSet<String>> {
let (out, is_nullable) = first_of_seq(alt, tokens, first_sets, nullable);
if is_nullable {
None
} else {
Some(out)
}
}
pub(crate) fn first_of_seq(
seq: &[Rc<Element>],
tokens: &Tokens,
first_sets: &FirstSets,
nullable: &Nullable,
) -> (IndexSet<String>, bool) {
let mut out: IndexSet<String> = IndexSet::new();
for el in seq {
match &el.kind {
Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } => {
out.insert(tokens.name(el));
return (out, false);
}
Kind::Ref { name, .. } => {
if let Some(rf) = first_sets.get(name) {
out.extend(rf.iter().cloned());
}
if !nullable.contains(name) {
return (out, false);
}
}
_ => panic!(
"{}: internal — unexpected kind in firstOfSeq: {}",
diag_name(),
kind_name(el)
),
}
}
(out, true)
}
pub(crate) fn compute_follow_sets(
grammar: &Grammar,
tokens: &Tokens,
first_sets: &FirstSets,
nullable: &Nullable,
start: &str,
budget: &EmitBudget,
) -> Result<FollowSets, EmitError> {
let mut follow: FollowSets = grammar
.productions
.iter()
.map(|p| (p.name.clone(), IndexSet::new()))
.collect();
let prods: IndexMap<&str, &Production> = grammar
.productions
.iter()
.map(|p| (p.name.as_str(), p))
.collect();
let begin = |name: &str| {
let p = prods[name];
budget.begin_rule(origin_of(p), p.sp, &STEP_FOLLOW);
};
if let Some(f) = follow.get_mut(start) {
begin(start);
budget.charge(1)?;
f.insert("#ZZ".to_string());
}
let mut changed = true;
while changed {
changed = false;
for prod in &grammar.productions {
for alt in &prod.alts {
for (i, el) in alt.iter().enumerate() {
let Kind::Ref { name, .. } = &el.kind else {
continue;
};
if !follow.contains_key(name) {
continue;
}
begin(name);
let (rest, rest_nullable) =
first_of_seq(&alt[i + 1..], tokens, first_sets, nullable);
let mut add: Vec<String> = rest.into_iter().collect();
if rest_nullable {
add.extend(follow[&prod.name].iter().cloned());
}
let target = follow.get_mut(name).expect("checked above");
for tok in add {
if !target.contains(&tok) {
budget.charge(1)?;
target.insert(tok);
changed = true;
}
}
}
}
}
}
Ok(follow)
}
pub(crate) fn compute_follow_pairs(
grammar: &Grammar,
tokens: &Tokens,
first_sets: &FirstSets,
nullable: &Nullable,
follow: &FollowSets,
budget: &EmitBudget,
) -> Result<FollowPairs, EmitError> {
let mut pairs: FollowPairs = grammar
.productions
.iter()
.map(|p| (p.name.clone(), IndexMap::new()))
.collect();
let prods: IndexMap<&str, &Production> = grammar
.productions
.iter()
.map(|p| (p.name.as_str(), p))
.collect();
fn add_pair(
pairs: &mut FollowPairs,
r: &str,
t: &str,
u: &str,
budget: &EmitBudget,
) -> Result<bool, EmitError> {
let Some(m) = pairs.get_mut(r) else {
return Ok(false);
};
let us = m.entry(t.to_string()).or_default();
if us.contains(u) {
return Ok(false);
}
budget.charge(1)?;
us.insert(u.to_string());
Ok(true)
}
let mut changed = true;
while changed {
changed = false;
for prod in &grammar.productions {
let prod_follow: Vec<String> = follow
.get(&prod.name)
.map(|s| s.iter().cloned().collect())
.unwrap_or_default();
for alt in &prod.alts {
for (i, el) in alt.iter().enumerate() {
let Kind::Ref { name, .. } = &el.kind else {
continue;
};
if !pairs.contains_key(name) {
continue;
}
let target = prods[name.as_str()];
budget.begin_rule(origin_of(target), target.sp, &STEP_PAIRS);
let mut j = i + 1;
let mut blocked = false;
while j < alt.len() {
let ej = &alt[j];
if let Kind::Ref { name: nj, .. } = &ej.kind {
if nullable.contains(nj) {
j += 1;
continue;
}
blocked = true;
break;
}
let Some(t) = tokens.of(ej) else {
blocked = true;
break;
};
let (rest, rest_nullable) =
first_of_seq(&alt[j + 1..], tokens, first_sets, nullable);
for u in &rest {
if add_pair(&mut pairs, name, &t, u, budget)? {
changed = true;
}
}
if rest_nullable {
for u in &prod_follow {
if add_pair(&mut pairs, name, &t, u, budget)? {
changed = true;
}
}
}
blocked = true;
break;
}
if !blocked {
let prod_pairs: Vec<(String, Vec<String>)> = pairs[&prod.name]
.iter()
.map(|(t, us)| (t.clone(), us.iter().cloned().collect()))
.collect();
for (t, us) in prod_pairs {
for u in us {
if add_pair(&mut pairs, name, &t, &u, budget)? {
changed = true;
}
}
}
}
}
}
}
}
Ok(pairs)
}
pub(crate) fn resolve_suffix_debts(
grammar: &mut Grammar,
tokens: &Tokens,
first_sets: &FirstSets,
nullable: &Nullable,
tokens_overlap: &dyn Fn(&str, &str) -> bool,
) {
let guarded: Vec<usize> = grammar
.productions
.iter()
.enumerate()
.filter(|(_, p)| p.debt_guard.is_some())
.map(|(i, _)| i)
.collect();
if guarded.is_empty() {
return;
}
for loop_idx in guarded {
let loop_name = grammar.productions[loop_idx].name.clone();
let counter = grammar.productions[loop_idx]
.debt_guard
.clone()
.expect("filtered on debt_guard");
let owner = grammar.productions.iter().enumerate().find(|(i, p)| {
*i != loop_idx
&& p.alts
.iter()
.any(|alt| alt.iter().any(|el| el.is_ref_to(&loop_name)))
});
let loop_first: IndexSet<String> = first_sets.get(&loop_name).cloned().unwrap_or_default();
let Some((_, owner)) = owner else {
grammar.productions[loop_idx].debt_guard = None;
continue;
};
if loop_first.is_empty() {
grammar.productions[loop_idx].debt_guard = None;
continue;
}
let carries = ref_callers_of(grammar, &owner.name);
let mut pending: Vec<(usize, usize, usize, i64)> = Vec::new();
let mut owed: IndexSet<String> = IndexSet::new();
for (pi, prod) in grammar.productions.iter().enumerate() {
for (ai, alt) in prod.alts.iter().enumerate() {
for (i, el) in alt.iter().enumerate() {
let Kind::Ref { name, .. } = &el.kind else {
continue;
};
if !carries.contains(name) {
continue;
}
let suffix = &alt[i + 1..];
if suffix.is_empty() {
continue;
}
let (f_tokens, f_nullable) = first_of_seq(suffix, tokens, first_sets, nullable);
if f_nullable {
continue;
}
let mut hits = false;
for u in &f_tokens {
for t in &loop_first {
if t == u || tokens_overlap(t, u) {
owed.insert(t.clone());
hits = true;
}
}
}
pending.push((pi, ai, i, if hits { 1 } else { 0 }));
}
}
}
if owed.is_empty() {
grammar.productions[loop_idx].debt_guard = None;
continue;
}
grammar.productions[loop_idx].debt_owed = Some(owed.into_iter().collect());
for (pi, ai, i, delta) in pending {
let el = Rc::make_mut(&mut grammar.productions[pi].alts[ai][i]);
if let Kind::Ref { debt, .. } = &mut el.kind {
let mut d = debt.clone().unwrap_or_default();
d.insert(counter.clone(), delta);
*debt = Some(d);
}
}
}
}
fn ref_callers_of(grammar: &Grammar, target: &str) -> IndexSet<String> {
let mut rev: IndexMap<String, Vec<String>> = IndexMap::new();
for p in &grammar.productions {
let mut out: IndexSet<String> = IndexSet::new();
for alt in &p.alts {
refs_in(alt, &mut out);
}
if let Some(pd) = &p.probe_dispatch {
out.insert(pd.probe_rule.clone());
out.insert(pd.with_branch.clone());
out.insert(pd.no_branch.clone());
}
for to in out {
rev.entry(to).or_default().push(p.name.clone());
}
}
let mut seen: IndexSet<String> = IndexSet::new();
seen.insert(target.to_string());
let mut queue = vec![target.to_string()];
while let Some(next) = queue.pop() {
if let Some(from) = rev.get(&next) {
for f in from {
if seen.insert(f.clone()) {
queue.push(f.clone());
}
}
}
}
seen
}
#[derive(Debug, Clone)]
pub(crate) struct PrefixPath {
pub tokens: Vec<Rc<str>>,
pub done: bool,
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn alt_prefixes_raw(
alt: &[Rc<Element>],
grammar: &Grammar,
tokens: &Tokens,
max_k: usize,
visited: &IndexSet<String>,
head_filter: Option<&dyn Fn(&str) -> bool>,
class_sets: Option<&IndexMap<String, String>>,
budget: &EmitBudget,
) -> Result<Vec<PrefixPath>, EmitError> {
budget.hold(1)?;
let mut paths: Vec<PrefixPath> = vec![PrefixPath {
tokens: Vec::new(),
done: false,
}];
for el in alt {
let mut next: Vec<PrefixPath> = Vec::new();
let mut open = false;
let mut put = |next: &mut Vec<PrefixPath>, tokens: Vec<Rc<str>>, done: bool| {
budget.hold(1 + tokens.len())?;
if !done && tokens.len() < max_k {
open = true;
}
next.push(PrefixPath { tokens, done });
Ok::<(), EmitError>(())
};
let admit = |p: &PrefixPath, tok: &str| -> bool {
match head_filter {
None => true,
Some(f) => !p.tokens.is_empty() || f(tok),
}
};
let mut target: Option<Option<&crate::shared::Production>> = None;
let added: Option<Rc<str>> = match &el.kind {
Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } => {
Some(Rc::from(tokens.name(el)))
}
Kind::Ref { name, .. } => class_sets
.and_then(|c| c.get(name))
.map(|set| Rc::from(set.as_str())),
_ => None,
};
let mut child_visited: IndexSet<String> = IndexSet::new();
let mut by_length: IndexMap<usize, Vec<Vec<PrefixPath>>> = IndexMap::new();
for p in &paths {
if p.done || p.tokens.len() >= max_k {
next.push(p.clone());
continue;
}
match &el.kind {
Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } => {
let tok = added.as_ref().expect("a terminal adds its token");
if admit(p, tok) {
let mut t = p.tokens.clone();
t.push(tok.clone());
put(&mut next, t, false)?;
}
}
Kind::Ref { name, .. } => {
if let Some(set) = &added {
if admit(p, set) {
let mut t = p.tokens.clone();
t.push(set.clone());
put(&mut next, t, false)?;
}
continue;
}
if visited.contains(name) {
put(&mut next, p.tokens.clone(), true)?;
continue;
}
let found = *target.get_or_insert_with(|| {
child_visited = visited.clone();
child_visited.insert(name.clone());
grammar.find(name)
});
let Some(found) = found.filter(|t| !t.alts.is_empty()) else {
put(&mut next, p.tokens.clone(), true)?;
continue;
};
let held = p.tokens.len();
if !by_length.contains_key(&held) {
let sub_filter = if held == 0 { head_filter } else { None };
let mut subs = Vec::with_capacity(found.alts.len());
for sub in &found.alts {
subs.push(alt_prefixes_raw(
sub,
grammar,
tokens,
max_k - held,
&child_visited,
sub_filter,
class_sets,
budget,
)?);
}
by_length.insert(held, subs);
}
for sub_paths in &by_length[&held] {
for sp in sub_paths {
let mut t = p.tokens.clone();
t.extend(sp.tokens.iter().cloned());
put(&mut next, t, sp.done)?;
}
}
}
_ => {
put(&mut next, p.tokens.clone(), true)?;
}
}
}
paths = next;
if !open {
break;
}
}
Ok(paths)
}
pub(crate) fn alt_prefixes(
alt: &[Rc<Element>],
grammar: &Grammar,
tokens: &Tokens,
max_k: usize,
class_sets: Option<&IndexMap<String, String>>,
budget: &EmitBudget,
) -> Result<Vec<Vec<String>>, EmitError> {
let base = budget.held();
let raw = alt_prefixes_raw(
alt,
grammar,
tokens,
max_k,
&IndexSet::new(),
None,
class_sets,
budget,
)?;
let mut seen: IndexSet<String> = IndexSet::new();
let mut out: Vec<Vec<String>> = Vec::new();
let mut kept = 0;
for p in raw {
let key = p.tokens.join(" ");
if seen.insert(key) {
kept += 1 + p.tokens.len();
out.push(p.tokens.iter().map(|t| t.to_string()).collect());
}
}
budget.keep(base, kept);
Ok(out)
}
pub(crate) fn is_single_segment(alt: &Sequence) -> bool {
let mut saw_ref = false;
for el in alt {
match &el.kind {
Kind::Ref { .. } => {
if saw_ref {
return false;
}
saw_ref = true;
}
Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } => {
if saw_ref {
return false; }
}
_ => return false,
}
}
true
}
pub(crate) fn is_name_space(c: char) -> bool {
c.is_whitespace() || c == '\u{FEFF}'
}
pub(crate) fn token_class_names(grammar: &Grammar) -> IndexSet<String> {
let mut out = IndexSet::new();
for prod in &grammar.productions {
if prod.probe_helper.is_some()
|| prod.probe_dispatch.is_some()
|| prod.tail_repeat.is_some()
{
continue;
}
if prod.value.is_some() || prod.alts.len() < 2 {
continue;
}
if prod.name.is_empty()
|| prod.name.chars().any(is_name_space)
|| crate::emit::is_engine_owned_token(&format!("#{}", prod.name))
{
continue;
}
let all = prod.alts.iter().all(|alt| {
alt.len() == 1
&& matches!(alt[0].kind, Kind::Term { .. } | Kind::Token { .. })
&& !crate::prose::element_derives_empty(&alt[0], &IndexSet::new())
});
if all {
out.insert(prod.name.clone());
}
}
if !out.is_empty() {
let mut spelled: IndexSet<String> = IndexSet::new();
for prod in &grammar.productions {
for alt in &prod.alts {
tokens_in(alt, &mut spelled);
}
}
out.retain(|name| !spelled.contains(&format!("#{name}")));
}
out
}
pub(crate) struct DispatchPrefixes {
pub prefixes: Vec<Vec<String>>,
pub nullable: bool,
}
const MEMO_PAIRS: usize = 1 << 22;
#[allow(clippy::too_many_arguments)]
pub(crate) fn dispatch_prefixes(
alts: &[Sequence],
grammar: &Grammar,
tokens: &Tokens,
max_k: usize,
contest: &dyn Fn(&str, &str) -> bool,
exit_paths: &[Vec<String>],
class_sets: &IndexMap<String, String>,
budget: &EmitBudget,
) -> Result<Vec<DispatchPrefixes>, EmitError> {
let base = budget.held();
let n = alts.len();
let enumerate = |alt: &Sequence,
k: usize,
filter: Option<&dyn Fn(&str) -> bool>|
-> Result<Vec<PrefixPath>, EmitError> {
let base = budget.held();
let paths = alt_prefixes_raw(
alt,
grammar,
tokens,
k,
&IndexSet::new(),
filter,
Some(class_sets),
budget,
)?;
budget.settle(base, &paths);
Ok(paths)
};
let mut one: Vec<Vec<PrefixPath>> = Vec::with_capacity(n);
let mut nullable: Vec<bool> = Vec::with_capacity(n);
let mut heads: Vec<Vec<String>> = Vec::with_capacity(n);
for alt in alts {
let paths = if alt.is_empty() {
Vec::new()
} else {
enumerate(alt, 1, None)?
};
nullable.push(paths.iter().any(|p| p.tokens.is_empty() && !p.done));
let mut seen: IndexSet<String> = IndexSet::new();
let mut hs: Vec<String> = Vec::new();
for p in &paths {
if p.tokens.len() != 1 {
continue;
}
if seen.insert(p.tokens[0].to_string()) {
hs.push(p.tokens[0].to_string());
}
}
heads.push(hs);
one.push(paths);
}
let mut contested: Vec<IndexSet<String>> = Vec::with_capacity(n);
for i in 0..n {
let mut out: IndexSet<String> = IndexSet::new();
for h in &heads[i] {
let mut hit = false;
for (j, others) in heads.iter().enumerate() {
if j == i || hit {
continue;
}
if others.iter().any(|o| contest(h, o)) {
hit = true;
}
}
if !hit && exit_paths.iter().any(|e| contest(h, &e[0])) {
hit = true;
}
if hit {
out.insert(h.clone());
}
}
contested.push(out);
}
let mut deep: Vec<Vec<PrefixPath>> = Vec::with_capacity(n);
for (i, alt) in alts.iter().enumerate() {
if contested[i].is_empty() {
deep.push(Vec::new());
continue;
}
let c = &contested[i];
let filter = |t: &str| c.contains(t);
deep.push(
enumerate(alt, max_k, Some(&filter))?
.into_iter()
.filter(|p| !p.tokens.is_empty())
.collect(),
);
}
fn intern<'a, T: AsRef<str>>(interned: &mut IndexSet<&'a str>, tokens: &'a [T]) -> Vec<usize> {
tokens
.iter()
.map(|t| interned.insert_full(t.as_ref()).0)
.collect()
}
let mut interned: IndexSet<&str> = IndexSet::new();
let mut deep_ids: Vec<Vec<Vec<usize>>> = Vec::with_capacity(deep.len());
for paths in &deep {
let mut ids = Vec::with_capacity(paths.len());
for p in paths {
ids.push(intern(&mut interned, &p.tokens));
}
deep_ids.push(ids);
}
let mut exit_ids: Vec<Vec<usize>> = Vec::with_capacity(exit_paths.len());
for e in exit_paths {
exit_ids.push(intern(&mut interned, e));
}
let width = interned.len();
let dense = width
.checked_mul(width)
.filter(|pairs| *pairs <= MEMO_PAIRS);
let answers = std::cell::RefCell::new(vec![0u8; dense.unwrap_or(0)]);
let meets = |a: usize, b: usize| -> bool {
if dense.is_none() {
return contest(interned[a], interned[b]);
}
let slot = a * width + b;
let known = answers.borrow()[slot];
if known != 0 {
return 2 == known;
}
let yes = contest(interned[a], interned[b]);
answers.borrow_mut()[slot] = if yes { 2 } else { 1 };
yes
};
let depth_of = |p: &[usize], i: usize| -> usize {
let mut d = 1usize;
let mut against = |q: &[usize]| -> bool {
let m = p.len().min(q.len());
let mut k = 0;
while k < m && meets(p[k], q[k]) {
k += 1;
}
if k == m {
return false;
}
if k + 1 > d {
d = k + 1;
}
true
};
for (j, paths) in deep_ids.iter().enumerate() {
if j == i {
continue;
}
for q in paths {
if !against(q) {
return p.len();
}
}
}
for e in &exit_ids {
if !against(e) {
return p.len();
}
}
d
};
let mut kept = 0;
let mut out: Vec<DispatchPrefixes> = Vec::with_capacity(n);
for i in 0..n {
let mut seen: IndexSet<String> = IndexSet::new();
let mut prefixes: Vec<Vec<String>> = Vec::new();
for h in &heads[i] {
if !contested[i].contains(h) {
if seen.insert(h.clone()) {
budget.hold(2)?;
kept += 2;
prefixes.push(vec![h.clone()]);
}
continue;
}
for (at, p) in deep[i].iter().enumerate() {
if &*p.tokens[0] != h.as_str() {
continue;
}
let d = depth_of(&deep_ids[i][at], i);
let prefix: Vec<String> = p.tokens[..d].iter().map(|t| t.to_string()).collect();
if seen.insert(prefix.join(" ")) {
budget.hold(1 + d)?;
kept += 1 + d;
prefixes.push(prefix);
}
}
}
out.push(DispatchPrefixes {
prefixes,
nullable: nullable[i],
});
}
let _ = one;
budget.keep(base, kept);
Ok(out)
}