ogopego

1from ogopego._ogopego import OgoError, compile, parse, parse_file
2
3__all__ = ["OgoError", "compile", "parse", "parse_file"]
class OgoError(builtins.Exception):
64class OgoError(Exception):
65    """Raised when the ogopego Go binary exits with a non-zero status."""
66
67    def __init__(self, returncode: int, stderr: str = ""):
68        self.returncode = returncode
69        self.stderr = stderr
70        super().__init__(f"ogo failed (exit {returncode}): {stderr}")

Raised when the ogopego Go binary exits with a non-zero status.

OgoError(returncode: int, stderr: str = '')
67    def __init__(self, returncode: int, stderr: str = ""):
68        self.returncode = returncode
69        self.stderr = stderr
70        super().__init__(f"ogo failed (exit {returncode}): {stderr}")
returncode
stderr
def compile( grammar: str, name: str | None = None, *, filename=None, trace: bool = False, color: str = 'auto') -> dict:
126def compile(
127    grammar: str,
128    name: str | None = None,
129    *,
130    filename=None,
131    trace: bool = False,
132    color: str = "auto",
133) -> dict:
134    """Compile a PEG grammar string and return the compiled grammar as a dict.
135
136    The result is cached by grammar content hash so repeated calls with
137    the same grammar string return the cached result.
138
139    Args:
140        grammar: PEG grammar source text.
141        name: Grammar name (unused, raises ValueError if set).
142        filename: Source filename hint (unused, raises ValueError if set).
143        trace: Enable trace output from the Go binary.
144        color: Color mode for CLI output ("auto", "never", "always").
145
146    Returns:
147        A dict representing the compiled grammar (JSON-serializable).
148
149    Raises:
150        OgoError: If the Go binary fails.
151        ValueError: If an unsupported argument is provided.
152    """
153    _check_unsupported(name=name, filename=filename)
154
155    key = _hasha(grammar)
156    if key in __cache:
157        return __cache[key]
158
159    with tempfile.NamedTemporaryFile(
160        mode="w", suffix=".ebnf", delete=False
161    ) as f:
162        f.write(grammar)
163        tmpfile = f.name
164
165    try:
166        cli_args = _build_cli_args(
167            "grammar", ["--json"], [tmpfile],
168            trace=trace, color=color,
169        )
170        stdout = _ogo_capture(*cli_args)
171        result = json.loads(stdout)
172        __cache[key] = result
173        return result
174    finally:
175        Path(tmpfile).unlink(missing_ok=True)

Compile a PEG grammar string and return the compiled grammar as a dict.

The result is cached by grammar content hash so repeated calls with the same grammar string return the cached result.

Args: grammar: PEG grammar source text. name: Grammar name (unused, raises ValueError if set). filename: Source filename hint (unused, raises ValueError if set). trace: Enable trace output from the Go binary. color: Color mode for CLI output ("auto", "never", "always").

Returns: A dict representing the compiled grammar (JSON-serializable).

Raises: OgoError: If the Go binary fails. ValueError: If an unsupported argument is provided.

