imandrax-api-models 21.0.0__tar.gz → 21.2.0__tar.gz

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 (45) hide show
  1. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/PKG-INFO +2 -2
  2. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/pyproject.toml +3 -7
  3. imandrax_api_models-21.2.0/src/imandrax_api_models/.DS_Store +0 -0
  4. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/operators.py +109 -8
  5. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/term_formatter.py +200 -98
  6. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/api.py +2 -2
  7. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/decomp.py +19 -0
  8. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/error.py +2 -2
  9. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/simple_api.py +12 -12
  10. imandrax_api_models-21.2.0/src/imandrax_api_models/region_decomp/.DS_Store +0 -0
  11. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/region_decomp/__init__.py +173 -2
  12. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/README.md +0 -0
  13. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/__init__.py +0 -0
  14. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/_import_err.py +0 -0
  15. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/_rec_limit.py +0 -0
  16. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/artifacts.py +0 -0
  17. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/client.py +0 -0
  18. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/client_evaluate.py +0 -0
  19. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/context_utils.py +0 -0
  20. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/logging_utils.py +0 -0
  21. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/__init__.py +0 -0
  22. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/_common.py +0 -0
  23. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/decomp.py +0 -0
  24. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/eval_formatter.py +0 -0
  25. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/goal_state.py +0 -0
  26. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/model_formatter.py +0 -0
  27. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/pretty.py +0 -0
  28. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/proof_formatter.py +0 -0
  29. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/report_formatter.py +0 -0
  30. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/term_builders.py +0 -0
  31. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/type_formatter.py +0 -0
  32. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/pp/xtype.py +0 -0
  33. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/__init__.py +0 -0
  34. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/artmsg.py +0 -0
  35. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/locs.py +0 -0
  36. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/session.py +0 -0
  37. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/system.py +0 -0
  38. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/task.py +0 -0
  39. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_models/utils.py +0 -0
  40. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/proto_utils.py +0 -0
  41. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/py.typed +0 -0
  42. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/region_decomp/_common.py +0 -0
  43. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/region_decomp/_region.py +0 -0
  44. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/trace_utils.py +0 -0
  45. {imandrax_api_models-21.0.0 → imandrax_api_models-21.2.0}/src/imandrax_api_models/yaml_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: imandrax-api-models
3
- Version: 21.0.0
3
+ Version: 21.2.0
4
4
  Summary: Pydantic model definitions for imandrax-api. Also provides a client wrapper with built-in validation and utility methods.
5
5
  Author: hongyu
6
6
  Author-email: hongyu <hongyu@imandra.ai>
@@ -8,7 +8,7 @@ Requires-Dist: devtools>=0.12.2
8
8
  Requires-Dist: imandrax-api[async]>=0.21.0,<0.22
9
9
  Requires-Dist: pydantic>=2.12.4
10
10
  Requires-Dist: pyyaml>=6.0.3
11
- Requires-Dist: iml-query>=0.14.0 ; extra == 'client'
11
+ Requires-Dist: iml-query>=0.17.0 ; extra == 'client'
12
12
  Requires-Dist: opentelemetry-api>=1.27 ; extra == 'tracing'
13
13
  Requires-Dist: opentelemetry-sdk>=1.27 ; extra == 'tracing'
14
14
  Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.41.1 ; extra == 'tracing'
@@ -1,11 +1,9 @@
1
1
  [project]
2
2
  name = "imandrax-api-models"
3
- version = "21.0.0"
3
+ version = "21.2.0"
4
4
  description = "Pydantic model definitions for imandrax-api. Also provides a client wrapper with built-in validation and utility methods."
5
5
  readme = "README.md"
6
- authors = [
7
- { name = "hongyu", email = "hongyu@imandra.ai" }
8
- ]
6
+ authors = [{ name = "hongyu", email = "hongyu@imandra.ai" }]
9
7
  requires-python = ">=3.12"
