net: remove muldiv64()
[qemu/cris-port.git] / scripts / qapi-introspect.py
blob7d393201741bb16b03ab8cae88336aef16c67891
2 # QAPI introspection generator
4 # Copyright (C) 2015 Red Hat, Inc.
6 # Authors:
7 # Markus Armbruster <armbru@redhat.com>
9 # This work is licensed under the terms of the GNU GPL, version 2.
10 # See the COPYING file in the top-level directory.
12 from qapi import *
15 # Caveman's json.dumps() replacement (we're stuck at Python 2.4)
16 # TODO try to use json.dumps() once we get unstuck
17 def to_json(obj, level=0):
18 if obj is None:
19 ret = 'null'
20 elif isinstance(obj, str):
21 ret = '"' + obj.replace('"', r'\"') + '"'
22 elif isinstance(obj, list):
23 elts = [to_json(elt, level + 1)
24 for elt in obj]
25 ret = '[' + ', '.join(elts) + ']'
26 elif isinstance(obj, dict):
27 elts = ['"%s": %s' % (key.replace('"', r'\"'),
28 to_json(obj[key], level + 1))
29 for key in sorted(obj.keys())]
30 ret = '{' + ', '.join(elts) + '}'
31 else:
32 assert False # not implemented
33 if level == 1:
34 ret = '\n' + ret
35 return ret
38 def to_c_string(string):
39 return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
42 class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
43 def __init__(self, unmask):
44 self._unmask = unmask
45 self.defn = None
46 self.decl = None
47 self._schema = None
48 self._jsons = None
49 self._used_types = None
50 self._name_map = None
52 def visit_begin(self, schema):
53 self._schema = schema
54 self._jsons = []
55 self._used_types = []
56 self._name_map = {}
57 return QAPISchemaType # don't visit types for now
59 def visit_end(self):
60 # visit the types that are actually used
61 jsons = self._jsons
62 self._jsons = []
63 for typ in self._used_types:
64 typ.visit(self)
65 # generate C
66 # TODO can generate awfully long lines
67 jsons.extend(self._jsons)
68 name = prefix + 'qmp_schema_json'
69 self.decl = mcgen('''
70 extern const char %(c_name)s[];
71 ''',
72 c_name=c_name(name))
73 lines = to_json(jsons).split('\n')
74 c_string = '\n '.join([to_c_string(line) for line in lines])
75 self.defn = mcgen('''
76 const char %(c_name)s[] = %(c_string)s;
77 ''',
78 c_name=c_name(name),
79 c_string=c_string)
80 self._schema = None
81 self._jsons = None
82 self._used_types = None
83 self._name_map = None
85 def _name(self, name):
86 if self._unmask:
87 return name
88 if name not in self._name_map:
89 self._name_map[name] = '%d' % len(self._name_map)
90 return self._name_map[name]
92 def _use_type(self, typ):
93 # Map the various integer types to plain int
94 if typ.json_type() == 'int':
95 typ = self._schema.lookup_type('int')
96 elif (isinstance(typ, QAPISchemaArrayType) and
97 typ.element_type.json_type() == 'int'):
98 typ = self._schema.lookup_type('intList')
99 # Add type to work queue if new
100 if typ not in self._used_types:
101 self._used_types.append(typ)
102 # Clients should examine commands and events, not types. Hide
103 # type names to reduce the temptation. Also saves a few
104 # characters.
105 if isinstance(typ, QAPISchemaBuiltinType):
106 return typ.name
107 return self._name(typ.name)
109 def _gen_json(self, name, mtype, obj):
110 if mtype != 'command' and mtype != 'event' and mtype != 'builtin':
111 name = self._name(name)
112 obj['name'] = name
113 obj['meta-type'] = mtype
114 self._jsons.append(obj)
116 def _gen_member(self, member):
117 ret = {'name': member.name, 'type': self._use_type(member.type)}
118 if member.optional:
119 ret['default'] = None
120 return ret
122 def _gen_variants(self, tag_name, variants):
123 return {'tag': tag_name,
124 'variants': [self._gen_variant(v) for v in variants]}
126 def _gen_variant(self, variant):
127 return {'case': variant.name, 'type': self._use_type(variant.type)}
129 def visit_builtin_type(self, name, info, json_type):
130 self._gen_json(name, 'builtin', {'json-type': json_type})
132 def visit_enum_type(self, name, info, values, prefix):
133 self._gen_json(name, 'enum', {'values': values})
135 def visit_array_type(self, name, info, element_type):
136 self._gen_json(name, 'array',
137 {'element-type': self._use_type(element_type)})
139 def visit_object_type_flat(self, name, info, members, variants):
140 obj = {'members': [self._gen_member(m) for m in members]}
141 if variants:
142 obj.update(self._gen_variants(variants.tag_member.name,
143 variants.variants))
144 self._gen_json(name, 'object', obj)
146 def visit_alternate_type(self, name, info, variants):
147 self._gen_json(name, 'alternate',
148 {'members': [{'type': self._use_type(m.type)}
149 for m in variants.variants]})
151 def visit_command(self, name, info, arg_type, ret_type,
152 gen, success_response):
153 arg_type = arg_type or self._schema.the_empty_object_type
154 ret_type = ret_type or self._schema.the_empty_object_type
155 self._gen_json(name, 'command',
156 {'arg-type': self._use_type(arg_type),
157 'ret-type': self._use_type(ret_type)})
159 def visit_event(self, name, info, arg_type):
160 arg_type = arg_type or self._schema.the_empty_object_type
161 self._gen_json(name, 'event', {'arg-type': self._use_type(arg_type)})
163 # Debugging aid: unmask QAPI schema's type names
164 # We normally mask them, because they're not QMP wire ABI
165 opt_unmask = False
167 (input_file, output_dir, do_c, do_h, prefix, opts) = \
168 parse_command_line("u", ["unmask-non-abi-names"])
170 for o, a in opts:
171 if o in ("-u", "--unmask-non-abi-names"):
172 opt_unmask = True
174 c_comment = '''
176 * QAPI/QMP schema introspection
178 * Copyright (C) 2015 Red Hat, Inc.
180 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
181 * See the COPYING.LIB file in the top-level directory.
185 h_comment = '''
187 * QAPI/QMP schema introspection
189 * Copyright (C) 2015 Red Hat, Inc.
191 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
192 * See the COPYING.LIB file in the top-level directory.
197 (fdef, fdecl) = open_output(output_dir, do_c, do_h, prefix,
198 'qmp-introspect.c', 'qmp-introspect.h',
199 c_comment, h_comment)
201 fdef.write(mcgen('''
202 #include "%(prefix)sqmp-introspect.h"
204 ''',
205 prefix=prefix))
207 schema = QAPISchema(input_file)
208 gen = QAPISchemaGenIntrospectVisitor(opt_unmask)
209 schema.visit(gen)
210 fdef.write(gen.defn)
211 fdecl.write(gen.decl)
213 close_output(fdef, fdecl)