Received: from eggs.gnu.org ([2001:4830:134:3::10]:36961) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1bn6OF-0003QK-Il for qemu-devel@nongnu.org; Thu, 22 Sep 2016 11:58:28 -0400 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1bn6OC-0000Pv-9k for qemu-devel@nongnu.org; Thu, 22 Sep 2016 11:58:22 -0400 Received: from mx1.redhat.com ([209.132.183.28]:60124) by eggs.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1bn6OB-0000Pj-Va for qemu-devel@nongnu.org; Thu, 22 Sep 2016 11:58:20 -0400 Received: from int-mx11.intmail.prod.int.phx2.redhat.com (int-mx11.intmail.prod.int.phx2.redhat.com [10.5.11.24]) (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 3ED554DBA2 for ; Thu, 22 Sep 2016 15:58:19 +0000 (UTC) From: =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= Date: Thu, 22 Sep 2016 19:58:05 +0400 Message-Id: <20160922155808.8504-2-marcandre.lureau@redhat.com> In-Reply-To: <20160922155808.8504-1-marcandre.lureau@redhat.com> References: <20160922155808.8504-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 1/4] 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 standalone texi file suitable for different target formats. It parses the following kind of blocks with some little variations: ## # =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 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 # # and continue... # # Example: # # -> { "execute": "quit" } # <- { "return": {} } # ## Thanks to the json declaration, it's able to give extra information about the type of arguments and return value expected. Signed-off-by: Marc-Andr=C3=A9 Lureau --- scripts/qapi.py | 90 ++++++++++++++- scripts/qapi2texi.py | 307 +++++++++++++++++++++++++++++++++++++++++++= ++++++ docs/qapi-code-gen.txt | 44 +++++-- 3 files changed, 429 insertions(+), 12 deletions(-) create mode 100755 scripts/qapi2texi.py diff --git a/scripts/qapi.py b/scripts/qapi.py index 21bc32f..7c14773 100644 --- a/scripts/qapi.py +++ b/scripts/qapi.py @@ -122,6 +122,69 @@ class QAPIExprError(Exception): "%s:%d: %s" % (self.info['file'], self.info['line'], self.ms= g) =20 =20 +class QAPIDoc: + def __init__(self, comment): + self.symbol =3D None + self.comment =3D "" + self.args =3D OrderedDict() + self.meta =3D OrderedDict() + self.section =3D None + + for line in comment.split('\n'): + sline =3D ' '.join(line.split()) + split =3D sline.split(' ', 1) + key =3D split[0].rstrip(':') + + if line.startswith(" @"): + key =3D key[1:] + sline =3D split[1] if len(split) > 1 else "" + if self.symbol is None: + self.symbol =3D key + else: + self.start_section(self.args, key) + elif self.symbol and \ + key in ("Since", "Returns", + "Note", "Notes", + "Example", "Examples"): + sline =3D split[1] if len(split) > 1 else "" + line =3D None + self.start_section(self.meta, key) + + if self.section and self.section[1] in ("Example", "Examples= "): + self.append_comment(line) + else: + self.append_comment(sline) + + self.end_section() + + def append_comment(self, line): + if line is None: + return + if self.section is not None: + if self.section[-1] =3D=3D "" and line =3D=3D "": + self.end_section() + else: + self.section.append(line) + elif self.comment =3D=3D "": + self.comment =3D line + else: + self.comment +=3D "\n" + line + + def end_section(self): + if self.section is not None: + dic =3D self.section[0] + key =3D self.section[1] + doc =3D "\n".join(self.section[2:]) + if key !=3D "Example": + doc =3D doc.strip() + dic[key] =3D doc + self.section =3D None + + def start_section(self, dic, key): + self.end_section() + self.section =3D [dic, key] # .. remaining elems will be the do= c + + class QAPISchemaParser(object): =20 def __init__(self, fp, previously_included=3D[], incl_info=3DNone): @@ -137,11 +200,14 @@ class QAPISchemaParser(object): self.line =3D 1 self.line_pos =3D 0 self.exprs =3D [] + self.comment =3D None + self.apidoc =3D incl_info['doc'] if incl_info else [] self.accept() =20 while self.tok is not None: expr_info =3D {'file': fname, 'line': self.line, - 'parent': self.incl_info} + 'parent': self.incl_info, 'doc': self.apidoc} + self.apidoc =3D [] expr =3D self.get_expr(False) if isinstance(expr, dict) and "include" in expr: if len(expr) !=3D 1: @@ -162,6 +228,8 @@ class QAPISchemaParser(object): inf =3D inf['parent'] # skip multiple include of the same file if incl_abs_fname in previously_included: + expr_info['doc'].extend(self.apidoc) + self.apidoc =3D expr_info['doc'] continue try: fobj =3D open(incl_abs_fname, 'r') @@ -176,6 +244,12 @@ class QAPISchemaParser(object): 'info': expr_info} self.exprs.append(expr_elem) =20 + def append_doc(self): + if self.comment: + apidoc =3D QAPIDoc(self.comment) + self.apidoc.append(apidoc) + self.comment =3D None + def accept(self): while True: self.tok =3D self.src[self.cursor] @@ -184,8 +258,20 @@ class QAPISchemaParser(object): self.val =3D None =20 if self.tok =3D=3D '#': - self.cursor =3D self.src.find('\n', self.cursor) + end =3D self.src.find('\n', self.cursor) + line =3D self.src[self.cursor:end+1] + # start a comment section after ## + if line[0] =3D=3D "#": + if self.comment is None: + self.comment =3D "" + # skip modeline + elif line.find("-*") =3D=3D -1 and self.comment is not N= one: + self.comment +=3D line + if self.src[end] =3D=3D "\n" and self.src[end+1] =3D=3D = "\n": + self.append_doc() + self.cursor =3D end elif self.tok in "{}:,[]": + self.append_doc() return elif self.tok =3D=3D "'": string =3D '' diff --git a/scripts/qapi2texi.py b/scripts/qapi2texi.py new file mode 100755 index 0000000..77bd1e2 --- /dev/null +++ b/scripts/qapi2texi.py @@ -0,0 +1,307 @@ +#!/usr/bin/env python +# QAPI texi generator +# +# This work is licensed under the terms of the GNU GPL, 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 QAPISchemaParser, QAPISchemaError, check_exprs, QAPIExp= rError + +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_emph(doc): + """Replaces *foo* by @emph{foo}""" + return re.sub(r'\*(\w+)\*', 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) + 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 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.comment) + + for k in ("Returns", "Note", "Notes", "Since", "Example", "Examples"= ): + if k not in doc.meta: + continue + func =3D texi_comment + if k in ("Example", "Examples"): + func =3D texi_example + body +=3D "\n@quotation %s\n%s\n@end quotation" % \ + (k, func(doc.meta[k])) + 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(exprs): + """ + Convert QAPI schema expressions to texi documentation + """ + res =3D [] + for qapi in exprs: + try: + docs =3D qapi['info']['doc'] + expr =3D qapi['expr'] + expr_doc =3D docs[-1] + body =3D docs[0:-1] + + (kind, _) =3D expr.items()[0] + + for doc in body: + res.append(texi_body(doc)) + + 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, 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) + return schema.exprs + except (QAPISchemaError, QAPIExprError), err: + print >>sys.stderr, err + exit(1) + + +def main(argv): + """ + Takes argv arguments, prints result to stdout + """ + if len(argv) !=3D 4: + print >>sys.stderr, "%s: need exactly 3 arguments: " \ + "TEMPLATE VERSION SCHEMA" % argv[0] + sys.exit(1) + + exprs =3D parse_schema(argv[3]) + + templ =3D open(argv[1]) + qapi =3D texi(exprs) + print templ.read().format(version=3Dargv[2], qapi=3Dqapi) + + +if __name__ =3D=3D "__main__": + main(sys.argv) diff --git a/docs/qapi-code-gen.txt b/docs/qapi-code-gen.txt index 5d4c2cd..0bf9a81 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