File size: 6,746 Bytes
e1f5446 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | diff --git a/pddl/parser/domain.py b/pddl/parser/domain.py
index b644fd0..e18029e 100644
--- a/pddl/parser/domain.py
+++ b/pddl/parser/domain.py
@@ -11,7 +11,7 @@
#
"""Implementation of the PDDL domain parser."""
-from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
+from typing import AbstractSet, Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
from lark import ParseError, Transformer
@@ -61,6 +61,14 @@ class DomainTransformer(Transformer[Any, Domain]):
self._current_parameters_by_name: Dict[str, Variable] = {}
self._requirements: Set[Requirements] = set()
self._extended_requirements: Set[Requirements] = set()
+ self._types: Optional[Mapping[name, Optional[name]]] = None
+
+ @property
+ def types_hierarchy(self) -> Mapping[name, Optional[name]]:
+ """Return the read-only types hierarchy."""
+ if self._types is None:
+ raise RuntimeError("Types hierarchy is not available yet.")
+ return self._types
def start(self, args):
"""Entry point."""
@@ -81,6 +89,7 @@ class DomainTransformer(Transformer[Any, Domain]):
assert_(isinstance(arg, dict))
kwargs.update(arg)
kwargs.update(actions=actions, derived_predicates=derived_predicates)
+ self._types = None
return Domain(**kwargs)
def domain_def(self, args):
@@ -104,6 +113,12 @@ class DomainTransformer(Transformer[Any, Domain]):
for k in types_definition:
if types_definition[k] == Symbols.OBJECT.value:
types_definition[k] = None
+
+ # record types hierarchy for later use during the parsing
+ # safety check: make sure self._types is not set
+ assert_(self._types is None, "parser is in an unexpected state")
+ self._types = types_definition
+
return dict(types=types_definition)
def constants(self, args):
@@ -139,16 +154,56 @@ class DomainTransformer(Transformer[Any, Domain]):
def derived_predicates(self, args):
"""Process the 'derived_predicates' rule."""
- predicate = args[2]
- condition = args[3]
+ dp_predicate = args[2]
+ dp_condition = args[3]
+
# we need to make sure the variables in the condition of the derived predicate
- # have the same type tags of the variables with the same name and scope in the predicate definition
+ # have type tags compatible with the variables in the corresponding predicate definition
+ # to do so, we read the type tags of the predicate arguments from the predicate definition in (:predicates ...)
+ if dp_predicate.name not in self._predicates_by_name:
+ raise ParseError(f"Predicate '{dp_predicate.name}' not defined.")
+ predicate_def = self._predicates_by_name[dp_predicate.name]
+ if len(predicate_def.terms) != len(dp_predicate.terms):
+ raise ParseError(
+ f"Derived predicate '{dp_predicate.name}' has {len(dp_predicate.terms)} arguments, "
+ f"but predicate definition has {len(predicate_def.terms)} arguments."
+ )
+
+ # this is the mapping we will use to update the type tags of the variables occurrences
+ # in the condition of the derived predicate
current_var_to_types = {}
- for term in predicate.terms:
- if isinstance(term, Variable):
+ for idx, term in enumerate(dp_predicate.terms):
+ assert_(
+ isinstance(term, Variable),
+ f"Expected Variable, got {type(term).__name__}",
+ )
+
+ # if the term has no type tags, we try to use the type tags from the predicate definition
+ if len(term.type_tags) == 0:
+ # if the predicate definition specifies type tags for this argument, we use it.
+ # this has the effect of updating the type tags of the variable occurrence in both the dp_predicate
+ # and the dp_condition.
+ if len(predicate_def.terms[idx].type_tags) != 0:
+ current_var_to_types[term.name] = predicate_def.terms[idx].type_tags
+ else:
+ # otherwise, we use the type tags from the definition of the derived predicate
current_var_to_types[term.name] = term.type_tags
- new_condition = update_type_tags(condition, current_var_to_types)
- return DerivedPredicate(predicate, new_condition)
+
+ # however, in this case, we also need to make sure that the type tags in the condition of the
+ # derived predicate are consistent with the type tags in the predicate definition
+ try:
+ self._check_subtypes(
+ term.type_tags, predicate_def.terms[idx].type_tags
+ )
+ except PDDLParsingError as e:
+ raise PDDLParsingError(
+ f"Type tags in condition and predicate definition do not match "
+ f"for variable '{term.name}' (position {idx}) in predicate '{dp_predicate.name}': {e}"
+ )
+
+ new_predicate = update_type_tags(dp_predicate, current_var_to_types)
+ new_condition = update_type_tags(dp_condition, current_var_to_types)
+ return DerivedPredicate(new_predicate, new_condition)
def action_parameters(self, args):
"""Process the 'action_parameters' rule."""
@@ -460,6 +515,26 @@ class DomainTransformer(Transformer[Any, Domain]):
"""Check whether a requirement is satisfied by the current state of the domain parsing."""
return requirement in self._extended_requirements
+ def _check_subtypes(
+ self, type_tags_left: AbstractSet[name], type_tags_right: AbstractSet[name]
+ ):
+ """Check that each type tag in the left set is a subtype of (one of) the type tags of the right."""
+ if len(type_tags_right) == 0:
+ # 'object' type includes everything
+ return
+
+ # for each lef type, navigate the type hierarchy until we find a type in the right set, or fail
+ for left_type in type_tags_left:
+ current_type = left_type
+ parent_type: Optional[name] = left_type
+ while parent_type is not None and parent_type not in type_tags_right:
+ parent_type = self.types_hierarchy.get(current_type, None)
+
+ if parent_type is None:
+ raise PDDLParsingError(
+ f"Type '{left_type}' not found in types: '{type_tags_right}'."
+ )
+
class DomainParser(BaseParser[Domain]):
"""PDDL domain parser class."""
|