use super::functions::*;
use crate::{BinderInfo, Expr, FVarId, Name};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct ContextSnapshot {
num_locals: usize,
next_fvar: u64,
}
#[allow(dead_code)]
pub struct SparseVec<T: Default + Clone + PartialEq> {
entries: std::collections::HashMap<usize, T>,
default_: T,
logical_len: usize,
}
#[allow(dead_code)]
impl<T: Default + Clone + PartialEq> SparseVec<T> {
pub fn new(len: usize) -> Self {
Self {
entries: std::collections::HashMap::new(),
default_: T::default(),
logical_len: len,
}
}
pub fn set(&mut self, idx: usize, val: T) {
if val == self.default_ {
self.entries.remove(&idx);
} else {
self.entries.insert(idx, val);
}
}
pub fn get(&self, idx: usize) -> &T {
self.entries.get(&idx).unwrap_or(&self.default_)
}
pub fn len(&self) -> usize {
self.logical_len
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn nnz(&self) -> usize {
self.entries.len()
}
}
#[allow(dead_code)]
pub struct TransformStat {
before: StatSummary,
after: StatSummary,
}
#[allow(dead_code)]
impl TransformStat {
pub fn new() -> Self {
Self {
before: StatSummary::new(),
after: StatSummary::new(),
}
}
pub fn record_before(&mut self, v: f64) {
self.before.record(v);
}
pub fn record_after(&mut self, v: f64) {
self.after.record(v);
}
pub fn mean_ratio(&self) -> Option<f64> {
let b = self.before.mean()?;
let a = self.after.mean()?;
if b.abs() < f64::EPSILON {
return None;
}
Some(a / b)
}
}
#[allow(dead_code)]
pub struct TransitiveClosure {
adj: Vec<Vec<usize>>,
n: usize,
}
#[allow(dead_code)]
impl TransitiveClosure {
pub fn new(n: usize) -> Self {
Self {
adj: vec![Vec::new(); n],
n,
}
}
pub fn add_edge(&mut self, from: usize, to: usize) {
if from < self.n {
self.adj[from].push(to);
}
}
pub fn reachable_from(&self, start: usize) -> Vec<usize> {
let mut visited = vec![false; self.n];
let mut queue = std::collections::VecDeque::new();
queue.push_back(start);
while let Some(node) = queue.pop_front() {
if node >= self.n || visited[node] {
continue;
}
visited[node] = true;
for &next in &self.adj[node] {
queue.push_back(next);
}
}
(0..self.n).filter(|&i| visited[i]).collect()
}
pub fn can_reach(&self, from: usize, to: usize) -> bool {
self.reachable_from(from).contains(&to)
}
}
#[derive(Debug, Clone)]
pub struct LocalVar {
pub name: Name,
pub binder_info: BinderInfo,
pub ty: Expr,
pub val: Option<Expr>,
pub fvar: FVarId,
pub index: usize,
}
#[allow(dead_code)]
pub enum Either2<A, B> {
First(A),
Second(B),
}
#[allow(dead_code)]
impl<A, B> Either2<A, B> {
pub fn is_first(&self) -> bool {
matches!(self, Either2::First(_))
}
pub fn is_second(&self) -> bool {
matches!(self, Either2::Second(_))
}
pub fn first(self) -> Option<A> {
match self {
Either2::First(a) => Some(a),
_ => None,
}
}
pub fn second(self) -> Option<B> {
match self {
Either2::Second(b) => Some(b),
_ => None,
}
}
pub fn map_first<C, F: FnOnce(A) -> C>(self, f: F) -> Either2<C, B> {
match self {
Either2::First(a) => Either2::First(f(a)),
Either2::Second(b) => Either2::Second(b),
}
}
}
#[allow(dead_code)]
pub struct StringPool {
free: Vec<String>,
}
#[allow(dead_code)]
impl StringPool {
pub fn new() -> Self {
Self { free: Vec::new() }
}
pub fn take(&mut self) -> String {
self.free.pop().unwrap_or_default()
}
pub fn give(&mut self, mut s: String) {
s.clear();
self.free.push(s);
}
pub fn free_count(&self) -> usize {
self.free.len()
}
}
#[allow(dead_code)]
pub struct SimpleDag {
edges: Vec<Vec<usize>>,
}
#[allow(dead_code)]
impl SimpleDag {
pub fn new(n: usize) -> Self {
Self {
edges: vec![Vec::new(); n],
}
}
pub fn add_edge(&mut self, from: usize, to: usize) {
if from < self.edges.len() {
self.edges[from].push(to);
}
}
pub fn successors(&self, node: usize) -> &[usize] {
self.edges.get(node).map(|v| v.as_slice()).unwrap_or(&[])
}
pub fn can_reach(&self, from: usize, to: usize) -> bool {
let mut visited = vec![false; self.edges.len()];
self.dfs(from, to, &mut visited)
}
fn dfs(&self, cur: usize, target: usize, visited: &mut Vec<bool>) -> bool {
if cur == target {
return true;
}
if cur >= visited.len() || visited[cur] {
return false;
}
visited[cur] = true;
for &next in self.successors(cur) {
if self.dfs(next, target, visited) {
return true;
}
}
false
}
pub fn topological_sort(&self) -> Option<Vec<usize>> {
let n = self.edges.len();
let mut in_degree = vec![0usize; n];
for succs in &self.edges {
for &s in succs {
if s < n {
in_degree[s] += 1;
}
}
}
let mut queue: std::collections::VecDeque<usize> =
(0..n).filter(|&i| in_degree[i] == 0).collect();
let mut order = Vec::new();
while let Some(node) = queue.pop_front() {
order.push(node);
for &s in self.successors(node) {
if s < n {
in_degree[s] -= 1;
if in_degree[s] == 0 {
queue.push_back(s);
}
}
}
}
if order.len() == n {
Some(order)
} else {
None
}
}
pub fn num_nodes(&self) -> usize {
self.edges.len()
}
}
#[allow(dead_code)]
pub struct RewriteRuleSet {
rules: Vec<RewriteRule>,
}
#[allow(dead_code)]
impl RewriteRuleSet {
pub fn new() -> Self {
Self { rules: Vec::new() }
}
pub fn add(&mut self, rule: RewriteRule) {
self.rules.push(rule);
}
pub fn len(&self) -> usize {
self.rules.len()
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
pub fn conditional_rules(&self) -> Vec<&RewriteRule> {
self.rules.iter().filter(|r| r.conditional).collect()
}
pub fn unconditional_rules(&self) -> Vec<&RewriteRule> {
self.rules.iter().filter(|r| !r.conditional).collect()
}
pub fn get(&self, name: &str) -> Option<&RewriteRule> {
self.rules.iter().find(|r| r.name == name)
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ScopedContext {
inner: Context,
scope_stack: Vec<ContextSnapshot>,
}
impl ScopedContext {
#[allow(dead_code)]
pub fn new() -> Self {
Self {
inner: Context::new(),
scope_stack: Vec::new(),
}
}
#[allow(dead_code)]
pub fn push_scope(&mut self) {
self.scope_stack.push(self.inner.save());
}
#[allow(dead_code)]
pub fn pop_scope(&mut self) {
if let Some(snap) = self.scope_stack.pop() {
self.inner.restore(&snap);
}
}
#[allow(dead_code)]
pub fn add_local(&mut self, name: Name, ty: Expr) -> FVarId {
self.inner.push_local(name, ty, None)
}
#[allow(dead_code)]
pub fn get_local(&self, fvar: FVarId) -> Option<&LocalVar> {
self.inner.get_local(fvar)
}
#[allow(dead_code)]
pub fn scope_depth(&self) -> usize {
self.scope_stack.len()
}
#[allow(dead_code)]
pub fn num_locals(&self) -> usize {
self.inner.num_locals()
}
#[allow(dead_code)]
pub fn inner(&self) -> &Context {
&self.inner
}
#[allow(dead_code)]
pub fn get_fvars(&self) -> Vec<Expr> {
self.inner.get_fvars()
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct FreshNameSeq {
base: String,
counter: u64,
used: Vec<String>,
}
impl FreshNameSeq {
#[allow(dead_code)]
pub fn new(base: &str) -> Self {
Self {
base: base.to_string(),
counter: 0,
used: Vec::new(),
}
}
#[allow(dead_code)]
#[allow(clippy::should_implement_trait)]
pub fn next(&mut self) -> Name {
loop {
let candidate = if self.counter == 0 {
self.base.clone()
} else {
format!("{}_{}", self.base, self.counter)
};
self.counter += 1;
if !self.used.contains(&candidate) {
self.used.push(candidate.clone());
return Name::str(&candidate);
}
}
}
#[allow(dead_code)]
pub fn reserve(&mut self, name: &str) {
if !self.used.contains(&name.to_string()) {
self.used.push(name.to_string());
}
}
#[allow(dead_code)]
pub fn count(&self) -> usize {
self.used.len()
}
}
#[allow(dead_code)]
pub struct Stopwatch {
start: std::time::Instant,
splits: Vec<f64>,
}
#[allow(dead_code)]
impl Stopwatch {
pub fn start() -> Self {
Self {
start: std::time::Instant::now(),
splits: Vec::new(),
}
}
pub fn split(&mut self) {
self.splits.push(self.elapsed_ms());
}
pub fn elapsed_ms(&self) -> f64 {
self.start.elapsed().as_secs_f64() * 1000.0
}
pub fn splits(&self) -> &[f64] {
&self.splits
}
pub fn num_splits(&self) -> usize {
self.splits.len()
}
}
#[allow(dead_code)]
#[allow(missing_docs)]
pub struct RewriteRule {
pub name: String,
pub lhs: String,
pub rhs: String,
pub conditional: bool,
}
#[allow(dead_code)]
impl RewriteRule {
pub fn unconditional(
name: impl Into<String>,
lhs: impl Into<String>,
rhs: impl Into<String>,
) -> Self {
Self {
name: name.into(),
lhs: lhs.into(),
rhs: rhs.into(),
conditional: false,
}
}
pub fn conditional(
name: impl Into<String>,
lhs: impl Into<String>,
rhs: impl Into<String>,
) -> Self {
Self {
name: name.into(),
lhs: lhs.into(),
rhs: rhs.into(),
conditional: true,
}
}
pub fn display(&self) -> String {
format!("{}: {} → {}", self.name, self.lhs, self.rhs)
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct HypContext {
inner: Context,
hyps: Vec<(Name, FVarId)>,
}
impl HypContext {
#[allow(dead_code)]
pub fn new() -> Self {
Self {
inner: Context::new(),
hyps: Vec::new(),
}
}
#[allow(dead_code)]
pub fn add_hyp(&mut self, name: Name, ty: Expr) -> FVarId {
let fvar = self.inner.push_local(name.clone(), ty, None);
self.hyps.push((name, fvar));
fvar
}
#[allow(dead_code)]
pub fn find_hyp(&self, name: &Name) -> Option<FVarId> {
self.hyps
.iter()
.rev()
.find(|(n, _)| n == name)
.map(|(_, id)| *id)
}
#[allow(dead_code)]
pub fn hyp_type(&self, fvar: FVarId) -> Option<&Expr> {
self.inner.get_type(fvar)
}
#[allow(dead_code)]
pub fn num_hyps(&self) -> usize {
self.hyps.len()
}
#[allow(dead_code)]
pub fn hyp_names(&self) -> Vec<&Name> {
self.hyps.iter().map(|(n, _)| n).collect()
}
#[allow(dead_code)]
pub fn remove_last_hyp(&mut self) {
if let Some((_, _)) = self.hyps.pop() {
self.inner.pop_local();
}
}
#[allow(dead_code)]
pub fn clear(&mut self) {
self.hyps.clear();
self.inner.clear();
}
}
#[allow(dead_code)]
pub struct FocusStack<T> {
items: Vec<T>,
}
#[allow(dead_code)]
impl<T> FocusStack<T> {
pub fn new() -> Self {
Self { items: Vec::new() }
}
pub fn focus(&mut self, item: T) {
self.items.push(item);
}
pub fn blur(&mut self) -> Option<T> {
self.items.pop()
}
pub fn current(&self) -> Option<&T> {
self.items.last()
}
pub fn depth(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
#[allow(dead_code)]
#[allow(missing_docs)]
pub enum DecisionNode {
Leaf(String),
Branch {
key: String,
val: String,
yes_branch: Box<DecisionNode>,
no_branch: Box<DecisionNode>,
},
}
#[allow(dead_code)]
impl DecisionNode {
pub fn evaluate(&self, ctx: &std::collections::HashMap<String, String>) -> &str {
match self {
DecisionNode::Leaf(action) => action.as_str(),
DecisionNode::Branch {
key,
val,
yes_branch,
no_branch,
} => {
let actual = ctx.get(key).map(|s| s.as_str()).unwrap_or("");
if actual == val.as_str() {
yes_branch.evaluate(ctx)
} else {
no_branch.evaluate(ctx)
}
}
}
}
pub fn depth(&self) -> usize {
match self {
DecisionNode::Leaf(_) => 0,
DecisionNode::Branch {
yes_branch,
no_branch,
..
} => 1 + yes_branch.depth().max(no_branch.depth()),
}
}
}
#[allow(dead_code)]
pub struct StatSummary {
count: u64,
sum: f64,
min: f64,
max: f64,
}
#[allow(dead_code)]
impl StatSummary {
pub fn new() -> Self {
Self {
count: 0,
sum: 0.0,
min: f64::INFINITY,
max: f64::NEG_INFINITY,
}
}
pub fn record(&mut self, val: f64) {
self.count += 1;
self.sum += val;
if val < self.min {
self.min = val;
}
if val > self.max {
self.max = val;
}
}
pub fn mean(&self) -> Option<f64> {
if self.count == 0 {
None
} else {
Some(self.sum / self.count as f64)
}
}
pub fn min(&self) -> Option<f64> {
if self.count == 0 {
None
} else {
Some(self.min)
}
}
pub fn max(&self) -> Option<f64> {
if self.count == 0 {
None
} else {
Some(self.max)
}
}
pub fn count(&self) -> u64 {
self.count
}
}
#[allow(dead_code)]
pub struct ConfigNode {
key: String,
value: Option<String>,
children: Vec<ConfigNode>,
}
#[allow(dead_code)]
impl ConfigNode {
pub fn leaf(key: impl Into<String>, value: impl Into<String>) -> Self {
Self {
key: key.into(),
value: Some(value.into()),
children: Vec::new(),
}
}
pub fn section(key: impl Into<String>) -> Self {
Self {
key: key.into(),
value: None,
children: Vec::new(),
}
}
pub fn add_child(&mut self, child: ConfigNode) {
self.children.push(child);
}
pub fn key(&self) -> &str {
&self.key
}
pub fn value(&self) -> Option<&str> {
self.value.as_deref()
}
pub fn num_children(&self) -> usize {
self.children.len()
}
pub fn lookup(&self, path: &str) -> Option<&str> {
let mut parts = path.splitn(2, '.');
let head = parts.next()?;
let tail = parts.next();
if head != self.key {
return None;
}
match tail {
None => self.value.as_deref(),
Some(rest) => self.children.iter().find_map(|c| c.lookup_relative(rest)),
}
}
fn lookup_relative(&self, path: &str) -> Option<&str> {
let mut parts = path.splitn(2, '.');
let head = parts.next()?;
let tail = parts.next();
if head != self.key {
return None;
}
match tail {
None => self.value.as_deref(),
Some(rest) => self.children.iter().find_map(|c| c.lookup_relative(rest)),
}
}
}
#[allow(dead_code)]
pub struct NonEmptyVec<T> {
head: T,
tail: Vec<T>,
}
#[allow(dead_code)]
impl<T> NonEmptyVec<T> {
pub fn singleton(val: T) -> Self {
Self {
head: val,
tail: Vec::new(),
}
}
pub fn push(&mut self, val: T) {
self.tail.push(val);
}
pub fn first(&self) -> &T {
&self.head
}
pub fn last(&self) -> &T {
self.tail.last().unwrap_or(&self.head)
}
pub fn len(&self) -> usize {
1 + self.tail.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn to_vec(&self) -> Vec<&T> {
let mut v = vec![&self.head];
v.extend(self.tail.iter());
v
}
}
#[derive(Debug, Clone)]
pub struct Context {
locals: Vec<LocalVar>,
fvar_map: HashMap<FVarId, usize>,
next_fvar: u64,
}
impl Context {
pub fn new() -> Self {
Self {
locals: Vec::new(),
fvar_map: HashMap::new(),
next_fvar: 0,
}
}
pub fn with_start_fvar(start: u64) -> Self {
Self {
locals: Vec::new(),
fvar_map: HashMap::new(),
next_fvar: start,
}
}
pub fn fresh_fvar(&mut self) -> FVarId {
let fvar = FVarId(self.next_fvar);
self.next_fvar += 1;
fvar
}
pub fn push_local(&mut self, name: Name, ty: Expr, val: Option<Expr>) -> FVarId {
self.push_local_with_binder(name, BinderInfo::Default, ty, val)
}
pub fn push_local_with_binder(
&mut self,
name: Name,
binder_info: BinderInfo,
ty: Expr,
val: Option<Expr>,
) -> FVarId {
let fvar = self.fresh_fvar();
let index = self.locals.len();
self.locals.push(LocalVar {
name,
binder_info,
ty,
val,
fvar,
index,
});
self.fvar_map.insert(fvar, index);
fvar
}
pub fn mk_local_decl(&mut self, name: Name, binder_info: BinderInfo, ty: Expr) -> Expr {
let fvar = self.push_local_with_binder(name, binder_info, ty, None);
Expr::FVar(fvar)
}
pub fn mk_let_decl(&mut self, name: Name, ty: Expr, val: Expr) -> Expr {
let fvar = self.push_local(name, ty, Some(val));
Expr::FVar(fvar)
}
pub fn pop_local(&mut self) -> Option<LocalVar> {
if let Some(local) = self.locals.pop() {
self.fvar_map.remove(&local.fvar);
Some(local)
} else {
None
}
}
pub fn save(&self) -> ContextSnapshot {
ContextSnapshot {
num_locals: self.locals.len(),
next_fvar: self.next_fvar,
}
}
pub fn restore(&mut self, snapshot: &ContextSnapshot) {
while self.locals.len() > snapshot.num_locals {
self.pop_local();
}
self.next_fvar = snapshot.next_fvar;
}
pub fn get_local(&self, fvar: FVarId) -> Option<&LocalVar> {
self.fvar_map
.get(&fvar)
.and_then(|&idx| self.locals.get(idx))
}
pub fn get_type(&self, fvar: FVarId) -> Option<&Expr> {
self.get_local(fvar).map(|l| &l.ty)
}
pub fn get_value(&self, fvar: FVarId) -> Option<&Expr> {
self.get_local(fvar).and_then(|l| l.val.as_ref())
}
pub fn is_let(&self, fvar: FVarId) -> bool {
self.get_local(fvar).is_some_and(|l| l.val.is_some())
}
pub fn find_local(&self, name: &Name) -> Option<&LocalVar> {
self.locals.iter().rev().find(|local| &local.name == name)
}
pub fn num_locals(&self) -> usize {
self.locals.len()
}
pub fn is_empty(&self) -> bool {
self.locals.is_empty()
}
pub fn all_locals(&self) -> &[LocalVar] {
&self.locals
}
pub fn get_fvars(&self) -> Vec<Expr> {
self.locals.iter().map(|l| Expr::FVar(l.fvar)).collect()
}
pub fn mk_lambda(&self, fvars: &[FVarId], body: Expr) -> Expr {
let mut result = body;
for &fvar in fvars.iter().rev() {
if let Some(local) = self.get_local(fvar) {
result = abstract_fvar(result, fvar);
result = Expr::Lam(
local.binder_info,
local.name.clone(),
Box::new(abstract_fvars_in_type(local.ty.clone(), fvars, fvar)),
Box::new(result),
);
}
}
result
}
pub fn mk_pi(&self, fvars: &[FVarId], body: Expr) -> Expr {
let mut result = body;
for &fvar in fvars.iter().rev() {
if let Some(local) = self.get_local(fvar) {
result = abstract_fvar(result, fvar);
result = Expr::Pi(
local.binder_info,
local.name.clone(),
Box::new(abstract_fvars_in_type(local.ty.clone(), fvars, fvar)),
Box::new(result),
);
}
}
result
}
pub fn clear(&mut self) {
self.locals.clear();
self.fvar_map.clear();
}
pub fn with_local<F, R>(&mut self, name: Name, ty: Expr, f: F) -> R
where
F: FnOnce(&mut Self, FVarId) -> R,
{
let fvar = self.push_local(name, ty, None);
let result = f(self, fvar);
self.pop_local();
result
}
}
#[allow(dead_code)]
pub struct WriteOnce<T> {
value: std::cell::Cell<Option<T>>,
}
#[allow(dead_code)]
impl<T: Copy> WriteOnce<T> {
pub fn new() -> Self {
Self {
value: std::cell::Cell::new(None),
}
}
pub fn write(&self, val: T) -> bool {
if self.value.get().is_some() {
return false;
}
self.value.set(Some(val));
true
}
pub fn read(&self) -> Option<T> {
self.value.get()
}
pub fn is_written(&self) -> bool {
self.value.get().is_some()
}
}
#[allow(dead_code)]
pub struct SmallMap<K: Ord + Clone, V: Clone> {
entries: Vec<(K, V)>,
}
#[allow(dead_code)]
impl<K: Ord + Clone, V: Clone> SmallMap<K, V> {
pub fn new() -> Self {
Self {
entries: Vec::new(),
}
}
pub fn insert(&mut self, key: K, val: V) {
match self.entries.binary_search_by_key(&&key, |(k, _)| k) {
Ok(i) => self.entries[i].1 = val,
Err(i) => self.entries.insert(i, (key, val)),
}
}
pub fn get(&self, key: &K) -> Option<&V> {
self.entries
.binary_search_by_key(&key, |(k, _)| k)
.ok()
.map(|i| &self.entries[i].1)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn keys(&self) -> Vec<&K> {
self.entries.iter().map(|(k, _)| k).collect()
}
pub fn values(&self) -> Vec<&V> {
self.entries.iter().map(|(_, v)| v).collect()
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ContextEntry {
pub name: Name,
pub ty: Expr,
pub val: Option<Expr>,
pub binder_info: BinderInfo,
}
impl ContextEntry {
#[allow(dead_code)]
pub fn local(name: Name, ty: Expr) -> Self {
Self {
name,
ty,
val: None,
binder_info: BinderInfo::Default,
}
}
#[allow(dead_code)]
pub fn implicit(name: Name, ty: Expr) -> Self {
Self {
name,
ty,
val: None,
binder_info: BinderInfo::Implicit,
}
}
#[allow(dead_code)]
pub fn let_binding(name: Name, ty: Expr, val: Expr) -> Self {
Self {
name,
ty,
val: Some(val),
binder_info: BinderInfo::Default,
}
}
#[allow(dead_code)]
pub fn is_let(&self) -> bool {
self.val.is_some()
}
#[allow(dead_code)]
pub fn is_implicit(&self) -> bool {
matches!(self.binder_info, BinderInfo::Implicit)
}
}
#[allow(dead_code)]
pub struct WindowIterator<'a, T> {
pub(super) data: &'a [T],
pub(super) pos: usize,
pub(super) window: usize,
}
#[allow(dead_code)]
impl<'a, T> WindowIterator<'a, T> {
pub fn new(data: &'a [T], window: usize) -> Self {
Self {
data,
pos: 0,
window,
}
}
}
#[allow(dead_code)]
pub struct SlidingSum {
window: Vec<f64>,
capacity: usize,
pos: usize,
sum: f64,
count: usize,
}
#[allow(dead_code)]
impl SlidingSum {
pub fn new(capacity: usize) -> Self {
Self {
window: vec![0.0; capacity],
capacity,
pos: 0,
sum: 0.0,
count: 0,
}
}
pub fn push(&mut self, val: f64) {
let oldest = self.window[self.pos];
self.sum -= oldest;
self.sum += val;
self.window[self.pos] = val;
self.pos = (self.pos + 1) % self.capacity;
if self.count < self.capacity {
self.count += 1;
}
}
pub fn sum(&self) -> f64 {
self.sum
}
pub fn mean(&self) -> Option<f64> {
if self.count == 0 {
None
} else {
Some(self.sum / self.count as f64)
}
}
pub fn count(&self) -> usize {
self.count
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Default)]
pub struct ContextChain {
entries: Vec<ContextEntry>,
}
impl ContextChain {
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
#[allow(dead_code)]
pub fn push(&mut self, entry: ContextEntry) {
self.entries.push(entry);
}
#[allow(dead_code)]
pub fn pop(&mut self) -> Option<ContextEntry> {
self.entries.pop()
}
#[allow(dead_code)]
pub fn len(&self) -> usize {
self.entries.len()
}
#[allow(dead_code)]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[allow(dead_code)]
pub fn entries(&self) -> &[ContextEntry] {
&self.entries
}
#[allow(dead_code)]
pub fn num_lets(&self) -> usize {
self.entries.iter().filter(|e| e.is_let()).count()
}
#[allow(dead_code)]
pub fn num_implicit(&self) -> usize {
self.entries.iter().filter(|e| e.is_implicit()).count()
}
#[allow(dead_code)]
pub fn find(&self, name: &Name) -> Option<&ContextEntry> {
self.entries.iter().rev().find(|e| &e.name == name)
}
#[allow(dead_code)]
pub fn from_context(ctx: &Context) -> Self {
let mut chain = Self::new();
for local in ctx.all_locals() {
chain.push(ContextEntry {
name: local.name.clone(),
ty: local.ty.clone(),
val: local.val.clone(),
binder_info: local.binder_info,
});
}
chain
}
}
#[allow(dead_code)]
pub struct LabelSet {
labels: Vec<String>,
}
#[allow(dead_code)]
impl LabelSet {
pub fn new() -> Self {
Self { labels: Vec::new() }
}
pub fn add(&mut self, label: impl Into<String>) {
let s = label.into();
if !self.labels.contains(&s) {
self.labels.push(s);
}
}
pub fn has(&self, label: &str) -> bool {
self.labels.iter().any(|l| l == label)
}
pub fn count(&self) -> usize {
self.labels.len()
}
pub fn all(&self) -> &[String] {
&self.labels
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Default)]
pub struct ContextDiff {
pub added: Vec<Name>,
pub removed: Vec<Name>,
}
impl ContextDiff {
#[allow(dead_code)]
pub fn compute(old: &Context, new: &Context) -> Self {
let old_names: std::collections::HashSet<&Name> =
old.all_locals().iter().map(|l| &l.name).collect();
let new_names: std::collections::HashSet<&Name> =
new.all_locals().iter().map(|l| &l.name).collect();
let added = new_names
.difference(&old_names)
.map(|&n| n.clone())
.collect();
let removed = old_names
.difference(&new_names)
.map(|&n| n.clone())
.collect();
Self { added, removed }
}
#[allow(dead_code)]
pub fn is_empty(&self) -> bool {
self.added.is_empty() && self.removed.is_empty()
}
}
#[allow(dead_code)]
pub struct PathBuf {
components: Vec<String>,
}
#[allow(dead_code)]
impl PathBuf {
pub fn new() -> Self {
Self {
components: Vec::new(),
}
}
pub fn push(&mut self, comp: impl Into<String>) {
self.components.push(comp.into());
}
pub fn pop(&mut self) {
self.components.pop();
}
pub fn as_str(&self) -> String {
self.components.join("/")
}
pub fn depth(&self) -> usize {
self.components.len()
}
pub fn clear(&mut self) {
self.components.clear();
}
}
#[derive(Debug, Clone)]
pub struct NameGenerator {
prefix: String,
next: u64,
}
impl NameGenerator {
pub fn new(prefix: impl Into<String>) -> Self {
Self {
prefix: prefix.into(),
next: 0,
}
}
#[allow(clippy::should_implement_trait)]
pub fn next(&mut self) -> Name {
let n = self.next;
self.next += 1;
Name::str(format!("{}_{}", self.prefix, n))
}
pub fn next_fvar_id(&mut self) -> FVarId {
let n = self.next;
self.next += 1;
FVarId(n)
}
}
#[allow(dead_code)]
pub struct StackCalc {
stack: Vec<i64>,
}
#[allow(dead_code)]
impl StackCalc {
pub fn new() -> Self {
Self { stack: Vec::new() }
}
pub fn push(&mut self, n: i64) {
self.stack.push(n);
}
pub fn add(&mut self) {
let b = self
.stack
.pop()
.expect("stack must have at least two values for add");
let a = self
.stack
.pop()
.expect("stack must have at least two values for add");
self.stack.push(a + b);
}
pub fn sub(&mut self) {
let b = self
.stack
.pop()
.expect("stack must have at least two values for sub");
let a = self
.stack
.pop()
.expect("stack must have at least two values for sub");
self.stack.push(a - b);
}
pub fn mul(&mut self) {
let b = self
.stack
.pop()
.expect("stack must have at least two values for mul");
let a = self
.stack
.pop()
.expect("stack must have at least two values for mul");
self.stack.push(a * b);
}
pub fn peek(&self) -> Option<i64> {
self.stack.last().copied()
}
pub fn depth(&self) -> usize {
self.stack.len()
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Default)]
pub struct ContextStats {
pub num_locals: usize,
pub num_lets: usize,
pub num_implicit: usize,
pub max_depth: usize,
}
impl ContextStats {
#[allow(dead_code)]
pub fn from_context(ctx: &Context) -> Self {
let locals = ctx.all_locals();
let num_lets = locals.iter().filter(|l| l.val.is_some()).count();
let num_implicit = locals
.iter()
.filter(|l| matches!(l.binder_info, BinderInfo::Implicit))
.count();
Self {
num_locals: locals.len(),
num_lets,
num_implicit,
max_depth: locals.len(),
}
}
}
#[allow(dead_code)]
pub struct RawFnPtr {
ptr: usize,
arity: usize,
name: String,
}
#[allow(dead_code)]
impl RawFnPtr {
pub fn new(ptr: usize, arity: usize, name: impl Into<String>) -> Self {
Self {
ptr,
arity,
name: name.into(),
}
}
pub fn arity(&self) -> usize {
self.arity
}
pub fn name(&self) -> &str {
&self.name
}
pub fn raw(&self) -> usize {
self.ptr
}
}
#[allow(dead_code)]
pub struct TokenBucket {
capacity: u64,
tokens: u64,
refill_per_ms: u64,
last_refill: std::time::Instant,
}
#[allow(dead_code)]
impl TokenBucket {
pub fn new(capacity: u64, refill_per_ms: u64) -> Self {
Self {
capacity,
tokens: capacity,
refill_per_ms,
last_refill: std::time::Instant::now(),
}
}
pub fn try_consume(&mut self, n: u64) -> bool {
self.refill();
if self.tokens >= n {
self.tokens -= n;
true
} else {
false
}
}
fn refill(&mut self) {
let now = std::time::Instant::now();
let elapsed_ms = now.duration_since(self.last_refill).as_millis() as u64;
if elapsed_ms > 0 {
let new_tokens = elapsed_ms * self.refill_per_ms;
self.tokens = (self.tokens + new_tokens).min(self.capacity);
self.last_refill = now;
}
}
pub fn available(&self) -> u64 {
self.tokens
}
pub fn capacity(&self) -> u64 {
self.capacity
}
}
#[allow(dead_code)]
pub struct FlatSubstitution {
pairs: Vec<(String, String)>,
}
#[allow(dead_code)]
impl FlatSubstitution {
pub fn new() -> Self {
Self { pairs: Vec::new() }
}
pub fn add(&mut self, from: impl Into<String>, to: impl Into<String>) {
self.pairs.push((from.into(), to.into()));
}
pub fn apply(&self, s: &str) -> String {
let mut result = s.to_string();
for (from, to) in &self.pairs {
result = result.replace(from.as_str(), to.as_str());
}
result
}
pub fn len(&self) -> usize {
self.pairs.len()
}
pub fn is_empty(&self) -> bool {
self.pairs.is_empty()
}
}
#[allow(dead_code)]
pub struct VersionedRecord<T: Clone> {
history: Vec<T>,
}
#[allow(dead_code)]
impl<T: Clone> VersionedRecord<T> {
pub fn new(initial: T) -> Self {
Self {
history: vec![initial],
}
}
pub fn update(&mut self, val: T) {
self.history.push(val);
}
pub fn current(&self) -> &T {
self.history
.last()
.expect("VersionedRecord history is always non-empty after construction")
}
pub fn at_version(&self, n: usize) -> Option<&T> {
self.history.get(n)
}
pub fn version(&self) -> usize {
self.history.len() - 1
}
pub fn has_history(&self) -> bool {
self.history.len() > 1
}
}