use super::functions::*;
use crate::equiv_manager::EquivManager;
use crate::expr_util::{get_app_args, get_app_fn, has_loose_bvar};
use crate::instantiate::instantiate_type_lparams;
use crate::level;
use crate::reduce::{Reducer, ReducibilityHint, TransparencyMode};
use crate::subst::instantiate;
use crate::{Environment, Expr, Level};
use std::collections::HashMap;
#[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 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)]
#[derive(Debug, Clone, Default)]
pub struct NameIndex {
names: Vec<String>,
index: std::collections::HashMap<String, usize>,
}
impl NameIndex {
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
#[allow(dead_code)]
pub fn insert(&mut self, name: impl Into<String>) -> usize {
let name = name.into();
if let Some(&id) = self.index.get(&name) {
return id;
}
let id = self.names.len();
self.index.insert(name.clone(), id);
self.names.push(name);
id
}
#[allow(dead_code)]
pub fn get_id(&self, name: &str) -> Option<usize> {
self.index.get(name).copied()
}
#[allow(dead_code)]
pub fn get_name(&self, id: usize) -> Option<&str> {
self.names.get(id).map(|s| s.as_str())
}
#[allow(dead_code)]
pub fn len(&self) -> usize {
self.names.len()
}
#[allow(dead_code)]
pub fn is_empty(&self) -> bool {
self.names.is_empty()
}
#[allow(dead_code)]
pub fn all_names(&self) -> &[String] {
&self.names
}
}
#[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 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 BatchDefEqChecker<'env> {
checker: DefEqChecker<'env>,
}
impl<'env> BatchDefEqChecker<'env> {
#[allow(dead_code)]
pub fn new(env: &'env Environment) -> Self {
Self {
checker: DefEqChecker::new(env),
}
}
#[allow(dead_code)]
pub fn check(&mut self, t: &Expr, s: &Expr) -> bool {
self.checker.is_def_eq(t, s)
}
#[allow(dead_code)]
pub fn check_all(&mut self, pairs: &[(Expr, Expr)]) -> bool {
pairs.iter().all(|(t, s)| self.checker.is_def_eq(t, s))
}
#[allow(dead_code)]
pub fn check_any(&mut self, pairs: &[(Expr, Expr)]) -> bool {
pairs.iter().any(|(t, s)| self.checker.is_def_eq(t, s))
}
#[allow(dead_code)]
pub fn count_equal(&mut self, pairs: &[(Expr, Expr)]) -> usize {
pairs
.iter()
.filter(|(t, s)| self.checker.is_def_eq(t, s))
.count()
}
#[allow(dead_code)]
pub fn reset(&mut self) {
self.checker.cache.clear();
self.checker.equiv_manager.clear();
}
}
#[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 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 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 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)]
#[derive(Debug, Clone, Default)]
pub struct DefEqStats {
pub cache_hits: u64,
pub cache_misses: u64,
pub reduction_steps: u64,
pub delta_reductions: u64,
pub beta_reductions: u64,
pub eta_attempts: u64,
pub equiv_hits: u64,
}
impl DefEqStats {
#[allow(dead_code)]
pub fn cache_hit_rate(&self) -> f64 {
let total = self.cache_hits + self.cache_misses;
if total == 0 {
1.0
} else {
self.cache_hits as f64 / total as f64
}
}
#[allow(dead_code)]
pub fn total_cache_accesses(&self) -> u64 {
self.cache_hits + self.cache_misses
}
#[allow(dead_code)]
pub fn total_reductions(&self) -> u64 {
self.reduction_steps + self.delta_reductions + self.beta_reductions
}
}
#[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)]
#[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 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 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 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 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()
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum ReductionStatus {
Continue(Expr, Expr),
Equal,
Stuck,
Unknown,
}
#[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)]
pub struct DefEqConfig {
pub max_steps: u32,
pub proof_irrelevance: bool,
pub eta: bool,
pub lazy_delta: bool,
pub transparency: TransparencyMode,
}
impl DefEqConfig {
#[allow(dead_code)]
pub fn full_transparency() -> Self {
Self {
transparency: TransparencyMode::All,
..Self::default()
}
}
#[allow(dead_code)]
pub fn opaque() -> Self {
Self {
lazy_delta: false,
transparency: TransparencyMode::None,
..Self::default()
}
}
#[allow(dead_code)]
pub fn no_proof_irrelevance() -> Self {
Self {
proof_irrelevance: false,
..Self::default()
}
}
}
#[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)]
#[derive(Debug, Clone, Default)]
pub struct StringTrie {
pub(super) children: std::collections::HashMap<char, StringTrie>,
is_end: bool,
pub(super) value: Option<String>,
}
impl StringTrie {
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
#[allow(dead_code)]
pub fn insert(&mut self, s: &str) {
let mut node = self;
for c in s.chars() {
node = node.children.entry(c).or_default();
}
node.is_end = true;
node.value = Some(s.to_string());
}
#[allow(dead_code)]
pub fn contains(&self, s: &str) -> bool {
let mut node = self;
for c in s.chars() {
match node.children.get(&c) {
Some(next) => node = next,
None => return false,
}
}
node.is_end
}
#[allow(dead_code)]
pub fn starts_with(&self, prefix: &str) -> Vec<String> {
let mut node = self;
for c in prefix.chars() {
match node.children.get(&c) {
Some(next) => node = next,
None => return vec![],
}
}
let mut results = Vec::new();
collect_strings(node, &mut results);
results
}
#[allow(dead_code)]
pub fn len(&self) -> usize {
let mut count = if self.is_end { 1 } else { 0 };
for child in self.children.values() {
count += child.len();
}
count
}
#[allow(dead_code)]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[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 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 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)]
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 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)]
#[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 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 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
}
}
pub struct DefEqChecker<'env> {
env: &'env Environment,
reducer: Reducer,
cache: HashMap<(Expr, Expr), bool>,
equiv_manager: EquivManager,
proof_irrelevance: bool,
}
impl<'env> DefEqChecker<'env> {
pub fn new(env: &'env Environment) -> Self {
Self {
env,
reducer: Reducer::new(),
cache: HashMap::new(),
equiv_manager: EquivManager::new(),
proof_irrelevance: true,
}
}
pub fn set_proof_irrelevance(&mut self, enabled: bool) {
self.proof_irrelevance = enabled;
}
pub fn set_transparency(&mut self, mode: TransparencyMode) {
self.reducer.set_transparency(mode);
self.cache.clear();
self.equiv_manager.clear();
}
pub fn is_def_eq(&mut self, t: &Expr, s: &Expr) -> bool {
if t == s {
return true;
}
if self.equiv_manager.is_equiv(t, s) {
return true;
}
if self.equiv_manager.is_failure(t, s) {
return false;
}
let key = (t.clone(), s.clone());
if let Some(&result) = self.cache.get(&key) {
return result;
}
let result = self.is_def_eq_core(t, s);
self.cache.insert(key, result);
if result {
self.equiv_manager.add_equiv(t, s);
} else {
self.equiv_manager.add_failure(t, s);
}
result
}
fn is_def_eq_core(&mut self, t: &Expr, s: &Expr) -> bool {
let t_whnf = self.reducer.whnf_env(t, self.env);
let s_whnf = self.reducer.whnf_env(s, self.env);
if t_whnf == s_whnf {
return true;
}
if self.is_proof_irrelevant_eq(&t_whnf, &s_whnf) {
return true;
}
match (&t_whnf, &s_whnf) {
(Expr::Sort(l1), Expr::Sort(l2)) => level::is_equivalent(l1, l2),
(Expr::BVar(i1), Expr::BVar(i2)) => i1 == i2,
(Expr::FVar(id1), Expr::FVar(id2)) => id1 == id2,
(Expr::Const(n1, ls1), Expr::Const(n2, ls2)) => {
n1 == n2
&& ls1.len() == ls2.len()
&& ls1
.iter()
.zip(ls2.iter())
.all(|(l1, l2)| level::is_equivalent(l1, l2))
}
(Expr::App(f1, a1), Expr::App(f2, a2)) => {
if self.is_def_eq_app(&t_whnf, &s_whnf) {
return true;
}
self.is_def_eq(f1, f2) && self.is_def_eq(a1, a2)
}
(Expr::Lam(_, _, ty1, b1), Expr::Lam(_, _, ty2, b2)) => {
self.is_def_eq(ty1, ty2) && self.is_def_eq(b1, b2)
}
(Expr::Pi(_, _, ty1, b1), Expr::Pi(_, _, ty2, b2)) => {
self.is_def_eq(ty1, ty2) && self.is_def_eq(b1, b2)
}
(Expr::Let(_, ty1, v1, b1), Expr::Let(_, ty2, v2, b2)) => {
self.is_def_eq(ty1, ty2) && self.is_def_eq(v1, v2) && self.is_def_eq(b1, b2)
}
(Expr::Lit(l1), Expr::Lit(l2)) => l1 == l2,
(Expr::Proj(n1, i1, e1), Expr::Proj(n2, i2, e2)) => {
n1 == n2 && i1 == i2 && self.is_def_eq(e1, e2)
}
(Expr::Lam(_, _, _, _), _) => self.try_eta_lhs(&t_whnf, &s_whnf),
(_, Expr::Lam(_, _, _, _)) => self.try_eta_rhs(&t_whnf, &s_whnf),
_ => self.try_lazy_delta(&t_whnf, &s_whnf),
}
}
fn try_lazy_delta(&mut self, t: &Expr, s: &Expr) -> bool {
let t_head = get_app_fn(t);
let s_head = get_app_fn(s);
let t_hint = self.get_hint(t_head);
let s_hint = self.get_hint(s_head);
match (t_hint, s_hint) {
(Some(th), Some(sh)) => {
if th.height() <= sh.height() {
if let Some(t_unfolded) = self.unfold_definition(t) {
let t_whnf = self.reducer.whnf_env(&t_unfolded, self.env);
return self.is_def_eq(&t_whnf, s);
}
}
if let Some(s_unfolded) = self.unfold_definition(s) {
let s_whnf = self.reducer.whnf_env(&s_unfolded, self.env);
return self.is_def_eq(t, &s_whnf);
}
false
}
(Some(_), None) => {
if let Some(t_unfolded) = self.unfold_definition(t) {
let t_whnf = self.reducer.whnf_env(&t_unfolded, self.env);
return self.is_def_eq(&t_whnf, s);
}
false
}
(None, Some(_)) => {
if let Some(s_unfolded) = self.unfold_definition(s) {
let s_whnf = self.reducer.whnf_env(&s_unfolded, self.env);
return self.is_def_eq(t, &s_whnf);
}
false
}
(None, None) => false,
}
}
fn get_hint(&self, head: &Expr) -> Option<ReducibilityHint> {
if let Expr::Const(name, _) = head {
if let Some(ci) = self.env.find(name) {
let hint = ci.reducibility_hint();
if hint.should_unfold() {
return Some(hint);
}
}
}
None
}
fn unfold_definition(&self, expr: &Expr) -> Option<Expr> {
let head = get_app_fn(expr);
if let Expr::Const(name, levels) = head {
if let Some(ci) = self.env.find(name) {
if let Some(val) = ci.value() {
let val_inst = if ci.level_params().is_empty() || levels.is_empty() {
val.clone()
} else {
crate::instantiate::instantiate_type_lparams(val, ci.level_params(), levels)
};
let args: Vec<Expr> = get_app_args(expr).into_iter().cloned().collect();
return Some(crate::expr_util::mk_app(val_inst, &args));
}
}
}
None
}
fn is_def_eq_app(&mut self, t: &Expr, s: &Expr) -> bool {
let t_head = get_app_fn(t);
let s_head = get_app_fn(s);
let t_args = get_app_args(t);
let s_args = get_app_args(s);
if t_args.len() != s_args.len() {
return false;
}
if !self.is_def_eq(t_head, s_head) {
return false;
}
t_args
.iter()
.zip(s_args.iter())
.all(|(a, b)| self.is_def_eq(a, b))
}
fn quick_infer_type(&mut self, expr: &Expr) -> Option<Expr> {
match expr {
Expr::Sort(l) => Some(Expr::Sort(crate::level::Level::succ(l.clone()))),
Expr::Lit(crate::Literal::Nat(_)) => Some(Expr::Const(crate::Name::str("Nat"), vec![])),
Expr::Lit(crate::Literal::Str(_)) => {
Some(Expr::Const(crate::Name::str("String"), vec![]))
}
Expr::Const(name, levels) => {
let ci = self.env.find(name)?;
let raw_ty = ci.ty().clone();
let params = ci.level_params().to_vec();
if params.is_empty() || levels.is_empty() {
Some(raw_ty)
} else {
Some(crate::instantiate::instantiate_type_lparams(
&raw_ty, ¶ms, levels,
))
}
}
Expr::App(f, a) => {
let f_ty = self.quick_infer_type(f)?;
let f_ty_whnf = self.reducer.whnf_env(&f_ty, self.env);
if let Expr::Pi(_, _, _, body) = f_ty_whnf {
Some(crate::subst::instantiate(&body, a))
} else {
None
}
}
Expr::Lam(bi, name, dom, body) => {
let body_ty = self.quick_infer_type(body)?;
Some(Expr::Pi(*bi, name.clone(), dom.clone(), Box::new(body_ty)))
}
Expr::Pi(_, _, dom, cod) => {
let dom_ty = self.quick_infer_type(dom)?;
let cod_ty = self.quick_infer_type(cod)?;
let dom_whnf = self.reducer.whnf_env(&dom_ty, self.env);
let cod_whnf = self.reducer.whnf_env(&cod_ty, self.env);
match (dom_whnf, cod_whnf) {
(Expr::Sort(l1), Expr::Sort(l2)) => {
Some(Expr::Sort(crate::level::Level::imax(l1, l2)))
}
_ => None,
}
}
Expr::Let(_, _ty, val, body) => {
let body_subst = crate::subst::instantiate(body, val);
self.quick_infer_type(&body_subst)
}
_ => None,
}
}
fn is_proof_irrelevant_eq(&mut self, t: &Expr, s: &Expr) -> bool {
if !self.proof_irrelevance {
return false;
}
let ty_t = match self.quick_infer_type(t) {
Some(ty) => ty,
None => return false,
};
let ty_ty_t = match self.quick_infer_type(&ty_t) {
Some(ty) => ty,
None => return false,
};
let ty_ty_t_whnf = self.reducer.whnf_env(&ty_ty_t, self.env);
if !matches!(& ty_ty_t_whnf, Expr::Sort(l) if l.is_zero()) {
return false;
}
let ty_s = match self.quick_infer_type(s) {
Some(ty) => ty,
None => return false,
};
let ty_ty_s = match self.quick_infer_type(&ty_s) {
Some(ty) => ty,
None => return false,
};
let ty_ty_s_whnf = self.reducer.whnf_env(&ty_ty_s, self.env);
if !matches!(& ty_ty_s_whnf, Expr::Sort(l) if l.is_zero()) {
return false;
}
let ty_t_whnf = self.reducer.whnf_env(&ty_t, self.env);
let ty_s_whnf = self.reducer.whnf_env(&ty_s, self.env);
self.is_def_eq(&ty_t_whnf, &ty_s_whnf)
}
fn try_eta_lhs(&mut self, t: &Expr, s: &Expr) -> bool {
if let Expr::Lam(_, _, _, body) = t {
if let Expr::App(f, a) = body.as_ref() {
if let Expr::BVar(0) = **a {
if !has_loose_bvar(f, 0) {
let f_shifted =
crate::subst::instantiate(f, &Expr::FVar(crate::FVarId(u64::MAX)));
return self.is_def_eq(&f_shifted, s);
}
}
}
}
false
}
fn try_eta_rhs(&mut self, t: &Expr, s: &Expr) -> bool {
if let Expr::Lam(_, _, _, body) = s {
if let Expr::App(f, a) = body.as_ref() {
if let Expr::BVar(0) = **a {
if !has_loose_bvar(f, 0) {
let f_shifted =
crate::subst::instantiate(f, &Expr::FVar(crate::FVarId(u64::MAX)));
return self.is_def_eq(t, &f_shifted);
}
}
}
}
false
}
}
#[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()
}
}