Metadata-Version: 2.5
Name: syntax-import
Version: 0.1.0
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.
Project-URL: Repository, https://github.com/Locked-chess-official/syntax-import
Author: HaoHua Huang
License-Expression: MIT
License-File: LICENSE
Keywords: ast,dsl,import hook,macro,source transformation,syntax,transpiler
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Compilers
Classifier: Topic :: Software Development :: Interpreters
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# syntax-import

Run "extended Python" files: the body is ordinary Python, but the file may start with **one**
`syntax import package.module` directive naming a *syntax module* that rewrites the source text
and the AST before compilation. Tracebacks and syntax errors point at the lines of the original
file. Pure standard library, Python 3.9+.

```python
#!/usr/bin/env python3
"""Optional module docstring."""
# comments are fine
syntax import syntax_import.examples.combo
from __future__ import annotations

items = [3, 1, 2]
unless items |> len:
    print("empty list")
```

```bash
pip install syntax-import
syntax-import script.spy arg1 arg2          # or: python -m syntax_import script.spy arg1 arg2
```

## 1. Directive rules

| Rule | On violation |
| --- | --- |
| Form: `syntax import package.module` (trailing comment and backslash continuation allowed) | `DirectiveError` |
| 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` |
| Must come before every `from __future__ import` | `DirectiveError` |
| At most one per file, naming exactly one module (`syntax import a, b` is rejected) | `DirectiveError` |
| Files without a directive | run as plain Python |

`DirectiveError` is a subclass of `SyntaxError` and carries the correct file name, line number
and offending line. The text `syntax import` inside string literals is never mistaken for a directive.

**How the directive line is removed: it is blanked.** The physical line(s) of the directive are
replaced by empty lines (only the line ending is kept), so the `text` handed to the editor has the
same number of lines as the file and line numbers match one-to-one without any extra mapping.
Module docstrings and `from __future__` imports stay valid.

## 2. The syntax module contract

A syntax module is an ordinary module (pure Python or a C extension) and can be imported normally.
To be used with `syntax import` it must export:

```python
def text_editor(text: str, original_text: str, context: dict) -> tuple[str, LineMapLike]: ...
def ast_editor(tree: ast.Module, line_map: LineMap, context: dict) -> ast.Module | None: ...
```

If either is missing (or not callable), `SyntaxModuleError` (a subclass of `ImportError`) is raised.

### text_editor(text, original_text, context)

* `text`: the code to rewrite (directive line already blanked).
* `original_text`: the original code. **At top level `text == original_text` and `context == {}`**;
  when called by a composite module, `text` is the output of the previous step and `context`
  carries delegation information (see section 4).
* Returns `(new_text, line_map)`. `line_map` maps **lines of new_text -> lines of the received
  `text`** and may be:
  * `None`: identity (line structure unchanged);
  * a `dict` `{new_lineno: old_lineno or None}`; `None` / unlisted lines are synthesized lines;
  * a `list`/`tuple`: `seq[i]` is the old line of new line `i + 1`;
  * a `LineMap`.
* May raise `SyntaxError` with line numbers of the received `text`; the framework fills in the
  file name and converts the line numbers.

### ast_editor(tree, line_map, context)

* `tree`: result of `ast.parse(new_text)`; node positions refer to **new_text**.
* `line_map`: a `LineMap` mapping **tree lines -> original lines** (file lines at top level).
* `context`: the **same dict** the `text_editor` received, so information can flow between stages.
* Returns a new `ast.Module`, or `None` for in-place edits. An editor that only accepts
  `(tree, line_map)` is supported too; for callables without an inspectable signature (typical of
  C functions) three arguments are tried first, then two on an argument-count `TypeError`.
* Synthesized nodes need no positions: the framework calls `fix_missing_locations` and then remaps.

### LineMap

`LineMap.get(n)` is an exact lookup; `LineMap.resolve(n)` falls back to the nearest preceding
mapped line (so synthesized lines point at the line that produced them); `a.compose(b)` composes
maps (C->B with B->A gives C->A).

## 3. Pipeline and tracebacks

```
read source (honouring the encoding cookie) -> validate and blank the directive -> import syntax module
-> text_editor(text, text, {}) -> ast.parse(new_text) -> ast_editor(tree, line_map, context)
-> fix_missing_locations -> remap node lines to the original file -> compile -> exec in a fresh module
```

The `show` option controls what tracebacks display:

* `show="original"` (default): every AST node is remapped to original file lines, so tracebacks
  show **the code of the real file**. When a line was changed by the transformation, column offsets
  are widened to the whole line so carets never point at the wrong place. `SyntaxError`s from
  `ast.parse`, from the `ast_editor` and from `compile` are remapped as well, with a note
  "transformed code line N: ...".
* `show="modified"`: line numbers of the modified code are kept and the modified code is
  registered in `linecache` under the pseudo file name `"<file> <syntax import module>"`, so
  tracebacks show **the modified code**. CLI flag: `--show-modified`.

## 4. Delegation: combining several syntaxes

A file can only have one `syntax import`. To combine syntaxes, write a new composite syntax module
that delegates:

```python
# mysyntax.py
from syntax_import import delegate_text, delegate_ast
from syntax_import.examples import pipe, unless

