Skip to contentSkip to conversation

Add qapi doc generation scripts

PATCH Superseded Marc-André Lureau 2 participants 7 messages Sep 22, 2016 Kbuild

v1 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

cover Add qapi doc generation scripts

Hi,

Add the qapi2texi script and a few optional targets to excercie the generator. The documentation isn't complete yet, so don't bother to build it by default or install it.

Marc-André Lureau (4):
qapi: add qapi2texi script
qapi: fix schema symbol sections
docs: add qapi texi template
build-sys: add qapi doc generation targets

 Makefile                        |  15 ++
 scripts/qapi.py                 |  90 +++++++++++-
 scripts/qapi2texi.py            | 307 ++++++++++++++++++++++++++++++++++++++++
 docs/qapi-code-gen.txt          |  44 ++++--
 docs/qemu-ga-qapi.template.texi |  58 ++++++++
 docs/qemu-qapi.template.texi    | 148 +++++++++++++++++++
 docs/qmp-intro.txt              |  87 ------------
 qapi-schema.json                |   9 +-
 qapi/block-core.json            |   1 +
 qga/qapi-schema.json            |   3 +
 10 files changed, 661 insertions(+), 101 deletions(-)
 create mode 100755 scripts/qapi2texi.py
 create mode 100644 docs/qemu-ga-qapi.template.texi
 create mode 100644 docs/qemu-qapi.template.texi
 delete mode 100644 docs/qmp-intro.txt
Signature · 1 line
2.10.0
#1 lore raw

PATCH 1/4 qapi: add qapi2texi script

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:

##
# = Section
# == 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.

---
 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
scripts/qapi.py +88 -2
index 21bc32f..7c14773 100644
@@ -122,6 +122,69 @@ class QAPIExprError(Exception):
             "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
 
 
+class QAPIDoc:
+    def __init__(self, comment):
+        self.symbol = None
+        self.comment = ""
+        self.args = OrderedDict()
+        self.meta = OrderedDict()
+        self.section = None
+
+        for line in comment.split('\n'):
+            sline = ' '.join(line.split())
+            split = sline.split(' ', 1)
+            key = split[0].rstrip(':')
+
+            if line.startswith(" @"):
+                key = key[1:]
+                sline = split[1] if len(split) > 1 else ""
+                if self.symbol is None:
+                    self.symbol = key
+                else:
+                    self.start_section(self.args, key)
+            elif self.symbol and \
+                    key in ("Since", "Returns",
+                            "Note", "Notes",
+                            "Example", "Examples"):
+                sline = split[1] if len(split) > 1 else ""
+                line = 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] == "" and line == "":
+                self.end_section()
+            else:
+                self.section.append(line)
+        elif self.comment == "":
+            self.comment = line
+        else:
+            self.comment += "\n" + line
+
+    def end_section(self):
+        if self.section is not None:
+            dic = self.section[0]
+            key = self.section[1]
+            doc = "\n".join(self.section[2:])
+            if key != "Example":
+                doc = doc.strip()
+            dic[key] = doc
+            self.section = None
+
+    def start_section(self, dic, key):
+        self.end_section()
+        self.section = [dic, key]  # .. remaining elems will be the doc
+
+
 class QAPISchemaParser(object):
 
     def __init__(self, fp, previously_included=[], incl_info=None):
@@ -137,11 +200,14 @@ class QAPISchemaParser(object):
         self.line = 1
         self.line_pos = 0
         self.exprs = []
+        self.comment = None
+        self.apidoc = incl_info['doc'] if incl_info else []
         self.accept()
 
         while self.tok is not None:
             expr_info = {'file': fname, 'line': self.line,
-                         'parent': self.incl_info}
+                         'parent': self.incl_info, 'doc': self.apidoc}
+            self.apidoc = []
             expr = self.get_expr(False)
             if isinstance(expr, dict) and "include" in expr:
                 if len(expr) != 1:
@@ -162,6 +228,8 @@ class QAPISchemaParser(object):
                     inf = inf['parent']
                 # skip multiple include of the same file
                 if incl_abs_fname in previously_included:
+                    expr_info['doc'].extend(self.apidoc)
+                    self.apidoc = expr_info['doc']
                     continue
                 try:
                     fobj = open(incl_abs_fname, 'r')
@@ -176,6 +244,12 @@ class QAPISchemaParser(object):
                              'info': expr_info}
                 self.exprs.append(expr_elem)
 
