Skip to contentSkip to conversation

qapi: Doc comment parsing & doc generation work

PATCH In review Markus Armbruster 2 participants 36 messages Feb 16, 2024 – Feb 22, 2024 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

cover qapi: Doc comment parsing & doc generation work

This series tightens doc comment syntax, and makes the doc comment parser easier to maintain.

* PATCH 01-03: Fix and extend tests
* PATCH 04: Drop dead code
* PATCH 05-07: Improve error messages
* PATCH 08-13: Clean up code and tighten doc comment syntax
* PATCH 14: Rewrite the doc comment parser
* PATCH 15-16: Clean up code and tighten doc comment syntax some more

The diffstat is deceptive. Most of it is due to PATCH 10 indenting examples. With whitespace ignored (-w), it's just

 34 files changed, 328 insertions(+), 335 deletions(-)

Markus Armbruster (16):
tests/qapi-schema: Fix test 'QAPI rST doc' tests/qapi-schema: Cover duplicate 'Features:' line tests/qapi-schema: Cover 'Features:' not followed by descriptions sphinx/qapidoc: Drop code to generate doc for simple union branch
qapi: Improve error position for bogus argument descriptions
qapi: Improve error position for bogus invalid "Returns" section
qapi: Improve error message for empty doc sections
qapi: Rename QAPIDoc.Section.name to .tag
qapi: Reject section heading in the middle of a doc comment
qapi: Require descriptions and tagged sections to be indented
qapi: Recognize section tags and 'Features:' only after blank line
qapi: Call QAPIDoc.check() always
qapi: Merge adjacent untagged sections
qapi: Rewrite doc comment parser
qapi: Reject multiple and empty feature descriptions
qapi: Divorce QAPIDoc from QAPIParseError

 docs/devel/qapi-code-gen.rst                  |  30 +-
 docs/sphinx/qapidoc.py                        |  28 +-
 qapi/acpi.json                                |  20 +-
 qapi/block-core.json                          | 868 +++++++++---------
 qapi/block.json                               | 274 +++---
 qapi/char.json                                | 172 ++--
 qapi/control.json                             |  54 +-
 qapi/dump.json                                |  26 +-
 qapi/machine-target.json                      |   6 +-
 qapi/machine.json                             | 302 +++---
 qapi/migration.json                           | 690 +++++++-------
 qapi/misc-target.json                         | 110 +--
 qapi/misc.json                                | 172 ++--
 qapi/net.json                                 | 118 +--
 qapi/pci.json                                 | 252 ++---
 qapi/qdev.json                                |  38 +-
 qapi/qom.json                                 |  54 +-
 qapi/rdma.json                                |  14 +-
 qapi/replay.json                              |  16 +-
 qapi/rocker.json                              |  66 +-
 qapi/run-state.json                           |  86 +-
 qapi/tpm.json                                 |  36 +-
 qapi/trace.json                               |  12 +-
 qapi/transaction.json                         |  36 +-
 qapi/ui.json                                  | 324 +++----
 qapi/virtio.json                              | 778 ++++++++--------
 qapi/yank.json                                |  24 +-
 scripts/qapi/parser.py                        | 517 +++++------
 scripts/qapi/schema.py                        |   7 +-
 .../qapi-schema/doc-bad-alternate-member.err  |   2 +-
 .../qapi-schema/doc-bad-boxed-command-arg.err |   2 +-
 tests/qapi-schema/doc-bad-command-arg.err     |   2 +-
 tests/qapi-schema/doc-bad-enum-member.err     |   2 +-
 tests/qapi-schema/doc-bad-event-arg.err       |   2 +-
 tests/qapi-schema/doc-bad-feature.err         |   2 +-
 tests/qapi-schema/doc-bad-union-member.err    |   2 +-
 tests/qapi-schema/doc-duplicate-features.err  |   1 +
 tests/qapi-schema/doc-duplicate-features.json |  11 +
 tests/qapi-schema/doc-duplicate-features.out  |   0
 tests/qapi-schema/doc-duplicated-arg.err      |   2 +-
 tests/qapi-schema/doc-duplicated-return.err   |   2 +-
 tests/qapi-schema/doc-duplicated-return.json  |   1 +
 tests/qapi-schema/doc-duplicated-since.err    |   2 +-
 tests/qapi-schema/doc-duplicated-since.json   |   1 +
 tests/qapi-schema/doc-empty-arg.err           |   2 +-
 tests/qapi-schema/doc-empty-features.err      |   1 +
 tests/qapi-schema/doc-empty-features.json     |  10 +
 tests/qapi-schema/doc-empty-features.out      |   0
 tests/qapi-schema/doc-empty-section.err       |   2 +-
 tests/qapi-schema/doc-good.json               |  25 +-
 tests/qapi-schema/doc-good.txt                |  21 +-
 tests/qapi-schema/doc-invalid-return.err      |   2 +-
 tests/qapi-schema/doc-invalid-return.json     |   1 +
 tests/qapi-schema/doc-non-first-section.err   |   1 +
 tests/qapi-schema/doc-non-first-section.json  |   6 +
 tests/qapi-schema/doc-non-first-section.out   |   0
 tests/qapi-schema/meson.build                 |  12 +-
 tests/qapi-schema/test-qapi.py                |   2 +-
 58 files changed, 2621 insertions(+), 2628 deletions(-)
 create mode 100644 tests/qapi-schema/doc-duplicate-features.err
 create mode 100644 tests/qapi-schema/doc-duplicate-features.json
 create mode 100644 tests/qapi-schema/doc-duplicate-features.out
 create mode 100644 tests/qapi-schema/doc-empty-features.err
 create mode 100644 tests/qapi-schema/doc-empty-features.json
 create mode 100644 tests/qapi-schema/doc-empty-features.out
 create mode 100644 tests/qapi-schema/doc-non-first-section.err
 create mode 100644 tests/qapi-schema/doc-non-first-section.json
 create mode 100644 tests/qapi-schema/doc-non-first-section.out
Signature · 1 line
2.43.0
#1 lore raw

PATCH 1/16 tests/qapi-schema: Fix test 'QAPI rST doc'

The test compares Sphinx plain-text output against a golden reference. To work on Windows hosts, it filters out carriage returns in both files. Unfortunately, the filter doesn't work: it creates an empty file. Comparing empty files always succeeds.

Fix the filter, and update the golden reference to current Sphinx output.

---
 tests/qapi-schema/doc-good.txt | 21 +++++++++------------
 tests/qapi-schema/meson.build  | 10 ++++++----
 2 files changed, 15 insertions(+), 16 deletions(-)
tests/qapi-schema/doc-good.txt +9 -12
index b3b76bd43f..879f6ff50a 100644
@@ -44,7 +44,7 @@ Values
 ~~~~~~
 
 "one" (**If: **"IFONE")
-   The _one_ {and only}
+   The _one_ {and only}, description on the same line
 
 "two"
    Not documented
@@ -76,7 +76,7 @@ Members
 ~~~~~~~
 
 "base1": "Enum"
-   the first member
+   description starts on a new line, minimally indented
 
 
 If
@@ -90,7 +90,9 @@ If
 
 A paragraph
 
-Another paragraph (but no "var": line)
+Another paragraph
+
+"var1" is undocumented
 
 
 Members
@@ -141,7 +143,8 @@ Members
 ~~~~~~~
 
 "i": "int"
-   an integer "b" is undocumented
+   description starts on the same line remainder indented the same "b"
+   is undocumented
 
 "b": "boolean"
    Not documented
@@ -172,10 +175,10 @@ Arguments
 ~~~~~~~~~
 
 "arg1": "int"
-   the first argument
+   description starts on a new line, indented
 
 "arg2": "string" (optional)
-   the second argument
+   description starts on the same line remainder indented differently
 
 "arg3": "boolean"
    Not documented
@@ -203,12 +206,6 @@ Returns
 "Object"
 
 
-TODO
-~~~~
-
-frobnicate
-
-
 Notes
 ~~~~~
 
tests/qapi-schema/meson.build +6 -4
index af085f745d..44a9385563 100644
@@ -273,15 +273,17 @@ if build_docs
                                     output: ['doc-good.txt.nocr'],
                                     input: qapi_doc_out[0],
                                     build_by_default: true,
-                                    command: [remove_cr, '@INPUT@'],
-                                    capture: true)
+                                    command: [remove_cr],
+                                    capture: true,
+                                    feed: true)
 
   qapi_doc_ref_nocr = custom_target('QAPI rST doc reference newline-sanitized',
                                     output: ['doc-good.ref.nocr'],
                                     input: files('doc-good.txt'),
                                     build_by_default: true,
-                                    command: [remove_cr, '@INPUT@'],
-                                    capture: true)
+                                    command: [remove_cr],
+                                    capture: true,
+                                    feed: true)
 
   test('QAPI rST doc', diff, args: ['-u', qapi_doc_ref_nocr[0], qapi_doc_out_nocr[0]],
        suite: ['qapi-schema', 'qapi-doc'])
Signature · 1 line
2.43.0
Reviewed-by on v1 1/16
#2 lore raw

Re: [PATCH 01/16] tests/qapi-schema: Fix test 'QAPI rST doc'

Quoted 4 lines · Markus Armbruster

The test compares Sphinx plain-text output against a golden reference. To work on Windows hosts, it filters out carriage returns in both files. Unfortunately, the filter doesn't work: it creates an empty file. Comparing empty files always succeeds.

lol, opps :)

Quoted 9 lines

Fix the filter, and update the golden reference to current Sphinx output.

---
 tests/qapi-schema/doc-good.txt | 21 +++++++++------------
 tests/qapi-schema/meson.build  | 10 ++++++----
 2 files changed, 15 insertions(+), 16 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#3 lore raw

PATCH 2/16 tests/qapi-schema: Cover duplicate 'Features:' line

In reply to Markus Armbruster

We don't actually recognize the second 'Features:' line. Instead, we treat it as an untagged section.

If it was followed by feature description, we'd reject that like "description of '@feat2:' follows a section". Less than clear.

To be improved shortly.

---
 tests/qapi-schema/doc-duplicate-features.err  |  0
 tests/qapi-schema/doc-duplicate-features.json | 11 ++++++++++
 tests/qapi-schema/doc-duplicate-features.out  | 22 +++++++++++++++++++
 tests/qapi-schema/meson.build                 |  1 +
 4 files changed, 34 insertions(+)
 create mode 100644 tests/qapi-schema/doc-duplicate-features.err
 create mode 100644 tests/qapi-schema/doc-duplicate-features.json
 create mode 100644 tests/qapi-schema/doc-duplicate-features.out
