Skip to contentSkip to conversation

qapi: Fix minor bugs, require boxed for conditional arguments

PATCH In review Markus Armbruster 3 participants 36 messages Mar 16, 2023 – Mar 17, 2023 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

cover qapi: Fix minor bugs, require boxed for conditional arguments

PATCH 01-08 fix a few minor bugs I found on the way. Could be a separate series, but keeping them here seems simpler.

PATCH 09-12 improve tests for 'if' conditionals.

PATCH 13 fixes a code generation regression, and PATCH 14 rejects uses conditionals that never worked and aren't worth fixing.

Markus Armbruster (14):
qapi: Fix error message format regression qapi/schema: Use super()
qapi: Clean up after removal of simple unions
qapi: Split up check_type()
qapi: Improve error message for unexpected array types
qapi: Simplify code a bit after previous commit
qapi: Fix error message when type name or array is expected
qapi: Fix to reject 'data': 'mumble' in struct tests/qapi-schema: Improve union discriminator coverage tests/qapi-schema: Rename a few conditionals tests/qapi-schema: Clean up positive test for conditionals tests/qapi-schema: Cover optional conditional struct member
qapi: Fix code generated for optional conditional struct member
qapi: Require boxed for conditional command and event arguments

 docs/devel/qapi-code-gen.rst                  |   5 +-
 scripts/qapi/commands.py                      |   1 +
 scripts/qapi/expr.py                          | 115 ++++++++++--------
 scripts/qapi/gen.py                           |   1 +
 scripts/qapi/main.py                          |   2 +-
 scripts/qapi/schema.py                        |  16 ++-
 scripts/qapi/visit.py                         |   2 +
 tests/qapi-schema/args-if-implicit.err        |   2 +
 tests/qapi-schema/args-if-implicit.json       |   4 +
 tests/qapi-schema/args-if-implicit.out        |   0
 tests/qapi-schema/args-if-unboxed.err         |   2 +
 tests/qapi-schema/args-if-unboxed.json        |   6 +
 tests/qapi-schema/args-if-unboxed.out         |   0
 tests/qapi-schema/bad-data.err                |   2 +-
 tests/qapi-schema/event-args-if-unboxed.err   |   2 +
 tests/qapi-schema/event-args-if-unboxed.json  |   4 +
 tests/qapi-schema/event-args-if-unboxed.out   |   0
 tests/qapi-schema/event-nest-struct.err       |   2 +-
 tests/qapi-schema/meson.build                 |   3 +
 tests/qapi-schema/nested-struct-data.err      |   2 +-
 tests/qapi-schema/qapi-schema-test.json       |  20 +--
 tests/qapi-schema/qapi-schema-test.out        |  32 ++---
 tests/qapi-schema/returns-dict.err            |   2 +-
 tests/qapi-schema/struct-data-typename.err    |   2 +
 tests/qapi-schema/struct-data-typename.json   |   2 +
 tests/qapi-schema/struct-data-typename.out    |   0
 tests/qapi-schema/struct-member-invalid.err   |   2 +-
 tests/qapi-schema/union-array-branch.err      |   2 +-
 .../union-invalid-discriminator.err           |   2 +-
 .../union-invalid-discriminator.json          |   4 +-
 30 files changed, 141 insertions(+), 98 deletions(-)
 create mode 100644 tests/qapi-schema/args-if-implicit.err
 create mode 100644 tests/qapi-schema/args-if-implicit.json
 create mode 100644 tests/qapi-schema/args-if-implicit.out
 create mode 100644 tests/qapi-schema/args-if-unboxed.err
 create mode 100644 tests/qapi-schema/args-if-unboxed.json
 create mode 100644 tests/qapi-schema/args-if-unboxed.out
 create mode 100644 tests/qapi-schema/event-args-if-unboxed.err
 create mode 100644 tests/qapi-schema/event-args-if-unboxed.json
 create mode 100644 tests/qapi-schema/event-args-if-unboxed.out
 create mode 100644 tests/qapi-schema/struct-data-typename.err
 create mode 100644 tests/qapi-schema/struct-data-typename.json
 create mode 100644 tests/qapi-schema/struct-data-typename.out
Signature · 1 line
2.39.2
#1 lore raw

PATCH 1/14 qapi: Fix error message format regression

Commit 52a474180ae3 changed reporting of errors connected to a source location without mentioning it in the commit message. For instance,

    $ python scripts/qapi-gen.py tests/qapi-schema/unknown-escape.json
    tests/qapi-schema/unknown-escape.json:3:21: unknown escape \x

became

scripts/qapi-gen.py: tests/qapi-schema/unknown-escape.json:3:21: unknown escape \x

This is not how compilers report such errors, and Emacs doesn't recognize the format. Revert this change.

Fixes 52a474180ae3 (qapi-gen: Separate arg-parsing from generation)
---
 scripts/qapi/main.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/qapi/main.py +1 -1
index fc216a53d3..316736b6a2 100644
@@ -98,6 +98,6 @@ def main() -> int:
                  builtins=args.builtins,
                  gen_tracing=not args.suppress_tracing)
     except QAPIError as err:
-        print(f"{sys.argv[0]}: {str(err)}", file=sys.stderr)
+        print(err, file=sys.stderr)
         return 1
     return 0
Signature · 1 line
2.39.2
Reviewed-by on v1 1/14
#2 lore raw

Re: [PATCH 01/14] qapi: Fix error message format regression

Quoted 10 lines · Markus Armbruster

Commit 52a474180ae3 changed reporting of errors connected to a source location without mentioning it in the commit message. For instance,

    $ python scripts/qapi-gen.py tests/qapi-schema/unknown-escape.json
    tests/qapi-schema/unknown-escape.json:3:21: unknown escape \x

became

scripts/qapi-gen.py: tests/qapi-schema/unknown-escape.json:3:21: unknown escape \x

Quoted 8 lines

This is not how compilers report such errors, and Emacs doesn't recognize the format. Revert this change.

Fixes 52a474180ae3 (qapi-gen: Separate arg-parsing from generation)
---
 scripts/qapi/main.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#3 lore raw

PATCH 2/14 qapi/schema: Use super()

In reply to Markus Armbruster

Commit 2cae67bcb5e (qapi: Use super() now we have Python 3) converted the code to super(). Shortly after, commit f965e8fea6a (qapi: New special feature flag "deprecated") neglected to use super(). Convert it now.

---
 scripts/qapi/schema.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/qapi/schema.py +1 -1
index 207e4d71f3..719152fe49 100644
@@ -259,7 +259,7 @@ def need_has_if_optional(self):
         return not self.c_type().endswith(POINTER_SUFFIX)
 
     def check(self, schema):
-        QAPISchemaEntity.check(self, schema)
+        super().check(schema)
         for feat in self.features:
             if feat.is_special():
                 raise QAPISemError(
Signature · 1 line
2.39.2
Reviewed-by on v1 2/14
#4 lore raw

Re: [PATCH 02/14] qapi/schema: Use super()

Quoted 9 lines · Markus Armbruster

Commit 2cae67bcb5e (qapi: Use super() now we have Python 3) converted the code to super(). Shortly after, commit f965e8fea6a (qapi: New special feature flag "deprecated") neglected to use super(). Convert it now.

---
  scripts/qapi/schema.py | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)
#5 lore raw

PATCH 3/14 qapi: Clean up after removal of simple unions

In reply to Markus Armbruster

Commit 4e99f4b12c0 (qapi: Drop simple unions) missed a bit of code dealing with simple union branches. Drop it.

---
 scripts/qapi/expr.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/qapi/expr.py +1 -1
index ca01ea6f4a..59bdd86024 100644
@@ -518,7 +518,7 @@ def check_union(expr: QAPIExpression) -> None:
         source = "'data' member '%s'" % key
         check_keys(value, info, source, ['type'], ['if'])
         check_if(value, info, source)
-        check_type(value['type'], info, source, allow_array=not base)
+        check_type(value['type'], info, source)
 
 
 def check_alternate(expr: QAPIExpression) -> None:
Signature · 1 line
2.39.2
Reviewed-by on v1 3/14
#6 lore raw

Re: [PATCH 03/14] qapi: Clean up after removal of simple unions

Quoted 5 lines · Markus Armbruster

Commit 4e99f4b12c0 (qapi: Drop simple unions) missed a bit of code dealing with simple union branches. Drop it.

---

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#7 lore raw

PATCH 4/14 qapi: Split up check_type()

In reply to Markus Armbruster

check_type() can check type names, arrays, and implicit struct types. Callers pass flags to select from this menu. This makes the function somewhat hard to read. Moreover, a few minor bugs are hiding in there, as we'll see shortly.

Split it into check_type_name(), check_type_name_or_implicit(). Each of them is a copy of the original specialized to a certain set of flags.

---
 scripts/qapi/expr.py | 116 +++++++++++++++++++++++++------------------
 1 file changed, 67 insertions(+), 49 deletions(-)
scripts/qapi/expr.py +67 -49
index 59bdd86024..bc04bf34c2 100644
@@ -333,62 +333,74 @@ def normalize_members(members: object) -> None:
             members[key] = {'type': arg}
 
 
-def check_type(value: Optional[object],
-               info: QAPISourceInfo,
-               source: str,
-               allow_array: bool = False,
-               allow_dict: Union[bool, str] = False) -> None:
-    """
-    Normalize and validate the QAPI type of ``value``.
-
-    Python types of ``str`` or ``None`` are always allowed.
-
-    :param value: The value to check.
-    :param info: QAPI schema source file information.
-    :param source: Error string describing this ``value``.
-    :param allow_array:
-        Allow a ``List[str]`` of length 1, which indicates an array of
-        the type named by the list element.
-    :param allow_dict:
-        Allow a dict.  Its members can be struct type members or union
-        branches.  When the value of ``allow_dict`` is in pragma
-        ``member-name-exceptions``, the dict's keys may violate the
-        member naming rules.  The dict members are normalized in place.
-
-    :raise QAPISemError: When ``value`` fails validation.
-    :return: None, ``value`` is normalized in-place as needed.
-    """
+def check_type_name(value: Optional[object],
+                    info: QAPISourceInfo, source: str) -> None:
+    if value is None:
+        return
+
+    if isinstance(value, str):
+        return
+
+    if isinstance(value, list):
+        raise QAPISemError(info, "%s cannot be an array" % source)
+
+    raise QAPISemError(info, "%s should be a type name" % source)
+
+
+def check_type_name_or_array(value: Optional[object],
+                             info: QAPISourceInfo, source: str) -> None:
     if value is None:
         return
 
