use std::collections::{BTreeMap, HashMap};
use rucc_rules::{Error, Term, TermKind, parse_terms};
const BUILTIN: [(&str, &str); 32] = [
("=", "="),
("and", "and"),
("or", "or"),
("not", "not"),
("<", "bvslt"),
("<=", "bvsle"),
(">", "bvsgt"),
(">=", "bvsge"),
("bvslt", "bvslt"),
("bvsle", "bvsle"),
("bvsgt", "bvsgt"),
("bvsge", "bvsge"),
("bvult", "bvult"),
("bvule", "bvule"),
("bvugt", "bvugt"),
("bvuge", "bvuge"),
("bvadd", "bvadd"),
("bvsub", "bvsub"),
("bvmul", "bvmul"),
("bvneg", "bvneg"),
("bvnot", "bvnot"),
("bvand", "bvand"),
("bvor", "bvor"),
("bvxor", "bvxor"),
("bvshl", "bvshl"),
("bvlshr", "bvlshr"),
("bvashr", "bvashr"),
("bvsdiv", "bvsdiv"),
("bvudiv", "bvudiv"),
("bvsrem", "bvsrem"),
("bvurem", "bvurem"),
("ite", "ite"),
];
const LOGICAL: [&str; 4] = ["and", "or", "not", "ite"];
const CONVERSION: [&str; 3] = ["sign_extend", "zero_extend", "extract"];
pub const DEFAULT_WIDTH: u32 = 64;
#[derive(Debug, Clone, Default)]
pub struct Widths {
natural: u32,
asked: u32,
at: BTreeMap<String, u32>,
}
impl Widths {
#[must_use]
pub fn of(pattern: &Term) -> Widths {
Widths::at(pattern, rule_width(pattern))
}
#[must_use]
pub fn at(pattern: &Term, asked: u32) -> Widths {
let natural = rule_width(pattern);
let mut widths = Widths { natural, asked, at: BTreeMap::new() };
widths.bind(pattern, asked);
widths
}
#[must_use]
pub fn width(&self) -> u32 {
self.asked
}
#[must_use]
pub fn natural(&self) -> u32 {
self.natural
}
pub fn names(&self) -> impl Iterator<Item = (&str, u32)> {
self.at.iter().map(|(name, width)| (name.as_str(), *width))
}
#[must_use]
pub fn with(&self, name: &str, width: u32) -> Widths {
let mut out = self.clone();
out.at.insert(name.to_owned(), width);
out
}
fn of_name(&self, name: &str) -> Option<u32> {
self.at.get(name).copied()
}
fn suffix(&self, head: &str) -> Option<u32> {
declared(head).map(|width| self.scale(width))
}
fn scale(&self, width: u32) -> u32 {
if self.asked == self.natural || self.natural == 0 {
return width;
}
self.index(width).max(1)
}
fn index(&self, position: u32) -> u32 {
if self.asked == self.natural || self.natural == 0 {
return position;
}
let scaled = u64::from(position) * u64::from(self.asked) / u64::from(self.natural);
u32::try_from(scaled).unwrap_or(position)
}
fn bind(&mut self, term: &Term, context: u32) {
match &term.kind {
TermKind::Var(name) => {
self.at.insert(name.clone(), context);
}
TermKind::Int(_) => {}
TermKind::App { head, args } => {
let inner = self.suffix(head).unwrap_or(context);
for arg in args {
self.bind(arg, inner);
}
}
}
}
}
#[must_use]
pub fn rule_width(pattern: &Term) -> u32 {
match &pattern.kind {
TermKind::App { head, .. } => declared(head).unwrap_or(DEFAULT_WIDTH),
_ => DEFAULT_WIDTH,
}
}
fn declared(head: &str) -> Option<u32> {
head.rsplit_once('.')
.and_then(|(_, suffix)| suffix.strip_prefix('i'))
.and_then(|bits| bits.parse::<u32>().ok())
}
#[derive(Debug, Clone)]
struct Meaning {
params: Vec<String>,
body: Term,
}
#[derive(Debug, Default)]
pub struct Model {
heads: HashMap<String, Meaning>,
}
impl Model {
pub fn read(path: &str, text: &str) -> Result<Model, Vec<Error>> {
let terms = parse_terms(path, text)?;
let mut model = Model::default();
let mut errors = Vec::new();
for term in terms {
let TermKind::App { head, args } = &term.kind else {
errors.push(fail(path, &term, "expected a `(semantics ...)` form".to_owned()));
continue;
};
if head != "semantics" || args.len() != 2 {
errors.push(fail(path, &term, "expected a `(semantics ...)` form".to_owned()));
continue;
}
let TermKind::App { head: name, args: params } = &args[0].kind else {
errors.push(fail(path, &args[0], "expected a head and its parameters".to_owned()));
continue;
};
let mut names = Vec::new();
for param in params {
match ¶m.kind {
TermKind::Var(name) => names.push(name.clone()),
_ => errors.push(fail(path, param, "a parameter has to be a name".to_owned())),
}
}
if known(name) {
let said = format!("`{name}` is something the solver already knows");
errors.push(fail(path, &args[0], said));
continue;
}
let meaning = Meaning { params: names, body: args[1].clone() };
if model.heads.insert(name.clone(), meaning).is_some() {
let said = format!("`{name}` is given a meaning twice");
errors.push(fail(path, &args[0], said));
}
}
if errors.is_empty() { Ok(model) } else { Err(errors) }
}
pub fn write(&self, path: &str, term: &Term, widths: &Widths) -> Result<(String, u32), Error> {
self.write_at(path, term, widths.width(), widths, &HashMap::new())
}
fn write_at(
&self,
path: &str,
term: &Term,
context: u32,
widths: &Widths,
bound: &HashMap<&str, (String, u32)>,
) -> Result<(String, u32), Error> {
match &term.kind {
TermKind::Var(name) => match bound.get(name.as_str()) {
Some((already, width)) => Ok((already.clone(), *width)),
None => Ok((name.clone(), widths.of_name(name).unwrap_or(context))),
},
TermKind::Int(value) => Ok((literal(*value, context), context)),
TermKind::App { head, args } => {
if CONVERSION.contains(&head.as_str()) {
return self.convert(path, term, head, args, context, widths, bound);
}
if let Some(name) = builtin(head) {
return self.combine(path, term, head, name, args, context, widths, bound);
}
let own = widths.suffix(head).unwrap_or(context);
let mut written = Vec::with_capacity(args.len());
for arg in args {
written.push(self.write_at(path, arg, own, widths, bound)?);
}
let Some(meaning) = self.heads.get(head) else {
let said = format!("nothing in the model says what `{head}` means");
return Err(fail(path, term, said));
};
if meaning.params.len() != written.len() {
let said = format!(
"`{head}` means something with {} arguments and this gives it {}",
meaning.params.len(),
written.len()
);
return Err(fail(path, term, said));
}
let inner: HashMap<&str, (String, u32)> =
meaning.params.iter().map(String::as_str).zip(written).collect();
let (text, width) = self.write_at(path, &meaning.body, own, widths, &inner)?;
if let Some(said) = widths.suffix(head) {
if said != width {
let told = format!(
"`{head}` is written for {said} bits and means something {width} \
bits wide"
);
return Err(fail(path, term, told));
}
}
Ok((text, width))
}
}
}
#[allow(clippy::too_many_arguments)]
fn combine(
&self,
path: &str,
term: &Term,
head: &str,
name: &str,
args: &[Term],
context: u32,
widths: &Widths,
bound: &HashMap<&str, (String, u32)>,
) -> Result<(String, u32), Error> {
let mut written = Vec::with_capacity(args.len());
for arg in args {
written.push(self.write_at(path, arg, context, widths, bound)?);
}
let Some((_, first)) = written.first() else {
return Err(fail(path, term, format!("`{head}` needs arguments")));
};
let first = *first;
if !LOGICAL.contains(&head) {
if let Some((_, other)) = written.iter().find(|(_, width)| *width != first) {
let said = format!(
"`{head}` is given something {first} bits wide and something {other} bits \
wide, and those are not the same kind of thing"
);
return Err(fail(path, term, said));
}
}
let width = if head == "ite" && written.len() > 1 { written[1].1 } else { first };
let texts: Vec<&str> = written.iter().map(|(text, _)| text.as_str()).collect();
Ok((format!("({name} {})", texts.join(" ")), width))
}
#[allow(clippy::too_many_arguments)]
fn convert(
&self,
path: &str,
term: &Term,
head: &str,
args: &[Term],
context: u32,
widths: &Widths,
bound: &HashMap<&str, (String, u32)>,
) -> Result<(String, u32), Error> {
if args.len() != 3 {
let said = format!("`{head}` takes two numbers and a value, and this gives it {}", {
args.len()
});
return Err(fail(path, term, said));
}
let (first, second) = (number(path, head, &args[0])?, number(path, head, &args[1])?);
if head == "extract" {
let (high, low) = (first, second);
if high < low {
let said = format!("`extract` takes bits {high} down to {low}, which is none");
return Err(fail(path, term, said));
}
let width = widths.scale(high - low + 1);
let bottom = widths.index(low);
let top = bottom + width - 1;
let (text, of) = self.write_at(path, &args[2], context, widths, bound)?;
if top >= of {
let said = format!(
"`extract` takes bits {top} down to {bottom} of something {of} bits wide"
);
return Err(fail(path, term, said));
}
return Ok((format!("((_ extract {top} {bottom}) {text})"), width));
}
let (from, to) = (widths.scale(first), widths.scale(second));
if to < from {
let said = format!("`{head}` goes from {from} bits to {to}, which is narrower");
return Err(fail(path, term, said));
}
let (text, of) = self.write_at(path, &args[2], from, widths, bound)?;
if of != from {
let said =
format!("`{head}` goes from {from} bits and is given something {of} bits wide");
return Err(fail(path, term, said));
}
if to == from {
return Ok((text, to));
}
Ok((format!("((_ {head} {}) {text})", to - from), to))
}
}
fn builtin(head: &str) -> Option<&'static str> {
BUILTIN.iter().find(|(name, _)| *name == head).map(|(_, smt)| *smt)
}
fn known(head: &str) -> bool {
builtin(head).is_some() || CONVERSION.contains(&head)
}
fn number(path: &str, head: &str, term: &Term) -> Result<u32, Error> {
match &term.kind {
TermKind::Int(value) => u32::try_from(*value).map_err(|_| {
let said = format!("`{head}` is given {value} where it needs a number of bits");
fail(path, term, said)
}),
_ => {
let said = format!("`{head}` says which widths it goes between, in numbers");
Err(fail(path, term, said))
}
}
}
fn literal(value: i128, width: u32) -> String {
let wrapped =
if width >= 128 { value as u128 } else { (value as u128) & ((1u128 << width) - 1) };
format!("(_ bv{wrapped} {width})")
}
fn fail(path: &str, term: &Term, message: String) -> Error {
Error { path: path.to_owned(), line: term.line, column: term.column, message }
}