tests/qapi-schema/doc-duplicate-features.err new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
tests/qapi-schema/doc-duplicate-features.json new file +11 -0
new file mode 100644
index 0000000000..a4d559e740
@@ -0,0 +1,11 @@
+# Duplicate 'Features:' line
+
+##
+# @foo:
+#
+# Features:
+# @feat: mumble
+#
+# Features:
+##
+{ 'command': 'foo', 'features': ['feat'] }
tests/qapi-schema/doc-duplicate-features.out new file +22 -0
new file mode 100644
index 0000000000..43bfe1034b
@@ -0,0 +1,22 @@
+module ./builtin
+object q_empty
+enum QType
+    prefix QTYPE
+    member none
+    member qnull
+    member qnum
+    member qstring
+    member qdict
+    member qlist
+    member qbool
+module doc-duplicate-features.json
+command foo None -> None
+    gen=True success_response=True boxed=False oob=False preconfig=False
+    feature feat
+doc symbol=foo
+    body=
+
+    feature=feat
+mumble
+    section=None
+Features:
tests/qapi-schema/meson.build +1 -0
index 44a9385563..4c714c792f 100644
@@ -66,6 +66,7 @@ schemas = [
   'doc-bad-union-member.json',
   'doc-before-include.json',
   'doc-before-pragma.json',
+  'doc-duplicate-features.json',
   'doc-duplicated-arg.json',
   'doc-duplicated-return.json',
   'doc-duplicated-since.json',
Signature · 1 line
2.43.0
Reviewed-by on v1 2/16
#4 lore raw

Re: [PATCH 02/16] tests/qapi-schema: Cover duplicate 'Features:' line

Quoted 9 lines · Markus Armbruster

We don't actually recognize the second 'Features:' line. Instead, we treat it as an untagged section.

If it was followed by feature description, we'd reject that like "description of '@feat2:' follows a section". Less than clear.

To be improved shortly.

Quoted 9 lines
---
 tests/qapi-schema/doc-duplicate-features.err  |  0
 tests/qapi-schema/doc-duplicate-features.json | 11 ++++++++++
 tests/qapi-schema/doc-duplicate-features.out  | 22 +++++++++++++++++++
 tests/qapi-schema/meson.build                 |  1 +
 4 files changed, 34 insertions(+)
 create mode 100644 tests/qapi-schema/doc-duplicate-features.err
 create mode 100644 tests/qapi-schema/doc-duplicate-features.json
 create mode 100644 tests/qapi-schema/doc-duplicate-features.out

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#5 lore raw

PATCH 3/16 tests/qapi-schema: Cover 'Features:' not followed by descriptions

In reply to Markus Armbruster

A 'Features:' line without any features is useless, but not an error now. However, a later commit will make it one, because that makes rejecting duplicate 'Features:' easier.

---
 tests/qapi-schema/doc-empty-features.err  |  0
 tests/qapi-schema/doc-empty-features.json | 10 ++++++++++
 tests/qapi-schema/doc-empty-features.out  | 19 +++++++++++++++++++
 tests/qapi-schema/meson.build             |  1 +
 4 files changed, 30 insertions(+)
 create mode 100644 tests/qapi-schema/doc-empty-features.err
 create mode 100644 tests/qapi-schema/doc-empty-features.json
 create mode 100644 tests/qapi-schema/doc-empty-features.out
tests/qapi-schema/doc-empty-features.err new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
tests/qapi-schema/doc-empty-features.json new file +10 -0
new file mode 100644
index 0000000000..06f814e45d
@@ -0,0 +1,10 @@
+# 'Features:' line not followed by feature descriptions
+
+##
+# @foo:
+#
+# Features:
+#
+# not a description
+##
+{ 'command': 'foo' }
tests/qapi-schema/doc-empty-features.out new file +19 -0
new file mode 100644
index 0000000000..0f85623dde
@@ -0,0 +1,19 @@
+module ./builtin
+object q_empty
+enum QType
+    prefix QTYPE
+    member none
+    member qnull
+    member qnum
+    member qstring
+    member qdict
+    member qlist
+    member qbool
+module doc-empty-features.json
+command foo None -> None
+    gen=True success_response=True boxed=False oob=False preconfig=False
+doc symbol=foo
+    body=
+
+    section=None
+not a description
tests/qapi-schema/meson.build +1 -0
index 4c714c792f..4b8329d070 100644
@@ -71,6 +71,7 @@ schemas = [
   'doc-duplicated-return.json',
   'doc-duplicated-since.json',
   'doc-empty-arg.json',
+  'doc-empty-features.json',
   'doc-empty-section.json',
   'doc-empty-symbol.json',
   'doc-good.json',
Signature · 1 line
2.43.0
Reviewed-by on v1 3/16
#6 lore raw

Re: [PATCH 03/16] tests/qapi-schema: Cover 'Features:' not followed by descriptions

Quoted 5 lines · Markus Armbruster

A 'Features:' line without any features is useless, but not an error now. However, a later commit will make it one, because that makes rejecting duplicate 'Features:' easier.

Quoted 9 lines
---
 tests/qapi-schema/doc-empty-features.err  |  0
 tests/qapi-schema/doc-empty-features.json | 10 ++++++++++
 tests/qapi-schema/doc-empty-features.out  | 19 +++++++++++++++++++
 tests/qapi-schema/meson.build             |  1 +
 4 files changed, 30 insertions(+)
 create mode 100644 tests/qapi-schema/doc-empty-features.err
 create mode 100644 tests/qapi-schema/doc-empty-features.json
 create mode 100644 tests/qapi-schema/doc-empty-features.out

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#7 lore raw

PATCH 4/16 sphinx/qapidoc: Drop code to generate doc for simple union branch

In reply to Markus Armbruster

Commit 4e99f4b12c0 (qapi: Drop simple unions) eliminated implicitly defined union branch types, except for the empty object type 'q_empty'. QAPISchemaGenRSTVisitor._nodes_for_members() still has code to generate documentation for implicitly defined union branch types. It does nothing for 'q_empty'. Simplify.

---
 docs/sphinx/qapidoc.py | 18 +++++++-----------
 1 file changed, 7 insertions(+), 11 deletions(-)
docs/sphinx/qapidoc.py +7 -11
index 05b809af27..488de23d72 100644
@@ -180,17 +180,13 @@ def _nodes_for_members(self, doc, what, base=None, variants=None):
 
         if variants:
             for v in variants.variants:
-                if v.type.is_implicit():
-                    assert not v.type.base and not v.type.variants
-                    for m in v.type.local_members:
-                        term = self._nodes_for_one_member(m)
-                        term.extend(self._nodes_for_variant_when(variants, v))
-                        dlnode += self._make_dlitem(term, None)
-                else:
-                    term = [nodes.Text('The members of '),
-                            nodes.literal('', v.type.doc_type())]
-                    term.extend(self._nodes_for_variant_when(variants, v))
-                    dlnode += self._make_dlitem(term, None)
+                if v.type.name == 'q_empty':
+                    continue
+                assert not v.type.is_implicit()
+                term = [nodes.Text('The members of '),
+                        nodes.literal('', v.type.doc_type())]
+                term.extend(self._nodes_for_variant_when(variants, v))
+                dlnode += self._make_dlitem(term, None)
 
         if not dlnode.children:
             return []
Signature · 1 line
2.43.0
Reviewed-by on v1 4/16
#8 lore raw

Re: [PATCH 04/16] sphinx/qapidoc: Drop code to generate doc for simple union branch

Quoted 10 lines · Markus Armbruster

Commit 4e99f4b12c0 (qapi: Drop simple unions) eliminated implicitly defined union branch types, except for the empty object type 'q_empty'. QAPISchemaGenRSTVisitor._nodes_for_members() still has code to generate documentation for implicitly defined union branch types. It does nothing for 'q_empty'. Simplify.

---
 docs/sphinx/qapidoc.py | 18 +++++++-----------
 1 file changed, 7 insertions(+), 11 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#9 lore raw

PATCH 5/16 qapi: Improve error position for bogus argument descriptions

In reply to Markus Armbruster

When documented arguments don't exist, the error message points to the beginning of the definition comment. Point to the first bogus argument description instead.

---
 scripts/qapi/parser.py                          | 4 +++-
 tests/qapi-schema/doc-bad-alternate-member.err  | 2 +-
 tests/qapi-schema/doc-bad-boxed-command-arg.err | 2 +-
 tests/qapi-schema/doc-bad-command-arg.err       | 2 +-
 tests/qapi-schema/doc-bad-enum-member.err       | 2 +-
 tests/qapi-schema/doc-bad-event-arg.err         | 2 +-
 tests/qapi-schema/doc-bad-feature.err           | 2 +-
 tests/qapi-schema/doc-bad-union-member.err      | 2 +-
 8 files changed, 10 insertions(+), 8 deletions(-)
scripts/qapi/parser.py +3 -1
index 88221b3c64..82db595dcf 100644
@@ -472,6 +472,8 @@ class Section:
         # pylint: disable=too-few-public-methods
         def __init__(self, parser: QAPISchemaParser,
                      name: Optional[str] = None):
+            # section source info, i.e. where it begins
+            self.info = parser.info
             # parser, for error messages about indentation
             self._parser = parser
             # optional section name (argument/member or section name)
@@ -770,7 +772,7 @@ def check_args_section(
                      if not section.member]
             if bogus:
                 raise QAPISemError(
-                    self.info,
+                    args[bogus[0]].info,
                     "documented %s%s '%s' %s not exist" % (
                         what,
                         "s" if len(bogus) > 1 else "",
tests/qapi-schema/doc-bad-alternate-member.err +1 -1
index d7286bb57c..1f6b7d2fe4 100644
@@ -1 +1 @@
-doc-bad-alternate-member.json:3: documented members 'aa', 'bb' do not exist
+doc-bad-alternate-member.json:7: documented members 'aa', 'bb' do not exist
tests/qapi-schema/doc-bad-boxed-command-arg.err +1 -1
index 7137af3ec9..d6793e7fd8 100644
@@ -1 +1 @@
-doc-bad-boxed-command-arg.json:9: documented member 'a' does not exist
+doc-bad-boxed-command-arg.json:11: documented member 'a' does not exist
tests/qapi-schema/doc-bad-command-arg.err +1 -1
index 18ed076cef..b76167ec60 100644
@@ -1 +1 @@
-doc-bad-command-arg.json:3: documented member 'b' does not exist
+doc-bad-command-arg.json:6: documented member 'b' does not exist
tests/qapi-schema/doc-bad-enum-member.err +1 -1
index 7efeb47363..0aa8d8e8e2 100644
@@ -1 +1 @@
-doc-bad-enum-member.json:3: documented member 'a' does not exist
+doc-bad-enum-member.json:5: documented member 'a' does not exist
tests/qapi-schema/doc-bad-event-arg.err +1 -1
index d13cacf21f..90527d5f82 100644
@@ -1 +1 @@
-doc-bad-event-arg.json:3: documented member 'a' does not exist
+doc-bad-event-arg.json:5: documented member 'a' does not exist
tests/qapi-schema/doc-bad-feature.err +1 -1
index 49d1746c3d..3166c6a305 100644
@@ -1 +1 @@
-doc-bad-feature.json:3: documented feature 'a' does not exist
+doc-bad-feature.json:7: documented feature 'a' does not exist
tests/qapi-schema/doc-bad-union-member.err +1 -1
index 6dd2726a65..cdf1225cab 100644
@@ -1 +1 @@
-doc-bad-union-member.json:3: documented members 'a', 'b' do not exist
+doc-bad-union-member.json:5: documented members 'a', 'b' do not exist
Signature · 1 line
2.43.0
Reviewed-by on v1 5/16
#10 lore raw

Re: [PATCH 05/16] qapi: Improve error position for bogus argument descriptions

Quoted 5 lines · Markus Armbruster

When documented arguments don't exist, the error message points to the beginning of the definition comment. Point to the first bogus argument description instead.

Quoted 10 lines
---
 scripts/qapi/parser.py                          | 4 +++-
 tests/qapi-schema/doc-bad-alternate-member.err  | 2 +-
 tests/qapi-schema/doc-bad-boxed-command-arg.err | 2 +-
 tests/qapi-schema/doc-bad-command-arg.err       | 2 +-
 tests/qapi-schema/doc-bad-enum-member.err       | 2 +-
 tests/qapi-schema/doc-bad-event-arg.err         | 2 +-
 tests/qapi-schema/doc-bad-feature.err           | 2 +-
 tests/qapi-schema/doc-bad-union-member.err      | 2 +-
 8 files changed, 10 insertions(+), 8 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#11 lore raw

PATCH 6/16 qapi: Improve error position for bogus invalid "Returns" section

In reply to Markus Armbruster

When something other than a command has a "Returns" section, the error message points to the beginning of the definition comment. Point to the "Returns" section instead.

---
 scripts/qapi/parser.py                   | 10 +++++++---
 tests/qapi-schema/doc-invalid-return.err |  2 +-
 2 files changed, 8 insertions(+), 4 deletions(-)
scripts/qapi/parser.py +7 -3
index 82db595dcf..a771013959 100644
@@ -759,9 +759,13 @@ def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
         self.features[feature.name].connect(feature)
 
     def check_expr(self, expr: QAPIExpression) -> None:
-        if self.has_section('Returns') and 'command' not in expr:
-            raise QAPISemError(self.info,
-                               "'Returns:' is only valid for commands")
+        if 'command' not in expr:
+            sec = next((sec for sec in self.sections
+                        if sec.name == 'Returns'),
+                       None)
+            if sec:
+                raise QAPISemError(sec.info,
+                                   "'Returns:' is only valid for commands")
 
     def check(self) -> None:
 
tests/qapi-schema/doc-invalid-return.err +1 -1
index 2ad89c5941..bc5826de20 100644
@@ -1 +1 @@
-doc-invalid-return.json:3: 'Returns:' is only valid for commands
+doc-invalid-return.json:5: 'Returns:' is only valid for commands
Signature · 1 line
2.43.0
Reviewed-by on v1 6/16
#12 lore raw

Re: [PATCH 06/16] qapi: Improve error position for bogus invalid "Returns" section

Quoted 9 lines · Markus Armbruster

When something other than a command has a "Returns" section, the error message points to the beginning of the definition comment. Point to the "Returns" section instead.

---
 scripts/qapi/parser.py                   | 10 +++++++---
 tests/qapi-schema/doc-invalid-return.err |  2 +-
 2 files changed, 8 insertions(+), 4 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#13 lore raw

PATCH 7/16 qapi: Improve error message for empty doc sections

In reply to Markus Armbruster

Improve the message for an empty tagged section from

empty doc section 'Note'

to

text required after 'Note:'

and the message for an empty argument or feature description from

empty doc section 'foo'

to

text required after '@foo:'

Improve the error position to refer to the beginning of the empty section instead of its end.

---
 docs/sphinx/qapidoc.py                  |  4 ++--
 scripts/qapi/parser.py                  | 14 +++++++-------
 tests/qapi-schema/doc-empty-section.err |  2 +-
 3 files changed, 10 insertions(+), 10 deletions(-)
docs/sphinx/qapidoc.py +2 -2
index 488de23d72..1e8b4a70a1 100644
@@ -239,8 +239,8 @@ def _nodes_for_features(self, doc):
         seen_item = False
         dlnode = nodes.definition_list()
         for section in doc.features.values():
-            dlnode += self._make_dlitem([nodes.literal('', section.name)],
-                                        section.text)
+            dlnode += self._make_dlitem(
+                [nodes.literal('', section.member.name)], section.text)
             seen_item = True
 
         if not seen_item:
scripts/qapi/parser.py +7 -7
index a771013959..43daf55860 100644
@@ -476,9 +476,9 @@ def __init__(self, parser: QAPISchemaParser,
             self.info = parser.info
             # parser, for error messages about indentation
             self._parser = parser
-            # optional section name (argument/member or section name)
+            # section tag, if any ('Returns', '@name', ...)
             self.name = name
-            # section text without section name
+            # section text without tag
             self.text = ''
             # indentation to strip (None means indeterminate)
             self._indent = None if self.name else 0
@@ -700,7 +700,7 @@ def _start_symbol_section(
             raise QAPIParseError(self._parser,
                                  "'%s' parameter name duplicated" % name)
         assert not self.sections
-        new_section = QAPIDoc.ArgSection(self._parser, name)
+        new_section = QAPIDoc.ArgSection(self._parser, '@' + name)
         self._switch_section(new_section)
         symbols_dict[name] = new_section
 
@@ -727,9 +727,9 @@ def _switch_section(self, new_section: 'QAPIDoc.Section') -> None:
             # We do not create anonymous sections unless there is
             # something to put in them; this is a parser bug.
             assert self._section.name
-            raise QAPIParseError(
-                self._parser,
-                "empty doc section '%s'" % self._section.name)
+            raise QAPISemError(
+                self._section.info,
+                "text required after '%s:'" % self._section.name)
 
         self._section = new_section
 
@@ -748,7 +748,7 @@ def connect_member(self, member: 'QAPISchemaMember') -> None:
                                    "%s '%s' lacks documentation"
                                    % (member.role, member.name))
             self.args[member.name] = QAPIDoc.ArgSection(self._parser,
-                                                        member.name)
+                                                        '@' + member.name)
         self.args[member.name].connect(member)
 
     def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
tests/qapi-schema/doc-empty-section.err +1 -1
index ba7ba70125..5f03a6d733 100644
@@ -1 +1 @@
-doc-empty-section.json:7:1: empty doc section 'Note'
+doc-empty-section.json:6: text required after 'Note:'
Signature · 1 line
2.43.0
Reviewed-by on v1 7/16
#14 lore raw

Re: [PATCH 07/16] qapi: Improve error message for empty doc sections

Quoted 19 lines · Markus Armbruster

Improve the message for an empty tagged section from

empty doc section 'Note'

to

text required after 'Note:'

and the message for an empty argument or feature description from

empty doc section 'foo'

to

text required after '@foo:'

Improve the error position to refer to the beginning of the empty section instead of its end.

Quoted 6 lines
---
 docs/sphinx/qapidoc.py                  |  4 ++--
 scripts/qapi/parser.py                  | 14 +++++++-------
 tests/qapi-schema/doc-empty-section.err |  2 +-
 3 files changed, 10 insertions(+), 10 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#15 lore raw

PATCH 8/16 qapi: Rename QAPIDoc.Section.name to .tag

In reply to Markus Armbruster

Since the previous commit, QAPIDoc.Section.name is either None (untagged section) or the section's tag string ('Returns', '@name', ...). Rename it to .tag.

---
 docs/sphinx/qapidoc.py         |  6 +++---
 scripts/qapi/parser.py         | 30 +++++++++++++++---------------
 tests/qapi-schema/test-qapi.py |  2 +-
 3 files changed, 19 insertions(+), 19 deletions(-)
docs/sphinx/qapidoc.py +3 -3
index 1e8b4a70a1..8d428c64b0 100644
@@ -258,11 +258,11 @@ def _nodes_for_sections(self, doc):
         """Return list of doctree nodes for additional sections"""
         nodelist = []
         for section in doc.sections:
-            if section.name and section.name == 'TODO':
+            if section.tag and section.tag == 'TODO':
                 # Hide TODO: sections
                 continue
-            snode = self._make_section(section.name)
-            if section.name and section.name.startswith('Example'):
+            snode = self._make_section(section.tag)
+            if section.tag and section.tag.startswith('Example'):
                 snode += self._nodes_for_example(section.text)
             else:
                 self._parse_text_into_node(section.text, snode)
scripts/qapi/parser.py +15 -15
index 43daf55860..cc69f4f770 100644
@@ -471,17 +471,17 @@ class QAPIDoc:
     class Section:
         # pylint: disable=too-few-public-methods
         def __init__(self, parser: QAPISchemaParser,
-                     name: Optional[str] = None):
+                     tag: Optional[str] = None):
             # section source info, i.e. where it begins
             self.info = parser.info
             # parser, for error messages about indentation
             self._parser = parser
             # section tag, if any ('Returns', '@name', ...)
-            self.name = name
+            self.tag = tag
             # section text without tag
             self.text = ''
             # indentation to strip (None means indeterminate)
-            self._indent = None if self.name else 0
+            self._indent = None if self.tag else 0
 
         def append(self, line: str) -> None:
             line = line.rstrip()
@@ -504,8 +504,8 @@ def append(self, line: str) -> None:
 
     class ArgSection(Section):
         def __init__(self, parser: QAPISchemaParser,
-                     name: str):
-            super().__init__(parser, name)
+                     tag: str):
+            super().__init__(parser, tag)
             self.member: Optional['QAPISchemaMember'] = None
 
         def connect(self, member: 'QAPISchemaMember') -> None:
@@ -536,10 +536,10 @@ def __init__(self, parser: QAPISchemaParser, info: QAPISourceInfo):
         self._section = self.body
         self._append_line = self._append_body_line
 
-    def has_section(self, name: str) -> bool:
-        """Return True if we have a section with this name."""
+    def has_section(self, tag: str) -> bool:
+        """Return True if we have a section with this tag."""
         for i in self.sections:
-            if i.name == name:
+            if i.tag == tag:
                 return True
         return False
 
@@ -710,11 +710,11 @@ def _start_args_section(self, name: str) -> None:
     def _start_features_section(self, name: str) -> None:
         self._start_symbol_section(self.features, name)
 
-    def _start_section(self, name: Optional[str] = None) -> None:
-        if name in ('Returns', 'Since') and self.has_section(name):
+    def _start_section(self, tag: Optional[str] = None) -> None:
+        if tag in ('Returns', 'Since') and self.has_section(tag):
             raise QAPIParseError(self._parser,
-                                 "duplicated '%s' section" % name)
-        new_section = QAPIDoc.Section(self._parser, name)
+                                 "duplicated '%s' section" % tag)
+        new_section = QAPIDoc.Section(self._parser, tag)
         self._switch_section(new_section)
         self.sections.append(new_section)
 
@@ -726,10 +726,10 @@ def _switch_section(self, new_section: 'QAPIDoc.Section') -> None:
         if self._section != self.body and not text:
             # We do not create anonymous sections unless there is
             # something to put in them; this is a parser bug.
-            assert self._section.name
+            assert self._section.tag
             raise QAPISemError(
                 self._section.info,
-                "text required after '%s:'" % self._section.name)
+                "text required after '%s:'" % self._section.tag)
 
         self._section = new_section
 
