summaryrefslogtreecommitdiffstats
path: root/third_party/rust/jsparagus/js_parser/try_it.py
blob: d8cb89457a46d906c8a65c1cceda12c183527424 (plain)
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
59
#!/usr/bin/env python

"""js.py - Repl-like toy to explore parsing of lines of JS.

See README.md for instructions.
"""

import argparse
import traceback
from .lexer import JSLexer
from .parser import JSParser
from jsparagus.lexer import SyntaxError


def interactive_input(lexer, prompt="js> "):
    while True:
        line = input(prompt)
        lexer.write(line + "\n")
        if lexer.can_close():
            return lexer.close()
        prompt = "..> "


def rpl():
    """Read-print loop."""
    while True:
        parser = JSLexer(JSParser(), filename="<stdin>")
        try:
            result = interactive_input(parser)
        except EOFError:
            print()
            break
        except SyntaxError:
            traceback.print_exc(limit=0)
            continue
        print(result)


def main():
    parser = argparse.ArgumentParser(description="Try out the JS parser.")
    parser.add_argument('input_file', metavar='FILE', nargs='?',
                        help=".js file to parse")
    options = parser.parse_args()

    if options.input_file is not None:
        with open(options.input_file) as f:
            source = f.readlines()
        lexer = JSLexer(JSParser())
        for line in source:
            print(line.rstrip())
            lexer.write(line)
        ast = lexer.close()
        print(ast)
    else:
        rpl()


if __name__ == '__main__':
    main()