-    # Type name
     if isinstance(value, str):
         return
 
-    # Array type
     if isinstance(value, list):
-        if not allow_array:
-            raise QAPISemError(info, "%s cannot be an array" % source)
         if len(value) != 1 or not isinstance(value[0], str):
             raise QAPISemError(info,
                                "%s: array type must contain single type name" %
                                source)
         return
 
-    # Anonymous type
+    raise QAPISemError(info,
+                       "%s should be a type name" % source)
 
-    if not allow_dict:
-        raise QAPISemError(info, "%s should be a type name" % source)
+
+def check_type_name_or_implicit(value: Optional[object],
+                                info: QAPISourceInfo, source: str,
+                                parent_name: Optional[str]) -> None:
+    """
+    Normalize and validate an optional implicit struct type.
+
+    Accept ``None``, ``str``, or a ``dict`` defining an implicit
+    struct type.  The latter is normalized in place.
+
+    :param value: The value to check.
+    :param info: QAPI schema source file information.
+    :param source: Error string describing this ``value``.
+    :param parent_name:
+        When the value of ``parent_name`` is in pragma
+        ``member-name-exceptions``, an implicit struct type may
+        violate the member naming rules.
+
+    :raise QAPISemError: When ``value`` fails validation.
+    :return: None
+    """
+    if value is None:
+        return
+
+    if isinstance(value, str):
+        return
+
+    if isinstance(value, list):
+        raise QAPISemError(info, "%s cannot be an array" % source)
 
     if not isinstance(value, dict):
         raise QAPISemError(info,
                            "%s should be an object or type name" % source)
 
-    permissive = False
-    if isinstance(allow_dict, str):
-        permissive = allow_dict in info.pragma.member_name_exceptions
+    permissive = parent_name in info.pragma.member_name_exceptions
 
-    # value is a dictionary, check that each member is okay
     for (key, arg) in value.items():
         key_source = "%s member '%s'" % (source, key)
         if key.startswith('*'):
