blob: 6d4e75713d98286342277e0f37c3496f3230c03f [file] [log] [blame]
Marc-André Lureau3313b612017-01-13 15:41:29 +01001#!/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"""
7import re
8import sys
9
10import qapi
11
Marc-André Lureau597494a2017-01-25 17:03:07 +040012MSG_FMT = """
Marc-André Lureau3313b612017-01-13 15:41:29 +010013@deftypefn {type} {{}} {name}
14
15{body}
16
17@end deftypefn
18
19""".format
20
Marc-André Lureau597494a2017-01-25 17:03:07 +040021TYPE_FMT = """
Marc-André Lureau3313b612017-01-13 15:41:29 +010022@deftp {{{type}}} {name}
23
24{body}
25
26@end deftp
27
28""".format
29
30EXAMPLE_FMT = """@example
31{code}
32@end example
33""".format
34
35
36def subst_strong(doc):
37 """Replaces *foo* by @strong{foo}"""
38 return re.sub(r'\*([^*\n]+)\*', r'@emph{\1}', doc)
39
40
41def subst_emph(doc):
42 """Replaces _foo_ by @emph{foo}"""
43 return re.sub(r'\b_([^_\n]+)_\b', r' @emph{\1} ', doc)
44
45
46def subst_vars(doc):
47 """Replaces @var by @code{var}"""
48 return re.sub(r'@([\w-]+)', r'@code{\1}', doc)
49
50
51def subst_braces(doc):
52 """Replaces {} with @{ @}"""
53 return doc.replace("{", "@{").replace("}", "@}")
54
55
56def 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
66def 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
Markus Armbrusteraa964b72017-03-15 13:57:05 +0100126def texi_body(doc):
127 """Format the main documentation body"""
128 return texi_format(str(doc.body)) + '\n'
Markus Armbruster860e8772017-03-15 13:57:04 +0100129
Marc-André Lureau3313b612017-01-13 15:41:29 +0100130
Markus Armbrusteraa964b72017-03-15 13:57:05 +0100131def 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
136def texi_member(member):
137 """Format a table of members item for an object type member"""
138 return "@item @code{'%s'}%s\n" % (
139 member.name, ' (optional)' if member.optional else '')
140
141
142def texi_members(doc, member_func, show_undocumented):
143 """Format the table of members"""
144 items = ''
145 for section in doc.args.itervalues():
146 if not section.content and not show_undocumented:
147 continue # Undocumented TODO require doc and drop
148 desc = re.sub(r'^ *#optional *\n?|\n? *#optional *$|#optional',
149 '', str(section))
150 items += member_func(section.member) + texi_format(desc) + '\n'
151 if not items:
152 return ''
153 return '@table @asis\n' + items + '@end table\n'
154
155
156def texi_sections(doc):
157 """Format additional sections following arguments"""
158 body = ''
Marc-André Lureau3313b612017-01-13 15:41:29 +0100159 for section in doc.sections:
160 name, doc = (section.name, str(section))
161 func = texi_format
162 if name.startswith("Example"):
163 func = texi_example
164
165 if name:
Marc-André Lureau1ede77d2017-02-17 13:34:16 +0400166 # prefer @b over @strong, so txt doesn't translate it to *Foo:*
167 body += "\n\n@b{%s:}\n" % name
168
169 body += func(doc)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100170 return body
171
172
Markus Armbrusteraa964b72017-03-15 13:57:05 +0100173def texi_entity(doc, member_func=texi_member, show_undocumented=False):
174 return (texi_body(doc)
175 + texi_members(doc, member_func, show_undocumented)
176 + texi_sections(doc))
Marc-André Lureau3313b612017-01-13 15:41:29 +0100177
178
Markus Armbrusteraa964b72017-03-15 13:57:05 +0100179class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
180 def __init__(self):
181 self.out = None
182 self.cur_doc = None
Marc-André Lureau3313b612017-01-13 15:41:29 +0100183
Markus Armbrusteraa964b72017-03-15 13:57:05 +0100184 def visit_begin(self, schema):
185 self.out = ''
186
187 def visit_enum_type(self, name, info, values, prefix):
188 doc = self.cur_doc
189 if self.out:
190 self.out += '\n'
191 self.out += TYPE_FMT(type='Enum',
192 name=doc.symbol,
193 body=texi_entity(doc,
194 member_func=texi_enum_value,
195 show_undocumented=True))
196
197 def visit_object_type(self, name, info, base, members, variants):
198 doc = self.cur_doc
199 if not variants:
200 typ = 'Struct'
201 elif variants._tag_name: # TODO unclean member access
202 typ = 'Flat Union'
203 else:
204 typ = 'Simple Union'
205 if self.out:
206 self.out += '\n'
207 self.out += TYPE_FMT(type=typ,
208 name=doc.symbol,
209 body=texi_entity(doc))
210
211 def visit_alternate_type(self, name, info, variants):
212 doc = self.cur_doc
213 if self.out:
214 self.out += '\n'
215 self.out += TYPE_FMT(type='Alternate',
216 name=doc.symbol,
217 body=texi_entity(doc))
218
219 def visit_command(self, name, info, arg_type, ret_type,
220 gen, success_response, boxed):
221 doc = self.cur_doc
222 if self.out:
223 self.out += '\n'
224 self.out += MSG_FMT(type='Command',
225 name=doc.symbol,
226 body=texi_entity(doc))
227
228 def visit_event(self, name, info, arg_type, boxed):
229 doc = self.cur_doc
230 if self.out:
231 self.out += '\n'
232 self.out += MSG_FMT(type='Event',
233 name=doc.symbol,
234 body=texi_entity(doc))
235
236 def symbol(self, doc, entity):
237 self.cur_doc = doc
238 entity.visit(self)
239 self.cur_doc = None
240
241 def freeform(self, doc):
242 assert not doc.args
243 if self.out:
244 self.out += '\n'
245 self.out += texi_body(doc) + texi_sections(doc)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100246
247
Markus Armbrusteraa964b72017-03-15 13:57:05 +0100248def texi_schema(schema):
249 """Convert QAPI schema documentation to Texinfo"""
250 gen = QAPISchemaGenDocVisitor()
251 gen.visit_begin(schema)
252 for doc in schema.docs:
253 if doc.symbol:
254 gen.symbol(doc, schema.lookup_entity(doc.symbol))
255 else:
256 gen.freeform(doc)
257 return gen.out
Marc-André Lureau3313b612017-01-13 15:41:29 +0100258
259
260def main(argv):
261 """Takes schema argument, prints result to stdout"""
262 if len(argv) != 2:
263 print >>sys.stderr, "%s: need exactly 1 argument: SCHEMA" % argv[0]
264 sys.exit(1)
265
266 schema = qapi.QAPISchema(argv[1])
Markus Armbrusterbc52d032017-03-15 13:56:51 +0100267 if not qapi.doc_required:
268 print >>sys.stderr, ("%s: need pragma 'doc-required' "
269 "to generate documentation" % argv[0])
Markus Armbrusteraa964b72017-03-15 13:57:05 +0100270 print texi_schema(schema)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100271
272
273if __name__ == "__main__":
274 main(sys.argv)