MODULES = [pipe, unless]          # the order is part of conflict resolution

def text_editor(text, original_text, context):
    return delegate_text(MODULES, text, original_text, context)

def ast_editor(tree, line_map, context):
    return delegate_ast(MODULES, tree, line_map, context)

# or in one line: text_editor, ast_editor = make_composite(pipe, unless)
```

`delegate_text` calls each sub-module's `text_editor` in turn: each receives the previous output,
the **same** `original_text` and a fresh sub-context; the line maps of all steps are composed
automatically and the result follows the `text_editor` contract. A `SyntaxError` raised by a
sub-module is converted to line numbers of the composite's input. `delegate_ast` calls the
`ast_editor`s in turn (`reverse=True` for reverse order), giving each sub-module back the context
it used in the text stage. Delegation can be nested.

Context received by a sub-module:

| Key | Meaning |
| --- | --- |
| `delegator` | name of the delegating composite module |
| `delegation_chain` | delegators from the outermost one down to the current composite |
| `index` / `modules` | index of the current sub-module / names of all sub-modules |
| `line_map` | `LineMap`: text received by this sub-module -> `original_text` |
| `previous_steps` | `DelegationStep`s of earlier steps (input, output, maps) |
| `parent_context` | the context the composite itself received |
| `shared` | a dict shared across all levels, for negotiation between modules |
| `stage` | `"text"` or `"ast"` |

### Resolving conflicts

* **Ordering**: in `examples/combo.py`, `unless` needs the colon on the same logical line while
  `pipe` allows `|>` continuation lines, so `pipe` must run before `unless` (the other order fails
  with "missing a colon").
* **Hooks**: `delegate_text(..., before=f, after=g)`
  * `before(index, module, text, sub_context)`: rewrite a sub-module's input before it runs;
  * `after(step)`: inspect / rewrite its output afterwards (`step` is a `DelegationStep`);
  * return `None` (unchanged), a `str` (same line structure) or `(str, line_map)` (new text -> text received by the hook).
  * `delegate_ast(..., before=, after=)` hooks take `(index, module, tree, sub_context)` and return a new tree or None.
* **Full control**: a composite module is itself an ordinary syntax module and may do anything
  before or after delegating.

## 5. Usage

Command line:

```bash
syntax-import file.spy [args...]          # sys.argv = ['file.spy', args...], __name__ == '__main__'
syntax-import --show-modified file.spy
syntax-import --dump file.spy             # print transformed code with "new line -> original line"; do not run
syntax-import --ext .xpy file.xpy         # extension recognized by the import hook (default .spy)
syntax-import --no-color file.spy         # disable color in tracebacks
```

The CLI adds the script's directory to `sys.path` and installs the import hook, so a script can
`import` neighbouring `.spy` modules.

API:

```python
import syntax_import as si

si.run_file("a.spy", argv=["a.spy", "x"])        # returns the module namespace dict
si.run_source(code_str, "<snippet>")             # source string (registered in linecache)
code = si.compile_source(code_str, "a.spy")      # just the code object
res = si.transform(code_str, "a.spy", show="modified")  # new_text / line_map / tree / code
si.install_import_hook((".spy",))                # afterwards `import xxx` loads xxx.spy or xxx/__init__.spy
si.get_current_source()                          # inside an editor: current file and syntax module name
```

The import hook follows `sys.path` order; a regular `.py` module or package of the same name in
the same directory takes precedence.

## 6. Examples (`syntax_import/examples/`, installed with the package)

| File | Description |
| --- | --- |
| `unless.py` | text level: `unless cond:` -> `if not (cond):`, identity line map |
| `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 |
| `combo.py` | composite module delegating to pipe and unless; shows an ordering conflict and an `after` hook |
| `*.spy` | scripts: `hello_unless`, `hello_pipe`, `hello_combo`, `error_demo` (traceback line mapping), `use_import_hook` + `mathutils` |

```bash
EX=$(python -c "import os, syntax_import.examples as e; print(os.path.dirname(e.__file__))")
syntax-import "$EX/hello_combo.spy"
syntax-import "$EX/error_demo.spy"     # traceback points at lines 13 and 5 of the original file
```

## 7. Tests

From a source checkout:

```bash
pip install .
python -m unittest discover -s tests -t .
```

## 8. Limitations

* Before calling `text_editor` the framework scans for the directive with `tokenize`; if the custom
  syntax makes `tokenize` fail, the rest of the file is scanned line by line with a regex.
* In "original" mode, positions inside rewritten lines are only accurate to the line; the columns cover the whole line.

## License

MIT