@@ -401,7 +413,7 @@ def check_type(value: Optional[object],
         check_keys(arg, info, key_source, ['type'], ['if', 'features'])
         check_if(arg, info, key_source)
         check_features(arg.get('features'), info)
-        check_type(arg['type'], info, key_source, allow_array=True)
+        check_type_name_or_array(arg['type'], info, key_source)
 
 
 def check_features(features: Optional[object],
@@ -489,8 +501,8 @@ def check_struct(expr: QAPIExpression) -> None:
     name = cast(str, expr['struct'])  # Checked in check_exprs
     members = expr['data']
 
-    check_type(members, expr.info, "'data'", allow_dict=name)
-    check_type(expr.get('base'), expr.info, "'base'")
+    check_type_name_or_implicit(members, expr.info, "'data'", name)
+    check_type_name(expr.get('base'), expr.info, "'base'")
 
 
 def check_union(expr: QAPIExpression) -> None:
@@ -508,7 +520,7 @@ def check_union(expr: QAPIExpression) -> None:
     members = expr['data']
     info = expr.info
 
-    check_type(base, info, "'base'", allow_dict=name)
+    check_type_name_or_implicit(base, info, "'base'", name)
     check_name_is_str(discriminator, info, "'discriminator'")
 
     if not isinstance(members, dict):
@@ -518,7 +530,7 @@ def check_union(expr: QAPIExpression) -> None:
         source = "'data' member '%s'" % key
         check_keys(value, info, source, ['type'], ['if'])
         check_if(value, info, source)
-        check_type(value['type'], info, source)
+        check_type_name(value['type'], info, source)
 
 
 def check_alternate(expr: QAPIExpression) -> None:
@@ -544,7 +556,7 @@ def check_alternate(expr: QAPIExpression) -> None:
         check_name_lower(key, info, source)
         check_keys(value, info, source, ['type'], ['if'])
         check_if(value, info, source)
-        check_type(value['type'], info, source, allow_array=True)
+        check_type_name_or_array(value['type'], info, source)
 
 
 def check_command(expr: QAPIExpression) -> None:
@@ -560,10 +572,13 @@ def check_command(expr: QAPIExpression) -> None:
     rets = expr.get('returns')
     boxed = expr.get('boxed', False)
 
-    if boxed and args is None:
-        raise QAPISemError(expr.info, "'boxed': true requires 'data'")
-    check_type(args, expr.info, "'data'", allow_dict=not boxed)
-    check_type(rets, expr.info, "'returns'", allow_array=True)
+    if boxed:
+        if args is None:
+            raise QAPISemError(expr.info, "'boxed': true requires 'data'")
+        check_type_name(args, expr.info, "'data'")
+    else:
+        check_type_name_or_implicit(args, expr.info, "'data'", None)
+    check_type_name_or_array(rets, expr.info, "'returns'")
 
 
 def check_event(expr: QAPIExpression) -> None:
@@ -578,9 +593,12 @@ def check_event(expr: QAPIExpression) -> None:
     args = expr.get('data')
     boxed = expr.get('boxed', False)
 
-    if boxed and args is None:
-        raise QAPISemError(expr.info, "'boxed': true requires 'data'")
-    check_type(args, expr.info, "'data'", allow_dict=not boxed)
+    if boxed:
+        if args is None:
+            raise QAPISemError(expr.info, "'boxed': true requires 'data'")
+        check_type_name(args, expr.info, "'data'")
+    else:
+        check_type_name_or_implicit(args, expr.info, "'data'", None)
 
 
 def check_exprs(exprs: List[QAPIExpression]) -> List[QAPIExpression]:
Signature · 1 line
2.39.2
Reviewed-by on v1 4/14
#8 lore raw

Re: [PATCH 04/14] qapi: Split up check_type()

Quoted 6 lines · Markus Armbruster

check_type() can check type names, arrays, and implicit struct types. Callers pass flags to select from this menu. This makes the function somewhat hard to read. Moreover, a few minor bugs are hiding in there, as we'll see shortly.

Split it into check_type_name(), check_type_name_or_implicit(). Each

You omitted check_type_name_or_array() in this summary

Quoted 14 lines

of them is a copy of the original specialized to a certain set of flags.

---
 scripts/qapi/expr.py | 116 +++++++++++++++++++++++++------------------
 1 file changed, 67 insertions(+), 49 deletions(-)
scripts/qapi/expr.py +0 -0
index 59bdd86024..bc04bf34c2 100644

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 340

Quoted 8 lines
scripts/qapi/expr.py +0 -5
@@ -333,62 +333,74 @@ def normalize_members(members: object) -> None:
             members[key] = {'type': arg}
 
 
-def check_type(value: Optional[object],
-               info: QAPISourceInfo,
-               source: str,
-               allow_array: bool = False,
-               allow_dict: Union[bool, str] = False) -> None:

There are few enough callers to see that they do indeed have exactly one of (nearly) three call patterns.

Quoted 12 lines
scripts/qapi/expr.py +0 -12
-    """
-    Normalize and validate the QAPI type of ``value``.
-
-    Python types of ``str`` or ``None`` are always allowed.
-
-    :param value: The value to check.
-    :param info: QAPI schema source file information.
-    :param source: Error string describing this ``value``.
-    :param allow_array:
-        Allow a ``List[str]`` of length 1, which indicates an array of
-        the type named by the list element.
-    :param allow_dict:

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 337

Quoted 10 lines
scripts/qapi/expr.py +2 -8
-        Allow a dict.  Its members can be struct type members or union
-        branches.  When the value of ``allow_dict`` is in pragma
-        ``member-name-exceptions``, the dict's keys may violate the
-        member naming rules.  The dict members are normalized in place.
-
-    :raise QAPISemError: When ``value`` fails validation.
-    :return: None, ``value`` is normalized in-place as needed.
-    """
+def check_type_name(value: Optional[object],
+                    info: QAPISourceInfo, source: str) -> None:

check_type_name() replaces callers that relied on the default for allow_array and allow_dict

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 338

Quoted 1 line
scripts/qapi/expr.py +1 -0
+    if value is None:

Loses out on the documentation. Not sure how much that matters to you?

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 351

Quoted 13 lines
scripts/qapi/expr.py +13 -0
+        return
+
+    if isinstance(value, str):
+        return
+
+    if isinstance(value, list):
+        raise QAPISemError(info, "%s cannot be an array" % source)
+
+    raise QAPISemError(info, "%s should be a type name" % source)
+
+
+def check_type_name_or_array(value: Optional[object],
+                             info: QAPISourceInfo, source: str) -> None:

check_type_name_or_array() replaces all callers that passed allow_array=True.

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 352

Quoted 1 line
scripts/qapi/expr.py +0 -0
     if value is None:

Another copy without documentation.

Quoted 16 lines
scripts/qapi/expr.py +0 -4
         return
 
-    # Type name
     if isinstance(value, str):
         return
 
-    # Array type
     if isinstance(value, list):
-        if not allow_array:
-            raise QAPISemError(info, "%s cannot be an array" % source)
         if len(value) != 1 or not isinstance(value[0], str):
             raise QAPISemError(info,
                                "%s: array type must contain single type name" %
                                source)
         return
 

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 371

Quoted 10 lines
scripts/qapi/expr.py +6 -3
-    # Anonymous type
+    raise QAPISemError(info,
+                       "%s should be a type name" % source)
 
-    if not allow_dict:
-        raise QAPISemError(info, "%s should be a type name" % source)
+
+def check_type_name_or_implicit(value: Optional[object],
+                                info: QAPISourceInfo, source: str,
+                                parent_name: Optional[str]) -> None:

And check_type_name_or_implicit replaces all callers that passed allow_dict=str, where str is now the parent_name. (Wow, that was an odd overload of the parameter name - I like the split version better).

...

Quoted 4 lines
scripts/qapi/expr.py +0 -0
@@ -560,10 +572,13 @@ def check_command(expr: QAPIExpression) -> None:
     rets = expr.get('returns')
     boxed = expr.get('boxed', False)
 

scripts/qapi/expr.py def check_command(expr: QAPIExpression) -> None: · line 580

Quoted 10 lines
scripts/qapi/expr.py +6 -4
-    if boxed and args is None:
-        raise QAPISemError(expr.info, "'boxed': true requires 'data'")
-    check_type(args, expr.info, "'data'", allow_dict=not boxed)
-    check_type(rets, expr.info, "'returns'", allow_array=True)
+    if boxed:
+        if args is None:
+            raise QAPISemError(expr.info, "'boxed': true requires 'data'")
+        check_type_name(args, expr.info, "'data'")
+    else:
+        check_type_name_or_implicit(args, expr.info, "'data'", None)

And this use of allow_dict was the weirdest, where it really does fit better as calls into two separate functions.

With the fixed commit message, and with or without more function docs,

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#9 lore raw

Re: [PATCH 04/14] qapi: Split up check_type()

Quoted 9 lines · Eric Blake
Quoted 6 lines · Markus Armbruster

check_type() can check type names, arrays, and implicit struct types. Callers pass flags to select from this menu. This makes the function somewhat hard to read. Moreover, a few minor bugs are hiding in there, as we'll see shortly.

Split it into check_type_name(), check_type_name_or_implicit(). Each

You omitted check_type_name_or_array() in this summary

Oops!

Quoted 43 lines
Quoted 14 lines

of them is a copy of the original specialized to a certain set of flags.

---
 scripts/qapi/expr.py | 116 +++++++++++++++++++++++++------------------
 1 file changed, 67 insertions(+), 49 deletions(-)
scripts/qapi/expr.py +0 -0
index 59bdd86024..bc04bf34c2 100644

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 340

Quoted 8 lines
scripts/qapi/expr.py +0 -5
@@ -333,62 +333,74 @@ def normalize_members(members: object) -> None:
             members[key] = {'type': arg}
 
 
-def check_type(value: Optional[object],
-               info: QAPISourceInfo,
-               source: str,
-               allow_array: bool = False,
-               allow_dict: Union[bool, str] = False) -> None:

There are few enough callers to see that they do indeed have exactly one of (nearly) three call patterns.

Quoted 17 lines
scripts/qapi/expr.py +0 -17
-    """
-    Normalize and validate the QAPI type of ``value``.
-
-    Python types of ``str`` or ``None`` are always allowed.
-
-    :param value: The value to check.
-    :param info: QAPI schema source file information.
-    :param source: Error string describing this ``value``.
-    :param allow_array:
-        Allow a ``List[str]`` of length 1, which indicates an array of
-        the type named by the list element.
-    :param allow_dict:
-        Allow a dict.  Its members can be struct type members or union
-        branches.  When the value of ``allow_dict`` is in pragma
-        ``member-name-exceptions``, the dict's keys may violate the
-        member naming rules.  The dict members are normalized in place.
-
Quoted 8 lines

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 337

Quoted 5 lines
scripts/qapi/expr.py +2 -3
-    :raise QAPISemError: When ``value`` fails validation.
-    :return: None, ``value`` is normalized in-place as needed.
-    """
+def check_type_name(value: Optional[object],
+                    info: QAPISourceInfo, source: str) -> None:

check_type_name() replaces callers that relied on the default for allow_array and allow_dict

Yes.

Quoted 4 lines

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 338

Quoted 1 line
scripts/qapi/expr.py +1 -0
+    if value is None:

Loses out on the documentation. Not sure how much that matters to you?

You mean the doc string?

I could copy and specialize it along with the code, but the new function is so simple... not sure it's worth explaining.

Quoted 8 lines
Quoted 8 lines
scripts/qapi/expr.py +8 -0
+        return
+
+    if isinstance(value, str):
+        return
+
+    if isinstance(value, list):
+        raise QAPISemError(info, "%s cannot be an array" % source)
+
Quoted 8 lines

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 351

Quoted 5 lines
scripts/qapi/expr.py +5 -0
+    raise QAPISemError(info, "%s should be a type name" % source)
+
+
+def check_type_name_or_array(value: Optional[object],
+                             info: QAPISourceInfo, source: str) -> None:

check_type_name_or_array() replaces all callers that passed allow_array=True.

Yes.

Quoted 3 lines

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 352

Quoted 1 line
scripts/qapi/expr.py +0 -0
     if value is None:

Another copy without documentation.

Same doubts.

Quoted 20 lines
Quoted 20 lines
scripts/qapi/expr.py +2 -5
         return
 
-    # Type name
     if isinstance(value, str):
         return
 
-    # Array type
     if isinstance(value, list):
-        if not allow_array:
-            raise QAPISemError(info, "%s cannot be an array" % source)
         if len(value) != 1 or not isinstance(value[0], str):
             raise QAPISemError(info,
                                "%s: array type must contain single type name" %
                                source)
         return
 
-    # Anonymous type
+    raise QAPISemError(info,
+                       "%s should be a type name" % source)
 
Quoted 9 lines

scripts/qapi/expr.py def normalize_members(members: object) -> None: · line 371

Quoted 6 lines
scripts/qapi/expr.py +4 -2
-    if not allow_dict:
-        raise QAPISemError(info, "%s should be a type name" % source)
+
+def check_type_name_or_implicit(value: Optional[object],
+                                info: QAPISourceInfo, source: str,
+                                parent_name: Optional[str]) -> None:

And check_type_name_or_implicit replaces all callers that passed allow_dict=str, where str is now the parent_name.

Yes.

Quoted 2 lines

(Wow, that was an
odd overload of the parameter name - I like the split version better).

It was less bad than what it replaced :)

Commit 638c4af9310 (qapi: Clean up member name case checking)

Quoted 19 lines

...

Quoted 4 lines
scripts/qapi/expr.py +0 -0
@@ -560,10 +572,13 @@ def check_command(expr: QAPIExpression) -> None:
     rets = expr.get('returns')
     boxed = expr.get('boxed', False)
 

scripts/qapi/expr.py def check_command(expr: QAPIExpression) -> None: · line 580

Quoted 10 lines
scripts/qapi/expr.py +6 -4
-    if boxed and args is None:
-        raise QAPISemError(expr.info, "'boxed': true requires 'data'")
-    check_type(args, expr.info, "'data'", allow_dict=not boxed)
-    check_type(rets, expr.info, "'returns'", allow_array=True)
+    if boxed:
+        if args is None:
+            raise QAPISemError(expr.info, "'boxed': true requires 'data'")
+        check_type_name(args, expr.info, "'data'")
+    else:
+        check_type_name_or_implicit(args, expr.info, "'data'", None)

And this use of allow_dict was the weirdest, where it really does fit better as calls into two separate functions.

Quoted 3 lines

With the fixed commit message, and with or without more function docs,

Thanks!

#10 lore raw

PATCH 5/14 qapi: Improve error message for unexpected array types

In reply to Markus Armbruster

We reject array types in certain places with "cannot be an array". Deleting this check improves the error message to "should be a type name" or "should be an object or type name", depending on context, so do that.

---
 scripts/qapi/expr.py                     | 6 ------
 tests/qapi-schema/bad-data.err           | 2 +-
 tests/qapi-schema/union-array-branch.err | 2 +-
 3 files changed, 2 insertions(+), 8 deletions(-)
scripts/qapi/expr.py +0 -6
index bc04bf34c2..5abeaa19dd 100644
@@ -341,9 +341,6 @@ def check_type_name(value: Optional[object],
     if isinstance(value, str):
         return
 
-    if isinstance(value, list):
-        raise QAPISemError(info, "%s cannot be an array" % source)
-
     raise QAPISemError(info, "%s should be a type name" % source)
 
 
@@ -392,9 +389,6 @@ def check_type_name_or_implicit(value: Optional[object],
     if isinstance(value, str):
         return
 
-    if isinstance(value, list):
-        raise QAPISemError(info, "%s cannot be an array" % source)
-
     if not isinstance(value, dict):
         raise QAPISemError(info,
                            "%s should be an object or type name" % source)
tests/qapi-schema/bad-data.err +1 -1
index 7991c8898d..a987df4108 100644
@@ -1,2 +1,2 @@
 bad-data.json: In command 'oops':
-bad-data.json:2: 'data' cannot be an array
+bad-data.json:2: 'data' should be an object or type name
tests/qapi-schema/union-array-branch.err +1 -1
index 5db9c17481..2aa146261a 100644
@@ -1,2 +1,2 @@
 union-array-branch.json: In union 'TestUnion':
-union-array-branch.json:8: 'data' member 'value1' cannot be an array
+union-array-branch.json:8: 'data' member 'value1' should be a type name
Signature · 1 line
2.39.2
Reviewed-by on v1 5/14
#11 lore raw

Re: [PATCH 05/14] qapi: Improve error message for unexpected array types

Quoted 11 lines · Markus Armbruster

We reject array types in certain places with "cannot be an array". Deleting this check improves the error message to "should be a type name" or "should be an object or type name", depending on context, so do that.

---
  scripts/qapi/expr.py                     | 6 ------
  tests/qapi-schema/bad-data.err           | 2 +-
  tests/qapi-schema/union-array-branch.err | 2 +-
  3 files changed, 2 insertions(+), 8 deletions(-)
#12 lore raw

PATCH 6/14 qapi: Simplify code a bit after previous commit

In reply to Markus Armbruster
---
 scripts/qapi/expr.py | 14 +++-----------
 1 file changed, 3 insertions(+), 11 deletions(-)
scripts/qapi/expr.py +3 -11
index 5abeaa19dd..8a8de9e3aa 100644
@@ -335,21 +335,13 @@ def normalize_members(members: object) -> None:
 
 def check_type_name(value: Optional[object],
                     info: QAPISourceInfo, source: str) -> None:
-    if value is None:
-        return
-
-    if isinstance(value, str):
-        return
-
-    raise QAPISemError(info, "%s should be a type name" % source)
+    if value is not None and not isinstance(value, str):
+        raise QAPISemError(info, "%s should be a type name" % source)
 
 
 def check_type_name_or_array(value: Optional[object],
                              info: QAPISourceInfo, source: str) -> None:
-    if value is None:
-        return
-
-    if isinstance(value, str):
+    if value is None or isinstance(value, str):
         return
 
     if isinstance(value, list):
Signature · 1 line
2.39.2
Reviewed-by on v1 6/14
#13 lore raw

Re: [PATCH 06/14] qapi: Simplify code a bit after previous commit

Quoted 1 line · Markus Armbruster

Looks like 'previous commit' in the subject line actually means 4/14 (two commits ago); a victim of rebasing, I'm sure.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#14 lore raw

Re: [PATCH 06/14] qapi: Simplify code a bit after previous commit

Quoted 5 lines · Eric Blake
Quoted 1 line · Markus Armbruster

Looks like 'previous commit' in the subject line actually means 4/14 (two commits ago); a victim of rebasing, I'm sure.

Hmm, actually both commits matter.

The first hunk simplifies check_type_name() by contracting its two conditionals. It is enabled by the previous commit, which removed the code between the two conditionals.

The second hunk simplifies check_type_name_or_array() the same way, but that one has had nothing in between since PATCH 04.

I'll change the title to "after previous commits".

Quoted 1 line

Thanks!

#15 lore raw

PATCH 7/14 qapi: Fix error message when type name or array is expected

In reply to Markus Armbruster

We incorrectly report "FOO should be a type name" when it could also be an array. Fix that.

---
 scripts/qapi/expr.py                        | 15 +++++++--------
 tests/qapi-schema/event-nest-struct.err     |  2 +-
 tests/qapi-schema/nested-struct-data.err    |  2 +-
 tests/qapi-schema/returns-dict.err          |  2 +-
 tests/qapi-schema/struct-member-invalid.err |  2 +-
 5 files changed, 11 insertions(+), 12 deletions(-)
scripts/qapi/expr.py +7 -8
index 8a8de9e3aa..9bae500a7d 100644
@@ -344,15 +344,14 @@ def check_type_name_or_array(value: Optional[object],
     if value is None or isinstance(value, str):
         return
 
-    if isinstance(value, list):
-        if len(value) != 1 or not isinstance(value[0], str):
-            raise QAPISemError(info,
-                               "%s: array type must contain single type name" %
-                               source)
-        return
+    if not isinstance(value, list):
+        raise QAPISemError(info,
+                           "%s should be a type name or array" % source)
 
-    raise QAPISemError(info,
-                       "%s should be a type name" % source)
+    if len(value) != 1 or not isinstance(value[0], str):
+        raise QAPISemError(info,
+                           "%s: array type must contain single type name" %
+                           source)
 
 
 def check_type_name_or_implicit(value: Optional[object],
tests/qapi-schema/event-nest-struct.err +1 -1
index 8c5f6ed311..15fc1406f8 100644
@@ -1,2 +1,2 @@
 event-nest-struct.json: In event 'EVENT_A':
-event-nest-struct.json:1: 'data' member 'a' should be a type name
+event-nest-struct.json:1: 'data' member 'a' should be a type name or array
tests/qapi-schema/nested-struct-data.err +1 -1
index c7258a0182..7dc5c7cb2d 100644
@@ -1,2 +1,2 @@
 nested-struct-data.json: In command 'foo':
-nested-struct-data.json:2: 'data' member 'a' should be a type name
+nested-struct-data.json:2: 'data' member 'a' should be a type name or array
tests/qapi-schema/returns-dict.err +1 -1
index 9b2d90c010..bf160e754b 100644
@@ -1,2 +1,2 @@
 returns-dict.json: In command 'oops':
-returns-dict.json:2: 'returns' should be a type name
+returns-dict.json:2: 'returns' should be a type name or array
tests/qapi-schema/struct-member-invalid.err +1 -1
index 7e01a41d7c..3130d69d9f 100644
@@ -1,2 +1,2 @@
 struct-member-invalid.json: In struct 'Foo':
-struct-member-invalid.json:1: 'data' member 'a' should be a type name
+struct-member-invalid.json:1: 'data' member 'a' should be a type name or array
Signature · 1 line
2.39.2
Reviewed-by on v1 7/14
#16 lore raw

Re: [PATCH 07/14] qapi: Fix error message when type name or array is expected

Quoted 12 lines · Markus Armbruster

We incorrectly report "FOO should be a type name" when it could also be an array. Fix that.

---
 scripts/qapi/expr.py                        | 15 +++++++--------
 tests/qapi-schema/event-nest-struct.err     |  2 +-
 tests/qapi-schema/nested-struct-data.err    |  2 +-
 tests/qapi-schema/returns-dict.err          |  2 +-
 tests/qapi-schema/struct-member-invalid.err |  2 +-
 5 files changed, 11 insertions(+), 12 deletions(-)

Doesn't change the set of schemas accepted, but does make it easier to understand when a schema is rejected.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#17 lore raw

PATCH 8/14 qapi: Fix to reject 'data': 'mumble' in struct

In reply to Markus Armbruster

A struct's 'data' must be a JSON object defining the struct's members. The QAPI code generator incorrectly accepts a JSON string instead, and then crashes in QAPISchema._make_members() called from ._def_struct_type().

Fix to reject it, and add a test case.

---
 scripts/qapi/expr.py                        | 24 +++++++++++++--------
 tests/qapi-schema/meson.build               |  1 +
 tests/qapi-schema/struct-data-typename.err  |  2 ++
 tests/qapi-schema/struct-data-typename.json |  2 ++
 tests/qapi-schema/struct-data-typename.out  |  0
 5 files changed, 20 insertions(+), 9 deletions(-)
 create mode 100644 tests/qapi-schema/struct-data-typename.err
 create mode 100644 tests/qapi-schema/struct-data-typename.json
 create mode 100644 tests/qapi-schema/struct-data-typename.out
scripts/qapi/expr.py +15 -9
index 9bae500a7d..cae0a08359 100644
@@ -354,14 +354,14 @@ def check_type_name_or_array(value: Optional[object],
                            source)
 
 
-def check_type_name_or_implicit(value: Optional[object],
-                                info: QAPISourceInfo, source: str,
-                                parent_name: Optional[str]) -> None:
+def check_type_implicit(value: Optional[object],
+                        info: QAPISourceInfo, source: str,
+                        parent_name: Optional[str]) -> None:
     """
     Normalize and validate an optional implicit struct type.
 
-    Accept ``None``, ``str``, or a ``dict`` defining an implicit
-    struct type.  The latter is normalized in place.
+    Accept ``None`` or a ``dict`` defining an implicit struct type.
+    The latter is normalized in place.
 
     :param value: The value to check.
     :param info: QAPI schema source file information.
@@ -377,9 +377,6 @@ def check_type_name_or_implicit(value: Optional[object],
     if value is None:
         return
 
-    if isinstance(value, str):
-        return
-
     if not isinstance(value, dict):
         raise QAPISemError(info,
                            "%s should be an object or type name" % source)
@@ -401,6 +398,15 @@ def check_type_name_or_implicit(value: Optional[object],
         check_type_name_or_array(arg['type'], info, key_source)
 
 
+def check_type_name_or_implicit(value: Optional[object],
+                                info: QAPISourceInfo, source: str,
+                                parent_name: Optional[str]) -> None:
+    if value is None or isinstance(value, str):
+        return
+
+    check_type_implicit(value, info, source, parent_name)
+
+
 def check_features(features: Optional[object],
                    info: QAPISourceInfo) -> None:
     """
@@ -486,7 +492,7 @@ def check_struct(expr: QAPIExpression) -> None:
     name = cast(str, expr['struct'])  # Checked in check_exprs
     members = expr['data']
 
-    check_type_name_or_implicit(members, expr.info, "'data'", name)
+    check_type_implicit(members, expr.info, "'data'", name)
     check_type_name(expr.get('base'), expr.info, "'base'")
 
 
tests/qapi-schema/meson.build +1 -0
index d85b14f28c..f88110bddf 100644
@@ -164,6 +164,7 @@ schemas = [
   'struct-base-clash-deep.json',
   'struct-base-clash.json',
   'struct-data-invalid.json',
+  'struct-data-typename.json',
   'struct-member-if-invalid.json',
   'struct-member-invalid-dict.json',
   'struct-member-invalid.json',
tests/qapi-schema/struct-data-typename.err new file +2 -0
new file mode 100644
index 0000000000..8fbfe99a42
@@ -0,0 +1,2 @@
+struct-data-typename.json: In struct 'Stru2':
+struct-data-typename.json:2: 'data' should be an object or type name
tests/qapi-schema/struct-data-typename.json new file +2 -0
new file mode 100644
index 0000000000..70fbad0ee4
@@ -0,0 +1,2 @@
+{ 'struct': 'Stru1', 'data': {} }
+{ 'struct': 'Stru2', 'data': 'Stru1' }
tests/qapi-schema/struct-data-typename.out new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
Signature · 1 line
2.39.2
Reviewed-by on v1 8/14
#18 lore raw

Re: [PATCH 08/14] qapi: Fix to reject 'data': 'mumble' in struct

Quoted 6 lines · Markus Armbruster

A struct's 'data' must be a JSON object defining the struct's members. The QAPI code generator incorrectly accepts a JSON string instead, and then crashes in QAPISchema._make_members() called from ._def_struct_type().

Fix to reject it, and add a test case.

Nice catch; I see why the split into three functions earlier on foreshadowed some subtle bug fixes to come.

scripts/qapi/expr.py def check_type_name_or_array(value: Optional[object], · line 359

Quoted 11 lines

+++ b/scripts/qapi/expr.py

scripts/qapi/expr.py +3 -3
@@ -354,14 +354,14 @@ def check_type_name_or_array(value: Optional[object],
                            source)
 
 
-def check_type_name_or_implicit(value: Optional[object],
-                                info: QAPISourceInfo, source: str,
-                                parent_name: Optional[str]) -> None:
+def check_type_implicit(value: Optional[object],
+                        info: QAPISourceInfo, source: str,
+                        parent_name: Optional[str]) -> None:

At first I thought this was a straight rename...

Quoted 21 lines
scripts/qapi/expr.py +2 -5
     """
     Normalize and validate an optional implicit struct type.
 
-    Accept ``None``, ``str``, or a ``dict`` defining an implicit
-    struct type.  The latter is normalized in place.
+    Accept ``None`` or a ``dict`` defining an implicit struct type.
+    The latter is normalized in place.
 
     :param value: The value to check.
     :param info: QAPI schema source file information.
@@ -377,9 +377,6 @@ def check_type_name_or_implicit(value: Optional[object],
     if value is None:
         return
 
-    if isinstance(value, str):
-        return
-
     if not isinstance(value, dict):
         raise QAPISemError(info,
                            "%s should be an object or type name" % source)

scripts/qapi/expr.py def check_type_name_or_implicit(value: Optional[object], · line 404

Quoted 7 lines
scripts/qapi/expr.py +4 -0
@@ -401,6 +398,15 @@ def check_type_name_or_implicit(value: Optional[object],
         check_type_name_or_array(arg['type'], info, key_source)
 
 
+def check_type_name_or_implicit(value: Optional[object],
+                                info: QAPISourceInfo, source: str,
+                                parent_name: Optional[str]) -> None:
+    if value is None or isinstance(value, str):

...until I got here and saw that you kept the original name, and added a new helper. Worth calling out the new function name check_type_implicit() in the commit message? It would have spared me a minute.

As earlier, you lost the doc comment. I'll leave it to your discretion if it is important to copy one back in.

Quoted 9 lines
scripts/qapi/expr.py +5 -0
+        return
+
+    check_type_implicit(value, info, source, parent_name)
+
+
 def check_features(features: Optional[object],
                    info: QAPISourceInfo) -> None:
     """

scripts/qapi/expr.py def check_struct(expr: QAPIExpression) -> None: · line 497

Quoted 7 lines
scripts/qapi/expr.py +1 -1
@@ -486,7 +492,7 @@ def check_struct(expr: QAPIExpression) -> None:
     name = cast(str, expr['struct'])  # Checked in check_exprs
     members = expr['data']
 
-    check_type_name_or_implicit(members, expr.info, "'data'", name)
+    check_type_implicit(members, expr.info, "'data'", name)
     check_type_name(expr.get('base'), expr.info, "'base'")
 
Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#19 lore raw

Re: [PATCH 08/14] qapi: Fix to reject 'data': 'mumble' in struct

Quoted 49 lines · Eric Blake
Quoted 6 lines · Markus Armbruster

A struct's 'data' must be a JSON object defining the struct's members. The QAPI code generator incorrectly accepts a JSON string instead, and then crashes in QAPISchema._make_members() called from ._def_struct_type().

Fix to reject it, and add a test case.

Nice catch; I see why the split into three functions earlier on foreshadowed some subtle bug fixes to come.

scripts/qapi/expr.py def check_type_name_or_array(value: Optional[object], · line 359

Quoted 11 lines

+++ b/scripts/qapi/expr.py

scripts/qapi/expr.py +3 -3
@@ -354,14 +354,14 @@ def check_type_name_or_array(value: Optional[object],
                            source)
 
 
-def check_type_name_or_implicit(value: Optional[object],
-                                info: QAPISourceInfo, source: str,
-                                parent_name: Optional[str]) -> None:
+def check_type_implicit(value: Optional[object],
+                        info: QAPISourceInfo, source: str,
+                        parent_name: Optional[str]) -> None:

At first I thought this was a straight rename...

Quoted 24 lines
scripts/qapi/expr.py +2 -5
     """
     Normalize and validate an optional implicit struct type.
 
-    Accept ``None``, ``str``, or a ``dict`` defining an implicit
-    struct type.  The latter is normalized in place.
+    Accept ``None`` or a ``dict`` defining an implicit struct type.
+    The latter is normalized in place.
 
     :param value: The value to check.
     :param info: QAPI schema source file information.
@@ -377,9 +377,6 @@ def check_type_name_or_implicit(value: Optional[object],
     if value is None:
         return
 
-    if isinstance(value, str):
-        return
-
     if not isinstance(value, dict):
         raise QAPISemError(info,
                            "%s should be an object or type name" % source)
@@ -401,6 +398,15 @@ def check_type_name_or_implicit(value: Optional[object],
         check_type_name_or_array(arg['type'], info, key_source)
 
 
Quoted 9 lines

scripts/qapi/expr.py def check_type_name_or_implicit(value: Optional[object], · line 404

Quoted 4 lines
scripts/qapi/expr.py +4 -0
+def check_type_name_or_implicit(value: Optional[object],
+                                info: QAPISourceInfo, source: str,
+                                parent_name: Optional[str]) -> None:
+    if value is None or isinstance(value, str):

...until I got here and saw that you kept the original name, and added a new helper. Worth calling out the new function name check_type_implicit() in the commit message? It would have spared me a minute.

Can do.

Quoted 2 lines

As earlier, you lost the doc comment. I'll leave it to your discretion if it is important to copy one back in.

I didn't duplicate the doc string, which means it moves from check_type_name_or_implicit() to check_type_implicit(), where the actual meat is.

John, you added the doc string in commit a48653638fa (qapi/expr.py: Add docstrings). Do you have an opinion?

Quoted 12 lines
Quoted 12 lines
scripts/qapi/expr.py +5 -0
+        return
+
+    check_type_implicit(value, info, source, parent_name)
+
+
 def check_features(features: Optional[object],
                    info: QAPISourceInfo) -> None:
     """
@@ -486,7 +492,7 @@ def check_struct(expr: QAPIExpression) -> None:
     name = cast(str, expr['struct'])  # Checked in check_exprs
     members = expr['data']
 
Quoted 6 lines

scripts/qapi/expr.py def check_struct(expr: QAPIExpression) -> None: · line 497

Quoted 4 lines
scripts/qapi/expr.py +1 -1
-    check_type_name_or_implicit(members, expr.info, "'data'", name)
+    check_type_implicit(members, expr.info, "'data'", name)
     check_type_name(expr.get('base'), expr.info, "'base'")
 

Thanks!

#20 lore raw

PATCH 9/14 tests/qapi-schema: Improve union discriminator coverage

In reply to Markus Armbruster

A union's 'discriminator' must name a one of the common members. QAPISchemaVariants.check() looks it up by its c_name(), then checks the name matches exactly (because c_name() is not injective).

Tests union-base-empty and union-invalid-discriminator both cover the case where lookup fails. Repurpose the latter to cover the case where it succeeds and the name check fails.

---
 tests/qapi-schema/union-invalid-discriminator.err  | 2 +-
 tests/qapi-schema/union-invalid-discriminator.json | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
tests/qapi-schema/union-invalid-discriminator.err +1 -1
index 38efb24b98..6bd774c156 100644
@@ -1,2 +1,2 @@
 union-invalid-discriminator.json: In union 'TestUnion':
-union-invalid-discriminator.json:10: discriminator 'enum_wrong' is not a member of 'base'
+union-invalid-discriminator.json:10: discriminator 'type_tag' is not a member of 'base'
tests/qapi-schema/union-invalid-discriminator.json +2 -2
index c4fce97362..f315f36e37 100644
@@ -8,7 +8,7 @@
   'data': { 'integer': 'int' } }
 
 { 'union': 'TestUnion',
-  'base': { 'enum1': 'TestEnum' },
-  'discriminator': 'enum_wrong',
+  'base': { 'type-tag': 'TestEnum' },
+  'discriminator': 'type_tag',
   'data': { 'value1': 'TestTypeA',
             'value2': 'TestTypeB' } }
Signature · 1 line
2.39.2
Reviewed-by on v1 9/14
#21 lore raw

Re: [PATCH 09/14] tests/qapi-schema: Improve union discriminator coverage

Quoted 1 line · Markus Armbruster

A union's 'discriminator' must name a one of the common members.

s/ a//

Quoted 7 lines

QAPISchemaVariants.check() looks it up by its c_name(), then checks the name matches exactly (because c_name() is not injective).

Tests union-base-empty and union-invalid-discriminator both cover the case where lookup fails. Repurpose the latter to cover the case where it succeeds and the name check fails.

Quoted 6 lines
---
 tests/qapi-schema/union-invalid-discriminator.err  | 2 +-
 tests/qapi-schema/union-invalid-discriminator.json | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

(- vs. _ is subtle, especially since I purposefully case-map them to one another whenever I can...)

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#22 lore raw

Re: [PATCH 09/14] tests/qapi-schema: Improve union discriminator coverage

Quoted 4 lines · Eric Blake
Quoted 1 line · Markus Armbruster

A union's 'discriminator' must name a one of the common members.

s/ a//

Yes.

Quoted 14 lines
Quoted 7 lines

QAPISchemaVariants.check() looks it up by its c_name(), then checks the name matches exactly (because c_name() is not injective).

Tests union-base-empty and union-invalid-discriminator both cover the case where lookup fails. Repurpose the latter to cover the case where it succeeds and the name check fails.

Quoted 6 lines
---
 tests/qapi-schema/union-invalid-discriminator.err  | 2 +-
 tests/qapi-schema/union-invalid-discriminator.json | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
Quoted 4 lines

(- vs. _ is subtle, especially since I purposefully case-map them to one another whenever I can...)

Abusing the clash checking machinery to look up the the tag member is kind of hacky, and it's why we have this odd case to cover.

Thanks!

#23 lore raw

PATCH 10/14 tests/qapi-schema: Rename a few conditionals

In reply to Markus Armbruster

Positive test case

    { 'enum': 'TestIfEnum',
      'data': [ 'foo', { 'name' : 'bar', 'if': 'TEST_IF_ENUM_BAR' } ],
      'if': 'TEST_IF_ENUM' }

generates

    #if defined(TEST_IF_ENUM)
    typedef enum TestIfEnum {
	TEST_IF_ENUM_FOO,
    #if defined(TEST_IF_ENUM_BAR)
	TEST_IF_ENUM_BAR,
    #endif /* defined(TEST_IF_ENUM_BAR) */
	TEST_IF_ENUM__MAX,
    } TestIfEnum;

Macro TEST_IF_ENUM_BAR clashes with the enumeration constant. Wouldn't compile with -DTEST_IF_BAR.

Rename the macro to TEST_IF_ENUM_MEMBER. For consistency, rename similar macros elsewhere as well.

---
 tests/qapi-schema/qapi-schema-test.json | 12 ++++++------
 tests/qapi-schema/qapi-schema-test.out  | 12 ++++++------
 2 files changed, 12 insertions(+), 12 deletions(-)
tests/qapi-schema/qapi-schema-test.json +6 -6
index ba7302f42b..5728d4de38 100644
@@ -220,18 +220,18 @@
 
 { 'struct': 'TestIfStruct',
   'data': { 'foo': 'int',
-            'bar': { 'type': 'int', 'if': 'TEST_IF_STRUCT_BAR'} },
+            'bar': { 'type': 'int', 'if': 'TEST_IF_STRUCT_MEMBER'} },
   'if': 'TEST_IF_STRUCT' }
 
 { 'enum': 'TestIfEnum',
-  'data': [ 'foo', { 'name' : 'bar', 'if': 'TEST_IF_ENUM_BAR' } ],
+  'data': [ 'foo', { 'name' : 'bar', 'if': 'TEST_IF_ENUM_MEMBER' } ],
   'if': 'TEST_IF_ENUM' }
 
 { 'union': 'TestIfUnion',
   'base': { 'type': 'TestIfEnum' },
   'discriminator': 'type',
   'data': { 'foo': 'TestStruct',
-            'bar': { 'type': 'UserDefZero', 'if': 'TEST_IF_ENUM_BAR'} },
+            'bar': { 'type': 'UserDefZero', 'if': 'TEST_IF_ENUM_MEMBER'} },
   'if': { 'all': ['TEST_IF_UNION', 'TEST_IF_STRUCT'] } }
 
 { 'command': 'test-if-union-cmd',
@@ -240,7 +240,7 @@
 
 { 'alternate': 'TestIfAlternate',
   'data': { 'foo': 'int',
-            'bar': { 'type': 'TestStruct', 'if': 'TEST_IF_ALT_BAR'} },
+            'bar': { 'type': 'TestStruct', 'if': 'TEST_IF_ALT_MEMBER'} },
   'if': { 'all': ['TEST_IF_ALT', 'TEST_IF_STRUCT'] } }
 
 { 'command': 'test-if-alternate-cmd',
@@ -250,7 +250,7 @@
 { 'command': 'test-if-cmd',
   'data': {
     'foo': 'TestIfStruct',
-    'bar': { 'type': 'TestIfEnum', 'if': 'TEST_IF_CMD_BAR' } },
+    'bar': { 'type': 'TestIfEnum', 'if': 'TEST_IF_CMD_ARG' } },
   'returns': 'UserDefThree',
   'if': { 'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT'] } }
 
@@ -258,7 +258,7 @@
 
 { 'event': 'TEST_IF_EVENT',
   'data': { 'foo': 'TestIfStruct',
-            'bar': { 'type': ['TestIfEnum'], 'if': 'TEST_IF_EVT_BAR' } },
+            'bar': { 'type': ['TestIfEnum'], 'if': 'TEST_IF_EVT_ARG' } },
   'if': { 'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT'] } }
 
 { 'event': 'TEST_IF_EVENT2', 'data': {},
tests/qapi-schema/qapi-schema-test.out +6 -6
index 043d75c655..cbd96f0b24 100644
@@ -246,12 +246,12 @@ command __org.qemu_x-command q_obj___org.qemu_x-command-arg -> None
 object TestIfStruct
     member foo: int optional=False
     member bar: int optional=False
-        if TEST_IF_STRUCT_BAR
+        if TEST_IF_STRUCT_MEMBER
     if TEST_IF_STRUCT
 enum TestIfEnum
     member foo
     member bar
-        if TEST_IF_ENUM_BAR
+        if TEST_IF_ENUM_MEMBER
     if TEST_IF_ENUM
 object q_obj_TestIfUnion-base
     member type: TestIfEnum optional=False
@@ -261,7 +261,7 @@ object TestIfUnion
     tag type
     case foo: TestStruct
     case bar: UserDefZero
-        if TEST_IF_ENUM_BAR
+        if TEST_IF_ENUM_MEMBER
     if {'all': ['TEST_IF_UNION', 'TEST_IF_STRUCT']}
 object q_obj_test-if-union-cmd-arg
     member union-cmd-arg: TestIfUnion optional=False
@@ -273,7 +273,7 @@ alternate TestIfAlternate
     tag type
     case foo: int
     case bar: TestStruct
-        if TEST_IF_ALT_BAR
+        if TEST_IF_ALT_MEMBER
     if {'all': ['TEST_IF_ALT', 'TEST_IF_STRUCT']}
 object q_obj_test-if-alternate-cmd-arg
     member alt-cmd-arg: TestIfAlternate optional=False
@@ -284,7 +284,7 @@ command test-if-alternate-cmd q_obj_test-if-alternate-cmd-arg -> None
 object q_obj_test-if-cmd-arg
     member foo: TestIfStruct optional=False
     member bar: TestIfEnum optional=False
-        if TEST_IF_CMD_BAR
+        if TEST_IF_CMD_ARG
     if {'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT']}
 command test-if-cmd q_obj_test-if-cmd-arg -> UserDefThree
     gen=True success_response=True boxed=False oob=False preconfig=False
@@ -296,7 +296,7 @@ array TestIfEnumList TestIfEnum
 object q_obj_TEST_IF_EVENT-arg
     member foo: TestIfStruct optional=False
     member bar: TestIfEnumList optional=False
-        if TEST_IF_EVT_BAR
+        if TEST_IF_EVT_ARG
     if {'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT']}
 event TEST_IF_EVENT q_obj_TEST_IF_EVENT-arg
     boxed=False
Signature · 1 line
2.39.2
Reviewed-by on v1 10/14
#24 lore raw

Re: [PATCH 10/14] tests/qapi-schema: Rename a few conditionals

Quoted 20 lines · Markus Armbruster

Positive test case

     { 'enum': 'TestIfEnum',
       'data': [ 'foo', { 'name' : 'bar', 'if': 'TEST_IF_ENUM_BAR' } ],
       'if': 'TEST_IF_ENUM' }

generates

     #if defined(TEST_IF_ENUM)
     typedef enum TestIfEnum {
	TEST_IF_ENUM_FOO,
     #if defined(TEST_IF_ENUM_BAR)
	TEST_IF_ENUM_BAR,
     #endif /* defined(TEST_IF_ENUM_BAR) */
	TEST_IF_ENUM__MAX,
     } TestIfEnum;

Macro TEST_IF_ENUM_BAR clashes with the enumeration constant. Wouldn't compile with -DTEST_IF_BAR.

Quoted 8 lines

Rename the macro to TEST_IF_ENUM_MEMBER. For consistency, rename similar macros elsewhere as well.

---
  tests/qapi-schema/qapi-schema-test.json | 12 ++++++------
  tests/qapi-schema/qapi-schema-test.out  | 12 ++++++------
  2 files changed, 12 insertions(+), 12 deletions(-)
#25 lore raw

PATCH 11/14 tests/qapi-schema: Clean up positive test for conditionals

In reply to Markus Armbruster

Union TestIfUnion is conditional on macros TEST_IF_UNION and TEST_IF_STRUCT. It uses TestIfEnum, which is conditional on macro TEST_IF_ENUM. If TEST_IF_ENUM and TEST_IF_STRUCT are defined, but TEST_IF_ENUM isn't, the generated code won't compile.

Command test-if-cmd is conditional an macros TEST_IF_CMD and TEST_IF_STRUCT, and uses TestIfEnum. Similar issue.

Event TEST_IF_EVENT is conditional an macros TEST_IF_EVT and TEST_IF_STRUCT, and uses TestIfEnum. Similar issue.

Replace the uses of TestIfEnum in the latter two by str.

TestIfUnion is now TestIfEnum's only user. Change TestIfEnum's condition to TEST_IF_UNION.

---
 tests/qapi-schema/qapi-schema-test.json | 6 +++---
 tests/qapi-schema/qapi-schema-test.out  | 8 +++-----
 2 files changed, 6 insertions(+), 8 deletions(-)
tests/qapi-schema/qapi-schema-test.json +3 -3
index 5728d4de38..8f0ee95d23 100644
@@ -225,7 +225,7 @@
 
 { 'enum': 'TestIfEnum',
   'data': [ 'foo', { 'name' : 'bar', 'if': 'TEST_IF_ENUM_MEMBER' } ],
-  'if': 'TEST_IF_ENUM' }
+  'if': 'TEST_IF_UNION' }
 
 { 'union': 'TestIfUnion',
   'base': { 'type': 'TestIfEnum' },
@@ -250,7 +250,7 @@
 { 'command': 'test-if-cmd',
   'data': {
     'foo': 'TestIfStruct',
-    'bar': { 'type': 'TestIfEnum', 'if': 'TEST_IF_CMD_ARG' } },
+    'bar': { 'type': 'str', 'if': 'TEST_IF_CMD_ARG' } },
   'returns': 'UserDefThree',
   'if': { 'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT'] } }
 
