blob: 7d393201741bb16b03ab8cae88336aef16c67891 [file] [log] [blame]
Markus Armbruster39a18152015-09-16 13:06:28 +02001#
2# QAPI introspection generator
3#
4# Copyright (C) 2015 Red Hat, Inc.
5#
6# Authors:
7# Markus Armbruster <armbru@redhat.com>
8#
9# This work is licensed under the terms of the GNU GPL, version 2.
10# See the COPYING file in the top-level directory.
11
12from qapi import *
13
14
15# Caveman's json.dumps() replacement (we're stuck at Python 2.4)
16# TODO try to use json.dumps() once we get unstuck
17def 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
36
37
38def to_c_string(string):
39 return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
40
41
42class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
Markus Armbruster1a9a5072015-09-16 13:06:29 +020043 def __init__(self, unmask):
44 self._unmask = unmask
Markus Armbruster39a18152015-09-16 13:06:28 +020045 self.defn = None
46 self.decl = None
47 self._schema = None
48 self._jsons = None
49 self._used_types = None
Markus Armbruster1a9a5072015-09-16 13:06:29 +020050 self._name_map = None
Markus Armbruster39a18152015-09-16 13:06:28 +020051
52 def visit_begin(self, schema):
53 self._schema = schema
54 self._jsons = []
55 self._used_types = []
Markus Armbruster1a9a5072015-09-16 13:06:29 +020056 self._name_map = {}
Markus Armbruster39a18152015-09-16 13:06:28 +020057 return QAPISchemaType # don't visit types for now
58
59 def visit_end(self):
60 # visit the types that are actually used
Markus Armbruster1a9a5072015-09-16 13:06:29 +020061 jsons = self._jsons
62 self._jsons = []
Markus Armbruster39a18152015-09-16 13:06:28 +020063 for typ in self._used_types:
64 typ.visit(self)
Markus Armbruster39a18152015-09-16 13:06:28 +020065 # generate C
66 # TODO can generate awfully long lines
Markus Armbruster1a9a5072015-09-16 13:06:29 +020067 jsons.extend(self._jsons)
Markus Armbruster39a18152015-09-16 13:06:28 +020068 name = prefix + 'qmp_schema_json'
69 self.decl = mcgen('''
70extern const char %(c_name)s[];
71''',
72 c_name=c_name(name))
Markus Armbruster1a9a5072015-09-16 13:06:29 +020073 lines = to_json(jsons).split('\n')
Markus Armbruster39a18152015-09-16 13:06:28 +020074 c_string = '\n '.join([to_c_string(line) for line in lines])
75 self.defn = mcgen('''
76const 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
Markus Armbruster1a9a5072015-09-16 13:06:29 +020083 self._name_map = None
84
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]
Markus Armbruster39a18152015-09-16 13:06:28 +020091
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)
Markus Armbruster1a9a5072015-09-16 13:06:29 +0200102 # 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)
Markus Armbruster39a18152015-09-16 13:06:28 +0200108
109 def _gen_json(self, name, mtype, obj):
Markus Armbruster1a9a5072015-09-16 13:06:29 +0200110 if mtype != 'command' and mtype != 'event' and mtype != 'builtin':
111 name = self._name(name)
Markus Armbruster39a18152015-09-16 13:06:28 +0200112 obj['name'] = name
113 obj['meta-type'] = mtype
114 self._jsons.append(obj)
115
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
121
122 def _gen_variants(self, tag_name, variants):
123 return {'tag': tag_name,
124 'variants': [self._gen_variant(v) for v in variants]}
125
126 def _gen_variant(self, variant):
127 return {'case': variant.name, 'type': self._use_type(variant.type)}
128
129 def visit_builtin_type(self, name, info, json_type):
130 self._gen_json(name, 'builtin', {'json-type': json_type})
131
132 def visit_enum_type(self, name, info, values, prefix):
133 self._gen_json(name, 'enum', {'values': values})
134
135 def visit_array_type(self, name, info, element_type):
136 self._gen_json(name, 'array',
137 {'element-type': self._use_type(element_type)})
138
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)
145
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]})
150
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)})
158
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)})
162
Markus Armbruster1a9a5072015-09-16 13:06:29 +0200163# Debugging aid: unmask QAPI schema's type names
164# We normally mask them, because they're not QMP wire ABI
165opt_unmask = False
166
167(input_file, output_dir, do_c, do_h, prefix, opts) = \
168 parse_command_line("u", ["unmask-non-abi-names"])
169
170for o, a in opts:
171 if o in ("-u", "--unmask-non-abi-names"):
172 opt_unmask = True
Markus Armbruster39a18152015-09-16 13:06:28 +0200173
174c_comment = '''
175/*
176 * QAPI/QMP schema introspection
177 *
178 * Copyright (C) 2015 Red Hat, Inc.
179 *
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.
182 *
183 */
184'''
185h_comment = '''
186/*
187 * QAPI/QMP schema introspection
188 *
189 * Copyright (C) 2015 Red Hat, Inc.
190 *
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.
193 *
194 */
195'''
196
197(fdef, fdecl) = open_output(output_dir, do_c, do_h, prefix,
198 'qmp-introspect.c', 'qmp-introspect.h',
199 c_comment, h_comment)
200
201fdef.write(mcgen('''
202#include "%(prefix)sqmp-introspect.h"
203
204''',
205 prefix=prefix))
206
207schema = QAPISchema(input_file)
Markus Armbruster1a9a5072015-09-16 13:06:29 +0200208gen = QAPISchemaGenIntrospectVisitor(opt_unmask)
Markus Armbruster39a18152015-09-16 13:06:28 +0200209schema.visit(gen)
210fdef.write(gen.defn)
211fdecl.write(gen.decl)
212
213close_output(fdef, fdecl)