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

105 lines, 44 significant
1#!/usr/bin/env python2
2"""Signal_gen.py."""
3from __future__ import print_function
4
5import sys
6
7import signal_def
8
9
10def CppPrintSignals(f):
11 f.write("""
12void PrintSignals() {
13""")
14
15 for abbrev, _ in signal_def._BY_NUMBER:
16 name = "SIG%s" % (abbrev, )
17 f.write("""\
18#ifdef %s
19 printf("%%2d %s\\n", %s);
20#endif
21""" % (name, name, name))
22
23 f.write("}\n")
24
25
26def CppGetNumber(f):
27 f.write("""\
28int GetNumber(BigStr* sig_spec) {
29 int length = len(sig_spec);
30 if (length == 0) {
31 return NO_SIGNAL;
32 }
33
34 const char* data = sig_spec->data_;
35
36""")
37 for abbrev, _ in signal_def._BY_NUMBER:
38 name = "SIG%s" % (abbrev, )
39 f.write("""\
40 if ((length == %d && memcmp("%s", data, %d) == 0) ||
41 (length == %d && memcmp("%s", data, %d) == 0)) {
42 return %s;
43 }
44""" % (len(name), name, len(name), len(abbrev), abbrev, len(abbrev), name))
45 f.write("""\
46 return NO_SIGNAL;
47}
48""")
49
50
51def main(argv):
52 try:
53 action = argv[1]
54 except IndexError:
55 raise RuntimeError('Action required')
56
57 if action == 'cpp':
58 out_prefix = argv[2]
59
60 with open(out_prefix + '.h', 'w') as f:
61 f.write("""\
62#ifndef FRONTEND_SIGNAL_H
63#define FRONTEND_SIGNAL_H
64
65#include "mycpp/runtime.h"
66
67namespace signal_def {
68
69const int NO_SIGNAL = -1;
70
71void PrintSignals();
72
73int GetNumber(BigStr* sig_spec);
74
75} // namespace signal_def
76
77#endif // FRONTEND_SIGNAL_H
78""")
79
80 with open(out_prefix + '.cc', 'w') as f:
81 f.write("""\
82#include "signal.h"
83
84#include <signal.h> // SIG*
85#include <stdio.h> // printf
86
87namespace signal_def {
88
89""")
90 CppPrintSignals(f)
91 f.write("\n")
92 CppGetNumber(f)
93
94 f.write("""\
95
96} // namespace signal_def
97""")
98
99
100if __name__ == '__main__':
101 try:
102 main(sys.argv)
103 except RuntimeError as e:
104 print('FATAL: %s' % e, file=sys.stderr)
105 sys.exit(1)