@@ -258,7 +258,7 @@
 
 { 'event': 'TEST_IF_EVENT',
   'data': { 'foo': 'TestIfStruct',
-            'bar': { 'type': ['TestIfEnum'], 'if': 'TEST_IF_EVT_ARG' } },
+            'bar': { 'type': ['str'], 'if': 'TEST_IF_EVT_ARG' } },
   'if': { 'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT'] } }
 
 { 'event': 'TEST_IF_EVENT2', 'data': {},
tests/qapi-schema/qapi-schema-test.out +3 -5
index cbd96f0b24..715f3a3f23 100644
@@ -252,7 +252,7 @@ enum TestIfEnum
     member foo
     member bar
         if TEST_IF_ENUM_MEMBER
-    if TEST_IF_ENUM
+    if TEST_IF_UNION
 object q_obj_TestIfUnion-base
     member type: TestIfEnum optional=False
     if {'all': ['TEST_IF_UNION', 'TEST_IF_STRUCT']}
@@ -283,7 +283,7 @@ command test-if-alternate-cmd q_obj_test-if-alternate-cmd-arg -> None
     if {'all': ['TEST_IF_ALT', 'TEST_IF_STRUCT']}
 object q_obj_test-if-cmd-arg
     member foo: TestIfStruct optional=False
-    member bar: TestIfEnum optional=False
+    member bar: str optional=False
         if TEST_IF_CMD_ARG
     if {'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT']}
 command test-if-cmd q_obj_test-if-cmd-arg -> UserDefThree
