qapi2texi: Generate documentation for variant members
[qemu.git] / scripts / qapi2texi.py
1 #!/usr/bin/env python
2 # QAPI texi generator
3 #
4 # This work is licensed under the terms of the GNU LGPL, version 2+.
5 # See the COPYING file in the top-level directory.
6 """This script produces the documentation of a qapi schema in texinfo format"""
7 import re
8 import sys
9
10 import qapi
11
12 MSG_FMT = """
13 @deftypefn {type} {{}} {name}
14
15 {body}
16
17 @end deftypefn
18
19 """.format
20
21 TYPE_FMT = """
22 @deftp {{{type}}} {name}
23
24 {body}
25
26 @end deftp
27
28 """.format
29
30 EXAMPLE_FMT = """@example
31 {code}
32 @end example
33 """.format
34
35
36 def subst_strong(doc):
37 """Replaces *foo* by @strong{foo}"""
38 return re.sub(r'\*([^*\n]+)\*', r'@emph{\1}', doc)
39
40
41 def subst_emph(doc):
42 """Replaces _foo_ by @emph{foo}"""
43 return re.sub(r'\b_([^_\n]+)_\b', r' @emph{\1} ', doc)
44
45
46 def subst_vars(doc):
47 """Replaces @var by @code{var}"""
48 return re.sub(r'@([\w-]+)', r'@code{\1}', doc)
49
50
51 def subst_braces(doc):
52 """Replaces {} with @{ @}"""
53 return doc.replace('{', '@{').replace('}', '@}')
54
55
56 def texi_example(doc):
57 """Format @example"""
58 # TODO: Neglects to escape @ characters.
59 # We should probably escape them in subst_braces(), and rename the
60 # function to subst_special() or subs_texi_special(). If we do that, we
61 # need to delay it until after subst_vars() in texi_format().
62 doc = subst_braces(doc).strip('\n')
63 return EXAMPLE_FMT(code=doc)
64
65
66 def texi_format(doc):
67 """
68 Format documentation
69
70 Lines starting with:
71 - |: generates an @example
72 - =: generates @section
73 - ==: generates @subsection
74 - 1. or 1): generates an @enumerate @item
75 - */-: generates an @itemize list
76 """
77 lines = []
78 doc = subst_braces(doc)
79 doc = subst_vars(doc)
80 doc = subst_emph(doc)
81 doc = subst_strong(doc)
82 inlist = ''
83 lastempty = False
84 for line in doc.split('\n'):
85 empty = line == ''
86
87 # FIXME: Doing this in a single if / elif chain is
88 # problematic. For instance, a line without markup terminates
89 # a list if it follows a blank line (reaches the final elif),
90 # but a line with some *other* markup, such as a = title
91 # doesn't.
92 #
93 # Make sure to update section "Documentation markup" in
94 # docs/qapi-code-gen.txt when fixing this.
95 if line.startswith('| '):
96 line = EXAMPLE_FMT(code=line[2:])
97 elif line.startswith('= '):
98 line = '@section ' + line[2:]
99 elif line.startswith('== '):
100 line = '@subsection ' + line[3:]
101 elif re.match(r'^([0-9]*\.) ', line):
102 if not inlist:
103 lines.append('@enumerate')
104 inlist = 'enumerate'
105 line = line[line.find(' ')+1:]
106 lines.append('@item')
107 elif re.match(r'^[*-] ', line):
108 if not inlist:
109 lines.append('@itemize %s' % {'*': '@bullet',
110 '-': '@minus'}[line[0]])
111 inlist = 'itemize'
112 lines.append('@item')
113 line = line[2:]
114 elif lastempty and inlist:
115 lines.append('@end %s\n' % inlist)
116 inlist = ''
117
118 lastempty = empty
119 lines.append(line)
120
121 if inlist:
122 lines.append('@end %s\n' % inlist)
123 return '\n'.join(lines)
124
125
126 def texi_body(doc):
127 """Format the main documentation body"""
128 return texi_format(str(doc.body)) + '\n'
129
130
131 def texi_enum_value(value):
132 """Format a table of members item for an enumeration value"""
133 return '@item @code{%s}\n' % value.name
134
135
136 def texi_member(member, suffix=''):
137 """Format a table of members item for an object type member"""
138 typ = member.type.doc_type()
139 return '@item @code{%s%s%s}%s%s\n' % (
140 member.name,
141 ': ' if typ else '',
142 typ if typ else '',
143 ' (optional)' if member.optional else '',
144 suffix)
145
146
147 def texi_members(doc, what, base, variants, member_func):
148 """Format the table of members"""
149 items = ''
150 for section in doc.args.itervalues():
151 if section.content:
152 desc = str(section)
153 else:
154 desc = 'Not documented'
155 items += member_func(section.member) + texi_format(desc) + '\n'
156 if base:
157 items += '@item The members of @code{%s}\n' % base.doc_type()
158 if variants:
159 for v in variants.variants:
160 when = ' when @code{%s} is @t{"%s"}' % (
161 variants.tag_member.name, v.name)
162 if v.type.is_implicit():
163 assert not v.type.base and not v.type.variants
164 for m in v.type.local_members:
165 items += member_func(m, when)
166 else:
167 items += '@item The members of @code{%s}%s\n' % (
168 v.type.doc_type(), when)
169 if not items:
170 return ''
171 return '\n@b{%s:}\n@table @asis\n%s@end table\n' % (what, items)
172
173
174 def texi_sections(doc):
175 """Format additional sections following arguments"""
176 body = ''
177 for section in doc.sections:
178 name, doc = (section.name, str(section))
179 func = texi_format
180 if name.startswith('Example'):
181 func = texi_example
182
183 if name:
184 # prefer @b over @strong, so txt doesn't translate it to *Foo:*
185 body += '\n\n@b{%s:}\n' % name
186
187 body += func(doc)
188 return body
189
190
191 def texi_entity(doc, what, base=None, variants=None,
192 member_func=texi_member):
193 return (texi_body(doc)
194 + texi_members(doc, what, base, variants, member_func)
195 + texi_sections(doc))
196
197
198 class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
199 def __init__(self):
200 self.out = None
201 self.cur_doc = None
202
203 def visit_begin(self, schema):
204 self.out = ''
205
206 def visit_enum_type(self, name, info, values, prefix):
207 doc = self.cur_doc
208 if self.out:
209 self.out += '\n'
210 self.out += TYPE_FMT(type='Enum',
211 name=doc.symbol,
212 body=texi_entity(doc, 'Values',
213 member_func=texi_enum_value))
214
215 def visit_object_type(self, name, info, base, members, variants):
216 doc = self.cur_doc
217 if not variants:
218 typ = 'Struct'
219 elif variants._tag_name: # TODO unclean member access
220 typ = 'Flat Union'
221 else:
222 typ = 'Simple Union'
223 if base and base.is_implicit():
224 base = None
225 if self.out:
226 self.out += '\n'
227 self.out += TYPE_FMT(type=typ,
228 name=doc.symbol,
229 body=texi_entity(doc, 'Members', base, variants))
230
231 def visit_alternate_type(self, name, info, variants):
232 doc = self.cur_doc
233 if self.out:
234 self.out += '\n'
235 self.out += TYPE_FMT(type='Alternate',
236 name=doc.symbol,
237 body=texi_entity(doc, 'Members'))
238
239 def visit_command(self, name, info, arg_type, ret_type,
240 gen, success_response, boxed):
241 doc = self.cur_doc
242 if self.out:
243 self.out += '\n'
244 if boxed:
245 body = texi_body(doc)
246 body += '\n@b{Arguments:} the members of @code{%s}' % arg_type.name
247 body += texi_sections(doc)
248 else:
249 body = texi_entity(doc, 'Arguments')
250 self.out += MSG_FMT(type='Command',
251 name=doc.symbol,
252 body=body)
253
254 def visit_event(self, name, info, arg_type, boxed):
255 doc = self.cur_doc
256 if self.out:
257 self.out += '\n'
258 self.out += MSG_FMT(type='Event',
259 name=doc.symbol,
260 body=texi_entity(doc, 'Arguments'))
261
262 def symbol(self, doc, entity):
263 self.cur_doc = doc
264 entity.visit(self)
265 self.cur_doc = None
266
267 def freeform(self, doc):
268 assert not doc.args
269 if self.out:
270 self.out += '\n'
271 self.out += texi_body(doc) + texi_sections(doc)
272
273
274 def texi_schema(schema):
275 """Convert QAPI schema documentation to Texinfo"""
276 gen = QAPISchemaGenDocVisitor()
277 gen.visit_begin(schema)
278 for doc in schema.docs:
279 if doc.symbol:
280 gen.symbol(doc, schema.lookup_entity(doc.symbol))
281 else:
282 gen.freeform(doc)
283 return gen.out
284
285
286 def main(argv):
287 """Takes schema argument, prints result to stdout"""
288 if len(argv) != 2:
289 print >>sys.stderr, "%s: need exactly 1 argument: SCHEMA" % argv[0]
290 sys.exit(1)
291
292 schema = qapi.QAPISchema(argv[1])
293 if not qapi.doc_required:
294 print >>sys.stderr, ("%s: need pragma 'doc-required' "
295 "to generate documentation" % argv[0])
296 print texi_schema(schema)
297
298
299 if __name__ == '__main__':
300 main(sys.argv)