ruml-parser 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. ruml_parser/__init__.py +183 -0
  2. ruml_parser/internal/__init__.py +2 -0
  3. ruml_parser/internal/extension.py +91 -0
  4. ruml_parser/internal/mapping.py +731 -0
  5. ruml_parser/internal/ruml/__init__.py +237 -0
  6. ruml_parser/internal/ruml/actions/__init__.py +2 -0
  7. ruml_parser/internal/ruml/actions/actions_capability_declaration.py +23 -0
  8. ruml_parser/internal/ruml/actions/actions_node_capability.py +40 -0
  9. ruml_parser/internal/ruml/ai_query/__init__.py +2 -0
  10. ruml_parser/internal/ruml/ai_query/ai_query_capability_declaration.py +25 -0
  11. ruml_parser/internal/ruml/ai_query/ai_query_node_capability.py +66 -0
  12. ruml_parser/internal/ruml/aliases.py +93 -0
  13. ruml_parser/internal/ruml/capability/__init__.py +2 -0
  14. ruml_parser/internal/ruml/capability/abstract_capability_declaration.py +23 -0
  15. ruml_parser/internal/ruml/capability/abstract_node_capability.py +14 -0
  16. ruml_parser/internal/ruml/capability/capability_declaration.py +52 -0
  17. ruml_parser/internal/ruml/capability/capability_declarations.py +199 -0
  18. ruml_parser/internal/ruml/capability/extension_node_capability.py +17 -0
  19. ruml_parser/internal/ruml/capability/node_capabilities.py +113 -0
  20. ruml_parser/internal/ruml/capability/other_node_capability.py +21 -0
  21. ruml_parser/internal/ruml/context/__init__.py +2 -0
  22. ruml_parser/internal/ruml/context/context.py +40 -0
  23. ruml_parser/internal/ruml/context/context_capability_declaration.py +25 -0
  24. ruml_parser/internal/ruml/context/context_refs_node_capability.py +17 -0
  25. ruml_parser/internal/ruml/datapoints/__init__.py +2 -0
  26. ruml_parser/internal/ruml/datapoints/datapoint.py +101 -0
  27. ruml_parser/internal/ruml/datapoints/datapoint_set.py +20 -0
  28. ruml_parser/internal/ruml/datapoints/datapoints_capability_declaration.py +29 -0
  29. ruml_parser/internal/ruml/datapoints/option.py +11 -0
  30. ruml_parser/internal/ruml/expression/__init__.py +2 -0
  31. ruml_parser/internal/ruml/expression/expression_capability_declaration.py +23 -0
  32. ruml_parser/internal/ruml/expression/expression_node_capability.py +20 -0
  33. ruml_parser/internal/ruml/metadata.py +83 -0
  34. ruml_parser/internal/ruml/nodes/__init__.py +2 -0
  35. ruml_parser/internal/ruml/nodes/abstract_node.py +29 -0
  36. ruml_parser/internal/ruml/nodes/branch_node.py +15 -0
  37. ruml_parser/internal/ruml/nodes/leaf_node.py +10 -0
  38. ruml_parser/internal/ruml/nodes/node.py +6 -0
  39. ruml_parser/internal/ruml/protocol/__init__.py +2 -0
  40. ruml_parser/internal/ruml/protocol/protocol_capability_declaration.py +29 -0
  41. ruml_parser/internal/ruml/query/__init__.py +2 -0
  42. ruml_parser/internal/ruml/query/query_capability_declaration.py +23 -0
  43. ruml_parser/internal/ruml/query/query_node_capability.py +17 -0
  44. ruml_parser/internal/ruml/ruml_document.py +45 -0
  45. ruml_parser/internal/ruml/text_reference/__init__.py +2 -0
  46. ruml_parser/internal/ruml/text_reference/text.py +69 -0
  47. ruml_parser/internal/ruml/text_reference/text_reference_capability_declaration.py +25 -0
  48. ruml_parser/internal/ruml/text_reference/text_refs_node_capability.py +32 -0
  49. ruml_parser/internal/ruml/tree/__init__.py +2 -0
  50. ruml_parser/internal/ruml/tree/tree_capability_declarations.py +30 -0
  51. ruml_parser/internal/validation/__init__.py +14 -0
  52. ruml_parser/internal/validation/capabilities.py +227 -0
  53. ruml_parser/internal/validation/contexts.py +51 -0
  54. ruml_parser/internal/validation/datapoint_sets.py +125 -0
  55. ruml_parser/internal/validation/modular.py +42 -0
  56. ruml_parser/internal/validation/recursion.py +197 -0
  57. ruml_parser/internal/validation/root.py +36 -0
  58. ruml_parser/internal/validation/texts.py +50 -0
  59. ruml_parser/model/__init__.py +2 -0
  60. ruml_parser/model/ruml.py +1156 -0
  61. ruml_parser/model/ruml_result.py +430 -0
  62. ruml_parser/node_result_status.py +19 -0
  63. ruml_parser/pydantic.py +96 -0
  64. ruml_parser/ruml_parser.py +75 -0
  65. ruml_parser/schema_files.py +23 -0
  66. ruml_parser/schema_validation.py +354 -0
  67. ruml_parser/structural_error.py +36 -0
  68. ruml_parser/text.py +220 -0
  69. ruml_parser-1.0.0.dist-info/METADATA +119 -0
  70. ruml_parser-1.0.0.dist-info/RECORD +72 -0
  71. ruml_parser-1.0.0.dist-info/WHEEL +4 -0
  72. ruml_parser-1.0.0.dist-info/licenses/LICENSE +73 -0
