use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpecError {
Unsupported(String),
}
impl fmt::Display for SpecError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unsupported(reason) => write!(f, "generation spec unsupported: {reason}"),
}
}
}
impl std::error::Error for SpecError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FormatLine {
Scalars(Vec<String>),
Array {
name: String,
length_var: String,
},
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InputFormat {
pub lines: Vec<FormatLine>,
scalars: BTreeSet<String>,
arrays: BTreeSet<String>,
}
impl InputFormat {
pub fn parse(text: &str) -> Result<Self, SpecError> {
let mut format = Self::default();
for raw in text.lines() {
let normalized = normalize_markup(raw);
let tokens: Vec<&str> = normalized.split_whitespace().collect();
if tokens.is_empty() {
continue;
}
let line = if tokens.contains(&"...") {
parse_array_line(&tokens)?
} else if tokens.iter().all(|t| is_ident(t)) {
for name in &tokens {
if !format.scalars.insert((*name).to_owned()) {
return Err(SpecError::Unsupported(format!(
"duplicate scalar variable `{name}`"
)));
}
}
FormatLine::Scalars(tokens.iter().map(|t| (*t).to_owned()).collect())
} else {
return Err(SpecError::Unsupported(format!(
"unrecognized input-format line: {}",
raw.trim()
)));
};
if let FormatLine::Array { name, .. } = &line {
if format.arrays.contains(name) {
return Err(SpecError::Unsupported(format!(
"duplicate array variable `{name}`"
)));
}
format.arrays.insert(name.clone());
}
format.lines.push(line);
}
if format.lines.is_empty() {
return Err(SpecError::Unsupported(
"input format block is empty".to_owned(),
));
}
Ok(format)
}
fn is_scalar(&self, name: &str) -> bool {
self.scalars.contains(name)
}
fn element_base(&self, name: &str) -> Option<String> {
let (base, _index) = name.rsplit_once('_')?;
self.arrays.contains(base).then(|| base.to_owned())
}
pub(crate) fn scalar_names(&self) -> impl Iterator<Item = &String> {
self.scalars.iter()
}
pub(crate) fn array_decls(&self) -> Vec<(String, String)> {
self.lines
.iter()
.filter_map(|line| match line {
FormatLine::Array {
name, length_var, ..
} => Some((name.clone(), length_var.clone())),
FormatLine::Scalars(_) => None,
})
.collect()
}
}
fn parse_array_line(tokens: &[&str]) -> Result<FormatLine, SpecError> {
let unsupported = || {
SpecError::Unsupported(format!(
"unrecognized input-format line: {}",
tokens.join(" ")
))
};
let ellipsis = tokens
.iter()
.position(|t| *t == "...")
.ok_or_else(unsupported)?;
if tokens.iter().filter(|t| **t == "...").count() != 1
|| ellipsis == 0
|| ellipsis + 1 != tokens.len() - 1
{
return Err(unsupported());
}
let before = &tokens[..ellipsis];
let after = tokens[ellipsis + 1];
let mut base: Option<&str> = None;
for token in before.iter().chain(std::iter::once(&after)) {
let Some((token_base, suffix)) = token.rsplit_once('_') else {
return Err(unsupported());
};
if suffix.is_empty()
|| !suffix
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
return Err(unsupported());
}
match base {
None => base = Some(token_base),
Some(existing) if existing != token_base => return Err(unsupported()),
_ => {}
}
}
let base = base.ok_or_else(unsupported)?;
if !is_ident(base) {
return Err(unsupported());
}
let Some((_, length_var)) = after.rsplit_once('_') else {
return Err(unsupported());
};
if !is_ident(length_var) {
return Err(unsupported());
}
Ok(FormatLine::Array {
name: base.to_owned(),
length_var: length_var.to_owned(),
})
}
fn is_ident(text: &str) -> bool {
let mut chars = text.chars();
chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum VarKey {
Scalar(String),
Element(String),
Other(String),
}
#[derive(Clone, Debug, Default)]
pub struct VarBounds {
pub lowers: Vec<Expr>,
pub uppers: Vec<Expr>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Expr {
Int(i64),
Var(String),
Neg(Box<Expr>),
Add(Box<Expr>, Box<Expr>),
Sub(Box<Expr>, Box<Expr>),
Mul(Box<Expr>, Box<Expr>),
Pow(Box<Expr>, Box<Expr>),
}
impl Expr {
#[must_use]
pub fn vars(&self) -> Vec<&str> {
match self {
Self::Int(_) => Vec::new(),
Self::Var(name) => vec![name.as_str()],
Self::Neg(inner) => inner.vars(),
Self::Add(a, b) | Self::Sub(a, b) | Self::Mul(a, b) | Self::Pow(a, b) => {
let mut vars = a.vars();
vars.extend(b.vars());
vars
}
}
}
pub fn eval(&self, env: &BTreeMap<String, i64>) -> Result<i64, ExprError> {
let value = self.eval_wide(env)?;
if value.unsigned_abs() > MAX_SAFE_INTEGER as u128 {
return Err(ExprError::Unsafe(value.to_string()));
}
i64::try_from(value).map_err(|_| ExprError::Unsafe(value.to_string()))
}
fn eval_wide(&self, env: &BTreeMap<String, i64>) -> Result<i128, ExprError> {
match self {
Self::Int(value) => Ok(i128::from(*value)),
Self::Var(name) => env
.get(name)
.map(|v| i128::from(*v))
.ok_or_else(|| ExprError::UnknownVar(name.clone())),
Self::Neg(inner) => Ok(-inner.eval_wide(env)?),
Self::Add(a, b) => Ok(a.eval_wide(env)? + b.eval_wide(env)?),
Self::Sub(a, b) => Ok(a.eval_wide(env)? - b.eval_wide(env)?),
Self::Mul(a, b) => Ok(a.eval_wide(env)? * b.eval_wide(env)?),
Self::Pow(base, exp) => {
let base = base.eval_wide(env)?;
let exp = exp.eval_wide(env)?;
if !(0..=62).contains(&exp) {
return Err(ExprError::BadExponent(exp.to_string()));
}
base.checked_pow(
u32::try_from(exp).map_err(|_| ExprError::BadExponent(exp.to_string()))?,
)
.ok_or(ExprError::Overflow)
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExprError {
UnknownVar(String),
BadExponent(String),
Overflow,
Unsafe(String),
}
impl fmt::Display for ExprError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownVar(name) => write!(f, "unknown variable `{name}`"),
Self::BadExponent(exp) => write!(f, "invalid exponent {exp}"),
Self::Overflow => write!(f, "expression overflow"),
Self::Unsafe(value) => write!(f, "expression result {value} is not a safe integer"),
}
}
}
impl std::error::Error for ExprError {}
struct ExprParser<'a> {
chars: std::str::Chars<'a>,
peeked: Option<char>,
}
impl<'a> ExprParser<'a> {
fn new(text: &'a str) -> Self {
Self {
chars: text.chars(),
peeked: None,
}
}
fn parse(mut self) -> Result<Expr, ()> {
let expr = self.expr()?;
self.skip_ws();
if self.peeked.is_some() || self.chars.next().is_some() {
return Err(());
}
Ok(expr)
}
fn peek(&mut self) -> Option<char> {
if self.peeked.is_none() {
self.peeked = self.chars.next();
}
self.peeked
}
fn bump(&mut self) -> Option<char> {
let ch = self.peek()?;
self.peeked = None;
Some(ch)
}
fn skip_ws(&mut self) {
while self.peek().is_some_and(char::is_whitespace) {
self.bump();
}
}
fn expr(&mut self) -> Result<Expr, ()> {
let mut left = self.term()?;
loop {
self.skip_ws();
match self.peek() {
Some('+') => {
self.bump();
let right = self.term()?;
left = Expr::Add(Box::new(left), Box::new(right));
}
Some('-') => {
self.bump();
let right = self.term()?;
left = Expr::Sub(Box::new(left), Box::new(right));
}
_ => return Ok(left),
}
}
}
fn term(&mut self) -> Result<Expr, ()> {
let mut left = self.factor()?;
loop {
self.skip_ws();
if self.peek() == Some('*') {
self.bump();
let right = self.factor()?;
left = Expr::Mul(Box::new(left), Box::new(right));
} else {
return Ok(left);
}
}
}
fn factor(&mut self) -> Result<Expr, ()> {
self.skip_ws();
let mut negative = false;
while self.peek() == Some('-') {
self.bump();
negative = !negative;
}
let mut base = self.atom()?;
self.skip_ws();
if self.peek() == Some('^') {
self.bump();
let exp = self.factor()?;
base = Expr::Pow(Box::new(base), Box::new(exp));
}
if negative {
base = Expr::Neg(Box::new(base));
}
Ok(base)
}
fn atom(&mut self) -> Result<Expr, ()> {
self.skip_ws();
match self.peek() {
Some('(') => {
self.bump();
let inner = self.expr()?;
self.skip_ws();
if self.bump() != Some(')') {
return Err(());
}
Ok(inner)
}
Some(c) if c.is_ascii_digit() => self.integer(),
Some(c) if c.is_ascii_alphabetic() || c == '_' => self.ident(),
_ => Err(()),
}
}
fn integer(&mut self) -> Result<Expr, ()> {
let mut text = String::new();
while self.peek().is_some_and(|c| c.is_ascii_digit()) {
text.push(self.bump().expect("peeked digit"));
}
let value: i64 = text.parse().map_err(|_| ())?;
Ok(Expr::Int(value))
}
fn ident(&mut self) -> Result<Expr, ()> {
let mut text = String::new();
while self
.peek()
.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
{
text.push(self.bump().expect("peeked ident char"));
}
if !is_ident(&text) {
return Err(());
}
Ok(Expr::Var(text))
}
}
pub fn parse_expr(text: &str) -> Result<Expr, SpecError> {
ExprParser::new(text)
.parse()
.map_err(|()| SpecError::Unsupported(format!("unparseable expression: {text}")))
}
#[derive(Clone, Debug, Default)]
pub struct ConstraintSet {
pub bounds: BTreeMap<VarKey, VarBounds>,
}
#[derive(Clone, Debug)]
pub struct GenSpec {
pub format: InputFormat,
pub bounds: BTreeMap<VarKey, VarBounds>,
}
impl GenSpec {
pub fn parse(input_format: &str, constraint_lines: &[String]) -> Result<Self, SpecError> {
let format = InputFormat::parse(input_format)?;
let constraints = ConstraintSet::parse(constraint_lines, &format)?;
let spec = Self {
format,
bounds: constraints.bounds,
};
spec.validate()?;
Ok(spec)
}
pub(crate) fn scalar_bounds(&self) -> impl Iterator<Item = (&str, &VarBounds)> {
self.bounds.iter().filter_map(|(key, bounds)| match key {
VarKey::Scalar(name) => Some((name.as_str(), bounds)),
_ => None,
})
}
pub(crate) fn element_bounds(&self, name: &str) -> Option<(&[Expr], &[Expr])> {
let bounds = self.bounds.get(&VarKey::Element(name.to_owned()))?;
Some((&bounds.lowers, &bounds.uppers))
}
fn validate(&self) -> Result<(), SpecError> {
for name in self.format.scalar_names() {
let bounds = self
.bounds
.get(&VarKey::Scalar(name.clone()))
.ok_or_else(|| {
SpecError::Unsupported(format!("scalar `{name}` has no constraints"))
})?;
if bounds.lowers.is_empty() || bounds.uppers.is_empty() {
return Err(SpecError::Unsupported(format!(
"scalar `{name}` lacks a lower or upper bound"
)));
}
}
for (name, length_var) in self.format.array_decls() {
if !self.format.is_scalar(&length_var) {
return Err(SpecError::Unsupported(format!(
"array `{name}` length variable `{length_var}` is not a declared scalar"
)));
}
let bounds = self
.bounds
.get(&VarKey::Element(name.clone()))
.ok_or_else(|| {
SpecError::Unsupported(format!("array `{name}` elements have no constraints"))
})?;
if bounds.lowers.is_empty() || bounds.uppers.is_empty() {
return Err(SpecError::Unsupported(format!(
"array `{name}` elements lack a lower or upper bound"
)));
}
}
Ok(())
}
}
impl ConstraintSet {
pub fn parse(lines: &[String], format: &InputFormat) -> Result<Self, SpecError> {
let mut set = Self::default();
for raw in lines {
for line in raw.lines() {
set.parse_line(line, format)?;
}
}
Ok(set)
}
fn parse_line(&mut self, raw: &str, format: &InputFormat) -> Result<(), SpecError> {
let trimmed = strip_list_marker(raw.trim());
if trimmed.is_empty() {
return Ok(());
}
if has_multi_index(trimmed) {
return Err(SpecError::Unsupported(format!(
"multi-dimensional constraint: {trimmed}"
)));
}
let mut normalized = normalize_markup(trimmed);
strip_annotation_parens(&mut normalized);
let normalized = normalized.trim();
if normalized.is_empty() || !normalized.contains(['<', '>', '=']) {
return Ok(());
}
let (segments, ops) = split_comparisons(normalized)
.ok_or_else(|| SpecError::Unsupported(format!("unparseable constraint: {trimmed}")))?;
match (segments.as_slice(), ops.as_slice()) {
([low, vars, high], [op1, op2]) if op1 == op2 => {
let names = parse_var_list(vars)?;
for name in &names {
self.add_bound(name, format, *op1, low, high)?;
}
}
([left, right], [op]) => {
if is_ident(left.trim()) {
self.add_two_part(left.trim(), right.trim(), *op, format, true)?;
} else if is_ident(right.trim()) {
self.add_two_part(right.trim(), left.trim(), *op, format, false)?;
} else {
return Err(SpecError::Unsupported(format!(
"unparseable constraint: {trimmed}"
)));
}
}
_ => {
return Err(SpecError::Unsupported(format!(
"unparseable constraint: {trimmed}"
)));
}
}
Ok(())
}
fn add_bound(
&mut self,
name: &str,
format: &InputFormat,
op: CmpOp,
low_text: &str,
high_text: &str,
) -> Result<(), SpecError> {
let (lower_text, upper_text) = match op {
CmpOp::Le => (low_text, high_text),
CmpOp::Ge => (high_text, low_text),
};
let lower = parse_expr(lower_text)?;
let upper = parse_expr(upper_text)?;
self.insert(name, format, lower, upper);
Ok(())
}
fn add_two_part(
&mut self,
var: &str,
expr_text: &str,
op: CmpOp,
format: &InputFormat,
var_is_left: bool,
) -> Result<(), SpecError> {
let expr = parse_expr(expr_text)?;
let (lower, upper) = match (op, var_is_left) {
(CmpOp::Le, true) | (CmpOp::Ge, false) => (None, Some(expr)),
_ => (Some(expr), None),
};
self.push_bound(var, format, lower, upper);
Ok(())
}
fn insert(&mut self, name: &str, format: &InputFormat, lower: Expr, upper: Expr) {
self.push_bound(name, format, Some(lower), Some(upper));
}
fn push_bound(
&mut self,
name: &str,
format: &InputFormat,
lower: Option<Expr>,
upper: Option<Expr>,
) {
let key = classify(name, format);
if matches!(key, VarKey::Other(_)) {
return;
}
let bounds = self.bounds.entry(key).or_default();
if let Some(expr) = lower {
bounds.lowers.push(expr);
}
if let Some(expr) = upper {
bounds.uppers.push(expr);
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CmpOp {
Le,
Ge,
}
fn split_comparisons(text: &str) -> Option<(Vec<String>, Vec<CmpOp>)> {
let bytes = text.as_bytes();
let mut segments = Vec::new();
let mut ops = Vec::new();
let mut start = 0;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'<' | b'>' if bytes.get(i + 1) == Some(&b'=') => {
segments.push(text[start..i].to_owned());
ops.push(if bytes[i] == b'<' {
CmpOp::Le
} else {
CmpOp::Ge
});
i += 2;
start = i;
}
b'<' | b'>' | b'=' | b'!' => return None,
_ => i += 1,
}
}
if start == 0 || start >= text.len() {
return None;
}
segments.push(text[start..].to_owned());
if segments.iter().any(|s| s.trim().is_empty()) {
return None;
}
Some((segments, ops))
}
fn parse_var_list(text: &str) -> Result<Vec<String>, SpecError> {
let names: Vec<String> = text.split(',').map(str::trim).map(str::to_owned).collect();
if names.iter().any(|n| !is_ident(n)) {
return Err(SpecError::Unsupported(format!(
"unparseable constraint variable list: {text}"
)));
}
Ok(names)
}
fn classify(name: &str, format: &InputFormat) -> VarKey {
if format.is_scalar(name) {
return VarKey::Scalar(name.to_owned());
}
if let Some(base) = format.element_base(name) {
return VarKey::Element(base);
}
VarKey::Other(name.to_owned())
}
fn strip_list_marker(text: &str) -> &str {
let text = text.trim_start();
for prefix in ["- ", "− ", "– ", "• ", "・ ", "* "] {
if let Some(rest) = text.strip_prefix(prefix) {
return rest.trim_start();
}
}
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
if i > 0
&& i + 1 < bytes.len()
&& matches!(bytes[i], b'.' | b')')
&& bytes[i + 1].is_ascii_whitespace()
{
return text[i + 1..].trim_start();
}
text
}
fn has_multi_index(raw: &str) -> bool {
let bytes = raw.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b'_' && bytes.get(i + 1) == Some(&b'{') {
if let Some(end) = raw[i + 2..].find('}').map(|e| i + 2 + e) {
if raw[i + 2..end].contains(',') {
return true;
}
}
}
}
false
}
fn strip_annotation_parens(text: &mut String) {
let mut search_from = 0;
while let Some(rel) = text[search_from..].find('(') {
let start = search_from + rel;
let mut depth = 0i32;
let mut end = None;
for (i, ch) in text.char_indices().skip_while(|(i, _)| *i < start) {
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
end = Some(i);
break;
}
}
_ => {}
}
}
let Some(end) = end else { return };
if text[start + 1..end].contains(['<', '>', '=']) {
text.replace_range(start..=end, " ");
search_from = start;
} else {
search_from = end + 1;
}
}
}
fn normalize_markup(text: &str) -> String {
const COMMANDS: &[(&str, &str)] = &[
("\\ldotsb", "..."),
("\\ldots", "..."),
("\\cdots", "..."),
("\\dots", "..."),
("\\leq", "<="),
("\\le", "<="),
("\\geq", ">="),
("\\ge", ">="),
("\\times", "*"),
("\\cdot", "*"),
("\\neq", "!="),
("\\ne", "!="),
("\\_", "_"),
("\\(", " "),
("\\)", " "),
("\\ ", " "),
];
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(ch) = rest.chars().next() {
if ch == '\\' {
if let Some((command, replacement)) = COMMANDS
.iter()
.find(|(command, _)| rest.starts_with(command))
{
out.push_str(replacement);
rest = &rest[command.len()..];
continue;
}
rest = &rest[1..];
continue;
}
let mapped = match ch {
'≤' | '≦' | '﹤' => Some("<="),
'≥' | '≧' | '﹥' => Some(">="),
'−' | '–' | '—' => Some("-"),
'×' | '⋅' | '∙' => Some("*"),
'…' | '⋯' => Some("..."),
'{' | '}' | '$' => Some(""),
'\u{a0}' => Some(" "),
_ => None,
};
if let Some(replacement) = mapped {
out.push_str(replacement);
} else {
out.push(ch);
}
rest = &rest[ch.len_utf8()..];
}
out
}
#[cfg(test)]
pub(crate) mod tests_support {
use super::*;
pub(crate) fn parse_simple_spec() -> GenSpec {
GenSpec::parse(
"N M\nA_1 A_2 ... A_N\n",
&[
"1 <= N <= 10".to_owned(),
"1 <= M <= 10".to_owned(),
"1 <= A_i <= 10 (1 <= i <= N)".to_owned(),
],
)
.expect("simple spec")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_scalar_and_array_lines() {
let format = InputFormat::parse("N M\nA_1 A_2 ... A_N\n").expect("format");
assert_eq!(format.lines.len(), 2);
assert_eq!(
format.lines[0],
FormatLine::Scalars(vec!["N".to_owned(), "M".to_owned()])
);
assert_eq!(
format.lines[1],
FormatLine::Array {
name: "A".to_owned(),
length_var: "N".to_owned()
}
);
}
#[test]
fn rejects_unsupported_format_lines() {
for text in [
"S T\n\"string\"\n", "A_{i,j}\n", "A_1 A_2 ... A_N extra\n", "N\n...\n", "N, M\n", ] {
assert!(
InputFormat::parse(text).is_err(),
"expected unsupported: {text:?}"
);
}
}
#[test]
fn parses_constraint_forms() {
let format = InputFormat::parse("N M\nA_1 A_2 ... A_N\n").expect("format");
let set = ConstraintSet::parse(
&[
"1 <= N <= 10".to_owned(),
"M <= 5".to_owned(),
"2 <= N, M <= 8".to_owned(),
"1 <= A_i <= N \\ (1 \\le i \\le N)".to_owned(),
"prose line without operators".to_owned(),
],
&format,
)
.expect("constraints");
let n = set
.bounds
.get(&VarKey::Scalar("N".to_owned()))
.expect("N bounds");
assert_eq!(n.lowers.len(), 2);
assert_eq!(n.uppers.len(), 2);
let m = set
.bounds
.get(&VarKey::Scalar("M".to_owned()))
.expect("M bounds");
assert_eq!(m.lowers.len(), 1);
assert_eq!(m.uppers.len(), 2);
let a = set
.bounds
.get(&VarKey::Element("A".to_owned()))
.expect("A bounds");
assert_eq!(a.lowers.len(), 1);
assert_eq!(a.uppers.len(), 1);
}
#[test]
fn strict_and_unknown_constraints_are_unsupported() {
let format = InputFormat::parse("N\n").expect("format");
for line in [
"1 <= N < 10".to_owned(), "N != 5".to_owned(), "N <= M +".to_owned(), "A_{i,j} <= N".to_owned(), ] {
assert!(
ConstraintSet::parse(std::slice::from_ref(&line), &format).is_err(),
"expected unsupported: {line}"
);
}
}
#[test]
fn evaluates_safe_integer_expressions() {
let env = BTreeMap::from([("N".to_owned(), 3_i64)]);
assert_eq!(parse_expr("10^5").expect("expr").eval(&env), Ok(100_000));
assert_eq!(
parse_expr("2 * 10^5").expect("expr").eval(&env),
Ok(200_000)
);
assert_eq!(parse_expr("N + 1").expect("expr").eval(&env), Ok(4));
assert_eq!(parse_expr("-N * 2").expect("expr").eval(&env), Ok(-6));
assert!(parse_expr("10^100").expect("expr").eval(&env).is_err());
assert!(parse_expr("M + 1").expect("expr").eval(&env).is_err());
assert!(parse_expr("1 / 2").is_err());
}
#[test]
fn spec_requires_bounds_for_everything() {
assert!(GenSpec::parse("A_1 A_2 ... A_N\n", &["1 <= A_i <= 10".to_owned()]).is_err());
assert!(GenSpec::parse("N\nA_1 A_2 ... A_N\n", &["1 <= N <= 10".to_owned()]).is_err());
}
}