10
8
  dependencies = [
11
9
  "devtools>=0.12.2",
@@ -15,9 +13,7 @@ dependencies = [
15
13
  ]
16
14
 
17
15
  [project.optional-dependencies]
18
- client = [
19
- "iml-query>=0.14.0",
20
- ]
16
+ client = ["iml-query>=0.17.0"]
21
17
  tracing = [
22
18
  "opentelemetry-api>=1.27",
23
19
  "opentelemetry-sdk>=1.27",
@@ -7,6 +7,7 @@ Precedence table follows OCaml 5.3 (https://ocaml.org/manual/5.3/expr.html).
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import re
10
11
  from dataclasses import dataclass
11
12
  from enum import IntEnum
12
13
 
@@ -45,6 +46,50 @@ def short_id(uid: xtype.Uid) -> str:
45
46
  return uid.name
46
47
 
47
48
 
49
+ _OPERATOR_CHARS = frozenset('!$%&*+-./:<=>?@^|~#')
50
+ _KEYWORD_OPERATORS = frozenset(
51
+ ('mod', 'land', 'lor', 'lxor', 'lsl', 'lsr', 'asr', 'or')
52
+ )
53
+
54
+
55
+ def is_operator_name(name: str) -> bool:
56
+ """
57
+ `name` is an operator, which OCaml lexes as infix or prefix: `+`, `::`, `mod`.
58
+
59
+ `$lambda_1` is not one: a generated name, `$` followed by an identifier.
60
+ """
61
+ return name in _KEYWORD_OPERATORS or (
62
+ name != '' and all(ch in _OPERATOR_CHARS for ch in name)
63
+ )
64
+
65
+
66
+ def const2str(c: xtype.Const) -> str:
67
+ """
68
+ IML source text of a constant.
69
+
70
+ Lives here, not in `term_formatter`, so that `operator_info_of_term` can
71
+ decide a constant's precedence from the text that is actually printed.
72
+ """
73
+ match c:
74
+ case xtype.Const_Const_float(arg=v):
75
+ return repr(v)
76
+ case xtype.Const_Const_string(arg=v):
77
+ return f'"{v}"'
78
+ case xtype.Const_Const_z(arg=v):
79
+ return str(v)
80
+ case xtype.Const_Const_q(arg=(num, den)):
81
+ if den != 1:
82
+ return f'{num}.0 /. {den}.0'
83
+ return f'{num}.0'
84
+ case xtype.Const_Const_real_approx(arg=v):
85
+ return v
86
+ case xtype.Const_Const_uid(arg=u):
87
+ return u.name
88
+ case xtype.Const_Const_bool(arg=v):
89
+ return 'true' if v else 'false'
90
+ return repr(c)
91
+
92
+
48
93
  def has_multiple_children(t: xtype.Mir_Term) -> bool:
49
94
  v = t.view
50
95
  match v:
@@ -86,8 +131,13 @@ def operator_info(op: str, more_than_one_arg: bool = False) -> OperatorInfo:
86
131
  if op == 'assert' or op == 'lazy':
87
132
  return OperatorInfo(op, Notation.PREFIX, Associativity.LEFT, 17)
88
133
  # unary minus
89
- if op in ('-', '-.', '~-', '~-.') and not more_than_one_arg:
90
- return OperatorInfo(op, Notation.PREFIX, Associativity.NONE, 16)
134
+ # `~-` and `~-.` are named `-` and `-.`: printed as `~-`, the lexer reads a
135
+ # prefix symbol binding tighter than application, so `~- f x` is `(~- f) x`.
136
+ # A binary `-` with fewer than two arguments is a partial application, not
137
+ # a negation: it falls through to the infix rule and prints as `( - ) x`.
138
+ if op in ('~-', '~-.'):
139
+ name = '-.' if op.endswith('.') else '-'
140
+ return OperatorInfo(name, Notation.PREFIX, Associativity.NONE, 16)
91
141
  # **… lsl lsr asr
92
142
  if op.startswith('**') or op in ('lsl', 'lsr', 'asr'):
93
143
  return OperatorInfo(op, Notation.INFIX, Associativity.RIGHT, 15)
@@ -122,7 +172,7 @@ def operator_info(op: str, more_than_one_arg: bool = False) -> OperatorInfo:
122
172
  op.startswith(('=', '<', '>'))
123
173
  or (op.startswith('|') and op != '||')
124
174
  or (op.startswith('&') and op not in ('&', '&&'))
125
- or op.startswith('$')
175
+ or (op.startswith('$') and is_operator_name(op))
126
176
  or op == '!='
127
177
  ):
128
178
  return OperatorInfo(op, Notation.INFIX, Associativity.LEFT, 10)
@@ -170,27 +220,78 @@ def is_default(x: OperatorInfo) -> bool:
170
220
  )
171
221
 
172
222
 
223
+ _MODULE_PATH = re.compile(r'^(?:[A-Z][A-Za-z0-9_\']*\.)+(?P<short>.+)$')
224
+
225
+
226
+ def short_name(full: str) -> str:
227
+ """
228
+ Name without its module path: `Int.<` -> `<`, `Float.+.` -> `+.`.
229
+
230
+ `+.` keeps its trailing dot, which is part of the operator, not a path.
231
+ """
232
+ if m := _MODULE_PATH.match(full):
233
+ return m['short']
234
+ dot = full.rfind('.')
235
+ return full[dot + 1 :] if 0 < dot < len(full) - 1 else full
236
+
237
+
238
+ def _is_fallback(info: OperatorInfo, op: str) -> bool:
239
+ """`operator_info` did not recognise `op` and treats it as a plain function."""
240
+ return info == OperatorInfo(op, Notation.PREFIX, Associativity.LEFT, 17)
241
+
242
+
243
+ def sym_operator_info(
244
+ full: str, more_than_one_arg: bool = False
245
+ ) -> tuple[OperatorInfo, str]:
246
+ """
247
+ Operator info of a symbol, and the text to print for it.
248
+
249
+ Both come from the same name, so the layout matches the text: the full name
250
+ when it is a known operator or alias (`implies` -> `==>`, `List.append` ->
251
+ `@`), otherwise the name without its module path (`Int.<` -> `<`, infix).
252
+ """
253
+ info = operator_info(full, more_than_one_arg)
254
+ if not _is_fallback(info, full):
255
+ return info, info.name
256
+ short = short_name(full)
257
+ info = operator_info(short, more_than_one_arg)
258
+ return info, (short if _is_fallback(info, short) else info.name)
259
+
260
+
173
261
  def operator_info_of_term(t: xtype.Mir_Term) -> OperatorInfo:
174
262
  v = t.view
175
263
  match v:
176
264
  case xtype.Mir_Term_view_If():
177
265
  return operator_info('if', False)
178
266
  case xtype.Mir_Term_view_Apply(f=f, l=args):
179
- if isinstance(f.view, xtype.Mir_Term_view_Sym):
180
- return operator_info(short_id(f.view.arg.sym.id), len(args) > 0)
267
+ # With no arguments, an operator prints as the atom `(+)`.
268
+ if isinstance(f.view, xtype.Mir_Term_view_Sym) and args:
269
+ return sym_operator_info(short_id(f.view.arg.sym.id), len(args) > 1)[0]
181
270
  return default_()
182
271
  case xtype.Mir_Term_view_Tuple():
183
272
  return operator_info(',', False)
184
273
  case xtype.Mir_Term_view_Case():
185
- return operator_info('match', False)
274
+ # NOTE: this deviates from `imandrax_operators.ts`, where `Case` is
275
+ # a `match`. We print it as the application `Case(u, [...])` (see
276
+ # `term_formatter.py`), so it binds like one.
277
+ return default_()
186
278
  case xtype.Mir_Term_view_Construct(c=c, args=args):
187
- return operator_info(short_id(c.sym.id), len(args) > 0)
279
+ return sym_operator_info(short_id(c.sym.id), len(args) > 1)[0]
188
280
  case xtype.Mir_Term_view_Const(arg=c):
189
281
  if isinstance(c, xtype.Const_Const_q) and c.arg[1] != 1:
190
282
  return operator_info('/.', True)
283
+ # A literal printed with a leading `-` binds like unary minus:
284
+ # `Some -1` parses as `Some - 1`.
285
+ if const2str(c).startswith('-'):
286
+ return operator_info('~-', False)
191
287
  return default_()
288
+ case xtype.Mir_Term_view_Sequence():
289
+ return operator_info(';', True)
192
290
  case xtype.Mir_Term_view_Is_a():
193
- return OperatorInfo('is-a', Notation.INFIX, Associativity.LEFT, 17)
291
+ # NOTE: this deviates from `imandrax_operators.ts`, where `Is_a`
292
+ # is the infix `is-a`. We print it as the application `Is_a(C, t)`
293
+ # (see `term_formatter.py`), so it binds like one.
294
+ return OperatorInfo('Is_a', Notation.PREFIX, Associativity.LEFT, 17)
194
295
  case _:
195
296
  return default_()
196
297
 
@@ -9,15 +9,17 @@ from . import operators as IXO
9
9
  from .operators import (
10
10
  Notation,
11
11
  OperatorInfo,
12
+ const2str,
12
13
  has_multiple_children,
14
+ is_operator_name,
13
15
  needs_parentheses,
14
16
  operator_info,
15
17
  operator_info_of_term,
16
18
  short_id,
19
+ sym_operator_info,
17
20
  )
18
21
  from .pretty import (
19
22
  Doc,
20
- brackets,
21
23
  flatten,
22
24
  group,
23
25
  hcat,
@@ -32,6 +34,69 @@ from .pretty import (
32
34
  text,
33
35
  )
34
36
 
37
+ # Note [MIR Term Formatter]
38
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~
39
+ #
40
+ # (A) Goal
41
+ #
42
+ # The output should read as IML: it should parse, with a parse tree matching
43
+ # the MIR term.
44
+ # Type-checking is not a goal. Some MIR nodes have no IML source form and are printed
45
+ # in a form that parses but is not defined in IML.
46
+ # Names are printed without their module path (`List.length` as `length`), so they may
47
+ # not resolve.
48
+ #
49
+ # (B) How it works
50
+ #
51
+ # `term2doc` walks the term's view and builds a `Doc`. `group`
52
+ # lays a part out flat if it fits the width and breaks its `line`s otherwise.
53
+ #
54
+ # Parentheses come from precedence. `operators.operator_info_of_term` gives the
55
+ # precedence, associativity and notation of a term as printed, following
56
+ # OCaml's table. `recwp` parenthesises a child when `needs_parentheses` says
57
+ # the parent binds tighter. Some positions have their own rule:
58
+ #
59
+ # - `_tuple_elem2doc`, a tuple element or constructor argument: parenthesise
60
+ # anything binding no tighter than `,`, as in `Set ((a; b), c)`.
61
+ # - `_atom2doc`, the base of `.f`, or an applied function that is not a
62
+ # symbol: parenthesise anything compound, as in `(hd l).x` and
63
+ # `(Destruct((::), 0, ts)) x`.
64
+ # - `if` branches: parenthesise anything binding looser than `if`.
65
+ # `if c then a; b else e` does not parse, and `if c then x else a; b`
66
+ # parses as `(if c then x else a); b`.
67
+ #
68
+ # `operators.sym_operator_info` gives both the layout (infix or prefix) and the
69
+ # printed text of a symbol, from the same name: `Int.<` prints as `x < y`,
70
+ # `List.append` as `x @ y`, `~-` as `- x`.
71
+ #
72
+ # (W1) Cases that parses but does not type-check
73
+ #
74
+ # MIR reads and tests constructors directly, where IML binds fields in a
75
+ # `match` pattern. These nodes are printed as a capitalised name applied to a
76
+ # tuple, which parses as a constructor application:
77
+ #
78
+ # - `Destruct(C, i, t)`: field `i` of `t`, built with constructor `C`.
79
+ # - `Is_a(C, t)`: `t` is built with `C`.
80
+ # - `Case(u, [(C1, t1); (C2, t2)], d)`: branch on the constructor of `u`; `d`
81
+ # is the default branch, printed only when present. MIR's `Case` binds no
82
+ # fields; branches read them with `Destruct`. A `match` would need each
83
+ # constructor's arity for its pattern.
84
+ #
85
+ # `Destruct` and `Is_a` are spelled as in ImandraX's region strings; `Case`
86
+ # follows them. None of the three is defined in IML. Operator constructors are
87
+ # parenthesised in them: `Destruct((::), 0, l)`, `Case(l, [((::), 1); ([], 0)])`.
88
+ #
89
+ # (W2) Does not parse
90
+ #
91
+ # - Tuple projections print as `t.0`, which is a syntax error. IML has no
92
+ # projection syntax, and a `match` would need the tuple's size.
93
+ # - Generated names, such as a lifted lambda `$lambda...` or `$opt_depth` in
94
+ # `Tactic.repeat`, print as is. `$` cannot start an identifier. Printing
95
+ # the lambda as `fun ...` would need the MIR DB.
96
+ #
97
+ # Both occur mostly in prelude internals (`fst`, `snd`, `Tactic`, `Decomp`).
98
+ #
99
+
35
100
  # Small helpers
36
101
  # =============
37
102
 
@@ -60,13 +125,7 @@ def _applied_sym_short(s: xtype.Common_Applied_symbol_t_poly) -> str:
60
125
  """
61
126
  Short, display-friendly name for an applied symbol, with module path stripped (the dotted prefix, if any).
62
127
  """
63
- sid = short_id(_applied_sym_id(s))
64
- op_info = operator_info(sid)
65
- op_name = sid if op_info.name == '' else op_info.name
66
- dot_inx = sid.rfind('.')
67
- if 0 < dot_inx < len(sid) - 1:
68
- op_name = sid[dot_inx + 1 :]
69
- return op_name
128
+ return sym_operator_info(short_id(_applied_sym_id(s)))[1]
70
129
 
71
130
 
72
131
  # Constants
@@ -74,24 +133,7 @@ def _applied_sym_short(s: xtype.Common_Applied_symbol_t_poly) -> str:
74
133
 
75
134
 
76
135
  def _const2doc(c: xtype.Const) -> Doc:
77
- match c:
78
- case xtype.Const_Const_float(arg=v):
79
- return text(repr(v))
80
- case xtype.Const_Const_string(arg=v):
81
- return text(f'"{v}"')
82
- case xtype.Const_Const_z(arg=v):
83
- return text(str(v))
84
- case xtype.Const_Const_q(arg=(num, den)):
85
- if den != 1:
86
- return text(f'{num}.0 /. {den}.0')
87
- return text(f'{num}.0')
88
- case xtype.Const_Const_real_approx(arg=v):
89
- return text(v)
90
- case xtype.Const_Const_uid(arg=u):
91
- return text(u.name)
92
- case xtype.Const_Const_bool(arg=v):
93
- return text('true' if v else 'false')
94
- return text(repr(c))
136
+ return text(const2str(c))
95
137
 
96
138
 
97
139
  # Subterm-selection (used inside `subterm_selection_select`)
@@ -119,6 +161,17 @@ def sym2doc(s: xtype.Common_Applied_symbol_t_poly) -> Doc:
119
161
  return text(_applied_sym_short(s))
120
162
 
121
163
 
164
+ def _standalone_sym2doc(s: xtype.Common_Applied_symbol_t_poly) -> Doc:
165
+ """
166
+ A symbol used as a value rather than applied.
167
+
168
+ As in `fold_left (+) 0 l` or `Destruct(C, i, t)`. An operator is
169
+ parenthesised: `(+)`, `Destruct((::), 0, l)`.
170
+ """
171
+ name = _applied_sym_short(s)
172
+ return text(f'({name})' if is_operator_name(name) else name)
173
+
174
+
122
175
  # subterm_selection_select(...) special-casing
123
176
  # --------------------------------------------
124
177
 
@@ -159,6 +212,44 @@ def _subterm_selection2doc(ts: list[xtype.Mir_Term]) -> Doc:
159
212
  # --------------
160
213
 
161
214
 
215
+ def _tuple_elem2doc(x: xtype.Mir_Term) -> Doc:
216
+ """
217
+ Print a term as one element of a tuple.
218
+
219
+ A term binding no tighter than `,` (a tuple, `if`, `match`, ...) is
220
+ parenthesised so it stays one element.
221
+ """
222
+ return _par_if(operator_info_of_term(x).precedence <= _COMMA_PREC, [term2doc(x)])
223
+
224
+
225
+ _COMMA_PREC = operator_info(',').precedence
226
+ _IF_PREC = operator_info('if').precedence
227
+
228
+
229
+ def _atom2doc(x: xtype.Mir_Term) -> Doc:
230
+ """
231
+ Print a term where only an atom fits.
232
+
233
+ These are the base of a field or tuple-element access, and the function of
234
+ an application. Both bind at least as tight as application, so any compound term is
235
+ parenthesised: `(f x).g`, not `f x.g`; `(Destruct(C, i, t)) x`, not
236
+ `Destruct(C, i, t) x`, which applies a constructor to two arguments.
237
+ """
238
+ return _par_if(has_multiple_children(x), [term2doc(x)])
239
+
240
+
241
+ def _tuple2doc(docs: list[Doc]) -> Doc:
242
+ """Print already-printed elements in IML tuple syntax, `(a, b, c)`."""
243
+ return _g(
244
+ [
245
+ text('('),
246
+ _indent([linebreak, join(hcat(text(','), line), docs)]),
247
+ linebreak,
248
+ text(')'),
249
+ ]
250
+ )
251
+
252
+
162
253
  def terms2doc(ts: list[xtype.Mir_Term]) -> Doc:
163
254
  """Show terms in one `Terms(t1, t2, ...)` block."""
164
255
  term_f = lambda t: flatten(term2doc(t))
@@ -195,27 +286,34 @@ def term2doc(t: xtype.Mir_Term) -> Doc:
195
286
  return _const2doc(c)
196
287
 
197
288
  case xtype.Mir_Term_view_If(args=(c, th, el)):
289
+ # A branch binding looser than `if` is parenthesised:
290
+ # `if c then a; b else e` does not parse, and `if c then x else a; b`
291
+ # parses as `(if c then x else a); b`.
292
+ def branch(x: xtype.Mir_Term) -> Doc:
293
+ looser = operator_info_of_term(x).precedence < _IF_PREC
294
+ return _par_if(looser, [rec(x)])
295
+
198
296
  return _g(
199
297
  [
200
- _g([_kw('if'), _indent([line, rec(c)]), line, _kw('then')]),
201
- _indent([line, rec(th)]),
298
+ _g([_kw('if'), _indent([line, branch(c)]), line, _kw('then')]),
299
+ _indent([line, branch(th)]),
202
300
  line,
203
301
  _kw('else'),
204
- _indent([line, rec(el)]),
302
+ _indent([line, branch(el)]),
205
303
  ]
206
304
  )
207
305
 
208
306
  case xtype.Mir_Term_view_Apply(f=f, l=args):
209
- fn = rec(f)
210
307
  if isinstance(f.view, xtype.Mir_Term_view_Sym):
211
308
  s = f.view.arg
212
309
  sid = short_id(s.sym.id)
213
- pi = operator_info(sid, len(args) > 1)
310
+ pi, name = sym_operator_info(sid, len(args) > 1)
311
+ fn = text(name)
214
312
 
215
313
  if sid == 'subterm_selection_select':
216
314
  return _subterm_selection2doc(args)
217
315
  if len(args) == 0:
218
- return fn
316
+ return _standalone_sym2doc(s)
219
317
  if pi.notation == Notation.INFIX:
220
318
  if len(args) == 2:
221
319
  lhs = recwp(pi, args[0], True)
@@ -236,27 +334,30 @@ def term2doc(t: xtype.Mir_Term) -> Doc:
236
334
  ]
237
335
  )
