use crate::{Expr, Level, Name};
use std::collections::{HashMap, HashSet};
use super::functions::*;
pub struct ProofTerm;
impl ProofTerm {
pub fn is_proof(term: &Expr, prop: &Expr) -> bool {
if Self::could_be_prop(prop) {
Self::is_well_formed(term)
} else {
false
}
}
pub fn could_be_prop(ty: &Expr) -> bool {
match ty {
Expr::Sort(Level::Zero) => true,
Expr::Pi(_, _, _, body) => Self::could_be_prop(body),
Expr::Const(_, _) => true,
Expr::App(_, _) => true,
_ => false,
}
}
pub fn is_sort_zero(ty: &Expr) -> bool {
matches!(ty, Expr::Sort(Level::Zero))
}
pub fn get_proposition(term: &Expr) -> Option<Expr> {
match term {
Expr::Lam(_, _, ty, _) if Self::could_be_prop(ty) => Some((**ty).clone()),
_ => None,
}
}
pub fn is_constructive(term: &Expr) -> bool {
let deps = collect_axiom_deps(term);
!deps
.iter()
.any(|name: &Name| CLASSICAL_AXIOMS.contains(&name.to_string().as_str()))
}
pub fn collect_constants(term: &Expr) -> HashSet<Name> {
let mut result = HashSet::new();
collect_constants_impl(term, &mut result);
result
}
pub fn size(term: &Expr) -> usize {
match term {
Expr::BVar(_) | Expr::FVar(_) | Expr::Const(_, _) | Expr::Sort(_) | Expr::Lit(_) => 1,
Expr::App(f, a) => 1 + Self::size(f) + Self::size(a),
Expr::Lam(_, _, ty, body) => 1 + Self::size(ty) + Self::size(body),
Expr::Pi(_, _, ty, body) => 1 + Self::size(ty) + Self::size(body),
Expr::Let(_, ty, val, body) => 1 + Self::size(ty) + Self::size(val) + Self::size(body),
Expr::Proj(_, _, e) => 1 + Self::size(e),
}
}
pub fn depth(term: &Expr) -> usize {
match term {
Expr::BVar(_) | Expr::FVar(_) | Expr::Const(_, _) | Expr::Sort(_) | Expr::Lit(_) => 0,
Expr::App(f, a) => 1 + Self::depth(f).max(Self::depth(a)),
Expr::Lam(_, _, ty, body) => 1 + Self::depth(ty).max(Self::depth(body)),
Expr::Pi(_, _, ty, body) => 1 + Self::depth(ty).max(Self::depth(body)),
Expr::Let(_, ty, val, body) => {
1 + Self::depth(ty).max(Self::depth(val)).max(Self::depth(body))
}
Expr::Proj(_, _, e) => 1 + Self::depth(e),
}
}
fn is_well_formed(term: &Expr) -> bool {
match term {
Expr::BVar(_) | Expr::FVar(_) | Expr::Const(_, _) | Expr::Sort(_) | Expr::Lit(_) => {
true
}
Expr::App(f, a) => Self::is_well_formed(f) && Self::is_well_formed(a),
Expr::Lam(_, _, ty, body) => Self::is_well_formed(ty) && Self::is_well_formed(body),
Expr::Pi(_, _, ty, body) => Self::is_well_formed(ty) && Self::is_well_formed(body),
Expr::Let(_, ty, val, body) => {
Self::is_well_formed(ty) && Self::is_well_formed(val) && Self::is_well_formed(body)
}
Expr::Proj(_, _, e) => Self::is_well_formed(e),
}
}
pub fn same_proposition_structure(p1: &Expr, p2: &Expr) -> bool {
match (p1, p2) {
(Expr::Sort(l1), Expr::Sort(l2)) => l1 == l2,
(Expr::Const(n1, _), Expr::Const(n2, _)) => n1 == n2,
(Expr::App(f1, a1), Expr::App(f2, a2)) => {
Self::same_proposition_structure(f1, f2) && Self::same_proposition_structure(a1, a2)
}
(Expr::Pi(_, _, ty1, body1), Expr::Pi(_, _, ty2, body2)) => {
Self::same_proposition_structure(ty1, ty2)
&& Self::same_proposition_structure(body1, body2)
}
_ => p1 == p2,
}
}
}
#[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 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)]
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)]
pub struct PrefixCounter {
children: std::collections::HashMap<char, PrefixCounter>,
count: usize,
}
#[allow(dead_code)]
impl PrefixCounter {
pub fn new() -> Self {
Self {
children: std::collections::HashMap::new(),
count: 0,
}
}
pub fn record(&mut self, s: &str) {
self.count += 1;
let mut node = self;
for c in s.chars() {
node = node.children.entry(c).or_default();
node.count += 1;
}
}
pub fn count_with_prefix(&self, prefix: &str) -> usize {
let mut node = self;
for c in prefix.chars() {
match node.children.get(&c) {
Some(n) => node = n,
None => return 0,
}
}
node.count
}
}
#[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)]
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 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)]
#[derive(Debug, Clone, Default)]
pub struct ProofState {
pub obligations: Vec<ProofObligation>,
}
impl ProofState {
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
#[allow(dead_code)]
pub fn add_obligation(&mut self, label: impl Into<String>, proposition: Expr) {
self.obligations
.push(ProofObligation::new(label, proposition));
}
#[allow(dead_code)]
pub fn remaining(&self) -> usize {
self.obligations
.iter()
.filter(|o| !o.is_discharged())
.count()
}
#[allow(dead_code)]
pub fn is_complete(&self) -> bool {
self.remaining() == 0
}
#[allow(dead_code)]
pub fn discharge_next(&mut self, proof: Expr) -> bool {
for obl in self.obligations.iter_mut() {
if !obl.discharged {
obl.discharge(proof);
return true;
}
}
false
}
#[allow(dead_code)]
pub fn open_obligations(&self) -> Vec<&ProofObligation> {
self.obligations
.iter()
.filter(|o| !o.is_discharged())
.collect()
}
}
#[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 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)
}
}
#[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();
}
}
#[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, PartialEq, Eq)]
pub enum ProofComplexity {
Atomic,
Abstraction,
Application,
LetBinding,
Projection,
Composite,
}
pub struct ProofAnalyzer;
impl ProofAnalyzer {
pub fn is_constructive(term: &Expr) -> bool {
!Self::uses_classical(term)
}
pub fn uses_classical(term: &Expr) -> bool {
match term {
Expr::Const(n, _) => {
let s = n.to_string();
s == "Classical.choice" || s == "Classical.em" || s == "propext"
}
Expr::App(f, a) => Self::uses_classical(f) || Self::uses_classical(a),
Expr::Lam(_, _, ty, body) | Expr::Pi(_, _, ty, body) => {
Self::uses_classical(ty) || Self::uses_classical(body)
}
Expr::Let(_, ty, val, body) => {
Self::uses_classical(ty) || Self::uses_classical(val) || Self::uses_classical(body)
}
_ => false,
}
}
pub fn count_applications(term: &Expr) -> usize {
match term {
Expr::App(f, a) => 1 + Self::count_applications(f) + Self::count_applications(a),
Expr::Lam(_, _, ty, body) | Expr::Pi(_, _, ty, body) => {
Self::count_applications(ty) + Self::count_applications(body)
}
Expr::Let(_, ty, val, body) => {
Self::count_applications(ty)
+ Self::count_applications(val)
+ Self::count_applications(body)
}
_ => 0,
}
}
}
#[allow(dead_code)]
pub struct ProofNormalizer;
impl ProofNormalizer {
#[allow(dead_code)]
pub fn beta_reduce(term: &Expr) -> Expr {
match term {
Expr::App(f, arg) => {
let f_reduced = Self::beta_reduce(f);
let arg_reduced = Self::beta_reduce(arg);
if let Expr::Lam(_, _, _, body) = f_reduced {
let substituted = Self::subst_bvar(*body, 0, &arg_reduced);
Self::beta_reduce(&substituted)
} else {
Expr::App(Box::new(f_reduced), Box::new(arg_reduced))
}
}
Expr::Lam(bk, n, ty, body) => {
let ty_red = Self::beta_reduce(ty);
let body_red = Self::beta_reduce(body);
Expr::Lam(*bk, n.clone(), Box::new(ty_red), Box::new(body_red))
}
Expr::Pi(bk, n, ty, body) => {
let ty_red = Self::beta_reduce(ty);
let body_red = Self::beta_reduce(body);
Expr::Pi(*bk, n.clone(), Box::new(ty_red), Box::new(body_red))
}
Expr::Let(_n, _ty, val, body) => {
let val_red = Self::beta_reduce(val);
let body_subst = Self::subst_bvar(*body.clone(), 0, &val_red);
Self::beta_reduce(&body_subst)
}
Expr::Proj(idx, n, e) => Expr::Proj(idx.clone(), *n, Box::new(Self::beta_reduce(e))),
other => other.clone(),
}
}
#[allow(dead_code)]
pub fn subst_bvar(term: Expr, depth: u32, replacement: &Expr) -> Expr {
match term {
Expr::BVar(i) => {
if i == depth {
replacement.clone()
} else if i > depth {
Expr::BVar(i - 1)
} else {
Expr::BVar(i)
}
}
Expr::App(f, a) => Expr::App(
Box::new(Self::subst_bvar(*f, depth, replacement)),
Box::new(Self::subst_bvar(*a, depth, replacement)),
),
Expr::Lam(bk, n, ty, body) => Expr::Lam(
bk,
n,
Box::new(Self::subst_bvar(*ty, depth, replacement)),
Box::new(Self::subst_bvar(*body, depth + 1, replacement)),
),
Expr::Pi(bk, n, ty, body) => Expr::Pi(
bk,
n,
Box::new(Self::subst_bvar(*ty, depth, replacement)),
Box::new(Self::subst_bvar(*body, depth + 1, replacement)),
),
Expr::Let(n, ty, val, body) => Expr::Let(
n,
Box::new(Self::subst_bvar(*ty, depth, replacement)),
Box::new(Self::subst_bvar(*val, depth, replacement)),
Box::new(Self::subst_bvar(*body, depth + 1, replacement)),
),
Expr::Proj(idx, n, e) => {
Expr::Proj(idx, n, Box::new(Self::subst_bvar(*e, depth, replacement)))
}
other => other,
}
}
#[allow(dead_code)]
pub fn count_redexes(term: &Expr) -> usize {
match term {
Expr::App(f, a) => {
let in_f = Self::count_redexes(f);
let in_a = Self::count_redexes(a);
let is_redex = matches!(f.as_ref(), Expr::Lam(_, _, _, _));
in_f + in_a + if is_redex { 1 } else { 0 }
}
Expr::Lam(_, _, ty, body) => Self::count_redexes(ty) + Self::count_redexes(body),
Expr::Pi(_, _, ty, body) => Self::count_redexes(ty) + Self::count_redexes(body),
Expr::Let(_, ty, val, body) => {
Self::count_redexes(ty) + Self::count_redexes(val) + Self::count_redexes(body)
}
Expr::Proj(_, _, e) => Self::count_redexes(e),
_ => 0,
}
}
#[allow(dead_code)]
pub fn is_beta_normal(term: &Expr) -> bool {
Self::count_redexes(term) == 0
}
}
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct ProofSkeleton {
pub term: Expr,
pub ty: Expr,
pub holes: Vec<Name>,
}
impl ProofSkeleton {
#[allow(dead_code)]
pub fn new(term: Expr, ty: Expr) -> Self {
let holes = Self::collect_holes(&term);
Self { term, ty, holes }
}
fn collect_holes(term: &Expr) -> Vec<Name> {
let mut holes = Vec::new();
Self::collect_holes_rec(term, &mut holes);
holes
}
fn collect_holes_rec(term: &Expr, holes: &mut Vec<Name>) {
match term {
Expr::Const(n, _) if n.to_string().contains("sorry") => {
holes.push(n.clone());
}
Expr::App(f, a) => {
Self::collect_holes_rec(f, holes);
Self::collect_holes_rec(a, holes);
}
Expr::Lam(_, _, ty, body) | Expr::Pi(_, _, ty, body) => {
Self::collect_holes_rec(ty, holes);
Self::collect_holes_rec(body, holes);
}
Expr::Let(_, ty, val, body) => {
Self::collect_holes_rec(ty, holes);
Self::collect_holes_rec(val, holes);
Self::collect_holes_rec(body, holes);
}
_ => {}
}
}
#[allow(dead_code)]
pub fn is_complete(&self) -> bool {
self.holes.is_empty()
}
#[allow(dead_code)]
pub fn num_holes(&self) -> usize {
self.holes.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 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
}
}
#[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)]
#[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)]
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 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)]
#[derive(Debug, Clone)]
pub struct ProofAnalysis {
pub size: usize,
pub depth: usize,
pub lambda_count: usize,
pub app_count: usize,
pub let_count: usize,
pub fvar_count: usize,
pub bvar_count: usize,
pub uses_classical: bool,
pub constants: HashSet<Name>,
}
impl ProofAnalysis {
#[allow(dead_code)]
pub fn analyse(term: &Expr) -> Self {
let mut analysis = ProofAnalysis {
size: 0,
depth: 0,
lambda_count: 0,
app_count: 0,
let_count: 0,
fvar_count: 0,
bvar_count: 0,
uses_classical: false,
constants: HashSet::new(),
};
analysis.visit(term, 0);
analysis.depth = ProofTerm::depth(term);
analysis.uses_classical = !ProofTerm::is_constructive(term);
analysis
}
fn visit(&mut self, term: &Expr, _depth: usize) {
self.size += 1;
match term {
Expr::BVar(_) => {
self.bvar_count += 1;
}
Expr::FVar(_) => {
self.fvar_count += 1;
}
Expr::Const(name, _) => {
self.constants.insert(name.clone());
}
Expr::Sort(_) | Expr::Lit(_) => {}
Expr::App(f, a) => {
self.app_count += 1;
self.visit(f, _depth + 1);
self.visit(a, _depth + 1);
}
Expr::Lam(_, _, ty, body) => {
self.lambda_count += 1;
self.visit(ty, _depth + 1);
self.visit(body, _depth + 1);
}
Expr::Pi(_, _, ty, body) => {
self.visit(ty, _depth + 1);
self.visit(body, _depth + 1);
}
Expr::Let(_, ty, val, body) => {
self.let_count += 1;
self.visit(ty, _depth + 1);
self.visit(val, _depth + 1);
self.visit(body, _depth + 1);
}
Expr::Proj(_, _, e) => {
self.visit(e, _depth + 1);
}
}
}
}
#[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)]
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 Fixture {
data: std::collections::HashMap<String, String>,
}
#[allow(dead_code)]
impl Fixture {
pub fn new() -> Self {
Self {
data: std::collections::HashMap::new(),
}
}
pub fn set(&mut self, key: impl Into<String>, val: impl Into<String>) {
self.data.insert(key.into(), val.into());
}
pub fn get(&self, key: &str) -> Option<&str> {
self.data.get(key).map(|s| s.as_str())
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[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 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)]
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)]
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)]
#[derive(Clone, Debug)]
pub struct ProofCertificate {
pub proposition: Expr,
pub proof_term: Expr,
pub is_constructive: bool,
pub has_sorry: bool,
}
impl ProofCertificate {
#[allow(dead_code)]
pub fn new(proposition: Expr, proof_term: Expr) -> Self {
let is_constructive = ProofAnalyzer::is_constructive(&proof_term);
let has_sorry = crate::proof::contains_classical_sorry(&proof_term);
Self {
proposition,
proof_term,
is_constructive,
has_sorry,
}
}
#[allow(dead_code)]
pub fn is_trusted(&self) -> bool {
!self.has_sorry && self.is_constructive
}
}
#[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 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 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
}
}
#[allow(dead_code)]
pub struct MinHeap<T: Ord> {
data: Vec<T>,
}
#[allow(dead_code)]
impl<T: Ord> MinHeap<T> {
pub fn new() -> Self {
Self { data: Vec::new() }
}
pub fn push(&mut self, val: T) {
self.data.push(val);
self.sift_up(self.data.len() - 1);
}
pub fn pop(&mut self) -> Option<T> {
if self.data.is_empty() {
return None;
}
let n = self.data.len();
self.data.swap(0, n - 1);
let min = self.data.pop();
if !self.data.is_empty() {
self.sift_down(0);
}
min
}
pub fn peek(&self) -> Option<&T> {
self.data.first()
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
fn sift_up(&mut self, mut i: usize) {
while i > 0 {
let parent = (i - 1) / 2;
if self.data[i] < self.data[parent] {
self.data.swap(i, parent);
i = parent;
} else {
break;
}
}
}
fn sift_down(&mut self, mut i: usize) {
let n = self.data.len();
loop {
let left = 2 * i + 1;
let right = 2 * i + 2;
let mut smallest = i;
if left < n && self.data[left] < self.data[smallest] {
smallest = left;
}
if right < n && self.data[right] < self.data[smallest] {
smallest = right;
}
if smallest == i {
break;
}
self.data.swap(i, smallest);
i = smallest;
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ProofObligation {
pub label: String,
pub proposition: Expr,
pub discharged: bool,
pub proof_term: Option<Expr>,
}
impl ProofObligation {
#[allow(dead_code)]
pub fn new(label: impl Into<String>, proposition: Expr) -> Self {
ProofObligation {
label: label.into(),
proposition,
discharged: false,
proof_term: None,
}
}
#[allow(dead_code)]
pub fn discharge(&mut self, proof: Expr) {
self.proof_term = Some(proof);
self.discharged = true;
}
#[allow(dead_code)]
pub fn is_discharged(&self) -> bool {
self.discharged
}
}