+    def append_doc(self):
+        if self.comment:
+            apidoc = QAPIDoc(self.comment)
+            self.apidoc.append(apidoc)
+            self.comment = None
+
     def accept(self):
         while True:
             self.tok = self.src[self.cursor]
@@ -184,8 +258,20 @@ class QAPISchemaParser(object):
             self.val = None
 
             if self.tok == '#':
-                self.cursor = self.src.find('\n', self.cursor)
+                end = self.src.find('\n', self.cursor)
+                line = self.src[self.cursor:end+1]
+                # start a comment section after ##
+                if line[0] == "#":
+                    if self.comment is None:
+                        self.comment = ""
+                # skip modeline
+                elif line.find("-*") == -1 and self.comment is not None:
+                    self.comment += line
+                if self.src[end] == "\n" and self.src[end+1] == "\n":
+                    self.append_doc()
+                self.cursor = end
             elif self.tok in "{}:,[]":
+                self.append_doc()
                 return
             elif self.tok == "'":
                 string = ''
scripts/qapi2texi.py new file +307 -0

307 lines not on this page · raw message

docs/qapi-code-gen.txt +34 -10

62 lines not on this page · raw message

Signature · 1 line
2.10.0
#2 lore raw

Re: [Qemu-devel] [PATCH 1/4] qapi: add qapi2texi script

Quoted 15 lines · Marc-André Lureau

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:

##
# = Section
# == Subsection
#
# Some text foo with *emphasis*
# 1. with a list
# 2. like that
#
# And some code:

Quoted 3 lines
  # | $ echo foo
  # | <- do this
  # | -> get that

Arrows are backwards; should be -> do this, <- get that.

Quoted 33 lines

#
##

##
# @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.

Quoted 7 lines
---
 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

Not a close review at this point, so much as first impressions...

scripts/qapi2texi.py line 4

Quoted 6 lines

+++ b/scripts/qapi2texi.py

scripts/qapi2texi.py new file +4 -0
@@ -0,0 +1,307 @@
+#!/usr/bin/env python
+# QAPI texi generator
+#
+# This work is licensed under the terms of the GNU GPL, version 2.

Can you fix this to GPLv2+? Our GPLv2-only scripts were a mistake that should not be repeated.

Quoted 30 lines
docs/qapi-code-gen.txt +9 -10
+++ 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.
 
 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:
 
     ##
@@ -73,12 +70,39 @@ x.y.z)' comment.  For example:
     #           (Since 2.0)
     #
     # Since: 0.14.0
+    #

docs/qapi-code-gen.txt x.y.z)' comment. For example: · line 83

Quoted 10 lines
docs/qapi-code-gen.txt +9 -0
+    # Notes: You can also make a list:
+    #        - with items
+    #        - like this
+    #
+    # Example:
+    #
+    # -> { "execute": ... }
+    # <- { "return": ... }
+    #
     ##

Thanks for remembering this. It does no good to parse a nebulous format, but calling out the format means we have something to copy from and to bring existing outliers into conformance.

Quoted 9 lines
docs/qapi-code-gen.txt +4 -0
     { 'struct': 'BlockStats',
       'data': {'*device': 'str', 'stats': 'BlockDeviceStats',
                '*parent': 'BlockStats',
                '*backing': 'BlockStats'} }
 
+It's also possible to create documentation sections, such as:
+
+    ##
+    # = Section

docs/qapi-code-gen.txt x.y.z)' comment. For example: · line 102

Quoted 10 lines
docs/qapi-code-gen.txt +10 -0
+    # == Subsection
+    #
+    # Some text foo with *emphasis*
+    # 1. with a list
+    # 2. like that
+    #
+    # And some code:
+    # | $ echo foo
+    # | <- do this
+    # | -> get that

Again, arrows look backwards here.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#3 lore raw

PATCH 2/4 qapi: fix schema symbol sections

In reply to Marc-André Lureau

According to documentation, there needs to be '##' to start a symbol section, that's also what the documentation parser expects.

---
 qapi-schema.json     | 9 +++++++--
 qapi/block-core.json | 1 +
 qga/qapi-schema.json | 3 +++
 3 files changed, 11 insertions(+), 2 deletions(-)
qapi-schema.json +7 -2
index e507061..f07ffd7 100644
@@ -65,6 +65,7 @@
 { 'enum': 'LostTickPolicy',
   'data': ['discard', 'delay', 'merge', 'slew' ] }
 
