OILS / frontend / option_gen.py View on Github | oilshell.org

94 lines, 43 significant
1#!/usr/bin/env python2
2"""Option_gen.py."""
3from __future__ import print_function
4
5import sys
6
7from asdl import ast
8from frontend import builtin_def
9from frontend import option_def
10
11
12def _CreateSum(sum_name, variant_names):
13 """Similar to frontend/id_kind_gen.py Usage of SYNTHETIC ASDL module:
14
15 C++:
16
17 using option_asdl::opt_num
18 opt_num::nounset
19
20 Python:
21 from _devbuild.gen.option_asdl import opt_num
22 opt_num.nounset
23 """
24 sum_ = ast.SimpleSum([ast.Constructor(name) for name in variant_names],
25 generate=['integers'])
26 typ = ast.TypeDecl(sum_name, sum_)
27 return typ
28
29
30def main(argv):
31 try:
32 action = argv[1]
33 except IndexError:
34 raise RuntimeError('Action required')
35
36 # generate builtin::echo, etc.
37 # This relies on the assigned option numbers matching ASDL's numbering!
38 # TODO: Allow controlling the integer values in ASDL enums?
39
40 option = _CreateSum('option', [opt.name for opt in option_def.All()])
41 builtin = _CreateSum('builtin', [b.enum_name for b in builtin_def.All()])
42 # TODO: could shrink array later.
43 # [opt.name for opt in option_def.All() if opt.implemented])
44
45 schema_ast = ast.Module('option', [], [option, builtin])
46
47 if action == 'cpp':
48 from asdl import gen_cpp
49
50 out_prefix = argv[2]
51
52 with open(out_prefix + '.h', 'w') as f:
53 f.write("""\
54#ifndef OPTION_ASDL_H
55#define OPTION_ASDL_H
56
57namespace option_asdl {
58
59#define ASDL_NAMES struct
60""")
61
62 # Don't need option_str()
63 v = gen_cpp.ClassDefVisitor(f, pretty_print_methods=False)
64 v.VisitModule(schema_ast)
65
66 f.write("""
67} // namespace option_asdl
68
69#endif // OPTION_ASDL_H
70""")
71
72 elif action == 'mypy':
73 from asdl import gen_python
74
75 f = sys.stdout
76
77 f.write("""\
78from asdl import pybase
79
80""")
81 # option_i type
82 v = gen_python.GenMyPyVisitor(f, None)
83 v.VisitModule(schema_ast)
84
85 else:
86 raise RuntimeError('Invalid action %r' % action)
87
88
89if __name__ == '__main__':
90 try:
91 main(sys.argv)
92 except RuntimeError as e:
93 print('FATAL: %s' % e, file=sys.stderr)
94 sys.exit(1)