Skip to contentSkip to conversation

qapi: untie 'if' conditions from C preprocessor

PATCH Superseded [email protected] 3 participants 16 messages Oct 15, 2020 – Nov 5, 2020

v1 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

cover qapi: untie 'if' conditions from C preprocessor

From: Marc-André Lureau <[email protected]>

Hi,

This series makes the 'if' conditions less liberal, by formalizing a simple expression tree based on bare boolean logic of configure option identifiers.

(this will allow to express conditions in Rust in my QAPI-Rust PoC series, but it is worth a standalone post)

This is based on John Snow QAPI cleanup branch:
https://gitlab.com/jsnow/qemu/-/tree/python-qapi-cleanup-pt6

thanks

Marc-André Lureau (9):
qapi: replace List[str] by IfCond
qapi: move gen_if/gen_endif to IfCond
qapi: start building an 'if' predicate tree
qapi: introduce IfPredicateList and IfAny
qapi: add IfNot
qapi: normalize 'if' condition to IfPredicate
qapi: convert 'if' C expressions to literal form
qapi: make 'if' condition strings simple identifiers
docs: update the documentation about schema configuration

 docs/devel/qapi-code-gen.txt                  |  32 ++---
 docs/sphinx/qapidoc.py                        |   6 +-
 qapi/block-core.json                          |  16 +--
 qapi/char.json                                |   8 +-
 qapi/machine-target.json                      |  28 +++--
 qapi/migration.json                           |  10 +-
 qapi/misc-target.json                         |  35 ++++--
 qapi/ui.json                                  |  48 ++++----
 scripts/qapi/commands.py                      |   4 +-
 scripts/qapi/common.py                        | 113 +++++++++++++++---
 scripts/qapi/events.py                        |   4 +-
 scripts/qapi/expr.py                          |  55 +++++----
 scripts/qapi/gen.py                           |  15 ++-
 scripts/qapi/introspect.py                    |  27 ++---
 scripts/qapi/schema.py                        |  91 +++++++-------
 scripts/qapi/types.py                         |  33 +++--
 scripts/qapi/visit.py                         |  23 ++--
 .../alternate-branch-if-invalid.err           |   2 +-
 tests/qapi-schema/bad-if-empty.err            |   2 +-
 tests/qapi-schema/bad-if-list.err             |   2 +-
 tests/qapi-schema/bad-if.err                  |   3 +-
 tests/qapi-schema/bad-if.json                 |   2 +-
 tests/qapi-schema/doc-good.json               |   6 +-
 tests/qapi-schema/doc-good.out                |  12 +-
 tests/qapi-schema/enum-if-invalid.err         |   3 +-
 tests/qapi-schema/features-if-invalid.err     |   2 +-
 tests/qapi-schema/features-missing-name.json  |   2 +-
 tests/qapi-schema/qapi-schema-test.json       |  55 +++++----
 tests/qapi-schema/qapi-schema-test.out        |  63 +++++-----
 .../qapi-schema/struct-member-if-invalid.err  |   2 +-
 tests/qapi-schema/union-branch-if-invalid.err |   2 +-
 tests/test-qmp-cmds.c                         |   1 +
 32 files changed, 423 insertions(+), 284 deletions(-)
Signature · 1 line
2.28.0
#1 lore raw

PATCH 1/9 qapi: replace List[str] by IfCond

From: Marc-André Lureau <[email protected]>

Wrap the 'if' condition in a higher-level object. Not only this is allows more type safety but also further refactoring without too much chrun. The following patches will extend the syntax of 'if' and will have some extra handling and types.

---
 docs/sphinx/qapidoc.py     |  2 +-
 scripts/qapi/commands.py   |  4 +-
 scripts/qapi/common.py     | 26 ++++++++---
 scripts/qapi/events.py     |  4 +-
 scripts/qapi/gen.py        |  9 ++--
 scripts/qapi/introspect.py | 21 ++++-----
 scripts/qapi/schema.py     | 91 ++++++++++++++++++++------------------
 scripts/qapi/types.py      | 11 ++---
 scripts/qapi/visit.py      |  9 ++--
 9 files changed, 102 insertions(+), 75 deletions(-)
docs/sphinx/qapidoc.py +1 -1
index 11e97839de..db9520f37f 100644
@@ -116,7 +116,7 @@ class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
         the conditions are in literal-text and the commas are not.
         If with_if is False, we don't return the "(If: " and ")".
         """
-        condlist = intersperse([nodes.literal('', c) for c in ifcond],
+        condlist = intersperse([nodes.literal('', c) for c in ifcond.ifcond],
                                nodes.Text(', '))
         if not with_if:
             return condlist
scripts/qapi/commands.py +2 -2
index 50978090b4..03deac5fdd 100644
@@ -20,7 +20,7 @@ from typing import (
     Set,
 )
 
-from .common import c_name, mcgen
+from .common import IfCond, c_name, mcgen
 from .gen import (
     QAPIGenC,
     QAPIGenCCode,
@@ -301,7 +301,7 @@ void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds);
     def visit_command(self,
                       name: str,
                       info: QAPISourceInfo,
-                      ifcond: List[str],
+                      ifcond: IfCond,
                       features: List[QAPISchemaFeature],
                       arg_type: Optional[QAPISchemaObjectType],
                       ret_type: Optional[QAPISchemaType],
scripts/qapi/common.py +21 -5
index 11b86beeab..59e6a400da 100644
@@ -12,7 +12,7 @@
 # See the COPYING file in the top-level directory.
 
 import re
-from typing import Optional, Sequence
+from typing import Optional, Sequence, Union
 
 
 #: Magic string that gets removed along with all space to its right.
@@ -194,18 +194,34 @@ def guardend(name: str) -> str:
                  name=c_fname(name).upper())
 
 
-def gen_if(ifcond: Sequence[str]) -> str:
+class IfCond:
+    def __init__(self, ifcond: Optional[Sequence[str]] = None):
+        self.ifcond = ifcond or []
+
+    def __bool__(self) -> bool:
+        return bool(self.ifcond)
+
+    def __repr__(self) -> str:
+        return repr(self.ifcond)
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, IfCond):
+            return NotImplemented
+        return self.ifcond == other.ifcond
+
+
+def gen_if(c: IfCond) -> str:
     ret = ''
-    for ifc in ifcond:
+    for ifc in c.ifcond:
         ret += mcgen('''
 #if %(cond)s
 ''', cond=ifc)
     return ret
 
 
-def gen_endif(ifcond: Sequence[str]) -> str:
+def gen_endif(c: IfCond) -> str:
     ret = ''
-    for ifc in reversed(ifcond):
+    for ifc in reversed(c.ifcond):
         ret += mcgen('''
 #endif /* %(cond)s */
 ''', cond=ifc)
scripts/qapi/events.py +2 -2
index 599f3d1f56..e95a95feca 100644
@@ -14,7 +14,7 @@ See the COPYING file in the top-level directory.
 
 from typing import List
 
-from .common import c_enum_const, c_name, mcgen
+from .common import IfCond, c_enum_const, c_name, mcgen
 from .gen import QAPISchemaModularCVisitor, build_params, ifcontext
 from .schema import (
     QAPISchema,
@@ -212,7 +212,7 @@ void %(event_emit)s(%(event_enum)s event, QDict *qdict);
     def visit_event(self,
                     name: str,
                     info: QAPISourceInfo,
-                    ifcond: List[str],
+                    ifcond: IfCond,
                     features: List[QAPISchemaFeature],
                     arg_type: QAPISchemaObjectType,
                     boxed: bool) -> None:
scripts/qapi/gen.py +5 -4
index b40f18eee3..b35ccb201f 100644
@@ -23,6 +23,7 @@ from typing import (
 )
 
 from .common import (
+    IfCond,
     c_fname,
     c_name,
     gen_endif,
@@ -81,7 +82,7 @@ class QAPIGen:
                 fp.write(text)
 
 
-def _wrap_ifcond(ifcond: List[str], before: str, after: str) -> str:
+def _wrap_ifcond(ifcond: IfCond, before: str, after: str) -> str:
     if before == after:
         return after   # suppress empty #if ... #endif
 
@@ -123,9 +124,9 @@ def build_params(arg_type: Optional[QAPISchemaObjectType],
 class QAPIGenCCode(QAPIGen):
     def __init__(self, fname: Optional[str]):
         super().__init__(fname)
-        self._start_if: Optional[Tuple[List[str], str, str]] = None
+        self._start_if: Optional[Tuple[IfCond, str, str]] = None
 
-    def start_if(self, ifcond: List[str]) -> None:
+    def start_if(self, ifcond: IfCond) -> None:
         assert self._start_if is None
         self._start_if = (ifcond, self._body, self._preamble)
 
@@ -186,7 +187,7 @@ class QAPIGenH(QAPIGenC):
 
 
 @contextmanager
-def ifcontext(ifcond: List[str], *args: QAPIGenCCode) -> Iterator[None]:
+def ifcontext(ifcond: IfCond, *args: QAPIGenCCode) -> Iterator[None]:
     """
     A with-statement context manager that wraps with `start_if()` / `end_if()`.
 