@@ -0,0 +1,227 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The spec's rules on capability declarations.
4
+
5
+ "No implicit capabilities" (chapter 4.3, rule CAP-15), the uniqueness of capability
6
+ ids at the root (chapter 4.2, rule CAP-10) and on a node (chapter 4.3, rule CAP-06),
7
+ and the combiner's placement (chapter 3.6.4, rules OP-02 and CAP-08).
8
+ """
9
+
10
+ from collections import Counter
11
+ from collections.abc import Sequence
12
+ from typing import assert_never
13
+
14
+ from ruml_parser.internal.ruml import (
15
+ BranchNode,
16
+ CapabilityId,
17
+ CapabilityRole,
18
+ LeafNode,
19
+ OfficialCapabilityId,
20
+ Operator,
21
+ RumlDocument,
22
+ )
23
+ from ruml_parser.schema_validation import json_pointer
24
+ from ruml_parser.structural_error import RumlStructuralError, StructuralViolation
25
+
26
+ _OFFICIAL_IDS = frozenset(str(official.value) for official in OfficialCapabilityId)
27
+
28
+
29
+ def reject_undeclared_node_capabilities(document: RumlDocument) -> None:
30
+ """Raise if a node uses a capability id the root does not declare.
31
+
32
+ Every capability id a node uses must be declared in the root-level `capabilities`,
33
+ whether the parser knows the capability or not (spec chapter 4.3, rule CAP-15: no
34
+ implicit capabilities). The schema cannot relate a node's ids to the root's, so the
35
+ rule is checked here; all offending nodes are reported at once.
36
+
37
+ Raises:
38
+ RumlStructuralError: With one CAP-15 violation per offending node, at the
39
+ node's entries of each undeclared id.
40
+ """
41
+ declared = document.capabilities.ids
42
+ violations = [
43
+ StructuralViolation(
44
+ rule="CAP-15",
45
+ message=f"node {lex_id!r} uses capabilities the root does not declare: "
46
+ + ", ".join(repr(capability_id) for capability_id in undeclared),
47
+ paths=[
48
+ json_pointer(("rulemap", "nodes", lex_id, "capabilities", index))
49
+ for index, capability_id in enumerate(node.capabilities.ids)
50
+ if capability_id not in declared
51
+ ],
52
+ )
53
+ for lex_id, node in document.nodes.items()
54
+ if (
55
+ undeclared := list(
56
+ dict.fromkeys(
57
+ capability_id
58
+ for capability_id in node.capabilities.ids
59
+ if capability_id not in declared
60
+ )
61
+ )
62
+ )
63
+ ]
64
+ if violations:
65
+ raise RumlStructuralError(violations)
66
+
67
+
68
+ def reject_duplicate_capability_ids(document: RumlDocument) -> None:
69
+ """Raise if the root lists the same capability id more than once.
70
+
71
+ Each capability id appears at most once in the root's `capabilities` list (spec
72
+ chapter 4.2, rule CAP-10); the schema checks that for the official ids only, so
73
+ the rule is checked here. The root's internal model keeps every listed id in
74
+ `declaration_order`, so a duplicate is still visible although the root's fields can
75
+ hold only one entry per id. A node's list may repeat some ids: see
76
+ `reject_repeated_data_capabilities`.
77
+
78
+ Raises:
79
+ RumlStructuralError: With one CAP-10 violation per repeated id, at every
80
+ entry of it after the first.
81
+ """
82
+ order = document.capabilities.declaration_order
83
+ violations = [
84
+ StructuralViolation(
85
+ rule="CAP-10",
86
+ message=f"the root declares the capability {capability_id!r} more than once",
87
+ paths=[
88
+ json_pointer(("capabilities", index))
89
+ for index, declared in enumerate(order)
90
+ if declared == capability_id
91
+ ][1:],
92
+ )
93
+ for capability_id, count in Counter(order).items()
94
+ if count > 1
95
+ ]
96
+ if violations:
97
+ raise RumlStructuralError(violations)
98
+
99
+
100
+ def reject_repeated_data_capabilities(document: RumlDocument) -> None:
101
+ """Raise if a node lists a capability with the `data` role more than once.
102
+
103
+ On a node, ids with the `decision` or `reaction` role may repeat, but one entry
104
+ carries all of a node's data for a `data` capability (spec chapter 4.3, rule
105
+ CAP-06). The schema enforces this for the official `data` ids only, since it cannot
106
+ see the role a root entry declares for any other. Ids the root does not declare are
107
+ left to `reject_undeclared_node_capabilities`; the combiner role to
108
+ `reject_invalid_number_of_combiners_per_node`.
109
+
110
+ Raises:
111
+ RumlStructuralError: With one CAP-06 violation per offending node, at the
112
+ node's entries of each repeated id.
113
+ """
114
+ data_ids = {
115
+ declaration.id
116
+ for declaration in document.capabilities.get_by_role(CapabilityRole.data)
117
+ }
118
+ violations = [
119
+ StructuralViolation(
120
+ rule="CAP-06",
121
+ message=f"node {lex_id!r} carries capabilities with the data role more"
122
+ f" than once: {', '.join(repr(id) for id in repeated)}",
123
+ paths=[
124
+ json_pointer(("rulemap", "nodes", lex_id, "capabilities", index))
125
+ for index, capability_id in enumerate(node.capabilities.ids)
126
+ if capability_id in repeated
127
+ ],
128
+ )
129
+ for lex_id, node in document.nodes.items()
130
+ if (
131
+ repeated := [
132
+ capability_id
133
+ for capability_id, count in Counter(node.capabilities.ids).items()
134
+ if count > 1 and capability_id in data_ids
135
+ ]
136
+ )
137
+ ]
138
+ if violations:
139
+ raise RumlStructuralError(violations)
140
+
141
+
142
+ def reject_invalid_number_of_combiners_per_node(document: RumlDocument) -> None:
143
+ """Raise if a node's combiners break OP-02 or CAP-08.
144
+
145
+ A `DELEGATED` node with children has exactly one combiner (OP-02). Without one,
146
+ the node is reported, and with it the root entry of every non-official capability
147
+ on the node: its role is the one declared there, and that is not `combiner`. With
148
+ several, every combiner entry after the first is reported. Any other node has no
149
+ combiner (CAP-08, reported at the node).
150
+
151
+ Raises:
152
+ RumlStructuralError: With one violation per offending node.
153
+ """
154
+ violations: list[StructuralViolation] = []
155
+ combiner_cap_ids = {
156
+ declaration.id
157
+ for declaration in document.capabilities.get_by_role(CapabilityRole.combiner)
158
+ }
159
+ for lex_id, node in document.nodes.items():
160
+ if violation := _detect_combiner_violation(
161
+ lex_id, node, combiner_cap_ids, document.capabilities.declaration_order
162
+ ):
163
+ violations.append(violation)
164
+ if violations:
165
+ raise RumlStructuralError(violations)
166
+
167
+
168
+ def _detect_combiner_violation(
169
+ lex_id: str,
170
+ node: LeafNode | BranchNode,
171
+ combiner_ids: set[CapabilityId],
172
+ declaration_order: Sequence[CapabilityId],
173
+ ) -> StructuralViolation | None:
174
+ combiner_indices = [
175
+ index
176
+ for index, capability in enumerate(node.capabilities.entries)
177
+ if capability.id in combiner_ids
178
+ ]
179
+ nr_combiners = len(combiner_indices)
180
+ node_path = ("rulemap", "nodes", lex_id)
181
+ match node:
182
+ case LeafNode():
183
+ if nr_combiners > 0:
184
+ return StructuralViolation(
185
+ rule="CAP-08",
186
+ message=f"node {lex_id!r} has {nr_combiners} combiners"
187
+ " (a leaf node must not have any combiners)",
188
+ paths=[json_pointer(node_path)],
189
+ )
190
+ case BranchNode():
191
+ if node.operator == Operator.DELEGATED:
192
+ if nr_combiners == 0:
193
+ used = set(node.capabilities.ids) - _OFFICIAL_IDS
194
+ return StructuralViolation(
195
+ rule="OP-02",
196
+ message=f"node {lex_id!r} has 0 combiners"
197
+ " (chapter 3.6.4: a DELEGATED node needs exactly one combiner)",
198
+ paths=[
199
+ *(
200
+ json_pointer(("capabilities", index))
201
+ for index, declared in enumerate(declaration_order)
202
+ if declared in used
203
+ ),
204
+ json_pointer(node_path),
205
+ ],
206
+ )
207
+ if nr_combiners > 1:
208
+ # The first combiner is the node's; every further one is extra.
209
+ return StructuralViolation(
210
+ rule="OP-02",
211
+ message=f"node {lex_id!r} has {nr_combiners} combiners"
212
+ " (chapter 3.6.4: a DELEGATED node needs exactly one combiner)",
213
+ paths=[
214
+ json_pointer((*node_path, "capabilities", index))
215
+ for index in combiner_indices[1:]
216
+ ],
217
+ )
218
+ elif nr_combiners > 0:
219
+ return StructuralViolation(
220
+ rule="CAP-08",
221
+ message=f"node {lex_id!r} has {nr_combiners} combiners"
222
+ " (a non DELEGATE branch node must not have any combiners)",
223
+ paths=[json_pointer(node_path)],
224
+ )
225
+ case _ as unreachable:
226
+ assert_never(unreachable)
227
+ return None
@@ -0,0 +1,51 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The spec's rule that context inputs name declared context entries (chapter 4.11)."""
4
+
5
+ from collections.abc import Iterator
6
+
7
+ from ruml_parser.internal.ruml import (
8
+ AiQueryNodeCapability,
9
+ ContextId,
10
+ LexId,
11
+ RumlDocument,
12
+ )
13
+
14
+
15
+ def reject_undeclared_context_inputs(document: RumlDocument) -> None:
16
+ """Raise if an ai-query names a context id the root does not declare.
17
+
18
+ Every id in the ``inputs.context`` of a node's ``ruml:ai-query`` must have an
19
+ entry in the root-level ``ruml:context`` data (spec chapter 4.11). The schema
20
+ cannot relate a node's ids to the root's, so the rule is checked here; all
21
+ offending nodes are reported at once. Consumers of the parsed document (e.g.
22
+ the evaluator's prompt and attachment builders) may assume every named id
23
+ resolves.
24
+
25
+ Raises:
26
+ ValueError: Naming every offending node and the ids it names undeclared.
27
+ """
28
+ context = document.capabilities.context
29
+ root_levels_context_ids = (
30
+ context.data.keys() if context is not None else frozenset()
31
+ )
32
+ offences = [
33
+ f"node {lex_id!r} -> context_id {context_id!r}"
34
+ for lex_id, context_id in _context_inputs(document)
35
+ if context_id not in root_levels_context_ids
36
+ ]
37
+ if offences:
38
+ raise ValueError(
39
+ "Some nodes reference undeclared contexts: "
40
+ + "; ".join(offences)
41
+ + " (spec chapter 4.11: context inputs name root-level context entries)"
42
+ )
43
+
44
+
45
+ def _context_inputs(document: RumlDocument) -> Iterator[tuple[LexId, ContextId]]:
46
+ """Yield every ``(lex_id, context id)`` an ai-query inputs, in document order."""
47
+ for lex_id, ai_query in document.all_node_capabilities_of_type(
48
+ AiQueryNodeCapability
49
+ ):
50
+ for context_input in ai_query.inputs.context:
51
+ yield lex_id, context_input.id
@@ -0,0 +1,125 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The spec's rules on datapoint sets (chapter 4.7.4, rules DP-16 and DP-17)."""
4
+
5
+ from collections import deque
6
+ from collections.abc import Iterator
7
+
8
+ from more_itertools import unique_everseen
9
+
10
+ from ruml_parser.internal.ruml import (
11
+ Datapoint,
12
+ DatapointsCapabilityDeclaration,
13
+ DatapointSet,
14
+ RumlDocument,
15
+ SetId,
16
+ )
17
+
18
+
19
+ def reject_undeclared_set_references(document: RumlDocument) -> None:
20
+ """Raise if a datapoint names a set the document does not declare (DP-16).
21
+
22
+ Every `set` a datapoint carries — in `data` as well as among the `fields` of a set
23
+ — must be an id declared in `sets` (spec chapter 4.7.4). The schema cannot relate
24
+ a datapoint's `set` to the keys of `sets`, so the rule is checked here; all
25
+ offending datapoints are reported at once.
26
+
27
+ Raises:
28
+ ValueError: Naming every offending datapoint and the set it references.
29
+ """
30
+ datapoints = document.capabilities.datapoints
31
+ if datapoints is None:
32
+ return
33
+ offences = [
34
+ f"{location} -> set {datapoint.set!r}"
35
+ for location, datapoint in _set_references(datapoints)
36
+ if datapoint.set not in datapoints.sets
37
+ ]
38
+ if offences:
39
+ raise ValueError(
40
+ "Some datapoints reference undeclared sets: "
41
+ + "; ".join(offences)
42
+ + " (spec rule DP-16, chapter 4.7.4: an object datapoint's set resolves "
43
+ "to an entry in sets)"
44
+ )
45
+
46
+
47
+ def reject_recursive_sets(document: RumlDocument) -> None:
48
+ """Raise if a set references itself, directly or transitively (DP-17).
49
+
50
+ A field of a set may itself be of type `object` (nesting), but the sets must not
51
+ form a cycle (spec chapter 4.7.4): an instance would have no end. Every set on a
52
+ cycle is reported, each with the shortest chain of references leading back to it.
53
+ A reference to an undeclared set is `reject_undeclared_set_references`' business
54
+ and does not count as an edge here.
55
+
56
+ Raises:
57
+ ValueError: Naming every offending set and the chain of references that leads
58
+ back to it.
59
+ """
60
+ datapoints = document.capabilities.datapoints
61
+ if datapoints is None:
62
+ return
63
+ references = {
64
+ set_id: _referenced_sets(set_) for set_id, set_ in datapoints.sets.items()
65
+ }
66
+ offences = [
67
+ f"set {set_id!r}: " + " -> ".join(repr(set_id) for set_id in cycle)
68
+ for set_id in references
69
+ if (cycle := _cycle_through(set_id, references)) is not None
70
+ ]
71
+ if offences:
72
+ raise ValueError(
73
+ "Some sets reference themselves: "
74
+ + "; ".join(offences)
75
+ + " (spec rule DP-17, chapter 4.7.4: a set must not reference itself, "
76
+ "directly or transitively)"
77
+ )
78
+
79
+
80
+ def _set_references(
81
+ datapoints: DatapointsCapabilityDeclaration,
82
+ ) -> Iterator[tuple[str, Datapoint]]:
83
+ """Yield every datapoint that carries a `set`, with a description of where it is."""
84
+ for datapoint_id, datapoint in datapoints.data.items():
85
+ if datapoint.set is not None:
86
+ yield f"datapoint {datapoint_id!r}", datapoint
87
+ for set_id, set_ in datapoints.sets.items():
88
+ for datapoint_id, datapoint in set_.fields.items():
89
+ if datapoint.set is not None:
90
+ yield f"field {datapoint_id!r} of set {set_id!r}", datapoint
91
+
92
+
93
+ def _referenced_sets(set_: DatapointSet) -> list[SetId]:
94
+ """Return the distinct sets the fields of `set_` reference, in field order."""
95
+ return list(
96
+ unique_everseen(
97
+ field.set for field in set_.fields.values() if field.set is not None
98
+ )
99
+ )
100
+
101
+
102
+ def _cycle_through(
103
+ start: SetId, references: dict[SetId, list[SetId]]
104
+ ) -> list[SetId] | None:
105
+ """Return the shortest chain of references from `start` back to itself.
106
+
107
+ Returns `None` if there is none.
108
+
109
+ A breadth-first search over `references`; the chain begins and ends with `start`,
110
+ so a set referencing itself directly yields `[start, start]`.
111
+ """
112
+ parents: dict[SetId, SetId] = {}
113
+ queue = deque([start])
114
+ while queue:
115
+ current = queue.popleft()
116
+ for referenced in references.get(current, ()):
117
+ if referenced == start:
118
+ chain = [current]
119
+ while chain[-1] != start:
120
+ chain.append(parents[chain[-1]])
121
+ return [*reversed(chain), start]
122
+ if referenced not in parents:
123
+ parents[referenced] = current
124
+ queue.append(referenced)
125
+ return None
@@ -0,0 +1,42 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The spec's rule on which nodes must be marked as modular (chapter 6.2)."""
4
+
5
+ from collections import Counter
6
+
7
+ from ruml_parser.internal.ruml import BranchNode, RumlDocument
8
+ from ruml_parser.schema_validation import json_pointer
9
+ from ruml_parser.structural_error import RumlStructuralError, StructuralViolation
10
+
11
+
12
+ def reject_unmarked_modular_nodes(document: RumlDocument) -> None:
13
+ """Raise if a node is referenced more than once without being `modular`.
14
+
15
+ A node whose LexID appears more than once in the `children` arrays of the rulemap
16
+ must have `modular: true` (spec chapter 6.2, rule MOD-01). Every appearance counts:
17
+ in two parents, twice in one parent, and a node's reference to itself. The schema
18
+ cannot count across nodes, so the rule is checked here.
19
+
20
+ Raises:
21
+ RumlStructuralError: With one MOD-01 violation per offending node, at the node.
22
+ """
23
+ references = Counter(
24
+ child
25
+ for node in document.nodes.values()
26
+ if isinstance(node, BranchNode)
27
+ for child in node.children
28
+ )
29
+ violations = [
30
+ StructuralViolation(
31
+ rule="MOD-01",
32
+ message=f"node {lex_id!r} is referenced {count} times as a child"
33
+ " but is not marked `modular: true`",
34
+ paths=[json_pointer(("rulemap", "nodes", lex_id))],
35
+ )
36
+ for lex_id, count in references.items()
37
+ if count > 1
38
+ and (node := document.nodes.get(lex_id)) is not None
39
+ and node.modular is not True
40
+ ]
41
+ if violations:
42
+ raise RumlStructuralError(violations)
@@ -0,0 +1,197 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The spec's rules on how a node may recurse safely (chapter 6.4)."""
4
+
5
+ import logging
6
+ from collections.abc import Iterator, Mapping
7
+ from dataclasses import dataclass
8
+ from enum import StrEnum
9
+
10
+ from ruml_parser.internal.ruml import BranchNode, LexId, Node, Operator, RumlDocument
11
+ from ruml_parser.schema_validation import json_pointer
12
+ from ruml_parser.structural_error import RumlStructuralError, StructuralViolation
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ UNSAFE_RECURSION_OPERATORS = frozenset(
17
+ {Operator.AND, Operator.NOT_AND, Operator.OR, Operator.NOT_OR}
18
+ )
19
+ """The operators §6.4 says a recursive node should not use.
20
+
21
+ Safe recursion needs an operator that stops as soon as a child becomes `true`, so
22
+ that an exit condition before the self-reference can end the recursion. Only
23
+ `XOR`/`NOT_XOR` do; under the other four the recursion cannot resolve.
24
+ """
25
+
26
+
27
+ class RecursionFlag(StrEnum):
28
+ """What a rulemap's recursions are flagged for.
29
+
30
+ One member per §6.4 rule about a recursive node. The chapter's one remaining
31
+ statement — that such a node `SHOULD NOT` use one of
32
+ `UNSAFE_RECURSION_OPERATORS` — is the same condition as `unsafe_operator`,
33
+ phrased as a recommendation rather than as the warning that member carries,
34
+ so it needs none of its own.
35
+
36
+ Declaration order is the order one node's findings are reported in.
37
+ """
38
+
39
+ unsafe_operator = "unsafeOperator"
40
+ """A node lists its own lexId among its children and combines them with one of
41
+ `UNSAFE_RECURSION_OPERATORS`. §6.4 requires a warning about it: the evaluation
42
+ is semantically blocked, since no child can end the recursion."""
43
+
44
+ self_reference_first = "selfReferenceFirst"
45
+ """The self-reference is the node's first child. §6.4: it `MUST NOT` sit at
46
+ position 0, because an exit condition can only end the recursion if it is
47
+ evaluated before the node re-enters itself."""
48
+
49
+ no_exit_condition = "noExitCondition"
50
+ """Every child of the node is the self-reference. §6.4: a recursive node
51
+ `MUST` have at least one non-recursive child, or nothing can ever end it.
52
+ This one implies `self_reference_first`: if every child is the
53
+ self-reference, so is the first."""
54
+
55
+
56
+ class Severity(StrEnum):
57
+ """What §6.4 asks an implementation to do about a flag."""
58
+
59
+ warning = "warning"
60
+ """§6.4 asks for a warning and nothing else: the document is legal RUML, and
61
+ whether to evaluate it anyway is the caller's decision."""
62
+
63
+ violation = "violation"
64
+ """§6.4 states the rule as `MUST` or `MUST NOT`: the document breaks the spec."""
65
+
66
+
67
+ _SEVERITY: dict[RecursionFlag, Severity] = {
68
+ RecursionFlag.unsafe_operator: Severity.warning,
69
+ RecursionFlag.self_reference_first: Severity.violation,
70
+ RecursionFlag.no_exit_condition: Severity.violation,
71
+ }
72
+ """The force §6.4 gives each rule. A member missing here raises `KeyError` on the
73
+ first finding that carries it, rather than defaulting to the lenient answer."""
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class RecursionFinding:
78
+ """One flag raised by one node."""
79
+
80
+ flag: RecursionFlag
81
+ lex_id: LexId
82
+ """The node the flag is about."""
83
+ operator: Operator
84
+ """That node's operator, so a caller can report it without a second lookup."""
85
+
86
+ @property
87
+ def severity(self) -> Severity:
88
+ """What §6.4 asks of this finding.
89
+
90
+ Derived from `flag` rather than stored: the normative force belongs to the
91
+ rule, not to the occurrence, so a finding cannot contradict it — and it
92
+ stays out of the dataclass's equality, where it would only repeat what the
93
+ flag already says.
94
+ """
95
+ return _SEVERITY[self.flag]
96
+
97
+
98
+ _VIOLATED_RULE: dict[RecursionFlag, tuple[str, str]] = {
99
+ RecursionFlag.self_reference_first: (
100
+ "MOD-04",
101
+ "the self-reference must not be a recursive node's first child",
102
+ ),
103
+ RecursionFlag.no_exit_condition: (
104
+ "MOD-05",
105
+ "a recursive node must have at least one non-recursive child",
106
+ ),
107
+ }
108
+ """The spec rule each violation-severity flag breaks, and what it says.
109
+
110
+ Only violations appear here: `unsafe_operator` carries no rule code because §6.4
111
+ asks for a warning, not a rejection.
112
+ """
113
+
114
+
115
+ def reject_forbidden_recursion(document: RumlDocument) -> None:
116
+ """Act on every §6.4 recursion flag the document's nodes raise (MOD-03 to MOD-05).
117
+
118
+ The chapter does not treat its rules alike, so neither does this. A recursion
119
+ under an operator that cannot end it is only logged as a warning: the document
120
+ is legal RUML and is evaluated as usual, the evaluator's depth cap being what
121
+ stops the walk. The other two rules are stated as `MUST`/`MUST NOT`, so a
122
+ document breaking them is rejected.
123
+
124
+ Raises:
125
+ RumlStructuralError: With one MOD-04 violation per node whose first child is
126
+ the self-reference, at that child, and one MOD-05 violation per node with
127
+ no other child, at its `children`.
128
+ """
129
+ violations: list[StructuralViolation] = []
130
+ for finding in check_recursion(document.nodes):
131
+ if finding.severity is Severity.violation:
132
+ rule, text = _VIOLATED_RULE[finding.flag]
133
+ path = json_pointer(("rulemap", "nodes", finding.lex_id, "children"))
134
+ if finding.flag is RecursionFlag.self_reference_first:
135
+ path += "/0"
136
+ violations.append(
137
+ StructuralViolation(
138
+ rule=rule,
139
+ message=f"node {finding.lex_id!r}: {finding.flag.value}: {text}",
140
+ paths=[path],
141
+ )
142
+ )
143
+ continue
144
+ logger.warning(
145
+ "Rulemap %s: recursion flagged on node %r (operator %s): %s",
146
+ document.metadata.id,
147
+ finding.lex_id,
148
+ finding.operator.value,
149
+ finding.flag.value,
150
+ )
151
+ if violations:
152
+ raise RumlStructuralError(violations)
153
+
154
+
155
+ def check_recursion(nodes: Mapping[LexId, Node]) -> list[RecursionFinding]:
156
+ """Report every §6.4 recursion flag the nodes raise.
157
+
158
+ A diagnostic that never raises; `reject_forbidden_recursion` is the validation
159
+ built on it, splitting the findings into the warnings §6.4 asks for and the
160
+ `MUST`/`MUST NOT` breaches it rejects. A caller wanting the raw findings —
161
+ a linter, say — calls this directly.
162
+
163
+ Takes the nodes mapping rather than a `RumlDocument` because the rule reads
164
+ nothing but each node's `operator` and `children`.
165
+
166
+ The `modular` flag is deliberately not consulted. §6.4 describes recursion on
167
+ modular nodes, but a self-reference resolves — and blocks — the same way
168
+ without the marker, and the evaluator does not read it either.
169
+
170
+ Returns:
171
+ The findings in the order `nodes` iterates and, within one node, in
172
+ `RecursionFlag` declaration order — one node can raise more than one.
173
+ """
174
+ return [
175
+ RecursionFinding(flag=flag, lex_id=lex_id, operator=node.operator)
176
+ for lex_id, node in nodes.items()
177
+ if isinstance(node, BranchNode) and lex_id in node.children
178
+ for flag in _flags_for(lex_id, node)
179
+ ]
180
+
181
+
182
+ def _flags_for(lex_id: LexId, node: Node) -> Iterator[RecursionFlag]:
183
+ """Every flag the recursive `node` raises, in declaration order.
184
+
185
+ Args:
186
+ lex_id: The node's own lexId.
187
+ node: The node to check. Must list `lex_id` among its children.
188
+ """
189
+ if not isinstance(node, BranchNode):
190
+ return
191
+ if node.operator in UNSAFE_RECURSION_OPERATORS:
192
+ yield RecursionFlag.unsafe_operator
193
+ # Safe to index: `node` lists `lex_id` among its children, so it has at least one.
194
+ if node.children[0] == lex_id:
195
+ yield RecursionFlag.self_reference_first
196
+ if all(child == lex_id for child in node.children):
197
+ yield RecursionFlag.no_exit_condition
@@ -0,0 +1,36 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The spec's rule that nothing contains the root node (chapter 3.5.1)."""
4
+
5
+ from ruml_parser.internal.ruml import BranchNode, RumlDocument
6
+ from ruml_parser.schema_validation import json_pointer
7
+ from ruml_parser.structural_error import RumlStructuralError, StructuralViolation
8
+
9
+ ROOT_LEX_ID = "1"
10
+
11
+
12
+ def reject_root_as_child(document: RumlDocument) -> None:
13
+ """Raise if the root node `"1"` appears in a `children` array (rule NODE-05).
14
+
15
+ This holds for a modular root as well: recursion (MOD-02) is open to any other node.
16
+
17
+ Raises:
18
+ RumlStructuralError: With one NODE-05 violation, at every such entry.
19
+ """
20
+ paths = [
21
+ json_pointer(("rulemap", "nodes", lex_id, "children", index))
22
+ for lex_id, node in document.nodes.items()
23
+ if isinstance(node, BranchNode)
24
+ for index, child in enumerate(node.children)
25
+ if child == ROOT_LEX_ID
26
+ ]
27
+ if paths:
28
+ raise RumlStructuralError(
29
+ [
30
+ StructuralViolation(
31
+ rule="NODE-05",
32
+ message="the root node '1' is listed as a child",
33
+ paths=paths,
34
+ )
35
+ ]
36
+ )