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

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