scripts/qapi/introspect.py +11 -10
index 1817f1d34e..103b8515eb 100644
@@ -21,6 +21,7 @@ from typing import (
 )
 
 from .common import (
+    IfCond,
     c_name,
     gen_endif,
     gen_if,
@@ -58,11 +59,11 @@ class Node(Generic[_NodeType]):
     """
     # Remove after 3.7 adds @dataclass:
     # pylint: disable=too-few-public-methods
-    def __init__(self, data: _NodeType, ifcond: Iterable[str],
+    def __init__(self, data: _NodeType, ifcond: IfCond,
                  comment: Optional[str] = None):
         self.data = data
         self.comment: Optional[str] = comment
-        self.ifcond: Sequence[str] = tuple(ifcond)
+        self.ifcond = ifcond
 
 
 def _tree_to_qlit(obj: TreeNode, level: int = 0,
@@ -197,7 +198,7 @@ const QLitObject %(c_name)s = %(c_string)s;
         return [Node(f.name, f.ifcond) for f in features]
 
     def _gen_tree(self, name: str, mtype: str, obj: _DObject,
-                  ifcond: List[str],
+                  ifcond: IfCond,
                   features: Optional[List[QAPISchemaFeature]]) -> None:
         comment: Optional[str] = None
         if mtype not in ('command', 'event', 'builtin', 'array'):
@@ -238,10 +239,10 @@ const QLitObject %(c_name)s = %(c_string)s;
 
     def visit_builtin_type(self, name: str, info: Optional[QAPISourceInfo],
                            json_type: str) -> None:
-        self._gen_tree(name, 'builtin', {'json-type': json_type}, [], None)
+        self._gen_tree(name, 'builtin', {'json-type': json_type}, IfCond(), None)
 
     def visit_enum_type(self, name: str, info: QAPISourceInfo,
-                        ifcond: List[str], features: List[QAPISchemaFeature],
+                        ifcond: IfCond, features: List[QAPISchemaFeature],
                         members: List[QAPISchemaEnumMember],
                         prefix: Optional[str]) -> None:
         self._gen_tree(name, 'enum',
@@ -249,14 +250,14 @@ const QLitObject %(c_name)s = %(c_string)s;
                        ifcond, features)
 
     def visit_array_type(self, name: str, info: Optional[QAPISourceInfo],
-                         ifcond: List[str],
+                         ifcond: IfCond,
                          element_type: QAPISchemaType) -> None:
         element = self._use_type(element_type)
         self._gen_tree('[' + element + ']', 'array', {'element-type': element},
                        ifcond, None)
 
     def visit_object_type_flat(self, name: str, info: Optional[QAPISourceInfo],
-                               ifcond: List[str],
+                               ifcond: IfCond,
                                features: List[QAPISchemaFeature],
                                members: Sequence[QAPISchemaObjectTypeMember],
                                variants: Optional[QAPISchemaVariants]) -> None:
@@ -268,7 +269,7 @@ const QLitObject %(c_name)s = %(c_string)s;
         self._gen_tree(name, 'object', obj, ifcond, features)
 
     def visit_alternate_type(self, name: str, info: QAPISourceInfo,
-                             ifcond: List[str],
+                             ifcond: IfCond,
                              features: List[QAPISchemaFeature],
                              variants: QAPISchemaVariants) -> None:
         self._gen_tree(name, 'alternate',
@@ -278,7 +279,7 @@ const QLitObject %(c_name)s = %(c_string)s;
                        ]},
                        ifcond, features)
 
-    def visit_command(self, name: str, info: QAPISourceInfo, ifcond: List[str],
+    def visit_command(self, name: str, info: QAPISourceInfo, ifcond: IfCond,
                       features: List[QAPISchemaFeature],
                       arg_type: QAPISchemaObjectType,
                       ret_type: Optional[QAPISchemaType], gen: bool,
@@ -295,7 +296,7 @@ const QLitObject %(c_name)s = %(c_string)s;
         self._gen_tree(name, 'command', obj, ifcond, features)
 
     def visit_event(self, name: str, info: QAPISourceInfo,
-                    ifcond: List[str], features: List[QAPISchemaFeature],
+                    ifcond: IfCond, features: List[QAPISchemaFeature],
                     arg_type: QAPISchemaObjectType, boxed: bool) -> None:
         arg_type = arg_type or self._schema.the_empty_object_type
         self._gen_tree(name, 'event', {'arg-type': self._use_type(arg_type)},
scripts/qapi/schema.py +49 -42

332 lines not on this page · raw message

scripts/qapi/types.py +6 -5
index 2b4916cdaa..c15613d13b 100644
@@ -16,6 +16,7 @@ This work is licensed under the terms of the GNU GPL, version 2.
 from typing import List, Optional
 
 from .common import (
+    IfCond,
     c_enum_const,
     c_name,
     gen_endif,
@@ -139,7 +140,7 @@ def gen_struct_members(members: List[QAPISchemaObjectTypeMember]) -> str:
     return ret
 
 
-def gen_object(name: str, ifcond: List[str],
+def gen_object(name: str, ifcond: IfCond,
                base: Optional[QAPISchemaObjectType],
                members: List[QAPISchemaObjectTypeMember],
                variants: Optional[QAPISchemaVariants]) -> str:
@@ -307,7 +308,7 @@ class QAPISchemaGenTypeVisitor(QAPISchemaModularCVisitor):
     def visit_enum_type(self,
                         name: str,
                         info: Optional[QAPISourceInfo],
-                        ifcond: List[str],
+                        ifcond: IfCond,
                         features: List[QAPISchemaFeature],
                         members: List[QAPISchemaEnumMember],
                         prefix: Optional[str]) -> None:
@@ -318,7 +319,7 @@ class QAPISchemaGenTypeVisitor(QAPISchemaModularCVisitor):
     def visit_array_type(self,
                          name: str,
                          info: Optional[QAPISourceInfo],
-                         ifcond: List[str],
+                         ifcond: IfCond,
                          element_type: QAPISchemaType) -> None:
         with ifcontext(ifcond, self._genh, self._genc):
             self._genh.preamble_add(gen_fwd_object_or_array(name))
@@ -328,7 +329,7 @@ class QAPISchemaGenTypeVisitor(QAPISchemaModularCVisitor):
     def visit_object_type(self,
                           name: str,
                           info: Optional[QAPISourceInfo],
-                          ifcond: List[str],
+                          ifcond: IfCond,
                           features: List[QAPISchemaFeature],
                           base: Optional[QAPISchemaObjectType],
                           members: List[QAPISchemaObjectTypeMember],
@@ -351,7 +352,7 @@ class QAPISchemaGenTypeVisitor(QAPISchemaModularCVisitor):
     def visit_alternate_type(self,
                              name: str,
                              info: QAPISourceInfo,
-                             ifcond: List[str],
+                             ifcond: IfCond,
                              features: List[QAPISchemaFeature],
                              variants: QAPISchemaVariants) -> None:
         with ifcontext(ifcond, self._genh):
scripts/qapi/visit.py +5 -4
index 339f152152..d10840bf7b 100644
@@ -16,6 +16,7 @@ See the COPYING file in the top-level directory.
 from typing import List, Optional
 
 from .common import (
+    IfCond,
     c_enum_const,
     c_name,
     gen_endif,
@@ -337,7 +338,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaModularCVisitor):
     def visit_enum_type(self,
                         name: str,
                         info: QAPISourceInfo,
-                        ifcond: List[str],
+                        ifcond: IfCond,
                         features: List[QAPISchemaFeature],
                         members: List[QAPISchemaEnumMember],
                         prefix: Optional[str]) -> None:
@@ -348,7 +349,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaModularCVisitor):
     def visit_array_type(self,
                          name: str,
                          info: Optional[QAPISourceInfo],
-                         ifcond: List[str],
+                         ifcond: IfCond,
                          element_type: QAPISchemaType) -> None:
         with ifcontext(ifcond, self._genh, self._genc):
             self._genh.add(gen_visit_decl(name))
@@ -357,7 +358,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaModularCVisitor):
     def visit_object_type(self,
                           name: str,
                           info: Optional[QAPISourceInfo],
-                          ifcond: List[str],
+                          ifcond: IfCond,
                           features: List[QAPISchemaFeature],
                           base: Optional[QAPISchemaObjectType],
                           members: List[QAPISchemaObjectTypeMember],
@@ -379,7 +380,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaModularCVisitor):
     def visit_alternate_type(self,
                              name: str,
                              info: QAPISourceInfo,
-                             ifcond: List[str],
+                             ifcond: IfCond,
                              features: List[QAPISchemaFeature],
                              variants: QAPISchemaVariants) -> None:
         with ifcontext(ifcond, self._genh, self._genc):
Signature · 1 line
2.28.0
#2 lore raw

Re: [PATCH 1/9] qapi: replace List[str] by IfCond

Quoted 7 lines · On 10/15/20 12:52 PM, [email protected] wrote:

From: Marc-André Lureau <[email protected]>

Wrap the 'if' condition in a higher-level object. Not only this is allows more type safety but also further refactoring without too much chrun. The following patches will extend the syntax of 'if' and will have some extra handling and types.

Probably a good idea. Thanks for basing it on Pt6; I'll try to push ahead as fast as I can -- though there are some more aggressive cleanups in error, expr, and parser that we haven't discussed on list yet much and are quite prone to change.

Let me know if you have any comments or feedbacks regarding what you found there!

Pts 2 (introspect.py) and 3 (expr.py) are recently re-sent to list, if you have specific critique in those areas.

Quoted 71 lines
---
  docs/sphinx/qapidoc.py     |  2 +-
  scripts/qapi/commands.py   |  4 +-
  scripts/qapi/common.py     | 26 ++++++++---
  scripts/qapi/events.py     |  4 +-
  scripts/qapi/gen.py        |  9 ++--
  scripts/qapi/introspect.py | 21 ++++-----
  scripts/qapi/schema.py     | 91 ++++++++++++++++++++------------------
  scripts/qapi/types.py      | 11 ++---
  scripts/qapi/visit.py      |  9 ++--
  9 files changed, 102 insertions(+), 75 deletions(-)
docs/sphinx/qapidoc.py +1 -1
index 11e97839de..db9520f37f 100644
@@ -116,7 +116,7 @@ class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
          the conditions are in literal-text and the commas are not.
          If with_if is False, we don't return the "(If: " and ")".
          """
-        condlist = intersperse([nodes.literal('', c) for c in ifcond],
+        condlist = intersperse([nodes.literal('', c) for c in ifcond.ifcond],
                                 nodes.Text(', '))
          if not with_if:
              return condlist
scripts/qapi/commands.py +2 -2
index 50978090b4..03deac5fdd 100644
@@ -20,7 +20,7 @@ from typing import (
      Set,
  )
 
-from .common import c_name, mcgen
+from .common import IfCond, c_name, mcgen
  from .gen import (
      QAPIGenC,
      QAPIGenCCode,
@@ -301,7 +301,7 @@ void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds);
      def visit_command(self,
                        name: str,
                        info: QAPISourceInfo,
-                      ifcond: List[str],
+                      ifcond: IfCond,
                        features: List[QAPISchemaFeature],
                        arg_type: Optional[QAPISchemaObjectType],
                        ret_type: Optional[QAPISchemaType],
scripts/qapi/common.py +6 -2
index 11b86beeab..59e6a400da 100644
@@ -12,7 +12,7 @@
  # See the COPYING file in the top-level directory.
 
  import re
-from typing import Optional, Sequence
+from typing import Optional, Sequence, Union
 
 
  #: Magic string that gets removed along with all space to its right.
@@ -194,18 +194,34 @@ def guardend(name: str) -> str:
                   name=c_fname(name).upper())
 
 
-def gen_if(ifcond: Sequence[str]) -> str:
+class IfCond:
+    def __init__(self, ifcond: Optional[Sequence[str]] = None):
+        self.ifcond = ifcond or []
+
+    def __bool__(self) -> bool:

scripts/qapi/common.py def guardend(name: str) -> str: · line 211

Quoted 10 lines
scripts/qapi/common.py +10 -0
+        return bool(self.ifcond)
+
+    def __repr__(self) -> str:
+        return repr(self.ifcond)
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, IfCond):
+            return NotImplemented
+        return self.ifcond == other.ifcond
+

Haven't looked ahead yet, forgive me if this is a bad idea:

worth adding an __iter__ method here so that callers don't have to call "for x in ifcond.ifcond" ?

Maybe you refactor such that this is becomes pointless.

Also; should we create an Ifcond object in schema.py instead in common, as it's a generic representation of the #if conditionals, less tied to the C generation?

[...]

#3 lore raw

Re: [PATCH 1/9] qapi: replace List[str] by IfCond

Hi

Quoted 9 lines · John Snow
Quoted 7 lines · On 10/15/20 12:52 PM, [email protected] wrote:

From: Marc-André Lureau <[email protected]>

Wrap the 'if' condition in a higher-level object. Not only this is allows more type safety but also further refactoring without too much chrun. The following patches will extend the syntax of 'if' and will have some extra handling and types.

Quoted 8 lines

Probably a good idea. Thanks for basing it on Pt6; I'll try to push ahead as fast as I can -- though there are some more aggressive cleanups in error, expr, and parser that we haven't discussed on list yet much and are quite prone to change.

Let me know if you have any comments or feedbacks regarding what you found there!

Overall, I was pretty happy with the result. Although it seemed a bit awkward to have types everywhere in Python (it doesn't feel as consistent as with other languages, I think I need to get used to it)

Quoted 3 lines

Pts 2 (introspect.py) and 3 (expr.py) are recently re-sent to list, if you have specific critique in those areas.

Done, not much comments

Quoted 86 lines
Quoted 18 lines
---
  docs/sphinx/qapidoc.py     |  2 +-
  scripts/qapi/commands.py   |  4 +-
  scripts/qapi/common.py     | 26 ++++++++---
  scripts/qapi/events.py     |  4 +-
  scripts/qapi/gen.py        |  9 ++--
  scripts/qapi/introspect.py | 21 ++++-----
  scripts/qapi/schema.py     | 91 ++++++++++++++++++++------------------
  scripts/qapi/types.py      | 11 ++---
  scripts/qapi/visit.py      |  9 ++--
  9 files changed, 102 insertions(+), 75 deletions(-)
docs/sphinx/qapidoc.py +0 -0
index 11e97839de..db9520f37f 100644

docs/sphinx/qapidoc.py class QAPISchemaGenRSTVisitor(QAPISchemaVisitor): · line 119

Quoted 5 lines
docs/sphinx/qapidoc.py +1 -1
@@ -116,7 +116,7 @@ class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
          the conditions are in literal-text and the commas are not.
          If with_if is False, we don't return the "(If: " and ")".
          """
-        condlist = intersperse([nodes.literal('', c) for c in ifcond],
+        condlist = intersperse([nodes.literal('', c) for c in

ifcond.ifcond],

scripts/qapi/commands.py void %(c_prefix)sqmp_init_marshal(QmpCommandList

Quoted 17 lines
docs/sphinx/qapidoc.py +0 -0
                                 nodes.Text(', '))
          if not with_if:
              return condlist
scripts/qapi/commands.py +1 -1
index 50978090b4..03deac5fdd 100644
@@ -20,7 +20,7 @@ from typing import (
      Set,
  )
 
-from .common import c_name, mcgen
+from .common import IfCond, c_name, mcgen
  from .gen import (
      QAPIGenC,
      QAPIGenCCode,
@@ -301,7 +301,7 @@ void %(c_prefix)sqmp_init_marshal(QmpCommandList

*cmds);

Quoted 31 lines
scripts/qapi/commands.py +1 -1
      def visit_command(self,
                        name: str,
                        info: QAPISourceInfo,
-                      ifcond: List[str],
+                      ifcond: IfCond,
                        features: List[QAPISchemaFeature],
                        arg_type: Optional[QAPISchemaObjectType],
                        ret_type: Optional[QAPISchemaType],
scripts/qapi/common.py +6 -2
index 11b86beeab..59e6a400da 100644
@@ -12,7 +12,7 @@
  # See the COPYING file in the top-level directory.
 
  import re
-from typing import Optional, Sequence
+from typing import Optional, Sequence, Union
 
 
  #: Magic string that gets removed along with all space to its right.
@@ -194,18 +194,34 @@ def guardend(name: str) -> str:
                   name=c_fname(name).upper())
 
 
-def gen_if(ifcond: Sequence[str]) -> str:
+class IfCond:
+    def __init__(self, ifcond: Optional[Sequence[str]] = None):
+        self.ifcond = ifcond or []
+
+    def __bool__(self) -> bool:

scripts/qapi/common.py def guardend(name: str) -> str: · line 211

Quoted 10 lines
scripts/qapi/common.py +10 -0
+        return bool(self.ifcond)
+
+    def __repr__(self) -> str:
+        return repr(self.ifcond)
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, IfCond):
+            return NotImplemented
+        return self.ifcond == other.ifcond
+

Haven't looked ahead yet, forgive me if this is a bad idea:

Quoted 5 lines

worth adding an __iter__ method here so that callers don't have to call "for x in ifcond.ifcond" ?

Maybe you refactor such that this is becomes pointless.

Yes, the new expression tree and generation code is quite different now. Not really worth it as an intermediary refactoring step.

Quoted 5 lines

Also; should we create an Ifcond object in schema.py instead in common, as it's a generic representation of the #if conditionals, less tied to the C generation?

Good point, I'll update.

thanks

Signature · 1 line
Marc-André Lureau
#4 lore raw

PATCH 2/9 qapi: move gen_if/gen_endif to IfCond

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

Move the generating function to the IfCond class. (avoid cluttering and potential missuse of global functions, allow access to private members etc)

---
 scripts/qapi/common.py     | 22 ++++++++++------------
 scripts/qapi/gen.py        |  6 ++----
 scripts/qapi/introspect.py |  6 ++----
 scripts/qapi/types.py      | 22 ++++++++++------------
 scripts/qapi/visit.py      | 14 ++++++--------
 5 files changed, 30 insertions(+), 40 deletions(-)
scripts/qapi/common.py +10 -12
index 59e6a400da..58ddec3bc5 100644
@@ -209,20 +209,18 @@ class IfCond:
             return NotImplemented
         return self.ifcond == other.ifcond
 
-
-def gen_if(c: IfCond) -> str:
-    ret = ''
-    for ifc in c.ifcond:
-        ret += mcgen('''
+    def gen_if(self) -> str:
+        ret = ''
+        for ifc in self.ifcond:
+            ret += mcgen('''
 #if %(cond)s
 ''', cond=ifc)
-    return ret
-
+        return ret
 
-def gen_endif(c: IfCond) -> str:
-    ret = ''
-    for ifc in reversed(c.ifcond):
-        ret += mcgen('''
+    def gen_endif(self) -> str:
+        ret = ''
+        for ifc in reversed(self.ifcond):
+            ret += mcgen('''
 #endif /* %(cond)s */
 ''', cond=ifc)
-    return ret
+        return ret
scripts/qapi/gen.py +2 -4
index b35ccb201f..5a8c66e628 100644
@@ -26,8 +26,6 @@ from .common import (
     IfCond,
     c_fname,
     c_name,
-    gen_endif,
-    gen_if,
     guardend,
     guardstart,
     mcgen,
@@ -92,9 +90,9 @@ def _wrap_ifcond(ifcond: IfCond, before: str, after: str) -> str:
     if added[0] == '\n':
         out += '\n'
         added = added[1:]
-    out += gen_if(ifcond)
+    out += ifcond.gen_if()
     out += added
-    out += gen_endif(ifcond)
+    out += ifcond.gen_endif()
     return out
 
 
scripts/qapi/introspect.py +2 -4
index 103b8515eb..d97dea8e4e 100644
@@ -23,8 +23,6 @@ from typing import (
 from .common import (
     IfCond,
     c_name,
-    gen_endif,
-    gen_if,
     mcgen,
 )
 from .gen import QAPISchemaMonolithicCVisitor
@@ -77,10 +75,10 @@ def _tree_to_qlit(obj: TreeNode, level: int = 0,
         if obj.comment:
             ret += indent(level) + '/* %s */\n' % obj.comment
         if obj.ifcond:
-            ret += gen_if(obj.ifcond)
+            ret += obj.ifcond.gen_if()
         ret += _tree_to_qlit(obj.data, level)
         if obj.ifcond:
-            ret += '\n' + gen_endif(obj.ifcond)
+            ret += '\n' + obj.ifcond.gen_endif()
         return ret
 
     ret = ''
scripts/qapi/types.py +10 -12
index c15613d13b..66ba2f62e4 100644
@@ -19,8 +19,6 @@ from .common import (
     IfCond,
     c_enum_const,
     c_name,
-    gen_endif,
-    gen_if,
     mcgen,
 )
 from .gen import QAPISchemaModularCVisitor, ifcontext
@@ -51,13 +49,13 @@ const QEnumLookup %(c_name)s_lookup = {
 ''',
                 c_name=c_name(name))
     for memb in members:
-        ret += gen_if(memb.ifcond)
+        ret += memb.ifcond.gen_if()
         index = c_enum_const(name, memb.name, prefix)
         ret += mcgen('''
         [%(index)s] = "%(name)s",
 ''',
                      index=index, name=memb.name)
-        ret += gen_endif(memb.ifcond)
+        ret += memb.ifcond.gen_endif()
 
     ret += mcgen('''
     },
@@ -81,12 +79,12 @@ typedef enum %(c_name)s {
                 c_name=c_name(name))
 
     for memb in enum_members:
-        ret += gen_if(memb.ifcond)
+        ret += memb.ifcond.gen_if()
         ret += mcgen('''
     %(c_enum)s,
 ''',
                      c_enum=c_enum_const(name, memb.name, prefix))
-        ret += gen_endif(memb.ifcond)
+        ret += memb.ifcond.gen_endif()
 
     ret += mcgen('''
 } %(c_name)s;
@@ -126,7 +124,7 @@ struct %(c_name)s {
 def gen_struct_members(members: List[QAPISchemaObjectTypeMember]) -> str:
     ret = ''
     for memb in members:
-        ret += gen_if(memb.ifcond)
+        ret += memb.ifcond.gen_if()
         if memb.optional:
             ret += mcgen('''
     bool has_%(c_name)s;
@@ -136,7 +134,7 @@ def gen_struct_members(members: List[QAPISchemaObjectTypeMember]) -> str:
     %(c_type)s %(c_name)s;
 ''',
                      c_type=memb.type.c_type(), c_name=c_name(memb.name))
-        ret += gen_endif(memb.ifcond)
+        ret += memb.ifcond.gen_endif()
     return ret
 
 
@@ -159,7 +157,7 @@ def gen_object(name: str, ifcond: IfCond,
     ret += mcgen('''
 
 ''')
-    ret += gen_if(ifcond)
+    ret += ifcond.gen_if()
     ret += mcgen('''
 struct %(c_name)s {
 ''',
@@ -193,7 +191,7 @@ struct %(c_name)s {
     ret += mcgen('''
 };
 ''')
-    ret += gen_endif(ifcond)
+    ret += ifcond.gen_endif()
 
     return ret
 
@@ -220,13 +218,13 @@ def gen_variants(variants: QAPISchemaVariants) -> str:
     for var in variants.variants:
         if var.type.name == 'q_empty':
             continue
-        ret += gen_if(var.ifcond)
+        ret += var.ifcond.gen_if()
         ret += mcgen('''
         %(c_type)s %(c_name)s;
 ''',
                      c_type=var.type.c_unboxed_type(),
                      c_name=c_name(var.name))
-        ret += gen_endif(var.ifcond)
+        ret += var.ifcond.gen_endif()
 
     ret += mcgen('''
     } u;
scripts/qapi/visit.py +6 -8
index d10840bf7b..b199e75946 100644
@@ -19,8 +19,6 @@ from .common import (
     IfCond,
     c_enum_const,
     c_name,
-    gen_endif,
-    gen_if,
     indent,
     mcgen,
 )
@@ -78,7 +76,7 @@ bool visit_type_%(c_name)s_members(Visitor *v, %(c_name)s *obj, Error **errp)
                      c_type=base.c_name())
 
     for memb in members:
-        ret += gen_if(memb.ifcond)
+        ret += memb.ifcond.gen_if()
         if memb.optional:
             ret += mcgen('''
     if (visit_optional(v, "%(name)s", &obj->has_%(c_name)s)) {
@@ -97,7 +95,7 @@ bool visit_type_%(c_name)s_members(Visitor *v, %(c_name)s *obj, Error **errp)
             ret += mcgen('''
     }
 ''')
-        ret += gen_endif(memb.ifcond)
+        ret += memb.ifcond.gen_endif()
 
     if variants:
         tag_member = variants.tag_member
@@ -111,7 +109,7 @@ bool visit_type_%(c_name)s_members(Visitor *v, %(c_name)s *obj, Error **errp)
         for var in variants.variants:
             case_str = c_enum_const(tag_member.type.name, var.name,
                                     tag_member.type.prefix)
-            ret += gen_if(var.ifcond)
+            ret += var.ifcond.gen_if()
             if var.type.name == 'q_empty':
                 # valid variant and nothing to do
                 ret += mcgen('''
@@ -127,7 +125,7 @@ bool visit_type_%(c_name)s_members(Visitor *v, %(c_name)s *obj, Error **errp)
                              case=case_str,
                              c_type=var.type.c_name(), c_name=c_name(var.name))
 
-            ret += gen_endif(var.ifcond)
+            ret += var.ifcond.gen_endif()
         ret += mcgen('''
     default:
         abort();
@@ -213,7 +211,7 @@ bool visit_type_%(c_name)s(Visitor *v, const char *name,
                 c_name=c_name(name))
 
     for var in variants.variants:
-        ret += gen_if(var.ifcond)
+        ret += var.ifcond.gen_if()
         ret += mcgen('''
     case %(case)s:
 ''',
@@ -239,7 +237,7 @@ bool visit_type_%(c_name)s(Visitor *v, const char *name,
         ret += mcgen('''
         break;
 ''')
-        ret += gen_endif(var.ifcond)
+        ret += var.ifcond.gen_endif()
 
     ret += mcgen('''
     case QTYPE_NONE:
Signature · 1 line
2.28.0
#5 lore raw

Re: [PATCH 2/9] qapi: move gen_if/gen_endif to IfCond

Quoted 6 lines · On 10/15/20 12:52 PM, [email protected] wrote:

From: Marc-André Lureau <[email protected]>

Move the generating function to the IfCond class. (avoid cluttering and potential missuse of global functions, allow access to private members etc)

Quoted 9 lines
---
  scripts/qapi/common.py     | 22 ++++++++++------------
  scripts/qapi/gen.py        |  6 ++----
  scripts/qapi/introspect.py |  6 ++----
  scripts/qapi/types.py      | 22 ++++++++++------------
  scripts/qapi/visit.py      | 14 ++++++--------
  5 files changed, 30 insertions(+), 40 deletions(-)

Seems straightforward enough, though I guess your 'Ifcond' object becomes something more of a code generator class than a pure abstract representation by absorbing C generation functions, yeah?

#6 lore raw

Re: [PATCH 2/9] qapi: move gen_if/gen_endif to IfCond

Hi

Quoted 17 lines · John Snow
Quoted 6 lines · On 10/15/20 12:52 PM, [email protected] wrote:

From: Marc-André Lureau <[email protected]>

Move the generating function to the IfCond class. (avoid cluttering and potential missuse of global functions, allow access to private members etc)

Quoted 9 lines
---
  scripts/qapi/common.py     | 22 ++++++++++------------
  scripts/qapi/gen.py        |  6 ++----
  scripts/qapi/introspect.py |  6 ++----
  scripts/qapi/types.py      | 22 ++++++++++------------
  scripts/qapi/visit.py      | 14 ++++++--------
  5 files changed, 30 insertions(+), 40 deletions(-)
Quoted 4 lines

Seems straightforward enough, though I guess your 'Ifcond' object becomes something more of a code generator class than a pure abstract representation by absorbing C generation functions, yeah?

Right, in its current form (
https://github.com/elmarco/qemu/blob/qapi-rs/scripts/qapi/common.py#L283),
it has "def gen_if(self) -> str" & "def gen_endif(self) -> str" (for C), as well as "def gen_rs_cfg(self) -> str" (for Rust).

I didn't bother doing a visitor or other fancy design, as it's easy to iterate later if needed, imho.

Signature · 1 line
Marc-André Lureau
#7 lore raw

PATCH 3/9 qapi: start building an 'if' predicate tree

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

The following patches are going to express conditions in some target language agostic way. For that, let's start building a predicate tree of configuration options.

The tree will be less expressive than full C macros expressions, and will be based only on identifier. For this reason, it will use have
operations: 'all', 'any' and 'not'. ('and'/'or' have a connotation of expression operands)

For now, the documentation will use the C condition expression (as that's already what is exposed with defined(FOO), &&, || etc). Eventually, we may want to generate a more human friendly syntax later.

---
 docs/sphinx/qapidoc.py                 |  6 +--
 scripts/qapi/common.py                 | 69 ++++++++++++++++++++------
 tests/qapi-schema/doc-good.out         | 12 ++---
 tests/qapi-schema/qapi-schema-test.out | 58 +++++++++++-----------
 4 files changed, 91 insertions(+), 54 deletions(-)
docs/sphinx/qapidoc.py +2 -4
index db9520f37f..31b47e4745 100644
@@ -112,12 +112,10 @@ class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
     def _nodes_for_ifcond(self, ifcond, with_if=True):
         """Return list of Text, literal nodes for the ifcond
 
-        Return a list which gives text like ' (If: cond1, cond2, cond3)', where
-        the conditions are in literal-text and the commas are not.
+        Return a list which gives text like ' (If: C-condition)'.
         If with_if is False, we don't return the "(If: " and ")".
         """
-        condlist = intersperse([nodes.literal('', c) for c in ifcond.ifcond],
-                               nodes.Text(', '))
+        condlist = [nodes.literal('', ifcond.gen_if())]
         if not with_if:
             return condlist
 
scripts/qapi/common.py +54 -15

87 lines not on this page · raw message

tests/qapi-schema/doc-good.out +6 -6
index 419284dae2..0d27323c47 100644
@@ -12,15 +12,15 @@ enum QType
 module doc-good.json
 enum Enum
     member one
-        if ['defined(IFONE)']
+        if IfAll(['defined(IFONE)'])
     member two
-    if ['defined(IFCOND)']
+    if IfAll(['defined(IFCOND)'])
     feature enum-feat
 object Base
     member base1: Enum optional=False
 object Variant1
     member var1: str optional=False
-        if ['defined(IFSTR)']
+        if IfAll(['defined(IFSTR)'])
         feature member-feat
     feature variant1-feat
 object Variant2
@@ -29,7 +29,7 @@ object Object
     tag base1
     case one: Variant1
     case two: Variant2
-        if ['IFTWO']
+        if IfAll(['IFTWO'])
     feature union-feat1
 object q_obj_Variant1-wrapper
     member data: Variant1 optional=False
@@ -38,13 +38,13 @@ object q_obj_Variant2-wrapper
 enum SugaredUnionKind
     member one
     member two
-        if ['IFTWO']
+        if IfAll(['IFTWO'])
 object SugaredUnion
     member type: SugaredUnionKind optional=False
     tag type
     case one: q_obj_Variant1-wrapper
     case two: q_obj_Variant2-wrapper
-        if ['IFTWO']
+        if IfAll(['IFTWO'])
     feature union-feat2
 alternate Alternate
     tag type
tests/qapi-schema/qapi-schema-test.out +29 -29

128 lines not on this page · raw message

Signature · 1 line
2.28.0
#8 lore raw

Re: [PATCH 3/9] qapi: start building an 'if' predicate tree

Quoted 47 lines · On 10/15/20 12:52 PM, [email protected] wrote:

From: Marc-André Lureau <[email protected]>

The following patches are going to express conditions in some target language agostic way. For that, let's start building a predicate tree of configuration options.

The tree will be less expressive than full C macros expressions, and will be based only on identifier. For this reason, it will use have
operations: 'all', 'any' and 'not'. ('and'/'or' have a connotation of expression operands)

For now, the documentation will use the C condition expression (as that's already what is exposed with defined(FOO), &&, || etc). Eventually, we may want to generate a more human friendly syntax later.

---
  docs/sphinx/qapidoc.py                 |  6 +--
  scripts/qapi/common.py                 | 69 ++++++++++++++++++++------
  tests/qapi-schema/doc-good.out         | 12 ++---
  tests/qapi-schema/qapi-schema-test.out | 58 +++++++++++-----------
  4 files changed, 91 insertions(+), 54 deletions(-)
docs/sphinx/qapidoc.py +2 -4
index db9520f37f..31b47e4745 100644
@@ -112,12 +112,10 @@ class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
      def _nodes_for_ifcond(self, ifcond, with_if=True):
          """Return list of Text, literal nodes for the ifcond
 
-        Return a list which gives text like ' (If: cond1, cond2, cond3)', where
-        the conditions are in literal-text and the commas are not.
+        Return a list which gives text like ' (If: C-condition)'.
          If with_if is False, we don't return the "(If: " and ")".
          """
-        condlist = intersperse([nodes.literal('', c) for c in ifcond.ifcond],
-                               nodes.Text(', '))
+        condlist = [nodes.literal('', ifcond.gen_if())]
          if not with_if:
              return condlist
 
scripts/qapi/common.py +0 -0
index 58ddec3bc5..29e0697c27 100644

scripts/qapi/common.py def guardend(name: str) -> str: · line 201

Quoted 8 lines
scripts/qapi/common.py +5 -0
@@ -194,33 +194,72 @@ def guardend(name: str) -> str:
                   name=c_fname(name).upper())
 
 
+class IfPredicate:
+    def cgen(self) -> str:
+        raise NotImplementedError()
+
+

docstrings will be helpful here for your final submission, when you get to it.

I guess right now the tree is IfCond -> IfPredicate -> IfAll -> IfOption.

scripts/qapi/common.py def guardend(name: str) -> str: · line 208

Quoted 7 lines
scripts/qapi/common.py +7 -0
+class IfOption(IfPredicate):
+    def __init__(self, option: str):
+        self.option = option
+
+    def cgen(self) -> str:
+        return self.option
+

cgen being baked into the core implementation strikes me as odd, but I'm not sure where you're headed here just yet.

Quoted 24 lines
scripts/qapi/common.py +24 -0
+    def __repr__(self) -> str:
+        return repr(self.option)
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, IfOption):
+            return False
+        return self.option == other.option
+
+
+class IfAll(IfPredicate):
+    def __init__(self, pred_list: Sequence[IfPredicate]):
+        self.pred_list = pred_list
+
+    def cgen(self) -> str:
+        return " && ".join([p.cgen() for p in self.pred_list])
+
+    def __bool__(self) -> bool:
+        return bool(self.pred_list)
+
+    def __repr__(self) -> str:
+        return f"IfAll({self.pred_list})"
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, IfAll):

scripts/qapi/common.py def guardend(name: str) -> str: · line 241

Quoted 10 lines
scripts/qapi/common.py +6 -1
+            return False
+        return self.pred_list == other.pred_list
+
+
  class IfCond:
      def __init__(self, ifcond: Optional[Sequence[str]] = None):
-        self.ifcond = ifcond or []
+        pred_list = [IfOption(opt) for opt in ifcond or []]
+        self.pred = IfAll(pred_list)
 

okay; so we're converting each string into an IfOption, then creating a predicate (All) with all the options as children.

Note that for some things like machine-target.json that we are passing multiple things as the ifcond, all as one string:

machine-target.json: 'if': 'defined(TARGET_PPC) || defined(TARGET_ARM) || defined(TARGET_I386) || defined(TARGET_S390X) || defined(TARGET_MIPS)' }

and in this case you'll have *one* option. I assume this is probably fine?

Quoted 28 lines
scripts/qapi/common.py +7 -9
      def __bool__(self) -> bool:
-        return bool(self.ifcond)
+        return bool(self.pred)
 
      def __repr__(self) -> str:
-        return repr(self.ifcond)
+        return repr(self.pred)
 
      def __eq__(self, other: object) -> bool:
          if not isinstance(other, IfCond):
              return NotImplemented
-        return self.ifcond == other.ifcond
+        return self.pred == other.pred
 
      def gen_if(self) -> str:
-        ret = ''
-        for ifc in self.ifcond:
-            ret += mcgen('''
+        if self.pred:
+            return mcgen('''
  #if %(cond)s
-''', cond=ifc)
-        return ret
+''', cond=self.pred.cgen())
+        return ""
 
      def gen_endif(self) -> str:
-        ret = ''

scripts/qapi/common.py def guardend(name: str) -> str: · line 265

Quoted 10 lines
scripts/qapi/common.py +5 -5
-        for ifc in reversed(self.ifcond):
-            ret += mcgen('''
-#endif /* %(cond)s */
-''', cond=ifc)
-        return ret
+        if self.pred:
+            return mcgen('''
+#endif // %(cond)s
+''', cond=self.pred.cgen())
+        return ""

Not your fault: reading these weirdly indented triple quote strings in changelogs is really difficult.

Quoted 184 lines
tests/qapi-schema/doc-good.out +6 -6
index 419284dae2..0d27323c47 100644
@@ -12,15 +12,15 @@ enum QType
  module doc-good.json
  enum Enum
      member one
-        if ['defined(IFONE)']
+        if IfAll(['defined(IFONE)'])
      member two
-    if ['defined(IFCOND)']
+    if IfAll(['defined(IFCOND)'])
      feature enum-feat
  object Base
      member base1: Enum optional=False
  object Variant1
      member var1: str optional=False
-        if ['defined(IFSTR)']
+        if IfAll(['defined(IFSTR)'])
          feature member-feat
      feature variant1-feat
  object Variant2
@@ -29,7 +29,7 @@ object Object
      tag base1
      case one: Variant1
      case two: Variant2
-        if ['IFTWO']
+        if IfAll(['IFTWO'])
      feature union-feat1
  object q_obj_Variant1-wrapper
      member data: Variant1 optional=False
@@ -38,13 +38,13 @@ object q_obj_Variant2-wrapper
  enum SugaredUnionKind
      member one
      member two
-        if ['IFTWO']
+        if IfAll(['IFTWO'])
  object SugaredUnion
      member type: SugaredUnionKind optional=False
      tag type
      case one: q_obj_Variant1-wrapper
      case two: q_obj_Variant2-wrapper
-        if ['IFTWO']
+        if IfAll(['IFTWO'])
      feature union-feat2
  alternate Alternate
      tag type
tests/qapi-schema/qapi-schema-test.out +29 -29
index 8868ca0dca..8ba658cd38 100644
@@ -298,65 +298,65 @@ command __org.qemu_x-command q_obj___org.qemu_x-command-arg -> __org.qemu_x-Unio
  object TestIfStruct
      member foo: int optional=False
      member bar: int optional=False
-        if ['defined(TEST_IF_STRUCT_BAR)']
-    if ['defined(TEST_IF_STRUCT)']
+        if IfAll(['defined(TEST_IF_STRUCT_BAR)'])
+    if IfAll(['defined(TEST_IF_STRUCT)'])
  enum TestIfEnum
      member foo
      member bar
-        if ['defined(TEST_IF_ENUM_BAR)']
-    if ['defined(TEST_IF_ENUM)']
+        if IfAll(['defined(TEST_IF_ENUM_BAR)'])
+    if IfAll(['defined(TEST_IF_ENUM)'])
  object q_obj_TestStruct-wrapper
      member data: TestStruct optional=False
  enum TestIfUnionKind
      member foo
      member union_bar
-        if ['defined(TEST_IF_UNION_BAR)']
-    if ['defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)']
+        if IfAll(['defined(TEST_IF_UNION_BAR)'])
+    if IfAll(['defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)'])
  object TestIfUnion
      member type: TestIfUnionKind optional=False
      tag type
      case foo: q_obj_TestStruct-wrapper
      case union_bar: q_obj_str-wrapper
-        if ['defined(TEST_IF_UNION_BAR)']
-    if ['defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)']
+        if IfAll(['defined(TEST_IF_UNION_BAR)'])
+    if IfAll(['defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)'])
  object q_obj_TestIfUnionCmd-arg
      member union_cmd_arg: TestIfUnion optional=False
-    if ['defined(TEST_IF_UNION)']
+    if IfAll(['defined(TEST_IF_UNION)'])
  command TestIfUnionCmd q_obj_TestIfUnionCmd-arg -> None
      gen=True success_response=True boxed=False oob=False preconfig=False
-    if ['defined(TEST_IF_UNION)']
+    if IfAll(['defined(TEST_IF_UNION)'])
  alternate TestIfAlternate
      tag type
      case foo: int
      case bar: TestStruct
-        if ['defined(TEST_IF_ALT_BAR)']
-    if ['defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)']
+        if IfAll(['defined(TEST_IF_ALT_BAR)'])
+    if IfAll(['defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)'])
  object q_obj_TestIfAlternateCmd-arg
      member alt_cmd_arg: TestIfAlternate optional=False
-    if ['defined(TEST_IF_ALT)']
+    if IfAll(['defined(TEST_IF_ALT)'])
  command TestIfAlternateCmd q_obj_TestIfAlternateCmd-arg -> None
      gen=True success_response=True boxed=False oob=False preconfig=False
-    if ['defined(TEST_IF_ALT)']
+    if IfAll(['defined(TEST_IF_ALT)'])
  object q_obj_TestIfCmd-arg
      member foo: TestIfStruct optional=False
      member bar: TestIfEnum optional=False
-        if ['defined(TEST_IF_CMD_BAR)']
-    if ['defined(TEST_IF_CMD)', 'defined(TEST_IF_STRUCT)']
+        if IfAll(['defined(TEST_IF_CMD_BAR)'])
+    if IfAll(['defined(TEST_IF_CMD)', 'defined(TEST_IF_STRUCT)'])
  command TestIfCmd q_obj_TestIfCmd-arg -> UserDefThree
      gen=True success_response=True boxed=False oob=False preconfig=False
-    if ['defined(TEST_IF_CMD)', 'defined(TEST_IF_STRUCT)']
+    if IfAll(['defined(TEST_IF_CMD)', 'defined(TEST_IF_STRUCT)'])
  command TestCmdReturnDefThree None -> UserDefThree
      gen=True success_response=True boxed=False oob=False preconfig=False
  array TestIfEnumList TestIfEnum
-    if ['defined(TEST_IF_ENUM)']
+    if IfAll(['defined(TEST_IF_ENUM)'])
  object q_obj_TestIfEvent-arg
      member foo: TestIfStruct optional=False
      member bar: TestIfEnumList optional=False
-        if ['defined(TEST_IF_EVT_BAR)']
-    if ['defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)']
+        if IfAll(['defined(TEST_IF_EVT_BAR)'])
+    if IfAll(['defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)'])
  event TestIfEvent q_obj_TestIfEvent-arg
      boxed=False
-    if ['defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)']
+    if IfAll(['defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)'])
  object FeatureStruct0
      member foo: int optional=False
  object FeatureStruct1
@@ -379,17 +379,17 @@ object FeatureStruct4
  object CondFeatureStruct1
      member foo: int optional=False
      feature feature1
-        if ['defined(TEST_IF_FEATURE_1)']
+        if IfAll(['defined(TEST_IF_FEATURE_1)'])
  object CondFeatureStruct2
      member foo: int optional=False
      feature feature1
-        if ['defined(TEST_IF_FEATURE_1)']
+        if IfAll(['defined(TEST_IF_FEATURE_1)'])
      feature feature2
-        if ['defined(TEST_IF_FEATURE_2)']
+        if IfAll(['defined(TEST_IF_FEATURE_2)'])
  object CondFeatureStruct3
      member foo: int optional=False
      feature feature1
-        if ['defined(TEST_IF_COND_1)', 'defined(TEST_IF_COND_2)']
+        if IfAll(['defined(TEST_IF_COND_1)', 'defined(TEST_IF_COND_2)'])
  enum FeatureEnum1
      member eins
      member zwei
@@ -429,17 +429,17 @@ command test-command-features3 None -> None
  command test-command-cond-features1 None -> None
      gen=True success_response=True boxed=False oob=False preconfig=False
      feature feature1
-        if ['defined(TEST_IF_FEATURE_1)']
+        if IfAll(['defined(TEST_IF_FEATURE_1)'])
  command test-command-cond-features2 None -> None
      gen=True success_response=True boxed=False oob=False preconfig=False
      feature feature1
-        if ['defined(TEST_IF_FEATURE_1)']
+        if IfAll(['defined(TEST_IF_FEATURE_1)'])
      feature feature2
-        if ['defined(TEST_IF_FEATURE_2)']
+        if IfAll(['defined(TEST_IF_FEATURE_2)'])
  command test-command-cond-features3 None -> None
      gen=True success_response=True boxed=False oob=False preconfig=False
      feature feature1
-        if ['defined(TEST_IF_COND_1)', 'defined(TEST_IF_COND_2)']
+        if IfAll(['defined(TEST_IF_COND_1)', 'defined(TEST_IF_COND_2)'])
  event TEST-EVENT-FEATURES1 None
      boxed=False
      feature deprecated
#9 lore raw

PATCH 4/9 qapi: introduce IfPredicateList and IfAny

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

Generalize IfAll to allow 'any' conditions.

---
 scripts/qapi/common.py | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
scripts/qapi/common.py +16 -4
index 29e0697c27..f5166e0bad 100644
@@ -215,25 +215,37 @@ class IfOption(IfPredicate):
         return self.option == other.option
 
 
-class IfAll(IfPredicate):
+class IfPredicateList(IfPredicate):
+    C_OP = ""
+
     def __init__(self, pred_list: Sequence[IfPredicate]):
         self.pred_list = pred_list
 
     def cgen(self) -> str:
-        return " && ".join([p.cgen() for p in self.pred_list])
+        op = " " + self.C_OP + " "
+        return "(%s)" % op.join([p.cgen() for p in self.pred_list])
 
     def __bool__(self) -> bool:
         return bool(self.pred_list)
 
     def __repr__(self) -> str:
-        return f"IfAll({self.pred_list})"
+        ty = type(self)
+        return f"{ty.__qualname__}({self.pred_list})"
 
     def __eq__(self, other: object) -> bool:
-        if not isinstance(other, IfAll):
+        if not isinstance(other, type(self)):
             return False
         return self.pred_list == other.pred_list
 
 
+class IfAll(IfPredicateList):
+    C_OP = "&&"
+
+
+class IfAny(IfPredicateList):
+    C_OP = "||"
+
+
 class IfCond:
     def __init__(self, ifcond: Optional[Sequence[str]] = None):
         pred_list = [IfOption(opt) for opt in ifcond or []]
Signature · 1 line
2.28.0
#10 lore raw

PATCH 5/9 qapi: add IfNot

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

---
 scripts/qapi/common.py | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
scripts/qapi/common.py +19 -0
index f5166e0bad..566913d69e 100644
@@ -246,6 +246,25 @@ class IfAny(IfPredicateList):
     C_OP = "||"
 
 
+class IfNot(IfPredicate):
+    def __init__(self, pred: IfPredicate):
+        self.pred = pred
+
+    def cgen(self) -> str:
+        return "!" + self.pred.cgen()
+
+    def __bool__(self) -> bool:
+        return bool(self.pred)
+
+    def __repr__(self) -> str:
+        return f"IfNot({self.pred!r})"
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, type(self)):
+            return False
+        return self.pred == other.pred
+
+
 class IfCond:
     def __init__(self, ifcond: Optional[Sequence[str]] = None):
         pred_list = [IfOption(opt) for opt in ifcond or []]
Signature · 1 line
2.28.0
#11 lore raw

PATCH 6/9 qapi: normalize 'if' condition to IfPredicate

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

---
 scripts/qapi/common.py                        |  5 +-
 scripts/qapi/expr.py                          | 55 ++++++++++++-------
 tests/qapi-schema/bad-if.err                  |  3 +-
 tests/qapi-schema/doc-good.out                | 12 ++--
 tests/qapi-schema/enum-if-invalid.err         |  3 +-
 tests/qapi-schema/features-if-invalid.err     |  2 +-
 tests/qapi-schema/qapi-schema-test.json       | 15 +++--
 tests/qapi-schema/qapi-schema-test.out        | 55 ++++++++++---------
 .../qapi-schema/struct-member-if-invalid.err  |  2 +-
 tests/test-qmp-cmds.c                         |  1 +
 10 files changed, 90 insertions(+), 63 deletions(-)
scripts/qapi/common.py +2 -3
index 566913d69e..b855a6dc78 100644
@@ -266,9 +266,8 @@ class IfNot(IfPredicate):
 
 
 class IfCond:
-    def __init__(self, ifcond: Optional[Sequence[str]] = None):
-        pred_list = [IfOption(opt) for opt in ifcond or []]
-        self.pred = IfAll(pred_list)
+    def __init__(self, pred: Optional[IfPredicate] = None):
+        self.pred = pred
 
     def __bool__(self) -> bool:
         return bool(self.pred)
scripts/qapi/expr.py +35 -20

83 lines not on this page · raw message

tests/qapi-schema/bad-if.err +2 -1
index f83dee65da..454fbae387 100644
@@ -1,2 +1,3 @@
 bad-if.json: In struct 'TestIfStruct':
-bad-if.json:2: 'if' condition of struct must be a string or a list of strings
+bad-if.json:2: 'if' condition has unknown key 'value'
+Valid keys are 'all', 'any', 'not'.
tests/qapi-schema/doc-good.out +6 -6
index 0d27323c47..6b723d2341 100644
@@ -12,15 +12,15 @@ enum QType
 module doc-good.json
 enum Enum
     member one
-        if IfAll(['defined(IFONE)'])
+        if 'defined(IFONE)'
     member two
-    if IfAll(['defined(IFCOND)'])
+    if 'defined(IFCOND)'
     feature enum-feat
 object Base
     member base1: Enum optional=False
 object Variant1
     member var1: str optional=False
-        if IfAll(['defined(IFSTR)'])
+        if 'defined(IFSTR)'
         feature member-feat
     feature variant1-feat
 object Variant2
@@ -29,7 +29,7 @@ object Object
     tag base1
     case one: Variant1
     case two: Variant2
-        if IfAll(['IFTWO'])
+        if 'IFTWO'
     feature union-feat1
 object q_obj_Variant1-wrapper
     member data: Variant1 optional=False
@@ -38,13 +38,13 @@ object q_obj_Variant2-wrapper
 enum SugaredUnionKind
     member one
     member two
-        if IfAll(['IFTWO'])
+        if 'IFTWO'
 object SugaredUnion
     member type: SugaredUnionKind optional=False
     tag type
     case one: q_obj_Variant1-wrapper
     case two: q_obj_Variant2-wrapper
-        if IfAll(['IFTWO'])
+        if 'IFTWO'
     feature union-feat2
 alternate Alternate
     tag type
tests/qapi-schema/enum-if-invalid.err +2 -1
index 0556dc967b..3bb84075a9 100644
@@ -1,2 +1,3 @@
 enum-if-invalid.json: In enum 'TestIfEnum':
-enum-if-invalid.json:2: 'if' condition of 'data' member 'bar' must be a string or a list of strings
+enum-if-invalid.json:2: 'if' condition has unknown key 'val'
+Valid keys are 'all', 'any', 'not'.
tests/qapi-schema/features-if-invalid.err +1 -1
index f63b89535e..724a810086 100644
@@ -1,2 +1,2 @@
 features-if-invalid.json: In struct 'Stru':
-features-if-invalid.json:2: 'if' condition of 'features' member 'f' must be a string or a list of strings
+features-if-invalid.json:2: 'if' condition of 'features' member 'f' must be a string, a list of strings or a dict
tests/qapi-schema/qapi-schema-test.json +10 -5
index 63f92adf68..6b3089a553 100644
@@ -228,7 +228,7 @@
 { 'union': 'TestIfUnion', 'data':
   { 'foo': 'TestStruct',
     'union_bar': { 'type': 'str', 'if': 'defined(TEST_IF_UNION_BAR)'} },
-  'if': 'defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)' }
+  'if': ['defined(TEST_IF_UNION)', 'defined(TEST_IF_STRUCT)'] }
 
 { 'command': 'TestIfUnionCmd', 'data': { 'union_cmd_arg': 'TestIfUnion' },
   'if': 'defined(TEST_IF_UNION)' }
@@ -236,10 +236,10 @@
 { 'alternate': 'TestIfAlternate', 'data':
   { 'foo': 'int',
     'bar': { 'type': 'TestStruct', 'if': 'defined(TEST_IF_ALT_BAR)'} },
-  'if': 'defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)' }
+  'if': {'all': ['defined(TEST_IF_ALT)', 'defined(TEST_IF_STRUCT)'] } }
 
 { 'command': 'TestIfAlternateCmd', 'data': { 'alt_cmd_arg': 'TestIfAlternate' },
-  'if': 'defined(TEST_IF_ALT)' }
+  'if': {'all': ['defined(TEST_IF_ALT)', {'not': 'defined(TEST_IF_NOT_ALT)'}] } }
 
 { 'command': 'TestIfCmd', 'data':
   { 'foo': 'TestIfStruct',
@@ -252,7 +252,7 @@
 { 'event': 'TestIfEvent', 'data':
   { 'foo': 'TestIfStruct',
     'bar': { 'type': ['TestIfEnum'], 'if': 'defined(TEST_IF_EVT_BAR)' } },
-  'if': 'defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)' }
+  'if': ['defined(TEST_IF_EVT)', 'defined(TEST_IF_STRUCT)'] }
 
 # test 'features'
 
@@ -283,6 +283,10 @@
   'data': { 'foo': 'int' },
   'features': [ { 'name': 'feature1', 'if': [ 'defined(TEST_IF_COND_1)',
                                               'defined(TEST_IF_COND_2)'] } ] }
+{ 'struct': 'CondFeatureStruct4',
+  'data': { 'foo': 'int' },
+  'features': [ { 'name': 'feature1', 'if': {'any': ['defined(TEST_IF_COND_1)',
+                                                     'defined(TEST_IF_COND_2)'] } } ] }
 
 { 'enum': 'FeatureEnum1',
   'data': [ 'eins', 'zwei', 'drei' ],
@@ -306,7 +310,8 @@
             'fs4': 'FeatureStruct4',
             'cfs1': 'CondFeatureStruct1',
             'cfs2': 'CondFeatureStruct2',
-            'cfs3': 'CondFeatureStruct3' },
+            'cfs3': 'CondFeatureStruct3',
+            'cfs4': 'CondFeatureStruct4' },
   'features': [] }
 
 { 'command': 'test-command-features1',
tests/qapi-schema/qapi-schema-test.out +30 -25

130 lines not on this page · raw message

tests/qapi-schema/struct-member-if-invalid.err +1 -1
index 42e7fdae3c..c18157c1f9 100644
@@ -1,2 +1,2 @@
 struct-member-if-invalid.json: In struct 'Stru':
-struct-member-if-invalid.json:2: 'if' condition of 'data' member 'member' must be a string or a list of strings
+struct-member-if-invalid.json:2: 'if' condition of 'data' member 'member' must be a string, a list of strings or a dict
tests/test-qmp-cmds.c +1 -0
index d3413bfef0..9aabf8ccd4 100644
@@ -53,6 +53,7 @@ void qmp_test_features0(FeatureStruct0 *fs0, FeatureStruct1 *fs1,
                        FeatureStruct2 *fs2, FeatureStruct3 *fs3,
                        FeatureStruct4 *fs4, CondFeatureStruct1 *cfs1,
                        CondFeatureStruct2 *cfs2, CondFeatureStruct3 *cfs3,
+                       CondFeatureStruct4 *cfs4,
                        Error **errp)
 {
 }
Signature · 1 line
2.28.0
#12 lore raw

PATCH 7/9 qapi: convert 'if' C expressions to literal form

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

---
 qapi/machine-target.json | 20 ++++++++++++++++----
 qapi/misc-target.json    | 13 ++++++++++++-
 2 files changed, 28 insertions(+), 5 deletions(-)
qapi/machine-target.json +16 -4
index 698850cc78..de52a5ab59 100644
@@ -213,7 +213,9 @@
 ##
 { 'struct': 'CpuModelExpansionInfo',
   'data': { 'model': 'CpuModelInfo' },
-  'if': 'defined(TARGET_S390X) || defined(TARGET_I386) || defined(TARGET_ARM)' }
+  'if': { 'any': [ 'defined(TARGET_S390X)',
+                   'defined(TARGET_I386)',
+                   'defined(TARGET_ARM)'] } }
 
 ##
 # @query-cpu-model-expansion:
@@ -252,7 +254,9 @@
   'data': { 'type': 'CpuModelExpansionType',
             'model': 'CpuModelInfo' },
   'returns': 'CpuModelExpansionInfo',
-  'if': 'defined(TARGET_S390X) || defined(TARGET_I386) || defined(TARGET_ARM)' }
+  'if': { 'any': [ 'defined(TARGET_S390X)',
+                   'defined(TARGET_I386)',
+                   'defined(TARGET_ARM)' ] } }
 
 ##
 # @CpuDefinitionInfo:
@@ -311,7 +315,11 @@
             '*unavailable-features': [ 'str' ],
             'typename': 'str',
             '*alias-of' : 'str' },
-  'if': 'defined(TARGET_PPC) || defined(TARGET_ARM) || defined(TARGET_I386) || defined(TARGET_S390X) || defined(TARGET_MIPS)' }
+  'if': { 'any': [ 'defined(TARGET_PPC)',
+                   'defined(TARGET_ARM)',
+                   'defined(TARGET_I386)',
+                   'defined(TARGET_S390X)',
+                   'defined(TARGET_MIPS)' ] } }
 
 ##
 # @query-cpu-definitions:
@@ -323,4 +331,8 @@
 # Since: 1.2.0
 ##
 { 'command': 'query-cpu-definitions', 'returns': ['CpuDefinitionInfo'],
-  'if': 'defined(TARGET_PPC) || defined(TARGET_ARM) || defined(TARGET_I386) || defined(TARGET_S390X) || defined(TARGET_MIPS)' }
+  'if': { 'any': [ 'defined(TARGET_PPC)',
+                   'defined(TARGET_ARM)',
+                   'defined(TARGET_I386)',
+                   'defined(TARGET_S390X)',
+                   'defined(TARGET_MIPS)' ] } }
qapi/misc-target.json +12 -1
index 1e561fa97b..c1aa592137 100644
@@ -23,7 +23,18 @@
 ##
 { 'event': 'RTC_CHANGE',
   'data': { 'offset': 'int' },
-  'if': 'defined(TARGET_ALPHA) || defined(TARGET_ARM) || defined(TARGET_HPPA) || defined(TARGET_I386) || defined(TARGET_MIPS) || defined(TARGET_MIPS64) || defined(TARGET_MOXIE) || defined(TARGET_PPC) || defined(TARGET_PPC64) || defined(TARGET_S390X) || defined(TARGET_SH4) || defined(TARGET_SPARC)' }
+  'if': { 'any': [ 'defined(TARGET_ALPHA)',
+                   'defined(TARGET_ARM)',
+                   'defined(TARGET_HPPA)',
+                   'defined(TARGET_I386)',
+                   'defined(TARGET_MIPS)',
+                   'defined(TARGET_MIPS64)',
+                   'defined(TARGET_MOXIE)',
+                   'defined(TARGET_PPC)',
+                   'defined(TARGET_PPC64)',
+                   'defined(TARGET_S390X)',
+                   'defined(TARGET_SH4)',
+                   'defined(TARGET_SPARC)' ] } }
 
 ##
 # @rtc-reset-reinjection:
Signature · 1 line
2.28.0
#13 lore raw

PATCH 8/9 qapi: make 'if' condition strings simple identifiers

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

Change the 'if' condition strings to be C-agnostic and be simple identifiers.

---
 docs/devel/qapi-code-gen.txt                  |  8 +--
 qapi/block-core.json                          | 16 ++---
 qapi/char.json                                |  8 +--
 qapi/machine-target.json                      | 40 ++++++-------
 qapi/migration.json                           | 10 ++--
 qapi/misc-target.json                         | 46 +++++++-------
 qapi/ui.json                                  | 48 +++++++--------
 scripts/qapi/common.py                        |  2 +-
 scripts/qapi/expr.py                          | 10 ++--
 .../alternate-branch-if-invalid.err           |  2 +-
 tests/qapi-schema/bad-if-empty.err            |  2 +-
 tests/qapi-schema/bad-if-list.err             |  2 +-
 tests/qapi-schema/bad-if.json                 |  2 +-
 tests/qapi-schema/doc-good.json               |  6 +-
 tests/qapi-schema/doc-good.out                |  6 +-
 tests/qapi-schema/features-missing-name.json  |  2 +-
 tests/qapi-schema/qapi-schema-test.json       | 52 ++++++++--------
 tests/qapi-schema/qapi-schema-test.out        | 60 +++++++++----------
 tests/qapi-schema/union-branch-if-invalid.err |  2 +-
 19 files changed, 162 insertions(+), 162 deletions(-)
docs/devel/qapi-code-gen.txt +4 -4
index c6438c6aa9..3d22a7ae21 100644
@@ -783,7 +783,7 @@ will then be guarded by #if STRING for each STRING in the COND list.
 Example: a conditional struct
 
  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
-   'if': ['defined(CONFIG_FOO)', 'defined(HAVE_BAR)'] }
+   'if': ['CONFIG_FOO', 'HAVE_BAR'] }
 
 gets its generated code guarded like this:
 
@@ -802,7 +802,7 @@ member 'bar'
 
 { 'struct': 'IfStruct', 'data':
   { 'foo': 'int',
-    'bar': { 'type': 'int', 'if': 'defined(IFCOND)'} } }
+    'bar': { 'type': 'int', 'if': 'IFCOND'} } }
 
 A union's discriminator may not be conditional.
 
@@ -814,7 +814,7 @@ value 'bar'
 
 { 'enum': 'IfEnum', 'data':
   [ 'foo',
-    { 'name' : 'bar', 'if': 'defined(IFCOND)' } ] }
+    { 'name' : 'bar', 'if': 'IFCOND' } ] }
 
 Likewise, features can be conditional.  This requires the longhand
 form of FEATURE.
@@ -824,7 +824,7 @@ Example: a struct with conditional feature 'allow-negative-numbers'
 { 'struct': 'TestType',
   'data': { 'number': 'int' },
   'features': [ { 'name': 'allow-negative-numbers',
-                  'if' 'defined(IFCOND)' } ] }
+                  'if': 'IFCOND' } ] }
 
 Please note that you are responsible to ensure that the C code will
 compile with an arbitrary combination of conditions, since the
qapi/block-core.json +8 -8
index 18f4ea90f1..9ebef3a705 100644
@@ -2791,7 +2791,7 @@
 ##
 { 'enum': 'BlockdevAioOptions',
   'data': [ 'threads', 'native',
-            { 'name': 'io_uring', 'if': 'defined(CONFIG_LINUX_IO_URING)' } ] }
+            { 'name': 'io_uring', 'if': 'CONFIG_LINUX_IO_URING' } ] }
 
 ##
 # @BlockdevCacheOptions:
@@ -2829,7 +2829,7 @@
             'gluster', 'host_cdrom', 'host_device', 'http', 'https', 'iscsi',
             'luks', 'nbd', 'nfs', 'null-aio', 'null-co', 'nvme', 'parallels',
             'qcow', 'qcow2', 'qed', 'quorum', 'raw', 'rbd',
-            { 'name': 'replication', 'if': 'defined(CONFIG_REPLICATION)' },
+            { 'name': 'replication', 'if': 'CONFIG_REPLICATION' },
             'sheepdog',
             'ssh', 'throttle', 'vdi', 'vhdx', 'vmdk', 'vpc', 'vvfat' ] }
 
@@ -2872,10 +2872,10 @@
             '*locking': 'OnOffAuto',
             '*aio': 'BlockdevAioOptions',
             '*drop-cache': {'type': 'bool',
-                            'if': 'defined(CONFIG_LINUX)'},
+                            'if': 'CONFIG_LINUX'},
             '*x-check-cache-dropped': 'bool' },
   'features': [ { 'name': 'dynamic-auto-read-only',
-                  'if': 'defined(CONFIG_POSIX)' } ] }
+                  'if': 'CONFIG_POSIX' } ] }
 
 ##
 # @BlockdevOptionsNull:
@@ -3678,7 +3678,7 @@
 # Since: 2.9
 ##
 { 'enum' : 'ReplicationMode', 'data' : [ 'primary', 'secondary' ],
-  'if': 'defined(CONFIG_REPLICATION)' }
+  'if': 'CONFIG_REPLICATION' }
 
 ##
 # @BlockdevOptionsReplication:
@@ -3697,7 +3697,7 @@
   'base': 'BlockdevOptionsGenericFormat',
   'data': { 'mode': 'ReplicationMode',
             '*top-id': 'str' },
-  'if': 'defined(CONFIG_REPLICATION)' }
+  'if': 'CONFIG_REPLICATION' }
 
 ##
 # @NFSTransport:
@@ -4009,7 +4009,7 @@
       'raw':        'BlockdevOptionsRaw',
       'rbd':        'BlockdevOptionsRbd',
       'replication': { 'type': 'BlockdevOptionsReplication',
-                       'if': 'defined(CONFIG_REPLICATION)' },
+                       'if': 'CONFIG_REPLICATION' },
       'sheepdog':   'BlockdevOptionsSheepdog',
       'ssh':        'BlockdevOptionsSsh',
       'throttle':   'BlockdevOptionsThrottle',
@@ -4311,7 +4311,7 @@
 # Since: 5.1
 ##
 { 'enum': 'Qcow2CompressionType',
-  'data': [ 'zlib', { 'name': 'zstd', 'if': 'defined(CONFIG_ZSTD)' } ] }
+  'data': [ 'zlib', { 'name': 'zstd', 'if': 'CONFIG_ZSTD' } ] }
 
 ##
 # @BlockdevCreateOptionsQcow2:
qapi/char.json +4 -4
index b4d66ec90b..be28845cf9 100644
@@ -343,7 +343,7 @@
 { 'struct': 'ChardevSpiceChannel',
   'data': { 'type': 'str' },
   'base': 'ChardevCommon',
-  'if': 'defined(CONFIG_SPICE)' }
+  'if': 'CONFIG_SPICE' }
 
 ##
 # @ChardevSpicePort:
@@ -357,7 +357,7 @@
 { 'struct': 'ChardevSpicePort',
   'data': { 'fqdn': 'str' },
   'base': 'ChardevCommon',
-  'if': 'defined(CONFIG_SPICE)' }
+  'if': 'CONFIG_SPICE' }
 
 ##
 # @ChardevVC:
@@ -415,9 +415,9 @@
             'stdio': 'ChardevStdio',
             'console': 'ChardevCommon',
             'spicevmc': { 'type': 'ChardevSpiceChannel',
-                          'if': 'defined(CONFIG_SPICE)' },
+                          'if': 'CONFIG_SPICE' },
             'spiceport': { 'type': 'ChardevSpicePort',
-                           'if': 'defined(CONFIG_SPICE)' },
+                           'if': 'CONFIG_SPICE' },
             'vc': 'ChardevVC',
             'ringbuf': 'ChardevRingbuf',
             # next one is just for compatibility
qapi/machine-target.json +20 -20
index de52a5ab59..4848ef70db 100644
@@ -89,7 +89,7 @@
 ##
 { 'struct': 'CpuModelBaselineInfo',
   'data': { 'model': 'CpuModelInfo' },
-  'if': 'defined(TARGET_S390X)' }
+  'if': 'TARGET_S390X' }
 
 ##
 # @CpuModelCompareInfo:
@@ -112,7 +112,7 @@
 { 'struct': 'CpuModelCompareInfo',
   'data': { 'result': 'CpuModelCompareResult',
             'responsible-properties': ['str'] },
-  'if': 'defined(TARGET_S390X)' }
+  'if': 'TARGET_S390X' }
 
 ##
 # @query-cpu-model-comparison:
@@ -156,7 +156,7 @@
 { 'command': 'query-cpu-model-comparison',
   'data': { 'modela': 'CpuModelInfo', 'modelb': 'CpuModelInfo' },
   'returns': 'CpuModelCompareInfo',
-  'if': 'defined(TARGET_S390X)' }
+  'if': 'TARGET_S390X' }
 
 ##
 # @query-cpu-model-baseline:
@@ -200,7 +200,7 @@
   'data': { 'modela': 'CpuModelInfo',
             'modelb': 'CpuModelInfo' },
   'returns': 'CpuModelBaselineInfo',
-  'if': 'defined(TARGET_S390X)' }
+  'if': 'TARGET_S390X' }
 
 ##
 # @CpuModelExpansionInfo:
@@ -213,9 +213,9 @@
 ##
 { 'struct': 'CpuModelExpansionInfo',
   'data': { 'model': 'CpuModelInfo' },
-  'if': { 'any': [ 'defined(TARGET_S390X)',
-                   'defined(TARGET_I386)',
-                   'defined(TARGET_ARM)'] } }
+  'if': { 'any': [ 'TARGET_S390X',
+                   'TARGET_I386',
+                   'TARGET_ARM' ] } }
 
 ##
 # @query-cpu-model-expansion:
@@ -254,9 +254,9 @@
   'data': { 'type': 'CpuModelExpansionType',
             'model': 'CpuModelInfo' },
   'returns': 'CpuModelExpansionInfo',
-  'if': { 'any': [ 'defined(TARGET_S390X)',
-                   'defined(TARGET_I386)',
-                   'defined(TARGET_ARM)' ] } }
+  'if': { 'any': [ 'TARGET_S390X',
+                   'TARGET_I386',
+                   'TARGET_ARM' ] } }
 
 ##
 # @CpuDefinitionInfo:
@@ -315,11 +315,11 @@
             '*unavailable-features': [ 'str' ],
             'typename': 'str',
             '*alias-of' : 'str' },
-  'if': { 'any': [ 'defined(TARGET_PPC)',
-                   'defined(TARGET_ARM)',
-                   'defined(TARGET_I386)',
-                   'defined(TARGET_S390X)',
-                   'defined(TARGET_MIPS)' ] } }
+  'if': { 'any': [ 'TARGET_PPC',
+                   'TARGET_ARM',
+                   'TARGET_I386',
+                   'TARGET_S390X',
+                   'TARGET_MIPS' ] } }
 
 ##
 # @query-cpu-definitions:
@@ -331,8 +331,8 @@
 # Since: 1.2.0
 ##
 { 'command': 'query-cpu-definitions', 'returns': ['CpuDefinitionInfo'],
-  'if': { 'any': [ 'defined(TARGET_PPC)',
-                   'defined(TARGET_ARM)',
-                   'defined(TARGET_I386)',
-                   'defined(TARGET_S390X)',
-                   'defined(TARGET_MIPS)' ] } }
+  'if': { 'any': [ 'TARGET_PPC',
+                   'TARGET_ARM',
+                   'TARGET_I386',
+                   'TARGET_S390X',
+                   'TARGET_MIPS' ] } }
qapi/migration.json +5 -5
index 7f5e6fd681..ebdd664dc7 100644
@@ -506,7 +506,7 @@
 ##
 { 'enum': 'MultiFDCompression',
   'data': [ 'none', 'zlib',
-            { 'name': 'zstd', 'if': 'defined(CONFIG_ZSTD)' } ] }
+            { 'name': 'zstd', 'if': 'CONFIG_ZSTD' } ] }
 
 ##
 # @BitmapMigrationBitmapAlias:
@@ -1575,7 +1575,7 @@
 ##
 { 'command': 'xen-set-replication',
   'data': { 'enable': 'bool', 'primary': 'bool', '*failover' : 'bool' },
-  'if': 'defined(CONFIG_REPLICATION)' }
+  'if': 'CONFIG_REPLICATION' }
 
 ##
 # @ReplicationStatus:
@@ -1591,7 +1591,7 @@
 ##
 { 'struct': 'ReplicationStatus',
   'data': { 'error': 'bool', '*desc': 'str' },
-  'if': 'defined(CONFIG_REPLICATION)' }
+  'if': 'CONFIG_REPLICATION' }
 
 ##
 # @query-xen-replication-status:
@@ -1609,7 +1609,7 @@
 ##
 { 'command': 'query-xen-replication-status',
   'returns': 'ReplicationStatus',
-  'if': 'defined(CONFIG_REPLICATION)' }
+  'if': 'CONFIG_REPLICATION' }
 
 ##
 # @xen-colo-do-checkpoint:
@@ -1626,7 +1626,7 @@
 # Since: 2.9
 ##
 { 'command': 'xen-colo-do-checkpoint',
-  'if': 'defined(CONFIG_REPLICATION)' }
+  'if': 'CONFIG_REPLICATION' }
 
 ##
 # @COLOStatus:
qapi/misc-target.json +23 -23

115 lines not on this page · raw message

qapi/ui.json +24 -24

192 lines not on this page · raw message

scripts/qapi/common.py +1 -1
index b855a6dc78..fcd29636a0 100644
@@ -204,7 +204,7 @@ class IfOption(IfPredicate):
         self.option = option
 
     def cgen(self) -> str:
-        return self.option
+        return f"defined({self.option})"
 
     def __repr__(self) -> str:
         return repr(self.option)
scripts/qapi/expr.py +5 -5
index 0f0e01cb78..655b010a7c 100644
@@ -209,11 +209,11 @@ def check_if(expr: _JSObject, info: QAPISourceInfo, source: str) -> None:
 
     def normalize(cond: Union[str, List[str], object]) -> IfPredicate:
         if isinstance(cond, str):
-            if not cond.strip():
-                 raise QAPISemError(
-                     info,
-                     "'if' condition '%s' of %s makes no sense"
-                     % (cond, source))
+            if not cond.isidentifier():
+                raise QAPISemError(
+                    info,
+                    "'if' option string '%s' of %s is not a valid identifier"
+                % (cond, source))
             return IfOption(cond)
         if isinstance(cond, list):
             cond = {'all': cond}
tests/qapi-schema/alternate-branch-if-invalid.err +1 -1
index d384929c51..e36580845e 100644
@@ -1,2 +1,2 @@
 alternate-branch-if-invalid.json: In alternate 'Alt':
-alternate-branch-if-invalid.json:2: 'if' condition ' ' of 'data' member 'branch' makes no sense
+alternate-branch-if-invalid.json:2: 'if' option string ' ' of 'data' member 'branch' is not a valid identifier
tests/qapi-schema/bad-if-empty.err +1 -1
index a0f3effefb..011aaab017 100644
@@ -1,2 +1,2 @@
 bad-if-empty.json: In struct 'TestIfStruct':
-bad-if-empty.json:2: 'if' condition '' of struct makes no sense
+bad-if-empty.json:2: 'if' option string '' of struct is not a valid identifier
tests/qapi-schema/bad-if-list.err +1 -1
index c462f11b90..f84b945bea 100644
@@ -1,2 +1,2 @@
 bad-if-list.json: In struct 'TestIfStruct':
-bad-if-list.json:2: 'if' condition ' ' of struct makes no sense
+bad-if-list.json:2: 'if' option string ' ' of struct is not a valid identifier
tests/qapi-schema/bad-if.json +1 -1
index 3edd1a0bf2..67818888de 100644
@@ -1,3 +1,3 @@
 # check invalid 'if' type
 { 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
-  'if': { 'value': 'defined(TEST_IF_STRUCT)' } }
+  'if': { 'value': 'TEST_IF_STRUCT' } }
tests/qapi-schema/doc-good.json +3 -3
index e9af0857db..b4a4175f26 100644
@@ -61,9 +61,9 @@
 # @two is undocumented
 ##
 { 'enum': 'Enum', 'data':
-  [ { 'name': 'one', 'if': 'defined(IFONE)' }, 'two' ],
+  [ { 'name': 'one', 'if': 'IFONE' }, 'two' ],
   'features': [ 'enum-feat' ],
-  'if': 'defined(IFCOND)' }
+  'if': 'IFCOND' }
 
 ##
 # @Base:
@@ -86,7 +86,7 @@
   'features': [ 'variant1-feat' ],
   'data': { 'var1': { 'type': 'str',
                       'features': [ 'member-feat' ],
-                      'if': 'defined(IFSTR)' } } }
+                      'if': 'IFSTR' } } }
 
 ##
 # @Variant2:
tests/qapi-schema/doc-good.out +3 -3
index 6b723d2341..f9af1836e1 100644
@@ -12,15 +12,15 @@ enum QType
 module doc-good.json
 enum Enum
     member one
-        if 'defined(IFONE)'
+        if 'IFONE'
     member two
-    if 'defined(IFCOND)'
+    if 'IFCOND'
     feature enum-feat
 object Base
     member base1: Enum optional=False
 object Variant1
     member var1: str optional=False
-        if 'defined(IFSTR)'
+        if 'IFSTR'
         feature member-feat
     feature variant1-feat
 object Variant2
tests/qapi-schema/features-missing-name.json +1 -1
index 2314f97c00..8772c8f7b3 100644
@@ -1,3 +1,3 @@
 { 'struct': 'FeatureStruct0',
   'data': { 'foo': 'int' },
-  'features': [ { 'if': 'defined(NAMELESS_FEATURES)' } ] }
+  'features': [ { 'if': 'NAMELESS_FEATURES' } ] }
tests/qapi-schema/qapi-schema-test.json +26 -26

99 lines not on this page · raw message

tests/qapi-schema/qapi-schema-test.out +30 -30

133 lines not on this page · raw message

tests/qapi-schema/union-branch-if-invalid.err +1 -1
index dd4518233e..b3c44d4068 100644
@@ -1,2 +1,2 @@
 union-branch-if-invalid.json: In union 'Uni':
-union-branch-if-invalid.json:4: 'if' condition '' of 'data' member 'branch1' makes no sense
+union-branch-if-invalid.json:4: 'if' option string '' of 'data' member 'branch1' is not a valid identifier
Signature · 1 line
2.28.0
#14 lore raw

PATCH 9/9 docs: update the documentation about schema configuration

In reply to [email protected]

From: Marc-André Lureau <[email protected]>

---
 docs/devel/qapi-code-gen.txt | 26 +++++++++++++++-----------
 1 file changed, 15 insertions(+), 11 deletions(-)
docs/devel/qapi-code-gen.txt +15 -11
index 3d22a7ae21..517bc29507 100644
@@ -772,26 +772,30 @@ downstream command __com.redhat_drive-mirror.
 === Configuring the schema ===
 
 Syntax:
-    COND = STRING
-         | [ STRING, ... ]
+    COND = CFG-ID
+         | [ CFG-ID, ... ]
+         | { 'all: [ CFG-ID, ... ] }
+         | { 'any: [ CFG-ID, ... ] }
+         | { 'not': COND }
 
-All definitions take an optional 'if' member.  Its value must be a
-string or a list of strings.  A string is shorthand for a list
-containing just that string.  The code generated for the definition
-will then be guarded by #if STRING for each STRING in the COND list.
+    CFG-ID = STRING
+
+All definitions take an optional 'if' member. Its value must be a string, a list
+of strings or an object with a single member 'all', 'any' or 'not'. A string is
+shorthand for a list containing just that string. A list is a shorthand for a
+'all'-member object. The C code generated for the definition will then be guarded
+by an #if precessor expression.
 
 Example: a conditional struct
 
  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
-   'if': ['CONFIG_FOO', 'HAVE_BAR'] }
+   'if': { 'all': [ 'CONFIG_FOO', 'HAVE_BAR' ] } }
 
 gets its generated code guarded like this:
 
- #if defined(CONFIG_FOO)
- #if defined(HAVE_BAR)
+ #if defined(CONFIG_FOO) && defined(HAVE_BAR)
  ... generated code ...
- #endif /* defined(HAVE_BAR) */
- #endif /* defined(CONFIG_FOO) */
+ #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
Signature · 1 line
2.28.0
#15 lore raw

Re: [PATCH 9/9] docs: update the documentation about schema configuration

Quoted 13 lines · On Thu, Oct 15, 2020 at 8:54 PM <[email protected]> wrote:

From: Marc-André Lureau <[email protected]>

---
 docs/devel/qapi-code-gen.txt | 26 +++++++++++++++-----------
 1 file changed, 15 insertions(+), 11 deletions(-)
docs/devel/qapi-code-gen.txt +0 -0
index 3d22a7ae21..517bc29507 100644

docs/devel/qapi-code-gen.txt downstream command __com.redhat_drive-mirror. · line 779

Quoted 10 lines
docs/devel/qapi-code-gen.txt +5 -2
@@ -772,26 +772,30 @@ downstream command __com.redhat_drive-mirror.
 === Configuring the schema ===
 
 Syntax:
-    COND = STRING
-         | [ STRING, ... ]
+    COND = CFG-ID
+         | [ CFG-ID, ... ]
+         | { 'all: [ CFG-ID, ... ] }
+         | { 'any: [ CFG-ID, ... ] }
+         | { 'not': COND }

Btw, I realized while writing that, the doc is actually quite faithfull with the currently limited supported expressions, but I will probably improve on that in v2 (unless it's considered a feature :)

Quoted 34 lines
docs/devel/qapi-code-gen.txt +10 -10
-All definitions take an optional 'if' member.  Its value must be a
-string or a list of strings.  A string is shorthand for a list
-containing just that string.  The code generated for the definition
-will then be guarded by #if STRING for each STRING in the COND list.
+    CFG-ID = STRING
+
+All definitions take an optional 'if' member. Its value must be a string, a list
+of strings or an object with a single member 'all', 'any' or 'not'. A string is
+shorthand for a list containing just that string. A list is a shorthand for a
+'all'-member object. The C code generated for the definition will then be guarded
+by an #if precessor expression.
 
 Example: a conditional struct
 
  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
-   'if': ['CONFIG_FOO', 'HAVE_BAR'] }
+   'if': { 'all': [ 'CONFIG_FOO', 'HAVE_BAR' ] } }
 
 gets its generated code guarded like this:
 
- #if defined(CONFIG_FOO)
- #if defined(HAVE_BAR)
+ #if defined(CONFIG_FOO) && defined(HAVE_BAR)
  ... generated code ...
- #endif /* defined(HAVE_BAR) */
- #endif /* defined(CONFIG_FOO) */
+ #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
--

2.28.0