use std::cell::{Cell, RefCell};
use crate::analysis::PrefixPath;
use crate::ir::{diag_name, EmitError, SrcSpan};
use crate::spec::{AltSpec, RuleSpec};
pub const MAX_EMIT_UNITS: usize = 3_500_000;
pub(crate) struct EmitStep {
doing: &'static str,
advice: &'static str,
}
pub(crate) const STEP_PROBE: EmitStep = EmitStep {
doing: "writing the probe for one of its optional prefixes",
advice: "Write that optional prefix and what follows it as two \
alternatives, one with the prefix and one without.",
};
pub(crate) const STEP_TOKEN_SET: EmitStep = EmitStep {
doing: "listing the members of its token set",
advice: "Write fewer character classes that overlap it.",
};
pub(crate) const STEP_TOKEN_CLASS: EmitStep = EmitStep {
doing: "listing the members of its token class",
advice: "Give it fewer alternatives.",
};
pub(crate) const STEP_FIRST: EmitStep = EmitStep {
doing: "collecting the tokens it can begin with",
advice: "Reduce the tokens it can begin with.",
};
pub(crate) const STEP_FOLLOW: EmitStep = EmitStep {
doing: "collecting the tokens that can follow it",
advice: "Reduce the tokens that can follow it.",
};
pub(crate) const STEP_PAIRS: EmitStep = EmitStep {
doing: "collecting the pairs of tokens that can follow it",
advice: "Reduce the tokens that can follow it.",
};
pub(crate) const STEP_ALTERNATES: EmitStep = EmitStep {
doing: "writing its alternates",
advice: "Factor what its alternatives share into rules of their own.",
};
const STEP_LOOKAHEAD: EmitStep = EmitStep {
doing: "enumerating the token sequences that tell its alternatives apart",
advice: "Give its alternatives first tokens that tell them apart, or \
factor what they begin with into a rule of its own.",
};
pub(crate) const STEP_REMOVE: EmitStep = EmitStep {
doing: "writing the rules and tokens it removes",
advice: "Remove fewer names.",
};
#[derive(Clone)]
pub(crate) enum Subject {
Rule(String),
Class(String),
Removals(usize),
}
struct Step {
subject: Subject,
sp: Option<SrcSpan>,
step: &'static EmitStep,
start: usize,
}
pub(crate) struct EmitBudget {
written: Cell<usize>,
held: Cell<usize>,
step: RefCell<Step>,
}
impl EmitBudget {
pub fn new() -> Self {
Self {
written: Cell::new(0),
held: Cell::new(0),
step: RefCell::new(Step {
subject: Subject::Rule(String::new()),
sp: None,
step: &STEP_ALTERNATES,
start: 0,
}),
}
}
pub fn held(&self) -> usize {
self.held.get()
}
pub fn begin(&self, subject: Subject, sp: Option<SrcSpan>, step: &'static EmitStep) {
*self.step.borrow_mut() = Step {
subject,
sp,
step,
start: self.written.get(),
};
}
pub fn begin_rule(&self, rule: &str, sp: Option<SrcSpan>, step: &'static EmitStep) {
self.begin(Subject::Rule(rule.to_string()), sp, step);
}
fn room(&self) -> usize {
MAX_EMIT_UNITS.saturating_sub(self.written.get() + self.held.get())
}
pub fn charge(&self, n: usize) -> Result<(), EmitError> {
if n > self.room() {
return Err(self.refusal(false));
}
self.written.set(self.written.get() + n);
Ok(())
}
pub fn hold(&self, n: usize) -> Result<(), EmitError> {
if n > self.room() {
return Err(self.refusal(true));
}
self.held.set(self.held.get() + n);
Ok(())
}
pub fn settle(&self, base: usize, paths: &[PrefixPath]) {
let n: usize = paths.iter().map(|p| 1 + p.tokens.len()).sum();
self.held.set(base + n);
}
pub fn keep(&self, base: usize, n: usize) {
self.held.set(base + n);
}
pub fn restore(&self, base: usize) {
self.held.set(base);
}
fn refusal(&self, holding: bool) -> EmitError {
let step = self.step.borrow();
let doing = if holding { &STEP_LOOKAHEAD } else { step.step };
let room = MAX_EMIT_UNITS - step.start;
let count = if holding {
format!(
"hold more than {room} units on top of the {} already written",
step.start
)
} else {
format!(
"add more than {room} units to the {} already written",
step.start
)
};
let (subject, rule) = match &step.subject {
Subject::Rule(name) => (format!("rule '{name}'"), Some(name.clone())),
Subject::Class(pattern) => (format!("the character class /{pattern}/"), None),
Subject::Removals(1) => ("the removal list of 1 name".to_string(), None),
Subject::Removals(n) => (format!("the removal list of {n} names"), None),
};
EmitError {
message: format!(
"{}: {subject} exceeds the emit limit of {MAX_EMIT_UNITS} units while {}, \
which would {count}. {}",
diag_name(),
doing.doing,
doing.advice
),
rule,
sp: step.sp,
}
}
}
pub(crate) fn alt_units(o: &AltSpec) -> usize {
let mut n = 1;
if let Some(s) = o.s().filter(|s| !s.is_empty()) {
n += 1 + s.matches(' ').count();
}
if o.p().is_some() {
n += 1;
}
if o.r().is_some() {
n += 1;
}
n
}
pub(crate) fn rule_units(rs: &RuleSpec) -> usize {
1 + rs.open.iter().map(alt_units).sum::<usize>()
+ rs.close.iter().flatten().map(alt_units).sum::<usize>()
}
pub(crate) fn probe_rule_units(n: usize) -> usize {
3 * n + 2
}
pub(crate) const MAX_MEMO_ENTRIES: usize = 65_536;
thread_local! {
static MEMO_LIMIT: Cell<usize> = const { Cell::new(MAX_MEMO_ENTRIES) };
}
pub(crate) fn memo_limit() -> usize {
MEMO_LIMIT.with(Cell::get)
}
#[cfg(test)]
pub(crate) fn set_memo_limit(n: usize) -> usize {
MEMO_LIMIT.with(|limit| limit.replace(n))
}