diff options
| author | Bobby <[email protected]> | 2026-07-10 16:59:00 +0530 |
|---|---|---|
| committer | GitHub <[email protected]> | 2026-07-10 16:59:00 +0530 |
| commit | 189bcdabe3865a0d52aea580d3fdbcc1cd48e896 (patch) | |
| tree | 8db00421de426b98a86d4b65665c71be7adcf0bf /tests/errors/context.test.py | |
| parent | c757ea1fea447df3ed69e74b407ca9710a9f85e0 (diff) | |
| parent | 174eb521850550830d97994719ca3d09c467cb5a (diff) | |
| download | edify-189bcdabe3865a0d52aea580d3fdbcc1cd48e896.tar.xz edify-189bcdabe3865a0d52aea580d3fdbcc1cd48e896.zip | |
feat: regex introspection API — explain, verbose export, ASCII + SVG visualize + annotated errors (#272)
Ships the regex introspection API on the `Regex` wrapper — three new
methods that turn a compiled pattern into something a human can read,
plus a full retrofit of every error message to a shape that shows the
caller *where* the failure happened and *how* to fix it.
## `Regex.explain()`
Plain-English bullet list of what the pattern accepts, followed by a
small set of concrete accepted strings.
```
- The text must start with either "http" or "https".
- Then the text must have "://".
- Then the text must have one or more letters, digits, or underscores.
Text this pattern accepts:
http://ab1
https://b1_c
http://1_c2d
```
## `Regex.to_verbose_string()`
An `re.VERBOSE`-compatible export where every fragment is annotated
inline. Copy-pasting the output into `re.compile(..., re.VERBOSE)`
compiles to the same pattern.
```
(?P<year> # begin group named "year"
\d{4} # exactly 4
) # end group named "year"
```
## `Regex.visualize(format='ascii')`
ASCII railroad diagram — `START` and `END` boxes flanking the pattern,
arrows between elements, fork/merge junctions for alternation,
dashed-caption blocks for captures and lookarounds.
```
+--------+
+--->| "cat" |----+
| +--------+ |
| |
+-------+ | +--------+ | +-----+
| START |------>+--->| "dog" |----+-->| END |
+-------+ | +--------+ | +-----+
| |
| +--------+ |
+--->| "fish" |----+
+--------+
```
## `Regex.visualize(format='svg', engine='graphviz')`
SVG rendered by Graphviz. Junction-point fork/merge for alternation,
dashed rounded clusters for captures/lookarounds, folded two-line node
labels for quantifiers (e.g. `digit\n(one or more)`). Requires the
optional `graphviz` extra; the missing-dependency error names the
install command.
## Annotated error messages
Every exception across `edify.errors` — anchors, captures, input,
internal, naming, quantifier, structure — now emits a message that names
the offending call in the caller's source, explains the invariant that
was violated, and prescribes the fix:
```
error: start_of_input has already been added to this pattern
--> user_code.py:14:26
|
14 | pattern = RegexBuilder().start_of_input().digit().start_of_input()
| ^^^^^^^^^^^^^^^^ second start_of_input added here
|
= note: a pattern can carry at most one start_of_input anchor; the earlier .start_of_input() call already set it.
help: remove the duplicate .start_of_input() call from the chain.
```
Caller source location is captured via `sys._getframe()` walking to the
first non-edify frame and `co_positions()` for precise column spans.
## Other landings
- `Regex` retains the AST elements the builder produced; every
introspection method operates on the AST directly rather than parsing
the emitted regex string.
- Lazy compile cache on `BuilderCore` — a builder's `to_regex()` result
is memoised so `.match()` / `.search()` / `.explain()` share one
compiled pattern.
- `Regex.__getattr__` delegates any attribute not on the wrapper to the
underlying `re.Pattern`, so `.pattern`, `.flags`, `.groups`,
`.groupindex` continue to work.
- `Regex.__eq__` / `Regex.__hash__` raise when called on an unfinished
builder, pointing at both the compare/hash call site and the still-open
frame or dangling quantifier.
- Property test extended: every recursively-built composition of
quantifiers, groups, captures, named captures, and subexpressions emits
its expected regex exactly, no fragment dropped or duplicated.
Diffstat (limited to 'tests/errors/context.test.py')
| -rw-r--r-- | tests/errors/context.test.py | 107 |
1 files changed, 107 insertions, 0 deletions
diff --git a/tests/errors/context.test.py b/tests/errors/context.test.py new file mode 100644 index 0000000..fff9e09 --- /dev/null +++ b/tests/errors/context.test.py @@ -0,0 +1,107 @@ +"""Tests for the caller-source-location capture helpers in :mod:`edify.errors.context`.""" + +from unittest import mock + +from edify.errors.context import ( + CallerContext, + _context_for_frame, + capture_caller_context, +) + + +class _FakeCode: + """A stand-in for ``types.CodeType`` used to force specific ``co_positions`` behaviour.""" + + def __init__(self, filename: str, positions: list[tuple]) -> None: + self.co_filename = filename + self._positions = list(positions) + + def co_positions(self): + return iter(self._positions) + + +class _FakeFrame: + """A stand-in for ``types.FrameType`` shaped for :func:`_context_for_frame`.""" + + def __init__( + self, + filename: str, + f_lineno: int, + f_lasti: int, + positions: list[tuple], + ) -> None: + self.f_code = _FakeCode(filename, positions) + self.f_lineno = f_lineno + self.f_lasti = f_lasti + + +def test_capture_caller_context_returns_none_when_every_frame_is_inside_edify(): + with mock.patch("edify.errors.context.sys._getframe", return_value=None): + assert capture_caller_context() is None + + +def test_context_for_frame_uses_lineno_fallback_when_instruction_index_out_of_range(): + frame = _FakeFrame( + filename="/tmp/fake.py", + f_lineno=42, + f_lasti=999, + positions=[], + ) + context = _context_for_frame(frame) + assert context.lineno == 42 + assert context.colno == 1 + assert context.end_colno == 1 + + +def test_context_for_frame_defaults_start_line_when_position_start_line_is_none(): + frame = _FakeFrame( + filename="/tmp/fake.py", + f_lineno=99, + f_lasti=0, + positions=[(None, None, None, None)], + ) + context = _context_for_frame(frame) + assert context.lineno == 99 + + +def test_context_for_frame_defaults_end_line_when_position_end_line_is_none(): + frame = _FakeFrame( + filename="/tmp/fake.py", + f_lineno=7, + f_lasti=0, + positions=[(5, None, 2, 4)], + ) + context = _context_for_frame(frame) + assert context.lineno == 5 + assert context.colno == 3 + assert context.end_colno == 5 + + +def test_context_for_frame_defaults_start_col_when_position_start_col_is_none(): + frame = _FakeFrame( + filename="/tmp/fake.py", + f_lineno=1, + f_lasti=0, + positions=[(1, 1, None, 5)], + ) + context = _context_for_frame(frame) + assert context.colno == 1 + assert context.end_colno == 6 + + +def test_context_for_frame_defaults_end_col_when_position_end_col_is_none(): + frame = _FakeFrame( + filename="/tmp/fake.py", + f_lineno=1, + f_lasti=0, + positions=[(1, 1, 3, None)], + ) + context = _context_for_frame(frame) + assert context.colno == 4 + assert context.end_colno == 4 + + +def test_caller_context_dataclass_is_frozen_and_holds_all_five_fields(): + context = CallerContext(filename="a.py", lineno=1, colno=1, end_colno=5, source_line="x = 1") + assert context.filename == "a.py" + assert context.source_line == "x = 1" |