@@ -291,11 +291,9 @@ command test-if-cmd q_obj_test-if-cmd-arg -> UserDefThree
     if {'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT']}
 command test-cmd-return-def-three None -> UserDefThree
     gen=True success_response=True boxed=False oob=False preconfig=False
-array TestIfEnumList TestIfEnum
-    if TEST_IF_ENUM
 object q_obj_TEST_IF_EVENT-arg
     member foo: TestIfStruct optional=False
-    member bar: TestIfEnumList optional=False
+    member bar: strList optional=False
         if TEST_IF_EVT_ARG
     if {'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT']}
 event TEST_IF_EVENT q_obj_TEST_IF_EVENT-arg
Signature · 1 line
2.39.2
Reviewed-by on v1 11/14
#26 lore raw

Re: [PATCH 11/14] tests/qapi-schema: Clean up positive test for conditionals

Quoted 4 lines · Markus Armbruster

Union TestIfUnion is conditional on macros TEST_IF_UNION and TEST_IF_STRUCT. It uses TestIfEnum, which is conditional on macro TEST_IF_ENUM. If TEST_IF_ENUM and TEST_IF_STRUCT are defined, but TEST_IF_ENUM isn't, the generated code won't compile.

s/ENUM/UNION/ in one of these two uses in this sentence.