238
336
  return _g([fn, hargs])
239
- # fn is a function term, not a symbol
337
+ # The function is a term, not a symbol.
338
+ fn = _atom2doc(f)
339
+ if len(args) == 0:
340
+ return fn
240
341
  hargs = _indent(
241
342
  [
242
343
  line,
243
344
  join(line, [recwp(IXO.default_(), x) for x in args]),
244
345
  ]
245
346
  )
246
- return _par_if(len(args) > 0, [fn, hargs])
347
+ return _g([fn, hargs])
247
348
 
248
349
  case xtype.Mir_Term_view_Var(arg=var):
249
350
  return text(var.id.name)
250
351
 
251
352
  case xtype.Mir_Term_view_Sym(arg=s):
252
- return sym2doc(s)
353
+ return _standalone_sym2doc(s)
253
354
 
254
355
  case xtype.Mir_Term_view_Construct(c=c, args=args):
255
356
  if len(args) == 0:
256
357
  return sym2doc(c)
257
- op_doc = sym2doc(c)
258
358
  sid = short_id(c.sym.id)
259
- pi = operator_info(sid, len(args) > 1)
359
+ pi, name = sym_operator_info(sid, len(args) > 1)
360
+ op_doc = text(name)
260
361
  if pi.notation == Notation.INFIX:
261
362
  if len(args) == 2:
262
363
  lhs = recwp(pi, args[0], True)
@@ -269,32 +370,58 @@ def term2doc(t: xtype.Mir_Term) -> Doc:
269
370
  ]
270
371
  )
271
372
  return _g([text('( '), op_doc, text(' )'), hargs])
272
- rargs = [rec(x) for x in args]
273
- return _g([op_doc, _indent([line, join(line, rargs)])])
373
+ # NOTE: this deviates from `term-formatter.ts`, which joins the
374
+ # arguments with spaces and no parentheses, producing `Set S1 a b`
375
+ # for `Set (S1, a, b)` and `Some f x` for `Some (f x)`, neither of
376
+ # which is valid IML. We print one argument as an application argument
377
+ # (parenthesised when needed), several as parenthesised.
378
+ if len(args) == 1:
379
+ return _g([op_doc, _indent([line, recwp(IXO.default_(), args[0])])])
380
+ return _g(
381
+ [op_doc, text(' '), _tuple2doc([_tuple_elem2doc(x) for x in args])]
382
+ )
274
383
 
384
+ # NOTE: `Destruct` and `Is_a` deviate from `term-formatter.ts`, which
385
+ # prints them as `destruct[C|i] t` and `t is-a C`, display notation
386
+ # that does not parse as IML.
387
+ # We print the form ImandraX itself uses in its region strings,
388
+ # `Destruct(C, i, t)` and `Is_a(C, t)`.
389
+ # These parse, though neither is defined in IML, so they do not type-check
390
+ # as source.
275
391
  case xtype.Mir_Term_view_Destruct(c=c, i=i, t=inner):