@@ -761,7 +761,7 @@ def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
     def check_expr(self, expr: QAPIExpression) -> None:
         if 'command' not in expr:
             sec = next((sec for sec in self.sections
-                        if sec.name == 'Returns'),
+                        if sec.tag == 'Returns'),
                        None)
             if sec:
                 raise QAPISemError(sec.info,
tests/qapi-schema/test-qapi.py +1 -1
index 14f7b62a44..40095431ae 100755
@@ -130,7 +130,7 @@ def test_frontend(fname):
         for feat, section in doc.features.items():
             print('    feature=%s\n%s' % (feat, section.text))
         for section in doc.sections:
-            print('    section=%s\n%s' % (section.name, section.text))
+            print('    section=%s\n%s' % (section.tag, section.text))
 
 
 def open_test_result(dir_name, file_name, update):
Signature · 1 line
2.43.0
Reviewed-by on v1 8/16
#16 lore raw

Re: [PATCH 08/16] qapi: Rename QAPIDoc.Section.name to .tag

Quoted 10 lines · Markus Armbruster

Since the previous commit, QAPIDoc.Section.name is either None (untagged section) or the section's tag string ('Returns', '@name', ...). Rename it to .tag.

---
 docs/sphinx/qapidoc.py         |  6 +++---
 scripts/qapi/parser.py         | 30 +++++++++++++++---------------
 tests/qapi-schema/test-qapi.py |  2 +-
 3 files changed, 19 insertions(+), 19 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#17 lore raw

PATCH 9/16 qapi: Reject section heading in the middle of a doc comment

In reply to Markus Armbruster

docs/devel/qapi-code-gen.txt claims "A heading line must be the first line of the documentation comment block" since commit 55ec69f8b16 (docs/devel/qapi-code-gen.txt: Update to new rST backend conventions). Not true, we have code to make it work anywhere in a free-form doc comment: commit dcdc07a97cb (qapi: Make section headings start a new doc comment block).

Make it true, for simplicity's sake.

---
 scripts/qapi/parser.py                       | 6 +++---
 tests/qapi-schema/doc-good.json              | 4 +++-
 tests/qapi-schema/doc-non-first-section.err  | 1 +
 tests/qapi-schema/doc-non-first-section.json | 6 ++++++
 tests/qapi-schema/doc-non-first-section.out  | 0
 5 files changed, 13 insertions(+), 4 deletions(-)
 create mode 100644 tests/qapi-schema/doc-non-first-section.err
 create mode 100644 tests/qapi-schema/doc-non-first-section.json
 create mode 100644 tests/qapi-schema/doc-non-first-section.out
scripts/qapi/parser.py +3 -3
index cc69f4f770..3aefec1c2b 100644
@@ -440,9 +440,9 @@ def get_doc(self, info: QAPISourceInfo) -> List['QAPIDoc']:
                         self,
                         "unexpected '=' markup in definition documentation")
                 if cur_doc.body.text:
-                    cur_doc.end_comment()
-                    docs.append(cur_doc)
-                    cur_doc = QAPIDoc(self, info)
+                    raise QAPIParseError(
+                        self,
+                        "'=' heading must come first in a comment block")
             cur_doc.append(self.val)
             self.accept(False)
 
tests/qapi-schema/doc-good.json +3 -1
index 24a84fe6d7..0479d16a01 100644
@@ -9,7 +9,9 @@
 
 ##
 # = Section
-#
+##
+
+##
 # == Subsection
 #
 # *with emphasis*
tests/qapi-schema/doc-non-first-section.err new file +1 -0
new file mode 100644
index 0000000000..eeced2bca7
@@ -0,0 +1 @@
+doc-non-first-section.json:5:1: '=' heading must come first in a comment block
tests/qapi-schema/doc-non-first-section.json new file +6 -0
new file mode 100644
index 0000000000..1590876061
@@ -0,0 +1,6 @@
+# = section must be first line
+
+##
+#
+# = Not first
+##
tests/qapi-schema/doc-non-first-section.out new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
Signature · 1 line
2.43.0
Reviewed-by on v1 9/16
#18 lore raw

Re: [PATCH 09/16] qapi: Reject section heading in the middle of a doc comment

Quoted 10 lines · Markus Armbruster

docs/devel/qapi-code-gen.txt claims "A heading line must be the first line of the documentation comment block" since commit 55ec69f8b16 (docs/devel/qapi-code-gen.txt: Update to new rST backend conventions). Not true, we have code to make it work anywhere in a free-form doc comment: commit dcdc07a97cb (qapi: Make section headings start a new doc comment block).

Make it true, for simplicity's sake.

Quoted 10 lines
---
 scripts/qapi/parser.py                       | 6 +++---
 tests/qapi-schema/doc-good.json              | 4 +++-
 tests/qapi-schema/doc-non-first-section.err  | 1 +
 tests/qapi-schema/doc-non-first-section.json | 6 ++++++
 tests/qapi-schema/doc-non-first-section.out  | 0
 5 files changed, 13 insertions(+), 4 deletions(-)
 create mode 100644 tests/qapi-schema/doc-non-first-section.err
 create mode 100644 tests/qapi-schema/doc-non-first-section.json
 create mode 100644 tests/qapi-schema/doc-non-first-section.out

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#19 lore raw

PATCH 10/16 qapi: Require descriptions and tagged sections to be indented

In reply to Markus Armbruster

By convention, we indent the second and subsequent lines of descriptions and tagged sections, except for examples.

Turn this into a hard rule, and apply it to examples, too.

