Received: from eggs.gnu.org ([2001:4830:134:3::10]:37969) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1c4rBs-0008AV-7B for qemu-devel@nongnu.org; Thu, 10 Nov 2016 10:23:06 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1c4rBo-0008FB-UX for qemu-devel@nongnu.org; Thu, 10 Nov 2016 10:23:00 -0500 Received: from mx1.redhat.com ([209.132.183.28]:35912) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1c4rBo-0008EI-Le for qemu-devel@nongnu.org; Thu, 10 Nov 2016 10:22:56 -0500 Received: from int-mx09.intmail.prod.int.phx2.redhat.com (int-mx09.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 003E361E51 for ; Thu, 10 Nov 2016 15:22:56 +0000 (UTC) From: =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= Date: Thu, 10 Nov 2016 19:22:05 +0400 Message-Id: <20161110152209.18379-12-marcandre.lureau@redhat.com> In-Reply-To: <20161110152209.18379-1-marcandre.lureau@redhat.com> References: <20161110152209.18379-1-marcandre.lureau@redhat.com> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Subject: [Qemu-devel] [PATCH v4 11/15] qapi: add qapi2texi script List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , To: qemu-devel@nongnu.org Cc: eblake@redhat.com, armbru@redhat.com, =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= As the name suggests, the qapi2texi script converts JSON QAPI description into a texi file suitable for different target formats (info/man/txt/pdf/html...). It parses the following kind of blocks: Free-form: ## # =3D Section # =3D=3D Subsection # # Some text foo with *emphasis* # 1. with a list # 2. like that # # And some code: # | $ echo foo # | -> do this # | <- get that # ## Symbol: ## # @symbol: # # Symbol body ditto ergo sum. Foo bar # baz ding. # # @arg: foo # @arg: #optional foo # # Returns: returns bla bla # Or bla blah # # Since: version # Notes: notes, comments can have # - itemized list # - like this # # Example: # # -> { "execute": "quit" } # <- { "return": {} } # ## That's roughly following the following BNF grammar: api_comment =3D "##\n" comment "##\n" comment =3D freeform_comment | symbol_comment freeform_comment =3D { "#" text "\n" } symbol_comment =3D "#" "@" name ":\n" { freeform | member | meta } member =3D "#" '@' name ':' [ text ] freeform_comment meta =3D "#" ( "Returns:", "Since:", "Note:", "Notes:", "Example:", "Exam= ples:" ) [ text ] freeform_comment text =3D free-text markdown-like, "#optional" for members Thanks to the following json expressions, the documentation is enhanced with extra information about the type of arguments and return value expected. Signed-off-by: Marc-Andr=C3=A9 Lureau --- scripts/qapi.py | 175 ++++++++++++++++++++++++++- scripts/qapi2texi.py | 316 +++++++++++++++++++++++++++++++++++++++++++= ++++++ docs/qapi-code-gen.txt | 44 +++++-- 3 files changed, 524 insertions(+), 11 deletions(-) create mode 100755 scripts/qapi2texi.py diff --git a/scripts/qapi.py b/scripts/qapi.py index 21bc32f..ed52ee4 100644 --- a/scripts/qapi.py +++ b/scripts/qapi.py @@ -122,6 +122,103 @@ class QAPIExprError(Exception): "%s:%d: %s" % (self.info['file'], self.info['line'], self.ms= g) =20 =20 +class QAPIDoc(object): + def __init__(self, parser): + self.parser =3D parser + self.symbol =3D None + self.body =3D [] + # args is {'arg': 'doc', ...} + self.args =3D OrderedDict() + # meta is [(Since/Notes/Examples/Returns:, 'doc'), ...] + self.meta =3D [] + # the current section to populate, array of [dict, key, comment.= ..] + self.section =3D None + self.expr_elem =3D None + + def get_body(self): + return "\n".join(self.body) + + def has_meta(self, name): + """Returns True if the doc has a meta section 'name'""" + return next((True for i in self.meta if i[0] =3D=3D name), False= ) + + def append(self, line): + """Adds a # comment line, to be parsed and added in a section""" + line =3D line[1:] + if len(line) =3D=3D 0: + self._append_section(line) + return + + if line[0] !=3D ' ': + raise QAPISchemaError(self.parser, "missing space after #") + + line =3D line[1:] + # take the first word out + name =3D line.split(' ', 1)[0] + if name.startswith("@") and name.endswith(":"): + line =3D line[len(name):] + name =3D name[1:-1] + if self.symbol is None: + # the first is the symbol this APIDoc object documents + if len(self.body): + raise QAPISchemaError(self.parser, "symbol must come= first") + self.symbol =3D name + else: + # else an arg + self._start_args_section(name) + elif self.symbol and name in ( + "Returns:", "Since:", + # those are often singular or plural + "Note:", "Notes:", + "Example:", "Examples:"): + # new "meta" section + line =3D line[len(name):] + self._start_meta_section(name[:-1]) + + self._append_section(line) + + def _start_args_section(self, name): + self.end_section() + if self.args.has_key(name): + raise QAPISchemaError(self.parser, "'%s' arg duplicated" % n= ame) + self.section =3D [self.args, name] + + def _start_meta_section(self, name): + self.end_section() + if name in ("Returns", "Since") and self.has_meta(name): + raise QAPISchemaError(self.parser, "'%s' section duplicated"= % name) + self.section =3D [self.meta, name] + + def _append_section(self, line): + """Add a comment to the current section, or the comment body""" + if self.section: + name =3D self.section[1] + if not name.startswith("Example"): + # an empty line ends the section, except with Example + if len(self.section) > 2 and len(line) =3D=3D 0: + self.end_section() + return + # Example is verbatim + line =3D line.strip() + if len(line) > 0: + self.section.append(line) + else: + self.body.append(line.strip()) + + def end_section(self): + if self.section is not None: + target =3D self.section[0] + name =3D self.section[1] + if len(self.section) < 3: + raise QAPISchemaError(self.parser, "Empty doc section") + doc =3D "\n".join(self.section[2:]) + if isinstance(target, dict): + target[name] =3D doc + else: + target.append((name, doc)) + self.section =3D None + + class QAPISchemaParser(object): =20 def __init__(self, fp, previously_included=3D[], incl_info=3DNone): @@ -137,9 +234,15 @@ class QAPISchemaParser(object): self.line =3D 1 self.line_pos =3D 0 self.exprs =3D [] + self.docs =3D [] self.accept() =20 while self.tok is not None: + if self.tok =3D=3D '#' and self.val.startswith('##'): + doc =3D self.get_doc() + self.docs.append(doc) + continue + expr_info =3D {'file': fname, 'line': self.line, 'parent': self.incl_info} expr =3D self.get_expr(False) @@ -160,6 +263,7 @@ class QAPISchemaParser(object): raise QAPIExprError(expr_info, "Inclusion loop f= or %s" % include) inf =3D inf['parent'] + # skip multiple include of the same file if incl_abs_fname in previously_included: continue @@ -171,12 +275,40 @@ class QAPISchemaParser(object): exprs_include =3D QAPISchemaParser(fobj, previously_incl= uded, expr_info) self.exprs.extend(exprs_include.exprs) + self.docs.extend(exprs_include.docs) else: expr_elem =3D {'expr': expr, 'info': expr_info} + if len(self.docs) > 0: + self.docs[-1].expr_elem =3D expr_elem self.exprs.append(expr_elem) =20 - def accept(self): + def get_doc(self): + if self.val !=3D '##': + raise QAPISchemaError(self, "Doc comment not starting with '= ##'") + + doc =3D QAPIDoc(self) + self.accept(False) + while self.tok =3D=3D '#': + if self.val.startswith('##'): + # ## ends doc + if self.val !=3D '##': + raise QAPISchemaError(self, "non-empty '##' line %s" + % self.val) + self.accept() + doc.end_section() + return doc + else: + doc.append(self.val) + self.accept(False) + + if self.val !=3D '##': + raise QAPISchemaError(self, "Doc comment not finishing with = '##'") + + doc.end_section() + return doc + + def accept(self, skip_comment=3DTrue): while True: self.tok =3D self.src[self.cursor] self.pos =3D self.cursor @@ -184,7 +316,13 @@ class QAPISchemaParser(object): self.val =3D None =20 if self.tok =3D=3D '#': + if self.src[self.cursor] =3D=3D '#': + # ## starts a doc comment + skip_comment =3D False self.cursor =3D self.src.find('\n', self.cursor) + self.val =3D self.src[self.pos:self.cursor] + if not skip_comment: + return elif self.tok in "{}:,[]": return elif self.tok =3D=3D "'": @@ -779,6 +917,41 @@ def check_exprs(exprs): =20 return exprs =20 +def check_docs(docs): + for doc in docs: + expr_elem =3D doc.expr_elem + if not expr_elem: + continue + + expr =3D expr_elem['expr'] + for i in ('enum', 'union', 'alternate', 'struct', 'command', 'ev= ent'): + if i in expr: + meta =3D i + break + + info =3D expr_elem['info'] + name =3D expr[meta] + if doc.symbol !=3D name: + raise QAPIExprError(info, + "Documentation symbol mismatch '%s' !=3D= '%s'" + % (doc.symbol, name)) + if not 'command' in expr and doc.has_meta('Returns'): + raise QAPIExprError(info, "Invalid return documentation") + + doc_args =3D set(doc.args.keys()) + if meta =3D=3D 'union': + data =3D expr.get('base', []) + else: + data =3D expr.get('data', []) + if isinstance(data, dict): + data =3D data.keys() + args =3D set([k.strip('*') for k in data]) + if meta =3D=3D 'alternate' or \ + (meta =3D=3D 'union' and not expr.get('discriminator')): + args.add('type') + if not doc_args.issubset(args): + raise QAPIExprError(info, "Members documentation is not a su= bset of" + " API %r > %r" % (list(doc_args), list(a= rgs))) =20 # # Schema compiler frontend diff --git a/scripts/qapi2texi.py b/scripts/qapi2texi.py new file mode 100755 index 0000000..7e2440c --- /dev/null +++ b/scripts/qapi2texi.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python +# QAPI texi generator +# +# This work is licensed under the terms of the GNU LGPL, version 2+. +# See the COPYING file in the top-level directory. +"""This script produces the documentation of a qapi schema in texinfo fo= rmat""" +import re +import sys + +from qapi import * + +COMMAND_FMT =3D """ +@deftypefn {type} {{{ret}}} {name} @ +{{{args}}} + +{body} + +@end deftypefn + +""".format + +ENUM_FMT =3D """ +@deftp Enum {name} + +{body} + +@end deftp + +""".format + +STRUCT_FMT =3D """ +@deftp {type} {name} @ +{{{attrs}}} + +{body} + +@end deftp + +""".format + +EXAMPLE_FMT =3D """@example +{code} +@end example +""".format + + +def subst_strong(doc): + """Replaces *foo* by @strong{foo}""" + return re.sub(r'\*([^_\n]+)\*', r'@emph{\1}', doc) + + +def subst_emph(doc): + """Replaces _foo_ by @emph{foo}""" + return re.sub(r'\s_([^_\n]+)_\s', r' @emph{\1} ', doc) + + +def subst_vars(doc): + """Replaces @var by @var{var}""" + return re.sub(r'@([\w-]+)', r'@var{\1}', doc) + + +def subst_braces(doc): + """Replaces {} with @{ @}""" + return doc.replace("{", "@{").replace("}", "@}") + + +def texi_example(doc): + """Format @example""" + doc =3D subst_braces(doc).strip('\n') + return EXAMPLE_FMT(code=3Ddoc) + + +def texi_comment(doc): + """ + Format a comment + + Lines starting with: + - |: generates an @example + - =3D: generates @section + - =3D=3D: generates @subsection + - 1. or 1): generates an @enumerate @item + - o/*/-: generates an @itemize list + """ + lines =3D [] + doc =3D subst_braces(doc) + doc =3D subst_vars(doc) + doc =3D subst_emph(doc) + doc =3D subst_strong(doc) + inlist =3D "" + lastempty =3D False + for line in doc.split('\n'): + empty =3D line =3D=3D "" + + if line.startswith("| "): + line =3D EXAMPLE_FMT(code=3Dline[1:]) + elif line.startswith("=3D "): + line =3D "@section " + line[1:] + elif line.startswith("=3D=3D "): + line =3D "@subsection " + line[2:] + elif re.match("^([0-9]*[.)]) ", line): + if not inlist: + lines.append("@enumerate") + inlist =3D "enumerate" + line =3D line[line.find(" ")+1:] + lines.append("@item") + elif re.match("^[o*-] ", line): + if not inlist: + lines.append("@itemize %s" % {'o': "@bullet", + '*': "@minus", + '-': ""}[line[0]]) + inlist =3D "itemize" + lines.append("@item") + line =3D line[2:] + elif lastempty and inlist: + lines.append("@end %s\n" % inlist) + inlist =3D "" + + lastempty =3D empty + lines.append(line) + + if inlist: + lines.append("@end %s\n" % inlist) + return "\n".join(lines) + + +def texi_args(expr): + """ + Format the functions/structure/events.. arguments/members + """ + data =3D expr["data"] if "data" in expr else {} + if isinstance(data, str): + args =3D data + else: + arg_list =3D [] + for name, typ in data.iteritems(): + # optional arg + if name.startswith("*"): + name =3D name[1:] + arg_list.append("['%s': @var{%s}]" % (name, typ)) + # regular arg + else: + arg_list.append("'%s': @var{%s}" % (name, typ)) + args =3D ", ".join(arg_list) + return args + +def section_order(section): + return {"Returns": 0, + "Note": 1, + "Notes": 1, + "Since": 2, + "Example": 3, + "Examples": 3}[section] + +def texi_body(doc, arg=3D"@var"): + """ + Format the body of a symbol documentation: + - a table of arguments + - followed by "Returns/Notes/Since/Example" sections + """ + body =3D "@table %s\n" % arg + for arg, desc in doc.args.iteritems(): + if desc.startswith("#optional"): + desc =3D desc[10:] + arg +=3D "*" + elif desc.endswith("#optional"): + desc =3D desc[:-10] + arg +=3D "*" + body +=3D "@item %s\n%s\n" % (arg, texi_comment(desc)) + body +=3D "@end table\n" + body +=3D texi_comment(doc.get_body()) + + meta =3D sorted(doc.meta, key=3Dlambda i: section_order(i[0])) + for m in meta: + key, doc =3D m + func =3D texi_comment + if key.startswith("Example"): + func =3D texi_example + + body +=3D "\n@quotation %s\n%s\n@end quotation" % \ + (key, func(doc)) + return body + + +def texi_alternate(expr, doc): + """ + Format an alternate to texi + """ + args =3D texi_args(expr) + body =3D texi_body(doc) + return STRUCT_FMT(type=3D"Alternate", + name=3Ddoc.symbol, + attrs=3D"[ " + args + " ]", + body=3Dbody) + + +def texi_union(expr, doc): + """ + Format an union to texi + """ + args =3D texi_args(expr) + body =3D texi_body(doc) + return STRUCT_FMT(type=3D"Union", + name=3Ddoc.symbol, + attrs=3D"[ " + args + " ]", + body=3Dbody) + + +def texi_enum(_, doc): + """ + Format an enum to texi + """ + body =3D texi_body(doc, "@samp") + return ENUM_FMT(name=3Ddoc.symbol, + body=3Dbody) + + +def texi_struct(expr, doc): + """ + Format a struct to texi + """ + args =3D texi_args(expr) + body =3D texi_body(doc) + return STRUCT_FMT(type=3D"Struct", + name=3Ddoc.symbol, + attrs=3D"@{ " + args + " @}", + body=3Dbody) + + +def texi_command(expr, doc): + """ + Format a command to texi + """ + args =3D texi_args(expr) + ret =3D expr["returns"] if "returns" in expr else "" + body =3D texi_body(doc) + return COMMAND_FMT(type=3D"Command", + name=3Ddoc.symbol, + ret=3Dret, + args=3D"(" + args + ")", + body=3Dbody) + + +def texi_event(expr, doc): + """ + Format an event to texi + """ + args =3D texi_args(expr) + body =3D texi_body(doc) + return COMMAND_FMT(type=3D"Event", + name=3Ddoc.symbol, + ret=3D"", + args=3D"(" + args + ")", + body=3Dbody) + + +def texi(docs): + """ + Convert QAPI schema expressions to texi documentation + """ + res =3D [] + for doc in docs: + try: + expr_elem =3D doc.expr_elem + if expr_elem is None: + res.append(texi_body(doc)) + continue + + expr =3D expr_elem['expr'] + (kind, _) =3D expr.items()[0] + + fmt =3D {"command": texi_command, + "struct": texi_struct, + "enum": texi_enum, + "union": texi_union, + "alternate": texi_alternate, + "event": texi_event} + try: + fmt =3D fmt[kind] + except KeyError: + raise ValueError("Unknown expression kind '%s'" % kind) + res.append(fmt(expr, doc)) + except: + print >>sys.stderr, "error at @%s" % qapi + raise + + return '\n'.join(res) + + +def parse_schema(fname): + """ + Parse the given schema file and return the exprs + """ + try: + schema =3D QAPISchemaParser(open(fname, "r")) + check_exprs(schema.exprs) + check_docs(schema.docs) + return schema.docs + except (QAPISchemaError, QAPIExprError), err: + print >>sys.stderr, err + exit(1) + + +def main(argv): + """ + Takes schema argument, prints result to stdout + """ + if len(argv) !=3D 2: + print >>sys.stderr, "%s: need exactly 1 argument: SCHEMA" % argv= [0] + sys.exit(1) + + docs =3D parse_schema(argv[1]) + print texi(docs) + + +if __name__ =3D=3D "__main__": + main(sys.argv) diff --git a/docs/qapi-code-gen.txt b/docs/qapi-code-gen.txt index 2841c51..d82e251 100644 --- a/docs/qapi-code-gen.txt +++ b/docs/qapi-code-gen.txt @@ -45,16 +45,13 @@ QAPI parser does not). At present, there is no place= where a QAPI schema requires the use of JSON numbers or null. =20 Comments are allowed; anything between an unquoted # and the following -newline is ignored. Although there is not yet a documentation -generator, a form of stylized comments has developed for consistently -documenting details about an expression and when it was added to the -schema. The documentation is delimited between two lines of ##, then -the first line names the expression, an optional overview is provided, -then individual documentation about each member of 'data' is provided, -and finally, a 'Since: x.y.z' tag lists the release that introduced -the expression. Optional members are tagged with the phrase -'#optional', often with their default value; and extensions added -after the expression was first released are also given a '(since +newline is ignored. The documentation is delimited between two lines +of ##, then the first line names the expression, an optional overview +is provided, then individual documentation about each member of 'data' +is provided, and finally, a 'Since: x.y.z' tag lists the release that +introduced the expression. Optional members are tagged with the +phrase '#optional', often with their default value; and extensions +added after the expression was first released are also given a '(since x.y.z)' comment. For example: =20 ## @@ -73,12 +70,39 @@ x.y.z)' comment. For example: # (Since 2.0) # # Since: 0.14.0 + # + # Notes: You can also make a list: + # - with items + # - like this + # + # Example: + # + # -> { "execute": ... } + # <- { "return": ... } + # ## { 'struct': 'BlockStats', 'data': {'*device': 'str', 'stats': 'BlockDeviceStats', '*parent': 'BlockStats', '*backing': 'BlockStats'} } =20 +It's also possible to create documentation sections, such as: + + ## + # =3D Section + # =3D=3D Subsection + # + # Some text foo with *emphasis* + # 1. with a list + # 2. like that + # + # And some code: + # | $ echo foo + # | -> do this + # | <- get that + # + ## + The schema sets up a series of types, as well as commands and events that will use those types. Forward references are allowed: the parser scans in two passes, where the first pass learns all type names, and --=20 2.10.0