mod temporal;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use pddl::{AtomicFormula, Domain, InitElement, Literal, Problem};
use crate::atom::{lower, Atom};
use crate::derived;
use crate::effects::Changes;
use crate::error::ModelError;
use crate::eval::{EvalError, Evaluator, Scope};
use crate::model::check::{self, Issue};
use crate::model::universe::type_text;
use crate::model::{self as model, Model};
use crate::plan::{Plan, PlanStep};
use crate::report::{
Construct, Metric, Outcome, Report, StepRef, StepTrace, Unsupported, Violation, ViolationKind,
};
use crate::state::State;
#[derive(Debug)]
pub struct Validator<'a> {
inner: Inner<'a>,
tolerance: f64,
epsilon: f64,
duration_tolerance: f64,
}
pub const DEFAULT_TOLERANCE: f64 = 1e-12;
pub const DEFAULT_EPSILON: f64 = 0.01;
pub const DEFAULT_DURATION_TOLERANCE: f64 = 0.0005;
#[derive(Debug)]
#[expect(
clippy::large_enum_variant,
reason = "one per validator, built once; boxing buys nothing"
)]
enum Inner<'a> {
Ready {
model: Model<'a>,
problem: &'a Problem,
initial: State,
},
Unsupported(Unsupported),
}
enum Stop {
Invalid(ViolationKind),
Unsupported(Construct),
}
impl From<EvalError> for Stop {
fn from(error: EvalError) -> Self {
match error {
EvalError::Unsupported(construct) => Self::Unsupported(construct),
EvalError::Undefined(fluent) => Self::Invalid(ViolationKind::Undefined(fluent)),
EvalError::DivisionByZero(exp) => Self::Invalid(ViolationKind::DivisionByZero(exp)),
EvalError::NonFinite(exp) => Self::Invalid(ViolationKind::NonFinite(exp)),
EvalError::ConflictingUpdates(fluent) => {
Self::Invalid(ViolationKind::ConflictingUpdates(fluent))
}
}
}
}
impl<'a> Validator<'a> {
pub fn new(domain: &'a Domain, problem: &'a Problem) -> Result<Self, ModelError> {
model::check_domain_name(domain, problem)?;
if let Some(unsupported) = model::unsupported_sections(domain, problem) {
return Ok(Self::unsupported(unsupported));
}
let mut model = Model::new(domain, problem)?;
let checked =
check::check_function_types(domain).and_then(|()| check::check(&model, problem));
match checked {
Err(Issue::Model(error)) => return Err(error),
Err(Issue::Unsupported(unsupported)) => return Ok(Self::unsupported(unsupported)),
Ok(()) => {}
}
if let Err(unsupported) = derived::stratify(&mut model) {
return Ok(Self::unsupported(unsupported));
}
let initial = initial_state(&model, problem);
Ok(Self {
inner: Inner::Ready {
model,
problem,
initial,
},
tolerance: DEFAULT_TOLERANCE,
epsilon: DEFAULT_EPSILON,
duration_tolerance: DEFAULT_DURATION_TOLERANCE,
})
}
const fn unsupported(unsupported: Unsupported) -> Self {
Self {
inner: Inner::Unsupported(unsupported),
tolerance: DEFAULT_TOLERANCE,
epsilon: DEFAULT_EPSILON,
duration_tolerance: DEFAULT_DURATION_TOLERANCE,
}
}
#[must_use]
pub fn with_tolerance(mut self, tolerance: f64) -> Self {
self.tolerance = if tolerance > 0.0 { tolerance } else { 0.0 };
self
}
#[must_use]
pub fn with_epsilon(mut self, epsilon: f64) -> Self {
self.epsilon = if epsilon > 0.0 { epsilon } else { 0.0 };
self
}
#[must_use]
pub fn with_duration_tolerance(mut self, tolerance: f64) -> Self {
self.duration_tolerance = if tolerance > 0.0 { tolerance } else { 0.0 };
self
}
#[must_use]
pub fn validate_text(&self, text: &str) -> Report {
match text.parse::<Plan>() {
Ok(plan) => self.validate(&plan),
Err(error) => {
let violation = Violation {
step: None,
kind: ViolationKind::PlanSyntax(error),
};
Report::new(Outcome::Invalid(violation), Vec::new())
}
}
}
#[must_use]
pub fn validate(&self, plan: &Plan) -> Report {
let (model, problem, initial) = match &self.inner {
Inner::Ready {
model,
problem,
initial,
} => (model, problem, initial),
Inner::Unsupported(unsupported) => {
return Report::new(Outcome::Unsupported(unsupported.clone()), Vec::new());
}
};
let tolerance = self.tolerance;
let timed = plan.steps().iter().any(|step| step.time().is_some());
if timed || model.is_temporal(problem) {
if !model.rules.is_empty() {
let construct = Construct::DerivedPredicatesInTemporalPlans;
let unsupported = Unsupported::new(construct, "domain");
return Report::new(Outcome::Unsupported(unsupported), Vec::new());
}
let timeline = temporal::Timeline {
model,
problem,
tolerance,
epsilon: self.epsilon,
duration_tolerance: self.duration_tolerance,
};
return timeline.run(initial, plan);
}
let mut state = initial.clone();
let mut trace = Vec::new();
if let Err(error) = derived::close(model, &mut state, tolerance) {
return stopped(Stop::from(error), None, String::from("init"), trace);
}
for (index, step) in plan.steps().iter().enumerate() {
let at = step_ref(index, step);
match run_step(model, &mut state, step, tolerance) {
Ok(mut changes) => {
changes.step = Some(at);
trace.push(changes);
}
Err(stop) => {
let location = format!("step {}", at.number);
return stopped(stop, Some(at), location, trace);
}
}
}
#[expect(
clippy::cast_precision_loss,
reason = "plans of more than 2^53 steps do not fit in memory"
)]
let total_time = plan.len() as f64;
let evaluator = Evaluator {
model,
state: &state,
tolerance,
observer: None,
};
finish(&evaluator, problem, total_time, trace)
}
}
fn finish(
evaluator: &Evaluator<'_, '_>,
problem: &Problem,
total_time: f64,
trace: Vec<StepTrace>,
) -> Report {
match evaluator.preconditions(problem.goals(), &mut Scope::new()) {
Ok(None) => {}
Ok(Some(unmet)) => {
let kind = ViolationKind::GoalUnsatisfied(unmet);
return stopped(Stop::Invalid(kind), None, String::from("goal"), trace);
}
Err(error) => return stopped(Stop::from(error), None, String::from("goal"), trace),
}
let Some(spec) = problem.metric_spec() else {
return Report::new(Outcome::Valid, trace);
};
match evaluator.metric(spec.expression(), total_time) {
Ok(value) => Report::new(Outcome::Valid, trace).with_metric(Metric {
optimization: spec.optimization(),
value,
}),
Err(error) if error.is_unknown() => Report::new(Outcome::Valid, trace),
Err(error) => stopped(Stop::from(error), None, String::from("metric"), trace),
}
}
fn step_ref(index: usize, step: &PlanStep) -> StepRef {
StepRef {
number: index + 1,
line: step.line(),
action: alloc::string::ToString::to_string(step),
time: step.time(),
}
}
fn stopped(reason: Stop, step: Option<StepRef>, location: String, trace: Vec<StepTrace>) -> Report {
match reason {
Stop::Invalid(kind) => Report::new(Outcome::Invalid(Violation { step, kind }), trace),
Stop::Unsupported(construct) => {
let unsupported = Unsupported::new(construct, location);
Report::new(Outcome::Unsupported(unsupported), Vec::new())
}
}
}
fn run_step(
model: &Model<'_>,
state: &mut State,
step: &PlanStep,
tolerance: f64,
) -> Result<StepTrace, Stop> {
let (action, mut scope) = bind(model, step)?;
if step.duration().is_some() {
return Err(Stop::Invalid(ViolationKind::UnexpectedDuration));
}
let evaluator = Evaluator {
model,
state: &*state,
tolerance,
observer: None,
};
if let Some(unmet) = evaluator.preconditions(action.precondition(), &mut scope)? {
return Err(Stop::Invalid(ViolationKind::PreconditionUnsatisfied(unmet)));
}
let mut changes = Changes::default();
if let Some(effects) = action.effect() {
changes.collect(&evaluator, effects, &mut scope)?;
}
let trace = changes.apply(state)?;
derived::close(model, state, tolerance)?;
Ok(trace)
}
fn bind<'m>(
model: &'m Model<'_>,
step: &PlanStep,
) -> Result<(&'m pddl::ActionDefinition, Scope), Stop> {
let Some(action) = model.actions.get(step.action()) else {
let kind = ViolationKind::UnknownAction(String::from(step.action()));
return Err(Stop::Invalid(kind));
};
Ok((action, bind_parameters(model, action.parameters(), step)?))
}
fn bind_parameters(
model: &Model<'_>,
parameters: &pddl::TypedVariables,
step: &PlanStep,
) -> Result<Scope, Stop> {
let invalid = |kind| Err(Stop::Invalid(kind));
if parameters.len() != step.arguments().len() {
return invalid(ViolationKind::Arity {
expected: parameters.len(),
found: step.arguments().len(),
});
}
let mut scope = Scope::new();
for (parameter, object) in parameters.iter().zip(step.arguments()) {
let name = lower(parameter.value());
if !model.universe.contains(object) {
return invalid(ViolationKind::UnknownObject {
parameter: name,
object: object.clone(),
});
}
if !model.universe.is_of(object, parameter.type_()) {
return invalid(ViolationKind::TypeMismatch {
parameter: name,
object: object.clone(),
expected: type_text(parameter.type_()),
});
}
scope.push((name, object.clone()));
}
Ok(scope)
}
fn initial_state(model: &Model<'_>, problem: &Problem) -> State {
let mut state = State::default();
if model.functions.get(TOTAL_COST) == Some(&0) {
let total_cost = Atom::lowered(String::from(TOTAL_COST), Vec::new());
state.fluents.insert(total_cost, 0.0);
}
for element in problem.init().iter() {
match element {
InitElement::Literal(Literal::AtomicFormula(AtomicFormula::Predicate(atom))) => {
let arguments = atom.values().iter().map(|name| lower(name)).collect();
let atom = Atom::lowered(lower(atom.predicate()), arguments);
state.facts.insert(atom);
}
InitElement::IsValue(term, value) => {
let arguments = term.names().iter().map(|name| lower(name)).collect();
let fluent = Atom::lowered(lower(term.symbol()), arguments);
state.fluents.insert(fluent, **value);
}
InitElement::Literal(_) | InitElement::At(..) | InitElement::IsObject(..) => {}
}
}
state
}
const TOTAL_COST: &str = "total-cost";