blob: 299dcf92d8e40ae013dc1283180b14e92d80c78d [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 Armbruster860e8772017-03-15 13:57:04 +0100126def texi_body(doc, only_documented=False):
Marc-André Lureau3313b612017-01-13 15:41:29 +0100127 """
128 Format the body of a symbol documentation:
129 - main body
130 - table of arguments
131 - followed by "Returns/Notes/Since/Example" sections
132 """
133 body = texi_format(str(doc.body)) + "\n"
Markus Armbruster860e8772017-03-15 13:57:04 +0100134
135 args = ''
136 for name, section in doc.args.iteritems():
137 if not section.content and not only_documented:
138 continue # Undocumented TODO require doc and drop
139 desc = str(section)
140 opt = ''
141 if section.optional:
142 desc = re.sub(r'^ *#optional *\n?|\n? *#optional *$|#optional',
143 '', desc)
144 opt = ' (optional)'
145 args += "@item @code{'%s'}%s\n%s\n" % (name, opt, texi_format(desc))
146 if args:
Marc-André Lureau3313b612017-01-13 15:41:29 +0100147 body += "@table @asis\n"
Markus Armbruster860e8772017-03-15 13:57:04 +0100148 body += args
Marc-André Lureau3313b612017-01-13 15:41:29 +0100149 body += "@end table\n"
150
151 for section in doc.sections:
152 name, doc = (section.name, str(section))
153 func = texi_format
154 if name.startswith("Example"):
155 func = texi_example
156
157 if name:
Marc-André Lureau1ede77d2017-02-17 13:34:16 +0400158 # prefer @b over @strong, so txt doesn't translate it to *Foo:*
159 body += "\n\n@b{%s:}\n" % name
160
161 body += func(doc)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100162
163 return body
164
165
166def texi_alternate(expr, doc):
167 """Format an alternate to texi"""
168 body = texi_body(doc)
Marc-André Lureau597494a2017-01-25 17:03:07 +0400169 return TYPE_FMT(type="Alternate",
170 name=doc.symbol,
171 body=body)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100172
173
174def texi_union(expr, doc):
175 """Format a union to texi"""
176 discriminator = expr.get("discriminator")
177 if discriminator:
178 union = "Flat Union"
179 else:
180 union = "Simple Union"
181
182 body = texi_body(doc)
Marc-André Lureau597494a2017-01-25 17:03:07 +0400183 return TYPE_FMT(type=union,
184 name=doc.symbol,
185 body=body)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100186
187
188def texi_enum(expr, doc):
189 """Format an enum to texi"""
Markus Armbruster860e8772017-03-15 13:57:04 +0100190 body = texi_body(doc, True)
Marc-André Lureau597494a2017-01-25 17:03:07 +0400191 return TYPE_FMT(type="Enum",
192 name=doc.symbol,
Marc-André Lureau3313b612017-01-13 15:41:29 +0100193 body=body)
194
195
196def texi_struct(expr, doc):
197 """Format a struct to texi"""
198 body = texi_body(doc)
Marc-André Lureau597494a2017-01-25 17:03:07 +0400199 return TYPE_FMT(type="Struct",
200 name=doc.symbol,
201 body=body)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100202
203
204def texi_command(expr, doc):
205 """Format a command to texi"""
206 body = texi_body(doc)
Marc-André Lureau597494a2017-01-25 17:03:07 +0400207 return MSG_FMT(type="Command",
208 name=doc.symbol,
209 body=body)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100210
211
212def texi_event(expr, doc):
213 """Format an event to texi"""
214 body = texi_body(doc)
Marc-André Lureau597494a2017-01-25 17:03:07 +0400215 return MSG_FMT(type="Event",
216 name=doc.symbol,
217 body=body)
Marc-André Lureau3313b612017-01-13 15:41:29 +0100218
219
220def texi_expr(expr, doc):
221 """Format an expr to texi"""
222 (kind, _) = expr.items()[0]
223
224 fmt = {"command": texi_command,
225 "struct": texi_struct,
226 "enum": texi_enum,
227 "union": texi_union,
228 "alternate": texi_alternate,
229 "event": texi_event}[kind]
230
231 return fmt(expr, doc)
232
233
234def texi(docs):
235 """Convert QAPI schema expressions to texi documentation"""
236 res = []
237 for doc in docs:
238 expr = doc.expr
239 if not expr:
240 res.append(texi_body(doc))
241 continue
242 try:
243 doc = texi_expr(expr, doc)
244 res.append(doc)
245 except:
246 print >>sys.stderr, "error at @%s" % doc.info
247 raise
248
249 return '\n'.join(res)
250
251
252def main(argv):
253 """Takes schema argument, prints result to stdout"""
254 if len(argv) != 2:
255 print >>sys.stderr, "%s: need exactly 1 argument: SCHEMA" % argv[0]
256 sys.exit(1)
257
258 schema = qapi.QAPISchema(argv[1])
Markus Armbrusterbc52d032017-03-15 13:56:51 +0100259 if not qapi.doc_required:
260 print >>sys.stderr, ("%s: need pragma 'doc-required' "
261 "to generate documentation" % argv[0])
Marc-André Lureau3313b612017-01-13 15:41:29 +0100262 print texi(schema.docs)
263
264
265if __name__ == "__main__":
266 main(sys.argv)