Skip to contentSkip to conversation

qapi: add #if pre-processor conditions to generated code

PATCH Superseded Marc-André Lureau 12 participants 140 messages Aug 22, 2017 – Sep 7, 2017 Page 1 of 2

Subsystems (5)

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v2 cover qapi: add #if pre-processor conditions to generated code

Hi,

In order to clean-up some hacks in qapi (having to unregister commands at runtime), I proposed a "[PATCH v5 02/20] qapi.py: add a simple #ifdef condition"

(see http://lists.gnu.org/archive/html/qemu-devel/2016-08/msg03106.html).

However, we decided to drop that patch from the series and solve the problem later. The main issues were:
- the syntax was awkward to the JSON schema and documentation
- the evaluation of the condition was done in the qapi scripts, with very limited capability
- each target/config would need different generated files.

Instead, it could defer the #if evaluation to the C-preprocessor.

With this series, top-level qapi JSON entity can take 'if' keys:

{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
'if': 'defined(TEST_IF_STRUCT)' }

Members can be exploded as dictionnary with 'type'/'if' keys:

{ 'struct': 'TestIfStruct', 'data':
{ 'foo': 'int',

    'bar': { 'type': 'int', 'if': 'defined(TEST_IF_STRUCT_BAR)'} } }

Enum values can be exploded as dictionnary with 'type'/'if' keys:

{ 'enum': 'TestIfEnum', 'data':
[ 'foo',

    { 'name' : 'bar', 'if': 'defined(TEST_IF_ENUM_BAR)' } ] }

A good benefit from having conditional schema is that introspection will reflect more accurately the capability of the server. Another benefit is that it may help to remove some dead code when disabling a functionality.

Starting from patch "qapi: add conditions to VNC type/commands/events on the schema", the series demonstrate adding conditions, in order to remove qmp_unregister_commands_hack(). However, it feels like I cheated a little bit by using per-target NEED_CPU_H in the headers to avoid #define poison. The alternative could be to split the headers in common/target?

There are a lot more things we could make conditional in the QAPI schema, like pci/kvm/xen/numa/vde/slirp/posix/win32/vsock/lzo etc etc, however I am still evaluating the implication of such changes both externally and internally, for those interested, I can share my wip branch.

Comments welcome,

v2: after Markus review
- "qboject: add literal qobject type", splitted & many updates
- "qapi: generate a literal qobject for introspection", fixed leak
- "visitor: pass size of strings array to enum visitor", rewrote as a series of patches to change char*[] to struct { int n, char *[] }.
- split the "if" patches in parsing, tests, generation
- added a docs/devel/qapi-code-gen.txt patch
- added a patch to remove enum value assignment, to avoid "holes" with #if values
- update #if VNC patch, compile out "info vnc", compile out des-rfb
- dropped "qobject: replace dump_qobject() by qobject_to_string()" patch
- dropped qapi.mk patch
- other smaller changes

Marc-André Lureau (54):
qapi: fix type_seen key error
qdict: add qdict_put_null() helper
qobject: add literal qobject type
qlit: add qobject_form_qlit()
qapi: generate a literal qobject for introspection
qapi: introduce qapi_enum_lookup()
tpm: simplify driver registration & lookup
hmp: use qapi_enum_parse() in hmp_migrate_set_capability
hmp: use qapi_enum_parse() in hmp_migrate_set_parameter
block: use qemu_enum_parse() in blkdebug_debug_breakpoint
quorum: use qapi_enum_parse() in quorum_open
qapi: change enum lookup structure
qapi: drop the sentinel in enum array
qapi2texi: minor python code simplification
qapi: add 'if' to top-level expressions
qapi: add a test for invalid 'if'
qapi: add 'if' condition on entity objects
qapi: add 'ifcond' to visitor methods
qapi: add #if/#endif helpers
qapi-introspect: modify to_qlit() to take an optional suffix
qapi-introspect: modify to_qlit() to generate #if code
qapi-introspect: add preprocessor conditions to generated QLit
qapi-commands: add #if conditions to commands
qapi-event: add #if conditions to events
qapi-visit: add #if conditions to visitors
qapi-types: refactor variants handling
qapi-types: add #if conditions to types
qapi: do not define enumeration value explicitely
qapi: add 'if' to enum members
qapi: add #if conditions on generated enum values
tests: add some enum members tests
qapi: add 'if' to struct members
qapi: add some struct member tests
qapi: add #if conditions to generated struct members
qapi: add 'if' on union variants
qapi: add #if conditions to generated variants
qapi: 'if' to alternate variant
qapi: add tests for invalid alternate
qapi: add #if conditions to generated alternate variants
docs: document schema configuration
qapi2texi: add 'If:' section to generated documentation
qapi2texi: add 'If:' condition to enum values
qapi2texi: add 'If:' condition to struct members
qapi2texi: add condition to variants
qapi: add conditions to VNC type/commands/events on the schema
qapi: add conditions to SPICE type/commands/events on the schema
qapi: add conditions to REPLICATION type/commands on the schema tests/qmp-test: add query-qmp-schema test
build-sys: make qemu qapi objects per-target
qapi: make rtc-reset-reinjection depend on TARGET_I386
qapi: make s390 commands depend on TARGET_S390X
qapi: make query-gic-capabilities depend on TARGET_ARM
qapi: make query-cpu-model-expansion depend on s390 or x86
qapi: make query-cpu-definitions depend on specific targets

 qapi-schema.json                                 |  98 +++++---
 qapi/block-core.json                             |  13 +-
 qapi/crypto.json                                 |   3 +-
 qapi/event.json                                  |  21 +-
 include/qapi/visitor.h                           |   2 +-
 scripts/qapi.py                                  | 279 +++++++++++++++++------
 scripts/qapi-commands.py                         |   4 +-
 scripts/qapi-event.py                            |   4 +-
 scripts/qapi-introspect.py                       | 124 ++++++----
 scripts/qapi-types.py                            |  62 +++--
 scripts/qapi-visit.py                            |  21 +-
 scripts/qapi2texi.py                             |  51 +++--
 include/hw/qdev-core.h                           |   2 +-
 include/qapi/qmp/qdict.h                         |   2 +
 include/qapi/qmp/qlit.h                          |  56 +++++
 include/qapi/util.h                              |   6 +-
 include/qom/object.h                             |   4 +-
 include/sysemu/arch_init.h                       |  11 -
 include/sysemu/tpm_backend.h                     |   2 +-
 qapi/qapi-visit-core.c                           |  24 +-
 backends/hostmem.c                               |   5 +-
 block.c                                          |   3 +-
 block/backup.c                                   |   3 +-
 block/blkdebug.c                                 |  28 +--
 block/file-posix.c                               |  18 +-
 block/file-win32.c                               |   6 +-
 block/gluster.c                                  |  12 +-
 block/iscsi.c                                    |   3 +-
 block/nfs.c                                      |   3 +-
 block/parallels.c                                |  11 +-
 block/qcow2.c                                    |  15 +-
 block/qed.c                                      |   3 +-
 block/quorum.c                                   |  27 +--
 block/rbd.c                                      |   3 +-
 block/sheepdog.c                                 |   3 +-
 blockdev.c                                       |   9 +-
 blockjob.c                                       |   9 +-
 chardev/char.c                                   |   7 +-
 crypto/block-luks.c                              |  43 ++--
 crypto/block.c                                   |   5 +-
 crypto/cipher-afalg.c                            |   2 +-
 crypto/cipher-builtin.c                          |  17 +-
 crypto/cipher-gcrypt.c                           |  14 +-
 crypto/cipher-nettle.c                           |  22 +-
 crypto/cipher.c                                  |  14 +-
 crypto/hmac-gcrypt.c                             |   2 +-
 crypto/hmac-glib.c                               |   3 +-
 crypto/hmac-nettle.c                             |   3 +-
 crypto/pbkdf-gcrypt.c                            |   3 +-
 crypto/pbkdf-nettle.c                            |   4 +-
 crypto/secret.c                                  |   2 +-
 crypto/tlscreds.c                                |   2 +-
 hmp.c                                            | 252 ++++++++++----------
 hw/block/fdc.c                                   |   9 +-
 hw/char/escc.c                                   |   3 +-
 hw/core/qdev-properties.c                        |  19 +-
 hw/input/virtio-input-hid.c                      |   5 +-
 migration/colo-failover.c                        |   6 +-
 migration/colo.c                                 |  31 +--
 migration/global_state.c                         |   5 +-
 monitor.c                                        |  94 ++------
 net/filter.c                                     |   2 +-
 net/net.c                                        |   5 +-
 qapi/qapi-util.c                                 |  16 +-
 qapi/qmp-dispatch.c                              |   4 +-
 qemu-img.c                                       |   6 +-
 qemu-nbd.c                                       |   3 +-
 qmp.c                                            |  72 +-----
 qobject/qlit.c                                   | 143 ++++++++++++
 qom/object.c                                     |  16 +-
 stubs/arch-query-cpu-def.c                       |  10 -
 stubs/arch-query-cpu-model-baseline.c            |  12 -
 stubs/arch-query-cpu-model-comparison.c          |  12 -
 stubs/arch-query-cpu-model-expansion.c           |  12 -
 stubs/qapi-event.c                               |  74 ++++++
 target/arm/helper.c                              |   3 +-
 target/i386/cpu.c                                |   5 +-
 target/ppc/translate_init.c                      |   3 +-
 target/s390x/cpu_models.c                        |   9 +-
 tests/check-qjson.c                              | 150 +++---------
 tests/check-qlit.c                               |  94 ++++++++
 tests/check-qom-proplist.c                       |   7 +-
 tests/qmp-test.c                                 |  21 ++
 tests/test-qapi-util.c                           |  17 +-
 tests/test-qmp-commands.c                        |   6 +
 tests/test-qobject-input-visitor.c               |  18 +-
 tests/test-qobject-output-visitor.c              |   4 +-
 tests/test-string-input-visitor.c                |   4 +-
 tests/test-string-output-visitor.c               |   6 +-
 tpm.c                                            |  44 ++--
 ui/input-legacy.c                                |   6 +-
 ui/input.c                                       |  13 +-
 ui/vnc.c                                         |   8 +-
 vl.c                                             |   7 +-
 Makefile.objs                                    |   9 +-
 Makefile.target                                  |   4 +
 docs/devel/qapi-code-gen.txt                     |  76 +++++-
 hmp-commands-info.hx                             |   2 +
 qobject/Makefile.objs                            |   2 +-
 stubs/Makefile.objs                              |   5 +-
 tests/Makefile.include                           |  11 +-
 tests/qapi-schema/alternate-conflict-string.json |   4 +-
 tests/qapi-schema/alternate-dict-invalid.err     |   1 +
 tests/qapi-schema/alternate-dict-invalid.exit    |   1 +
 tests/qapi-schema/alternate-dict-invalid.json    |   4 +
 tests/qapi-schema/alternate-dict-invalid.out     |   0
 tests/qapi-schema/bad-if.err                     |   1 +
 tests/qapi-schema/bad-if.exit                    |   1 +
 tests/qapi-schema/bad-if.json                    |   3 +
 tests/qapi-schema/bad-if.out                     |   0
 tests/qapi-schema/enum-dict-member-invalid.err   |   1 +
 tests/qapi-schema/enum-dict-member-invalid.exit  |   1 +
 tests/qapi-schema/enum-dict-member-invalid.json  |   2 +
 tests/qapi-schema/enum-dict-member-invalid.out   |   0
 tests/qapi-schema/enum-dict-member.err           |   1 -
 tests/qapi-schema/enum-dict-member.exit          |   2 +-
 tests/qapi-schema/enum-dict-member.json          |   3 +-
 tests/qapi-schema/enum-dict-member.out           |   4 +
 tests/qapi-schema/enum-if-invalid.err            |   1 +
 tests/qapi-schema/enum-if-invalid.exit           |   1 +
 tests/qapi-schema/enum-if-invalid.json           |   3 +
 tests/qapi-schema/enum-if-invalid.out            |   0
 tests/qapi-schema/qapi-schema-test.json          |  32 +++
 tests/qapi-schema/qapi-schema-test.out           |  47 ++++
 tests/qapi-schema/struct-if-invalid.err          |   1 +
 tests/qapi-schema/struct-if-invalid.exit         |   1 +
 tests/qapi-schema/struct-if-invalid.json         |   3 +
 tests/qapi-schema/struct-if-invalid.out          |   0
 tests/qapi-schema/struct-member-type.err         |   0
 tests/qapi-schema/struct-member-type.exit        |   1 +
 tests/qapi-schema/struct-member-type.json        |   1 +
 tests/qapi-schema/struct-member-type.out         |   5 +
 tests/qapi-schema/test-qapi.py                   |  31 ++-
 trace/Makefile.objs                              |   2 +-
 134 files changed, 1606 insertions(+), 990 deletions(-)
 create mode 100644 include/qapi/qmp/qlit.h
 create mode 100644 qobject/qlit.c
 delete mode 100644 stubs/arch-query-cpu-def.c
 delete mode 100644 stubs/arch-query-cpu-model-baseline.c
 delete mode 100644 stubs/arch-query-cpu-model-comparison.c
 delete mode 100644 stubs/arch-query-cpu-model-expansion.c
 create mode 100644 stubs/qapi-event.c
 create mode 100644 tests/check-qlit.c
 create mode 100644 tests/qapi-schema/alternate-dict-invalid.err
 create mode 100644 tests/qapi-schema/alternate-dict-invalid.exit
 create mode 100644 tests/qapi-schema/alternate-dict-invalid.json
 create mode 100644 tests/qapi-schema/alternate-dict-invalid.out
 create mode 100644 tests/qapi-schema/bad-if.err
 create mode 100644 tests/qapi-schema/bad-if.exit
 create mode 100644 tests/qapi-schema/bad-if.json
 create mode 100644 tests/qapi-schema/bad-if.out
 create mode 100644 tests/qapi-schema/enum-dict-member-invalid.err
 create mode 100644 tests/qapi-schema/enum-dict-member-invalid.exit
 create mode 100644 tests/qapi-schema/enum-dict-member-invalid.json
 create mode 100644 tests/qapi-schema/enum-dict-member-invalid.out
 create mode 100644 tests/qapi-schema/enum-if-invalid.err
 create mode 100644 tests/qapi-schema/enum-if-invalid.exit
 create mode 100644 tests/qapi-schema/enum-if-invalid.json
 create mode 100644 tests/qapi-schema/enum-if-invalid.out
 create mode 100644 tests/qapi-schema/struct-if-invalid.err
 create mode 100644 tests/qapi-schema/struct-if-invalid.exit
 create mode 100644 tests/qapi-schema/struct-if-invalid.json
 create mode 100644 tests/qapi-schema/struct-if-invalid.out
 create mode 100644 tests/qapi-schema/struct-member-type.err
 create mode 100644 tests/qapi-schema/struct-member-type.exit
 create mode 100644 tests/qapi-schema/struct-member-type.json
 create mode 100644 tests/qapi-schema/struct-member-type.out
Signature · 1 line
2.14.1.146.gd35faa819
#1 lore raw

PATCH v2 1/54 qapi: fix type_seen key error

The type_seen member can be of a different type than the 'qtype' being checked, since a string create several conflicts. Lookup the real conflicting type in the conflict set, that one must be present in type_seen.

This fixes the following error, reproducible with the modified test:

Traceback (most recent call last):
File "/home/elmarco/src/qq/tests/qapi-schema/test-qapi.py", line 56, in <module>
schema = QAPISchema(sys.argv[1])
File "/home/elmarco/src/qq/scripts/qapi.py", line 1470, in __init__
self.exprs = check_exprs(parser.exprs)
File "/home/elmarco/src/qq/scripts/qapi.py", line 959, in check_exprs
check_alternate(expr, info)
File "/home/elmarco/src/qq/scripts/qapi.py", line 831, in check_alternate

    % (name, key, types_seen[qtype]))

KeyError: 'QTYPE_QSTRING'

---
 scripts/qapi.py                                  | 6 ++++--
 tests/qapi-schema/alternate-conflict-string.json | 4 ++--
 2 files changed, 6 insertions(+), 4 deletions(-)
scripts/qapi.py +4 -2
index 8aa2775f12..a3ac799535 100644
@@ -825,10 +825,12 @@ def check_alternate(expr, info):
             else:
                 conflicting.add('QTYPE_QNUM')
                 conflicting.add('QTYPE_QBOOL')
-        if conflicting & set(types_seen):
+        conflict = conflicting & set(types_seen)
+        if conflict:
+            conflict_qtype = list(conflict)[0]
             raise QAPISemError(info, "Alternate '%s' member '%s' can't "
                                "be distinguished from member '%s'"
-                               % (name, key, types_seen[qtype]))
+                               % (name, key, types_seen[conflict_qtype]))
         for qt in conflicting:
             types_seen[qt] = key
 
tests/qapi-schema/alternate-conflict-string.json +2 -2
index 85adbd4adc..bb2702978e 100644
@@ -1,4 +1,4 @@
 # alternate branches of 'str' type conflict with all scalar types
 { 'alternate': 'Alt',
-  'data': { 'one': 'str',
-            'two': 'int' } }
+  'data': { 'one': 'int',
+            'two': 'str' } }
Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 1/54
#2 lore raw

Re: [Qemu-devel] [PATCH v2 01/54] qapi: fix type_seen key error

Quoted 29 lines · Marc-André Lureau

The type_seen member can be of a different type than the 'qtype' being checked, since a string create several conflicts. Lookup the real conflicting type in the conflict set, that one must be present in type_seen.

This fixes the following error, reproducible with the modified test:

Traceback (most recent call last):
File "/home/elmarco/src/qq/tests/qapi-schema/test-qapi.py", line 56, in <module>
schema = QAPISchema(sys.argv[1])
File "/home/elmarco/src/qq/scripts/qapi.py", line 1470, in __init__
self.exprs = check_exprs(parser.exprs)
File "/home/elmarco/src/qq/scripts/qapi.py", line 959, in check_exprs
check_alternate(expr, info)
File "/home/elmarco/src/qq/scripts/qapi.py", line 831, in check_alternate

    % (name, key, types_seen[qtype]))

KeyError: 'QTYPE_QSTRING'

---
 scripts/qapi.py                                  | 6 ++++--
 tests/qapi-schema/alternate-conflict-string.json | 4 ++--
 2 files changed, 6 insertions(+), 4 deletions(-)
scripts/qapi.py +0 -0
index 8aa2775f12..a3ac799535 100644

scripts/qapi.py def check_alternate(expr, info): · line 830

Quoted 7 lines
scripts/qapi.py +3 -1
@@ -825,10 +825,12 @@ def check_alternate(expr, info):
             else:
                 conflicting.add('QTYPE_QNUM')
                 conflicting.add('QTYPE_QBOOL')
-        if conflicting & set(types_seen):
+        conflict = conflicting & set(types_seen)
+        if conflict:
+            conflict_qtype = list(conflict)[0]

Converting from set to list just to extract an element is clumsly. Let's use conflict.pop(), and eliminate the variable. Can do on commit.

Quoted 12 lines
scripts/qapi.py +1 -1
             raise QAPISemError(info, "Alternate '%s' member '%s' can't "
                                "be distinguished from member '%s'"
-                               % (name, key, types_seen[qtype]))
+                               % (name, key, types_seen[conflict_qtype]))
         for qt in conflicting:
             types_seen[qt] = key
 
tests/qapi-schema/alternate-conflict-string.json +0 -0
index 85adbd4adc..bb2702978e 100644

tests/qapi-schema/alternate-conflict-string.json line 4

Quoted 6 lines
tests/qapi-schema/alternate-conflict-string.json +2 -2
@@ -1,4 +1,4 @@
 # alternate branches of 'str' type conflict with all scalar types
 { 'alternate': 'Alt',
-  'data': { 'one': 'str',
-            'two': 'int' } }
+  'data': { 'one': 'int',
+            'two': 'str' } }
#3 lore raw

Re: [Qemu-devel] [PATCH v2 01/54] qapi: fix type_seen key error

Hi

----- Original Message -----

Quoted 27 lines
Quoted 25 lines · Marc-André Lureau

The type_seen member can be of a different type than the 'qtype' being checked, since a string create several conflicts. Lookup the real conflicting type in the conflict set, that one must be present in type_seen.

This fixes the following error, reproducible with the modified test:

Traceback (most recent call last):
File "/home/elmarco/src/qq/tests/qapi-schema/test-qapi.py", line 56, in <module>
schema = QAPISchema(sys.argv[1])
File "/home/elmarco/src/qq/scripts/qapi.py", line 1470, in __init__
self.exprs = check_exprs(parser.exprs)
File "/home/elmarco/src/qq/scripts/qapi.py", line 959, in check_exprs
check_alternate(expr, info)
File "/home/elmarco/src/qq/scripts/qapi.py", line 831, in check_alternate

    % (name, key, types_seen[qtype]))

KeyError: 'QTYPE_QSTRING'

---
 scripts/qapi.py                                  | 6 ++++--
 tests/qapi-schema/alternate-conflict-string.json | 4 ++--
 2 files changed, 6 insertions(+), 4 deletions(-)
Quoted 15 lines

scripts/qapi.py def check_alternate(expr, info): · line 830

Quoted 12 lines
scripts/qapi.py +3 -1
index 8aa2775f12..a3ac799535 100644
@@ -825,10 +825,12 @@ def check_alternate(expr, info):
             else:
                 conflicting.add('QTYPE_QNUM')
                 conflicting.add('QTYPE_QBOOL')
-        if conflicting & set(types_seen):
+        conflict = conflicting & set(types_seen)
+        if conflict:
+            conflict_qtype = list(conflict)[0]

Converting from set to list just to extract an element is clumsly. Let's use conflict.pop(), and eliminate the variable. Can do on commit.

I didn't realize that. thanks

Quoted 23 lines
Quoted 14 lines
scripts/qapi.py +1 -1
             raise QAPISemError(info, "Alternate '%s' member '%s' can't "
                                "be distinguished from member '%s'"
-                               % (name, key, types_seen[qtype]))
+                               % (name, key, types_seen[conflict_qtype]))
         for qt in conflicting:
             types_seen[qt] = key
 
tests/qapi-schema/alternate-conflict-string.json +0 -0
index 85adbd4adc..bb2702978e 100644

tests/qapi-schema/alternate-conflict-string.json line 4

Quoted 6 lines
tests/qapi-schema/alternate-conflict-string.json +2 -2
@@ -1,4 +1,4 @@
 # alternate branches of 'str' type conflict with all scalar types
 { 'alternate': 'Alt',
-  'data': { 'one': 'str',
-            'two': 'int' } }
+  'data': { 'one': 'int',
+            'two': 'str' } }
#4 lore raw

Re: [Qemu-devel] [PATCH v2 01/54] qapi: fix type_seen key error

Quoted 46 lines · Marc-André Lureau

Hi

----- Original Message -----

Quoted 27 lines
Quoted 25 lines · Marc-André Lureau

The type_seen member can be of a different type than the 'qtype' being checked, since a string create several conflicts. Lookup the real conflicting type in the conflict set, that one must be present in type_seen.

This fixes the following error, reproducible with the modified test:

Traceback (most recent call last):
File "/home/elmarco/src/qq/tests/qapi-schema/test-qapi.py", line 56, in <module>
schema = QAPISchema(sys.argv[1])
File "/home/elmarco/src/qq/scripts/qapi.py", line 1470, in __init__
self.exprs = check_exprs(parser.exprs)
File "/home/elmarco/src/qq/scripts/qapi.py", line 959, in check_exprs
check_alternate(expr, info)
File "/home/elmarco/src/qq/scripts/qapi.py", line 831, in check_alternate

    % (name, key, types_seen[qtype]))

KeyError: 'QTYPE_QSTRING'

---
 scripts/qapi.py                                  | 6 ++++--
 tests/qapi-schema/alternate-conflict-string.json | 4 ++--
 2 files changed, 6 insertions(+), 4 deletions(-)
Quoted 15 lines

scripts/qapi.py def check_alternate(expr, info): · line 830

Quoted 12 lines
scripts/qapi.py +3 -1
index 8aa2775f12..a3ac799535 100644
@@ -825,10 +825,12 @@ def check_alternate(expr, info):
             else:
                 conflicting.add('QTYPE_QNUM')
                 conflicting.add('QTYPE_QBOOL')
-        if conflicting & set(types_seen):
+        conflict = conflicting & set(types_seen)
+        if conflict:
+            conflict_qtype = list(conflict)[0]

Converting from set to list just to extract an element is clumsly. Let's use conflict.pop(), and eliminate the variable. Can do on commit.

Quoted 1 line

I didn't realize that. thanks

I didn't know about .pop() either, but I went "there's *got* to be a better way!" and searched the docs for it :)

[...]

#5 lore raw

Re: [Qemu-devel] [PATCH v2 01/54] qapi: fix type_seen key error

In reply to Marc-André Lureau

Conflicts with Eduardo's "[PATCH v2] qapi: Fix error handling code on alternate conflict".
Message-Id: <[email protected]>

Marc-André, could you have a look? You can rebase your fix on top of Eduardo's, or merge the two into one commit.

Quoted 54 lines · Marc-André Lureau

The type_seen member can be of a different type than the 'qtype' being checked, since a string create several conflicts. Lookup the real conflicting type in the conflict set, that one must be present in type_seen.

This fixes the following error, reproducible with the modified test:

Traceback (most recent call last):
File "/home/elmarco/src/qq/tests/qapi-schema/test-qapi.py", line 56, in <module>
schema = QAPISchema(sys.argv[1])
File "/home/elmarco/src/qq/scripts/qapi.py", line 1470, in __init__
self.exprs = check_exprs(parser.exprs)
File "/home/elmarco/src/qq/scripts/qapi.py", line 959, in check_exprs
check_alternate(expr, info)
File "/home/elmarco/src/qq/scripts/qapi.py", line 831, in check_alternate

    % (name, key, types_seen[qtype]))

KeyError: 'QTYPE_QSTRING'

---
 scripts/qapi.py                                  | 6 ++++--
 tests/qapi-schema/alternate-conflict-string.json | 4 ++--
 2 files changed, 6 insertions(+), 4 deletions(-)
scripts/qapi.py +4 -2
index 8aa2775f12..a3ac799535 100644
@@ -825,10 +825,12 @@ def check_alternate(expr, info):
             else:
                 conflicting.add('QTYPE_QNUM')
                 conflicting.add('QTYPE_QBOOL')
-        if conflicting & set(types_seen):
+        conflict = conflicting & set(types_seen)
+        if conflict:
+            conflict_qtype = list(conflict)[0]
             raise QAPISemError(info, "Alternate '%s' member '%s' can't "
                                "be distinguished from member '%s'"
-                               % (name, key, types_seen[qtype]))
+                               % (name, key, types_seen[conflict_qtype]))
         for qt in conflicting:
             types_seen[qt] = key
 
tests/qapi-schema/alternate-conflict-string.json +2 -2
index 85adbd4adc..bb2702978e 100644
@@ -1,4 +1,4 @@
 # alternate branches of 'str' type conflict with all scalar types
 { 'alternate': 'Alt',
-  'data': { 'one': 'str',
-            'two': 'int' } }
+  'data': { 'one': 'int',
+            'two': 'str' } }
#6 lore raw

Re: [Qemu-devel] [PATCH v2 01/54] qapi: fix type_seen key error

Quoted 6 lines · Markus Armbruster

Conflicts with Eduardo's "[PATCH v2] qapi: Fix error handling code on alternate conflict".
Message-Id: <[email protected]>

Marc-André, could you have a look? You can rebase your fix on top of Eduardo's, or merge the two into one commit.

Both patches seem to be fixing the same bug.

Quoted 57 lines
Quoted 54 lines · Marc-André Lureau

The type_seen member can be of a different type than the 'qtype' being checked, since a string create several conflicts. Lookup the real conflicting type in the conflict set, that one must be present in type_seen.

This fixes the following error, reproducible with the modified test:

Traceback (most recent call last):
File "/home/elmarco/src/qq/tests/qapi-schema/test-qapi.py", line 56, in <module>
schema = QAPISchema(sys.argv[1])
File "/home/elmarco/src/qq/scripts/qapi.py", line 1470, in __init__
self.exprs = check_exprs(parser.exprs)
File "/home/elmarco/src/qq/scripts/qapi.py", line 959, in check_exprs
check_alternate(expr, info)
File "/home/elmarco/src/qq/scripts/qapi.py", line 831, in check_alternate

    % (name, key, types_seen[qtype]))

KeyError: 'QTYPE_QSTRING'

---
 scripts/qapi.py                                  | 6 ++++--
 tests/qapi-schema/alternate-conflict-string.json | 4 ++--
 2 files changed, 6 insertions(+), 4 deletions(-)
scripts/qapi.py +4 -2
index 8aa2775f12..a3ac799535 100644
@@ -825,10 +825,12 @@ def check_alternate(expr, info):
             else:
                 conflicting.add('QTYPE_QNUM')
                 conflicting.add('QTYPE_QBOOL')
-        if conflicting & set(types_seen):
+        conflict = conflicting & set(types_seen)
+        if conflict:
+            conflict_qtype = list(conflict)[0]
             raise QAPISemError(info, "Alternate '%s' member '%s' can't "
                                "be distinguished from member '%s'"
-                               % (name, key, types_seen[qtype]))
+                               % (name, key, types_seen[conflict_qtype]))
         for qt in conflicting:
             types_seen[qt] = key
 
tests/qapi-schema/alternate-conflict-string.json +2 -2
index 85adbd4adc..bb2702978e 100644
@@ -1,4 +1,4 @@
 # alternate branches of 'str' type conflict with all scalar types
 { 'alternate': 'Alt',
-  'data': { 'one': 'str',
-            'two': 'int' } }
+  'data': { 'one': 'int',
+            'two': 'str' } }
Signature · 1 line
Eduardo
#7 lore raw

Re: [Qemu-devel] [PATCH v2 01/54] qapi: fix type_seen key error

Quoted 10 lines · Eduardo Habkost
Quoted 6 lines · Markus Armbruster

Conflicts with Eduardo's "[PATCH v2] qapi: Fix error handling code on alternate conflict".
Message-Id: <[email protected]>

Marc-André, could you have a look? You can rebase your fix on top of Eduardo's, or merge the two into one commit.

Both patches seem to be fixing the same bug.

Yes, it is solved differently. But take Eduardo's patch, it has more extensive tests .

Quoted 67 lines
Quoted 9 lines
Quoted 5 lines · Marc-André Lureau

The type_seen member can be of a different type than the 'qtype' being checked, since a string create several conflicts. Lookup the real conflicting type in the conflict set, that one must be present in type_seen.

Quoted 4 lines
Quoted 4 lines

This fixes the following error, reproducible with the modified test:

Traceback (most recent call last):
File "/home/elmarco/src/qq/tests/qapi-schema/test-qapi.py", line 56,

in <module>

Quoted 6 lines
Quoted 6 lines

schema = QAPISchema(sys.argv[1])
File "/home/elmarco/src/qq/scripts/qapi.py", line 1470, in __init__
self.exprs = check_exprs(parser.exprs)
File "/home/elmarco/src/qq/scripts/qapi.py", line 959, in check_exprs
check_alternate(expr, info)
File "/home/elmarco/src/qq/scripts/qapi.py", line 831, in

check_alternate

Quoted 9 lines
Quoted 9 lines
    % (name, key, types_seen[qtype]))

KeyError: 'QTYPE_QSTRING'

---
 scripts/qapi.py                                  | 6 ++++--
 tests/qapi-schema/alternate-conflict-string.json | 4 ++--
 2 files changed, 6 insertions(+), 4 deletions(-)
Quoted 13 lines

scripts/qapi.py def check_alternate(expr, info): · line 831

Quoted 13 lines
scripts/qapi.py +3 -1
index 8aa2775f12..a3ac799535 100644
@@ -825,10 +825,12 @@ def check_alternate(expr, info):
             else:
                 conflicting.add('QTYPE_QNUM')
                 conflicting.add('QTYPE_QBOOL')
-        if conflicting & set(types_seen):
+        conflict = conflicting & set(types_seen)
+        if conflict:
+            conflict_qtype = list(conflict)[0]
             raise QAPISemError(info, "Alternate '%s' member '%s'

can't "

Quoted 3 lines

scripts/qapi.py def check_alternate(expr, info):

Quoted 3 lines
scripts/qapi.py +1 -1
                                "be distinguished from member '%s'"
-                               % (name, key, types_seen[qtype]))
+                               % (name, key,

types_seen[conflict_qtype]))

Quoted 4 lines

Review

Quoted 4 lines
scripts/qapi.py +0 -0
         for qt in conflicting:
             types_seen[qt] = key
 
(quoted diff) +0 -0

b/tests/qapi-schema/alternate-conflict-string.json

Quoted 10 lines

tests/qapi-schema/alternate-conflict-string.json line 4

Quoted 10 lines

index 85adbd4adc..bb2702978e 100644

tests/qapi-schema/alternate-conflict-string.json +2 -2
@@ -1,4 +1,4 @@
 # alternate branches of 'str' type conflict with all scalar types
 { 'alternate': 'Alt',
-  'data': { 'one': 'str',
-            'two': 'int' } }
+  'data': { 'one': 'int',
+            'two': 'str' } }

--
Eduardo

Quoted 1 line

--

Marc-André Lureau

#8 lore raw

Re: [Qemu-devel] [PATCH v2 01/54] qapi: fix type_seen key error

Quoted 7 lines · Marc-André Lureau
Quoted 5 lines · Eduardo Habkost
Quoted 4 lines · Markus Armbruster

Conflicts with Eduardo's "[PATCH v2] qapi: Fix error handling code on alternate conflict".
Message-Id: <[email protected]>

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Marc-André, could you have a look? You can rebase your fix on top of Eduardo's, or merge the two into one commit.

Both patches seem to be fixing the same bug.

Yes, it is solved differently. But take Eduardo's patch, it has more extensive tests .

Okay.

Too bad I didn't remember Eduardo's patch when I got yours.

#9 lore raw

PATCH v2 2/54 qdict: add qdict_put_null() helper

In reply to Marc-André Lureau
---
 include/qapi/qmp/qdict.h | 2 ++
 1 file changed, 2 insertions(+)
include/qapi/qmp/qdict.h +2 -0
index 363e431106..a35bed9f16 100644
@@ -60,6 +60,8 @@ void qdict_destroy_obj(QObject *obj);
         qdict_put(qdict, key, qbool_from_bool(value))
 #define qdict_put_str(qdict, key, value) \
         qdict_put(qdict, key, qstring_from_str(value))
+#define qdict_put_null(qdict, key) \
+        qdict_put(qdict, key, qnull())
 
 /* High level helpers */
 double qdict_get_double(const QDict *qdict, const char *key);
Signature · 1 line
2.14.1.146.gd35faa819
#10 lore raw

Re: [Qemu-devel] [PATCH v2 02/54] qdict: add qdict_put_null() helper

include/qapi/qmp/qdict.h void qdict_destroy_obj(QObject *obj);

Quoted 10 lines · Marc-André Lureau
---
 include/qapi/qmp/qdict.h | 2 ++
 1 file changed, 2 insertions(+)
include/qapi/qmp/qdict.h +0 -0
index 363e431106..a35bed9f16 100644
@@ -60,6 +60,8 @@ void qdict_destroy_obj(QObject *obj);

/* Helpers for int, bool, and string */ #define qdict_put_int(qdict, key, value) \
qdict_put(qdict, key, qnum_from_int(value))
#define qdict_put_bool(qdict, key, value) \

include/qapi/qmp/qdict.h void qdict_destroy_obj(QObject *obj); · line 67

Quoted 8 lines
include/qapi/qmp/qdict.h +2 -0
         qdict_put(qdict, key, qbool_from_bool(value))
 #define qdict_put_str(qdict, key, value) \
         qdict_put(qdict, key, qstring_from_str(value))
+#define qdict_put_null(qdict, key) \
+        qdict_put(qdict, key, qnull())
 
 /* High level helpers */
 double qdict_get_double(const QDict *qdict, const char *key);

Marginal. I can accept it for completeness's sake, or rather a step towards completeness. But please update the "Helpers for ..." comment, and convert existing qdict_put(QD, K, qnull()) to use qdict_put_null(). A quick grep finds some in target/i386/cpu.c. There might be more.

#11 lore raw

Re: [Qemu-devel] [PATCH v2 02/54] qdict: add qdict_put_null() helper

Quoted 7 lines · Markus Armbruster
   #define qdict_put_bool(qdict, key, value) \
Quoted 6 lines

qdict_put(qdict, key, qbool_from_bool(value))
#define qdict_put_str(qdict, key, value) \
qdict_put(qdict, key, qstring_from_str(value))

include/qapi/qmp/qdict.h +2 -0
+#define qdict_put_null(qdict, key) \
+        qdict_put(qdict, key, qnull())
Quoted 7 lines
Quoted 2 lines

/* High level helpers */
double qdict_get_double(const QDict *qdict, const char *key);

Marginal. I can accept it for completeness's sake, or rather a step towards completeness. But please update the "Helpers for ..." comment, and convert existing qdict_put(QD, K, qnull()) to use qdict_put_null(). A quick grep finds some in target/i386/cpu.c. There might be more.

And we already used Coccinelle to find candidates for qdict_put_bool and friends, so that should be the reasonable approach to use here as well.

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

PATCH v2 3/54 qobject: add literal qobject type

In reply to Marc-André Lureau

Promote LiteralQObject from tests/check-qjson.c to qobject/qlit.c, allowing to statically declare complex qobjects.

---
 include/qapi/qmp/qlit.h |  54 +++++++++++++++++
 qobject/qlit.c          | 106 ++++++++++++++++++++++++++++++++++
 tests/check-qjson.c     | 150 +++++++++---------------------------------------
 tests/check-qlit.c      |  68 ++++++++++++++++++++++
 qobject/Makefile.objs   |   2 +-
 tests/Makefile.include  |   5 +-
 6 files changed, 261 insertions(+), 124 deletions(-)
 create mode 100644 include/qapi/qmp/qlit.h
 create mode 100644 qobject/qlit.c
 create mode 100644 tests/check-qlit.c
include/qapi/qmp/qlit.h new file +54 -0
new file mode 100644
index 0000000000..2cdceb448d
@@ -0,0 +1,54 @@
+/*
+ * Copyright IBM, Corp. 2009
+ * Copyright (c) 2013, 2015, 2017 Red Hat Inc.
+ *
+ * Authors:
+ *  Anthony Liguori   <[email protected]>
+ *  Markus Armbruster <[email protected]>
+ *  Marc-André Lureau <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
+ * See the COPYING.LIB file in the top-level directory.
+ *
+ */
+#ifndef QLIT_H_
+#define QLIT_H_
+
+#include "qapi-types.h"
+#include "qobject.h"
+
+typedef struct QLitDictEntry QLitDictEntry;
+typedef struct QLitObject QLitObject;
+
+struct QLitObject {
+    int type;
+    union {
+        bool qbool;
+        int64_t qnum;
+        const char *qstr;
+        QLitDictEntry *qdict;
+        QLitObject *qlist;
+    } value;
+};
+
+struct QLitDictEntry {
+    const char *key;
+    QLitObject value;
+};
+
+#define QLIT_QNULL \
+    { .type = QTYPE_QNULL }
+#define QLIT_QBOOL(val) \
+    { .type = QTYPE_QBOOL, .value.qbool = (val) }
+#define QLIT_QNUM(val) \
+    { .type = QTYPE_QNUM, .value.qnum = (val) }
+#define QLIT_QSTR(val) \
+    { .type = QTYPE_QSTRING, .value.qstr = (val) }
+#define QLIT_QDICT(val) \
+    { .type = QTYPE_QDICT, .value.qdict = (val) }
+#define QLIT_QLIST(val) \
+    { .type = QTYPE_QLIST, .value.qlist = (val) }
+
+bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs);
+
+#endif /* QLIT_H_ */
qobject/qlit.c new file +106 -0

106 lines not on this page · raw message

tests/check-qjson.c +28 -122

281 lines not on this page · raw message

tests/check-qlit.c new file +68 -0

68 lines not on this page · raw message

qobject/Makefile.objs +1 -1
index fc8885c9a4..002d25873a 100644
@@ -1,2 +1,2 @@
-util-obj-y = qnull.o qnum.o qstring.o qdict.o qlist.o qbool.o
+util-obj-y = qnull.o qnum.o qstring.o qdict.o qlist.o qbool.o qlit.o
 util-obj-y += qjson.o qobject.o json-lexer.o json-streamer.o json-parser.o
tests/Makefile.include +4 -1
index 37c1bed683..3653c7b40a 100644
@@ -43,6 +43,8 @@ check-unit-y += tests/check-qnull$(EXESUF)
 gcov-files-check-qnull-y = qobject/qnull.c
 check-unit-y += tests/check-qjson$(EXESUF)
 gcov-files-check-qjson-y = qobject/qjson.c
+check-unit-y += tests/check-qlit$(EXESUF)
+gcov-files-check-qlit-y = qobject/qlit.c
 check-unit-y += tests/test-qobject-output-visitor$(EXESUF)
 gcov-files-test-qobject-output-visitor-y = qapi/qobject-output-visitor.c
 check-unit-y += tests/test-clone-visitor$(EXESUF)
@@ -535,7 +537,7 @@ GENERATED_FILES += tests/test-qapi-types.h tests/test-qapi-visit.h \
 
 test-obj-y = tests/check-qnum.o tests/check-qstring.o tests/check-qdict.o \
 	tests/check-qlist.o tests/check-qnull.o \
-	tests/check-qjson.o \
+	tests/check-qjson.o tests/check-qlit.o \
 	tests/test-coroutine.o tests/test-string-output-visitor.o \
 	tests/test-string-input-visitor.o tests/test-qobject-output-visitor.o \
 	tests/test-clone-visitor.o \
@@ -569,6 +571,7 @@ tests/check-qdict$(EXESUF): tests/check-qdict.o $(test-util-obj-y)
 tests/check-qlist$(EXESUF): tests/check-qlist.o $(test-util-obj-y)
 tests/check-qnull$(EXESUF): tests/check-qnull.o $(test-util-obj-y)
 tests/check-qjson$(EXESUF): tests/check-qjson.o $(test-util-obj-y)
+tests/check-qlit$(EXESUF): tests/check-qlit.o $(test-util-obj-y)
 tests/check-qom-interface$(EXESUF): tests/check-qom-interface.o $(test-qom-obj-y)
 tests/check-qom-proplist$(EXESUF): tests/check-qom-proplist.o $(test-qom-obj-y)
 
Signature · 1 line
2.14.1.146.gd35faa819
#13 lore raw

Re: [Qemu-devel] [PATCH v2 03/54] qobject: add literal qobject type

Quoted 4 lines · Marc-André Lureau

Promote LiteralQObject from tests/check-qjson.c to qobject/qlit.c, allowing to statically declare complex qobjects.

Your patch does more than that! It also

* renames the now externally visible identifiers,

* adds support for qnull and qnum,

* cleans up types (int vs. bool) and style,

* makes compare_litqobj_to_qobj() case QTYPE_QNULL and QTYPE_QSTRING more robust, and

* fixes bugs in compare_litqobj_to_qobj() case QTYPE_QDICT, QTYPE_QLIST (I think).

Squashing the renames into the code motion is tolerable, but the rest isn't, because it makes patch review harder for no benefit at all. Moreover, the commit message fails to record the changes. I noticed them only because out of an abundance of caution I checked the patch is just what it's advertised to be: code motion. Well, it isn't.

Separate patches, please!

#14 lore raw

Re: [Qemu-devel] [PATCH v2 03/54] qobject: add literal qobject type

Hi

----- Original Message -----

Quoted 15 lines
Quoted 4 lines · Marc-André Lureau

Promote LiteralQObject from tests/check-qjson.c to qobject/qlit.c, allowing to statically declare complex qobjects.

Your patch does more than that! It also

* renames the now externally visible identifiers,

* adds support for qnull and qnum,

* cleans up types (int vs. bool) and style,

Quoted 8 lines

* makes compare_litqobj_to_qobj() case QTYPE_QNULL and QTYPE_QSTRING more robust, and

* fixes bugs in compare_litqobj_to_qobj() case QTYPE_QDICT, QTYPE_QLIST (I think).

Squashing the renames into the code motion is tolerable, but the rest isn't, because it makes patch review harder for no benefit at all.

The title said "add" and in the commit message "promote", it's not just a "move".

Imho, it's best to take a fresh look at the implementation since it is no longer in tests and can be used from qemu/programs.

As such you can review the code as "new" code, and check the corresponding tests. Finally, the existing test is simply adapted to that code.

Quoted 5 lines

Moreover, the commit message fails to record the changes. I noticed them only because out of an abundance of caution I checked the patch is just what it's advertised to be: code motion. Well, it isn't.

Separate patches, please!

Sure, I can do that, I just thought it was extra overhead given my approach.

thanks

#15 lore raw

Re: [Qemu-devel] [PATCH v2 03/54] qobject: add literal qobject type

Quoted 21 lines · Marc-André Lureau

Hi

----- Original Message -----

Quoted 18 lines
Quoted 4 lines · Marc-André Lureau

Promote LiteralQObject from tests/check-qjson.c to qobject/qlit.c, allowing to statically declare complex qobjects.

Your patch does more than that! It also

* renames the now externally visible identifiers,

* adds support for qnull and qnum,

* cleans up types (int vs. bool) and style,

* makes compare_litqobj_to_qobj() case QTYPE_QNULL and QTYPE_QSTRING more robust, and

Quoted 7 lines
Quoted 5 lines

* fixes bugs in compare_litqobj_to_qobj() case QTYPE_QDICT, QTYPE_QLIST (I think).

Squashing the renames into the code motion is tolerable, but the rest isn't, because it makes patch review harder for no benefit at all.

The title said "add" and in the commit message "promote", it's not just a "move".

Yes, that's what it says, and it fooled me just fine %-}

Quoted 11 lines

Imho, it's best to take a fresh look at the implementation since it is no longer in tests and can be used from qemu/programs.

As such you can review the code as "new" code, and check the corresponding tests. Finally, the existing test is simply adapted to that code.

Quoted 5 lines

Moreover, the commit message fails to record the changes. I noticed them only because out of an abundance of caution I checked the patch is just what it's advertised to be: code motion. Well, it isn't.

Separate patches, please!

Sure, I can do that, I just thought it was extra overhead given my approach.

Thanks.

#16 lore raw

PATCH v2 4/54 qlit: add qobject_form_qlit()

In reply to Marc-André Lureau
---
 include/qapi/qmp/qlit.h |  2 ++
 qobject/qlit.c          | 37 +++++++++++++++++++++++++++++++++++++
 tests/check-qlit.c      | 26 ++++++++++++++++++++++++++
 3 files changed, 65 insertions(+)
include/qapi/qmp/qlit.h +2 -0
index 2cdceb448d..dd562b7d69 100644
@@ -51,4 +51,6 @@ struct QLitDictEntry {
 
 bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs);
 
+QObject *qobject_from_qlit(const QLitObject *qlit);
+
 #endif /* QLIT_H_ */
qobject/qlit.c +37 -0
index f4ebeb6259..5a2aa44355 100644
@@ -104,3 +104,40 @@ bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs)
 
     return false;
 }
+
+QObject *qobject_from_qlit(const QLitObject *qlit)
+{
+    int i;
+
+    switch (qlit->type) {
+    case QTYPE_QNULL:
+        return QOBJECT(qnull());
+    case QTYPE_QNUM:
+        return QOBJECT(qnum_from_int(qlit->value.qnum));
+    case QTYPE_QSTRING:
+        return QOBJECT(qstring_from_str(qlit->value.qstr));
+    case QTYPE_QDICT: {
+        QDict *qdict = qdict_new();
+        for (i = 0; qlit->value.qdict[i].value.type != QTYPE_NONE; i++) {
+            QLitDictEntry *e = &qlit->value.qdict[i];
+
+            qdict_put_obj(qdict, e->key, qobject_from_qlit(&e->value));
+        }
+        return QOBJECT(qdict);
+    }
+    case QTYPE_QLIST: {
+        QList *qlist = qlist_new();
+
+        for (i = 0; qlit->value.qlist[i].type != QTYPE_NONE; i++) {
+            qlist_append_obj(qlist, qobject_from_qlit(&qlit->value.qlist[i]));
+        }
+        return QOBJECT(qlist);
+    }
+    case QTYPE_QBOOL:
+        return QOBJECT(qbool_from_bool(qlit->value.qbool));
+    case QTYPE_NONE:
+        assert(0);
+    }
+
+    return NULL;
+}
tests/check-qlit.c +26 -0
index 5736b61ebf..f25f3d9633 100644
@@ -58,11 +58,37 @@ static void qlit_equal_qobject_test(void)
     qobject_decref(qobj);
 }
 
+static void qobject_from_qlit_test(void)
+{
+    QObject *obj, *qobj = qobject_from_qlit(&qlit);
+    QDict *qdict;
+    QList *bee;
+
+    qdict = qobject_to_qdict(qobj);
+    g_assert_cmpint(qdict_get_int(qdict, "foo"), ==, 42);
+    g_assert_cmpstr(qdict_get_str(qdict, "bar"), ==, "hello world");
+    g_assert(qobject_type(qdict_get(qdict, "baz")) == QTYPE_QNULL);
+
+    bee = qdict_get_qlist(qdict, "bee");
+    obj = qlist_pop(bee);
+    g_assert_cmpint(qnum_get_int(qobject_to_qnum(obj)), ==, 43);
+    qobject_decref(obj);
+    obj = qlist_pop(bee);
+    g_assert_cmpint(qnum_get_int(qobject_to_qnum(obj)), ==, 44);
+    qobject_decref(obj);
+    obj = qlist_pop(bee);
+    g_assert(qbool_get_bool(qobject_to_qbool(obj)));
+    qobject_decref(obj);
+
+    qobject_decref(qobj);
+}
+
 int main(int argc, char **argv)
 {
     g_test_init(&argc, &argv, NULL);
 
     g_test_add_func("/qlit/equal_qobject", qlit_equal_qobject_test);
+    g_test_add_func("/qlit/qobject_from_qlit", qobject_from_qlit_test);
 
     return g_test_run();
 }
Signature · 1 line
2.14.1.146.gd35faa819
#17 lore raw

Re: [Qemu-devel] [PATCH v2 04/54] qlit: add qobject_form_qlit()

Typo in the subject: s/form/from/

Quoted 31 lines · Marc-André Lureau
---
 include/qapi/qmp/qlit.h |  2 ++
 qobject/qlit.c          | 37 +++++++++++++++++++++++++++++++++++++
 tests/check-qlit.c      | 26 ++++++++++++++++++++++++++
 3 files changed, 65 insertions(+)
include/qapi/qmp/qlit.h +2 -0
index 2cdceb448d..dd562b7d69 100644
@@ -51,4 +51,6 @@ struct QLitDictEntry {
 
 bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs);
 
+QObject *qobject_from_qlit(const QLitObject *qlit);
+
 #endif /* QLIT_H_ */
qobject/qlit.c +5 -0
index f4ebeb6259..5a2aa44355 100644
@@ -104,3 +104,40 @@ bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs)
 
     return false;
 }
+
+QObject *qobject_from_qlit(const QLitObject *qlit)
+{
+    int i;
+

qobject/qlit.c bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs) · line 121

Quoted 10 lines
qobject/qlit.c +10 -0
+    switch (qlit->type) {
+    case QTYPE_QNULL:
+        return QOBJECT(qnull());
+    case QTYPE_QNUM:
+        return QOBJECT(qnum_from_int(qlit->value.qnum));
+    case QTYPE_QSTRING:
+        return QOBJECT(qstring_from_str(qlit->value.qstr));
+    case QTYPE_QDICT: {
+        QDict *qdict = qdict_new();
+        for (i = 0; qlit->value.qdict[i].value.type != QTYPE_NONE; i++) {

Terser:

           for (i = 0; qlit->value.qdict[i].key; i++) {

qobject/qlit.c bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs) · line 131

Quoted 10 lines
qobject/qlit.c +10 -0
+            QLitDictEntry *e = &qlit->value.qdict[i];
+
+            qdict_put_obj(qdict, e->key, qobject_from_qlit(&e->value));
+        }
+        return QOBJECT(qdict);
+    }
+    case QTYPE_QLIST: {
+        QList *qlist = qlist_new();
+
+        for (i = 0; qlit->value.qlist[i].type != QTYPE_NONE; i++) {

Could omit != QTYPE_NONE, because we're very much relying on QTYPE_NONE being zero anyway. Matter of taste.

qobject/qlit.c bool qlit_equal_qobject(QLitObject *lhs, QObject *rhs) · line 138

Quoted 7 lines
qobject/qlit.c +7 -0
+            qlist_append_obj(qlist, qobject_from_qlit(&qlit->value.qlist[i]));
+        }
+        return QOBJECT(qlist);
+    }
+    case QTYPE_QBOOL:
+        return QOBJECT(qbool_from_bool(qlit->value.qbool));
+    case QTYPE_NONE:

Make that

default:

to remove all doubt.

Quoted 47 lines
qobject/qlit.c +5 -0
+        assert(0);
+    }
+
+    return NULL;
+}
tests/check-qlit.c +26 -0
index 5736b61ebf..f25f3d9633 100644
@@ -58,11 +58,37 @@ static void qlit_equal_qobject_test(void)
     qobject_decref(qobj);
 }
 
+static void qobject_from_qlit_test(void)
+{
+    QObject *obj, *qobj = qobject_from_qlit(&qlit);
+    QDict *qdict;
+    QList *bee;
+
+    qdict = qobject_to_qdict(qobj);
+    g_assert_cmpint(qdict_get_int(qdict, "foo"), ==, 42);
+    g_assert_cmpstr(qdict_get_str(qdict, "bar"), ==, "hello world");
+    g_assert(qobject_type(qdict_get(qdict, "baz")) == QTYPE_QNULL);
+
+    bee = qdict_get_qlist(qdict, "bee");
+    obj = qlist_pop(bee);
+    g_assert_cmpint(qnum_get_int(qobject_to_qnum(obj)), ==, 43);
+    qobject_decref(obj);
+    obj = qlist_pop(bee);
+    g_assert_cmpint(qnum_get_int(qobject_to_qnum(obj)), ==, 44);
+    qobject_decref(obj);
+    obj = qlist_pop(bee);
+    g_assert(qbool_get_bool(qobject_to_qbool(obj)));
+    qobject_decref(obj);
+
+    qobject_decref(qobj);
+}
+
 int main(int argc, char **argv)
 {
     g_test_init(&argc, &argv, NULL);
 
     g_test_add_func("/qlit/equal_qobject", qlit_equal_qobject_test);
+    g_test_add_func("/qlit/qobject_from_qlit", qobject_from_qlit_test);
 
     return g_test_run();
 }
#18 lore raw

PATCH v2 5/54 qapi: generate a literal qobject for introspection

In reply to Marc-André Lureau

Replace the generated json string with a literal qobject. The later is easier to deal with, at run time as well as compile time: adding #if conditionals will be easier than in a json string.

---
 scripts/qapi-introspect.py         | 91 ++++++++++++++++++++++----------------
 monitor.c                          |  2 +-
 tests/test-qobject-input-visitor.c | 11 +++--
 docs/devel/qapi-code-gen.txt       | 29 +++++++-----
 4 files changed, 80 insertions(+), 53 deletions(-)
scripts/qapi-introspect.py +53 -38
index 032bcea491..1b96926fa7 100644
@@ -12,72 +12,80 @@
 from qapi import *
 
 
-# Caveman's json.dumps() replacement (we're stuck at Python 2.4)
-# TODO try to use json.dumps() once we get unstuck
-def to_json(obj, level=0):
+def to_c_string(s):
+    return '"' + s.replace('\\', r'\\').replace('"', r'\"') + '"'
+
+
+def to_qlit(obj, level=0, first_indent=True):
+
+    def indent(level):
+        return level * 4 * ' '
+
+    ret = ''
+    if first_indent:
+        ret += indent(level)
     if obj is None:
-        ret = 'null'
+        ret += 'QLIT_QNULL'
     elif isinstance(obj, str):
-        ret = '"' + obj.replace('"', r'\"') + '"'
+        ret += 'QLIT_QSTR(' + to_c_string(obj) + ')'
     elif isinstance(obj, list):
-        elts = [to_json(elt, level + 1)
+        elts = [to_qlit(elt, level + 1)
                 for elt in obj]
-        ret = '[' + ', '.join(elts) + ']'
+        elts.append(indent(level + 1) + "{}")
+        ret += 'QLIT_QLIST(((QLitObject[]) {\n'
+        ret += ',\n'.join(elts) + '\n'
+        ret += indent(level) + '}))'
     elif isinstance(obj, dict):
-        elts = ['"%s": %s' % (key.replace('"', r'\"'),
-                              to_json(obj[key], level + 1))
-                for key in sorted(obj.keys())]
-        ret = '{' + ', '.join(elts) + '}'
+        elts = []
+        for key, value in sorted(obj.iteritems()):
+            elts.append(indent(level + 1) + '{ %s, %s }' %
+                        (to_c_string(key), to_qlit(value, level + 1, False)))
+        elts.append(indent(level + 1) + '{}')
+        ret += 'QLIT_QDICT(((QLitDictEntry[]) {\n'
+        ret += ',\n'.join(elts) + '\n'
+        ret += indent(level) + '}))'
     else:
         assert False                # not implemented
-    if level == 1:
-        ret = '\n' + ret
     return ret
 
 
-def to_c_string(string):
-    return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
-
-
 class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
     def __init__(self, unmask):
         self._unmask = unmask
         self.defn = None
         self.decl = None
         self._schema = None
-        self._jsons = None
+        self._qlits = None
         self._used_types = None
         self._name_map = None
 
     def visit_begin(self, schema):
         self._schema = schema
-        self._jsons = []
+        self._qlits = []
         self._used_types = []
         self._name_map = {}
 
     def visit_end(self):
         # visit the types that are actually used
-        jsons = self._jsons
-        self._jsons = []
+        qlits = self._qlits
+        self._qlits = []
         for typ in self._used_types:
             typ.visit(self)
         # generate C
         # TODO can generate awfully long lines
-        jsons.extend(self._jsons)
-        name = c_name(prefix, protect=False) + 'qmp_schema_json'
+        qlits.extend(self._qlits)
+        name = c_name(prefix, protect=False) + 'qmp_schema_qlit'
         self.decl = mcgen('''
-extern const char %(c_name)s[];
+extern const QLitObject %(c_name)s;
 ''',
                           c_name=c_name(name))
-        lines = to_json(jsons).split('\n')
-        c_string = '\n    '.join([to_c_string(line) for line in lines])
         self.defn = mcgen('''
-const char %(c_name)s[] = %(c_string)s;
+const QLitObject %(c_name)s = %(c_string)s;
 ''',
                           c_name=c_name(name),
-                          c_string=c_string)
+                          c_string=to_qlit(qlits))
         self._schema = None
-        self._jsons = None
+        self._qlits = None
         self._used_types = None
         self._name_map = None
 
@@ -111,12 +119,12 @@ const char %(c_name)s[] = %(c_string)s;
             return '[' + self._use_type(typ.element_type) + ']'
         return self._name(typ.name)
 
-    def _gen_json(self, name, mtype, obj):
+    def _gen_qlit(self, name, mtype, obj):
         if mtype not in ('command', 'event', 'builtin', 'array'):
             name = self._name(name)
         obj['name'] = name
         obj['meta-type'] = mtype
-        self._jsons.append(obj)
+        self._qlits.append(obj)
 
     def _gen_member(self, member):
         ret = {'name': member.name, 'type': self._use_type(member.type)}
@@ -132,24 +140,24 @@ const char %(c_name)s[] = %(c_string)s;
         return {'case': variant.name, 'type': self._use_type(variant.type)}
 
     def visit_builtin_type(self, name, info, json_type):
-        self._gen_json(name, 'builtin', {'json-type': json_type})
+        self._gen_qlit(name, 'builtin', {'json-type': json_type})
 
     def visit_enum_type(self, name, info, values, prefix):
-        self._gen_json(name, 'enum', {'values': values})
+        self._gen_qlit(name, 'enum', {'values': values})
 
     def visit_array_type(self, name, info, element_type):
         element = self._use_type(element_type)
-        self._gen_json('[' + element + ']', 'array', {'element-type': element})
+        self._gen_qlit('[' + element + ']', 'array', {'element-type': element})
 
     def visit_object_type_flat(self, name, info, members, variants):
         obj = {'members': [self._gen_member(m) for m in members]}
         if variants:
             obj.update(self._gen_variants(variants.tag_member.name,
                                           variants.variants))
-        self._gen_json(name, 'object', obj)
+        self._gen_qlit(name, 'object', obj)
 
     def visit_alternate_type(self, name, info, variants):
-        self._gen_json(name, 'alternate',
+        self._gen_qlit(name, 'alternate',
                        {'members': [{'type': self._use_type(m.type)}
                                     for m in variants.variants]})
 
@@ -157,13 +165,13 @@ const char %(c_name)s[] = %(c_string)s;
                       gen, success_response, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
         ret_type = ret_type or self._schema.the_empty_object_type
-        self._gen_json(name, 'command',
+        self._gen_qlit(name, 'command',
                        {'arg-type': self._use_type(arg_type),
                         'ret-type': self._use_type(ret_type)})
 
     def visit_event(self, name, info, arg_type, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
-        self._gen_json(name, 'event', {'arg-type': self._use_type(arg_type)})
+        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)})
 
 # Debugging aid: unmask QAPI schema's type names
 # We normally mask them, because they're not QMP wire ABI
@@ -205,11 +213,18 @@ h_comment = '''
 
 fdef.write(mcgen('''
 #include "qemu/osdep.h"
+#include "qapi/qmp/qlit.h"
 #include "%(prefix)sqmp-introspect.h"
 
 ''',
                  prefix=prefix))
 
+fdecl.write(mcgen('''
+#include "qemu/osdep.h"
+#include "qapi/qmp/qlit.h"
+
+'''))
+
 schema = QAPISchema(input_file)
 gen = QAPISchemaGenIntrospectVisitor(opt_unmask)
 schema.visit(gen)
monitor.c +1 -1
index e0f880107f..14c27d4b6f 100644
@@ -953,7 +953,7 @@ EventInfoList *qmp_query_events(Error **errp)
 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
                                  Error **errp)
 {
-    *ret_data = qobject_from_json(qmp_schema_json, &error_abort);
+    *ret_data = qobject_from_qlit(&qmp_schema_qlit);
 }
 
 /*
tests/test-qobject-input-visitor.c +7 -4
index bcf02617dc..bdd00f6bd8 100644
@@ -1247,24 +1247,27 @@ static void test_visitor_in_fail_alternate(TestInputVisitorData *data,
 }
 
 static void do_test_visitor_in_qmp_introspect(TestInputVisitorData *data,
-                                              const char *schema_json)
+                                              const QLitObject *qlit)
 {
     SchemaInfoList *schema = NULL;
+    QObject *obj = qobject_from_qlit(qlit);
     Visitor *v;
 
-    v = visitor_input_test_init_raw(data, schema_json);
+    v = qobject_input_visitor_new(obj);
 
     visit_type_SchemaInfoList(v, NULL, &schema, &error_abort);
     g_assert(schema);
 
     qapi_free_SchemaInfoList(schema);
+    qobject_decref(obj);
+    visit_free(v);
 }
 
 static void test_visitor_in_qmp_introspect(TestInputVisitorData *data,
                                            const void *unused)
 {
-    do_test_visitor_in_qmp_introspect(data, test_qmp_schema_json);
-    do_test_visitor_in_qmp_introspect(data, qmp_schema_json);
+    do_test_visitor_in_qmp_introspect(data, &test_qmp_schema_qlit);
+    do_test_visitor_in_qmp_introspect(data, &qmp_schema_qlit);
 }
 
 int main(int argc, char **argv)
docs/devel/qapi-code-gen.txt +19 -10
index 9903ac4c19..b653e86bff 100644
@@ -1295,18 +1295,27 @@ Example:
     #ifndef EXAMPLE_QMP_INTROSPECT_H
     #define EXAMPLE_QMP_INTROSPECT_H
 
-    extern const char example_qmp_schema_json[];
+    extern const QLitObject qmp_schema_qlit;
 
     #endif
     $ cat qapi-generated/example-qmp-introspect.c
 [Uninteresting stuff omitted...]
 
-    const char example_qmp_schema_json[] = "["
-        "{\"arg-type\": \"0\", \"meta-type\": \"event\", \"name\": \"MY_EVENT\"}, "
-        "{\"arg-type\": \"1\", \"meta-type\": \"command\", \"name\": \"my-command\", \"ret-type\": \"2\"}, "
-        "{\"members\": [], \"meta-type\": \"object\", \"name\": \"0\"}, "
-        "{\"members\": [{\"name\": \"arg1\", \"type\": \"[2]\"}], \"meta-type\": \"object\", \"name\": \"1\"}, "
-        "{\"members\": [{\"name\": \"integer\", \"type\": \"int\"}, {\"default\": null, \"name\": \"string\", \"type\": \"str\"}], \"meta-type\": \"object\", \"name\": \"2\"}, "
-        "{\"element-type\": \"2\", \"meta-type\": \"array\", \"name\": \"[2]\"}, "
-        "{\"json-type\": \"int\", \"meta-type\": \"builtin\", \"name\": \"int\"}, "
-        "{\"json-type\": \"string\", \"meta-type\": \"builtin\", \"name\": \"str\"}]";
+    const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
+        QLIT_QDICT(((QLitDictEntry[]) {
+            { "arg-type", QLIT_QSTR("0") },
+            { "meta-type", QLIT_QSTR("event") },
+            { "name", QLIT_QSTR("Event") },
+            { }
+        })),
+        QLIT_QDICT(((QLitDictEntry[]) {
+            { "members", QLIT_QLIST(((QLitObject[]) {
+                { }
+            })) },
+            { "meta-type", QLIT_QSTR("object") },
+            { "name", QLIT_QSTR("0") },
+            { }
+        })),
+        ...
+        { }
+    }));
Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 5/54
#19 lore raw

Re: [Qemu-devel] [PATCH v2 05/54] qapi: generate a literal qobject for introspection

Quoted 18 lines · Marc-André Lureau

Replace the generated json string with a literal qobject. The later is easier to deal with, at run time as well as compile time: adding #if conditionals will be easier than in a json string.

---
 scripts/qapi-introspect.py         | 91 ++++++++++++++++++++++----------------
 monitor.c                          |  2 +-
 tests/test-qobject-input-visitor.c | 11 +++--
 docs/devel/qapi-code-gen.txt       | 29 +++++++-----
 4 files changed, 80 insertions(+), 53 deletions(-)
scripts/qapi-introspect.py +0 -0
index 032bcea491..1b96926fa7 100644
@@ -12,72 +12,80 @@
 from qapi import *

scripts/qapi-introspect.py line 19

Quoted 10 lines
scripts/qapi-introspect.py +5 -3
 
 
-# Caveman's json.dumps() replacement (we're stuck at Python 2.4)
-# TODO try to use json.dumps() once we get unstuck
-def to_json(obj, level=0):
+def to_c_string(s):
+    return '"' + s.replace('\\', r'\\').replace('"', r'\"') + '"'
+
+
+def to_qlit(obj, level=0, first_indent=True):

I still think suppress_first_indent=False would be nicer, but it's not worth arguing now.

Quoted 30 lines
scripts/qapi-introspect.py +17 -8
+
+    def indent(level):
+        return level * 4 * ' '
+
+    ret = ''
+    if first_indent:
+        ret += indent(level)
     if obj is None:
-        ret = 'null'
+        ret += 'QLIT_QNULL'
     elif isinstance(obj, str):
-        ret = '"' + obj.replace('"', r'\"') + '"'
+        ret += 'QLIT_QSTR(' + to_c_string(obj) + ')'
     elif isinstance(obj, list):
-        elts = [to_json(elt, level + 1)
+        elts = [to_qlit(elt, level + 1)
                 for elt in obj]
-        ret = '[' + ', '.join(elts) + ']'
+        elts.append(indent(level + 1) + "{}")
+        ret += 'QLIT_QLIST(((QLitObject[]) {\n'
+        ret += ',\n'.join(elts) + '\n'
+        ret += indent(level) + '}))'
     elif isinstance(obj, dict):
-        elts = ['"%s": %s' % (key.replace('"', r'\"'),
-                              to_json(obj[key], level + 1))
-                for key in sorted(obj.keys())]
-        ret = '{' + ', '.join(elts) + '}'
+        elts = []
+        for key, value in sorted(obj.iteritems()):
+            elts.append(indent(level + 1) + '{ %s, %s }' %

scripts/qapi-introspect.py line 49

Quoted 10 lines
scripts/qapi-introspect.py +5 -2
+                        (to_c_string(key), to_qlit(value, level + 1, False)))
+        elts.append(indent(level + 1) + '{}')
+        ret += 'QLIT_QDICT(((QLitDictEntry[]) {\n'
+        ret += ',\n'.join(elts) + '\n'
+        ret += indent(level) + '}))'
     else:
         assert False                # not implemented
-    if level == 1:
-        ret = '\n' + ret
     return ret

Note to self: is there simple a way to get rid of the extra pair of parenthesis in QLIT_QLIST(( ... )) and QLIT_QDICT(( ... ))?

scripts/qapi-introspect.py line 41

Quoted 6 lines
scripts/qapi-introspect.py +0 -4
-def to_c_string(string):
-    return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
-
-

Let's not move to_c_string() without need.

Quoted 213 lines
scripts/qapi-introspect.py +26 -21
 class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
     def __init__(self, unmask):
         self._unmask = unmask
         self.defn = None
         self.decl = None
         self._schema = None
-        self._jsons = None
+        self._qlits = None
         self._used_types = None
         self._name_map = None
 
     def visit_begin(self, schema):
         self._schema = schema
-        self._jsons = []
+        self._qlits = []
         self._used_types = []
         self._name_map = {}
 
     def visit_end(self):
         # visit the types that are actually used
-        jsons = self._jsons
-        self._jsons = []
+        qlits = self._qlits
+        self._qlits = []
         for typ in self._used_types:
             typ.visit(self)
         # generate C
         # TODO can generate awfully long lines
-        jsons.extend(self._jsons)
-        name = c_name(prefix, protect=False) + 'qmp_schema_json'
+        qlits.extend(self._qlits)
+        name = c_name(prefix, protect=False) + 'qmp_schema_qlit'
         self.decl = mcgen('''
-extern const char %(c_name)s[];
+extern const QLitObject %(c_name)s;
 ''',
                           c_name=c_name(name))
-        lines = to_json(jsons).split('\n')
-        c_string = '\n    '.join([to_c_string(line) for line in lines])
         self.defn = mcgen('''
-const char %(c_name)s[] = %(c_string)s;
+const QLitObject %(c_name)s = %(c_string)s;
 ''',
                           c_name=c_name(name),
-                          c_string=c_string)
+                          c_string=to_qlit(qlits))
         self._schema = None
-        self._jsons = None
+        self._qlits = None
         self._used_types = None
         self._name_map = None
 
@@ -111,12 +119,12 @@ const char %(c_name)s[] = %(c_string)s;
             return '[' + self._use_type(typ.element_type) + ']'
         return self._name(typ.name)
 
-    def _gen_json(self, name, mtype, obj):
+    def _gen_qlit(self, name, mtype, obj):
         if mtype not in ('command', 'event', 'builtin', 'array'):
             name = self._name(name)
         obj['name'] = name
         obj['meta-type'] = mtype
-        self._jsons.append(obj)
+        self._qlits.append(obj)
 
     def _gen_member(self, member):
         ret = {'name': member.name, 'type': self._use_type(member.type)}
@@ -132,24 +140,24 @@ const char %(c_name)s[] = %(c_string)s;
         return {'case': variant.name, 'type': self._use_type(variant.type)}
 
     def visit_builtin_type(self, name, info, json_type):
-        self._gen_json(name, 'builtin', {'json-type': json_type})
+        self._gen_qlit(name, 'builtin', {'json-type': json_type})
 
     def visit_enum_type(self, name, info, values, prefix):
-        self._gen_json(name, 'enum', {'values': values})
+        self._gen_qlit(name, 'enum', {'values': values})
 
     def visit_array_type(self, name, info, element_type):
         element = self._use_type(element_type)
-        self._gen_json('[' + element + ']', 'array', {'element-type': element})
+        self._gen_qlit('[' + element + ']', 'array', {'element-type': element})
 
     def visit_object_type_flat(self, name, info, members, variants):
         obj = {'members': [self._gen_member(m) for m in members]}
         if variants:
             obj.update(self._gen_variants(variants.tag_member.name,
                                           variants.variants))
-        self._gen_json(name, 'object', obj)
+        self._gen_qlit(name, 'object', obj)
 
     def visit_alternate_type(self, name, info, variants):
-        self._gen_json(name, 'alternate',
+        self._gen_qlit(name, 'alternate',
                        {'members': [{'type': self._use_type(m.type)}
                                     for m in variants.variants]})
 
@@ -157,13 +165,13 @@ const char %(c_name)s[] = %(c_string)s;
                       gen, success_response, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
         ret_type = ret_type or self._schema.the_empty_object_type
-        self._gen_json(name, 'command',
+        self._gen_qlit(name, 'command',
                        {'arg-type': self._use_type(arg_type),
                         'ret-type': self._use_type(ret_type)})
 
     def visit_event(self, name, info, arg_type, boxed):
         arg_type = arg_type or self._schema.the_empty_object_type
-        self._gen_json(name, 'event', {'arg-type': self._use_type(arg_type)})
+        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)})
 
 # Debugging aid: unmask QAPI schema's type names
 # We normally mask them, because they're not QMP wire ABI
@@ -205,11 +213,18 @@ h_comment = '''
 
 fdef.write(mcgen('''
 #include "qemu/osdep.h"
+#include "qapi/qmp/qlit.h"
 #include "%(prefix)sqmp-introspect.h"
 
 ''',
                  prefix=prefix))
 
+fdecl.write(mcgen('''
+#include "qemu/osdep.h"
+#include "qapi/qmp/qlit.h"
+
+'''))
+
 schema = QAPISchema(input_file)
 gen = QAPISchemaGenIntrospectVisitor(opt_unmask)
 schema.visit(gen)
monitor.c +1 -1
index e0f880107f..14c27d4b6f 100644
@@ -953,7 +953,7 @@ EventInfoList *qmp_query_events(Error **errp)
 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
                                  Error **errp)
 {
-    *ret_data = qobject_from_json(qmp_schema_json, &error_abort);
+    *ret_data = qobject_from_qlit(&qmp_schema_qlit);
 }
 
 /*
tests/test-qobject-input-visitor.c +7 -4
index bcf02617dc..bdd00f6bd8 100644
@@ -1247,24 +1247,27 @@ static void test_visitor_in_fail_alternate(TestInputVisitorData *data,
 }
 
 static void do_test_visitor_in_qmp_introspect(TestInputVisitorData *data,
-                                              const char *schema_json)
+                                              const QLitObject *qlit)
 {
     SchemaInfoList *schema = NULL;
+    QObject *obj = qobject_from_qlit(qlit);
     Visitor *v;
 
-    v = visitor_input_test_init_raw(data, schema_json);
+    v = qobject_input_visitor_new(obj);
 
     visit_type_SchemaInfoList(v, NULL, &schema, &error_abort);
     g_assert(schema);
 
     qapi_free_SchemaInfoList(schema);
+    qobject_decref(obj);
+    visit_free(v);
 }
 
 static void test_visitor_in_qmp_introspect(TestInputVisitorData *data,
                                            const void *unused)
 {
-    do_test_visitor_in_qmp_introspect(data, test_qmp_schema_json);
-    do_test_visitor_in_qmp_introspect(data, qmp_schema_json);
+    do_test_visitor_in_qmp_introspect(data, &test_qmp_schema_qlit);
+    do_test_visitor_in_qmp_introspect(data, &qmp_schema_qlit);
 }
 
 int main(int argc, char **argv)
docs/devel/qapi-code-gen.txt +9 -10
index 9903ac4c19..b653e86bff 100644
@@ -1295,18 +1295,27 @@ Example:
     #ifndef EXAMPLE_QMP_INTROSPECT_H
     #define EXAMPLE_QMP_INTROSPECT_H
 
-    extern const char example_qmp_schema_json[];
+    extern const QLitObject qmp_schema_qlit;
 
     #endif
     $ cat qapi-generated/example-qmp-introspect.c
 [Uninteresting stuff omitted...]
 
-    const char example_qmp_schema_json[] = "["
-        "{\"arg-type\": \"0\", \"meta-type\": \"event\", \"name\": \"MY_EVENT\"}, "
-        "{\"arg-type\": \"1\", \"meta-type\": \"command\", \"name\": \"my-command\", \"ret-type\": \"2\"}, "
-        "{\"members\": [], \"meta-type\": \"object\", \"name\": \"0\"}, "
-        "{\"members\": [{\"name\": \"arg1\", \"type\": \"[2]\"}], \"meta-type\": \"object\", \"name\": \"1\"}, "
-        "{\"members\": [{\"name\": \"integer\", \"type\": \"int\"}, {\"default\": null, \"name\": \"string\", \"type\": \"str\"}], \"meta-type\": \"object\", \"name\": \"2\"}, "
-        "{\"element-type\": \"2\", \"meta-type\": \"array\", \"name\": \"[2]\"}, "
-        "{\"json-type\": \"int\", \"meta-type\": \"builtin\", \"name\": \"int\"}, "
-        "{\"json-type\": \"string\", \"meta-type\": \"builtin\", \"name\": \"str\"}]";
+    const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
+        QLIT_QDICT(((QLitDictEntry[]) {
+            { "arg-type", QLIT_QSTR("0") },
+            { "meta-type", QLIT_QSTR("event") },
+            { "name", QLIT_QSTR("Event") },
+            { }
+        })),
+        QLIT_QDICT(((QLitDictEntry[]) {

docs/devel/qapi-code-gen.txt Example: · line 1321

Quoted 10 lines
docs/devel/qapi-code-gen.txt +10 -0
+            { "members", QLIT_QLIST(((QLitObject[]) {
+                { }
+            })) },
+            { "meta-type", QLIT_QSTR("object") },
+            { "name", QLIT_QSTR("0") },
+            { }
+        })),
+        ...
+        { }
+    }));

Preferably without the to_c_string() move:

#20 lore raw

PATCH v2 6/54 qapi: introduce qapi_enum_lookup()

In reply to Marc-André Lureau

This will help with the introduction of a new structure to handle enum lookup.

---
 include/qapi/util.h                 |  2 +
 backends/hostmem.c                  |  3 +-
 block/backup.c                      |  3 +-
 block/file-posix.c                  |  5 ++-
 block/file-win32.c                  |  2 +-
 block/gluster.c                     |  4 +-
 block/iscsi.c                       |  3 +-
 block/nfs.c                         |  3 +-
 block/qcow2.c                       |  5 ++-
 block/qed.c                         |  3 +-
 block/rbd.c                         |  3 +-
 block/sheepdog.c                    |  3 +-
 blockdev.c                          |  6 ++-
 blockjob.c                          |  9 +++--
 chardev/char.c                      |  7 +++-
 crypto/block-luks.c                 | 17 ++++++---
 crypto/block.c                      |  5 ++-
 crypto/cipher-afalg.c               |  2 +-
 crypto/cipher-builtin.c             |  8 ++--
 crypto/cipher-gcrypt.c              |  4 +-
 crypto/cipher-nettle.c              |  8 ++--
 crypto/cipher.c                     |  1 +
 crypto/hmac-gcrypt.c                |  2 +-
 crypto/hmac-glib.c                  |  3 +-
 crypto/hmac-nettle.c                |  3 +-
 crypto/pbkdf-gcrypt.c               |  3 +-
 crypto/pbkdf-nettle.c               |  4 +-
 hmp.c                               | 74 +++++++++++++++++++++++--------------
 hw/block/fdc.c                      |  9 +++--
 hw/char/escc.c                      |  3 +-
 hw/core/qdev-properties.c           |  9 +++--
 hw/input/virtio-input-hid.c         |  5 ++-
 migration/colo-failover.c           |  6 ++-
 migration/colo.c                    | 17 +++++----
 migration/global_state.c            |  2 +-
 monitor.c                           | 24 +++++++-----
 net/net.c                           |  5 ++-
 qapi/qapi-util.c                    |  7 ++++
 qapi/qmp-dispatch.c                 |  4 +-
 tests/test-qobject-output-visitor.c |  4 +-
 tests/test-string-output-visitor.c  |  6 ++-
 tpm.c                               |  4 +-
 ui/input.c                          | 13 ++++---
 ui/vnc.c                            |  8 ++--
 vl.c                                |  7 ++--
 45 files changed, 206 insertions(+), 122 deletions(-)
include/qapi/util.h +2 -0
index 7436ed815c..60733b6a80 100644
@@ -11,6 +11,8 @@
 #ifndef QAPI_UTIL_H
 #define QAPI_UTIL_H
 
+const char *qapi_enum_lookup(const char * const lookup[], int val);
+
 int qapi_enum_parse(const char * const lookup[], const char *buf,
                     int max, int def, Error **errp);
 
backends/hostmem.c +2 -1
index 4606b73849..c4f795475c 100644
@@ -13,6 +13,7 @@
 #include "sysemu/hostmem.h"
 #include "hw/boards.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qapi/visitor.h"
 #include "qapi-types.h"
 #include "qapi-visit.h"
@@ -304,7 +305,7 @@ host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)
             return;
         } else if (maxnode == 0 && backend->policy != MPOL_DEFAULT) {
             error_setg(errp, "host-nodes must be set for policy %s",
-                       HostMemPolicy_lookup[backend->policy]);
+                qapi_enum_lookup(HostMemPolicy_lookup, backend->policy));
             return;
         }
 
block/backup.c +2 -1
index 504a089150..a700cc0315 100644
@@ -19,6 +19,7 @@
 #include "block/blockjob_int.h"
 #include "block/block_backup.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qapi/qmp/qerror.h"
 #include "qemu/ratelimit.h"
 #include "qemu/cutils.h"
@@ -596,7 +597,7 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
         error_setg(errp,
                    "a sync_bitmap was provided to backup_run, "
                    "but received an incompatible sync_mode (%s)",
-                   MirrorSyncMode_lookup[sync_mode]);
+                   qapi_enum_lookup(MirrorSyncMode_lookup, sync_mode));
         return NULL;
     }
 
block/file-posix.c +3 -2
index cb3bfce147..48200aef0b 100644
@@ -1725,7 +1725,7 @@ static int raw_regular_truncate(int fd, int64_t offset, PreallocMode prealloc,
     default:
         result = -ENOTSUP;
         error_setg(errp, "Unsupported preallocation mode: %s",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return result;
     }
 
@@ -1760,7 +1760,8 @@ static int raw_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Preallocation mode '%s' unsupported for this "
-                   "non-regular file", PreallocMode_lookup[prealloc]);
+                   "non-regular file", qapi_enum_lookup(PreallocMode_lookup,
+                                                        prealloc));
         return -ENOTSUP;
     }
 
block/file-win32.c +1 -1
index 4706335cff..2f3975f040 100644
@@ -470,7 +470,7 @@ static int raw_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(reallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/gluster.c +2 -2
index 3064a45047..934f459014 100644
@@ -1050,7 +1050,7 @@ static int qemu_gluster_create(const char *filename,
     default:
         ret = -EINVAL;
         error_setg(errp, "Unsupported preallocation mode: %s",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         break;
     }
 
@@ -1102,7 +1102,7 @@ static int qemu_gluster_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/iscsi.c +2 -1
index d557c99668..5c1870340b 100644
@@ -39,6 +39,7 @@
 #include "qemu/uuid.h"
 #include "qmp-commands.h"
 #include "qapi/qmp/qstring.h"
+#include "qapi/util.h"
 #include "crypto/secret.h"
 
 #include <iscsi/iscsi.h>
@@ -2087,7 +2088,7 @@ static int iscsi_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/nfs.c +2 -1
index bec16b72a6..953728ae31 100644
@@ -40,6 +40,7 @@
 #include "qapi-visit.h"
 #include "qapi/qobject-input-visitor.h"
 #include "qapi/qobject-output-visitor.h"
+#include "qapi/util.h"
 #include <nfsc/libnfs.h>
 
 
@@ -772,7 +773,7 @@ static int nfs_file_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/qcow2.c +3 -2
index 40ba26c111..45b0579caa 100644
@@ -2732,7 +2732,8 @@ static int qcow2_create2(const char *filename, int64_t total_size,
         int64_t prealloc_size =
             qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order);
         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort);
-        qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
+        qemu_opt_set(opts, BLOCK_OPT_PREALLOC,
+                     qapi_enum_lookup(PreallocMode_lookup, prealloc),
                      &error_abort);
     }
 
@@ -3098,7 +3099,7 @@ static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
         prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
     {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/qed.c +2 -1
index dc54bf4a93..756fcb85a7 100644
@@ -19,6 +19,7 @@
 #include "trace.h"
 #include "qed.h"
 #include "qapi/qmp/qerror.h"
+#include "qapi/util.h"
 #include "sysemu/block-backend.h"
 
 static int bdrv_qed_probe(const uint8_t *buf, int buf_size,
@@ -1399,7 +1400,7 @@ static int bdrv_qed_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/rbd.c +2 -1
index 9c3aa638e7..09f8d18d1b 100644
@@ -21,6 +21,7 @@
 #include "qemu/cutils.h"
 #include "qapi/qmp/qstring.h"
 #include "qapi/qmp/qjson.h"
+#include "qapi/util.h"
 
 /*
  * When specifying the image filename use:
@@ -944,7 +945,7 @@ static int qemu_rbd_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/sheepdog.c +2 -1
index abb2e79065..69d49fb720 100644
@@ -17,6 +17,7 @@
 #include "qapi/error.h"
 #include "qapi/qmp/qdict.h"
 #include "qapi/qobject-input-visitor.h"
+#include "qapi/util.h"
 #include "qemu/uri.h"
 #include "qemu/error-report.h"
 #include "qemu/sockets.h"
@@ -2176,7 +2177,7 @@ static int sd_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   PreallocMode_lookup[prealloc]);
+                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
blockdev.c +4 -2
index 02cd69bc21..6a067e81bf 100644
@@ -1468,8 +1468,10 @@ static int action_check_completion_mode(BlkActionState *s, Error **errp)
         error_setg(errp,
                    "Action '%s' does not support Transaction property "
                    "completion-mode = %s",
-                   TransactionActionKind_lookup[s->action->type],
-                   ActionCompletionMode_lookup[s->txn_props->completion_mode]);
+                   qapi_enum_lookup(TransactionActionKind_lookup,
+                                    s->action->type),
+                   qapi_enum_lookup(ActionCompletionMode_lookup,
+                                    s->txn_props->completion_mode));
         return -1;
     }
     return 0;
blockjob.c +6 -3
index 70a78188b7..fca71123e0 100644
@@ -31,6 +31,7 @@
 #include "sysemu/block-backend.h"
 #include "qapi/qmp/qerror.h"
 #include "qapi/qmp/qjson.h"
+#include "qapi/util.h"
 #include "qemu/coroutine.h"
 #include "qemu/id.h"
 #include "qmp-commands.h"
@@ -208,7 +209,8 @@ static char *child_job_get_parent_desc(BdrvChild *c)
 {
     BlockJob *job = c->opaque;
     return g_strdup_printf("%s job '%s'",
-                           BlockJobType_lookup[job->driver->job_type],
+                           qapi_enum_lookup(BlockJobType_lookup,
+                                            job->driver->job_type),
                            job->id);
 }
 
@@ -553,7 +555,8 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
         return NULL;
     }
     info = g_new0(BlockJobInfo, 1);
-    info->type      = g_strdup(BlockJobType_lookup[job->driver->job_type]);
+    info->type      = g_strdup(qapi_enum_lookup(BlockJobType_lookup,
+                                                job->driver->job_type));
     info->device    = g_strdup(job->id);
     info->len       = job->len;
     info->busy      = job->busy;
@@ -666,7 +669,7 @@ void *block_job_create(const char *job_id, const BlockJobDriver *driver,
     job->refcnt        = 1;
 
     error_setg(&job->blocker, "block device is in use by block job: %s",
-               BlockJobType_lookup[driver->job_type]);
+               qapi_enum_lookup(BlockJobType_lookup, driver->job_type));
     block_job_add_bdrv(job, "main node", bs, 0, BLK_PERM_ALL, &error_abort);
     bs->job = job;
 
chardev/char.c +5 -2
index 5d283b90d3..4408d12a08 100644
@@ -30,6 +30,7 @@
 #include "chardev/char.h"
 #include "qmp-commands.h"
 #include "qapi-visit.h"
+#include "qapi/util.h"
 #include "sysemu/replay.h"
 #include "qemu/help_option.h"
 
@@ -931,7 +932,8 @@ ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
     ChardevReturn *ret;
     Chardev *chr;
 
-    cc = char_get_class(ChardevBackendKind_lookup[backend->type], errp);
+    cc = char_get_class(qapi_enum_lookup(ChardevBackendKind_lookup,
+                                         backend->type), errp);
     if (!cc) {
         return NULL;
     }
@@ -989,7 +991,8 @@ ChardevReturn *qmp_chardev_change(const char *id, ChardevBackend *backend,
         return NULL;
     }
 
-    cc = char_get_class(ChardevBackendKind_lookup[backend->type], errp);
+    cc = char_get_class(qapi_enum_lookup(ChardevBackendKind_lookup,
+                                         backend->type), errp);
     if (!cc) {
         return NULL;
     }
crypto/block-luks.c +11 -6
index afb8543108..b78a6345f3 100644
@@ -20,6 +20,7 @@
 
 #include "qemu/osdep.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qemu/bswap.h"
 
 #include "crypto/block-luks.h"
@@ -257,7 +258,7 @@ qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg,
     }
 
     error_setg(errp, "Algorithm '%s' not supported",
-               QCryptoCipherAlgorithm_lookup[alg]);
+               qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
     return NULL;
 }
 
@@ -398,7 +399,7 @@ qcrypto_block_luks_essiv_cipher(QCryptoCipherAlgorithm cipher,
         break;
     default:
         error_setg(errp, "Cipher %s not supported with essiv",
-                   QCryptoCipherAlgorithm_lookup[cipher]);
+                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, cipher));
         return 0;
     }
 }
@@ -968,16 +969,20 @@ qcrypto_block_luks_create(QCryptoBlock *block,
         goto error;
     }
 
-    cipher_mode = QCryptoCipherMode_lookup[luks_opts.cipher_mode];
-    ivgen_alg = QCryptoIVGenAlgorithm_lookup[luks_opts.ivgen_alg];
+    cipher_mode = qapi_enum_lookup(QCryptoCipherMode_lookup,
+                                   luks_opts.cipher_mode);
+    ivgen_alg = qapi_enum_lookup(QCryptoIVGenAlgorithm_lookup,
+                                 luks_opts.ivgen_alg);
     if (luks_opts.has_ivgen_hash_alg) {
-        ivgen_hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.ivgen_hash_alg];
+        ivgen_hash_alg = qapi_enum_lookup(QCryptoHashAlgorithm_lookup,
+                                          luks_opts.ivgen_hash_alg);
         cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
                                            ivgen_hash_alg);
     } else {
         cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
     }
-    hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.hash_alg];
+    hash_alg = qapi_enum_lookup(QCryptoHashAlgorithm_lookup,
+                                luks_opts.hash_alg);
 
 
     if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
crypto/block.c +3 -2
index b097d451af..2140e55426 100644
@@ -20,6 +20,7 @@
 
 #include "qemu/osdep.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "crypto/blockpriv.h"
 #include "crypto/block-qcow.h"
 #include "crypto/block-luks.h"
@@ -61,7 +62,7 @@ QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options,
     if (options->format >= G_N_ELEMENTS(qcrypto_block_drivers) ||
         !qcrypto_block_drivers[options->format]) {
         error_setg(errp, "Unsupported block driver %s",
-                   QCryptoBlockFormat_lookup[options->format]);
+            qapi_enum_lookup(QCryptoBlockFormat_lookup, options->format));
         g_free(block);
         return NULL;
     }
@@ -92,7 +93,7 @@ QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options,
     if (options->format >= G_N_ELEMENTS(qcrypto_block_drivers) ||
         !qcrypto_block_drivers[options->format]) {
         error_setg(errp, "Unsupported block driver %s",
-                   QCryptoBlockFormat_lookup[options->format]);
+            qapi_enum_lookup(QCryptoBlockFormat_lookup, options->format));
         g_free(block);
         return NULL;
     }
crypto/cipher-afalg.c +1 -1
index 01343b2b7c..24d7ba8277 100644
@@ -52,7 +52,7 @@ qcrypto_afalg_cipher_format_name(QCryptoCipherAlgorithm alg,
         return NULL;
     }
 
-    mode_name = QCryptoCipherMode_lookup[mode];
+    mode_name = qapi_enum_lookup(QCryptoCipherMode_lookup, mode);
     name = g_strdup_printf("%s(%s)", mode_name, alg_name);
 
     return name;
crypto/cipher-builtin.c +4 -4
index 16a36d4532..76c76fb05b 100644
@@ -247,7 +247,7 @@ qcrypto_cipher_init_aes(QCryptoCipherMode mode,
         mode != QCRYPTO_CIPHER_MODE_ECB &&
         mode != QCRYPTO_CIPHER_MODE_XTS) {
         error_setg(errp, "Unsupported cipher mode %s",
-                   QCryptoCipherMode_lookup[mode]);
+                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -379,7 +379,7 @@ qcrypto_cipher_init_des_rfb(QCryptoCipherMode mode,
 
     if (mode != QCRYPTO_CIPHER_MODE_ECB) {
         error_setg(errp, "Unsupported cipher mode %s",
-                   QCryptoCipherMode_lookup[mode]);
+                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -440,7 +440,7 @@ static QCryptoCipherBuiltin *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
         break;
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   QCryptoCipherMode_lookup[mode]);
+                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -460,7 +460,7 @@ static QCryptoCipherBuiltin *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
     default:
         error_setg(errp,
                    "Unsupported cipher algorithm %s",
-                   QCryptoCipherAlgorithm_lookup[alg]);
+                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/cipher-gcrypt.c +2 -2
index 0489147398..09210195a4 100644
@@ -105,7 +105,7 @@ static QCryptoCipherGcrypt *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
         break;
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   QCryptoCipherMode_lookup[mode]);
+                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -160,7 +160,7 @@ static QCryptoCipherGcrypt *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
 
     default:
         error_setg(errp, "Unsupported cipher algorithm %s",
-                   QCryptoCipherAlgorithm_lookup[alg]);
+                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/cipher-nettle.c +4 -4
index c51f119cbc..7c02b3e7a2 100644
@@ -281,7 +281,7 @@ static QCryptoCipherNettle *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
         break;
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   QCryptoCipherMode_lookup[mode]);
+                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -420,7 +420,7 @@ static QCryptoCipherNettle *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
 
     default:
         error_setg(errp, "Unsupported cipher algorithm %s",
-                   QCryptoCipherAlgorithm_lookup[alg]);
+                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
         goto error;
     }
 
@@ -491,7 +491,7 @@ qcrypto_nettle_cipher_encrypt(QCryptoCipher *cipher,
 
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   QCryptoCipherMode_lookup[cipher->mode]);
+                   qapi_enum_lookup(QCryptoCipherMode_lookup, cipher->mode));
         return -1;
     }
     return 0;
@@ -537,7 +537,7 @@ qcrypto_nettle_cipher_decrypt(QCryptoCipher *cipher,
 
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   QCryptoCipherMode_lookup[cipher->mode]);
+                   qapi_enum_lookup(QCryptoCipherMode_lookup, cipher->mode));
         return -1;
     }
     return 0;
crypto/cipher.c +1 -0
index 0aad9d6d79..43291cba7e 100644
@@ -22,6 +22,7 @@
 #include "qapi/error.h"
 #include "crypto/cipher.h"
 #include "cipherpriv.h"
+#include "qapi/util.h"
 
 
 static size_t alg_key_len[QCRYPTO_CIPHER_ALG__MAX] = {
crypto/hmac-gcrypt.c +1 -1
index 76ca61ba24..0784795269 100644
@@ -52,7 +52,7 @@ void *qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
 
     if (!qcrypto_hmac_supports(alg)) {
         error_setg(errp, "Unsupported hmac algorithm %s",
-                   QCryptoHashAlgorithm_lookup[alg]);
+                   qapi_enum_lookup(QCryptoHashAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/hmac-glib.c +2 -1
index 8cf6b221ed..56b71dbf85 100644
@@ -14,6 +14,7 @@
 
 #include "qemu/osdep.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "crypto/hmac.h"
 #include "hmacpriv.h"
 
@@ -58,7 +59,7 @@ void *qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
 
     if (!qcrypto_hmac_supports(alg)) {
         error_setg(errp, "Unsupported hmac algorithm %s",
-                   QCryptoHashAlgorithm_lookup[alg]);
+                   qapi_enum_lookup(QCryptoHashAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/hmac-nettle.c +2 -1
index 1d5a915f03..be43511252 100644
@@ -14,6 +14,7 @@
 
 #include "qemu/osdep.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "crypto/hmac.h"
 #include "hmacpriv.h"
 #include <nettle/hmac.h>
@@ -106,7 +107,7 @@ void *qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
 
     if (!qcrypto_hmac_supports(alg)) {
         error_setg(errp, "Unsupported hmac algorithm %s",
-                   QCryptoHashAlgorithm_lookup[alg]);
+                   qapi_enum_lookup(QCryptoHashAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/pbkdf-gcrypt.c +2 -1
index 40289858bf..a815138c46 100644
@@ -22,6 +22,7 @@
 #include <gcrypt.h>
 #include "qapi/error.h"
 #include "crypto/pbkdf.h"
+#include "qapi/util.h"
 
 bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
 {
@@ -68,7 +69,7 @@ int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
         hash_map[hash] == GCRY_MD_NONE) {
         error_setg_errno(errp, ENOSYS,
                          "PBKDF does not support hash algorithm %s",
-                         QCryptoHashAlgorithm_lookup[hash]);
+                         qapi_enum_lookup(QCryptoHashAlgorithm_lookup, hash));
         return -1;
     }
 
crypto/pbkdf-nettle.c +2 -2
index 6fb2671656..84977fdd69 100644
@@ -23,7 +23,7 @@
 #include <nettle/hmac.h>
 #include "qapi/error.h"
 #include "crypto/pbkdf.h"
-
+#include "qapi/util.h"
 
 bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
 {
@@ -110,7 +110,7 @@ int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
     default:
         error_setg_errno(errp, ENOSYS,
                          "PBKDF does not support hash algorithm %s",
-                         QCryptoHashAlgorithm_lookup[hash]);
+                         qapi_enum_lookup(QCryptoHashAlgorithm_lookup, hash));
         return -1;
     }
     return 0;
hmp.c +46 -28

190 lines not on this page · raw message

hw/block/fdc.c +6 -3
index 401129073b..8ebe08d1af 100644
@@ -31,6 +31,7 @@
 #include "hw/hw.h"
 #include "hw/block/fdc.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qemu/error-report.h"
 #include "qemu/timer.h"
 #include "hw/isa/isa.h"
@@ -392,9 +393,11 @@ static int pick_geometry(FDrive *drv)
             FLOPPY_DPRINTF("User requested floppy drive type '%s', "
                            "but inserted medium appears to be a "
                            "%"PRId64" sector '%s' type\n",
-                           FloppyDriveType_lookup[drv->drive],
+                           qapi_enum_lookup(FloppyDriveType_lookup,
+                                            drv->drive),
                            nb_sectors,
-                           FloppyDriveType_lookup[parse->drive]);
+                           qapi_enum_lookup(FloppyDriveType_lookup,
+                                            parse->drive));
         }
         match = type_match;
     }
@@ -403,7 +406,7 @@ static int pick_geometry(FDrive *drv)
     if (match == -1) {
         error_setg(&error_abort, "No candidate geometries present in table "
                    " for floppy drive type '%s'",
-                   FloppyDriveType_lookup[drv->drive]);
+                   qapi_enum_lookup(FloppyDriveType_lookup, drv->drive));
     }
 
     parse = &(fd_formats[match]);
hw/char/escc.c +2 -1
index 1aca564e33..5c1d7b0e29 100644
@@ -31,6 +31,7 @@
 #include "ui/console.h"
 #include "ui/input.h"
 #include "trace.h"
+#include "qapi/util.h"
 
 /*
  * Chipset docs:
@@ -848,7 +849,7 @@ static void sunkbd_handle_event(DeviceState *dev, QemuConsole *src,
     assert(evt->type == INPUT_EVENT_KIND_KEY);
     key = evt->u.key.data;
     qcode = qemu_input_key_value_to_qcode(key->key);
-    trace_escc_sunkbd_event_in(qcode, QKeyCode_lookup[qcode],
+    trace_escc_sunkbd_event_in(qcode, qapi_enum_lookup(QKeyCode_lookup, qcode),
                                key->down);
 
     if (qcode == Q_KEY_CODE_CAPS_LOCK) {
hw/core/qdev-properties.c +6 -3
index 078fc5d239..c82c693bca 100644
@@ -2,6 +2,7 @@
 #include "net/net.h"
 #include "hw/qdev.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "hw/pci/pci.h"
 #include "qapi/qmp/qerror.h"
 #include "qemu/error-report.h"
@@ -72,8 +73,9 @@ static void set_enum(Object *obj, Visitor *v, const char *name, void *opaque,
 
 static void set_default_value_enum(Object *obj, const Property *prop)
 {
-    object_property_set_str(obj, prop->info->enum_table[prop->defval.i],
-                            prop->name, &error_abort);
+    object_property_set_str(obj,
+        qapi_enum_lookup(prop->info->enum_table, prop->defval.i),
+        prop->name, &error_abort);
 }
 
 /* Bit */
@@ -1095,7 +1097,8 @@ void qdev_prop_set_enum(DeviceState *dev, const char *name, int value)
     Property *prop;
 
     prop = qdev_prop_find(dev, name);
-    object_property_set_str(OBJECT(dev), prop->info->enum_table[value],
+    object_property_set_str(OBJECT(dev),
+                            qapi_enum_lookup(prop->info->enum_table, value),
                             name, &error_abort);
 }
 
hw/input/virtio-input-hid.c +3 -2
index 46c038110c..64039236f1 100644
@@ -15,6 +15,7 @@
 #include "ui/console.h"
 
 #include "standard-headers/linux/input.h"
+#include "qapi/util.h"
 
 #define VIRTIO_ID_NAME_KEYBOARD "QEMU Virtio Keyboard"
 #define VIRTIO_ID_NAME_MOUSE    "QEMU Virtio Mouse"
@@ -209,7 +210,7 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
         } else {
             if (key->down) {
                 fprintf(stderr, "%s: unmapped key: %d [%s]\n", __func__,
-                        qcode, QKeyCode_lookup[qcode]);
+                        qcode, qapi_enum_lookup(QKeyCode_lookup, qcode));
             }
         }
         break;
@@ -224,7 +225,7 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
             if (btn->down) {
                 fprintf(stderr, "%s: unmapped button: %d [%s]\n", __func__,
                         btn->button,
-                        InputButton_lookup[btn->button]);
+                        qapi_enum_lookup(InputButton_lookup, btn->button));
             }
         }
         break;
migration/colo-failover.c +4 -2
index f9914869c5..e5394ba631 100644
@@ -17,6 +17,7 @@
 #include "migration.h"
 #include "qmp-commands.h"
 #include "qapi/qmp/qerror.h"
+#include "qapi/util.h"
 #include "qemu/error-report.h"
 #include "trace.h"
 
@@ -34,7 +35,7 @@ static void colo_failover_bh(void *opaque)
                                    FAILOVER_STATUS_ACTIVE);
     if (old_state != FAILOVER_STATUS_REQUIRE) {
         error_report("Unknown error for failover, old_state = %s",
-                    FailoverStatus_lookup[old_state]);
+                     qapi_enum_lookup(FailoverStatus_lookup, old_state));
         return;
     }
 
@@ -64,7 +65,8 @@ FailoverStatus failover_set_state(FailoverStatus old_state,
 
     old = atomic_cmpxchg(&failover_state, old_state, new_state);
     if (old == old_state) {
-        trace_colo_failover_set_state(FailoverStatus_lookup[new_state]);
+        trace_colo_failover_set_state(qapi_enum_lookup(FailoverStatus_lookup,
+                                                       new_state));
     }
     return old;
 }
migration/colo.c +10 -7
index a4255432ac..2b683a0afc 100644
@@ -24,6 +24,7 @@
 #include "migration/failover.h"
 #include "replication.h"
 #include "qmp-commands.h"
+#include "qapi/util.h"
 
 static bool vmstate_loading;
 
@@ -61,7 +62,8 @@ static void secondary_vm_do_failover(void)
                         FAILOVER_STATUS_RELAUNCH);
         if (old_state != FAILOVER_STATUS_ACTIVE) {
             error_report("Unknown error while do failover for secondary VM,"
-                         "old_state: %s", FailoverStatus_lookup[old_state]);
+                         "old_state: %s",
+                         qapi_enum_lookup(FailoverStatus_lookup, old_state));
         }
         return;
     }
@@ -91,7 +93,8 @@ static void secondary_vm_do_failover(void)
                                    FAILOVER_STATUS_COMPLETED);
     if (old_state != FAILOVER_STATUS_ACTIVE) {
         error_report("Incorrect state (%s) while doing failover for "
-                     "secondary VM", FailoverStatus_lookup[old_state]);
+                     "secondary VM",
+                     qapi_enum_lookup(FailoverStatus_lookup, old_state));
         return;
     }
     /* Notify COLO incoming thread that failover work is finished */
@@ -126,7 +129,7 @@ static void primary_vm_do_failover(void)
                                    FAILOVER_STATUS_COMPLETED);
     if (old_state != FAILOVER_STATUS_ACTIVE) {
         error_report("Incorrect state (%s) while doing failover for Primary VM",
-                     FailoverStatus_lookup[old_state]);
+                     qapi_enum_lookup(FailoverStatus_lookup, old_state));
         return;
     }
     /* Notify COLO thread that failover work is finished */
@@ -222,7 +225,7 @@ static void colo_send_message(QEMUFile *f, COLOMessage msg,
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Can't send COLO message");
     }
-    trace_colo_send_message(COLOMessage_lookup[msg]);
+    trace_colo_send_message(qapi_enum_lookup(COLOMessage_lookup, msg));
 }
 
 static void colo_send_message_value(QEMUFile *f, COLOMessage msg,
@@ -242,7 +245,7 @@ static void colo_send_message_value(QEMUFile *f, COLOMessage msg,
     ret = qemu_file_get_error(f);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Failed to send value for message:%s",
-                         COLOMessage_lookup[msg]);
+                         qapi_enum_lookup(COLOMessage_lookup, msg));
     }
 }
 
@@ -261,7 +264,7 @@ static COLOMessage colo_receive_message(QEMUFile *f, Error **errp)
         error_setg(errp, "%s: Invalid message", __func__);
         return msg;
     }
-    trace_colo_receive_message(COLOMessage_lookup[msg]);
+    trace_colo_receive_message(qapi_enum_lookup(COLOMessage_lookup, msg));
     return msg;
 }
 
@@ -299,7 +302,7 @@ static uint64_t colo_receive_message_value(QEMUFile *f, uint32_t expect_msg,
     ret = qemu_file_get_error(f);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Failed to get value for COLO message: %s",
-                         COLOMessage_lookup[expect_msg]);
+                         qapi_enum_lookup(COLOMessage_lookup, expect_msg));
     }
     return value;
 }
migration/global_state.c +1 -1
index dcbbcb28be..4d57a9c5f2 100644
@@ -42,7 +42,7 @@ int global_state_store(void)
 
 void global_state_store_running(void)
 {
-    const char *state = RunState_lookup[RUN_STATE_RUNNING];
+    const char *state = qapi_enum_lookup(RunState_lookup, RUN_STATE_RUNNING);
     strncpy((char *)global_state.runstate,
            state, sizeof(global_state.runstate));
 }
monitor.c +14 -10
index 14c27d4b6f..ee2fdfd4f1 100644
@@ -78,6 +78,7 @@
 #include "sysemu/cpus.h"
 #include "qemu/cutils.h"
 #include "qapi/qmp/dispatch.h"
+#include "qapi/util.h"
 
 #if defined(TARGET_S390X)
 #include "hw/s390x/storage-keys.h"
@@ -928,7 +929,7 @@ EventInfoList *qmp_query_events(Error **errp)
     QAPIEvent e;
 
     for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
-        const char *event_name = QAPIEvent_lookup[e];
+        const char *event_name = qapi_enum_lookup(QAPIEvent_lookup, e);
         assert(event_name != NULL);
         info = g_malloc0(sizeof(*info));
         info->value = g_malloc0(sizeof(*info->value));
@@ -3249,8 +3250,9 @@ void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
     }
     len = strlen(str);
     readline_set_completion_index(rs, len);
-    for (i = 0; NetClientDriver_lookup[i]; i++) {
-        add_completion_option(rs, str, NetClientDriver_lookup[i]);
+    for (i = 0; qapi_enum_lookup(NetClientDriver_lookup, i); i++) {
+        add_completion_option(rs, str,
+                              qapi_enum_lookup(NetClientDriver_lookup, i));
     }
 }
 
@@ -3434,8 +3436,8 @@ void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
     len = strlen(str);
     readline_set_completion_index(rs, len);
     for (i = 0; i < Q_KEY_CODE__MAX; i++) {
-        if (!strncmp(str, QKeyCode_lookup[i], len)) {
-            readline_add_completion(rs, QKeyCode_lookup[i]);
+        if (!strncmp(str, qapi_enum_lookup(QKeyCode_lookup, i), len)) {
+            readline_add_completion(rs, qapi_enum_lookup(QKeyCode_lookup, i));
         }
     }
 }
@@ -3537,8 +3539,9 @@ void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
         return;
     }
     readline_set_completion_index(rs, strlen(str));
-    for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
-        add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
+    for (i = 0; qapi_enum_lookup(WatchdogExpirationAction_lookup, i); i++) {
+        add_completion_option(rs, str,
+            qapi_enum_lookup(WatchdogExpirationAction_lookup, i));
     }
 }
 
@@ -3552,7 +3555,7 @@ void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
     if (nb_args == 2) {
         int i;
         for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
-            const char *name = MigrationCapability_lookup[i];
+            const char *name = qapi_enum_lookup(MigrationCapability_lookup, i);
             if (!strncmp(str, name, len)) {
                 readline_add_completion(rs, name);
             }
@@ -3573,7 +3576,7 @@ void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
     if (nb_args == 2) {
         int i;
         for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
-            const char *name = MigrationParameter_lookup[i];
+            const char *name = qapi_enum_lookup(MigrationParameter_lookup, i);
             if (!strncmp(str, name, len)) {
                 readline_add_completion(rs, name);
             }
@@ -3852,7 +3855,8 @@ static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
         qdict = qdict_get_qdict(qobject_to_qdict(rsp), "error");
         if (qdict
             && !g_strcmp0(qdict_get_try_str(qdict, "class"),
-                    QapiErrorClass_lookup[ERROR_CLASS_COMMAND_NOT_FOUND])) {
+                          qapi_enum_lookup(QapiErrorClass_lookup,
+                                           ERROR_CLASS_COMMAND_NOT_FOUND))) {
             /* Provide a more useful error message */
             qdict_del(qdict, "desc");
             qdict_put_str(qdict, "desc", "Expecting capabilities negotiation"
net/net.c +3 -2
index 0e28099554..efe2252c59 100644
@@ -48,6 +48,7 @@
 #include "sysemu/qtest.h"
 #include "net/filter.h"
 #include "qapi/string-output-visitor.h"
+#include "qapi/util.h"
 
 /* Net bridge is currently not supported for W32. */
 #if !defined(_WIN32)
@@ -1064,7 +1065,7 @@ static int net_client_init1(const void *object, bool is_netdev, Error **errp)
         /* FIXME drop when all init functions store an Error */
         if (errp && !*errp) {
             error_setg(errp, QERR_DEVICE_INIT_FAILED,
-                       NetClientDriver_lookup[netdev->type]);
+                       qapi_enum_lookup(NetClientDriver_lookup, netdev->type));
         }
         return -1;
     }
@@ -1288,7 +1289,7 @@ void print_net_client(Monitor *mon, NetClientState *nc)
 
     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
                    nc->queue_index,
-                   NetClientDriver_lookup[nc->info->type],
+                   qapi_enum_lookup(NetClientDriver_lookup, nc->info->type),
                    nc->info_str);
     if (!QTAILQ_EMPTY(&nc->filters)) {
         monitor_printf(mon, "filters:\n");
qapi/qapi-util.c +7 -0
index 46eda7d196..7677caa51e 100644
@@ -34,6 +34,13 @@ int qapi_enum_parse(const char * const lookup[], const char *buf,
     return def;
 }
 
+const char *qapi_enum_lookup(const char * const lookup[], int val)
+{
+    assert(val >= 0);
+
+    return lookup[val];
+}
+
 /*
  * Parse a valid QAPI name from @str.
  * A valid name consists of letters, digits, hyphen and underscore.
qapi/qmp-dispatch.c +3 -1
index 5ad36f8a09..06f1470516 100644
@@ -19,6 +19,7 @@
 #include "qapi/qmp/qjson.h"
 #include "qapi-types.h"
 #include "qapi/qmp/qerror.h"
+#include "qapi/util.h"
 
 static QDict *qmp_dispatch_check_obj(const QObject *request, Error **errp)
 {
@@ -118,7 +119,8 @@ static QObject *do_qmp_dispatch(QmpCommandList *cmds, QObject *request,
 QObject *qmp_build_error_object(Error *err)
 {
     return qobject_from_jsonf("{ 'class': %s, 'desc': %s }",
-                              QapiErrorClass_lookup[error_get_class(err)],
+                              qapi_enum_lookup(QapiErrorClass_lookup,
+                                               error_get_class(err)),
                               error_get_pretty(err));
 }
 
tests/test-qobject-output-visitor.c +3 -1
index 7eb162059c..bb2d66b666 100644
@@ -19,6 +19,7 @@
 #include "test-qapi-visit.h"
 #include "qapi/qmp/types.h"
 #include "qapi/qmp/qjson.h"
+#include "qapi/util.h"
 
 typedef struct TestOutputVisitorData {
     Visitor *ov;
@@ -133,7 +134,8 @@ static void test_visitor_out_enum(TestOutputVisitorData *data,
 
         qstr = qobject_to_qstring(visitor_get(data));
         g_assert(qstr);
-        g_assert_cmpstr(qstring_get_str(qstr), ==, EnumOne_lookup[i]);
+        g_assert_cmpstr(qstring_get_str(qstr), ==,
+                        qapi_enum_lookup(EnumOne_lookup, i));
         visitor_reset(data);
     }
 }
tests/test-string-output-visitor.c +4 -2
index e736db3af8..0b2087d312 100644
@@ -14,6 +14,7 @@
 
 #include "qemu-common.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qapi/string-output-visitor.h"
 #include "test-qapi-types.h"
 #include "test-qapi-visit.h"
@@ -194,12 +195,13 @@ static void test_visitor_out_enum(TestOutputVisitorData *data,
 
         str = visitor_get(data);
         if (data->human) {
-            char *str_human = g_strdup_printf("\"%s\"", EnumOne_lookup[i]);
+            char *str_human =
+                g_strdup_printf("\"%s\"", qapi_enum_lookup(EnumOne_lookup, i));
 
             g_assert_cmpstr(str, ==, str_human);
             g_free(str_human);
         } else {
-            g_assert_cmpstr(str, ==, EnumOne_lookup[i]);
+            g_assert_cmpstr(str, ==, qapi_enum_lookup(EnumOne_lookup, i));
         }
         visitor_reset(data);
     }
tpm.c +3 -1
index 9a7c7114d3..c3b731b3f2 100644
@@ -19,6 +19,7 @@
 #include "qemu/config-file.h"
 #include "qemu/error-report.h"
 #include "qmp-commands.h"
+#include "qapi/util.h"
 
 static QLIST_HEAD(, TPMBackend) tpm_backends =
     QLIST_HEAD_INITIALIZER(tpm_backends);
@@ -102,7 +103,8 @@ static void tpm_display_backend_drivers(void)
 
     for (i = 0; i < TPM_MAX_DRIVERS && be_drivers[i] != NULL; i++) {
         fprintf(stderr, "%12s   %s\n",
-                TpmType_lookup[be_drivers[i]->type], be_drivers[i]->desc());
+                qapi_enum_lookup(TpmType_lookup, be_drivers[i]->type),
+                be_drivers[i]->desc());
     }
     fprintf(stderr, "\n");
 }
ui/input.c +7 -6
index af05f06368..6bceb6b825 100644
@@ -7,6 +7,7 @@
 #include "ui/input.h"
 #include "ui/console.h"
 #include "sysemu/replay.h"
+#include "qapi/util.h"
 
 struct QemuInputHandlerState {
     DeviceState       *dev;
@@ -151,7 +152,7 @@ void qmp_input_send_event(bool has_device, const char *device,
         if (!qemu_input_find_handler(1 << event->type, con)) {
             error_setg(errp, "Input handler not found for "
                              "event type %s",
-                            InputEventKind_lookup[event->type]);
+                       qapi_enum_lookup(InputEventKind_lookup, event->type));
             return;
         }
     }
@@ -213,12 +214,12 @@ static void qemu_input_event_trace(QemuConsole *src, InputEvent *evt)
         switch (key->key->type) {
         case KEY_VALUE_KIND_NUMBER:
             qcode = qemu_input_key_number_to_qcode(key->key->u.number.data);
-            name = QKeyCode_lookup[qcode];
+            name = qapi_enum_lookup(QKeyCode_lookup, qcode);
             trace_input_event_key_number(idx, key->key->u.number.data,
                                          name, key->down);
             break;
         case KEY_VALUE_KIND_QCODE:
-            name = QKeyCode_lookup[key->key->u.qcode.data];
+            name = qapi_enum_lookup(QKeyCode_lookup, key->key->u.qcode.data);
             trace_input_event_key_qcode(idx, name, key->down);
             break;
         case KEY_VALUE_KIND__MAX:
@@ -228,17 +229,17 @@ static void qemu_input_event_trace(QemuConsole *src, InputEvent *evt)
         break;
     case INPUT_EVENT_KIND_BTN:
         btn = evt->u.btn.data;
-        name = InputButton_lookup[btn->button];
+        name = qapi_enum_lookup(InputButton_lookup, btn->button);
         trace_input_event_btn(idx, name, btn->down);
         break;
     case INPUT_EVENT_KIND_REL:
         move = evt->u.rel.data;
-        name = InputAxis_lookup[move->axis];
+        name = qapi_enum_lookup(InputAxis_lookup, move->axis);
         trace_input_event_rel(idx, name, move->value);
         break;
     case INPUT_EVENT_KIND_ABS:
         move = evt->u.abs.data;
-        name = InputAxis_lookup[move->axis];
+        name = qapi_enum_lookup(InputAxis_lookup, move->axis);
         trace_input_event_abs(idx, name, move->value);
         break;
     case INPUT_EVENT_KIND__MAX:
ui/vnc.c +5 -3
index 651cbb8606..20a45a7241 100644
@@ -36,6 +36,7 @@
 #include "qemu/config-file.h"
 #include "qapi/qmp/qerror.h"
 #include "qapi/qmp/types.h"
+#include "qapi/util.h"
 #include "qmp-commands.h"
 #include "ui/input.h"
 #include "qapi-event.h"
@@ -131,7 +132,7 @@ static void vnc_init_basic_info(SocketAddress *addr,
     case SOCKET_ADDRESS_TYPE_VSOCK:
     case SOCKET_ADDRESS_TYPE_FD:
         error_setg(errp, "Unsupported socket address type %s",
-                   SocketAddressType_lookup[addr->type]);
+                   qapi_enum_lookup(SocketAddressType_lookup, addr->type));
         break;
     default:
         abort();
@@ -416,7 +417,7 @@ VncInfo *qmp_query_vnc(Error **errp)
         case SOCKET_ADDRESS_TYPE_VSOCK:
         case SOCKET_ADDRESS_TYPE_FD:
             error_setg(errp, "Unsupported socket address type %s",
-                       SocketAddressType_lookup[addr->type]);
+                       qapi_enum_lookup(SocketAddressType_lookup, addr->type));
             goto out_error;
         default:
             abort();
@@ -1839,7 +1840,8 @@ static void vnc_release_modifiers(VncState *vs)
 
 static const char *code2name(int keycode)
 {
-    return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
+    return qapi_enum_lookup(QKeyCode_lookup,
+                            qemu_input_key_number_to_qcode(keycode));
 }
 
 static void key_event(VncState *vs, int down, uint32_t sym)
vl.c +4 -3
index 8e247cc2a2..def4f5f05f 100644
@@ -99,6 +99,7 @@ int main(int argc, char **argv)
 #include "sysemu/hax.h"
 #include "qapi/qobject-input-visitor.h"
 #include "qapi/qobject-input-visitor.h"
+#include "qapi/util.h"
 #include "qapi-visit.h"
 #include "qapi/qmp/qjson.h"
 #include "qemu/option.h"
@@ -688,7 +689,7 @@ bool runstate_check(RunState state)
 
 bool runstate_store(char *str, size_t size)
 {
-    const char *state = RunState_lookup[current_run_state];
+    const char *state = qapi_enum_lookup(RunState_lookup, current_run_state);
     size_t len = strlen(state) + 1;
 
     if (len > size) {
@@ -721,8 +722,8 @@ void runstate_set(RunState new_state)
 
     if (!runstate_valid_transitions[current_run_state][new_state]) {
         error_report("invalid runstate transition: '%s' -> '%s'",
-                     RunState_lookup[current_run_state],
-                     RunState_lookup[new_state]);
+                     qapi_enum_lookup(RunState_lookup, current_run_state),
+                     qapi_enum_lookup(RunState_lookup, new_state));
         abort();
     }
     trace_runstate_set(new_state);
Signature · 1 line
2.14.1.146.gd35faa819
#21 lore raw

Re: [Qemu-devel] [PATCH v2 06/54] qapi: introduce qapi_enum_lookup()

Quoted 3 lines · Marc-André Lureau

This will help with the introduction of a new structure to handle enum lookup.

Procedurally for the sake of review, it's a little odd to introduce the function, deploy it, and then change it and update all callers.

content-wise, I'm really glad to have a function like this that we can use universally.

ACK (6, 12)

#22 lore raw

Re: [Qemu-devel] [PATCH v2 06/54] qapi: introduce qapi_enum_lookup()

In reply to Marc-André Lureau
Quoted 5 lines · Marc-André Lureau

This will help with the introduction of a new structure to handle enum lookup.

---

[...]

Quoted 1 line
 45 files changed, 206 insertions(+), 122 deletions(-)

Hmm.

Quoted 26 lines
include/qapi/util.h +2 -0
index 7436ed815c..60733b6a80 100644
@@ -11,6 +11,8 @@
 #ifndef QAPI_UTIL_H
 #define QAPI_UTIL_H
 
+const char *qapi_enum_lookup(const char * const lookup[], int val);
+
 int qapi_enum_parse(const char * const lookup[], const char *buf,
                     int max, int def, Error **errp);
 
backends/hostmem.c +1 -0
index 4606b73849..c4f795475c 100644
@@ -13,6 +13,7 @@
 #include "sysemu/hostmem.h"
 #include "hw/boards.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qapi/visitor.h"
 #include "qapi-types.h"
 #include "qapi-visit.h"

backends/hostmem.c host_memory_backend_memory_complete(UserCreatable *uc, Error **errp) · line 311

Quoted 8 lines
backends/hostmem.c +1 -1
@@ -304,7 +305,7 @@ host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)
             return;
         } else if (maxnode == 0 && backend->policy != MPOL_DEFAULT) {
             error_setg(errp, "host-nodes must be set for policy %s",
-                       HostMemPolicy_lookup[backend->policy]);
+                qapi_enum_lookup(HostMemPolicy_lookup, backend->policy));
             return;
         }
 

Lookup becomes even more verbose.

Could we claw back some readability with macros? Say in addition to

    typedef enum FOO {
        ...
    } FOO;

    extern const char *const FOO_lookup[];

generate

    #define FOO_str(val) qapi_enum_lookup(FOO_lookup, (val))

Needs a matching qapi-code-gen.txt update.

With that, this patch hunk would become

error_setg(errp, "host-nodes must be set for policy %s",
- HostMemPolicy_lookup[backend->policy]);
+ HostMemPolicy_str(backend->policy);

Perhaps we could even throw in some type checking:

#define FOO_str(val) (type_check(typeof((val)), FOO) \
+ qapi_enum_lookup(FOO_lookup, (val)))

What do you think? Want me to explore a fixup patch you could squash in?

[Skipping lots of mechanical changes...]

I think you missed test-qobject-input-visitor.c and string-input-visitor.c.

In test-qobject-input-visitor.c's test_visitor_in_enum():

        v = visitor_input_test_init(data, "%s", EnumOne_lookup[i]);

You update it in PATCH 12, but the code only works as long as EnumOne has no holes. Mapping the enum to string like we do everywhere else in this patch would be cleaner.

The loop control also subscripts EnumOne_lookup[i]. You take care of that one in PATCH 12. That's okay.

Same for test-string-input-visitor.c's test_visitor_in_enum().

There's one more in test_native_list_integer_helper():

    g_string_append_printf(gstr_union,  "{ 'type': '%s', 'data': [ %s ] }",
                           UserDefNativeListUnionKind_lookup[kind],
                           gstr_list->str);

Same story.

The patch doesn't touch the _lookup[] subscripts you're going to replace by qapi_enum_parse() in PATCH 07-11. Understand, but I'd reorder the
patches: first replace by qapi_enum_parse(), because DRY (no need to explain more at that point). Then get rid of all the remaining subscripting into _lookup[], i.e. this patch (explain it helps the next one), then PATCH 12.

#23 lore raw

Re: [Qemu-devel] [PATCH v2 06/54] qapi: introduce qapi_enum_lookup()

Hi

----- Original Message -----

Quoted 70 lines
Quoted 5 lines · Marc-André Lureau

This will help with the introduction of a new structure to handle enum lookup.

---

[...]

Quoted 1 line
 45 files changed, 206 insertions(+), 122 deletions(-)

Hmm.

Quoted 27 lines
include/qapi/util.h +2 -0
index 7436ed815c..60733b6a80 100644
@@ -11,6 +11,8 @@
 #ifndef QAPI_UTIL_H
 #define QAPI_UTIL_H
 
+const char *qapi_enum_lookup(const char * const lookup[], int val);
+
 int qapi_enum_parse(const char * const lookup[], const char *buf,
                     int max, int def, Error **errp);
 
backends/hostmem.c +1 -0
index 4606b73849..c4f795475c 100644
@@ -13,6 +13,7 @@
 #include "sysemu/hostmem.h"
 #include "hw/boards.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qapi/visitor.h"
 #include "qapi-types.h"
 #include "qapi-visit.h"

backends/hostmem.c host_memory_backend_memory_complete(UserCreatable *uc, · line 311

Quoted 8 lines
backends/hostmem.c +1 -1
@@ -304,7 +305,7 @@ host_memory_backend_memory_complete(UserCreatable *uc,
 Error **errp)
             return;
         } else if (maxnode == 0 && backend->policy != MPOL_DEFAULT) {
             error_setg(errp, "host-nodes must be set for policy %s",
-                       HostMemPolicy_lookup[backend->policy]);
+                qapi_enum_lookup(HostMemPolicy_lookup, backend->policy));
             return;
         }

Lookup becomes even more verbose.

Could we claw back some readability with macros? Say in addition to

    typedef enum FOO {
        ...
    } FOO;

    extern const char *const FOO_lookup[];

generate

    #define FOO_str(val) qapi_enum_lookup(FOO_lookup, (val))

Needs a matching qapi-code-gen.txt update.

With that, this patch hunk would become

error_setg(errp, "host-nodes must be set for policy %s",
- HostMemPolicy_lookup[backend->policy]);
+ HostMemPolicy_str(backend->policy);

Quoted 8 lines

Perhaps we could even throw in some type checking:

#define FOO_str(val) (type_check(typeof((val)), FOO) \
+ qapi_enum_lookup(FOO_lookup, (val)))

What do you think? Want me to explore a fixup patch you could squash in?

Yes, I had similar thoughts, but didn't spent too much time finding the best proposal, that wasn't my main goal in the series.

Indeed, I would prefer that further improvements be done as follow-up. Or if you have a ready solution, I can squash it there. I can picture the conflicts with the next patch though...

Quoted 5 lines

[Skipping lots of mechanical changes...]

I think you missed test-qobject-input-visitor.c and string-input-visitor.c.

Quoted 8 lines

In test-qobject-input-visitor.c's test_visitor_in_enum():

        v = visitor_input_test_init(data, "%s", EnumOne_lookup[i]);

You update it in PATCH 12, but the code only works as long as EnumOne has no holes. Mapping the enum to string like we do everywhere else in this patch would be cleaner.

ok

Quoted 11 lines

The loop control also subscripts EnumOne_lookup[i]. You take care of that one in PATCH 12. That's okay.

Same for test-string-input-visitor.c's test_visitor_in_enum().

There's one more in test_native_list_integer_helper():

    g_string_append_printf(gstr_union,  "{ 'type': '%s', 'data': [ %s ] }",
                           UserDefNativeListUnionKind_lookup[kind],
                           gstr_list->str);
Quoted 9 lines

Same story.

The patch doesn't touch the _lookup[] subscripts you're going to replace by qapi_enum_parse() in PATCH 07-11. Understand, but I'd reorder the
patches: first replace by qapi_enum_parse(), because DRY (no need to explain more at that point). Then get rid of all the remaining subscripting into _lookup[], i.e. this patch (explain it helps the next one), then PATCH 12.

ok

#24 lore raw

Re: [Qemu-devel] [PATCH v2 06/54] qapi: introduce qapi_enum_lookup()

Quoted 7 lines · * Marc-André Lureau ([email protected]) wrote:

Hi

----- Original Message -----

Quoted 4 lines
Quoted 2 lines · Marc-André Lureau

This will help with the introduction of a new structure to handle enum lookup.

It would be good to make that comment explain why it's necessary.

Quoted 70 lines
Quoted 70 lines
Quoted 2 lines

---

[...]

Quoted 1 line
 45 files changed, 206 insertions(+), 122 deletions(-)

Hmm.

Quoted 27 lines
include/qapi/util.h +2 -0
index 7436ed815c..60733b6a80 100644
@@ -11,6 +11,8 @@
 #ifndef QAPI_UTIL_H
 #define QAPI_UTIL_H
 
+const char *qapi_enum_lookup(const char * const lookup[], int val);
+
 int qapi_enum_parse(const char * const lookup[], const char *buf,
                     int max, int def, Error **errp);
 
backends/hostmem.c +1 -0
index 4606b73849..c4f795475c 100644
@@ -13,6 +13,7 @@
 #include "sysemu/hostmem.h"
 #include "hw/boards.h"
 #include "qapi/error.h"
+#include "qapi/util.h"
 #include "qapi/visitor.h"
 #include "qapi-types.h"
 #include "qapi-visit.h"

backends/hostmem.c host_memory_backend_memory_complete(UserCreatable *uc, · line 311

Quoted 8 lines
backends/hostmem.c +1 -1
@@ -304,7 +305,7 @@ host_memory_backend_memory_complete(UserCreatable *uc,
 Error **errp)
             return;
         } else if (maxnode == 0 && backend->policy != MPOL_DEFAULT) {
             error_setg(errp, "host-nodes must be set for policy %s",
-                       HostMemPolicy_lookup[backend->policy]);
+                qapi_enum_lookup(HostMemPolicy_lookup, backend->policy));
             return;
         }

Lookup becomes even more verbose.

Could we claw back some readability with macros? Say in addition to

    typedef enum FOO {
        ...
    } FOO;

    extern const char *const FOO_lookup[];

generate

    #define FOO_str(val) qapi_enum_lookup(FOO_lookup, (val))

Needs a matching qapi-code-gen.txt update.

With that, this patch hunk would become

error_setg(errp, "host-nodes must be set for policy %s",
- HostMemPolicy_lookup[backend->policy]);
+ HostMemPolicy_str(backend->policy);

Perhaps we could even throw in some type checking:

#define FOO_str(val) (type_check(typeof((val)), FOO) \
+ qapi_enum_lookup(FOO_lookup, (val)))

Quoted 7 lines
Quoted 3 lines

What do you think? Want me to explore a fixup patch you could squash in?

Yes, I had similar thoughts, but didn't spent too much time finding the best proposal, that wasn't my main goal in the series.

Indeed, I would prefer that further improvements be done as follow-up. Or if you have a ready solution, I can squash it there. I can picture the conflicts with the next patch though...

If you did it as a separate patch it would have to be another huge patch changing lots of areas.
I think the use of the macro to keep it simple should be in this one; you can add the type check change later.

Dave

Quoted 37 lines
Quoted 5 lines

[Skipping lots of mechanical changes...]

I think you missed test-qobject-input-visitor.c and string-input-visitor.c.

Quoted 8 lines

In test-qobject-input-visitor.c's test_visitor_in_enum():

        v = visitor_input_test_init(data, "%s", EnumOne_lookup[i]);

You update it in PATCH 12, but the code only works as long as EnumOne has no holes. Mapping the enum to string like we do everywhere else in this patch would be cleaner.

ok

Quoted 11 lines

The loop control also subscripts EnumOne_lookup[i]. You take care of that one in PATCH 12. That's okay.

Same for test-string-input-visitor.c's test_visitor_in_enum().

There's one more in test_native_list_integer_helper():

    g_string_append_printf(gstr_union,  "{ 'type': '%s', 'data': [ %s ] }",
                           UserDefNativeListUnionKind_lookup[kind],
                           gstr_list->str);
Quoted 9 lines

Same story.

The patch doesn't touch the _lookup[] subscripts you're going to replace by qapi_enum_parse() in PATCH 07-11. Understand, but I'd reorder the
patches: first replace by qapi_enum_parse(), because DRY (no need to explain more at that point). Then get rid of all the remaining subscripting into _lookup[], i.e. this patch (explain it helps the next one), then PATCH 12.

Quoted 1 line

ok

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#25 lore raw

PATCH v2 7/54 tpm: simplify driver registration & lookup

In reply to Marc-André Lureau

Make be_drivers[n] match order of TpmType enum.

Use qapi_enum_parse() in tpm_get_backend_driver.

---
 include/sysemu/tpm_backend.h |  2 +-
 tpm.c                        | 42 ++++++++++++------------------------------
 2 files changed, 13 insertions(+), 31 deletions(-)
include/sysemu/tpm_backend.h +1 -1
index b58f52d39f..1d21c6b19b 100644
@@ -227,6 +227,6 @@ TPMBackend *qemu_find_tpm(const char *id);
 
 const TPMDriverOps *tpm_get_backend_driver(const char *type);
 int tpm_register_model(enum TpmModel model);
-int tpm_register_driver(const TPMDriverOps *tdo);
+void tpm_register_driver(const TPMDriverOps *tdo);
 
 #endif
tpm.c +12 -30

75 lines not on this page · raw message

Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 7/54
#26 lore raw

Re: [Qemu-devel] [PATCH v2 07/54] tpm: simplify driver registration & lookup

Note: cc'ing the code's author.

Quoted 9 lines · Marc-André Lureau

Make be_drivers[n] match order of TpmType enum.

Use qapi_enum_parse() in tpm_get_backend_driver.

---
 include/sysemu/tpm_backend.h |  2 +-
 tpm.c                        | 42 ++++++++++++------------------------------
 2 files changed, 13 insertions(+), 31 deletions(-)

Before the patch, we have a strict separation between enum TpmModel / tpm_models[] and enum TpmType / be_drivers[]:

* TpmModel may have any number of members. It just happens to have one.

* Same for TpmType.

* tpm_models[] may have any number of elements. It just happens to have the same number of elements as TpmModel has members.

If it had more, they'd be wasted: tpm_register_model() can't use more than one per TpmModel member. If it had fewer, tpm_register_model() could fail. Its caller ignores failure.

* be_drivers[] is different: tpm_register_driver() happily adds drivers as long as be_drivers[] has space. Its caller ignores failure.

If you register more than one with a given TpmType, tpm_driver_find_by_type(), tpm_get_backend_driver() will find only the one one that registered first. tpm_display_backend_drivers() happily shows all of them.

* The order of TpmModel members and tpm_models[] elements is independent. The former is fixed in the QAPI schema, the latter is determined by registration order, which is unspecified.

Corollary: using a TpmModel to subscript tpm_models[] is wrong.

* Same for TpmType and be_drivers[]: using a TpmType to subscript be_drivers[] is wrong.

Hard to tell whether this is / has become more a case of overengineering or more a case of under-make-sense-ing.

Quoted 85 lines
include/sysemu/tpm_backend.h +1 -1
index b58f52d39f..1d21c6b19b 100644
@@ -227,6 +227,6 @@ TPMBackend *qemu_find_tpm(const char *id);
 
 const TPMDriverOps *tpm_get_backend_driver(const char *type);
 int tpm_register_model(enum TpmModel model);
-int tpm_register_driver(const TPMDriverOps *tdo);
+void tpm_register_driver(const TPMDriverOps *tdo);
 
 #endif
tpm.c +11 -24
index c3b731b3f2..f175661bfe 100644
@@ -26,9 +26,8 @@ static QLIST_HEAD(, TPMBackend) tpm_backends =
 
 
 #define TPM_MAX_MODELS      1
-#define TPM_MAX_DRIVERS     1
 
-static TPMDriverOps const *be_drivers[TPM_MAX_DRIVERS] = {
+static TPMDriverOps const *be_drivers[TPM_TYPE__MAX] = {
     NULL,
 };
 
@@ -64,31 +63,18 @@ static bool tpm_model_is_registered(enum TpmModel model)
 
 const TPMDriverOps *tpm_get_backend_driver(const char *type)
 {
-    int i;
+    int i = qapi_enum_parse(TpmType_lookup, type, TPM_TYPE__MAX, -1, NULL);
 
-    for (i = 0; i < TPM_MAX_DRIVERS && be_drivers[i] != NULL; i++) {
-        if (!strcmp(TpmType_lookup[be_drivers[i]->type], type)) {
-            return be_drivers[i];
-        }
-    }
-
-    return NULL;
+    return i >= 0 ? be_drivers[i] : NULL;
 }
 
 #ifdef CONFIG_TPM
 
-int tpm_register_driver(const TPMDriverOps *tdo)
+void tpm_register_driver(const TPMDriverOps *tdo)
 {
-    int i;
+    assert(!be_drivers[tdo->type]);
 
-    for (i = 0; i < TPM_MAX_DRIVERS; i++) {
-        if (!be_drivers[i]) {
-            be_drivers[i] = tdo;
-            return 0;
-        }
-    }
-    error_report("Could not register TPM driver");
-    return 1;
+    be_drivers[tdo->type] = tdo;
 }
 
 /*
@@ -101,9 +87,12 @@ static void tpm_display_backend_drivers(void)
 
     fprintf(stderr, "Supported TPM types (choose only one):\n");
 
-    for (i = 0; i < TPM_MAX_DRIVERS && be_drivers[i] != NULL; i++) {
+    for (i = 0; i < TPM_TYPE__MAX; i++) {
+        if (be_drivers[i] == NULL) {
+            continue;
+        }
         fprintf(stderr, "%12s   %s\n",
-                qapi_enum_lookup(TpmType_lookup, be_drivers[i]->type),
+                qapi_enum_lookup(TpmType_lookup, i),
                 be_drivers[i]->desc());
     }
     fprintf(stderr, "\n");
@@ -241,14 +230,7 @@ int tpm_config_parse(QemuOptsList *opts_list, const char *optarg)
 
 static const TPMDriverOps *tpm_driver_find_by_type(enum TpmType type)
 {
-    int i;
-

tpm.c int tpm_config_parse(QemuOptsList *opts_list, const char *optarg) · line 236

Quoted 10 lines
tpm.c +1 -6
-    for (i = 0; i < TPM_MAX_DRIVERS && be_drivers[i] != NULL; i++) {
-        if (be_drivers[i]->type == type) {
-            return be_drivers[i];
-        }
-    }
-    return NULL;
+    return be_drivers[type];
 }
 
 static TPMInfo *qmp_query_tpm_inst(TPMBackend *drv)

You kill the separation of TpmType and be_drivers[]: TpmType values become valid subscripts of be_drivers[]. Good!

You don't touch TpmModel and tpm_models[]. Half of the mess remains in place to confuse the next reader (it certainly confused me, thus the long "before the patch" treatise). Not wrong, therefore

but could you complete the cleanup job? Pretty-please?

Also: since I wrote the "before the patch" treatise already, could (some of) it be worked into the commit message?

#27 lore raw

PATCH v2 8/54 hmp: use qapi_enum_parse() in hmp_migrate_set_capability

In reply to Marc-André Lureau
---
 hmp.c | 24 +++++++++++-------------
 1 file changed, 11 insertions(+), 13 deletions(-)
hmp.c +11 -13
index 29e42ab661..4ba50e8e26 100644
@@ -1544,23 +1544,21 @@ void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict)
     bool state = qdict_get_bool(qdict, "state");
     Error *err = NULL;
     MigrationCapabilityStatusList *caps = g_malloc0(sizeof(*caps));
-    int i;
+    int val;
 
-    for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
-        if (strcmp(cap, MigrationCapability_lookup[i]) == 0) {
-            caps->value = g_malloc0(sizeof(*caps->value));
-            caps->value->capability = i;
-            caps->value->state = state;
-            caps->next = NULL;
-            qmp_migrate_set_capabilities(caps, &err);
-            break;
-        }
+    val = qapi_enum_parse(MigrationCapability_lookup, cap,
+                          MIGRATION_CAPABILITY__MAX, -1, &err);
+    if (val < 0) {
+        goto end;
     }
 
-    if (i == MIGRATION_CAPABILITY__MAX) {
-        error_setg(&err, QERR_INVALID_PARAMETER, cap);
-    }
+    caps->value = g_malloc0(sizeof(*caps->value));
+    caps->value->capability = val;
+    caps->value->state = state;
+    caps->next = NULL;
+    qmp_migrate_set_capabilities(caps, &err);
 
+end:
     qapi_free_MigrationCapabilityStatusList(caps);
 
     if (err) {
Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 8/54
#28 lore raw

Re: [Qemu-devel] [PATCH v2 08/54] hmp: use qapi_enum_parse() in hmp_migrate_set_capability

Quoted 34 lines · Marc-André Lureau
---
 hmp.c | 24 +++++++++++-------------
 1 file changed, 11 insertions(+), 13 deletions(-)
hmp.c +5 -13
index 29e42ab661..4ba50e8e26 100644
@@ -1544,23 +1544,21 @@ void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict)
     bool state = qdict_get_bool(qdict, "state");
     Error *err = NULL;
     MigrationCapabilityStatusList *caps = g_malloc0(sizeof(*caps));
-    int i;
+    int val;
 
-    for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
-        if (strcmp(cap, MigrationCapability_lookup[i]) == 0) {
-            caps->value = g_malloc0(sizeof(*caps->value));
-            caps->value->capability = i;
-            caps->value->state = state;
-            caps->next = NULL;
-            qmp_migrate_set_capabilities(caps, &err);
-            break;
-        }
+    val = qapi_enum_parse(MigrationCapability_lookup, cap,
+                          MIGRATION_CAPABILITY__MAX, -1, &err);
+    if (val < 0) {
+        goto end;
     }
 
-    if (i == MIGRATION_CAPABILITY__MAX) {
-        error_setg(&err, QERR_INVALID_PARAMETER, cap);
-    }

hmp.c void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict) · line 1564

Quoted 10 lines
hmp.c +6 -0
+    caps->value = g_malloc0(sizeof(*caps->value));
+    caps->value->capability = val;
+    caps->value->state = state;
+    caps->next = NULL;
+    qmp_migrate_set_capabilities(caps, &err);
 
+end:
     qapi_free_MigrationCapabilityStatusList(caps);
 
     if (err) {
Reviewed-by on v2 8/54
#29 lore raw

Re: [Qemu-devel] [PATCH v2 08/54] hmp: use qapi_enum_parse() in hmp_migrate_set_capability

In reply to Marc-André Lureau
Quoted 17 lines · * Marc-André Lureau ([email protected]) wrote:
---
 hmp.c | 24 +++++++++++-------------
 1 file changed, 11 insertions(+), 13 deletions(-)
hmp.c +1 -2
index 29e42ab661..4ba50e8e26 100644
@@ -1544,23 +1544,21 @@ void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict)
     bool state = qdict_get_bool(qdict, "state");
     Error *err = NULL;
     MigrationCapabilityStatusList *caps = g_malloc0(sizeof(*caps));
-    int i;
+    int val;
 
-    for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {

hmp.c void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict) · line 1550

Quoted 10 lines
hmp.c +2 -8
-        if (strcmp(cap, MigrationCapability_lookup[i]) == 0) {
-            caps->value = g_malloc0(sizeof(*caps->value));
-            caps->value->capability = i;
-            caps->value->state = state;
-            caps->next = NULL;
-            qmp_migrate_set_capabilities(caps, &err);
-            break;
-        }
+    val = qapi_enum_parse(MigrationCapability_lookup, cap,
+                          MIGRATION_CAPABILITY__MAX, -1, &err);

It would be nice to macro that to something like:
MigrationCapability_parse(cap, -1, &err);

which would stop the inevitable case of someone using the wrong _lookup with the wrong _MAX.

I also wonder if having the qapi_enum_parse return a bool and take a &int would be nicer - it would get rid of the need for the -1 default and mean actually it could be an unsigned.

Still, those are only suggestions, so:

Quoted 20 lines
hmp.c +8 -3
+    if (val < 0) {
+        goto end;
     }
 
-    if (i == MIGRATION_CAPABILITY__MAX) {
-        error_setg(&err, QERR_INVALID_PARAMETER, cap);
-    }
+    caps->value = g_malloc0(sizeof(*caps->value));
+    caps->value->capability = val;
+    caps->value->state = state;
+    caps->next = NULL;
+    qmp_migrate_set_capabilities(caps, &err);
 
+end:
     qapi_free_MigrationCapabilityStatusList(caps);
 
     if (err) {
Signature · 1 line
2.14.1.146.gd35faa819

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#30 lore raw

PATCH v2 9/54 hmp: use qapi_enum_parse() in hmp_migrate_set_parameter

In reply to Marc-André Lureau
---
 hmp.c | 139 ++++++++++++++++++++++++++++++++----------------------------------
 1 file changed, 68 insertions(+), 71 deletions(-)
hmp.c +68 -71
index 4ba50e8e26..ccc58e6d88 100644
@@ -1574,84 +1574,81 @@ void hmp_migrate_set_parameter(Monitor *mon, const QDict *qdict)
     MigrateSetParameters *p = g_new0(MigrateSetParameters, 1);
     uint64_t valuebw = 0;
     Error *err = NULL;
-    int i, ret;
-
-    for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
-        if (strcmp(param, MigrationParameter_lookup[i]) == 0) {
-            switch (i) {
-            case MIGRATION_PARAMETER_COMPRESS_LEVEL:
-                p->has_compress_level = true;
-                visit_type_int(v, param, &p->compress_level, &err);
-                break;
-            case MIGRATION_PARAMETER_COMPRESS_THREADS:
-                p->has_compress_threads = true;
-                visit_type_int(v, param, &p->compress_threads, &err);
-                break;
-            case MIGRATION_PARAMETER_DECOMPRESS_THREADS:
-                p->has_decompress_threads = true;
-                visit_type_int(v, param, &p->decompress_threads, &err);
-                break;
-            case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:
-                p->has_cpu_throttle_initial = true;
-                visit_type_int(v, param, &p->cpu_throttle_initial, &err);
-                break;
-            case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:
-                p->has_cpu_throttle_increment = true;
-                visit_type_int(v, param, &p->cpu_throttle_increment, &err);
-                break;
-            case MIGRATION_PARAMETER_TLS_CREDS:
-                p->has_tls_creds = true;
-                p->tls_creds = g_new0(StrOrNull, 1);
-                p->tls_creds->type = QTYPE_QSTRING;
-                visit_type_str(v, param, &p->tls_creds->u.s, &err);
-                break;
-            case MIGRATION_PARAMETER_TLS_HOSTNAME:
-                p->has_tls_hostname = true;
-                p->tls_hostname = g_new0(StrOrNull, 1);
-                p->tls_hostname->type = QTYPE_QSTRING;
-                visit_type_str(v, param, &p->tls_hostname->u.s, &err);
-                break;
-            case MIGRATION_PARAMETER_MAX_BANDWIDTH:
-                p->has_max_bandwidth = true;
-                /*
-                 * Can't use visit_type_size() here, because it
-                 * defaults to Bytes rather than Mebibytes.
-                 */
-                ret = qemu_strtosz_MiB(valuestr, NULL, &valuebw);
-                if (ret < 0 || valuebw > INT64_MAX
-                    || (size_t)valuebw != valuebw) {
-                    error_setg(&err, "Invalid size %s", valuestr);
-                    break;
-                }
-                p->max_bandwidth = valuebw;
-                break;
-            case MIGRATION_PARAMETER_DOWNTIME_LIMIT:
-                p->has_downtime_limit = true;
-                visit_type_int(v, param, &p->downtime_limit, &err);
-                break;
-            case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:
-                p->has_x_checkpoint_delay = true;
-                visit_type_int(v, param, &p->x_checkpoint_delay, &err);
-                break;
-            case MIGRATION_PARAMETER_BLOCK_INCREMENTAL:
-                p->has_block_incremental = true;
-                visit_type_bool(v, param, &p->block_incremental, &err);
-                break;
-            }
+    int val, ret;
 
-            if (err) {
-                goto cleanup;
-            }
-
-            qmp_migrate_set_parameters(p, &err);
+    val = qapi_enum_parse(MigrationParameter_lookup, param,
+                          MIGRATION_PARAMETER__MAX,  -1, &err);
+    if (val < 0) {
+        goto cleanup;
+    }
+
+    switch (val) {
+    case MIGRATION_PARAMETER_COMPRESS_LEVEL:
+        p->has_compress_level = true;
+        visit_type_int(v, param, &p->compress_level, &err);
+        break;
+    case MIGRATION_PARAMETER_COMPRESS_THREADS:
+        p->has_compress_threads = true;
+        visit_type_int(v, param, &p->compress_threads, &err);
+        break;
+    case MIGRATION_PARAMETER_DECOMPRESS_THREADS:
+        p->has_decompress_threads = true;
+        visit_type_int(v, param, &p->decompress_threads, &err);
+        break;
+    case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:
+        p->has_cpu_throttle_initial = true;
+        visit_type_int(v, param, &p->cpu_throttle_initial, &err);
+        break;
+    case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:
+        p->has_cpu_throttle_increment = true;
+        visit_type_int(v, param, &p->cpu_throttle_increment, &err);
+        break;
+    case MIGRATION_PARAMETER_TLS_CREDS:
+        p->has_tls_creds = true;
+        p->tls_creds = g_new0(StrOrNull, 1);
+        p->tls_creds->type = QTYPE_QSTRING;
+        visit_type_str(v, param, &p->tls_creds->u.s, &err);
+        break;
+    case MIGRATION_PARAMETER_TLS_HOSTNAME:
+        p->has_tls_hostname = true;
+        p->tls_hostname = g_new0(StrOrNull, 1);
+        p->tls_hostname->type = QTYPE_QSTRING;
+        visit_type_str(v, param, &p->tls_hostname->u.s, &err);
+        break;
+    case MIGRATION_PARAMETER_MAX_BANDWIDTH:
+        p->has_max_bandwidth = true;
+        /*
+         * Can't use visit_type_size() here, because it
+         * defaults to Bytes rather than Mebibytes.
+         */
+        ret = qemu_strtosz_MiB(valuestr, NULL, &valuebw);
+        if (ret < 0 || valuebw > INT64_MAX
+            || (size_t)valuebw != valuebw) {
+            error_setg(&err, "Invalid size %s", valuestr);
             break;
         }
+        p->max_bandwidth = valuebw;
+        break;
+    case MIGRATION_PARAMETER_DOWNTIME_LIMIT:
+        p->has_downtime_limit = true;
+        visit_type_int(v, param, &p->downtime_limit, &err);
+        break;
+    case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:
+        p->has_x_checkpoint_delay = true;
+        visit_type_int(v, param, &p->x_checkpoint_delay, &err);
+        break;
+    case MIGRATION_PARAMETER_BLOCK_INCREMENTAL:
+        p->has_block_incremental = true;
+        visit_type_bool(v, param, &p->block_incremental, &err);
+        break;
     }
 
-    if (i == MIGRATION_PARAMETER__MAX) {
-        error_setg(&err, QERR_INVALID_PARAMETER, param);
+    if (err) {
+        goto cleanup;
     }
 
+    qmp_migrate_set_parameters(p, &err);
+
  cleanup:
     qapi_free_MigrateSetParameters(p);
     visit_free(v);
Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 9/54
#31 lore raw

Re: [Qemu-devel] [PATCH v2 09/54] hmp: use qapi_enum_parse() in hmp_migrate_set_parameter

Quoted 152 lines · Marc-André Lureau
---
 hmp.c | 139 ++++++++++++++++++++++++++++++++----------------------------------
 1 file changed, 68 insertions(+), 71 deletions(-)
hmp.c +64 -70
index 4ba50e8e26..ccc58e6d88 100644
@@ -1574,84 +1574,81 @@ void hmp_migrate_set_parameter(Monitor *mon, const QDict *qdict)
     MigrateSetParameters *p = g_new0(MigrateSetParameters, 1);
     uint64_t valuebw = 0;
     Error *err = NULL;
-    int i, ret;
-
-    for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
-        if (strcmp(param, MigrationParameter_lookup[i]) == 0) {
-            switch (i) {
-            case MIGRATION_PARAMETER_COMPRESS_LEVEL:
-                p->has_compress_level = true;
-                visit_type_int(v, param, &p->compress_level, &err);
-                break;
-            case MIGRATION_PARAMETER_COMPRESS_THREADS:
-                p->has_compress_threads = true;
-                visit_type_int(v, param, &p->compress_threads, &err);
-                break;
-            case MIGRATION_PARAMETER_DECOMPRESS_THREADS:
-                p->has_decompress_threads = true;
-                visit_type_int(v, param, &p->decompress_threads, &err);
-                break;
-            case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:
-                p->has_cpu_throttle_initial = true;
-                visit_type_int(v, param, &p->cpu_throttle_initial, &err);
-                break;
-            case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:
-                p->has_cpu_throttle_increment = true;
-                visit_type_int(v, param, &p->cpu_throttle_increment, &err);
-                break;
-            case MIGRATION_PARAMETER_TLS_CREDS:
-                p->has_tls_creds = true;
-                p->tls_creds = g_new0(StrOrNull, 1);
-                p->tls_creds->type = QTYPE_QSTRING;
-                visit_type_str(v, param, &p->tls_creds->u.s, &err);
-                break;
-            case MIGRATION_PARAMETER_TLS_HOSTNAME:
-                p->has_tls_hostname = true;
-                p->tls_hostname = g_new0(StrOrNull, 1);
-                p->tls_hostname->type = QTYPE_QSTRING;
-                visit_type_str(v, param, &p->tls_hostname->u.s, &err);
-                break;
-            case MIGRATION_PARAMETER_MAX_BANDWIDTH:
-                p->has_max_bandwidth = true;
-                /*
-                 * Can't use visit_type_size() here, because it
-                 * defaults to Bytes rather than Mebibytes.
-                 */
-                ret = qemu_strtosz_MiB(valuestr, NULL, &valuebw);
-                if (ret < 0 || valuebw > INT64_MAX
-                    || (size_t)valuebw != valuebw) {
-                    error_setg(&err, "Invalid size %s", valuestr);
-                    break;
-                }
-                p->max_bandwidth = valuebw;
-                break;
-            case MIGRATION_PARAMETER_DOWNTIME_LIMIT:
-                p->has_downtime_limit = true;
-                visit_type_int(v, param, &p->downtime_limit, &err);
-                break;
-            case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:
-                p->has_x_checkpoint_delay = true;
-                visit_type_int(v, param, &p->x_checkpoint_delay, &err);
-                break;
-            case MIGRATION_PARAMETER_BLOCK_INCREMENTAL:
-                p->has_block_incremental = true;
-                visit_type_bool(v, param, &p->block_incremental, &err);
-                break;
-            }
+    int val, ret;
 
-            if (err) {
-                goto cleanup;
-            }
-
-            qmp_migrate_set_parameters(p, &err);
+    val = qapi_enum_parse(MigrationParameter_lookup, param,
+                          MIGRATION_PARAMETER__MAX,  -1, &err);
+    if (val < 0) {
+        goto cleanup;
+    }
+
+    switch (val) {
+    case MIGRATION_PARAMETER_COMPRESS_LEVEL:
+        p->has_compress_level = true;
+        visit_type_int(v, param, &p->compress_level, &err);
+        break;
+    case MIGRATION_PARAMETER_COMPRESS_THREADS:
+        p->has_compress_threads = true;
+        visit_type_int(v, param, &p->compress_threads, &err);
+        break;
+    case MIGRATION_PARAMETER_DECOMPRESS_THREADS:
+        p->has_decompress_threads = true;
+        visit_type_int(v, param, &p->decompress_threads, &err);
+        break;
+    case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:
+        p->has_cpu_throttle_initial = true;
+        visit_type_int(v, param, &p->cpu_throttle_initial, &err);
+        break;
+    case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:
+        p->has_cpu_throttle_increment = true;
+        visit_type_int(v, param, &p->cpu_throttle_increment, &err);
+        break;
+    case MIGRATION_PARAMETER_TLS_CREDS:
+        p->has_tls_creds = true;
+        p->tls_creds = g_new0(StrOrNull, 1);
+        p->tls_creds->type = QTYPE_QSTRING;
+        visit_type_str(v, param, &p->tls_creds->u.s, &err);
+        break;
+    case MIGRATION_PARAMETER_TLS_HOSTNAME:
+        p->has_tls_hostname = true;
+        p->tls_hostname = g_new0(StrOrNull, 1);
+        p->tls_hostname->type = QTYPE_QSTRING;
+        visit_type_str(v, param, &p->tls_hostname->u.s, &err);
+        break;
+    case MIGRATION_PARAMETER_MAX_BANDWIDTH:
+        p->has_max_bandwidth = true;
+        /*
+         * Can't use visit_type_size() here, because it
+         * defaults to Bytes rather than Mebibytes.
+         */
+        ret = qemu_strtosz_MiB(valuestr, NULL, &valuebw);
+        if (ret < 0 || valuebw > INT64_MAX
+            || (size_t)valuebw != valuebw) {
+            error_setg(&err, "Invalid size %s", valuestr);
             break;
         }
+        p->max_bandwidth = valuebw;
+        break;
+    case MIGRATION_PARAMETER_DOWNTIME_LIMIT:
+        p->has_downtime_limit = true;
+        visit_type_int(v, param, &p->downtime_limit, &err);
+        break;
+    case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:
+        p->has_x_checkpoint_delay = true;
+        visit_type_int(v, param, &p->x_checkpoint_delay, &err);
+        break;
+    case MIGRATION_PARAMETER_BLOCK_INCREMENTAL:
+        p->has_block_incremental = true;
+        visit_type_bool(v, param, &p->block_incremental, &err);
+        break;
     }
 
-    if (i == MIGRATION_PARAMETER__MAX) {

hmp.c void hmp_migrate_set_parameter(Monitor *mon, const QDict *qdict) · line 1654

Quoted 10 lines
hmp.c +4 -1
-        error_setg(&err, QERR_INVALID_PARAMETER, param);
+    if (err) {
+        goto cleanup;
     }
 
+    qmp_migrate_set_parameters(p, &err);
+
  cleanup:
     qapi_free_MigrateSetParameters(p);
     visit_free(v);

Easier to review with space change ignored:

  diff --git a/hmp.c b/hmp.c
  index 4ba50e8..ccc58e6 100644
  --- a/hmp.c
  +++ b/hmp.c
  @@ -1574,11 +1574,15 @@
       MigrateSetParameters *p = g_new0(MigrateSetParameters, 1);
       uint64_t valuebw = 0;
       Error *err = NULL;
  -    int i, ret;
  +    int val, ret;

- for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
- if (strcmp(param, MigrationParameter_lookup[i]) == 0) {
- switch (i) {
+ val = qapi_enum_parse(MigrationParameter_lookup, param,
+ MIGRATION_PARAMETER__MAX, -1, &err);
+ if (val < 0) {
+ goto cleanup;
+ }
+

  +    switch (val) {
               case MIGRATION_PARAMETER_COMPRESS_LEVEL:
                   p->has_compress_level = true;
                   visit_type_int(v, param, &p->compress_level, &err);
  @@ -1644,13 +1648,6 @@
               }

               qmp_migrate_set_parameters(p, &err);

- break;
- }
- }
-
- if (i == MIGRATION_PARAMETER__MAX) {
- error_setg(&err, QERR_INVALID_PARAMETER, param);
- }

    cleanup:
       qapi_free_MigrateSetParameters(p);

--
2.7.5

Looks good, although a default: abort() wouldn't hurt.

#32 lore raw

Re: [Qemu-devel] [PATCH v2 09/54] hmp: use qapi_enum_parse() in hmp_migrate_set_parameter

Quoted 203 lines · * Markus Armbruster ([email protected]) wrote:
Quoted 152 lines · Marc-André Lureau
---
 hmp.c | 139 ++++++++++++++++++++++++++++++++----------------------------------
 1 file changed, 68 insertions(+), 71 deletions(-)
hmp.c +64 -70
index 4ba50e8e26..ccc58e6d88 100644
@@ -1574,84 +1574,81 @@ void hmp_migrate_set_parameter(Monitor *mon, const QDict *qdict)
     MigrateSetParameters *p = g_new0(MigrateSetParameters, 1);
     uint64_t valuebw = 0;
     Error *err = NULL;
-    int i, ret;
-
-    for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
-        if (strcmp(param, MigrationParameter_lookup[i]) == 0) {
-            switch (i) {
-            case MIGRATION_PARAMETER_COMPRESS_LEVEL:
-                p->has_compress_level = true;
-                visit_type_int(v, param, &p->compress_level, &err);
-                break;
-            case MIGRATION_PARAMETER_COMPRESS_THREADS:
-                p->has_compress_threads = true;
-                visit_type_int(v, param, &p->compress_threads, &err);
-                break;
-            case MIGRATION_PARAMETER_DECOMPRESS_THREADS:
-                p->has_decompress_threads = true;
-                visit_type_int(v, param, &p->decompress_threads, &err);
-                break;
-            case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:
-                p->has_cpu_throttle_initial = true;
-                visit_type_int(v, param, &p->cpu_throttle_initial, &err);
-                break;
-            case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:
-                p->has_cpu_throttle_increment = true;
-                visit_type_int(v, param, &p->cpu_throttle_increment, &err);
-                break;
-            case MIGRATION_PARAMETER_TLS_CREDS:
-                p->has_tls_creds = true;
-                p->tls_creds = g_new0(StrOrNull, 1);
-                p->tls_creds->type = QTYPE_QSTRING;
-                visit_type_str(v, param, &p->tls_creds->u.s, &err);
-                break;
-            case MIGRATION_PARAMETER_TLS_HOSTNAME:
-                p->has_tls_hostname = true;
-                p->tls_hostname = g_new0(StrOrNull, 1);
-                p->tls_hostname->type = QTYPE_QSTRING;
-                visit_type_str(v, param, &p->tls_hostname->u.s, &err);
-                break;
-            case MIGRATION_PARAMETER_MAX_BANDWIDTH:
-                p->has_max_bandwidth = true;
-                /*
-                 * Can't use visit_type_size() here, because it
-                 * defaults to Bytes rather than Mebibytes.
-                 */
-                ret = qemu_strtosz_MiB(valuestr, NULL, &valuebw);
-                if (ret < 0 || valuebw > INT64_MAX
-                    || (size_t)valuebw != valuebw) {
-                    error_setg(&err, "Invalid size %s", valuestr);
-                    break;
-                }
-                p->max_bandwidth = valuebw;
-                break;
-            case MIGRATION_PARAMETER_DOWNTIME_LIMIT:
-                p->has_downtime_limit = true;
-                visit_type_int(v, param, &p->downtime_limit, &err);
-                break;
-            case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:
-                p->has_x_checkpoint_delay = true;
-                visit_type_int(v, param, &p->x_checkpoint_delay, &err);
-                break;
-            case MIGRATION_PARAMETER_BLOCK_INCREMENTAL:
-                p->has_block_incremental = true;
-                visit_type_bool(v, param, &p->block_incremental, &err);
-                break;
-            }
+    int val, ret;
 
-            if (err) {
-                goto cleanup;
-            }
-
-            qmp_migrate_set_parameters(p, &err);
+    val = qapi_enum_parse(MigrationParameter_lookup, param,
+                          MIGRATION_PARAMETER__MAX,  -1, &err);
+    if (val < 0) {
+        goto cleanup;
+    }
+
+    switch (val) {
+    case MIGRATION_PARAMETER_COMPRESS_LEVEL:
+        p->has_compress_level = true;
+        visit_type_int(v, param, &p->compress_level, &err);
+        break;
+    case MIGRATION_PARAMETER_COMPRESS_THREADS:
+        p->has_compress_threads = true;
+        visit_type_int(v, param, &p->compress_threads, &err);
+        break;
+    case MIGRATION_PARAMETER_DECOMPRESS_THREADS:
+        p->has_decompress_threads = true;
+        visit_type_int(v, param, &p->decompress_threads, &err);
+        break;
+    case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:
+        p->has_cpu_throttle_initial = true;
+        visit_type_int(v, param, &p->cpu_throttle_initial, &err);
+        break;
+    case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:
+        p->has_cpu_throttle_increment = true;
+        visit_type_int(v, param, &p->cpu_throttle_increment, &err);
+        break;
+    case MIGRATION_PARAMETER_TLS_CREDS:
+        p->has_tls_creds = true;
+        p->tls_creds = g_new0(StrOrNull, 1);
+        p->tls_creds->type = QTYPE_QSTRING;
+        visit_type_str(v, param, &p->tls_creds->u.s, &err);
+        break;
+    case MIGRATION_PARAMETER_TLS_HOSTNAME:
+        p->has_tls_hostname = true;
+        p->tls_hostname = g_new0(StrOrNull, 1);
+        p->tls_hostname->type = QTYPE_QSTRING;
+        visit_type_str(v, param, &p->tls_hostname->u.s, &err);
+        break;
+    case MIGRATION_PARAMETER_MAX_BANDWIDTH:
+        p->has_max_bandwidth = true;
+        /*
+         * Can't use visit_type_size() here, because it
+         * defaults to Bytes rather than Mebibytes.
+         */
+        ret = qemu_strtosz_MiB(valuestr, NULL, &valuebw);
+        if (ret < 0 || valuebw > INT64_MAX
+            || (size_t)valuebw != valuebw) {
+            error_setg(&err, "Invalid size %s", valuestr);
             break;
         }
+        p->max_bandwidth = valuebw;
+        break;
+    case MIGRATION_PARAMETER_DOWNTIME_LIMIT:
+        p->has_downtime_limit = true;
+        visit_type_int(v, param, &p->downtime_limit, &err);
+        break;
+    case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:
+        p->has_x_checkpoint_delay = true;
+        visit_type_int(v, param, &p->x_checkpoint_delay, &err);
+        break;
+    case MIGRATION_PARAMETER_BLOCK_INCREMENTAL:
+        p->has_block_incremental = true;
+        visit_type_bool(v, param, &p->block_incremental, &err);
+        break;
     }
 
-    if (i == MIGRATION_PARAMETER__MAX) {

hmp.c void hmp_migrate_set_parameter(Monitor *mon, const QDict *qdict) · line 1654

Quoted 10 lines
hmp.c +4 -1
-        error_setg(&err, QERR_INVALID_PARAMETER, param);
+    if (err) {
+        goto cleanup;
     }
 
+    qmp_migrate_set_parameters(p, &err);
+
  cleanup:
     qapi_free_MigrateSetParameters(p);
     visit_free(v);

Easier to review with space change ignored:

  diff --git a/hmp.c b/hmp.c
  index 4ba50e8..ccc58e6 100644
  --- a/hmp.c
  +++ b/hmp.c
  @@ -1574,11 +1574,15 @@
       MigrateSetParameters *p = g_new0(MigrateSetParameters, 1);
       uint64_t valuebw = 0;
       Error *err = NULL;
  -    int i, ret;
  +    int val, ret;

- for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
- if (strcmp(param, MigrationParameter_lookup[i]) == 0) {
- switch (i) {
+ val = qapi_enum_parse(MigrationParameter_lookup, param,
+ MIGRATION_PARAMETER__MAX, -1, &err);
+ if (val < 0) {
+ goto cleanup;
+ }
+

  +    switch (val) {
               case MIGRATION_PARAMETER_COMPRESS_LEVEL:
                   p->has_compress_level = true;
                   visit_type_int(v, param, &p->compress_level, &err);
  @@ -1644,13 +1648,6 @@
               }

               qmp_migrate_set_parameters(p, &err);

- break;
- }
- }
-
- if (i == MIGRATION_PARAMETER__MAX) {
- error_setg(&err, QERR_INVALID_PARAMETER, param);
- }

Quoted 8 lines
    cleanup:
       qapi_free_MigrateSetParameters(p);

--
2.7.5

Looks good, although a default: abort() wouldn't hurt.

--
Dr. David Alan Gilbert / [email protected] / Manchester, UK

#33 lore raw

PATCH v2 10/54 block: use qemu_enum_parse() in blkdebug_debug_breakpoint

In reply to Marc-André Lureau

This slightly change the error report message from "Invalid event name" to "Invalid parameter".

---
 block/blkdebug.c | 28 ++++++++--------------------
 1 file changed, 8 insertions(+), 20 deletions(-)
block/blkdebug.c +8 -20
index c19ab28f07..50edda2a31 100644
@@ -32,6 +32,7 @@
 #include "qapi/qmp/qbool.h"
 #include "qapi/qmp/qdict.h"
 #include "qapi/qmp/qstring.h"
+#include "qapi/util.h"
 #include "sysemu/qtest.h"
 
 typedef struct BDRVBlkdebugState {
@@ -149,20 +150,6 @@ static QemuOptsList *config_groups[] = {
     NULL
 };
 
-static int get_event_by_name(const char *name, BlkdebugEvent *event)
-{
-    int i;
-
-    for (i = 0; i < BLKDBG__MAX; i++) {
-        if (!strcmp(BlkdebugEvent_lookup[i], name)) {
-            *event = i;
-            return 0;
-        }
-    }
-
-    return -1;
-}
-
 struct add_rule_data {
     BDRVBlkdebugState *s;
     int action;
@@ -173,7 +160,7 @@ static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
     struct add_rule_data *d = opaque;
     BDRVBlkdebugState *s = d->s;
     const char* event_name;
-    BlkdebugEvent event;
+    int event;
     struct BlkdebugRule *rule;
     int64_t sector;
 
@@ -182,8 +169,9 @@ static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
     if (!event_name) {
         error_setg(errp, "Missing event name for rule");
         return -1;
-    } else if (get_event_by_name(event_name, &event) < 0) {
-        error_setg(errp, "Invalid event name \"%s\"", event_name);
+    }
+    event = qapi_enum_parse(BlkdebugEvent_lookup, event_name, BLKDBG__MAX, -1, errp);
+    if (event < 0) {
         return -1;
     }
 
@@ -743,13 +731,13 @@ static int blkdebug_debug_breakpoint(BlockDriverState *bs, const char *event,
 {
     BDRVBlkdebugState *s = bs->opaque;
     struct BlkdebugRule *rule;
-    BlkdebugEvent blkdebug_event;
+    int blkdebug_event;
 
-    if (get_event_by_name(event, &blkdebug_event) < 0) {
+    blkdebug_event = qapi_enum_parse(BlkdebugEvent_lookup, event, BLKDBG__MAX, -1, NULL);
+    if (blkdebug_event < 0) {
         return -ENOENT;
     }
 
-
     rule = g_malloc(sizeof(*rule));
     *rule = (struct BlkdebugRule) {
         .event  = blkdebug_event,
Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 10/54
#34 lore raw

Re: [Qemu-devel] [PATCH v2 10/54] block: use qemu_enum_parse() in blkdebug_debug_breakpoint

Quoted 2 lines · Marc-André Lureau

This slightly change the error report message from "Invalid event name" to "Invalid parameter".

Actually from

qemu-system-x86_64: LOCATION: Invalid event name "VALUE"

to

qemu-system-x86_64: LOCATION: invalid parameter value: VALUE

Let's get that exactly right in the commit message.

Slight degradation, but the message is sub-par even before the patch. When complaining about a parameter value, both parameter name and value should be mentioned, as the value may well not be unique. Not this patch's problem.

Aside: LOCATION points to where the blkdebug driver is configured. It should point to the error's actual location instead: the configuration file named with config=... Also not this patch's problem.

Quoted 49 lines
---
 block/blkdebug.c | 28 ++++++++--------------------
 1 file changed, 8 insertions(+), 20 deletions(-)
block/blkdebug.c +2 -15
index c19ab28f07..50edda2a31 100644
@@ -32,6 +32,7 @@
 #include "qapi/qmp/qbool.h"
 #include "qapi/qmp/qdict.h"
 #include "qapi/qmp/qstring.h"
+#include "qapi/util.h"
 #include "sysemu/qtest.h"
 
 typedef struct BDRVBlkdebugState {
@@ -149,20 +150,6 @@ static QemuOptsList *config_groups[] = {
     NULL
 };
 
-static int get_event_by_name(const char *name, BlkdebugEvent *event)
-{
-    int i;
-
-    for (i = 0; i < BLKDBG__MAX; i++) {
-        if (!strcmp(BlkdebugEvent_lookup[i], name)) {
-            *event = i;
-            return 0;
-        }
-    }
-
-    return -1;
-}
-
 struct add_rule_data {
     BDRVBlkdebugState *s;
     int action;
@@ -173,7 +160,7 @@ static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
     struct add_rule_data *d = opaque;
     BDRVBlkdebugState *s = d->s;
     const char* event_name;
-    BlkdebugEvent event;
+    int event;
     struct BlkdebugRule *rule;
     int64_t sector;
 

block/blkdebug.c static int add_rule(void *opaque, QemuOpts *opts, Error **errp) · line 173

Quoted 7 lines
block/blkdebug.c +2 -2
@@ -182,8 +169,9 @@ static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
     if (!event_name) {
         error_setg(errp, "Missing event name for rule");
         return -1;
-    } else if (get_event_by_name(event_name, &event) < 0) {
-        error_setg(errp, "Invalid event name \"%s\"", event_name);
+    }
+    event = qapi_enum_parse(BlkdebugEvent_lookup, event_name, BLKDBG__MAX, -1, errp);

Long line.

block/blkdebug.c static int blkdebug_debug_breakpoint(BlockDriverState *bs, const char *event, · line 736

Quoted 13 lines
block/blkdebug.c +3 -2
+    if (event < 0) {
         return -1;
     }
 
@@ -743,13 +731,13 @@ static int blkdebug_debug_breakpoint(BlockDriverState *bs, const char *event,
 {
     BDRVBlkdebugState *s = bs->opaque;
     struct BlkdebugRule *rule;
-    BlkdebugEvent blkdebug_event;
+    int blkdebug_event;
 
-    if (get_event_by_name(event, &blkdebug_event) < 0) {
+    blkdebug_event = qapi_enum_parse(BlkdebugEvent_lookup, event, BLKDBG__MAX, -1, NULL);

Long line.

block/blkdebug.c static int blkdebug_debug_breakpoint(BlockDriverState *bs, const char *event, · line 743

Quoted 8 lines
block/blkdebug.c +1 -1
+    if (blkdebug_event < 0) {
         return -ENOENT;
     }
 
-
     rule = g_malloc(sizeof(*rule));
     *rule = (struct BlkdebugRule) {
         .event  = blkdebug_event,

With the nits touched up:

#35 lore raw

PATCH v2 11/54 quorum: use qapi_enum_parse() in quorum_open

In reply to Marc-André Lureau
---
 block/quorum.c | 27 ++++++++-------------------
 1 file changed, 8 insertions(+), 19 deletions(-)
block/quorum.c +8 -19
index d04da4f430..e4271caa7a 100644
@@ -22,6 +22,7 @@
 #include "qapi/qmp/qjson.h"
 #include "qapi/qmp/qlist.h"
 #include "qapi/qmp/qstring.h"
+#include "qapi/util.h"
 #include "qapi-event.h"
 #include "crypto/hash.h"
 
@@ -867,24 +868,6 @@ static QemuOptsList quorum_runtime_opts = {
     },
 };
 
-static int parse_read_pattern(const char *opt)
-{
-    int i;
-
-    if (!opt) {
-        /* Set quorum as default */
-        return QUORUM_READ_PATTERN_QUORUM;
-    }
-
-    for (i = 0; i < QUORUM_READ_PATTERN__MAX; i++) {
-        if (!strcmp(opt, QuorumReadPattern_lookup[i])) {
-            return i;
-        }
-    }
-
-    return -EINVAL;
-}
-
 static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
                        Error **errp)
 {
@@ -925,7 +908,13 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
         goto exit;
     }
 
-    ret = parse_read_pattern(qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN));
+    if (!qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN)) {
+        ret = QUORUM_READ_PATTERN_QUORUM;
+    } else {
+        ret = qapi_enum_parse(QuorumReadPattern_lookup,
+                              qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
+                              QUORUM_READ_PATTERN__MAX, -EINVAL, NULL);
+    }
     if (ret < 0) {
         error_setg(&local_err, "Please set read-pattern as fifo or quorum");
         goto exit;
Signature · 1 line
2.14.1.146.gd35faa819
#36 lore raw

Re: [Qemu-devel] [PATCH v2 11/54] quorum: use qapi_enum_parse() in quorum_open

block/quorum.c static int quorum_open(BlockDriverState *bs, QDict *options, int flags, · line 917

Quoted 12 lines · Marc-André Lureau
block/quorum.c +7 -1
@@ -925,7 +908,13 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
         goto exit;
     }
 
-    ret = parse_read_pattern(qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN));
+    if (!qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN)) {
+        ret = QUORUM_READ_PATTERN_QUORUM;
+    } else {
+        ret = qapi_enum_parse(QuorumReadPattern_lookup,
+                              qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
+                              QUORUM_READ_PATTERN__MAX, -EINVAL, NULL);
+    }

I don't like so much that you call qemu_opt_get() twice with the same parameters, but else the change makes sense.

Berto

#37 lore raw

Re: [Qemu-devel] [PATCH v2 11/54] quorum: use qapi_enum_parse() in quorum_open

Quoted 6 lines · Alberto Garcia
Quoted 4 lines · Marc-André Lureau
block/quorum.c +0 -0
@@ -925,7 +908,13 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
         goto exit;
     }
 
Quoted 11 lines

block/quorum.c static int quorum_open(BlockDriverState *bs, QDict *options, int flags, · line 917

Quoted 8 lines
block/quorum.c +7 -1
-    ret = parse_read_pattern(qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN));
+    if (!qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN)) {
+        ret = QUORUM_READ_PATTERN_QUORUM;
+    } else {
+        ret = qapi_enum_parse(QuorumReadPattern_lookup,
+                              qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
+                              QUORUM_READ_PATTERN__MAX, -EINVAL, NULL);
+    }

I don't like so much that you call qemu_opt_get() twice with the same parameters,

Easy enough to avoid.

Quoted 1 line

but else the change makes sense.

Is that an R-by? R-by if qemu_opt_get() is called just once?

#38 lore raw

Re: [Qemu-devel] [PATCH v2 11/54] quorum: use qapi_enum_parse() in quorum_open

In reply to Marc-André Lureau
Quoted 47 lines · Marc-André Lureau
---
 block/quorum.c | 27 ++++++++-------------------
 1 file changed, 8 insertions(+), 19 deletions(-)
block/quorum.c +1 -19
index d04da4f430..e4271caa7a 100644
@@ -22,6 +22,7 @@
 #include "qapi/qmp/qjson.h"
 #include "qapi/qmp/qlist.h"
 #include "qapi/qmp/qstring.h"
+#include "qapi/util.h"
 #include "qapi-event.h"
 #include "crypto/hash.h"
 
@@ -867,24 +868,6 @@ static QemuOptsList quorum_runtime_opts = {
     },
 };
 
-static int parse_read_pattern(const char *opt)
-{
-    int i;
-
-    if (!opt) {
-        /* Set quorum as default */
-        return QUORUM_READ_PATTERN_QUORUM;
-    }
-
-    for (i = 0; i < QUORUM_READ_PATTERN__MAX; i++) {
-        if (!strcmp(opt, QuorumReadPattern_lookup[i])) {
-            return i;
-        }
-    }
-
-    return -EINVAL;
-}
-
 static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
                        Error **errp)
 {
@@ -925,7 +908,13 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
         goto exit;
     }
 
-    ret = parse_read_pattern(qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN));

block/quorum.c static int quorum_open(BlockDriverState *bs, QDict *options, int flags, · line 920

Quoted 10 lines
block/quorum.c +7 -0
+    if (!qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN)) {
+        ret = QUORUM_READ_PATTERN_QUORUM;
+    } else {
+        ret = qapi_enum_parse(QuorumReadPattern_lookup,
+                              qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
+                              QUORUM_READ_PATTERN__MAX, -EINVAL, NULL);
+    }
     if (ret < 0) {
         error_setg(&local_err, "Please set read-pattern as fifo or quorum");
         goto exit;

qapi_enum_parse() copes with null input: it returns its fourth argument then. I don't like that also returns it on error, but that shouldn't be a problem here.

If we can live with qapi_enum_parse()'s sub-par error message, then this should do:

       ret = qapi_enum_parse(QuorumReadPattern_lookup,
                             qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
                             QUORUM_READ_PATTERN__MAX,
                             QUORUM_READ_PATTERN_QUORUM, &local_err);
       if (local_err) {
           goto exit;
       }

If not, we'd have to replace @local_err:

       if (local_err) {
           error_free(local_err);
           error_setg(&local_err, "Please set read-pattern as fifo or quorum");
           goto exit;
       }

or amend it with error_append_hint() or error_prepend().

Berto, what do you think?

Reviewed-by
#39 lore raw

Re: [Qemu-devel] [PATCH v2 11/54] quorum: use qapi_enum_parse() in quorum_open

Quoted 26 lines · Markus Armbruster
Quoted 8 lines

static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{

block/quorum.c +0 -1
@@ -925,7 +908,13 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
         goto exit;
     }
 
-    ret = parse_read_pattern(qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN));

block/quorum.c static int quorum_open(BlockDriverState *bs, QDict *options, int flags, · line 920

Quoted 10 lines
block/quorum.c +7 -0
+    if (!qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN)) {
+        ret = QUORUM_READ_PATTERN_QUORUM;
+    } else {
+        ret = qapi_enum_parse(QuorumReadPattern_lookup,
+                              qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
+                              QUORUM_READ_PATTERN__MAX, -EINVAL, NULL);
+    }
     if (ret < 0) {
         error_setg(&local_err, "Please set read-pattern as fifo or quorum");
         goto exit;

qapi_enum_parse() copes with null input: it returns its fourth argument then. I don't like that also returns it on error, but that shouldn't be a problem here.

If we can live with qapi_enum_parse()'s sub-par error message, then this should do:

Quoted 7 lines
       ret = qapi_enum_parse(QuorumReadPattern_lookup,
                             qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
                             QUORUM_READ_PATTERN__MAX,
                             QUORUM_READ_PATTERN_QUORUM, &local_err);
       if (local_err) {
           goto exit;
       }

That actually doesn't sound so bad.

Quoted 7 lines

If not, we'd have to replace @local_err:

       if (local_err) {
           error_free(local_err);
           error_setg(&local_err, "Please set read-pattern as fifo or quorum");
           goto exit;
       }

Instead of replacing @local_err I'd rather have an intermediate variable like this:

    pattern_str = qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN); 
    if (!pattern_str) {
        ret = QUORUM_READ_PATTERN_QUORUM;
    } else {
        ret = qapi_enum_parse(QuorumReadPattern_lookup, pattern_str,
                              QUORUM_READ_PATTERN__MAX, -EINVAL, NULL);
    }

I think I prefer this last one the best, but using the default error message is also ok. With either solution,

Berto

#40 lore raw

PATCH v2 12/54 qapi: change enum lookup structure

In reply to Marc-André Lureau

Store the length in the lookup table, i.e. change it from const char *const[] to struct { int n, const char *const s[] }.

The following conditional enum entry change will create "hole" elements in the generated lookup array, that should be skipped.

---
 include/qapi/visitor.h              |  2 +-
 scripts/qapi.py                     | 11 +++++--
 scripts/qapi-types.py               |  6 ++++
 scripts/qapi-visit.py               |  2 +-
 include/hw/qdev-core.h              |  2 +-
 include/qapi/util.h                 |  6 ++--
 include/qom/object.h                |  4 +--
 qapi/qapi-visit-core.c              | 24 +++++++-------
 backends/hostmem.c                  |  4 +--
 block.c                             |  3 +-
 block/backup.c                      |  2 +-
 block/blkdebug.c                    |  4 +--
 block/file-posix.c                  | 17 +++++-----
 block/file-win32.c                  |  6 ++--
 block/gluster.c                     | 12 +++----
 block/iscsi.c                       |  2 +-
 block/nfs.c                         |  2 +-
 block/parallels.c                   | 10 ++++--
 block/qcow2.c                       | 14 ++++----
 block/qed.c                         |  2 +-
 block/quorum.c                      |  4 +--
 block/rbd.c                         |  2 +-
 block/sheepdog.c                    |  2 +-
 blockdev.c                          |  7 ++--
 blockjob.c                          |  6 ++--
 chardev/char.c                      |  4 +--
 crypto/block-luks.c                 | 38 +++++++++-------------
 crypto/block.c                      |  4 +--
 crypto/cipher-afalg.c               |  2 +-
 crypto/cipher-builtin.c             |  8 ++---
 crypto/cipher-gcrypt.c              |  4 +--
 crypto/cipher-nettle.c              |  8 ++---
 crypto/hmac-gcrypt.c                |  2 +-
 crypto/hmac-glib.c                  |  2 +-
 crypto/hmac-nettle.c                |  2 +-
 crypto/pbkdf-gcrypt.c               |  2 +-
 crypto/pbkdf-nettle.c               |  2 +-
 crypto/secret.c                     |  2 +-
 crypto/tlscreds.c                   |  2 +-
 hmp.c                               | 64 +++++++++++++++++--------------------
 hw/block/fdc.c                      |  6 ++--
 hw/char/escc.c                      |  2 +-
 hw/core/qdev-properties.c           | 10 +++---
 hw/input/virtio-input-hid.c         |  4 +--
 migration/colo-failover.c           |  4 +--
 migration/colo.c                    | 14 ++++----
 migration/global_state.c            |  5 ++-
 monitor.c                           | 20 ++++++------
 net/filter.c                        |  2 +-
 net/net.c                           |  4 +--
 qapi/qapi-util.c                    | 13 ++++----
 qapi/qmp-dispatch.c                 |  2 +-
 qemu-img.c                          |  6 ++--
 qemu-nbd.c                          |  3 +-
 qom/object.c                        | 16 +++++-----
 tests/check-qom-proplist.c          |  7 +++-
 tests/test-qapi-util.c              | 17 ++++------
 tests/test-qobject-input-visitor.c  |  8 ++---
 tests/test-qobject-output-visitor.c |  2 +-
 tests/test-string-input-visitor.c   |  4 +--
 tests/test-string-output-visitor.c  |  4 +--
 tpm.c                               |  4 +--
 ui/input-legacy.c                   |  6 ++--
 ui/input.c                          | 12 +++----
 ui/vnc.c                            |  6 ++--
 vl.c                                |  6 ++--
 66 files changed, 241 insertions(+), 248 deletions(-)
include/qapi/visitor.h +1 -1
index 0f3b8cb459..62a51a54cb 100644
@@ -469,7 +469,7 @@ bool visit_optional(Visitor *v, const char *name, bool *present);
  * that visit_type_str() must have no unwelcome side effects.
  */
 void visit_type_enum(Visitor *v, const char *name, int *obj,
-                     const char *const strings[], Error **errp);
+                     const QEnumLookup *lookup, Error **errp);
 
 /*
  * Check if visitor is an input visitor.
scripts/qapi.py +8 -3
index a3ac799535..314d7e0365 100644
@@ -1851,7 +1851,7 @@ def guardend(name):
 def gen_enum_lookup(name, values, prefix=None):
     ret = mcgen('''
 
-const char *const %(c_name)s_lookup[] = {
+static const char *const %(c_name)s_array[] = {
 ''',
                 c_name=c_name(name))
     for value in values:
@@ -1865,8 +1865,13 @@ const char *const %(c_name)s_lookup[] = {
     ret += mcgen('''
     [%(max_index)s] = NULL,
 };
+
+const QEnumLookup %(c_name)s_lookup = {
+    .array = %(c_name)s_array,
+    .size = %(max_index)s
+};
 ''',
-                 max_index=max_index)
+                 max_index=max_index, c_name=c_name(name))
     return ret
 
 
@@ -1896,7 +1901,7 @@ typedef enum %(c_name)s {
 
     ret += mcgen('''
 
-extern const char *const %(c_name)s_lookup[];
+extern const QEnumLookup %(c_name)s_lookup;
 ''',
                  c_name=c_name(name))
     return ret
scripts/qapi-types.py +6 -0
index b45e7b5634..dc05268917 100644
@@ -179,6 +179,12 @@ class QAPISchemaGenTypeVisitor(QAPISchemaVisitor):
         self.defn = ''
         self._fwdecl = ''
         self._btin = guardstart('QAPI_TYPES_BUILTIN')
+        self._btin += '''
+typedef struct QEnumLookup {
+    const char *const *array;
+    int size;
+} QEnumLookup;
+'''
 
     def visit_end(self):
         self.decl = self._fwdecl + self.decl
scripts/qapi-visit.py +1 -1
index bd0b742236..7e1cfc13f0 100644
@@ -153,7 +153,7 @@ def gen_visit_enum(name):
 void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s *obj, Error **errp)
 {
     int value = *obj;
-    visit_type_enum(v, name, &value, %(c_name)s_lookup, errp);
+    visit_type_enum(v, name, &value, &%(c_name)s_lookup, errp);
     *obj = value;
 }
 ''',
include/hw/qdev-core.h +1 -1
index ae317286a4..089146197f 100644
@@ -249,7 +249,7 @@ struct Property {
 struct PropertyInfo {
     const char *name;
     const char *description;
-    const char * const *enum_table;
+    const QEnumLookup *enum_table;
     int (*print)(DeviceState *dev, Property *prop, char *dest, size_t len);
     void (*set_default_value)(Object *obj, const Property *prop);
     void (*create)(Object *obj, Property *prop, Error **errp);
include/qapi/util.h +3 -3
index 60733b6a80..613f82bdcd 100644
@@ -11,10 +11,10 @@
 #ifndef QAPI_UTIL_H
 #define QAPI_UTIL_H
 
-const char *qapi_enum_lookup(const char * const lookup[], int val);
+const char *qapi_enum_lookup(const QEnumLookup *lookup, int val);
 
-int qapi_enum_parse(const char * const lookup[], const char *buf,
-                    int max, int def, Error **errp);
+int qapi_enum_parse(const QEnumLookup *lookup, const char *buf,
+                    int def, Error **errp);
 
 int parse_qapi_name(const char *name, bool complete);
 
include/qom/object.h +2 -2
index 1b828994fa..f3e5cff37a 100644
@@ -1415,14 +1415,14 @@ void object_class_property_add_bool(ObjectClass *klass, const char *name,
  */
 void object_property_add_enum(Object *obj, const char *name,
                               const char *typename,
-                              const char * const *strings,
+                              const QEnumLookup *lookup,
                               int (*get)(Object *, Error **),
                               void (*set)(Object *, int, Error **),
                               Error **errp);
 
 void object_class_property_add_enum(ObjectClass *klass, const char *name,
                                     const char *typename,
-                                    const char * const *strings,
+                                    const QEnumLookup *lookup,
                                     int (*get)(Object *, Error **),
                                     void (*set)(Object *, int, Error **),
                                     Error **errp);
qapi/qapi-visit-core.c +11 -13
index ed6d2af462..8876ecf0cd 100644
@@ -333,24 +333,22 @@ void visit_type_null(Visitor *v, const char *name, QNull **obj,
 }
 
 static void output_type_enum(Visitor *v, const char *name, int *obj,
-                             const char *const strings[], Error **errp)
+                             const QEnumLookup *lookup, Error **errp)
 {
-    int i = 0;
     int value = *obj;
     char *enum_str;
 
-    while (strings[i++] != NULL);
-    if (value < 0 || value >= i - 1) {
+    if (value < 0 || value > lookup->size || !lookup->array[value]) {
         error_setg(errp, QERR_INVALID_PARAMETER, name ? name : "null");
         return;
     }
 
-    enum_str = (char *)strings[value];
+    enum_str = (char *)lookup->array[value];
     visit_type_str(v, name, &enum_str, errp);
 }
 
 static void input_type_enum(Visitor *v, const char *name, int *obj,
-                            const char *const strings[], Error **errp)
+                            const QEnumLookup *lookup, Error **errp)
 {
     Error *local_err = NULL;
     int64_t value = 0;
@@ -362,14 +360,14 @@ static void input_type_enum(Visitor *v, const char *name, int *obj,
         return;
     }
 
-    while (strings[value] != NULL) {
-        if (strcmp(strings[value], enum_str) == 0) {
+    while (value < lookup->size) {
+        if (!g_strcmp0(lookup->array[value], enum_str)) {
             break;
         }
         value++;
     }
 
-    if (strings[value] == NULL) {
+    if (value == lookup->size) {
         error_setg(errp, QERR_INVALID_PARAMETER, enum_str);
         g_free(enum_str);
         return;
@@ -380,16 +378,16 @@ static void input_type_enum(Visitor *v, const char *name, int *obj,
 }
 
 void visit_type_enum(Visitor *v, const char *name, int *obj,
-                     const char *const strings[], Error **errp)
+                     const QEnumLookup *lookup, Error **errp)
 {
-    assert(obj && strings);
+    assert(obj && lookup);
     trace_visit_type_enum(v, name, obj);
     switch (v->type) {
     case VISITOR_INPUT:
-        input_type_enum(v, name, obj, strings, errp);
+        input_type_enum(v, name, obj, lookup, errp);
         break;
     case VISITOR_OUTPUT:
-        output_type_enum(v, name, obj, strings, errp);
+        output_type_enum(v, name, obj, lookup, errp);
         break;
     case VISITOR_CLONE:
         /* nothing further to do, scalar value was already copied by
backends/hostmem.c +2 -2
index c4f795475c..ce430f1d14 100644
@@ -305,7 +305,7 @@ host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)
             return;
         } else if (maxnode == 0 && backend->policy != MPOL_DEFAULT) {
             error_setg(errp, "host-nodes must be set for policy %s",
-                qapi_enum_lookup(HostMemPolicy_lookup, backend->policy));
+                qapi_enum_lookup(&HostMemPolicy_lookup, backend->policy));
             return;
         }
 
@@ -396,7 +396,7 @@ host_memory_backend_class_init(ObjectClass *oc, void *data)
         host_memory_backend_set_host_nodes,
         NULL, NULL, &error_abort);
     object_class_property_add_enum(oc, "policy", "HostMemPolicy",
-        HostMemPolicy_lookup,
+        &HostMemPolicy_lookup,
         host_memory_backend_get_policy,
         host_memory_backend_set_policy, &error_abort);
     object_class_property_add_str(oc, "id", get_id, set_id, &error_abort);
block.c +1 -2
index 3615a6809e..ffb1f8db13 100644
@@ -1333,9 +1333,8 @@ static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
     detect_zeroes = qemu_opt_get(opts, "detect-zeroes");
     if (detect_zeroes) {
         BlockdevDetectZeroesOptions value =
-            qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
+            qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
                             detect_zeroes,
-                            BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
                             &local_err);
         if (local_err) {
block/backup.c +1 -1
index a700cc0315..8d4f3bcc13 100644
@@ -597,7 +597,7 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
         error_setg(errp,
                    "a sync_bitmap was provided to backup_run, "
                    "but received an incompatible sync_mode (%s)",
-                   qapi_enum_lookup(MirrorSyncMode_lookup, sync_mode));
+                   qapi_enum_lookup(&MirrorSyncMode_lookup, sync_mode));
         return NULL;
     }
 
block/blkdebug.c +2 -2
index 50edda2a31..94068156dc 100644
@@ -170,7 +170,7 @@ static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
         error_setg(errp, "Missing event name for rule");
         return -1;
     }
-    event = qapi_enum_parse(BlkdebugEvent_lookup, event_name, BLKDBG__MAX, -1, errp);
+    event = qapi_enum_parse(&BlkdebugEvent_lookup, event_name, -1, errp);
     if (event < 0) {
         return -1;
     }
@@ -733,7 +733,7 @@ static int blkdebug_debug_breakpoint(BlockDriverState *bs, const char *event,
     struct BlkdebugRule *rule;
     int blkdebug_event;
 
-    blkdebug_event = qapi_enum_parse(BlkdebugEvent_lookup, event, BLKDBG__MAX, -1, NULL);
+    blkdebug_event = qapi_enum_parse(&BlkdebugEvent_lookup, event, -1, NULL);
     if (blkdebug_event < 0) {
         return -ENOENT;
     }
block/file-posix.c +8 -9
index 48200aef0b..578f9aae39 100644
@@ -438,8 +438,8 @@ static int raw_open_common(BlockDriverState *bs, QDict *options,
     aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO)
                   ? BLOCKDEV_AIO_OPTIONS_NATIVE
                   : BLOCKDEV_AIO_OPTIONS_THREADS;
-    aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
-                          BLOCKDEV_AIO_OPTIONS__MAX, aio_default, &local_err);
+    aio = qapi_enum_parse(&BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
+                          aio_default, &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
         ret = -EINVAL;
@@ -447,8 +447,8 @@ static int raw_open_common(BlockDriverState *bs, QDict *options,
     }
     s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
 
-    locking = qapi_enum_parse(OnOffAuto_lookup, qemu_opt_get(opts, "locking"),
-                              ON_OFF_AUTO__MAX, ON_OFF_AUTO_AUTO, &local_err);
+    locking = qapi_enum_parse(&OnOffAuto_lookup, qemu_opt_get(opts, "locking"),
+                              ON_OFF_AUTO_AUTO, &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
         ret = -EINVAL;
@@ -1725,7 +1725,7 @@ static int raw_regular_truncate(int fd, int64_t offset, PreallocMode prealloc,
     default:
         result = -ENOTSUP;
         error_setg(errp, "Unsupported preallocation mode: %s",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return result;
     }
 
@@ -1760,7 +1760,7 @@ static int raw_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Preallocation mode '%s' unsupported for this "
-                   "non-regular file", qapi_enum_lookup(PreallocMode_lookup,
+                   "non-regular file", qapi_enum_lookup(&PreallocMode_lookup,
                                                         prealloc));
         return -ENOTSUP;
     }
@@ -1975,9 +1975,8 @@ static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
                           BDRV_SECTOR_SIZE);
     nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
-    prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
-                               PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
-                               &local_err);
+    prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
+                               PREALLOC_MODE_OFF, &local_err);
     g_free(buf);
     if (local_err) {
         error_propagate(errp, local_err);
block/file-win32.c +3 -3
index 2f3975f040..be4146e030 100644
@@ -303,8 +303,8 @@ static bool get_aio_option(QemuOpts *opts, int flags, Error **errp)
 
     aio_default = (flags & BDRV_O_NATIVE_AIO) ? BLOCKDEV_AIO_OPTIONS_NATIVE
                                               : BLOCKDEV_AIO_OPTIONS_THREADS;
-    aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
-                          BLOCKDEV_AIO_OPTIONS__MAX, aio_default, errp);
+    aio = qapi_enum_parse(&BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
+                          aio_default, errp);
 
     switch (aio) {
     case BLOCKDEV_AIO_OPTIONS_NATIVE:
@@ -470,7 +470,7 @@ static int raw_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(reallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&reallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/gluster.c +5 -7
index 934f459014..bc8eff5dd3 100644
@@ -544,8 +544,7 @@ static int qemu_gluster_parse_json(BlockdevOptionsGluster *gconf,
         if (!strcmp(ptr, "tcp")) {
             ptr = "inet";       /* accept legacy "tcp" */
         }
-        type = qapi_enum_parse(SocketAddressType_lookup, ptr,
-                               SOCKET_ADDRESS_TYPE__MAX, -1, NULL);
+        type = qapi_enum_parse(&SocketAddressType_lookup, ptr, -1, NULL);
         if (type != SOCKET_ADDRESS_TYPE_INET
             && type != SOCKET_ADDRESS_TYPE_UNIX) {
             error_setg(&local_err,
@@ -1002,9 +1001,8 @@ static int qemu_gluster_create(const char *filename,
                           BDRV_SECTOR_SIZE);
 
     tmp = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
-    prealloc = qapi_enum_parse(PreallocMode_lookup, tmp,
-                               PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
-                               &local_err);
+    prealloc = qapi_enum_parse(&PreallocMode_lookup, tmp,
+                               PREALLOC_MODE_OFF, &local_err);
     g_free(tmp);
     if (local_err) {
         error_propagate(errp, local_err);
@@ -1050,7 +1048,7 @@ static int qemu_gluster_create(const char *filename,
     default:
         ret = -EINVAL;
         error_setg(errp, "Unsupported preallocation mode: %s",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         break;
     }
 
@@ -1102,7 +1100,7 @@ static int qemu_gluster_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/iscsi.c +1 -1
index 5c1870340b..c6bb0049bf 100644
@@ -2088,7 +2088,7 @@ static int iscsi_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/nfs.c +1 -1
index 953728ae31..f0ac050169 100644
@@ -773,7 +773,7 @@ static int nfs_file_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/parallels.c +7 -3
index e1e06d23cc..f870bbac3e 100644
@@ -69,12 +69,16 @@ typedef enum ParallelsPreallocMode {
     PRL_PREALLOC_MODE__MAX = 2,
 } ParallelsPreallocMode;
 
-static const char *prealloc_mode_lookup[] = {
+static const char *prealloc_mode_array[] = {
     "falloc",
     "truncate",
     NULL,
 };
 
+static QEnumLookup prealloc_mode_lookup = {
+    .array = prealloc_mode_array,
+    .size = G_N_ELEMENTS(prealloc_mode_array),
+};
 
 typedef struct BDRVParallelsState {
     /** Locking is conservative, the lock protects
@@ -696,8 +700,8 @@ static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
         qemu_opt_get_size_del(opts, PARALLELS_OPT_PREALLOC_SIZE, 0);
     s->prealloc_size = MAX(s->tracks, s->prealloc_size >> BDRV_SECTOR_BITS);
     buf = qemu_opt_get_del(opts, PARALLELS_OPT_PREALLOC_MODE);
-    s->prealloc_mode = qapi_enum_parse(prealloc_mode_lookup, buf,
-            PRL_PREALLOC_MODE__MAX, PRL_PREALLOC_MODE_FALLOCATE, &local_err);
+    s->prealloc_mode = qapi_enum_parse(&prealloc_mode_lookup, buf,
+                                       PRL_PREALLOC_MODE_FALLOCATE, &local_err);
     g_free(buf);
     if (local_err != NULL) {
         goto fail_options;
block/qcow2.c +6 -8
index 45b0579caa..c72fa2b476 100644
@@ -2733,7 +2733,7 @@ static int qcow2_create2(const char *filename, int64_t total_size,
             qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order);
         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort);
         qemu_opt_set(opts, BLOCK_OPT_PREALLOC,
-                     qapi_enum_lookup(PreallocMode_lookup, prealloc),
+                     qapi_enum_lookup(&PreallocMode_lookup, prealloc),
                      &error_abort);
     }
 
@@ -2933,9 +2933,8 @@ static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
         goto finish;
     }
     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
-    prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
-                               PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
-                               &local_err);
+    prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
+                               PREALLOC_MODE_OFF, &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
         ret = -EINVAL;
@@ -3099,7 +3098,7 @@ static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
         prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
     {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
@@ -3624,9 +3623,8 @@ static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
     }
 
     optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
-    prealloc = qapi_enum_parse(PreallocMode_lookup, optstr,
-                               PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
-                               &local_err);
+    prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
+                               PREALLOC_MODE_OFF, &local_err);
     g_free(optstr);
     if (local_err) {
         goto err;
block/qed.c +1 -1
index 756fcb85a7..aec2a559ce 100644
@@ -1400,7 +1400,7 @@ static int bdrv_qed_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/quorum.c +2 -2
index e4271caa7a..44acd2702c 100644
@@ -911,9 +911,9 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
     if (!qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN)) {
         ret = QUORUM_READ_PATTERN_QUORUM;
     } else {
-        ret = qapi_enum_parse(QuorumReadPattern_lookup,
+        ret = qapi_enum_parse(&QuorumReadPattern_lookup,
                               qemu_opt_get(opts, QUORUM_OPT_READ_PATTERN),
-                              QUORUM_READ_PATTERN__MAX, -EINVAL, NULL);
+                              -EINVAL, NULL);
     }
     if (ret < 0) {
         error_setg(&local_err, "Please set read-pattern as fifo or quorum");
block/rbd.c +1 -1
index 09f8d18d1b..ff71259f05 100644
@@ -945,7 +945,7 @@ static int qemu_rbd_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
block/sheepdog.c +1 -1
index 69d49fb720..9eac7c0ec7 100644
@@ -2177,7 +2177,7 @@ static int sd_truncate(BlockDriverState *bs, int64_t offset,
 
     if (prealloc != PREALLOC_MODE_OFF) {
         error_setg(errp, "Unsupported preallocation mode '%s'",
-                   qapi_enum_lookup(PreallocMode_lookup, prealloc));
+                   qapi_enum_lookup(&PreallocMode_lookup, prealloc));
         return -ENOTSUP;
     }
 
blockdev.c +3 -4
index 6a067e81bf..7834b8830e 100644
@@ -438,9 +438,8 @@ static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
 
     if (detect_zeroes) {
         *detect_zeroes =
-            qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
+            qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
                             qemu_opt_get(opts, "detect-zeroes"),
-                            BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
                             &local_error);
         if (local_error) {
@@ -1468,9 +1467,9 @@ static int action_check_completion_mode(BlkActionState *s, Error **errp)
         error_setg(errp,
                    "Action '%s' does not support Transaction property "
                    "completion-mode = %s",
-                   qapi_enum_lookup(TransactionActionKind_lookup,
+                   qapi_enum_lookup(&TransactionActionKind_lookup,
                                     s->action->type),
-                   qapi_enum_lookup(ActionCompletionMode_lookup,
+                   qapi_enum_lookup(&ActionCompletionMode_lookup,
                                     s->txn_props->completion_mode));
         return -1;
     }
blockjob.c +3 -3
index fca71123e0..3c815b89e4 100644
@@ -209,7 +209,7 @@ static char *child_job_get_parent_desc(BdrvChild *c)
 {
     BlockJob *job = c->opaque;
     return g_strdup_printf("%s job '%s'",
-                           qapi_enum_lookup(BlockJobType_lookup,
+                           qapi_enum_lookup(&BlockJobType_lookup,
                                             job->driver->job_type),
                            job->id);
 }
@@ -555,7 +555,7 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
         return NULL;
     }
     info = g_new0(BlockJobInfo, 1);
-    info->type      = g_strdup(qapi_enum_lookup(BlockJobType_lookup,
+    info->type      = g_strdup(qapi_enum_lookup(&BlockJobType_lookup,
                                                 job->driver->job_type));
     info->device    = g_strdup(job->id);
     info->len       = job->len;
@@ -669,7 +669,7 @@ void *block_job_create(const char *job_id, const BlockJobDriver *driver,
     job->refcnt        = 1;
 
     error_setg(&job->blocker, "block device is in use by block job: %s",
-               qapi_enum_lookup(BlockJobType_lookup, driver->job_type));
+               qapi_enum_lookup(&BlockJobType_lookup, driver->job_type));
     block_job_add_bdrv(job, "main node", bs, 0, BLK_PERM_ALL, &error_abort);
     bs->job = job;
 
chardev/char.c +2 -2
index 4408d12a08..ba2d110ae5 100644
@@ -932,7 +932,7 @@ ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
     ChardevReturn *ret;
     Chardev *chr;
 
-    cc = char_get_class(qapi_enum_lookup(ChardevBackendKind_lookup,
+    cc = char_get_class(qapi_enum_lookup(&ChardevBackendKind_lookup,
                                          backend->type), errp);
     if (!cc) {
         return NULL;
@@ -991,7 +991,7 @@ ChardevReturn *qmp_chardev_change(const char *id, ChardevBackend *backend,
         return NULL;
     }
 
-    cc = char_get_class(qapi_enum_lookup(ChardevBackendKind_lookup,
+    cc = char_get_class(qapi_enum_lookup(&ChardevBackendKind_lookup,
                                          backend->type), errp);
     if (!cc) {
         return NULL;
crypto/block-luks.c +15 -23
index b78a6345f3..a3c96d768b 100644
@@ -258,47 +258,39 @@ qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg,
     }
 
     error_setg(errp, "Algorithm '%s' not supported",
-               qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
+               qapi_enum_lookup(&QCryptoCipherAlgorithm_lookup, alg));
     return NULL;
 }
 
-/* XXX replace with qapi_enum_parse() in future, when we can
+/* XXX replace with qapi_enum_parse(&) in future, when we can
  * make that function emit a more friendly error message */
 static int qcrypto_block_luks_name_lookup(const char *name,
-                                          const char *const *map,
-                                          size_t maplen,
+                                          const QEnumLookup *lookup,
                                           const char *type,
                                           Error **errp)
 {
-    size_t i;
-    for (i = 0; i < maplen; i++) {
-        if (g_str_equal(map[i], name)) {
-            return i;
-        }
+    int i = qapi_enum_parse(lookup, name, -1, NULL);
+    if (i < 0) {
+        error_setg(errp, "%s %s not supported", type, name);
     }
-
-    error_setg(errp, "%s %s not supported", type, name);
-    return 0;
+    return i;
 }
 
 #define qcrypto_block_luks_cipher_mode_lookup(name, errp)               \
     qcrypto_block_luks_name_lookup(name,                                \
-                                   QCryptoCipherMode_lookup,            \
-                                   QCRYPTO_CIPHER_MODE__MAX,            \
+                                   &QCryptoCipherMode_lookup,            \
                                    "Cipher mode",                       \
                                    errp)
 
 #define qcrypto_block_luks_hash_name_lookup(name, errp)                 \
     qcrypto_block_luks_name_lookup(name,                                \
-                                   QCryptoHashAlgorithm_lookup,         \
-                                   QCRYPTO_HASH_ALG__MAX,               \
+                                   &QCryptoHashAlgorithm_lookup,         \
                                    "Hash algorithm",                    \
                                    errp)
 
 #define qcrypto_block_luks_ivgen_name_lookup(name, errp)                \
     qcrypto_block_luks_name_lookup(name,                                \
-                                   QCryptoIVGenAlgorithm_lookup,        \
-                                   QCRYPTO_IVGEN_ALG__MAX,              \
+                                   &QCryptoIVGenAlgorithm_lookup,        \
                                    "IV generator",                      \
                                    errp)
 
@@ -399,7 +391,7 @@ qcrypto_block_luks_essiv_cipher(QCryptoCipherAlgorithm cipher,
         break;
     default:
         error_setg(errp, "Cipher %s not supported with essiv",
-                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, cipher));
+                   qapi_enum_lookup(&QCryptoCipherAlgorithm_lookup, cipher));
         return 0;
     }
 }
@@ -969,19 +961,19 @@ qcrypto_block_luks_create(QCryptoBlock *block,
         goto error;
     }
 
-    cipher_mode = qapi_enum_lookup(QCryptoCipherMode_lookup,
+    cipher_mode = qapi_enum_lookup(&QCryptoCipherMode_lookup,
                                    luks_opts.cipher_mode);
-    ivgen_alg = qapi_enum_lookup(QCryptoIVGenAlgorithm_lookup,
+    ivgen_alg = qapi_enum_lookup(&QCryptoIVGenAlgorithm_lookup,
                                  luks_opts.ivgen_alg);
     if (luks_opts.has_ivgen_hash_alg) {
-        ivgen_hash_alg = qapi_enum_lookup(QCryptoHashAlgorithm_lookup,
+        ivgen_hash_alg = qapi_enum_lookup(&QCryptoHashAlgorithm_lookup,
                                           luks_opts.ivgen_hash_alg);
         cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
                                            ivgen_hash_alg);
     } else {
         cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
     }
-    hash_alg = qapi_enum_lookup(QCryptoHashAlgorithm_lookup,
+    hash_alg = qapi_enum_lookup(&QCryptoHashAlgorithm_lookup,
                                 luks_opts.hash_alg);
 
 
crypto/block.c +2 -2
index 2140e55426..99606fe63a 100644
@@ -62,7 +62,7 @@ QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options,
     if (options->format >= G_N_ELEMENTS(qcrypto_block_drivers) ||
         !qcrypto_block_drivers[options->format]) {
         error_setg(errp, "Unsupported block driver %s",
-            qapi_enum_lookup(QCryptoBlockFormat_lookup, options->format));
+            qapi_enum_lookup(&QCryptoBlockFormat_lookup, options->format));
         g_free(block);
         return NULL;
     }
@@ -93,7 +93,7 @@ QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options,
     if (options->format >= G_N_ELEMENTS(qcrypto_block_drivers) ||
         !qcrypto_block_drivers[options->format]) {
         error_setg(errp, "Unsupported block driver %s",
-            qapi_enum_lookup(QCryptoBlockFormat_lookup, options->format));
+            qapi_enum_lookup(&QCryptoBlockFormat_lookup, options->format));
         g_free(block);
         return NULL;
     }
crypto/cipher-afalg.c +1 -1
index 24d7ba8277..f15fb2a9c8 100644
@@ -52,7 +52,7 @@ qcrypto_afalg_cipher_format_name(QCryptoCipherAlgorithm alg,
         return NULL;
     }
 
-    mode_name = qapi_enum_lookup(QCryptoCipherMode_lookup, mode);
+    mode_name = qapi_enum_lookup(&QCryptoCipherMode_lookup, mode);
     name = g_strdup_printf("%s(%s)", mode_name, alg_name);
 
     return name;
crypto/cipher-builtin.c +4 -4
index 76c76fb05b..e956cc5a53 100644
@@ -247,7 +247,7 @@ qcrypto_cipher_init_aes(QCryptoCipherMode mode,
         mode != QCRYPTO_CIPHER_MODE_ECB &&
         mode != QCRYPTO_CIPHER_MODE_XTS) {
         error_setg(errp, "Unsupported cipher mode %s",
-                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
+                   qapi_enum_lookup(&QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -379,7 +379,7 @@ qcrypto_cipher_init_des_rfb(QCryptoCipherMode mode,
 
     if (mode != QCRYPTO_CIPHER_MODE_ECB) {
         error_setg(errp, "Unsupported cipher mode %s",
-                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
+                   qapi_enum_lookup(&QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -440,7 +440,7 @@ static QCryptoCipherBuiltin *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
         break;
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
+                   qapi_enum_lookup(&QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -460,7 +460,7 @@ static QCryptoCipherBuiltin *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
     default:
         error_setg(errp,
                    "Unsupported cipher algorithm %s",
-                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
+                   qapi_enum_lookup(&QCryptoCipherAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/cipher-gcrypt.c +2 -2
index 09210195a4..3e46ee7502 100644
@@ -105,7 +105,7 @@ static QCryptoCipherGcrypt *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
         break;
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
+                   qapi_enum_lookup(&QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -160,7 +160,7 @@ static QCryptoCipherGcrypt *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
 
     default:
         error_setg(errp, "Unsupported cipher algorithm %s",
-                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
+                   qapi_enum_lookup(&QCryptoCipherAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/cipher-nettle.c +4 -4
index 7c02b3e7a2..5e70c7984a 100644
@@ -281,7 +281,7 @@ static QCryptoCipherNettle *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
         break;
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   qapi_enum_lookup(QCryptoCipherMode_lookup, mode));
+                   qapi_enum_lookup(&QCryptoCipherMode_lookup, mode));
         return NULL;
     }
 
@@ -420,7 +420,7 @@ static QCryptoCipherNettle *qcrypto_cipher_ctx_new(QCryptoCipherAlgorithm alg,
 
     default:
         error_setg(errp, "Unsupported cipher algorithm %s",
-                   qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
+                   qapi_enum_lookup(&QCryptoCipherAlgorithm_lookup, alg));
         goto error;
     }
 
@@ -491,7 +491,7 @@ qcrypto_nettle_cipher_encrypt(QCryptoCipher *cipher,
 
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   qapi_enum_lookup(QCryptoCipherMode_lookup, cipher->mode));
+                   qapi_enum_lookup(&QCryptoCipherMode_lookup, cipher->mode));
         return -1;
     }
     return 0;
@@ -537,7 +537,7 @@ qcrypto_nettle_cipher_decrypt(QCryptoCipher *cipher,
 
     default:
         error_setg(errp, "Unsupported cipher mode %s",
-                   qapi_enum_lookup(QCryptoCipherMode_lookup, cipher->mode));
+                   qapi_enum_lookup(&QCryptoCipherMode_lookup, cipher->mode));
         return -1;
     }
     return 0;
crypto/hmac-gcrypt.c +1 -1
index 0784795269..f24d5a48c2 100644
@@ -52,7 +52,7 @@ void *qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
 
     if (!qcrypto_hmac_supports(alg)) {
         error_setg(errp, "Unsupported hmac algorithm %s",
-                   qapi_enum_lookup(QCryptoHashAlgorithm_lookup, alg));
+                   qapi_enum_lookup(&QCryptoHashAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/hmac-glib.c +1 -1
index 56b71dbf85..aac4b217c0 100644
@@ -59,7 +59,7 @@ void *qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
 
     if (!qcrypto_hmac_supports(alg)) {
         error_setg(errp, "Unsupported hmac algorithm %s",
-                   qapi_enum_lookup(QCryptoHashAlgorithm_lookup, alg));
+                   qapi_enum_lookup(&QCryptoHashAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/hmac-nettle.c +1 -1
index be43511252..07cc8af9b9 100644
@@ -107,7 +107,7 @@ void *qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
 
     if (!qcrypto_hmac_supports(alg)) {
         error_setg(errp, "Unsupported hmac algorithm %s",
-                   qapi_enum_lookup(QCryptoHashAlgorithm_lookup, alg));
+                   qapi_enum_lookup(&QCryptoHashAlgorithm_lookup, alg));
         return NULL;
     }
 
crypto/pbkdf-gcrypt.c +1 -1
index a815138c46..eff037f08f 100644
@@ -69,7 +69,7 @@ int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
         hash_map[hash] == GCRY_MD_NONE) {
         error_setg_errno(errp, ENOSYS,
                          "PBKDF does not support hash algorithm %s",
-                         qapi_enum_lookup(QCryptoHashAlgorithm_lookup, hash));
+                         qapi_enum_lookup(&QCryptoHashAlgorithm_lookup, hash));
         return -1;
     }
 
crypto/pbkdf-nettle.c +1 -1
index 84977fdd69..bb6454b80c 100644
@@ -110,7 +110,7 @@ int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
     default:
         error_setg_errno(errp, ENOSYS,
                          "PBKDF does not support hash algorithm %s",
-                         qapi_enum_lookup(QCryptoHashAlgorithm_lookup, hash));
+                         qapi_enum_lookup(&QCryptoHashAlgorithm_lookup, hash));
         return -1;
     }
     return 0;
crypto/secret.c +1 -1
index 285ab7a63c..388abd7df5 100644
@@ -378,7 +378,7 @@ qcrypto_secret_class_init(ObjectClass *oc, void *data)
                                    NULL);
     object_class_property_add_enum(oc, "format",
                                    "QCryptoSecretFormat",
-                                   QCryptoSecretFormat_lookup,
+                                   &QCryptoSecretFormat_lookup,
                                    qcrypto_secret_prop_get_format,
                                    qcrypto_secret_prop_set_format,
                                    NULL);
crypto/tlscreds.c +1 -1
index a8965531b6..3cd41035bb 100644
@@ -233,7 +233,7 @@ qcrypto_tls_creds_class_init(ObjectClass *oc, void *data)
                                   NULL);
     object_class_property_add_enum(oc, "endpoint",
                                    "QCryptoTLSCredsEndpoint",
-                                   QCryptoTLSCredsEndpoint_lookup,
+                                   &QCryptoTLSCredsEndpoint_lookup,
                                    qcrypto_tls_creds_prop_get_endpoint,
                                    qcrypto_tls_creds_prop_set_endpoint,
                                    NULL);
hmp.c +30 -34

208 lines not on this page · raw message

hw/block/fdc.c +3 -3
index 8ebe08d1af..df35f3e1cc 100644
@@ -393,10 +393,10 @@ static int pick_geometry(FDrive *drv)
             FLOPPY_DPRINTF("User requested floppy drive type '%s', "
                            "but inserted medium appears to be a "
                            "%"PRId64" sector '%s' type\n",
-                           qapi_enum_lookup(FloppyDriveType_lookup,
+                           qapi_enum_lookup(&FloppyDriveType_lookup,
                                             drv->drive),
                            nb_sectors,
-                           qapi_enum_lookup(FloppyDriveType_lookup,
+                           qapi_enum_lookup(&FloppyDriveType_lookup,
                                             parse->drive));
         }
         match = type_match;
@@ -406,7 +406,7 @@ static int pick_geometry(FDrive *drv)
     if (match == -1) {
         error_setg(&error_abort, "No candidate geometries present in table "
                    " for floppy drive type '%s'",
-                   qapi_enum_lookup(FloppyDriveType_lookup, drv->drive));
+                   qapi_enum_lookup(&FloppyDriveType_lookup, drv->drive));
     }
 
     parse = &(fd_formats[match]);
hw/char/escc.c +1 -1
index 5c1d7b0e29..d5aba2a8a4 100644
@@ -849,7 +849,7 @@ static void sunkbd_handle_event(DeviceState *dev, QemuConsole *src,
     assert(evt->type == INPUT_EVENT_KIND_KEY);
     key = evt->u.key.data;
     qcode = qemu_input_key_value_to_qcode(key->key);
-    trace_escc_sunkbd_event_in(qcode, qapi_enum_lookup(QKeyCode_lookup, qcode),
+    trace_escc_sunkbd_event_in(qcode, qapi_enum_lookup(&QKeyCode_lookup, qcode),
                                key->down);
 
     if (qcode == Q_KEY_CODE_CAPS_LOCK) {
hw/core/qdev-properties.c +5 -5
index c82c693bca..ee4fc9812b 100644
@@ -587,7 +587,7 @@ const PropertyInfo qdev_prop_macaddr = {
 const PropertyInfo qdev_prop_on_off_auto = {
     .name = "OnOffAuto",
     .description = "on/off/auto",
-    .enum_table = OnOffAuto_lookup,
+    .enum_table = &OnOffAuto_lookup,
     .get = get_enum,
     .set = set_enum,
     .set_default_value = set_default_value_enum,
@@ -599,7 +599,7 @@ QEMU_BUILD_BUG_ON(sizeof(LostTickPolicy) != sizeof(int));
 
 const PropertyInfo qdev_prop_losttickpolicy = {
     .name  = "LostTickPolicy",
-    .enum_table  = LostTickPolicy_lookup,
+    .enum_table  = &LostTickPolicy_lookup,
     .get   = get_enum,
     .set   = set_enum,
     .set_default_value = set_default_value_enum,
@@ -613,7 +613,7 @@ const PropertyInfo qdev_prop_blockdev_on_error = {
     .name = "BlockdevOnError",
     .description = "Error handling policy, "
                    "report/ignore/enospc/stop/auto",
-    .enum_table = BlockdevOnError_lookup,
+    .enum_table = &BlockdevOnError_lookup,
     .get = get_enum,
     .set = set_enum,
     .set_default_value = set_default_value_enum,
@@ -627,7 +627,7 @@ const PropertyInfo qdev_prop_bios_chs_trans = {
     .name = "BiosAtaTranslation",
     .description = "Logical CHS translation algorithm, "
                    "auto/none/lba/large/rechs",
-    .enum_table = BiosAtaTranslation_lookup,
+    .enum_table = &BiosAtaTranslation_lookup,
     .get = get_enum,
     .set = set_enum,
     .set_default_value = set_default_value_enum,
@@ -639,7 +639,7 @@ const PropertyInfo qdev_prop_fdc_drive_type = {
     .name = "FdcDriveType",
     .description = "FDC drive type, "
                    "144/288/120/none/auto",
-    .enum_table = FloppyDriveType_lookup,
+    .enum_table = &FloppyDriveType_lookup,
     .get = get_enum,
     .set = set_enum,
     .set_default_value = set_default_value_enum,
hw/input/virtio-input-hid.c +2 -2
index 64039236f1..235b11082f 100644
@@ -210,7 +210,7 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
         } else {
             if (key->down) {
                 fprintf(stderr, "%s: unmapped key: %d [%s]\n", __func__,
-                        qcode, qapi_enum_lookup(QKeyCode_lookup, qcode));
+                        qcode, qapi_enum_lookup(&QKeyCode_lookup, qcode));
             }
         }
         break;
@@ -225,7 +225,7 @@ static void virtio_input_handle_event(DeviceState *dev, QemuConsole *src,
             if (btn->down) {
                 fprintf(stderr, "%s: unmapped button: %d [%s]\n", __func__,
                         btn->button,
-                        qapi_enum_lookup(InputButton_lookup, btn->button));
+                        qapi_enum_lookup(&InputButton_lookup, btn->button));
             }
         }
         break;
migration/colo-failover.c +2 -2
index e5394ba631..c3dd0969d6 100644
@@ -35,7 +35,7 @@ static void colo_failover_bh(void *opaque)
                                    FAILOVER_STATUS_ACTIVE);
     if (old_state != FAILOVER_STATUS_REQUIRE) {
         error_report("Unknown error for failover, old_state = %s",
-                     qapi_enum_lookup(FailoverStatus_lookup, old_state));
+                     qapi_enum_lookup(&FailoverStatus_lookup, old_state));
         return;
     }
 
@@ -65,7 +65,7 @@ FailoverStatus failover_set_state(FailoverStatus old_state,
 
     old = atomic_cmpxchg(&failover_state, old_state, new_state);
     if (old == old_state) {
-        trace_colo_failover_set_state(qapi_enum_lookup(FailoverStatus_lookup,
+        trace_colo_failover_set_state(qapi_enum_lookup(&FailoverStatus_lookup,
                                                        new_state));
     }
     return old;
migration/colo.c +7 -7
index 2b683a0afc..8bd7ef0531 100644
@@ -63,7 +63,7 @@ static void secondary_vm_do_failover(void)
         if (old_state != FAILOVER_STATUS_ACTIVE) {
             error_report("Unknown error while do failover for secondary VM,"
                          "old_state: %s",
-                         qapi_enum_lookup(FailoverStatus_lookup, old_state));
+                         qapi_enum_lookup(&FailoverStatus_lookup, old_state));
         }
         return;
     }
@@ -94,7 +94,7 @@ static void secondary_vm_do_failover(void)
     if (old_state != FAILOVER_STATUS_ACTIVE) {
         error_report("Incorrect state (%s) while doing failover for "
                      "secondary VM",
-                     qapi_enum_lookup(FailoverStatus_lookup, old_state));
+                     qapi_enum_lookup(&FailoverStatus_lookup, old_state));
         return;
     }
     /* Notify COLO incoming thread that failover work is finished */
@@ -129,7 +129,7 @@ static void primary_vm_do_failover(void)
                                    FAILOVER_STATUS_COMPLETED);
     if (old_state != FAILOVER_STATUS_ACTIVE) {
         error_report("Incorrect state (%s) while doing failover for Primary VM",
-                     qapi_enum_lookup(FailoverStatus_lookup, old_state));
+                     qapi_enum_lookup(&FailoverStatus_lookup, old_state));
         return;
     }
     /* Notify COLO thread that failover work is finished */
@@ -225,7 +225,7 @@ static void colo_send_message(QEMUFile *f, COLOMessage msg,
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Can't send COLO message");
     }
-    trace_colo_send_message(qapi_enum_lookup(COLOMessage_lookup, msg));
+    trace_colo_send_message(qapi_enum_lookup(&COLOMessage_lookup, msg));
 }
 
 static void colo_send_message_value(QEMUFile *f, COLOMessage msg,
@@ -245,7 +245,7 @@ static void colo_send_message_value(QEMUFile *f, COLOMessage msg,
     ret = qemu_file_get_error(f);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Failed to send value for message:%s",
-                         qapi_enum_lookup(COLOMessage_lookup, msg));
+                         qapi_enum_lookup(&COLOMessage_lookup, msg));
     }
 }
 
@@ -264,7 +264,7 @@ static COLOMessage colo_receive_message(QEMUFile *f, Error **errp)
         error_setg(errp, "%s: Invalid message", __func__);
         return msg;
     }
-    trace_colo_receive_message(qapi_enum_lookup(COLOMessage_lookup, msg));
+    trace_colo_receive_message(qapi_enum_lookup(&COLOMessage_lookup, msg));
     return msg;
 }
 
@@ -302,7 +302,7 @@ static uint64_t colo_receive_message_value(QEMUFile *f, uint32_t expect_msg,
     ret = qemu_file_get_error(f);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Failed to get value for COLO message: %s",
-                         qapi_enum_lookup(COLOMessage_lookup, expect_msg));
+                         qapi_enum_lookup(&COLOMessage_lookup, expect_msg));
     }
     return value;
 }
migration/global_state.c +2 -3
index 4d57a9c5f2..486979c4cc 100644
@@ -42,7 +42,7 @@ int global_state_store(void)
 
 void global_state_store_running(void)
 {
-    const char *state = qapi_enum_lookup(RunState_lookup, RUN_STATE_RUNNING);
+    const char *state = qapi_enum_lookup(&RunState_lookup, RUN_STATE_RUNNING);
     strncpy((char *)global_state.runstate,
            state, sizeof(global_state.runstate));
 }
@@ -89,8 +89,7 @@ static int global_state_post_load(void *opaque, int version_id)
     s->received = true;
     trace_migrate_global_state_post_load(runstate);
 
-    r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE__MAX,
-                                -1, &local_err);
+    r = qapi_enum_parse(&RunState_lookup, runstate, -1, &local_err);
 
     if (r == -1) {
         if (local_err) {
monitor.c +10 -10
index ee2fdfd4f1..228f246fcc 100644
@@ -929,7 +929,7 @@ EventInfoList *qmp_query_events(Error **errp)
     QAPIEvent e;
 
     for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
-        const char *event_name = qapi_enum_lookup(QAPIEvent_lookup, e);
+        const char *event_name = qapi_enum_lookup(&QAPIEvent_lookup, e);
         assert(event_name != NULL);
         info = g_malloc0(sizeof(*info));
         info->value = g_malloc0(sizeof(*info->value));
@@ -3250,9 +3250,9 @@ void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
     }
     len = strlen(str);
     readline_set_completion_index(rs, len);
-    for (i = 0; qapi_enum_lookup(NetClientDriver_lookup, i); i++) {
+    for (i = 0; qapi_enum_lookup(&NetClientDriver_lookup, i); i++) {
         add_completion_option(rs, str,
-                              qapi_enum_lookup(NetClientDriver_lookup, i));
+                              qapi_enum_lookup(&NetClientDriver_lookup, i));
     }
 }
 
@@ -3436,8 +3436,8 @@ void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
     len = strlen(str);
     readline_set_completion_index(rs, len);
     for (i = 0; i < Q_KEY_CODE__MAX; i++) {
-        if (!strncmp(str, qapi_enum_lookup(QKeyCode_lookup, i), len)) {
-            readline_add_completion(rs, qapi_enum_lookup(QKeyCode_lookup, i));
+        if (!strncmp(str, qapi_enum_lookup(&QKeyCode_lookup, i), len)) {
+            readline_add_completion(rs, qapi_enum_lookup(&QKeyCode_lookup, i));
         }
     }
 }
@@ -3539,9 +3539,9 @@ void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
         return;
     }
     readline_set_completion_index(rs, strlen(str));
-    for (i = 0; qapi_enum_lookup(WatchdogExpirationAction_lookup, i); i++) {
+    for (i = 0; qapi_enum_lookup(&WatchdogExpirationAction_lookup, i); i++) {
         add_completion_option(rs, str,
-            qapi_enum_lookup(WatchdogExpirationAction_lookup, i));
+            qapi_enum_lookup(&WatchdogExpirationAction_lookup, i));
     }
 }
 
@@ -3555,7 +3555,7 @@ void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
     if (nb_args == 2) {
         int i;
         for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
-            const char *name = qapi_enum_lookup(MigrationCapability_lookup, i);
+            const char *name = qapi_enum_lookup(&MigrationCapability_lookup, i);
             if (!strncmp(str, name, len)) {
                 readline_add_completion(rs, name);
             }
@@ -3576,7 +3576,7 @@ void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
     if (nb_args == 2) {
         int i;
         for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
-            const char *name = qapi_enum_lookup(MigrationParameter_lookup, i);
+            const char *name = qapi_enum_lookup(&MigrationParameter_lookup, i);
             if (!strncmp(str, name, len)) {
                 readline_add_completion(rs, name);
             }
@@ -3855,7 +3855,7 @@ static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
         qdict = qdict_get_qdict(qobject_to_qdict(rsp), "error");
         if (qdict
             && !g_strcmp0(qdict_get_try_str(qdict, "class"),
-                          qapi_enum_lookup(QapiErrorClass_lookup,
+                          qapi_enum_lookup(&QapiErrorClass_lookup,
                                            ERROR_CLASS_COMMAND_NOT_FOUND))) {
             /* Provide a more useful error message */
             qdict_del(qdict, "desc");
net/filter.c +1 -1
index 1dfd2caa23..2fd7d7d663 100644
@@ -179,7 +179,7 @@ static void netfilter_init(Object *obj)
                             netfilter_get_netdev_id, netfilter_set_netdev_id,
                             NULL);
     object_property_add_enum(obj, "queue", "NetFilterDirection",
-                             NetFilterDirection_lookup,
+                             &NetFilterDirection_lookup,
                              netfilter_get_direction, netfilter_set_direction,
                              NULL);
     object_property_add_str(obj, "status",
net/net.c +2 -2
index efe2252c59..f4b8739b0b 100644
@@ -1065,7 +1065,7 @@ static int net_client_init1(const void *object, bool is_netdev, Error **errp)
         /* FIXME drop when all init functions store an Error */
         if (errp && !*errp) {
             error_setg(errp, QERR_DEVICE_INIT_FAILED,
-                       qapi_enum_lookup(NetClientDriver_lookup, netdev->type));
+                       qapi_enum_lookup(&NetClientDriver_lookup, netdev->type));
         }
         return -1;
     }
@@ -1289,7 +1289,7 @@ void print_net_client(Monitor *mon, NetClientState *nc)
 
     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
                    nc->queue_index,
-                   qapi_enum_lookup(NetClientDriver_lookup, nc->info->type),
+                   qapi_enum_lookup(&NetClientDriver_lookup, nc->info->type),
                    nc->info_str);
     if (!QTAILQ_EMPTY(&nc->filters)) {
         monitor_printf(mon, "filters:\n");
qapi/qapi-util.c +7 -6
index 7677caa51e..363214efb1 100644
@@ -15,8 +15,8 @@
 #include "qemu-common.h"
 #include "qapi/util.h"
 
-int qapi_enum_parse(const char * const lookup[], const char *buf,
-                    int max, int def, Error **errp)
+int qapi_enum_parse(const QEnumLookup *lookup, const char *buf,
+                    int def, Error **errp)
 {
     int i;
 
@@ -24,8 +24,8 @@ int qapi_enum_parse(const char * const lookup[], const char *buf,
         return def;
     }
 
-    for (i = 0; i < max; i++) {
-        if (!strcmp(buf, lookup[i])) {
+    for (i = 0; i < lookup->size; i++) {
+        if (!g_strcmp0(buf, lookup->array[i])) {
             return i;
         }
     }
@@ -34,11 +34,12 @@ int qapi_enum_parse(const char * const lookup[], const char *buf,
     return def;
 }
 
-const char *qapi_enum_lookup(const char * const lookup[], int val)
+const char *qapi_enum_lookup(const QEnumLookup *lookup, int val)
 {
     assert(val >= 0);
+    assert(val < lookup->size);
 
-    return lookup[val];
+    return lookup->array[val];
 }
 
 /*
qapi/qmp-dispatch.c +1 -1
index 06f1470516..7f3302ad3c 100644
@@ -119,7 +119,7 @@ static QObject *do_qmp_dispatch(QmpCommandList *cmds, QObject *request,
 QObject *qmp_build_error_object(Error *err)
 {
     return qobject_from_jsonf("{ 'class': %s, 'desc': %s }",
-                              qapi_enum_lookup(QapiErrorClass_lookup,
+                              qapi_enum_lookup(&QapiErrorClass_lookup,
                                                error_get_class(err)),
                               error_get_pretty(err));
 }
qemu-img.c +2 -4
index 56ef49e214..19f1996f90 100644
@@ -3490,10 +3490,8 @@ static int img_resize(int argc, char **argv)
             image_opts = true;
             break;
         case OPTION_PREALLOCATION:
-            prealloc = qapi_enum_parse(PreallocMode_lookup, optarg,
-                                       PREALLOC_MODE__MAX, PREALLOC_MODE__MAX,
-                                       NULL);
-            if (prealloc == PREALLOC_MODE__MAX) {
+            prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg, -1, NULL);
+            if (prealloc == -1) {
                 error_report("Invalid preallocation mode '%s'", optarg);
                 return 1;
             }
qemu-nbd.c +1 -2
index 27164b8205..0dda0cce05 100644
@@ -639,9 +639,8 @@ int main(int argc, char **argv)
             break;
         case QEMU_NBD_OPT_DETECT_ZEROES:
             detect_zeroes =
-                qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
+                qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
                                 optarg,
-                                BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
                                 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
                                 &local_err);
             if (local_err) {
qom/object.c +8 -8
index fe6e744b4d..3e18537e9b 100644
@@ -1246,7 +1246,7 @@ uint64_t object_property_get_uint(Object *obj, const char *name,
 }
 
 typedef struct EnumProperty {
-    const char * const *strings;
+    const QEnumLookup *lookup;
     int (*get)(Object *, Error **);
     void (*set)(Object *, int, Error **);
 } EnumProperty;
@@ -1284,7 +1284,7 @@ int object_property_get_enum(Object *obj, const char *name,
     visit_complete(v, &str);
     visit_free(v);
     v = string_input_visitor_new(str);
-    visit_type_enum(v, name, &ret, enumprop->strings, errp);
+    visit_type_enum(v, name, &ret, enumprop->lookup, errp);
 
     g_free(str);
     visit_free(v);
@@ -1950,7 +1950,7 @@ static void property_get_enum(Object *obj, Visitor *v, const char *name,
         return;
     }
 
-    visit_type_enum(v, name, &value, prop->strings, errp);
+    visit_type_enum(v, name, &value, prop->lookup, errp);
 }
 
 static void property_set_enum(Object *obj, Visitor *v, const char *name,
@@ -1960,7 +1960,7 @@ static void property_set_enum(Object *obj, Visitor *v, const char *name,
     int value;
     Error *err = NULL;
 
-    visit_type_enum(v, name, &value, prop->strings, &err);
+    visit_type_enum(v, name, &value, prop->lookup, &err);
     if (err) {
         error_propagate(errp, err);
         return;
@@ -1977,7 +1977,7 @@ static void property_release_enum(Object *obj, const char *name,
 
 void object_property_add_enum(Object *obj, const char *name,
                               const char *typename,
-                              const char * const *strings,
+                              const QEnumLookup *lookup,
                               int (*get)(Object *, Error **),
                               void (*set)(Object *, int, Error **),
                               Error **errp)
@@ -1985,7 +1985,7 @@ void object_property_add_enum(Object *obj, const char *name,
     Error *local_err = NULL;
     EnumProperty *prop = g_malloc(sizeof(*prop));
 
-    prop->strings = strings;
+    prop->lookup = lookup;
     prop->get = get;
     prop->set = set;
 
@@ -2002,7 +2002,7 @@ void object_property_add_enum(Object *obj, const char *name,
 
 void object_class_property_add_enum(ObjectClass *klass, const char *name,
                                     const char *typename,
-                                    const char * const *strings,
+                                    const QEnumLookup *lookup,
                                     int (*get)(Object *, Error **),
                                     void (*set)(Object *, int, Error **),
                                     Error **errp)
@@ -2010,7 +2010,7 @@ void object_class_property_add_enum(ObjectClass *klass, const char *name,
     Error *local_err = NULL;
     EnumProperty *prop = g_malloc(sizeof(*prop));
 
-    prop->strings = strings;
+    prop->lookup = lookup;
     prop->get = get;
     prop->set = set;
 
tests/check-qom-proplist.c +6 -1
index c51e6e734d..0ba8b55ce1 100644
@@ -53,6 +53,11 @@ static const char *const dummy_animal_map[DUMMY_LAST + 1] = {
     [DUMMY_LAST] = NULL,
 };
 
+const QEnumLookup dummy_animal_lookup = {
+    .array = dummy_animal_map,
+    .size = DUMMY_LAST
+};
+
 struct DummyObject {
     Object parent_obj;
 
@@ -142,7 +147,7 @@ static void dummy_class_init(ObjectClass *cls, void *data)
                                   NULL);
     object_class_property_add_enum(cls, "av",
                                    "DummyAnimal",
-                                   dummy_animal_map,
+                                   &dummy_animal_lookup,
                                    dummy_get_av,
                                    dummy_set_av,
                                    NULL);
tests/test-qapi-util.c +7 -10
index e8697577a5..fc9436ff94 100644
@@ -20,24 +20,21 @@ static void test_qapi_enum_parse(void)
     Error *err = NULL;
     int ret;
 
-    ret = qapi_enum_parse(QType_lookup, NULL, QTYPE__MAX, QTYPE_NONE,
-                          &error_abort);
+    ret = qapi_enum_parse(&QType_lookup, NULL, QTYPE_NONE, &error_abort);
     g_assert_cmpint(ret, ==, QTYPE_NONE);
 
-    ret = qapi_enum_parse(QType_lookup, "junk", QTYPE__MAX, -1,
-                          NULL);
+    ret = qapi_enum_parse(&QType_lookup, "junk", -1, NULL);
     g_assert_cmpint(ret, ==, -1);
 
-    ret = qapi_enum_parse(QType_lookup, "junk", QTYPE__MAX, -1,
-                          &err);
+    ret = qapi_enum_parse(&QType_lookup, "junk", -1, &err);
     error_free_or_abort(&err);
 
-    ret = qapi_enum_parse(QType_lookup, "none", QTYPE__MAX, -1,
-                          &error_abort);
+    ret = qapi_enum_parse(&QType_lookup, "none", -1, &error_abort);
     g_assert_cmpint(ret, ==, QTYPE_NONE);
 
-    ret = qapi_enum_parse(QType_lookup, QType_lookup[QTYPE__MAX - 1],
-                          QTYPE__MAX, QTYPE__MAX - 1,
+    ret = qapi_enum_parse(&QType_lookup,
+                          qapi_enum_lookup(&QType_lookup, QTYPE__MAX - 1),
+                          QTYPE__MAX - 1,
                           &error_abort);
     g_assert_cmpint(ret, ==, QTYPE__MAX - 1);
 }
tests/test-qobject-input-visitor.c +4 -4
index bdd00f6bd8..be7d7ea654 100644
@@ -382,10 +382,10 @@ static void test_visitor_in_enum(TestInputVisitorData *data,
     Visitor *v;
     EnumOne i;
 
-    for (i = 0; EnumOne_lookup[i]; i++) {
+    for (i = 0; i < EnumOne_lookup.size; i++) {
         EnumOne res = -1;
 
-        v = visitor_input_test_init(data, "%s", EnumOne_lookup[i]);
+        v = visitor_input_test_init(data, "%s", EnumOne_lookup.array[i]);
 
         visit_type_EnumOne(v, NULL, &res, &error_abort);
         g_assert_cmpint(i, ==, res);
@@ -699,7 +699,7 @@ static void test_native_list_integer_helper(TestInputVisitorData *data,
         }
     }
     g_string_append_printf(gstr_union,  "{ 'type': '%s', 'data': [ %s ] }",
-                           UserDefNativeListUnionKind_lookup[kind],
+                           UserDefNativeListUnionKind_lookup.array[kind],
                            gstr_list->str);
     v = visitor_input_test_init_raw(data,  gstr_union->str);
 
@@ -1110,7 +1110,7 @@ static void test_visitor_in_fail_struct_missing(TestInputVisitorData *data,
     error_free_or_abort(&err);
     visit_optional(v, "optional", &present);
     g_assert(!present);
-    visit_type_enum(v, "enum", &en, EnumOne_lookup, &err);
+    visit_type_enum(v, "enum", &en, &EnumOne_lookup, &err);
     error_free_or_abort(&err);
     visit_type_int(v, "i64", &i64, &err);
     error_free_or_abort(&err);
tests/test-qobject-output-visitor.c +1 -1
index bb2d66b666..55a8c932e0 100644
@@ -135,7 +135,7 @@ static void test_visitor_out_enum(TestOutputVisitorData *data,
         qstr = qobject_to_qstring(visitor_get(data));
         g_assert(qstr);
         g_assert_cmpstr(qstring_get_str(qstr), ==,
-                        qapi_enum_lookup(EnumOne_lookup, i));
+                        qapi_enum_lookup(&EnumOne_lookup, i));
         visitor_reset(data);
     }
 }
tests/test-string-input-visitor.c +2 -2
index 79313a7f7a..5828359830 100644
@@ -279,10 +279,10 @@ static void test_visitor_in_enum(TestInputVisitorData *data,
     Visitor *v;
     EnumOne i;
 
-    for (i = 0; EnumOne_lookup[i]; i++) {
+    for (i = 0; i < EnumOne_lookup.size; i++) {
         EnumOne res = -1;
 
-        v = visitor_input_test_init(data, EnumOne_lookup[i]);
+        v = visitor_input_test_init(data, EnumOne_lookup.array[i]);
 
         visit_type_EnumOne(v, NULL, &res, &err);
         g_assert(!err);
tests/test-string-output-visitor.c +2 -2
index 0b2087d312..a5d26ac0ca 100644
@@ -196,12 +196,12 @@ static void test_visitor_out_enum(TestOutputVisitorData *data,
         str = visitor_get(data);
         if (data->human) {
             char *str_human =
-                g_strdup_printf("\"%s\"", qapi_enum_lookup(EnumOne_lookup, i));
+                g_strdup_printf("\"%s\"", qapi_enum_lookup(&EnumOne_lookup, i));
 
             g_assert_cmpstr(str, ==, str_human);
             g_free(str_human);
         } else {
-            g_assert_cmpstr(str, ==, qapi_enum_lookup(EnumOne_lookup, i));
+            g_assert_cmpstr(str, ==, qapi_enum_lookup(&EnumOne_lookup, i));
         }
         visitor_reset(data);
     }
tpm.c +2 -2
index f175661bfe..3ddd889906 100644
@@ -63,7 +63,7 @@ static bool tpm_model_is_registered(enum TpmModel model)
 
 const TPMDriverOps *tpm_get_backend_driver(const char *type)
 {
-    int i = qapi_enum_parse(TpmType_lookup, type, TPM_TYPE__MAX, -1, NULL);
+    int i = qapi_enum_parse(&TpmType_lookup, type, -1, NULL);
 
     return i >= 0 ? be_drivers[i] : NULL;
 }
@@ -92,7 +92,7 @@ static void tpm_display_backend_drivers(void)
             continue;
         }
         fprintf(stderr, "%12s   %s\n",
-                qapi_enum_lookup(TpmType_lookup, i),
+                qapi_enum_lookup(&TpmType_lookup, i),
                 be_drivers[i]->desc());
     }
     fprintf(stderr, "\n");
ui/input-legacy.c +3 -3
index 7159747404..c597bdc711 100644
@@ -61,9 +61,9 @@ int index_from_key(const char *key, size_t key_length)
 {
     int i;
 
-    for (i = 0; QKeyCode_lookup[i] != NULL; i++) {
-        if (!strncmp(key, QKeyCode_lookup[i], key_length) &&
-            !QKeyCode_lookup[i][key_length]) {
+    for (i = 0; QKeyCode_lookup.array[i] != NULL; i++) {
+        if (!strncmp(key, QKeyCode_lookup.array[i], key_length) &&
+            !QKeyCode_lookup.array[i][key_length]) {
             break;
         }
     }
ui/input.c +6 -6
index 6bceb6b825..dfae347154 100644
@@ -152,7 +152,7 @@ void qmp_input_send_event(bool has_device, const char *device,
         if (!qemu_input_find_handler(1 << event->type, con)) {
             error_setg(errp, "Input handler not found for "
                              "event type %s",
-                       qapi_enum_lookup(InputEventKind_lookup, event->type));
+                       qapi_enum_lookup(&InputEventKind_lookup, event->type));
             return;
         }
     }
@@ -214,12 +214,12 @@ static void qemu_input_event_trace(QemuConsole *src, InputEvent *evt)
         switch (key->key->type) {
         case KEY_VALUE_KIND_NUMBER:
             qcode = qemu_input_key_number_to_qcode(key->key->u.number.data);
-            name = qapi_enum_lookup(QKeyCode_lookup, qcode);
+            name = qapi_enum_lookup(&QKeyCode_lookup, qcode);
             trace_input_event_key_number(idx, key->key->u.number.data,
                                          name, key->down);
             break;
         case KEY_VALUE_KIND_QCODE:
-            name = qapi_enum_lookup(QKeyCode_lookup, key->key->u.qcode.data);
+            name = qapi_enum_lookup(&QKeyCode_lookup, key->key->u.qcode.data);
             trace_input_event_key_qcode(idx, name, key->down);
             break;
         case KEY_VALUE_KIND__MAX:
@@ -229,17 +229,17 @@ static void qemu_input_event_trace(QemuConsole *src, InputEvent *evt)
         break;
     case INPUT_EVENT_KIND_BTN:
         btn = evt->u.btn.data;
-        name = qapi_enum_lookup(InputButton_lookup, btn->button);
+        name = qapi_enum_lookup(&InputButton_lookup, btn->button);
         trace_input_event_btn(idx, name, btn->down);
         break;
     case INPUT_EVENT_KIND_REL:
         move = evt->u.rel.data;
-        name = qapi_enum_lookup(InputAxis_lookup, move->axis);
+        name = qapi_enum_lookup(&InputAxis_lookup, move->axis);
         trace_input_event_rel(idx, name, move->value);
         break;
     case INPUT_EVENT_KIND_ABS:
         move = evt->u.abs.data;
-        name = qapi_enum_lookup(InputAxis_lookup, move->axis);
+        name = qapi_enum_lookup(&InputAxis_lookup, move->axis);
         trace_input_event_abs(idx, name, move->value);
         break;
     case INPUT_EVENT_KIND__MAX:
ui/vnc.c +3 -3
index 20a45a7241..afe46dd8ae 100644
@@ -132,7 +132,7 @@ static void vnc_init_basic_info(SocketAddress *addr,
     case SOCKET_ADDRESS_TYPE_VSOCK:
     case SOCKET_ADDRESS_TYPE_FD:
         error_setg(errp, "Unsupported socket address type %s",
-                   qapi_enum_lookup(SocketAddressType_lookup, addr->type));
+                   qapi_enum_lookup(&SocketAddressType_lookup, addr->type));
         break;
     default:
         abort();
@@ -417,7 +417,7 @@ VncInfo *qmp_query_vnc(Error **errp)
         case SOCKET_ADDRESS_TYPE_VSOCK:
         case SOCKET_ADDRESS_TYPE_FD:
             error_setg(errp, "Unsupported socket address type %s",
-                       qapi_enum_lookup(SocketAddressType_lookup, addr->type));
+                       qapi_enum_lookup(&SocketAddressType_lookup, addr->type));
             goto out_error;
         default:
             abort();
@@ -1840,7 +1840,7 @@ static void vnc_release_modifiers(VncState *vs)
 
 static const char *code2name(int keycode)
 {
-    return qapi_enum_lookup(QKeyCode_lookup,
+    return qapi_enum_lookup(&QKeyCode_lookup,
                             qemu_input_key_number_to_qcode(keycode));
 }
 
vl.c +3 -3
index def4f5f05f..adeb6ed479 100644
@@ -689,7 +689,7 @@ bool runstate_check(RunState state)
 
 bool runstate_store(char *str, size_t size)
 {
-    const char *state = qapi_enum_lookup(RunState_lookup, current_run_state);
+    const char *state = qapi_enum_lookup(&RunState_lookup, current_run_state);
     size_t len = strlen(state) + 1;
 
     if (len > size) {
@@ -722,8 +722,8 @@ void runstate_set(RunState new_state)
 
     if (!runstate_valid_transitions[current_run_state][new_state]) {
         error_report("invalid runstate transition: '%s' -> '%s'",
-                     qapi_enum_lookup(RunState_lookup, current_run_state),
-                     qapi_enum_lookup(RunState_lookup, new_state));
+                     qapi_enum_lookup(&RunState_lookup, current_run_state),
+                     qapi_enum_lookup(&RunState_lookup, new_state));
         abort();
     }
     trace_runstate_set(new_state);
Signature · 1 line
2.14.1.146.gd35faa819
#41 lore raw

Re: [Qemu-devel] [PATCH v2 12/54] qapi: change enum lookup structure

Quoted 5 lines · Marc-André Lureau

Store the length in the lookup table, i.e. change it from const char *const[] to struct { int n, const char *const s[] }.

The following conditional enum entry change will create "hole" elements in the generated lookup array, that should be skipped.

The commit message could use some love. I know what the "conditional enum entry change" will be about, but most other's won't, and even I may not remember it in a few months.

Quoted 4 lines

---

 66 files changed, 241 insertions(+), 248 deletions(-)

Lot's of churn because we need to take the address of FOO_lookup now. Macros in PATCH 06 could perhaps limit the churn to that patch. I'll play with it.

Quoted 31 lines
include/qapi/visitor.h +1 -1
index 0f3b8cb459..62a51a54cb 100644
@@ -469,7 +469,7 @@ bool visit_optional(Visitor *v, const char *name, bool *present);
  * that visit_type_str() must have no unwelcome side effects.
  */
 void visit_type_enum(Visitor *v, const char *name, int *obj,
-                     const char *const strings[], Error **errp);
+                     const QEnumLookup *lookup, Error **errp);
 
 /*
  * Check if visitor is an input visitor.
scripts/qapi.py +2 -1
index a3ac799535..314d7e0365 100644
@@ -1851,7 +1851,7 @@ def guardend(name):
 def gen_enum_lookup(name, values, prefix=None):
     ret = mcgen('''
 
-const char *const %(c_name)s_lookup[] = {
+static const char *const %(c_name)s_array[] = {
 ''',
                 c_name=c_name(name))
     for value in values:
@@ -1865,8 +1865,13 @@ const char *const %(c_name)s_lookup[] = {
     ret += mcgen('''
     [%(max_index)s] = NULL,
 };
+

scripts/qapi.py const char *const %(c_name)s_lookup[] = { · line 1877

Quoted 10 lines
scripts/qapi.py +5 -1
+const QEnumLookup %(c_name)s_lookup = {
+    .array = %(c_name)s_array,
+    .size = %(max_index)s
+};
 ''',
-                 max_index=max_index)
+                 max_index=max_index, c_name=c_name(name))
     return ret
 
 

This generates

    static const char *const ACPISlotType_array[] = {
        [ACPI_SLOT_TYPE_DIMM] = "DIMM",
        [ACPI_SLOT_TYPE_CPU] = "CPU",
        [ACPI_SLOT_TYPE__MAX] = NULL,
    };

    const QEnumLookup ACPISlotType_lookup = {
        .array = ACPISlotType_array,
        .size = ACPI_SLOT_TYPE__MAX
    };

Old-fashioned. We can avoid the extra variable easily:

    const QEnumLookup ACPISlotType_lookup = {
        .array = (const char *const[]) {
            [ACPI_SLOT_TYPE_DIMM] = "DIMM",
            [ACPI_SLOT_TYPE_CPU] = "CPU",
            [ACPI_SLOT_TYPE__MAX] = NULL,
        },
        .size = ACPI_SLOT_TYPE__MAX
    };

Could be done in a followup. Extra churn. Up to you.

Quoted 99 lines
scripts/qapi.py +1 -1
@@ -1896,7 +1901,7 @@ typedef enum %(c_name)s {
 
     ret += mcgen('''
 
-extern const char *const %(c_name)s_lookup[];
+extern const QEnumLookup %(c_name)s_lookup;
 ''',
                  c_name=c_name(name))
     return ret
scripts/qapi-types.py +6 -0
index b45e7b5634..dc05268917 100644
@@ -179,6 +179,12 @@ class QAPISchemaGenTypeVisitor(QAPISchemaVisitor):
         self.defn = ''
         self._fwdecl = ''
         self._btin = guardstart('QAPI_TYPES_BUILTIN')
+        self._btin += '''
+typedef struct QEnumLookup {
+    const char *const *array;
+    int size;
+} QEnumLookup;
+'''
 
     def visit_end(self):
         self.decl = self._fwdecl + self.decl
scripts/qapi-visit.py +1 -1
index bd0b742236..7e1cfc13f0 100644
@@ -153,7 +153,7 @@ def gen_visit_enum(name):
 void visit_type_%(c_name)s(Visitor *v, const char *name, %(c_name)s *obj, Error **errp)
 {
     int value = *obj;
-    visit_type_enum(v, name, &value, %(c_name)s_lookup, errp);
+    visit_type_enum(v, name, &value, &%(c_name)s_lookup, errp);
     *obj = value;
 }
 ''',
include/hw/qdev-core.h +1 -1
index ae317286a4..089146197f 100644
@@ -249,7 +249,7 @@ struct Property {
 struct PropertyInfo {
     const char *name;
     const char *description;
-    const char * const *enum_table;
+    const QEnumLookup *enum_table;
     int (*print)(DeviceState *dev, Property *prop, char *dest, size_t len);
     void (*set_default_value)(Object *obj, const Property *prop);
     void (*create)(Object *obj, Property *prop, Error **errp);
include/qapi/util.h +3 -3
index 60733b6a80..613f82bdcd 100644
@@ -11,10 +11,10 @@
 #ifndef QAPI_UTIL_H
 #define QAPI_UTIL_H
 
-const char *qapi_enum_lookup(const char * const lookup[], int val);
+const char *qapi_enum_lookup(const QEnumLookup *lookup, int val);
 
-int qapi_enum_parse(const char * const lookup[], const char *buf,
-                    int max, int def, Error **errp);
+int qapi_enum_parse(const QEnumLookup *lookup, const char *buf,
+                    int def, Error **errp);
 
 int parse_qapi_name(const char *name, bool complete);
 
include/qom/object.h +2 -2
index 1b828994fa..f3e5cff37a 100644
@@ -1415,14 +1415,14 @@ void object_class_property_add_bool(ObjectClass *klass, const char *name,
  */
 void object_property_add_enum(Object *obj, const char *name,
                               const char *typename,
-                              const char * const *strings,
+                              const QEnumLookup *lookup,
                               int (*get)(Object *, Error **),
                               void (*set)(Object *, int, Error **),
                               Error **errp);
 
 void object_class_property_add_enum(ObjectClass *klass, const char *name,
                                     const char *typename,
-                                    const char * const *strings,
+                                    const QEnumLookup *lookup,
                                     int (*get)(Object *, Error **),
                                     void (*set)(Object *, int, Error **),
                                     Error **errp);
qapi/qapi-visit-core.c +0 -0
index ed6d2af462..8876ecf0cd 100644
@@ -333,24 +333,22 @@ void visit_type_null(Visitor *v, const char *name, QNull **obj,
 }
 
 static void output_type_enum(Visitor *v, const char *name, int *obj,

qapi/qapi-visit-core.c void visit_type_null(Visitor *v, const char *name, QNull **obj, · line 341

Quoted 10 lines
qapi/qapi-visit-core.c +2 -4
-                             const char *const strings[], Error **errp)
+                             const QEnumLookup *lookup, Error **errp)
 {
-    int i = 0;
     int value = *obj;
     char *enum_str;
 
-    while (strings[i++] != NULL);
-    if (value < 0 || value >= i - 1) {
+    if (value < 0 || value > lookup->size || !lookup->array[value]) {

!lookup->array[value] feels premature. Hole support should be done in a later patch, possibly a separate one.

qapi/qapi-visit-core.c void visit_type_null(Visitor *v, const char *name, QNull **obj, · line 346

Quoted 6 lines
qapi/qapi-visit-core.c +1 -1
         error_setg(errp, QERR_INVALID_PARAMETER, name ? name : "null");
         return;
     }
 
-    enum_str = (char *)strings[value];
+    enum_str = (char *)lookup->array[value];

Why not qapi_enum_lookup()? In PATCH 06?

Quoted 17 lines
qapi/qapi-visit-core.c +3 -3
     visit_type_str(v, name, &enum_str, errp);
 }
 
 static void input_type_enum(Visitor *v, const char *name, int *obj,
-                            const char *const strings[], Error **errp)
+                            const QEnumLookup *lookup, Error **errp)
 {
     Error *local_err = NULL;
     int64_t value = 0;
@@ -362,14 +360,14 @@ static void input_type_enum(Visitor *v, const char *name, int *obj,
         return;
     }
 
-    while (strings[value] != NULL) {
-        if (strcmp(strings[value], enum_str) == 0) {
+    while (value < lookup->size) {
+        if (!g_strcmp0(lookup->array[value], enum_str)) {

qapi/qapi-visit-core.c static void input_type_enum(Visitor *v, const char *name, int *obj, · line 373

Quoted 10 lines
qapi/qapi-visit-core.c +1 -1
             break;
         }
         value++;
     }
 
-    if (strings[value] == NULL) {
+    if (value == lookup->size) {
         error_setg(errp, QERR_INVALID_PARAMETER, enum_str);
         g_free(enum_str);
         return;

Can we use qapi_enum_parse() here? In a preparatory patch like PATCH 07-11?

Quoted 11 lines
qapi/qapi-visit-core.c +2 -2
@@ -380,16 +378,16 @@ static void input_type_enum(Visitor *v, const char *name, int *obj,
 }
 
 void visit_type_enum(Visitor *v, const char *name, int *obj,
-                     const char *const strings[], Error **errp)
+                     const QEnumLookup *lookup, Error **errp)
 {
-    assert(obj && strings);
+    assert(obj && lookup);
     trace_visit_type_enum(v, name, obj);
     switch (v->type) {

qapi/qapi-visit-core.c static void input_type_enum(Visitor *v, const char *name, int *obj, · line 393

Quoted 10 lines
qapi/qapi-visit-core.c +2 -2
     case VISITOR_INPUT:
-        input_type_enum(v, name, obj, strings, errp);
+        input_type_enum(v, name, obj, lookup, errp);
         break;
     case VISITOR_OUTPUT:
-        output_type_enum(v, name, obj, strings, errp);
+        output_type_enum(v, name, obj, lookup, errp);
         break;
     case VISITOR_CLONE:
         /* nothing further to do, scalar value was already copied by

[Skipping churn I hope to reduce...]

Quoted 12 lines
block/parallels.c +1 -1
index e1e06d23cc..f870bbac3e 100644
@@ -69,12 +69,16 @@ typedef enum ParallelsPreallocMode {
     PRL_PREALLOC_MODE__MAX = 2,
 } ParallelsPreallocMode;
 
-static const char *prealloc_mode_lookup[] = {
+static const char *prealloc_mode_array[] = {
     "falloc",
     "truncate",

block/parallels.c typedef enum ParallelsPreallocMode { · line 84

Quoted 10 lines
block/parallels.c +4 -0
     NULL,
 };
 
+static QEnumLookup prealloc_mode_lookup = {
+    .array = prealloc_mode_array,
+    .size = G_N_ELEMENTS(prealloc_mode_array),
+};
 
 typedef struct BDRVParallelsState {
     /** Locking is conservative, the lock protects

My comment on scripts/qapi.py applies.

block/parallels.c static int parallels_open(BlockDriverState *bs, QDict *options, int flags, · line 707

Quoted 11 lines
block/parallels.c +2 -2
@@ -696,8 +700,8 @@ static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
         qemu_opt_get_size_del(opts, PARALLELS_OPT_PREALLOC_SIZE, 0);
     s->prealloc_size = MAX(s->tracks, s->prealloc_size >> BDRV_SECTOR_BITS);
     buf = qemu_opt_get_del(opts, PARALLELS_OPT_PREALLOC_MODE);
-    s->prealloc_mode = qapi_enum_parse(prealloc_mode_lookup, buf,
-            PRL_PREALLOC_MODE__MAX, PRL_PREALLOC_MODE_FALLOCATE, &local_err);
+    s->prealloc_mode = qapi_enum_parse(&prealloc_mode_lookup, buf,
+                                       PRL_PREALLOC_MODE_FALLOCATE, &local_err);
     g_free(buf);
     if (local_err != NULL) {
         goto fail_options;

[Skipping more churn...]

Quoted 5 lines
crypto/block-luks.c +0 -0
index b78a6345f3..a3c96d768b 100644

crypto/block-luks.c qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg, · line 265

Quoted 10 lines
crypto/block-luks.c +2 -2
@@ -258,47 +258,39 @@ qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg,
     }
 
     error_setg(errp, "Algorithm '%s' not supported",
-               qapi_enum_lookup(QCryptoCipherAlgorithm_lookup, alg));
+               qapi_enum_lookup(&QCryptoCipherAlgorithm_lookup, alg));
     return NULL;
 }
 
-/* XXX replace with qapi_enum_parse() in future, when we can
+/* XXX replace with qapi_enum_parse(&) in future, when we can

Whoops!

Quoted 12 lines
crypto/block-luks.c +1 -6
  * make that function emit a more friendly error message */
 static int qcrypto_block_luks_name_lookup(const char *name,
-                                          const char *const *map,
-                                          size_t maplen,
+                                          const QEnumLookup *lookup,
                                           const char *type,
                                           Error **errp)
 {
-    size_t i;
-    for (i = 0; i < maplen; i++) {
-        if (g_str_equal(map[i], name)) {
-            return i;

crypto/block-luks.c qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg, · line 277

Quoted 10 lines
crypto/block-luks.c +4 -4
-        }
+    int i = qapi_enum_parse(lookup, name, -1, NULL);
+    if (i < 0) {
+        error_setg(errp, "%s %s not supported", type, name);
     }
-
-    error_setg(errp, "%s %s not supported", type, name);
-    return 0;
+    return i;
 }

Here, you do use qapi_enum_parse(). Good, but let's do it in a separate, preparatory patch like PATCH 07-11.

[Skipping more churn...]

Quoted 16 lines
qapi/qapi-util.c +2 -2
index 7677caa51e..363214efb1 100644
@@ -15,8 +15,8 @@
 #include "qemu-common.h"
 #include "qapi/util.h"
 
-int qapi_enum_parse(const char * const lookup[], const char *buf,
-                    int max, int def, Error **errp)
+int qapi_enum_parse(const QEnumLookup *lookup, const char *buf,
+                    int def, Error **errp)
 {
     int i;
 

qapi/qapi-util.c int qapi_enum_parse(const char * const lookup[], const char *buf, · line 31

Quoted 10 lines
qapi/qapi-util.c +2 -2
@@ -24,8 +24,8 @@ int qapi_enum_parse(const char * const lookup[], const char *buf,
         return def;
     }
 
-    for (i = 0; i < max; i++) {
-        if (!strcmp(buf, lookup[i])) {
+    for (i = 0; i < lookup->size; i++) {
+        if (!g_strcmp0(buf, lookup->array[i])) {
             return i;
         }
     }

Why switch from strcmp() to g_strcmp0()?

If it's to support holes: hole support should be done in a later patch, possibly a separate one.

qapi/qapi-util.c int qapi_enum_parse(const char * const lookup[], const char *buf, · line 40

Quoted 9 lines
qapi/qapi-util.c +2 -1
@@ -34,11 +34,12 @@ int qapi_enum_parse(const char * const lookup[], const char *buf,
     return def;
 }
 
-const char *qapi_enum_lookup(const char * const lookup[], int val)
+const char *qapi_enum_lookup(const QEnumLookup *lookup, int val)
 {
     assert(val >= 0);
+    assert(val < lookup->size);

The additional bounds check is a nice extra. But let's fuse the assertions.

The patch that introduces hole support should additionally assert lookup->array[val].

qapi/qapi-util.c int qapi_enum_parse(const char * const lookup[], const char *buf, · line 45

Quoted 6 lines
qapi/qapi-util.c +1 -1
-    return lookup[val];
+    return lookup->array[val];
 }
 
 /*

[Skipping more churn...]

Quoted 6 lines
tests/check-qom-proplist.c +0 -0
index c51e6e734d..0ba8b55ce1 100644
@@ -53,6 +53,11 @@ static const char *const dummy_animal_map[DUMMY_LAST + 1] = {
     [DUMMY_LAST] = NULL,

tests/check-qom-proplist.c static const char *const dummy_animal_map[DUMMY_LAST + 1] = { · line 63

Quoted 10 lines
tests/check-qom-proplist.c +5 -0
 };
 
+const QEnumLookup dummy_animal_lookup = {
+    .array = dummy_animal_map,
+    .size = DUMMY_LAST
+};
+
 struct DummyObject {
     Object parent_obj;
 

My comment on scripts/qapi.py applies.

tests/check-qom-proplist.c static void dummy_class_init(ObjectClass *cls, void *data) · line 153

Quoted 9 lines
tests/check-qom-proplist.c +1 -1
@@ -142,7 +147,7 @@ static void dummy_class_init(ObjectClass *cls, void *data)
                                   NULL);
     object_class_property_add_enum(cls, "av",
                                    "DummyAnimal",
-                                   dummy_animal_map,
+                                   &dummy_animal_lookup,
                                    dummy_get_av,
                                    dummy_set_av,
                                    NULL);

[Skipping more churn...]

Quoted 17 lines

index bdd00f6bd8..be7d7ea654 100644

tests/test-qobject-input-visitor.c +2 -2
@@ -382,10 +382,10 @@ static void test_visitor_in_enum(TestInputVisitorData *data,
     Visitor *v;
     EnumOne i;
 
-    for (i = 0; EnumOne_lookup[i]; i++) {
+    for (i = 0; i < EnumOne_lookup.size; i++) {
         EnumOne res = -1;
 
-        v = visitor_input_test_init(data, "%s", EnumOne_lookup[i]);
+        v = visitor_input_test_init(data, "%s", EnumOne_lookup.array[i]);
 
         visit_type_EnumOne(v, NULL, &res, &error_abort);
         g_assert_cmpint(i, ==, res);

tests/test-qobject-input-visitor.c static void test_native_list_integer_helper(TestInputVisitorData *data, · line 702

Quoted 5 lines
tests/test-qobject-input-visitor.c +1 -1
@@ -699,7 +699,7 @@ static void test_native_list_integer_helper(TestInputVisitorData *data,
         }
     }
     g_string_append_printf(gstr_union,  "{ 'type': '%s', 'data': [ %s ] }",
-                           UserDefNativeListUnionKind_lookup[kind],
+                           UserDefNativeListUnionKind_lookup.array[kind],

PATCH 06 should have changed this to qapi_enum_lookup(), as noted in my review there.

Quoted 31 lines
tests/test-qobject-input-visitor.c +1 -1
                            gstr_list->str);
     v = visitor_input_test_init_raw(data,  gstr_union->str);
 
@@ -1110,7 +1110,7 @@ static void test_visitor_in_fail_struct_missing(TestInputVisitorData *data,
     error_free_or_abort(&err);
     visit_optional(v, "optional", &present);
     g_assert(!present);
-    visit_type_enum(v, "enum", &en, EnumOne_lookup, &err);
+    visit_type_enum(v, "enum", &en, &EnumOne_lookup, &err);
     error_free_or_abort(&err);
     visit_type_int(v, "i64", &i64, &err);
     error_free_or_abort(&err);
tests/test-qobject-output-visitor.c +1 -1
index bb2d66b666..55a8c932e0 100644
@@ -135,7 +135,7 @@ static void test_visitor_out_enum(TestOutputVisitorData *data,
         qstr = qobject_to_qstring(visitor_get(data));
         g_assert(qstr);
         g_assert_cmpstr(qstring_get_str(qstr), ==,
-                        qapi_enum_lookup(EnumOne_lookup, i));
+                        qapi_enum_lookup(&EnumOne_lookup, i));
         visitor_reset(data);
     }
 }
tests/test-string-input-visitor.c +0 -0
index 79313a7f7a..5828359830 100644
@@ -279,10 +279,10 @@ static void test_visitor_in_enum(TestInputVisitorData *data,
     Visitor *v;

tests/test-string-input-visitor.c static void test_visitor_in_enum(TestInputVisitorData *data, · line 287

Quoted 10 lines
tests/test-string-input-visitor.c +2 -2
     EnumOne i;
 
-    for (i = 0; EnumOne_lookup[i]; i++) {
+    for (i = 0; i < EnumOne_lookup.size; i++) {
         EnumOne res = -1;
 
-        v = visitor_input_test_init(data, EnumOne_lookup[i]);
+        v = visitor_input_test_init(data, EnumOne_lookup.array[i]);
 
         visit_type_EnumOne(v, NULL, &res, &err);

Likewise.

Quoted 49 lines
tests/test-string-input-visitor.c +0 -0
         g_assert(!err);
tests/test-string-output-visitor.c +2 -2
index 0b2087d312..a5d26ac0ca 100644
@@ -196,12 +196,12 @@ static void test_visitor_out_enum(TestOutputVisitorData *data,
         str = visitor_get(data);
         if (data->human) {
             char *str_human =
-                g_strdup_printf("\"%s\"", qapi_enum_lookup(EnumOne_lookup, i));
+                g_strdup_printf("\"%s\"", qapi_enum_lookup(&EnumOne_lookup, i));
 
             g_assert_cmpstr(str, ==, str_human);
             g_free(str_human);
         } else {
-            g_assert_cmpstr(str, ==, qapi_enum_lookup(EnumOne_lookup, i));
+            g_assert_cmpstr(str, ==, qapi_enum_lookup(&EnumOne_lookup, i));
         }
         visitor_reset(data);
     }
tpm.c +2 -2
index f175661bfe..3ddd889906 100644
@@ -63,7 +63,7 @@ static bool tpm_model_is_registered(enum TpmModel model)
 
 const TPMDriverOps *tpm_get_backend_driver(const char *type)
 {
-    int i = qapi_enum_parse(TpmType_lookup, type, TPM_TYPE__MAX, -1, NULL);
+    int i = qapi_enum_parse(&TpmType_lookup, type, -1, NULL);
 
     return i >= 0 ? be_drivers[i] : NULL;
 }
@@ -92,7 +92,7 @@ static void tpm_display_backend_drivers(void)
             continue;
         }
         fprintf(stderr, "%12s   %s\n",
-                qapi_enum_lookup(TpmType_lookup, i),
+                qapi_enum_lookup(&TpmType_lookup, i),
                 be_drivers[i]->desc());
     }
     fprintf(stderr, "\n");
ui/input-legacy.c +0 -0
index 7159747404..c597bdc711 100644
@@ -61,9 +61,9 @@ int index_from_key(const char *key, size_t key_length)
 {
     int i;

ui/input-legacy.c int index_from_key(const char *key, size_t key_length) · line 69

Quoted 10 lines
ui/input-legacy.c +3 -3
 
-    for (i = 0; QKeyCode_lookup[i] != NULL; i++) {
-        if (!strncmp(key, QKeyCode_lookup[i], key_length) &&
-            !QKeyCode_lookup[i][key_length]) {
+    for (i = 0; QKeyCode_lookup.array[i] != NULL; i++) {
+        if (!strncmp(key, QKeyCode_lookup.array[i], key_length) &&
+            !QKeyCode_lookup.array[i][key_length]) {
             break;
         }
     }

This is almost qapi_enum_parse(), but not quite: the key isn't zero-terminated. Pity, because it looks like the last user that dots into QEnumLookup. If we get rid of it, we can make it opaque. I'd do it right away, but if you prefer to leave it for later, I can accept that.

[Skipping more churn...]

I may well have missed issues in the stuff I skipped here. Hopefully, I can reduce the churn and make this patch reviewable in full.

#42 lore raw

PATCH v2 13/54 qapi: drop the sentinel in enum array

In reply to Marc-André Lureau

Now that all usages have been converted to user lookup helpers.

---
 scripts/qapi.py   | 1 -
 block/parallels.c | 1 -
 ui/input-legacy.c | 2 +-
 3 files changed, 1 insertion(+), 3 deletions(-)
scripts/qapi.py +0 -1
index 314d7e0365..73adb90379 100644
@@ -1863,7 +1863,6 @@ static const char *const %(c_name)s_array[] = {
 
     max_index = c_enum_const(name, '_MAX', prefix)
     ret += mcgen('''
-    [%(max_index)s] = NULL,
 };
 
 const QEnumLookup %(c_name)s_lookup = {
block/parallels.c +0 -1
index f870bbac3e..d5de692c9c 100644
@@ -72,7 +72,6 @@ typedef enum ParallelsPreallocMode {
 static const char *prealloc_mode_array[] = {
     "falloc",
     "truncate",
-    NULL,
 };
 
 static QEnumLookup prealloc_mode_lookup = {
ui/input-legacy.c +1 -1
index c597bdc711..d50a18a505 100644
@@ -61,7 +61,7 @@ int index_from_key(const char *key, size_t key_length)
 {
     int i;
 
-    for (i = 0; QKeyCode_lookup.array[i] != NULL; i++) {
+    for (i = 0; i < QKeyCode_lookup.size; i++) {
         if (!strncmp(key, QKeyCode_lookup.array[i], key_length) &&
             !QKeyCode_lookup.array[i][key_length]) {
             break;
Signature · 1 line
2.14.1.146.gd35faa819
#43 lore raw

Re: [Qemu-devel] [PATCH v2 13/54] qapi: drop the sentinel in enum array

Quoted 1 line · Marc-André Lureau

Now that all usages have been converted to user lookup helpers.

I don't think you got them all:

    $ git-grep -F _lookup.
    tests/test-qobject-input-visitor.c:    for (i = 0; i < EnumOne_lookup.size; i++) {
    tests/test-qobject-input-visitor.c:        v = visitor_input_test_init(data, "%s", EnumOne_lookup.array[i]);
    tests/test-qobject-input-visitor.c:                           UserDefNativeListUnionKind_lookup.array[kind],
    tests/test-string-input-visitor.c:    for (i = 0; i < EnumOne_lookup.size; i++) {
    tests/test-string-input-visitor.c:        v = visitor_input_test_init(data, EnumOne_lookup.array[i]);
    ui/input-legacy.c:    for (i = 0; i < QKeyCode_lookup.size; i++) {
    ui/input-legacy.c:        if (!strncmp(key, QKeyCode_lookup.array[i], key_length) &&
    ui/input-legacy.c:            !QKeyCode_lookup.array[i][key_length]) {

I think I commented on all of these guys in my review of PATCH 06-12.

#44 lore raw

PATCH v2 14/54 qapi2texi: minor python code simplification

In reply to Marc-André Lureau
---
 scripts/qapi2texi.py | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
scripts/qapi2texi.py +3 -4
index a317526e51..8b542f9fff 100755
@@ -136,10 +136,9 @@ def texi_enum_value(value):
 def texi_member(member, suffix=''):
     """Format a table of members item for an object type member"""
     typ = member.type.doc_type()
-    return '@item @code{%s%s%s}%s%s\n' % (
-        member.name,
-        ': ' if typ else '',
-        typ if typ else '',
+    membertype = ': %s' % typ if typ else ''
+    return '@item @code{%s%s}%s%s\n' % (
+        member.name, membertype,
         ' (optional)' if member.optional else '',
         suffix)
 
Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 14/54
#45 lore raw

Re: [Qemu-devel] [PATCH v2 14/54] qapi2texi: minor python code simplification

Quoted 1 line · Marc-André Lureau
Quoted 23 lines
---
  scripts/qapi2texi.py | 7 +++----
  1 file changed, 3 insertions(+), 4 deletions(-)
scripts/qapi2texi.py +3 -4
index a317526e51..8b542f9fff 100755
@@ -136,10 +136,9 @@ def texi_enum_value(value):
  def texi_member(member, suffix=''):
      """Format a table of members item for an object type member"""
      typ = member.type.doc_type()
-    return '@item @code{%s%s%s}%s%s\n' % (
-        member.name,
-        ': ' if typ else '',
-        typ if typ else '',
+    membertype = ': %s' % typ if typ else ''
+    return '@item @code{%s%s}%s%s\n' % (
+        member.name, membertype,
          ' (optional)' if member.optional else '',
          suffix)
 
Reviewed-by on v2 14/54
#46 lore raw

Re: [Qemu-devel] [PATCH v2 14/54] qapi2texi: minor python code simplification

In reply to Marc-André Lureau
Quoted 10 lines · Marc-André Lureau
---
 scripts/qapi2texi.py | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
scripts/qapi2texi.py +0 -0
index a317526e51..8b542f9fff 100755

scripts/qapi2texi.py def texi_enum_value(value): · line 139

Quoted 8 lines
scripts/qapi2texi.py +1 -4
@@ -136,10 +136,9 @@ def texi_enum_value(value):
 def texi_member(member, suffix=''):
     """Format a table of members item for an object type member"""
     typ = member.type.doc_type()
-    return '@item @code{%s%s%s}%s%s\n' % (
-        member.name,
-        ': ' if typ else '',
-        typ if typ else '',
+    membertype = ': %s' % typ if typ else ''

I'd use string concatenation (': ' + typ) instead of interpolation. Matter of taste. Could make the change when I apply.

scripts/qapi2texi.py def texi_enum_value(value): · line 143

Quoted 4 lines
scripts/qapi2texi.py +2 -0
+    return '@item @code{%s%s}%s%s\n' % (
+        member.name, membertype,
         ' (optional)' if member.optional else '',
         suffix)
#47 lore raw

Re: [Qemu-devel] [PATCH v2 14/54] qapi2texi: minor python code simplification

Hi

----- Original Message -----

Quoted 7 lines
Quoted 5 lines · Marc-André Lureau
---
 scripts/qapi2texi.py | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
Quoted 16 lines

scripts/qapi2texi.py def texi_enum_value(value): · line 139

Quoted 13 lines
scripts/qapi2texi.py +1 -4
index a317526e51..8b542f9fff 100755
@@ -136,10 +136,9 @@ def texi_enum_value(value):
 def texi_member(member, suffix=''):
     """Format a table of members item for an object type member"""
     typ = member.type.doc_type()
-    return '@item @code{%s%s%s}%s%s\n' % (
-        member.name,
-        ': ' if typ else '',
-        typ if typ else '',
+    membertype = ': %s' % typ if typ else ''

I'd use string concatenation (': ' + typ) instead of interpolation. Matter of taste. Could make the change when I apply.

Good idea

Quoted 8 lines

scripts/qapi2texi.py def texi_enum_value(value): · line 143

Quoted 5 lines
scripts/qapi2texi.py +2 -0
+    return '@item @code{%s%s}%s%s\n' % (
+        member.name, membertype,
         ' (optional)' if member.optional else '',
         suffix)

thanks

#48 lore raw

PATCH v2 15/54 qapi: add 'if' to top-level expressions

In reply to Marc-André Lureau

Accept 'if' key in top-level elements, accepted as string or list of string type. The following patches will modify the test visitor to check the value is correctly saved, and generate #if/#endif code (as a single #if/endif line or a series for a list).

Example of 'if' key:
{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' }, 'if': 'defined(TEST_IF_STRUCT)' }

A following patch for qapi-code-gen.txt will provide more complete documentation for 'if' usage.

---
 scripts/qapi.py                         | 13 +++++++++++++
 tests/test-qmp-commands.c               |  6 ++++++
 tests/qapi-schema/qapi-schema-test.json | 20 ++++++++++++++++++++
 tests/qapi-schema/qapi-schema-test.out  | 22 ++++++++++++++++++++++
 4 files changed, 61 insertions(+)
scripts/qapi.py +13 -0
index 73adb90379..a94d93ada4 100644
@@ -639,6 +639,16 @@ def add_name(name, info, meta, implicit=False):
     all_names[name] = meta
 
 
+def check_if(expr, info):
+    ifcond = expr.get('if')
+    if not ifcond or isinstance(ifcond, str):
+        return
+    if (not isinstance(ifcond, list) or
+            any([not isinstance(elt, str) for elt in ifcond])):
+        raise QAPISemError(info, "'if' condition requires a string or "
+                           "a list of string")
+
+
 def check_type(info, source, value, allow_array=False,
                allow_dict=False, allow_optional=False,
                allow_metas=[]):
@@ -865,6 +875,7 @@ def check_keys(expr_elem, meta, required, optional=[]):
     expr = expr_elem['expr']
     info = expr_elem['info']
     name = expr[meta]
+    optional = optional + ['if']  # all top-level elem accept if
     if not isinstance(name, str):
         raise QAPISemError(info, "'%s' key must have a string value" % meta)
     required = required + [meta]
@@ -880,6 +891,8 @@ def check_keys(expr_elem, meta, required, optional=[]):
             raise QAPISemError(info,
                                "'%s' of %s '%s' should only use true value"
                                % (key, meta, name))
+        if key == 'if':
+            check_if(expr, info)
     for key in required:
         if key not in expr:
             raise QAPISemError(info, "Key '%s' is missing from %s '%s'"
tests/test-qmp-commands.c +6 -0
index 904c89d4d4..9b9a7ffee7 100644
@@ -10,6 +10,12 @@
 
 static QmpCommandList qmp_commands;
 
+/* #if defined(TEST_IF_CMD) */
+void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
+{
+}
+/* #endif */
+
 void qmp_user_def_cmd(Error **errp)
 {
 }
tests/qapi-schema/qapi-schema-test.json +20 -0
index c72dbd8050..dc2c444fc1 100644
@@ -188,3 +188,23 @@
   'data': { 'a': ['__org.qemu_x-Enum'], 'b': ['__org.qemu_x-Struct'],
             'c': '__org.qemu_x-Union2', 'd': '__org.qemu_x-Alt' },
   'returns': '__org.qemu_x-Union1' }
+
+# test 'if' condition handling
+
+{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
+  'if': 'defined(TEST_IF_STRUCT)' }
+
+{ 'enum': 'TestIfEnum', 'data': [ 'foo', 'bar' ],
+  'if': 'defined(TEST_IF_ENUM)' }
+
+{ 'union': 'TestIfUnion', 'data': { 'foo': 'TestStruct' },
+  'if': 'defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)' }
+
+{ 'alternate': 'TestIfAlternate', 'data': { 'foo': 'int', 'bar': 'TestStruct' },
+  'if': 'defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)' }
+
+{ 'command': 'TestIfCmd', 'data': { 'foo': 'TestIfStruct' },
+  'if': 'defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)' }
+
+{ 'event': 'TestIfEvent', 'data': { 'foo': 'TestIfStruct' },
+  'if': 'defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)' }
tests/qapi-schema/qapi-schema-test.out +22 -0
index 3b1e9082d3..7fbaea19bc 100644
@@ -52,6 +52,22 @@ enum QEnumTwo ['value1', 'value2']
     prefix QENUM_TWO
 enum QType ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist', 'qbool']
     prefix QTYPE
+alternate TestIfAlternate
+    tag type
+    case foo: int
+    case bar: TestStruct
+command TestIfCmd q_obj_TestIfCmd-arg -> None
+   gen=True success_response=True boxed=False
+enum TestIfEnum ['foo', 'bar']
+event TestIfEvent q_obj_TestIfEvent-arg
+   boxed=False
+object TestIfStruct
+    member foo: int optional=False
+object TestIfUnion
+    member type: TestIfUnionKind optional=False
+    tag type
+    case foo: q_obj_TestStruct-wrapper
+enum TestIfUnionKind ['foo']
 object TestStruct
     member integer: int optional=False
     member boolean: bool optional=False
@@ -172,6 +188,12 @@ object q_obj_EVENT_D-arg
     member b: str optional=False
     member c: str optional=True
     member enum3: EnumOne optional=True
+object q_obj_TestIfCmd-arg
+    member foo: TestIfStruct optional=False
+object q_obj_TestIfEvent-arg
+    member foo: TestIfStruct optional=False
+object q_obj_TestStruct-wrapper
+    member data: TestStruct optional=False
 object q_obj_UserDefFlatUnion2-base
     member integer: int optional=True
     member string: str optional=False
Signature · 1 line
2.14.1.146.gd35faa819
#49 lore raw

Re: [Qemu-devel] [PATCH v2 15/54] qapi: add 'if' to top-level expressions

Quoted 7 lines · Marc-André Lureau

Accept 'if' key in top-level elements, accepted as string or list of string type. The following patches will modify the test visitor to check the value is correctly saved, and generate #if/#endif code (as a single #if/endif line or a series for a list).

Example of 'if' key:
{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' }, 'if': 'defined(TEST_IF_STRUCT)' }

Lost line break?

Quoted 17 lines

A following patch for qapi-code-gen.txt will provide more complete documentation for 'if' usage.

---
 scripts/qapi.py                         | 13 +++++++++++++
 tests/test-qmp-commands.c               |  6 ++++++
 tests/qapi-schema/qapi-schema-test.json | 20 ++++++++++++++++++++
 tests/qapi-schema/qapi-schema-test.out  | 22 ++++++++++++++++++++++
 4 files changed, 61 insertions(+)
scripts/qapi.py +0 -0
index 73adb90379..a94d93ada4 100644
@@ -639,6 +639,16 @@ def add_name(name, info, meta, implicit=False):
     all_names[name] = meta

scripts/qapi.py def add_name(name, info, meta, implicit=False): · line 649

Quoted 10 lines
scripts/qapi.py +8 -0
 
 
+def check_if(expr, info):
+    ifcond = expr.get('if')
+    if not ifcond or isinstance(ifcond, str):
+        return
+    if (not isinstance(ifcond, list) or
+            any([not isinstance(elt, str) for elt in ifcond])):
+        raise QAPISemError(info, "'if' condition requires a string or "
+                           "a list of string")

The error also triggers on inputs 'if': '' and 'if': [].

The first one doesn't make sense (the C compiler will surely barf). We could leave rejecting it to the C compiler. If we choose to reject it here, we need a better error message, because the one above is misleading.

The second one is a roundabout way to say "unconditional". If we choose to reject that, we also need a non-misleading error message.

The error can't trigger on absent 'if', because we don't get called then. To make that locally obvious, please say

       ifcond = expr['if']

Moreover, I'd prefer to avoid mixing conditionals with opposite sense, i.e. if good: return; if bad: raise.

Taken together:

def check_if(expr, info):
ifcond = expr['if']
if isinstance(ifcond, str):
if ifcond == '':
raise QAPISemError(info, "'if' condition '' makes no sense")
return
if isinstance(ifcond, list):
if ifcond == []:
raise QAPISemError(info, "'if' condition [] is useless")
for elt in ifcond:
if not isinstance(elt, str):
raise QAPISemError(
info, "'if' condition %s makes no sense" % elt)
return
raise QAPISemError(
info, "'if' condition must be a string or a list of strings")

Written this way (one case after the other), each error has to report just one narrow problem. Makes crafting precise error messages easier.

scripts/qapi.py def check_keys(expr_elem, meta, required, optional=[]): · line 881

Quoted 13 lines
scripts/qapi.py +3 -0
+
+
 def check_type(info, source, value, allow_array=False,
                allow_dict=False, allow_optional=False,
                allow_metas=[]):
@@ -865,6 +875,7 @@ def check_keys(expr_elem, meta, required, optional=[]):
     expr = expr_elem['expr']
     info = expr_elem['info']
     name = expr[meta]
+    optional = optional + ['if']  # all top-level elem accept if
     if not isinstance(name, str):
         raise QAPISemError(info, "'%s' key must have a string value" % meta)
     required = required + [meta]

All top-level expressions require 'data'. Done the obvious way: all callers pass 'data' in @required. Let's do 'if' the same way for consistency.

Quoted 84 lines
scripts/qapi.py +2 -0
@@ -880,6 +891,8 @@ def check_keys(expr_elem, meta, required, optional=[]):
             raise QAPISemError(info,
                                "'%s' of %s '%s' should only use true value"
                                % (key, meta, name))
+        if key == 'if':
+            check_if(expr, info)
     for key in required:
         if key not in expr:
             raise QAPISemError(info, "Key '%s' is missing from %s '%s'"
tests/test-qmp-commands.c +6 -0
index 904c89d4d4..9b9a7ffee7 100644
@@ -10,6 +10,12 @@
 
 static QmpCommandList qmp_commands;
 
+/* #if defined(TEST_IF_CMD) */
+void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
+{
+}
+/* #endif */
+
 void qmp_user_def_cmd(Error **errp)
 {
 }
tests/qapi-schema/qapi-schema-test.json +20 -0
index c72dbd8050..dc2c444fc1 100644
@@ -188,3 +188,23 @@
   'data': { 'a': ['__org.qemu_x-Enum'], 'b': ['__org.qemu_x-Struct'],
             'c': '__org.qemu_x-Union2', 'd': '__org.qemu_x-Alt' },
   'returns': '__org.qemu_x-Union1' }
+
+# test 'if' condition handling
+
+{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
+  'if': 'defined(TEST_IF_STRUCT)' }
+
+{ 'enum': 'TestIfEnum', 'data': [ 'foo', 'bar' ],
+  'if': 'defined(TEST_IF_ENUM)' }
+
+{ 'union': 'TestIfUnion', 'data': { 'foo': 'TestStruct' },
+  'if': 'defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)' }
+
+{ 'alternate': 'TestIfAlternate', 'data': { 'foo': 'int', 'bar': 'TestStruct' },
+  'if': 'defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)' }
+
+{ 'command': 'TestIfCmd', 'data': { 'foo': 'TestIfStruct' },
+  'if': 'defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)' }
+
+{ 'event': 'TestIfEvent', 'data': { 'foo': 'TestIfStruct' },
+  'if': 'defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)' }
tests/qapi-schema/qapi-schema-test.out +16 -0
index 3b1e9082d3..7fbaea19bc 100644
@@ -52,6 +52,22 @@ enum QEnumTwo ['value1', 'value2']
     prefix QENUM_TWO
 enum QType ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist', 'qbool']
     prefix QTYPE
+alternate TestIfAlternate
+    tag type
+    case foo: int
+    case bar: TestStruct
+command TestIfCmd q_obj_TestIfCmd-arg -> None
+   gen=True success_response=True boxed=False
+enum TestIfEnum ['foo', 'bar']
+event TestIfEvent q_obj_TestIfEvent-arg
+   boxed=False
+object TestIfStruct
+    member foo: int optional=False
+object TestIfUnion
+    member type: TestIfUnionKind optional=False
+    tag type
+    case foo: q_obj_TestStruct-wrapper
+enum TestIfUnionKind ['foo']
 object TestStruct
     member integer: int optional=False
     member boolean: bool optional=False
@@ -172,6 +188,12 @@ object q_obj_EVENT_D-arg
     member b: str optional=False
     member c: str optional=True

tests/qapi-schema/qapi-schema-test.out object q_obj_EVENT_D-arg · line 199

Quoted 10 lines
tests/qapi-schema/qapi-schema-test.out +6 -0
     member enum3: EnumOne optional=True
+object q_obj_TestIfCmd-arg
+    member foo: TestIfStruct optional=False
+object q_obj_TestIfEvent-arg
+    member foo: TestIfStruct optional=False
+object q_obj_TestStruct-wrapper
+    member data: TestStruct optional=False
 object q_obj_UserDefFlatUnion2-base
     member integer: int optional=True
     member string: str optional=False

The conditionals aren't visible in qapi-schema-test.out. They should be.

*Much* easier to review than its predecessor PATCH 07/26. Appreciated!

#50 lore raw

Re: [Qemu-devel] [PATCH v2 15/54] qapi: add 'if' to top-level expressions

Hi

Quoted 11 lines · Markus Armbruster
Quoted 7 lines · Marc-André Lureau

Accept 'if' key in top-level elements, accepted as string or list of string type. The following patches will modify the test visitor to check the value is correctly saved, and generate #if/#endif code (as a single #if/endif line or a series for a list).

Example of 'if' key:
{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' }, 'if': 'defined(TEST_IF_STRUCT)' }

Lost line break?

yes

Quoted 66 lines
Quoted 18 lines

A following patch for qapi-code-gen.txt will provide more complete documentation for 'if' usage.

---
 scripts/qapi.py                         | 13 +++++++++++++
 tests/test-qmp-commands.c               |  6 ++++++
 tests/qapi-schema/qapi-schema-test.json | 20 ++++++++++++++++++++
 tests/qapi-schema/qapi-schema-test.out  | 22 ++++++++++++++++++++++
 4 files changed, 61 insertions(+)
scripts/qapi.py +0 -0
index 73adb90379..a94d93ada4 100644
@@ -639,6 +639,16 @@ def add_name(name, info, meta, implicit=False):
     all_names[name] = meta

scripts/qapi.py def add_name(name, info, meta, implicit=False): · line 649

Quoted 10 lines
scripts/qapi.py +8 -0
 
 
+def check_if(expr, info):
+    ifcond = expr.get('if')
+    if not ifcond or isinstance(ifcond, str):
+        return
+    if (not isinstance(ifcond, list) or
+            any([not isinstance(elt, str) for elt in ifcond])):
+        raise QAPISemError(info, "'if' condition requires a string or "
+                           "a list of string")

The error also triggers on inputs 'if': '' and 'if': [].

The first one doesn't make sense (the C compiler will surely barf). We could leave rejecting it to the C compiler. If we choose to reject it here, we need a better error message, because the one above is misleading.

The second one is a roundabout way to say "unconditional". If we choose to reject that, we also need a non-misleading error message.

The error can't trigger on absent 'if', because we don't get called then. To make that locally obvious, please say

       ifcond = expr['if']

Moreover, I'd prefer to avoid mixing conditionals with opposite sense, i.e. if good: return; if bad: raise.

Taken together:

def check_if(expr, info):
ifcond = expr['if']
if isinstance(ifcond, str):
if ifcond == '':
raise QAPISemError(info, "'if' condition '' makes no sense")
return
if isinstance(ifcond, list):
if ifcond == []:
raise QAPISemError(info, "'if' condition [] is useless")
for elt in ifcond:
if not isinstance(elt, str):
raise QAPISemError(
info, "'if' condition %s makes no sense" % elt)
return
raise QAPISemError(
info, "'if' condition must be a string or a list of strings")

Quoted 3 lines

Written this way (one case after the other), each error has to report just one narrow problem. Makes crafting precise error messages easier.

ok, thanks

Quoted 9 lines
Quoted 9 lines
scripts/qapi.py +2 -0
+
+
 def check_type(info, source, value, allow_array=False,
                allow_dict=False, allow_optional=False,
                allow_metas=[]):
@@ -865,6 +875,7 @@ def check_keys(expr_elem, meta, required, optional=[]):
     expr = expr_elem['expr']
     info = expr_elem['info']
     name = expr[meta]
Quoted 8 lines

scripts/qapi.py def check_keys(expr_elem, meta, required, optional=[]): · line 881

Quoted 4 lines
scripts/qapi.py +1 -0
+    optional = optional + ['if']  # all top-level elem accept if
     if not isinstance(name, str):
         raise QAPISemError(info, "'%s' key must have a string value" % meta)
     required = required + [meta]

All top-level expressions require 'data'. Done the obvious way: all callers pass 'data' in @required. Let's do 'if' the same way for consistency.

Not all, 'data' is not required for commands & events.

And 'if' is always optional.

But anyway, I modified it now to pass it as argument...

Quoted 90 lines
Quoted 90 lines
scripts/qapi.py +2 -0
@@ -880,6 +891,8 @@ def check_keys(expr_elem, meta, required, optional=[]):
             raise QAPISemError(info,
                                "'%s' of %s '%s' should only use true value"
                                % (key, meta, name))
+        if key == 'if':
+            check_if(expr, info)
     for key in required:
         if key not in expr:
             raise QAPISemError(info, "Key '%s' is missing from %s '%s'"
tests/test-qmp-commands.c +6 -0
index 904c89d4d4..9b9a7ffee7 100644
@@ -10,6 +10,12 @@
 
 static QmpCommandList qmp_commands;
 
+/* #if defined(TEST_IF_CMD) */
+void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
+{
+}
+/* #endif */
+
 void qmp_user_def_cmd(Error **errp)
 {
 }
tests/qapi-schema/qapi-schema-test.json +20 -0
index c72dbd8050..dc2c444fc1 100644
@@ -188,3 +188,23 @@
   'data': { 'a': ['__org.qemu_x-Enum'], 'b': ['__org.qemu_x-Struct'],
             'c': '__org.qemu_x-Union2', 'd': '__org.qemu_x-Alt' },
   'returns': '__org.qemu_x-Union1' }
+
+# test 'if' condition handling
+
+{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
+  'if': 'defined(TEST_IF_STRUCT)' }
+
+{ 'enum': 'TestIfEnum', 'data': [ 'foo', 'bar' ],
+  'if': 'defined(TEST_IF_ENUM)' }
+
+{ 'union': 'TestIfUnion', 'data': { 'foo': 'TestStruct' },
+  'if': 'defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)' }
+
+{ 'alternate': 'TestIfAlternate', 'data': { 'foo': 'int', 'bar': 'TestStruct' },
+  'if': 'defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)' }
+
+{ 'command': 'TestIfCmd', 'data': { 'foo': 'TestIfStruct' },
+  'if': 'defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)' }
+
+{ 'event': 'TestIfEvent', 'data': { 'foo': 'TestIfStruct' },
+  'if': 'defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)' }
tests/qapi-schema/qapi-schema-test.out +20 -0
index 3b1e9082d3..7fbaea19bc 100644
@@ -52,6 +52,22 @@ enum QEnumTwo ['value1', 'value2']
     prefix QENUM_TWO
 enum QType ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist', 'qbool']
     prefix QTYPE
+alternate TestIfAlternate
+    tag type
+    case foo: int
+    case bar: TestStruct
+command TestIfCmd q_obj_TestIfCmd-arg -> None
+   gen=True success_response=True boxed=False
+enum TestIfEnum ['foo', 'bar']
+event TestIfEvent q_obj_TestIfEvent-arg
+   boxed=False
+object TestIfStruct
+    member foo: int optional=False
+object TestIfUnion
+    member type: TestIfUnionKind optional=False
+    tag type
+    case foo: q_obj_TestStruct-wrapper
+enum TestIfUnionKind ['foo']
 object TestStruct
     member integer: int optional=False
     member boolean: bool optional=False
@@ -172,6 +188,12 @@ object q_obj_EVENT_D-arg
     member b: str optional=False
     member c: str optional=True
     member enum3: EnumOne optional=True
+object q_obj_TestIfCmd-arg
+    member foo: TestIfStruct optional=False
+object q_obj_TestIfEvent-arg
+    member foo: TestIfStruct optional=False
Quoted 9 lines

tests/qapi-schema/qapi-schema-test.out object q_obj_EVENT_D-arg · line 199

Quoted 5 lines
tests/qapi-schema/qapi-schema-test.out +2 -0
+object q_obj_TestStruct-wrapper
+    member data: TestStruct optional=False
 object q_obj_UserDefFlatUnion2-base
     member integer: int optional=True
     member string: str optional=False

The conditionals aren't visible in qapi-schema-test.out. They should be.

That's a follow-up patch "qapi: add 'ifcond' to visitor methods"

Quoted 1 line

*Much* easier to review than its predecessor PATCH 07/26. Appreciated!

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

Re: [Qemu-devel] [PATCH v2 15/54] qapi: add 'if' to top-level expressions

Quoted 22 lines · Marc-André Lureau

Hi

Quoted 11 lines · Markus Armbruster
Quoted 7 lines · Marc-André Lureau

Accept 'if' key in top-level elements, accepted as string or list of string type. The following patches will modify the test visitor to check the value is correctly saved, and generate #if/#endif code (as a single #if/endif line or a series for a list).

Example of 'if' key:
{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' }, 'if': 'defined(TEST_IF_STRUCT)' }

Lost line break?

yes

Quoted 5 lines
Quoted 5 lines

A following patch for qapi-code-gen.txt will provide more complete documentation for 'if' usage.

[...]

Quoted 45 lines
Quoted 35 lines
Quoted 35 lines
tests/qapi-schema/qapi-schema-test.out +20 -0
index 3b1e9082d3..7fbaea19bc 100644
@@ -52,6 +52,22 @@ enum QEnumTwo ['value1', 'value2']
     prefix QENUM_TWO
 enum QType ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist', 'qbool']
     prefix QTYPE
+alternate TestIfAlternate
+    tag type
+    case foo: int
+    case bar: TestStruct
+command TestIfCmd q_obj_TestIfCmd-arg -> None
+   gen=True success_response=True boxed=False
+enum TestIfEnum ['foo', 'bar']
+event TestIfEvent q_obj_TestIfEvent-arg
+   boxed=False
+object TestIfStruct
+    member foo: int optional=False
+object TestIfUnion
+    member type: TestIfUnionKind optional=False
+    tag type
+    case foo: q_obj_TestStruct-wrapper
+enum TestIfUnionKind ['foo']
 object TestStruct
     member integer: int optional=False
     member boolean: bool optional=False
@@ -172,6 +188,12 @@ object q_obj_EVENT_D-arg
     member b: str optional=False
     member c: str optional=True
     member enum3: EnumOne optional=True
+object q_obj_TestIfCmd-arg
+    member foo: TestIfStruct optional=False
+object q_obj_TestIfEvent-arg
+    member foo: TestIfStruct optional=False
Quoted 9 lines

tests/qapi-schema/qapi-schema-test.out object q_obj_EVENT_D-arg · line 199

Quoted 5 lines
tests/qapi-schema/qapi-schema-test.out +2 -0
+object q_obj_TestStruct-wrapper
+    member data: TestStruct optional=False
 object q_obj_UserDefFlatUnion2-base
     member integer: int optional=True
     member string: str optional=False

The conditionals aren't visible in qapi-schema-test.out. They should be.

Quoted 1 line

That's a follow-up patch "qapi: add 'ifcond' to visitor methods"

Which I've since found %-}

Similarly, the generated code is for now *unconditional*. Later patches generate the conditionals.

Let's point this out in the commit message.

Remember, your poor, ignorant reviewer squints at your patches through a toiler paper tube, and may need your help to see the bigger picture.

Quoted 1 line
Quoted 1 line

*Much* easier to review than its predecessor PATCH 07/26. Appreciated!

#52 lore raw

PATCH v2 16/54 qapi: add a test for invalid 'if'

In reply to Marc-André Lureau
---
 tests/Makefile.include        | 1 +
 tests/qapi-schema/bad-if.err  | 1 +
 tests/qapi-schema/bad-if.exit | 1 +
 tests/qapi-schema/bad-if.json | 3 +++
 tests/qapi-schema/bad-if.out  | 0
 5 files changed, 6 insertions(+)
 create mode 100644 tests/qapi-schema/bad-if.err
 create mode 100644 tests/qapi-schema/bad-if.exit
 create mode 100644 tests/qapi-schema/bad-if.json
 create mode 100644 tests/qapi-schema/bad-if.out
tests/Makefile.include +1 -0
index 3653c7b40a..1f1d8f075b 100644
@@ -396,6 +396,7 @@ qapi-schema += args-unknown.json
 qapi-schema += bad-base.json
 qapi-schema += bad-data.json
 qapi-schema += bad-ident.json
+qapi-schema += bad-if.json
 qapi-schema += bad-type-bool.json
 qapi-schema += bad-type-dict.json
 qapi-schema += bad-type-int.json
tests/qapi-schema/bad-if.err new file +1 -0
new file mode 100644
index 0000000000..8054fbb143
@@ -0,0 +1 @@
+tests/qapi-schema/bad-if.json:2: 'if' condition requires a string or a list of string
tests/qapi-schema/bad-if.exit new file +1 -0
new file mode 100644
index 0000000000..d00491fd7e
@@ -0,0 +1 @@
+1
tests/qapi-schema/bad-if.json new file +3 -0
new file mode 100644
index 0000000000..3edd1a0bf2
@@ -0,0 +1,3 @@
+# check invalid 'if' type
+{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
+  'if': { 'value': 'defined(TEST_IF_STRUCT)' } }
tests/qapi-schema/bad-if.out new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
Signature · 1 line
2.14.1.146.gd35faa819
#53 lore raw

Re: [Qemu-devel] [PATCH v2 16/54] qapi: add a test for invalid 'if'

tests/qapi-schema/bad-if.out

Quoted 51 lines · Marc-André Lureau
---
 tests/Makefile.include        | 1 +
 tests/qapi-schema/bad-if.err  | 1 +
 tests/qapi-schema/bad-if.exit | 1 +
 tests/qapi-schema/bad-if.json | 3 +++
 tests/qapi-schema/bad-if.out  | 0
 5 files changed, 6 insertions(+)
 create mode 100644 tests/qapi-schema/bad-if.err
 create mode 100644 tests/qapi-schema/bad-if.exit
 create mode 100644 tests/qapi-schema/bad-if.json
 create mode 100644 tests/qapi-schema/bad-if.out
tests/Makefile.include +1 -0
index 3653c7b40a..1f1d8f075b 100644
@@ -396,6 +396,7 @@ qapi-schema += args-unknown.json
 qapi-schema += bad-base.json
 qapi-schema += bad-data.json
 qapi-schema += bad-ident.json
+qapi-schema += bad-if.json
 qapi-schema += bad-type-bool.json
 qapi-schema += bad-type-dict.json
 qapi-schema += bad-type-int.json
tests/qapi-schema/bad-if.err new file +1 -0
new file mode 100644
index 0000000000..8054fbb143
@@ -0,0 +1 @@
+tests/qapi-schema/bad-if.json:2: 'if' condition requires a string or a list of string
tests/qapi-schema/bad-if.exit new file +1 -0
new file mode 100644
index 0000000000..d00491fd7e
@@ -0,0 +1 @@
+1
tests/qapi-schema/bad-if.json new file +3 -0
new file mode 100644
index 0000000000..3edd1a0bf2
@@ -0,0 +1,3 @@
+# check invalid 'if' type
+{ 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
+  'if': { 'value': 'defined(TEST_IF_STRUCT)' } }
tests/qapi-schema/bad-if.out new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2

Adding a test for each error is good practice. You did, but your error is a bit of a catch-all. The code I proposed in my review of the previous patch splits it up. To keep up good practice, we need a test case for each shard.

I'd squash this into the previous patch to stop "you're lacking tests" review comments :)

#54 lore raw

PATCH v2 17/54 qapi: add 'if' condition on entity objects

In reply to Marc-André Lureau

Take 'if' from expression, and use it to construct entity objects. Shared implicit objects must share the same 'if' condition.

---
 scripts/qapi.py | 81 +++++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 53 insertions(+), 28 deletions(-)
scripts/qapi.py +53 -28
index a94d93ada4..dc40d74abb 100644
@@ -992,7 +992,7 @@ def check_exprs(exprs):
 #
 
 class QAPISchemaEntity(object):
-    def __init__(self, name, info, doc):
+    def __init__(self, name, info, doc, ifcond=None):
         assert isinstance(name, str)
         self.name = name
         # For explicitly defined entities, info points to the (explicit)
@@ -1002,6 +1002,7 @@ class QAPISchemaEntity(object):
         # such place).
         self.info = info
         self.doc = doc
+        self.ifcond = ifcond
 
     def c_name(self):
         return c_name(self.name)
@@ -1118,8 +1119,8 @@ class QAPISchemaBuiltinType(QAPISchemaType):
 
 
 class QAPISchemaEnumType(QAPISchemaType):
-    def __init__(self, name, info, doc, values, prefix):
-        QAPISchemaType.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, values, prefix, ifcond=None):
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         for v in values:
             assert isinstance(v, QAPISchemaMember)
             v.set_owner(name)
@@ -1162,6 +1163,7 @@ class QAPISchemaArrayType(QAPISchemaType):
     def check(self, schema):
         self.element_type = schema.lookup_type(self._element_type_name)
         assert self.element_type
+        self.ifcond = self.element_type.ifcond
 
     def is_implicit(self):
         return True
@@ -1183,11 +1185,12 @@ class QAPISchemaArrayType(QAPISchemaType):
 
 
 class QAPISchemaObjectType(QAPISchemaType):
-    def __init__(self, name, info, doc, base, local_members, variants):
+    def __init__(self, name, info, doc, base, local_members, variants,
+                 ifcond=None):
         # struct has local_members, optional base, and no variants
         # flat union has base, variants, and no local_members
         # simple union has local_members, variants, and no base
-        QAPISchemaType.__init__(self, name, info, doc)
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         assert base is None or isinstance(base, str)
         for m in local_members:
             assert isinstance(m, QAPISchemaObjectTypeMember)
@@ -1375,8 +1378,8 @@ class QAPISchemaObjectTypeVariant(QAPISchemaObjectTypeMember):
 
 
 class QAPISchemaAlternateType(QAPISchemaType):
-    def __init__(self, name, info, doc, variants):
-        QAPISchemaType.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, variants, ifcond):
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         assert isinstance(variants, QAPISchemaObjectTypeVariants)
         assert variants.tag_member
         variants.set_owner(name)
@@ -1413,8 +1416,8 @@ class QAPISchemaAlternateType(QAPISchemaType):
 
 class QAPISchemaCommand(QAPISchemaEntity):
     def __init__(self, name, info, doc, arg_type, ret_type,
-                 gen, success_response, boxed):
-        QAPISchemaEntity.__init__(self, name, info, doc)
+                 gen, success_response, boxed, ifcond):
+        QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
         assert not arg_type or isinstance(arg_type, str)
         assert not ret_type or isinstance(ret_type, str)
         self._arg_type_name = arg_type
@@ -1451,8 +1454,8 @@ class QAPISchemaCommand(QAPISchemaEntity):
 
 
 class QAPISchemaEvent(QAPISchemaEntity):
-    def __init__(self, name, info, doc, arg_type, boxed):
-        QAPISchemaEntity.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, arg_type, boxed, ifcond):
+        QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
         assert not arg_type or isinstance(arg_type, str)
         self._arg_type_name = arg_type
         self.arg_type = None
@@ -1547,11 +1550,11 @@ class QAPISchema(object):
     def _make_enum_members(self, values):
         return [QAPISchemaMember(v) for v in values]
 
-    def _make_implicit_enum_type(self, name, info, values):
+    def _make_implicit_enum_type(self, name, info, values, ifcond):
         # See also QAPISchemaObjectTypeMember._pretty_owner()
         name = name + 'Kind'   # Use namespace reserved by add_name()
         self._def_entity(QAPISchemaEnumType(
-            name, info, None, self._make_enum_members(values), None))
+            name, info, None, self._make_enum_members(values), None, ifcond))
         return name
 
     def _make_array_type(self, element_type, info):
@@ -1560,22 +1563,29 @@ class QAPISchema(object):
             self._def_entity(QAPISchemaArrayType(name, info, element_type))
         return name
 
-    def _make_implicit_object_type(self, name, info, doc, role, members):
+    def _make_implicit_object_type(self, name, info, doc, role, members,
+                                   ifcond=None):
         if not members:
             return None
         # See also QAPISchemaObjectTypeMember._pretty_owner()
         name = 'q_obj_%s-%s' % (name, role)
-        if not self.lookup_entity(name, QAPISchemaObjectType):
+        typ = self.lookup_entity(name, QAPISchemaObjectType)
+        if typ:
+            # FIXME: generating the disjunction of all conditions
+            assert ifcond == typ.ifcond
+        else:
             self._def_entity(QAPISchemaObjectType(name, info, doc, None,
-                                                  members, None))
+                                                  members, None, ifcond))
         return name
 
     def _def_enum_type(self, expr, info, doc):
         name = expr['enum']
         data = expr['data']
         prefix = expr.get('prefix')
+        ifcond = expr.get('if')
         self._def_entity(QAPISchemaEnumType(
-            name, info, doc, self._make_enum_members(data), prefix))
+            name, info, doc, self._make_enum_members(data), prefix,
+            ifcond))
 
     def _make_member(self, name, typ, info):
         optional = False
@@ -1595,9 +1605,10 @@ class QAPISchema(object):
         name = expr['struct']
         base = expr.get('base')
         data = expr['data']
+        ifcond = expr.get('if')
         self._def_entity(QAPISchemaObjectType(name, info, doc, base,
                                               self._make_members(data, info),
-                                              None))
+                                              None, ifcond))
 
     def _make_variant(self, case, typ):
         return QAPISchemaObjectTypeVariant(case, typ)
@@ -1606,19 +1617,23 @@ class QAPISchema(object):
         if isinstance(typ, list):
             assert len(typ) == 1
             typ = self._make_array_type(typ[0], info)
+        type_entity = self.lookup_type(typ)
         typ = self._make_implicit_object_type(
-            typ, info, None, 'wrapper', [self._make_member('data', typ, info)])
+            typ, info, None, 'wrapper',
+            [self._make_member('data', typ, info)], type_entity.ifcond)
         return QAPISchemaObjectTypeVariant(case, typ)
 
     def _def_union_type(self, expr, info, doc):
         name = expr['union']
         data = expr['data']
         base = expr.get('base')
+        ifcond = expr.get('if')
         tag_name = expr.get('discriminator')
         tag_member = None
         if isinstance(base, dict):
-            base = (self._make_implicit_object_type(
-                name, info, doc, 'base', self._make_members(base, info)))
+            base = self._make_implicit_object_type(
+                name, info, doc, 'base', self._make_members(base, info),
+                ifcond)
         if tag_name:
             variants = [self._make_variant(key, value)
                         for (key, value) in data.iteritems()]
@@ -1627,18 +1642,21 @@ class QAPISchema(object):
             variants = [self._make_simple_variant(key, value, info)
                         for (key, value) in data.iteritems()]
             typ = self._make_implicit_enum_type(name, info,
-                                                [v.name for v in variants])
+                                                [v.name for v in variants],
+                                                ifcond)
             tag_member = QAPISchemaObjectTypeMember('type', typ, False)
             members = [tag_member]
         self._def_entity(
             QAPISchemaObjectType(name, info, doc, base, members,
                                  QAPISchemaObjectTypeVariants(tag_name,
                                                               tag_member,
-                                                              variants)))
+                                                              variants),
+                                 ifcond))
 
     def _def_alternate_type(self, expr, info, doc):
         name = expr['alternate']
         data = expr['data']
+        ifcond = expr.get('if')
         variants = [self._make_variant(key, value)
                     for (key, value) in data.iteritems()]
         tag_member = QAPISchemaObjectTypeMember('type', 'QType', False)
@@ -1646,7 +1664,8 @@ class QAPISchema(object):
             QAPISchemaAlternateType(name, info, doc,
                                     QAPISchemaObjectTypeVariants(None,
                                                                  tag_member,
-                                                                 variants)))
+                                                                 variants),
+                                    ifcond))
 
     def _def_command(self, expr, info, doc):
         name = expr['command']
@@ -1655,23 +1674,29 @@ class QAPISchema(object):
         gen = expr.get('gen', True)
         success_response = expr.get('success-response', True)
         boxed = expr.get('boxed', False)
+        ifcond = expr.get('if')
         if isinstance(data, OrderedDict):
             data = self._make_implicit_object_type(
-                name, info, doc, 'arg', self._make_members(data, info))
+                name, info, doc, 'arg', self._make_members(data, info),
+                ifcond)
         if isinstance(rets, list):
             assert len(rets) == 1
             rets = self._make_array_type(rets[0], info)
         self._def_entity(QAPISchemaCommand(name, info, doc, data, rets,
-                                           gen, success_response, boxed))
+                                           gen, success_response, boxed,
+                                           ifcond))
 
     def _def_event(self, expr, info, doc):
         name = expr['event']
         data = expr.get('data')
         boxed = expr.get('boxed', False)
+        ifcond = expr.get('if')
         if isinstance(data, OrderedDict):
             data = self._make_implicit_object_type(
-                name, info, doc, 'arg', self._make_members(data, info))
-        self._def_entity(QAPISchemaEvent(name, info, doc, data, boxed))
+                name, info, doc, 'arg', self._make_members(data, info),
+                ifcond)
+        self._def_entity(QAPISchemaEvent(name, info, doc, data, boxed,
+                                         ifcond))
 
     def _def_exprs(self):
         for expr_elem in self.exprs:
Signature · 1 line
2.14.1.146.gd35faa819
#55 lore raw

Re: [Qemu-devel] [PATCH v2 17/54] qapi: add 'if' condition on entity objects

Quoted 2 lines · Marc-André Lureau

Take 'if' from expression, and use it to construct entity objects. Shared implicit objects must share the same 'if' condition.

Shared by what?

Quoted 11 lines
---
 scripts/qapi.py | 81 +++++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 53 insertions(+), 28 deletions(-)
scripts/qapi.py +0 -0
index a94d93ada4..dc40d74abb 100644

scripts/qapi.py def check_exprs(exprs): · line 998

Quoted 8 lines
scripts/qapi.py +1 -1
@@ -992,7 +992,7 @@ def check_exprs(exprs):
 #
 
 class QAPISchemaEntity(object):
-    def __init__(self, name, info, doc):
+    def __init__(self, name, info, doc, ifcond=None):
         assert isinstance(name, str)
         self.name = name
         # For explicitly defined entities, info points to the (explicit)

Not visible here: QAPISchemaType inherits this.

Quoted 20 lines
scripts/qapi.py +3 -2
@@ -1002,6 +1002,7 @@ class QAPISchemaEntity(object):
         # such place).
         self.info = info
         self.doc = doc
+        self.ifcond = ifcond
 
     def c_name(self):
         return c_name(self.name)
@@ -1118,8 +1119,8 @@ class QAPISchemaBuiltinType(QAPISchemaType):
 
 
 class QAPISchemaEnumType(QAPISchemaType):
-    def __init__(self, name, info, doc, values, prefix):
-        QAPISchemaType.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, values, prefix, ifcond=None):
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         for v in values:
             assert isinstance(v, QAPISchemaMember)
             v.set_owner(name)

scripts/qapi.py class QAPISchemaArrayType(QAPISchemaType): · line 1166

Quoted 4 lines
scripts/qapi.py +1 -0
@@ -1162,6 +1163,7 @@ class QAPISchemaArrayType(QAPISchemaType):
     def check(self, schema):
         self.element_type = schema.lookup_type(self._element_type_name)
         assert self.element_type
+        self.ifcond = self.element_type.ifcond

This is subtler than it looks on first glance.

All the other entities set self.ifcond in their constructor to the true value passed in as argument.

QAPISchemaArrayType doesn't take such an argument. Instead, it inherits its .ifcond from its .element_type. However, .element_type isn't known at construction time if it's a forward reference. We therefore delay setting it until .check() time. You do the same for .ifcond (no choice).

Before .check(), .ifcond is None, because the constructor sets it that
way: it calls QAPISchemaType.__init__() without passing a ifcond argument, which then sets self.ifcond to its default argument None.

Pitfall: accessing ent.ifcond before ent.check() works *except* when ent is an array type. Hmm.

Quoted 41 lines
scripts/qapi.py +7 -6
     def is_implicit(self):
         return True
@@ -1183,11 +1185,12 @@ class QAPISchemaArrayType(QAPISchemaType):
 
 
 class QAPISchemaObjectType(QAPISchemaType):
-    def __init__(self, name, info, doc, base, local_members, variants):
+    def __init__(self, name, info, doc, base, local_members, variants,
+                 ifcond=None):
         # struct has local_members, optional base, and no variants
         # flat union has base, variants, and no local_members
         # simple union has local_members, variants, and no base
-        QAPISchemaType.__init__(self, name, info, doc)
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         assert base is None or isinstance(base, str)
         for m in local_members:
             assert isinstance(m, QAPISchemaObjectTypeMember)
@@ -1375,8 +1378,8 @@ class QAPISchemaObjectTypeVariant(QAPISchemaObjectTypeMember):
 
 
 class QAPISchemaAlternateType(QAPISchemaType):
-    def __init__(self, name, info, doc, variants):
-        QAPISchemaType.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, variants, ifcond):
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         assert isinstance(variants, QAPISchemaObjectTypeVariants)
         assert variants.tag_member
         variants.set_owner(name)
@@ -1413,8 +1416,8 @@ class QAPISchemaAlternateType(QAPISchemaType):
 
 class QAPISchemaCommand(QAPISchemaEntity):
     def __init__(self, name, info, doc, arg_type, ret_type,
-                 gen, success_response, boxed):
-        QAPISchemaEntity.__init__(self, name, info, doc)
+                 gen, success_response, boxed, ifcond):
+        QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
         assert not arg_type or isinstance(arg_type, str)
         assert not ret_type or isinstance(ret_type, str)
         self._arg_type_name = arg_type

scripts/qapi.py class QAPISchemaCommand(QAPISchemaEntity): · line 1461

Quoted 10 lines
scripts/qapi.py +2 -2
@@ -1451,8 +1454,8 @@ class QAPISchemaCommand(QAPISchemaEntity):
 
 
 class QAPISchemaEvent(QAPISchemaEntity):
-    def __init__(self, name, info, doc, arg_type, boxed):
-        QAPISchemaEntity.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, arg_type, boxed, ifcond):
+        QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
         assert not arg_type or isinstance(arg_type, str)
         self._arg_type_name = arg_type
         self.arg_type = None

Hmm. You're adding parameter ifcond to all entity constructors. The entity constructors' signatures all look like this:

def __init__(<common parameters>, <specific parameters>)

where <common parameters> is self, name, info, doc.

Since ifcond is common, let's add it to <common parameters>. Pick a position you like.

scripts/qapi.py class QAPISchema(object): · line 1558

Quoted 12 lines
scripts/qapi.py +2 -2
@@ -1547,11 +1550,11 @@ class QAPISchema(object):
     def _make_enum_members(self, values):
         return [QAPISchemaMember(v) for v in values]
 
-    def _make_implicit_enum_type(self, name, info, values):
+    def _make_implicit_enum_type(self, name, info, values, ifcond):
         # See also QAPISchemaObjectTypeMember._pretty_owner()
         name = name + 'Kind'   # Use namespace reserved by add_name()
         self._def_entity(QAPISchemaEnumType(
-            name, info, None, self._make_enum_members(values), None))
+            name, info, None, self._make_enum_members(values), None, ifcond))
         return name

Called by _def_union_type() to create the implicit tag enum, with the same ifcond it passes to QAPISchemaObjectType(). Thus, the implicit type's ifcond matches the ifcond of its only user. Good.

Quoted 7 lines
scripts/qapi.py +0 -1
     def _make_array_type(self, element_type, info):
@@ -1560,22 +1563,29 @@ class QAPISchema(object):
             self._def_entity(QAPISchemaArrayType(name, info, element_type))
         return name
 
-    def _make_implicit_object_type(self, name, info, doc, role, members):

scripts/qapi.py class QAPISchema(object): · line 1574

Quoted 10 lines
scripts/qapi.py +5 -1
+    def _make_implicit_object_type(self, name, info, doc, role, members,
+                                   ifcond=None):
         if not members:
             return None
         # See also QAPISchemaObjectTypeMember._pretty_owner()
         name = 'q_obj_%s-%s' % (name, role)
-        if not self.lookup_entity(name, QAPISchemaObjectType):
+        typ = self.lookup_entity(name, QAPISchemaObjectType)
+        if typ:
+            # FIXME: generating the disjunction of all conditions

What are "all conditions"? I hope I can shed some light on that below.

scripts/qapi.py class QAPISchema(object): · line 1579

Quoted 6 lines
scripts/qapi.py +3 -1
+            assert ifcond == typ.ifcond
+        else:
             self._def_entity(QAPISchemaObjectType(name, info, doc, None,
-                                                  members, None))
+                                                  members, None, ifcond))
         return name

Several callers:

* _make_simple_variant() to create a wrapper type, with the wrapped type's ifcond. The wrapped type's ifcond is necessary for the wrapper type to compile. It's not sufficient for it to be needed. The "needed" condition is the disjunction of all users' ifcond.

In other words, your code generates condition that is correct, but not tight. Your FIXME is about tightening it. I'd make it a TODO, because nothing is actually broken now.

Need a comment explaining this. Perhaps:

if typ:
# The implicit object type has multiple users. This can # happen only for simple unions' implicit wrapper types. # Its ifcond should be the disjunction of its user's # ifconds. Not implemented. Instead, we always pass the # wrapped type's ifcond, which is trivially the same for all # users. It's also necessary for the wrapper to compile. # But it's not tight: the disjunction need not imply it. We # may end up compiling useless wrapper types.
# TODO kill simple unions or implement the disjunction

I hate simple unions.

* _def_union_type() to create an implicit base type, with same ifcond it passes to QAPISchemaObjectType(). Thus, the implicit base type's ifcond matches the ifcond of its only user. Good.

* _def_command() to create an implicit argument type, with the same ifcond it passes to QAPISchemaCommand(). Thus, the implicit argument type's ifcond matches the ifcond of its only user. Good.

* _def_event() likewise.

I still can't make sense of the commit message's "Shared implicit objects must share the same 'if' condition."

Quoted 26 lines
scripts/qapi.py +5 -2
     def _def_enum_type(self, expr, info, doc):
         name = expr['enum']
         data = expr['data']
         prefix = expr.get('prefix')
+        ifcond = expr.get('if')
         self._def_entity(QAPISchemaEnumType(
-            name, info, doc, self._make_enum_members(data), prefix))
+            name, info, doc, self._make_enum_members(data), prefix,
+            ifcond))
 
     def _make_member(self, name, typ, info):
         optional = False
@@ -1595,9 +1605,10 @@ class QAPISchema(object):
         name = expr['struct']
         base = expr.get('base')
         data = expr['data']
+        ifcond = expr.get('if')
         self._def_entity(QAPISchemaObjectType(name, info, doc, base,
                                               self._make_members(data, info),
-                                              None))
+                                              None, ifcond))
 
     def _make_variant(self, case, typ):
         return QAPISchemaObjectTypeVariant(case, typ)

scripts/qapi.py class QAPISchema(object): · line 1624

Quoted 9 lines
scripts/qapi.py +3 -1
@@ -1606,19 +1617,23 @@ class QAPISchema(object):
         if isinstance(typ, list):
             assert len(typ) == 1
             typ = self._make_array_type(typ[0], info)
+        type_entity = self.lookup_type(typ)
         typ = self._make_implicit_object_type(
-            typ, info, None, 'wrapper', [self._make_member('data', typ, info)])
+            typ, info, None, 'wrapper',
+            [self._make_member('data', typ, info)], type_entity.ifcond)
         return QAPISchemaObjectTypeVariant(case, typ)

This is where you create the wrapper type with the wrapped type's ifcond.

I don't like the name type_entity. I'd simply eliminate the variable.

Quoted 7 lines
scripts/qapi.py +1 -0
     def _def_union_type(self, expr, info, doc):
         name = expr['union']
         data = expr['data']
         base = expr.get('base')
+        ifcond = expr.get('if')
         tag_name = expr.get('discriminator')

scripts/qapi.py class QAPISchema(object): · line 1639

Quoted 10 lines
scripts/qapi.py +3 -2
         tag_member = None
         if isinstance(base, dict):
-            base = (self._make_implicit_object_type(
-                name, info, doc, 'base', self._make_members(base, info)))
+            base = self._make_implicit_object_type(
+                name, info, doc, 'base', self._make_members(base, info),
+                ifcond)
         if tag_name:
             variants = [self._make_variant(key, value)
                         for (key, value) in data.iteritems()]

This is where you create a union's implicit base type with the union's ifcond.

scripts/qapi.py class QAPISchema(object): · line 1648

Quoted 9 lines
scripts/qapi.py +2 -1
@@ -1627,18 +1642,21 @@ class QAPISchema(object):
             variants = [self._make_simple_variant(key, value, info)
                         for (key, value) in data.iteritems()]
             typ = self._make_implicit_enum_type(name, info,
-                                                [v.name for v in variants])
+                                                [v.name for v in variants],
+                                                ifcond)
             tag_member = QAPISchemaObjectTypeMember('type', typ, False)
             members = [tag_member]

This is where you create a union's implicit tag enum with the union's ifcond.

Quoted 26 lines
scripts/qapi.py +5 -2
         self._def_entity(
             QAPISchemaObjectType(name, info, doc, base, members,
                                  QAPISchemaObjectTypeVariants(tag_name,
                                                               tag_member,
-                                                              variants)))
+                                                              variants),
+                                 ifcond))
 
     def _def_alternate_type(self, expr, info, doc):
         name = expr['alternate']
         data = expr['data']
+        ifcond = expr.get('if')
         variants = [self._make_variant(key, value)
                     for (key, value) in data.iteritems()]
         tag_member = QAPISchemaObjectTypeMember('type', 'QType', False)
@@ -1646,7 +1664,8 @@ class QAPISchema(object):
             QAPISchemaAlternateType(name, info, doc,
                                     QAPISchemaObjectTypeVariants(None,
                                                                  tag_member,
-                                                                 variants)))
+                                                                 variants),
+                                    ifcond))
 
     def _def_command(self, expr, info, doc):
         name = expr['command']

scripts/qapi.py class QAPISchema(object): · line 1681

Quoted 9 lines
scripts/qapi.py +3 -1
@@ -1655,23 +1674,29 @@ class QAPISchema(object):
         gen = expr.get('gen', True)
         success_response = expr.get('success-response', True)
         boxed = expr.get('boxed', False)
+        ifcond = expr.get('if')
         if isinstance(data, OrderedDict):
             data = self._make_implicit_object_type(
-                name, info, doc, 'arg', self._make_members(data, info))
+                name, info, doc, 'arg', self._make_members(data, info),
+                ifcond)

This is where you create a command's implicit argument type with the command's ifcond.

Quoted 9 lines
scripts/qapi.py +2 -1
         if isinstance(rets, list):
             assert len(rets) == 1
             rets = self._make_array_type(rets[0], info)
         self._def_entity(QAPISchemaCommand(name, info, doc, data, rets,
-                                           gen, success_response, boxed))
+                                           gen, success_response, boxed,
+                                           ifcond))
 
     def _def_event(self, expr, info, doc):

scripts/qapi.py class QAPISchema(object): · line 1697

Quoted 10 lines
scripts/qapi.py +3 -2
         name = expr['event']
         data = expr.get('data')
         boxed = expr.get('boxed', False)
+        ifcond = expr.get('if')
         if isinstance(data, OrderedDict):
             data = self._make_implicit_object_type(
-                name, info, doc, 'arg', self._make_members(data, info))
-        self._def_entity(QAPISchemaEvent(name, info, doc, data, boxed))
+                name, info, doc, 'arg', self._make_members(data, info),
+                ifcond)

This is where you create an event's implicit argument type with the event's ifcond.

Quoted 5 lines
scripts/qapi.py +2 -0
+        self._def_entity(QAPISchemaEvent(name, info, doc, data, boxed,
+                                         ifcond))
 
     def _def_exprs(self):
         for expr_elem in self.exprs:
#56 lore raw

Re: [Qemu-devel] [PATCH v2 17/54] qapi: add 'if' condition on entity objects

Hi

----- Original Message -----

Quoted 6 lines
Quoted 2 lines · Marc-André Lureau

Take 'if' from expression, and use it to construct entity objects. Shared implicit objects must share the same 'if' condition.

Shared by what?

Shared by various make_implicit_object_type() users.

Quoted 123 lines
Quoted 13 lines
---
 scripts/qapi.py | 81
 +++++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 53 insertions(+), 28 deletions(-)
scripts/qapi.py +0 -0
index a94d93ada4..dc40d74abb 100644

scripts/qapi.py def check_exprs(exprs): · line 998

Quoted 8 lines
scripts/qapi.py +1 -1
@@ -992,7 +992,7 @@ def check_exprs(exprs):
 #
 
 class QAPISchemaEntity(object):
-    def __init__(self, name, info, doc):
+    def __init__(self, name, info, doc, ifcond=None):
         assert isinstance(name, str)
         self.name = name
         # For explicitly defined entities, info points to the (explicit)

Not visible here: QAPISchemaType inherits this.

Quoted 20 lines
scripts/qapi.py +3 -2
@@ -1002,6 +1002,7 @@ class QAPISchemaEntity(object):
         # such place).
         self.info = info
         self.doc = doc
+        self.ifcond = ifcond
 
     def c_name(self):
         return c_name(self.name)
@@ -1118,8 +1119,8 @@ class QAPISchemaBuiltinType(QAPISchemaType):
 
 
 class QAPISchemaEnumType(QAPISchemaType):
-    def __init__(self, name, info, doc, values, prefix):
-        QAPISchemaType.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, values, prefix, ifcond=None):
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         for v in values:
             assert isinstance(v, QAPISchemaMember)
             v.set_owner(name)

scripts/qapi.py class QAPISchemaArrayType(QAPISchemaType): · line 1166

Quoted 4 lines
scripts/qapi.py +1 -0
@@ -1162,6 +1163,7 @@ class QAPISchemaArrayType(QAPISchemaType):
     def check(self, schema):
         self.element_type = schema.lookup_type(self._element_type_name)
         assert self.element_type
+        self.ifcond = self.element_type.ifcond

This is subtler than it looks on first glance.

All the other entities set self.ifcond in their constructor to the true value passed in as argument.

QAPISchemaArrayType doesn't take such an argument. Instead, it inherits its .ifcond from its .element_type. However, .element_type isn't known at construction time if it's a forward reference. We therefore delay setting it until .check() time. You do the same for .ifcond (no choice).

Before .check(), .ifcond is None, because the constructor sets it that
way: it calls QAPISchemaType.__init__() without passing a ifcond argument, which then sets self.ifcond to its default argument None.

Pitfall: accessing ent.ifcond before ent.check() works *except* when ent is an array type. Hmm.

Quoted 42 lines
scripts/qapi.py +3 -2
     def is_implicit(self):
         return True
@@ -1183,11 +1185,12 @@ class QAPISchemaArrayType(QAPISchemaType):
 
 
 class QAPISchemaObjectType(QAPISchemaType):
-    def __init__(self, name, info, doc, base, local_members, variants):
+    def __init__(self, name, info, doc, base, local_members, variants,
+                 ifcond=None):
         # struct has local_members, optional base, and no variants
         # flat union has base, variants, and no local_members
         # simple union has local_members, variants, and no base
-        QAPISchemaType.__init__(self, name, info, doc)
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         assert base is None or isinstance(base, str)
         for m in local_members:
             assert isinstance(m, QAPISchemaObjectTypeMember)
@@ -1375,8 +1378,8 @@ class

QAPISchemaObjectTypeVariant(QAPISchemaObjectTypeMember):

class QAPISchemaAlternateType(QAPISchemaType):

scripts/qapi.py +4 -4
-    def __init__(self, name, info, doc, variants):
-        QAPISchemaType.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, variants, ifcond):
+        QAPISchemaType.__init__(self, name, info, doc, ifcond)
         assert isinstance(variants, QAPISchemaObjectTypeVariants)
         assert variants.tag_member
         variants.set_owner(name)
@@ -1413,8 +1416,8 @@ class QAPISchemaAlternateType(QAPISchemaType):
 
 class QAPISchemaCommand(QAPISchemaEntity):
     def __init__(self, name, info, doc, arg_type, ret_type,
-                 gen, success_response, boxed):
-        QAPISchemaEntity.__init__(self, name, info, doc)
+                 gen, success_response, boxed, ifcond):
+        QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
         assert not arg_type or isinstance(arg_type, str)
         assert not ret_type or isinstance(ret_type, str)
         self._arg_type_name = arg_type

scripts/qapi.py class QAPISchemaCommand(QAPISchemaEntity): · line 1461

Quoted 10 lines
scripts/qapi.py +2 -2
@@ -1451,8 +1454,8 @@ class QAPISchemaCommand(QAPISchemaEntity):
 
 
 class QAPISchemaEvent(QAPISchemaEntity):
-    def __init__(self, name, info, doc, arg_type, boxed):
-        QAPISchemaEntity.__init__(self, name, info, doc)
+    def __init__(self, name, info, doc, arg_type, boxed, ifcond):
+        QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
         assert not arg_type or isinstance(arg_type, str)
         self._arg_type_name = arg_type
         self.arg_type = None

Hmm. You're adding parameter ifcond to all entity constructors. The entity constructors' signatures all look like this:

Quoted 7 lines

def __init__(<common parameters>, <specific parameters>)

where <common parameters> is self, name, info, doc.

Since ifcond is common, let's add it to <common parameters>. Pick a position you like.

ok

Quoted 70 lines

scripts/qapi.py class QAPISchema(object): · line 1559

Quoted 13 lines
scripts/qapi.py +2 -2
@@ -1547,11 +1550,11 @@ class QAPISchema(object):
     def _make_enum_members(self, values):
         return [QAPISchemaMember(v) for v in values]
 
-    def _make_implicit_enum_type(self, name, info, values):
+    def _make_implicit_enum_type(self, name, info, values, ifcond):
         # See also QAPISchemaObjectTypeMember._pretty_owner()
         name = name + 'Kind'   # Use namespace reserved by add_name()
         self._def_entity(QAPISchemaEnumType(
-            name, info, None, self._make_enum_members(values), None))
+            name, info, None, self._make_enum_members(values), None,
 ifcond))
         return name

Called by _def_union_type() to create the implicit tag enum, with the same ifcond it passes to QAPISchemaObjectType(). Thus, the implicit type's ifcond matches the ifcond of its only user. Good.

Quoted 8 lines
scripts/qapi.py +0 -1
     def _make_array_type(self, element_type, info):
@@ -1560,22 +1563,29 @@ class QAPISchema(object):
             self._def_entity(QAPISchemaArrayType(name, info,
             element_type))
         return name
 
-    def _make_implicit_object_type(self, name, info, doc, role, members):

scripts/qapi.py class QAPISchema(object): · line 1575

Quoted 10 lines
scripts/qapi.py +5 -1
+    def _make_implicit_object_type(self, name, info, doc, role, members,
+                                   ifcond=None):
         if not members:
             return None
         # See also QAPISchemaObjectTypeMember._pretty_owner()
         name = 'q_obj_%s-%s' % (name, role)
-        if not self.lookup_entity(name, QAPISchemaObjectType):
+        typ = self.lookup_entity(name, QAPISchemaObjectType)
+        if typ:
+            # FIXME: generating the disjunction of all conditions

What are "all conditions"? I hope I can shed some light on that below.

scripts/qapi.py class QAPISchema(object): · line 1579

Quoted 6 lines
scripts/qapi.py +3 -1
+            assert ifcond == typ.ifcond
+        else:
             self._def_entity(QAPISchemaObjectType(name, info, doc, None,
-                                                  members, None))
+                                                  members, None, ifcond))
         return name

Several callers:

* _make_simple_variant() to create a wrapper type, with the wrapped type's ifcond. The wrapped type's ifcond is necessary for the wrapper type to compile. It's not sufficient for it to be needed. The "needed" condition is the disjunction of all users' ifcond.

In other words, your code generates condition that is correct, but not tight. Your FIXME is about tightening it. I'd make it a TODO, because nothing is actually broken now.

Need a comment explaining this. Perhaps:

if typ:
# The implicit object type has multiple users. This can # happen only for simple unions' implicit wrapper types. # Its ifcond should be the disjunction of its user's # ifconds. Not implemented. Instead, we always pass the # wrapped type's ifcond, which is trivially the same for all # users. It's also necessary for the wrapper to compile. # But it's not tight: the disjunction need not imply it. We # may end up compiling useless wrapper types.
# TODO kill simple unions or implement the disjunction

Quoted 1 line

I hate simple unions.

ok

Quoted 55 lines

* _def_union_type() to create an implicit base type, with same ifcond it passes to QAPISchemaObjectType(). Thus, the implicit base type's ifcond matches the ifcond of its only user. Good.

* _def_command() to create an implicit argument type, with the same ifcond it passes to QAPISchemaCommand(). Thus, the implicit argument type's ifcond matches the ifcond of its only user. Good.

* _def_event() likewise.

I still can't make sense of the commit message's "Shared implicit objects must share the same 'if' condition."

Quoted 27 lines
scripts/qapi.py +5 -2
     def _def_enum_type(self, expr, info, doc):
         name = expr['enum']
         data = expr['data']
         prefix = expr.get('prefix')
+        ifcond = expr.get('if')
         self._def_entity(QAPISchemaEnumType(
-            name, info, doc, self._make_enum_members(data), prefix))
+            name, info, doc, self._make_enum_members(data), prefix,
+            ifcond))
 
     def _make_member(self, name, typ, info):
         optional = False
@@ -1595,9 +1605,10 @@ class QAPISchema(object):
         name = expr['struct']
         base = expr.get('base')
         data = expr['data']
+        ifcond = expr.get('if')
         self._def_entity(QAPISchemaObjectType(name, info, doc, base,
                                               self._make_members(data,
                                               info),
-                                              None))
+                                              None, ifcond))
 
     def _make_variant(self, case, typ):

return QAPISchemaObjectTypeVariant(case, typ)

scripts/qapi.py class QAPISchema(object): · line 1625

Quoted 10 lines
scripts/qapi.py +3 -1
@@ -1606,19 +1617,23 @@ class QAPISchema(object):
         if isinstance(typ, list):
             assert len(typ) == 1
             typ = self._make_array_type(typ[0], info)
+        type_entity = self.lookup_type(typ)
         typ = self._make_implicit_object_type(
-            typ, info, None, 'wrapper', [self._make_member('data', typ,
 info)])
+            typ, info, None, 'wrapper',
+            [self._make_member('data', typ, info)], type_entity.ifcond)
         return QAPISchemaObjectTypeVariant(case, typ)

This is where you create the wrapper type with the wrapped type's ifcond.

Quoted 2 lines

I don't like the name type_entity. I'd simply eliminate the variable.

ok

Quoted 105 lines
Quoted 7 lines
scripts/qapi.py +1 -0
     def _def_union_type(self, expr, info, doc):
         name = expr['union']
         data = expr['data']
         base = expr.get('base')
+        ifcond = expr.get('if')
         tag_name = expr.get('discriminator')

scripts/qapi.py class QAPISchema(object): · line 1639

Quoted 10 lines
scripts/qapi.py +3 -2
         tag_member = None
         if isinstance(base, dict):
-            base = (self._make_implicit_object_type(
-                name, info, doc, 'base', self._make_members(base, info)))
+            base = self._make_implicit_object_type(
+                name, info, doc, 'base', self._make_members(base, info),
+                ifcond)
         if tag_name:
             variants = [self._make_variant(key, value)
                         for (key, value) in data.iteritems()]

This is where you create a union's implicit base type with the union's ifcond.

scripts/qapi.py class QAPISchema(object): · line 1650

Quoted 11 lines
scripts/qapi.py +2 -1
@@ -1627,18 +1642,21 @@ class QAPISchema(object):
             variants = [self._make_simple_variant(key, value, info)
                         for (key, value) in data.iteritems()]
             typ = self._make_implicit_enum_type(name, info,
-                                                [v.name for v in
 variants])
+                                                [v.name for v in
 variants],
+                                                ifcond)
             tag_member = QAPISchemaObjectTypeMember('type', typ, False)
             members = [tag_member]

This is where you create a union's implicit tag enum with the union's ifcond.

Quoted 28 lines
scripts/qapi.py +3 -1
         self._def_entity(
             QAPISchemaObjectType(name, info, doc, base, members,
                                  QAPISchemaObjectTypeVariants(tag_name,
                                                               tag_member,
-                                                              variants)))
+                                                              variants),
+                                 ifcond))
 
     def _def_alternate_type(self, expr, info, doc):
         name = expr['alternate']
         data = expr['data']
+        ifcond = expr.get('if')
         variants = [self._make_variant(key, value)

for (key, value) in data.iteritems()]
tag_member = QAPISchemaObjectTypeMember('type', 'QType', False)

scripts/qapi.py +2 -1
@@ -1646,7 +1664,8 @@ class QAPISchema(object):
             QAPISchemaAlternateType(name, info, doc,
                                     QAPISchemaObjectTypeVariants(None,
                                                                  tag_member,
-
 variants)))
+
 variants),
+                                    ifcond))
 

def _def_command(self, expr, info, doc):
name = expr['command']

scripts/qapi.py class QAPISchema(object): · line 1681

Quoted 9 lines
scripts/qapi.py +3 -1
@@ -1655,23 +1674,29 @@ class QAPISchema(object):
         gen = expr.get('gen', True)
         success_response = expr.get('success-response', True)
         boxed = expr.get('boxed', False)
+        ifcond = expr.get('if')
         if isinstance(data, OrderedDict):
             data = self._make_implicit_object_type(
-                name, info, doc, 'arg', self._make_members(data, info))
+                name, info, doc, 'arg', self._make_members(data, info),
+                ifcond)

This is where you create a command's implicit argument type with the command's ifcond.

Quoted 9 lines
scripts/qapi.py +2 -1
         if isinstance(rets, list):
             assert len(rets) == 1
             rets = self._make_array_type(rets[0], info)
         self._def_entity(QAPISchemaCommand(name, info, doc, data, rets,
-                                           gen, success_response, boxed))
+                                           gen, success_response, boxed,
+                                           ifcond))
 
     def _def_event(self, expr, info, doc):

scripts/qapi.py class QAPISchema(object): · line 1697

Quoted 10 lines
scripts/qapi.py +3 -2
         name = expr['event']
         data = expr.get('data')
         boxed = expr.get('boxed', False)
+        ifcond = expr.get('if')
         if isinstance(data, OrderedDict):
             data = self._make_implicit_object_type(
-                name, info, doc, 'arg', self._make_members(data, info))
-        self._def_entity(QAPISchemaEvent(name, info, doc, data, boxed))
+                name, info, doc, 'arg', self._make_members(data, info),
+                ifcond)

This is where you create an event's implicit argument type with the event's ifcond.

Quoted 5 lines
scripts/qapi.py +2 -0
+        self._def_entity(QAPISchemaEvent(name, info, doc, data, boxed,
+                                         ifcond))
 
     def _def_exprs(self):
         for expr_elem in self.exprs:
#57 lore raw

Re: [Qemu-devel] [PATCH v2 17/54] qapi: add 'if' condition on entity objects

Quoted 11 lines · Marc-André Lureau

Hi

----- Original Message -----

Quoted 6 lines
Quoted 2 lines · Marc-André Lureau

Take 'if' from expression, and use it to construct entity objects. Shared implicit objects must share the same 'if' condition.

Shared by what?

Shared by various make_implicit_object_type() users.

The only ones that are shared right now are simple union wrappers. For those, you pick a condition that isn't tight, but works. Now we need to work that into the commit message. Perhaps:

qapi: Pass 'if' condition into QAPISchemaEntity objects

Built-in objects remain unconditional. Explicitly defined objects use the condition specified in the schema. Implicitly defined objects inherit their condition from their users. For most of them, there is exactly one user, so the condition to use is obvious. The exception is the wrapper types generated for simple union variants, which can be shared by any number of simple unions. The tight condition would be the disjunction of the conditions of these simple unions. For now, use wrapped type's condition instead. Much simpler and good enough for now.

[...]

#58 lore raw

PATCH v2 18/54 qapi: add 'ifcond' to visitor methods

In reply to Marc-André Lureau

Modify the test visitor to check correct passing of values.

---
 scripts/qapi.py                        | 34 ++++++++++++++++++++--------------
 scripts/qapi-commands.py               |  2 +-
 scripts/qapi-event.py                  |  2 +-
 scripts/qapi-introspect.py             | 12 ++++++------
 scripts/qapi-types.py                  |  8 ++++----
 scripts/qapi-visit.py                  |  8 ++++----
 scripts/qapi2texi.py                   | 10 +++++-----
 tests/qapi-schema/qapi-schema-test.out |  9 +++++++++
 tests/qapi-schema/test-qapi.py         | 21 ++++++++++++++++-----
 9 files changed, 66 insertions(+), 40 deletions(-)
scripts/qapi.py +20 -14
index dc40d74abb..86845a28f9 100644
@@ -1031,26 +1031,26 @@ class QAPISchemaVisitor(object):
     def visit_builtin_type(self, name, info, json_type):
         pass
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         pass
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         pass
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         pass
 
-    def visit_object_type_flat(self, name, info, members, variants):
+    def visit_object_type_flat(self, name, info, members, variants, ifcond):
         pass
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         pass
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         pass
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         pass
 
 
@@ -1150,7 +1150,7 @@ class QAPISchemaEnumType(QAPISchemaType):
 
     def visit(self, visitor):
         visitor.visit_enum_type(self.name, self.info,
-                                self.member_names(), self.prefix)
+                                self.member_names(), self.prefix, self.ifcond)
 
 
 class QAPISchemaArrayType(QAPISchemaType):
@@ -1181,7 +1181,8 @@ class QAPISchemaArrayType(QAPISchemaType):
         return 'array of ' + elt_doc_type
 
     def visit(self, visitor):
-        visitor.visit_array_type(self.name, self.info, self.element_type)
+        visitor.visit_array_type(self.name, self.info, self.element_type,
+                                 self.ifcond)
 
 
 class QAPISchemaObjectType(QAPISchemaType):
@@ -1263,9 +1264,11 @@ class QAPISchemaObjectType(QAPISchemaType):
 
     def visit(self, visitor):
         visitor.visit_object_type(self.name, self.info,
-                                  self.base, self.local_members, self.variants)
+                                  self.base, self.local_members, self.variants,
+                                  self.ifcond)
         visitor.visit_object_type_flat(self.name, self.info,
-                                       self.members, self.variants)
+                                       self.members, self.variants,
+                                       self.ifcond)
 
 
 class QAPISchemaMember(object):
@@ -1408,7 +1411,8 @@ class QAPISchemaAlternateType(QAPISchemaType):
         return 'value'
 
     def visit(self, visitor):
-        visitor.visit_alternate_type(self.name, self.info, self.variants)
+        visitor.visit_alternate_type(self.name, self.info,
+                                     self.variants, self.ifcond)
 
     def is_empty(self):
         return False
@@ -1450,7 +1454,8 @@ class QAPISchemaCommand(QAPISchemaEntity):
     def visit(self, visitor):
         visitor.visit_command(self.name, self.info,
                               self.arg_type, self.ret_type,
-                              self.gen, self.success_response, self.boxed)
+                              self.gen, self.success_response, self.boxed,
+                              self.ifcond)
 
 
 class QAPISchemaEvent(QAPISchemaEntity):
@@ -1478,7 +1483,8 @@ class QAPISchemaEvent(QAPISchemaEntity):
             raise QAPISemError(self.info, "Use of 'boxed' requires 'data'")
 
     def visit(self, visitor):
-        visitor.visit_event(self.name, self.info, self.arg_type, self.boxed)
+        visitor.visit_event(self.name, self.info, self.arg_type, self.boxed,
+                            self.ifcond)
 
 
 class QAPISchema(object):
scripts/qapi-commands.py +1 -1
index 974d0a4a80..5eb96b2d95 100644
@@ -241,7 +241,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._visited_ret_types = None
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         if not gen:
             return
         self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
scripts/qapi-event.py +1 -1
index bcbef1035f..fec27fe2e1 100644
@@ -163,7 +163,7 @@ class QAPISchemaGenEventVisitor(QAPISchemaVisitor):
         self.defn += gen_enum_lookup(event_enum_name, self._event_names)
         self._event_names = None
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         self.decl += gen_event_send_decl(name, arg_type, boxed)
         self.defn += gen_event_send(name, arg_type, boxed)
         self._event_names.append(name)
scripts/qapi-introspect.py +6 -6
index 1b96926fa7..4c437d60ec 100644
@@ -142,34 +142,34 @@ const QLitObject %(c_name)s = %(c_string)s;
     def visit_builtin_type(self, name, info, json_type):
         self._gen_qlit(name, 'builtin', {'json-type': json_type})
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         self._gen_qlit(name, 'enum', {'values': values})
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         element = self._use_type(element_type)
         self._gen_qlit('[' + element + ']', 'array', {'element-type': element})
 
-    def visit_object_type_flat(self, name, info, members, variants):
+    def visit_object_type_flat(self, name, info, members, variants, ifcond):
         obj = {'members': [self._gen_member(m) for m in members]}
         if variants:
             obj.update(self._gen_variants(variants.tag_member.name,
                                           variants.variants))
         self._gen_qlit(name, 'object', obj)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         self._gen_qlit(name, 'alternate',
                        {'members': [{'type': self._use_type(m.type)}
                                     for m in variants.variants]})
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         arg_type = arg_type or self._schema.the_empty_object_type
         ret_type = ret_type or self._schema.the_empty_object_type
         self._gen_qlit(name, 'command',
                        {'arg-type': self._use_type(arg_type),
                         'ret-type': self._use_type(ret_type)})
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         arg_type = arg_type or self._schema.the_empty_object_type
         self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)})
 
scripts/qapi-types.py +4 -4
index dc05268917..6f06720adc 100644
@@ -201,7 +201,7 @@ typedef struct QEnumLookup {
         self.decl += gen_type_cleanup_decl(name)
         self.defn += gen_type_cleanup(name)
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
         if not info:
@@ -212,7 +212,7 @@ typedef struct QEnumLookup {
             self._fwdecl += gen_enum(name, values, prefix)
             self.defn += gen_enum_lookup(name, values, prefix)
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         if isinstance(element_type, QAPISchemaBuiltinType):
             self._btin += gen_fwd_object_or_array(name)
             self._btin += gen_array(name, element_type)
@@ -224,7 +224,7 @@ typedef struct QEnumLookup {
             self.decl += gen_array(name, element_type)
             self._gen_type_cleanup(name)
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         # Nothing to do for the special empty builtin
         if name == 'q_empty':
             return
@@ -238,7 +238,7 @@ typedef struct QEnumLookup {
             # implicit types won't be directly allocated/freed
             self._gen_type_cleanup(name)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         self._fwdecl += gen_fwd_object_or_array(name)
         self.decl += gen_object(name, None, [variants.tag_member], variants)
         self._gen_type_cleanup(name)
scripts/qapi-visit.py +4 -4
index 7e1cfc13f0..c29c2d869e 100644
@@ -282,7 +282,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = self._btin + self.decl
         self._btin = None
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
         if not info:
@@ -293,7 +293,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name, scalar=True)
             self.defn += gen_visit_enum(name)
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         decl = gen_visit_decl(name)
         defn = gen_visit_list(name, element_type)
         if isinstance(element_type, QAPISchemaBuiltinType):
@@ -304,7 +304,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += decl
             self.defn += defn
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         # Nothing to do for the special empty builtin
         if name == 'q_empty':
             return
@@ -317,7 +317,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name)
             self.defn += gen_visit_object(name, base, members, variants)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         self.decl += gen_visit_decl(name)
         self.defn += gen_visit_alternate(name, variants)
 
scripts/qapi2texi.py +5 -5
index 8b542f9fff..ae7920aa87 100755
@@ -207,7 +207,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
     def visit_begin(self, schema):
         self.out = ''
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
@@ -216,7 +216,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                              body=texi_entity(doc, 'Values',
                                               member_func=texi_enum_value))
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         doc = self.cur_doc
         if base and base.is_implicit():
             base = None
@@ -226,7 +226,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                              name=doc.symbol,
                              body=texi_entity(doc, 'Members', base, variants))
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
@@ -235,7 +235,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                              body=texi_entity(doc, 'Members'))
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
@@ -249,7 +249,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                             name=doc.symbol,
                             body=body)
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
tests/qapi-schema/qapi-schema-test.out +9 -0
index 7fbaea19bc..fc5fd25f1b 100644
@@ -56,18 +56,25 @@ alternate TestIfAlternate
     tag type
     case foo: int
     case bar: TestStruct
+    if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
 command TestIfCmd q_obj_TestIfCmd-arg -> None
    gen=True success_response=True boxed=False
+    if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
 enum TestIfEnum ['foo', 'bar']
+    if defined(TEST_IF_ENUM)
 event TestIfEvent q_obj_TestIfEvent-arg
    boxed=False
+    if defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)
 object TestIfStruct
     member foo: int optional=False
+    if defined(TEST_IF_STRUCT)
 object TestIfUnion
     member type: TestIfUnionKind optional=False
     tag type
     case foo: q_obj_TestStruct-wrapper
+    if defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)
 enum TestIfUnionKind ['foo']
+    if defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)
 object TestStruct
     member integer: int optional=False
     member boolean: bool optional=False
@@ -190,8 +197,10 @@ object q_obj_EVENT_D-arg
     member enum3: EnumOne optional=True
 object q_obj_TestIfCmd-arg
     member foo: TestIfStruct optional=False
+    if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
 object q_obj_TestIfEvent-arg
     member foo: TestIfStruct optional=False
+    if defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)
 object q_obj_TestStruct-wrapper
     member data: TestStruct optional=False
 object q_obj_UserDefFlatUnion2-base
tests/qapi-schema/test-qapi.py +16 -5
index c7724d3437..17fd975812 100644
@@ -17,12 +17,13 @@ import sys
 
 
 class QAPISchemaTestVisitor(QAPISchemaVisitor):
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         print 'enum %s %s' % (name, values)
         if prefix:
             print '    prefix %s' % prefix
+        self._print_if(ifcond)
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         print 'object %s' % name
         if base:
             print '    base %s' % base.name
@@ -30,21 +31,25 @@ class QAPISchemaTestVisitor(QAPISchemaVisitor):
             print '    member %s: %s optional=%s' % \
                 (m.name, m.type.name, m.optional)
         self._print_variants(variants)
+        self._print_if(ifcond)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         print 'alternate %s' % name
         self._print_variants(variants)
+        self._print_if(ifcond)
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         print 'command %s %s -> %s' % \
             (name, arg_type and arg_type.name, ret_type and ret_type.name)
         print '   gen=%s success_response=%s boxed=%s' % \
             (gen, success_response, boxed)
+        self._print_if(ifcond)
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         print 'event %s %s' % (name, arg_type and arg_type.name)
         print '   boxed=%s' % boxed
+        self._print_if(ifcond)
 
     @staticmethod
     def _print_variants(variants):
@@ -53,6 +58,12 @@ class QAPISchemaTestVisitor(QAPISchemaVisitor):
             for v in variants.variants:
                 print '    case %s: %s' % (v.name, v.type.name)
 
+    @staticmethod
+    def _print_if(ifcond):
+        if ifcond:
+            print '    if %s' % ifcond
+
+
 schema = QAPISchema(sys.argv[1])
 schema.visit(QAPISchemaTestVisitor())
 
Signature · 1 line
2.14.1.146.gd35faa819
#59 lore raw

Re: [Qemu-devel] [PATCH v2 18/54] qapi: add 'ifcond' to visitor methods

Quoted 43 lines · Marc-André Lureau

Modify the test visitor to check correct passing of values.

---
 scripts/qapi.py                        | 34 ++++++++++++++++++++--------------
 scripts/qapi-commands.py               |  2 +-
 scripts/qapi-event.py                  |  2 +-
 scripts/qapi-introspect.py             | 12 ++++++------
 scripts/qapi-types.py                  |  8 ++++----
 scripts/qapi-visit.py                  |  8 ++++----
 scripts/qapi2texi.py                   | 10 +++++-----
 tests/qapi-schema/qapi-schema-test.out |  9 +++++++++
 tests/qapi-schema/test-qapi.py         | 21 ++++++++++++++++-----
 9 files changed, 66 insertions(+), 40 deletions(-)
scripts/qapi.py +5 -5
index dc40d74abb..86845a28f9 100644
@@ -1031,26 +1031,26 @@ class QAPISchemaVisitor(object):
     def visit_builtin_type(self, name, info, json_type):
         pass
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         pass
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         pass
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         pass
 
-    def visit_object_type_flat(self, name, info, members, variants):
+    def visit_object_type_flat(self, name, info, members, variants, ifcond):
         pass
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         pass
 

scripts/qapi.py class QAPISchemaVisitor(object): · line 1056

Quoted 10 lines
scripts/qapi.py +2 -2
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         pass
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         pass
 
 

Let's add the new common parameter ifcond among the existing common parameters self, name, info. Preferably in the same position as in entity constructors.

Quoted 294 lines
scripts/qapi.py +13 -7
@@ -1150,7 +1150,7 @@ class QAPISchemaEnumType(QAPISchemaType):
 
     def visit(self, visitor):
         visitor.visit_enum_type(self.name, self.info,
-                                self.member_names(), self.prefix)
+                                self.member_names(), self.prefix, self.ifcond)
 
 
 class QAPISchemaArrayType(QAPISchemaType):
@@ -1181,7 +1181,8 @@ class QAPISchemaArrayType(QAPISchemaType):
         return 'array of ' + elt_doc_type
 
     def visit(self, visitor):
-        visitor.visit_array_type(self.name, self.info, self.element_type)
+        visitor.visit_array_type(self.name, self.info, self.element_type,
+                                 self.ifcond)
 
 
 class QAPISchemaObjectType(QAPISchemaType):
@@ -1263,9 +1264,11 @@ class QAPISchemaObjectType(QAPISchemaType):
 
     def visit(self, visitor):
         visitor.visit_object_type(self.name, self.info,
-                                  self.base, self.local_members, self.variants)
+                                  self.base, self.local_members, self.variants,
+                                  self.ifcond)
         visitor.visit_object_type_flat(self.name, self.info,
-                                       self.members, self.variants)
+                                       self.members, self.variants,
+                                       self.ifcond)
 
 
 class QAPISchemaMember(object):
@@ -1408,7 +1411,8 @@ class QAPISchemaAlternateType(QAPISchemaType):
         return 'value'
 
     def visit(self, visitor):
-        visitor.visit_alternate_type(self.name, self.info, self.variants)
+        visitor.visit_alternate_type(self.name, self.info,
+                                     self.variants, self.ifcond)
 
     def is_empty(self):
         return False
@@ -1450,7 +1454,8 @@ class QAPISchemaCommand(QAPISchemaEntity):
     def visit(self, visitor):
         visitor.visit_command(self.name, self.info,
                               self.arg_type, self.ret_type,
-                              self.gen, self.success_response, self.boxed)
+                              self.gen, self.success_response, self.boxed,
+                              self.ifcond)
 
 
 class QAPISchemaEvent(QAPISchemaEntity):
@@ -1478,7 +1483,8 @@ class QAPISchemaEvent(QAPISchemaEntity):
             raise QAPISemError(self.info, "Use of 'boxed' requires 'data'")
 
     def visit(self, visitor):
-        visitor.visit_event(self.name, self.info, self.arg_type, self.boxed)
+        visitor.visit_event(self.name, self.info, self.arg_type, self.boxed,
+                            self.ifcond)
 
 
 class QAPISchema(object):
scripts/qapi-commands.py +1 -1
index 974d0a4a80..5eb96b2d95 100644
@@ -241,7 +241,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._visited_ret_types = None
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         if not gen:
             return
         self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
scripts/qapi-event.py +1 -1
index bcbef1035f..fec27fe2e1 100644
@@ -163,7 +163,7 @@ class QAPISchemaGenEventVisitor(QAPISchemaVisitor):
         self.defn += gen_enum_lookup(event_enum_name, self._event_names)
         self._event_names = None
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         self.decl += gen_event_send_decl(name, arg_type, boxed)
         self.defn += gen_event_send(name, arg_type, boxed)
         self._event_names.append(name)
scripts/qapi-introspect.py +6 -6
index 1b96926fa7..4c437d60ec 100644
@@ -142,34 +142,34 @@ const QLitObject %(c_name)s = %(c_string)s;
     def visit_builtin_type(self, name, info, json_type):
         self._gen_qlit(name, 'builtin', {'json-type': json_type})
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         self._gen_qlit(name, 'enum', {'values': values})
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         element = self._use_type(element_type)
         self._gen_qlit('[' + element + ']', 'array', {'element-type': element})
 
-    def visit_object_type_flat(self, name, info, members, variants):
+    def visit_object_type_flat(self, name, info, members, variants, ifcond):
         obj = {'members': [self._gen_member(m) for m in members]}
         if variants:
             obj.update(self._gen_variants(variants.tag_member.name,
                                           variants.variants))
         self._gen_qlit(name, 'object', obj)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         self._gen_qlit(name, 'alternate',
                        {'members': [{'type': self._use_type(m.type)}
                                     for m in variants.variants]})
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         arg_type = arg_type or self._schema.the_empty_object_type
         ret_type = ret_type or self._schema.the_empty_object_type
         self._gen_qlit(name, 'command',
                        {'arg-type': self._use_type(arg_type),
                         'ret-type': self._use_type(ret_type)})
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         arg_type = arg_type or self._schema.the_empty_object_type
         self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)})
 
scripts/qapi-types.py +4 -4
index dc05268917..6f06720adc 100644
@@ -201,7 +201,7 @@ typedef struct QEnumLookup {
         self.decl += gen_type_cleanup_decl(name)
         self.defn += gen_type_cleanup(name)
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
         if not info:
@@ -212,7 +212,7 @@ typedef struct QEnumLookup {
             self._fwdecl += gen_enum(name, values, prefix)
             self.defn += gen_enum_lookup(name, values, prefix)
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         if isinstance(element_type, QAPISchemaBuiltinType):
             self._btin += gen_fwd_object_or_array(name)
             self._btin += gen_array(name, element_type)
@@ -224,7 +224,7 @@ typedef struct QEnumLookup {
             self.decl += gen_array(name, element_type)
             self._gen_type_cleanup(name)
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         # Nothing to do for the special empty builtin
         if name == 'q_empty':
             return
@@ -238,7 +238,7 @@ typedef struct QEnumLookup {
             # implicit types won't be directly allocated/freed
             self._gen_type_cleanup(name)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         self._fwdecl += gen_fwd_object_or_array(name)
         self.decl += gen_object(name, None, [variants.tag_member], variants)
         self._gen_type_cleanup(name)
scripts/qapi-visit.py +4 -4
index 7e1cfc13f0..c29c2d869e 100644
@@ -282,7 +282,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = self._btin + self.decl
         self._btin = None
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
         if not info:
@@ -293,7 +293,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name, scalar=True)
             self.defn += gen_visit_enum(name)
 
-    def visit_array_type(self, name, info, element_type):
+    def visit_array_type(self, name, info, element_type, ifcond):
         decl = gen_visit_decl(name)
         defn = gen_visit_list(name, element_type)
         if isinstance(element_type, QAPISchemaBuiltinType):
@@ -304,7 +304,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += decl
             self.defn += defn
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         # Nothing to do for the special empty builtin
         if name == 'q_empty':
             return
@@ -317,7 +317,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name)
             self.defn += gen_visit_object(name, base, members, variants)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         self.decl += gen_visit_decl(name)
         self.defn += gen_visit_alternate(name, variants)
 
scripts/qapi2texi.py +5 -5
index 8b542f9fff..ae7920aa87 100755
@@ -207,7 +207,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
     def visit_begin(self, schema):
         self.out = ''
 
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
@@ -216,7 +216,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                              body=texi_entity(doc, 'Values',
                                               member_func=texi_enum_value))
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         doc = self.cur_doc
         if base and base.is_implicit():
             base = None
@@ -226,7 +226,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                              name=doc.symbol,
                              body=texi_entity(doc, 'Members', base, variants))
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
@@ -235,7 +235,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                              body=texi_entity(doc, 'Members'))
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
@@ -249,7 +249,7 @@ class QAPISchemaGenDocVisitor(qapi.QAPISchemaVisitor):
                             name=doc.symbol,
                             body=body)
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         doc = self.cur_doc
         if self.out:
             self.out += '\n'
tests/qapi-schema/qapi-schema-test.out +7 -0
index 7fbaea19bc..fc5fd25f1b 100644
@@ -56,18 +56,25 @@ alternate TestIfAlternate
     tag type
     case foo: int
     case bar: TestStruct
+    if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
 command TestIfCmd q_obj_TestIfCmd-arg -> None
    gen=True success_response=True boxed=False
+    if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
 enum TestIfEnum ['foo', 'bar']
+    if defined(TEST_IF_ENUM)
 event TestIfEvent q_obj_TestIfEvent-arg
    boxed=False
+    if defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)
 object TestIfStruct
     member foo: int optional=False
+    if defined(TEST_IF_STRUCT)
 object TestIfUnion
     member type: TestIfUnionKind optional=False
     tag type
     case foo: q_obj_TestStruct-wrapper
+    if defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)
 enum TestIfUnionKind ['foo']
+    if defined(TEST_IF_UNION) && defined(TEST_IF_STRUCT)
 object TestStruct
     member integer: int optional=False
     member boolean: bool optional=False

tests/qapi-schema/qapi-schema-test.out object q_obj_EVENT_D-arg · line 206

Quoted 10 lines
tests/qapi-schema/qapi-schema-test.out +2 -0
@@ -190,8 +197,10 @@ object q_obj_EVENT_D-arg
     member enum3: EnumOne optional=True
 object q_obj_TestIfCmd-arg
     member foo: TestIfStruct optional=False
+    if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
 object q_obj_TestIfEvent-arg
     member foo: TestIfStruct optional=False
+    if defined(TEST_IF_EVT) && defined(TEST_IF_STRUCT)
 object q_obj_TestStruct-wrapper
     member data: TestStruct optional=False
 object q_obj_UserDefFlatUnion2-base

Ah, now the ifcond become visible! Announcing that in PATCH 15 would've avoided me asking for it :)

Quoted 61 lines
tests/qapi-schema/test-qapi.py +16 -5
index c7724d3437..17fd975812 100644
@@ -17,12 +17,13 @@ import sys
 
 
 class QAPISchemaTestVisitor(QAPISchemaVisitor):
-    def visit_enum_type(self, name, info, values, prefix):
+    def visit_enum_type(self, name, info, values, prefix, ifcond):
         print 'enum %s %s' % (name, values)
         if prefix:
             print '    prefix %s' % prefix
+        self._print_if(ifcond)
 
-    def visit_object_type(self, name, info, base, members, variants):
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
         print 'object %s' % name
         if base:
             print '    base %s' % base.name
@@ -30,21 +31,25 @@ class QAPISchemaTestVisitor(QAPISchemaVisitor):
             print '    member %s: %s optional=%s' % \
                 (m.name, m.type.name, m.optional)
         self._print_variants(variants)
+        self._print_if(ifcond)
 
-    def visit_alternate_type(self, name, info, variants):
+    def visit_alternate_type(self, name, info, variants, ifcond):
         print 'alternate %s' % name
         self._print_variants(variants)
+        self._print_if(ifcond)
 
     def visit_command(self, name, info, arg_type, ret_type,
-                      gen, success_response, boxed):
+                      gen, success_response, boxed, ifcond):
         print 'command %s %s -> %s' % \
             (name, arg_type and arg_type.name, ret_type and ret_type.name)
         print '   gen=%s success_response=%s boxed=%s' % \
             (gen, success_response, boxed)
+        self._print_if(ifcond)
 
-    def visit_event(self, name, info, arg_type, boxed):
+    def visit_event(self, name, info, arg_type, boxed, ifcond):
         print 'event %s %s' % (name, arg_type and arg_type.name)
         print '   boxed=%s' % boxed
+        self._print_if(ifcond)
 
     @staticmethod
     def _print_variants(variants):
@@ -53,6 +58,12 @@ class QAPISchemaTestVisitor(QAPISchemaVisitor):
             for v in variants.variants:
                 print '    case %s: %s' % (v.name, v.type.name)
 
+    @staticmethod
+    def _print_if(ifcond):
+        if ifcond:
+            print '    if %s' % ifcond
+
+
 schema = QAPISchema(sys.argv[1])
 schema.visit(QAPISchemaTestVisitor())
#60 lore raw

PATCH v2 19/54 qapi: add #if/#endif helpers

In reply to Marc-André Lureau

Add helpers to generate #if/#endif and wrap visitor methods generating code. Used in the following patches.

---
 scripts/qapi.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
scripts/qapi.py +51 -0
index 86845a28f9..52099332f1 100644
@@ -1892,6 +1892,57 @@ def guardend(name):
                  name=guardname(name))
 
 
+def gen_if(ifcond):
+    if not ifcond:
+        return ''
+    if isinstance(ifcond, str):
+        ifcond = [ifcond]
+    # Not using mcgen() because we don't want indent or \n stipped
+    ret = '\n'
+    for ifc in ifcond:
+        ret += '#if %s\n' % ifc
+    ret += '\n'
+    return ret
+
+
+def gen_endif(ifcond):
+    if not ifcond:
+        return ''
+    if isinstance(ifcond, str):
+        ifcond = [ifcond]
+    # Not using mcgen() because we don't want indent or \n stipped
+    ret = '\n'
+    for ifc in reversed(ifcond):
+        ret += '#endif /* %s */\n' % ifc
+    ret += '\n'
+    return ret
+
+
+# Wrap a method to add #if / #endif to generated code, only if some
+# code was generated.
+# self must have 'if_members' listing the attributes to wrap.
+# The last argument of the wrapped function must be the 'ifcond'.
+def ifcond_decorator(func):
+
+    def func_wrapper(self, *args, **kwargs):
+        ifcond = args[-1]
+        save = {}
+        for mem in self.if_members:
+            save[mem] = getattr(self, mem)
+        func(self, *args, **kwargs)
+        for mem, val in save.items():
+            newval = getattr(self, mem)
+            if newval != val:
+                assert newval.startswith(val)
+                newval = newval[len(val):]
+                val += gen_if(ifcond)
+                val += newval
+                val += gen_endif(ifcond)
+            setattr(self, mem, val)
+
+    return func_wrapper
+
+
 def gen_enum_lookup(name, values, prefix=None):
     ret = mcgen('''
 
Signature · 1 line
2.14.1.146.gd35faa819
#61 lore raw

Re: [Qemu-devel] [PATCH v2 19/54] qapi: add #if/#endif helpers

Quoted 13 lines · Marc-André Lureau

Add helpers to generate #if/#endif and wrap visitor methods generating code. Used in the following patches.

---
 scripts/qapi.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
scripts/qapi.py +0 -0
index 86845a28f9..52099332f1 100644

scripts/qapi.py def guardend(name): · line 1900

Quoted 9 lines
scripts/qapi.py +6 -0
@@ -1892,6 +1892,57 @@ def guardend(name):
                  name=guardname(name))
 
 
+def gen_if(ifcond):
+    if not ifcond:
+        return ''
+    if isinstance(ifcond, str):
+        ifcond = [ifcond]
+    # Not using mcgen() because we don't want indent or \n stipped

s/stipped/stripped/ I guess.

Which newline exactly don't you want to strip?

Here's what mcgen() currently does:

* Strip one leading newline, so that this works:

      mcgen('''

line 1
line 2
''')

* Interpolate keywords

* Indent by @indent_level spaces

* Strip @eatspace.

scripts/qapi.py def guardend(name): · line 1913

Quoted 13 lines
scripts/qapi.py +13 -0
+    ret = '\n'
+    for ifc in ifcond:
+        ret += '#if %s\n' % ifc
+    ret += '\n'
+    return ret
+
+
+def gen_endif(ifcond):
+    if not ifcond:
+        return ''
+    if isinstance(ifcond, str):
+        ifcond = [ifcond]
+    # Not using mcgen() because we don't want indent or \n stipped

Likewise.

scripts/qapi.py def guardend(name): · line 1918

Quoted 5 lines
scripts/qapi.py +5 -0
+    ret = '\n'
+    for ifc in reversed(ifcond):
+        ret += '#endif /* %s */\n' % ifc
+    ret += '\n'
+    return ret

I guess factoring out the common parts of gen_if() and gen_endif() would make the code longer and more complex.

Quoted 19 lines
scripts/qapi.py +19 -0
+
+
+# Wrap a method to add #if / #endif to generated code, only if some
+# code was generated.
+# self must have 'if_members' listing the attributes to wrap.
+# The last argument of the wrapped function must be the 'ifcond'.
+def ifcond_decorator(func):
+
+    def func_wrapper(self, *args, **kwargs):
+        ifcond = args[-1]
+        save = {}
+        for mem in self.if_members:
+            save[mem] = getattr(self, mem)
+        func(self, *args, **kwargs)
+        for mem, val in save.items():
+            newval = getattr(self, mem)
+            if newval != val:
+                assert newval.startswith(val)
+                newval = newval[len(val):]

scripts/qapi.py def guardend(name): · line 1947

Quoted 10 lines
scripts/qapi.py +8 -0
+                val += gen_if(ifcond)
+                val += newval
+                val += gen_endif(ifcond)
+            setattr(self, mem, val)
+
+    return func_wrapper
+
+
 def gen_enum_lookup(name, values, prefix=None):
     ret = mcgen('''

My gut feeling is "too clever by half", but i'm reserving judgement until after review of its use.

#62 lore raw

Re: [Qemu-devel] [PATCH v2 19/54] qapi: add #if/#endif helpers

Quoted 27 lines · Markus Armbruster
Quoted 13 lines · Marc-André Lureau

Add helpers to generate #if/#endif and wrap visitor methods generating code. Used in the following patches.

---
 scripts/qapi.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
scripts/qapi.py +0 -0
index 86845a28f9..52099332f1 100644

scripts/qapi.py def guardend(name): · line 1900

Quoted 9 lines
scripts/qapi.py +6 -0
@@ -1892,6 +1892,57 @@ def guardend(name):
                  name=guardname(name))
 
 
+def gen_if(ifcond):
+    if not ifcond:
+        return ''
+    if isinstance(ifcond, str):
+        ifcond = [ifcond]
+    # Not using mcgen() because we don't want indent or \n stipped

s/stipped/stripped/ I guess.

Quoted 1 line

Which newline exactly don't you want to strip?

My first attempt at using mcgen() was a fail.

Quoted 10 lines

Here's what mcgen() currently does:

* Strip one leading newline, so that this works:

      mcgen('''

line 1
line 2
''')

Quoted 6 lines

* Interpolate keywords

* Indent by @indent_level spaces

* Strip @eatspace.

So we don't need much from mcgen(), especailly, we don't want indent on preprocessor lines. I have added a patch to fix that. And now, I switch to mcgen() for more consistency.

Quoted 49 lines

scripts/qapi.py def guardend(name): · line 1913

Quoted 13 lines
scripts/qapi.py +13 -0
+    ret = '\n'
+    for ifc in ifcond:
+        ret += '#if %s\n' % ifc
+    ret += '\n'
+    return ret
+
+
+def gen_endif(ifcond):
+    if not ifcond:
+        return ''
+    if isinstance(ifcond, str):
+        ifcond = [ifcond]
+    # Not using mcgen() because we don't want indent or \n stipped

Likewise.

scripts/qapi.py def guardend(name): · line 1918

Quoted 5 lines
scripts/qapi.py +5 -0
+    ret = '\n'
+    for ifc in reversed(ifcond):
+        ret += '#endif /* %s */\n' % ifc
+    ret += '\n'
+    return ret

I guess factoring out the common parts of gen_if() and gen_endif() would make the code longer and more complex.

Quoted 24 lines
scripts/qapi.py +24 -0
+
+
+# Wrap a method to add #if / #endif to generated code, only if some
+# code was generated.
+# self must have 'if_members' listing the attributes to wrap.
+# The last argument of the wrapped function must be the 'ifcond'.
+def ifcond_decorator(func):
+
+    def func_wrapper(self, *args, **kwargs):
+        ifcond = args[-1]
+        save = {}
+        for mem in self.if_members:
+            save[mem] = getattr(self, mem)
+        func(self, *args, **kwargs)
+        for mem, val in save.items():
+            newval = getattr(self, mem)
+            if newval != val:
+                assert newval.startswith(val)
+                newval = newval[len(val):]
+                val += gen_if(ifcond)
+                val += newval
+                val += gen_endif(ifcond)
+            setattr(self, mem, val)
+
Quoted 9 lines

scripts/qapi.py def guardend(name): · line 1947

Quoted 5 lines
scripts/qapi.py +3 -0
+    return func_wrapper
+
+
 def gen_enum_lookup(name, values, prefix=None):
     ret = mcgen('''

My gut feeling is "too clever by half", but i'm reserving judgement until after review of its use.

Well easy to change later on too, I'd not focus on this for now.

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

PATCH v2 20/54 qapi-introspect: modify to_qlit() to take an optional suffix

In reply to Marc-André Lureau

The following patch is going to break list entries with #if/#endif, so they should have the trailing ',' as suffix.

---
 scripts/qapi-introspect.py | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
scripts/qapi-introspect.py +4 -4
index 4c437d60ec..dfb6d2ded4 100644
@@ -16,7 +16,7 @@ def to_c_string(s):
     return '"' + s.replace('\\', r'\\').replace('"', r'\"') + '"'
 
 
-def to_qlit(obj, level=0, first_indent=True):
+def to_qlit(obj, level=0, first_indent=True, suffix=''):
 
     def indent(level):
         return level * 4 * ' '
@@ -29,11 +29,11 @@ def to_qlit(obj, level=0, first_indent=True):
     elif isinstance(obj, str):
         ret += 'QLIT_QSTR(' + to_c_string(obj) + ')'
     elif isinstance(obj, list):
-        elts = [to_qlit(elt, level + 1)
+        elts = [to_qlit(elt, level + 1, suffix=',')
                 for elt in obj]
         elts.append(indent(level + 1) + "{}")
         ret += 'QLIT_QLIST(((QLitObject[]) {\n'
-        ret += ',\n'.join(elts) + '\n'
+        ret += '\n'.join(elts) + '\n'
         ret += indent(level) + '}))'
     elif isinstance(obj, dict):
         elts = []
@@ -46,7 +46,7 @@ def to_qlit(obj, level=0, first_indent=True):
         ret += indent(level) + '}))'
     else:
         assert False                # not implemented
-    return ret
+    return ret + suffix
 
 
 class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
Signature · 1 line
2.14.1.146.gd35faa819
#64 lore raw

Re: [Qemu-devel] [PATCH v2 20/54] qapi-introspect: modify to_qlit() to take an optional suffix

Quoted 36 lines · Marc-André Lureau

The following patch is going to break list entries with #if/#endif, so they should have the trailing ',' as suffix.

---
 scripts/qapi-introspect.py | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
scripts/qapi-introspect.py +3 -3
index 4c437d60ec..dfb6d2ded4 100644
@@ -16,7 +16,7 @@ def to_c_string(s):
     return '"' + s.replace('\\', r'\\').replace('"', r'\"') + '"'
 
 
-def to_qlit(obj, level=0, first_indent=True):
+def to_qlit(obj, level=0, first_indent=True, suffix=''):
 
     def indent(level):
         return level * 4 * ' '
@@ -29,11 +29,11 @@ def to_qlit(obj, level=0, first_indent=True):
     elif isinstance(obj, str):
         ret += 'QLIT_QSTR(' + to_c_string(obj) + ')'
     elif isinstance(obj, list):
-        elts = [to_qlit(elt, level + 1)
+        elts = [to_qlit(elt, level + 1, suffix=',')
                 for elt in obj]
         elts.append(indent(level + 1) + "{}")
         ret += 'QLIT_QLIST(((QLitObject[]) {\n'
-        ret += ',\n'.join(elts) + '\n'
+        ret += '\n'.join(elts) + '\n'
         ret += indent(level) + '}))'
     elif isinstance(obj, dict):
         elts = []

scripts/qapi-introspect.py def to_qlit(obj, level=0, first_indent=True): · line 52

Quoted 8 lines
scripts/qapi-introspect.py +1 -1
@@ -46,7 +46,7 @@ def to_qlit(obj, level=0, first_indent=True):
         ret += indent(level) + '}))'
     else:
         assert False                # not implemented
-    return ret
+    return ret + suffix
 
 
 class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):

Hmm. I wonder the appended simpler patch would do.

scripts/qapi-introspect.py +3 -1
index 4c437d60ec..73edb55cd5 100644
@@ -33,7 +33,7 @@ def to_qlit(obj, level=0, first_indent=True):
                 for elt in obj]
         elts.append(indent(level + 1) + "{}")
         ret += 'QLIT_QLIST(((QLitObject[]) {\n'
-        ret += ',\n'.join(elts) + '\n'
+        ret += '\n'.join(elts) + '\n'
         ret += indent(level) + '}))'
     elif isinstance(obj, dict):
         elts = []
@@ -46,6 +46,8 @@ def to_qlit(obj, level=0, first_indent=True):
         ret += indent(level) + '}))'
     else:
         assert False                # not implemented
+    if level > 0:
+        ret += ','
     return ret
 
 
#65 lore raw

Re: [Qemu-devel] [PATCH v2 20/54] qapi-introspect: modify to_qlit() to take an optional suffix

Quoted 45 lines · Markus Armbruster
Quoted 43 lines · Marc-André Lureau

The following patch is going to break list entries with #if/#endif, so they should have the trailing ',' as suffix.

---
 scripts/qapi-introspect.py | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
scripts/qapi-introspect.py +4 -4
index 4c437d60ec..dfb6d2ded4 100644
@@ -16,7 +16,7 @@ def to_c_string(s):
     return '"' + s.replace('\\', r'\\').replace('"', r'\"') + '"'
 
 
-def to_qlit(obj, level=0, first_indent=True):
+def to_qlit(obj, level=0, first_indent=True, suffix=''):
 
     def indent(level):
         return level * 4 * ' '
@@ -29,11 +29,11 @@ def to_qlit(obj, level=0, first_indent=True):
     elif isinstance(obj, str):
         ret += 'QLIT_QSTR(' + to_c_string(obj) + ')'
     elif isinstance(obj, list):
-        elts = [to_qlit(elt, level + 1)
+        elts = [to_qlit(elt, level + 1, suffix=',')
                 for elt in obj]
         elts.append(indent(level + 1) + "{}")
         ret += 'QLIT_QLIST(((QLitObject[]) {\n'
-        ret += ',\n'.join(elts) + '\n'
+        ret += '\n'.join(elts) + '\n'
         ret += indent(level) + '}))'
     elif isinstance(obj, dict):
         elts = []
@@ -46,7 +46,7 @@ def to_qlit(obj, level=0, first_indent=True):
         ret += indent(level) + '}))'
     else:
         assert False                # not implemented
-    return ret
+    return ret + suffix
 
 
Quoted 3 lines

scripts/qapi-introspect.py def to_qlit(obj, level=0, first_indent=True): · line 52

Quoted 1 line
scripts/qapi-introspect.py +0 -0
 class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):

Hmm. I wonder the appended simpler patch would do.

It works, thanks for the suggestion

Quoted 24 lines
scripts/qapi-introspect.py +3 -1
index 4c437d60ec..73edb55cd5 100644
@@ -33,7 +33,7 @@ def to_qlit(obj, level=0, first_indent=True):
                 for elt in obj]
         elts.append(indent(level + 1) + "{}")
         ret += 'QLIT_QLIST(((QLitObject[]) {\n'
-        ret += ',\n'.join(elts) + '\n'
+        ret += '\n'.join(elts) + '\n'
         ret += indent(level) + '}))'
     elif isinstance(obj, dict):
         elts = []
@@ -46,6 +46,8 @@ def to_qlit(obj, level=0, first_indent=True):
         ret += indent(level) + '}))'
     else:
         assert False                # not implemented
+    if level > 0:
+        ret += ','
     return ret
 
 
Signature · 1 line
Marc-André Lureau
#66 lore raw

PATCH v2 21/54 qapi-introspect: modify to_qlit() to generate #if code

In reply to Marc-André Lureau

The generator now accepts (obj, condition) tuples to wrap generated QLit objects with #if/#endif conditions.

---
 scripts/qapi-introspect.py | 6 ++++++
 1 file changed, 6 insertions(+)
scripts/qapi-introspect.py +6 -0
index dfb6d2ded4..9ef6f271d4 100644
@@ -26,6 +26,12 @@ def to_qlit(obj, level=0, first_indent=True, suffix=''):
         ret += indent(level)
     if obj is None:
         ret += 'QLIT_QNULL'
+    elif isinstance(obj, tuple):
+        obj, ifcond = obj
+        ret += gen_if(ifcond)
+        ret += to_qlit(obj, level, first_indent=False) + suffix
+        ret += gen_endif(ifcond)
+        suffix = ''
     elif isinstance(obj, str):
         ret += 'QLIT_QSTR(' + to_c_string(obj) + ')'
     elif isinstance(obj, list):
Signature · 1 line
2.14.1.146.gd35faa819
#67 lore raw

PATCH v2 22/54 qapi-introspect: add preprocessor conditions to generated QLit

In reply to Marc-André Lureau

Add 'ifcond' condition to QLit objects.

to_qlit() handles the (obj, ifcond) tuples.

---
 scripts/qapi-introspect.py | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
scripts/qapi-introspect.py +11 -9
index 9ef6f271d4..5e736a06df 100644
@@ -125,12 +125,12 @@ const QLitObject %(c_name)s = %(c_string)s;
             return '[' + self._use_type(typ.element_type) + ']'
         return self._name(typ.name)
 
-    def _gen_qlit(self, name, mtype, obj):
+    def _gen_qlit(self, name, mtype, obj, ifcond):
         if mtype not in ('command', 'event', 'builtin', 'array'):
             name = self._name(name)
         obj['name'] = name
         obj['meta-type'] = mtype
-        self._qlits.append(obj)
+        self._qlits.append((obj, ifcond))
 
     def _gen_member(self, member):
         ret = {'name': member.name, 'type': self._use_type(member.type)}
@@ -146,26 +146,27 @@ const QLitObject %(c_name)s = %(c_string)s;
         return {'case': variant.name, 'type': self._use_type(variant.type)}
 
     def visit_builtin_type(self, name, info, json_type):
-        self._gen_qlit(name, 'builtin', {'json-type': json_type})
+        self._gen_qlit(name, 'builtin', {'json-type': json_type}, None)
 
     def visit_enum_type(self, name, info, values, prefix, ifcond):
-        self._gen_qlit(name, 'enum', {'values': values})
+        self._gen_qlit(name, 'enum', {'values': values}, ifcond)
 
     def visit_array_type(self, name, info, element_type, ifcond):
         element = self._use_type(element_type)
-        self._gen_qlit('[' + element + ']', 'array', {'element-type': element})
+        self._gen_qlit('[' + element + ']', 'array', {'element-type': element},
+                       ifcond)
 
     def visit_object_type_flat(self, name, info, members, variants, ifcond):
         obj = {'members': [self._gen_member(m) for m in members]}
         if variants:
             obj.update(self._gen_variants(variants.tag_member.name,
                                           variants.variants))
-        self._gen_qlit(name, 'object', obj)
+        self._gen_qlit(name, 'object', obj, ifcond)
 
     def visit_alternate_type(self, name, info, variants, ifcond):
         self._gen_qlit(name, 'alternate',
                        {'members': [{'type': self._use_type(m.type)}
-                                    for m in variants.variants]})
+                                    for m in variants.variants]}, ifcond)
 
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
@@ -173,11 +174,12 @@ const QLitObject %(c_name)s = %(c_string)s;
         ret_type = ret_type or self._schema.the_empty_object_type
         self._gen_qlit(name, 'command',
                        {'arg-type': self._use_type(arg_type),
-                        'ret-type': self._use_type(ret_type)})
+                        'ret-type': self._use_type(ret_type)}, ifcond)
 
     def visit_event(self, name, info, arg_type, boxed, ifcond):
         arg_type = arg_type or self._schema.the_empty_object_type
-        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)})
+        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)},
+                       ifcond)
 
 # Debugging aid: unmask QAPI schema's type names
 # We normally mask them, because they're not QMP wire ABI
Signature · 1 line
2.14.1.146.gd35faa819
#68 lore raw

Re: [Qemu-devel] [PATCH v2 22/54] qapi-introspect: add preprocessor conditions to generated QLit

Quoted 15 lines · Marc-André Lureau

Add 'ifcond' condition to QLit objects.

to_qlit() handles the (obj, ifcond) tuples.

---
 scripts/qapi-introspect.py | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
scripts/qapi-introspect.py +0 -0
index 9ef6f271d4..5e736a06df 100644
@@ -125,12 +125,12 @@ const QLitObject %(c_name)s = %(c_string)s;
             return '[' + self._use_type(typ.element_type) + ']'

scripts/qapi-introspect.py const QLitObject %(c_name)s = %(c_string)s; · line 133

Quoted 10 lines
scripts/qapi-introspect.py +2 -2
         return self._name(typ.name)
 
-    def _gen_qlit(self, name, mtype, obj):
+    def _gen_qlit(self, name, mtype, obj, ifcond):
         if mtype not in ('command', 'event', 'builtin', 'array'):
             name = self._name(name)
         obj['name'] = name
         obj['meta-type'] = mtype
-        self._qlits.append(obj)
+        self._qlits.append((obj, ifcond))

If I read this correctly, all elements of self._qlits become pairs, even the unconditional ones. They all go through to_qlit()'s tuple case. Works, because gen_if(None) and gen_endif(None) do nothing.

Would

if ifcond:
obj = (obj, ifcond)
self.qlits.append(obj)

be clearer? It could be a bit more efficient, but I doubt that matters.

Quoted 51 lines
scripts/qapi-introspect.py +9 -7
     def _gen_member(self, member):
         ret = {'name': member.name, 'type': self._use_type(member.type)}
@@ -146,26 +146,27 @@ const QLitObject %(c_name)s = %(c_string)s;
         return {'case': variant.name, 'type': self._use_type(variant.type)}
 
     def visit_builtin_type(self, name, info, json_type):
-        self._gen_qlit(name, 'builtin', {'json-type': json_type})
+        self._gen_qlit(name, 'builtin', {'json-type': json_type}, None)
 
     def visit_enum_type(self, name, info, values, prefix, ifcond):
-        self._gen_qlit(name, 'enum', {'values': values})
+        self._gen_qlit(name, 'enum', {'values': values}, ifcond)
 
     def visit_array_type(self, name, info, element_type, ifcond):
         element = self._use_type(element_type)
-        self._gen_qlit('[' + element + ']', 'array', {'element-type': element})
+        self._gen_qlit('[' + element + ']', 'array', {'element-type': element},
+                       ifcond)
 
     def visit_object_type_flat(self, name, info, members, variants, ifcond):
         obj = {'members': [self._gen_member(m) for m in members]}
         if variants:
             obj.update(self._gen_variants(variants.tag_member.name,
                                           variants.variants))
-        self._gen_qlit(name, 'object', obj)
+        self._gen_qlit(name, 'object', obj, ifcond)
 
     def visit_alternate_type(self, name, info, variants, ifcond):
         self._gen_qlit(name, 'alternate',
                        {'members': [{'type': self._use_type(m.type)}
-                                    for m in variants.variants]})
+                                    for m in variants.variants]}, ifcond)
 
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
@@ -173,11 +174,12 @@ const QLitObject %(c_name)s = %(c_string)s;
         ret_type = ret_type or self._schema.the_empty_object_type
         self._gen_qlit(name, 'command',
                        {'arg-type': self._use_type(arg_type),
-                        'ret-type': self._use_type(ret_type)})
+                        'ret-type': self._use_type(ret_type)}, ifcond)
 
     def visit_event(self, name, info, arg_type, boxed, ifcond):
         arg_type = arg_type or self._schema.the_empty_object_type
-        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)})
+        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)},
+                       ifcond)
 
 # Debugging aid: unmask QAPI schema's type names
 # We normally mask them, because they're not QMP wire ABI
#69 lore raw

Re: [Qemu-devel] [PATCH v2 22/54] qapi-introspect: add preprocessor conditions to generated QLit

Quoted 32 lines · Markus Armbruster
Quoted 15 lines · Marc-André Lureau

Add 'ifcond' condition to QLit objects.

to_qlit() handles the (obj, ifcond) tuples.

---
 scripts/qapi-introspect.py | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
scripts/qapi-introspect.py +0 -0
index 9ef6f271d4..5e736a06df 100644
@@ -125,12 +125,12 @@ const QLitObject %(c_name)s = %(c_string)s;
             return '[' + self._use_type(typ.element_type) + ']'

scripts/qapi-introspect.py const QLitObject %(c_name)s = %(c_string)s; · line 133

Quoted 10 lines
scripts/qapi-introspect.py +2 -2
         return self._name(typ.name)
 
-    def _gen_qlit(self, name, mtype, obj):
+    def _gen_qlit(self, name, mtype, obj, ifcond):
         if mtype not in ('command', 'event', 'builtin', 'array'):
             name = self._name(name)
         obj['name'] = name
         obj['meta-type'] = mtype
-        self._qlits.append(obj)
+        self._qlits.append((obj, ifcond))

If I read this correctly, all elements of self._qlits become pairs, even the unconditional ones. They all go through to_qlit()'s tuple case. Works, because gen_if(None) and gen_endif(None) do nothing.

Quoted 7 lines

Would

if ifcond:
obj = (obj, ifcond)
self.qlits.append(obj)

be clearer? It could be a bit more efficient, but I doubt that matters.

I prefer the tuple case only version, but up to you if you want me to change it.

Quoted 53 lines
Quoted 52 lines
scripts/qapi-introspect.py +9 -7
     def _gen_member(self, member):
         ret = {'name': member.name, 'type': self._use_type(member.type)}
@@ -146,26 +146,27 @@ const QLitObject %(c_name)s = %(c_string)s;
         return {'case': variant.name, 'type': self._use_type(variant.type)}
 
     def visit_builtin_type(self, name, info, json_type):
-        self._gen_qlit(name, 'builtin', {'json-type': json_type})
+        self._gen_qlit(name, 'builtin', {'json-type': json_type}, None)
 
     def visit_enum_type(self, name, info, values, prefix, ifcond):
-        self._gen_qlit(name, 'enum', {'values': values})
+        self._gen_qlit(name, 'enum', {'values': values}, ifcond)
 
     def visit_array_type(self, name, info, element_type, ifcond):
         element = self._use_type(element_type)
-        self._gen_qlit('[' + element + ']', 'array', {'element-type': element})
+        self._gen_qlit('[' + element + ']', 'array', {'element-type': element},
+                       ifcond)
 
     def visit_object_type_flat(self, name, info, members, variants, ifcond):
         obj = {'members': [self._gen_member(m) for m in members]}
         if variants:
             obj.update(self._gen_variants(variants.tag_member.name,
                                           variants.variants))
-        self._gen_qlit(name, 'object', obj)
+        self._gen_qlit(name, 'object', obj, ifcond)
 
     def visit_alternate_type(self, name, info, variants, ifcond):
         self._gen_qlit(name, 'alternate',
                        {'members': [{'type': self._use_type(m.type)}
-                                    for m in variants.variants]})
+                                    for m in variants.variants]}, ifcond)
 
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
@@ -173,11 +174,12 @@ const QLitObject %(c_name)s = %(c_string)s;
         ret_type = ret_type or self._schema.the_empty_object_type
         self._gen_qlit(name, 'command',
                        {'arg-type': self._use_type(arg_type),
-                        'ret-type': self._use_type(ret_type)})
+                        'ret-type': self._use_type(ret_type)}, ifcond)
 
     def visit_event(self, name, info, arg_type, boxed, ifcond):
         arg_type = arg_type or self._schema.the_empty_object_type
-        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)})
+        self._gen_qlit(name, 'event', {'arg-type': self._use_type(arg_type)},
+                       ifcond)
 
 # Debugging aid: unmask QAPI schema's type names
 # We normally mask them, because they're not QMP wire ABI
Signature · 1 line
Marc-André Lureau
#70 lore raw

Re: [Qemu-devel] [PATCH v2 22/54] qapi-introspect: add preprocessor conditions to generated QLit

In reply to Marc-André Lureau
Quoted 5 lines · Marc-André Lureau

Add 'ifcond' condition to QLit objects.

to_qlit() handles the (obj, ifcond) tuples.

I my testing, the generated code changes like this:

    diff -rup qapi-gen-21-64300535f0/test-qmp-introspect.c qapi-gen-22-050f2a5d9d/test-qmp-introspect.c
    --- qapi-gen-21-64300535f0/test-qmp-introspect.c	2017-09-06 12:02:11.808681800 +0200
    +++ qapi-gen-22-050f2a5d9d/test-qmp-introspect.c	2017-09-06 12:02:19.085578791 +0200
    @@ -51,19 +51,31 @@ const QLitObject test_qmp_schema_qlit =
             { "name", QLIT_QSTR("EVENT_F") },
             {}
         })),
    -    QLIT_QDICT(((QLitDictEntry[]) {
    +    
    +#if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
    +
--> +QLIT_QDICT(((QLitDictEntry[]) {
             { "arg-type", QLIT_QSTR("5") },
             { "meta-type", QLIT_QSTR("command") },
             { "name", QLIT_QSTR("TestIfCmd") },

Indentation's off at the line I marked.

#71 lore raw

Re: [Qemu-devel] [PATCH v2 22/54] qapi-introspect: add preprocessor conditions to generated QLit

----- Original Message -----

Quoted 29 lines
Quoted 5 lines · Marc-André Lureau

Add 'ifcond' condition to QLit objects.

to_qlit() handles the (obj, ifcond) tuples.

I my testing, the generated code changes like this:

    diff -rup qapi-gen-21-64300535f0/test-qmp-introspect.c
    qapi-gen-22-050f2a5d9d/test-qmp-introspect.c
    --- qapi-gen-21-64300535f0/test-qmp-introspect.c	2017-09-06
    12:02:11.808681800 +0200
    +++ qapi-gen-22-050f2a5d9d/test-qmp-introspect.c	2017-09-06
    12:02:19.085578791 +0200
    @@ -51,19 +51,31 @@ const QLitObject test_qmp_schema_qlit =
             { "name", QLIT_QSTR("EVENT_F") },
             {}
         })),
    -    QLIT_QDICT(((QLitDictEntry[]) {
    +
    +#if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
    +
--> +QLIT_QDICT(((QLitDictEntry[]) {
             { "arg-type", QLIT_QSTR("5") },
             { "meta-type", QLIT_QSTR("command") },
             { "name", QLIT_QSTR("TestIfCmd") },
Quoted 2 lines

Indentation's off at the line I marked.

fixed, thanks

#72 lore raw

PATCH v2 23/54 qapi-commands: add #if conditions to commands

In reply to Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-commands.py  | 2 ++
 tests/test-qmp-commands.c | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)
scripts/qapi-commands.py +2 -0
index 5eb96b2d95..db45415c41 100644
@@ -228,6 +228,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
+        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -240,6 +241,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
+    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
tests/test-qmp-commands.c +2 -2
index 9b9a7ffee7..ad7b6e4e1d 100644
@@ -10,11 +10,11 @@
 
 static QmpCommandList qmp_commands;
 
-/* #if defined(TEST_IF_CMD) */
+#if defined(TEST_IF_CMD)
 void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
 {
 }
-/* #endif */
+#endif
 
 void qmp_user_def_cmd(Error **errp)
 {
Signature · 1 line
2.14.1.146.gd35faa819
#73 lore raw

Re: [Qemu-devel] [PATCH v2 23/54] qapi-commands: add #if conditions to commands

Quoted 36 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-commands.py  | 2 ++
 tests/test-qmp-commands.c | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)
scripts/qapi-commands.py +2 -0
index 5eb96b2d95..db45415c41 100644
@@ -228,6 +228,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
+        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -240,6 +241,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
+    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
tests/test-qmp-commands.c +0 -0
index 9b9a7ffee7..ad7b6e4e1d 100644
@@ -10,11 +10,11 @@
 
 static QmpCommandList qmp_commands;
 

tests/test-qmp-commands.c line 20

Quoted 10 lines
tests/test-qmp-commands.c +2 -2
-/* #if defined(TEST_IF_CMD) */
+#if defined(TEST_IF_CMD)
 void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
 {
 }
-/* #endif */
+#endif
 
 void qmp_user_def_cmd(Error **errp)
 {

To find out whether the clever decorator is worth its keep, I replaced it with the dumbest, most obvious code I could think of (appended). Does this make visit_command() easier or harder to understand?

scripts/qapi-commands.py +9 -7
index db45415c41..13d37d2ac2 100644
@@ -228,7 +228,6 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
-        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -241,18 +240,21 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
-    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
             return
-        self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
+        decl = gen_command_decl(name, arg_type, boxed, ret_type)
+        defn = ''
         if ret_type and ret_type not in self._visited_ret_types:
             self._visited_ret_types.add(ret_type)
-            self.defn += gen_marshal_output(ret_type)
-        self.decl += gen_marshal_decl(name)
-        self.defn += gen_marshal(name, arg_type, boxed, ret_type)
-        self._regy += gen_register_command(name, success_response)
+            defn += gen_marshal_output(ret_type)
+        decl += gen_marshal_decl(name)
+        defn += gen_marshal(name, arg_type, boxed, ret_type)
+        self.decl += gen_ifcond(ifcond, decl)
+        self.defn += gen_ifcond(ifcond, defn)
+        self._regy += gen_ifcond(ifcond,
+                                 gen_register_command(name, success_response))
 
 
 (input_file, output_dir, do_c, do_h, prefix, opts) = parse_command_line()
scripts/qapi.py +4 -23
index 52099332f1..3de5b8b8f0 100644
@@ -1918,29 +1918,10 @@ def gen_endif(ifcond):
     return ret
 
 
-# Wrap a method to add #if / #endif to generated code, only if some
-# code was generated.
-# self must have 'if_members' listing the attributes to wrap.
-# The last argument of the wrapped function must be the 'ifcond'.
-def ifcond_decorator(func):
-
-    def func_wrapper(self, *args, **kwargs):
-        ifcond = args[-1]
-        save = {}
-        for mem in self.if_members:
-            save[mem] = getattr(self, mem)
-        func(self, *args, **kwargs)
-        for mem, val in save.items():
-            newval = getattr(self, mem)
-            if newval != val:
-                assert newval.startswith(val)
-                newval = newval[len(val):]
-                val += gen_if(ifcond)
-                val += newval
-                val += gen_endif(ifcond)
-            setattr(self, mem, val)
-
-    return func_wrapper
+def gen_ifcond(ifcond, ctext):
+    if ifcond:
+        return gen_if(ifcond) + ctext + gen_endif(ifcond)
+    return ctext
 
 
 def gen_enum_lookup(name, values, prefix=None):
#74 lore raw

Re: [Qemu-devel] [PATCH v2 23/54] qapi-commands: add #if conditions to commands

Hi

----- Original Message -----

Quoted 83 lines
Quoted 36 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-commands.py  | 2 ++
 tests/test-qmp-commands.c | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)
scripts/qapi-commands.py +2 -0
index 5eb96b2d95..db45415c41 100644
@@ -228,6 +228,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
+        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -240,6 +241,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
+    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
tests/test-qmp-commands.c +0 -0
index 9b9a7ffee7..ad7b6e4e1d 100644
@@ -10,11 +10,11 @@
 
 static QmpCommandList qmp_commands;
 

tests/test-qmp-commands.c line 20

Quoted 10 lines
tests/test-qmp-commands.c +2 -2
-/* #if defined(TEST_IF_CMD) */
+#if defined(TEST_IF_CMD)
 void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
 {
 }
-/* #endif */
+#endif
 
 void qmp_user_def_cmd(Error **errp)
 {

To find out whether the clever decorator is worth its keep, I replaced it with the dumbest, most obvious code I could think of (appended). Does this make visit_command() easier or harder to understand?

scripts/qapi-commands.py +2 -5
index db45415c41..13d37d2ac2 100644
@@ -228,7 +228,6 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
-        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -241,18 +240,21 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
-    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
             return
-        self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
+        decl = gen_command_decl(name, arg_type, boxed, ret_type)
+        defn = ''
         if ret_type and ret_type not in self._visited_ret_types:
             self._visited_ret_types.add(ret_type)
-            self.defn += gen_marshal_output(ret_type)
-        self.decl += gen_marshal_decl(name)

scripts/qapi-commands.py class QAPISchemaGenCommandVisitor(QAPISchemaVisitor): · line 258

Quoted 10 lines
scripts/qapi-commands.py +7 -2
-        self.defn += gen_marshal(name, arg_type, boxed, ret_type)
-        self._regy += gen_register_command(name, success_response)
+            defn += gen_marshal_output(ret_type)
+        decl += gen_marshal_decl(name)
+        defn += gen_marshal(name, arg_type, boxed, ret_type)
+        self.decl += gen_ifcond(ifcond, decl)
+        self.defn += gen_ifcond(ifcond, defn)
+        self._regy += gen_ifcond(ifcond,
+                                 gen_register_command(name,
 success_response))

This is one of the most simple case, and it is already very intrusive. If you have more branches / early return it becomes awful.

Do it for all the places where we have @ifcond_decorator and you will probably prefer the concise decorated version. For me this case is one of the reason why decorators exist: to wrap enter/exit of a function.

Quoted 42 lines
scripts/qapi-commands.py +0 -0
 (input_file, output_dir, do_c, do_h, prefix, opts) = parse_command_line()
scripts/qapi.py +4 -23
index 52099332f1..3de5b8b8f0 100644
@@ -1918,29 +1918,10 @@ def gen_endif(ifcond):
     return ret
 
 
-# Wrap a method to add #if / #endif to generated code, only if some
-# code was generated.
-# self must have 'if_members' listing the attributes to wrap.
-# The last argument of the wrapped function must be the 'ifcond'.
-def ifcond_decorator(func):
-
-    def func_wrapper(self, *args, **kwargs):
-        ifcond = args[-1]
-        save = {}
-        for mem in self.if_members:
-            save[mem] = getattr(self, mem)
-        func(self, *args, **kwargs)
-        for mem, val in save.items():
-            newval = getattr(self, mem)
-            if newval != val:
-                assert newval.startswith(val)
-                newval = newval[len(val):]
-                val += gen_if(ifcond)
-                val += newval
-                val += gen_endif(ifcond)
-            setattr(self, mem, val)
-
-    return func_wrapper
+def gen_ifcond(ifcond, ctext):
+    if ifcond:
+        return gen_if(ifcond) + ctext + gen_endif(ifcond)
+    return ctext
 
 
 def gen_enum_lookup(name, values, prefix=None):
#75 lore raw

Re: [Qemu-devel] [PATCH v2 23/54] qapi-commands: add #if conditions to commands

----- Original Message -----

Quoted 100 lines

Hi

----- Original Message -----

Quoted 83 lines
Quoted 36 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-commands.py  | 2 ++
 tests/test-qmp-commands.c | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)
scripts/qapi-commands.py +2 -0
index 5eb96b2d95..db45415c41 100644
@@ -228,6 +228,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
+        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -240,6 +241,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
+    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
tests/test-qmp-commands.c +0 -0
index 9b9a7ffee7..ad7b6e4e1d 100644
@@ -10,11 +10,11 @@
 
 static QmpCommandList qmp_commands;
 

tests/test-qmp-commands.c line 20

Quoted 10 lines
tests/test-qmp-commands.c +2 -2
-/* #if defined(TEST_IF_CMD) */
+#if defined(TEST_IF_CMD)
 void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
 {
 }
-/* #endif */
+#endif
 
 void qmp_user_def_cmd(Error **errp)
 {

To find out whether the clever decorator is worth its keep, I replaced it with the dumbest, most obvious code I could think of (appended). Does this make visit_command() easier or harder to understand?

scripts/qapi-commands.py +2 -5
index db45415c41..13d37d2ac2 100644
@@ -228,7 +228,6 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
-        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -241,18 +240,21 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
-    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
             return
-        self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
+        decl = gen_command_decl(name, arg_type, boxed, ret_type)
+        defn = ''
         if ret_type and ret_type not in self._visited_ret_types:
             self._visited_ret_types.add(ret_type)
-            self.defn += gen_marshal_output(ret_type)
-        self.decl += gen_marshal_decl(name)

scripts/qapi-commands.py class QAPISchemaGenCommandVisitor(QAPISchemaVisitor): · line 258

Quoted 10 lines
scripts/qapi-commands.py +7 -2
-        self.defn += gen_marshal(name, arg_type, boxed, ret_type)
-        self._regy += gen_register_command(name, success_response)
+            defn += gen_marshal_output(ret_type)
+        decl += gen_marshal_decl(name)
+        defn += gen_marshal(name, arg_type, boxed, ret_type)
+        self.decl += gen_ifcond(ifcond, decl)
+        self.defn += gen_ifcond(ifcond, defn)
+        self._regy += gen_ifcond(ifcond,
+                                 gen_register_command(name,
 success_response))

This is one of the most simple case, and it is already very intrusive. If you have more branches / early return it becomes awful.

Quoted 4 lines

Do it for all the places where we have @ifcond_decorator and you will probably prefer the concise decorated version. For me this case is one of the reason why decorators exist: to wrap enter/exit of a function.

Oh and your version looks inferior, since it will generate empty #if/#endif blocks. You seemed to be quite strict about having the generated output be nicely formatted & human friendly, so I thought clearing those empty block was a must for you.

Quoted 43 lines
Quoted 42 lines
scripts/qapi-commands.py +0 -0
 (input_file, output_dir, do_c, do_h, prefix, opts) = parse_command_line()
scripts/qapi.py +4 -23
index 52099332f1..3de5b8b8f0 100644
@@ -1918,29 +1918,10 @@ def gen_endif(ifcond):
     return ret
 
 
-# Wrap a method to add #if / #endif to generated code, only if some
-# code was generated.
-# self must have 'if_members' listing the attributes to wrap.
-# The last argument of the wrapped function must be the 'ifcond'.
-def ifcond_decorator(func):
-
-    def func_wrapper(self, *args, **kwargs):
-        ifcond = args[-1]
-        save = {}
-        for mem in self.if_members:
-            save[mem] = getattr(self, mem)
-        func(self, *args, **kwargs)
-        for mem, val in save.items():
-            newval = getattr(self, mem)
-            if newval != val:
-                assert newval.startswith(val)
-                newval = newval[len(val):]
-                val += gen_if(ifcond)
-                val += newval
-                val += gen_endif(ifcond)
-            setattr(self, mem, val)
-
-    return func_wrapper
+def gen_ifcond(ifcond, ctext):
+    if ifcond:
+        return gen_if(ifcond) + ctext + gen_endif(ifcond)
+    return ctext
 
 
 def gen_enum_lookup(name, values, prefix=None):
#76 lore raw

Re: [Qemu-devel] [PATCH v2 23/54] qapi-commands: add #if conditions to commands

Quoted 104 lines · Marc-André Lureau

----- Original Message -----

Quoted 103 lines

Hi

----- Original Message -----

Quoted 83 lines
Quoted 36 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-commands.py  | 2 ++
 tests/test-qmp-commands.c | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)
scripts/qapi-commands.py +2 -0
index 5eb96b2d95..db45415c41 100644
@@ -228,6 +228,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
+        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -240,6 +241,7 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
+    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
tests/test-qmp-commands.c +0 -0
index 9b9a7ffee7..ad7b6e4e1d 100644
@@ -10,11 +10,11 @@
 
 static QmpCommandList qmp_commands;
 

tests/test-qmp-commands.c line 20

Quoted 10 lines
tests/test-qmp-commands.c +2 -2
-/* #if defined(TEST_IF_CMD) */
+#if defined(TEST_IF_CMD)
 void qmp_TestIfCmd(TestIfStruct *foo, Error **errp)
 {
 }
-/* #endif */
+#endif
 
 void qmp_user_def_cmd(Error **errp)
 {

To find out whether the clever decorator is worth its keep, I replaced it with the dumbest, most obvious code I could think of (appended). Does this make visit_command() easier or harder to understand?

scripts/qapi-commands.py +2 -5
index db45415c41..13d37d2ac2 100644
@@ -228,7 +228,6 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self.defn = None
         self._regy = None
         self._visited_ret_types = None
-        self.if_members = ['decl', 'defn', '_regy']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -241,18 +240,21 @@ class QAPISchemaGenCommandVisitor(QAPISchemaVisitor):
         self._regy = None
         self._visited_ret_types = None
 
-    @ifcond_decorator
     def visit_command(self, name, info, arg_type, ret_type,
                       gen, success_response, boxed, ifcond):
         if not gen:
             return
-        self.decl += gen_command_decl(name, arg_type, boxed, ret_type)
+        decl = gen_command_decl(name, arg_type, boxed, ret_type)
+        defn = ''
         if ret_type and ret_type not in self._visited_ret_types:
             self._visited_ret_types.add(ret_type)
-            self.defn += gen_marshal_output(ret_type)
-        self.decl += gen_marshal_decl(name)

scripts/qapi-commands.py class QAPISchemaGenCommandVisitor(QAPISchemaVisitor): · line 258

Quoted 10 lines
scripts/qapi-commands.py +7 -2
-        self.defn += gen_marshal(name, arg_type, boxed, ret_type)
-        self._regy += gen_register_command(name, success_response)
+            defn += gen_marshal_output(ret_type)
+        decl += gen_marshal_decl(name)
+        defn += gen_marshal(name, arg_type, boxed, ret_type)
+        self.decl += gen_ifcond(ifcond, decl)
+        self.defn += gen_ifcond(ifcond, defn)
+        self._regy += gen_ifcond(ifcond,
+                                 gen_register_command(name,
 success_response))

This is one of the most simple case, and it is already very intrusive. If you have more branches / early return it becomes awful.

Do it for all the places where we have @ifcond_decorator and you will probably prefer the concise decorated version. For me this case is one of the reason why decorators exist: to wrap enter/exit of a function.

This is just a quick experiment. We certainly have to compare complete solutions to decide whether the decorator is worthwhile.

Quoted 1 line

Oh and your version looks inferior, since it will generate empty #if/#endif blocks. You seemed to be quite strict about having the generated output be nicely formatted & human friendly, so I thought clearing those empty block was a must for you.

Yes, it is a must for me. Should be easy enough to fix: in gen_ifcond(), replace "if ifcond" by "if ifcond and text is not blank".

Quoted 43 lines
Quoted 43 lines
Quoted 42 lines
scripts/qapi-commands.py +0 -0
 (input_file, output_dir, do_c, do_h, prefix, opts) = parse_command_line()
scripts/qapi.py +4 -23
index 52099332f1..3de5b8b8f0 100644
@@ -1918,29 +1918,10 @@ def gen_endif(ifcond):
     return ret
 
 
-# Wrap a method to add #if / #endif to generated code, only if some
-# code was generated.
-# self must have 'if_members' listing the attributes to wrap.
-# The last argument of the wrapped function must be the 'ifcond'.
-def ifcond_decorator(func):
-
-    def func_wrapper(self, *args, **kwargs):
-        ifcond = args[-1]
-        save = {}
-        for mem in self.if_members:
-            save[mem] = getattr(self, mem)
-        func(self, *args, **kwargs)
-        for mem, val in save.items():
-            newval = getattr(self, mem)
-            if newval != val:
-                assert newval.startswith(val)
-                newval = newval[len(val):]
-                val += gen_if(ifcond)
-                val += newval
-                val += gen_endif(ifcond)
-            setattr(self, mem, val)
-
-    return func_wrapper
+def gen_ifcond(ifcond, ctext):
+    if ifcond:
+        return gen_if(ifcond) + ctext + gen_endif(ifcond)
+    return ctext
 
 
 def gen_enum_lookup(name, values, prefix=None):
#77 lore raw

PATCH v2 24/54 qapi-event: add #if conditions to events

In reply to Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-event.py | 2 ++
 1 file changed, 2 insertions(+)
scripts/qapi-event.py +2 -0
index fec27fe2e1..f21ecd39f3 100644
@@ -152,6 +152,7 @@ class QAPISchemaGenEventVisitor(QAPISchemaVisitor):
         self.decl = None
         self.defn = None
         self._event_names = None
+        self.if_members = ['decl', 'defn']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -163,6 +164,7 @@ class QAPISchemaGenEventVisitor(QAPISchemaVisitor):
         self.defn += gen_enum_lookup(event_enum_name, self._event_names)
         self._event_names = None
 
+    @ifcond_decorator
     def visit_event(self, name, info, arg_type, boxed, ifcond):
         self.decl += gen_event_send_decl(name, arg_type, boxed)
         self.defn += gen_event_send(name, arg_type, boxed)
Signature · 1 line
2.14.1.146.gd35faa819
#78 lore raw

PATCH v2 25/54 qapi-visit: add #if conditions to visitors

In reply to Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-visit.py | 5 +++++
 1 file changed, 5 insertions(+)
scripts/qapi-visit.py +5 -0
index c29c2d869e..bb18c9edee 100644
@@ -267,6 +267,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = None
         self.defn = None
         self._btin = None
+        self.if_members = ['decl', 'defn', '_btin']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -282,6 +283,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = self._btin + self.decl
         self._btin = None
 
+    @ifcond_decorator
     def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
@@ -293,6 +295,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name, scalar=True)
             self.defn += gen_visit_enum(name)
 
+    @ifcond_decorator
     def visit_array_type(self, name, info, element_type, ifcond):
         decl = gen_visit_decl(name)
         defn = gen_visit_list(name, element_type)
@@ -304,6 +307,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += decl
             self.defn += defn
 
+    @ifcond_decorator
     def visit_object_type(self, name, info, base, members, variants, ifcond):
         # Nothing to do for the special empty builtin
         if name == 'q_empty':
@@ -317,6 +321,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name)
             self.defn += gen_visit_object(name, base, members, variants)
 
+    @ifcond_decorator
     def visit_alternate_type(self, name, info, variants, ifcond):
         self.decl += gen_visit_decl(name)
         self.defn += gen_visit_alternate(name, variants)
Signature · 1 line
2.14.1.146.gd35faa819
#79 lore raw

Re: [Qemu-devel] [PATCH v2 25/54] qapi-visit: add #if conditions to visitors

Quoted 44 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-visit.py | 5 +++++
 1 file changed, 5 insertions(+)
scripts/qapi-visit.py +4 -0
index c29c2d869e..bb18c9edee 100644
@@ -267,6 +267,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = None
         self.defn = None
         self._btin = None
+        self.if_members = ['decl', 'defn', '_btin']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -282,6 +283,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = self._btin + self.decl
         self._btin = None
 
+    @ifcond_decorator
     def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
@@ -293,6 +295,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name, scalar=True)
             self.defn += gen_visit_enum(name)
 
+    @ifcond_decorator
     def visit_array_type(self, name, info, element_type, ifcond):
         decl = gen_visit_decl(name)
         defn = gen_visit_list(name, element_type)
@@ -304,6 +307,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += decl
             self.defn += defn
 
+    @ifcond_decorator
     def visit_object_type(self, name, info, base, members, variants, ifcond):
         # Nothing to do for the special empty builtin
         if name == 'q_empty':

scripts/qapi-visit.py class QAPISchemaGenVisitVisitor(QAPISchemaVisitor): · line 327

Quoted 7 lines
scripts/qapi-visit.py +1 -0
@@ -317,6 +321,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name)
             self.defn += gen_visit_object(name, base, members, variants)
 
+    @ifcond_decorator
     def visit_alternate_type(self, name, info, variants, ifcond):
         self.decl += gen_visit_decl(name)
         self.defn += gen_visit_alternate(name, variants)

make check fails to compile, first error:

make -C ~/work/qemu/bld-x86/ check
make: Entering directory '/work/armbru/qemu/bld-x86'
[...]
GEN tests/test-qapi-types.c
CC tests/test-qapi-types.o
tests/test-qapi-types.c: In function ‘qapi_free_TestIfAlternate’:
tests/test-qapi-types.c:190:5: warning: implicit declaration of function ‘visit_type_TestIfAlternate’; did you mean ‘visit_type_UserDefAlternate’? [-Wimplicit-function-declaration]

     visit_type_TestIfAlternate(v, NULL, &obj, NULL);
     ^~~~~~~~~~~~~~~~~~~~~~~~~~
     visit_type_UserDefAlternate
tests/test-qapi-types.c:190:5: warning: nested extern declaration of ‘visit_type_TestIfAlternate’ [-Wnested-externs]
tests/test-qapi-types.c: In function ‘qapi_free_TestIfStruct’:
tests/test-qapi-types.c:213:5: warning: implicit declaration of function ‘visit_type_TestIfStruct’; did you mean ‘visit_type_TestStruct’? [-Wimplicit-function-declaration]
     visit_type_TestIfStruct(v, NULL, &obj, NULL);
     ^~~~~~~~~~~~~~~~~~~~~~~
     visit_type_TestStruct
tests/test-qapi-types.c:213:5: warning: nested extern declaration of ‘visit_type_TestIfStruct’ [-Wnested-externs]
tests/test-qapi-types.c: In function ‘qapi_free_TestIfUnion’:
tests/test-qapi-types.c:226:5: warning: implicit declaration of function ‘visit_type_TestIfUnion’; did you mean ‘visit_type_TestStruct’? [-Wimplicit-function-declaration]
     visit_type_TestIfUnion(v, NULL, &obj, NULL);
     ^~~~~~~~~~~~~~~~~~~~~~
     visit_type_TestStruct
tests/test-qapi-types.c:226:5: warning: nested extern declaration of ‘visit_type_TestIfUnion’ [-Wnested-externs]
  GEN     tests/test-qapi-event.c
  CC      tests/test-qapi-event.o
  GEN     tests/test-qmp-introspect.c
  CC      tests/test-qmp-introspect.o
  LINK    tests/test-qobject-output-visitor

tests/test-qapi-types.o: In function `qapi_free_TestIfAlternate':
/work/armbru/qemu/bld-x86/tests/test-qapi-types.c:190: undefined reference to visit_type_TestIfAlternate' tests/test-qapi-types.o: In function qapi_free_TestIfStruct':
test-qapi-types.c:(.text+0x361): undefined reference to visit_type_TestIfStruct' tests/test-qapi-types.o: In function qapi_free_TestIfUnion':
test-qapi-types.c:(.text+0x3af): undefined reference to `visit_type_TestIfUnion'
collect2: error: ld returned 1 exit status
make: *** [/work/armbru/qemu/rules.mak:121: tests/test-qobject-output-visitor] Error 1
make: Leaving directory '/work/armbru/qemu/bld-x86'

#80 lore raw

Re: [Qemu-devel] [PATCH v2 25/54] qapi-visit: add #if conditions to visitors

----- Original Message -----

Quoted 50 lines
Quoted 48 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-visit.py | 5 +++++
 1 file changed, 5 insertions(+)
scripts/qapi-visit.py +4 -0
index c29c2d869e..bb18c9edee 100644
@@ -267,6 +267,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = None
         self.defn = None
         self._btin = None
+        self.if_members = ['decl', 'defn', '_btin']
 
     def visit_begin(self, schema):
         self.decl = ''
@@ -282,6 +283,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
         self.decl = self._btin + self.decl
         self._btin = None
 
+    @ifcond_decorator
     def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
@@ -293,6 +295,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name, scalar=True)
             self.defn += gen_visit_enum(name)
 
+    @ifcond_decorator
     def visit_array_type(self, name, info, element_type, ifcond):
         decl = gen_visit_decl(name)
         defn = gen_visit_list(name, element_type)
@@ -304,6 +307,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += decl
             self.defn += defn
 
+    @ifcond_decorator
     def visit_object_type(self, name, info, base, members, variants,
     ifcond):
         # Nothing to do for the special empty builtin
         if name == 'q_empty':
scripts/qapi-visit.py +0 -0
@@ -317,6 +321,7 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
             self.decl += gen_visit_decl(name)
             self.defn += gen_visit_object(name, base, members, variants)
 
Quoted 7 lines

scripts/qapi-visit.py class QAPISchemaGenVisitVisitor(QAPISchemaVisitor): · line 327

Quoted 4 lines
scripts/qapi-visit.py +1 -0
+    @ifcond_decorator
     def visit_alternate_type(self, name, info, variants, ifcond):
         self.decl += gen_visit_decl(name)
         self.defn += gen_visit_alternate(name, variants)

make check fails to compile, first error:

I'll merge back qapi-types & qapi-visited #if addition (regression from the split).

Quoted 51 lines

make -C ~/work/qemu/bld-x86/ check
make: Entering directory '/work/armbru/qemu/bld-x86'
[...]
GEN tests/test-qapi-types.c
CC tests/test-qapi-types.o
tests/test-qapi-types.c: In function ‘qapi_free_TestIfAlternate’:
tests/test-qapi-types.c:190:5: warning: implicit declaration of function ‘visit_type_TestIfAlternate’; did you mean ‘visit_type_UserDefAlternate’? [-Wimplicit-function-declaration]

     visit_type_TestIfAlternate(v, NULL, &obj, NULL);
     ^~~~~~~~~~~~~~~~~~~~~~~~~~
     visit_type_UserDefAlternate

tests/test-qapi-types.c:190:5: warning: nested extern declaration of ‘visit_type_TestIfAlternate’ [-Wnested-externs] tests/test-qapi-types.c: In function ‘qapi_free_TestIfStruct’:
tests/test-qapi-types.c:213:5: warning: implicit declaration of function ‘visit_type_TestIfStruct’; did you mean ‘visit_type_TestStruct’? [-Wimplicit-function-declaration]

     visit_type_TestIfStruct(v, NULL, &obj, NULL);
     ^~~~~~~~~~~~~~~~~~~~~~~
     visit_type_TestStruct

tests/test-qapi-types.c:213:5: warning: nested extern declaration of ‘visit_type_TestIfStruct’ [-Wnested-externs] tests/test-qapi-types.c: In function ‘qapi_free_TestIfUnion’:
tests/test-qapi-types.c:226:5: warning: implicit declaration of function ‘visit_type_TestIfUnion’; did you mean ‘visit_type_TestStruct’? [-Wimplicit-function-declaration]

     visit_type_TestIfUnion(v, NULL, &obj, NULL);
     ^~~~~~~~~~~~~~~~~~~~~~
     visit_type_TestStruct
tests/test-qapi-types.c:226:5: warning: nested extern declaration of
‘visit_type_TestIfUnion’ [-Wnested-externs]
  GEN     tests/test-qapi-event.c
  CC      tests/test-qapi-event.o
  GEN     tests/test-qmp-introspect.c
  CC      tests/test-qmp-introspect.o
  LINK    tests/test-qobject-output-visitor

tests/test-qapi-types.o: In function `qapi_free_TestIfAlternate':
/work/armbru/qemu/bld-x86/tests/test-qapi-types.c:190: undefined reference to `visit_type_TestIfAlternate'
tests/test-qapi-types.o: In function `qapi_free_TestIfStruct':
test-qapi-types.c:(.text+0x361): undefined reference to `visit_type_TestIfStruct'
tests/test-qapi-types.o: In function `qapi_free_TestIfUnion':
test-qapi-types.c:(.text+0x3af): undefined reference to `visit_type_TestIfUnion'
collect2: error: ld returned 1 exit status
make: *** [/work/armbru/qemu/rules.mak:121:
tests/test-qobject-output-visitor] Error 1
make: Leaving directory '/work/armbru/qemu/bld-x86'

#81 lore raw

PATCH v2 26/54 qapi-types: refactor variants handling

In reply to Marc-André Lureau

Generate variants objects outside gen_object(). This will allow to easily wrap gen_object() with ifcond_decorator in the following patch.

---
 scripts/qapi-types.py | 34 +++++++++++++++++++++-------------
 1 file changed, 21 insertions(+), 13 deletions(-)
scripts/qapi-types.py +21 -13
index 6f06720adc..05b0eee482 100644
@@ -53,19 +53,23 @@ def gen_struct_members(members):
     return ret
 
 
-def gen_object(name, base, members, variants):
-    if name in objects_seen:
-        return ''
-    objects_seen.add(name)
-
+def gen_variants_objects(variants):
     ret = ''
     if variants:
         for v in variants.variants:
             if isinstance(v.type, QAPISchemaObjectType):
+                ret += gen_variants_objects(v.type.variants)
                 ret += gen_object(v.type.name, v.type.base,
                                   v.type.local_members, v.type.variants)
+    return ret
 
-    ret += mcgen('''
+
+def gen_object(name, base, members, variants):
+    if name in objects_seen:
+        return ''
+    objects_seen.add(name)
+
+    ret = mcgen('''
 
 struct %(c_name)s {
 ''',
@@ -224,11 +228,7 @@ typedef struct QEnumLookup {
             self.decl += gen_array(name, element_type)
             self._gen_type_cleanup(name)
 
-    def visit_object_type(self, name, info, base, members, variants, ifcond):
-        # Nothing to do for the special empty builtin
-        if name == 'q_empty':
-            return
-        self._fwdecl += gen_fwd_object_or_array(name)
+    def _gen_object(self, name, info, base, members, variants):
         self.decl += gen_object(name, base, members, variants)
         if base and not base.is_implicit():
             self.decl += gen_upcast(name, base)
@@ -238,10 +238,18 @@ typedef struct QEnumLookup {
             # implicit types won't be directly allocated/freed
             self._gen_type_cleanup(name)
 
+    def visit_object_type(self, name, info, base, members, variants, ifcond):
+        # Nothing to do for the special empty builtin
+        if name == 'q_empty':
+            return
+        self._fwdecl += gen_fwd_object_or_array(name)
+        self.decl += gen_variants_objects(variants)
+        self._gen_object(name, info, base, members, variants)
+
     def visit_alternate_type(self, name, info, variants, ifcond):
         self._fwdecl += gen_fwd_object_or_array(name)
-        self.decl += gen_object(name, None, [variants.tag_member], variants)
-        self._gen_type_cleanup(name)
+        self.decl += gen_variants_objects(variants)
+        self._gen_object(name, info, None, [variants.tag_member], variants)
 
 # If you link code generated from multiple schemata, you want only one
 # instance of the code for built-in types.  Generate it only when
Signature · 1 line
2.14.1.146.gd35faa819
#82 lore raw

PATCH v2 27/54 qapi-types: add #if conditions to types

In reply to Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

---
 scripts/qapi-types.py | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)
scripts/qapi-types.py +12 -6
index 05b0eee482..c1316312ac 100644
@@ -175,6 +175,7 @@ class QAPISchemaGenTypeVisitor(QAPISchemaVisitor):
         self.defn = None
         self._fwdecl = None
         self._btin = None
+        self.if_members = ['decl', 'defn', '_fwdecl', '_btin']
 
     def visit_begin(self, schema):
         # gen_object() is recursive, ensure it doesn't visit the empty type
@@ -201,10 +202,12 @@ typedef struct QEnumLookup {
         self.decl = self._btin + self.decl
         self._btin = None
 
-    def _gen_type_cleanup(self, name):
+    @ifcond_decorator
+    def _gen_type_cleanup(self, name, ifcond):
         self.decl += gen_type_cleanup_decl(name)
         self.defn += gen_type_cleanup(name)
 
+    @ifcond_decorator
     def visit_enum_type(self, name, info, values, prefix, ifcond):
         # Special case for our lone builtin enum type
         # TODO use something cleaner than existence of info
@@ -216,6 +219,7 @@ typedef struct QEnumLookup {
             self._fwdecl += gen_enum(name, values, prefix)
             self.defn += gen_enum_lookup(name, values, prefix)
 
+    @ifcond_decorator
     def visit_array_type(self, name, info, element_type, ifcond):
         if isinstance(element_type, QAPISchemaBuiltinType):
             self._btin += gen_fwd_object_or_array(name)
@@ -226,9 +230,10 @@ typedef struct QEnumLookup {
         else:
             self._fwdecl += gen_fwd_object_or_array(name)
             self.decl += gen_array(name, element_type)
-            self._gen_type_cleanup(name)
+            self._gen_type_cleanup(name, ifcond)
 
-    def _gen_object(self, name, info, base, members, variants):
+    @ifcond_decorator
+    def _gen_object(self, name, info, base, members, variants, ifcond):
         self.decl += gen_object(name, base, members, variants)
         if base and not base.is_implicit():
             self.decl += gen_upcast(name, base)
@@ -236,7 +241,7 @@ typedef struct QEnumLookup {
         # directly use rather than repeat type.is_implicit()?
         if not name.startswith('q_'):
             # implicit types won't be directly allocated/freed
-            self._gen_type_cleanup(name)
+            self._gen_type_cleanup(name, ifcond)
 
     def visit_object_type(self, name, info, base, members, variants, ifcond):
         # Nothing to do for the special empty builtin
@@ -244,12 +249,13 @@ typedef struct QEnumLookup {
             return
         self._fwdecl += gen_fwd_object_or_array(name)
         self.decl += gen_variants_objects(variants)
-        self._gen_object(name, info, base, members, variants)
+        self._gen_object(name, info, base, members, variants, ifcond)
 
     def visit_alternate_type(self, name, info, variants, ifcond):
         self._fwdecl += gen_fwd_object_or_array(name)
         self.decl += gen_variants_objects(variants)
-        self._gen_object(name, info, None, [variants.tag_member], variants)
+        self._gen_object(name, info, None, [variants.tag_member],
+                         variants, ifcond)
 
 # If you link code generated from multiple schemata, you want only one
 # instance of the code for built-in types.  Generate it only when
Signature · 1 line
2.14.1.146.gd35faa819
#83 lore raw

Re: [Qemu-devel] [PATCH v2 27/54] qapi-types: add #if conditions to types

Quoted 3 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

In my testing, this generates repeated conditionals, e.g.

    diff -rup qapi-gen-24-dc1833e3fb/test-qapi-types.c qapi-gen-27-9600b4638d/test-qapi-types.c
    --- qapi-gen-24-dc1833e3fb/test-qapi-types.c	2017-09-06 12:02:33.440375590 +0200
    +++ qapi-gen-27-9600b4638d/test-qapi-types.c	2017-09-06 12:55:08.709973386 +0200
    @@ -178,6 +178,12 @@ const QEnumLookup QEnumTwo_lookup = {
         .size = QENUM_TWO__MAX
     };

    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
     void qapi_free_TestIfAlternate(TestIfAlternate *obj)
     {
         Visitor *v;
    @@ -191,6 +197,15 @@ void qapi_free_TestIfAlternate(TestIfAlt
         visit_free(v);
     }

    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +
    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +

and

    diff -rup qapi-gen-24-dc1833e3fb/test-qapi-types.h qapi-gen-27-9600b4638d/test-qapi-types.h
    --- qapi-gen-24-dc1833e3fb/test-qapi-types.h	2017-09-06 12:02:27.386461287 +0200
    +++ qapi-gen-27-9600b4638d/test-qapi-types.h	2017-09-06 12:55:02.365062236 +0200
    [...]
    @@ -486,6 +498,9 @@ struct NestedEnumsOne {

     void qapi_free_NestedEnumsOne(NestedEnumsOne *obj);

    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
     struct TestIfAlternate {
         QType type;
         union { /* union tag is @type */
    @@ -494,18 +509,42 @@ struct TestIfAlternate {
         } u;
     };

    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
     void qapi_free_TestIfAlternate(TestIfAlternate *obj);

    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +
    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +

Let's ignore this until we've made up our mind *how* to best generate conditionals.

#84 lore raw

Re: [Qemu-devel] [PATCH v2 27/54] qapi-types: add #if conditions to types

Hi

Quoted 67 lines · Markus Armbruster
Quoted 3 lines · Marc-André Lureau

Wrap generated code with #if/#endif using the ifcond_decorator.

In my testing, this generates repeated conditionals, e.g.

    diff -rup qapi-gen-24-dc1833e3fb/test-qapi-types.c qapi-gen-27-9600b4638d/test-qapi-types.c
    --- qapi-gen-24-dc1833e3fb/test-qapi-types.c        2017-09-06 12:02:33.440375590 +0200
    +++ qapi-gen-27-9600b4638d/test-qapi-types.c        2017-09-06 12:55:08.709973386 +0200
    @@ -178,6 +178,12 @@ const QEnumLookup QEnumTwo_lookup = {
         .size = QENUM_TWO__MAX
     };

    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
     void qapi_free_TestIfAlternate(TestIfAlternate *obj)
     {
         Visitor *v;
    @@ -191,6 +197,15 @@ void qapi_free_TestIfAlternate(TestIfAlt
         visit_free(v);
     }

    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +
    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +

and

    diff -rup qapi-gen-24-dc1833e3fb/test-qapi-types.h qapi-gen-27-9600b4638d/test-qapi-types.h
    --- qapi-gen-24-dc1833e3fb/test-qapi-types.h        2017-09-06 12:02:27.386461287 +0200
    +++ qapi-gen-27-9600b4638d/test-qapi-types.h        2017-09-06 12:55:02.365062236 +0200
    [...]
    @@ -486,6 +498,9 @@ struct NestedEnumsOne {

     void qapi_free_NestedEnumsOne(NestedEnumsOne *obj);

    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
     struct TestIfAlternate {
         QType type;
         union { /* union tag is @type */
    @@ -494,18 +509,42 @@ struct TestIfAlternate {
         } u;
     };

    +#if defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)
    +
    +
     void qapi_free_TestIfAlternate(TestIfAlternate *obj);

    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +
    +#endif /* defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT) */
    +
    +
Quoted 3 lines

Let's ignore this until we've made up our mind *how* to best generate conditionals.

Fixed, that was being extra cautious :)

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

PATCH v2 28/54 qapi: do not define enumeration value explicitely

In reply to Marc-André Lureau

The C standard has the initial value at 0 and the subsequent values incremented by 1. No need to set this explicitely.

This will prevent from artificial "gaps" when compiling out some enum values and having unnecessarily large MAX values & enums arrays.

---
 scripts/qapi.py | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
scripts/qapi.py +2 -5
index 52099332f1..9d075440d3 100644
@@ -1979,14 +1979,11 @@ typedef enum %(c_name)s {
 ''',
                 c_name=c_name(name))
 
-    i = 0
     for value in enum_values:
         ret += mcgen('''
-    %(c_enum)s = %(i)d,
+    %(c_enum)s,
 ''',
-                     c_enum=c_enum_const(name, value, prefix),
-                     i=i)
-        i += 1
+                     c_enum=c_enum_const(name, value, prefix))
 
     ret += mcgen('''
 } %(c_name)s;
Signature · 1 line
2.14.1.146.gd35faa819
Reviewed-by on v2 28/54
#86 lore raw

Re: [Qemu-devel] [PATCH v2 28/54] qapi: do not define enumeration value explicitely

Quoted 7 lines · Marc-André Lureau

The C standard has the initial value at 0 and the subsequent values incremented by 1. No need to set this explicitely.

This will prevent from artificial "gaps" when compiling out some enum values and having unnecessarily large MAX values & enums arrays.

Quoted 26 lines
---
  scripts/qapi.py | 7 ++-----
  1 file changed, 2 insertions(+), 5 deletions(-)
scripts/qapi.py +2 -5
index 52099332f1..9d075440d3 100644
@@ -1979,14 +1979,11 @@ typedef enum %(c_name)s {
  ''',
                  c_name=c_name(name))
 
-    i = 0
      for value in enum_values:
          ret += mcgen('''
-    %(c_enum)s = %(i)d,
+    %(c_enum)s,
  ''',
-                     c_enum=c_enum_const(name, value, prefix),
-                     i=i)
-        i += 1
+                     c_enum=c_enum_const(name, value, prefix))
 
      ret += mcgen('''
  } %(c_name)s;
#87 lore raw

Re: [Qemu-devel] [PATCH v2 28/54] qapi: do not define enumeration value explicitely

In reply to Marc-André Lureau
Quoted 5 lines · Marc-André Lureau

The C standard has the initial value at 0 and the subsequent values incremented by 1. No need to set this explicitely.

This will prevent from artificial "gaps" when compiling out some enum values and having unnecessarily large MAX values & enums arrays.

Yes, but it also risks entertaining mishaps like compiling this one

    typedef enum Color {
        COLOR_WHITE,

#if defined(NEED_CPU_H)
#if defined(TARGET_S390X)
COLOR_BLUE,
#endif /* defined(TARGET_S390X) */

#endif /* defined(NEED_CPU_H) */
        COLOR_BLACK,
    } Color;

in s390x-code (COLOR_BLACK = 2) and in target-independent code (COLOR_BLACK = 1), then linking the two together.

Quoted 26 lines
---
 scripts/qapi.py | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
scripts/qapi.py +2 -5
index 52099332f1..9d075440d3 100644
@@ -1979,14 +1979,11 @@ typedef enum %(c_name)s {
 ''',
                 c_name=c_name(name))
 
-    i = 0
     for value in enum_values:
         ret += mcgen('''
-    %(c_enum)s = %(i)d,
+    %(c_enum)s,
 ''',
-                     c_enum=c_enum_const(name, value, prefix),
-                     i=i)
-        i += 1
+                     c_enum=c_enum_const(name, value, prefix))
 
     ret += mcgen('''
 } %(c_name)s;
#88 lore raw

Re: [Qemu-devel] [PATCH v2 28/54] qapi: do not define enumeration value explicitely

----- Original Message -----

Quoted 16 lines
Quoted 5 lines · Marc-André Lureau

The C standard has the initial value at 0 and the subsequent values incremented by 1. No need to set this explicitely.

This will prevent from artificial "gaps" when compiling out some enum values and having unnecessarily large MAX values & enums arrays.

Yes, but it also risks entertaining mishaps like compiling this one

    typedef enum Color {
        COLOR_WHITE,

#if defined(NEED_CPU_H)
#if defined(TARGET_S390X)
COLOR_BLUE,
#endif /* defined(TARGET_S390X) */

Quoted 6 lines
#endif /* defined(NEED_CPU_H) */
        COLOR_BLACK,
    } Color;

in s390x-code (COLOR_BLACK = 2) and in target-independent code (COLOR_BLACK = 1), then linking the two together.

This is also true with other kind of types, like struct.

One of the main reason why we should have schemas for target-only and the NEED_CPU_H is a temporary working hack.

Quoted 28 lines
Quoted 27 lines
---
 scripts/qapi.py | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
scripts/qapi.py +2 -5
index 52099332f1..9d075440d3 100644
@@ -1979,14 +1979,11 @@ typedef enum %(c_name)s {
 ''',
                 c_name=c_name(name))
 
-    i = 0
     for value in enum_values:
         ret += mcgen('''
-    %(c_enum)s = %(i)d,
+    %(c_enum)s,
 ''',
-                     c_enum=c_enum_const(name, value, prefix),
-                     i=i)
-        i += 1
+                     c_enum=c_enum_const(name, value, prefix))
 
     ret += mcgen('''
 } %(c_name)s;
#89 lore raw

Re: [Qemu-devel] [PATCH v2 28/54] qapi: do not define enumeration value explicitely

Quoted 21 lines · Marc-André Lureau

----- Original Message -----

Quoted 20 lines
Quoted 5 lines · Marc-André Lureau

The C standard has the initial value at 0 and the subsequent values incremented by 1. No need to set this explicitely.

This will prevent from artificial "gaps" when compiling out some enum values and having unnecessarily large MAX values & enums arrays.

Yes, but it also risks entertaining mishaps like compiling this one

    typedef enum Color {
        COLOR_WHITE,

#if defined(NEED_CPU_H)
#if defined(TARGET_S390X)
COLOR_BLUE,
#endif /* defined(TARGET_S390X) */

#endif /* defined(NEED_CPU_H) */
        COLOR_BLACK,
    } Color;
Quoted 6 lines
Quoted 2 lines

in s390x-code (COLOR_BLACK = 2) and in target-independent code (COLOR_BLACK = 1), then linking the two together.

This is also true with other kind of types, like struct.

One of the main reason why we should have schemas for target-only and the NEED_CPU_H is a temporary working hack.

A temporary hack that's ugly or occasionally breaks in an obvious way is okay, but this is an open deathtrap. I'm afraid we need to rethink our short term conditional code generation strategy.

Stupidest solution that could possibly work: apply conditionals *only* to qmp-introspect.c, leave everything unconditional elsewhere. What do you think?

#90 lore raw

Re: [Qemu-devel] [PATCH v2 28/54] qapi: do not define enumeration value explicitely

Hi

----- Original Message -----

Quoted 31 lines
Quoted 21 lines · Marc-André Lureau

----- Original Message -----

Quoted 20 lines
Quoted 5 lines · Marc-André Lureau

The C standard has the initial value at 0 and the subsequent values incremented by 1. No need to set this explicitely.

This will prevent from artificial "gaps" when compiling out some enum values and having unnecessarily large MAX values & enums arrays.

Yes, but it also risks entertaining mishaps like compiling this one

    typedef enum Color {
        COLOR_WHITE,

#if defined(NEED_CPU_H)
#if defined(TARGET_S390X)
COLOR_BLUE,
#endif /* defined(TARGET_S390X) */

#endif /* defined(NEED_CPU_H) */
        COLOR_BLACK,
    } Color;
Quoted 7 lines
Quoted 2 lines

in s390x-code (COLOR_BLACK = 2) and in target-independent code (COLOR_BLACK = 1), then linking the two together.

This is also true with other kind of types, like struct.

One of the main reason why we should have schemas for target-only and the NEED_CPU_H is a temporary working hack.

Quoted 7 lines

A temporary hack that's ugly or occasionally breaks in an obvious way is okay, but this is an open deathtrap. I'm afraid we need to rethink our short term conditional code generation strategy.

Stupidest solution that could possibly work: apply conditionals *only* to qmp-introspect.c, leave everything unconditional elsewhere. What do you think?

That's not what I had in mind when I started. My first 45 loc approach would have saved us a lot of troubles :)

I would rather fix this, and split the schema. I'll investigate.

#91 lore raw

Re: [Qemu-devel] [PATCH v2 28/54] qapi: do not define enumeration value explicitely

Quoted 38 lines · Marc-André Lureau

Hi

----- Original Message -----

Quoted 35 lines
Quoted 21 lines · Marc-André Lureau

----- Original Message -----

Quoted 20 lines
Quoted 5 lines · Marc-André Lureau

The C standard has the initial value at 0 and the subsequent values incremented by 1. No need to set this explicitely.

This will prevent from artificial "gaps" when compiling out some enum values and having unnecessarily large MAX values & enums arrays.

Yes, but it also risks entertaining mishaps like compiling this one

    typedef enum Color {
        COLOR_WHITE,

#if defined(NEED_CPU_H)
#if defined(TARGET_S390X)
COLOR_BLUE,
#endif /* defined(TARGET_S390X) */

#endif /* defined(NEED_CPU_H) */
        COLOR_BLACK,
    } Color;
Quoted 7 lines
Quoted 2 lines

in s390x-code (COLOR_BLACK = 2) and in target-independent code (COLOR_BLACK = 1), then linking the two together.

This is also true with other kind of types, like struct.

One of the main reason why we should have schemas for target-only and the NEED_CPU_H is a temporary working hack.

A temporary hack that's ugly or occasionally breaks in an obvious way is okay, but this is an open deathtrap. I'm afraid we need to rethink our short term conditional code generation strategy.

Quoted 7 lines
Quoted 3 lines

Stupidest solution that could possibly work: apply conditionals *only* to qmp-introspect.c, leave everything unconditional elsewhere. What do you think?

That's not what I had in mind when I started. My first 45 loc approach would have saved us a lot of troubles :)

I would rather fix this, and split the schema. I'll investigate.

Beware of prerequisites escalating into "boil the ocean".

Don't get me wrong, I *want* the qapi monolith broken up. I also think applying conditionals everywhere would be neat, and save us quite a few silly stubs. But we need to identify intermedeate steps that are in reasonably easy reach.

Applying conditionals just to qmp-introspect.c could be such a step. It solves the "can't introspect whether compile-time conditional stuff is available" problem. It may not be the simplest solution for that problem, but it should be a stepping stone towards solving other problems.

On breaking up the monolith, just to avoid misunderstandings: I don't think we should split the schema into several independent schemas. Instead, we should have the QAPI generators generate split output.

An obvious and stupid split is one set of files per .json, where the headers include each other exactly like the .json do. By itself not enough to solve the poisoned symbol problem. Could become enough if we manage to move target-dependent stuff to separate .json.

We might need a smarter split.

Running a full generator once per generated file has always been stupid and slow, and the more files we generate, the stupider and slower it'll become. There's no reason a single generator run can't generate all the files. Requires a bit of Make wizardry, though.

#92 lore raw

PATCH v2 29/54 qapi: add 'if' to enum members

In reply to Marc-André Lureau
---
 scripts/qapi.py                         | 33 +++++++++++++++++++++++++++------
 tests/qapi-schema/enum-dict-member.err  |  1 -
 tests/qapi-schema/enum-dict-member.exit |  2 +-
 tests/qapi-schema/enum-dict-member.json |  3 +--
 tests/qapi-schema/enum-dict-member.out  |  4 ++++
 tests/qapi-schema/qapi-schema-test.json |  5 +++--
 tests/qapi-schema/qapi-schema-test.out  |  3 ++-
 tests/qapi-schema/test-qapi.py          |  4 +++-
 8 files changed, 41 insertions(+), 14 deletions(-)
scripts/qapi.py +27 -6
index 9d075440d3..9c7c01c11d 100644
@@ -729,6 +729,10 @@ def check_event(expr, info):
                allow_metas=meta)
 
 
+def enum_get_values(expr):
+    return [e if isinstance(e, str) else e['name'] for e in expr['data']]
+
+
 def check_union(expr, info):
     name = expr['union']
     base = expr.get('base')
@@ -788,7 +792,7 @@ def check_union(expr, info):
         # If the discriminator names an enum type, then all members
         # of 'data' must also be members of the enum type.
         if enum_define:
-            if key not in enum_define['data']:
+            if key not in enum_get_values(enum_define):
                 raise QAPISemError(info,
                                    "Discriminator value '%s' is not found in "
                                    "enum '%s'"
@@ -796,7 +800,7 @@ def check_union(expr, info):
 
     # If discriminator is user-defined, ensure all values are covered
     if enum_define:
-        for value in enum_define['data']:
+        for value in enum_get_values(enum_define):
             if value not in members.keys():
                 raise QAPISemError(info, "Union '%s' data missing '%s' branch"
                                    % (name, value))
@@ -827,7 +831,7 @@ def check_alternate(expr, info):
         if qtype == 'QTYPE_QSTRING':
             enum_expr = enum_types.get(value)
             if enum_expr:
-                for v in enum_expr['data']:
+                for v in enum_get_values(enum_expr):
                     if v in ['on', 'off']:
                         conflicting.add('QTYPE_QBOOL')
                     if re.match(r'[-+0-9.]', v): # lazy, could be tightened
@@ -857,6 +861,12 @@ def check_enum(expr, info):
         raise QAPISemError(info,
                            "Enum '%s' requires a string for 'prefix'" % name)
     for member in members:
+        if isinstance(member, dict):
+            if not 'name' in member:
+                raise QAPISemError(info, "Dictionary member of enum '%s' must "
+                                   "have a 'name' key" % name)
+            check_if(member, info)
+            member = member['name']
         check_name(info, "Member of enum '%s'" % name, member,
                    enum_member=True)
 
@@ -1145,12 +1155,15 @@ class QAPISchemaEnumType(QAPISchemaType):
     def member_names(self):
         return [v.name for v in self.values]
 
+    def members(self):
+        return [(v.name, v.ifcond) for v in self.values]
+
     def json_type(self):
         return 'string'
 
     def visit(self, visitor):
         visitor.visit_enum_type(self.name, self.info,
-                                self.member_names(), self.prefix, self.ifcond)
+                                self.members(), self.prefix, self.ifcond)
 
 
 class QAPISchemaArrayType(QAPISchemaType):
@@ -1274,9 +1287,11 @@ class QAPISchemaObjectType(QAPISchemaType):
 class QAPISchemaMember(object):
     role = 'member'
 
-    def __init__(self, name):
+    def __init__(self, name, ifcond=None):
         assert isinstance(name, str)
+        assert ifcond is None or isinstance(ifcond, str)
         self.name = name
+        self.ifcond = ifcond
         self.owner = None
 
     def set_owner(self, name):
@@ -1554,7 +1569,9 @@ class QAPISchema(object):
                                             qtype_values, 'QTYPE'))
 
     def _make_enum_members(self, values):
-        return [QAPISchemaMember(v) for v in values]
+        return [QAPISchemaMember(v['name'], v.get('if')) if isinstance(v, dict)
+                else QAPISchemaMember(v)
+                for v in values]
 
     def _make_implicit_enum_type(self, name, info, values, ifcond):
         # See also QAPISchemaObjectTypeMember._pretty_owner()
@@ -1950,6 +1967,8 @@ static const char *const %(c_name)s_array[] = {
 ''',
                 c_name=c_name(name))
     for value in values:
+        if isinstance(value, tuple):
+            value, ifcond = value
         index = c_enum_const(name, value, prefix)
         ret += mcgen('''
     [%(index)s] = "%(value)s",
@@ -1980,6 +1999,8 @@ typedef enum %(c_name)s {
                 c_name=c_name(name))
 
     for value in enum_values:
+        if isinstance(value, tuple):
+            value, ifcond = value
         ret += mcgen('''
     %(c_enum)s,
 ''',
tests/qapi-schema/enum-dict-member.err +0 -1
index 8ca146ea59..e69de29bb2 100644
@@ -1 +0,0 @@
-tests/qapi-schema/enum-dict-member.json:2: Member of enum 'MyEnum' requires a string name
tests/qapi-schema/enum-dict-member.exit +1 -1
index d00491fd7e..573541ac97 100644
@@ -1 +1 @@
-1
+0
tests/qapi-schema/enum-dict-member.json +1 -2
index 79672e0f09..b09a83061c 100644
@@ -1,2 +1 @@
-# we reject any enum member that is not a string
-{ 'enum': 'MyEnum', 'data': [ { 'value': 'str' } ] }
+{ 'enum': 'TestEnum', 'data': [ { 'name': 'foo' }, { 'name': 'bar' } ]}
tests/qapi-schema/enum-dict-member.out +4 -0
index e69de29bb2..cf8e3cce2b 100644
@@ -0,0 +1,4 @@
+enum QType ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist', 'qbool']
+    prefix QTYPE
+enum TestEnum ['foo', 'bar']
+object q_empty
tests/qapi-schema/qapi-schema-test.json +3 -2
index dc2c444fc1..ad2b405d83 100644
@@ -194,7 +194,8 @@
 { 'struct': 'TestIfStruct', 'data': { 'foo': 'int' },
   'if': 'defined(TEST_IF_STRUCT)' }
 
-{ 'enum': 'TestIfEnum', 'data': [ 'foo', 'bar' ],
+{ 'enum': 'TestIfEnum', 'data':
+  [ 'foo', { 'name' : 'bar', 'if': 'defined(TEST_IF_ENUM_BAR)' } ],
   'if': 'defined(TEST_IF_ENUM)' }
 
 { 'union': 'TestIfUnion', 'data': { 'foo': 'TestStruct' },
@@ -203,7 +204,7 @@
 { 'alternate': 'TestIfAlternate', 'data': { 'foo': 'int', 'bar': 'TestStruct' },
   'if': 'defined(TEST_IF_ALT) && defined(TEST_IF_STRUCT)' }
 
-{ 'command': 'TestIfCmd', 'data': { 'foo': 'TestIfStruct' },
+{ 'command': 'TestIfCmd', 'data': { 'foo': 'TestIfStruct', 'bar': 'TestIfEnum' },
   'if': 'defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)' }
 
 { 'event': 'TestIfEvent', 'data': { 'foo': 'TestIfStruct' },
tests/qapi-schema/qapi-schema-test.out +2 -1
index fc5fd25f1b..211c367632 100644
@@ -60,7 +60,7 @@ alternate TestIfAlternate
 command TestIfCmd q_obj_TestIfCmd-arg -> None
    gen=True success_response=True boxed=False
     if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
-enum TestIfEnum ['foo', 'bar']
+enum TestIfEnum ['foo', ('bar', 'defined(TEST_IF_ENUM_BAR)')]
     if defined(TEST_IF_ENUM)
 event TestIfEvent q_obj_TestIfEvent-arg
    boxed=False
@@ -197,6 +197,7 @@ object q_obj_EVENT_D-arg
     member enum3: EnumOne optional=True
 object q_obj_TestIfCmd-arg
     member foo: TestIfStruct optional=False
+    member bar: TestIfEnum optional=False
     if defined(TEST_IF_CMD) && defined(TEST_IF_STRUCT)
 object q_obj_TestIfEvent-arg
     member foo: TestIfStruct optional=False
tests/qapi-schema/test-qapi.py +3 -1
index 17fd975812..70054848f0 100644
@@ -18,7 +18,9 @@ import sys
 
 class QAPISchemaTestVisitor(QAPISchemaVisitor):
     def visit_enum_type(self, name, info, values, prefix, ifcond):
-        print 'enum %s %s' % (name, values)
+        values = ', '.join(["'%s'" % v[0] if not v[1] else str(v)
+                            for v in values])
+        print 'enum %s [%s]' % (name, values)
         if prefix:
             print '    prefix %s' % prefix
         self._print_if(ifcond)
Signature · 1 line
2.14.1.146.gd35faa819