+##
 # @add_client
 #
 # Allow client connections for VNC, Spice and socket based
@@ -439,6 +440,7 @@
            'cache-miss': 'int', 'cache-miss-rate': 'number',
            'overflow': 'int' } }
 
+##
 # @MigrationStatus:
 #
 # An enumeration of migration status.
@@ -617,6 +619,7 @@
 ##
 { 'command': 'query-migrate-capabilities', 'returns':   ['MigrationCapabilityStatus']}
 
+##
 # @MigrationParameter
 #
 # Migration parameters enumeration
@@ -665,7 +668,7 @@
            'cpu-throttle-initial', 'cpu-throttle-increment',
            'tls-creds', 'tls-hostname'] }
 
-#
+##
 # @migrate-set-parameters
 #
 # Set the following migration parameters
@@ -710,7 +713,7 @@
             '*tls-creds': 'str',
             '*tls-hostname': 'str'} }
 
-#
+##
 # @MigrationParameters
 #
 # @compress-level: compression level
@@ -2172,6 +2175,7 @@
 ##
 { 'command': 'migrate-incoming', 'data': {'uri': 'str' } }
 
+##
 # @xen-save-devices-state:
 #
 # Save the state of all devices to file. The RAM and the block devices
@@ -3359,6 +3363,7 @@
             'modelb': 'CpuModelInfo' },
   'returns': 'CpuModelBaselineInfo' }
 
+##
 # @AddfdInfo:
 #
 # Information about a file descriptor that was added to an fd set.
qapi/block-core.json +1 -0
index 24223fd..043c21e 100644
@@ -2665,6 +2665,7 @@
             'offset': 'int',
             'speed' : 'int' } }
 
+##
 # @PreallocMode
 #
 # Preallocation mode of QEMU image file
qga/qapi-schema.json +3 -0
index c21f308..09c9728 100644
@@ -837,6 +837,7 @@
 { 'command': 'guest-set-user-password',
   'data': { 'username': 'str', 'password': 'str', 'crypted': 'bool' } }
 
+##
 # @GuestMemoryBlock:
 #
 # @phys-index: Arbitrary guest-specific unique identifier of the MEMORY BLOCK.
@@ -936,6 +937,7 @@
   'data':    {'mem-blks': ['GuestMemoryBlock'] },
   'returns': ['GuestMemoryBlockResponse'] }
 
+##
 # @GuestMemoryBlockInfo:
 #
 # @size: the size (in bytes) of the guest memory blocks,
@@ -960,6 +962,7 @@
 { 'command': 'guest-get-memory-block-info',
   'returns': 'GuestMemoryBlockInfo' }
 
+##
 # @GuestExecStatus:
 #
 # @exited: true if process has already terminated.
Signature · 1 line
2.10.0
Reviewed-by on v1 2/4
#4 lore raw

Re: [Qemu-devel] [PATCH 2/4] qapi: fix schema symbol sections

Quoted 9 lines · Marc-André Lureau

According to documentation, there needs to be '##' to start a symbol section, that's also what the documentation parser expects.

---
 qapi-schema.json     | 9 +++++++--
 qapi/block-core.json | 1 +
 qga/qapi-schema.json | 3 +++
 3 files changed, 11 insertions(+), 2 deletions(-)
Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#5 lore raw

PATCH 3/4 docs: add qapi texi template

In reply to Marc-André Lureau

The qapi2texi scripts uses a template for the texi file. Since we are going to generate the documentation in multiple formats, move qmp-intro to qemu-qapi template. (it would be nice to write something similar for qemu-ga, but this is left for a future patch)

---
 docs/qemu-ga-qapi.template.texi |  58 ++++++++++++++++
 docs/qemu-qapi.template.texi    | 148 ++++++++++++++++++++++++++++++++++++++++
 docs/qmp-intro.txt              |  87 -----------------------
 3 files changed, 206 insertions(+), 87 deletions(-)
 create mode 100644 docs/qemu-ga-qapi.template.texi
 create mode 100644 docs/qemu-qapi.template.texi
 delete mode 100644 docs/qmp-intro.txt
