use core::fmt;
use hir_lang::{Hir, IdKind};
use crate::profile::Discipline;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Budget {
pub steps: u64,
pub type_nodes: usize,
pub trait_depth: u32,
}
impl Default for Budget {
fn default() -> Self {
Self {
steps: 50_000_000,
type_nodes: 1 << 26,
trait_depth: 256,
}
}
}
impl Budget {
#[must_use]
pub fn for_hir(hir: &Hir) -> Self {
let nodes: usize = [
IdKind::Item,
IdKind::Expr,
IdKind::Stmt,
IdKind::Pat,
IdKind::Ty,
IdKind::Path,
IdKind::Field,
IdKind::Variant,
IdKind::Param,
IdKind::Binder,
]
.into_iter()
.map(|k| hir.count(k))
.sum();
let base = Self::default();
Self {
steps: base.steps.max((nodes as u64).saturating_mul(256)),
type_nodes: base.type_nodes.max(nodes.saturating_mul(64)),
trait_depth: base.trait_depth,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Limit {
Steps,
TypeNodes,
TraitDepth,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CheckError {
NotImplemented {
discipline: Discipline,
},
InvalidProfile,
BudgetExceeded {
limit: Limit,
},
}
impl fmt::Display for CheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotImplemented { discipline } => write!(
f,
"the `{}` discipline is not implemented in this version",
discipline.name()
),
Self::InvalidProfile => f.write_str(
"invalid profile: the literal defaults must be an integer and a float type",
),
Self::BudgetExceeded { limit } => write!(
f,
"type checking exceeded its {} budget",
match limit {
Limit::Steps => "step",
Limit::TypeNodes => "type-store",
Limit::TraitDepth => "trait-resolution depth",
}
),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for CheckError {}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Meter {
pub(crate) used: u64,
pub(crate) budget: Budget,
}
impl Meter {
pub(crate) const fn new(budget: Budget) -> Self {
Self { used: 0, budget }
}
#[inline]
pub(crate) fn tick(&mut self, n: u64) -> Result<(), CheckError> {
self.used = self.used.saturating_add(n);
if self.used > self.budget.steps {
Err(CheckError::BudgetExceeded {
limit: Limit::Steps,
})
} else {
Ok(())
}
}
}