expressir 2.5.1__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.
expressir/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """expressir — Python runtime for the EXPRESS/Part-21 core.
2
+
3
+ Drives the expressir-rs engine through its C ABI: schema parse,
4
+ remark attach, format, check, and the ISO 10303-21 population — the
5
+ same engine the ruby, rust, wasm, and TypeScript runtimes use.
6
+ """
7
+
8
+ from ._ffi import ExpressirError, ParseFailed, engine_version, load
9
+ from .api import (
10
+ attach_remarks,
11
+ check,
12
+ flatten_schema,
13
+ format,
14
+ parse_population,
15
+ parse_population_recovering,
16
+ parse_schema,
17
+ validate_population,
18
+ )
19
+
20
+ try:
21
+ from importlib.metadata import PackageNotFoundError, version
22
+
23
+ __version__ = version("expressir")
24
+ except PackageNotFoundError: # running from a source checkout
25
+ __version__ = "0.0.0.dev0"
26
+
27
+ __all__ = [
28
+ "ExpressirError",
29
+ "ParseFailed",
30
+ "attach_remarks",
31
+ "check",
32
+ "engine_version",
33
+ "flatten_schema",
34
+ "format",
35
+ "load",
36
+ "parse_population",
37
+ "parse_population_recovering",
38
+ "parse_schema",
39
+ "validate_population",
40
+ "__version__",
41
+ ]
expressir/_ffi.py ADDED
@@ -0,0 +1,135 @@
1
+ """ctypes binding for the expressir C ABI (libexpressir cdylib).
2
+
3
+ The C surface is expressir-rs's `expr_*` family (expressir#620): JSON
4
+ in, JSON out, NULL on failure with `expr_last_error()` holding the
5
+ message, and `expr_string_free` releasing every returned string.
6
+ Nothing here interprets wires — that is `expressir.api`'s job.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ctypes
12
+ import os
13
+ from pathlib import Path
14
+
15
+ _LIB_NAMES = (
16
+ "libexpressir.dylib",
17
+ "libexpressir.so",
18
+ "expressir.dll", # cargo emits no lib prefix on windows
19
+ "libexpressir.dll",
20
+ )
21
+
22
+
23
+ class ExpressirError(RuntimeError):
24
+ """The engine reported a hard error (loading, ABI, NULL input)."""
25
+
26
+
27
+ class ParseFailed(ExpressirError):
28
+ """The engine refused the input; `str()` carries the last error."""
29
+
30
+
31
+ def _candidate_paths() -> list[str]:
32
+ candidates: list[str] = []
33
+ env = os.environ.get("EXPRESSIR_CDYLIB")
34
+ if env:
35
+ candidates.append(env)
36
+ packaged = Path(__file__).resolve().parent / "lib"
37
+ for name in _LIB_NAMES:
38
+ candidates.append(str(packaged / name))
39
+ for name in _LIB_NAMES:
40
+ candidates.append(name) # system loader search
41
+ return candidates
42
+
43
+
44
+ _lib: ctypes.CDLL | None = None
45
+ _version: str | None = None
46
+
47
+
48
+ def load() -> ctypes.CDLL:
49
+ """dlopen the cdylib once and bind the entry points."""
50
+ global _lib, _version
51
+ if _lib is not None:
52
+ return _lib
53
+
54
+ errors: list[str] = []
55
+ lib: ctypes.CDLL | None = None
56
+ for candidate in _candidate_paths():
57
+ try:
58
+ lib = ctypes.CDLL(candidate)
59
+ break
60
+ except OSError as error:
61
+ errors.append(f"{candidate}: {error}")
62
+ if lib is None:
63
+ raise ExpressirError(
64
+ "libexpressir not found (build it with `cargo build --release` "
65
+ "in expressir-rs and point EXPRESSIR_CDYLIB at the dylib, or "
66
+ "install a wheel that vendors it). Tried:\n " + "\n ".join(errors)
67
+ )
68
+
69
+ c_char_p = ctypes.c_char_p
70
+ c_void_p = ctypes.c_void_p
71
+
72
+ lib.expr_version.argtypes = []
73
+ lib.expr_version.restype = c_char_p
74
+ lib.expr_last_error.argtypes = []
75
+ lib.expr_last_error.restype = c_char_p
76
+ lib.expr_string_free.argtypes = [c_void_p]
77
+ lib.expr_string_free.restype = None
78
+
79
+ for name, arity in (
80
+ ("expr_parse_schema", 1),
81
+ ("expr_attach_remarks", 3),
82
+ ("expr_format", 2),
83
+ ("expr_check", 2),
84
+ ("expr_parse_population", 1),
85
+ ("expr_validate_population", 2),
86
+ ("expr_concat_schema", 2),
87
+ ("expr_flatten_schema", 3),
88
+ ("expr_parse_population_recovering", 1),
89
+ ):
90
+ fn = getattr(lib, name)
91
+ fn.argtypes = [c_char_p] * arity
92
+ fn.restype = c_void_p
93
+
94
+ _lib = lib
95
+ _version = _borrow(lib.expr_version())
96
+ return lib
97
+
98
+
99
+ def _borrow(ptr: int | None) -> str:
100
+ """Copy a returned C string the engine still owns.
101
+
102
+ `expr_version` points into static memory and `expr_last_error`
103
+ into a thread-local slot — freeing those is undefined behavior.
104
+ """
105
+ if not ptr:
106
+ return ""
107
+ return ctypes.cast(ptr, ctypes.c_char_p).value.decode("utf-8")
108
+
109
+
110
+ def _take(ptr: int | None) -> str:
111
+ """Copy a returned C string and release it (the expr_* results)."""
112
+ if not ptr:
113
+ raise ExpressirError(_last_error() or "NULL with no error message")
114
+ try:
115
+ return _borrow(ptr)
116
+ finally:
117
+ load().expr_string_free(ptr)
118
+
119
+
120
+ def _last_error() -> str:
121
+ return _borrow(load().expr_last_error())
122
+
123
+
124
+ def call(fn, *args: str | None) -> str:
125
+ """Run one expr_* function; NULL means failure."""
126
+ encoded = [a.encode("utf-8") if isinstance(a, str) else a for a in args]
127
+ ptr = fn(*encoded)
128
+ if not ptr:
129
+ raise ParseFailed(_last_error() or f"{fn.__name__ if hasattr(fn, '__name__') else 'expr_*'} returned NULL")
130
+ return _take(ptr)
131
+
132
+
133
+ def engine_version() -> str:
134
+ load()
135
+ return _version or ""
expressir/api.py ADDED
@@ -0,0 +1,75 @@
1
+ """The expressir core surface, one function per C ABI entry point.
2
+
3
+ Every tier (rust, C, wasm, python) exposes the same six operations
4
+ over the model-hash wire JSON; this module is the python projection.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+
11
+ from ._ffi import call, engine_version, load
12
+
13
+
14
+ def parse_schema(source: str) -> dict:
15
+ """Parses an EXPRESS schema into the model-hash wire JSON."""
16
+ return json.loads(call(load().expr_parse_schema, source))
17
+
18
+
19
+ def attach_remarks(wire: dict | str, source: str, annotations: bool = False) -> dict:
20
+ """Attaches tagged + untagged remarks to a wire."""
21
+ wire_json = wire if isinstance(wire, str) else json.dumps(wire)
22
+ return json.loads(call(load().expr_attach_remarks, wire_json, source, "1" if annotations else "0"))
23
+
24
+
25
+ def format(wire: dict | str, no_remarks: bool = False) -> str:
26
+ """Formats a wire to EXPRESS text."""
27
+ wire_json = wire if isinstance(wire, str) else json.dumps(wire)
28
+ return call(load().expr_format, wire_json, "1" if no_remarks else "0")
29
+
30
+
31
+ def check(wire: dict | str, dialect: str | None = None) -> list:
32
+ """Runs the checker over a wire; returns the findings array."""
33
+ wire_json = wire if isinstance(wire, str) else json.dumps(wire)
34
+ return json.loads(call(load().expr_check, wire_json, dialect))
35
+
36
+
37
+ def parse_population(source: str) -> dict:
38
+ """Parses an ISO-10303-21 population into its structural inventory."""
39
+ return json.loads(call(load().expr_parse_population, source))
40
+
41
+
42
+ def validate_population(entities: list[str], source: str) -> dict:
43
+ """Validates a population's records against an entity inventory."""
44
+ return json.loads(call(load().expr_validate_population, json.dumps(list(entities)), source))
45
+
46
+
47
+ __all__ = [
48
+ "attach_remarks",
49
+ "check",
50
+ "engine_version",
51
+ "flatten_schema",
52
+ "format",
53
+ "parse_population",
54
+ "parse_population_recovering",
55
+ "parse_schema",
56
+ "validate_population",
57
+ ]
58
+
59
+
60
+ def flatten_schema(repository_wire: dict | str, root_id: str, longform_name: str) -> str:
61
+ """Runs the SHTOLO longform over a resolved repository wire (#636).
62
+
63
+ The full stage order returns the longform schema wire JSON.
64
+ """
65
+ wire_json = repository_wire if isinstance(repository_wire, str) else json.dumps(repository_wire)
66
+ return call(load().expr_flatten_schema, wire_json, root_id, longform_name)
67
+
68
+
69
+ def parse_population_recovering(source: str) -> dict:
70
+ """Parses an ISO-10303-21 population through the recovery envelope (#627).
71
+
72
+ The population inventory on well-formed input; the failure
73
+ forensics on malformed input.
74
+ """
75
+ return json.loads(call(load().expr_parse_population_recovering, source))
Binary file
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: expressir
3
+ Version: 2.5.1
4
+ Summary: Python runtime for Expressir: schema parse, remark attach, format, check, and the Part 21 population through the expressir-rs C ABI
5
+ License: MIT
6
+ Project-URL: Homepage, https://expressir.org
7
+ Project-URL: Repository, https://github.com/lutaml/expressir-python
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Software Development :: Compilers
10
+ Classifier: Topic :: Text Processing :: General
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+
14
+ # expressir-python
15
+
16
+ Python runtime for [Expressir](https://github.com/lutaml/expressir):
17
+ EXPRESS schema parse, remark attach, format, check, and the
18
+ ISO 10303-21 population — through the [expressir-rs](https://github.com/lutaml/expressir-rs)
19
+ C ABI, the same engine the ruby, rust, wasm, and TypeScript runtimes use.
20
+
21
+ ```python
22
+ import expressir
23
+
24
+ wire = expressir.parse_schema("SCHEMA demo; ENTITY e; a : STRING; END_ENTITY; END_SCHEMA;")
25
+ attached = expressir.attach_remarks(wire, source)
26
+ print(expressir.format(attached))
27
+
28
+ inventory = expressir.parse_population("ISO-10303-21; ...;")
29
+ verdict = expressir.validate_population(["E"], population_source)
30
+ ```
31
+
32
+ ## Development
33
+
34
+ ```sh
35
+ git clone --recurse-submodules https://github.com/lutaml/expressir-python
36
+ cd expressir-python
37
+ (cd expressir-rs && cargo build --release)
38
+ EXPRESSIR_CDYLIB=$PWD/expressir-rs/target/release/libexpressir_rs.dylib \
39
+ python3 -m pip install -e . pytest && python3 -m pytest tests -q
40
+ ```
41
+
42
+ ## Architecture
43
+
44
+ One core (`expressir-rs`), many tiers: rust (this ABI's home), C
45
+ (`expr_*` family), wasm (`expressir-ts`), ruby (`expressir`), and
46
+ python (here). Every tier exposes the same six operations over the
47
+ model-hash wire JSON. See [expressir.org](https://expressir.org).
@@ -0,0 +1,8 @@
1
+ expressir/__init__.py,sha256=kkSEyaxSIxfXr5MKkN_9Fbcea-7m7kJz531G-meNIyg,1006
2
+ expressir/_ffi.py,sha256=OFqjlKU0YHpjRlCYl2AJ5RtmTbhzGULTxJsA6LYGvuE,3925
3
+ expressir/api.py,sha256=yIfC3cqKC7mhnrhCEPNrPEGv1KxTY0Oyv63F4pVHFa0,2682
4
+ expressir/lib/libexpressir.dylib,sha256=J8Po1PXt1qZCMooItwhA1kkJ9RtrIe3aZ64EUkFYYgA,4540992
5
+ expressir-2.5.1.dist-info/METADATA,sha256=v0PMdJMRGRybEm1azGvE8YjHfYY6CI1dWwGQkBKpTCU,1777
6
+ expressir-2.5.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ expressir-2.5.1.dist-info/top_level.txt,sha256=a0OLO4BuJyHOTyyaVAgl3Gkt2rg0y2D8Bth3uJgWbkc,10
8
+ expressir-2.5.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ expressir