expressir 2.5.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.
@@ -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,34 @@
1
+ # expressir-python
2
+
3
+ Python runtime for [Expressir](https://github.com/lutaml/expressir):
4
+ EXPRESS schema parse, remark attach, format, check, and the
5
+ ISO 10303-21 population — through the [expressir-rs](https://github.com/lutaml/expressir-rs)
6
+ C ABI, the same engine the ruby, rust, wasm, and TypeScript runtimes use.
7
+
8
+ ```python
9
+ import expressir
10
+
11
+ wire = expressir.parse_schema("SCHEMA demo; ENTITY e; a : STRING; END_ENTITY; END_SCHEMA;")
12
+ attached = expressir.attach_remarks(wire, source)
13
+ print(expressir.format(attached))
14
+
15
+ inventory = expressir.parse_population("ISO-10303-21; ...;")
16
+ verdict = expressir.validate_population(["E"], population_source)
17
+ ```
18
+
19
+ ## Development
20
+
21
+ ```sh
22
+ git clone --recurse-submodules https://github.com/lutaml/expressir-python
23
+ cd expressir-python
24
+ (cd expressir-rs && cargo build --release)
25
+ EXPRESSIR_CDYLIB=$PWD/expressir-rs/target/release/libexpressir_rs.dylib \
26
+ python3 -m pip install -e . pytest && python3 -m pytest tests -q
27
+ ```
28
+
29
+ ## Architecture
30
+
31
+ One core (`expressir-rs`), many tiers: rust (this ABI's home), C
32
+ (`expr_*` family), wasm (`expressir-ts`), ruby (`expressir`), and
33
+ python (here). Every tier exposes the same six operations over the
34
+ model-hash wire JSON. See [expressir.org](https://expressir.org).
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "expressir"
7
+ version = "2.5.1"
8
+ description = "Python runtime for Expressir: schema parse, remark attach, format, check, and the Part 21 population through the expressir-rs C ABI"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.9"
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "Topic :: Software Development :: Compilers",
15
+ "Topic :: Text Processing :: General",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://expressir.org"
20
+ Repository = "https://github.com/lutaml/expressir-python"
21
+
22
+ [tool.setuptools.packages.find]
23
+ where = ["src"]
24
+
25
+ [tool.setuptools.package-data]
26
+ expressir = ["lib/*.so", "lib/*.dylib", "lib/*.dll", "assets/*.json"]
27
+
28
+ [tool.pytest.ini_options]
29
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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 ""
@@ -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))
@@ -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,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/expressir/__init__.py
4
+ src/expressir/_ffi.py
5
+ src/expressir/api.py
6
+ src/expressir.egg-info/PKG-INFO
7
+ src/expressir.egg-info/SOURCES.txt
8
+ src/expressir.egg-info/dependency_links.txt
9
+ src/expressir.egg-info/top_level.txt
10
+ src/expressir/lib/libexpressir.dylib
11
+ tests/test_binding.py
@@ -0,0 +1 @@
1
+ expressir
@@ -0,0 +1,125 @@
1
+ """The C ABI binding tests: load, version, and the six surfaces.
2
+
3
+ The cdylib is built by CI from the expressir-rs submodule; locally
4
+ point EXPRESSIR_CDYLIB at it. Tests skip with the load error message
5
+ when the engine is absent.
6
+ """
7
+
8
+ import json
9
+ import pathlib
10
+
11
+ import pytest
12
+
13
+ import expressir
14
+ from expressir._ffi import ExpressirError, load
15
+
16
+ SCHEMA = (
17
+ "SCHEMA demo;\n"
18
+ "ENTITY e;\n"
19
+ " a : STRING;\n"
20
+ " (*\"demo.e\" the note *)\n"
21
+ "END_ENTITY;\n"
22
+ "END_SCHEMA;\n"
23
+ )
24
+ POPULATION = (
25
+ "ISO-10303-21;\nHEADER;\nFILE_NAME('x');\nENDSEC;\n"
26
+ "DATA;\n#1=E('v');\nENDSEC;\nEND-ISO-10303-21;\n"
27
+ )
28
+
29
+
30
+ def _cdylib_available() -> bool:
31
+ try:
32
+ load()
33
+ return True
34
+ except ExpressirError:
35
+ return False
36
+
37
+
38
+ pytestmark = pytest.mark.skipif(
39
+ not _cdylib_available(),
40
+ reason="libexpressir_rs not built (cargo build --release in expressir-rs; EXPRESSIR_CDYLIB)",
41
+ )
42
+
43
+
44
+ def test_engine_version_is_reported():
45
+ assert expressir.engine_version()
46
+
47
+
48
+ def test_parse_schema_returns_the_model_wire():
49
+ wire = expressir.parse_schema(SCHEMA)
50
+ schema = wire["schemas"][0]
51
+ assert schema["id"] == "demo"
52
+ assert schema["entities"][0]["id"] == "e"
53
+
54
+
55
+ def test_attach_format_round_trip():
56
+ wire = expressir.parse_schema(SCHEMA)
57
+ attached = expressir.attach_remarks(wire, SCHEMA)
58
+ text = expressir.format(attached)
59
+ assert "SCHEMA demo;" in text
60
+ stripped = expressir.format(attached, no_remarks=True)
61
+ assert "END_ENTITY;" in stripped
62
+
63
+
64
+ def test_check_returns_a_findings_array():
65
+ wire = expressir.parse_schema(SCHEMA)
66
+ findings = expressir.check(wire)
67
+ assert isinstance(findings, list)
68
+
69
+
70
+ def test_parse_population_inventory():
71
+ inventory = expressir.parse_population(POPULATION)
72
+ keywords = {record["keyword"] for record in inventory["records"]}
73
+ assert keywords == {"E"}
74
+
75
+
76
+ def test_validate_population_verdict():
77
+ verdict = expressir.validate_population(["E"], POPULATION)
78
+ assert verdict["valid"] is True
79
+ bad = expressir.validate_population(["NotE"], POPULATION)
80
+ assert bad["valid"] is False
81
+
82
+
83
+ def test_parse_failure_raises_with_the_last_error():
84
+ with pytest.raises(ExpressirError):
85
+ expressir.parse_schema("not express at all")
86
+
87
+
88
+ def test_flatten_schema_runs_the_longform():
89
+ repo_wire = {
90
+ "schemas": [
91
+ {
92
+ "id": "mim",
93
+ "file": "/x/mim.exp",
94
+ "interfaces": [
95
+ {
96
+ "_class": "Expressir::Model::Declarations::Interface",
97
+ "kind": "USE",
98
+ "schema": {
99
+ "_class": "Expressir::Model::References::SimpleReference",
100
+ "id": "arm",
101
+ },
102
+ }
103
+ ],
104
+ },
105
+ {"id": "arm", "file": "/x/arm.exp", "interfaces": []},
106
+ ]
107
+ }
108
+ longform = expressir.flatten_schema(repo_wire, "mim", "mim_long")
109
+ parsed = json.loads(longform)
110
+ assert parsed["id"] == "mim_long"
111
+
112
+
113
+ def test_parse_population_recovering_envelope():
114
+ ok = expressir.parse_population_recovering(POPULATION)
115
+ assert ok["ok"] is True
116
+ assert ok["population"]["records"][0]["keyword"] == "E"
117
+
118
+ junked = POPULATION.replace(
119
+ "ENDSEC;\nEND-ISO-10303-21;",
120
+ "\n#9999=JUNK(%%%);\nENDSEC;\nEND-ISO-10303-21;",
121
+ )
122
+ bad = expressir.parse_population_recovering(junked)
123
+ assert bad["ok"] is False
124
+ assert bad["error"]["offset"] >= 0
125
+ assert bad["consumed_upto"] == bad["error"]["offset"]