Quoted 11 lines

Command test-if-cmd is conditional an macros TEST_IF_CMD and TEST_IF_STRUCT, and uses TestIfEnum. Similar issue.

Event TEST_IF_EVENT is conditional an macros TEST_IF_EVT and TEST_IF_STRUCT, and uses TestIfEnum. Similar issue.

Replace the uses of TestIfEnum in the latter two by str.

TestIfUnion is now TestIfEnum's only user. Change TestIfEnum's condition to TEST_IF_UNION.

Fair enough, once the commit message doesn't confuse me in the first paragraph ;)

Quoted 7 lines
---
 tests/qapi-schema/qapi-schema-test.json | 6 +++---
 tests/qapi-schema/qapi-schema-test.out  | 8 +++-----
 2 files changed, 6 insertions(+), 8 deletions(-)
Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#27 lore raw

Re: [PATCH 11/14] tests/qapi-schema: Clean up positive test for conditionals

Quoted 7 lines · Eric Blake
Quoted 4 lines · Markus Armbruster

Union TestIfUnion is conditional on macros TEST_IF_UNION and TEST_IF_STRUCT. It uses TestIfEnum, which is conditional on macro TEST_IF_ENUM. If TEST_IF_ENUM and TEST_IF_STRUCT are defined, but TEST_IF_ENUM isn't, the generated code won't compile.