276
392
  return _g(
277
393
  [
278
- _kw('destruct'),
279
- brackets(hcat(sym2doc(c), text('|'), text(str(i)))),
280
- _indent([line, recwp(IXO.default_(), inner)]),
394
+ _kw('Destruct'),
395
+ _tuple2doc(
396
+ [_standalone_sym2doc(c), text(str(i)), _tuple_elem2doc(inner)]
397
+ ),
281
398
  ]
282
399
  )
283
400
 
284
401
  case xtype.Mir_Term_view_Is_a(c=c, t=inner):
285
- pi = operator_info_of_term(t)
286
- lhs = recwp(pi, inner, True)
287
- rhs = sym2doc(c)
288
- return _g([lhs, line, _kw(pi.name), line, rhs])
402
+ return _g(
403
+ [
404
+ _kw('Is_a'),
405
+ _tuple2doc([_standalone_sym2doc(c), _tuple_elem2doc(inner)]),
406
+ ]
407
+ )
289
408
 
290
409
  case xtype.Mir_Term_view_Tuple(l=ls):
291
- return _g([_indent([join(hcat(text(','), line), [rec(x) for x in ls])])])
410
+ return _g(
411
+ [
412
+ _indent(
413
+ [join(hcat(text(','), line), [_tuple_elem2doc(x) for x in ls])]
414
+ )
415
+ ]
416
+ )
292
417
 
293
418
  case xtype.Mir_Term_view_Field(f=f, t=inner):
294
- return _g([rec(inner), text('.'), linebreak, sym2doc(f)])
419
+ inner_doc = _atom2doc(inner)
420
+ return hcat(inner_doc, text('.'), sym2doc(f))
295
421
 
296
422
  case xtype.Mir_Term_view_Tuple_field(i=i, t=inner):
297
- return _g([rec(inner), text('.'), linebreak, text(str(i))])
423
+ inner_doc = _atom2doc(inner)
424
+ return hcat(inner_doc, text('.'), text(str(i)))
298
425
 
299
426
  case xtype.Mir_Term_view_Record(rows=rows, rest=rest):
300
427
  if False:
@@ -317,9 +444,9 @@ def term2doc(t: xtype.Mir_Term) -> Doc:
317
444
  return hcat(text('{'), hrest, hrows, text('}'))
318
445
  else:
319
446
  # leading separators style, with
320
- # `{`, `;` and `}` aligned when broken. Flat: `{ a: 1; b: 2 }`.
321
- # { fst_key: fst_item
322
- # ; snd_key: snd_item
447
+ # `{`, `;` and `}` aligned when broken. Flat: `{ a = 1; b = 2 }`.
448
+ # { fst_key = fst_item
449
+ # ; snd_key = snd_item
323
450
  # }
324
451
  if not rows:
325
452
  return (
@@ -328,7 +455,7 @@ def term2doc(t: xtype.Mir_Term) -> Doc:
328
455
  else _g([text('{ '), rec(rest), text(' }')])
329
456
  )
330
457
  fields = [
331
- group(_indent([sym2doc(sym), text(':'), line, rec(term)]))
458
+ group(_indent([sym2doc(sym), text(' ='), line, rec(term)]))
332
459
  for sym, term in rows
333
460
  ]
334
461
  head: list[Doc] = [text('{ ')]
@@ -341,55 +468,30 @@ def term2doc(t: xtype.Mir_Term) -> Doc:
341
468
  body += [linebreak, text('; '), fd]
342
469
  return group(hcat(*head, *body, line, text('}')))
343
470
 
471
+ # NOTE: this deviates from `term-formatter.ts`, which prints
472
+ # `case u of | C -> t | ...`. That does not parse as IML, and a real
473
+ # `match` would need a pattern for each constructor's fields, which MIR's
474
+ # `Case` does not bind: branches read them with `Destruct`.
475
+ # We print the MIR node as a pseudo-constructor, like `Destruct`:
476
+ # `Case(u, [(C1, t1); (C2, t2)])`, with the default branch as a third
477
+ # element when present, `Case(u, [(C1, t1)], d)`.
344
478
  case xtype.Mir_Term_view_Case(u=u, cases=cases, default=default):
