qapi: Split up scripts/qapi/common.py
[qemu/ar7.git] / scripts / qapi / doc.py
blob1c5125249fcd3caa6f31f90a912da9125aca36e2
1 #!/usr/bin/env python
2 # QAPI texi generator
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"""
8 from __future__ import print_function
9 import re
10 from qapi.gen import QAPIGenDoc, QAPISchemaVisitor
13 MSG_FMT = """
14 @deftypefn {type} {{}} {name}
16 {body}
17 @end deftypefn
19 """.format
21 TYPE_FMT = """
22 @deftp {{{type}}} {name}
24 {body}
25 @end deftp
27 """.format
29 EXAMPLE_FMT = """@example
30 {code}
31 @end example
32 """.format
35 def subst_strong(doc):
36 """Replaces *foo* by @strong{foo}"""
37 return re.sub(r'\*([^*\n]+)\*', r'@strong{\1}', doc)
40 def subst_emph(doc):
41 """Replaces _foo_ by @emph{foo}"""
42 return re.sub(r'\b_([^_\n]+)_\b', r'@emph{\1}', doc)
45 def subst_vars(doc):
46 """Replaces @var by @code{var}"""
47 return re.sub(r'@([\w-]+)', r'@code{\1}', doc)
50 def subst_braces(doc):
51 """Replaces {} with @{ @}"""
52 return doc.replace('{', '@{').replace('}', '@}')
55 def texi_example(doc):
56 """Format @example"""
57 # TODO: Neglects to escape @ characters.
58 # We should probably escape them in subst_braces(), and rename the
59 # function to subst_special() or subs_texi_special(). If we do that, we
60 # need to delay it until after subst_vars() in texi_format().
61 doc = subst_braces(doc).strip('\n')
62 return EXAMPLE_FMT(code=doc)
65 def texi_format(doc):
66 """
67 Format documentation
69 Lines starting with:
70 - |: generates an @example
71 - =: generates @section
72 - ==: generates @subsection
73 - 1. or 1): generates an @enumerate @item
74 - */-: generates an @itemize list
75 """
76 ret = ''
77 doc = subst_braces(doc)
78 doc = subst_vars(doc)
79 doc = subst_emph(doc)
80 doc = subst_strong(doc)
81 inlist = ''
82 lastempty = False
83 for line in doc.split('\n'):
84 empty = line == ''
86 # FIXME: Doing this in a single if / elif chain is
87 # problematic. For instance, a line without markup terminates
88 # a list if it follows a blank line (reaches the final elif),
89 # but a line with some *other* markup, such as a = title
90 # doesn't.
92 # Make sure to update section "Documentation markup" in
93 # docs/devel/qapi-code-gen.txt when fixing this.
94 if line.startswith('| '):
95 line = EXAMPLE_FMT(code=line[2:])
96 elif line.startswith('= '):
97 line = '@section ' + line[2:]
98 elif line.startswith('== '):
99 line = '@subsection ' + line[3:]
100 elif re.match(r'^([0-9]*\.) ', line):
101 if not inlist:
102 ret += '@enumerate\n'
103 inlist = 'enumerate'
104 ret += '@item\n'
105 line = line[line.find(' ')+1:]
106 elif re.match(r'^[*-] ', line):
107 if not inlist:
108 ret += '@itemize %s\n' % {'*': '@bullet',
109 '-': '@minus'}[line[0]]
110 inlist = 'itemize'
111 ret += '@item\n'
112 line = line[2:]
113 elif lastempty and inlist:
114 ret += '@end %s\n\n' % inlist
115 inlist = ''
117 lastempty = empty
118 ret += line + '\n'
120 if inlist:
121 ret += '@end %s\n\n' % inlist
122 return ret
125 def texi_body(doc):
126 """Format the main documentation body"""
127 return texi_format(doc.body.text)
130 def texi_if(ifcond, prefix='\n', suffix='\n'):
131 """Format the #if condition"""
132 if not ifcond:
133 return ''
134 return '%s@b{If:} @code{%s}%s' % (prefix, ', '.join(ifcond), suffix)
137 def texi_enum_value(value, desc, suffix):
138 """Format a table of members item for an enumeration value"""
139 return '@item @code{%s}\n%s%s' % (
140 value.name, desc, texi_if(value.ifcond, prefix='@*'))
143 def texi_member(member, desc, suffix):
144 """Format a table of members item for an object type member"""
145 typ = member.type.doc_type()
146 membertype = ': ' + typ if typ else ''
147 return '@item @code{%s%s}%s%s\n%s%s' % (
148 member.name, membertype,
149 ' (optional)' if member.optional else '',
150 suffix, desc, texi_if(member.ifcond, prefix='@*'))
153 def texi_members(doc, what, base, variants, member_func):
154 """Format the table of members"""
155 items = ''
156 for section in doc.args.values():
157 # TODO Drop fallbacks when undocumented members are outlawed
158 if section.text:
159 desc = texi_format(section.text)
160 elif (variants and variants.tag_member == section.member
161 and not section.member.type.doc_type()):
162 values = section.member.type.member_names()
163 members_text = ', '.join(['@t{"%s"}' % v for v in values])
164 desc = 'One of ' + members_text + '\n'
165 else:
166 desc = 'Not documented\n'
167 items += member_func(section.member, desc, suffix='')
168 if base:
169 items += '@item The members of @code{%s}\n' % base.doc_type()
170 if variants:
171 for v in variants.variants:
172 when = ' when @code{%s} is @t{"%s"}%s' % (
173 variants.tag_member.name, v.name, texi_if(v.ifcond, " (", ")"))
174 if v.type.is_implicit():
175 assert not v.type.base and not v.type.variants
176 for m in v.type.local_members:
177 items += member_func(m, desc='', suffix=when)
178 else:
179 items += '@item The members of @code{%s}%s\n' % (
180 v.type.doc_type(), when)
181 if not items:
182 return ''
183 return '\n@b{%s:}\n@table @asis\n%s@end table\n' % (what, items)
186 def texi_features(doc):
187 """Format the table of features"""
188 items = ''
189 for section in doc.features.values():
190 desc = texi_format(section.text)
191 items += '@item @code{%s}\n%s' % (section.name, desc)
192 if not items:
193 return ''
194 return '\n@b{Features:}\n@table @asis\n%s@end table\n' % (items)
197 def texi_sections(doc, ifcond):
198 """Format additional sections following arguments"""
199 body = ''
200 for section in doc.sections:
201 if section.name:
202 # prefer @b over @strong, so txt doesn't translate it to *Foo:*
203 body += '\n@b{%s:}\n' % section.name
204 if section.name and section.name.startswith('Example'):
205 body += texi_example(section.text)
206 else:
207 body += texi_format(section.text)
208 body += texi_if(ifcond, suffix='')
209 return body
212 def texi_entity(doc, what, ifcond, base=None, variants=None,
213 member_func=texi_member):
214 return (texi_body(doc)
215 + texi_members(doc, what, base, variants, member_func)
216 + texi_features(doc)
217 + texi_sections(doc, ifcond))
220 class QAPISchemaGenDocVisitor(QAPISchemaVisitor):
221 def __init__(self, prefix):
222 self._prefix = prefix
223 self._gen = QAPIGenDoc(self._prefix + 'qapi-doc.texi')
224 self.cur_doc = None
226 def write(self, output_dir):
227 self._gen.write(output_dir)
229 def visit_enum_type(self, name, info, ifcond, members, prefix):
230 doc = self.cur_doc
231 self._gen.add(TYPE_FMT(type='Enum',
232 name=doc.symbol,
233 body=texi_entity(doc, 'Values', ifcond,
234 member_func=texi_enum_value)))
236 def visit_object_type(self, name, info, ifcond, base, members, variants,
237 features):
238 doc = self.cur_doc
239 if base and base.is_implicit():
240 base = None
241 self._gen.add(TYPE_FMT(type='Object',
242 name=doc.symbol,
243 body=texi_entity(doc, 'Members', ifcond,
244 base, variants)))
246 def visit_alternate_type(self, name, info, ifcond, variants):
247 doc = self.cur_doc
248 self._gen.add(TYPE_FMT(type='Alternate',
249 name=doc.symbol,
250 body=texi_entity(doc, 'Members', ifcond)))
252 def visit_command(self, name, info, ifcond, arg_type, ret_type, gen,
253 success_response, boxed, allow_oob, allow_preconfig):
254 doc = self.cur_doc
255 if boxed:
256 body = texi_body(doc)
257 body += ('\n@b{Arguments:} the members of @code{%s}\n'
258 % arg_type.name)
259 body += texi_sections(doc, ifcond)
260 else:
261 body = texi_entity(doc, 'Arguments', ifcond)
262 self._gen.add(MSG_FMT(type='Command',
263 name=doc.symbol,
264 body=body))
266 def visit_event(self, name, info, ifcond, arg_type, boxed):
267 doc = self.cur_doc
268 self._gen.add(MSG_FMT(type='Event',
269 name=doc.symbol,
270 body=texi_entity(doc, 'Arguments', ifcond)))
272 def symbol(self, doc, entity):
273 if self._gen._body:
274 self._gen.add('\n')
275 self.cur_doc = doc
276 entity.visit(self)
277 self.cur_doc = None
279 def freeform(self, doc):
280 assert not doc.args
281 if self._gen._body:
282 self._gen.add('\n')
283 self._gen.add(texi_body(doc) + texi_sections(doc, None))
286 def gen_doc(schema, output_dir, prefix):
287 vis = QAPISchemaGenDocVisitor(prefix)
288 vis.visit_begin(schema)
289 for doc in schema.docs:
290 if doc.symbol:
291 vis.symbol(doc, schema.lookup_entity(doc.symbol))
292 else:
293 vis.freeform(doc)
294 vis.write(output_dir)