s/ENUM/UNION/ in one of these two uses in this sentence.

Yes: If TEST_IF_UNION and TEST_IF_UNION are defined, ...

Quoted 15 lines
Quoted 10 lines

Command test-if-cmd is conditional an macros TEST_IF_CMD and TEST_IF_STRUCT, and uses TestIfEnum. Similar issue.

Event TEST_IF_EVENT is conditional an macros TEST_IF_EVT and TEST_IF_STRUCT, and uses TestIfEnum. Similar issue.

Replace the uses of TestIfEnum in the latter two by str.

TestIfUnion is now TestIfEnum's only user. Change TestIfEnum's condition to TEST_IF_UNION.

Fair enough, once the commit message doesn't confuse me in the first paragraph ;)

Quoted 1 line
Quoted 8 lines
Quoted 6 lines
---
 tests/qapi-schema/qapi-schema-test.json | 6 +++---
 tests/qapi-schema/qapi-schema-test.out  | 8 +++-----
 2 files changed, 6 insertions(+), 8 deletions(-)

Thanks!

#28 lore raw

Re: [PATCH 11/14] tests/qapi-schema: Clean up positive test for conditionals

Quoted 11 lines · Markus Armbruster
Quoted 7 lines · Eric Blake
Quoted 4 lines · Markus Armbruster

Union TestIfUnion is conditional on macros TEST_IF_UNION and TEST_IF_STRUCT. It uses TestIfEnum, which is conditional on macro TEST_IF_ENUM. If TEST_IF_ENUM and TEST_IF_STRUCT are defined, but TEST_IF_ENUM isn't, the generated code won't compile.

s/ENUM/UNION/ in one of these two uses in this sentence.

Yes: If TEST_IF_UNION and TEST_IF_UNION are defined, ...

If TEST_IF_UNION and TEST_IF_STRUCT are defined, ...

(you are stuck in a maze of twisty little passages, all alike)

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#29 lore raw

Re: [PATCH 11/14] tests/qapi-schema: Clean up positive test for conditionals

Quoted 9 lines · Eric Blake
Quoted 8 lines · Markus Armbruster
Quoted 6 lines · Eric Blake
Quoted 4 lines · Markus Armbruster

Union TestIfUnion is conditional on macros TEST_IF_UNION and TEST_IF_STRUCT. It uses TestIfEnum, which is conditional on macro TEST_IF_ENUM. If TEST_IF_ENUM and TEST_IF_STRUCT are defined, but TEST_IF_ENUM isn't, the generated code won't compile.

Quoted 7 lines
Quoted 3 lines
Quoted 1 line

s/ENUM/UNION/ in one of these two uses in this sentence.

Yes: If TEST_IF_UNION and TEST_IF_UNION are defined, ...

If TEST_IF_UNION and TEST_IF_STRUCT are defined, ...

(you are stuck in a maze of twisty little passages, all alike)

I am!

Thanks :)

#30 lore raw

PATCH 12/14 tests/qapi-schema: Cover optional conditional struct member

In reply to Markus Armbruster
---
 tests/qapi-schema/qapi-schema-test.json | 3 ++-
 tests/qapi-schema/qapi-schema-test.out  | 2 ++
 2 files changed, 4 insertions(+), 1 deletion(-)
