syntax-import 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.
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ build/
4
+ dist/
5
+ *.egg-info/
6
+ .venv/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HaoHua Huang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,247 @@
1
+ Metadata-Version: 2.5
2
+ Name: syntax-import
3
+ Version: 0.1.0
4
+ Summary: Run Python files extended by a single top-level `syntax import` directive that rewrites the source text and AST, with tracebacks mapped back to the original lines.
5
+ Project-URL: Repository, https://github.com/Locked-chess-official/syntax-import
6
+ Author: HaoHua Huang
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: ast,dsl,import hook,macro,source transformation,syntax,transpiler
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Compilers
21
+ Classifier: Topic :: Software Development :: Interpreters
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # syntax-import
27
+
28
+ Run "extended Python" files: the body is ordinary Python, but the file may start with **one**
29
+ `syntax import package.module` directive naming a *syntax module* that rewrites the source text
30
+ and the AST before compilation. Tracebacks and syntax errors point at the lines of the original
31
+ file. Pure standard library, Python 3.9+.
32
+
33
+ ```python
34
+ #!/usr/bin/env python3
35
+ """Optional module docstring."""
36
+ # comments are fine
37
+ syntax import syntax_import.examples.combo
38
+ from __future__ import annotations
39
+
40
+ items = [3, 1, 2]
41
+ unless items |> len:
42
+ print("empty list")
43
+ ```
44
+
45
+ ```bash
46
+ pip install syntax-import
47
+ syntax-import script.spy arg1 arg2 # or: python -m syntax_import script.spy arg1 arg2
48
+ ```
49
+
50
+ ## 1. Directive rules
51
+
52
+ | Rule | On violation |
53
+ | --- | --- |
54
+ | Form: `syntax import package.module` (trailing comment and backslash continuation allowed) | `DirectiveError` |
55
+ | Must be the first statement: only blank lines, comments (incl. shebang and encoding cookie) and at most one module docstring may precede it; it must not be indented | `DirectiveError` |
56
+ | Must come before every `from __future__ import` | `DirectiveError` |
57
+ | At most one per file, naming exactly one module (`syntax import a, b` is rejected) | `DirectiveError` |
58
+ | Files without a directive | run as plain Python |
59
+
60
+ `DirectiveError` is a subclass of `SyntaxError` and carries the correct file name, line number
61
+ and offending line. The text `syntax import` inside string literals is never mistaken for a directive.
62
+
63
+ **How the directive line is removed: it is blanked.** The physical line(s) of the directive are
64
+ replaced by empty lines (only the line ending is kept), so the `text` handed to the editor has the
65
+ same number of lines as the file and line numbers match one-to-one without any extra mapping.
66
+ Module docstrings and `from __future__` imports stay valid.
67
+
68
+ ## 2. The syntax module contract
69
+
70
+ A syntax module is an ordinary module (pure Python or a C extension) and can be imported normally.
71
+ To be used with `syntax import` it must export:
72
+
73
+ ```python
74
+ def text_editor(text: str, original_text: str, context: dict) -> tuple[str, LineMapLike]: ...
75
+ def ast_editor(tree: ast.Module, line_map: LineMap, context: dict) -> ast.Module | None: ...
76
+ ```
77
+
78
+ If either is missing (or not callable), `SyntaxModuleError` (a subclass of `ImportError`) is raised.
79
+
80
+ ### text_editor(text, original_text, context)
81
+
82
+ * `text`: the code to rewrite (directive line already blanked).
83
+ * `original_text`: the original code. **At top level `text == original_text` and `context == {}`**;
84
+ when called by a composite module, `text` is the output of the previous step and `context`
85
+ carries delegation information (see section 4).
86
+ * Returns `(new_text, line_map)`. `line_map` maps **lines of new_text -> lines of the received
87
+ `text`** and may be:
88
+ * `None`: identity (line structure unchanged);
89
+ * a `dict` `{new_lineno: old_lineno or None}`; `None` / unlisted lines are synthesized lines;
90
+ * a `list`/`tuple`: `seq[i]` is the old line of new line `i + 1`;
91
+ * a `LineMap`.
92
+ * May raise `SyntaxError` with line numbers of the received `text`; the framework fills in the
93
+ file name and converts the line numbers.
94
+
95
+ ### ast_editor(tree, line_map, context)
96
+
97
+ * `tree`: result of `ast.parse(new_text)`; node positions refer to **new_text**.
98
+ * `line_map`: a `LineMap` mapping **tree lines -> original lines** (file lines at top level).
99
+ * `context`: the **same dict** the `text_editor` received, so information can flow between stages.
100
+ * Returns a new `ast.Module`, or `None` for in-place edits. An editor that only accepts
101
+ `(tree, line_map)` is supported too; for callables without an inspectable signature (typical of
102
+ C functions) three arguments are tried first, then two on an argument-count `TypeError`.
103
+ * Synthesized nodes need no positions: the framework calls `fix_missing_locations` and then remaps.
104
+
105
+ ### LineMap
106
+
107
+ `LineMap.get(n)` is an exact lookup; `LineMap.resolve(n)` falls back to the nearest preceding
108
+ mapped line (so synthesized lines point at the line that produced them); `a.compose(b)` composes
109
+ maps (C->B with B->A gives C->A).
110
+
111
+ ## 3. Pipeline and tracebacks
112
+
113
+ ```
114
+ read source (honouring the encoding cookie) -> validate and blank the directive -> import syntax module
115
+ -> text_editor(text, text, {}) -> ast.parse(new_text) -> ast_editor(tree, line_map, context)
116
+ -> fix_missing_locations -> remap node lines to the original file -> compile -> exec in a fresh module
117
+ ```
118
+
119
+ The `show` option controls what tracebacks display:
120
+
121
+ * `show="original"` (default): every AST node is remapped to original file lines, so tracebacks
122
+ show **the code of the real file**. When a line was changed by the transformation, column offsets
123
+ are widened to the whole line so carets never point at the wrong place. `SyntaxError`s from
124
+ `ast.parse`, from the `ast_editor` and from `compile` are remapped as well, with a note
125
+ "transformed code line N: ...".
126
+ * `show="modified"`: line numbers of the modified code are kept and the modified code is
127
+ registered in `linecache` under the pseudo file name `"<file> <syntax import module>"`, so
128
+ tracebacks show **the modified code**. CLI flag: `--show-modified`.
129
+
130
+ ## 4. Delegation: combining several syntaxes
131
+
132
+ A file can only have one `syntax import`. To combine syntaxes, write a new composite syntax module
133
+ that delegates:
134
+
135
+ ```python
136
+ # mysyntax.py
137
+ from syntax_import import delegate_text, delegate_ast
138
+ from syntax_import.examples import pipe, unless
139
+
140
+ MODULES = [pipe, unless] # the order is part of conflict resolution
141
+
142
+ def text_editor(text, original_text, context):
143
+ return delegate_text(MODULES, text, original_text, context)
144
+
145
+ def ast_editor(tree, line_map, context):
146
+ return delegate_ast(MODULES, tree, line_map, context)
147
+
148
+ # or in one line: text_editor, ast_editor = make_composite(pipe, unless)
149
+ ```
150
+
151
+ `delegate_text` calls each sub-module's `text_editor` in turn: each receives the previous output,
152
+ the **same** `original_text` and a fresh sub-context; the line maps of all steps are composed
153
+ automatically and the result follows the `text_editor` contract. A `SyntaxError` raised by a
154
+ sub-module is converted to line numbers of the composite's input. `delegate_ast` calls the
155
+ `ast_editor`s in turn (`reverse=True` for reverse order), giving each sub-module back the context
156
+ it used in the text stage. Delegation can be nested.
157
+
158
+ Context received by a sub-module:
159
+
160
+ | Key | Meaning |
161
+ | --- | --- |
162
+ | `delegator` | name of the delegating composite module |
163
+ | `delegation_chain` | delegators from the outermost one down to the current composite |
164
+ | `index` / `modules` | index of the current sub-module / names of all sub-modules |
165
+ | `line_map` | `LineMap`: text received by this sub-module -> `original_text` |
166
+ | `previous_steps` | `DelegationStep`s of earlier steps (input, output, maps) |
167
+ | `parent_context` | the context the composite itself received |
168
+ | `shared` | a dict shared across all levels, for negotiation between modules |
169
+ | `stage` | `"text"` or `"ast"` |
170
+
171
+ ### Resolving conflicts
172
+
173
+ * **Ordering**: in `examples/combo.py`, `unless` needs the colon on the same logical line while
174
+ `pipe` allows `|>` continuation lines, so `pipe` must run before `unless` (the other order fails
175
+ with "missing a colon").
176
+ * **Hooks**: `delegate_text(..., before=f, after=g)`
177
+ * `before(index, module, text, sub_context)`: rewrite a sub-module's input before it runs;
178
+ * `after(step)`: inspect / rewrite its output afterwards (`step` is a `DelegationStep`);
179
+ * return `None` (unchanged), a `str` (same line structure) or `(str, line_map)` (new text -> text received by the hook).
180
+ * `delegate_ast(..., before=, after=)` hooks take `(index, module, tree, sub_context)` and return a new tree or None.
181
+ * **Full control**: a composite module is itself an ordinary syntax module and may do anything
182
+ before or after delegating.
183
+
184
+ ## 5. Usage
185
+
186
+ Command line:
187
+
188
+ ```bash
189
+ syntax-import file.spy [args...] # sys.argv = ['file.spy', args...], __name__ == '__main__'
190
+ syntax-import --show-modified file.spy
191
+ syntax-import --dump file.spy # print transformed code with "new line -> original line"; do not run
192
+ syntax-import --ext .xpy file.xpy # extension recognized by the import hook (default .spy)
193
+ syntax-import --no-color file.spy # disable color in tracebacks
194
+ ```
195
+
196
+ The CLI adds the script's directory to `sys.path` and installs the import hook, so a script can
197
+ `import` neighbouring `.spy` modules.
198
+
199
+ API:
200
+
201
+ ```python
202
+ import syntax_import as si
203
+
204
+ si.run_file("a.spy", argv=["a.spy", "x"]) # returns the module namespace dict
205
+ si.run_source(code_str, "<snippet>") # source string (registered in linecache)
206
+ code = si.compile_source(code_str, "a.spy") # just the code object
207
+ res = si.transform(code_str, "a.spy", show="modified") # new_text / line_map / tree / code
208
+ si.install_import_hook((".spy",)) # afterwards `import xxx` loads xxx.spy or xxx/__init__.spy
209
+ si.get_current_source() # inside an editor: current file and syntax module name
210
+ ```
211
+
212
+ The import hook follows `sys.path` order; a regular `.py` module or package of the same name in
213
+ the same directory takes precedence.
214
+
215
+ ## 6. Examples (`syntax_import/examples/`, installed with the package)
216
+
217
+ | File | Description |
218
+ | --- | --- |
219
+ | `unless.py` | text level: `unless cond:` -> `if not (cond):`, identity line map |
220
+ | `pipe.py` | text + AST level: `x \|> f` -> `f(x)`, `x \|> f(a, _)` -> `f(a, x)`; `\|>` continuation lines (fewer lines, non-identity line map); uses the context to pass its marker between stages |
221
+ | `combo.py` | composite module delegating to pipe and unless; shows an ordering conflict and an `after` hook |
222
+ | `*.spy` | scripts: `hello_unless`, `hello_pipe`, `hello_combo`, `error_demo` (traceback line mapping), `use_import_hook` + `mathutils` |
223
+
224
+ ```bash
225
+ EX=$(python -c "import os, syntax_import.examples as e; print(os.path.dirname(e.__file__))")
226
+ syntax-import "$EX/hello_combo.spy"
227
+ syntax-import "$EX/error_demo.spy" # traceback points at lines 13 and 5 of the original file
228
+ ```
229
+
230
+ ## 7. Tests
231
+
232
+ From a source checkout:
233
+
234
+ ```bash
235
+ pip install .
236
+ python -m unittest discover -s tests -t .
237
+ ```
238
+
239
+ ## 8. Limitations
240
+
241
+ * Before calling `text_editor` the framework scans for the directive with `tokenize`; if the custom
242
+ syntax makes `tokenize` fail, the rest of the file is scanned line by line with a regex.
243
+ * In "original" mode, positions inside rewritten lines are only accurate to the line; the columns cover the whole line.
244
+
245
+ ## License
246
+
247
+ MIT
@@ -0,0 +1,222 @@
1
+ # syntax-import
2
+
3
+ Run "extended Python" files: the body is ordinary Python, but the file may start with **one**
4
+ `syntax import package.module` directive naming a *syntax module* that rewrites the source text
5
+ and the AST before compilation. Tracebacks and syntax errors point at the lines of the original
6
+ file. Pure standard library, Python 3.9+.
7
+
8
+ ```python
9
+ #!/usr/bin/env python3
10
+ """Optional module docstring."""
11
+ # comments are fine
12
+ syntax import syntax_import.examples.combo
13
+ from __future__ import annotations
14
+
15
+ items = [3, 1, 2]
16
+ unless items |> len:
17
+ print("empty list")
18
+ ```
19
+
20
+ ```bash
21
+ pip install syntax-import
22
+ syntax-import script.spy arg1 arg2 # or: python -m syntax_import script.spy arg1 arg2
23
+ ```
24
+
25
+ ## 1. Directive rules
26
+
27
+ | Rule | On violation |
28
+ | --- | --- |
29
+ | Form: `syntax import package.module` (trailing comment and backslash continuation allowed) | `DirectiveError` |
30
+ | Must be the first statement: only blank lines, comments (incl. shebang and encoding cookie) and at most one module docstring may precede it; it must not be indented | `DirectiveError` |
31
+ | Must come before every `from __future__ import` | `DirectiveError` |
32
+ | At most one per file, naming exactly one module (`syntax import a, b` is rejected) | `DirectiveError` |
33
+ | Files without a directive | run as plain Python |
34
+
35
+ `DirectiveError` is a subclass of `SyntaxError` and carries the correct file name, line number
36
+ and offending line. The text `syntax import` inside string literals is never mistaken for a directive.
37
+
38
+ **How the directive line is removed: it is blanked.** The physical line(s) of the directive are
39
+ replaced by empty lines (only the line ending is kept), so the `text` handed to the editor has the
40
+ same number of lines as the file and line numbers match one-to-one without any extra mapping.
41
+ Module docstrings and `from __future__` imports stay valid.
42
+
43
+ ## 2. The syntax module contract
44
+
45
+ A syntax module is an ordinary module (pure Python or a C extension) and can be imported normally.
46
+ To be used with `syntax import` it must export:
47
+
48
+ ```python
49
+ def text_editor(text: str, original_text: str, context: dict) -> tuple[str, LineMapLike]: ...
50
+ def ast_editor(tree: ast.Module, line_map: LineMap, context: dict) -> ast.Module | None: ...
51
+ ```
52
+
53
+ If either is missing (or not callable), `SyntaxModuleError` (a subclass of `ImportError`) is raised.
54
+
55
+ ### text_editor(text, original_text, context)
56
+
57
+ * `text`: the code to rewrite (directive line already blanked).
58
+ * `original_text`: the original code. **At top level `text == original_text` and `context == {}`**;
59
+ when called by a composite module, `text` is the output of the previous step and `context`
60
+ carries delegation information (see section 4).
61
+ * Returns `(new_text, line_map)`. `line_map` maps **lines of new_text -> lines of the received
62
+ `text`** and may be:
63
+ * `None`: identity (line structure unchanged);
64
+ * a `dict` `{new_lineno: old_lineno or None}`; `None` / unlisted lines are synthesized lines;
65
+ * a `list`/`tuple`: `seq[i]` is the old line of new line `i + 1`;
66
+ * a `LineMap`.
67
+ * May raise `SyntaxError` with line numbers of the received `text`; the framework fills in the
68
+ file name and converts the line numbers.
69
+
70
+ ### ast_editor(tree, line_map, context)
71
+
72
+ * `tree`: result of `ast.parse(new_text)`; node positions refer to **new_text**.
73
+ * `line_map`: a `LineMap` mapping **tree lines -> original lines** (file lines at top level).
74
+ * `context`: the **same dict** the `text_editor` received, so information can flow between stages.
75
+ * Returns a new `ast.Module`, or `None` for in-place edits. An editor that only accepts
76
+ `(tree, line_map)` is supported too; for callables without an inspectable signature (typical of
77
+ C functions) three arguments are tried first, then two on an argument-count `TypeError`.
78
+ * Synthesized nodes need no positions: the framework calls `fix_missing_locations` and then remaps.
79
+
80
+ ### LineMap
81
+
82
+ `LineMap.get(n)` is an exact lookup; `LineMap.resolve(n)` falls back to the nearest preceding
83
+ mapped line (so synthesized lines point at the line that produced them); `a.compose(b)` composes
84
+ maps (C->B with B->A gives C->A).
85
+
86
+ ## 3. Pipeline and tracebacks
87
+
88
+ ```
89
+ read source (honouring the encoding cookie) -> validate and blank the directive -> import syntax module
90
+ -> text_editor(text, text, {}) -> ast.parse(new_text) -> ast_editor(tree, line_map, context)
91
+ -> fix_missing_locations -> remap node lines to the original file -> compile -> exec in a fresh module
92
+ ```
93
+
94
+ The `show` option controls what tracebacks display:
95
+
96
+ * `show="original"` (default): every AST node is remapped to original file lines, so tracebacks
97
+ show **the code of the real file**. When a line was changed by the transformation, column offsets
98
+ are widened to the whole line so carets never point at the wrong place. `SyntaxError`s from
99
+ `ast.parse`, from the `ast_editor` and from `compile` are remapped as well, with a note
100
+ "transformed code line N: ...".
101
+ * `show="modified"`: line numbers of the modified code are kept and the modified code is
102
+ registered in `linecache` under the pseudo file name `"<file> <syntax import module>"`, so
103
+ tracebacks show **the modified code**. CLI flag: `--show-modified`.
104
+
105
+ ## 4. Delegation: combining several syntaxes
106
+
107
+ A file can only have one `syntax import`. To combine syntaxes, write a new composite syntax module
108
+ that delegates:
109
+
110
+ ```python
111
+ # mysyntax.py
112
+ from syntax_import import delegate_text, delegate_ast
113
+ from syntax_import.examples import pipe, unless
114
+
115
+ MODULES = [pipe, unless] # the order is part of conflict resolution
116
+
117
+ def text_editor(text, original_text, context):
118
+ return delegate_text(MODULES, text, original_text, context)
119
+
120
+ def ast_editor(tree, line_map, context):
121
+ return delegate_ast(MODULES, tree, line_map, context)
122
+
123
+ # or in one line: text_editor, ast_editor = make_composite(pipe, unless)
124
+ ```
125
+
126
+ `delegate_text` calls each sub-module's `text_editor` in turn: each receives the previous output,
127
+ the **same** `original_text` and a fresh sub-context; the line maps of all steps are composed
128
+ automatically and the result follows the `text_editor` contract. A `SyntaxError` raised by a
129
+ sub-module is converted to line numbers of the composite's input. `delegate_ast` calls the
130
+ `ast_editor`s in turn (`reverse=True` for reverse order), giving each sub-module back the context
131
+ it used in the text stage. Delegation can be nested.
132
+
133
+ Context received by a sub-module:
134
+
135
+ | Key | Meaning |
136
+ | --- | --- |
137
+ | `delegator` | name of the delegating composite module |
138
+ | `delegation_chain` | delegators from the outermost one down to the current composite |
139
+ | `index` / `modules` | index of the current sub-module / names of all sub-modules |
140
+ | `line_map` | `LineMap`: text received by this sub-module -> `original_text` |
141
+ | `previous_steps` | `DelegationStep`s of earlier steps (input, output, maps) |
142
+ | `parent_context` | the context the composite itself received |
143
+ | `shared` | a dict shared across all levels, for negotiation between modules |
144
+ | `stage` | `"text"` or `"ast"` |
145
+
146
+ ### Resolving conflicts
147
+
148
+ * **Ordering**: in `examples/combo.py`, `unless` needs the colon on the same logical line while
149
+ `pipe` allows `|>` continuation lines, so `pipe` must run before `unless` (the other order fails
150
+ with "missing a colon").
151
+ * **Hooks**: `delegate_text(..., before=f, after=g)`
152
+ * `before(index, module, text, sub_context)`: rewrite a sub-module's input before it runs;
153
+ * `after(step)`: inspect / rewrite its output afterwards (`step` is a `DelegationStep`);
154
+ * return `None` (unchanged), a `str` (same line structure) or `(str, line_map)` (new text -> text received by the hook).
155
+ * `delegate_ast(..., before=, after=)` hooks take `(index, module, tree, sub_context)` and return a new tree or None.
156
+ * **Full control**: a composite module is itself an ordinary syntax module and may do anything
157
+ before or after delegating.
158
+
159
+ ## 5. Usage
160
+
161
+ Command line:
162
+
163
+ ```bash
164
+ syntax-import file.spy [args...] # sys.argv = ['file.spy', args...], __name__ == '__main__'
165
+ syntax-import --show-modified file.spy
166
+ syntax-import --dump file.spy # print transformed code with "new line -> original line"; do not run
167
+ syntax-import --ext .xpy file.xpy # extension recognized by the import hook (default .spy)
168
+ syntax-import --no-color file.spy # disable color in tracebacks
169
+ ```
170
+
171
+ The CLI adds the script's directory to `sys.path` and installs the import hook, so a script can
172
+ `import` neighbouring `.spy` modules.
173
+
174
+ API:
175
+
176
+ ```python
177
+ import syntax_import as si
178
+
179
+ si.run_file("a.spy", argv=["a.spy", "x"]) # returns the module namespace dict
180
+ si.run_source(code_str, "<snippet>") # source string (registered in linecache)
181
+ code = si.compile_source(code_str, "a.spy") # just the code object
182
+ res = si.transform(code_str, "a.spy", show="modified") # new_text / line_map / tree / code
183
+ si.install_import_hook((".spy",)) # afterwards `import xxx` loads xxx.spy or xxx/__init__.spy
184
+ si.get_current_source() # inside an editor: current file and syntax module name
185
+ ```
186
+
187
+ The import hook follows `sys.path` order; a regular `.py` module or package of the same name in
188
+ the same directory takes precedence.
189
+
190
+ ## 6. Examples (`syntax_import/examples/`, installed with the package)
191
+
192
+ | File | Description |
193
+ | --- | --- |
194
+ | `unless.py` | text level: `unless cond:` -> `if not (cond):`, identity line map |
195
+ | `pipe.py` | text + AST level: `x \|> f` -> `f(x)`, `x \|> f(a, _)` -> `f(a, x)`; `\|>` continuation lines (fewer lines, non-identity line map); uses the context to pass its marker between stages |
196
+ | `combo.py` | composite module delegating to pipe and unless; shows an ordering conflict and an `after` hook |
197
+ | `*.spy` | scripts: `hello_unless`, `hello_pipe`, `hello_combo`, `error_demo` (traceback line mapping), `use_import_hook` + `mathutils` |
198
+
199
+ ```bash
200
+ EX=$(python -c "import os, syntax_import.examples as e; print(os.path.dirname(e.__file__))")
201
+ syntax-import "$EX/hello_combo.spy"
202
+ syntax-import "$EX/error_demo.spy" # traceback points at lines 13 and 5 of the original file
203
+ ```
204
+
205
+ ## 7. Tests
206
+
207
+ From a source checkout:
208
+
209
+ ```bash
210
+ pip install .
211
+ python -m unittest discover -s tests -t .
212
+ ```
213
+
214
+ ## 8. Limitations
215
+
216
+ * Before calling `text_editor` the framework scans for the directive with `tokenize`; if the custom
217
+ syntax makes `tokenize` fail, the rest of the file is scanned line by line with a regex.
218
+ * In "original" mode, positions inside rewritten lines are only accurate to the line; the columns cover the whole line.
219
+
220
+ ## License
221
+
222
+ MIT
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "syntax-import"
7
+ version = "0.1.0"
8
+ description = "Run Python files extended by a single top-level `syntax import` directive that rewrites the source text and AST, with tracebacks mapped back to the original lines."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "HaoHua Huang" }]
14
+ keywords = ["syntax", "ast", "transpiler", "macro", "import hook", "dsl", "source transformation"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Topic :: Software Development :: Compilers",
27
+ "Topic :: Software Development :: Interpreters",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ ]
30
+ dependencies = []
31
+
32
+ urls = { Repository = "https://github.com/Locked-chess-official/syntax-import" }
33
+
34
+ [project.scripts]
35
+ syntax-import = "syntax_import.__main__:main"
36
+
37
+ [tool.hatch.build]
38
+ packages = ["src/syntax_import"]
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ include = [
42
+ "src/syntax_import/**/*.py",
43
+ "src/syntax_import/examples/*.spy",
44
+ ]
45
+
46
+ [tool.hatch.build.targets.sdist]
47
+ include = [
48
+ "src/**/*.py",
49
+ "src/syntax_import/examples/*.spy",
50
+ "tests/**/*.py",
51
+ "pyproject.toml",
52
+ "README.md",
53
+ "LICENSE",
54
+ "MANIFEST.in",
55
+ ".gitignore",
56
+ ]
@@ -0,0 +1,55 @@
1
+ """syntax_import -- run "extended Python" code that starts with a ``syntax import`` directive.
2
+
3
+ Quick start::
4
+
5
+ python -m syntax_import script.spy [args...] # or: syntax-import script.spy
6
+
7
+ import syntax_import
8
+ syntax_import.run_file("script.spy")
9
+ syntax_import.install_import_hook() # afterwards ``import xxx`` can load xxx.spy
10
+
11
+ See README.md for details.
12
+ """
13
+
14
+ from .core import (
15
+ CurrentSource,
16
+ Directive,
17
+ DirectiveError,
18
+ SyntaxModuleError,
19
+ TransformResult,
20
+ call_ast_editor,
21
+ call_text_editor,
22
+ check_syntax_module,
23
+ compile_source,
24
+ exec_transformed,
25
+ get_current_source,
26
+ load_syntax_module,
27
+ modified_filename,
28
+ parse_directive,
29
+ remap_syntax_error,
30
+ remap_tree,
31
+ run_file,
32
+ run_source,
33
+ transform,
34
+ )
35
+ from .delegate import DelegationStep, delegate_ast, delegate_text, make_composite
36
+ from .importer import (
37
+ DEFAULT_EXTENSIONS,
38
+ SyntaxImportFinder,
39
+ SyntaxImportLoader,
40
+ install_import_hook,
41
+ uninstall_import_hook,
42
+ )
43
+ from .linemap import LineMap
44
+
45
+ __version__ = "0.1.0"
46
+
47
+ __all__ = [
48
+ "CurrentSource", "Directive", "DirectiveError", "SyntaxModuleError", "TransformResult",
49
+ "call_ast_editor", "call_text_editor", "check_syntax_module", "compile_source", "exec_transformed",
50
+ "get_current_source", "load_syntax_module", "modified_filename", "parse_directive",
51
+ "remap_syntax_error", "remap_tree", "run_file", "run_source", "transform",
52
+ "DelegationStep", "delegate_ast", "delegate_text", "make_composite",
53
+ "DEFAULT_EXTENSIONS", "SyntaxImportFinder", "SyntaxImportLoader",
54
+ "install_import_hook", "uninstall_import_hook", "LineMap",
55
+ ]