use super::env::Env;
use super::{Expander, Options, Report};
use crate::diagnostic::{Code, Diagnostic, Location, Stage};
use crate::expanded::{self, Content, Origin};
use std::ops;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Used {
pub(crate) made: usize,
pub(crate) worked: usize,
}
impl ops::Add for Used {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
made: self.made + other.made,
worked: self.worked + other.worked,
}
}
}
impl Options {
#[must_use]
pub(crate) fn after(&self, used: Used) -> Self {
Self {
limit: self.limit.saturating_sub(used.made),
work: self.work.saturating_sub(used.worked),
..self.clone()
}
}
}
impl Expander<'_> {
pub(super) fn used(&self) -> Used {
Used {
made: self.made,
worked: self.worked,
}
}
pub(super) fn made(&mut self, content: Content, origin: Option<Origin>) -> expanded::Node {
self.made += 1;
if self.made > self.options.limit {
let limit = self.options.limit;
self.cross(format!(
"the expanded document would have more than {limit} nodes; this renders its fallback"
));
}
expanded::Node { content, origin }
}
fn worked(&mut self) {
self.worked += 1;
if self.worked > self.options.work {
let work = self.options.work;
self.cross(format!(
"the expansion would take more than {work} iterations and invocations; this renders its fallback"
));
}
}
fn cross(&mut self, message: String) {
if self.crossed.is_some() {
return;
}
let Some((id, at)) = self.expanding.last().copied() else {
return;
};
self.crossed = Some(self.expanding.len());
self.reports.push(Report {
once: None,
diagnostic: Diagnostic::new(Code::F034, at, message)
.in_stage(Stage::Evaluate)
.in_file(self.resolved.file(id)),
});
}
pub(super) fn over_limit(&self) -> bool {
self.crossed.is_some()
}
pub(super) fn expanding<T>(
&mut self,
env: &Env,
at: Location,
expansion: impl FnOnce(&mut Self) -> T,
) -> Option<T> {
if self.over_limit() {
return None;
}
self.expanding.push((env.document, at));
let depth = self.expanding.len();
self.worked();
let result = (!self.over_limit()).then(|| expansion(self));
self.expanding.pop();
result.filter(|_| self.crossed != Some(depth))
}
pub(super) fn iterate<T>(
&mut self,
count: usize,
mut iteration: impl FnMut(&mut Self, usize) -> T,
) -> Vec<T> {
let mut done = Vec::new();
for index in 0..count {
self.worked();
if self.over_limit() {
break;
}
done.push(iteration(self, index));
}
done
}
}