joints 0.1.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.
- joints-0.1.0/.gitignore +55 -0
- joints-0.1.0/LICENSE +202 -0
- joints-0.1.0/NOTICE +20 -0
- joints-0.1.0/PKG-INFO +83 -0
- joints-0.1.0/README.md +61 -0
- joints-0.1.0/joints/__init__.py +34 -0
- joints-0.1.0/joints/_api.py +488 -0
- joints-0.1.0/joints/_native.py +114 -0
- joints-0.1.0/joints/py.typed +0 -0
- joints-0.1.0/pyproject.toml +54 -0
joints-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Zig
|
|
2
|
+
zig-out/
|
|
3
|
+
.zig-cache/
|
|
4
|
+
zig-cache/
|
|
5
|
+
zig-pkg/
|
|
6
|
+
|
|
7
|
+
# Rust (bindings/rust)
|
|
8
|
+
target/
|
|
9
|
+
# The crates.io landing page, minted from the repository README at package
|
|
10
|
+
# time. Never committed: a checked-in copy is a second README to keep in step
|
|
11
|
+
# with the first.
|
|
12
|
+
bindings/rust/PROJECT_README.md
|
|
13
|
+
|
|
14
|
+
# Go (bindings/go) — the cross-repo development override. A published go.mod
|
|
15
|
+
# carries no `replace`, because Go ignores one in a dependency; a `go.work` is
|
|
16
|
+
# the sanctioned way to point at a sibling checkout instead of the proxy, and
|
|
17
|
+
# it is one developer's local wiring rather than a fact about the module.
|
|
18
|
+
go.work
|
|
19
|
+
go.work.sum
|
|
20
|
+
|
|
21
|
+
# Python (bindings/python)
|
|
22
|
+
__pycache__/
|
|
23
|
+
*.py[cod]
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.venv/
|
|
26
|
+
dist/
|
|
27
|
+
.pytest_cache/
|
|
28
|
+
.ruff_cache/
|
|
29
|
+
|
|
30
|
+
# Compiled grammar artifacts. A folio is minted by the press from a rubric, so
|
|
31
|
+
# a committed one is a build output pretending to be a source.
|
|
32
|
+
*.folio
|
|
33
|
+
|
|
34
|
+
# Search artifact home (index · atlas · shelf), shared with the sibling CLIs
|
|
35
|
+
.gist/
|
|
36
|
+
|
|
37
|
+
# Upstream clones kept for study — tree-sitter, lezer, antlr, gpeg
|
|
38
|
+
upstream/
|
|
39
|
+
|
|
40
|
+
# The sealed holdout's BYTES. The pins, the seal and the ledger are tracked
|
|
41
|
+
# (`holdout/holdout.toml`, `holdout/README.md`, `holdout/ledger.json`); the
|
|
42
|
+
# grammars and source files they name are re-fetchable from those pins and are
|
|
43
|
+
# nobody's to vendor. Same trade as `upstream/`, one directory over.
|
|
44
|
+
holdout/vendor/
|
|
45
|
+
|
|
46
|
+
# Toolchain overrides for one machine. `.mise.toml` and `mise.lock` are
|
|
47
|
+
# tracked; these are the per-checkout escape hatch and nobody else's business.
|
|
48
|
+
mise.local.toml
|
|
49
|
+
mise.local.lock
|
|
50
|
+
|
|
51
|
+
# Machine-local scratch. Globbed, not literal: ad-hoc probe dirs get named
|
|
52
|
+
# `.local-something`, land one character outside a literal rule, and are then
|
|
53
|
+
# one `git add -A` away from committing a hardcoded home path.
|
|
54
|
+
.local*/
|
|
55
|
+
.DS_Store
|
joints-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 The Billy Company
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
joints-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
joints — parsing as algebra: one binary, one folio, every language
|
|
2
|
+
Copyright 2026 The Billy Company
|
|
3
|
+
|
|
4
|
+
This product includes software developed at The Billy Company
|
|
5
|
+
(https://billylives.com/).
|
|
6
|
+
|
|
7
|
+
joints stands on the irregex package for its regex engine, C-ABI floor, and
|
|
8
|
+
shared math primitives; the attributions for what irregex bundles live in its
|
|
9
|
+
own NOTICE file.
|
|
10
|
+
|
|
11
|
+
No third-party source is bundled here. One third-party data file is:
|
|
12
|
+
|
|
13
|
+
test/grammar/json.json
|
|
14
|
+
The generated grammar of tree-sitter/tree-sitter-json, committed byte for
|
|
15
|
+
byte as a test fixture so the test build needs nothing from the network.
|
|
16
|
+
The MIT License (MIT), Copyright (c) 2014 Max Brunsfeld.
|
|
17
|
+
https://github.com/tree-sitter/tree-sitter-json
|
|
18
|
+
|
|
19
|
+
joints reads tree-sitter grammars; it does not link, vendor, or ship
|
|
20
|
+
tree-sitter itself, and nothing at run time depends on it.
|
joints-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: joints
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Experimental parsing and structural queries over grammar data, with Python bindings to libjnt.
|
|
5
|
+
Project-URL: Homepage, https://github.com/The-Billy-Company/joints
|
|
6
|
+
Project-URL: Source, https://github.com/The-Billy-Company/joints
|
|
7
|
+
Project-URL: Documentation, https://github.com/The-Billy-Company/joints/blob/main/bindings/python/README.md
|
|
8
|
+
Project-URL: Changelog, https://github.com/The-Billy-Company/joints/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/The-Billy-Company/joints/issues
|
|
10
|
+
Author: The Billy Company
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
License-File: NOTICE
|
|
14
|
+
Keywords: cst,incremental,parser,parsing,syntax-tree,tree-sitter
|
|
15
|
+
Classifier: Development Status :: 3 - Alpha
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Topic :: Software Development :: Compilers
|
|
19
|
+
Classifier: Topic :: Text Processing :: General
|
|
20
|
+
Requires-Python: >=3.12
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# joints for Python
|
|
24
|
+
|
|
25
|
+
Open a grammar folio, parse source, and run structural queries through `libjnt`.
|
|
26
|
+
The 0.1.0 binding is experimental and requires a separately supplied native
|
|
27
|
+
library with ABI 2.
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
zig build
|
|
31
|
+
export PYTHONPATH="$PWD/bindings/python"
|
|
32
|
+
export JOINTS_LIB="$PWD/zig-out/lib/libjnt.so" # libjnt.dylib on macOS
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from joints import Bank
|
|
37
|
+
|
|
38
|
+
with Bank("python.folio") as bank, bank.parser() as parser:
|
|
39
|
+
with parser.parse(source_bytes) as tree:
|
|
40
|
+
with parser.query("(function_definition name: (identifier) @name)") as query:
|
|
41
|
+
for node in query.captures(tree).get("name", []):
|
|
42
|
+
print(node.text, node.start_point)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`Bank` accepts a single folio, a multi-language codex, or a tree-sitter
|
|
46
|
+
`grammar.json`. Select a codex language with `bank.parser("python")`.
|
|
47
|
+
Minting once avoids rebuilding grammar tables when a process opens the bank.
|
|
48
|
+
|
|
49
|
+
A strict parse requires one root, acceptance, no deleted or supplied tokens,
|
|
50
|
+
and a structurally sound tree. It raises `ParseError` when that evidence is
|
|
51
|
+
missing. `parser.parse(source, strict=False)` exposes a partial forest together
|
|
52
|
+
with `stop`, `mends`, `skipped`, `supplied`, `repairs`, and `roots`
|
|
53
|
+
for callers that can use recovery. A sound forest alone does not establish that
|
|
54
|
+
source was understood.
|
|
55
|
+
|
|
56
|
+
Nodes expose byte spans, source text, byte-based row/column positions, children,
|
|
57
|
+
fields, parents, and siblings. Queries return ordered matches or captures grouped
|
|
58
|
+
by name. Unknown predicates are refused unless the caller explicitly passes
|
|
59
|
+
`foreign="admit"` or `foreign="deny"`.
|
|
60
|
+
|
|
61
|
+
Use one bank and parser per thread. Close trees and queries before their parser,
|
|
62
|
+
then close the bank; context managers enforce that order. Accessing nodes after
|
|
63
|
+
their tree closes raises an error. Importing the package does not load native code.
|
|
64
|
+
`JOINTS_LIB` selects a library explicitly; otherwise a bundled library, the local
|
|
65
|
+
checkout's build, or the system library is tried.
|
|
66
|
+
|
|
67
|
+
Run the native integration checks after building:
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
PYTHONPATH=bindings/python python3 -m unittest discover -s bindings/python/tests
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The Python wheel and sdist contain the interface; no native library or grammar
|
|
74
|
+
bank is bundled. Install the package and download the matching native archive
|
|
75
|
+
from [Joints releases](https://github.com/The-Billy-Company/joints/releases):
|
|
76
|
+
`joints-0.1.0-linux-x86_64.tar.gz` or `joints-0.1.0-macos-arm64.tar.gz`.
|
|
77
|
+
Set `JOINTS_LIB` to the extracted archive's `lib/libjnt.so` or
|
|
78
|
+
`lib/libjnt.dylib`. Its `grammar/json.json` is a reproducible starting bank;
|
|
79
|
+
compile other grammars with the included CLI. The native archives are tested
|
|
80
|
+
on Ubuntu 24.04 (glibc 2.39) and macOS 14. Other targets require a source build.
|
|
81
|
+
The [Rust binding](../rust/README.md) uses the same native archives.
|
|
82
|
+
|
|
83
|
+
Apache-2.0; see `LICENSE` and `NOTICE`.
|
joints-0.1.0/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# joints for Python
|
|
2
|
+
|
|
3
|
+
Open a grammar folio, parse source, and run structural queries through `libjnt`.
|
|
4
|
+
The 0.1.0 binding is experimental and requires a separately supplied native
|
|
5
|
+
library with ABI 2.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
zig build
|
|
9
|
+
export PYTHONPATH="$PWD/bindings/python"
|
|
10
|
+
export JOINTS_LIB="$PWD/zig-out/lib/libjnt.so" # libjnt.dylib on macOS
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from joints import Bank
|
|
15
|
+
|
|
16
|
+
with Bank("python.folio") as bank, bank.parser() as parser:
|
|
17
|
+
with parser.parse(source_bytes) as tree:
|
|
18
|
+
with parser.query("(function_definition name: (identifier) @name)") as query:
|
|
19
|
+
for node in query.captures(tree).get("name", []):
|
|
20
|
+
print(node.text, node.start_point)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`Bank` accepts a single folio, a multi-language codex, or a tree-sitter
|
|
24
|
+
`grammar.json`. Select a codex language with `bank.parser("python")`.
|
|
25
|
+
Minting once avoids rebuilding grammar tables when a process opens the bank.
|
|
26
|
+
|
|
27
|
+
A strict parse requires one root, acceptance, no deleted or supplied tokens,
|
|
28
|
+
and a structurally sound tree. It raises `ParseError` when that evidence is
|
|
29
|
+
missing. `parser.parse(source, strict=False)` exposes a partial forest together
|
|
30
|
+
with `stop`, `mends`, `skipped`, `supplied`, `repairs`, and `roots`
|
|
31
|
+
for callers that can use recovery. A sound forest alone does not establish that
|
|
32
|
+
source was understood.
|
|
33
|
+
|
|
34
|
+
Nodes expose byte spans, source text, byte-based row/column positions, children,
|
|
35
|
+
fields, parents, and siblings. Queries return ordered matches or captures grouped
|
|
36
|
+
by name. Unknown predicates are refused unless the caller explicitly passes
|
|
37
|
+
`foreign="admit"` or `foreign="deny"`.
|
|
38
|
+
|
|
39
|
+
Use one bank and parser per thread. Close trees and queries before their parser,
|
|
40
|
+
then close the bank; context managers enforce that order. Accessing nodes after
|
|
41
|
+
their tree closes raises an error. Importing the package does not load native code.
|
|
42
|
+
`JOINTS_LIB` selects a library explicitly; otherwise a bundled library, the local
|
|
43
|
+
checkout's build, or the system library is tried.
|
|
44
|
+
|
|
45
|
+
Run the native integration checks after building:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
PYTHONPATH=bindings/python python3 -m unittest discover -s bindings/python/tests
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The Python wheel and sdist contain the interface; no native library or grammar
|
|
52
|
+
bank is bundled. Install the package and download the matching native archive
|
|
53
|
+
from [Joints releases](https://github.com/The-Billy-Company/joints/releases):
|
|
54
|
+
`joints-0.1.0-linux-x86_64.tar.gz` or `joints-0.1.0-macos-arm64.tar.gz`.
|
|
55
|
+
Set `JOINTS_LIB` to the extracted archive's `lib/libjnt.so` or
|
|
56
|
+
`lib/libjnt.dylib`. Its `grammar/json.json` is a reproducible starting bank;
|
|
57
|
+
compile other grammars with the included CLI. The native archives are tested
|
|
58
|
+
on Ubuntu 24.04 (glibc 2.39) and macOS 14. Other targets require a source build.
|
|
59
|
+
The [Rust binding](../rust/README.md) uses the same native archives.
|
|
60
|
+
|
|
61
|
+
Apache-2.0; see `LICENSE` and `NOTICE`.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Parse grammar folios and run structural queries through libjnt.
|
|
2
|
+
|
|
3
|
+
Banks own parsers, parsers own trees and queries. Use nested context managers
|
|
4
|
+
for explicit release. Strict parsing rejects repairs and partial trees so CI
|
|
5
|
+
checks cannot mistake recovery for understood source.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from ._api import (
|
|
9
|
+
Bank,
|
|
10
|
+
Capture,
|
|
11
|
+
JointsError,
|
|
12
|
+
Match,
|
|
13
|
+
Node,
|
|
14
|
+
ParseError,
|
|
15
|
+
Parser,
|
|
16
|
+
Query,
|
|
17
|
+
Repair,
|
|
18
|
+
Tree,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0" # x-release-please-version
|
|
22
|
+
__all__ = [
|
|
23
|
+
"Bank",
|
|
24
|
+
"Parser",
|
|
25
|
+
"Tree",
|
|
26
|
+
"Node",
|
|
27
|
+
"Query",
|
|
28
|
+
"Capture",
|
|
29
|
+
"Match",
|
|
30
|
+
"JointsError",
|
|
31
|
+
"ParseError",
|
|
32
|
+
"Repair",
|
|
33
|
+
"__version__",
|
|
34
|
+
]
|
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
"""Owned parser handles and borrowed nodes over the native C ABI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from bisect import bisect_right
|
|
6
|
+
import ctypes as c
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from functools import cached_property
|
|
9
|
+
import os
|
|
10
|
+
import threading
|
|
11
|
+
from weakref import WeakSet
|
|
12
|
+
|
|
13
|
+
from ._native import NativeScar, native
|
|
14
|
+
|
|
15
|
+
NONE = 0xFFFFFFFF
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class JointsError(RuntimeError):
|
|
19
|
+
"""A native operation could not run."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ParseError(JointsError):
|
|
23
|
+
"""A strict parse produced a partial, repaired, or unsound tree."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Repair:
|
|
28
|
+
"""A deletion over [at, over), or a zero-width supplied token."""
|
|
29
|
+
|
|
30
|
+
at: int
|
|
31
|
+
over: int
|
|
32
|
+
supplied: bool
|
|
33
|
+
word: str | None
|
|
34
|
+
stop: str
|
|
35
|
+
heads: int
|
|
36
|
+
shifted: int
|
|
37
|
+
felled: int
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _z(value: str | os.PathLike[str]) -> bytes:
|
|
41
|
+
result = os.fsencode(value)
|
|
42
|
+
if b"\0" in result:
|
|
43
|
+
raise ValueError("paths and language names cannot contain NUL")
|
|
44
|
+
return result
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _bytes(value: str | bytes) -> bytes:
|
|
48
|
+
if isinstance(value, str):
|
|
49
|
+
return value.encode("utf-8")
|
|
50
|
+
if not isinstance(value, bytes):
|
|
51
|
+
raise TypeError("source must be str or bytes")
|
|
52
|
+
return value
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _check(lib, status: int) -> None:
|
|
56
|
+
if status < 0:
|
|
57
|
+
message = lib.jnt_last_error().decode("utf-8", errors="replace")
|
|
58
|
+
raise JointsError(message or f"libjnt failed with status {status}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _string(fn, *args) -> str | None:
|
|
62
|
+
length = c.c_size_t()
|
|
63
|
+
address = fn(*args, c.byref(length))
|
|
64
|
+
return c.string_at(address, length.value).decode("utf-8") if address else None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _Handle:
|
|
68
|
+
def _init(self, lib, pointer, owner=None) -> None:
|
|
69
|
+
self._lib, self._handle, self._owner = lib, pointer, owner
|
|
70
|
+
self._thread = threading.get_ident()
|
|
71
|
+
self._children: WeakSet = WeakSet()
|
|
72
|
+
if owner is not None:
|
|
73
|
+
owner._children.add(self)
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def _ptr(self):
|
|
77
|
+
if not self._handle:
|
|
78
|
+
raise JointsError(f"{type(self).__name__} is closed")
|
|
79
|
+
if self._thread != threading.get_ident():
|
|
80
|
+
raise JointsError("use one bank and parser per thread")
|
|
81
|
+
if self._owner is not None:
|
|
82
|
+
self._owner._ptr
|
|
83
|
+
return self._handle
|
|
84
|
+
|
|
85
|
+
def close(self) -> None:
|
|
86
|
+
"""Release this handle after its dependent handles have closed."""
|
|
87
|
+
if not getattr(self, "_handle", None):
|
|
88
|
+
return
|
|
89
|
+
if any(child._handle for child in self._children):
|
|
90
|
+
raise JointsError(f"close dependent handles before {type(self).__name__}")
|
|
91
|
+
self._ptr
|
|
92
|
+
getattr(self._lib, self._free)(self._handle)
|
|
93
|
+
self._handle = None
|
|
94
|
+
if self._owner is not None:
|
|
95
|
+
self._owner._children.discard(self)
|
|
96
|
+
self._owner = None
|
|
97
|
+
|
|
98
|
+
def __enter__(self):
|
|
99
|
+
self._ptr
|
|
100
|
+
return self
|
|
101
|
+
|
|
102
|
+
def __exit__(self, *exc) -> None:
|
|
103
|
+
self.close()
|
|
104
|
+
|
|
105
|
+
def __del__(self) -> None:
|
|
106
|
+
try:
|
|
107
|
+
self.close()
|
|
108
|
+
except Exception:
|
|
109
|
+
# Explicit close reports misuse; finalization must not raise.
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Bank(_Handle):
|
|
114
|
+
"""An opened folio, multi-language codex, or grammar.json."""
|
|
115
|
+
|
|
116
|
+
_free = "jnt_close"
|
|
117
|
+
|
|
118
|
+
def __init__(self, path: str | os.PathLike[str], *, library=None):
|
|
119
|
+
lib = native(library)
|
|
120
|
+
pointer = c.c_void_p()
|
|
121
|
+
_check(lib, lib.jnt_open(_z(path), c.byref(pointer)))
|
|
122
|
+
self._init(lib, pointer)
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def languages(self) -> tuple[str, ...]:
|
|
126
|
+
pointer = self._ptr
|
|
127
|
+
return tuple(
|
|
128
|
+
_string(self._lib.jnt_bank_title, pointer, i)
|
|
129
|
+
for i in range(self._lib.jnt_bank_count(pointer))
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
def parser(self, language: str | None = None) -> Parser:
|
|
133
|
+
"""Bind one language; unnamed selection requires a single-language bank."""
|
|
134
|
+
return Parser(self, language)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Parser(_Handle):
|
|
138
|
+
"""One language with reusable scratch, used from its creating thread."""
|
|
139
|
+
|
|
140
|
+
_free = "jnt_parser_free"
|
|
141
|
+
|
|
142
|
+
def __init__(self, bank: Bank, language: str | None = None):
|
|
143
|
+
pointer = c.c_void_p()
|
|
144
|
+
_check(
|
|
145
|
+
bank._lib,
|
|
146
|
+
bank._lib.jnt_parser_new(
|
|
147
|
+
bank._ptr,
|
|
148
|
+
_z(language) if language is not None else None,
|
|
149
|
+
c.byref(pointer),
|
|
150
|
+
),
|
|
151
|
+
)
|
|
152
|
+
self._init(bank._lib, pointer, bank)
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def language(self) -> str:
|
|
156
|
+
return _string(self._lib.jnt_parser_language, self._ptr)
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def blind(self) -> int:
|
|
160
|
+
"""External terminals without a scanner rule in this grammar."""
|
|
161
|
+
return self._lib.jnt_parser_blind(self._ptr)
|
|
162
|
+
|
|
163
|
+
def parse(self, source: str | bytes, *, strict: bool = True) -> Tree:
|
|
164
|
+
"""Parse bytes, rejecting partial or repaired trees unless explicitly allowed."""
|
|
165
|
+
data = _bytes(source)
|
|
166
|
+
pointer = c.c_void_p()
|
|
167
|
+
_check(
|
|
168
|
+
self._lib, self._lib.jnt_parse(self._ptr, data, len(data), c.byref(pointer))
|
|
169
|
+
)
|
|
170
|
+
tree = Tree(self, pointer, data)
|
|
171
|
+
try:
|
|
172
|
+
if strict:
|
|
173
|
+
tree.require_complete()
|
|
174
|
+
return tree
|
|
175
|
+
except Exception:
|
|
176
|
+
tree.close()
|
|
177
|
+
raise
|
|
178
|
+
|
|
179
|
+
def query(self, source: str | bytes) -> Query:
|
|
180
|
+
"""Compile a tree-sitter structural query for this parser's grammar."""
|
|
181
|
+
return Query(self, source)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class Tree(_Handle):
|
|
185
|
+
"""A forest plus its parse verdict and original source bytes."""
|
|
186
|
+
|
|
187
|
+
_free = "jnt_tree_free"
|
|
188
|
+
|
|
189
|
+
def __init__(self, parser: Parser, pointer, source: bytes):
|
|
190
|
+
self._init(parser._lib, pointer, parser)
|
|
191
|
+
self._source = source
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def source(self) -> bytes:
|
|
195
|
+
return self._source
|
|
196
|
+
|
|
197
|
+
@property
|
|
198
|
+
def stop(self) -> str:
|
|
199
|
+
return ("accepted", "stray", "unexpected", "truncated")[
|
|
200
|
+
self._lib.jnt_tree_stop(self._ptr)
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def stop_at(self) -> int:
|
|
205
|
+
return self._lib.jnt_tree_stop_at(self._ptr)
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def mends(self) -> int:
|
|
209
|
+
return self._lib.jnt_tree_mends(self._ptr)
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def skipped(self) -> int:
|
|
213
|
+
return self._lib.jnt_tree_skipped(self._ptr)
|
|
214
|
+
|
|
215
|
+
@property
|
|
216
|
+
def supplied(self) -> int:
|
|
217
|
+
return self._lib.jnt_tree_supplied(self._ptr)
|
|
218
|
+
|
|
219
|
+
@property
|
|
220
|
+
def repairs(self) -> tuple[Repair, ...]:
|
|
221
|
+
pointer = self._ptr
|
|
222
|
+
repairs = []
|
|
223
|
+
for i in range(self._lib.jnt_tree_scars(pointer)):
|
|
224
|
+
scar = NativeScar()
|
|
225
|
+
_check(self._lib, self._lib.jnt_tree_scar(pointer, i, c.byref(scar)))
|
|
226
|
+
repairs.append(
|
|
227
|
+
Repair(
|
|
228
|
+
scar.at,
|
|
229
|
+
scar.over,
|
|
230
|
+
bool(scar.supplied),
|
|
231
|
+
_string(self._lib.jnt_tree_scar_word, pointer, i),
|
|
232
|
+
("accepted", "stray", "unexpected", "truncated")[scar.stop],
|
|
233
|
+
scar.heads,
|
|
234
|
+
scar.shifted,
|
|
235
|
+
scar.felled,
|
|
236
|
+
)
|
|
237
|
+
)
|
|
238
|
+
return tuple(repairs)
|
|
239
|
+
|
|
240
|
+
@property
|
|
241
|
+
def sound(self) -> bool:
|
|
242
|
+
status = self._lib.jnt_tree_sound(self._ptr)
|
|
243
|
+
_check(self._lib, status)
|
|
244
|
+
return bool(status)
|
|
245
|
+
|
|
246
|
+
@property
|
|
247
|
+
def roots(self) -> tuple[Node, ...]:
|
|
248
|
+
pointer = self._ptr
|
|
249
|
+
return tuple(
|
|
250
|
+
Node(self, self._lib.jnt_tree_root(pointer, i))
|
|
251
|
+
for i in range(self._lib.jnt_tree_roots(pointer))
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def root_node(self) -> Node:
|
|
256
|
+
roots = self.roots
|
|
257
|
+
if len(roots) != 1:
|
|
258
|
+
raise ParseError(f"expected one root, found {len(roots)}")
|
|
259
|
+
return roots[0]
|
|
260
|
+
|
|
261
|
+
def require_complete(self) -> None:
|
|
262
|
+
"""Require a whole, unrepaired, structurally sound tree for CI use."""
|
|
263
|
+
roots = self._lib.jnt_tree_roots(self._ptr)
|
|
264
|
+
if (
|
|
265
|
+
self.stop != "accepted"
|
|
266
|
+
or self.mends
|
|
267
|
+
or self.skipped
|
|
268
|
+
or self.supplied
|
|
269
|
+
or roots != 1
|
|
270
|
+
):
|
|
271
|
+
raise ParseError(
|
|
272
|
+
f"{self._owner.language}: {self.stop} at byte {self.stop_at}; "
|
|
273
|
+
f"{roots} roots, {self.mends} repairs, "
|
|
274
|
+
f"{self.skipped} skipped bytes, {self.supplied} supplied tokens"
|
|
275
|
+
)
|
|
276
|
+
if not self.sound:
|
|
277
|
+
raise ParseError("the parsed forest is structurally unsound")
|
|
278
|
+
|
|
279
|
+
def sexp(self, *, all: bool = False) -> str:
|
|
280
|
+
result = _string(self._lib.jnt_tree_sexp, self._ptr, int(all))
|
|
281
|
+
if result is None:
|
|
282
|
+
raise JointsError("could not render tree")
|
|
283
|
+
return result
|
|
284
|
+
|
|
285
|
+
@cached_property
|
|
286
|
+
def _lines(self) -> tuple[int, ...]:
|
|
287
|
+
return (0, *(i + 1 for i, byte in enumerate(self.source) if byte == 10))
|
|
288
|
+
|
|
289
|
+
def _point(self, offset: int) -> tuple[int, int]:
|
|
290
|
+
row = bisect_right(self._lines, offset) - 1
|
|
291
|
+
return row, offset - self._lines[row]
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
class Node:
|
|
295
|
+
"""A node reference borrowed from a tree."""
|
|
296
|
+
|
|
297
|
+
def __init__(self, tree: Tree, ref: int):
|
|
298
|
+
self._tree, self.id = tree, ref
|
|
299
|
+
|
|
300
|
+
def __eq__(self, other) -> bool:
|
|
301
|
+
return (
|
|
302
|
+
isinstance(other, Node)
|
|
303
|
+
and self._tree is other._tree
|
|
304
|
+
and self.id == other.id
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
def __hash__(self) -> int:
|
|
308
|
+
return hash((id(self._tree), self.id))
|
|
309
|
+
|
|
310
|
+
def _get(self, name, *args):
|
|
311
|
+
return getattr(self._tree._lib, name)(self._tree._ptr, self.id, *args)
|
|
312
|
+
|
|
313
|
+
def _node(self, ref: int) -> Node | None:
|
|
314
|
+
return None if ref == NONE else Node(self._tree, ref)
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def type(self) -> str:
|
|
318
|
+
return _string(self._tree._lib.jnt_node_name, self._tree._ptr, self.id)
|
|
319
|
+
|
|
320
|
+
@property
|
|
321
|
+
def is_named(self) -> bool:
|
|
322
|
+
return bool(self._get("jnt_node_named"))
|
|
323
|
+
|
|
324
|
+
@property
|
|
325
|
+
def start_byte(self) -> int:
|
|
326
|
+
return self._get("jnt_node_start")
|
|
327
|
+
|
|
328
|
+
@property
|
|
329
|
+
def end_byte(self) -> int:
|
|
330
|
+
return self._get("jnt_node_end")
|
|
331
|
+
|
|
332
|
+
@property
|
|
333
|
+
def text(self) -> bytes:
|
|
334
|
+
return self._tree.source[self.start_byte : self.end_byte]
|
|
335
|
+
|
|
336
|
+
@property
|
|
337
|
+
def start_point(self) -> tuple[int, int]:
|
|
338
|
+
return self._tree._point(self.start_byte)
|
|
339
|
+
|
|
340
|
+
@property
|
|
341
|
+
def end_point(self) -> tuple[int, int]:
|
|
342
|
+
return self._tree._point(self.end_byte)
|
|
343
|
+
|
|
344
|
+
@property
|
|
345
|
+
def child_count(self) -> int:
|
|
346
|
+
return self._get("jnt_node_kids")
|
|
347
|
+
|
|
348
|
+
@property
|
|
349
|
+
def children(self) -> list[Node]:
|
|
350
|
+
return [self.child(i) for i in range(self.child_count)]
|
|
351
|
+
|
|
352
|
+
@property
|
|
353
|
+
def named_children(self) -> list[Node]:
|
|
354
|
+
return [node for node in self.children if node.is_named]
|
|
355
|
+
|
|
356
|
+
@property
|
|
357
|
+
def parent(self) -> Node | None:
|
|
358
|
+
return self._node(self._get("jnt_node_parent"))
|
|
359
|
+
|
|
360
|
+
@property
|
|
361
|
+
def next_sibling(self) -> Node | None:
|
|
362
|
+
return self._node(self._get("jnt_node_next"))
|
|
363
|
+
|
|
364
|
+
@property
|
|
365
|
+
def prev_sibling(self) -> Node | None:
|
|
366
|
+
return self._node(self._get("jnt_node_prev"))
|
|
367
|
+
|
|
368
|
+
@property
|
|
369
|
+
def next_named_sibling(self) -> Node | None:
|
|
370
|
+
return self._node(self._get("jnt_node_next_named"))
|
|
371
|
+
|
|
372
|
+
@property
|
|
373
|
+
def prev_named_sibling(self) -> Node | None:
|
|
374
|
+
return self._node(self._get("jnt_node_prev_named"))
|
|
375
|
+
|
|
376
|
+
def child(self, index: int) -> Node | None:
|
|
377
|
+
if index < 0:
|
|
378
|
+
return None
|
|
379
|
+
return self._node(self._get("jnt_node_kid", index))
|
|
380
|
+
|
|
381
|
+
def child_by_field_name(self, name: str) -> Node | None:
|
|
382
|
+
field = name.encode("utf-8")
|
|
383
|
+
return self._node(self._get("jnt_node_by_field", field, len(field)))
|
|
384
|
+
|
|
385
|
+
def field_name_for_child(self, index: int) -> str | None:
|
|
386
|
+
child = self.child(index)
|
|
387
|
+
return (
|
|
388
|
+
_string(self._tree._lib.jnt_node_field, self._tree._ptr, child.id)
|
|
389
|
+
if child is not None
|
|
390
|
+
else None
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
@dataclass(frozen=True)
|
|
395
|
+
class Capture:
|
|
396
|
+
"""A query capture and the node it names."""
|
|
397
|
+
|
|
398
|
+
name: str
|
|
399
|
+
node: Node
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@dataclass(frozen=True)
|
|
403
|
+
class Match:
|
|
404
|
+
"""One matched pattern, retaining capture order and multiplicity."""
|
|
405
|
+
|
|
406
|
+
pattern_index: int
|
|
407
|
+
captures: tuple[Capture, ...]
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
class Query(_Handle):
|
|
411
|
+
"""A compiled query bound to one parser's grammar."""
|
|
412
|
+
|
|
413
|
+
_free = "jnt_query_free"
|
|
414
|
+
|
|
415
|
+
def __init__(self, parser: Parser, source: str | bytes):
|
|
416
|
+
data = _bytes(source)
|
|
417
|
+
pointer = c.c_void_p()
|
|
418
|
+
_check(
|
|
419
|
+
parser._lib,
|
|
420
|
+
parser._lib.jnt_query_compile(
|
|
421
|
+
parser._ptr, data, len(data), c.byref(pointer)
|
|
422
|
+
),
|
|
423
|
+
)
|
|
424
|
+
self._init(parser._lib, pointer, parser)
|
|
425
|
+
|
|
426
|
+
@property
|
|
427
|
+
def capture_names(self) -> tuple[str, ...]:
|
|
428
|
+
pointer = self._ptr
|
|
429
|
+
return tuple(
|
|
430
|
+
_string(self._lib.jnt_query_capture_name, pointer, i)
|
|
431
|
+
for i in range(self._lib.jnt_query_capture_count(pointer))
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
def matches(self, tree: Tree, *, foreign: str = "refuse") -> list[Match]:
|
|
435
|
+
"""Match a tree; unknown predicates are refused unless explicitly configured."""
|
|
436
|
+
policies = {"refuse": 0, "admit": 1, "deny": 2}
|
|
437
|
+
if foreign not in policies:
|
|
438
|
+
raise ValueError("foreign must be refuse, admit, or deny")
|
|
439
|
+
if tree._owner is not self._owner:
|
|
440
|
+
raise JointsError("query and tree must belong to the same parser")
|
|
441
|
+
result = c.c_void_p()
|
|
442
|
+
_check(
|
|
443
|
+
self._lib,
|
|
444
|
+
self._lib.jnt_query_exec(
|
|
445
|
+
self._ptr,
|
|
446
|
+
tree._ptr,
|
|
447
|
+
tree.source,
|
|
448
|
+
len(tree.source),
|
|
449
|
+
policies[foreign],
|
|
450
|
+
c.byref(result),
|
|
451
|
+
),
|
|
452
|
+
)
|
|
453
|
+
try:
|
|
454
|
+
names = self.capture_names
|
|
455
|
+
return [
|
|
456
|
+
Match(
|
|
457
|
+
self._lib.jnt_query_result_pattern(result, i),
|
|
458
|
+
tuple(
|
|
459
|
+
Capture(
|
|
460
|
+
names[self._lib.jnt_query_result_capture_id(result, i, j)],
|
|
461
|
+
Node(
|
|
462
|
+
tree,
|
|
463
|
+
self._lib.jnt_query_result_capture_node(result, i, j),
|
|
464
|
+
),
|
|
465
|
+
)
|
|
466
|
+
for j in range(
|
|
467
|
+
self._lib.jnt_query_result_capture_count(result, i)
|
|
468
|
+
)
|
|
469
|
+
),
|
|
470
|
+
)
|
|
471
|
+
for i in range(self._lib.jnt_query_result_count(result))
|
|
472
|
+
]
|
|
473
|
+
finally:
|
|
474
|
+
self._lib.jnt_query_result_free(result)
|
|
475
|
+
|
|
476
|
+
def captures(self, tree: Tree, *, foreign: str = "refuse") -> dict[str, list[Node]]:
|
|
477
|
+
"""Group distinct captured nodes by name in source order."""
|
|
478
|
+
captured: dict[str, list[Node]] = {}
|
|
479
|
+
seen: dict[str, set[int]] = {}
|
|
480
|
+
for match in self.matches(tree, foreign=foreign):
|
|
481
|
+
for capture in match.captures:
|
|
482
|
+
ids = seen.setdefault(capture.name, set())
|
|
483
|
+
if capture.node.id not in ids:
|
|
484
|
+
ids.add(capture.node.id)
|
|
485
|
+
captured.setdefault(capture.name, []).append(capture.node)
|
|
486
|
+
for nodes in captured.values():
|
|
487
|
+
nodes.sort(key=lambda node: (node.start_byte, node.end_byte, node.id))
|
|
488
|
+
return captured
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Load and type libjnt lazily; importing joints needs no native library."""
|
|
2
|
+
|
|
3
|
+
import ctypes as c
|
|
4
|
+
from ctypes.util import find_library
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
P, U, INT, Z, S = c.c_void_p, c.c_uint32, c.c_int32, c.c_size_t, c.c_char_p
|
|
11
|
+
OUT, LEN = c.POINTER(P), c.POINTER(Z)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class NativeScar(c.Structure):
|
|
15
|
+
_fields_ = [
|
|
16
|
+
(name, U) for name in ("at", "over", "supplied", "heads", "shifted", "felled")
|
|
17
|
+
] + [("stop", INT)]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@lru_cache(maxsize=None)
|
|
21
|
+
def native(path=None):
|
|
22
|
+
name = (
|
|
23
|
+
"jnt.dll"
|
|
24
|
+
if sys.platform == "win32"
|
|
25
|
+
else ("libjnt.dylib" if sys.platform == "darwin" else "libjnt.so")
|
|
26
|
+
)
|
|
27
|
+
explicit = path or os.environ.get("JOINTS_LIB")
|
|
28
|
+
if explicit:
|
|
29
|
+
candidates = [os.fspath(explicit)]
|
|
30
|
+
else:
|
|
31
|
+
package = Path(__file__).resolve().parent
|
|
32
|
+
candidates = [
|
|
33
|
+
str(package / "_native" / name),
|
|
34
|
+
str(package.parents[2] / "zig-out" / "lib" / name),
|
|
35
|
+
]
|
|
36
|
+
if found := find_library("jnt"):
|
|
37
|
+
candidates.append(found)
|
|
38
|
+
failures = []
|
|
39
|
+
for candidate in candidates:
|
|
40
|
+
try:
|
|
41
|
+
lib = c.CDLL(candidate)
|
|
42
|
+
break
|
|
43
|
+
except OSError as error:
|
|
44
|
+
failures.append(str(error))
|
|
45
|
+
else:
|
|
46
|
+
raise OSError(
|
|
47
|
+
"libjnt is unavailable; build joints and set JOINTS_LIB. "
|
|
48
|
+
+ "; ".join(failures)
|
|
49
|
+
)
|
|
50
|
+
signatures = {
|
|
51
|
+
"jnt_abi_version": (U, []),
|
|
52
|
+
"jnt_last_error": (S, []),
|
|
53
|
+
"jnt_open": (INT, [S, OUT]),
|
|
54
|
+
"jnt_close": (None, [P]),
|
|
55
|
+
"jnt_bank_count": (U, [P]),
|
|
56
|
+
"jnt_bank_title": (P, [P, U, LEN]),
|
|
57
|
+
"jnt_parser_new": (INT, [P, S, OUT]),
|
|
58
|
+
"jnt_parser_free": (None, [P]),
|
|
59
|
+
"jnt_parser_language": (P, [P, LEN]),
|
|
60
|
+
"jnt_parser_blind": (U, [P]),
|
|
61
|
+
"jnt_parse": (INT, [P, S, Z, OUT]),
|
|
62
|
+
"jnt_tree_free": (None, [P]),
|
|
63
|
+
"jnt_tree_stop": (INT, [P]),
|
|
64
|
+
"jnt_tree_stop_at": (U, [P]),
|
|
65
|
+
"jnt_tree_mends": (U, [P]),
|
|
66
|
+
"jnt_tree_skipped": (U, [P]),
|
|
67
|
+
"jnt_tree_supplied": (U, [P]),
|
|
68
|
+
"jnt_tree_scars": (U, [P]),
|
|
69
|
+
"jnt_tree_scar": (INT, [P, U, c.POINTER(NativeScar)]),
|
|
70
|
+
"jnt_tree_scar_word": (P, [P, U, LEN]),
|
|
71
|
+
"jnt_tree_sound": (INT, [P]),
|
|
72
|
+
"jnt_tree_roots": (U, [P]),
|
|
73
|
+
"jnt_tree_root": (U, [P, U]),
|
|
74
|
+
"jnt_tree_sexp": (P, [P, INT, LEN]),
|
|
75
|
+
"jnt_node_name": (P, [P, U, LEN]),
|
|
76
|
+
"jnt_node_field": (P, [P, U, LEN]),
|
|
77
|
+
"jnt_node_named": (INT, [P, U]),
|
|
78
|
+
"jnt_node_kid": (U, [P, U, U]),
|
|
79
|
+
"jnt_node_by_field": (U, [P, U, S, Z]),
|
|
80
|
+
"jnt_query_compile": (INT, [P, S, Z, OUT]),
|
|
81
|
+
"jnt_query_free": (None, [P]),
|
|
82
|
+
"jnt_query_pattern_count": (U, [P]),
|
|
83
|
+
"jnt_query_capture_count": (U, [P]),
|
|
84
|
+
"jnt_query_capture_name": (P, [P, U, LEN]),
|
|
85
|
+
"jnt_query_exec": (INT, [P, P, S, Z, INT, OUT]),
|
|
86
|
+
"jnt_query_result_free": (None, [P]),
|
|
87
|
+
"jnt_query_result_count": (U, [P]),
|
|
88
|
+
"jnt_query_result_pattern": (U, [P, U]),
|
|
89
|
+
"jnt_query_result_capture_count": (U, [P, U]),
|
|
90
|
+
"jnt_query_result_capture_id": (U, [P, U, U]),
|
|
91
|
+
"jnt_query_result_capture_node": (U, [P, U, U]),
|
|
92
|
+
}
|
|
93
|
+
for suffix in (
|
|
94
|
+
"start",
|
|
95
|
+
"end",
|
|
96
|
+
"kids",
|
|
97
|
+
"parent",
|
|
98
|
+
"next",
|
|
99
|
+
"prev",
|
|
100
|
+
"next_named",
|
|
101
|
+
"prev_named",
|
|
102
|
+
):
|
|
103
|
+
signatures[f"jnt_node_{suffix}"] = (U, [P, U])
|
|
104
|
+
for symbol, (result, args) in signatures.items():
|
|
105
|
+
try:
|
|
106
|
+
fn = getattr(lib, symbol)
|
|
107
|
+
except AttributeError as error:
|
|
108
|
+
raise OSError(
|
|
109
|
+
f"libjnt lacks {symbol}; rebuild it with query support"
|
|
110
|
+
) from error
|
|
111
|
+
fn.restype, fn.argtypes = result, args
|
|
112
|
+
if lib.jnt_abi_version() != 2:
|
|
113
|
+
raise OSError("this binding requires libjnt ABI version 2")
|
|
114
|
+
return lib
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# The Python interface uses ctypes over a separately supplied libjnt.
|
|
2
|
+
# Native archives are distributed separately from the portable Python package.
|
|
3
|
+
|
|
4
|
+
[build-system]
|
|
5
|
+
requires = [ "hatchling>=1.27" ]
|
|
6
|
+
build-backend = "hatchling.build"
|
|
7
|
+
|
|
8
|
+
[project]
|
|
9
|
+
name = "joints"
|
|
10
|
+
version = "0.1.0" # x-release-please-version
|
|
11
|
+
# Says what the project is, then what this version is not, in that order. PyPI
|
|
12
|
+
# renders this line in search results where a caveat further down never reaches
|
|
13
|
+
# the reader deciding whether to install.
|
|
14
|
+
description = "Experimental parsing and structural queries over grammar data, with Python bindings to libjnt."
|
|
15
|
+
readme = "README.md"
|
|
16
|
+
# Not caution, and not the eventual binding's floor discovered by testing: it is
|
|
17
|
+
# the floor the sibling packages hold, and admitting interpreters this project
|
|
18
|
+
# will not test against is a promise nobody here intends to keep. It can only
|
|
19
|
+
# move down later, which is the harmless direction.
|
|
20
|
+
requires-python = ">=3.12"
|
|
21
|
+
license = "Apache-2.0"
|
|
22
|
+
license-files = [ "LICENSE", "NOTICE" ]
|
|
23
|
+
authors = [ { name = "The Billy Company" } ]
|
|
24
|
+
# PyPI scores name, summary and keywords together, so these are the words
|
|
25
|
+
# somebody types when they have the problem this solves rather than a
|
|
26
|
+
# restatement of the name.
|
|
27
|
+
keywords = [ "parser", "parsing", "incremental", "tree-sitter", "cst", "syntax-tree" ]
|
|
28
|
+
classifiers = [
|
|
29
|
+
# This interface is experimental; native distribution is still separate.
|
|
30
|
+
"Development Status :: 3 - Alpha",
|
|
31
|
+
"Intended Audience :: Developers",
|
|
32
|
+
"Programming Language :: Python :: 3",
|
|
33
|
+
"Topic :: Software Development :: Compilers",
|
|
34
|
+
"Topic :: Text Processing :: General",
|
|
35
|
+
]
|
|
36
|
+
# The engine is Zig; the interface is Python and ships no native binary yet.
|
|
37
|
+
# No `License ::` classifier: the SPDX `license` field above is PEP 639
|
|
38
|
+
# metadata, and the two spellings together are an error in current tooling
|
|
39
|
+
# rather than a belt and braces.
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://github.com/The-Billy-Company/joints"
|
|
43
|
+
Source = "https://github.com/The-Billy-Company/joints"
|
|
44
|
+
Documentation = "https://github.com/The-Billy-Company/joints/blob/main/bindings/python/README.md"
|
|
45
|
+
Changelog = "https://github.com/The-Billy-Company/joints/blob/main/CHANGELOG.md"
|
|
46
|
+
Issues = "https://github.com/The-Billy-Company/joints/issues"
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = [ "joints" ]
|
|
50
|
+
|
|
51
|
+
[tool.hatch.build.targets.sdist]
|
|
52
|
+
# Explicit rather than "whatever is in the directory", so a stray virtualenv or
|
|
53
|
+
# a build cache cannot ride along into a published artifact.
|
|
54
|
+
include = [ "joints", "README.md", "LICENSE", "NOTICE", "pyproject.toml" ]
|