cxlib 0.18.0rc1__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,441 @@
1
+ Metadata-Version: 2.1
2
+ Name: cxlib
3
+ Version: 0.18.0rc1
4
+ Summary: CX format library — parse, stream, and convert CX/XML/JSON/YAML/TOML
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Provides-Extra: arrow
8
+ Requires-Dist: pyarrow>=14; extra == "arrow"
9
+ Description-Content-Type: text/markdown
10
+
11
+ # CX — Python
12
+
13
+ Python binding for the CX format library. Parses, streams, queries, and
14
+ transforms CX documents; converts between CX, XML, JSON, YAML, and TOML
15
+ via `libcx`.
16
+
17
+
18
+ ## Requirements
19
+
20
+ - Python 3.10 or newer
21
+ - `libcx` built from source (one command — see Install)
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ # 1. Clone the repo and build libcx (requires the V compiler — ships with devbox)
27
+ git clone https://github.com/cx-lang/cx
28
+ cd cx
29
+ make build-vcx # produces vcx/target/libcx.dylib (or .so on Linux)
30
+
31
+ # 2. Point Python at the binding
32
+ export PYTHONPATH="$PWD/lang/python:$PYTHONPATH"
33
+ ```
34
+
35
+ The binding discovers `libcx` automatically relative to its own file. No
36
+ extra environment variables are needed as long as you run from the repo root
37
+ or have `make install` installed the library to `/usr/local/lib`.
38
+
39
+ ## Quick Start
40
+
41
+ ### Parse and read
42
+
43
+ ```python
44
+ import cxlib
45
+
46
+ src = """[config version='1.0'
47
+ [server host=localhost port=8080]
48
+ [database host=db.local port=5432]
49
+ ]"""
50
+
51
+ doc = cxlib.parse(src)
52
+
53
+ # Navigate by path
54
+ server = doc.at('config/server')
55
+ print(server.attr('host')) # localhost
56
+ print(server.attr('port')) # 8080
57
+
58
+ # Find all descendants named 'server'
59
+ for el in doc.find_all('server'):
60
+ print(el.name)
61
+ ```
62
+
63
+ ### Transform (immutable update)
64
+
65
+ `transform` and `transform_all` return a **new document** — the original is
66
+ unchanged.
67
+
68
+ ```python
69
+ import cxlib
70
+
71
+ doc = cxlib.parse("""[config
72
+ [server host=localhost port=8080]
73
+ [database host=db.local port=5432]
74
+ ]""")
75
+
76
+ # Replace config/server — returns a new document
77
+ def update_host(el):
78
+ el.set_attr('host', 'prod.example.com')
79
+ return el
80
+
81
+ updated = doc.transform('config/server', update_host)
82
+
83
+ print(updated.at('config/server').attr('host')) # prod.example.com
84
+ print(doc.at('config/server').attr('host')) # localhost (original unchanged)
85
+
86
+ # Chain multiple transforms
87
+ result = (doc
88
+ .transform('config/server', lambda el: (el.set_attr('host', 'web.example.com') or el))
89
+ .transform('config/database', lambda el: (el.set_attr('host', 'db.example.com') or el)))
90
+
91
+ print(result.to_cx())
92
+ ```
93
+
94
+ ### CXPath: select
95
+
96
+ `select` and `select_all` evaluate CXPath expressions against a document or
97
+ element. Expressions support descendant axes (`//`), child paths (`a/b/c`),
98
+ wildcards (`*`), attribute predicates, boolean operators, position, and
99
+ string functions.
100
+
101
+ ```python
102
+ import cxlib
103
+
104
+ doc = cxlib.parse("""[services
105
+ [service name=auth port=8080 active=true]
106
+ [service name=api port=9000 active=false]
107
+ [service name=web port=80 active=true]
108
+ ]""")
109
+
110
+ # First match
111
+ first = doc.select('//service')
112
+ print(first.attr('name')) # auth
113
+
114
+ # All active services
115
+ for svc in doc.select_all('//service[= $_@active true]'):
116
+ print(svc.attr('name'))
117
+ # auth
118
+ # web
119
+
120
+ # Attribute predicate with numeric comparison
121
+ high = doc.select_all('//service[>= $_@port 8000]')
122
+ print(len(high)) # 2
123
+
124
+ # Position
125
+ second = doc.select('//service[2]')
126
+ print(second.attr('name')) # api
127
+
128
+ # select on an Element searches only its subtree (excludes the element itself)
129
+ services_el = doc.at('services')
130
+ for svc in services_el.select_all('service[= $_@active true]'):
131
+ print(svc.attr('name'))
132
+ ```
133
+
134
+ ### transform_all
135
+
136
+ `transform_all` applies a function to every element matching a CXPath
137
+ expression and returns a new document.
138
+
139
+ ```python
140
+ import cxlib
141
+
142
+ doc = cxlib.parse("""[services
143
+ [service name=auth port=8080]
144
+ [service name=api port=9000]
145
+ ]""")
146
+
147
+ def activate(el):
148
+ el.set_attr('active', True)
149
+ return el
150
+
151
+ updated = doc.transform_all('//service', activate)
152
+
153
+ for svc in updated.find_all('service'):
154
+ print(svc.attr('active')) # True
155
+ ```
156
+
157
+ ### Streaming
158
+
159
+ `cxlib.stream(src)` returns a `Stream` iterator over all events.
160
+
161
+ ```python
162
+ import cxlib
163
+
164
+ src = """[config version='1.0'
165
+ [server host=localhost port=8080]
166
+ ]"""
167
+
168
+ for ev in cxlib.stream(src):
169
+ if ev.is_start_element():
170
+ attrs = ' '.join(f'{a.name}={a.value}' for a in ev.attrs)
171
+ print(f'{ev.name} {attrs}')
172
+ ```
173
+
174
+ Output:
175
+ ```
176
+ config version=1.0
177
+ server host=localhost port=8080
178
+ ```
179
+
180
+ ### CX code: query / transform / template
181
+
182
+ CX code is CX's unified pattern / query / transform language — a CX program is itself a `.cx` file (same parser, same data model). `eval_code(input, program, output_target)` runs the program against an optional input document. `output_target` is `""` (default `"text"`), `"cx"`, `"json"`, `"yaml"`, `"xml"`, `"csv"`, or `"tsv"`.
183
+
184
+ ```python
185
+ import cxlib
186
+
187
+ ctx = "[fleet [svc name=auth :status up] [svc name=web :status up] [svc name=db :status down]]"
188
+
189
+ # Find every service via a CXPath path value
190
+ prog = "//svc"
191
+
192
+ print(cxlib.eval_code(ctx, prog))
193
+ # [svc name=auth :status up]
194
+ # [svc name=web :status up]
195
+ # [svc name=db :status down]
196
+ ```
197
+
198
+ See [`cx-core-code:spec/03-approved/core/code.md`](https://github.com/cx-home/cx-core-code/blob/main/spec/03-approved/core/code.md) for the full language reference. `eval_code` is the eval entry point.
199
+
200
+ ## Run the Examples
201
+
202
+ ```sh
203
+ python lang/python/examples/transform.py
204
+ ```
205
+
206
+ ## API Reference
207
+
208
+ ### Parse
209
+
210
+ | Function | Description |
211
+ |---|---|
212
+ | `parse(s)` | Parse a CX string into a `Document` |
213
+ | `parse_xml(s)` | Parse XML into a `Document` |
214
+ | `parse_json(s)` | Parse JSON into a `Document` |
215
+ | `parse_yaml(s)` | Parse YAML into a `Document` |
216
+ | `parse_toml(s)` | Parse TOML into a `Document` |
217
+
218
+ ### Document
219
+
220
+ | Method | Description |
221
+ |---|---|
222
+ | `doc.root()` | First top-level `Element` |
223
+ | `doc.get(name)` | First top-level `Element` by name |
224
+ | `doc.at(path)` | Navigate by slash-separated path (`'config/server'`) |
225
+ | `doc.find_first(name)` | First matching descendant, depth-first |
226
+ | `doc.find_all(name)` | All matching descendants |
227
+ | `doc.select(expr)` | First element matching a CXPath expression |
228
+ | `doc.select_all(expr)` | All elements matching a CXPath expression |
229
+ | `doc.transform(path, fn)` | Return new doc with element at path replaced by `fn(el)` |
230
+ | `doc.transform_all(expr, fn)` | Return new doc with all matching elements replaced |
231
+ | `doc.append(node)` | Add a top-level node |
232
+ | `doc.prepend(node)` | Insert a top-level node at position 0 |
233
+ | `doc.to_cx()` | Emit canonical CX |
234
+ | `doc.to_xml()` | Emit XML |
235
+ | `doc.to_json()` | Emit JSON |
236
+ | `doc.to_yaml()` | Emit YAML |
237
+ | `doc.to_toml()` | Emit TOML |
238
+
239
+ ### Element
240
+
241
+ | Method | Description |
242
+ |---|---|
243
+ | `el.get(name)` | First direct child `Element` by name |
244
+ | `el.get_all(name)` | All direct child `Element`s by name |
245
+ | `el.at(path)` | Navigate relative path from this element |
246
+ | `el.attr(name)` | Read an attribute value (`int`/`float`/`bool`/`str`/`None`) |
247
+ | `el.text()` | Concatenated text and scalar child content |
248
+ | `el.scalar()` | Value of the first `Scalar` child |
249
+ | `el.children()` | All direct child `Element`s |
250
+ | `el.find_first(name)` | First matching descendant |
251
+ | `el.find_all(name)` | All matching descendants |
252
+ | `el.select(expr)` | First descendant matching a CXPath expression |
253
+ | `el.select_all(expr)` | All descendants matching a CXPath expression |
254
+ | `el.set_attr(name, value)` | Set or update an attribute |
255
+ | `el.remove_attr(name)` | Remove an attribute |
256
+ | `el.append(node)` | Add a child node at the end |
257
+ | `el.prepend(node)` | Insert a child node at position 0 |
258
+ | `el.insert(index, node)` | Insert a child node at a given index |
259
+ | `el.remove(node)` | Remove a child node by identity |
260
+ | `el.remove_at(index)` | Remove child node at a given index |
261
+ | `el.remove_child(name)` | Remove all direct child `Element`s with the given name |
262
+
263
+ ### CXPath expressions
264
+
265
+ | Syntax | Matches |
266
+ |---|---|
267
+ | `//name` | All descendants named `name` |
268
+ | `a/b/c` | Child path |
269
+ | `*` | Any element (wildcard) |
270
+ | `[@attr]` | Has attribute |
271
+ | `[= $_@attr val]` | Attribute equals value (typed) |
272
+ | `[!= $_@attr val]` | Attribute not equal |
273
+ | `[>= $_@attr val]` | Numeric comparison (`>`, `<`, `>=`, `<=`) |
274
+ | `[and [= $_@a x] [= $_@b y]]` | Boolean `and` / `or` |
275
+ | `[not [$exists $_@attr]]` | Negation |
276
+ | `[childname]` | Has a direct child element named `childname` |
277
+ | `[1]`, `[2]`, `[= $_position $_last]` | Position (1-based; `[= $_position $_last]` = last) |
278
+ | `[$contains $_@k v]` | Attribute contains substring |
279
+ | `[$starts-with $_@k v]` | Attribute starts with prefix |
280
+
281
+ Attribute values auto-type: `true`/`false` → `bool`, integers → `int`,
282
+ decimals → `float`, everything else → `str`. An invalid expression raises
283
+ `ValueError`.
284
+
285
+ ### Stream
286
+
287
+ | Function / Method | Description |
288
+ |---|---|
289
+ | `stream(s)` | Return a `Stream` iterator over a CX string |
290
+ | `ev.type` | Event type string: `StartDoc` `EndDoc` `StartElement` `EndElement` `Text` `Scalar` `Comment` `PI` `EntityRef` `RawText` `Alias` |
291
+ | `ev.name` | Element name (set on `StartElement` and `EndElement`) |
292
+ | `ev.attrs` | `list[Attr]` (set on `StartElement`) |
293
+ | `ev.value` | Text / comment / scalar raw value |
294
+ | `ev.is_start_element(name)` | `True` if `StartElement`, optionally matching `name` |
295
+ | `ev.is_end_element(name)` | `True` if `EndElement`, optionally matching `name` |
296
+
297
+ ### Conversion functions
298
+
299
+ | Function | Description |
300
+ |---|---|
301
+ | `to_cx(s)` | CX → canonical CX |
302
+ | `to_xml(s)` | CX → XML |
303
+ | `to_json(s)` | CX → JSON |
304
+ | `to_yaml(s)` | CX → YAML |
305
+ | `to_toml(s)` | CX → TOML |
306
+ | `xml_to_cx(s)`, `json_to_cx(s)`, … | Any format → CX |
307
+ | `loads(s)` | Parse CX into native Python types (`dict`/`list`/scalar) |
308
+ | `dumps(data)` | Serialize Python types back to CX |
309
+ | `version()` | Return the libcx version string |
310
+
311
+ ### Canonical-form tooling (v3.4)
312
+
313
+ | Function | Description |
314
+ |---|---|
315
+ | `cx.fmt(s)` | Lossless canonical text — preserves comments/anchors; normalizes presentation. Idempotent: `fmt(fmt(x)) == fmt(x)`. |
316
+ | `cx.canonical(s)` | Strict canonical text — strips presentation. Two CX inputs have identical strict canonical bytes iff they encode the same data. |
317
+ | `cx.hash(s)` | SHA-256 hex (64 lowercase hex chars) of the strict canonical bytes. Use for content-addressable hashing or signed config bundles. |
318
+ | `cx.eq(a, b)` | `True` iff `strict-canonical(a) == strict-canonical(b)`. |
319
+
320
+ ```py
321
+ from cxlib import cx
322
+ src1 = "[config\n [; a comment]\n [server host=localhost]\n]"
323
+ src2 = "[config [server host=localhost]]"
324
+ cx.fmt(src1) # preserves the comment, normalizes whitespace
325
+ cx.canonical(src1) # comment stripped
326
+ cx.eq(src1, src2) # True — same data, different presentation
327
+ cx.hash(src1) == cx.hash(src2) # True
328
+ ```
329
+
330
+ ### `data_bin` one-shot conversions (v3.4)
331
+
332
+ Direct format ↔ binary AST conversions, skipping the text-CX
333
+ intermediate. Useful when a tool already produces CX-binary payloads
334
+ (or wants to consume them) and the text form would only add a
335
+ parse/emit roundtrip.
336
+
337
+ | Function | Description |
338
+ |---|---|
339
+ | `cxlib.xml_to_data_bin(s)` | XML text → CXCol v1 framed bytes |
340
+ | `cxlib.json_to_data_bin(s)` | JSON text → CXCol v1 framed bytes |
341
+ | `cxlib.yaml_to_data_bin(s)` | YAML text → CXCol v1 framed bytes |
342
+ | `cxlib.toml_to_data_bin(s)` | TOML text → CXCol v1 framed bytes |
343
+ | `cxlib.data_bin_to_xml(b)` | CXCol v1 framed bytes → XML text |
344
+ | `cxlib.data_bin_to_json(b)` | CXCol v1 framed bytes → JSON text |
345
+ | `cxlib.data_bin_to_yaml(b)` | CXCol v1 framed bytes → YAML text |
346
+ | `cxlib.data_bin_to_toml(b)` | CXCol v1 framed bytes → TOML text |
347
+
348
+ The framed bytes are CX Data Binary v1 — see `cx-core-data:spec/03-approved/core/data-bin.md` for
349
+ the wire format. Round-trip: `data_bin_to_X(X_to_data_bin(s)) == s`
350
+ (after canonicalization).
351
+
352
+ ### Apache Arrow C-Data interop (optional)
353
+
354
+ Bridges CXCol chunked-tables to Apache Arrow's
355
+ [C-Data ABI](https://arrow.apache.org/docs/format/CDataInterface.html)
356
+ via the separate `libcx_arrow` shared library
357
+ (`make lib-arrow` → `vcx/target/libcx_arrow.dylib` / `.so`). Arrow is an
358
+ optional dependency; install with `pip install cxlib[arrow]` to pull in
359
+ PyArrow ≥ 14. With the bridge wired up CXCol becomes a canonical
360
+ hashable origin that flows zero-copy into Polars / DuckDB / Pandas via
361
+ PyArrow, and the Parquet bridge chains for free
362
+ (`pyarrow.parquet.write_table(reader.read_all(), 'file.parquet')`).
363
+
364
+ ```python
365
+ import cxlib
366
+ import cxlib.arrow as cxa
367
+
368
+ # Discover capability — bit 23 (0x800000) reports libcx_arrow present
369
+ assert cxa.available()
370
+ assert cxa.merged_features() & 0x800000
371
+
372
+ # CXCol chunked-table → pyarrow.RecordBatchReader (one ArrayChunk per row group)
373
+ src = '[points [table[name::string score::int]] alice 91 bob 88 carol 73]'
374
+ framed = cxlib.to_data_bin_chunked(src)
375
+ reader = cxa.export(framed)
376
+ table = reader.read_all() # pyarrow.Table
377
+
378
+ # Inverse: pyarrow.Table or pyarrow.RecordBatchReader → framed CXCol
379
+ import pyarrow as pa
380
+ table_in = pa.table({'name': pa.array(['alice'], type=pa.string()),
381
+ 'score': pa.array([91], type=pa.int64())})
382
+ framed_again = cxa.import_to_data_bin(table_in)
383
+ ```
384
+
385
+ Supported column types (`cx-core-data:spec/03-approved/core/abi.md §2.11.1`):
386
+
387
+ | CXCol type | Arrow format | PyArrow type |
388
+ |------------------|--------------|----------------|
389
+ | `int` / `i64` | `l` | `int64` |
390
+ | `i8` | `c` | `int8` |
391
+ | `i16` | `s` | `int16` |
392
+ | `i32` | `i` | `int32` |
393
+ | `float` / `f64` | `g` | `float64` |
394
+ | `bool` | `b` | `bool` |
395
+ | `string` | `u` | `string` |
396
+ | `date` | `tdD` | `date32[day]` |
397
+ | `bytes` | `z` | `binary` |
398
+
399
+ `datetime` and `decimal` columns are deferred to a follow-up phase
400
+ (`cx-core-data:spec/03-approved/core/abi.md §2.11.1`); they surface a clear deferred-type error at
401
+ chunked-emit time. NULL handling is also deferred (`null_count = 0`
402
+ on both sides).
403
+
404
+ `cxa.available()` is `False` if either `libcx_arrow` is missing or
405
+ PyArrow is not importable; consumers can fall back to materializing
406
+ through `cxlib.data_bin_to_csv()` / `cxlib.data_bin_to_json()` for
407
+ those environments.
408
+
409
+ ## Tests
410
+
411
+ ```sh
412
+ make test-python
413
+ ```
414
+
415
+ ## 30-second quickstart
416
+
417
+ <!-- quickstart-begin: python -->
418
+ ```python
419
+ import cxlib
420
+ from cxlib import Table
421
+
422
+ # Parse + read a typed value out
423
+ doc = cxlib.parse('[server [port :u16 8080] [host localhost]]')
424
+ print(doc.at('server/port').int_value()) # 8080
425
+
426
+ # Round-trip to JSON, lossless
427
+ print(cxlib.to_json('[user [id :i64 9007199254740993]]'))
428
+
429
+ # Public Table API — 17-member surface
430
+ src = """[users [table[name age::int]]
431
+ alice 30
432
+ bob 25
433
+ ]"""
434
+ t = Table.from_cx(src)
435
+ print(t.row_count, t.cols) # 2 ['name', 'age']
436
+ for row in t: # iterate rows as dicts
437
+ print(row['name'], row['age'])
438
+ print(t.column('age')) # [30, 25]
439
+ print(t.to_csv()) # CSV emit
440
+ ```
441
+ <!-- quickstart-end -->