itf-py 0.4.1__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.

Potentially problematic release.


This version of itf-py might be problematic. Click here for more details.

itf_py-0.4.1/PKG-INFO ADDED
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: itf-py
3
+ Version: 0.4.1
4
+ Summary: Python library to parse and emit Apalache/Quint traces in ITF JSON
5
+ Keywords: itf,trace,parser,tlaplus,apalache,quint
6
+ Author: Igor Konnov
7
+ Author-email: igor@konnov.phd
8
+ Requires-Python: >=3.12,<4.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Dist: frozendict (>=2.4.6,<3.0.0)
14
+ Project-URL: Homepage, https://github.com/konnov/itf-py
15
+ Description-Content-Type: text/markdown
16
+
17
+ # ITF-py: Parser and Encoder for the ITF Trace Format
18
+
19
+ Python library to parse and emit Apalache ITF traces. Refer to [ADR015][] for
20
+ the format. ITF traces are emitted by [Apalache][] and [Quint][].
21
+
22
+ **Intentionally minimalistic.** We keep this library intentionally minimalistic.
23
+ You can use it in your projects without worrying about pulling dozens of
24
+ dependencies. The package depends on `frozendict`.
25
+
26
+ **Why?** It's much more convenient to manipulate with trace data in an
27
+ interactive prompt, similar to SQL.
28
+
29
+ See usage examples on the [itf-py][] page on Github.
30
+
31
+ **Alternatives.** If you need to deserialize/serialize ITF traces in Rust, check
32
+ [itf-rs][].
33
+
34
+ [ADR015]: https://apalache-mc.org/docs/adr/015adr-trace.html
35
+ [Apalache]: https://github.com/apalache-mc/apalache
36
+ [Quint]: https://github.com/informalsystems/quint
37
+ [itf-rs]: https://github.com/informalsystems/itf-rs
38
+ [itf-py]: https://github.com/konnov/itf-py
itf_py-0.4.1/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # ITF-py: Parser and Encoder for the ITF Trace Format
2
+
3
+ Python library to parse and emit Apalache ITF traces. Refer to [ADR015][] for
4
+ the format. ITF traces are emitted by [Apalache][] and [Quint][].
5
+
6
+ **Intentionally minimalistic.** We keep this library intentionally minimalistic.
7
+ You can use it in your projects without worrying about pulling dozens of
8
+ dependencies. The package depends on `frozendict`.
9
+
10
+ **Why?** It's much more convenient to manipulate with trace data in an
11
+ interactive prompt, similar to SQL.
12
+
13
+ See usage examples on the [itf-py][] page on Github.
14
+
15
+ **Alternatives.** If you need to deserialize/serialize ITF traces in Rust, check
16
+ [itf-rs][].
17
+
18
+ [ADR015]: https://apalache-mc.org/docs/adr/015adr-trace.html
19
+ [Apalache]: https://github.com/apalache-mc/apalache
20
+ [Quint]: https://github.com/informalsystems/quint
21
+ [itf-rs]: https://github.com/informalsystems/itf-rs
22
+ [itf-py]: https://github.com/konnov/itf-py
@@ -0,0 +1,86 @@
1
+ [tool.poetry]
2
+ name = "itf-py"
3
+ version = "0.4.1"
4
+ description = "Python library to parse and emit Apalache/Quint traces in ITF JSON"
5
+ homepage = "https://github.com/konnov/itf-py"
6
+ authors = ["Igor Konnov <igor@konnov.phd>"]
7
+ readme = "README.md"
8
+ keywords = ["itf", "trace", "parser", "tlaplus", "apalache", "quint"]
9
+ packages = [{include = "itf_py", from = "src"}]
10
+
11
+ [tool.poetry.dependencies]
12
+ python = "^3.12"
13
+ frozendict = "^2.4.6"
14
+
15
+ [tool.poetry.group.dev.dependencies]
16
+ pytest = "^8.0.0"
17
+ pytest-cov = "^5.0.0"
18
+ black = "^24.0.0"
19
+ isort = "^5.13.0"
20
+ flake8 = "^7.0.0"
21
+ mypy = "^1.8.0"
22
+ markdown-pytest = "^0.3.2"
23
+
24
+
25
+ [build-system]
26
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
27
+ build-backend = "poetry.core.masonry.api"
28
+
29
+ [tool.black]
30
+ line-length = 88
31
+ target-version = ['py312']
32
+ include = '\.pyi?$'
33
+ extend-exclude = '''
34
+ /(
35
+ # directories
36
+ \.eggs
37
+ | \.git
38
+ | \.hg
39
+ | \.mypy_cache
40
+ | \.tox
41
+ | \.venv
42
+ | build
43
+ | dist
44
+ )/
45
+ '''
46
+
47
+ [tool.isort]
48
+ profile = "black"
49
+ multi_line_output = 3
50
+ line_length = 88
51
+ known_first_party = ["itf_py"]
52
+
53
+ [tool.mypy]
54
+ python_version = "3.12"
55
+ warn_return_any = true
56
+ warn_unused_configs = true
57
+ disallow_untyped_defs = true
58
+ disallow_incomplete_defs = true
59
+ check_untyped_defs = true
60
+ disallow_untyped_decorators = true
61
+ no_implicit_optional = true
62
+ warn_redundant_casts = true
63
+ warn_unused_ignores = true
64
+ warn_no_return = true
65
+ warn_unreachable = true
66
+ strict_equality = true
67
+
68
+ [tool.pytest.ini_options]
69
+ testpaths = ["tests"]
70
+ python_files = ["test_*.py"]
71
+ python_classes = ["Test*"]
72
+ python_functions = ["test_*"]
73
+ addopts = "--strict-markers --strict-config --verbose"
74
+
75
+ [tool.flake8]
76
+ max-line-length = 88
77
+ extend-ignore = ["E203", "W503"]
78
+ exclude = [
79
+ ".git",
80
+ "__pycache__",
81
+ ".venv",
82
+ ".eggs",
83
+ "*.egg",
84
+ "dist",
85
+ "build",
86
+ ]
@@ -0,0 +1,26 @@
1
+ """
2
+ Python library to parse and emit Apalache ITF traces.
3
+ """
4
+
5
+ from .itf import (
6
+ State,
7
+ Trace,
8
+ state_from_json,
9
+ state_to_json,
10
+ trace_from_json,
11
+ trace_to_json,
12
+ value_from_json,
13
+ value_to_json,
14
+ )
15
+
16
+ __version__ = "0.2.1"
17
+ __all__ = [
18
+ "State",
19
+ "Trace",
20
+ "value_to_json",
21
+ "value_from_json",
22
+ "state_to_json",
23
+ "state_from_json",
24
+ "trace_to_json",
25
+ "trace_from_json",
26
+ ]
@@ -0,0 +1,201 @@
1
+ from collections import namedtuple
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict, Iterable, List, NoReturn, Optional, SupportsIndex
4
+
5
+ from frozendict import frozendict
6
+
7
+
8
+ @dataclass
9
+ class State:
10
+ """A single state in an ITF trace as a Python object."""
11
+
12
+ meta: Dict[str, Any]
13
+ values: Dict[str, Any]
14
+
15
+
16
+ @dataclass
17
+ class Trace:
18
+ """An ITF trace as a Python object."""
19
+
20
+ meta: Dict[str, Any]
21
+ params: List[str]
22
+ vars: List[str]
23
+ states: List[State]
24
+ loop: Optional[int]
25
+
26
+
27
+ class ImmutableList(list):
28
+ """An immutable wrapper around list that supports hashing,
29
+ yet displays as a list."""
30
+
31
+ # frozenlist.FrozenList is what we want, but it does not display
32
+ # nicely in pretty-printing.
33
+
34
+ def __init__(self, items: Iterable[Any]):
35
+ super().__init__(items)
36
+
37
+ def __hash__(self) -> int: # type: ignore
38
+ return hash(tuple(self))
39
+
40
+ def _forbid_modification(self) -> NoReturn:
41
+ """Forbid modification of the list."""
42
+ raise TypeError("This list is immutable and cannot be modified.")
43
+
44
+ def __setitem__(self, _key: Any, _value: Any) -> NoReturn:
45
+ self._forbid_modification()
46
+
47
+ def __delitem__(self, _key: Any) -> NoReturn:
48
+ self._forbid_modification()
49
+
50
+ def append(self, _value: Any) -> NoReturn:
51
+ self._forbid_modification()
52
+
53
+ def extend(self, _values: Iterable[Any]) -> NoReturn:
54
+ self._forbid_modification()
55
+
56
+ def insert(self, _index: SupportsIndex, _value: Any) -> None:
57
+ self._forbid_modification()
58
+
59
+ def pop(self, _index: SupportsIndex = -1) -> NoReturn:
60
+ self._forbid_modification()
61
+
62
+ def remove(self, _value: Any) -> NoReturn:
63
+ self._forbid_modification()
64
+
65
+ def clear(self) -> NoReturn:
66
+ self._forbid_modification()
67
+
68
+ def reverse(self) -> NoReturn:
69
+ self._forbid_modification()
70
+
71
+
72
+ class ImmutableDict(frozendict):
73
+ """A wrapper around frozendict that displays dictionaries as
74
+ `{k1: v_1, ..., k_n: v_n}`."""
75
+
76
+ def __new__(cls, items: Dict[str, Any]) -> Any:
77
+ return super().__new__(cls, items)
78
+
79
+
80
+ ImmutableDict.__str__ = ( # type: ignore
81
+ dict.__str__
82
+ ) # use the default dict representation in pretty-printing
83
+
84
+ ImmutableDict.__repr__ = ( # type: ignore
85
+ dict.__repr__
86
+ ) # use the default dict representation in pretty-printing
87
+
88
+
89
+ @dataclass
90
+ class ITFUnserializable:
91
+ """A placeholder for unserializable values."""
92
+
93
+ value: str
94
+
95
+
96
+ def value_from_json(val: Any) -> Any:
97
+ """Deserialize a Python value from JSON"""
98
+ if isinstance(val, dict):
99
+ if "#bigint" in val:
100
+ return int(val["#bigint"])
101
+ elif "#tup" in val:
102
+ return tuple(value_from_json(v) for v in val["#tup"])
103
+ elif "#set" in val:
104
+ return frozenset(value_from_json(v) for v in val["#set"])
105
+ elif "#map" in val:
106
+ d = {value_from_json(k): value_from_json(v) for (k, v) in val["#map"]}
107
+ return ImmutableDict(d)
108
+ elif "#unserializable" in val:
109
+ return ITFUnserializable(value=val["#unserializable"])
110
+ else:
111
+ ks = val.keys()
112
+ if len(ks) == 2 and "tag" in ks and "value" in ks:
113
+ # This is a tagged union, e.g., {"tag": "Banana", "value": {...}}.
114
+ # Produce Banana(...)
115
+ value_field = val["value"]
116
+ if isinstance(value_field, dict):
117
+ # The value is a record: {"tag": "Banana", "value": {"length": 5}}
118
+ union_type_record = namedtuple( # type: ignore[misc]
119
+ val["tag"], value_field.keys()
120
+ )
121
+ return union_type_record(
122
+ **{k: value_from_json(v) for k, v in value_field.items()}
123
+ )
124
+ else:
125
+ # The value is a scalar: {"tag": "Banana", "value": "u_OF_UNIT"}
126
+ union_type_scalar = namedtuple( # type: ignore[misc]
127
+ val["tag"], ["value"]
128
+ )
129
+ return union_type_scalar( # type: ignore[call-arg]
130
+ value=value_from_json(value_field)
131
+ )
132
+ else:
133
+ # This is a general record, e.g., {"field1": ..., "field2": ...}.
134
+ rec_type = namedtuple("Rec", val.keys()) # type: ignore[misc]
135
+ return rec_type(**{k: value_from_json(v) for k, v in val.items()})
136
+ elif isinstance(val, list):
137
+ return ImmutableList([value_from_json(v) for v in val])
138
+ else:
139
+ return val # int, str, bool
140
+
141
+
142
+ def value_to_json(val: Any) -> Any:
143
+ """Serialize a Python value into JSON"""
144
+ if isinstance(val, bool):
145
+ return val
146
+ elif isinstance(val, int):
147
+ return {"#bigint": str(val)}
148
+ elif isinstance(val, tuple) and not hasattr(val, "_fields"):
149
+ return {"#tup": [value_to_json(v) for v in val]}
150
+ elif isinstance(val, frozenset):
151
+ return {"#set": [value_to_json(v) for v in val]}
152
+ elif isinstance(val, dict):
153
+ return {"#map": [[value_to_json(k), value_to_json(v)] for k, v in val.items()]}
154
+ elif isinstance(val, list):
155
+ return [value_to_json(v) for v in val]
156
+ elif hasattr(val, "__dict__"):
157
+ # An object-like structure, e.g., a record, or a union.
158
+ # Note that we cannot distinguish between a record and a tagged union here.
159
+ return {k: value_to_json(v) for k, v in val.__dict__.items()}
160
+ elif isinstance(val, tuple) and hasattr(val, "_fields"):
161
+ # namedtuple (could be a record or tagged union, but we treat them the same)
162
+ return {k: value_to_json(v) for k, v in val._asdict().items()} # type: ignore
163
+ elif isinstance(val, str):
164
+ return val
165
+ else:
166
+ return ITFUnserializable(value=str(val))
167
+
168
+
169
+ def state_from_json(raw_state: Dict[str, Any]) -> State:
170
+ """Deserialize a single State from JSON"""
171
+ state_meta = raw_state["#meta"] if "#meta" in raw_state else {}
172
+ values = {k: value_from_json(v) for k, v in raw_state.items() if k != "#meta"}
173
+ return State(meta=state_meta, values=values)
174
+
175
+
176
+ def state_to_json(state: State) -> Dict[str, Any]:
177
+ """Serialize a single State to JSON"""
178
+ result = {"#meta": state.meta}
179
+ for k, v in state.values.items():
180
+ result[k] = value_to_json(v)
181
+ return result
182
+
183
+
184
+ def trace_from_json(data: Dict[str, Any]) -> Trace:
185
+ """Deserialize a Trace from JSON"""
186
+ meta = data["#meta"] if "#meta" in data else {}
187
+ params = data.get("params", [])
188
+ vars_ = data["vars"]
189
+ loop = data.get("loop", None)
190
+ states = [state_from_json(s) for s in data["states"]]
191
+ return Trace(meta=meta, params=params, vars=vars_, states=states, loop=loop)
192
+
193
+
194
+ def trace_to_json(trace: Trace) -> Dict[str, Any]:
195
+ """Serialize a Trace to JSON"""
196
+ result: Dict[str, Any] = {"#meta": trace.meta}
197
+ result["params"] = trace.params
198
+ result["vars"] = trace.vars
199
+ result["loop"] = trace.loop
200
+ result["states"] = [state_to_json(s) for s in trace.states]
201
+ return result