OILS / frontend / option_gen.py View on Github | oils.pub

89 lines, 41 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(
25 [ast.MakeSimpleVariant(name) for name in variant_names],
26 generate=['integers'])
27 typ = ast.TypeDecl(sum_name, sum_)
28 return typ
29
30
31def main(argv):
32 try:
33 action = argv[1]
34 except IndexError:
35 raise RuntimeError('Action required')
36
37 # generate builtin::echo, etc.
38 # This relies on the assigned option numbers matching ASDL's numbering!
39 # TODO: Allow controlling the integer values in ASDL enums?
40
41 option = _CreateSum('option', [opt.name for opt in option_def.All()])
42 builtin = _CreateSum('builtin', [b.enum_name for b in builtin_def.All()])
43 # TODO: could shrink array later.
44 # [opt.name for opt in option_def.All() if opt.implemented])
45
46 schema_ast = ast.Module('option', [], [], [option, builtin])
47
48 if action == 'cpp':
49 from asdl import gen_cpp
50
51 out_prefix = argv[2]
52
53 with open(out_prefix + '.h', 'w') as f:
54 f.write("""\
55#ifndef OPTION_ASDL_H
56#define OPTION_ASDL_H
57
58namespace option_asdl {
59
60#define ASDL_NAMES struct
61""")
62
63 # Don't need option_str()
64 v = gen_cpp.ClassDefVisitor(f, pretty_print_methods=False)
65 v.VisitModule(schema_ast)
66
67 f.write("""
68} // namespace option_asdl
69
70#endif // OPTION_ASDL_H
71""")
72
73 elif action == 'mypy':
74 from asdl import gen_python
75
76 # option_i type
77 v = gen_python.GenMyPyVisitor(sys.stdout)
78 v.VisitModule(schema_ast)
79
80 else:
81 raise RuntimeError('Invalid action %r' % action)
82
83
84if __name__ == '__main__':
85 try:
86 main(sys.argv)
87 except RuntimeError as e:
88 print('FATAL: %s' % e, file=sys.stderr)
89 sys.exit(1)