1mod temporal;
19
20use alloc::format;
21use alloc::string::String;
22use alloc::vec::Vec;
23
24use pddl::{AtomicFormula, Domain, InitElement, Literal, Problem};
25
26use crate::atom::{lower, Atom};
27use crate::derived;
28use crate::effects::Changes;
29use crate::error::ModelError;
30use crate::eval::{EvalError, Evaluator, Scope};
31use crate::model::check::{self, Issue};
32use crate::model::universe::type_text;
33use crate::model::{self as model, Model};
34use crate::plan::{Plan, PlanStep};
35use crate::report::{
36 Construct, Metric, Outcome, Report, StepRef, StepTrace, Unsupported, Violation, ViolationKind,
37};
38use crate::state::State;
39
40#[derive(Debug)]
68pub struct Validator<'a> {
69 inner: Inner<'a>,
71 tolerance: f64,
73 epsilon: f64,
75 duration_tolerance: f64,
78}
79
80pub const DEFAULT_TOLERANCE: f64 = 1e-12;
88
89pub const DEFAULT_EPSILON: f64 = 0.01;
91
92pub const DEFAULT_DURATION_TOLERANCE: f64 = 0.0005;
102
103#[derive(Debug)]
105#[expect(
106 clippy::large_enum_variant,
107 reason = "one per validator, built once; boxing buys nothing"
108)]
109enum Inner<'a> {
110 Ready {
112 model: Model<'a>,
114 problem: &'a Problem,
116 initial: State,
118 },
119 Unsupported(Unsupported),
121}
122
123enum Stop {
125 Invalid(ViolationKind),
127 Unsupported(Construct),
129}
130
131impl From<EvalError> for Stop {
132 fn from(error: EvalError) -> Self {
133 match error {
134 EvalError::Unsupported(construct) => Self::Unsupported(construct),
135 EvalError::Undefined(fluent) => Self::Invalid(ViolationKind::Undefined(fluent)),
136 EvalError::DivisionByZero(exp) => Self::Invalid(ViolationKind::DivisionByZero(exp)),
137 EvalError::NonFinite(exp) => Self::Invalid(ViolationKind::NonFinite(exp)),
138 EvalError::ConflictingUpdates(fluent) => {
139 Self::Invalid(ViolationKind::ConflictingUpdates(fluent))
140 }
141 }
142 }
143}
144
145impl<'a> Validator<'a> {
146 pub fn new(domain: &'a Domain, problem: &'a Problem) -> Result<Self, ModelError> {
159 model::check_domain_name(domain, problem)?;
160 if let Some(unsupported) = model::unsupported_sections(domain, problem) {
161 return Ok(Self::unsupported(unsupported));
162 }
163
164 let mut model = Model::new(domain, problem)?;
165 let checked =
166 check::check_function_types(domain).and_then(|()| check::check(&model, problem));
167 match checked {
168 Err(Issue::Model(error)) => return Err(error),
169 Err(Issue::Unsupported(unsupported)) => return Ok(Self::unsupported(unsupported)),
170 Ok(()) => {}
171 }
172
173 if let Err(unsupported) = derived::stratify(&mut model) {
174 return Ok(Self::unsupported(unsupported));
175 }
176
177 let initial = initial_state(&model, problem);
178
179 Ok(Self {
180 inner: Inner::Ready {
181 model,
182 problem,
183 initial,
184 },
185 tolerance: DEFAULT_TOLERANCE,
186 epsilon: DEFAULT_EPSILON,
187 duration_tolerance: DEFAULT_DURATION_TOLERANCE,
188 })
189 }
190
191 const fn unsupported(unsupported: Unsupported) -> Self {
193 Self {
194 inner: Inner::Unsupported(unsupported),
195 tolerance: DEFAULT_TOLERANCE,
196 epsilon: DEFAULT_EPSILON,
197 duration_tolerance: DEFAULT_DURATION_TOLERANCE,
198 }
199 }
200
201 #[must_use]
227 pub fn with_tolerance(mut self, tolerance: f64) -> Self {
228 self.tolerance = if tolerance > 0.0 { tolerance } else { 0.0 };
229 self
230 }
231
232 #[must_use]
241 pub fn with_epsilon(mut self, epsilon: f64) -> Self {
242 self.epsilon = if epsilon > 0.0 { epsilon } else { 0.0 };
243 self
244 }
245
246 #[must_use]
253 pub fn with_duration_tolerance(mut self, tolerance: f64) -> Self {
254 self.duration_tolerance = if tolerance > 0.0 { tolerance } else { 0.0 };
255 self
256 }
257
258 #[must_use]
263 pub fn validate_text(&self, text: &str) -> Report {
264 match text.parse::<Plan>() {
265 Ok(plan) => self.validate(&plan),
266 Err(error) => {
267 let violation = Violation {
268 step: None,
269 kind: ViolationKind::PlanSyntax(error),
270 };
271 Report::new(Outcome::Invalid(violation), Vec::new())
272 }
273 }
274 }
275
276 #[must_use]
281 pub fn validate(&self, plan: &Plan) -> Report {
282 let (model, problem, initial) = match &self.inner {
283 Inner::Ready {
284 model,
285 problem,
286 initial,
287 } => (model, problem, initial),
288 Inner::Unsupported(unsupported) => {
289 return Report::new(Outcome::Unsupported(unsupported.clone()), Vec::new());
290 }
291 };
292
293 let tolerance = self.tolerance;
294 let timed = plan.steps().iter().any(|step| step.time().is_some());
295 if timed || model.is_temporal(problem) {
296 if !model.rules.is_empty() {
297 let construct = Construct::DerivedPredicatesInTemporalPlans;
298 let unsupported = Unsupported::new(construct, "domain");
299 return Report::new(Outcome::Unsupported(unsupported), Vec::new());
300 }
301
302 let timeline = temporal::Timeline {
303 model,
304 problem,
305 tolerance,
306 epsilon: self.epsilon,
307 duration_tolerance: self.duration_tolerance,
308 };
309 return timeline.run(initial, plan);
310 }
311
312 let mut state = initial.clone();
313 let mut trace = Vec::new();
314 if let Err(error) = derived::close(model, &mut state, tolerance) {
315 return stopped(Stop::from(error), None, String::from("init"), trace);
316 }
317
318 for (index, step) in plan.steps().iter().enumerate() {
319 let at = step_ref(index, step);
320 match run_step(model, &mut state, step, tolerance) {
321 Ok(mut changes) => {
322 changes.step = Some(at);
323 trace.push(changes);
324 }
325 Err(stop) => {
326 let location = format!("step {}", at.number);
327 return stopped(stop, Some(at), location, trace);
328 }
329 }
330 }
331
332 #[expect(
333 clippy::cast_precision_loss,
334 reason = "plans of more than 2^53 steps do not fit in memory"
335 )]
336 let total_time = plan.len() as f64;
337 let evaluator = Evaluator {
338 model,
339 state: &state,
340 tolerance,
341 observer: None,
342 };
343
344 finish(&evaluator, problem, total_time, trace)
345 }
346}
347
348fn finish(
352 evaluator: &Evaluator<'_, '_>,
353 problem: &Problem,
354 total_time: f64,
355 trace: Vec<StepTrace>,
356) -> Report {
357 match evaluator.preconditions(problem.goals(), &mut Scope::new()) {
358 Ok(None) => {}
359 Ok(Some(unmet)) => {
360 let kind = ViolationKind::GoalUnsatisfied(unmet);
361 return stopped(Stop::Invalid(kind), None, String::from("goal"), trace);
362 }
363 Err(error) => return stopped(Stop::from(error), None, String::from("goal"), trace),
364 }
365
366 let Some(spec) = problem.metric_spec() else {
367 return Report::new(Outcome::Valid, trace);
368 };
369
370 match evaluator.metric(spec.expression(), total_time) {
371 Ok(value) => Report::new(Outcome::Valid, trace).with_metric(Metric {
372 optimization: spec.optimization(),
373 value,
374 }),
375 Err(error) if error.is_unknown() => Report::new(Outcome::Valid, trace),
376 Err(error) => stopped(Stop::from(error), None, String::from("metric"), trace),
377 }
378}
379
380fn step_ref(index: usize, step: &PlanStep) -> StepRef {
382 StepRef {
383 number: index + 1,
384 line: step.line(),
385 action: alloc::string::ToString::to_string(step),
386 time: step.time(),
387 }
388}
389
390fn stopped(reason: Stop, step: Option<StepRef>, location: String, trace: Vec<StepTrace>) -> Report {
392 match reason {
393 Stop::Invalid(kind) => Report::new(Outcome::Invalid(Violation { step, kind }), trace),
394 Stop::Unsupported(construct) => {
395 let unsupported = Unsupported::new(construct, location);
396 Report::new(Outcome::Unsupported(unsupported), Vec::new())
397 }
398 }
399}
400
401fn run_step(
403 model: &Model<'_>,
404 state: &mut State,
405 step: &PlanStep,
406 tolerance: f64,
407) -> Result<StepTrace, Stop> {
408 let (action, mut scope) = bind(model, step)?;
409 if step.duration().is_some() {
410 return Err(Stop::Invalid(ViolationKind::UnexpectedDuration));
411 }
412
413 let evaluator = Evaluator {
414 model,
415 state: &*state,
416 tolerance,
417 observer: None,
418 };
419 if let Some(unmet) = evaluator.preconditions(action.precondition(), &mut scope)? {
420 return Err(Stop::Invalid(ViolationKind::PreconditionUnsatisfied(unmet)));
421 }
422
423 let mut changes = Changes::default();
424 if let Some(effects) = action.effect() {
425 changes.collect(&evaluator, effects, &mut scope)?;
426 }
427
428 let trace = changes.apply(state)?;
429 derived::close(model, state, tolerance)?;
430
431 Ok(trace)
432}
433
434fn bind<'m>(
436 model: &'m Model<'_>,
437 step: &PlanStep,
438) -> Result<(&'m pddl::ActionDefinition, Scope), Stop> {
439 let Some(action) = model.actions.get(step.action()) else {
440 let kind = ViolationKind::UnknownAction(String::from(step.action()));
441 return Err(Stop::Invalid(kind));
442 };
443
444 Ok((action, bind_parameters(model, action.parameters(), step)?))
445}
446
447fn bind_parameters(
449 model: &Model<'_>,
450 parameters: &pddl::TypedVariables,
451 step: &PlanStep,
452) -> Result<Scope, Stop> {
453 let invalid = |kind| Err(Stop::Invalid(kind));
454 if parameters.len() != step.arguments().len() {
455 return invalid(ViolationKind::Arity {
456 expected: parameters.len(),
457 found: step.arguments().len(),
458 });
459 }
460
461 let mut scope = Scope::new();
462 for (parameter, object) in parameters.iter().zip(step.arguments()) {
463 let name = lower(parameter.value());
464 if !model.universe.contains(object) {
465 return invalid(ViolationKind::UnknownObject {
466 parameter: name,
467 object: object.clone(),
468 });
469 }
470
471 if !model.universe.is_of(object, parameter.type_()) {
472 return invalid(ViolationKind::TypeMismatch {
473 parameter: name,
474 object: object.clone(),
475 expected: type_text(parameter.type_()),
476 });
477 }
478
479 scope.push((name, object.clone()));
480 }
481
482 Ok(scope)
483}
484
485fn initial_state(model: &Model<'_>, problem: &Problem) -> State {
492 let mut state = State::default();
493 if model.functions.get(TOTAL_COST) == Some(&0) {
494 let total_cost = Atom::lowered(String::from(TOTAL_COST), Vec::new());
495 state.fluents.insert(total_cost, 0.0);
496 }
497
498 for element in problem.init().iter() {
499 match element {
500 InitElement::Literal(Literal::AtomicFormula(AtomicFormula::Predicate(atom))) => {
501 let arguments = atom.values().iter().map(|name| lower(name)).collect();
502 let atom = Atom::lowered(lower(atom.predicate()), arguments);
503 state.facts.insert(atom);
504 }
505 InitElement::IsValue(term, value) => {
506 let arguments = term.names().iter().map(|name| lower(name)).collect();
507 let fluent = Atom::lowered(lower(term.symbol()), arguments);
508 state.fluents.insert(fluent, **value);
509 }
510 InitElement::Literal(_) | InitElement::At(..) | InitElement::IsObject(..) => {}
511 }
512 }
513
514 state
515}
516
517const TOTAL_COST: &str = "total-cost";