tests/qapi-schema/qapi-schema-test.json +2 -1
index 8f0ee95d23..f1f742d38c 100644
@@ -220,7 +220,8 @@
 
 { 'struct': 'TestIfStruct',
   'data': { 'foo': 'int',
-            'bar': { 'type': 'int', 'if': 'TEST_IF_STRUCT_MEMBER'} },
+            'bar': { 'type': 'int', 'if': 'TEST_IF_STRUCT_MEMBER'},
+            '*baz': { 'type': 'str', 'if': 'TEST_IF_STRUCT_MEMBER'} },
   'if': 'TEST_IF_STRUCT' }
 
 { 'enum': 'TestIfEnum',
tests/qapi-schema/qapi-schema-test.out +2 -0
index 715f3a3f23..cee92c0d2e 100644
@@ -247,6 +247,8 @@ object TestIfStruct
     member foo: int optional=False
     member bar: int optional=False
         if TEST_IF_STRUCT_MEMBER
+    member baz: str optional=True
+        if TEST_IF_STRUCT_MEMBER
     if TEST_IF_STRUCT
 enum TestIfEnum
     member foo
Signature · 1 line
2.39.2
#32 lore raw

PATCH 13/14 qapi: Fix code generated for optional conditional struct member

In reply to Markus Armbruster

The generated member visit neglects to emit #if around a conditional struct member's has_ variable. For instance, tests/qapi-schema/qapi-schema-test.json generates

    #if defined(TEST_IF_STRUCT)
    bool visit_type_TestIfStruct_members(Visitor *v, TestIfStruct *obj, Error **errp)
    {

---> bool has_baz = !!obj->baz;

	if (!visit_type_int(v, "foo", &obj->foo, errp)) {
	    return false;
	}
    #if defined(TEST_IF_STRUCT_MEMBER)
	if (!visit_type_int(v, "bar", &obj->bar, errp)) {
	    return false;
	}
    #endif /* defined(TEST_IF_STRUCT_MEMBER) */
    #if defined(TEST_IF_STRUCT_MEMBER)
	if (visit_optional(v, "baz", &has_baz)) {
	    if (!visit_type_str(v, "baz", &obj->baz, errp)) {
		return false;
	    }
	}
    #endif /* defined(TEST_IF_STRUCT_MEMBER) */
	return true;
    }
    [...]
    #endif /* defined(TEST_IF_STRUCT) */

Won't compile when TEST_IF_STRUCT is defined and TEST_IF_STRUCT_MEMBER isn't.

Fix that the obvious way:

    #if defined(TEST_IF_STRUCT_MEMBER)
	bool has_baz = !!obj->baz;
    #endif /* defined(TEST_IF_STRUCT_MEMBER) */
Fixes 44ea9d9be33c (qapi: Start to elide redundant has_FOO in generated C)
---
 scripts/qapi/visit.py | 2 ++
 1 file changed, 2 insertions(+)
scripts/qapi/visit.py +2 -0
index 26a584ee4c..c56ea4d724 100644
@@ -74,11 +74,13 @@ def gen_visit_object_members(name: str,
     sep = ''
     for memb in members:
         if memb.optional and not memb.need_has():
+            ret += memb.ifcond.gen_if()
             ret += mcgen('''
     bool has_%(c_name)s = !!obj->%(c_name)s;
 ''',
                          c_name=c_name(memb.name))
             sep = '\n'
+            ret += memb.ifcond.gen_endif()
     ret += sep
 
     if base:
Signature · 1 line
2.39.2
Reviewed-by on v1 13/14
#33 lore raw

Re: [PATCH 13/14] qapi: Fix code generated for optional conditional struct member

Quoted 9 lines · Markus Armbruster

The generated member visit neglects to emit #if around a conditional struct member's has_ variable. For instance, tests/qapi-schema/qapi-schema-test.json generates

    #if defined(TEST_IF_STRUCT)
    bool visit_type_TestIfStruct_members(Visitor *v, TestIfStruct *obj, Error **errp)
    {

---> bool has_baz = !!obj->baz;

...

Quoted 10 lines

Won't compile when TEST_IF_STRUCT is defined and TEST_IF_STRUCT_MEMBER isn't.

Fix that the obvious way:

    #if defined(TEST_IF_STRUCT_MEMBER)
	bool has_baz = !!obj->baz;
    #endif /* defined(TEST_IF_STRUCT_MEMBER) */
Quoted 6 lines
Fixes 44ea9d9be33c (qapi: Start to elide redundant has_FOO in generated C)
---
 scripts/qapi/visit.py | 2 ++
 1 file changed, 2 insertions(+)
Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#34 lore raw

PATCH 14/14 qapi: Require boxed for conditional command and event arguments

In reply to Markus Armbruster

The C code generator fails to honor 'if' conditions of command and event arguments.

For instance, tests/qapi-schema/qapi-schema-test.json has

    { 'event': 'TEST_IF_EVENT',
      'data': { 'foo': 'TestIfStruct',
		'bar': { 'type': ['str'], 'if': 'TEST_IF_EVT_ARG' } },
      'if': { 'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT'] } }

Generated tests/test-qapi-events.h fails to honor the TEST_IF_EVT_ARG condition:

    #if defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)
    void qapi_event_send_test_if_event(TestIfStruct *foo, strList *bar);
    #endif /* defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT) */

Only uses so far are in tests/.

We could fix the generator to emit something like

    #if defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)
    void qapi_event_send_test_if_event(TestIfStruct *foo
    #if defined(TEST_IF_EVT_ARG)
                    , strList *bar
    #endif
                    );
    #endif /* defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT) */

Ugly. Calls become similarly ugly. Not worth fixing.

Conditional arguments work fine with 'boxed': true, simply because complex types with conditional members work fine. Not worth breaking.

Reject conditional arguments unless boxed.

Move the tests cases covering unboxed conditional arguments out of tests/qapi-schema/qapi-schema-test.json. Cover boxed conditional arguments there instead.

---
 docs/devel/qapi-code-gen.rst                 |  5 ++---
 scripts/qapi/commands.py                     |  1 +
 scripts/qapi/gen.py                          |  1 +
 scripts/qapi/schema.py                       | 14 ++++++++++++++
 tests/qapi-schema/args-if-implicit.err       |  2 ++
 tests/qapi-schema/args-if-implicit.json      |  4 ++++
 tests/qapi-schema/args-if-implicit.out       |  0
 tests/qapi-schema/args-if-unboxed.err        |  2 ++
 tests/qapi-schema/args-if-unboxed.json       |  6 ++++++
 tests/qapi-schema/args-if-unboxed.out        |  0
 tests/qapi-schema/event-args-if-unboxed.err  |  2 ++
 tests/qapi-schema/event-args-if-unboxed.json |  4 ++++
 tests/qapi-schema/event-args-if-unboxed.out  |  0
 tests/qapi-schema/meson.build                |  2 ++
 tests/qapi-schema/qapi-schema-test.json      |  9 ++++-----
 tests/qapi-schema/qapi-schema-test.out       | 18 ++++--------------
 16 files changed, 48 insertions(+), 22 deletions(-)
 create mode 100644 tests/qapi-schema/args-if-implicit.err
 create mode 100644 tests/qapi-schema/args-if-implicit.json
 create mode 100644 tests/qapi-schema/args-if-implicit.out
 create mode 100644 tests/qapi-schema/args-if-unboxed.err
 create mode 100644 tests/qapi-schema/args-if-unboxed.json
 create mode 100644 tests/qapi-schema/args-if-unboxed.out
 create mode 100644 tests/qapi-schema/event-args-if-unboxed.err
 create mode 100644 tests/qapi-schema/event-args-if-unboxed.json
 create mode 100644 tests/qapi-schema/event-args-if-unboxed.out
docs/devel/qapi-code-gen.rst +2 -3
index 23e7f2fb1c..879a649e8c 100644
@@ -805,9 +805,8 @@ gets its generated code guarded like this::
  ... generated code ...
  #endif /* defined(HAVE_BAR) && defined(CONFIG_FOO) */
 
-Individual members of complex types, commands arguments, and
-event-specific data can also be made conditional.  This requires the
-longhand form of MEMBER.
+Individual members of complex types can also be made conditional.
+This requires the longhand form of MEMBER.
 
 Example: a struct type with unconditional member 'foo' and conditional
 member 'bar' ::
scripts/qapi/commands.py +1 -0
index 79c5e5c3a9..bda6896076 100644
@@ -64,6 +64,7 @@ def gen_call(name: str,
     elif arg_type:
         assert not arg_type.variants
         for memb in arg_type.members:
+            assert not memb.ifcond.is_present()
             if memb.need_has():
                 argstr += 'arg.has_%s, ' % c_name(memb.name)
             argstr += 'arg.%s, ' % c_name(memb.name)
scripts/qapi/gen.py +1 -0
index b5a8d03e8e..8f8f784f4a 100644
@@ -119,6 +119,7 @@ def build_params(arg_type: Optional[QAPISchemaObjectType],
     elif arg_type:
         assert not arg_type.variants
         for memb in arg_type.members:
+            assert not memb.ifcond.is_present()
             ret += sep
             sep = ', '
             if memb.need_has():
scripts/qapi/schema.py +14 -0
index 719152fe49..8f31f8832f 100644
@@ -486,6 +486,10 @@ def is_empty(self):
         assert self.members is not None
         return not self.members and not self.variants
 
+    def has_conditional_members(self):
+        assert self.members is not None
+        return any(m.ifcond.is_present() for m in self.members)
+
     def c_name(self):
         assert self.name != 'q_empty'
         return super().c_name()
@@ -817,6 +821,11 @@ def check(self, schema):
                     self.info,
                     "command's 'data' can take %s only with 'boxed': true"
                     % self.arg_type.describe())
+            self.arg_type.check(schema)
+            if self.arg_type.has_conditional_members() and not self.boxed:
+                raise QAPISemError(
+                    self.info,
+                    "conditional command arguments require 'boxed': true")
         if self._ret_type_name:
             self.ret_type = schema.resolve_type(
                 self._ret_type_name, self.info, "command's 'returns'")
@@ -872,6 +881,11 @@ def check(self, schema):
                     self.info,
                     "event's 'data' can take %s only with 'boxed': true"
                     % self.arg_type.describe())
+            self.arg_type.check(schema)
+            if self.arg_type.has_conditional_members() and not self.boxed:
+                raise QAPISemError(
+                    self.info,
+                    "conditional event arguments require 'boxed': true")
 
     def connect_doc(self, doc=None):
         super().connect_doc(doc)
tests/qapi-schema/args-if-implicit.err new file +2 -0
new file mode 100644
index 0000000000..da2447d397
@@ -0,0 +1,2 @@
+args-if-implicit.json: In command 'test-if-cmd':
+args-if-implicit.json:1: conditional command arguments require 'boxed': true
tests/qapi-schema/args-if-implicit.json new file +4 -0
new file mode 100644
index 0000000000..1eda39cb1e
@@ -0,0 +1,4 @@
+{ 'command': 'test-if-cmd',
+  'data': {
+    'foo': 'int',
+    'bar': { 'type': 'str', 'if': 'TEST_IF_CMD_ARG' } } }
tests/qapi-schema/args-if-implicit.out new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
tests/qapi-schema/args-if-unboxed.err new file +2 -0
new file mode 100644
index 0000000000..3d2fc836ef
@@ -0,0 +1,2 @@
+args-if-unboxed.json: In command 'test-if-cmd':
+args-if-unboxed.json:5: conditional command arguments require 'boxed': true
tests/qapi-schema/args-if-unboxed.json new file +6 -0
new file mode 100644
index 0000000000..6e04c13e72
@@ -0,0 +1,6 @@
+{ 'struct': 'TestIfCmdArgs',
+  'data': {
+    'foo': 'int',
+    'bar': { 'type': 'str', 'if': 'TEST_IF_CMD_ARG' } } }
+{ 'command': 'test-if-cmd',
+  'data': 'TestIfCmdArgs' }
tests/qapi-schema/args-if-unboxed.out new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
tests/qapi-schema/event-args-if-unboxed.err new file +2 -0
new file mode 100644
index 0000000000..41ac64c6f3
@@ -0,0 +1,2 @@
+tests/qapi-schema/event-args-if-unboxed.json: In event 'TEST_IF_EVENT':
+tests/qapi-schema/event-args-if-unboxed.json:1: event's 'data' members may have 'if' conditions only with 'boxed': true
tests/qapi-schema/event-args-if-unboxed.json new file +4 -0
new file mode 100644
index 0000000000..ca42a74e3a
@@ -0,0 +1,4 @@
+ { 'event': 'TEST_IF_EVENT',
+  'data': {
+    'foo': 'int',
+    'bar': { 'type': 'str', 'if': 'TEST_IF_CMD_ARG' } } }
tests/qapi-schema/event-args-if-unboxed.out new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
tests/qapi-schema/meson.build +2 -0
index f88110bddf..a06515ca17 100644
@@ -27,6 +27,8 @@ schemas = [
   'args-bad-boxed.json',
   'args-boxed-anon.json',
   'args-boxed-string.json',
+  'args-if-implicit.json',
+  'args-if-unboxed.json',
   'args-int.json',
   'args-invalid.json',
   'args-member-array-bad.json',
tests/qapi-schema/qapi-schema-test.json +4 -5
index f1f742d38c..8bbf94834a 100644
@@ -249,17 +249,16 @@
   'if': { 'all': ['TEST_IF_ALT', 'TEST_IF_STRUCT'] } }
 
 { 'command': 'test-if-cmd',
-  'data': {
-    'foo': 'TestIfStruct',
-    'bar': { 'type': 'str', 'if': 'TEST_IF_CMD_ARG' } },
+  'boxed': true,
+  'data': 'TestIfStruct',
   'returns': 'UserDefThree',
   'if': { 'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT'] } }
 
 { 'command': 'test-cmd-return-def-three', 'returns': 'UserDefThree' }
 
 { 'event': 'TEST_IF_EVENT',
-  'data': { 'foo': 'TestIfStruct',
-            'bar': { 'type': ['str'], 'if': 'TEST_IF_EVT_ARG' } },
+  'boxed': true,
+  'data': 'TestIfStruct',
   'if': { 'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT'] } }
 
 { 'event': 'TEST_IF_EVENT2', 'data': {},
tests/qapi-schema/qapi-schema-test.out +4 -14
index cee92c0d2e..cc34b422e6 100644
@@ -283,23 +283,13 @@ object q_obj_test-if-alternate-cmd-arg
 command test-if-alternate-cmd q_obj_test-if-alternate-cmd-arg -> None
     gen=True success_response=True boxed=False oob=False preconfig=False
     if {'all': ['TEST_IF_ALT', 'TEST_IF_STRUCT']}
-object q_obj_test-if-cmd-arg
-    member foo: TestIfStruct optional=False
-    member bar: str optional=False
-        if TEST_IF_CMD_ARG
-    if {'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT']}
-command test-if-cmd q_obj_test-if-cmd-arg -> UserDefThree
-    gen=True success_response=True boxed=False oob=False preconfig=False
+command test-if-cmd TestIfStruct -> UserDefThree
+    gen=True success_response=True boxed=True oob=False preconfig=False
     if {'all': ['TEST_IF_CMD', 'TEST_IF_STRUCT']}
 command test-cmd-return-def-three None -> UserDefThree
     gen=True success_response=True boxed=False oob=False preconfig=False
-object q_obj_TEST_IF_EVENT-arg
-    member foo: TestIfStruct optional=False
-    member bar: strList optional=False
-        if TEST_IF_EVT_ARG
-    if {'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT']}
-event TEST_IF_EVENT q_obj_TEST_IF_EVENT-arg
-    boxed=False
+event TEST_IF_EVENT TestIfStruct
+    boxed=True
     if {'all': ['TEST_IF_EVT', 'TEST_IF_STRUCT']}
 event TEST_IF_EVENT2 None
     boxed=False
Signature · 1 line
2.39.2
Reviewed-by on v1 14/14
#35 lore raw

Re: [PATCH 14/14] qapi: Require boxed for conditional command and event arguments

Quoted 3 lines · Markus Armbruster

The C code generator fails to honor 'if' conditions of command and event arguments.

...

Quoted 5 lines

Conditional arguments work fine with 'boxed': true, simply because complex types with conditional members work fine. Not worth breaking.

Reject conditional arguments unless boxed.

Yay - matches my earlier suggestion at how to avoid #if in the middle of a parameter list.

Quoted 7 lines

Move the tests cases covering unboxed conditional arguments out of tests/qapi-schema/qapi-schema-test.json. Cover boxed conditional arguments there instead.

---

A big end to the series, but I'm glad we got here.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org