scripts/qemu.py: use a more consistent docstring style
[qemu/ar7.git] / scripts / qapi / doc.py
blob987fd3c9435d15692fcd26a88ddb60fb40b23c36
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 import qapi.common
12 MSG_FMT = """
13 @deftypefn {type} {{}} {name}
15 {body}
16 @end deftypefn
18 """.format
20 TYPE_FMT = """
21 @deftp {{{type}}} {name}
23 {body}
24 @end deftp
26 """.format
28 EXAMPLE_FMT = """@example
29 {code}
30 @end example
31 """.format
34 def subst_strong(doc):
35 """Replaces *foo* by @strong{foo}"""
36 return re.sub(r'\*([^*\n]+)\*', r'@strong{\1}', doc)
39 def subst_emph(doc):
40 """Replaces _foo_ by @emph{foo}"""
41 return re.sub(r'\b_([^_\n]+)_\b', r'@emph{\1}', doc)
44 def subst_vars(doc):
45 """Replaces @var by @code{var}"""
46 return re.sub(r'@([\w-]+)', r'@code{\1}', doc)
49 def subst_braces(doc):
50 """Replaces {} with @{ @}"""
51 return doc.replace('{', '@{').replace('}', '@}')
54 def texi_example(doc):
55 """Format @example"""
56 # TODO: Neglects to escape @ characters.
57 # We should probably escape them in subst_braces(), and rename the
58 # function to subst_special() or subs_texi_special(). If we do that, we
59 # need to delay it until after subst_vars() in texi_format().
60 doc = subst_braces(doc).strip('\n')
61 return EXAMPLE_FMT(code=doc)
64 def texi_format(doc):
65 """
66 Format documentation
68 Lines starting with:
69 - |: generates an @example
70 - =: generates @section
71 - ==: generates @subsection
72 - 1. or 1): generates an @enumerate @item
73 - */-: generates an @itemize list
74 """
75 ret = ''
76 doc = subst_braces(doc)
77 doc = subst_vars(doc)
78 doc = subst_emph(doc)
79 doc = subst_strong(doc)
80 inlist = ''
81 lastempty = False
82 for line in doc.split('\n'):
83 empty = line == ''
85 # FIXME: Doing this in a single if / elif chain is
86 # problematic. For instance, a line without markup terminates
87 # a list if it follows a blank line (reaches the final elif),
88 # but a line with some *other* markup, such as a = title
89 # doesn't.
91 # Make sure to update section "Documentation markup" in
92 # docs/devel/qapi-code-gen.txt when fixing this.
93 if line.startswith('| '):
94 line = EXAMPLE_FMT(code=line[2:])
95 elif line.startswith('= '):
96 line = '@section ' + line[2:]
97 elif line.startswith('== '):
98 line = '@subsection ' + line[3:]
99 elif re.match(r'^([0-9]*\.) ', line):
100 if not inlist:
101 ret += '@enumerate\n'
102 inlist = 'enumerate'
103 ret += '@item\n'
104 line = line[line.find(' ')+1:]
105 elif re.match(r'^[*-] ', line):
106 if not inlist:
107 ret += '@itemize %s\n' % {'*': '@bullet',
108 '-': '@minus'}[line[0]]
109 inlist = 'itemize'
110 ret += '@item\n'
111 line = line[2:]
112 elif lastempty and inlist:
113 ret += '@end %s\n\n' % inlist
114 inlist = ''
116 lastempty = empty
117 ret += line + '\n'
119 if inlist:
120 ret += '@end %s\n\n' % inlist
121 return ret
124 def texi_body(doc):
125 """Format the main documentation body"""
126 return texi_format(doc.body.text)
129 def texi_enum_value(value):
130 """Format a table of members item for an enumeration value"""
131 return '@item @code{%s}\n' % value.name
134 def texi_member(member, suffix=''):
135 """Format a table of members item for an object type member"""
136 typ = member.type.doc_type()
137 membertype = ': ' + typ if typ else ''
138 return '@item @code{%s%s}%s%s\n' % (
139 member.name, membertype,
140 ' (optional)' if member.optional else '',
141 suffix)
144 def texi_members(doc, what, base, variants, member_func):
145 """Format the table of members"""
146 items = ''
147 for section in doc.args.values():
148 # TODO Drop fallbacks when undocumented members are outlawed
149 if section.text:
150 desc = texi_format(section.text)
151 elif (variants and variants.tag_member == section.member
152 and not section.member.type.doc_type()):
153 values = section.member.type.member_names()
154 members_text = ', '.join(['@t{"%s"}' % v for v in values])
155 desc = 'One of ' + members_text + '\n'
156 else:
157 desc = 'Not documented\n'
158 items += member_func(section.member) + desc
159 if base:
160 items += '@item The members of @code{%s}\n' % base.doc_type()
161 if variants:
162 for v in variants.variants:
163 when = ' when @code{%s} is @t{"%s"}' % (
164 variants.tag_member.name, v.name)
165 if v.type.is_implicit():
166 assert not v.type.base and not v.type.variants
167 for m in v.type.local_members:
168 items += member_func(m, when)
169 else:
170 items += '@item The members of @code{%s}%s\n' % (
171 v.type.doc_type(), when)
172 if not items:
173 return ''
174 return '\n@b{%s:}\n@table @asis\n%s@end table\n' % (what, items)
177 def texi_sections(doc, ifcond):
178 """Format additional sections following arguments"""
179 body = ''
180 for section in doc.sections:
181 if section.name:
182 # prefer @b over @strong, so txt doesn't translate it to *Foo:*
183 body += '\n@b{%s:}\n' % section.name
184 if section.name and section.name.startswith('Example'):
185 body += texi_example(section.text)
186 else:
187 body += texi_format(section.text)
188 if ifcond:
189 body += '\n\n@b{If:} @code{%s}' % ", ".join(ifcond)
190 return body
193 def texi_entity(doc, what, ifcond, base=None, variants=None,
194 member_func=texi_member):
195 return (texi_body(doc)
196 + texi_members(doc, what, base, variants, member_func)
197 + texi_sections(doc, ifcond))
200 class QAPISchemaGenDocVisitor(qapi.common.QAPISchemaVisitor):
201 def __init__(self, prefix):
202 self._prefix = prefix
203 self._gen = qapi.common.QAPIGenDoc()
204 self.cur_doc = None
206 def write(self, output_dir):
207 self._gen.write(output_dir, self._prefix + 'qapi-doc.texi')
209 def visit_enum_type(self, name, info, ifcond, values, prefix):
210 doc = self.cur_doc
211 self._gen.add(TYPE_FMT(type='Enum',
212 name=doc.symbol,
213 body=texi_entity(doc, 'Values', ifcond,
214 member_func=texi_enum_value)))
216 def visit_object_type(self, name, info, ifcond, base, members, variants):
217 doc = self.cur_doc
218 if base and base.is_implicit():
219 base = None
220 self._gen.add(TYPE_FMT(type='Object',
221 name=doc.symbol,
222 body=texi_entity(doc, 'Members', ifcond,
223 base, variants)))
225 def visit_alternate_type(self, name, info, ifcond, variants):
226 doc = self.cur_doc
227 self._gen.add(TYPE_FMT(type='Alternate',
228 name=doc.symbol,
229 body=texi_entity(doc, 'Members', ifcond)))
231 def visit_command(self, name, info, ifcond, arg_type, ret_type, gen,
232 success_response, boxed, allow_oob, allow_preconfig):
233 doc = self.cur_doc
234 if boxed:
235 body = texi_body(doc)
236 body += ('\n@b{Arguments:} the members of @code{%s}\n'
237 % arg_type.name)
238 body += texi_sections(doc, ifcond)
239 else:
240 body = texi_entity(doc, 'Arguments', ifcond)
241 self._gen.add(MSG_FMT(type='Command',
242 name=doc.symbol,
243 body=body))
245 def visit_event(self, name, info, ifcond, arg_type, boxed):
246 doc = self.cur_doc
247 self._gen.add(MSG_FMT(type='Event',
248 name=doc.symbol,
249 body=texi_entity(doc, 'Arguments', ifcond)))
251 def symbol(self, doc, entity):
252 if self._gen._body:
253 self._gen.add('\n')
254 self.cur_doc = doc
255 entity.visit(self)
256 self.cur_doc = None
258 def freeform(self, doc):
259 assert not doc.args
260 if self._gen._body:
261 self._gen.add('\n')
262 self._gen.add(texi_body(doc) + texi_sections(doc, None))
265 def gen_doc(schema, output_dir, prefix):
266 if not qapi.common.doc_required:
267 return
268 vis = QAPISchemaGenDocVisitor(prefix)
269 vis.visit_begin(schema)
270 for doc in schema.docs:
271 if doc.symbol:
272 vis.symbol(doc, schema.lookup_entity(doc.symbol))
273 else:
274 vis.freeform(doc)
275 vis.write(output_dir)