---
 docs/devel/qapi-code-gen.rst    |  15 +-
 qapi/acpi.json                  |  20 +-
 qapi/block-core.json            | 868 ++++++++++++++++----------------
 qapi/block.json                 | 274 +++++-----
 qapi/char.json                  | 172 +++----
 qapi/control.json               |  54 +-
 qapi/dump.json                  |  26 +-
 qapi/machine-target.json        |   6 +-
 qapi/machine.json               | 302 +++++------
 qapi/migration.json             | 690 ++++++++++++-------------
 qapi/misc-target.json           | 110 ++--
 qapi/misc.json                  | 172 +++----
 qapi/net.json                   | 118 ++---
 qapi/pci.json                   | 252 +++++-----
 qapi/qdev.json                  |  38 +-
 qapi/qom.json                   |  54 +-
 qapi/rdma.json                  |  14 +-
 qapi/replay.json                |  16 +-
 qapi/rocker.json                |  66 +--
 qapi/run-state.json             |  84 ++--
 qapi/tpm.json                   |  36 +-
 qapi/trace.json                 |  12 +-
 qapi/transaction.json           |  36 +-
 qapi/ui.json                    | 324 ++++++------
 qapi/virtio.json                | 778 ++++++++++++++--------------
 qapi/yank.json                  |  24 +-
 scripts/qapi/parser.py          |   3 +
 tests/qapi-schema/doc-good.json |  12 +-
 28 files changed, 2289 insertions(+), 2287 deletions(-)
docs/devel/qapi-code-gen.rst +7 -8
index 756adc187e..77a40f3bdc 100644
@@ -973,7 +973,7 @@ commands and events), member (for structs and unions), branch (for
 alternates), or value (for enums), a description of each feature (if
 any), and finally optional tagged sections.
 
-Descriptions start with '\@name:'.  The description text should be
+Descriptions start with '\@name:'.  The description text must be
 indented like this::
 
  # @name: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
@@ -997,8 +997,8 @@ A tagged section starts with one of the following words:
 "Note:"/"Notes:", "Since:", "Example:"/"Examples:", "Returns:",
 "TODO:".  The section ends with the start of a new section.
 
-The second and subsequent lines of sections other than
-"Example"/"Examples" should be indented like this::
+The second and subsequent lines of tagged sections must be indented
+like this::
 
  # Note: Ut enim ad minim veniam, quis nostrud exercitation ullamco
  #     laboris nisi ut aliquip ex ea commodo consequat.
@@ -1049,11 +1049,10 @@ For example::
  #
  # Example:
  #