docs/qemu-ga-qapi.template.texi new file +58 -0
new file mode 100644
index 0000000..3ddbf56
@@ -0,0 +1,58 @@
+\input texinfo
+@setfilename qemu-ga-qapi
+@documentlanguage en
+@exampleindent 0
+@paragraphindent 0
+
+@settitle QEMU-GA QAPI Reference Manual
+
+@ifinfo
+@direntry
+* QEMU-GA-QAPI: (qemu-doc).    QEMU-GA QAPI Reference Manual
+@end direntry
+@end ifinfo
+
+@iftex
+@titlepage
+@sp 7
+@center @titlefont{{QEMU Guest Agent {version}}}
+@sp 1
+@center @titlefont{{QAPI Reference Manual}}
+@sp 3
+@end titlepage
+@end iftex
+
+@ifnottex
+@node Top
+@top
+
+This is the QEMU Guest Agent QAPI reference for QEMU {version}.
+
+@menu
+* API Reference::
+* Commands and Events Index::
+* Data Types Index::
+@end menu
+
+@end ifnottex
+
+@contents
+
+@node API Reference
+@chapter API Reference
+
+@c man begin DESCRIPTION
+{qapi}
+@c man end
+
+@c man begin SEEALSO
+The HTML documentation of QEMU for more precise information.
+@c man end
+
+@node Commands and Events Index
+@unnumbered Commands and Events Index
+@printindex fn
+@node Data Types Index
+@unnumbered Data Types Index
+@printindex tp
+@bye
docs/qemu-qapi.template.texi new file +148 -0

148 lines not on this page · raw message

docs/qmp-intro.txt deleted +0 -87

87 lines not on this page · raw message

Signature · 1 line
2.10.0
#6 lore raw

PATCH 4/4 build-sys: add qapi doc generation targets

In reply to Marc-André Lureau

Add qapi doc generation targets, qemu-qapi.texi, qemu-ga-qapi.texi (implicit pdf works too) and qemu-qapi.txt. The generated documentation isn't complete yet, so don't bother to build it by default or install it yet.

---
 Makefile | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
Makefile +15 -0
index f103616..6e00559 100644
@@ -269,6 +269,7 @@ qemu-ga$(EXESUF): QEMU_CFLAGS += -I qga/qapi-generated
 gen-out-type = $(subst .,-,$(suffix $@))
 
 qapi-py = $(SRC_PATH)/scripts/qapi.py $(SRC_PATH)/scripts/ordereddict.py
+qapi-py += $(SRC_PATH)/scripts/qapi2texi.py
 
 qga/qapi-generated/qga-qapi-types.c qga/qapi-generated/qga-qapi-types.h :\
 $(SRC_PATH)/qga/qapi-schema.json $(SRC_PATH)/scripts/qapi-types.py $(qapi-py)
@@ -558,9 +559,23 @@ qemu-monitor.texi: $(SRC_PATH)/hmp-commands.hx $(SRC_PATH)/scripts/hxtool
 qemu-monitor-info.texi: $(SRC_PATH)/hmp-commands-info.hx $(SRC_PATH)/scripts/hxtool
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -t < $< > $@,"  GEN   $@")
 
+qemu-qapi.txt: qemu-qapi.texi
+	$(call quiet-command,LC_ALL=C $(MAKEINFO) $(MAKEINFOFLAGS) --plaintext $< -o $@,\
+	"  GEN   $@")
+
 qemu-img-cmds.texi: $(SRC_PATH)/qemu-img-cmds.hx $(SRC_PATH)/scripts/hxtool
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -t < $< > $@,"  GEN   $@")
 
+qemu-qapi.texi: $(qapi-modules) $(qapi-py) \
+	$(SRC_PATH)/docs/qemu-qapi.template.texi
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi2texi.py \
+	$(SRC_PATH)/docs/qemu-qapi.template.texi $(VERSION) $< > $@,"  GEN   $@")
+
+qemu-ga-qapi.texi: $(SRC_PATH)/qga/qapi-schema.json $(qapi-py) \
+	$(SRC_PATH)/docs/qemu-ga-qapi.template.texi
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi2texi.py \
+	$(SRC_PATH)/docs/qemu-ga-qapi.template.texi $(VERSION) $< > $@,"  GEN   $@")
+
 qemu.1: qemu-doc.texi qemu-options.texi qemu-monitor.texi qemu-monitor-info.texi
 	$(call quiet-command, \
 	  perl -Ww -- $(SRC_PATH)/scripts/texi2pod.pl $< qemu.pod && \
Signature · 1 line
2.10.0