use crate::errors::counted;
use std::fmt::{self, Display, Formatter};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serialize",
derive(Serialize, Deserialize),
serde(default, deny_unknown_fields)
)]
pub struct Limits {
#[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
pub memory_bytes: Option<u64>,
#[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
pub occurrences: Option<u64>,
#[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
pub terms: Option<u64>,
#[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
pub derivation_bytes: Option<u64>,
#[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
pub work: Option<u64>,
pub table_atoms: Option<u32>,
pub recursion_depth: u32,
}
impl Limits {
pub const DEFAULT_MEMORY_BYTES: u64 = 1 << 30;
pub const DEFAULT_OCCURRENCES: u64 = 50_000_000;
pub const DEFAULT_TERMS: u64 = 50_000_000;
pub const DEFAULT_DERIVATION_BYTES: u64 = 64 << 20;
pub const DEFAULT_TABLE_ATOMS: u32 = 10;
pub const DEFAULT_RECURSION_DEPTH: u32 = 2048;
pub const UNBOUNDED: Self = Self {
memory_bytes: None,
occurrences: None,
terms: None,
derivation_bytes: None,
work: None,
table_atoms: None,
recursion_depth: Self::DEFAULT_RECURSION_DEPTH,
};
const PER_LEVEL: usize = if cfg!(debug_assertions) { 13312 } else { 3072 };
const RESERVE: usize = 1 << 20;
#[must_use]
pub const fn stack_bytes(&self) -> usize {
let needed = (self.recursion_depth as usize)
.saturating_mul(Self::PER_LEVEL)
.saturating_add(Self::RESERVE);
if needed > 8 << 20 { needed } else { 8 << 20 }
}
#[must_use]
pub const fn recursion_depth_for_stack(bytes: usize) -> u32 {
let levels = bytes.saturating_sub(Self::RESERVE) / Self::PER_LEVEL;
if levels > u32::MAX as usize {
u32::MAX
} else {
levels as u32
}
}
#[must_use]
pub const fn with_memory_bytes(mut self, memory_bytes: Option<u64>) -> Self {
self.memory_bytes = memory_bytes;
self
}
#[must_use]
pub const fn with_occurrences(mut self, occurrences: Option<u64>) -> Self {
self.occurrences = occurrences;
self
}
#[must_use]
pub const fn with_terms(mut self, terms: Option<u64>) -> Self {
self.terms = terms;
self
}
#[must_use]
pub const fn with_derivation_bytes(mut self, derivation_bytes: Option<u64>) -> Self {
self.derivation_bytes = derivation_bytes;
self
}
#[must_use]
pub const fn with_work(mut self, work: Option<u64>) -> Self {
self.work = work;
self
}
#[must_use]
pub const fn with_table_atoms(mut self, table_atoms: Option<u32>) -> Self {
self.table_atoms = table_atoms;
self
}
#[must_use]
pub const fn with_recursion_depth(mut self, recursion_depth: u32) -> Self {
self.recursion_depth = recursion_depth;
self
}
}
impl Default for Limits {
fn default() -> Self {
Self {
memory_bytes: Some(Self::DEFAULT_MEMORY_BYTES),
occurrences: Some(Self::DEFAULT_OCCURRENCES),
terms: Some(Self::DEFAULT_TERMS),
derivation_bytes: Some(Self::DEFAULT_DERIVATION_BYTES),
work: None,
table_atoms: Some(Self::DEFAULT_TABLE_ATOMS),
recursion_depth: Self::DEFAULT_RECURSION_DEPTH,
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
pub struct Progress {
pub work: u64,
pub done: u64,
pub held_bytes: u64,
pub phase: Phase,
pub item: u32,
}
impl Progress {
pub(crate) const fn new(phase: Phase, work: u64, done: u64) -> Self {
Self {
work,
done,
held_bytes: 0,
phase,
item: 0,
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serialize",
derive(Serialize),
serde(rename_all = "snake_case")
)]
pub enum Phase {
#[default]
Read,
Search,
Refute,
Check,
View,
Write,
Render,
Net,
ReadBack,
Eliminate,
}
impl Phase {
pub const fn name(self) -> &'static str {
match self {
Self::Read => "reading",
Self::Search => "search",
Self::Refute => "refutation",
Self::Check => "check",
Self::View => "derivation",
Self::Write => "writing",
Self::Render => "render",
Self::Net => "net",
Self::ReadBack => "read-back",
Self::Eliminate => "elimination",
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serialize",
derive(Serialize),
serde(rename_all = "snake_case")
)]
pub enum Space {
Atom,
Term,
Node,
Occurrence,
Member,
Vertex,
Inference,
Formula,
Symbol,
World,
}
impl Space {
pub(crate) const fn singular(self) -> &'static str {
match self {
Self::Atom => "atom",
Self::Term => "term",
Self::Node => "node",
Self::Occurrence => "occurrence",
Self::Member => "member",
Self::Vertex => "vertex",
Self::Inference => "inference",
Self::Formula => "formula",
Self::Symbol => "symbol",
Self::World => "world",
}
}
pub const fn plural(self) -> &'static str {
match self {
Self::Atom => "atoms",
Self::Term => "terms",
Self::Node => "nodes",
Self::Occurrence => "occurrences",
Self::Member => "members",
Self::Vertex => "vertices",
Self::Inference => "inferences",
Self::Formula => "formulas",
Self::Symbol => "symbols",
Self::World => "worlds",
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serialize",
derive(Serialize),
serde(rename_all = "snake_case")
)]
pub enum Bound {
Steps,
Nodes,
Vertices,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
feature = "serialize",
derive(Serialize),
serde(tag = "kind", rename_all = "snake_case")
)]
pub enum Refusal {
#[non_exhaustive]
Stopped {
phase: Phase,
},
#[non_exhaustive]
Memory {
phase: Phase,
limit_bytes: u64,
needed_bytes: Option<u64>,
},
#[non_exhaustive]
Occurrences {
occurrences: u64,
limit: u64,
},
#[non_exhaustive]
Terms {
terms: u64,
limit: u64,
},
#[non_exhaustive]
Output {
what: &'static str,
estimate_bytes: u64,
limit_bytes: u64,
least_bytes: Option<u64>,
},
#[non_exhaustive]
Work {
limit: u64,
},
#[non_exhaustive]
Pixels {
pixels: u64,
limit: u64,
},
#[non_exhaustive]
Elimination {
what: Bound,
limit: u64,
},
#[non_exhaustive]
Atoms {
atoms: u64,
limit: u64,
},
#[non_exhaustive]
Index {
what: Space,
count: u64,
most: u64,
},
}
impl Refusal {
pub const fn code(&self) -> &'static str {
match self {
Self::Stopped { .. } => "stopped",
Self::Memory { .. } => "memory_limit",
Self::Occurrences { .. } => "too_many_occurrences",
Self::Terms { .. } => "too_many_terms",
Self::Output { .. } => "output_too_large",
Self::Work { .. } => "work_limit",
Self::Pixels { .. } => "too_many_pixels",
Self::Elimination { .. } => "elimination_limit",
Self::Atoms { .. } => "too_many_atoms",
Self::Index { .. } => "index_limit",
}
}
pub const fn setting(&self) -> Option<&'static str> {
match self {
Self::Memory { .. } => Some("limits.memory_bytes"),
Self::Occurrences { .. } => Some("limits.occurrences"),
Self::Terms { .. } => Some("limits.terms"),
Self::Output { .. } => Some("limits.derivation_bytes"),
Self::Work { .. } => Some("limits.work"),
Self::Atoms { .. } => Some("limits.table_atoms"),
Self::Pixels { .. } => Some("styles.png.pixels"),
Self::Elimination {
what: Bound::Steps, ..
} => Some("cut.steps"),
Self::Elimination {
what: Bound::Nodes | Bound::Vertices,
..
} => Some("cut.nodes"),
Self::Stopped { .. } | Self::Index { .. } => None,
}
}
pub const fn is_stop(&self) -> bool {
matches!(self, Self::Stopped { .. })
}
}
impl Display for Refusal {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Stopped { phase } => write!(f, "the {} was stopped", phase.name()),
Self::Memory {
phase,
limit_bytes,
needed_bytes: Some(needed),
} => write!(
f,
"the {} would take {}, more than the memory limit of {}",
phase.name(),
counted(*needed, "byte", "bytes"),
counted(*limit_bytes, "byte", "bytes")
),
Self::Memory {
phase,
limit_bytes,
needed_bytes: None,
} => write!(
f,
"the {} takes more than the memory limit of {}",
phase.name(),
counted(*limit_bytes, "byte", "bytes")
),
Self::Occurrences { occurrences, limit } => write!(
f,
"the sequent unfolds to at least {}, more than the limit of {limit}",
counted(
*occurrences,
"subformula occurrence",
"subformula occurrences"
)
),
Self::Terms { terms, limit } => write!(
f,
"the first-order terms unfold to at least {}, more than the limit of {limit}",
counted(*terms, "term", "terms")
),
Self::Output {
what,
estimate_bytes,
limit_bytes,
least_bytes,
} => {
write!(
f,
"the {what} is estimated at {}, more than the limit of {limit_bytes}",
counted(*estimate_bytes, "byte", "bytes")
)?;
match least_bytes {
Some(least) => write!(
f,
", and a compact one at {} at least",
counted(*least, "byte", "bytes")
),
None => Ok(()),
}
}
Self::Work { limit } => {
write!(
f,
"the call did the most work allowed, {}",
counted(*limit, "unit", "units")
)
}
Self::Pixels { pixels, limit } => write!(
f,
"the image would have {}, more than the limit of {limit}",
counted(*pixels, "pixel", "pixels")
),
Self::Elimination {
what: Bound::Steps,
limit,
} => write!(f, "the elimination took the most steps allowed, {limit}"),
Self::Elimination {
what: Bound::Nodes,
limit,
} => write!(
f,
"the next step of the elimination makes a proof of more than {}",
counted(*limit, "node", "nodes")
),
Self::Elimination {
what: Bound::Vertices,
limit,
} => write!(
f,
"the next step of the elimination makes a net of more than {}",
counted(*limit, "vertex", "vertices")
),
Self::Atoms { atoms, limit } => write!(
f,
"the truth table of {} would have 2^{atoms} rows, more than the limit of {} \
allows",
counted(*atoms, "atom", "atoms"),
counted(*limit, "atom", "atoms")
),
Self::Index { what, count, most } => write!(
f,
"{count} {} are more than this representation can index ({most})",
what.plural()
),
}
}
}
impl std::error::Error for Refusal {}
pub(crate) fn counting(
mut stop: impl FnMut(Progress) -> bool,
phase: Phase,
) -> impl FnMut() -> bool {
let mut done = 0u64;
move || {
done = done.saturating_add(1);
stop(Progress::new(phase, 1, done))
}
}