- # -> { "execute": "query-blockstats" }
- # <- {
- #      ... lots of output ...
- #    }
- #
+ #     -> { "execute": "query-blockstats" }
+ #     <- {
+ #          ... lots of output ...
+ #        }
  ##
  { 'command': 'query-blockstats',
    'data': { '*query-nodes': 'bool' },
qapi/acpi.json +10 -10
index e0739bd6ae..aa4dbe5794 100644
@@ -113,12 +113,12 @@
 #
 # Example:
 #
-# -> { "execute": "query-acpi-ospm-status" }
-# <- { "return": [ { "device": "d1", "slot": "0", "slot-type": "DIMM", "source": 1, "status": 0},
-#                  { "slot": "1", "slot-type": "DIMM", "source": 0, "status": 0},
-#                  { "slot": "2", "slot-type": "DIMM", "source": 0, "status": 0},
-#                  { "slot": "3", "slot-type": "DIMM", "source": 0, "status": 0}
-#    ]}
+#     -> { "execute": "query-acpi-ospm-status" }
+#     <- { "return": [ { "device": "d1", "slot": "0", "slot-type": "DIMM", "source": 1, "status": 0},
+#                      { "slot": "1", "slot-type": "DIMM", "source": 0, "status": 0},
+#                      { "slot": "2", "slot-type": "DIMM", "source": 0, "status": 0},
+#                      { "slot": "3", "slot-type": "DIMM", "source": 0, "status": 0}
+#        ]}
 ##
 { 'command': 'query-acpi-ospm-status', 'returns': ['ACPIOSTInfo'] }
 
@@ -133,10 +133,10 @@
 #
 # Example:
 #
-# <- { "event": "ACPI_DEVICE_OST",
-#      "data": { "info": { "device": "d1", "slot": "0",
-#                          "slot-type": "DIMM", "source": 1, "status": 0 } },
-#      "timestamp": { "seconds": 1265044230, "microseconds": 450486 } }
+#     <- { "event": "ACPI_DEVICE_OST",
+#          "data": { "info": { "device": "d1", "slot": "0",
+#                              "slot-type": "DIMM", "source": 1, "status": 0 } },
+#          "timestamp": { "seconds": 1265044230, "microseconds": 450486 } }
 ##
 { 'event': 'ACPI_DEVICE_OST',
      'data': { 'info': 'ACPIOSTInfo' } }
qapi/block-core.json +434 -434

1,091 lines not on this page · raw message

qapi/block.json +137 -137

366 lines not on this page · raw message

qapi/char.json +86 -86

229 lines not on this page · raw message

qapi/control.json +27 -27

78 lines not on this page · raw message

qapi/dump.json +13 -13
index 1997c1d1d4..f82dd6a1af 100644
@@ -98,9 +98,9 @@
 #
 # Example:
 #
-# -> { "execute": "dump-guest-memory",
-#      "arguments": { "paging": false, "protocol": "fd:dump" } }
-# <- { "return": {} }
+#     -> { "execute": "dump-guest-memory",
+#          "arguments": { "paging": false, "protocol": "fd:dump" } }
+#     <- { "return": {} }
 ##
 { 'command': 'dump-guest-memory',
   'data': { 'paging': 'bool', 'protocol': 'str', '*detach': 'bool',
@@ -154,9 +154,9 @@
 #
 # Example:
 #
-# -> { "execute": "query-dump" }
-# <- { "return": { "status": "active", "completed": 1024000,
-#                  "total": 2048000 } }
+#     -> { "execute": "query-dump" }
+#     <- { "return": { "status": "active", "completed": 1024000,
+#                      "total": 2048000 } }
 ##
 { 'command': 'query-dump', 'returns': 'DumpQueryResult' }
 
@@ -175,10 +175,10 @@
 #
 # Example:
 #
-# <- { "event": "DUMP_COMPLETED",
-#      "data": { "result": { "total": 1090650112, "status": "completed",
-#                            "completed": 1090650112 } },
-#      "timestamp": { "seconds": 1648244171, "microseconds": 950316 } }
+#     <- { "event": "DUMP_COMPLETED",
+#          "data": { "result": { "total": 1090650112, "status": "completed",
+#                                "completed": 1090650112 } },
+#          "timestamp": { "seconds": 1648244171, "microseconds": 950316 } }
 ##
 { 'event': 'DUMP_COMPLETED' ,
   'data': { 'result': 'DumpQueryResult', '*error': 'str' } }
@@ -206,9 +206,9 @@
 #
 # Example:
 #
-# -> { "execute": "query-dump-guest-memory-capability" }
-# <- { "return": { "formats":
-#                  ["elf", "kdump-zlib", "kdump-lzo", "kdump-snappy"] } }
+#     -> { "execute": "query-dump-guest-memory-capability" }
+#     <- { "return": { "formats":
+#                      ["elf", "kdump-zlib", "kdump-lzo", "kdump-snappy"] } }
 ##
 { 'command': 'query-dump-guest-memory-capability',
   'returns': 'DumpGuestMemoryCapability' }
qapi/machine-target.json +3 -3
index 7b7149f81c..2c5dda735e 100644
@@ -447,9 +447,9 @@
 #
 # Example:
 #
-# <- { "event": "CPU_POLARIZATION_CHANGE",
-#      "data": { "polarization": "horizontal" },
-#      "timestamp": { "seconds": 1401385907, "microseconds": 422329 } }
+#     <- { "event": "CPU_POLARIZATION_CHANGE",
+#          "data": { "polarization": "horizontal" },
+#          "timestamp": { "seconds": 1401385907, "microseconds": 422329 } }
 ##
 { 'event': 'CPU_POLARIZATION_CHANGE',
   'data': { 'polarization': 'CpuS390Polarization' },
qapi/machine.json +151 -151

436 lines not on this page · raw message

qapi/migration.json +345 -345

673 lines not on this page · raw message

qapi/misc-target.json +55 -55

110 lines not on this page · raw message

qapi/misc.json +86 -86

172 lines not on this page · raw message

qapi/net.json +59 -59

118 lines not on this page · raw message

qapi/pci.json +126 -126

252 lines not on this page · raw message

qapi/qdev.json +19 -19
index 3b3ccfa413..32ffaee644 100644

Lines of this file are not shown. View the raw message.

qapi/qom.json +27 -27

54 lines not on this page · raw message

qapi/rdma.json +7 -7
index 23ebcf7885..195c001850 100644

Lines of this file are not shown. View the raw message.

qapi/replay.json +8 -8
index 289b2d3658..8626fb58f4 100644

Lines of this file are not shown. View the raw message.

qapi/rocker.json +33 -33

66 lines not on this page · raw message

qapi/run-state.json +42 -42

84 lines not on this page · raw message

qapi/tpm.json +18 -18
index f9c1e866e7..07a73e5f2b 100644

Lines of this file are not shown. View the raw message.

qapi/trace.json +6 -6
index 2077d7e117..043d12f83e 100644

Lines of this file are not shown. View the raw message.

qapi/transaction.json +18 -18
index 7a95c081e9..45233ddd2a 100644

Lines of this file are not shown. View the raw message.

qapi/ui.json +162 -162

324 lines not on this page · raw message

qapi/virtio.json +389 -389

778 lines not on this page · raw message

qapi/yank.json +12 -12
index ee038a11a1..b7aeb9ceef 100644

Lines of this file are not shown. View the raw message.

scripts/qapi/parser.py +3 -0
index 3aefec1c2b..f8da315332 100644

Lines of this file are not shown. View the raw message.

tests/qapi-schema/doc-good.json +6 -6
index 0479d16a01..977bb38b6e 100644

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.43.0

Part of the diff is not shown here. View the raw message.

Reviewed-by on v1 10/16
#20 lore raw

Re: [PATCH 10/16] qapi: Require descriptions and tagged sections to be indented

Quoted 28 lines · Markus Armbruster

By convention, we indent the second and subsequent lines of descriptions and tagged sections, except for examples.

Turn this into a hard rule, and apply it to examples, too.

---
 docs/devel/qapi-code-gen.rst    |  15 +-
 qapi/acpi.json                  |  20 +-
 qapi/block-core.json            | 868 ++++++++++++++++----------------
 qapi/block.json                 | 274 +++++-----
 qapi/char.json                  | 172 +++----
 qapi/control.json               |  54 +-
 qapi/dump.json                  |  26 +-
 qapi/machine-target.json        |   6 +-
 qapi/machine.json               | 302 +++++------
 qapi/migration.json             | 690 ++++++++++++-------------
 qapi/misc-target.json           | 110 ++--
 qapi/misc.json                  | 172 +++----
 qapi/net.json                   | 118 ++---
 qapi/pci.json                   | 252 +++++-----
 qapi/qdev.json                  |  38 +-
 qapi/qom.json                   |  54 +-
 qapi/rdma.json                  |  14 +-
 qapi/replay.json                |  16 +-
 qapi/rocker.json                |  66 +--
 qapi/run-state.json             |  84 ++--
 qapi/tpm.json                   |  36 +-
Quoted 9 lines
 qapi/trace.json                 |  12 +-
 qapi/transaction.json           |  36 +-
 qapi/ui.json                    | 324 ++++++------
 qapi/virtio.json                | 778 ++++++++++++++--------------
 qapi/yank.json                  |  24 +-
 scripts/qapi/parser.py          |   3 +
 tests/qapi-schema/doc-good.json |  12 +-
 28 files changed, 2289 insertions(+), 2287 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#21 lore raw

PATCH 11/16 qapi: Recognize section tags and 'Features:' only after blank line

In reply to Markus Armbruster

Putting a blank line before section tags and 'Features:' is good, existing practice. Enforce it.

---
 docs/devel/qapi-code-gen.rst                 | 15 +++++++++------
 scripts/qapi/parser.py                       | 11 ++++++++---
 tests/qapi-schema/doc-duplicated-return.err  |  2 +-
 tests/qapi-schema/doc-duplicated-return.json |  1 +
 tests/qapi-schema/doc-duplicated-since.err   |  2 +-
 tests/qapi-schema/doc-duplicated-since.json  |  1 +
 tests/qapi-schema/doc-good.json              |  9 +++++++++
 tests/qapi-schema/doc-invalid-return.err     |  2 +-
 tests/qapi-schema/doc-invalid-return.json    |  1 +
 9 files changed, 32 insertions(+), 12 deletions(-)
docs/devel/qapi-code-gen.rst +9 -6
index 77a40f3bdc..6804a4b596 100644
@@ -986,16 +986,17 @@ indented like this::
 Extensions added after the definition was first released carry a
 "(since x.y.z)" comment.
 
-The feature descriptions must be preceded by a line "Features:", like
-this::
+The feature descriptions must be preceded by a blank line and then a
+line "Features:", like this::
 
+  #
   # Features:
   #
   # @feature: Description text
 
-A tagged section starts with one of the following words:
-"Note:"/"Notes:", "Since:", "Example:"/"Examples:", "Returns:",
-"TODO:".  The section ends with the start of a new section.
+A tagged section begins with a paragraph that starts with one of the
+following words: "Note:"/"Notes:", "Since:", "Example:"/"Examples:",
+"Returns:", "TODO:".  It ends with the start of a new section.
 
 The second and subsequent lines of tagged sections must be indented
 like this::
@@ -1086,8 +1087,10 @@ need to line up with each other, like this::
  #     or cache associativity unknown)
  #     (since 5.0)
 
-Section tags are case-sensitive and end with a colon.  Good example::
+Section tags are case-sensitive and end with a colon.  They are only
+recognized after a blank line.  Good example::
 
+ #
  # Since: 7.1
 
 Bad examples (all ordinary paragraphs)::
scripts/qapi/parser.py +8 -3
index f8da315332..de2ce3ec2c 100644
@@ -538,6 +538,7 @@ def __init__(self, parser: QAPISchemaParser, info: QAPISourceInfo):
         # the current section
         self._section = self.body
         self._append_line = self._append_body_line
+        self._first_line_in_paragraph = False
 
     def has_section(self, tag: str) -> bool:
         """Return True if we have a section with this tag."""
@@ -560,12 +561,14 @@ def append(self, line: str) -> None:
         line = line[1:]
         if not line:
             self._append_freeform(line)
+            self._first_line_in_paragraph = True
             return
 
         if line[0] != ' ':
             raise QAPIParseError(self._parser, "missing space after #")
         line = line[1:]
         self._append_line(line)
+        self._first_line_in_paragraph = False
 
     def end_comment(self) -> None:
         self._switch_section(QAPIDoc.NullSection(self._parser))
@@ -574,9 +577,11 @@ def end_comment(self) -> None:
     def _match_at_name_colon(string: str) -> Optional[Match[str]]:
         return re.match(r'@([^:]*): *', string)
 
-    @staticmethod
-    def _match_section_tag(string: str) -> Optional[Match[str]]:
-        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *', string)
+    def _match_section_tag(self, string: str) -> Optional[Match[str]]:
+        if not self._first_line_in_paragraph:
+            return None
+        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *',
+                        string)
 
     def _append_body_line(self, line: str) -> None:
         """
tests/qapi-schema/doc-duplicated-return.err +1 -1
index fe97e3db8d..f19a2b8ec4 100644
@@ -1 +1 @@
-doc-duplicated-return.json:7:1: duplicated 'Returns' section
+doc-duplicated-return.json:8:1: duplicated 'Returns' section
tests/qapi-schema/doc-duplicated-return.json +1 -0
index b44b5ae979..4e1ec2ef42 100644
@@ -4,5 +4,6 @@
 # @foo:
 #
 # Returns: 0
+#
 # Returns: 1
 ##
tests/qapi-schema/doc-duplicated-since.err +1 -1
index abca141a2c..565b753b6a 100644
@@ -1 +1 @@
-doc-duplicated-since.json:7:1: duplicated 'Since' section
+doc-duplicated-since.json:8:1: duplicated 'Since' section
tests/qapi-schema/doc-duplicated-since.json +1 -0
index 343cd872cb..2755f95719 100644
@@ -4,5 +4,6 @@
 # @foo:
 #
 # Since: 0
+#
 # Since: 1
 ##
tests/qapi-schema/doc-good.json +9 -0
index 977bb38b6e..5bb2b69071 100644
@@ -154,22 +154,29 @@
 # Features:
 # @cmd-feat1: a feature
 # @cmd-feat2: another feature
+#
 # Note: @arg3 is undocumented
+#
 # Returns: @Object
+#
 # TODO: frobnicate
+#
 # Notes:
 #
 #  - Lorem ipsum dolor sit amet
 #  - Ut enim ad minim veniam
 #
 #  Duis aute irure dolor
+#
 # Example:
 #
 #  -> in
 #  <- out
+#
 # Examples:
 #  - *verbatim*
 #  - {braces}
+#
 # Since: 2.10
 ##
 { 'command': 'cmd',
@@ -180,9 +187,11 @@
 ##
 # @cmd-boxed:
 # If you're bored enough to read this, go see a video of boxed cats
+#
 # Features:
 # @cmd-feat1: a feature
 # @cmd-feat2: another feature
+#
 # Example:
 #
 #  -> in
tests/qapi-schema/doc-invalid-return.err +1 -1
index bc5826de20..3d9e71c2b3 100644
@@ -1 +1 @@
-doc-invalid-return.json:5: 'Returns:' is only valid for commands
+doc-invalid-return.json:6: 'Returns:' is only valid for commands
tests/qapi-schema/doc-invalid-return.json +1 -0
index 95e7583930..1aabef3482 100644
@@ -2,6 +2,7 @@
 
 ##
 # @FOO:
+#
 # Returns: blah
 ##
 { 'event': 'FOO' }
Signature · 1 line
2.43.0
Reviewed-by on v1 11/16
#22 lore raw

Re: [PATCH 11/16] qapi: Recognize section tags and 'Features:' only after blank line

Quoted 4 lines · Markus Armbruster

Putting a blank line before section tags and 'Features:' is good, existing practice. Enforce it.

Quoted 11 lines
---
 docs/devel/qapi-code-gen.rst                 | 15 +++++++++------
 scripts/qapi/parser.py                       | 11 ++++++++---
 tests/qapi-schema/doc-duplicated-return.err  |  2 +-
 tests/qapi-schema/doc-duplicated-return.json |  1 +
 tests/qapi-schema/doc-duplicated-since.err   |  2 +-
 tests/qapi-schema/doc-duplicated-since.json  |  1 +
 tests/qapi-schema/doc-good.json              |  9 +++++++++
 tests/qapi-schema/doc-invalid-return.err     |  2 +-
 tests/qapi-schema/doc-invalid-return.json    |  1 +
 9 files changed, 32 insertions(+), 12 deletions(-)

scripts/qapi/parser.py def end_comment(self) -> None: · line 584

Quoted 12 lines
scripts/qapi/parser.py +5 -3
@@ -574,9 +577,11 @@ def end_comment(self) -> None:
     def _match_at_name_colon(string: str) -> Optional[Match[str]]:
         return re.match(r'@([^:]*): *', string)
 
-    @staticmethod
-    def _match_section_tag(string: str) -> Optional[Match[str]]:
-        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *', string)
+    def _match_section_tag(self, string: str) -> Optional[Match[str]]:
+        if not self._first_line_in_paragraph:
+            return None
+        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *',
+                        string)

I guess I have a minor worry that we're silently ignoring these tags when there's no blank line. Could result in docs silently rendering in the wrong way if (when) someone forgets the blank line.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#23 lore raw

Re: [PATCH 11/16] qapi: Recognize section tags and 'Features:' only after blank line

Quoted 24 lines · Daniel P. Berrangé
Quoted 4 lines · Markus Armbruster

Putting a blank line before section tags and 'Features:' is good, existing practice. Enforce it.

Quoted 11 lines
---
 docs/devel/qapi-code-gen.rst                 | 15 +++++++++------
 scripts/qapi/parser.py                       | 11 ++++++++---
 tests/qapi-schema/doc-duplicated-return.err  |  2 +-
 tests/qapi-schema/doc-duplicated-return.json |  1 +
 tests/qapi-schema/doc-duplicated-since.err   |  2 +-
 tests/qapi-schema/doc-duplicated-since.json  |  1 +
 tests/qapi-schema/doc-good.json              |  9 +++++++++
 tests/qapi-schema/doc-invalid-return.err     |  2 +-
 tests/qapi-schema/doc-invalid-return.json    |  1 +
 9 files changed, 32 insertions(+), 12 deletions(-)
Quoted 4 lines
scripts/qapi/parser.py +0 -0
@@ -574,9 +577,11 @@ def end_comment(self) -> None:
     def _match_at_name_colon(string: str) -> Optional[Match[str]]:
         return re.match(r'@([^:]*): *', string)
 
Quoted 13 lines

scripts/qapi/parser.py def end_comment(self) -> None: · line 584

Quoted 8 lines
scripts/qapi/parser.py +5 -3
-    @staticmethod
-    def _match_section_tag(string: str) -> Optional[Match[str]]:
-        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *', string)
+    def _match_section_tag(self, string: str) -> Optional[Match[str]]:
+        if not self._first_line_in_paragraph:
+            return None
+        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *',
+                        string)

I guess I have a minor worry that we're silently ignoring these tags when there's no blank line. Could result in docs silently rendering in the wrong way if (when) someone forgets the blank line.

True.

We could make it an error. Can flag occurences in the middle of a free-form paragraph that happen to be at the beginning of a line, but that seems unlikely.

Of course, rST is full of similar syntactic traps anyway. To quote Paolo, "I find it to be the Perl of ASCII-based markups."

#24 lore raw

Re: [PATCH 11/16] qapi: Recognize section tags and 'Features:' only after blank line

Quoted 40 lines · Markus Armbruster
Quoted 24 lines · Daniel P. Berrangé
Quoted 4 lines · Markus Armbruster

Putting a blank line before section tags and 'Features:' is good, existing practice. Enforce it.

Quoted 11 lines
---
 docs/devel/qapi-code-gen.rst                 | 15 +++++++++------
 scripts/qapi/parser.py                       | 11 ++++++++---
 tests/qapi-schema/doc-duplicated-return.err  |  2 +-
 tests/qapi-schema/doc-duplicated-return.json |  1 +
 tests/qapi-schema/doc-duplicated-since.err   |  2 +-
 tests/qapi-schema/doc-duplicated-since.json  |  1 +
 tests/qapi-schema/doc-good.json              |  9 +++++++++
 tests/qapi-schema/doc-invalid-return.err     |  2 +-
 tests/qapi-schema/doc-invalid-return.json    |  1 +
 9 files changed, 32 insertions(+), 12 deletions(-)
Quoted 4 lines
scripts/qapi/parser.py +0 -0
@@ -574,9 +577,11 @@ def end_comment(self) -> None:
     def _match_at_name_colon(string: str) -> Optional[Match[str]]:
         return re.match(r'@([^:]*): *', string)
 
Quoted 13 lines

scripts/qapi/parser.py def end_comment(self) -> None: · line 584

Quoted 8 lines
scripts/qapi/parser.py +5 -3
-    @staticmethod
-    def _match_section_tag(string: str) -> Optional[Match[str]]:
-        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *', string)
+    def _match_section_tag(self, string: str) -> Optional[Match[str]]:
+        if not self._first_line_in_paragraph:
+            return None
+        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *',
+                        string)

I guess I have a minor worry that we're silently ignoring these tags when there's no blank line. Could result in docs silently rendering in the wrong way if (when) someone forgets the blank line.

Quoted 8 lines

True.

We could make it an error. Can flag occurences in the middle of a free-form paragraph that happen to be at the beginning of a line, but that seems unlikely.

Of course, rST is full of similar syntactic traps anyway. To quote Paolo, "I find it to be the Perl of ASCII-based markups."

Yes, probably not worth the hassle.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#25 lore raw

PATCH 12/16 qapi: Call QAPIDoc.check() always

In reply to Markus Armbruster

We currently call QAPIDoc.check() only for definition documentation. Calling it for free-form documentation as well is simpler. No change, because it doesn't actually do anything there.

---
 scripts/qapi/schema.py | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
scripts/qapi/schema.py +2 -5
index 6a836950a9..8ba5665bc6 100644
@@ -95,10 +95,6 @@ def connect_doc(self, doc=None):
             for f in self.features:
                 doc.connect_feature(f)
 
-    def check_doc(self):
-        if self.doc:
-            self.doc.check()
-
     def _set_module(self, schema, info):
         assert self._checked
         fname = info.fname if info else QAPISchemaModule.BUILTIN_MODULE_NAME
@@ -1223,9 +1219,10 @@ def check(self):
         for ent in self._entity_list:
             ent.check(self)
             ent.connect_doc()
-            ent.check_doc()
         for ent in self._entity_list:
             ent.set_module(self)
+        for doc in self.docs:
+            doc.check()
 
     def visit(self, visitor):
         visitor.visit_begin(self)
Signature · 1 line
2.43.0
Reviewed-by on v1 12/16
#26 lore raw

Re: [PATCH 12/16] qapi: Call QAPIDoc.check() always

Quoted 8 lines · Markus Armbruster

We currently call QAPIDoc.check() only for definition documentation. Calling it for free-form documentation as well is simpler. No change, because it doesn't actually do anything there.

---
 scripts/qapi/schema.py | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#27 lore raw

PATCH 13/16 qapi: Merge adjacent untagged sections

In reply to Markus Armbruster

The parser mostly doesn't create adjacent untagged sections, and merging the ones it does create is hardly worth the bother. I'm doing it to avoid behavioral change in the next commit.

---
 scripts/qapi/parser.py                   | 3 +++
 tests/qapi-schema/doc-empty-features.out | 2 --
 2 files changed, 3 insertions(+), 2 deletions(-)
scripts/qapi/parser.py +3 -0
index de2ce3ec2c..48cc9a6367 100644
@@ -719,6 +719,9 @@ def _start_features_section(self, name: str) -> None:
         self._start_symbol_section(self.features, name)
 
     def _start_section(self, tag: Optional[str] = None) -> None:
+        if not tag and not self._section.tag:
+            # extend current section
+            return
         if tag in ('Returns', 'Since') and self.has_section(tag):
             raise QAPIParseError(self._parser,
                                  "duplicated '%s' section" % tag)
tests/qapi-schema/doc-empty-features.out +0 -2
index 0f85623dde..473f59552d 100644
@@ -14,6 +14,4 @@ command foo None -> None
     gen=True success_response=True boxed=False oob=False preconfig=False
 doc symbol=foo
     body=
-
-    section=None
 not a description
Signature · 1 line
2.43.0
Reviewed-by on v1 13/16
#28 lore raw

Re: [PATCH 13/16] qapi: Merge adjacent untagged sections

Quoted 9 lines · Markus Armbruster

The parser mostly doesn't create adjacent untagged sections, and merging the ones it does create is hardly worth the bother. I'm doing it to avoid behavioral change in the next commit.

---
 scripts/qapi/parser.py                   | 3 +++
 tests/qapi-schema/doc-empty-features.out | 2 --
 2 files changed, 3 insertions(+), 2 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#29 lore raw

PATCH 14/16 qapi: Rewrite doc comment parser

In reply to Markus Armbruster

QAPISchemaParser is a conventional recursive descent parser. Except QAPISchemaParser.get_doc() delegates most of the doc comment parsing work to a state machine in QAPIDoc. The state machine doesn't get tokens like a recursive descent parser, it is fed tokens.

I find this state machine rather opaque and hard to maintain.

Replace it by a conventional parser, all in QAPISchemaParser. Less code, and (at least in my opinion) easier to understand.

---
 scripts/qapi/parser.py | 478 ++++++++++++++++++-----------------------
 1 file changed, 210 insertions(+), 268 deletions(-)
scripts/qapi/parser.py +210 -268
index 48cc9a6367..73ff150430 100644
@@ -134,8 +134,8 @@ def _parse(self) -> None:
             info = self.info
             if self.tok == '#':
                 self.reject_expr_doc(cur_doc)
-                for cur_doc in self.get_doc(info):
-                    self.docs.append(cur_doc)
+                cur_doc = self.get_doc()
+                self.docs.append(cur_doc)
                 continue
 
             expr = self.get_expr()
@@ -414,39 +414,171 @@ def get_expr(self) -> _ExprValue:
                 self, "expected '{', '[', string, or boolean")
         return expr
 
-    def get_doc(self, info: QAPISourceInfo) -> List['QAPIDoc']:
+    def get_doc_line(self) -> Optional[str]:
+        if self.tok != '#':
+            raise QAPIParseError(
+                self, "documentation comment must end with '##'")
+        assert isinstance(self.val, str)
+        if self.val.startswith('##'):
+            # End of doc comment
+            if self.val != '##':
+                raise QAPIParseError(
+                    self, "junk after '##' at end of documentation comment")
+            return None
+        if self.val == '#':
+            return ''
+        if self.val[1] != ' ':
+            raise QAPIParseError(self, "missing space after #")
+        return self.val[2:].rstrip()
+
+    @staticmethod
+    def _match_at_name_colon(string: str) -> Optional[Match[str]]:
+        return re.match(r'@([^:]*): *', string)
+
+    def get_doc_indented(self, doc: 'QAPIDoc') -> Optional[str]:
+        self.accept(False)
+        line = self.get_doc_line()
+        while line == '':
+            doc.append_line(line)
+            self.accept(False)
+            line = self.get_doc_line()
+        if line is None:
+            return line
+        indent = must_match(r'\s*', line).end()
+        if not indent:
+            return line
+        doc.append_line(line[indent:])
+        prev_line_blank = False
+        while True:
+            self.accept(False)
+            line = self.get_doc_line()
+            if line is None:
+                return line
+            if self._match_at_name_colon(line):
+                return line
+            cur_indent = must_match(r'\s*', line).end()
+            if line != '' and cur_indent < indent:
+                if prev_line_blank:
+                    return line
+                raise QAPIParseError(
+                    self,
+                    "unexpected de-indent (expected at least %d spaces)" %
+                    indent)
+            doc.append_line(line[indent:])
+            prev_line_blank = True
+
+    def get_doc_paragraph(self, doc: 'QAPIDoc') -> Optional[str]:
+        while True:
+            self.accept(False)
+            line = self.get_doc_line()
+            if line is None:
+                return line
+            if line == '':
+                return line
+            doc.append_line(line)
+
+    def get_doc(self) -> 'QAPIDoc':
         if self.val != '##':
             raise QAPIParseError(
                 self, "junk after '##' at start of documentation comment")
-
-        docs = []
-        cur_doc = QAPIDoc(self, info)
+        info = self.info
         self.accept(False)
-        while self.tok == '#':
-            assert isinstance(self.val, str)
-            if self.val.startswith('##'):
-                # End of doc comment
-                if self.val != '##':
-                    raise QAPIParseError(
-                        self,
-                        "junk after '##' at end of documentation comment")
-                cur_doc.end_comment()
-                docs.append(cur_doc)
-                self.accept()
-                return docs
-            if self.val.startswith('# ='):
-                if cur_doc.symbol:
+        line = self.get_doc_line()
+        if line is not None and line.startswith('@'):
+            # Definition documentation
+            if not line.endswith(':'):
+                raise QAPIParseError(self, "line should end with ':'")
+            # Invalid names are not checked here, but the name
+            # provided *must* match the following definition,
+            # which *is* validated in expr.py.
+            symbol = line[1:-1]
+            if not symbol:
+                raise QAPIParseError(self, "name required after '@'")
+            doc = QAPIDoc(self, info, symbol)
+            self.accept(False)
+            line = self.get_doc_line()
+            no_more_args = False
+
+            while line is not None:
+                # Blank lines
+                while line == '':
+                    self.accept(False)
+                    line = self.get_doc_line()
+                if line is None:
+                    break
+                # Non-blank line, first of a section
+                if line == 'Features:' and not doc.features:
+                    self.accept(False)
+                    line = self.get_doc_line()
+                    while line == '':
+                        self.accept(False)
+                        line = self.get_doc_line()
+                    while (line is not None
+                           and (match := self._match_at_name_colon(line))):
+                        doc.new_feature(match.group(1))
+                        text = line[match.end():]
+                        if text:
+                            doc.append_line(text)
+                        line = self.get_doc_indented(doc)
+                    no_more_args = True
+                elif match := self._match_at_name_colon(line):
+                    # description
+                    if no_more_args:
+                        raise QAPIParseError(
+                            self,
+                            "description of '@%s:' follows a section"
+                            % match.group(1))
+                    while (line is not None
+                           and (match := self._match_at_name_colon(line))):
+                        doc.new_argument(match.group(1))
+                        text = line[match.end():]
+                        if text:
+                            doc.append_line(text)
+                        line = self.get_doc_indented(doc)
+                    no_more_args = True
+                elif match := re.match(
+                        r'(Returns|Since|Notes?|Examples?|TODO): *',
+                        line):
+                    # tagged section
+                    doc.new_tagged_section(match.group(1))
+                    text = line[match.end():]
+                    if text:
+                        doc.append_line(text)
+                    line = self.get_doc_indented(doc)
+                    no_more_args = True
+                elif line.startswith('='):
                     raise QAPIParseError(
                         self,
                         "unexpected '=' markup in definition documentation")
-                if cur_doc.body.text:
+                else:
+                    # tag-less paragraph
+                    doc.ensure_untagged_section()
+                    doc.append_line(line)
+                    line = self.get_doc_paragraph(doc)
+        else:
+            # Free-form documentation
+            doc = QAPIDoc(self, info)
+            doc.ensure_untagged_section()
+            first = True
+            while line is not None:
+                if match := self._match_at_name_colon(line):
                     raise QAPIParseError(
                         self,
-                        "'=' heading must come first in a comment block")
-            cur_doc.append(self.val)
-            self.accept(False)
+                        "'@%s:' not allowed in free-form documentation"
+                        % match.group(1))
+                if line.startswith('='):
+                    if not first:
+                        raise QAPIParseError(
+                            self,
+                            "'=' heading must come first in a comment block")
+                doc.append_line(line)
+                self.accept(False)
+                line = self.get_doc_line()
+                first = False
 
-        raise QAPIParseError(self, "documentation comment must end with '##'")
+        self.accept(False)
+        doc.end()
+        return doc
 
 
 class QAPIDoc:
@@ -469,7 +601,6 @@ class QAPIDoc:
     """
 
     class Section:
-        # pylint: disable=too-few-public-methods
         def __init__(self, parser: QAPISchemaParser,
                      tag: Optional[str] = None):
             # section source info, i.e. where it begins
@@ -480,29 +611,8 @@ def __init__(self, parser: QAPISchemaParser,
             self.tag = tag
             # section text without tag
             self.text = ''
-            # indentation to strip (None means indeterminate)
-            self._indent = None if self.tag else 0
-
-        def append(self, line: str) -> None:
-            line = line.rstrip()
-
-            if line:
-                indent = must_match(r'\s*', line).end()
-                if self._indent is None:
-                    # indeterminate indentation
-                    if self.text != '':
-                        # non-blank, non-first line determines indentation
-                        if indent == 0:
-                            raise QAPIParseError(
-                                self._parser, "line needs to be indented")
-                        self._indent = indent
-                elif indent < self._indent:
-                    raise QAPIParseError(
-                        self._parser,
-                        "unexpected de-indent (expected at least %d spaces)" %
-                        self._indent)
-                line = line[self._indent:]
 
+        def append_line(self, line: str) -> None:
             self.text += line + '\n'
 
     class ArgSection(Section):
@@ -514,243 +624,75 @@ def __init__(self, parser: QAPISchemaParser,
         def connect(self, member: 'QAPISchemaMember') -> None:
             self.member = member
 
-    class NullSection(Section):
-        """
-        Immutable dummy section for use at the end of a doc block.
-        """
-        # pylint: disable=too-few-public-methods
-        def append(self, line: str) -> None:
-            assert False, "Text appended after end_comment() called."
-
-    def __init__(self, parser: QAPISchemaParser, info: QAPISourceInfo):
+    def __init__(self, parser: QAPISchemaParser, info: QAPISourceInfo,
+                 symbol: Optional[str] = None):
         # self._parser is used to report errors with QAPIParseError.  The
         # resulting error position depends on the state of the parser.
         # It happens to be the beginning of the comment.  More or less
         # servicable, but action at a distance.
         self._parser = parser
+        # info points to the doc comment block's first line
         self.info = info
-        self.symbol: Optional[str] = None
-        self.body = QAPIDoc.Section(parser)
-        # dicts mapping parameter/feature names to their ArgSection
-        self.args: Dict[str, QAPIDoc.ArgSection] = OrderedDict()
-        self.features: Dict[str, QAPIDoc.ArgSection] = OrderedDict()
+        # definition doc's symbol, None for free-form doc
+        self.symbol: Optional[str] = symbol
+        # the sections in textual order
+        self.all_sections: List[QAPIDoc.Section] = [QAPIDoc.Section(parser)]
+        # the body section
+        self.body: Optional[QAPIDoc.Section] = self.all_sections[0]
+        # dicts mapping parameter/feature names to their description
+        self.args: Dict[str, QAPIDoc.ArgSection] = {}
+        self.features: Dict[str, QAPIDoc.ArgSection] = {}
+        # sections other than .body, .args, .features
         self.sections: List[QAPIDoc.Section] = []
-        # the current section
-        self._section = self.body
-        self._append_line = self._append_body_line
-        self._first_line_in_paragraph = False
 
-    def has_section(self, tag: str) -> bool:
-        """Return True if we have a section with this tag."""
-        for i in self.sections:
-            if i.tag == tag:
-                return True
-        return False
+    def end(self) -> None:
+        for section in self.all_sections:
+            section.text = section.text.strip('\n')
+            if section.tag is not None and section.text == '':
+                raise QAPISemError(
+                    section.info, "text required after '%s:'" % section.tag)
 
-    def append(self, line: str) -> None:
-        """
-        Parse a comment line and add it to the documentation.
-
-        The way that the line is dealt with depends on which part of
-        the documentation we're parsing right now:
-        * The body section: ._append_line is ._append_body_line
-        * An argument section: ._append_line is ._append_args_line
-        * A features section: ._append_line is ._append_features_line
-        * An additional section: ._append_line is ._append_various_line
-        """
-        line = line[1:]
-        if not line:
-            self._append_freeform(line)
-            self._first_line_in_paragraph = True
+    def ensure_untagged_section(self) -> None:
+        if self.all_sections and not self.all_sections[-1].tag:
+            # extend current section
+            self.all_sections[-1].text += '\n'
             return
+        # start new section
+        section = self.Section(self._parser)
+        self.sections.append(section)
+        self.all_sections.append(section)
 
-        if line[0] != ' ':
-            raise QAPIParseError(self._parser, "missing space after #")
-        line = line[1:]
-        self._append_line(line)
-        self._first_line_in_paragraph = False
+    def new_tagged_section(self, tag: str) -> None:
+        if tag in ('Returns', 'Since'):
+            for section in self.all_sections:
+                if isinstance(section, self.ArgSection):
+                    continue
+                if section.tag == tag:
+                    raise QAPIParseError(
+                        self._parser, "duplicated '%s' section" % tag)
+        section = self.Section(self._parser, tag)
+        self.sections.append(section)
+        self.all_sections.append(section)
 
-    def end_comment(self) -> None:
-        self._switch_section(QAPIDoc.NullSection(self._parser))
-
-    @staticmethod
-    def _match_at_name_colon(string: str) -> Optional[Match[str]]:
-        return re.match(r'@([^:]*): *', string)
-
-    def _match_section_tag(self, string: str) -> Optional[Match[str]]:
-        if not self._first_line_in_paragraph:
-            return None
-        return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *',
-                        string)
-
-    def _append_body_line(self, line: str) -> None:
-        """
-        Process a line of documentation text in the body section.
-
-        If this a symbol line and it is the section's first line, this
-        is a definition documentation block for that symbol.
-
-        If it's a definition documentation block, another symbol line
-        begins the argument section for the argument named by it, and
-        a section tag begins an additional section.  Start that
-        section and append the line to it.
-
-        Else, append the line to the current section.
-        """
-        # FIXME not nice: things like '#  @foo:' and '# @foo: ' aren't
-        # recognized, and get silently treated as ordinary text
-        if not self.symbol and not self.body.text and line.startswith('@'):
-            if not line.endswith(':'):
-                raise QAPIParseError(self._parser, "line should end with ':'")
-            self.symbol = line[1:-1]
-            # Invalid names are not checked here, but the name provided MUST
-            # match the following definition, which *is* validated in expr.py.
-            if not self.symbol:
-                raise QAPIParseError(
-                    self._parser, "name required after '@'")
-        elif self.symbol:
-            # This is a definition documentation block
-            if self._match_at_name_colon(line):
-                self._append_line = self._append_args_line
-                self._append_args_line(line)
-            elif line == 'Features:':
-                self._append_line = self._append_features_line
-            elif self._match_section_tag(line):
-                self._append_line = self._append_various_line
-                self._append_various_line(line)
-            else:
-                self._append_freeform(line)
-        else:
-            # This is a free-form documentation block
-            self._append_freeform(line)
-
-    def _append_args_line(self, line: str) -> None:
-        """
-        Process a line of documentation text in an argument section.
-
-        A symbol line begins the next argument section, a section tag
-        section or a non-indented line after a blank line begins an
-        additional section.  Start that section and append the line to
-        it.
-
-        Else, append the line to the current section.
-
-        """
-        match = self._match_at_name_colon(line)
-        if match:
-            line = line[match.end():]
-            self._start_args_section(match.group(1))
-        elif self._match_section_tag(line):
-            self._append_line = self._append_various_line
-            self._append_various_line(line)
-            return
-        elif (self._section.text.endswith('\n\n')
-              and line and not line[0].isspace()):
-            if line == 'Features:':
-                self._append_line = self._append_features_line
-            else:
-                self._start_section()
-                self._append_line = self._append_various_line
-                self._append_various_line(line)
-            return
-
-        self._append_freeform(line)
-
-    def _append_features_line(self, line: str) -> None:
-        match = self._match_at_name_colon(line)
-        if match:
-            line = line[match.end():]
-            self._start_features_section(match.group(1))
-        elif self._match_section_tag(line):
-            self._append_line = self._append_various_line
-            self._append_various_line(line)
-            return
-        elif (self._section.text.endswith('\n\n')
-              and line and not line[0].isspace()):
-            self._start_section()
-            self._append_line = self._append_various_line
-            self._append_various_line(line)
-            return
-
-        self._append_freeform(line)
-
-    def _append_various_line(self, line: str) -> None:
-        """
-        Process a line of documentation text in an additional section.
-
-        A symbol line is an error.
-
-        A section tag begins an additional section.  Start that
-        section and append the line to it.
-
-        Else, append the line to the current section.
-        """
-        match = self._match_at_name_colon(line)
-        if match:
-            raise QAPIParseError(self._parser,
-                                 "description of '@%s:' follows a section"
-                                 % match.group(1))
-        match = self._match_section_tag(line)
-        if match:
-            line = line[match.end():]
-            self._start_section(match.group(1))
-
-        self._append_freeform(line)
-
-    def _start_symbol_section(
-            self,
-            symbols_dict: Dict[str, 'QAPIDoc.ArgSection'],
-            name: str) -> None:
-        # FIXME invalid names other than the empty string aren't flagged
+    def _new_description(self, name: str,
+                         desc: Dict[str, ArgSection]) -> None:
         if not name:
             raise QAPIParseError(self._parser, "invalid parameter name")
-        if name in symbols_dict:
+        if name in desc:
             raise QAPIParseError(self._parser,
                                  "'%s' parameter name duplicated" % name)
-        assert not self.sections
-        new_section = QAPIDoc.ArgSection(self._parser, '@' + name)
-        self._switch_section(new_section)
-        symbols_dict[name] = new_section
+        section = self.ArgSection(self._parser, '@' + name)
+        self.all_sections.append(section)
+        desc[name] = section
 
-    def _start_args_section(self, name: str) -> None:
-        self._start_symbol_section(self.args, name)
+    def new_argument(self, name: str) -> None:
+        self._new_description(name, self.args)
 
-    def _start_features_section(self, name: str) -> None:
-        self._start_symbol_section(self.features, name)
+    def new_feature(self, name: str) -> None:
+        self._new_description(name, self.features)
 
-    def _start_section(self, tag: Optional[str] = None) -> None:
-        if not tag and not self._section.tag:
-            # extend current section
-            return
-        if tag in ('Returns', 'Since') and self.has_section(tag):
-            raise QAPIParseError(self._parser,
-                                 "duplicated '%s' section" % tag)
-        new_section = QAPIDoc.Section(self._parser, tag)
-        self._switch_section(new_section)
-        self.sections.append(new_section)
-
-    def _switch_section(self, new_section: 'QAPIDoc.Section') -> None:
-        text = self._section.text = self._section.text.strip('\n')
-
-        # Only the 'body' section is allowed to have an empty body.
-        # All other sections, including anonymous ones, must have text.
-        if self._section != self.body and not text:
-            # We do not create anonymous sections unless there is
-            # something to put in them; this is a parser bug.
-            assert self._section.tag
-            raise QAPISemError(
-                self._section.info,
-                "text required after '%s:'" % self._section.tag)
-
-        self._section = new_section
-
-    def _append_freeform(self, line: str) -> None:
-        match = re.match(r'(@\S+:)', line)
-        if match:
-            raise QAPIParseError(self._parser,
-                                 "'%s' not allowed in free-form documentation"
-                                 % match.group(1))
-        self._section.append(line)
+    def append_line(self, line: str) -> None:
+        self.all_sections[-1].append_line(line)
 
     def connect_member(self, member: 'QAPISchemaMember') -> None:
         if member.name not in self.args:
@@ -758,8 +700,8 @@ def connect_member(self, member: 'QAPISchemaMember') -> None:
                 raise QAPISemError(member.info,
                                    "%s '%s' lacks documentation"
                                    % (member.role, member.name))
-            self.args[member.name] = QAPIDoc.ArgSection(self._parser,
-                                                        '@' + member.name)
+            self.args[member.name] = QAPIDoc.ArgSection(
+                self._parser, '@' + member.name)
         self.args[member.name].connect(member)
 
     def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
Signature · 1 line
2.43.0
Tested-by on v1 14/16
#30 lore raw

Re: [PATCH 14/16] qapi: Rewrite doc comment parser

Quoted 7 lines · Markus Armbruster

QAPISchemaParser is a conventional recursive descent parser. Except QAPISchemaParser.get_doc() delegates most of the doc comment parsing work to a state machine in QAPIDoc. The state machine doesn't get tokens like a recursive descent parser, it is fed tokens.

I find this state machine rather opaque and hard to maintain.

Quoted 7 lines

Replace it by a conventional parser, all in QAPISchemaParser. Less code, and (at least in my opinion) easier to understand.

---
 scripts/qapi/parser.py | 478 ++++++++++++++++++-----------------------
 1 file changed, 210 insertions(+), 268 deletions(-)

Reviewing parsing code typically gives me a headache, and reviewing diffs of parsing code is even worse. Thus instead of R-b I'll give a

on the basis that we've got great test coverage and I think that's the real killer requirement for parsing code. The tests still pass with this commit, so functionally it is working as expected.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#31 lore raw

Re: [PATCH 14/16] qapi: Rewrite doc comment parser

Quoted 20 lines · Daniel P. Berrangé
Quoted 7 lines · Markus Armbruster

QAPISchemaParser is a conventional recursive descent parser. Except QAPISchemaParser.get_doc() delegates most of the doc comment parsing work to a state machine in QAPIDoc. The state machine doesn't get tokens like a recursive descent parser, it is fed tokens.

I find this state machine rather opaque and hard to maintain.

Quoted 7 lines

Replace it by a conventional parser, all in QAPISchemaParser. Less code, and (at least in my opinion) easier to understand.

---
 scripts/qapi/parser.py | 478 ++++++++++++++++++-----------------------
 1 file changed, 210 insertions(+), 268 deletions(-)

Reviewing parsing code typically gives me a headache, and reviewing diffs of parsing code is even worse. Thus instead of R-b I'll give a

Quoted 5 lines

on the basis that we've got great test coverage and I think that's the real killer requirement for parsing code. The tests still pass with this commit, so functionally it is working as expected.

Makes sense. Figuring out what language the old parser parses gave me a headache or three, too.

Thanks!

#32 lore raw

PATCH 15/16 qapi: Reject multiple and empty feature descriptions

In reply to Markus Armbruster

The parser recognizes only the first "Features:" line. Any subsequent ones are treated as ordinary text, as visible in test case doc-duplicate-features. Recognize "Features:" lines anywhere. A second one is an error.

A 'Features:' line without any features is useless, but not an error. Make it an error. This makes detecting a second "Features:" line easier.

qapi/run-state.json actually has an instance of this since commit fe17522d854 (qapi: Remove deprecated 'singlestep' member of StatusInfo). Clean it up.

---
 qapi/run-state.json                          |  2 --
 scripts/qapi/parser.py                       |  8 ++++++-
 tests/qapi-schema/doc-duplicate-features.err |  1 +
 tests/qapi-schema/doc-duplicate-features.out | 22 --------------------
 tests/qapi-schema/doc-empty-features.err     |  1 +
 tests/qapi-schema/doc-empty-features.out     | 17 ---------------
 6 files changed, 9 insertions(+), 42 deletions(-)
qapi/run-state.json +0 -2
index d19d23a0fd..dd0770b379 100644
@@ -108,8 +108,6 @@
 #
 # @status: the virtual machine @RunState
 #
-# Features:
-#
 # Since: 0.14
 #
 ##
scripts/qapi/parser.py +7 -1
index 73ff150430..3d8c62b412 100644
@@ -507,7 +507,10 @@ def get_doc(self) -> 'QAPIDoc':
                 if line is None:
                     break
                 # Non-blank line, first of a section
-                if line == 'Features:' and not doc.features:
+                if line == 'Features:':
+                    if doc.features:
+                        raise QAPIParseError(
+                            self, "duplicated 'Features:' line")
                     self.accept(False)
                     line = self.get_doc_line()
                     while line == '':
@@ -520,6 +523,9 @@ def get_doc(self) -> 'QAPIDoc':
                         if text:
                             doc.append_line(text)
                         line = self.get_doc_indented(doc)
+                    if not doc.features:
+                        raise QAPIParseError(
+                            self, 'feature descriptions expected')
                     no_more_args = True
                 elif match := self._match_at_name_colon(line):
                     # description
tests/qapi-schema/doc-duplicate-features.err +1 -0
index e69de29bb2..cadb2957a6 100644
@@ -0,0 +1 @@
+doc-duplicate-features.json:9:1: duplicated 'Features:' line
tests/qapi-schema/doc-duplicate-features.out +0 -22
index 43bfe1034b..e69de29bb2 100644
@@ -1,22 +0,0 @@
-module ./builtin
-object q_empty
-enum QType
-    prefix QTYPE
-    member none
-    member qnull
-    member qnum
-    member qstring
-    member qdict
-    member qlist
-    member qbool
-module doc-duplicate-features.json
-command foo None -> None
-    gen=True success_response=True boxed=False oob=False preconfig=False
-    feature feat
-doc symbol=foo
-    body=
-
-    feature=feat
-mumble
-    section=None
-Features:
tests/qapi-schema/doc-empty-features.err +1 -0
index e69de29bb2..2709a18d8f 100644
@@ -0,0 +1 @@
+doc-empty-features.json:8:1: feature descriptions expected
tests/qapi-schema/doc-empty-features.out +0 -17
index 473f59552d..e69de29bb2 100644
@@ -1,17 +0,0 @@
-module ./builtin
-object q_empty
-enum QType
-    prefix QTYPE
-    member none
-    member qnull
-    member qnum
-    member qstring
-    member qdict
-    member qlist
-    member qbool
-module doc-empty-features.json
-command foo None -> None
-    gen=True success_response=True boxed=False oob=False preconfig=False
-doc symbol=foo
-    body=
-not a description
Signature · 1 line
2.43.0
Reviewed-by on v1 15/16
#33 lore raw

Re: [PATCH 15/16] qapi: Reject multiple and empty feature descriptions

Quoted 14 lines · Markus Armbruster

The parser recognizes only the first "Features:" line. Any subsequent ones are treated as ordinary text, as visible in test case doc-duplicate-features. Recognize "Features:" lines anywhere. A second one is an error.

A 'Features:' line without any features is useless, but not an error. Make it an error. This makes detecting a second "Features:" line easier.

qapi/run-state.json actually has an instance of this since commit fe17522d854 (qapi: Remove deprecated 'singlestep' member of StatusInfo). Clean it up.

Quoted 8 lines
---
 qapi/run-state.json                          |  2 --
 scripts/qapi/parser.py                       |  8 ++++++-
 tests/qapi-schema/doc-duplicate-features.err |  1 +
 tests/qapi-schema/doc-duplicate-features.out | 22 --------------------
 tests/qapi-schema/doc-empty-features.err     |  1 +
 tests/qapi-schema/doc-empty-features.out     | 17 ---------------
 6 files changed, 9 insertions(+), 42 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#34 lore raw

PATCH 16/16 qapi: Divorce QAPIDoc from QAPIParseError

In reply to Markus Armbruster

QAPIDoc stores a reference to QAPIParser just to pass it to QAPIParseError. The resulting error position depends on the state of the parser. It happens to be the current comment line. Servicable, but action at a distance.

The commit before previous moved most uses of QAPIParseError from QAPIDoc to QAPIParser. There are just three left. Convert them to QAPISemError. This involves passing info to a few methods. Then drop the reference to QAPIParser.

The three errors lose the column number. Not really interesting here:
it's the comment line's indentation.

---
 scripts/qapi/parser.py                      | 66 +++++++++------------
 tests/qapi-schema/doc-duplicated-arg.err    |  2 +-
 tests/qapi-schema/doc-duplicated-return.err |  2 +-
 tests/qapi-schema/doc-duplicated-since.err  |  2 +-
 tests/qapi-schema/doc-empty-arg.err         |  2 +-
 5 files changed, 32 insertions(+), 42 deletions(-)
scripts/qapi/parser.py +28 -38
index 3d8c62b412..11707418fb 100644
@@ -494,7 +494,7 @@ def get_doc(self) -> 'QAPIDoc':
             symbol = line[1:-1]
             if not symbol:
                 raise QAPIParseError(self, "name required after '@'")
-            doc = QAPIDoc(self, info, symbol)
+            doc = QAPIDoc(info, symbol)
             self.accept(False)
             line = self.get_doc_line()
             no_more_args = False
@@ -518,7 +518,7 @@ def get_doc(self) -> 'QAPIDoc':
                         line = self.get_doc_line()
                     while (line is not None
                            and (match := self._match_at_name_colon(line))):
-                        doc.new_feature(match.group(1))
+                        doc.new_feature(self.info, match.group(1))
                         text = line[match.end():]
                         if text:
                             doc.append_line(text)
@@ -536,7 +536,7 @@ def get_doc(self) -> 'QAPIDoc':
                             % match.group(1))
                     while (line is not None
                            and (match := self._match_at_name_colon(line))):
-                        doc.new_argument(match.group(1))
+                        doc.new_argument(self.info, match.group(1))
                         text = line[match.end():]
                         if text:
                             doc.append_line(text)
@@ -546,7 +546,7 @@ def get_doc(self) -> 'QAPIDoc':
                         r'(Returns|Since|Notes?|Examples?|TODO): *',
                         line):
                     # tagged section
-                    doc.new_tagged_section(match.group(1))
+                    doc.new_tagged_section(self.info, match.group(1))
                     text = line[match.end():]
                     if text:
                         doc.append_line(text)
@@ -558,13 +558,13 @@ def get_doc(self) -> 'QAPIDoc':
                         "unexpected '=' markup in definition documentation")
                 else:
                     # tag-less paragraph
-                    doc.ensure_untagged_section()
+                    doc.ensure_untagged_section(self.info)
                     doc.append_line(line)
                     line = self.get_doc_paragraph(doc)
         else:
             # Free-form documentation
-            doc = QAPIDoc(self, info)
-            doc.ensure_untagged_section()
+            doc = QAPIDoc(info)
+            doc.ensure_untagged_section(self.info)
             first = True
             while line is not None:
                 if match := self._match_at_name_colon(line):
@@ -607,12 +607,10 @@ class QAPIDoc:
     """
 
     class Section:
-        def __init__(self, parser: QAPISchemaParser,
+        def __init__(self, info: QAPISourceInfo,
                      tag: Optional[str] = None):
             # section source info, i.e. where it begins
-            self.info = parser.info
-            # parser, for error messages about indentation
-            self._parser = parser
+            self.info = info
             # section tag, if any ('Returns', '@name', ...)
             self.tag = tag
             # section text without tag
@@ -622,27 +620,20 @@ def append_line(self, line: str) -> None:
             self.text += line + '\n'
 
     class ArgSection(Section):
-        def __init__(self, parser: QAPISchemaParser,
-                     tag: str):
-            super().__init__(parser, tag)
+        def __init__(self, info: QAPISourceInfo, tag: str):
+            super().__init__(info, tag)
             self.member: Optional['QAPISchemaMember'] = None
 
         def connect(self, member: 'QAPISchemaMember') -> None:
             self.member = member
 
-    def __init__(self, parser: QAPISchemaParser, info: QAPISourceInfo,
-                 symbol: Optional[str] = None):
-        # self._parser is used to report errors with QAPIParseError.  The
-        # resulting error position depends on the state of the parser.
-        # It happens to be the beginning of the comment.  More or less
-        # servicable, but action at a distance.
-        self._parser = parser
+    def __init__(self, info: QAPISourceInfo, symbol: Optional[str] = None):
         # info points to the doc comment block's first line
         self.info = info
         # definition doc's symbol, None for free-form doc
         self.symbol: Optional[str] = symbol
         # the sections in textual order
-        self.all_sections: List[QAPIDoc.Section] = [QAPIDoc.Section(parser)]
+        self.all_sections: List[QAPIDoc.Section] = [QAPIDoc.Section(info)]
         # the body section
         self.body: Optional[QAPIDoc.Section] = self.all_sections[0]
         # dicts mapping parameter/feature names to their description
@@ -658,44 +649,43 @@ def end(self) -> None:
                 raise QAPISemError(
                     section.info, "text required after '%s:'" % section.tag)
 
-    def ensure_untagged_section(self) -> None:
+    def ensure_untagged_section(self, info: QAPISourceInfo) -> None:
         if self.all_sections and not self.all_sections[-1].tag:
             # extend current section
             self.all_sections[-1].text += '\n'
             return
         # start new section
-        section = self.Section(self._parser)
+        section = self.Section(info)
         self.sections.append(section)
         self.all_sections.append(section)
 
-    def new_tagged_section(self, tag: str) -> None:
+    def new_tagged_section(self, info: QAPISourceInfo, tag: str) -> None:
         if tag in ('Returns', 'Since'):
             for section in self.all_sections:
                 if isinstance(section, self.ArgSection):
                     continue
                 if section.tag == tag:
-                    raise QAPIParseError(
-                        self._parser, "duplicated '%s' section" % tag)
-        section = self.Section(self._parser, tag)
+                    raise QAPISemError(
+                        info, "duplicated '%s' section" % tag)
+        section = self.Section(info, tag)
         self.sections.append(section)
         self.all_sections.append(section)
 
-    def _new_description(self, name: str,
+    def _new_description(self, info: QAPISourceInfo, name: str,
                          desc: Dict[str, ArgSection]) -> None:
         if not name:
-            raise QAPIParseError(self._parser, "invalid parameter name")
+            raise QAPISemError(info, "invalid parameter name")
         if name in desc:
-            raise QAPIParseError(self._parser,
-                                 "'%s' parameter name duplicated" % name)
-        section = self.ArgSection(self._parser, '@' + name)
+            raise QAPISemError(info, "'%s' parameter name duplicated" % name)
+        section = self.ArgSection(info, '@' + name)
         self.all_sections.append(section)
         desc[name] = section
 
-    def new_argument(self, name: str) -> None:
-        self._new_description(name, self.args)
+    def new_argument(self, info: QAPISourceInfo, name: str) -> None:
+        self._new_description(info, name, self.args)
 
-    def new_feature(self, name: str) -> None:
-        self._new_description(name, self.features)
+    def new_feature(self, info: QAPISourceInfo, name: str) -> None:
+        self._new_description(info, name, self.features)
 
     def append_line(self, line: str) -> None:
         self.all_sections[-1].append_line(line)
@@ -707,7 +697,7 @@ def connect_member(self, member: 'QAPISchemaMember') -> None:
                                    "%s '%s' lacks documentation"
                                    % (member.role, member.name))
             self.args[member.name] = QAPIDoc.ArgSection(
-                self._parser, '@' + member.name)
+                self.info, '@' + member.name)
         self.args[member.name].connect(member)
 
     def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
tests/qapi-schema/doc-duplicated-arg.err +1 -1
index 0d0d777a1f..d876312734 100644
@@ -1 +1 @@
-doc-duplicated-arg.json:6:1: 'a' parameter name duplicated
+doc-duplicated-arg.json:6: 'a' parameter name duplicated
tests/qapi-schema/doc-duplicated-return.err +1 -1
index f19a2b8ec4..503b916b25 100644
@@ -1 +1 @@
-doc-duplicated-return.json:8:1: duplicated 'Returns' section
+doc-duplicated-return.json:8: duplicated 'Returns' section
tests/qapi-schema/doc-duplicated-since.err +1 -1
index 565b753b6a..a9b60c0c3d 100644
@@ -1 +1 @@
-doc-duplicated-since.json:8:1: duplicated 'Since' section
+doc-duplicated-since.json:8: duplicated 'Since' section
tests/qapi-schema/doc-empty-arg.err +1 -1
index 2d0f35f310..83f4fc66d5 100644
@@ -1 +1 @@
-doc-empty-arg.json:5:1: invalid parameter name
+doc-empty-arg.json:5: invalid parameter name
Signature · 1 line
2.43.0
Reviewed-by on v1 16/16
#35 lore raw

Re: [PATCH 16/16] qapi: Divorce QAPIDoc from QAPIParseError

Quoted 13 lines · Markus Armbruster

QAPIDoc stores a reference to QAPIParser just to pass it to QAPIParseError. The resulting error position depends on the state of the parser. It happens to be the current comment line. Servicable, but action at a distance.

The commit before previous moved most uses of QAPIParseError from QAPIDoc to QAPIParser. There are just three left. Convert them to QAPISemError. This involves passing info to a few methods. Then drop the reference to QAPIParser.

The three errors lose the column number. Not really interesting here:
it's the comment line's indentation.

Quoted 8 lines
---
 scripts/qapi/parser.py                      | 66 +++++++++------------
 tests/qapi-schema/doc-duplicated-arg.err    |  2 +-
 tests/qapi-schema/doc-duplicated-return.err |  2 +-
 tests/qapi-schema/doc-duplicated-since.err  |  2 +-
 tests/qapi-schema/doc-empty-arg.err         |  2 +-
 5 files changed, 32 insertions(+), 42 deletions(-)

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|