345
- hcases = join(
346
- line,
347
- [
348
- _g(
349
- [
350
- text('|'),
351
- line,
352
- sym2doc(sym),
353
- line,
354
- text('->'),
355
- line,
356
- rec(term),
357
- ]
358
- )
359
- for sym, term in cases
360
- ],
361
- )
362
- hdefault: Doc = (
363
- _g(
364
- [
365
- line,
366
- text('|'),
367
- line,
368
- text('_'),
369
- line,
370
- text('->'),
371
- line,
372
- rec(default),
373
- ]
374
- )
375
- if default is not None
376
- else nil
377
- )
378
- # NOTE: this deviates from `term-formatter.ts`, which writes
379
- # `rec(v.u), kw("of")` with no separator — producing `optof`.
380
- # We add a `line` so the scrutinee and `of` are space-separated.
381
- return _g(
479
+ branches = [
480
+ _tuple2doc([_standalone_sym2doc(sym), _tuple_elem2doc(term)])
481
+ for sym, term in cases
482
+ ]
483
+ hcases = _g(
382
484
  [
383
- _kw('case'),
384
- line,
385
- rec(u),
386
- line,
387
- _kw('of'),
388
- line,
389
- hcases,
390
- hdefault,
485
+ text('['),
486
+ _indent([linebreak, join(hcat(text(';'), line), branches)]),
487
+ linebreak,
488
+ text(']'),
391
489
  ]
392
490
  )
491
+ elems = [_tuple_elem2doc(u), hcases]
492
+ if default is not None:
493
+ elems.append(_tuple_elem2doc(default))
494
+ return _g([_kw('Case'), _tuple2doc(elems)])
393
495
 
394
496
  case xtype.Mir_Term_view_Sequence(args=(items, last)):
395
497
  # NOTE: this deviates from `term-formatter.ts`, which joins
@@ -83,7 +83,7 @@ class ArtifactZip(BaseModel):
83
83
 
84
84
 
85
85
  class ArtifactResultError(Exception):
86
- """Raised by `unwrap` on an artifact result that holds an error."""
86
+ """Error hold by an artifact result"""
87
87
 
88
88
  def __init__(self, error: Error) -> None:
89
89
  self.error = error
@@ -95,7 +95,7 @@ class _OkOrError[T](BaseModel):
95
95
  # oneof result
96
96
  ok: T | None = Field(default=None)
97
97
  error: Error | None = Field(default=None)
98
- # oneof result
98
+ # /oneof result
99
99
 
100
100
  @model_validator(mode='after')
101
101
  def one_of_result(self) -> Self:
@@ -385,10 +385,19 @@ def _decomp_of_cst(d: DecompCST, name: str) -> Decomp:
385
385
  function from an identifier to a result, and `<<` / `<|<` compose on the
386
386
  left of that application. So `name` is threaded down the left spine, while
387
387
  each right operand is a `LazyRet` carrying its own identifier.
388
+
389
+ Refiners map onto the plan API as checked against ImandraX evaluating the
390
+ same `[@@decomp ...]` attribute: `m |>> prune` / `m |>> combine` / `~| m`
391
+ are `Prune(m)` / `Combine(m)`, and `m |>> enumerate d` and
392
+ `m |>> enumerate_all ~style:s [d1; ...]` are `Enumerate(d_f=m, ds=[d1, ...],
393
+ style=s)`. With a single `d` the style makes no difference.
388
394
  """
389
395
  from iml_query.processing.decomp import (
396
+ Combine as CombineCST,
390
397
  CompoundMerge as CompoundMergeCST,
398
+ Enumerate as EnumerateCST,
391
399
  Merge as MergeCST,
400
+ Prune as PruneCST,
392
401
  Top as TopCST,
393
402
  )
394
403
 
@@ -413,6 +422,16 @@ def _decomp_of_cst(d: DecompCST, name: str) -> Decomp:
413
422
  d1=_decomp_of_cst(d.m, name),
414
423
  d2=_decomp_of_cst(d.d1.m, d.d1.identifier),
415
424
  )
425
+ case PruneCST():
426
+ return Prune(d=_decomp_of_cst(d.m, name))
427
+ case CombineCST():
428
+ return Combine(d=_decomp_of_cst(d.m, name))
429
+ case EnumerateCST():
430
+ return Enumerate(
431
+ d_f=_decomp_of_cst(d.m, name),
432
+ ds=[_decomp_of_cst(r.m, r.identifier) for r in d.ds],
433
+ style=EnumerationStyle[d.style or 'Additive'],
434
+ )
416
435
  case _:
417
436
  assert_never(d)
418
437
 
@@ -175,7 +175,7 @@ ERROR_KIND_DESCRIPTIONS: dict[ErrorKind, str] = {
175
175
  class ErrorMessage(BaseModel):
176
176
  msg: str
177
177
  locs: list[Location] = Field(
178
- default_factory=list, description='Locations for this message'
178
+ default_factory=list[Location], description='Locations for this message'
179
179
  )
180
180
  backtrace: str | None = Field(default=None, description='Captured backtrace')
181
181
 
@@ -186,6 +186,6 @@ class Error(BaseModel):
186
186
  )
187
187
  kind: str = Field(description='A string description of the kind of error')
188
188
  stack: list[ErrorMessage] = Field(
189
- default_factory=list, description='Context for the error'
189
+ default_factory=list[ErrorMessage], description='Context for the error'
190
190
  )
191
191
  process: str | None = Field(default=None)
@@ -55,7 +55,7 @@ class DecomposeResProto(BaseModel):
55
55
  artifact: Artifact | None = Field(default=None, exclude_if=lambda v: v is None)
56
56
  err: Empty | None = Field(default=None, exclude_if=lambda v: v is None)
57
57
  # oneof_res
58
- errors: list[Error] = Field(default_factory=list)
58
+ errors: list[Error] = Field(default_factory=list[Error])
59
59
  task: Task | None = Field(default=None)
60
60
 
61
61
  @model_validator(mode='after')
@@ -157,21 +157,21 @@ class EvalOutput(BaseModel):
157
157
  value_as_ocaml: str | None = Field(
158
158
  default=None, description='result as a OCaml value, if any'
159
159
  )
160
- errors: list[Error] = Field(default_factory=list)
160
+ errors: list[Error] = Field(default_factory=list[Error])
161
161
 
162
162
 
163
163
  class EvalRes(BaseModel):
164
164
  success: bool = Field()
165
165
  messages: list[str] = Field(default_factory=list, description='"normal" messages')
166
- errors: list[Error] = Field(default_factory=list, description='akin to stderr')
166
+ errors: list[Error] = Field(default_factory=list[Error], description='akin to stderr')
167
167
 
168
168
  # All tasks started during eval
169
169
  tasks: list[Task] = Field(
170
- default_factory=list, description='all tasks started during eval'
170
+ default_factory=list[Task], description='all tasks started during eval'
171
171
  )
172
- po_results: list[PO_Res] = Field(default_factory=list)
173
- eval_results: list[EvalOutput] = Field(default_factory=list)
174
- decomp_results: list[DecomposeRes] = Field(default_factory=list)
172
+ po_results: list[PO_Res] = Field(default_factory=lambda: list[PO_Res]())
173
+ eval_results: list[EvalOutput] = Field(default_factory=list[EvalOutput])
174
+ decomp_results: list[DecomposeRes] = Field(default_factory=list[DecomposeRes])
175
175
 
176
176
  def __repr__(self) -> str:
177
177
  return pformat(self, indent=2)
@@ -304,7 +304,7 @@ class PO_Res(BaseModel):
304
304
  test_ok: Test_ok | None = Field(default=None, exclude_if=lambda v: v is None)
305
305
  # /oneof_res
306
306
 
307
- errors: list[Error] = Field(default_factory=list)
307
+ errors: list[Error] = Field(default_factory=list[Error])
308
308
  task: Task | None = Field(default=None, description='the ID of the task')
309
309
  origin: Origin | None = Field(
310
310
  default=None, description='where did the task originate?'
@@ -363,7 +363,7 @@ class VerifyRes(BaseModel):
363
363
  )
364
364
  # /oneof res
365
365
 
366
- errors: list[Error] = Field(default_factory=list)
366
+ errors: list[Error] = Field(default_factory=list[Error])
367
367
  task: Task | None = Field(default=None, description='the ID of the task')
368
368
 
369
369
  @property
@@ -428,7 +428,7 @@ class TestRes(BaseModel):
428
428
  default=None, exclude_if=lambda v: v is None
429
429
  )
430
430
  # /oneof res
431
- errors: list[Error] = Field(default_factory=list)
431
+ errors: list[Error] = Field(default_factory=list[Error])
432
432
  task: Task | None = Field(default=None, description='the ID of the task')
433
433
 
434
434
  @property
@@ -467,7 +467,7 @@ class InstanceRes(BaseModel):
467
467
  sat: Sat | None = Field(default=None, exclude_if=lambda v: v is None)
468
468
  # /oneof res
469
469
 
470
- errors: list[Error] = Field(default_factory=list)
470
+ errors: list[Error] = Field(default_factory=list[Error])
471
471
  task: Task | None = Field(default=None, description='the ID of the task')
472
472
 
473
473
  @property
@@ -518,7 +518,7 @@ class TypecheckReq(BaseModel):
518
518
  class TypecheckResProto(BaseModel):
519
519
  success: bool
520
520
  types: str = Field(description='JSON string of inferred types')
521
- errors: list[Error] = Field(default_factory=list)
521
+ errors: list[Error] = Field(default_factory=list[Error])
522
522
 
523
523
 
524
524
  class InferredType(BaseModel):
@@ -11,9 +11,11 @@ On different "stat":
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import warnings
14
15
  from collections.abc import Callable, Sequence
15
16
  from dataclasses import fields, is_dataclass
16
17
  from functools import reduce
18
+ from pathlib import Path
17
19
  from types import SimpleNamespace
18
20
  from typing import Annotated, Any, NamedTuple, Protocol, Self, cast
19
21
 
@@ -40,6 +42,7 @@ from ._region import (
40
42
  __all__ = (
41
43
  'EnrichedDecomposeRes',
42
44
  'ForTesting',
45
+ 'OverlappingRegionsWarning',
43
46
  'Region',
44
47
  'RegionGroup',
45
48
  'RegionGroupView',
@@ -328,6 +331,14 @@ def group_regions(
328
331
  """
329
332
  Group regions hierarchically based on constraints.
330
333
 
334
+ Emits one `OverlappingRegionsWarning` if any two regions overlap visibly in
335
+ their constraints (see `_warn_if_overlapping`). Regions with the same
336
+ constraint set are merged into one leaf with `weight` = number of copies,
337
+ keeping the first copy's model; every other region keeps its own leaf.
338
+
339
+ Raises:
340
+ ValueError: if regions with the same constraint set differ in invariant.
341
+
331
342
  Args:
332
343
  eq_term: constraint equality. Defaults to `eq_term_with_pp`, memoized
333
344
  for the duration of this call.
@@ -336,9 +347,135 @@ def group_regions(
336
347
  pp = _mk_memo_term_to_string()
337
348
  if eq_term is None:
338
349
  eq_term = lambda l, r: pp(l) == pp(r)
350
+
351
+ _warn_if_overlapping(regions, pp)
352
+
339
353
  return _loop_group_regions([], [], regions, eq_term, pp)
340
354
 
341
355
 
356
+ # Overlapping region handling
357
+ # ====================
358
+ # rare case, should only happen with `enumerate_all ~style:Additive`
359
+
360
+
361
+ class _TextualOverlaps(NamedTuple):
362
+ identical: list[tuple[int, int]]
363
+ """`(i, j)`: region `j` has the same constraint set as region `i`, the first
364
+ region with that set."""
365
+ contained: list[tuple[int, int]]
366
+ """`(i, j)`: region `i`'s constraints, ignoring `true`, are a subset of region
367
+ `j`'s, so region `i` contains region `j`. One pair per pair of distinct sets
368
+ (e.g. `['x > 0']` and `['true', 'x > 0']` are one pair)."""
369
+
370
+
371
+ def _textual_overlaps(constraints: Sequence[Sequence[str]]) -> _TextualOverlaps:
372
+ """
373
+ Find regions whose constraint sets are equal or nested.
374
+
375
+ Constraints are compared as printed strings. Identical sets are the copies
376
+ that grouping merges; for containment, `true` counts as no constraint. This
377
+ finds the overlap visible from the constraints alone; regions like `x > 0`
378
+ and `x > 1` also overlap but are not found.
379
+ """
380
+ by_set: dict[frozenset[str], list[int]] = {}
381
+ for i, cs in enumerate(constraints):
382
+ by_set.setdefault(frozenset(cs), []).append(i)
383
+
384
+ identical = [(idxs[0], j) for idxs in by_set.values() for j in idxs[1:]]
385
+
386
+ # (first region, set without `true`) per distinct set, smallest first
387
+ distinct = sorted(
388
+ ((idxs[0], s - {'true'}) for s, idxs in by_set.items()),
389
+ key=lambda x: len(x[1]),
390
+ )
391
+ contained = [
392
+ (i, j)
393
+ for k, (i, small) in enumerate(distinct)
394
+ for j, big in distinct[k + 1 :]
395
+ if small <= big
396
+ ]
397
+ return _TextualOverlaps(identical=identical, contained=contained)
398
+
399
+
400
+ class OverlappingRegionsWarning(UserWarning):
401
+ """The decomposition returned regions that overlap (see `group_regions`)."""
402
+
403
+
404
+ _PACKAGE_DIR = str(Path(__file__).parent.parent)
405
+ """Warnings are attributed to the first caller outside this package."""
406
+
407
+
408
+ def _warn_if_overlapping(
409
+ regions: Sequence[Region], show_term: Callable[[xtype.Mir_Term_term], str]
410
+ ) -> None:
411
+ """Emit one `OverlappingRegionsWarning` summarizing `_textual_overlaps`."""
412
+ constraints = [[show_term(c) for c in r.constraints] for r in regions]
413
+ overlaps = _textual_overlaps(constraints)
414
+ if not overlaps.identical and not overlaps.contained:
415
+ return
416
+
417
+ parts: list[str] = []
418
+ if overlaps.identical:
419
+ i, _ = overlaps.identical[0]
420
+ parts.append(
421
+ f'{len(overlaps.identical)} region(s) repeat the constraints of'
422
+ f' another region and are merged into it, e.g. {constraints[i]}'
423
+ )
424
+ other_model = [
425
+ (i, j)
426
+ for i, j in overlaps.identical
427
+ if regions[i].non_group_stat().model != regions[j].non_group_stat().model
428
+ ]
429
+ if other_model:
430
+ i, j = other_model[0]
431
+ parts.append(
432
+ f'{len(other_model)} of them have a different model than the region'
433
+ f' they are merged into, whose model is kept, e.g. for {constraints[i]}:'
434
+ f' {regions[i].non_group_stat().model!r}, not'
435
+ f' {regions[j].non_group_stat().model!r}'
436
+ )
437
+ if overlaps.contained:
438
+ i, j = overlaps.contained[0]
439
+ parts.append(
440
+ f'{len(overlaps.contained)} pair(s) where one region contains another'
441
+ f' (its constraints are a subset of the other one), e.g. {constraints[i]}'
442
+ f' contains {constraints[j]}; both are kept'
443
+ )
444
+ warnings.warn(
445
+ 'the decomposition returned overlapping regions: ' + '; '.join(parts) + '.',
446
+ OverlappingRegionsWarning,
447
+ skip_file_prefixes=(_PACKAGE_DIR,),
448
+ )
449
+
450
+
451
+ def _merge_copies(
452
+ copies: Sequence[Region],
453
+ constraint_path: list[xtype.Mir_Term_term],
454
+ show_term: Callable[[xtype.Mir_Term_term], str],
455
+ ) -> Region:
456
+ """
457
+ The one region that `copies` (regions with the same constraint set) stand for.
458
+
459
+ The first copy is kept, with its model. Copies may differ in model: each is
460
+ only one witness of the region (`group_regions` warns about it).
461
+
462
+ Raises:
463
+ ValueError: if the copies differ in invariant, which ImandraX should
464
+ never return for one constraint set.
465
+
466
+ """
467
+ invariant = copies[0].non_group_stat().invariant
468
+ for r in copies[1:]:
469
+ other = r.non_group_stat().invariant
470
+ if other != invariant:
471
+ raise ValueError(
472
+ 'regions with the same constraints'
473
+ f' {[show_term(c) for c in constraint_path]} have different'
474
+ f' invariants: {invariant!r} and {other!r}'
475
+ )
476
+ return copies[0]
477
+
478
+
342
479
  # Tree rendering
343
480
  # ====================
344
481
 
@@ -462,7 +599,15 @@ def _loop_group_regions(
462
599
  when stored in `RegionGroup.label_path`.
463
600
 
464
601
  Postconditions:
465
- - Every input region appears in exactly one output `RegionGroup` (partition).
602
+ - Every input region is in exactly one leaf. Regions with the same constraint
603
+ set (copies) share one leaf, whose `weight` is the number of copies; a
604
+ node's `weight` is the sum of its leaves' weights. (`group_regions` warns
605
+ about copies up front, and raises if they differ in invariant.)
606
+ - If the input regions are disjoint, each node's children partition it (the
607
+ inputs its regions cover). The converse does not hold: merged copies and
608
+ overlap between top-level groups leave no overlapping siblings.
609
+ A region whose constraint set is a strict subset of other regions' is
610
+ kept as a sibling leaf of the regions it contains.
466
611
  - `RegionGroup.constraints` is the full accumulated constraint path from root
467
612
  to that node (root-first). `constraints[-1]` is the constraint introduced
468
613
  at that node's own level (its "own constraint").
@@ -603,7 +748,33 @@ def _loop_group_regions(
603
748
  idx_path=idx_path,
604
749
  constraint_path=constraint_path,
605
750
  )
606
- return reduce(loop, constraints_by_most_frequent, init).groups
751
+ acc = reduce(loop, constraints_by_most_frequent, init)
752
+
753
+ # ::: ai-generated
754
+ # Leftover regions: they carry no constraint outside `constraint_path`, and every
755
+ # region at this level carries all of it, so each leftover's constraint set is
756
+ # exactly `constraint_path`. A single leftover is alone at this level (the
757
+ # caller attaches it to its own group), or it contains the regions grouped
758
+ # above as siblings. Several leftovers are copies of one region, which
759
+ # `group_regions` has already warned about: merge them into one leaf whose
760
+ # weight counts the copies.
761
+ if len(regions) > 1 and acc.regions:
762
+ region = _merge_copies(acc.regions, constraint_path, show_term)
763
+ if acc.groups:
764
+ label_path = [*idx_path, len(acc.groups) + 1]
765
+ else:
766
+ # The only node at this level: the caller promotes it into its own place.
767
+ label_path = idx_path or [1]
768
+ leftover_leaf = RegionGroup(
769
+ constraints=[show_term(c) for c in constraint_path],
770
+ region=region,
771
+ children=[],
772
+ label_path=label_path,
773
+ weight=len(acc.regions),
774
+ )
775
+ return [*acc.groups, leftover_leaf]
776
+ # :::
777
+ return acc.groups
607
778
 
608
779
 
609
780
  # For test