File: __init__.py

package info (click to toggle)
python-tatsu 5.13.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 892 kB
  • sloc: python: 10,202; makefile: 54
file content (58 lines) | stat: -rw-r--r-- 1,296 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python3
from __future__ import annotations

import pkgutil
import sys
from pathlib import Path

from tatsu import compile

from .semantics import ANTLRSemantics


def antlr_grammar():
    return str(pkgutil.get_data(__name__, 'antlr.ebnf'), 'utf-8')


def translate(
    text=None, filename=None, name=None, encoding='utf-8', trace=False,
):
    if text is None and filename is None:
        raise ValueError('either `text` or `filename` must be provided')
    if filename:
        filename = Path(filename)

    if text is None:
        name = name or filename.stem
        with filename.open(encoding=encoding) as f:
            text = f.read()

    name = name or 'Unknown'

    semantics = ANTLRSemantics(name)
    grammar = compile(antlr_grammar())
    model = grammar.parse(
        text,
        name=name,
        filename=filename,
        semantics=semantics,
        trace=trace,
        colorize=True,
    )
    print(model)


def main():
    if len(sys.argv) < 2:
        thisprog = Path(sys.argv[0]).name
        print(thisprog)
        print('Usage:')
        print('\t', thisprog, 'FILENAME.g [--trace]')
        sys.exit(1)
    translate(
        filename=sys.argv[1], trace='--trace' in sys.argv or '-t' in sys.argv,
    )


if __name__ == '__main__':
    main()