1use std::collections::HashMap;
20
21use pddl_runtime::{Comparison, Expr, Formula};
22
23use crate::{
24 AtomicFormula, BinaryComparison, BinaryOp, FluentExpression, FunctionHead, GoalDescription,
25 InitElement, Literal, MetricFluentExpression, MultiOp, Name, Optimization,
26 PreconditionGoalDescription, PreconditionGoalDescriptions, PreferenceGoalDescription, Problem,
27 Term, Type, TypedVariables,
28};
29
30#[derive(Debug)]
32pub struct Signature {
33 pub domain: &'static str,
35 pub types: &'static [TypeSignature],
38 pub predicates: &'static [Symbol],
40 pub functions: &'static [Symbol],
42 pub constants: &'static [(&'static str, usize)],
44}
45
46#[derive(Debug)]
48pub struct TypeSignature {
49 pub name: &'static str,
51 pub parent: Option<usize>,
53}
54
55#[derive(Debug)]
57pub struct Symbol {
58 pub name: &'static str,
60 pub args: &'static [usize],
62}
63
64#[derive(Debug, Clone)]
66pub struct Loaded {
67 pub names: Vec<String>,
69 pub starts: Vec<u32>,
71 pub ends: Vec<u32>,
73 pub constants: Vec<u32>,
75 pub facts: Vec<(usize, Vec<u32>)>,
77 pub values: Vec<(usize, Vec<u32>, f64)>,
80 pub goal: Formula,
82 pub minimize_total_cost: bool,
84}
85
86#[derive(Debug, Clone, PartialEq, thiserror::Error)]
88pub enum LoadError {
89 #[error("the problem is for domain `{found}`, not `{expected}`")]
91 WrongDomain {
92 expected: &'static str,
94 found: String,
96 },
97 #[error("unknown type `{0}`")]
99 UnknownType(String),
100 #[error("object `{0}` has more than one type")]
102 MultipleTypes(String),
103 #[error("unknown object `{0}`")]
105 UnknownObject(String),
106 #[error("unknown predicate or function `{0}`")]
108 UnknownSymbol(String),
109 #[error("`{0}` has the wrong number of arguments")]
111 WrongArity(String),
112 #[error("`{object}` is not of the type `{expected}` that `{symbol}` takes")]
114 WrongType {
115 symbol: String,
117 object: String,
119 expected: &'static str,
121 },
122 #[error("unknown variable `{0}`")]
124 UnknownVariable(String),
125 #[error("unsupported in a problem: {0}")]
127 Unsupported(&'static str),
128 #[error("`{function}` is {value}, but action costs must be non-negative integers")]
131 InvalidCost {
132 function: String,
134 value: f64,
136 },
137}
138
139fn lc(name: &str) -> String {
141 name.to_lowercase()
142}
143
144pub fn load(signature: &Signature, problem: &Problem) -> Result<Loaded, LoadError> {
153 if lc(problem.domain()) != signature.domain {
154 return Err(LoadError::WrongDomain {
155 expected: signature.domain,
156 found: problem.domain().to_string(),
157 });
158 }
159 if !problem.constraints().is_empty() {
160 return Err(LoadError::Unsupported("constraints"));
161 }
162 let minimize_total_cost = match problem.metric_spec() {
163 None => false,
164 Some(metric) => match (metric.optimization(), metric.expression()) {
165 (Optimization::Minimize, MetricFluentExpression::Function(symbol, args))
166 if args.is_empty() && lc(symbol) == "total-cost" =>
167 {
168 true
169 }
170 _ => {
171 return Err(LoadError::Unsupported(
172 "metrics other than minimizing total-cost",
173 ))
174 }
175 },
176 };
177
178 let loader = Loader::new(signature, problem)?;
179 let mut facts = Vec::new();
180 let mut values = Vec::new();
181 for element in problem.init().iter() {
182 match element {
183 InitElement::Literal(Literal::AtomicFormula(AtomicFormula::Predicate(atom))) => {
184 let names: Vec<&Name> = atom.values().iter().collect();
185 let (pred, args) = loader.symbol(true, atom.predicate(), &names)?;
186 facts.push((pred, args));
187 }
188 InitElement::Literal(Literal::NotAtomicFormula(AtomicFormula::Predicate(_))) => {}
190 InitElement::Literal(_) => {
191 return Err(LoadError::Unsupported("equality in the initial state"))
192 }
193 InitElement::At(..) => return Err(LoadError::Unsupported("timed initial literals")),
194 InitElement::IsValue(head, value) => {
195 if lc(head.symbol()) == "total-cost" && head.names().is_empty() {
196 continue; }
198 let names: Vec<&Name> = head.names().iter().collect();
199 let (func, args) = loader.symbol(false, head.symbol(), &names)?;
200 values.push((func, args, **value));
201 }
202 InitElement::IsObject(..) => return Err(LoadError::Unsupported("object fluents")),
203 }
204 }
205 let goal = loader.goals(problem.goals(), &HashMap::new())?;
206
207 Ok(Loaded {
208 names: loader.names,
209 starts: loader.starts,
210 ends: loader.ends,
211 constants: loader.constants,
212 facts,
213 values,
214 goal,
215 minimize_total_cost,
216 })
217}
218
219type Scope = HashMap<String, u32>;
221
222type OnBinding<'f> = dyn FnMut(&Scope) -> Result<(), LoadError> + 'f;
224
225struct Loader<'a> {
227 signature: &'a Signature,
229 names: Vec<String>,
231 numbers: HashMap<String, u32>,
233 starts: Vec<u32>,
235 ends: Vec<u32>,
237 constants: Vec<u32>,
239}
240
241impl<'a> Loader<'a> {
242 fn new(signature: &'a Signature, problem: &Problem) -> Result<Self, LoadError> {
244 let type_index = |ty: &Type, object: &str| -> Result<usize, LoadError> {
245 let name = match ty {
246 Type::Exactly(name) => lc(name),
247 Type::EitherOf(names) if names.len() == 1 => lc(&names[0]),
248 Type::EitherOf(_) => return Err(LoadError::MultipleTypes(object.to_string())),
249 };
250 signature
251 .types
252 .iter()
253 .position(|t| t.name == name)
254 .ok_or(LoadError::UnknownType(name))
255 };
256
257 let mut declared: Vec<(String, usize)> = signature
259 .constants
260 .iter()
261 .map(|&(name, ty)| (name.to_string(), ty))
262 .collect();
263 for typed in problem.objects().iter() {
264 let name = lc(typed.value());
265 let ty = type_index(typed.type_(), &name)?;
266 match declared.iter().find(|(n, _)| *n == name) {
267 Some(&(_, other)) if other == ty => {} Some(_) => return Err(LoadError::MultipleTypes(name)),
269 None => declared.push((name, ty)),
270 }
271 }
272
273 let count = signature.types.len();
274 let mut starts = vec![0; count];
275 let mut ends = vec![0; count];
276 let mut names = Vec::new();
277 for (t, start) in starts.iter_mut().enumerate() {
278 *start = u32::try_from(names.len()).expect("fewer than 2^32 objects");
279 names.extend(
280 declared
281 .iter()
282 .filter(|(_, ty)| *ty == t)
283 .map(|(n, _)| n.clone()),
284 );
285 ends[t] = u32::try_from(names.len()).expect("fewer than 2^32 objects");
286 }
287 for t in (0..count).rev() {
289 if let Some(parent) = signature.types[t].parent {
290 ends[parent] = ends[parent].max(ends[t]);
291 }
292 }
293 let numbers: HashMap<String, u32> = names
294 .iter()
295 .enumerate()
296 .map(|(i, n)| {
297 (
298 n.clone(),
299 u32::try_from(i).expect("fewer than 2^32 objects"),
300 )
301 })
302 .collect();
303 let constants = signature
304 .constants
305 .iter()
306 .map(|(name, _)| numbers[*name])
307 .collect();
308
309 Ok(Self {
310 signature,
311 names,
312 numbers,
313 starts,
314 ends,
315 constants,
316 })
317 }
318
319 fn object(&self, name: &str) -> Result<u32, LoadError> {
321 let name = lc(name);
322 self.numbers
323 .get(&name)
324 .copied()
325 .ok_or(LoadError::UnknownObject(name))
326 }
327
328 fn symbol(
330 &self,
331 predicate: bool,
332 name: &str,
333 args: &[&Name],
334 ) -> Result<(usize, Vec<u32>), LoadError> {
335 let args = args
336 .iter()
337 .map(|a| self.object(a))
338 .collect::<Result<Vec<_>, _>>()?;
339 self.check(predicate, name, args)
340 }
341
342 fn check(
345 &self,
346 predicate: bool,
347 name: &str,
348 args: Vec<u32>,
349 ) -> Result<(usize, Vec<u32>), LoadError> {
350 let name = lc(name);
351 let symbols = if predicate {
352 self.signature.predicates
353 } else {
354 self.signature.functions
355 };
356 let index = symbols
357 .iter()
358 .position(|s| s.name == name)
359 .ok_or_else(|| LoadError::UnknownSymbol(name.clone()))?;
360 let symbol = &symbols[index];
361 if symbol.args.len() != args.len() {
362 return Err(LoadError::WrongArity(name));
363 }
364 for (&arg, &ty) in args.iter().zip(symbol.args) {
365 if !(self.starts[ty]..self.ends[ty]).contains(&arg) {
366 return Err(LoadError::WrongType {
367 symbol: name,
368 object: self.names[arg as usize].clone(),
369 expected: self.signature.types[ty].name,
370 });
371 }
372 }
373 Ok((index, args))
374 }
375
376 fn term(&self, term: &Term, scope: &HashMap<String, u32>) -> Result<u32, LoadError> {
378 match term {
379 Term::Name(name) => self.object(name),
380 Term::Variable(var) => {
381 let name = lc(var);
382 scope
383 .get(&name)
384 .copied()
385 .ok_or(LoadError::UnknownVariable(name))
386 }
387 Term::Function(_) => Err(LoadError::Unsupported("object fluents")),
388 }
389 }
390
391 fn each_binding(
393 &self,
394 vars: &TypedVariables,
395 scope: &HashMap<String, u32>,
396 f: &mut OnBinding<'_>,
397 ) -> Result<(), LoadError> {
398 let mut domains = Vec::new();
399 for var in vars.iter() {
400 let mut objects = Vec::new();
401 for ty in var.type_().clone() {
402 let name = lc(&ty);
403 let t = self
404 .signature
405 .types
406 .iter()
407 .position(|t| t.name == name)
408 .ok_or(LoadError::UnknownType(name))?;
409 objects.extend(self.starts[t]..self.ends[t]);
410 }
411 objects.sort_unstable();
412 objects.dedup();
413 domains.push((lc(var.value()), objects));
414 }
415 bind(&domains, &mut scope.clone(), f)
416 }
417
418 fn goals(
420 &self,
421 goals: &PreconditionGoalDescriptions,
422 scope: &HashMap<String, u32>,
423 ) -> Result<Formula, LoadError> {
424 let mut parts = Vec::new();
425 for goal in goals {
426 match goal {
427 PreconditionGoalDescription::Preference(PreferenceGoalDescription::Goal(gd)) => {
428 parts.push(self.goal(gd, scope)?);
429 }
430 PreconditionGoalDescription::Preference(PreferenceGoalDescription::Preference(
431 _,
432 )) => return Err(LoadError::Unsupported("preferences")),
433 PreconditionGoalDescription::Forall(vars, inner) => {
434 self.each_binding(vars, scope, &mut |s| {
435 parts.push(self.goals(inner, s)?);
436 Ok(())
437 })?;
438 }
439 }
440 }
441 Ok(flatten_and(parts))
442 }
443
444 fn goal(
446 &self,
447 gd: &GoalDescription,
448 scope: &HashMap<String, u32>,
449 ) -> Result<Formula, LoadError> {
450 Ok(match gd {
451 GoalDescription::AtomicFormula(formula)
452 | GoalDescription::Literal(Literal::AtomicFormula(formula)) => {
453 self.atom(formula, scope)?
454 }
455 GoalDescription::Literal(Literal::NotAtomicFormula(formula)) => {
456 Formula::Not(Box::new(self.atom(formula, scope)?))
457 }
458 GoalDescription::Not(inner) => Formula::Not(Box::new(self.goal(inner, scope)?)),
459 GoalDescription::And(parts) => flatten_and(
460 parts
461 .iter()
462 .map(|p| self.goal(p, scope))
463 .collect::<Result<_, _>>()?,
464 ),
465 GoalDescription::Or(parts) => Formula::Or(
466 parts
467 .iter()
468 .map(|p| self.goal(p, scope))
469 .collect::<Result<_, _>>()?,
470 ),
471 GoalDescription::Imply(a, b) => Formula::Or(vec![
472 Formula::Not(Box::new(self.goal(a, scope)?)),
473 self.goal(b, scope)?,
474 ]),
475 GoalDescription::Exists(vars, inner) => {
476 let mut parts = Vec::new();
477 self.each_binding(vars, scope, &mut |s| {
478 parts.push(self.goal(inner, s)?);
479 Ok(())
480 })?;
481 Formula::Or(parts)
482 }
483 GoalDescription::ForAll(vars, inner) => {
484 let mut parts = Vec::new();
485 self.each_binding(vars, scope, &mut |s| {
486 parts.push(self.goal(inner, s)?);
487 Ok(())
488 })?;
489 flatten_and(parts)
490 }
491 GoalDescription::FluentComparison(comparison) => Formula::Compare(
492 match comparison.comparison() {
493 BinaryComparison::LessThan => Comparison::Less,
494 BinaryComparison::LessThanOrEqual => Comparison::LessOrEqual,
495 BinaryComparison::Equal => Comparison::Equal,
496 BinaryComparison::GreaterOrEqual => Comparison::GreaterOrEqual,
497 BinaryComparison::GreaterThan => Comparison::Greater,
498 },
499 self.expr(comparison.first(), scope)?,
500 self.expr(comparison.second(), scope)?,
501 ),
502 })
503 }
504
505 fn atom(
507 &self,
508 formula: &AtomicFormula<Term>,
509 scope: &HashMap<String, u32>,
510 ) -> Result<Formula, LoadError> {
511 Ok(match formula {
512 AtomicFormula::Equality(eq) => match (eq.first(), eq.second()) {
513 (Term::Function(a), Term::Function(b)) => Formula::Compare(
515 Comparison::Equal,
516 self.fluent(a.symbol(), a.terms(), scope)?,
517 self.fluent(b.symbol(), b.terms(), scope)?,
518 ),
519 (a, b) => {
520 if self.term(a, scope)? == self.term(b, scope)? {
521 Formula::True
522 } else {
523 Formula::False
524 }
525 }
526 },
527 AtomicFormula::Predicate(atom) => {
528 let args = atom
529 .values()
530 .iter()
531 .map(|t| self.term(t, scope))
532 .collect::<Result<Vec<_>, _>>()?;
533 match self.check(true, atom.predicate(), args) {
534 Ok((pred, args)) => Formula::Atom {
535 pred,
536 args: args.into(),
537 },
538 Err(LoadError::WrongType { .. }) => Formula::False,
540 Err(e) => return Err(e),
541 }
542 }
543 })
544 }
545
546 fn fluent(
548 &self,
549 symbol: &str,
550 terms: &[Term],
551 scope: &HashMap<String, u32>,
552 ) -> Result<Expr, LoadError> {
553 let args = terms
554 .iter()
555 .map(|t| self.term(t, scope))
556 .collect::<Result<Vec<_>, _>>()?;
557 let (func, args) = self.check(false, symbol, args)?;
558
559 Ok(Expr::Fluent {
560 func,
561 args: args.into(),
562 })
563 }
564
565 fn expr(
567 &self,
568 expr: &FluentExpression,
569 scope: &HashMap<String, u32>,
570 ) -> Result<Expr, LoadError> {
571 let boxed = |e: &FluentExpression| self.expr(e, scope).map(Box::new);
572 Ok(match expr {
573 FluentExpression::Number(n) => Expr::Number(**n),
574 FluentExpression::Function(head) => {
575 let (symbol, terms): (&Name, &[Term]) = match head {
576 FunctionHead::Simple(symbol) => (symbol, &[]),
577 FunctionHead::WithTerms(symbol, terms) => (symbol, terms),
578 };
579 self.fluent(symbol, terms, scope)?
580 }
581 FluentExpression::Negative(inner) => Expr::Neg(boxed(inner)?),
582 FluentExpression::BinaryOp(op, a, b) => {
583 let (a, b) = (boxed(a)?, boxed(b)?);
584 match op {
585 BinaryOp::Addition => Expr::Add(a, b),
586 BinaryOp::Subtraction => Expr::Sub(a, b),
587 BinaryOp::Multiplication => Expr::Mul(a, b),
588 BinaryOp::Division => Expr::Div(a, b),
589 }
590 }
591 FluentExpression::MultiOp(op, first, rest) => {
592 let mut acc = self.expr(first, scope)?;
593 for e in rest {
594 let e = boxed(e)?;
595 acc = match op {
596 MultiOp::Addition => Expr::Add(Box::new(acc), e),
597 MultiOp::Multiplication => Expr::Mul(Box::new(acc), e),
598 };
599 }
600 acc
601 }
602 })
603 }
604}
605
606fn bind(
608 domains: &[(String, Vec<u32>)],
609 scope: &mut HashMap<String, u32>,
610 f: &mut OnBinding<'_>,
611) -> Result<(), LoadError> {
612 let Some(((name, objects), rest)) = domains.split_first() else {
613 return f(scope);
614 };
615 let shadowed = scope.get(name).copied();
616 for &object in objects {
617 scope.insert(name.clone(), object);
618 bind(rest, scope, f)?;
619 }
620 match shadowed {
621 Some(object) => scope.insert(name.clone(), object),
622 None => scope.remove(name),
623 };
624 Ok(())
625}
626
627fn flatten_and(parts: Vec<Formula>) -> Formula {
629 let mut flat = Vec::new();
630 for part in parts {
631 match part {
632 Formula::And(inner) => flat.extend(inner),
633 other => flat.push(other),
634 }
635 }
636 Formula::And(flat)
637}
638
639#[cfg(all(test, feature = "parser"))]
640mod tests {
641 use super::*;
642 use crate::Parser;
643
644 static SIGNATURE: Signature = Signature {
646 domain: "d",
647 types: &[
648 TypeSignature {
649 name: "object",
650 parent: None,
651 },
652 TypeSignature {
653 name: "vehicle",
654 parent: Some(0),
655 },
656 TypeSignature {
657 name: "truck",
658 parent: Some(1),
659 },
660 TypeSignature {
661 name: "place",
662 parent: Some(0),
663 },
664 ],
665 predicates: &[Symbol {
666 name: "at",
667 args: &[1, 3],
668 }],
669 functions: &[Symbol {
670 name: "fuel",
671 args: &[1],
672 }],
673 constants: &[("depot", 3)],
674 };
675
676 fn load_str(text: &str) -> Result<Loaded, LoadError> {
678 load(&SIGNATURE, &Problem::from_str(text).unwrap())
679 }
680
681 #[test]
682 fn numbers_subtypes_inside_their_supertypes() {
683 let loaded = load_str(
684 "(define (problem p) (:domain d)
685 (:objects t1 - truck v1 - vehicle shop - place t2 - truck depot - place)
686 (:init (at t1 depot) (= (fuel t2) 3) (= (total-cost) 0))
687 (:goal (and (at t2 shop) (forall (?v - vehicle) (>= (fuel ?v) 1))))
688 (:metric minimize (total-cost)))",
689 )
690 .unwrap();
691 assert_eq!(loaded.names, ["v1", "t1", "t2", "depot", "shop"]);
692 assert_eq!(loaded.starts, [0, 0, 1, 3]);
693 assert_eq!(loaded.ends, [5, 3, 3, 5]);
694 assert_eq!(loaded.constants, [3]);
695 assert_eq!(loaded.facts, [(0, vec![1, 3])]);
696 assert_eq!(loaded.values, [(0, vec![2], 3.0)]);
697 assert!(loaded.minimize_total_cost);
698 let Formula::And(goal) = &loaded.goal else {
699 panic!("{:?}", loaded.goal)
700 };
701 assert_eq!(goal.len(), 4, "{goal:?}");
702 }
703
704 #[test]
705 fn rejects_problems_that_do_not_fit() {
706 let problem = |objects: &str, init: &str, goal: &str| {
707 load_str(&format!(
708 "(define (problem p) (:domain d) (:objects {objects}) (:init {init}) (:goal {goal}))"
709 ))
710 };
711 assert_eq!(
712 problem("x - robot", "", "(and)").unwrap_err(),
713 LoadError::UnknownType("robot".into())
714 );
715 assert_eq!(
716 problem("x - (either truck place)", "", "(and)").unwrap_err(),
717 LoadError::MultipleTypes("x".into())
718 );
719 assert_eq!(
720 problem("depot - truck", "", "(and)").unwrap_err(),
721 LoadError::MultipleTypes("depot".into())
722 );
723 assert_eq!(
724 problem("t - truck", "(at t nowhere)", "(and)").unwrap_err(),
725 LoadError::UnknownObject("nowhere".into())
726 );
727 assert_eq!(
728 problem("t - truck", "(at depot t)", "(and)").unwrap_err(),
729 LoadError::WrongType {
730 symbol: "at".into(),
731 object: "depot".into(),
732 expected: "vehicle"
733 }
734 );
735 assert_eq!(
736 problem("t - truck", "(on t)", "(and)").unwrap_err(),
737 LoadError::UnknownSymbol("on".into())
738 );
739 assert_eq!(
740 problem("t - truck", "(at t)", "(and)").unwrap_err(),
741 LoadError::WrongArity("at".into())
742 );
743 assert_eq!(
744 problem("t - truck", "(at 5 (at t depot))", "(and)").unwrap_err(),
745 LoadError::Unsupported("timed initial literals")
746 );
747 assert_eq!(
748 problem("t - truck", "", "(at ?x depot)").unwrap_err(),
749 LoadError::UnknownVariable("x".into())
750 );
751 assert!(matches!(
752 load_str("(define (problem p) (:domain other) (:init) (:goal (and)))"),
753 Err(LoadError::WrongDomain { .. })
754 ));
755 assert_eq!(
756 load_str("(define (problem p) (:domain d) (:init) (:goal (and)) (:metric maximize (total-cost)))")
757 .unwrap_err(),
758 LoadError::Unsupported("metrics other than minimizing total-cost")
759 );
760 }
761
762 #[test]
763 fn reads_every_init_and_goal_form() {
764 let loaded = load_str(
765 "(define (problem p) (:domain d) (:objects t - truck depot - place)
766 (:init (at t depot) (not (at t depot)) (= (fuel t) 2))
767 (:goal (and (not (at t depot))
768 (forall (?v - vehicle) (exists (?p - place) (at ?v ?p)))
769 (<= (- (fuel t)) (* (fuel t) 2 3))
770 (= (+ (fuel t) 1 1) 4)
771 (> (/ (fuel t) 2) 0))))",
772 )
773 .unwrap();
774 assert_eq!(loaded.names, ["t", "depot"]);
776 let fact = |_: usize, _: &[u32]| true;
777 let value = |_: usize, _: &[u32]| Some(2.0);
778 let Formula::And(goal) = &loaded.goal else {
779 panic!("{:?}", loaded.goal)
780 };
781 assert!(!goal[0].holds(&fact, &value));
782 assert!(goal[1..].iter().all(|g| g.holds(&fact, &value)), "{goal:?}");
783 }
784
785 #[test]
786 fn reads_an_equality_of_two_functions_as_numeric() {
787 let loaded = load_str(
788 "(define (problem p) (:domain d) (:objects t u - truck)
789 (:init) (:goal (= (fuel t) (fuel u))))",
790 )
791 .unwrap();
792 let value = |_: usize, args: &[u32]| Some(f64::from(args[0]));
793 assert!(!loaded.goal.holds(&|_, _| false, &value));
794 assert!(loaded.goal.holds(&|_, _| false, &|_, _| Some(1.0)));
795 }
796
797 #[test]
798 fn rejects_unsupported_problem_constructs() {
799 let problem = |rest: &str| {
800 load_str(&format!(
801 "(define (problem p) (:domain d) (:objects t - truck) {rest})"
802 ))
803 };
804 assert_eq!(
805 problem("(:init) (:goal (and)) (:constraints (always (at t depot)))").unwrap_err(),
806 LoadError::Unsupported("constraints")
807 );
808 assert_eq!(
809 problem("(:init (= (owner t) depot)) (:goal (and))").unwrap_err(),
810 LoadError::Unsupported("object fluents")
811 );
812 assert_eq!(
813 problem("(:init) (:goal (preference g (at t depot)))").unwrap_err(),
814 LoadError::Unsupported("preferences")
815 );
816 assert_eq!(
817 problem("(:init) (:goal (exists (?x - robot) (at t ?x)))").unwrap_err(),
818 LoadError::UnknownType("robot".into())
819 );
820 assert_eq!(
821 problem("(:init) (:goal (at t nowhere))").unwrap_err(),
822 LoadError::UnknownObject("nowhere".into())
823 );
824 assert_eq!(
825 problem("(:init (= (speed t) 1)) (:goal (and))").unwrap_err(),
826 LoadError::UnknownSymbol("speed".into())
827 );
828 }
829
830 #[test]
831 fn grounds_goal_connectives() {
832 let loaded = load_str(
833 "(define (problem p) (:domain d) (:objects t - truck)
834 (:init (at t depot))
835 (:goal (and (or (at t depot) (not (= t depot)))
836 (imply (at t depot) (exists (?p - place) (at t ?p)))
837 (at depot depot)
838 (< (- (* 2 (fuel t) 1) (/ 4 (fuel t))) (+ 1 (fuel t))))))",
839 )
840 .unwrap();
841 let fact = |pred: usize, args: &[u32]| {
842 loaded
843 .facts
844 .iter()
845 .any(|(p, a)| *p == pred && a.as_slice() == args)
846 };
847 let Formula::And(parts) = &loaded.goal else {
848 panic!()
849 };
850 assert_eq!(parts[2], Formula::False);
852 assert!(parts[0].holds(&fact, &|_, _| None));
853 assert!(parts[1].holds(&fact, &|_, _| None));
854 assert!(parts[3].holds(&fact, &|_, _| Some(2.0)));
855 assert!(!parts[3].holds(&fact, &|_, _| None));
856 }
857}