def parse( grammar: str, text: str, /, *, start=None, name=None, filename=None, trace: bool = False, color: str = 'auto'):
178def parse(
179    grammar: str,
180    text: str,
181    /,
182    *,
183    start=None,
184    name=None,
185    filename=None,
186    trace: bool = False,
187    color: str = "auto",
188):
189    """Parse input text against a PEG grammar and return the parse tree.
190
191    Compiles the grammar first (with caching), then runs the parser on
192    the input text via the Go binary.
193
194    Args:
195        grammar: PEG grammar source text.
196        text: Input text to parse.
197        start: Start rule name (unused, raises ValueError if set).
198        name: Grammar name hint (unused, raises ValueError if set).
199        filename: Source filename hint (unused, raises ValueError if set).
200        trace: Enable trace output from the Go binary.
201        color: Color mode for CLI output ("auto", "never", "always").
202
203    Returns:
204        A dict representing the parse tree (JSON-serializable).
205
206    Raises:
207        OgoError: If compilation or parsing fails.
208        ValueError: If an unsupported argument is provided.
209    """
210    _check_unsupported(start=start, name=name, filename=filename)
211
212    grammar_dict = compile(grammar, trace=trace, color=color)
213
214    with tempfile.NamedTemporaryFile(
215        mode="w", suffix=".json", delete=False
216    ) as f:
217        json.dump(grammar_dict, f)
218        grammar_file = f.name
219
220    with tempfile.NamedTemporaryFile(
221        mode="w", suffix=".txt", delete=False
222    ) as f:
223        f.write(text)
224        input_file = f.name
225
226    try:
227        cli_args = _build_cli_args(
228            "run", ["--json"], [grammar_file, input_file],
229            trace=trace, color=color,
230        )
231        stdout = _ogo_capture(*cli_args)
232        return json.loads(stdout)
233    finally:
234        Path(grammar_file).unlink(missing_ok=True)
235        Path(input_file).unlink(missing_ok=True)

Parse input text against a PEG grammar and return the parse tree.

Compiles the grammar first (with caching), then runs the parser on the input text via the Go binary.

Args: grammar: PEG grammar source text. text: Input text to parse. start: Start rule name (unused, raises ValueError if set). name: Grammar name hint (unused, raises ValueError if set). filename: Source filename hint (unused, raises ValueError if set). trace: Enable trace output from the Go binary. color: Color mode for CLI output ("auto", "never", "always").

Returns: A dict representing the parse tree (JSON-serializable).

Raises: OgoError: If compilation or parsing fails. ValueError: If an unsupported argument is provided.

def parse_file( grammar: str, path: str, /, *, start=None, name=None, filename=None, trace: bool = False, color: str = 'auto'):
238def parse_file(
239    grammar: str,
240    path: str,
241    /,
242    *,
243    start=None,
244    name=None,
245    filename=None,
246    trace: bool = False,
247    color: str = "auto",
248):
249    """Parse a file against a PEG grammar and return the parse tree.
250
251    Compiles the grammar first (with caching), then runs the parser on
252    the file at *path* via the Go binary.
253
254    Args:
255        grammar: PEG grammar source text.
256        path: Path to the input file to parse.
257        start: Start rule name (unused, raises ValueError if set).
258        name: Grammar name hint (unused, raises ValueError if set).
259        filename: Source filename hint (unused, raises ValueError if set).
260        trace: Enable trace output from the Go binary.
261        color: Color mode for CLI output ("auto", "never", "always").
262
263    Returns:
264        A dict representing the parse tree (JSON-serializable).
265
266    Raises:
267        OgoError: If compilation or parsing fails.
268        ValueError: If an unsupported argument is provided.
269    """
270    _check_unsupported(start=start, name=name, filename=filename)
271
272    grammar_dict = compile(grammar, trace=trace, color=color)
273
274    with tempfile.NamedTemporaryFile(
275        mode="w", suffix=".json", delete=False
276    ) as f:
277        json.dump(grammar_dict, f)
278        grammar_file = f.name
279
280    try:
281        cli_args = _build_cli_args(
282            "run", ["--json"], [grammar_file, path],
283            trace=trace, color=color,
284        )
285        stdout = _ogo_capture(*cli_args)
286        return json.loads(stdout)
287    finally:
288        Path(grammar_file).unlink(missing_ok=True)

Parse a file against a PEG grammar and return the parse tree.

Compiles the grammar first (with caching), then runs the parser on the file at path via the Go binary.

Args: grammar: PEG grammar source text. path: Path to the input file to parse. start: Start rule name (unused, raises ValueError if set). name: Grammar name hint (unused, raises ValueError if set). filename: Source filename hint (unused, raises ValueError if set). trace: Enable trace output from the Go binary. color: Color mode for CLI output ("auto", "never", "always").

Returns: A dict representing the parse tree (JSON-serializable).

Raises: OgoError: If compilation or parsing fails. ValueError: If an unsupported argument is provided.