Skip to contentSkip to conversation

drop qapi nested structs

PATCH Superseded Eric Blake 3 participants 62 messages Sep 19, 2014 – Mar 23, 2015

v4 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

Eric Blake

author
#0 lore raw

v4 cover drop qapi nested structs

After dragging my feet due to some libvirt work, I've finally revived this patch series as promised.

v3 was here:
https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg00725.html

v4:
update commit message style [Markus]
add docs (patches 3-4 are new) [Markus]
lots of new tests (spread among 5, 7, 9, 11, 12)
add comments to all new tests [Markus]
rework check for valid expressions (patches 8, 10 are pretty much
new, later patches rebased and simplified as a result)
rebase to master
fix tests to match file name (broken test in v3 patch 7 now fixed
in patch 12)
drop expr_name (v3 patch 8); series now validates expressions
earlier (patch 8)
consolidate '**' magic, and reject 'gen':'yes' in commands (patch

    14 is new)

probably other stuff - it's been more than a month, so reviewers
will probably want to start from scratch anyways :)

v3:
No code changes, but fix mis-send of 11-14 [Peter]

v2:
New patches: 1-2, 5-9
consistent TAB usage in Makefile [Fam]
catch more bad coding constructs, and test them
avoid code duplication in type validity checks (patch 14 [former 7] is
simpler because of patch 9)

Eric Blake (19):
qapi: Consistent whitespace in tests/Makefile
qapi: Ignore files created during make check
qapi: Update docs given recent event, spacing fixes
qapi: Document type-safety considerations
qapi: Add some enum tests
qapi: Better error messages for bad enums
qapi: Add some expr tests
qapi: Better error messages for bad expressions
qapi: Add tests of redefined expressions
qapi: Better error messages for duplicated expressions
qapi: Add tests of type bypass
qapi: Add some type check tests
qapi: More rigourous checking of types
qapi: More rigorous checking for type safety bypass
qapi: Merge UserDefTwo and UserDefNested in tests
qapi: Drop tests for inline subtypes
qapi: Drop inline subtype in query-version
qapi: Drop inline subtype in query-pci
qapi: Drop support for inline subtypes

 docs/qapi-code-gen.txt                       | 349 +++++++++++++++++++++++----
 hmp.c                                        |  28 +--
 hw/pci/pci.c                                 |  42 ++--
 qapi-schema.json                             |  96 +++++---
 qapi/common.json                             |  26 +-
 qmp.c                                        |   9 +-
 scripts/qapi-commands.py                     |   8 +-
 scripts/qapi-event.py                        |   4 +-
 scripts/qapi-types.py                        |   9 +-
 scripts/qapi-visit.py                        |  37 +--
 scripts/qapi.py                              | 261 ++++++++++++++++----
 tests/.gitignore                             |   3 +
 tests/Makefile                               |  43 ++--
 tests/qapi-schema/bad-type-dict.err          |   1 +
 tests/qapi-schema/bad-type-dict.exit         |   1 +
 tests/qapi-schema/bad-type-dict.json         |   2 +
 tests/qapi-schema/bad-type-dict.out          |   0
 tests/qapi-schema/bad-type-int.err           |   1 +
 tests/qapi-schema/bad-type-int.exit          |   1 +
 tests/qapi-schema/bad-type-int.json          |   3 +
 tests/qapi-schema/bad-type-int.out           |   0
 tests/qapi-schema/data-array-empty.err       |   1 +
 tests/qapi-schema/data-array-empty.exit      |   1 +
 tests/qapi-schema/data-array-empty.json      |   2 +
 tests/qapi-schema/data-array-empty.out       |   0
 tests/qapi-schema/data-array-unknown.err     |   1 +
 tests/qapi-schema/data-array-unknown.exit    |   1 +
 tests/qapi-schema/data-array-unknown.json    |   2 +
 tests/qapi-schema/data-array-unknown.out     |   0
 tests/qapi-schema/data-int.err               |   1 +
 tests/qapi-schema/data-int.exit              |   1 +
 tests/qapi-schema/data-int.json              |   2 +
 tests/qapi-schema/data-int.out               |   0
 tests/qapi-schema/data-member-array-bad.err  |   1 +
 tests/qapi-schema/data-member-array-bad.exit |   1 +
 tests/qapi-schema/data-member-array-bad.json |   2 +
 tests/qapi-schema/data-member-array-bad.out  |   0
 tests/qapi-schema/data-member-array.err      |   0
 tests/qapi-schema/data-member-array.exit     |   1 +
 tests/qapi-schema/data-member-array.json     |   4 +
 tests/qapi-schema/data-member-array.out      |   5 +
 tests/qapi-schema/data-member-unknown.err    |   1 +
 tests/qapi-schema/data-member-unknown.exit   |   1 +
 tests/qapi-schema/data-member-unknown.json   |   2 +
 tests/qapi-schema/data-member-unknown.out    |   0
 tests/qapi-schema/data-unknown.err           |   1 +
 tests/qapi-schema/data-unknown.exit          |   1 +
 tests/qapi-schema/data-unknown.json          |   2 +
 tests/qapi-schema/data-unknown.out           |   0
 tests/qapi-schema/double-data.err            |   1 +
 tests/qapi-schema/double-data.exit           |   1 +
 tests/qapi-schema/double-data.json           |   2 +
 tests/qapi-schema/double-data.out            |   0
 tests/qapi-schema/double-type.err            |   1 +
 tests/qapi-schema/double-type.exit           |   1 +
 tests/qapi-schema/double-type.json           |   2 +
 tests/qapi-schema/double-type.out            |   0
 tests/qapi-schema/enum-clash-member.err      |   1 +
 tests/qapi-schema/enum-clash-member.exit     |   1 +
 tests/qapi-schema/enum-clash-member.json     |   2 +
 tests/qapi-schema/enum-clash-member.out      |   0
 tests/qapi-schema/enum-dict-member.err       |   1 +
 tests/qapi-schema/enum-dict-member.exit      |   1 +
 tests/qapi-schema/enum-dict-member.json      |   2 +
 tests/qapi-schema/enum-dict-member.out       |   0
 tests/qapi-schema/enum-empty.err             |   0
 tests/qapi-schema/enum-empty.exit            |   1 +
 tests/qapi-schema/enum-empty.json            |   2 +
 tests/qapi-schema/enum-empty.out             |   3 +
 tests/qapi-schema/enum-int-member.err        |   1 +
 tests/qapi-schema/enum-int-member.exit       |   1 +
 tests/qapi-schema/enum-int-member.json       |   3 +
 tests/qapi-schema/enum-int-member.out        |   0
 tests/qapi-schema/enum-max-member.err        |   1 +
 tests/qapi-schema/enum-max-member.exit       |   1 +
 tests/qapi-schema/enum-max-member.json       |   3 +
 tests/qapi-schema/enum-max-member.out        |   0
 tests/qapi-schema/enum-missing-data.err      |   1 +
 tests/qapi-schema/enum-missing-data.exit     |   1 +
 tests/qapi-schema/enum-missing-data.json     |   2 +
 tests/qapi-schema/enum-missing-data.out      |   0
 tests/qapi-schema/enum-wrong-data.err        |   1 +
 tests/qapi-schema/enum-wrong-data.exit       |   1 +
 tests/qapi-schema/enum-wrong-data.json       |   2 +
 tests/qapi-schema/enum-wrong-data.out        |   0
 tests/qapi-schema/event-nest-struct.err      |   2 +-
 tests/qapi-schema/indented-expr.json         |   4 +-
 tests/qapi-schema/indented-expr.out          |   2 +-
 tests/qapi-schema/missing-type.err           |   1 +
 tests/qapi-schema/missing-type.exit          |   1 +
 tests/qapi-schema/missing-type.json          |   2 +
 tests/qapi-schema/missing-type.out           |   0
 tests/qapi-schema/nested-struct-data.err     |   1 +
 tests/qapi-schema/nested-struct-data.exit    |   1 +
 tests/qapi-schema/nested-struct-data.json    |   4 +
 tests/qapi-schema/nested-struct-data.out     |   0
 tests/qapi-schema/nested-struct-returns.err  |   1 +
 tests/qapi-schema/nested-struct-returns.exit |   1 +
 tests/qapi-schema/nested-struct-returns.json |   3 +
 tests/qapi-schema/nested-struct-returns.out  |   0
 tests/qapi-schema/qapi-schema-test.json      |  18 +-
 tests/qapi-schema/qapi-schema-test.out       |  10 +-
 tests/qapi-schema/redefined-builtin.err      |   1 +
 tests/qapi-schema/redefined-builtin.exit     |   1 +
 tests/qapi-schema/redefined-builtin.json     |   2 +
 tests/qapi-schema/redefined-builtin.out      |   0
 tests/qapi-schema/redefined-command.err      |   1 +
 tests/qapi-schema/redefined-command.exit     |   1 +
 tests/qapi-schema/redefined-command.json     |   3 +
 tests/qapi-schema/redefined-command.out      |   0
 tests/qapi-schema/redefined-event.err        |   1 +
 tests/qapi-schema/redefined-event.exit       |   1 +
 tests/qapi-schema/redefined-event.json       |   3 +
 tests/qapi-schema/redefined-event.out        |   0
 tests/qapi-schema/redefined-type.err         |   1 +
 tests/qapi-schema/redefined-type.exit        |   1 +
 tests/qapi-schema/redefined-type.json        |   3 +
 tests/qapi-schema/redefined-type.out         |   0
 tests/qapi-schema/returns-array-bad.err      |   1 +
 tests/qapi-schema/returns-array-bad.exit     |   1 +
 tests/qapi-schema/returns-array-bad.json     |   2 +
 tests/qapi-schema/returns-array-bad.out      |   0
 tests/qapi-schema/returns-int.err            |   0
 tests/qapi-schema/returns-int.exit           |   1 +
 tests/qapi-schema/returns-int.json           |   2 +
 tests/qapi-schema/returns-int.out            |   3 +
 tests/qapi-schema/returns-unknown.err        |   1 +
 tests/qapi-schema/returns-unknown.exit       |   1 +
 tests/qapi-schema/returns-unknown.json       |   2 +
 tests/qapi-schema/returns-unknown.out        |   0
 tests/qapi-schema/type-bypass-bad-gen.err    |   1 +
 tests/qapi-schema/type-bypass-bad-gen.exit   |   1 +
 tests/qapi-schema/type-bypass-bad-gen.json   |   2 +
 tests/qapi-schema/type-bypass-bad-gen.out    |   0
 tests/qapi-schema/type-bypass-no-gen.err     |   1 +
 tests/qapi-schema/type-bypass-no-gen.exit    |   1 +
 tests/qapi-schema/type-bypass-no-gen.json    |   2 +
 tests/qapi-schema/type-bypass-no-gen.out     |   0
 tests/qapi-schema/type-bypass.err            |   0
 tests/qapi-schema/type-bypass.exit           |   1 +
 tests/qapi-schema/type-bypass.json           |   2 +
 tests/qapi-schema/type-bypass.out            |   3 +
 tests/qapi-schema/unknown-expr-key.err       |   1 +
 tests/qapi-schema/unknown-expr-key.exit      |   1 +
 tests/qapi-schema/unknown-expr-key.json      |   2 +
 tests/qapi-schema/unknown-expr-key.out       |   0
 tests/test-qmp-commands.c                    |  35 +--
 tests/test-qmp-input-strict.c                |  19 +-
 tests/test-qmp-input-visitor.c               |  25 +-
 tests/test-qmp-output-visitor.c              |  64 ++---
 tests/test-visitor-serialization.c           |  84 ++++---
 151 files changed, 979 insertions(+), 348 deletions(-)
 create mode 100644 tests/qapi-schema/bad-type-dict.err
 create mode 100644 tests/qapi-schema/bad-type-dict.exit
 create mode 100644 tests/qapi-schema/bad-type-dict.json
 create mode 100644 tests/qapi-schema/bad-type-dict.out
 create mode 100644 tests/qapi-schema/bad-type-int.err
 create mode 100644 tests/qapi-schema/bad-type-int.exit
 create mode 100644 tests/qapi-schema/bad-type-int.json
 create mode 100644 tests/qapi-schema/bad-type-int.out
 create mode 100644 tests/qapi-schema/data-array-empty.err
 create mode 100644 tests/qapi-schema/data-array-empty.exit
 create mode 100644 tests/qapi-schema/data-array-empty.json
 create mode 100644 tests/qapi-schema/data-array-empty.out
 create mode 100644 tests/qapi-schema/data-array-unknown.err
 create mode 100644 tests/qapi-schema/data-array-unknown.exit
 create mode 100644 tests/qapi-schema/data-array-unknown.json
 create mode 100644 tests/qapi-schema/data-array-unknown.out
 create mode 100644 tests/qapi-schema/data-int.err
 create mode 100644 tests/qapi-schema/data-int.exit
 create mode 100644 tests/qapi-schema/data-int.json
 create mode 100644 tests/qapi-schema/data-int.out
 create mode 100644 tests/qapi-schema/data-member-array-bad.err
 create mode 100644 tests/qapi-schema/data-member-array-bad.exit
 create mode 100644 tests/qapi-schema/data-member-array-bad.json
 create mode 100644 tests/qapi-schema/data-member-array-bad.out
 create mode 100644 tests/qapi-schema/data-member-array.err
 create mode 100644 tests/qapi-schema/data-member-array.exit
 create mode 100644 tests/qapi-schema/data-member-array.json
 create mode 100644 tests/qapi-schema/data-member-array.out
 create mode 100644 tests/qapi-schema/data-member-unknown.err
 create mode 100644 tests/qapi-schema/data-member-unknown.exit
 create mode 100644 tests/qapi-schema/data-member-unknown.json
 create mode 100644 tests/qapi-schema/data-member-unknown.out
 create mode 100644 tests/qapi-schema/data-unknown.err
 create mode 100644 tests/qapi-schema/data-unknown.exit
 create mode 100644 tests/qapi-schema/data-unknown.json
 create mode 100644 tests/qapi-schema/data-unknown.out
 create mode 100644 tests/qapi-schema/double-data.err
 create mode 100644 tests/qapi-schema/double-data.exit
 create mode 100644 tests/qapi-schema/double-data.json
 create mode 100644 tests/qapi-schema/double-data.out
 create mode 100644 tests/qapi-schema/double-type.err
 create mode 100644 tests/qapi-schema/double-type.exit
 create mode 100644 tests/qapi-schema/double-type.json
 create mode 100644 tests/qapi-schema/double-type.out
 create mode 100644 tests/qapi-schema/enum-clash-member.err
 create mode 100644 tests/qapi-schema/enum-clash-member.exit
 create mode 100644 tests/qapi-schema/enum-clash-member.json
 create mode 100644 tests/qapi-schema/enum-clash-member.out
 create mode 100644 tests/qapi-schema/enum-dict-member.err
 create mode 100644 tests/qapi-schema/enum-dict-member.exit
 create mode 100644 tests/qapi-schema/enum-dict-member.json
 create mode 100644 tests/qapi-schema/enum-dict-member.out
 create mode 100644 tests/qapi-schema/enum-empty.err
 create mode 100644 tests/qapi-schema/enum-empty.exit
 create mode 100644 tests/qapi-schema/enum-empty.json
 create mode 100644 tests/qapi-schema/enum-empty.out
 create mode 100644 tests/qapi-schema/enum-int-member.err
 create mode 100644 tests/qapi-schema/enum-int-member.exit
 create mode 100644 tests/qapi-schema/enum-int-member.json
 create mode 100644 tests/qapi-schema/enum-int-member.out
 create mode 100644 tests/qapi-schema/enum-max-member.err
 create mode 100644 tests/qapi-schema/enum-max-member.exit
 create mode 100644 tests/qapi-schema/enum-max-member.json
 create mode 100644 tests/qapi-schema/enum-max-member.out
 create mode 100644 tests/qapi-schema/enum-missing-data.err
 create mode 100644 tests/qapi-schema/enum-missing-data.exit
 create mode 100644 tests/qapi-schema/enum-missing-data.json
 create mode 100644 tests/qapi-schema/enum-missing-data.out
 create mode 100644 tests/qapi-schema/enum-wrong-data.err
 create mode 100644 tests/qapi-schema/enum-wrong-data.exit
 create mode 100644 tests/qapi-schema/enum-wrong-data.json
 create mode 100644 tests/qapi-schema/enum-wrong-data.out
 create mode 100644 tests/qapi-schema/missing-type.err
 create mode 100644 tests/qapi-schema/missing-type.exit
 create mode 100644 tests/qapi-schema/missing-type.json
 create mode 100644 tests/qapi-schema/missing-type.out
 create mode 100644 tests/qapi-schema/nested-struct-data.err
 create mode 100644 tests/qapi-schema/nested-struct-data.exit
 create mode 100644 tests/qapi-schema/nested-struct-data.json
 create mode 100644 tests/qapi-schema/nested-struct-data.out
 create mode 100644 tests/qapi-schema/nested-struct-returns.err
 create mode 100644 tests/qapi-schema/nested-struct-returns.exit
 create mode 100644 tests/qapi-schema/nested-struct-returns.json
 create mode 100644 tests/qapi-schema/nested-struct-returns.out
 create mode 100644 tests/qapi-schema/redefined-builtin.err
 create mode 100644 tests/qapi-schema/redefined-builtin.exit
 create mode 100644 tests/qapi-schema/redefined-builtin.json
 create mode 100644 tests/qapi-schema/redefined-builtin.out
 create mode 100644 tests/qapi-schema/redefined-command.err
 create mode 100644 tests/qapi-schema/redefined-command.exit
 create mode 100644 tests/qapi-schema/redefined-command.json
 create mode 100644 tests/qapi-schema/redefined-command.out
 create mode 100644 tests/qapi-schema/redefined-event.err
 create mode 100644 tests/qapi-schema/redefined-event.exit
 create mode 100644 tests/qapi-schema/redefined-event.json
 create mode 100644 tests/qapi-schema/redefined-event.out
 create mode 100644 tests/qapi-schema/redefined-type.err
 create mode 100644 tests/qapi-schema/redefined-type.exit
 create mode 100644 tests/qapi-schema/redefined-type.json
 create mode 100644 tests/qapi-schema/redefined-type.out
 create mode 100644 tests/qapi-schema/returns-array-bad.err
 create mode 100644 tests/qapi-schema/returns-array-bad.exit
 create mode 100644 tests/qapi-schema/returns-array-bad.json
 create mode 100644 tests/qapi-schema/returns-array-bad.out
 create mode 100644 tests/qapi-schema/returns-int.err
 create mode 100644 tests/qapi-schema/returns-int.exit
 create mode 100644 tests/qapi-schema/returns-int.json
 create mode 100644 tests/qapi-schema/returns-int.out
 create mode 100644 tests/qapi-schema/returns-unknown.err
 create mode 100644 tests/qapi-schema/returns-unknown.exit
 create mode 100644 tests/qapi-schema/returns-unknown.json
 create mode 100644 tests/qapi-schema/returns-unknown.out
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.err
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.exit
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.json
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.out
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.err
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.exit
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.json
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.out
 create mode 100644 tests/qapi-schema/type-bypass.err
 create mode 100644 tests/qapi-schema/type-bypass.exit
 create mode 100644 tests/qapi-schema/type-bypass.json
 create mode 100644 tests/qapi-schema/type-bypass.out
 create mode 100644 tests/qapi-schema/unknown-expr-key.err
 create mode 100644 tests/qapi-schema/unknown-expr-key.exit
 create mode 100644 tests/qapi-schema/unknown-expr-key.json
 create mode 100644 tests/qapi-schema/unknown-expr-key.out
Signature · 1 line
1.9.3
author
#1 lore raw

PATCH v4 1/19 qapi: Consistent whitespace in tests/Makefile

tests/Makefile had a mix of TAB vs. 8-space indentation; given that it is a Makefile, TAB is more idiomatic even though in these particular cases the choice of whitespace didn't matter.

---
 tests/Makefile | 32 ++++++++++++++++----------------
 1 file changed, 16 insertions(+), 16 deletions(-)
tests/Makefile +16 -16
index a5e3d0c..976388a 100644
@@ -195,23 +195,23 @@ $(foreach target,$(SYSEMU_TARGET_LIST), \
     $(eval check-qtest-$(target)-y += tests/qom-test$(EXESUF)))
 
 check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
-        comments.json empty.json funny-char.json indented-expr.json \
-        missing-colon.json missing-comma-list.json \
-        missing-comma-object.json non-objects.json \
-        qapi-schema-test.json quoted-structural-chars.json \
-        trailing-comma-list.json trailing-comma-object.json \
-        unclosed-list.json unclosed-object.json unclosed-string.json \
-        duplicate-key.json union-invalid-base.json flat-union-no-base.json \
-        flat-union-invalid-discriminator.json \
-        flat-union-invalid-branch-key.json flat-union-reverse-define.json \
-        flat-union-string-discriminator.json \
-        include-simple.json include-relpath.json include-format-err.json \
-        include-non-file.json include-no-file.json include-before-err.json \
-        include-nested-err.json include-self-cycle.json include-cycle.json \
-        include-repetition.json event-nest-struct.json)
+	comments.json empty.json funny-char.json indented-expr.json \
+	missing-colon.json missing-comma-list.json \
+	missing-comma-object.json non-objects.json \
+	qapi-schema-test.json quoted-structural-chars.json \
+	trailing-comma-list.json trailing-comma-object.json \
+	unclosed-list.json unclosed-object.json unclosed-string.json \
+	duplicate-key.json union-invalid-base.json flat-union-no-base.json \
+	flat-union-invalid-discriminator.json \
+	flat-union-invalid-branch-key.json flat-union-reverse-define.json \
+	flat-union-string-discriminator.json \
+	include-simple.json include-relpath.json include-format-err.json \
+	include-non-file.json include-no-file.json include-before-err.json \
+	include-nested-err.json include-self-cycle.json include-cycle.json \
+	include-repetition.json event-nest-struct.json)
 
 GENERATED_HEADERS += tests/test-qapi-types.h tests/test-qapi-visit.h \
-                     tests/test-qmp-commands.h tests/test-qapi-event.h
+		     tests/test-qmp-commands.h tests/test-qapi-event.h
 
 test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
 	tests/check-qlist.o tests/check-qfloat.o tests/check-qjson.o \
@@ -223,7 +223,7 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
 	tests/test-opts-visitor.o tests/test-qmp-event.o
 
 test-qapi-obj-y = tests/test-qapi-visit.o tests/test-qapi-types.o \
-                  tests/test-qapi-event.o
+		  tests/test-qapi-event.o
 
 $(test-obj-y): QEMU_INCLUDES += -Itests
 QEMU_CFLAGS += -I$(SRC_PATH)/tests
Signature · 1 line
1.9.3
author
#3 lore raw

PATCH v4 2/19 qapi: Ignore files created during make check

In reply to Eric Blake

After an in-tree build and run of 'make check-{qapi-schema,unit}', I noticed some leftover files.

---
 tests/.gitignore | 3 +++
 1 file changed, 3 insertions(+)
tests/.gitignore +3 -0
index c71c110..e2e4957 100644
@@ -14,11 +14,14 @@ test-int128
 test-iov
 test-mul64
 test-opts-visitor
+test-qapi-event.[ch]
 test-qapi-types.[ch]
 test-qapi-visit.[ch]
 test-qdev-global-props
+test-qemu-opts
 test-qmp-commands
 test-qmp-commands.h
+test-qmp-event
 test-qmp-input-strict
 test-qmp-input-visitor
 test-qmp-marshal.c
Signature · 1 line
1.9.3
author
#5 lore raw

PATCH v4 3/19 qapi: Update docs given recent event, spacing fixes

In reply to Eric Blake

Commit 21cd70d added event support but didn't document what the generated code looks like. Commit 05dfb26 removed some unwanted spaces in the generated code, but didn't reflect those changes into the documentation. Finally, the docs start with a big disclaimer about QMP not using QAPI yet, which feels rather stale.

---
 docs/qapi-code-gen.txt | 100 +++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 80 insertions(+), 20 deletions(-)
docs/qapi-code-gen.txt +80 -20
index a6197a9..8313ba6 100644
@@ -1,10 +1,5 @@
 = How to use the QAPI code generator =
 
-* Note: as of this writing, QMP does not use QAPI. Eventually QMP
-commands will be converted to use QAPI internally. The following
-information describes QMP/QAPI as it will exist after the
-conversion.
-
 QAPI is a native C API within QEMU which provides management-level
 functionality to internal/external users. For external
 users/processes, this interface is made available by a JSON-based
@@ -19,7 +14,7 @@ marshaling/dispatch code for the guest agent server running in the
 guest.
 
 This document will describe how the schemas, scripts, and resulting
-code is used.
+code are used.
 
 
 == QMP/Guest agent schema ==
@@ -234,6 +229,7 @@ Resulting in this JSON object:
   "data": { "b": "test string" },
   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
 
+
 == Code generation ==
 
 Schemas are fed into 3 scripts to generate all the code/files that, paired
@@ -256,6 +252,8 @@ command which takes that type as a parameter and returns the same type:
       'data':    {'arg1': 'UserDefOne'},
       'returns': 'UserDefOne' }
 
+    { 'event': 'MY_EVENT' }
+
 === scripts/qapi-types.py ===
 
 Used to generate the C types defined by a schema. The following files are
@@ -277,7 +275,7 @@ Example:
     $ cat qapi-generated/example-qapi-types.c
 [Uninteresting stuff omitted...]
 
-    void qapi_free_UserDefOneList(UserDefOneList * obj)
+    void qapi_free_UserDefOneList(UserDefOneList *obj)
     {
         QapiDeallocVisitor *md;
         Visitor *v;
@@ -292,7 +290,7 @@ Example:
         qapi_dealloc_visitor_cleanup(md);
     }
 
-    void qapi_free_UserDefOne(UserDefOne * obj)
+    void qapi_free_UserDefOne(UserDefOne *obj)
     {
         QapiDeallocVisitor *md;
         Visitor *v;
@@ -331,11 +329,11 @@ Example:
     struct UserDefOne
     {
         int64_t integer;
-        char * string;
+        char *string;
     };
 
-    void qapi_free_UserDefOneList(UserDefOneList * obj);
-    void qapi_free_UserDefOne(UserDefOne * obj);
+    void qapi_free_UserDefOneList(UserDefOneList *obj);
+    void qapi_free_UserDefOne(UserDefOne *obj);
 
     #endif
 
@@ -364,7 +362,7 @@ Example:
     $ cat qapi-generated/example-qapi-visit.c
 [Uninteresting stuff omitted...]
 
-    static void visit_type_UserDefOne_fields(Visitor *m, UserDefOne ** obj, Error **errp)
+    static void visit_type_UserDefOne_fields(Visitor *m, UserDefOne **obj, Error **errp)
     {
         Error *err = NULL;
         visit_type_int(m, &(*obj)->integer, "integer", &err);
@@ -380,7 +378,7 @@ Example:
         error_propagate(errp, err);
     }
 
-    void visit_type_UserDefOne(Visitor *m, UserDefOne ** obj, const char *name, Error **errp)
+    void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp)
     {
         Error *err = NULL;
 
@@ -394,7 +392,7 @@ Example:
         error_propagate(errp, err);
     }
 
-    void visit_type_UserDefOneList(Visitor *m, UserDefOneList ** obj, const char *name, Error **errp)
+    void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp)
     {
         Error *err = NULL;
         GenericList *i, **prev;
@@ -427,8 +425,8 @@ Example:
 
 [Visitors for builtin types omitted...]
 
-    void visit_type_UserDefOne(Visitor *m, UserDefOne ** obj, const char *name, Error **errp);
-    void visit_type_UserDefOneList(Visitor *m, UserDefOneList ** obj, const char *name, Error **errp);
+    void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
+    void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);
 
     #endif
 
@@ -451,10 +449,12 @@ $(prefix)qmp-commands.h: Function prototypes for the QMP commands
 
 Example:
 
+    $ python scripts/qapi-commands.py --output-dir="qapi-generated"
+    --prefix="example-" --input-file=example-schema.json
     $ cat qapi-generated/example-qmp-marshal.c
 [Uninteresting stuff omitted...]
 
-    static void qmp_marshal_output_my_command(UserDefOne * ret_in, QObject **ret_out, Error **errp)
+    static void qmp_marshal_output_my_command(UserDefOne *ret_in, QObject **ret_out, Error **errp)
     {
         Error *local_err = NULL;
         QmpOutputVisitor *mo = qmp_output_visitor_new();
@@ -480,11 +480,11 @@ Example:
     static void qmp_marshal_input_my_command(QDict *args, QObject **ret, Error **errp)
     {
         Error *local_err = NULL;
-        UserDefOne * retval = NULL;
+        UserDefOne *retval = NULL;
         QmpInputVisitor *mi = qmp_input_visitor_new_strict(QOBJECT(args));
         QapiDeallocVisitor *md;
         Visitor *v;
-        UserDefOne * arg1 = NULL;
+        UserDefOne *arg1 = NULL;
 
         v = qmp_input_get_visitor(mi);
         visit_type_UserDefOne(v, &arg1, "arg1", &local_err);
@@ -525,6 +525,66 @@ Example:
     #include "qapi/qmp/qdict.h"
     #include "qapi/error.h"
 
-    UserDefOne * qmp_my_command(UserDefOne * arg1, Error **errp);
+    UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
+
+    #endif
+
+=== scripts/qapi-event.py ===
+
+Used to generate the event-related C code defined by a schema. The
+following files are created:
+
+$(prefix)qapi-event.h - Function prototypes for each event type, plus an
+                        enumeration of all event names
+$(prefix)qapi-event.c - Implementation of functions to send an event
+
+Example:
+
+    $ python scripts/qapi-event.py --output-dir="qapi-generated"
+    --prefix="example-" --input-file=example-schema.json
+    $ cat qapi-generated/example-qapi-event.c
+[Uninteresting stuff omitted...]
+
+    void qapi_event_send_my_event(Error **errp)
+    {
+        QDict *qmp;
+        Error *local_err = NULL;
+        QMPEventFuncEmit emit;
+        emit = qmp_event_get_func_emit();
+        if (!emit) {
+            return;
+        }
+
+        qmp = qmp_event_build_dict("MY_EVENT");
+
+        emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &local_err);
+
+        error_propagate(errp, local_err);
+        QDECREF(qmp);
+    }
+
+    const char *EXAMPLE_QAPIEvent_lookup[] = {
+        "MY_EVENT",
+        NULL,
+    };
+    $ cat qapi-generated/example-qapi-event.h
+[Uninteresting stuff omitted...]
+
+    #ifndef EXAMPLE_QAPI_EVENT_H
+    #define EXAMPLE_QAPI_EVENT_H
+
+    #include "qapi/error.h"
+    #include "qapi/qmp/qdict.h"
+    #include "example-qapi-types.h"
+
+
+    void qapi_event_send_my_event(Error **errp);
+
+    extern const char *EXAMPLE_QAPIEvent_lookup[];
+    typedef enum EXAMPLE_QAPIEvent
+    {
+        EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
+        EXAMPLE_QAPI_EVENT_MAX = 1,
+    } EXAMPLE_QAPIEvent;
 
     #endif
Signature · 1 line
1.9.3
Reviewed-by on v4 3/19
#6 lore raw

Re: [Qemu-devel] [PATCH v4 03/19] qapi: Update docs given recent event, spacing fixes

Quoted 7 lines · Eric Blake

Commit 21cd70d added event support but didn't document what the generated code looks like. Commit 05dfb26 removed some unwanted spaces in the generated code, but didn't reflect those changes into the documentation. Finally, the docs start with a big disclaimer about QMP not using QAPI yet, which feels rather stale.

author
#7 lore raw

PATCH v4 4/19 qapi: Document type-safety considerations

In reply to Eric Blake

Go into more details about the various types of valid expressions in a qapi schema, including tweaks to document fixes being done later in the current patch series.

---
 docs/qapi-code-gen.txt | 249 ++++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 217 insertions(+), 32 deletions(-)
docs/qapi-code-gen.txt +217 -32
index 8313ba6..3a79629 100644
@@ -22,35 +22,136 @@ code are used.
 This file defines the types, commands, and events used by QMP.  It should
 fully describe the interface used by QMP.
 
-This file is designed to be loosely based on JSON although it's technically
-executable Python.  While dictionaries are used, they are parsed as
-OrderedDicts so that ordering is preserved.
+A QAPI file is designed to be loosely based on JSON although it's
+technically executable Python.  A valid QAPI schema consists of a list
+of top-level expressions, with no commas between them.  While
+dictionaries are used, they are parsed as OrderedDicts so that
+ordering is preserved; ordering doesn't matter for top-level
+expressions, but does matter within 'data' members.  QAPI input is
+written using 'single quotes' instead of JSON's "double quotes" (in
+contrast, QMP is strict JSON and only uses "double quotes").  As in
+JSON, trailing commas are not permitted in arrays or dictionaries.
 
-There are two basic syntaxes used, type definitions and command definitions.
+Comments are allowed; anything between an unquoted # and the following
+newline is ignored.  Although there is not yet a documentation
+generator, a form of stylized comments has developed for consistently
+documenting details about an expression and when it was added to the
+schema.  The documentation is delimited between two lines of ##, then
+the first line names the expression, an optional overview is provided,
+then individual documentation about each member of 'data' is provided,
+and finally, a 'Since: x.y.z' tag lists the release that introduced
+the expression.  Optional fields are tagged with the phrase
+'#optional', often with their default value; and extensions added
+after the expression was first released are also given a '(since
+x.y.z)' comment.  For example:
 
-The first syntax defines a type and is represented by a dictionary.  There are
-three kinds of user-defined types that are supported: complex types,
-enumeration types and union types.
+    ##
+    # @BlockStats:
+    #
+    # Statistics of a virtual block device or a block backing device.
+    #
+    # @device: #optional If the stats are for a virtual block device, the name
+    #          corresponding to the virtual block device.
+    #
+    # @stats:  A @BlockDeviceStats for the device.
+    #
+    # @parent: #optional This describes the file block device if it has one.
+    #
+    # @backing: #optional This describes the backing block device if it has one.
+    #           (Since 2.0)
+    #
+    # Since: 0.14.0
+    ##
+    { 'type': 'BlockStats',
+      'data': {'*device': 'str', 'stats': 'BlockDeviceStats',
+               '*parent': 'BlockStats',
+               '*backing': 'BlockStats'} }
 
-Generally speaking, types definitions should always use CamelCase for the type
-names. Command names should be all lower case with words separated by a hyphen.
+The schema sets up a series of types, as well as commands and events
+that will use those types.  Forward references are allowed: the parser
+scans in two passes, where the first pass learns all type names, and
+the second validates the schema and generates the code.  This allows
+the definition of complex structs that can have mutually recursive
+types, and allows for indefinite nesting of QMP that satisfies the
+schema.  A type name should not be defined more than once.
 
+There are six top-level expressions recognized by the parser:
+'include', 'command', 'type', 'enum', 'union', and 'event'.  There are
+several built-in types, such as 'int' and 'str'; additionally, the
+top-level expressions can define complex types, enumeration types, and
+union types.  The 'command' expression can refer to existing types by
+name, or list an anonymous type as a dictionary.  Listing a type name
+inside an array refers to a single-dimension array of that type;
+multi-dimension arrays are not directly supported (although an array
+of a complex struct that contains an array member is possible).
+
+Generally speaking, types definitions should always use CamelCase for
+user-defined type names, while built-in types are lowercase. Command
+names, and field names within a type, should be all lower case with
+words separated by a hyphen.  However, some existing older commands
+and complex types use underscore; when extending such expressions,
+consistency is preferred over blindly avoiding underscore.  Event
+names should be ALL_CAPS with words separated by underscore.  The
+special string '**' appears for some commands that manually perform
+their own type checking rather than relying on the type-safe code
+produced by the qapi code generators.
+
+Any command, type, or field name beginning with "x-" is marked
+experimental, and may be withdrawn in a future release.  Downstream
+vendors may add extensions; such extensions should begin with a prefix
+matching "__RFQDN_" (for the reverse-fully-qualified-domain-name of
+the vendor), even if the rest of the command or field name uses dash
+(example: __com.redhat_drive-mirror).  Other than the dots used in
+RFQDN of a downstream extension, all command, type, and field names
+should begin with a letter, and contain only ASCII letters, numbers,
+dash, and underscore.  It is okay to reuse names that might collide
+with programming languages; the generator will rename a field named
+"default" in the QAPI to "q_default" in the generated C code.
+
+
+=== Built-in Types ===
+
+The following types are built-in to the parser:
+  'str' - arbitrary UTF-8 string
+  'int' - 64-bit signed integer (although the C code may place further
+          restrictions on acceptable range)
+  'number' - floating point number
+  'bool' - JSON value of true or false
+  'int8', 'int16', 'int32', 'int64' - like 'int', but enforce maximum
+                                      bit size
+  'uint8', 'uint16', 'uint32', 'uint64' - unsigned counterparts
+  'size' - like 'uint64', but allows scaled suffix from command line
+           visitor
 
 === Includes ===
 
+Usage: { 'include': 'str' }
+
 The QAPI schema definitions can be modularized using the 'include' directive:
 
  { 'include': 'path/to/file.json'}
 
 The directive is evaluated recursively, and include paths are relative to the
-file using the directive. Multiple includes of the same file are safe.
+file using the directive. Multiple includes of the same file are
+safe.  No other keys should appear in the expression, and the include
+value should be a string.
+
+As a matter of style, it is a good idea to have all files be
+self-contained, but at the moment, nothing prevents an included file
+from making a forward reference to a type that is only introduced by
+an outer file.  The parser may be made stricter in the future to
+prevent incomplete include files.
 
 
 === Complex types ===
 
-A complex type is a dictionary containing a single key whose value is a
-dictionary.  This corresponds to a struct in C or an Object in JSON.  An
-example of a complex type is:
+Usage: { 'type': 'str', 'data': 'dict', '*base': 'complex-type-name' }
+
+A complex type is a dictionary containing a single 'data' key whose
+value is a dictionary.  This corresponds to a struct in C or an Object
+in JSON. Each value of the 'data' dictionary must be the name of a
+complex, enum, union, or built-in type, or a one-element array
+containing a type name.  An example of a complex type is:
 
  { 'type': 'MyType',
    'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
@@ -100,15 +201,42 @@ both fields like this:
  { "file": "/some/place/my-image",
    "backing": "/some/place/my-backing-file" }
 
+
 === Enumeration types ===
 
-An enumeration type is a dictionary containing a single key whose value is a
-list of strings.  An example enumeration is:
+Usage: { 'enum': 'str', 'data': [ 'str' ] }
+
+An enumeration type is a dictionary containing a single 'data' key
+whose value is a list of strings.  An example enumeration is:
 
  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
 
+Nothing prevents an empty enumeration, although it is probably not
+useful.  The list of strings should be lower case; if an enum name
+represents multiple words, use '-' between words.  The string 'max' is
+not allowed as an enum value, and values should not be repeated.
+
+The enumeration values are passed as strings over the QMP protocol,
+but are encoded as C enum integral values in generated code.  While
+the C code starts numbering at 0, it is better to use explicit
+comparisons to enum values than implicit comparisons to 0; the C code
+will also include a generated enum member ending in _MAX for tracking
+the size of the enum, useful when using common functions for
+converting between strings and enum values.  Since the wire format
+always passes by name, it is acceptable to reorder or add new
+enumeration members in any location without breaking QMP clients;
+however, removing enum values would break compatibility.  For any
+complex type that has a field that will only contain a finite set of
+string values, using an enum type for that field is better than
+open-coding the field to be type 'str'.
+
+
 === Union types ===
 
+Usage: { 'union': 'str', 'data': 'dict', '*base': 'complex-type-name',
+         '*discriminator': 'enum-type-name' }
+or:    { 'union': 'str', 'data': 'dict', 'discriminator': {} }
+
 Union types are used to let the user choose between several different data
 types.  A union type is defined using a dictionary as explained in the
 following paragraphs.
@@ -153,8 +281,10 @@ And it looks like this on the wire:
 
 Flat union types avoid the nesting on the wire. They are used whenever a
 specific field of the base type is declared as the discriminator ('type' is
-then no longer generated). The discriminator must be of enumeration type.
-The above example can then be modified as follows:
+then no longer generated). The discriminator must be of enumeration
+type, and the keys of the 'data' dictionary must match the enumeration
+keys (although not necessarily in the same order). The above example
+can then be modified as follows:
 
  { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
  { 'type': 'BlockdevCommonOptions',
@@ -200,23 +330,78 @@ This example allows using both of the following example objects:
 
 === Commands ===
 
-Commands are defined by using a list containing three members.  The first
-member is the command name, the second member is a dictionary containing
-arguments, and the third member is the return type.
+Usage: { 'command': 'str', '*data': 'dict-or-complex-type-name',
+         '*returns': 'type',
+         '*gen': 'no', '*success-response': 'no' }
 
-An example command is:
+Commands are defined by using a dictionary containing several members,
+where three members are most common.  The 'data' member is optional; if
+absent, the command accepts an optional empty dictionary.  If present,
+it must be the string name of a complex type, a one-element array
+containing the name of a complex type, or a dictionary that declares
+an anonymous type with the same semantics as a 'type' expression, with
+one exception noted below.  The 'returns' member is optional; if
+absent, the command returns an empty dictionary.  If present, it must
+be the string name of a complex or built-in type, a one-element array
+containing the name of a complex or built-in type, or a dictionary
+that declares an anonymous type with the same semantics as a 'type'
+expression, with one exception noted below.
+
+Although it is permitted to have the 'returns' member name a built-in
+type, any command that does this cannot be extended to return
+additional information in the future; thus, new commands should
+strongly consider returning a dictionary-based type, even if it only
+contains one field at the present.  Besides, all commands return a
+dictionary to report failure.
+
+Some example commands:
+
+ { 'command': 'my-first-command',
+   'data': { 'arg1': 'str', '*arg2': 'str' } }
+ { 'type': 'MyType', 'data': { '*value': 'str' } }
+ { 'command': 'my-second-command',
+   'returns': [ 'MyType' ] }
+
+which would validate this QMP transaction:
+
+ => { "execute": "my-first-command",
+      "arguments": { "arg1": "hello" } }
+ <= { "return": { } }
+ => { "execute": "my-second-command" }
+ <= { "return": [ { "value": "one" }, { } ] }
+
+In rare cases, QAPI cannot express a type-safe representation of a
+corresponding QMP command.  In these cases, if the command expression
+includes the key 'gen' with value 'no', then the 'data' or 'returns'
+member that intends to bypass generated type-safety and do its own
+manual validation should use '**' rather than a valid type name.
+Please try to avoid adding new commands that rely on this, and instead
+use type-safe unions.  For an example of bypass usage:
+
+ { 'command': 'netdev_add',
+   'data': {'type': 'str', 'id': 'str', '*props': '**'},
+   'gen': 'no' }
+
+Normally, the QAPI schema is used to describe synchronous exchanges,
+where a response is expected.  But in some cases, the action of a
+command is expected to change state in a way that a successful
+response is not possible (a failure message still returns a
+dictionary).  In this case, the command expression should include the
+optional key 'success-response' with value 'no'.
 
- { 'command': 'my-command',
-   'data': { 'arg1': 'str', '*arg2': 'str' },
-   'returns': 'str' }
 
 === Events ===
 
-Events are defined with the keyword 'event'.  When 'data' is also specified,
-additional info will be included in the event.  Finally there will be C API
-generated in qapi-event.h; when called by QEMU code, a message with timestamp
-will be emitted on the wire.  If timestamp is -1, it means failure to retrieve
-host time.
+Usage: { 'event': 'str', '*data': 'dict-or-complex-type-name' }
+
+Events are defined with the keyword 'event'.  It is not allowed to
+name an event 'MAX', since the generator also produces a C enumeration
+of all event names with a generated _MAX value at the end.  When
+'data' is also specified, additional info will be included in the
+event, with similar semantics to a 'type' expression.  Finally there
+will be C API generated in qapi-event.h; when called by QEMU code, a
+message with timestamp will be emitted on the wire.  If timestamp is
+-1, it means failure to retrieve host time.
 
 An example event is:
 
@@ -311,7 +496,7 @@ Example:
     #ifndef EXAMPLE_QAPI_TYPES_H
     #define EXAMPLE_QAPI_TYPES_H
 
-[Builtin types omitted...]
+[Built-in types omitted...]
 
     typedef struct UserDefOne UserDefOne;
 
@@ -324,7 +509,7 @@ Example:
         struct UserDefOneList *next;
     } UserDefOneList;
 
-[Functions on builtin types omitted...]
+[Functions on built-in types omitted...]
 
     struct UserDefOne
     {
@@ -423,7 +608,7 @@ Example:
     #ifndef EXAMPLE_QAPI_VISIT_H
     #define EXAMPLE_QAPI_VISIT_H
 
-[Visitors for builtin types omitted...]
+[Visitors for built-in types omitted...]
 
     void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
     void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);
Signature · 1 line
1.9.3
#8 lore raw

Re: [Qemu-devel] [PATCH v4 04/19] qapi: Document type-safety considerations

Quoted 195 lines · Eric Blake

Go into more details about the various types of valid expressions in a qapi schema, including tweaks to document fixes being done later in the current patch series.

---
 docs/qapi-code-gen.txt | 249 ++++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 217 insertions(+), 32 deletions(-)
docs/qapi-code-gen.txt +135 -15
index 8313ba6..3a79629 100644
@@ -22,35 +22,136 @@ code are used.
 This file defines the types, commands, and events used by QMP.  It should
 fully describe the interface used by QMP.
 
-This file is designed to be loosely based on JSON although it's technically
-executable Python.  While dictionaries are used, they are parsed as
-OrderedDicts so that ordering is preserved.
+A QAPI file is designed to be loosely based on JSON although it's
+technically executable Python.  A valid QAPI schema consists of a list
+of top-level expressions, with no commas between them.  While
+dictionaries are used, they are parsed as OrderedDicts so that
+ordering is preserved; ordering doesn't matter for top-level
+expressions, but does matter within 'data' members.  QAPI input is
+written using 'single quotes' instead of JSON's "double quotes" (in
+contrast, QMP is strict JSON and only uses "double quotes").  As in
+JSON, trailing commas are not permitted in arrays or dictionaries.
 
-There are two basic syntaxes used, type definitions and command definitions.
+Comments are allowed; anything between an unquoted # and the following
+newline is ignored.  Although there is not yet a documentation
+generator, a form of stylized comments has developed for consistently
+documenting details about an expression and when it was added to the
+schema.  The documentation is delimited between two lines of ##, then
+the first line names the expression, an optional overview is provided,
+then individual documentation about each member of 'data' is provided,
+and finally, a 'Since: x.y.z' tag lists the release that introduced
+the expression.  Optional fields are tagged with the phrase
+'#optional', often with their default value; and extensions added
+after the expression was first released are also given a '(since
+x.y.z)' comment.  For example:
 
-The first syntax defines a type and is represented by a dictionary.  There are
-three kinds of user-defined types that are supported: complex types,
-enumeration types and union types.
+    ##
+    # @BlockStats:
+    #
+    # Statistics of a virtual block device or a block backing device.
+    #
+    # @device: #optional If the stats are for a virtual block device, the name
+    #          corresponding to the virtual block device.
+    #
+    # @stats:  A @BlockDeviceStats for the device.
+    #
+    # @parent: #optional This describes the file block device if it has one.
+    #
+    # @backing: #optional This describes the backing block device if it has one.
+    #           (Since 2.0)
+    #
+    # Since: 0.14.0
+    ##
+    { 'type': 'BlockStats',
+      'data': {'*device': 'str', 'stats': 'BlockDeviceStats',
+               '*parent': 'BlockStats',
+               '*backing': 'BlockStats'} }
 
-Generally speaking, types definitions should always use CamelCase for the type
-names. Command names should be all lower case with words separated by a hyphen.
+The schema sets up a series of types, as well as commands and events
+that will use those types.  Forward references are allowed: the parser
+scans in two passes, where the first pass learns all type names, and
+the second validates the schema and generates the code.  This allows
+the definition of complex structs that can have mutually recursive
+types, and allows for indefinite nesting of QMP that satisfies the
+schema.  A type name should not be defined more than once.
 
+There are six top-level expressions recognized by the parser:
+'include', 'command', 'type', 'enum', 'union', and 'event'.  There are
+several built-in types, such as 'int' and 'str'; additionally, the
+top-level expressions can define complex types, enumeration types, and
+union types.  The 'command' expression can refer to existing types by
+name, or list an anonymous type as a dictionary.  Listing a type name
+inside an array refers to a single-dimension array of that type;
+multi-dimension arrays are not directly supported (although an array
+of a complex struct that contains an array member is possible).
+
+Generally speaking, types definitions should always use CamelCase for
+user-defined type names, while built-in types are lowercase. Command
+names, and field names within a type, should be all lower case with
+words separated by a hyphen.  However, some existing older commands
+and complex types use underscore; when extending such expressions,
+consistency is preferred over blindly avoiding underscore.  Event
+names should be ALL_CAPS with words separated by underscore.  The
+special string '**' appears for some commands that manually perform
+their own type checking rather than relying on the type-safe code
+produced by the qapi code generators.
+
+Any command, type, or field name beginning with "x-" is marked
+experimental, and may be withdrawn in a future release.  Downstream
+vendors may add extensions; such extensions should begin with a prefix
+matching "__RFQDN_" (for the reverse-fully-qualified-domain-name of
+the vendor), even if the rest of the command or field name uses dash
+(example: __com.redhat_drive-mirror).  Other than the dots used in
+RFQDN of a downstream extension, all command, type, and field names
+should begin with a letter, and contain only ASCII letters, numbers,
+dash, and underscore.  It is okay to reuse names that might collide
+with programming languages; the generator will rename a field named
+"default" in the QAPI to "q_default" in the generated C code.
+
+
+=== Built-in Types ===
+
+The following types are built-in to the parser:
+  'str' - arbitrary UTF-8 string
+  'int' - 64-bit signed integer (although the C code may place further
+          restrictions on acceptable range)
+  'number' - floating point number
+  'bool' - JSON value of true or false
+  'int8', 'int16', 'int32', 'int64' - like 'int', but enforce maximum
+                                      bit size
+  'uint8', 'uint16', 'uint32', 'uint64' - unsigned counterparts
+  'size' - like 'uint64', but allows scaled suffix from command line
+           visitor
 
 === Includes ===
 
+Usage: { 'include': 'str' }
+
 The QAPI schema definitions can be modularized using the 'include' directive:
 
  { 'include': 'path/to/file.json'}
 
 The directive is evaluated recursively, and include paths are relative to the
-file using the directive. Multiple includes of the same file are safe.
+file using the directive. Multiple includes of the same file are
+safe.  No other keys should appear in the expression, and the include
+value should be a string.
+
+As a matter of style, it is a good idea to have all files be
+self-contained, but at the moment, nothing prevents an included file
+from making a forward reference to a type that is only introduced by
+an outer file.  The parser may be made stricter in the future to
+prevent incomplete include files.
 
 
 === Complex types ===
 
-A complex type is a dictionary containing a single key whose value is a
-dictionary.  This corresponds to a struct in C or an Object in JSON.  An
-example of a complex type is:
+Usage: { 'type': 'str', 'data': 'dict', '*base': 'complex-type-name' }
+
+A complex type is a dictionary containing a single 'data' key whose
+value is a dictionary.  This corresponds to a struct in C or an Object
+in JSON. Each value of the 'data' dictionary must be the name of a
+complex, enum, union, or built-in type, or a one-element array
+containing a type name.  An example of a complex type is:
 
  { 'type': 'MyType',
    'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
@@ -100,15 +201,42 @@ both fields like this:
  { "file": "/some/place/my-image",
    "backing": "/some/place/my-backing-file" }
 
+
 === Enumeration types ===
 
-An enumeration type is a dictionary containing a single key whose value is a
-list of strings.  An example enumeration is:
+Usage: { 'enum': 'str', 'data': [ 'str' ] }
+
+An enumeration type is a dictionary containing a single 'data' key
+whose value is a list of strings.  An example enumeration is:
 
  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
 
+Nothing prevents an empty enumeration, although it is probably not
+useful.  The list of strings should be lower case; if an enum name
+represents multiple words, use '-' between words.  The string 'max' is
+not allowed as an enum value, and values should not be repeated.
+
+The enumeration values are passed as strings over the QMP protocol,
+but are encoded as C enum integral values in generated code.  While
+the C code starts numbering at 0, it is better to use explicit
+comparisons to enum values than implicit comparisons to 0; the C code
+will also include a generated enum member ending in _MAX for tracking
+the size of the enum, useful when using common functions for
+converting between strings and enum values.  Since the wire format
+always passes by name, it is acceptable to reorder or add new
+enumeration members in any location without breaking QMP clients;
+however, removing enum values would break compatibility.  For any
+complex type that has a field that will only contain a finite set of

docs/qapi-code-gen.txt both fields like this: · line 239

Quoted 10 lines
docs/qapi-code-gen.txt +8 -0
+string values, using an enum type for that field is better than
+open-coding the field to be type 'str'.
+
+
 === Union types ===
 
+Usage: { 'union': 'str', 'data': 'dict', '*base': 'complex-type-name',
+         '*discriminator': 'enum-type-name' }
+or:    { 'union': 'str', 'data': 'dict', 'discriminator': {} }
+

Suggest to split usage into simple union, flat union and anonymous union, like this:

Usage: { 'union': 'str', 'data': 'dict', '*base': 'complex-type-name' }
or:    { 'union': 'str', 'data': 'dict', 'base': 'complex-type-name',
         '*discriminator': 'enum-type-name' }

or: { 'union': 'str', 'data': 'dict', 'discriminator': {} }

Quoted 20 lines
docs/qapi-code-gen.txt +4 -2
 Union types are used to let the user choose between several different data
 types.  A union type is defined using a dictionary as explained in the
 following paragraphs.
@@ -153,8 +281,10 @@ And it looks like this on the wire:
 
 Flat union types avoid the nesting on the wire. They are used whenever a
 specific field of the base type is declared as the discriminator ('type' is
-then no longer generated). The discriminator must be of enumeration type.
-The above example can then be modified as follows:
+then no longer generated). The discriminator must be of enumeration
+type, and the keys of the 'data' dictionary must match the enumeration
+keys (although not necessarily in the same order). The above example
+can then be modified as follows:
 
  { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
  { 'type': 'BlockdevCommonOptions',
@@ -200,23 +330,78 @@ This example allows using both of the following example objects:
 
 === Commands ===
 

docs/qapi-code-gen.txt This example allows using both of the following example objects: · line 338

Quoted 10 lines
docs/qapi-code-gen.txt +5 -4
-Commands are defined by using a list containing three members.  The first
-member is the command name, the second member is a dictionary containing
-arguments, and the third member is the return type.
+Usage: { 'command': 'str', '*data': 'dict-or-complex-type-name',
+         '*returns': 'type',
+         '*gen': 'no', '*success-response': 'no' }
 
-An example command is:
+Commands are defined by using a dictionary containing several members,
+where three members are most common.

Suggest paragraph break here.

docs/qapi-code-gen.txt This example allows using both of the following example objects:

Quoted 6 lines
docs/qapi-code-gen.txt +6 -0
+                                      The 'data' member is optional; if
+absent, the command accepts an optional empty dictionary.  If present,
+it must be the string name of a complex type, a one-element array
+containing the name of a complex type, or a dictionary that declares
+an anonymous type with the same semantics as a 'type' expression, with
+one exception noted below.

Suggest to say explicitly that 'data' specifies command arguments.

Suggest paragraph break here.

docs/qapi-code-gen.txt This example allows using both of the following example objects: · line 355

Quoted 13 lines
docs/qapi-code-gen.txt +13 -0
+                            The 'returns' member is optional; if
+absent, the command returns an empty dictionary.  If present, it must
+be the string name of a complex or built-in type, a one-element array
+containing the name of a complex or built-in type, or a dictionary
+that declares an anonymous type with the same semantics as a 'type'
+expression, with one exception noted below.
+
+Although it is permitted to have the 'returns' member name a built-in
+type, any command that does this cannot be extended to return
+additional information in the future; thus, new commands should
+strongly consider returning a dictionary-based type, even if it only
+contains one field at the present.  Besides, all commands return a
+dictionary to report failure.

Suggest to say explicitly that 'returns' specifies the reply on success.

Suggest to replace the last sentence by a separate paragraph discussing the reply on failure.

Quoted 10 lines
docs/qapi-code-gen.txt +10 -0
+
+Some example commands:
+
+ { 'command': 'my-first-command',
+   'data': { 'arg1': 'str', '*arg2': 'str' } }
+ { 'type': 'MyType', 'data': { '*value': 'str' } }
+ { 'command': 'my-second-command',
+   'returns': [ 'MyType' ] }
+
+which would validate this QMP transaction:

docs/qapi-code-gen.txt This example allows using both of the following example objects: · line 375

Quoted 10 lines
docs/qapi-code-gen.txt +10 -0
+
+ => { "execute": "my-first-command",
+      "arguments": { "arg1": "hello" } }
+ <= { "return": { } }
+ => { "execute": "my-second-command" }
+ <= { "return": [ { "value": "one" }, { } ] }
+
+In rare cases, QAPI cannot express a type-safe representation of a
+corresponding QMP command.  In these cases, if the command expression
+includes the key 'gen' with value 'no', then the 'data' or 'returns'

The implementation actually ignores the value of 'gen', but specifying it must be 'no' doesn't hurt.

Quoted 5 lines
docs/qapi-code-gen.txt +5 -0
+member that intends to bypass generated type-safety and do its own
+manual validation should use '**' rather than a valid type name.
+Please try to avoid adding new commands that rely on this, and instead
+use type-safe unions.  For an example of bypass usage:
+

docs/qapi-code-gen.txt This example allows using both of the following example objects: · line 390

Quoted 10 lines
docs/qapi-code-gen.txt +10 -0
+ { 'command': 'netdev_add',
+   'data': {'type': 'str', 'id': 'str', '*props': '**'},
+   'gen': 'no' }
+
+Normally, the QAPI schema is used to describe synchronous exchanges,
+where a response is expected.  But in some cases, the action of a
+command is expected to change state in a way that a successful
+response is not possible (a failure message still returns a
+dictionary).  In this case, the command expression should include the
+optional key 'success-response' with value 'no'.

Learned something new here.

Suggest to change the parenthesis to something like (it still sends a normal error reply on failure).

Quoted 7 lines
docs/qapi-code-gen.txt +0 -3
- { 'command': 'my-command',
-   'data': { 'arg1': 'str', '*arg2': 'str' },
-   'returns': 'str' }
 
 === Events ===
 

docs/qapi-code-gen.txt This example allows using both of the following example objects:

Quoted 10 lines
docs/qapi-code-gen.txt +5 -5
-Events are defined with the keyword 'event'.  When 'data' is also specified,
-additional info will be included in the event.  Finally there will be C API
-generated in qapi-event.h; when called by QEMU code, a message with timestamp
-will be emitted on the wire.  If timestamp is -1, it means failure to retrieve
-host time.
+Usage: { 'event': 'str', '*data': 'dict-or-complex-type-name' }
+
+Events are defined with the keyword 'event'.  It is not allowed to
+name an event 'MAX', since the generator also produces a C enumeration
+of all event names with a generated _MAX value at the end.

One of the several places where the generator can thoughtlessly produce clashing identifiers. You're documenting one of them, which is an improvement of sorts.

docs/qapi-code-gen.txt This example allows using both of the following example objects: · line 404

Quoted 6 lines
docs/qapi-code-gen.txt +5 -0
                                                             When
+'data' is also specified, additional info will be included in the
+event, with similar semantics to a 'type' expression.  Finally there
+will be C API generated in qapi-event.h; when called by QEMU code, a
+message with timestamp will be emitted on the wire.  If timestamp is
+-1, it means failure to retrieve host time.

As far as I can tell, this can happen only if gettimeofday() fails. Highly unlikely. But since the code could do it, the spec should mention it.

Quoted 22 lines
docs/qapi-code-gen.txt +2 -2
 An example event is:
@@ -311,7 +496,7 @@ Example:
     #ifndef EXAMPLE_QAPI_TYPES_H
     #define EXAMPLE_QAPI_TYPES_H
 
-[Builtin types omitted...]
+[Built-in types omitted...]
 
     typedef struct UserDefOne UserDefOne;
 
@@ -324,7 +509,7 @@ Example:
         struct UserDefOneList *next;
     } UserDefOneList;
 
-[Functions on builtin types omitted...]
+[Functions on built-in types omitted...]
 
     struct UserDefOne
     {

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

Quoted 8 lines
docs/qapi-code-gen.txt +1 -1
@@ -423,7 +608,7 @@ Example:
     #ifndef EXAMPLE_QAPI_VISIT_H
     #define EXAMPLE_QAPI_VISIT_H
 
-[Visitors for builtin types omitted...]
+[Visitors for built-in types omitted...]
 
     void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
     void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);

Major improvement, thank you very much!

author
#9 lore raw

Re: [Qemu-devel] [PATCH v4 04/19] qapi: Document type-safety considerations

Quoted 13 lines · Markus Armbruster

docs/qapi-code-gen.txt both fields like this: · line 239

Quoted 6 lines · Eric Blake

=== Union types ===

docs/qapi-code-gen.txt +4 -0
+Usage: { 'union': 'str', 'data': 'dict', '*base': 'complex-type-name',
+         '*discriminator': 'enum-type-name' }
+or:    { 'union': 'str', 'data': 'dict', 'discriminator': {} }
+

Suggest to split usage into simple union, flat union and anonymous union, like this:

Quoted 1 line

Usage: { 'union': 'str', 'data': 'dict', '*base': 'complex-type-name' }

^ simple

Quoted 2 lines

or: { 'union': 'str', 'data': 'dict', 'base': 'complex-type-name',

         '*discriminator': 'enum-type-name' }

^ flat

Quoted 1 line

or: { 'union': 'str', 'data': 'dict', 'discriminator': {} }

^ anonymous

Except that someday, I'd like to have:

{ 'union': str', 'data': 'dict', 'discriminator': 'enum-type-name' }

which, when compared with the simple and flat versions, means that base and discriminator are equally optional. But you are right that we don't have that form yet, and that the code currently requires that if base is specified, then discriminator is non-optional. I'll have to tweak this.

Quoted 7 lines

docs/qapi-code-gen.txt This example allows using both of the following example objects: · line 375

Quoted 4 lines
docs/qapi-code-gen.txt +4 -0
+
+In rare cases, QAPI cannot express a type-safe representation of a
+corresponding QMP command.  In these cases, if the command expression
+includes the key 'gen' with value 'no', then the 'data' or 'returns'

The implementation actually ignores the value of 'gen', but specifying it must be 'no' doesn't hurt.

Actually, see patch 14/19 later in the series, where I fix the code to enforce that it must be 'no' :)

Quoted 10 lines
Quoted 10 lines
docs/qapi-code-gen.txt +9 -0
+member that intends to bypass generated type-safety and do its own
+manual validation should use '**' rather than a valid type name.
+Please try to avoid adding new commands that rely on this, and instead
+use type-safe unions.  For an example of bypass usage:
+
+ { 'command': 'netdev_add',
+   'data': {'type': 'str', 'id': 'str', '*props': '**'},
+   'gen': 'no' }
+
Quoted 8 lines

docs/qapi-code-gen.txt This example allows using both of the following example objects: · line 390

Quoted 6 lines
docs/qapi-code-gen.txt +6 -0
+Normally, the QAPI schema is used to describe synchronous exchanges,
+where a response is expected.  But in some cases, the action of a
+command is expected to change state in a way that a successful
+response is not possible (a failure message still returns a
+dictionary).  In this case, the command expression should include the
+optional key 'success-response' with value 'no'.

Learned something new here.

To date, only qga uses this form.

Quoted 8 lines

docs/qapi-code-gen.txt This example allows using both of the following example objects:

Quoted 4 lines
docs/qapi-code-gen.txt +4 -0
+
+Events are defined with the keyword 'event'.  It is not allowed to
+name an event 'MAX', since the generator also produces a C enumeration
+of all event names with a generated _MAX value at the end.

One of the several places where the generator can thoughtlessly produce clashing identifiers. You're documenting one of them, which is an improvement of sorts.

I also enhance things later in the series to enforce this documentation :)

Quoted 2 lines

Major improvement, thank you very much!

I've trimmed your other comments (such as suggested line breaks) because I agree with them, and will incorporate them into either v5 (if the series needs respinning) or a followup patch (if this is the only patch that needs improvement).

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

PATCH v4 5/19 qapi: Add some enum tests

In reply to Eric Blake

Demonstrate that the qapi generator doesn't deal well with enums that aren't up to par. Later patches will update the expected results as the generator is made stricter.

---
 tests/Makefile                           | 5 ++++-
 tests/qapi-schema/enum-clash-member.err  | 0
 tests/qapi-schema/enum-clash-member.exit | 1 +
 tests/qapi-schema/enum-clash-member.json | 2 ++
 tests/qapi-schema/enum-clash-member.out  | 3 +++
 tests/qapi-schema/enum-dict-member.err   | 0
 tests/qapi-schema/enum-dict-member.exit  | 1 +
 tests/qapi-schema/enum-dict-member.json  | 2 ++
 tests/qapi-schema/enum-dict-member.out   | 3 +++
 tests/qapi-schema/enum-empty.err         | 0
 tests/qapi-schema/enum-empty.exit        | 1 +
 tests/qapi-schema/enum-empty.json        | 2 ++
 tests/qapi-schema/enum-empty.out         | 3 +++
 tests/qapi-schema/enum-int-member.err    | 1 +
 tests/qapi-schema/enum-int-member.exit   | 1 +
 tests/qapi-schema/enum-int-member.json   | 3 +++
 tests/qapi-schema/enum-int-member.out    | 0
 tests/qapi-schema/enum-max-member.err    | 0
 tests/qapi-schema/enum-max-member.exit   | 1 +
 tests/qapi-schema/enum-max-member.json   | 3 +++
 tests/qapi-schema/enum-max-member.out    | 3 +++
 tests/qapi-schema/enum-missing-data.err  | 6 ++++++
 tests/qapi-schema/enum-missing-data.exit | 1 +
 tests/qapi-schema/enum-missing-data.json | 2 ++
 tests/qapi-schema/enum-missing-data.out  | 0
 tests/qapi-schema/enum-wrong-data.err    | 0
 tests/qapi-schema/enum-wrong-data.exit   | 1 +
 tests/qapi-schema/enum-wrong-data.json   | 2 ++
 tests/qapi-schema/enum-wrong-data.out    | 3 +++
 29 files changed, 49 insertions(+), 1 deletion(-)
 create mode 100644 tests/qapi-schema/enum-clash-member.err
 create mode 100644 tests/qapi-schema/enum-clash-member.exit
 create mode 100644 tests/qapi-schema/enum-clash-member.json
 create mode 100644 tests/qapi-schema/enum-clash-member.out
 create mode 100644 tests/qapi-schema/enum-dict-member.err
 create mode 100644 tests/qapi-schema/enum-dict-member.exit
 create mode 100644 tests/qapi-schema/enum-dict-member.json
 create mode 100644 tests/qapi-schema/enum-dict-member.out
 create mode 100644 tests/qapi-schema/enum-empty.err
 create mode 100644 tests/qapi-schema/enum-empty.exit
 create mode 100644 tests/qapi-schema/enum-empty.json
 create mode 100644 tests/qapi-schema/enum-empty.out
 create mode 100644 tests/qapi-schema/enum-int-member.err
 create mode 100644 tests/qapi-schema/enum-int-member.exit
 create mode 100644 tests/qapi-schema/enum-int-member.json
 create mode 100644 tests/qapi-schema/enum-int-member.out
 create mode 100644 tests/qapi-schema/enum-max-member.err
 create mode 100644 tests/qapi-schema/enum-max-member.exit
 create mode 100644 tests/qapi-schema/enum-max-member.json
 create mode 100644 tests/qapi-schema/enum-max-member.out
 create mode 100644 tests/qapi-schema/enum-missing-data.err
 create mode 100644 tests/qapi-schema/enum-missing-data.exit
 create mode 100644 tests/qapi-schema/enum-missing-data.json
 create mode 100644 tests/qapi-schema/enum-missing-data.out
 create mode 100644 tests/qapi-schema/enum-wrong-data.err
 create mode 100644 tests/qapi-schema/enum-wrong-data.exit
 create mode 100644 tests/qapi-schema/enum-wrong-data.json
 create mode 100644 tests/qapi-schema/enum-wrong-data.out
tests/Makefile +4 -1
index 976388a..6a4e5a6 100644
@@ -195,7 +195,10 @@ $(foreach target,$(SYSEMU_TARGET_LIST), \
     $(eval check-qtest-$(target)-y += tests/qom-test$(EXESUF)))
 
 check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
-	comments.json empty.json funny-char.json indented-expr.json \
+	comments.json empty.json enum-empty.json enum-missing-data.json \
+	enum-wrong-data.json enum-int-member.json enum-dict-member.json \
+	enum-clash-member.json enum-max-member.json \
+	funny-char.json indented-expr.json \
 	missing-colon.json missing-comma-list.json \
 	missing-comma-object.json non-objects.json \
 	qapi-schema-test.json quoted-structural-chars.json \
tests/qapi-schema/enum-clash-member.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/enum-clash-member.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/enum-clash-member.json new file +2 -0
new file mode 100644
index 0000000..cb4b428
@@ -0,0 +1,2 @@
+# FIXME: we should reject enums where members will clash in C switch
+{ 'enum': 'MyEnum', 'data': [ 'one', 'ONE' ] }
tests/qapi-schema/enum-clash-member.out new file +3 -0
new file mode 100644
index 0000000..0814459
@@ -0,0 +1,3 @@
+[OrderedDict([('enum', 'MyEnum'), ('data', ['one', 'ONE'])])]
+[{'enum_name': 'MyEnum', 'enum_values': ['one', 'ONE']}]
+[]
tests/qapi-schema/enum-dict-member.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/enum-dict-member.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/enum-dict-member.json new file +2 -0
new file mode 100644
index 0000000..de4d6bf
@@ -0,0 +1,2 @@
+# FIXME: we should reject any enum member that is not a string
+{ 'enum': 'MyEnum', 'data': [ { 'value': 'str' } ] }
tests/qapi-schema/enum-dict-member.out new file +3 -0
new file mode 100644
index 0000000..8b293f8
@@ -0,0 +1,3 @@
+[OrderedDict([('enum', 'MyEnum'), ('data', [OrderedDict([('value', 'str')])])])]
+[{'enum_name': 'MyEnum', 'enum_values': [OrderedDict([('value', 'str')])]}]
+[]
tests/qapi-schema/enum-empty.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/enum-empty.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/enum-empty.json new file +2 -0
new file mode 100644
index 0000000..40d4e85
@@ -0,0 +1,2 @@
+# An empty enum, although unusual, is currently acceptable
+{ 'enum': 'MyEnum', 'data': [ ] }
tests/qapi-schema/enum-empty.out new file +3 -0
new file mode 100644
index 0000000..3b75c16
@@ -0,0 +1,3 @@
+[OrderedDict([('enum', 'MyEnum'), ('data', [])])]
+[{'enum_name': 'MyEnum', 'enum_values': []}]
+[]
tests/qapi-schema/enum-int-member.err new file +1 -0
new file mode 100644
index 0000000..071c521
@@ -0,0 +1 @@
+tests/qapi-schema/enum-int-member.json:3:31: Stray "1"
tests/qapi-schema/enum-int-member.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/enum-int-member.json new file +3 -0
new file mode 100644
index 0000000..6c9c32e
@@ -0,0 +1,3 @@
+# we reject any enum member that is not a string
+# FIXME: once the parser understands integer inputs, improve the error message
+{ 'enum': 'MyEnum', 'data': [ 1 ] }
tests/qapi-schema/enum-int-member.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/enum-max-member.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/enum-max-member.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/enum-max-member.json new file +3 -0
new file mode 100644
index 0000000..ea854c4
@@ -0,0 +1,3 @@
+# FIXME: we should either reject user-supplied 'max', or munge the implicit
+# max value we generate at the end of an array
+{ 'enum': 'MyEnum', 'data': [ 'max' ] }
tests/qapi-schema/enum-max-member.out new file +3 -0
new file mode 100644
index 0000000..c933044
@@ -0,0 +1,3 @@
+[OrderedDict([('enum', 'MyEnum'), ('data', ['max'])])]
+[{'enum_name': 'MyEnum', 'enum_values': ['max']}]
+[]
tests/qapi-schema/enum-missing-data.err new file +6 -0
new file mode 100644
index 0000000..1fec213
@@ -0,0 +1,6 @@
+Traceback (most recent call last):
+  File "tests/qapi-schema/test-qapi.py", line 19, in <module>
+    exprs = parse_schema(sys.argv[1])
+  File "scripts/qapi.py", line 339, in parse_schema
+    add_enum(expr['enum'], expr['data'])
+KeyError: 'data'
tests/qapi-schema/enum-missing-data.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/enum-missing-data.json new file +2 -0
new file mode 100644
index 0000000..01f3f32
@@ -0,0 +1,2 @@
+# FIXME: we should require that all QAPI enums have a data array
+{ 'enum': 'MyEnum' }
tests/qapi-schema/enum-missing-data.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/enum-wrong-data.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/enum-wrong-data.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/enum-wrong-data.json new file +2 -0
new file mode 100644
index 0000000..61d25ec
@@ -0,0 +1,2 @@
+# FIXME: we should require that all qapi enums have an array for data
+{ 'enum': 'MyEnum', 'data': { 'value': 'str' } }
tests/qapi-schema/enum-wrong-data.out new file +3 -0
new file mode 100644
index 0000000..28d2211
@@ -0,0 +1,3 @@
+[OrderedDict([('enum', 'MyEnum'), ('data', OrderedDict([('value', 'str')]))])]
+[{'enum_name': 'MyEnum', 'enum_values': OrderedDict([('value', 'str')])}]
+[]
Signature · 1 line
1.9.3
author
#12 lore raw

PATCH v4 6/19 qapi: Better error messages for bad enums

In reply to Eric Blake

The previous commit demonstrated that the generator had several flaws with less-than-perfect enums:
- an enum that listed the same string twice (or two variant strings that map to the same C enum) ended up generating an invalid C enum
- because the generator adds a _MAX terminator to each enum, the use of an enum member 'max' can also cause this clash
- if an enum omits 'data', the generator left a python stack trace rather than a graceful message
- an enum used a non-array 'data' was silently accepted by the parser
- an enum that used non-string members in the 'data' member was silently accepted by the parser

Add check_enum to cover these situations, and update testcases to match. While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---
 scripts/qapi.py                          | 32 ++++++++++++++++++++++++++++----
 tests/qapi-schema/enum-clash-member.err  |  1 +
 tests/qapi-schema/enum-clash-member.exit |  2 +-
 tests/qapi-schema/enum-clash-member.json |  2 +-
 tests/qapi-schema/enum-clash-member.out  |  3 ---
 tests/qapi-schema/enum-dict-member.err   |  1 +
 tests/qapi-schema/enum-dict-member.exit  |  2 +-
 tests/qapi-schema/enum-dict-member.json  |  2 +-
 tests/qapi-schema/enum-dict-member.out   |  3 ---
 tests/qapi-schema/enum-max-member.err    |  1 +
 tests/qapi-schema/enum-max-member.exit   |  2 +-
 tests/qapi-schema/enum-max-member.json   |  4 ++--
 tests/qapi-schema/enum-max-member.out    |  3 ---
 tests/qapi-schema/enum-missing-data.err  |  7 +------
 tests/qapi-schema/enum-missing-data.json |  2 +-
 tests/qapi-schema/enum-wrong-data.err    |  1 +
 tests/qapi-schema/enum-wrong-data.exit   |  2 +-
 tests/qapi-schema/enum-wrong-data.json   |  2 +-
 tests/qapi-schema/enum-wrong-data.out    |  3 ---
 19 files changed, 43 insertions(+), 32 deletions(-)
scripts/qapi.py +28 -4
index 77d46aa..85aa8bf 100644
@@ -2,7 +2,7 @@
 # QAPI helper library
 #
 # Copyright IBM, Corp. 2011
-# Copyright (c) 2013 Red Hat Inc.
+# Copyright (c) 2013-2014 Red Hat Inc.
 #
 # Authors:
 #  Anthony Liguori <[email protected]>
@@ -316,13 +316,37 @@ def check_union(expr, expr_info):
         # Todo: add checking for values. Key is checked as above, value can be
         # also checked here, but we need more functions to handle array case.
 
+def check_enum(expr, expr_info):
+    name = expr['enum']
+    members = expr.get('data')
+    values = { 'MAX': '(automatic)' }
+
+    if not isinstance(members, list):
+        raise QAPIExprError(expr_info,
+                            "enum '%s' requires an array for 'data'" % name)
+    for member in members:
+        if not isinstance(member, basestring):
+            raise QAPIExprError(expr_info,
+                                "enum '%s' member '%s' is not a string"
+                                % (name, member))
+        key = _generate_enum_string(member)
+        if key in values:
+            raise QAPIExprError(expr_info,
+                                "enum '%s' member '%s' clashes with '%s'"
+                                % (name, member, values[key]))
+        values[key] = member
+
 def check_exprs(schema):
     for expr_elem in schema.exprs:
         expr = expr_elem['expr']
+        info = expr_elem['info']
+
         if expr.has_key('union'):
-            check_union(expr, expr_elem['info'])
+            check_union(expr, info)
         if expr.has_key('event'):
-            check_event(expr, expr_elem['info'])
+            check_event(expr, info)
+        if expr.has_key('enum'):
+            check_enum(expr, info)
 
 def parse_schema(input_file):
     try:
@@ -336,7 +360,7 @@ def parse_schema(input_file):
     for expr_elem in schema.exprs:
         expr = expr_elem['expr']
         if expr.has_key('enum'):
-            add_enum(expr['enum'], expr['data'])
+            add_enum(expr['enum'], expr.get('data'))
         elif expr.has_key('union'):
             add_union(expr)
         elif expr.has_key('type'):
tests/qapi-schema/enum-clash-member.err +1 -0
index e69de29..3731fc2 100644
@@ -0,0 +1 @@
+tests/qapi-schema/enum-clash-member.json:2: enum 'MyEnum' member 'ONE' clashes with 'one'
tests/qapi-schema/enum-clash-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-clash-member.json +1 -1
index cb4b428..c668ff5 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject enums where members will clash in C switch
+# we reject enums where members will clash in C switch
 { 'enum': 'MyEnum', 'data': [ 'one', 'ONE' ] }
tests/qapi-schema/enum-clash-member.out +0 -3
index 0814459..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('enum', 'MyEnum'), ('data', ['one', 'ONE'])])]
-[{'enum_name': 'MyEnum', 'enum_values': ['one', 'ONE']}]
-[]
tests/qapi-schema/enum-dict-member.err +1 -0
index e69de29..f5a8ffe 100644
@@ -0,0 +1 @@
+tests/qapi-schema/enum-dict-member.json:2: enum 'MyEnum' member 'OrderedDict([('value', 'str')])' is not a string
tests/qapi-schema/enum-dict-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-dict-member.json +1 -1
index de4d6bf..79672e0 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject any enum member that is not a string
+# we reject any enum member that is not a string
 { 'enum': 'MyEnum', 'data': [ { 'value': 'str' } ] }
tests/qapi-schema/enum-dict-member.out +0 -3
index 8b293f8..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('enum', 'MyEnum'), ('data', [OrderedDict([('value', 'str')])])])]
-[{'enum_name': 'MyEnum', 'enum_values': [OrderedDict([('value', 'str')])]}]
-[]
tests/qapi-schema/enum-max-member.err +1 -0
index e69de29..a6c5db1 100644
@@ -0,0 +1 @@
+tests/qapi-schema/enum-max-member.json:3: enum 'MyEnum' member 'max' clashes with '(automatic)'
tests/qapi-schema/enum-max-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-max-member.json +2 -2
index ea854c4..6af4662 100644
@@ -1,3 +1,3 @@
-# FIXME: we should either reject user-supplied 'max', or munge the implicit
-# max value we generate at the end of an array
+# we reject user-supplied 'max' for clashing with implicit enum end
+# FIXME: should we instead munge the the implicit value to avoid the clash?
 { 'enum': 'MyEnum', 'data': [ 'max' ] }
tests/qapi-schema/enum-max-member.out +0 -3
index c933044..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('enum', 'MyEnum'), ('data', ['max'])])]
-[{'enum_name': 'MyEnum', 'enum_values': ['max']}]
-[]
tests/qapi-schema/enum-missing-data.err +1 -6
index 1fec213..4b8b59e 100644
@@ -1,6 +1 @@
-Traceback (most recent call last):
-  File "tests/qapi-schema/test-qapi.py", line 19, in <module>
-    exprs = parse_schema(sys.argv[1])
-  File "scripts/qapi.py", line 339, in parse_schema
-    add_enum(expr['enum'], expr['data'])
-KeyError: 'data'
+tests/qapi-schema/enum-missing-data.json:2: enum 'MyEnum' requires an array for 'data'
tests/qapi-schema/enum-missing-data.json +1 -1
index 01f3f32..558fd35 100644
@@ -1,2 +1,2 @@
-# FIXME: we should require that all QAPI enums have a data array
+# we require that all QAPI enums have a data array
 { 'enum': 'MyEnum' }
tests/qapi-schema/enum-wrong-data.err +1 -0
index e69de29..0d14e80 100644
@@ -0,0 +1 @@
+tests/qapi-schema/enum-wrong-data.json:2: enum 'MyEnum' requires an array for 'data'
tests/qapi-schema/enum-wrong-data.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-wrong-data.json +1 -1
index 61d25ec..7b3e255 100644
@@ -1,2 +1,2 @@
-# FIXME: we should require that all qapi enums have an array for data
+# we require that all qapi enums have an array for data
 { 'enum': 'MyEnum', 'data': { 'value': 'str' } }
tests/qapi-schema/enum-wrong-data.out +0 -3
index 28d2211..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('enum', 'MyEnum'), ('data', OrderedDict([('value', 'str')]))])]
-[{'enum_name': 'MyEnum', 'enum_values': OrderedDict([('value', 'str')])}]
-[]
Signature · 1 line
1.9.3
Reviewed-by on v4 6/19
#13 lore raw

Re: [Qemu-devel] [PATCH v4 06/19] qapi: Better error messages for bad enums

Quoted 122 lines · Eric Blake

The previous commit demonstrated that the generator had several flaws with less-than-perfect enums:
- an enum that listed the same string twice (or two variant strings that map to the same C enum) ended up generating an invalid C enum
- because the generator adds a _MAX terminator to each enum, the use of an enum member 'max' can also cause this clash
- if an enum omits 'data', the generator left a python stack trace rather than a graceful message
- an enum used a non-array 'data' was silently accepted by the parser
- an enum that used non-string members in the 'data' member was silently accepted by the parser

Add check_enum to cover these situations, and update testcases to match. While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---
 scripts/qapi.py                          | 32 ++++++++++++++++++++++++++++----
 tests/qapi-schema/enum-clash-member.err  |  1 +
 tests/qapi-schema/enum-clash-member.exit |  2 +-
 tests/qapi-schema/enum-clash-member.json |  2 +-
 tests/qapi-schema/enum-clash-member.out  |  3 ---
 tests/qapi-schema/enum-dict-member.err   |  1 +
 tests/qapi-schema/enum-dict-member.exit  |  2 +-
 tests/qapi-schema/enum-dict-member.json  |  2 +-
 tests/qapi-schema/enum-dict-member.out   |  3 ---
 tests/qapi-schema/enum-max-member.err    |  1 +
 tests/qapi-schema/enum-max-member.exit   |  2 +-
 tests/qapi-schema/enum-max-member.json   |  4 ++--
 tests/qapi-schema/enum-max-member.out    |  3 ---
 tests/qapi-schema/enum-missing-data.err  |  7 +------
 tests/qapi-schema/enum-missing-data.json |  2 +-
 tests/qapi-schema/enum-wrong-data.err    |  1 +
 tests/qapi-schema/enum-wrong-data.exit   |  2 +-
 tests/qapi-schema/enum-wrong-data.json   |  2 +-
 tests/qapi-schema/enum-wrong-data.out    |  3 ---
 19 files changed, 43 insertions(+), 32 deletions(-)
scripts/qapi.py +28 -4
index 77d46aa..85aa8bf 100644
@@ -2,7 +2,7 @@
 # QAPI helper library
 #
 # Copyright IBM, Corp. 2011
-# Copyright (c) 2013 Red Hat Inc.
+# Copyright (c) 2013-2014 Red Hat Inc.
 #
 # Authors:
 #  Anthony Liguori <[email protected]>
@@ -316,13 +316,37 @@ def check_union(expr, expr_info):
         # Todo: add checking for values. Key is checked as above, value can be
         # also checked here, but we need more functions to handle array case.
 
+def check_enum(expr, expr_info):
+    name = expr['enum']
+    members = expr.get('data')
+    values = { 'MAX': '(automatic)' }
+
+    if not isinstance(members, list):
+        raise QAPIExprError(expr_info,
+                            "enum '%s' requires an array for 'data'" % name)
+    for member in members:
+        if not isinstance(member, basestring):
+            raise QAPIExprError(expr_info,
+                                "enum '%s' member '%s' is not a string"
+                                % (name, member))
+        key = _generate_enum_string(member)
+        if key in values:
+            raise QAPIExprError(expr_info,
+                                "enum '%s' member '%s' clashes with '%s'"
+                                % (name, member, values[key]))
+        values[key] = member
+
 def check_exprs(schema):
     for expr_elem in schema.exprs:
         expr = expr_elem['expr']
+        info = expr_elem['info']
+
         if expr.has_key('union'):
-            check_union(expr, expr_elem['info'])
+            check_union(expr, info)
         if expr.has_key('event'):
-            check_event(expr, expr_elem['info'])
+            check_event(expr, info)
+        if expr.has_key('enum'):
+            check_enum(expr, info)
 
 def parse_schema(input_file):
     try:
@@ -336,7 +360,7 @@ def parse_schema(input_file):
     for expr_elem in schema.exprs:
         expr = expr_elem['expr']
         if expr.has_key('enum'):
-            add_enum(expr['enum'], expr['data'])
+            add_enum(expr['enum'], expr.get('data'))
         elif expr.has_key('union'):
             add_union(expr)
         elif expr.has_key('type'):
tests/qapi-schema/enum-clash-member.err +1 -0
index e69de29..3731fc2 100644
@@ -0,0 +1 @@
+tests/qapi-schema/enum-clash-member.json:2: enum 'MyEnum' member 'ONE' clashes with 'one'
tests/qapi-schema/enum-clash-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-clash-member.json +0 -0
index cb4b428..c668ff5 100644

tests/qapi-schema/enum-clash-member.json line 2

Quoted 3 lines
tests/qapi-schema/enum-clash-member.json +1 -1
@@ -1,2 +1,2 @@
-# FIXME: we should reject enums where members will clash in C switch
+# we reject enums where members will clash in C switch
 { 'enum': 'MyEnum', 'data': [ 'one', 'ONE' ] }

Actually in PATCH 05 already: "clash in C switch". I guess you mean we generate an enum with clashing enumeration constants. In the test case, we'd generate MY_ENUM_ONE (I think) both for 'one' and 'ONE'. Correct?

Quoted 13 lines
tests/qapi-schema/enum-clash-member.out +0 -3
index 0814459..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('enum', 'MyEnum'), ('data', ['one', 'ONE'])])]
-[{'enum_name': 'MyEnum', 'enum_values': ['one', 'ONE']}]
-[]
tests/qapi-schema/enum-dict-member.err +0 -0
index e69de29..f5a8ffe 100644

tests/qapi-schema/enum-dict-member.err line 1

Quoted 1 line
tests/qapi-schema/enum-dict-member.err +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/enum-dict-member.json:2: enum 'MyEnum' member 'OrderedDict([('value', 'str')])' is not a string

Error message is in terms of implementation instead of source. Since this is merely a development tool, it'll do. Same elsewhere, and I'm not going to flag it. Precedents in master quite possible.

Quoted 41 lines
tests/qapi-schema/enum-dict-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-dict-member.json +1 -1
index de4d6bf..79672e0 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject any enum member that is not a string
+# we reject any enum member that is not a string
 { 'enum': 'MyEnum', 'data': [ { 'value': 'str' } ] }
tests/qapi-schema/enum-dict-member.out +0 -3
index 8b293f8..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('enum', 'MyEnum'), ('data', [OrderedDict([('value', 'str')])])])]
-[{'enum_name': 'MyEnum', 'enum_values': [OrderedDict([('value', 'str')])]}]
-[]
tests/qapi-schema/enum-max-member.err +1 -0
index e69de29..a6c5db1 100644
@@ -0,0 +1 @@
+tests/qapi-schema/enum-max-member.json:3: enum 'MyEnum' member 'max' clashes with '(automatic)'
tests/qapi-schema/enum-max-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-max-member.json +0 -0
index ea854c4..6af4662 100644

tests/qapi-schema/enum-max-member.json line 2

Quoted 4 lines
tests/qapi-schema/enum-max-member.json +2 -2
@@ -1,3 +1,3 @@
-# FIXME: we should either reject user-supplied 'max', or munge the implicit
-# max value we generate at the end of an array
+# we reject user-supplied 'max' for clashing with implicit enum end
+# FIXME: should we instead munge the the implicit value to avoid the clash?

Or pick an identifier for the max member so that it cannot clash with the ones we generate for the user's members.

The generator picks identifiers pretty much thoughtlessly in general. If something clashes, the C compiler spits it out, and you get to fiddle with the .json.

[...]

author
#14 lore raw

Re: [Qemu-devel] [PATCH v4 06/19] qapi: Better error messages for bad enums

Quoted 39 lines · Markus Armbruster
Quoted 37 lines · Eric Blake

The previous commit demonstrated that the generator had several flaws with less-than-perfect enums:
- an enum that listed the same string twice (or two variant strings that map to the same C enum) ended up generating an invalid C enum
- because the generator adds a _MAX terminator to each enum, the use of an enum member 'max' can also cause this clash
- if an enum omits 'data', the generator left a python stack trace rather than a graceful message
- an enum used a non-array 'data' was silently accepted by the parser
- an enum that used non-string members in the 'data' member was silently accepted by the parser

Add check_enum to cover these situations, and update testcases to match. While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---

tests/qapi-schema/enum-clash-member.err +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/enum-clash-member.json:2: enum 'MyEnum' member 'ONE' clashes with 'one'
tests/qapi-schema/enum-clash-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-clash-member.json +0 -0
index cb4b428..c668ff5 100644
Quoted 8 lines

tests/qapi-schema/enum-clash-member.json line 2

Quoted 4 lines
tests/qapi-schema/enum-clash-member.json +1 -1
@@ -1,2 +1,2 @@
-# FIXME: we should reject enums where members will clash in C switch
+# we reject enums where members will clash in C switch
 { 'enum': 'MyEnum', 'data': [ 'one', 'ONE' ] }

Actually in PATCH 05 already: "clash in C switch". I guess you mean we generate an enum with clashing enumeration constants. In the test case, we'd generate MY_ENUM_ONE (I think) both for 'one' and 'ONE'. Correct?

Correct; the generated C code would include an invalid switch statement with two repetitions of the same spelling of a case label. In patch 5, the test case demonstrates that the parser was silently accepting code that resulted in a clash in the generated C code; this patch updates both qapi.py to make it a hard error, and the testsuite to change from (accidental) pass to (intentional) error detection, so that we no longer have to worry about the issue in the generated C code.

The same principle applies throughout my series - I first introduced new tests in isolation for existing pre-patch behavior, with FIXME comments where the tests expose bogus behavior, then in later patches fix the parser to reject bogus behavior and update the test to match that it now covers the new error message.

Quoted 7 lines

tests/qapi-schema/enum-clash-member.json line 1

Quoted 3 lines

+++ b/tests/qapi-schema/enum-dict-member.err

tests/qapi-schema/enum-clash-member.json +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/enum-dict-member.json:2: enum 'MyEnum' member 'OrderedDict([('value', 'str')])' is not a string

Error message is in terms of implementation instead of source. Since this is merely a development tool, it'll do. Same elsewhere, and I'm not going to flag it. Precedents in master quite possible.

Yeah, I couldn't figure a way to get back at the original text typed by the user. I'm open to suggestions, but I'm (obviously) okay with leaving it as is.

Quoted 10 lines

tests/qapi-schema/enum-clash-member.json line 2

Quoted 6 lines

+++ b/tests/qapi-schema/enum-max-member.json

tests/qapi-schema/enum-clash-member.json +2 -2
@@ -1,3 +1,3 @@
-# FIXME: we should either reject user-supplied 'max', or munge the implicit
-# max value we generate at the end of an array
+# we reject user-supplied 'max' for clashing with implicit enum end
+# FIXME: should we instead munge the the implicit value to avoid the clash?

Or pick an identifier for the max member so that it cannot clash with the ones we generate for the user's members.

Quoted 3 lines

The generator picks identifiers pretty much thoughtlessly in general. If something clashes, the C compiler spits it out, and you get to fiddle with the .json.

Well, hopefully by hoisting the error message away from C compilation time (late) to qapi.py runtime (early), we have made it easier for anyone actually needing the name 'max' to identify what still needs fixing. At any rate, I'm always a fan of erroring out as early as possible, rather than waiting for an obscure crash later on in the C compilation :)

Quoted 4 lines

[...]

Thanks.

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

Re: [Qemu-devel] [PATCH v4 06/19] qapi: Better error messages for bad enums

Quoted 49 lines · Eric Blake
Quoted 39 lines · Markus Armbruster
Quoted 37 lines · Eric Blake

The previous commit demonstrated that the generator had several flaws with less-than-perfect enums:
- an enum that listed the same string twice (or two variant strings that map to the same C enum) ended up generating an invalid C enum
- because the generator adds a _MAX terminator to each enum, the use of an enum member 'max' can also cause this clash
- if an enum omits 'data', the generator left a python stack trace rather than a graceful message
- an enum used a non-array 'data' was silently accepted by the parser
- an enum that used non-string members in the 'data' member was silently accepted by the parser

Add check_enum to cover these situations, and update testcases to match. While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---

tests/qapi-schema/enum-clash-member.err +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/enum-clash-member.json:2: enum 'MyEnum' member 'ONE' clashes with 'one'
tests/qapi-schema/enum-clash-member.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/enum-clash-member.json +0 -0
index cb4b428..c668ff5 100644
Quoted 8 lines

tests/qapi-schema/enum-clash-member.json line 2

Quoted 4 lines
tests/qapi-schema/enum-clash-member.json +1 -1
@@ -1,2 +1,2 @@
-# FIXME: we should reject enums where members will clash in C switch
+# we reject enums where members will clash in C switch
 { 'enum': 'MyEnum', 'data': [ 'one', 'ONE' ] }

Actually in PATCH 05 already: "clash in C switch". I guess you mean we generate an enum with clashing enumeration constants. In the test case, we'd generate MY_ENUM_ONE (I think) both for 'one' and 'ONE'. Correct?

Quoted 2 lines

Correct; the generated C code would include an invalid switch statement with two repetitions of the same spelling of a case label.

Actually, it generates a broken enum definition.

For instance,

    { 'enum': 'MyEnum', 'data': [ 'one', 'ONE' ] }

produces

    typedef enum BadEnum
    {
        BAD_ENUM_ONE = 0,
        BAD_ENUM_ONE = 1,
        BAD_ENUM_MAX = 2,
    } BadEnum;

Drop "in C switch" from the comment?

Quoted 7 lines

In patch 5,
the test case demonstrates that the parser was silently accepting code that resulted in a clash in the generated C code; this patch updates both qapi.py to make it a hard error, and the testsuite to change from (accidental) pass to (intentional) error detection, so that we no longer have to worry about the issue in the generated C code.

Quoted 5 lines

The same principle applies throughout my series - I first introduced new tests in isolation for existing pre-patch behavior, with FIXME comments where the tests expose bogus behavior, then in later patches fix the parser to reject bogus behavior and update the test to match that it now covers the new error message.

That's exactly how I like it done.

Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

+++ b/tests/qapi-schema/enum-dict-member.err

tests/qapi-schema/enum-clash-member.json +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/enum-dict-member.json:2: enum 'MyEnum' member

OrderedDict([('value', 'str')])' is not a string

Error message is in terms of implementation instead of source. Since this is merely a development tool, it'll do. Same elsewhere, and I'm not going to flag it. Precedents in master quite possible.

Quoted 3 lines

Yeah, I couldn't figure a way to get back at the original text typed by the user. I'm open to suggestions, but I'm (obviously) okay with leaving it as is.

Let's leave it as is for now.

Quoted 14 lines
Quoted 10 lines

tests/qapi-schema/enum-clash-member.json line 2

Quoted 6 lines

+++ b/tests/qapi-schema/enum-max-member.json

tests/qapi-schema/enum-clash-member.json +2 -2
@@ -1,3 +1,3 @@
-# FIXME: we should either reject user-supplied 'max', or munge the implicit
-# max value we generate at the end of an array
+# we reject user-supplied 'max' for clashing with implicit enum end
+# FIXME: should we instead munge the the implicit value to avoid the clash?

Or pick an identifier for the max member so that it cannot clash with the ones we generate for the user's members.

Quoted 3 lines

The generator picks identifiers pretty much thoughtlessly in general. If something clashes, the C compiler spits it out, and you get to fiddle with the .json.

Quoted 6 lines

Well, hopefully by hoisting the error message away from C compilation time (late) to qapi.py runtime (early), we have made it easier for anyone actually needing the name 'max' to identify what still needs fixing. At any rate, I'm always a fan of erroring out as early as possible, rather than waiting for an obscure crash later on in the C compilation :)

One saturday of happy hacking, followed by years of chipping away at the mess...

Quoted 5 lines
Quoted 3 lines

[...]

Thanks.

author
#16 lore raw

PATCH v4 7/19 qapi: Add some expr tests

In reply to Eric Blake

Demonstrate that the qapi generator doesn't deal well with expressions that aren't up to par. Later patches will improve the expected results as the generator is made stricter. Only one of the added tests actually behaves sanely at rejecting obvious problems.

Note that in some cases, we reject bad QAPI merely because our pseudo-JSON parser does not yet know how to parse numbers. This series does not address that, but when a later series adds support for numeric defaults of integer fields, the testsuite will ensure that we don't lose the error (and hopefully that the error message quality is improved).

---
 tests/Makefile                          | 4 +++-
 tests/qapi-schema/bad-type-dict.err     | 0
 tests/qapi-schema/bad-type-dict.exit    | 1 +
 tests/qapi-schema/bad-type-dict.json    | 2 ++
 tests/qapi-schema/bad-type-dict.out     | 3 +++
 tests/qapi-schema/bad-type-int.err      | 1 +
 tests/qapi-schema/bad-type-int.exit     | 1 +
 tests/qapi-schema/bad-type-int.json     | 3 +++
 tests/qapi-schema/bad-type-int.out      | 0
 tests/qapi-schema/double-data.err       | 1 +
 tests/qapi-schema/double-data.exit      | 1 +
 tests/qapi-schema/double-data.json      | 2 ++
 tests/qapi-schema/double-data.out       | 0
 tests/qapi-schema/double-type.err       | 0
 tests/qapi-schema/double-type.exit      | 1 +
 tests/qapi-schema/double-type.json      | 2 ++
 tests/qapi-schema/double-type.out       | 3 +++
 tests/qapi-schema/missing-type.err      | 0
 tests/qapi-schema/missing-type.exit     | 1 +
 tests/qapi-schema/missing-type.json     | 2 ++
 tests/qapi-schema/missing-type.out      | 3 +++
 tests/qapi-schema/unknown-expr-key.err  | 0
 tests/qapi-schema/unknown-expr-key.exit | 1 +
 tests/qapi-schema/unknown-expr-key.json | 2 ++
 tests/qapi-schema/unknown-expr-key.out  | 3 +++
 25 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 tests/qapi-schema/bad-type-dict.err
 create mode 100644 tests/qapi-schema/bad-type-dict.exit
 create mode 100644 tests/qapi-schema/bad-type-dict.json
 create mode 100644 tests/qapi-schema/bad-type-dict.out
 create mode 100644 tests/qapi-schema/bad-type-int.err
 create mode 100644 tests/qapi-schema/bad-type-int.exit
 create mode 100644 tests/qapi-schema/bad-type-int.json
 create mode 100644 tests/qapi-schema/bad-type-int.out
 create mode 100644 tests/qapi-schema/double-data.err
 create mode 100644 tests/qapi-schema/double-data.exit
 create mode 100644 tests/qapi-schema/double-data.json
 create mode 100644 tests/qapi-schema/double-data.out
 create mode 100644 tests/qapi-schema/double-type.err
 create mode 100644 tests/qapi-schema/double-type.exit
 create mode 100644 tests/qapi-schema/double-type.json
 create mode 100644 tests/qapi-schema/double-type.out
 create mode 100644 tests/qapi-schema/missing-type.err
 create mode 100644 tests/qapi-schema/missing-type.exit
 create mode 100644 tests/qapi-schema/missing-type.json
 create mode 100644 tests/qapi-schema/missing-type.out
 create mode 100644 tests/qapi-schema/unknown-expr-key.err
 create mode 100644 tests/qapi-schema/unknown-expr-key.exit
 create mode 100644 tests/qapi-schema/unknown-expr-key.json
 create mode 100644 tests/qapi-schema/unknown-expr-key.out
tests/Makefile +3 -1
index 6a4e5a6..753f7bd 100644
@@ -198,7 +198,9 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
 	comments.json empty.json enum-empty.json enum-missing-data.json \
 	enum-wrong-data.json enum-int-member.json enum-dict-member.json \
 	enum-clash-member.json enum-max-member.json \
-	funny-char.json indented-expr.json \
+	funny-char.json indented-expr.json missing-type.json \
+	double-type.json bad-type-int.json bad-type-dict.json \
+	double-data.json unknown-expr-key.json \
 	missing-colon.json missing-comma-list.json \
 	missing-comma-object.json non-objects.json \
 	qapi-schema-test.json quoted-structural-chars.json \
tests/qapi-schema/bad-type-dict.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/bad-type-dict.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/bad-type-dict.json new file +2 -0
new file mode 100644
index 0000000..3c392a7
@@ -0,0 +1,2 @@
+# FIXME: we should reject an expression with a metatype that is not a string
+{ 'command': { } }
tests/qapi-schema/bad-type-dict.out new file +3 -0
new file mode 100644
index 0000000..c62f1ed
@@ -0,0 +1,3 @@
+[OrderedDict([('command', OrderedDict())])]
+[]
+[]
tests/qapi-schema/bad-type-int.err new file +1 -0
new file mode 100644
index 0000000..9808550
@@ -0,0 +1 @@
+tests/qapi-schema/bad-type-int.json:3:11: Stray "1"
tests/qapi-schema/bad-type-int.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/bad-type-int.json new file +3 -0
new file mode 100644
index 0000000..398879d
@@ -0,0 +1,3 @@
+# we reject an expression with a metatype that is not a string
+# FIXME: once the parser understands integer inputs, improve the error message
+{ 'type': 1, 'data': { } }
tests/qapi-schema/bad-type-int.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/double-data.err new file +1 -0
new file mode 100644
index 0000000..6f1a67b
@@ -0,0 +1 @@
+tests/qapi-schema/double-data.json:2:39: Duplicate key "data"
tests/qapi-schema/double-data.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/double-data.json new file +2 -0
new file mode 100644
index 0000000..a94b7df
@@ -0,0 +1,2 @@
+# we reject an expression with duplicate top-level keys
+{ 'type': 'bar', 'data': { }, 'data': { 'string': 'str'} }
tests/qapi-schema/double-data.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/double-type.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/double-type.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/double-type.json new file +2 -0
new file mode 100644
index 0000000..6ca96b9
@@ -0,0 +1,2 @@
+# FIXME: we should reject an expression with ambiguous metatype
+{ 'command': 'foo', 'type': 'bar', 'data': { } }
tests/qapi-schema/double-type.out new file +3 -0
new file mode 100644
index 0000000..3e244f5
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'foo'), ('type', 'bar'), ('data', OrderedDict())])]
+[]
+[OrderedDict([('command', 'foo'), ('type', 'bar'), ('data', OrderedDict())])]
tests/qapi-schema/missing-type.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/missing-type.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/missing-type.json new file +2 -0
new file mode 100644
index 0000000..1696f5c
@@ -0,0 +1,2 @@
+# FIXME: we should reject an expression with missing metatype
+{ 'data': { } }
tests/qapi-schema/missing-type.out new file +3 -0
new file mode 100644
index 0000000..67fd4fa
@@ -0,0 +1,3 @@
+[OrderedDict([('data', OrderedDict())])]
+[]
+[]
tests/qapi-schema/unknown-expr-key.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/unknown-expr-key.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/unknown-expr-key.json new file +2 -0
new file mode 100644
index 0000000..1e9282d
@@ -0,0 +1,2 @@
+# FIXME: we should reject an expression with unknown top-level keys
+{ 'type': 'bar', 'data': { 'string': 'str'}, 'bogus': { } }
tests/qapi-schema/unknown-expr-key.out new file +3 -0
new file mode 100644
index 0000000..c93f020
@@ -0,0 +1,3 @@
+[OrderedDict([('type', 'bar'), ('data', OrderedDict([('string', 'str')])), ('bogus', OrderedDict())])]
+[]
+[OrderedDict([('type', 'bar'), ('data', OrderedDict([('string', 'str')])), ('bogus', OrderedDict())])]
Signature · 1 line
1.9.3
Reviewed-by on v4 7/19
#17 lore raw

Re: [Qemu-devel] [PATCH v4 07/19] qapi: Add some expr tests

Quoted 6 lines · Eric Blake

Demonstrate that the qapi generator doesn't deal well with expressions that aren't up to par. Later patches will improve the expected results as the generator is made stricter. Only one of the added tests actually behaves sanely at rejecting obvious problems.

Quoted 8 lines

Note that in some cases, we reject bad QAPI merely because our pseudo-JSON parser does not yet know how to parse numbers. This series does not address that, but when a later series adds support for numeric defaults of integer fields, the testsuite will ensure that we don't lose the error (and hopefully that the error message quality is improved).

author
#18 lore raw

PATCH v4 8/19 qapi: Better error messages for bad expressions

In reply to Eric Blake

The previous commit demonstrated that the generator overlooked some fairly basic broken expressions:
- missing metataype
- metatype key has a non-string value
- unknown key in relation to the metatype
- conflicting metatype (this patch treats the second metatype as an unknown key of the first key visited, which is not necessarily the first key the user typed)

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---
 scripts/qapi.py                         | 76 +++++++++++++++++++++++++--------
 tests/qapi-schema/bad-type-dict.err     |  1 +
 tests/qapi-schema/bad-type-dict.exit    |  2 +-
 tests/qapi-schema/bad-type-dict.json    |  2 +-
 tests/qapi-schema/bad-type-dict.out     |  3 --
 tests/qapi-schema/double-type.err       |  1 +
 tests/qapi-schema/double-type.exit      |  2 +-
 tests/qapi-schema/double-type.json      |  2 +-
 tests/qapi-schema/double-type.out       |  3 --
 tests/qapi-schema/enum-missing-data.err |  2 +-
 tests/qapi-schema/indented-expr.json    |  4 +-
 tests/qapi-schema/indented-expr.out     |  2 +-
 tests/qapi-schema/missing-type.err      |  1 +
 tests/qapi-schema/missing-type.exit     |  2 +-
 tests/qapi-schema/missing-type.json     |  2 +-
 tests/qapi-schema/missing-type.out      |  3 --
 tests/qapi-schema/unknown-expr-key.err  |  1 +
 tests/qapi-schema/unknown-expr-key.exit |  2 +-
 tests/qapi-schema/unknown-expr-key.json |  2 +-
 tests/qapi-schema/unknown-expr-key.out  |  3 --
 20 files changed, 75 insertions(+), 41 deletions(-)
scripts/qapi.py +59 -17
index 85aa8bf..8fbc45f 100644
@@ -348,7 +348,29 @@ def check_exprs(schema):
         if expr.has_key('enum'):
             check_enum(expr, info)
 
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]
+    if not isinstance(name, basestring):
+        raise QAPIExprError(info,
+                            "%s key must have a string value" % meta)
+    expr_elem['name'] = name
+    required.append(meta)
+    for (key, value) in expr.items():
+        if not key in required and not key in optional:
+            raise QAPIExprError(info,
+                                "%s '%s' has unknown key '%s'"
+                                % (meta, name, key))
+    for key in required:
+        if not expr.has_key(key):
+            raise QAPIExprError(info,
+                                "%s '%s' is missing key '%s'"
+                                % (meta, name, key))
+
+
 def parse_schema(input_file):
+    # First pass: read entire file into memory
     try:
         schema = QAPISchema(open(input_file, "r"))
     except (QAPISchemaError, QAPIExprError), e:
@@ -357,24 +379,44 @@ def parse_schema(input_file):
 
     exprs = []
 
-    for expr_elem in schema.exprs:
-        expr = expr_elem['expr']
-        if expr.has_key('enum'):
-            add_enum(expr['enum'], expr.get('data'))
-        elif expr.has_key('union'):
-            add_union(expr)
-        elif expr.has_key('type'):
-            add_struct(expr)
-        exprs.append(expr)
-
-    # Try again for hidden UnionKind enum
-    for expr_elem in schema.exprs:
-        expr = expr_elem['expr']
-        if expr.has_key('union'):
-            if not discriminator_find_enum_define(expr):
-                add_enum('%sKind' % expr['union'])
-
     try:
+        # Next pass: learn the types and check for valid expression keys. At
+        # this point, top-level 'include' has already been flattened.
+        for expr_elem in schema.exprs:
+            expr = expr_elem['expr']
+            if expr.has_key('enum'):
+                check_keys(expr_elem, 'enum', ['data'])
+                add_enum(expr['enum'], expr['data'])
+            elif expr.has_key('union'):
+                # Two styles of union, based on discriminator
+                discriminator = expr.get('discriminator')
+                if discriminator == {}:
+                    check_keys(expr_elem, 'union', ['data', 'discriminator'])
+                else:
+                    check_keys(expr_elem, 'union', ['data'],
+                               ['base', 'discriminator'])
+                add_union(expr)
+            elif expr.has_key('type'):
+                check_keys(expr_elem, 'type', ['data'], ['base'])
+                add_struct(expr)
+            elif expr.has_key('command'):
+                check_keys(expr_elem, 'command', [],
+                           ['data', 'returns', 'gen', 'success-response'])
+            elif expr.has_key('event'):
+                check_keys(expr_elem, 'event', [], ['data'])
+            else:
+                raise QAPIExprError(expr_elem['info'],
+                                    "expression is missing metatype")
+            exprs.append(expr)
+
+        # Try again for hidden UnionKind enum
+        for expr_elem in schema.exprs:
+            expr = expr_elem['expr']
+            if expr.has_key('union'):
+                if not discriminator_find_enum_define(expr):
+                    add_enum('%sKind' % expr['union'])
+
+        # Final pass - validate that exprs make sense
         check_exprs(schema)
     except QAPIExprError, e:
         print >>sys.stderr, e
tests/qapi-schema/bad-type-dict.err +1 -0
index e69de29..b7c73cc 100644
@@ -0,0 +1 @@
+tests/qapi-schema/bad-type-dict.json:2: command key must have a string value
tests/qapi-schema/bad-type-dict.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/bad-type-dict.json +1 -1
index 3c392a7..2a91b24 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an expression with a metatype that is not a string
+# we reject an expression with a metatype that is not a string
 { 'command': { } }
tests/qapi-schema/bad-type-dict.out +0 -3
index c62f1ed..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', OrderedDict())])]
-[]
-[]
tests/qapi-schema/double-type.err +1 -0
index e69de29..394127b 100644
@@ -0,0 +1 @@
+tests/qapi-schema/double-type.json:2: type 'bar' has unknown key 'command'
tests/qapi-schema/double-type.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/double-type.json +1 -1
index 6ca96b9..471623a 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an expression with ambiguous metatype
+# we reject an expression with ambiguous metatype
 { 'command': 'foo', 'type': 'bar', 'data': { } }
tests/qapi-schema/double-type.out +0 -3
index 3e244f5..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'foo'), ('type', 'bar'), ('data', OrderedDict())])]
-[]
-[OrderedDict([('command', 'foo'), ('type', 'bar'), ('data', OrderedDict())])]
tests/qapi-schema/enum-missing-data.err +1 -1
index 4b8b59e..62f4a7f 100644
@@ -1 +1 @@
-tests/qapi-schema/enum-missing-data.json:2: enum 'MyEnum' requires an array for 'data'
+tests/qapi-schema/enum-missing-data.json:2: enum 'MyEnum' is missing key 'data'
tests/qapi-schema/indented-expr.json +2 -2
index d80af60..7115d31 100644
@@ -1,2 +1,2 @@
-{ 'id' : 'eins' }
- { 'id' : 'zwei' }
+{ 'command' : 'eins' }
+ { 'command' : 'zwei' }
tests/qapi-schema/indented-expr.out +1 -1
index 98af89a..b5ce915 100644
@@ -1,3 +1,3 @@
-[OrderedDict([('id', 'eins')]), OrderedDict([('id', 'zwei')])]
+[OrderedDict([('command', 'eins')]), OrderedDict([('command', 'zwei')])]
 []
 []
tests/qapi-schema/missing-type.err +1 -0
index e69de29..19b7c49 100644
@@ -0,0 +1 @@
+tests/qapi-schema/missing-type.json:2: expression is missing metatype
tests/qapi-schema/missing-type.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/missing-type.json +1 -1
index 1696f5c..ff5349d 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an expression with missing metatype
+# we reject an expression with missing metatype
 { 'data': { } }
tests/qapi-schema/missing-type.out +0 -3
index 67fd4fa..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('data', OrderedDict())])]
-[]
-[]
tests/qapi-schema/unknown-expr-key.err +1 -0
index e69de29..3b35508 100644
@@ -0,0 +1 @@
+tests/qapi-schema/unknown-expr-key.json:2: type 'bar' has unknown key 'bogus'
tests/qapi-schema/unknown-expr-key.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/unknown-expr-key.json +1 -1
index 1e9282d..ba7bdf3 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an expression with unknown top-level keys
+# we reject an expression with unknown top-level keys
 { 'type': 'bar', 'data': { 'string': 'str'}, 'bogus': { } }
tests/qapi-schema/unknown-expr-key.out +0 -3
index c93f020..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('type', 'bar'), ('data', OrderedDict([('string', 'str')])), ('bogus', OrderedDict())])]
-[]
-[OrderedDict([('type', 'bar'), ('data', OrderedDict([('string', 'str')])), ('bogus', OrderedDict())])]
Signature · 1 line
1.9.3
#19 lore raw

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

Quoted 8 lines · Eric Blake

The previous commit demonstrated that the generator overlooked some fairly basic broken expressions:
- missing metataype
- metatype key has a non-string value
- unknown key in relation to the metatype
- conflicting metatype (this patch treats the second metatype as an unknown key of the first key visited, which is not necessarily the first key the user typed)

The whole thing is a Saturday afternoon hack, with extra hacks bolted on left & right.

Quoted 38 lines

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---
 scripts/qapi.py                         | 76 +++++++++++++++++++++++++--------
 tests/qapi-schema/bad-type-dict.err     |  1 +
 tests/qapi-schema/bad-type-dict.exit    |  2 +-
 tests/qapi-schema/bad-type-dict.json    |  2 +-
 tests/qapi-schema/bad-type-dict.out     |  3 --
 tests/qapi-schema/double-type.err       |  1 +
 tests/qapi-schema/double-type.exit      |  2 +-
 tests/qapi-schema/double-type.json      |  2 +-
 tests/qapi-schema/double-type.out       |  3 --
 tests/qapi-schema/enum-missing-data.err |  2 +-
 tests/qapi-schema/indented-expr.json    |  4 +-
 tests/qapi-schema/indented-expr.out     |  2 +-
 tests/qapi-schema/missing-type.err      |  1 +
 tests/qapi-schema/missing-type.exit     |  2 +-
 tests/qapi-schema/missing-type.json     |  2 +-
 tests/qapi-schema/missing-type.out      |  3 --
 tests/qapi-schema/unknown-expr-key.err  |  1 +
 tests/qapi-schema/unknown-expr-key.exit |  2 +-
 tests/qapi-schema/unknown-expr-key.json |  2 +-
 tests/qapi-schema/unknown-expr-key.out  |  3 --
 20 files changed, 75 insertions(+), 41 deletions(-)
scripts/qapi.py +0 -0
index 85aa8bf..8fbc45f 100644

scripts/qapi.py def check_exprs(schema): · line 354

Quoted 7 lines
scripts/qapi.py +4 -0
@@ -348,7 +348,29 @@ def check_exprs(schema):
         if expr.has_key('enum'):
             check_enum(expr, info)
 
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]

Caller ensures expr[meta] exists. Okay.

scripts/qapi.py def check_exprs(schema): · line 355

Quoted 1 line
scripts/qapi.py +1 -0
+    if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

scripts/qapi.py def check_exprs(schema): · line 358

Quoted 3 lines
scripts/qapi.py +3 -0
+        raise QAPIExprError(info,
+                            "%s key must have a string value" % meta)
+    expr_elem['name'] = name

Where is this used?

scripts/qapi.py def check_exprs(schema): · line 359

Quoted 1 line
scripts/qapi.py +1 -0
+    required.append(meta)

Ugly side effect. To avoid, either make a new list here

required = required + [ meta ]

or do nothing here and...

scripts/qapi.py def check_exprs(schema): · line 361

Quoted 2 lines
scripts/qapi.py +2 -0
+    for (key, value) in expr.items():
+        if not key in required and not key in optional:

... add "and key != meta" to this condition.

Quoted 67 lines
scripts/qapi.py +41 -17
+            raise QAPIExprError(info,
+                                "%s '%s' has unknown key '%s'"
+                                % (meta, name, key))
+    for key in required:
+        if not expr.has_key(key):
+            raise QAPIExprError(info,
+                                "%s '%s' is missing key '%s'"
+                                % (meta, name, key))
+
+
 def parse_schema(input_file):
+    # First pass: read entire file into memory
     try:
         schema = QAPISchema(open(input_file, "r"))
     except (QAPISchemaError, QAPIExprError), e:
@@ -357,24 +379,44 @@ def parse_schema(input_file):
 
     exprs = []
 
-    for expr_elem in schema.exprs:
-        expr = expr_elem['expr']
-        if expr.has_key('enum'):
-            add_enum(expr['enum'], expr.get('data'))
-        elif expr.has_key('union'):
-            add_union(expr)
-        elif expr.has_key('type'):
-            add_struct(expr)
-        exprs.append(expr)
-
-    # Try again for hidden UnionKind enum
-    for expr_elem in schema.exprs:
-        expr = expr_elem['expr']
-        if expr.has_key('union'):
-            if not discriminator_find_enum_define(expr):
-                add_enum('%sKind' % expr['union'])
-
     try:
+        # Next pass: learn the types and check for valid expression keys. At
+        # this point, top-level 'include' has already been flattened.
+        for expr_elem in schema.exprs:
+            expr = expr_elem['expr']
+            if expr.has_key('enum'):
+                check_keys(expr_elem, 'enum', ['data'])
+                add_enum(expr['enum'], expr['data'])
+            elif expr.has_key('union'):
+                # Two styles of union, based on discriminator
+                discriminator = expr.get('discriminator')
+                if discriminator == {}:
+                    check_keys(expr_elem, 'union', ['data', 'discriminator'])
+                else:
+                    check_keys(expr_elem, 'union', ['data'],
+                               ['base', 'discriminator'])
+                add_union(expr)
+            elif expr.has_key('type'):
+                check_keys(expr_elem, 'type', ['data'], ['base'])
+                add_struct(expr)
+            elif expr.has_key('command'):
+                check_keys(expr_elem, 'command', [],
+                           ['data', 'returns', 'gen', 'success-response'])
+            elif expr.has_key('event'):
+                check_keys(expr_elem, 'event', [], ['data'])
+            else:
+                raise QAPIExprError(expr_elem['info'],
+                                    "expression is missing metatype")
+            exprs.append(expr)
+
+        # Try again for hidden UnionKind enum

scripts/qapi.py def parse_schema(input_file): · line 422

Quoted 10 lines
scripts/qapi.py +7 -0
+        for expr_elem in schema.exprs:
+            expr = expr_elem['expr']
+            if expr.has_key('union'):
+                if not discriminator_find_enum_define(expr):
+                    add_enum('%sKind' % expr['union'])
+
+        # Final pass - validate that exprs make sense
         check_exprs(schema)
     except QAPIExprError, e:
         print >>sys.stderr, e

This hunk is easier to review with whitespace ignored:

@@ -356,13 +356,34 @@

       exprs = []
  -    for expr_elem in schema.exprs:
  +    try:
  +        # Next pass: learn the types and check for valid expression keys. At
  +        # this point, top-level 'include' has already been flattened.
  +        for expr_elem in schema.exprs:
           expr = expr_elem['expr']
           if expr.has_key('enum'):
  -            add_enum(expr['enum'], expr.get('data'))
  +                check_keys(expr_elem, 'enum', ['data'])
  +                add_enum(expr['enum'], expr['data'])
           elif expr.has_key('union'):
  +                # Two styles of union, based on discriminator
  +                discriminator = expr.get('discriminator')
  +                if discriminator == {}:
  +                    check_keys(expr_elem, 'union', ['data', 'discriminator'])
  +                else:
  +                    check_keys(expr_elem, 'union', ['data'],
  +                               ['base', 'discriminator'])
               add_union(expr)
           elif expr.has_key('type'):

+ check_keys(expr_elem, 'type', ['data'], ['base'])
add_struct(expr)
+ elif expr.has_key('command'):
+ check_keys(expr_elem, 'command', [],
+ ['data', 'returns', 'gen', 'success-response'])
+ elif expr.has_key('event'):
+ check_keys(expr_elem, 'event', [], ['data'])
+ else:
+ raise QAPIExprError(expr_elem['info'],
+ "expression is missing metatype")
exprs.append(expr)

# Try again for hidden UnionKind enum
@@ -372,7 +393,7 @@
if not discriminator_find_enum_define(expr):
add_enum('%sKind' % expr['union'])

- try:
+ # Final pass - validate that exprs make sense
check_exprs(schema)
except QAPIExprError, e:
print >>sys.stderr, e

Looks good to me. The tests, too.

[...]

author
#20 lore raw

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

Quoted 11 lines · Markus Armbruster
Quoted 8 lines · Eric Blake

The previous commit demonstrated that the generator overlooked some fairly basic broken expressions:
- missing metataype
- metatype key has a non-string value
- unknown key in relation to the metatype
- conflicting metatype (this patch treats the second metatype as an unknown key of the first key visited, which is not necessarily the first key the user typed)

Quoted 2 lines

The whole thing is a Saturday afternoon hack, with extra hacks bolted on left & right.

And this series is a sequence of MY Saturday afternoon hacks in cleaning it up :)

Quoted 17 lines
Quoted 12 lines

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

scripts/qapi.py def check_exprs(schema): · line 354

Quoted 4 lines
scripts/qapi.py +4 -0
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]
Quoted 5 lines

Caller ensures expr[meta] exists. Okay.

Quoted 1 line

+ if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

Me too. No clue. Copy and paste from existing code.
http://git.qemu.org/?p=qemu.git;a=blob;f=scripts/qapi.py;h=77d46aa;hb=769188d3b#l361

Quoted 6 lines

scripts/qapi.py def check_exprs(schema): · line 358

Quoted 4 lines
scripts/qapi.py +3 -0
+        raise QAPIExprError(info,
+                            "%s key must have a string value" % meta)
+    expr_elem['name'] = name

Where is this used?

Hmm, I know I used it at one point in my series (to be able to print the name of an expression in check_type added in 13/19, without having to repeat the dance of if enum: expr['enum'] elif union: expr['union'] etc. in multiple places). Although in my refactoring, I may have eliminated the need for it after all. If it's not in use at the end of the series, I can drop it.

Quoted 5 lines
Quoted 2 lines

+ required.append(meta)

Ugly side effect. To avoid, either make a new list here

Quoted 8 lines

required = required + [ meta ]

or do nothing here and...

scripts/qapi.py def check_exprs(schema): · line 361

Quoted 2 lines
scripts/qapi.py +2 -0
+    for (key, value) in expr.items():
+        if not key in required and not key in optional:

... add "and key != meta" to this condition.

Shows my inexperience in python. Sure, I can fix. Looks like I get to spin a v5.

Quoted 2 lines

This hunk is easier to review with whitespace ignored:

Indeed. Alas, python is a stickler about whitespace reindentation. Since I have to respin, I'll probably split into two pieces (one with a no-op change that reindents, the other for the improvements).

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

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

Quoted 12 lines · Eric Blake
Quoted 11 lines · Markus Armbruster
Quoted 8 lines · Eric Blake

The previous commit demonstrated that the generator overlooked some fairly basic broken expressions:
- missing metataype
- metatype key has a non-string value
- unknown key in relation to the metatype
- conflicting metatype (this patch treats the second metatype as an unknown key of the first key visited, which is not necessarily the first key the user typed)

Quoted 5 lines
Quoted 2 lines

The whole thing is a Saturday afternoon hack, with extra hacks bolted on left & right.

And this series is a sequence of MY Saturday afternoon hacks in cleaning it up :)

Much appreciated!

Quoted 16 lines
Quoted 16 lines
Quoted 15 lines

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

scripts/qapi.py +4 -0
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]
Quoted 8 lines
Quoted 5 lines

Caller ensures expr[meta] exists. Okay.

Quoted 1 line

+ if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

Me too. No clue. Copy and paste from existing code.
http://git.qemu.org/?p=qemu.git;a=blob;f=scripts/qapi.py;h=77d46aa;hb=769188d3b#l361

Yes. It's our only use of basestring. Other places use isinstance(FOO, str).

The basestring use comes from Kevin's commit b35284e. Kevin, why basestring and not str?

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
scripts/qapi.py +3 -0
+        raise QAPIExprError(info,
+                            "%s key must have a string value" % meta)
+    expr_elem['name'] = name
Quoted 8 lines
Quoted 1 line

Where is this used?

Hmm, I know I used it at one point in my series (to be able to print the name of an expression in check_type added in 13/19, without having to repeat the dance of if enum: expr['enum'] elif union: expr['union'] etc. in multiple places). Although in my refactoring, I may have eliminated the need for it after all. If it's not in use at the end of the series, I can drop it.

A quick grep comes up empty.

Quoted 17 lines
Quoted 4 lines
Quoted 1 line

+ required.append(meta)

Ugly side effect. To avoid, either make a new list here

Quoted 8 lines

required = required + [ meta ]

or do nothing here and...

scripts/qapi.py def check_exprs(schema): · line 361

Quoted 2 lines
scripts/qapi.py +2 -0
+    for (key, value) in expr.items():
+        if not key in required and not key in optional:

... add "and key != meta" to this condition.

Shows my inexperience in python. Sure, I can fix. Looks like I get to spin a v5.

Quoted 1 line
Quoted 5 lines
Quoted 1 line

This hunk is easier to review with whitespace ignored:

Indeed. Alas, python is a stickler about whitespace reindentation. Since I have to respin, I'll probably split into two pieces (one with a no-op change that reindents, the other for the improvements).

Not necessary for me, I'm comfy with telling Emacs to hide whitespace differences :)

#22 lore raw

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

Am 24.09.2014 um 09:34 hat Markus Armbruster geschrieben:

Quoted 26 lines
Quoted 24 lines · Eric Blake
Quoted 22 lines · Markus Armbruster
Quoted 11 lines · Eric Blake

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

scripts/qapi.py def check_exprs(schema): · line 354

Quoted 4 lines
scripts/qapi.py +4 -0
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]

Caller ensures expr[meta] exists. Okay.

Quoted 1 line

+ if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

Quoted 8 lines
Quoted 2 lines

Me too. No clue. Copy and paste from existing code.
http://git.qemu.org/?p=qemu.git;a=blob;f=scripts/qapi.py;h=77d46aa;hb=769188d3b#l361

Yes. It's our only use of basestring. Other places use isinstance(FOO, str).

The basestring use comes from Kevin's commit b35284e. Kevin, why basestring and not str?

Do I look as if I knew what I'm doing when I write Python code? :-)

Apparently basestring is the superclass for ASCII and Unicode strings. I seem to dimly remember that I did indeed get a Unicode string somewhere (even though probably no non-ASCII characters in it) and it caused trouble. Might well have been here.

Kevin

#23 lore raw

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

Quoted 36 lines · Kevin Wolf

Am 24.09.2014 um 09:34 hat Markus Armbruster geschrieben:

Quoted 26 lines
Quoted 24 lines · Eric Blake
Quoted 22 lines · Markus Armbruster
Quoted 11 lines · Eric Blake

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

scripts/qapi.py def check_exprs(schema): · line 354

Quoted 4 lines
scripts/qapi.py +4 -0
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]

Caller ensures expr[meta] exists. Okay.

Quoted 1 line

+ if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

Quoted 8 lines
Quoted 2 lines

Me too. No clue. Copy and paste from existing code.
http://git.qemu.org/?p=qemu.git;a=blob;f=scripts/qapi.py;h=77d46aa;hb=769188d3b#l361

Yes. It's our only use of basestring. Other places use isinstance(FOO, str).

The basestring use comes from Kevin's commit b35284e. Kevin, why basestring and not str?

Quoted 6 lines

Do I look as if I knew what I'm doing when I write Python code? :-)

Apparently basestring is the superclass for ASCII and Unicode strings. I seem to dimly remember that I did indeed get a Unicode string somewhere (even though probably no non-ASCII characters in it) and it caused trouble. Might well have been here.

Aha. These links apply:

https://stackoverflow.com/questions/11301138/how-to-check-if-variable-is-string-with-python-2-and-3-compatibility
https://en.wikipedia.org/wiki/File:Pieter_Bruegel_the_Elder_%281568%29_The_Blind_Leading_the_Blind.jpg

#24 lore raw

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

In reply to Kevin Wolf
Quoted 36 lines · Kevin Wolf

Am 24.09.2014 um 09:34 hat Markus Armbruster geschrieben:

Quoted 26 lines
Quoted 24 lines · Eric Blake
Quoted 22 lines · Markus Armbruster
Quoted 11 lines · Eric Blake

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

scripts/qapi.py def check_exprs(schema): · line 354

Quoted 4 lines
scripts/qapi.py +4 -0
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]

Caller ensures expr[meta] exists. Okay.

Quoted 1 line

+ if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

Quoted 8 lines
Quoted 2 lines

Me too. No clue. Copy and paste from existing code.
http://git.qemu.org/?p=qemu.git;a=blob;f=scripts/qapi.py;h=77d46aa;hb=769188d3b#l361

Yes. It's our only use of basestring. Other places use isinstance(FOO, str).

The basestring use comes from Kevin's commit b35284e. Kevin, why basestring and not str?

Quoted 6 lines

Do I look as if I knew what I'm doing when I write Python code? :-)

Apparently basestring is the superclass for ASCII and Unicode strings. I seem to dimly remember that I did indeed get a Unicode string somewhere (even though probably no non-ASCII characters in it) and it caused trouble. Might well have been here.

I think there are two sane ways forward:

1. Declare QAPI schemas to be ASCII only for now. Replace the one instance of basestring by plain str.

2. Fix the code to work with both ASCII and Unicode strings even in Python 2. Package six could be used.

I'm voting for 1.

#25 lore raw

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

Am 26.09.2014 um 11:15 hat Markus Armbruster geschrieben:

Quoted 47 lines
Quoted 36 lines · Kevin Wolf

Am 24.09.2014 um 09:34 hat Markus Armbruster geschrieben:

Quoted 26 lines
Quoted 24 lines · Eric Blake
Quoted 22 lines · Markus Armbruster
Quoted 11 lines · Eric Blake

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

scripts/qapi.py def check_exprs(schema): · line 354

Quoted 4 lines
scripts/qapi.py +4 -0
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]

Caller ensures expr[meta] exists. Okay.

Quoted 1 line

+ if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

Quoted 8 lines
Quoted 2 lines

Me too. No clue. Copy and paste from existing code.
http://git.qemu.org/?p=qemu.git;a=blob;f=scripts/qapi.py;h=77d46aa;hb=769188d3b#l361

Yes. It's our only use of basestring. Other places use isinstance(FOO, str).

The basestring use comes from Kevin's commit b35284e. Kevin, why basestring and not str?

Quoted 6 lines

Do I look as if I knew what I'm doing when I write Python code? :-)

Apparently basestring is the superclass for ASCII and Unicode strings. I seem to dimly remember that I did indeed get a Unicode string somewhere (even though probably no non-ASCII characters in it) and it caused trouble. Might well have been here.

I think there are two sane ways forward:

Quoted 7 lines

1. Declare QAPI schemas to be ASCII only for now. Replace the one instance of basestring by plain str.

2. Fix the code to work with both ASCII and Unicode strings even in Python 2. Package six could be used.

I'm voting for 1.

As I said, the problem is probably not about the actual value of the string (I doubt we use anything but ASCII at the moment), but about its type. We may need to convert something somewhere. If you think it's worth the effort of finding that place, go ahead.

Kevin

#26 lore raw

Re: [Qemu-devel] [PATCH v4 08/19] qapi: Better error messages for bad expressions

Quoted 54 lines · Kevin Wolf

Am 26.09.2014 um 11:15 hat Markus Armbruster geschrieben:

Quoted 53 lines
Quoted 36 lines · Kevin Wolf

Am 24.09.2014 um 09:34 hat Markus Armbruster geschrieben:

Quoted 26 lines
Quoted 24 lines · Eric Blake
Quoted 22 lines · Markus Armbruster
Quoted 11 lines · Eric Blake

Add check_keys to cover these situations, and update testcases to match. A couple other tests (enum-missing-data, indented-expr) had to change since the validation added here occurs so early.

While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

Review

Quoted 4 lines
(quoted diff) +4 -0
+def check_keys(expr_elem, meta, required, optional=[]):
+    expr = expr_elem['expr']
+    info = expr_elem['info']
+    name = expr[meta]

Caller ensures expr[meta] exists. Okay.

Quoted 1 line

+ if not isinstance(name, basestring):

I'm a Python noob: why basestring and not str?

Quoted 8 lines
Quoted 2 lines

Me too. No clue. Copy and paste from existing code.
http://git.qemu.org/?p=qemu.git;a=blob;f=scripts/qapi.py;h=77d46aa;hb=769188d3b#l361

Yes. It's our only use of basestring. Other places use isinstance(FOO, str).

The basestring use comes from Kevin's commit b35284e. Kevin, why basestring and not str?

Quoted 6 lines

Do I look as if I knew what I'm doing when I write Python code? :-)

Apparently basestring is the superclass for ASCII and Unicode strings. I seem to dimly remember that I did indeed get a Unicode string somewhere (even though probably no non-ASCII characters in it) and it caused trouble. Might well have been here.

I think there are two sane ways forward:

1. Declare QAPI schemas to be ASCII only for now. Replace the one instance of basestring by plain str.

2. Fix the code to work with both ASCII and Unicode strings even in Python 2. Package six could be used.

Quoted 6 lines
Quoted 1 line

I'm voting for 1.

As I said, the problem is probably not about the actual value of the string (I doubt we use anything but ASCII at the moment), but about its type. We may need to convert something somewhere. If you think it's worth the effort of finding that place, go ahead.

A value always has a concrete type. I'd expect all string values in the qapi scripts to be of type str.

We have to mess with Python 2's basestring only where we need to cope with string values that may be either of type str or of type unicode. Since there should not be any values of type unicode, I don't see why we'd want to do the extra work required for 2.

author
#27 lore raw

PATCH v4 9/19 qapi: Add tests of redefined expressions

In reply to Eric Blake

Demonstrate that the qapi generator doesn't deal very well with redefined expressions. At the parse level, they are silently accepted; I'm not sure what would happen if we tried to go further and use it in generated code, but the end result can't be good. A later patch will tighten things up and adjust the testsuite to match.

---
 tests/Makefile                           | 3 ++-
 tests/qapi-schema/redefined-builtin.err  | 0
 tests/qapi-schema/redefined-builtin.exit | 1 +
 tests/qapi-schema/redefined-builtin.json | 2 ++
 tests/qapi-schema/redefined-builtin.out  | 3 +++
 tests/qapi-schema/redefined-command.err  | 0
 tests/qapi-schema/redefined-command.exit | 1 +
 tests/qapi-schema/redefined-command.json | 3 +++
 tests/qapi-schema/redefined-command.out  | 4 ++++
 tests/qapi-schema/redefined-event.err    | 0
 tests/qapi-schema/redefined-event.exit   | 1 +
 tests/qapi-schema/redefined-event.json   | 3 +++
 tests/qapi-schema/redefined-event.out    | 4 ++++
 tests/qapi-schema/redefined-type.err     | 0
 tests/qapi-schema/redefined-type.exit    | 1 +
 tests/qapi-schema/redefined-type.json    | 3 +++
 tests/qapi-schema/redefined-type.out     | 4 ++++
 17 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 tests/qapi-schema/redefined-builtin.err
 create mode 100644 tests/qapi-schema/redefined-builtin.exit
 create mode 100644 tests/qapi-schema/redefined-builtin.json
 create mode 100644 tests/qapi-schema/redefined-builtin.out
 create mode 100644 tests/qapi-schema/redefined-command.err
 create mode 100644 tests/qapi-schema/redefined-command.exit
 create mode 100644 tests/qapi-schema/redefined-command.json
 create mode 100644 tests/qapi-schema/redefined-command.out
 create mode 100644 tests/qapi-schema/redefined-event.err
 create mode 100644 tests/qapi-schema/redefined-event.exit
 create mode 100644 tests/qapi-schema/redefined-event.json
 create mode 100644 tests/qapi-schema/redefined-event.out
 create mode 100644 tests/qapi-schema/redefined-type.err
 create mode 100644 tests/qapi-schema/redefined-type.exit
 create mode 100644 tests/qapi-schema/redefined-type.json
 create mode 100644 tests/qapi-schema/redefined-type.out
tests/Makefile +2 -1
index 753f7bd..201e006 100644
@@ -200,7 +200,8 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
 	enum-clash-member.json enum-max-member.json \
 	funny-char.json indented-expr.json missing-type.json \
 	double-type.json bad-type-int.json bad-type-dict.json \
-	double-data.json unknown-expr-key.json \
+	double-data.json unknown-expr-key.json redefined-type.json \
+	redefined-command.json redefined-builtin.json redefined-event.json \
 	missing-colon.json missing-comma-list.json \
 	missing-comma-object.json non-objects.json \
 	qapi-schema-test.json quoted-structural-chars.json \
tests/qapi-schema/redefined-builtin.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/redefined-builtin.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/redefined-builtin.json new file +2 -0
new file mode 100644
index 0000000..a10050d
@@ -0,0 +1,2 @@
+# FIXME: we should reject types that duplicate builtin names
+{ 'type': 'size', 'data': { 'myint': 'size' } }
tests/qapi-schema/redefined-builtin.out new file +3 -0
new file mode 100644
index 0000000..b0a9aea
@@ -0,0 +1,3 @@
+[OrderedDict([('type', 'size'), ('data', OrderedDict([('myint', 'size')]))])]
+[]
+[OrderedDict([('type', 'size'), ('data', OrderedDict([('myint', 'size')]))])]
tests/qapi-schema/redefined-command.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/redefined-command.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/redefined-command.json new file +3 -0
new file mode 100644
index 0000000..d8c9975
@@ -0,0 +1,3 @@
+# FIXME: we should reject commands defined more than once
+{ 'command': 'foo', 'data': { 'one': 'str' } }
+{ 'command': 'foo', 'data': { '*two': 'str' } }
tests/qapi-schema/redefined-command.out new file +4 -0
new file mode 100644
index 0000000..44ddba6
@@ -0,0 +1,4 @@
+[OrderedDict([('command', 'foo'), ('data', OrderedDict([('one', 'str')]))]),
+ OrderedDict([('command', 'foo'), ('data', OrderedDict([('*two', 'str')]))])]
+[]
+[]
tests/qapi-schema/redefined-event.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/redefined-event.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/redefined-event.json new file +3 -0
new file mode 100644
index 0000000..152cce7
@@ -0,0 +1,3 @@
+# FIXME: we should reject duplicate events
+{ 'event': 'EVENT_A', 'data': { 'myint': 'int' } }
+{ 'event': 'EVENT_A', 'data': { 'myint': 'int' } }
tests/qapi-schema/redefined-event.out new file +4 -0
new file mode 100644
index 0000000..261b183
@@ -0,0 +1,4 @@
+[OrderedDict([('event', 'EVENT_A'), ('data', OrderedDict([('myint', 'int')]))]),
+ OrderedDict([('event', 'EVENT_A'), ('data', OrderedDict([('myint', 'int')]))])]
+[]
+[]
tests/qapi-schema/redefined-type.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/redefined-type.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/redefined-type.json new file +3 -0
new file mode 100644
index 0000000..7972194
@@ -0,0 +1,3 @@
+# FIXME: we should reject types defined more than once
+{ 'type': 'foo', 'data': { 'one': 'str' } }
+{ 'enum': 'foo', 'data': [ 'two' ] }
tests/qapi-schema/redefined-type.out new file +4 -0
new file mode 100644
index 0000000..b509e57
@@ -0,0 +1,4 @@
+[OrderedDict([('type', 'foo'), ('data', OrderedDict([('one', 'str')]))]),
+ OrderedDict([('enum', 'foo'), ('data', ['two'])])]
+[{'enum_name': 'foo', 'enum_values': ['two']}]
+[OrderedDict([('type', 'foo'), ('data', OrderedDict([('one', 'str')]))])]
Signature · 1 line
1.9.3
Reviewed-by on v4 9/19
#28 lore raw

Re: [Qemu-devel] [PATCH v4 09/19] qapi: Add tests of redefined expressions

Quoted 8 lines · Eric Blake

Demonstrate that the qapi generator doesn't deal very well with redefined expressions. At the parse level, they are silently accepted; I'm not sure what would happen if we tried to go further and use it in generated code, but the end result can't be good. A later patch will tighten things up and adjust the testsuite to match.

author
#29 lore raw

PATCH v4 10/19 qapi: Better error messages for duplicated expressions

In reply to Eric Blake

The previous commit demonstrated that the generator overlooked duplicate expressions:
- a complex type reusing a built-in type name
- redeclaration of a type name, whether by the same or different metatype
- redeclaration of a command or event
- lack of tracking of 'size' as a built-in type

Add a global array to track all known types and their source, as well as enhancing check_exprs to also check for duplicate events and commands. While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---
 scripts/qapi.py                          | 71 +++++++++++++++++++++++++-------
 tests/qapi-schema/redefined-builtin.err  |  1 +
 tests/qapi-schema/redefined-builtin.exit |  2 +-
 tests/qapi-schema/redefined-builtin.json |  2 +-
 tests/qapi-schema/redefined-builtin.out  |  3 --
 tests/qapi-schema/redefined-command.err  |  1 +
 tests/qapi-schema/redefined-command.exit |  2 +-
 tests/qapi-schema/redefined-command.json |  2 +-
 tests/qapi-schema/redefined-command.out  |  4 --
 tests/qapi-schema/redefined-event.err    |  1 +
 tests/qapi-schema/redefined-event.exit   |  2 +-
 tests/qapi-schema/redefined-event.json   |  2 +-
 tests/qapi-schema/redefined-event.out    |  4 --
 tests/qapi-schema/redefined-type.err     |  1 +
 tests/qapi-schema/redefined-type.exit    |  2 +-
 tests/qapi-schema/redefined-type.json    |  2 +-
 tests/qapi-schema/redefined-type.out     |  4 --
 17 files changed, 69 insertions(+), 37 deletions(-)
scripts/qapi.py +57 -14
index 8fbc45f..bf243fa 100644
@@ -19,8 +19,15 @@ import sys
 builtin_types = [
     'str', 'int', 'number', 'bool',
     'int8', 'int16', 'int32', 'int64',
-    'uint8', 'uint16', 'uint32', 'uint64'
+    'uint8', 'uint16', 'uint32', 'uint64',
+    'size'
 ]
+enum_types = []
+struct_types = []
+union_types = []
+all_types = {}
+commands = []
+events = ['MAX']
 
 builtin_type_qtypes = {
     'str':      'QTYPE_QSTRING',
@@ -248,8 +255,22 @@ def discriminator_find_enum_define(expr):
 
     return find_enum(discriminator_type)
 
+def check_command(expr, expr_info):
+    global commands
+    name = expr['command']
+    if name in commands:
+        raise QAPIExprError(expr_info,
+                            "command '%s' is already defined" % name)
+    commands.append(name)
+
 def check_event(expr, expr_info):
+    global events
+    name = expr['event']
     params = expr.get('data')
+    if name in events:
+        raise QAPIExprError(expr_info,
+                            "event '%s' is already defined" % name)
+    events.append(name)
     if params:
         for argname, argentry, optional, structured in parse_args(params):
             if structured:
@@ -347,6 +368,8 @@ def check_exprs(schema):
             check_event(expr, info)
         if expr.has_key('enum'):
             check_enum(expr, info)
+        if expr.has_key('command'):
+            check_command(expr, info)
 
 def check_keys(expr_elem, meta, required, optional=[]):
     expr = expr_elem['expr']
@@ -370,6 +393,9 @@ def check_keys(expr_elem, meta, required, optional=[]):
 
 
 def parse_schema(input_file):
+    global all_types
+    exprs = []
+
     # First pass: read entire file into memory
     try:
         schema = QAPISchema(open(input_file, "r"))
@@ -377,16 +403,17 @@ def parse_schema(input_file):
         print >>sys.stderr, e
         exit(1)
 
-    exprs = []
-
     try:
         # Next pass: learn the types and check for valid expression keys. At
         # this point, top-level 'include' has already been flattened.
+        for builtin in builtin_types:
+            all_types[builtin] = 'built-in'
         for expr_elem in schema.exprs:
             expr = expr_elem['expr']
+            info = expr_elem['info']
             if expr.has_key('enum'):
                 check_keys(expr_elem, 'enum', ['data'])
-                add_enum(expr['enum'], expr['data'])
+                add_enum(expr['enum'], info, expr['data'])
             elif expr.has_key('union'):
                 # Two styles of union, based on discriminator
                 discriminator = expr.get('discriminator')
@@ -395,10 +422,10 @@ def parse_schema(input_file):
                 else:
                     check_keys(expr_elem, 'union', ['data'],
                                ['base', 'discriminator'])
-                add_union(expr)
+                add_union(expr, info)
             elif expr.has_key('type'):
                 check_keys(expr_elem, 'type', ['data'], ['base'])
-                add_struct(expr)
+                add_struct(expr, info)
             elif expr.has_key('command'):
                 check_keys(expr_elem, 'command', [],
                            ['data', 'returns', 'gen', 'success-response'])
@@ -414,7 +441,7 @@ def parse_schema(input_file):
             expr = expr_elem['expr']
             if expr.has_key('union'):
                 if not discriminator_find_enum_define(expr):
-                    add_enum('%sKind' % expr['union'])
+                    add_enum('%sKind' % expr['union'], expr_elem['info'])
 
         # Final pass - validate that exprs make sense
         check_exprs(schema)
@@ -508,12 +535,15 @@ def type_name(name):
         return c_list_type(name[0])
     return name
 
-enum_types = []
-struct_types = []
-union_types = []
-
-def add_struct(definition):
+def add_struct(definition, info):
     global struct_types
+    global all_types
+    name = definition['type']
+    if name in all_types:
+        raise QAPIExprError(info,
+                            "%s '%s' is already defined"
+                            %(all_types[name], name))
+    all_types[name] = 'struct'
     struct_types.append(definition)
 
 def find_struct(name):
@@ -523,8 +553,15 @@ def find_struct(name):
             return struct
     return None
 
-def add_union(definition):
+def add_union(definition, info):
     global union_types
+    global all_types
+    name = definition['union']
+    if name in all_types:
+        raise QAPIExprError(info,
+                            "%s '%s' is already defined"
+                            %(all_types[name], name))
+    all_types[name] = 'union'
     union_types.append(definition)
 
 def find_union(name):
@@ -534,8 +571,14 @@ def find_union(name):
             return union
     return None
 
-def add_enum(name, enum_values = None):
+def add_enum(name, info, enum_values = None):
     global enum_types
+    global all_types
+    if name in all_types:
+        raise QAPIExprError(info,
+                            "%s '%s' is already defined"
+                            %(all_types[name], name))
+    all_types[name] = 'enum'
     enum_types.append({"enum_name": name, "enum_values": enum_values})
 
 def find_enum(name):
tests/qapi-schema/redefined-builtin.err +1 -0
index e69de29..b275722 100644
@@ -0,0 +1 @@
+tests/qapi-schema/redefined-builtin.json:2: built-in 'size' is already defined
tests/qapi-schema/redefined-builtin.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/redefined-builtin.json +1 -1
index a10050d..df328cc 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject types that duplicate builtin names
+# we reject types that duplicate builtin names
 { 'type': 'size', 'data': { 'myint': 'size' } }
tests/qapi-schema/redefined-builtin.out +0 -3
index b0a9aea..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('type', 'size'), ('data', OrderedDict([('myint', 'size')]))])]
-[]
-[OrderedDict([('type', 'size'), ('data', OrderedDict([('myint', 'size')]))])]
tests/qapi-schema/redefined-command.err +1 -0
index e69de29..82ae256 100644
@@ -0,0 +1 @@
+tests/qapi-schema/redefined-command.json:3: command 'foo' is already defined
tests/qapi-schema/redefined-command.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/redefined-command.json +1 -1
index d8c9975..247e401 100644
@@ -1,3 +1,3 @@
-# FIXME: we should reject commands defined more than once
+# we reject commands defined more than once
 { 'command': 'foo', 'data': { 'one': 'str' } }
 { 'command': 'foo', 'data': { '*two': 'str' } }
tests/qapi-schema/redefined-command.out +0 -4
index 44ddba6..e69de29 100644
@@ -1,4 +0,0 @@
-[OrderedDict([('command', 'foo'), ('data', OrderedDict([('one', 'str')]))]),
- OrderedDict([('command', 'foo'), ('data', OrderedDict([('*two', 'str')]))])]
-[]
-[]
tests/qapi-schema/redefined-event.err +1 -0
index e69de29..35429cb 100644
@@ -0,0 +1 @@
+tests/qapi-schema/redefined-event.json:3: event 'EVENT_A' is already defined
tests/qapi-schema/redefined-event.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/redefined-event.json +1 -1
index 152cce7..7717e91 100644
@@ -1,3 +1,3 @@
-# FIXME: we should reject duplicate events
+# we reject duplicate events
 { 'event': 'EVENT_A', 'data': { 'myint': 'int' } }
 { 'event': 'EVENT_A', 'data': { 'myint': 'int' } }
tests/qapi-schema/redefined-event.out +0 -4
index 261b183..e69de29 100644
@@ -1,4 +0,0 @@
-[OrderedDict([('event', 'EVENT_A'), ('data', OrderedDict([('myint', 'int')]))]),
- OrderedDict([('event', 'EVENT_A'), ('data', OrderedDict([('myint', 'int')]))])]
-[]
-[]
tests/qapi-schema/redefined-type.err +1 -0
index e69de29..06ea78c 100644
@@ -0,0 +1 @@
+tests/qapi-schema/redefined-type.json:3: struct 'foo' is already defined
tests/qapi-schema/redefined-type.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/redefined-type.json +1 -1
index 7972194..e6a5f24 100644
@@ -1,3 +1,3 @@
-# FIXME: we should reject types defined more than once
+# we reject types defined more than once
 { 'type': 'foo', 'data': { 'one': 'str' } }
 { 'enum': 'foo', 'data': [ 'two' ] }
tests/qapi-schema/redefined-type.out +0 -4
index b509e57..e69de29 100644
@@ -1,4 +0,0 @@
-[OrderedDict([('type', 'foo'), ('data', OrderedDict([('one', 'str')]))]),
- OrderedDict([('enum', 'foo'), ('data', ['two'])])]
-[{'enum_name': 'foo', 'enum_values': ['two']}]
-[OrderedDict([('type', 'foo'), ('data', OrderedDict([('one', 'str')]))])]
Signature · 1 line
1.9.3
#30 lore raw

Re: [Qemu-devel] [PATCH v4 10/19] qapi: Better error messages for duplicated expressions

Quoted 40 lines · Eric Blake

The previous commit demonstrated that the generator overlooked duplicate expressions:
- a complex type reusing a built-in type name
- redeclaration of a type name, whether by the same or different metatype
- redeclaration of a command or event
- lack of tracking of 'size' as a built-in type

Add a global array to track all known types and their source, as well as enhancing check_exprs to also check for duplicate events and commands. While valid .json files won't trigger any of these cases, we might as well be nicer to developers that make a typo while trying to add new QAPI code.

---
 scripts/qapi.py                          | 71 +++++++++++++++++++++++++-------
 tests/qapi-schema/redefined-builtin.err  |  1 +
 tests/qapi-schema/redefined-builtin.exit |  2 +-
 tests/qapi-schema/redefined-builtin.json |  2 +-
 tests/qapi-schema/redefined-builtin.out  |  3 --
 tests/qapi-schema/redefined-command.err  |  1 +
 tests/qapi-schema/redefined-command.exit |  2 +-
 tests/qapi-schema/redefined-command.json |  2 +-
 tests/qapi-schema/redefined-command.out  |  4 --
 tests/qapi-schema/redefined-event.err    |  1 +
 tests/qapi-schema/redefined-event.exit   |  2 +-
 tests/qapi-schema/redefined-event.json   |  2 +-
 tests/qapi-schema/redefined-event.out    |  4 --
 tests/qapi-schema/redefined-type.err     |  1 +
 tests/qapi-schema/redefined-type.exit    |  2 +-
 tests/qapi-schema/redefined-type.json    |  2 +-
 tests/qapi-schema/redefined-type.out     |  4 --
 17 files changed, 69 insertions(+), 37 deletions(-)
scripts/qapi.py +0 -0
index 8fbc45f..bf243fa 100644

scripts/qapi.py import sys · line 24

Quoted 7 lines
scripts/qapi.py +2 -1
@@ -19,8 +19,15 @@ import sys
 builtin_types = [
     'str', 'int', 'number', 'bool',
     'int8', 'int16', 'int32', 'int64',
-    'uint8', 'uint16', 'uint32', 'uint64'
+    'uint8', 'uint16', 'uint32', 'uint64',
+    'size'
 ]

I figure we want a blank line here.

Adding 'size' should have the following effects:

* Type sizeList is generated into qapi-types.h

* Declaration of qapi_free_sizeList() is generated into qapi-types.h, definition into qapi-types.c

* generate_visit_anon_union() no longer fails an assertion when it runs into a member of type 'size'

* Declaration of visit_type_sizeList() is generated into qapi-visit.h, definition into qapi-visit.c

Make sense.

How can we be sure we now got all built-in types covered? Documentation says yes, but it cannot be trusted. I figure the best evidence we have is c_type(). Looks good.

Aside: have a look at how it recognizes event names: "name == name.upper()". Ugh! I guess this patch lets us clean it up to "name in events".

I think you should add 'size' to builtin_type_qtypes[], too.

scripts/qapi.py import sys · line 27

Quoted 3 lines
scripts/qapi.py +3 -0
+enum_types = []
+struct_types = []
+union_types = []

Semi-related code motion. Okay.

Quoted 8 lines
scripts/qapi.py +3 -0
+all_types = {}
+commands = []
+events = ['MAX']
 
 builtin_type_qtypes = {
     'str':      'QTYPE_QSTRING',
@@ -248,8 +255,22 @@ def discriminator_find_enum_define(expr):
 

scripts/qapi.py def discriminator_find_enum_define(expr): · line 265

Quoted 10 lines
scripts/qapi.py +8 -0
     return find_enum(discriminator_type)
 
+def check_command(expr, expr_info):
+    global commands
+    name = expr['command']
+    if name in commands:
+        raise QAPIExprError(expr_info,
+                            "command '%s' is already defined" % name)
+    commands.append(name)
+

This rejects duplicate commands. Good.

scripts/qapi.py def discriminator_find_enum_define(expr): · line 276

Quoted 11 lines
scripts/qapi.py +6 -0
 def check_event(expr, expr_info):
+    global events
+    name = expr['event']
     params = expr.get('data')
+    if name in events:
+        raise QAPIExprError(expr_info,
+                            "event '%s' is already defined" % name)
+    events.append(name)
     if params:
         for argname, argentry, optional, structured in parse_args(params):
             if structured:

This rejects duplicate events. Good.

Quoted 106 lines
scripts/qapi.py +29 -13
@@ -347,6 +368,8 @@ def check_exprs(schema):
             check_event(expr, info)
         if expr.has_key('enum'):
             check_enum(expr, info)
+        if expr.has_key('command'):
+            check_command(expr, info)
 
 def check_keys(expr_elem, meta, required, optional=[]):
     expr = expr_elem['expr']
@@ -370,6 +393,9 @@ def check_keys(expr_elem, meta, required, optional=[]):
 
 
 def parse_schema(input_file):
+    global all_types
+    exprs = []
+
     # First pass: read entire file into memory
     try:
         schema = QAPISchema(open(input_file, "r"))
@@ -377,16 +403,17 @@ def parse_schema(input_file):
         print >>sys.stderr, e
         exit(1)
 
-    exprs = []
-
     try:
         # Next pass: learn the types and check for valid expression keys. At
         # this point, top-level 'include' has already been flattened.
+        for builtin in builtin_types:
+            all_types[builtin] = 'built-in'
         for expr_elem in schema.exprs:
             expr = expr_elem['expr']
+            info = expr_elem['info']
             if expr.has_key('enum'):
                 check_keys(expr_elem, 'enum', ['data'])
-                add_enum(expr['enum'], expr['data'])
+                add_enum(expr['enum'], info, expr['data'])
             elif expr.has_key('union'):
                 # Two styles of union, based on discriminator
                 discriminator = expr.get('discriminator')
@@ -395,10 +422,10 @@ def parse_schema(input_file):
                 else:
                     check_keys(expr_elem, 'union', ['data'],
                                ['base', 'discriminator'])
-                add_union(expr)
+                add_union(expr, info)
             elif expr.has_key('type'):
                 check_keys(expr_elem, 'type', ['data'], ['base'])
-                add_struct(expr)
+                add_struct(expr, info)
             elif expr.has_key('command'):
                 check_keys(expr_elem, 'command', [],
                            ['data', 'returns', 'gen', 'success-response'])
@@ -414,7 +441,7 @@ def parse_schema(input_file):
             expr = expr_elem['expr']
             if expr.has_key('union'):
                 if not discriminator_find_enum_define(expr):
-                    add_enum('%sKind' % expr['union'])
+                    add_enum('%sKind' % expr['union'], expr_elem['info'])
 
         # Final pass - validate that exprs make sense
         check_exprs(schema)
@@ -508,12 +535,15 @@ def type_name(name):
         return c_list_type(name[0])
     return name
 
-enum_types = []
-struct_types = []
-union_types = []
-
-def add_struct(definition):
+def add_struct(definition, info):
     global struct_types
+    global all_types
+    name = definition['type']
+    if name in all_types:
+        raise QAPIExprError(info,
+                            "%s '%s' is already defined"
+                            %(all_types[name], name))
+    all_types[name] = 'struct'
     struct_types.append(definition)
 
 def find_struct(name):
@@ -523,8 +553,15 @@ def find_struct(name):
             return struct
     return None
 
-def add_union(definition):
+def add_union(definition, info):
     global union_types
+    global all_types
+    name = definition['union']
+    if name in all_types:
+        raise QAPIExprError(info,
+                            "%s '%s' is already defined"
+                            %(all_types[name], name))
+    all_types[name] = 'union'
     union_types.append(definition)
 
 def find_union(name):
@@ -534,8 +571,14 @@ def find_union(name):
             return union
     return None
 
-def add_enum(name, enum_values = None):
+def add_enum(name, info, enum_values = None):

scripts/qapi.py def find_union(name): · line 584

Quoted 10 lines
scripts/qapi.py +6 -0
     global enum_types
+    global all_types
+    if name in all_types:
+        raise QAPIExprError(info,
+                            "%s '%s' is already defined"
+                            %(all_types[name], name))
+    all_types[name] = 'enum'
     enum_types.append({"enum_name": name, "enum_values": enum_values})
 
 def find_enum(name):

These hunks reject duplicate types of any kind: enum, complex (a.k.a. struct), union.

We have separate name spaces for events, commands and types. Works for me. A single name space would work for me, too.

[Tests snipped, they look good...]

author
#31 lore raw

Re: [Qemu-devel] [PATCH v4 10/19] qapi: Better error messages for duplicated expressions

Quoted 3 lines · Markus Armbruster

We have separate name spaces for events, commands and types. Works for me. A single name space would work for me, too.

I thought about that too. Our conventions are that commands are all-lower-case, events are ALL_UPPER, and user-defined types are CamelCase - so a single namespace would not have any collisions, except for one case: built-in types like 'int' are also all lower, which collides with commands. But I see no technical reason why we wouldn't be able to generate C code for a command named 'int'. I can go either way, but should probably add a test for a .json file that does {'command':'int'} to test which way we go. Preferences on whether that should be allowed or forbidden?

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

Re: [Qemu-devel] [PATCH v4 10/19] qapi: Better error messages for duplicated expressions

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

We have separate name spaces for events, commands and types. Works for me. A single name space would work for me, too.

Quoted 9 lines

I thought about that too. Our conventions are that commands are all-lower-case, events are ALL_UPPER, and user-defined types are CamelCase - so a single namespace would not have any collisions, except for one case: built-in types like 'int' are also all lower, which collides with commands. But I see no technical reason why we wouldn't be able to generate C code for a command named 'int'. I can go either way, but should probably add a test for a .json file that does {'command':'int'} to test which way we go. Preferences on whether that should be allowed or forbidden?

With a single name space, 'command': 'int' should collide with the built-in type.

With separate name spaces, it should in theory just work. No big deal if it doesn't due to generator sloppiness or something.

As I said, I'm fine both with keeping the current separate name space, and with switching to a single name space. Either way, documentation would be nice.

author
#33 lore raw

PATCH v4 11/19 qapi: Add tests of type bypass

In reply to Eric Blake

For a few QMP commands, we are forced to pass an arbitrary type without tracking it properly in QAPI. Among the existing clients, this unnamed type was spelled 'dict', 'visitor', and '**'; this patch standardizes on '**'. There is no difference to the generated code. As the feature was previously undocumented, add some tests and documentation on what we'd like to guarantee, although it will take later patches to clean up test results.

---
 qapi-schema.json                           | 6 +++---
 tests/Makefile                             | 1 +
 tests/qapi-schema/type-bypass-bad-gen.err  | 0
 tests/qapi-schema/type-bypass-bad-gen.exit | 1 +
 tests/qapi-schema/type-bypass-bad-gen.json | 2 ++
 tests/qapi-schema/type-bypass-bad-gen.out  | 3 +++
 tests/qapi-schema/type-bypass-no-gen.err   | 0
 tests/qapi-schema/type-bypass-no-gen.exit  | 1 +
 tests/qapi-schema/type-bypass-no-gen.json  | 2 ++
 tests/qapi-schema/type-bypass-no-gen.out   | 3 +++
 tests/qapi-schema/type-bypass.err          | 0
 tests/qapi-schema/type-bypass.exit         | 1 +
 tests/qapi-schema/type-bypass.json         | 2 ++
 tests/qapi-schema/type-bypass.out          | 3 +++
 14 files changed, 22 insertions(+), 3 deletions(-)
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.err
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.exit
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.json
 create mode 100644 tests/qapi-schema/type-bypass-bad-gen.out
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.err
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.exit
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.json
 create mode 100644 tests/qapi-schema/type-bypass-no-gen.out
 create mode 100644 tests/qapi-schema/type-bypass.err
 create mode 100644 tests/qapi-schema/type-bypass.exit
 create mode 100644 tests/qapi-schema/type-bypass.json
 create mode 100644 tests/qapi-schema/type-bypass.out
qapi-schema.json +3 -3
index 689b548..0b612bf 100644
@@ -1455,7 +1455,7 @@
 ##
 { 'command': 'qom-get',
   'data': { 'path': 'str', 'property': 'str' },
-  'returns': 'visitor',
+  'returns': '**',
   'gen': 'no' }
 
 ##
@@ -1473,7 +1473,7 @@
 # Since: 1.2
 ##
 { 'command': 'qom-set',
-  'data': { 'path': 'str', 'property': 'str', 'value': 'visitor' },
+  'data': { 'path': 'str', 'property': 'str', 'value': '**' },
   'gen': 'no' }
 
 ##
@@ -1850,7 +1850,7 @@
 # Since: 2.0
 ##
 { 'command': 'object-add',
-  'data': {'qom-type': 'str', 'id': 'str', '*props': 'dict'},
+  'data': {'qom-type': 'str', 'id': 'str', '*props': '**'},
   'gen': 'no' }
 
 ##
tests/Makefile +1 -0
index 201e006..5e01952 100644
@@ -202,6 +202,7 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
 	double-type.json bad-type-int.json bad-type-dict.json \
 	double-data.json unknown-expr-key.json redefined-type.json \
 	redefined-command.json redefined-builtin.json redefined-event.json \
+	type-bypass.json type-bypass-no-gen.json type-bypass-bad-gen.json \
 	missing-colon.json missing-comma-list.json \
 	missing-comma-object.json non-objects.json \
 	qapi-schema-test.json quoted-structural-chars.json \
tests/qapi-schema/type-bypass-bad-gen.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/type-bypass-bad-gen.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/type-bypass-bad-gen.json new file +2 -0
new file mode 100644
index 0000000..6894526
@@ -0,0 +1,2 @@
+# FIXME: 'gen' should only appear with value 'no'
+{ 'command': 'foo', 'gen': 'whatever' }
tests/qapi-schema/type-bypass-bad-gen.out new file +3 -0
new file mode 100644
index 0000000..e678f2c
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'foo'), ('gen', 'whatever')])]
+[]
+[]
tests/qapi-schema/type-bypass-no-gen.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/type-bypass-no-gen.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/type-bypass-no-gen.json new file +2 -0
new file mode 100644
index 0000000..72c817f
@@ -0,0 +1,2 @@
+# FIXME: type bypass should only work with 'gen':'no'
+{ 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**' }
tests/qapi-schema/type-bypass-no-gen.out new file +3 -0
new file mode 100644
index 0000000..8b2a9ac
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**')])]
+[]
+[]
tests/qapi-schema/type-bypass.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/type-bypass.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/type-bypass.json new file +2 -0
new file mode 100644
index 0000000..fd65073
@@ -0,0 +1,2 @@
+# Use of 'gen':'no' allows bypassing type system
+{ 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**', 'gen': 'no' }
tests/qapi-schema/type-bypass.out new file +3 -0
new file mode 100644
index 0000000..8957dcb
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**'), ('gen', 'no')])]
+[]
+[]
Signature · 1 line
1.9.3
Reviewed-by on v4 11/19
#34 lore raw

Re: [Qemu-devel] [PATCH v4 11/19] qapi: Add tests of type bypass

Quoted 9 lines · Eric Blake

For a few QMP commands, we are forced to pass an arbitrary type without tracking it properly in QAPI. Among the existing clients, this unnamed type was spelled 'dict', 'visitor', and '**'; this patch standardizes on '**'. There is no difference to the generated code. As the feature was previously undocumented, add some tests and documentation on what we'd like to guarantee, although it will take later patches to clean up test results.

author
#35 lore raw

PATCH v4 12/19 qapi: Add some type check tests

In reply to Eric Blake

Demonstrate that the qapi generator silently parses confusing types, which may cause other errors later on. Later patches will update the expected results as the generator is made stricter.

---
 tests/Makefile                               | 8 ++++++--
 tests/qapi-schema/data-array-empty.err       | 0
 tests/qapi-schema/data-array-empty.exit      | 1 +
 tests/qapi-schema/data-array-empty.json      | 2 ++
 tests/qapi-schema/data-array-empty.out       | 3 +++
 tests/qapi-schema/data-array-unknown.err     | 0
 tests/qapi-schema/data-array-unknown.exit    | 1 +
 tests/qapi-schema/data-array-unknown.json    | 2 ++
 tests/qapi-schema/data-array-unknown.out     | 3 +++
 tests/qapi-schema/data-int.err               | 0
 tests/qapi-schema/data-int.exit              | 1 +
 tests/qapi-schema/data-int.json              | 2 ++
 tests/qapi-schema/data-int.out               | 3 +++
 tests/qapi-schema/data-member-array-bad.err  | 0
 tests/qapi-schema/data-member-array-bad.exit | 1 +
 tests/qapi-schema/data-member-array-bad.json | 2 ++
 tests/qapi-schema/data-member-array-bad.out  | 3 +++
 tests/qapi-schema/data-member-array.err      | 0
 tests/qapi-schema/data-member-array.exit     | 1 +
 tests/qapi-schema/data-member-array.json     | 4 ++++
 tests/qapi-schema/data-member-array.out      | 5 +++++
 tests/qapi-schema/data-member-unknown.err    | 0
 tests/qapi-schema/data-member-unknown.exit   | 1 +
 tests/qapi-schema/data-member-unknown.json   | 2 ++
 tests/qapi-schema/data-member-unknown.out    | 3 +++
 tests/qapi-schema/data-unknown.err           | 0
 tests/qapi-schema/data-unknown.exit          | 1 +
 tests/qapi-schema/data-unknown.json          | 2 ++
 tests/qapi-schema/data-unknown.out           | 3 +++
 tests/qapi-schema/nested-struct-data.err     | 0
 tests/qapi-schema/nested-struct-data.exit    | 1 +
 tests/qapi-schema/nested-struct-data.json    | 4 ++++
 tests/qapi-schema/nested-struct-data.out     | 3 +++
 tests/qapi-schema/nested-struct-returns.err  | 0
 tests/qapi-schema/nested-struct-returns.exit | 1 +
 tests/qapi-schema/nested-struct-returns.json | 3 +++
 tests/qapi-schema/nested-struct-returns.out  | 3 +++
 tests/qapi-schema/returns-array-bad.err      | 0
 tests/qapi-schema/returns-array-bad.exit     | 1 +
 tests/qapi-schema/returns-array-bad.json     | 2 ++
 tests/qapi-schema/returns-array-bad.out      | 3 +++
 tests/qapi-schema/returns-int.err            | 0
 tests/qapi-schema/returns-int.exit           | 1 +
 tests/qapi-schema/returns-int.json           | 2 ++
 tests/qapi-schema/returns-int.out            | 3 +++
 tests/qapi-schema/returns-unknown.err        | 0
 tests/qapi-schema/returns-unknown.exit       | 1 +
 tests/qapi-schema/returns-unknown.json       | 2 ++
 tests/qapi-schema/returns-unknown.out        | 3 +++
 49 files changed, 85 insertions(+), 2 deletions(-)
 create mode 100644 tests/qapi-schema/data-array-empty.err
 create mode 100644 tests/qapi-schema/data-array-empty.exit
 create mode 100644 tests/qapi-schema/data-array-empty.json
 create mode 100644 tests/qapi-schema/data-array-empty.out
 create mode 100644 tests/qapi-schema/data-array-unknown.err
 create mode 100644 tests/qapi-schema/data-array-unknown.exit
 create mode 100644 tests/qapi-schema/data-array-unknown.json
 create mode 100644 tests/qapi-schema/data-array-unknown.out
 create mode 100644 tests/qapi-schema/data-int.err
 create mode 100644 tests/qapi-schema/data-int.exit
 create mode 100644 tests/qapi-schema/data-int.json
 create mode 100644 tests/qapi-schema/data-int.out
 create mode 100644 tests/qapi-schema/data-member-array-bad.err
 create mode 100644 tests/qapi-schema/data-member-array-bad.exit
 create mode 100644 tests/qapi-schema/data-member-array-bad.json
 create mode 100644 tests/qapi-schema/data-member-array-bad.out
 create mode 100644 tests/qapi-schema/data-member-array.err
 create mode 100644 tests/qapi-schema/data-member-array.exit
 create mode 100644 tests/qapi-schema/data-member-array.json
 create mode 100644 tests/qapi-schema/data-member-array.out
 create mode 100644 tests/qapi-schema/data-member-unknown.err
 create mode 100644 tests/qapi-schema/data-member-unknown.exit
 create mode 100644 tests/qapi-schema/data-member-unknown.json
 create mode 100644 tests/qapi-schema/data-member-unknown.out
 create mode 100644 tests/qapi-schema/data-unknown.err
 create mode 100644 tests/qapi-schema/data-unknown.exit
 create mode 100644 tests/qapi-schema/data-unknown.json
 create mode 100644 tests/qapi-schema/data-unknown.out
 create mode 100644 tests/qapi-schema/nested-struct-data.err
 create mode 100644 tests/qapi-schema/nested-struct-data.exit
 create mode 100644 tests/qapi-schema/nested-struct-data.json
 create mode 100644 tests/qapi-schema/nested-struct-data.out
 create mode 100644 tests/qapi-schema/nested-struct-returns.err
 create mode 100644 tests/qapi-schema/nested-struct-returns.exit
 create mode 100644 tests/qapi-schema/nested-struct-returns.json
 create mode 100644 tests/qapi-schema/nested-struct-returns.out
 create mode 100644 tests/qapi-schema/returns-array-bad.err
 create mode 100644 tests/qapi-schema/returns-array-bad.exit
 create mode 100644 tests/qapi-schema/returns-array-bad.json
 create mode 100644 tests/qapi-schema/returns-array-bad.out
 create mode 100644 tests/qapi-schema/returns-int.err
 create mode 100644 tests/qapi-schema/returns-int.exit
 create mode 100644 tests/qapi-schema/returns-int.json
 create mode 100644 tests/qapi-schema/returns-int.out
 create mode 100644 tests/qapi-schema/returns-unknown.err
 create mode 100644 tests/qapi-schema/returns-unknown.exit
 create mode 100644 tests/qapi-schema/returns-unknown.json
 create mode 100644 tests/qapi-schema/returns-unknown.out
tests/Makefile +6 -2
index 5e01952..6fe34f7 100644
@@ -203,8 +203,12 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
 	double-data.json unknown-expr-key.json redefined-type.json \
 	redefined-command.json redefined-builtin.json redefined-event.json \
 	type-bypass.json type-bypass-no-gen.json type-bypass-bad-gen.json \
-	missing-colon.json missing-comma-list.json \
-	missing-comma-object.json non-objects.json \
+	data-array-empty.json data-array-unknown.json data-int.json \
+	data-unknown.json data-member-unknown.json data-member-array.json \
+	data-member-array-bad.json returns-array-bad.json returns-int.json \
+	returns-unknown.json missing-colon.json missing-comma-list.json \
+	missing-comma-object.json nested-struct-data.json \
+	nested-struct-returns.json non-objects.json \
 	qapi-schema-test.json quoted-structural-chars.json \
 	trailing-comma-list.json trailing-comma-object.json \
 	unclosed-list.json unclosed-object.json unclosed-string.json \
tests/qapi-schema/data-array-empty.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-array-empty.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-array-empty.json new file +2 -0
new file mode 100644
index 0000000..41b6c1e
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array for data if it does not contain a known type
+{ 'command': 'oops', 'data': [ ] }
tests/qapi-schema/data-array-empty.out new file +3 -0
new file mode 100644
index 0000000..67802be
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', [])])]
+[]
+[]
tests/qapi-schema/data-array-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-array-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-array-unknown.json new file +2 -0
new file mode 100644
index 0000000..434fb5f
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array for data if it does not contain a known type
+{ 'command': 'oops', 'data': [ 'NoSuchType' ] }
tests/qapi-schema/data-array-unknown.out new file +3 -0
new file mode 100644
index 0000000..c3bc05e
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', ['NoSuchType'])])]
+[]
+[]
tests/qapi-schema/data-int.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-int.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-int.json new file +2 -0
new file mode 100644
index 0000000..37916e0
@@ -0,0 +1,2 @@
+# FIXME: we should reject commands where data is not an array or complex type
+{ 'command': 'oops', 'data': 'int' }
tests/qapi-schema/data-int.out new file +3 -0
new file mode 100644
index 0000000..e589a4f
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', 'int')])]
+[]
+[]
tests/qapi-schema/data-member-array-bad.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-member-array-bad.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-member-array-bad.json new file +2 -0
new file mode 100644
index 0000000..c954af1
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a valid array type
+{ 'command': 'oops', 'data': { 'member': [ { 'nested': 'str' } ] } }
tests/qapi-schema/data-member-array-bad.out new file +3 -0
new file mode 100644
index 0000000..0e00c41
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', [OrderedDict([('nested', 'str')])])]))])]
+[]
+[]
tests/qapi-schema/data-member-array.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-member-array.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-member-array.json new file +4 -0
new file mode 100644
index 0000000..7cce276
@@ -0,0 +1,4 @@
+# valid array members
+{ 'enum': 'abc', 'data': [ 'a', 'b', 'c' ] }
+{ 'type': 'def', 'data': { 'array': [ 'abc' ] } }
+{ 'command': 'okay', 'data': { 'member1': [ 'int' ], 'member2': [ 'def' ] } }
tests/qapi-schema/data-member-array.out new file +5 -0
new file mode 100644
index 0000000..8287120
@@ -0,0 +1,5 @@
+[OrderedDict([('enum', 'abc'), ('data', ['a', 'b', 'c'])]),
+ OrderedDict([('type', 'def'), ('data', OrderedDict([('array', ['abc'])]))]),
+ OrderedDict([('command', 'okay'), ('data', OrderedDict([('member1', ['int']), ('member2', ['def'])]))])]
+[{'enum_name': 'abc', 'enum_values': ['a', 'b', 'c']}]
+[OrderedDict([('type', 'def'), ('data', OrderedDict([('array', ['abc'])]))])]
tests/qapi-schema/data-member-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-member-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-member-unknown.json new file +2 -0
new file mode 100644
index 0000000..40e6252
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a known type
+{ 'command': 'oops', 'data': { 'member': 'NoSuchType' } }
tests/qapi-schema/data-member-unknown.out new file +3 -0
new file mode 100644
index 0000000..36252a5
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', 'NoSuchType')]))])]
+[]
+[]
tests/qapi-schema/data-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-unknown.json new file +2 -0
new file mode 100644
index 0000000..776bd34
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a known type
+{ 'command': 'oops', 'data': 'NoSuchType' }
tests/qapi-schema/data-unknown.out new file +3 -0
new file mode 100644
index 0000000..2c60726
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', 'NoSuchType')])]
+[]
+[]
tests/qapi-schema/nested-struct-data.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/nested-struct-data.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/nested-struct-data.json new file +4 -0
new file mode 100644
index 0000000..0247c8c
@@ -0,0 +1,4 @@
+# FIXME: inline subtypes collide with our desired future use of defaults
+{ 'command': 'foo',
+  'data': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' },
+  'returns': {} }
tests/qapi-schema/nested-struct-data.out new file +3 -0
new file mode 100644
index 0000000..999cbb8
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'foo'), ('data', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')])), ('returns', OrderedDict())])]
+[]
+[]
tests/qapi-schema/nested-struct-returns.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/nested-struct-returns.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/nested-struct-returns.json new file +3 -0
new file mode 100644
index 0000000..5a46840
@@ -0,0 +1,3 @@
+# FIXME: inline subtypes collide with our desired future use of defaults
+{ 'command': 'foo',
+  'returns': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' } }
tests/qapi-schema/nested-struct-returns.out new file +3 -0
new file mode 100644
index 0000000..c53d23b
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'foo'), ('returns', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')]))])]
+[]
+[]
tests/qapi-schema/returns-array-bad.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/returns-array-bad.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/returns-array-bad.json new file +2 -0
new file mode 100644
index 0000000..14882c1
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array return that is not a single type
+{ 'command': 'oops', 'returns': [ 'str', 'str' ] }
tests/qapi-schema/returns-array-bad.out new file +3 -0
new file mode 100644
index 0000000..eccad55
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('returns', ['str', 'str'])])]
+[]
+[]
tests/qapi-schema/returns-int.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/returns-int.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/returns-int.json new file +2 -0
new file mode 100644
index 0000000..7888fb1
@@ -0,0 +1,2 @@
+# It is okay (although not extensible) to return a non-dictionary
+{ 'command': 'okay', 'returns': 'int' }
tests/qapi-schema/returns-int.out new file +3 -0
new file mode 100644
index 0000000..36b00a9
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'okay'), ('returns', 'int')])]
+[]
+[]
tests/qapi-schema/returns-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/returns-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/returns-unknown.json new file +2 -0
new file mode 100644
index 0000000..61f20eb
@@ -0,0 +1,2 @@
+# FIXME: we should reject returns if it does not contain a known type
+{ 'command': 'oops', 'returns': 'NoSuchType' }
tests/qapi-schema/returns-unknown.out new file +3 -0
new file mode 100644
index 0000000..a482c83
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('returns', 'NoSuchType')])]
+[]
+[]
Signature · 1 line
1.9.3
#36 lore raw

Re: [Qemu-devel] [PATCH v4 12/19] qapi: Add some type check tests

Quoted 10 lines · Eric Blake

Demonstrate that the qapi generator silently parses confusing types, which may cause other errors later on. Later patches will update the expected results as the generator is made stricter.

---
 tests/Makefile                               | 8 ++++++--
 tests/qapi-schema/data-array-empty.err       | 0
 tests/qapi-schema/data-array-empty.exit      | 1 +
 tests/qapi-schema/data-array-empty.json      | 2 ++

[Twelve new tests...]

Quoted 4 lines
 create mode 100644 tests/qapi-schema/returns-unknown.err
 create mode 100644 tests/qapi-schema/returns-unknown.exit
 create mode 100644 tests/qapi-schema/returns-unknown.json
 create mode 100644 tests/qapi-schema/returns-unknown.out

Holy moly!

Quoted 35 lines
tests/Makefile +6 -2
index 5e01952..6fe34f7 100644
@@ -203,8 +203,12 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
 	double-data.json unknown-expr-key.json redefined-type.json \
 	redefined-command.json redefined-builtin.json redefined-event.json \
 	type-bypass.json type-bypass-no-gen.json type-bypass-bad-gen.json \
-	missing-colon.json missing-comma-list.json \
-	missing-comma-object.json non-objects.json \
+	data-array-empty.json data-array-unknown.json data-int.json \
+	data-unknown.json data-member-unknown.json data-member-array.json \
+	data-member-array-bad.json returns-array-bad.json returns-int.json \
+	returns-unknown.json missing-colon.json missing-comma-list.json \
+	missing-comma-object.json nested-struct-data.json \
+	nested-struct-returns.json non-objects.json \
 	qapi-schema-test.json quoted-structural-chars.json \
 	trailing-comma-list.json trailing-comma-object.json \
 	unclosed-list.json unclosed-object.json unclosed-string.json \
tests/qapi-schema/data-array-empty.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-array-empty.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-array-empty.json new file +0 -0
new file mode 100644
index 0000000..41b6c1e

tests/qapi-schema/data-array-empty.json line 2

Quoted 2 lines
tests/qapi-schema/data-array-empty.json new file +2 -0
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array for data if it does not contain a known type
+{ 'command': 'oops', 'data': [ ] }

Do we want to permit anything but a complex type for 'data'?

For what it's worth, docs/qmp/qmp-spec.txt specifies:

2.3 Issuing Commands
--------------------

The format for command execution is:

{ "execute": json-string, "arguments": json-object, "id": json-value }

Where,

- The "execute" member identifies the command to be executed by the Server
- The "arguments" member is used to pass any arguments required for the execution of the command, it is optional when no arguments are required
- The "id" member is a transaction identification associated with the command execution, it is optional and will be part of the response if provided

The QAPI schema's 'data' is "arguments" on the wire.

Semantically, 'data' of a complex type / json-object "arguments" is an ordered list of named parameters. Makes obvious sense.

'data' of list type / json-array "arguments" is an ordered list of unnamed parameters. Makes sense, but it isn't how QMP works. Or C for that matter. Do we really want to support this in QAPI?

If yes, then 'data': [] means the same thing as 'data': {} or no 'data':
no arguments.

Aside: discussion of list types in qapi-code-gen.txt is spread over the places that use them. I feel giving them their own section on the same level as complex types etc. would make sense.

'data' of built-in or enumeration type / json-number or json-string "arguments" could be regarded as a single unnamed parameter. Even if we want unnamed parameters, the question remains whether we want two syntactic forms for a single unnamed parameter, boxed in a [ ] and unboxed. I doubt it.

One kind of types left to discuss: unions. I figure the semantics of a simple or flat union type are obvious enough, so we can discuss whether we want them. Anonymous unions are a different matter, because they boil down to a single parameter that need not be json-object.

Quoted 79 lines
tests/qapi-schema/data-array-empty.out new file +3 -0
new file mode 100644
index 0000000..67802be
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', [])])]
+[]
+[]
tests/qapi-schema/data-array-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-array-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-array-unknown.json new file +2 -0
new file mode 100644
index 0000000..434fb5f
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array for data if it does not contain a known type
+{ 'command': 'oops', 'data': [ 'NoSuchType' ] }
tests/qapi-schema/data-array-unknown.out new file +3 -0
new file mode 100644
index 0000000..c3bc05e
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', ['NoSuchType'])])]
+[]
+[]
tests/qapi-schema/data-int.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-int.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-int.json new file +2 -0
new file mode 100644
index 0000000..37916e0
@@ -0,0 +1,2 @@
+# FIXME: we should reject commands where data is not an array or complex type
+{ 'command': 'oops', 'data': 'int' }
tests/qapi-schema/data-int.out new file +3 -0
new file mode 100644
index 0000000..e589a4f
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', 'int')])]
+[]
+[]
tests/qapi-schema/data-member-array-bad.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-member-array-bad.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-member-array-bad.json new file +0 -0
new file mode 100644
index 0000000..c954af1

tests/qapi-schema/data-member-array-bad.json line 2

Quoted 2 lines
tests/qapi-schema/data-member-array-bad.json new file +2 -0
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a valid array type
+{ 'command': 'oops', 'data': { 'member': [ { 'nested': 'str' } ] } }

I'm probably just suffering from temporary denseness here... why is this example problematic? To me, it looks like a single argument 'member' of type "array of complex type with a single member 'nested' of builtin-type 'str'".

Quoted 167 lines
tests/qapi-schema/data-member-array-bad.out new file +3 -0
new file mode 100644
index 0000000..0e00c41
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', [OrderedDict([('nested', 'str')])])]))])]
+[]
+[]
tests/qapi-schema/data-member-array.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-member-array.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-member-array.json new file +4 -0
new file mode 100644
index 0000000..7cce276
@@ -0,0 +1,4 @@
+# valid array members
+{ 'enum': 'abc', 'data': [ 'a', 'b', 'c' ] }
+{ 'type': 'def', 'data': { 'array': [ 'abc' ] } }
+{ 'command': 'okay', 'data': { 'member1': [ 'int' ], 'member2': [ 'def' ] } }
tests/qapi-schema/data-member-array.out new file +5 -0
new file mode 100644
index 0000000..8287120
@@ -0,0 +1,5 @@
+[OrderedDict([('enum', 'abc'), ('data', ['a', 'b', 'c'])]),
+ OrderedDict([('type', 'def'), ('data', OrderedDict([('array', ['abc'])]))]),
+ OrderedDict([('command', 'okay'), ('data', OrderedDict([('member1', ['int']), ('member2', ['def'])]))])]
+[{'enum_name': 'abc', 'enum_values': ['a', 'b', 'c']}]
+[OrderedDict([('type', 'def'), ('data', OrderedDict([('array', ['abc'])]))])]
tests/qapi-schema/data-member-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-member-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-member-unknown.json new file +2 -0
new file mode 100644
index 0000000..40e6252
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a known type
+{ 'command': 'oops', 'data': { 'member': 'NoSuchType' } }
tests/qapi-schema/data-member-unknown.out new file +3 -0
new file mode 100644
index 0000000..36252a5
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', 'NoSuchType')]))])]
+[]
+[]
tests/qapi-schema/data-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/data-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/data-unknown.json new file +2 -0
new file mode 100644
index 0000000..776bd34
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a known type
+{ 'command': 'oops', 'data': 'NoSuchType' }
tests/qapi-schema/data-unknown.out new file +3 -0
new file mode 100644
index 0000000..2c60726
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('data', 'NoSuchType')])]
+[]
+[]
tests/qapi-schema/nested-struct-data.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/nested-struct-data.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/nested-struct-data.json new file +4 -0
new file mode 100644
index 0000000..0247c8c
@@ -0,0 +1,4 @@
+# FIXME: inline subtypes collide with our desired future use of defaults
+{ 'command': 'foo',
+  'data': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' },
+  'returns': {} }
tests/qapi-schema/nested-struct-data.out new file +3 -0
new file mode 100644
index 0000000..999cbb8
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'foo'), ('data', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')])), ('returns', OrderedDict())])]
+[]
+[]
tests/qapi-schema/nested-struct-returns.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/nested-struct-returns.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/nested-struct-returns.json new file +3 -0
new file mode 100644
index 0000000..5a46840
@@ -0,0 +1,3 @@
+# FIXME: inline subtypes collide with our desired future use of defaults
+{ 'command': 'foo',
+  'returns': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' } }
tests/qapi-schema/nested-struct-returns.out new file +3 -0
new file mode 100644
index 0000000..c53d23b
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'foo'), ('returns', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')]))])]
+[]
+[]
tests/qapi-schema/returns-array-bad.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/returns-array-bad.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/returns-array-bad.json new file +0 -0
new file mode 100644
index 0000000..14882c1

tests/qapi-schema/returns-array-bad.json line 2

Quoted 2 lines
tests/qapi-schema/returns-array-bad.json new file +2 -0
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array return that is not a single type
+{ 'command': 'oops', 'returns': [ 'str', 'str' ] }

Do we want to permit anything but a complex type for 'returns'?

For what it's worth, docs/qmp/qmp-spec.txt specifies:

2.4.1 success
-------------

The format of a success response is:

{ "return": json-object, "id": json-value }

Where,

- The "return" member contains the command returned data, which is defined in a per-command basis or an empty json-object if the command does not return data
- The "id" member contains the transaction identification associated with the command execution if issued by the Client

The QAPI schema's 'returns' becomes "return" on the wire. We suck.

qmp-spec.txt is *wrong*! We actually use json-array in addition to json-object.

Similar argument on types wanted as for 'data' / "arguments" above. I think we should permit exactly the same QAPI types, plus lists.

Quoted 60 lines
tests/qapi-schema/returns-array-bad.out new file +3 -0
new file mode 100644
index 0000000..eccad55
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('returns', ['str', 'str'])])]
+[]
+[]
tests/qapi-schema/returns-int.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/returns-int.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/returns-int.json new file +2 -0
new file mode 100644
index 0000000..7888fb1
@@ -0,0 +1,2 @@
+# It is okay (although not extensible) to return a non-dictionary
+{ 'command': 'okay', 'returns': 'int' }
tests/qapi-schema/returns-int.out new file +3 -0
new file mode 100644
index 0000000..36b00a9
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'okay'), ('returns', 'int')])]
+[]
+[]
tests/qapi-schema/returns-unknown.err new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/returns-unknown.exit new file +1 -0
new file mode 100644
index 0000000..573541a
@@ -0,0 +1 @@
+0
tests/qapi-schema/returns-unknown.json new file +2 -0
new file mode 100644
index 0000000..61f20eb
@@ -0,0 +1,2 @@
+# FIXME: we should reject returns if it does not contain a known type
+{ 'command': 'oops', 'returns': 'NoSuchType' }
tests/qapi-schema/returns-unknown.out new file +0 -0
new file mode 100644
index 0000000..a482c83

tests/qapi-schema/returns-unknown.out line 3

Quoted 3 lines
tests/qapi-schema/returns-unknown.out new file +3 -0
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('returns', 'NoSuchType')])]
+[]
+[]

scripts/qapi* is a sick joke when it comes to semantic analysis.

#37 lore raw

Re: [Qemu-devel] [PATCH v4 12/19] qapi: Add some type check tests

Quoted 5 lines · Markus Armbruster
Quoted 3 lines · Eric Blake

Demonstrate that the qapi generator silently parses confusing types, which may cause other errors later on. Later patches will update the expected results as the generator is made stricter.

[...]

Quoted 9 lines

tests/qapi-schema/returns-array-bad.json line 2

Quoted 9 lines
tests/qapi-schema/returns-array-bad.json new file +2 -0
new file mode 100644
index 0000000..14882c1
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array return that is not a single type
+{ 'command': 'oops', 'returns': [ 'str', 'str' ] }

Yes, we want this test, and your remaining tests of 'returns' are fine, too.

Quoted 19 lines

Do we want to permit anything but a complex type for 'returns'?

For what it's worth, docs/qmp/qmp-spec.txt specifies:

2.4.1 success
-------------

The format of a success response is:

{ "return": json-object, "id": json-value }

Where,

- The "return" member contains the command returned data, which is defined in a per-command basis or an empty json-object if the command does not return data
- The "id" member contains the transaction identification associated with the command execution if issued by the Client

Quoted 4 lines

The QAPI schema's 'returns' becomes "return" on the wire. We suck.

qmp-spec.txt is *wrong*! We actually use json-array in addition to json-object.

Actually, we use json-int and json-str as well:
query-migrate-cache-size, ringbuf-read, human-monitor-command.

Quoted 2 lines

Similar argument on types wanted as for 'data' / "arguments" above. I think we should permit exactly the same QAPI types, plus lists.

The similarity to 'data' just isn't there. Separate analysis needed.

Any QAPI types that don't make sense, other than list with length != 1?

[...]

author
#38 lore raw

Re: [Qemu-devel] [PATCH v4 12/19] qapi: Add some type check tests

Quoted 6 lines · Markus Armbruster
Quoted 5 lines

The QAPI schema's 'returns' becomes "return" on the wire. We suck.

qmp-spec.txt is *wrong*! We actually use json-array in addition to json-object.

Quoted 7 lines

Actually, we use json-int and json-str as well:
query-migrate-cache-size, ringbuf-read, human-monitor-command.

Quoted 2 lines

Similar argument on types wanted as for 'data' / "arguments" above. I think we should permit exactly the same QAPI types, plus lists.

The similarity to 'data' just isn't there. Separate analysis needed.

Correct. 'data' and 'returns' are different beasts when it comes to acceptable types. And different still from the acceptable type of each member of a dictionary. But my check_type function in 13/19 is flexible enough to cover all the cases.

Quoted 2 lines

Any QAPI types that don't make sense, other than list with length != 1?

Return of an anon union isn't used yet, but _might_ make sense (as the only feasible way of changing existing commands that return an array or primitive extensible to instead return a dict) - except that back-compat demands that we can't return a dict in place of a primitive unless the arguments of the command are also enhanced (that is, older callers are not expecting a dict, so we can't return a dict unless the caller witnesses they are new enough by explicitly asking for a dict return).

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

Re: [Qemu-devel] [PATCH v4 12/19] qapi: Add some type check tests

Quoted 22 lines · Eric Blake
Quoted 6 lines · Markus Armbruster
Quoted 5 lines

The QAPI schema's 'returns' becomes "return" on the wire. We suck.

qmp-spec.txt is *wrong*! We actually use json-array in addition to json-object.

Quoted 7 lines

Actually, we use json-int and json-str as well:
query-migrate-cache-size, ringbuf-read, human-monitor-command.

Quoted 2 lines

Similar argument on types wanted as for 'data' / "arguments" above. I think we should permit exactly the same QAPI types, plus lists.

The similarity to 'data' just isn't there. Separate analysis needed.

Correct. 'data' and 'returns' are different beasts when it comes to acceptable types. And different still from the acceptable type of each member of a dictionary. But my check_type function in 13/19 is flexible enough to cover all the cases.

Quoted 1 line
Quoted 5 lines
Quoted 1 line

Any QAPI types that don't make sense, other than list with length != 1?

Return of an anon union isn't used yet, but _might_ make sense (as the only feasible way of changing existing commands that return an array or primitive extensible to instead return a dict) -

Good point.

Quoted 5 lines

except that back-compat
demands that we can't return a dict in place of a primitive unless the arguments of the command are also enhanced (that is, older callers are not expecting a dict, so we can't return a dict unless the caller witnesses they are new enough by explicitly asking for a dict return).

I think we can keep things simple for now and reject anonymous unions. We can always relax the check when we run into a use.

You're giving the generator a good shove from "god knows what it accepts, but as long as you stick to stuff that is being used already, probably generates something that works" towards "if it accepts it, it works". I like it.

author
#40 lore raw

[Qemu-devel] RFC: 'alternate' qapi top-level expression [was: [PATCH v4 12/19] qapi: Add some type check tests]

[revisiting this series, finally!]

Quoted 6 lines · Markus Armbruster
Quoted 3 lines

Return of an anon union isn't used yet, but _might_ make sense (as the only feasible way of changing existing commands that return an array or primitive extensible to instead return a dict) -

Good point.

Quoted 8 lines
Quoted 5 lines

except that back-compat
demands that we can't return a dict in place of a primitive unless the arguments of the command are also enhanced (that is, older callers are not expecting a dict, so we can't return a dict unless the caller witnesses they are new enough by explicitly asking for a dict return).

I think we can keep things simple for now and reject anonymous unions. We can always relax the check when we run into a use.

In trying to code up what it would take to easily reject anonymous unions from a return type, I'm realizing that it would be smarter to quit mixing anonymous unions in with other unions.

Refresher course: on the wire, both a regular union:

QAPI:
{ 'type': 'Type1', 'data': { 'value': 'int' } }
{ 'union': 'Foo', 'data': { 'a': 'Type1', 'b': 'Type2' } } { 'command': 'bar', 'data': 'Foo' }
Wire:
{ "execute": "bar", "arguments": { "type": "a",
"data": { "value": 1 } } }

and a flat union:

QAPI:
{ 'type': 'Type1', 'data': { 'value': 'int' } }
{ 'enum': 'Enum', 'data': [ 'a', 'b' ] }
{ 'type': 'Base', { 'switch': 'Enum' } }
{ 'union': 'Foo', 'base': 'Base', 'discriminator': 'switch',
'data': { 'a': 'Type1', 'b': 'Type2' } }
{ 'command': 'bar', 'data': 'Foo' }
Wire:
{ "execute": "bar", "arguments": { "switch": "a",
"value": 1 } }

happen to guarantee a top-level dictionary (plain unions always have a two-element dictionary, flat unions are required to have a base type which is itself a dictionary). But an anonymous union is explicitly allowing a multi-type variable, where the determination of which branch of the union is made by the type of the variable. Furthermore, we do not allow two branches to have the same type, so at least one branch must be a non-dictionary; but as _all_ QMP commands currently take a dictionary for the "arguments" key, we do not want to allow:

QAPI:
{ 'type': 'Type1', 'data': { 'value': 'int' } }
{ 'union': 'Foo', 'discriminator': {},
'data': { 'a': 'Type1', 'b': 'int' } }
{ 'command': 'bar', 'data': 'Foo' }
Wire:
{ "execute": "bar", "arguments": 1 }

Tracking all three qapi expressions as union types is making the generator code a bit verbose, especially since the code generation for all three is so distinct.

Proposal: I am proposing that we convert to an alternate syntax for what we now term as anonymous unions. It will not have any impact to the wire representation of QMP, only to the qapi code generators. The proposal is simple: instead of using "'union':'Name', 'discriminator':{}", we instead use "'alternate': 'Foo'" when declaring a type as an anonymous union (which, for obvious reasons, I would then update the documentation to call an "alternate" instead of an "anonymous union").

I'll go ahead and propose the patches (I've already done the bulk of the conversion work, to prove that not many files were affected).

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

Re: [Qemu-devel] RFC: 'alternate' qapi top-level expression [was: [PATCH v4 12/19] qapi: Add some type check tests]

Cc'ing Kevin as fair punishment for is previous work on QAPI code generation in general, and union types in particular.

Quoted 46 lines · Eric Blake

[revisiting this series, finally!]

Quoted 6 lines · Markus Armbruster
Quoted 3 lines

Return of an anon union isn't used yet, but _might_ make sense (as the only feasible way of changing existing commands that return an array or primitive extensible to instead return a dict) -

Good point.

Quoted 8 lines
Quoted 5 lines

except that back-compat
demands that we can't return a dict in place of a primitive unless the arguments of the command are also enhanced (that is, older callers are not expecting a dict, so we can't return a dict unless the caller witnesses they are new enough by explicitly asking for a dict return).

I think we can keep things simple for now and reject anonymous unions. We can always relax the check when we run into a use.

In trying to code up what it would take to easily reject anonymous unions from a return type, I'm realizing that it would be smarter to quit mixing anonymous unions in with other unions.

Refresher course: on the wire, both a regular union:

QAPI:
{ 'type': 'Type1', 'data': { 'value': 'int' } }
{ 'union': 'Foo', 'data': { 'a': 'Type1', 'b': 'Type2' } } { 'command': 'bar', 'data': 'Foo' }
Wire:
{ "execute": "bar", "arguments": { "type": "a",
"data": { "value": 1 } } }

and a flat union:

QAPI:
{ 'type': 'Type1', 'data': { 'value': 'int' } }
{ 'enum': 'Enum', 'data': [ 'a', 'b' ] }
{ 'type': 'Base', { 'switch': 'Enum' } }
{ 'union': 'Foo', 'base': 'Base', 'discriminator': 'switch',
'data': { 'a': 'Type1', 'b': 'Type2' } }
{ 'command': 'bar', 'data': 'Foo' }
Wire:
{ "execute": "bar", "arguments": { "switch": "a",
"value": 1 } }

Quoted 3 lines

happen to guarantee a top-level dictionary (plain unions always have a two-element dictionary, flat unions are required to have a base type which is itself a dictionary).

Yes.

Quoted 4 lines

But an anonymous union is explicitly
allowing a multi-type variable, where the determination of which branch of the union is made by the type of the variable. Furthermore, we do not allow two branches to have the same type,

Even more severe: the JSON types have to be different! Thus, at most one can be a complex or union type, and at most one can be a string or enum type.

Quoted 2 lines

so at least one branch
must be a non-dictionary;

Correct.

Quoted 10 lines

but as _all_ QMP commands currently take a
dictionary for the "arguments" key, we do not want to allow:

QAPI:
{ 'type': 'Type1', 'data': { 'value': 'int' } }
{ 'union': 'Foo', 'discriminator': {},
'data': { 'a': 'Type1', 'b': 'int' } }
{ 'command': 'bar', 'data': 'Foo' }
Wire:
{ "execute": "bar", "arguments": 1 }

Yes, let's stay out of the generalization tar pits and stick to named parameters, i.e. JSON object arguments.

Quoted 5 lines

Tracking all three qapi expressions as union types is making the generator code a bit verbose, especially since the code generation for all three is so distinct.

Quoted 8 lines

Proposal: I am proposing that we convert to an alternate syntax for what we now term as anonymous unions. It will not have any impact to the wire representation of QMP, only to the qapi code generators. The proposal is simple: instead of using "'union':'Name', 'discriminator':{}", we instead use "'alternate': 'Foo'" when declaring a type as an anonymous union (which, for obvious reasons, I would then update the documentation to call an "alternate" instead of an "anonymous union").

This separates tagged and untagged unions more clearly: reserve 'union' for the two kinds of tagged unions, switch the untagged union to 'alternate'.

I don't mind. Kevin, any objections?

Quoted 2 lines

I'll go ahead and propose the patches (I've already done the bulk of the conversion work, to prove that not many files were affected).

I'll gladly review.

author
#42 lore raw

Re: [Qemu-devel] [PATCH v4 12/19] qapi: Add some type check tests

In reply to Markus Armbruster
Quoted 12 lines · Markus Armbruster
Quoted 10 lines · Eric Blake

Demonstrate that the qapi generator silently parses confusing types, which may cause other errors later on. Later patches will update the expected results as the generator is made stricter.

---
 tests/Makefile                               | 8 ++++++--
 tests/qapi-schema/data-array-empty.err       | 0
 tests/qapi-schema/data-array-empty.exit      | 1 +
 tests/qapi-schema/data-array-empty.json      | 2 ++
Quoted 7 lines

[Twelve new tests...]

Quoted 4 lines
 create mode 100644 tests/qapi-schema/returns-unknown.err
 create mode 100644 tests/qapi-schema/returns-unknown.exit
 create mode 100644 tests/qapi-schema/returns-unknown.json
 create mode 100644 tests/qapi-schema/returns-unknown.out

Holy moly!

Yeah, this series cleans up a lot of cruft, which means a lot of testing.

Quoted 6 lines

tests/qapi-schema/data-array-empty.json line 2

Quoted 4 lines

+++ b/tests/qapi-schema/data-array-empty.json

tests/qapi-schema/data-array-empty.json new file +2 -0
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array for data if it does not contain a known type
+{ 'command': 'oops', 'data': [ ] }

Do we want to permit anything but a complex type for 'data'?

Oh, good question. Probably not (I just tested, and nothing already does that). I'll tighten it in v5 (mostly doc changes, plus a one-liner in 13/19 to remove allow_array=True when calling check_type for a command data member).

Quoted 2 lines

For what it's worth, docs/qmp/qmp-spec.txt specifies:

Ooh, I probably ought to skim that file when making my doc improvements on the front end of the series.

Quoted 4 lines

'data' of list type / json-array "arguments" is an ordered list of unnamed parameters. Makes sense, but it isn't how QMP works. Or C for that matter. Do we really want to support this in QAPI?

No existing command takes a non-dict for "arguments", and the generator probably chokes on it.

Quoted 7 lines

If yes, then 'data': [] means the same thing as 'data': {} or no 'data':
no arguments.

Aside: discussion of list types in qapi-code-gen.txt is spread over the places that use them. I feel giving them their own section on the same level as complex types etc. would make sense.

Good idea, will do in v5.

Quoted 6 lines

'data' of built-in or enumeration type / json-number or json-string "arguments" could be regarded as a single unnamed parameter. Even if we want unnamed parameters, the question remains whether we want two syntactic forms for a single unnamed parameter, boxed in a [ ] and unboxed. I doubt it.

No. We don't (patch 13/19 already forbids them, with no violators found). It's not extensible (well, maybe it is by having some way to mark a dict so that at most one of its keys is the default key to be implied when used in a non-dict form, and all other keys being optional, but that's ugly).

Quoted 5 lines

One kind of types left to discuss: unions. I figure the semantics of a simple or flat union type are obvious enough, so we can discuss whether we want them. Anonymous unions are a different matter, because they boil down to a single parameter that need not be json-object.

Oooh, I didn't even consider anon unions. We absolutely need to support { 'command': 'foo', 'data': 'FlatUnion' } (blockdev-add, anyone), but you are probably right that we don't want to support { 'command': 'foo', 'data': 'AnonUnion'}, because it would allow "arguments" to be a non-dictionary (unless the AnonUnion has only a dict branch, but then why make it a union?). I'll have to make qapi.py be smarter about regular vs. anon unions - it might be easier by using an actual different keyword for anon unions, because they are so different in nature. (Generated code will be the same, just a tweak to the qapi representation and to qapi.py). I'll play with that for v5.

Quoted 9 lines

tests/qapi-schema/data-member-array-bad.json line 2

Quoted 4 lines

+++ b/tests/qapi-schema/data-member-array-bad.json

tests/qapi-schema/data-member-array-bad.json new file +2 -0
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a valid array type
+{ 'command': 'oops', 'data': { 'member': [ { 'nested': 'str' } ] } }

I'm probably just suffering from temporary denseness here... why is this example problematic? To me, it looks like a single argument 'member' of type "array of complex type with a single member 'nested' of builtin-type 'str'".

The generator does not have a way to produce a List of an unnamed type.
All lists are of named types (or rather, every creation of a named type
generates code for both that type and its list counterpart). Maybe we eventually want to support an array of an anonymous type, but the generator doesn't handle it now. So it was easier to forbid it when writing 13/19.

Quoted 4 lines

tests/qapi-schema/returns-array-bad.json line 2

Quoted 2 lines
tests/qapi-schema/returns-array-bad.json new file +2 -0
+# FIXME: we should reject an array return that is not a single type
+{ 'command': 'oops', 'returns': [ 'str', 'str' ] }

Do we want to permit anything but a complex type for 'returns'?

Sadly, yes. We have existing commands that do just that. I already documented that new commands should avoid it (it's not extensible).

Quoted 2 lines

The QAPI schema's 'returns' becomes "return" on the wire. We suck.

We could search-and-replace the schema, but why bother. Yeah, the discrepancy is a bit annoying; on the other hand, it makes it easy to tell schema apart from on-the-wire samples, at least for commands that return something :)

Quoted 3 lines

qmp-spec.txt is *wrong*! We actually use json-array in addition to json-object.

Yep, added to my list of doc improvements for v5.

Quoted 7 lines

tests/qapi-schema/returns-unknown.out line 3

Quoted 5 lines

+++ b/tests/qapi-schema/returns-unknown.out

tests/qapi-schema/returns-unknown.out new file +3 -0
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('returns', 'NoSuchType')])]
+[]
+[]

scripts/qapi* is a sick joke when it comes to semantic analysis.

That gets a lot better in 13/19 :)

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

Re: [Qemu-devel] [PATCH v4 12/19] qapi: Add some type check tests

Quoted 14 lines · Eric Blake
Quoted 13 lines · Markus Armbruster
Quoted 10 lines · Eric Blake

Demonstrate that the qapi generator silently parses confusing types, which may cause other errors later on. Later patches will update the expected results as the generator is made stricter.

---
 tests/Makefile                               | 8 ++++++--
 tests/qapi-schema/data-array-empty.err       | 0
 tests/qapi-schema/data-array-empty.exit      | 1 +
 tests/qapi-schema/data-array-empty.json      | 2 ++

[Twelve new tests...]

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines
 create mode 100644 tests/qapi-schema/returns-unknown.err
 create mode 100644 tests/qapi-schema/returns-unknown.exit
 create mode 100644 tests/qapi-schema/returns-unknown.json
 create mode 100644 tests/qapi-schema/returns-unknown.out

Holy moly!

Yeah, this series cleans up a lot of cruft, which means a lot of testing.

Very much appreciated.

Quoted 8 lines
Quoted 7 lines
Quoted 5 lines

+++ b/tests/qapi-schema/data-array-empty.json

(quoted diff) +1 -0
@@ -0,0 +1,2 @@
+# FIXME: we should reject an array for data if it does not contain

a known type
+{ 'command': 'oops', 'data': [ ] }

Do we want to permit anything but a complex type for 'data'?

Quoted 4 lines

Oh, good question. Probably not (I just tested, and nothing already does that). I'll tighten it in v5 (mostly doc changes, plus a one-liner in 13/19 to remove allow_array=True when calling check_type for a command data member).

Yes, please.

Quoted 11 lines
Quoted 1 line

For what it's worth, docs/qmp/qmp-spec.txt specifies:

Ooh, I probably ought to skim that file when making my doc improvements on the front end of the series.

Quoted 3 lines

'data' of list type / json-array "arguments" is an ordered list of unnamed parameters. Makes sense, but it isn't how QMP works. Or C for that matter. Do we really want to support this in QAPI?

No existing command takes a non-dict for "arguments", and the generator probably chokes on it.

Let's stick to dict arguments.

Quoted 16 lines
Quoted 6 lines

If yes, then 'data': [] means the same thing as 'data': {} or no 'data':
no arguments.

Aside: discussion of list types in qapi-code-gen.txt is spread over the places that use them. I feel giving them their own section on the same level as complex types etc. would make sense.

Good idea, will do in v5.

Quoted 6 lines

'data' of built-in or enumeration type / json-number or json-string "arguments" could be regarded as a single unnamed parameter. Even if we want unnamed parameters, the question remains whether we want two syntactic forms for a single unnamed parameter, boxed in a [ ] and unboxed. I doubt it.

Quoted 5 lines

No. We don't (patch 13/19 already forbids them, with no violators found). It's not extensible (well, maybe it is by having some way to mark a dict so that at most one of its keys is the default key to be implied when used in a non-dict form, and all other keys being optional, but that's ugly).

Agreed.

Quoted 5 lines
Quoted 4 lines

One kind of types left to discuss: unions. I figure the semantics of a simple or flat union type are obvious enough, so we can discuss whether we want them. Anonymous unions are a different matter, because they boil down to a single parameter that need not be json-object.

Quoted 10 lines

Oooh, I didn't even consider anon unions. We absolutely need to support { 'command': 'foo', 'data': 'FlatUnion' } (blockdev-add, anyone), but you are probably right that we don't want to support { 'command': 'foo', 'data': 'AnonUnion'}, because it would allow "arguments" to be a non-dictionary (unless the AnonUnion has only a dict branch, but then why make it a union?). I'll have to make qapi.py be smarter about regular vs. anon unions - it might be easier by using an actual different keyword for anon unions, because they are so different in nature. (Generated code will be the same, just a tweak to the qapi representation and to qapi.py). I'll play with that for v5.

Okay :)

Quoted 10 lines
Quoted 9 lines

tests/qapi-schema/data-member-array-bad.json line 2

Quoted 4 lines

+++ b/tests/qapi-schema/data-member-array-bad.json

tests/qapi-schema/data-member-array-bad.json new file +2 -0
@@ -0,0 +1,2 @@
+# FIXME: we should reject data if it does not contain a valid array type
+{ 'command': 'oops', 'data': { 'member': [ { 'nested': 'str' } ] } }

I'm probably just suffering from temporary denseness here... why is this example problematic? To me, it looks like a single argument 'member' of type "array of complex type with a single member 'nested' of builtin-type 'str'".

Quoted 6 lines

The generator does not have a way to produce a List of an unnamed type.
All lists are of named types (or rather, every creation of a named type
generates code for both that type and its list counterpart). Maybe we eventually want to support an array of an anonymous type, but the generator doesn't handle it now. So it was easier to forbid it when writing 13/19.

I see. We already accepted restricting nested structs (see series subject), and this is just one instance.

Quoted 7 lines
Quoted 4 lines

tests/qapi-schema/returns-array-bad.json line 2

Quoted 2 lines
tests/qapi-schema/returns-array-bad.json new file +2 -0
+# FIXME: we should reject an array return that is not a single type
+{ 'command': 'oops', 'returns': [ 'str', 'str' ] }

Do we want to permit anything but a complex type for 'returns'?

Sadly, yes. We have existing commands that do just that. I already documented that new commands should avoid it (it's not extensible).

If we care, we can whitelist the existing offenders, and reject new offenders.

Quoted 22 lines
Quoted 1 line

The QAPI schema's 'returns' becomes "return" on the wire. We suck.

We could search-and-replace the schema, but why bother. Yeah, the discrepancy is a bit annoying; on the other hand, it makes it easy to tell schema apart from on-the-wire samples, at least for commands that return something :)

Quoted 3 lines

qmp-spec.txt is *wrong*! We actually use json-array in addition to json-object.

Yep, added to my list of doc improvements for v5.

Quoted 7 lines

tests/qapi-schema/returns-unknown.out line 3

Quoted 5 lines

+++ b/tests/qapi-schema/returns-unknown.out

tests/qapi-schema/returns-unknown.out new file +3 -0
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'oops'), ('returns', 'NoSuchType')])]
+[]
+[]

scripts/qapi* is a sick joke when it comes to semantic analysis.

Quoted 1 line

That gets a lot better in 13/19 :)

Will review as soon as I can!

author
#44 lore raw

Re: [Qemu-devel] [PATCH v4 12/19] qapi: Add some type check tests

Quoted 7 lines · Markus Armbruster
Quoted 4 lines
Quoted 1 line

Do we want to permit anything but a complex type for 'returns'?

Sadly, yes. We have existing commands that do just that. I already documented that new commands should avoid it (it's not extensible).

If we care, we can whitelist the existing offenders, and reject new offenders.

Also a good idea. The whitelist may grow over time, but forcing a developer to modify the whitelist calls attention to their action :)

I'll add that to my v5 queue. Thanks again for a thought-provoking review.

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

PATCH v4 13/19 qapi: More rigourous checking of types

In reply to Eric Blake

Now that we know every expression is valid with regards to its keys, we can add further tests that those keys refer to valid types. With this patch, all references to a type (the 'data': of command, type, union, and event, and the 'returns':
of command) must resolve to a builtin or another type declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested sub-structs will be done in later patches.

Update the testsuite to match improved output.

---
 scripts/qapi.py                              | 73 ++++++++++++++++++++++++++--
 tests/qapi-schema/data-array-empty.err       |  1 +
 tests/qapi-schema/data-array-empty.exit      |  2 +-
 tests/qapi-schema/data-array-empty.json      |  2 +-
 tests/qapi-schema/data-array-empty.out       |  3 --
 tests/qapi-schema/data-array-unknown.err     |  1 +
 tests/qapi-schema/data-array-unknown.exit    |  2 +-
 tests/qapi-schema/data-array-unknown.json    |  2 +-
 tests/qapi-schema/data-array-unknown.out     |  3 --
 tests/qapi-schema/data-int.err               |  1 +
 tests/qapi-schema/data-int.exit              |  2 +-
 tests/qapi-schema/data-int.json              |  2 +-
 tests/qapi-schema/data-int.out               |  3 --
 tests/qapi-schema/data-member-array-bad.err  |  1 +
 tests/qapi-schema/data-member-array-bad.exit |  2 +-
 tests/qapi-schema/data-member-array-bad.json |  2 +-
 tests/qapi-schema/data-member-array-bad.out  |  3 --
 tests/qapi-schema/data-member-unknown.err    |  1 +
 tests/qapi-schema/data-member-unknown.exit   |  2 +-
 tests/qapi-schema/data-member-unknown.json   |  2 +-
 tests/qapi-schema/data-member-unknown.out    |  3 --
 tests/qapi-schema/data-unknown.err           |  1 +
 tests/qapi-schema/data-unknown.exit          |  2 +-
 tests/qapi-schema/data-unknown.json          |  2 +-
 tests/qapi-schema/data-unknown.out           |  3 --
 tests/qapi-schema/returns-array-bad.err      |  1 +
 tests/qapi-schema/returns-array-bad.exit     |  2 +-
 tests/qapi-schema/returns-array-bad.json     |  2 +-
 tests/qapi-schema/returns-array-bad.out      |  3 --
 tests/qapi-schema/returns-unknown.err        |  1 +
 tests/qapi-schema/returns-unknown.exit       |  2 +-
 tests/qapi-schema/returns-unknown.json       |  2 +-
 tests/qapi-schema/returns-unknown.out        |  3 --
 33 files changed, 93 insertions(+), 44 deletions(-)
scripts/qapi.py +69 -4
index bf243fa..20c0ce9 100644
@@ -255,6 +255,52 @@ def discriminator_find_enum_define(expr):
 
     return find_enum(discriminator_type)
 
+def check_type(expr_info, source, data, allow_array = False,
+               allowed_names = [], allow_dict = True):
+    global all_types
+
+    if data is None:
+        return
+
+    if data == '**':
+        return
+
+    # Check if array type for data is okay
+    if isinstance(data, list):
+        if not allow_array:
+            raise QAPIExprError(expr_info,
+                                "%s cannot be an array" % source)
+        if len(data) != 1 or not isinstance(data[0], basestring):
+            raise QAPIExprError(expr_info,
+                                "%s: array type must contain single type name"
+                                % source)
+        data = data[0]
+
+    # Check if type name for data is okay
+    if isinstance(data, basestring):
+        if not data in all_types:
+            raise QAPIExprError(expr_info,
+                                "%s references unknown type '%s'"
+                                % (source, data))
+        if not all_types[data] in allowed_names:
+            raise QAPIExprError(expr_info,
+                                "%s cannot reference %s type '%s'"
+                                % (source, all_types[data], data))
+        return
+
+    # data is a dictionary, check that each member is okay
+    if not isinstance(data, OrderedDict):
+        raise QAPIExprError(expr_info,
+                            "%s should be a dictionary" % source)
+    if not allow_dict:
+        raise QAPIExprError(expr_info,
+                            "%s should be a type name" % source)
+    for (key, value) in data.items():
+        check_type(expr_info, "member '%s' of %s" % (key, source), value,
+                   allow_array=True,
+                   allowed_names=['built-in', 'union', 'struct', 'enum'],
+                   allow_dict=True)
+
 def check_command(expr, expr_info):
     global commands
     name = expr['command']
@@ -262,6 +308,15 @@ def check_command(expr, expr_info):
         raise QAPIExprError(expr_info,
                             "command '%s' is already defined" % name)
     commands.append(name)
+    check_type(expr_info, "'data' for command '%s'" % name,
+               expr.get('data'), allow_array=True,
+               allowed_names=['union', 'struct'])
+    check_type(expr_info, "'base' for command '%s'" % name,
+               expr.get('base'), allowed_names=['struct'],
+               allow_dict=False)
+    check_type(expr_info, "'returns' for command '%s'" % name,
+               expr.get('returns'), allow_array=True,
+               allowed_names=['built-in', 'union', 'struct', 'enum'])
 
 def check_event(expr, expr_info):
     global events
@@ -271,6 +326,8 @@ def check_event(expr, expr_info):
         raise QAPIExprError(expr_info,
                             "event '%s' is already defined" % name)
     events.append(name)
+    check_type(expr_info, "'data' for event '%s'" % name,
+               expr.get('data'), allowed_names=['union', 'struct'])
     if params:
         for argname, argentry, optional, structured in parse_args(params):
             if structured:
@@ -357,19 +414,27 @@ def check_enum(expr, expr_info):
                                 % (name, member, values[key]))
         values[key] = member
 
+def check_struct(expr, expr_info):
+    name = expr['type']
+    members = expr['data']
+
+    check_type(expr_info, "'data' for type '%s'" % name, members)
+
 def check_exprs(schema):
     for expr_elem in schema.exprs:
         expr = expr_elem['expr']
         info = expr_elem['info']
 
-        if expr.has_key('union'):
-            check_union(expr, info)
-        if expr.has_key('event'):
-            check_event(expr, info)
         if expr.has_key('enum'):
             check_enum(expr, info)
+        if expr.has_key('union'):
+            check_union(expr, info)
+        if expr.has_key('type'):
+            check_struct(expr, info)
         if expr.has_key('command'):
             check_command(expr, info)
+        if expr.has_key('event'):
+            check_event(expr, info)
 
 def check_keys(expr_elem, meta, required, optional=[]):
     expr = expr_elem['expr']
tests/qapi-schema/data-array-empty.err +1 -0
index e69de29..94e046b 100644
@@ -0,0 +1 @@
+tests/qapi-schema/data-array-empty.json:2: 'data' for command 'oops': array type must contain single type name
tests/qapi-schema/data-array-empty.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-array-empty.json +1 -1
index 41b6c1e..fdd5612 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an array for data if it does not contain a known type
+# we reject an array for data if it does not contain a known type
 { 'command': 'oops', 'data': [ ] }
tests/qapi-schema/data-array-empty.out +0 -3
index 67802be..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', [])])]
-[]
-[]
tests/qapi-schema/data-array-unknown.err +1 -0
index e69de29..a66c2d6 100644
@@ -0,0 +1 @@
+tests/qapi-schema/data-array-unknown.json:2: 'data' for command 'oops' references unknown type 'NoSuchType'
tests/qapi-schema/data-array-unknown.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-array-unknown.json +1 -1
index 434fb5f..9c75b96 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an array for data if it does not contain a known type
+# we reject an array for data if it does not contain a known type
 { 'command': 'oops', 'data': [ 'NoSuchType' ] }
tests/qapi-schema/data-array-unknown.out +0 -3
index c3bc05e..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', ['NoSuchType'])])]
-[]
-[]
tests/qapi-schema/data-int.err +1 -0
index e69de29..e1d3ed5 100644
@@ -0,0 +1 @@
+tests/qapi-schema/data-int.json:2: 'data' for command 'oops' cannot reference built-in type 'int'
tests/qapi-schema/data-int.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-int.json +1 -1
index 37916e0..a334d92 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject commands where data is not an array or complex type
+# we reject commands where data is not an array or complex type
 { 'command': 'oops', 'data': 'int' }
tests/qapi-schema/data-int.out +0 -3
index e589a4f..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', 'int')])]
-[]
-[]
tests/qapi-schema/data-member-array-bad.err +1 -0
index e69de29..ac45442 100644
@@ -0,0 +1 @@
+tests/qapi-schema/data-member-array-bad.json:2: member 'member' of 'data' for command 'oops': array type must contain single type name
tests/qapi-schema/data-member-array-bad.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-member-array-bad.json +1 -1
index c954af1..b2ff144 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject data if it does not contain a valid array type
+# we reject data if it does not contain a valid array type
 { 'command': 'oops', 'data': { 'member': [ { 'nested': 'str' } ] } }
tests/qapi-schema/data-member-array-bad.out +0 -3
index 0e00c41..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', [OrderedDict([('nested', 'str')])])]))])]
-[]
-[]
tests/qapi-schema/data-member-unknown.err +1 -0
index e69de29..89dce36 100644
@@ -0,0 +1 @@
+tests/qapi-schema/data-member-unknown.json:2: member 'member' of 'data' for command 'oops' references unknown type 'NoSuchType'
tests/qapi-schema/data-member-unknown.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-member-unknown.json +1 -1
index 40e6252..342a41e 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject data if it does not contain a known type
+# we reject data if it does not contain a known type
 { 'command': 'oops', 'data': { 'member': 'NoSuchType' } }
tests/qapi-schema/data-member-unknown.out +0 -3
index 36252a5..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', 'NoSuchType')]))])]
-[]
-[]
tests/qapi-schema/data-unknown.err +1 -0
index e69de29..d1a6086 100644
@@ -0,0 +1 @@
+tests/qapi-schema/data-unknown.json:2: 'data' for command 'oops' references unknown type 'NoSuchType'
tests/qapi-schema/data-unknown.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-unknown.json +1 -1
index 776bd34..32aba43 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject data if it does not contain a known type
+# we reject data if it does not contain a known type
 { 'command': 'oops', 'data': 'NoSuchType' }
tests/qapi-schema/data-unknown.out +0 -3
index 2c60726..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', 'NoSuchType')])]
-[]
-[]
tests/qapi-schema/returns-array-bad.err +1 -0
index e69de29..138095c 100644
@@ -0,0 +1 @@
+tests/qapi-schema/returns-array-bad.json:2: 'returns' for command 'oops': array type must contain single type name
tests/qapi-schema/returns-array-bad.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/returns-array-bad.json +1 -1
index 14882c1..09b0b1f 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an array return that is not a single type
+# we reject an array return that is not a single type
 { 'command': 'oops', 'returns': [ 'str', 'str' ] }
tests/qapi-schema/returns-array-bad.out +0 -3
index eccad55..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('returns', ['str', 'str'])])]
-[]
-[]
tests/qapi-schema/returns-unknown.err +1 -0
index e69de29..962f27c 100644
@@ -0,0 +1 @@
+tests/qapi-schema/returns-unknown.json:2: 'returns' for command 'oops' references unknown type 'NoSuchType'
tests/qapi-schema/returns-unknown.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/returns-unknown.json +1 -1
index 61f20eb..25bd498 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject returns if it does not contain a known type
+# we reject returns if it does not contain a known type
 { 'command': 'oops', 'returns': 'NoSuchType' }
tests/qapi-schema/returns-unknown.out +0 -3
index a482c83..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('returns', 'NoSuchType')])]
-[]
-[]
Signature · 1 line
1.9.3
#46 lore raw

Re: [Qemu-devel] [PATCH v4 13/19] qapi: More rigourous checking of types

Quoted 91 lines · Eric Blake

Now that we know every expression is valid with regards to its keys, we can add further tests that those keys refer to valid types. With this patch, all references to a type (the 'data': of command, type, union, and event, and the 'returns':
of command) must resolve to a builtin or another type declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested sub-structs will be done in later patches.

Update the testsuite to match improved output.

---
 scripts/qapi.py                              | 73 ++++++++++++++++++++++++++--
 tests/qapi-schema/data-array-empty.err       |  1 +
 tests/qapi-schema/data-array-empty.exit      |  2 +-
 tests/qapi-schema/data-array-empty.json      |  2 +-
 tests/qapi-schema/data-array-empty.out       |  3 --
 tests/qapi-schema/data-array-unknown.err     |  1 +
 tests/qapi-schema/data-array-unknown.exit    |  2 +-
 tests/qapi-schema/data-array-unknown.json    |  2 +-
 tests/qapi-schema/data-array-unknown.out     |  3 --
 tests/qapi-schema/data-int.err               |  1 +
 tests/qapi-schema/data-int.exit              |  2 +-
 tests/qapi-schema/data-int.json              |  2 +-
 tests/qapi-schema/data-int.out               |  3 --
 tests/qapi-schema/data-member-array-bad.err  |  1 +
 tests/qapi-schema/data-member-array-bad.exit |  2 +-
 tests/qapi-schema/data-member-array-bad.json |  2 +-
 tests/qapi-schema/data-member-array-bad.out  |  3 --
 tests/qapi-schema/data-member-unknown.err    |  1 +
 tests/qapi-schema/data-member-unknown.exit   |  2 +-
 tests/qapi-schema/data-member-unknown.json   |  2 +-
 tests/qapi-schema/data-member-unknown.out    |  3 --
 tests/qapi-schema/data-unknown.err           |  1 +
 tests/qapi-schema/data-unknown.exit          |  2 +-
 tests/qapi-schema/data-unknown.json          |  2 +-
 tests/qapi-schema/data-unknown.out           |  3 --
 tests/qapi-schema/returns-array-bad.err      |  1 +
 tests/qapi-schema/returns-array-bad.exit     |  2 +-
 tests/qapi-schema/returns-array-bad.json     |  2 +-
 tests/qapi-schema/returns-array-bad.out      |  3 --
 tests/qapi-schema/returns-unknown.err        |  1 +
 tests/qapi-schema/returns-unknown.exit       |  2 +-
 tests/qapi-schema/returns-unknown.json       |  2 +-
 tests/qapi-schema/returns-unknown.out        |  3 --
 33 files changed, 93 insertions(+), 44 deletions(-)
scripts/qapi.py +35 -0
index bf243fa..20c0ce9 100644
@@ -255,6 +255,52 @@ def discriminator_find_enum_define(expr):
 
     return find_enum(discriminator_type)
 
+def check_type(expr_info, source, data, allow_array = False,
+               allowed_names = [], allow_dict = True):
+    global all_types
+
+    if data is None:
+        return
+
+    if data == '**':
+        return
+
+    # Check if array type for data is okay
+    if isinstance(data, list):
+        if not allow_array:
+            raise QAPIExprError(expr_info,
+                                "%s cannot be an array" % source)
+        if len(data) != 1 or not isinstance(data[0], basestring):
+            raise QAPIExprError(expr_info,
+                                "%s: array type must contain single type name"
+                                % source)
+        data = data[0]
+
+    # Check if type name for data is okay
+    if isinstance(data, basestring):
+        if not data in all_types:
+            raise QAPIExprError(expr_info,
+                                "%s references unknown type '%s'"
+                                % (source, data))
+        if not all_types[data] in allowed_names:
+            raise QAPIExprError(expr_info,
+                                "%s cannot reference %s type '%s'"
+                                % (source, all_types[data], data))
+        return
+
+    # data is a dictionary, check that each member is okay
+    if not isinstance(data, OrderedDict):

scripts/qapi.py def discriminator_find_enum_define(expr): · line 302

Quoted 10 lines
scripts/qapi.py +10 -0
+        raise QAPIExprError(expr_info,
+                            "%s should be a dictionary" % source)
+    if not allow_dict:
+        raise QAPIExprError(expr_info,
+                            "%s should be a type name" % source)
+    for (key, value) in data.items():
+        check_type(expr_info, "member '%s' of %s" % (key, source), value,
+                   allow_array=True,
+                   allowed_names=['built-in', 'union', 'struct', 'enum'],
+                   allow_dict=True)

Hmm, allowed_names isn't about allowed names, it's about allowed meta-types. Rename?

Quoted 8 lines
scripts/qapi.py +1 -0
+
 def check_command(expr, expr_info):
     global commands
     name = expr['command']
@@ -262,6 +308,15 @@ def check_command(expr, expr_info):
         raise QAPIExprError(expr_info,
                             "command '%s' is already defined" % name)
     commands.append(name)

scripts/qapi.py def check_command(expr, expr_info): · line 320

Quoted 10 lines
scripts/qapi.py +9 -0
+    check_type(expr_info, "'data' for command '%s'" % name,
+               expr.get('data'), allow_array=True,
+               allowed_names=['union', 'struct'])
+    check_type(expr_info, "'base' for command '%s'" % name,
+               expr.get('base'), allowed_names=['struct'],
+               allow_dict=False)
+    check_type(expr_info, "'returns' for command '%s'" % name,
+               expr.get('returns'), allow_array=True,
+               allowed_names=['built-in', 'union', 'struct', 'enum'])
 

Nicely done.

Quoted 30 lines
scripts/qapi.py +8 -4
 def check_event(expr, expr_info):
     global events
@@ -271,6 +326,8 @@ def check_event(expr, expr_info):
         raise QAPIExprError(expr_info,
                             "event '%s' is already defined" % name)
     events.append(name)
+    check_type(expr_info, "'data' for event '%s'" % name,
+               expr.get('data'), allowed_names=['union', 'struct'])
     if params:
         for argname, argentry, optional, structured in parse_args(params):
             if structured:
@@ -357,19 +414,27 @@ def check_enum(expr, expr_info):
                                 % (name, member, values[key]))
         values[key] = member
 
+def check_struct(expr, expr_info):
+    name = expr['type']
+    members = expr['data']
+
+    check_type(expr_info, "'data' for type '%s'" % name, members)
+
 def check_exprs(schema):
     for expr_elem in schema.exprs:
         expr = expr_elem['expr']
         info = expr_elem['info']
 
-        if expr.has_key('union'):
-            check_union(expr, info)
-        if expr.has_key('event'):
-            check_event(expr, info)

scripts/qapi.py def check_enum(expr, expr_info): · line 437

Quoted 10 lines
scripts/qapi.py +6 -0
         if expr.has_key('enum'):
             check_enum(expr, info)
+        if expr.has_key('union'):
+            check_union(expr, info)
+        if expr.has_key('type'):
+            check_struct(expr, info)
         if expr.has_key('command'):
             check_command(expr, info)
+        if expr.has_key('event'):
+            check_event(expr, info)

Not related to this patch: this chain of ifs bothers me. The conditions should be exclusive, because each expression must have a well-defined meta-type. If I remember correctly, you actually enforce this elsewhere in your series. Do we want to make it obvious in the code here? elif instead of if, perhaps?

Quoted 37 lines
scripts/qapi.py +0 -0
 def check_keys(expr_elem, meta, required, optional=[]):
     expr = expr_elem['expr']
tests/qapi-schema/data-array-empty.err +1 -0
index e69de29..94e046b 100644
@@ -0,0 +1 @@
+tests/qapi-schema/data-array-empty.json:2: 'data' for command 'oops': array type must contain single type name
tests/qapi-schema/data-array-empty.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-array-empty.json +1 -1
index 41b6c1e..fdd5612 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an array for data if it does not contain a known type
+# we reject an array for data if it does not contain a known type
 { 'command': 'oops', 'data': [ ] }
tests/qapi-schema/data-array-empty.out +0 -3
index 67802be..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', [])])]
-[]
-[]
tests/qapi-schema/data-array-unknown.err +0 -0
index e69de29..a66c2d6 100644

tests/qapi-schema/data-array-unknown.err line 1

Quoted 1 line
tests/qapi-schema/data-array-unknown.err +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/data-array-unknown.json:2: 'data' for command 'oops' references unknown type 'NoSuchType'

The wording "references type" somehow unduly excites my "reference type" synapses :)

Perhaps something like "Type 'NoSuchType' is unknown" would suffice. Entirely up to you; feel free to keep the wording as is.

Quoted 28 lines
tests/qapi-schema/data-array-unknown.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/data-array-unknown.json +1 -1
index 434fb5f..9c75b96 100644
@@ -1,2 +1,2 @@
-# FIXME: we should reject an array for data if it does not contain a known type
+# we reject an array for data if it does not contain a known type
 { 'command': 'oops', 'data': [ 'NoSuchType' ] }
tests/qapi-schema/data-array-unknown.out +0 -3
index c3bc05e..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'oops'), ('data', ['NoSuchType'])])]
-[]
-[]
tests/qapi-schema/data-int.err +0 -0
index e69de29..e1d3ed5 100644

tests/qapi-schema/data-int.err line 1

Quoted 1 line
tests/qapi-schema/data-int.err +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/data-int.json:2: 'data' for command 'oops' cannot reference built-in type 'int'

Perhaps something like "'data' for command 'oops' can't be of built-in type 'int'", or maybe positive instead of negative: "a command's 'data' must be of complex type".

Again, entirely up to you.

[...]

#47 lore raw

Re: [Qemu-devel] [PATCH v4 13/19] qapi: More rigourous checking of types

Quoted 14 lines · Markus Armbruster
Quoted 12 lines · Eric Blake

Now that we know every expression is valid with regards to its keys, we can add further tests that those keys refer to valid types. With this patch, all references to a type (the 'data': of command, type, union, and event, and the 'returns':
of command) must resolve to a builtin or another type declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested sub-structs will be done in later patches.

Update the testsuite to match improved output.

[...]

Quoted 8 lines
Quoted 8 lines
scripts/qapi.py +4 -0
@@ -262,6 +308,15 @@ def check_command(expr, expr_info):
         raise QAPIExprError(expr_info,
                             "command '%s' is already defined" % name)
     commands.append(name)
+    check_type(expr_info, "'data' for command '%s'" % name,
+               expr.get('data'), allow_array=True,
+               allowed_names=['union', 'struct'])
+    check_type(expr_info, "'base' for command '%s'" % name,
Quoted 8 lines

scripts/qapi.py def check_command(expr, expr_info): · line 320

Quoted 6 lines
scripts/qapi.py +5 -0
+               expr.get('base'), allowed_names=['struct'],
+               allow_dict=False)
+    check_type(expr_info, "'returns' for command '%s'" % name,
+               expr.get('returns'), allow_array=True,
+               allowed_names=['built-in', 'union', 'struct', 'enum'])
 

Nicely done.

Wait a sec! What's a command's 'base'?

[...]

author
#48 lore raw

Re: [Qemu-devel] [PATCH v4 13/19] qapi: More rigourous checking of types

Quoted 31 lines · Markus Armbruster
Quoted 14 lines · Markus Armbruster
Quoted 12 lines · Eric Blake

Now that we know every expression is valid with regards to its keys, we can add further tests that those keys refer to valid types. With this patch, all references to a type (the 'data': of command, type, union, and event, and the 'returns':
of command) must resolve to a builtin or another type declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested sub-structs will be done in later patches.

Update the testsuite to match improved output.

[...]

Quoted 5 lines
Quoted 5 lines
scripts/qapi.py +1 -0
@@ -262,6 +308,15 @@ def check_command(expr, expr_info):
         raise QAPIExprError(expr_info,
                             "command '%s' is already defined" % name)
     commands.append(name)
+    check_type(expr_info, "'data' for command '%s'" % name,
Quoted 8 lines

scripts/qapi.py def check_command(expr, expr_info): · line 316

Quoted 5 lines
scripts/qapi.py +5 -0
+               expr.get('data'), allow_array=True,
+               allowed_names=['union', 'struct'])
+    check_type(expr_info, "'base' for command '%s'" % name,
+               expr.get('base'), allowed_names=['struct'],
+               allow_dict=False)

Nicely done.

Quoted 1 line

Wait a sec! What's a command's 'base'?

Blech. You're right - only 'union' and 'struct' have a base. And since an earlier patch already filtered out 'base' as a non-allowed key for 'command, this check_type is dead code. All the more reason for me to spin v5 :)

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

Re: [Qemu-devel] [PATCH v4 13/19] qapi: More rigourous checking of types

In reply to Markus Armbruster
Quoted 12 lines · Markus Armbruster
Quoted 9 lines · Eric Blake

Now that we know every expression is valid with regards to its keys, we can add further tests that those keys refer to valid types. With this patch, all references to a type (the 'data': of command, type, union, and event, and the 'returns':
of command) must resolve to a builtin or another type declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested sub-structs will be done in later patches.

Quoted 8 lines

scripts/qapi.py def discriminator_find_enum_define(expr): · line 302

Quoted 5 lines
scripts/qapi.py +5 -0
+    for (key, value) in data.items():
+        check_type(expr_info, "member '%s' of %s" % (key, source), value,
+                   allow_array=True,
+                   allowed_names=['built-in', 'union', 'struct', 'enum'],
+                   allow_dict=True)

Hmm, allowed_names isn't about allowed names, it's about allowed meta-types. Rename?

Will do.

Quoted 20 lines
Quoted 9 lines

def check_exprs(schema):
for expr_elem in schema.exprs:
expr = expr_elem['expr']
info = expr_elem['info']

scripts/qapi.py +0 -4
-        if expr.has_key('union'):
-            check_union(expr, info)
-        if expr.has_key('event'):
-            check_event(expr, info)

scripts/qapi.py def check_enum(expr, expr_info): · line 437

Quoted 10 lines
scripts/qapi.py +6 -0
         if expr.has_key('enum'):
             check_enum(expr, info)
+        if expr.has_key('union'):
+            check_union(expr, info)
+        if expr.has_key('type'):
+            check_struct(expr, info)
         if expr.has_key('command'):
             check_command(expr, info)
+        if expr.has_key('event'):
+            check_event(expr, info)
Quoted 5 lines

Not related to this patch: this chain of ifs bothers me. The conditions should be exclusive, because each expression must have a well-defined meta-type. If I remember correctly, you actually enforce this elsewhere in your series. Do we want to make it obvious in the code here? elif instead of if, perhaps?

Yes, earlier in the series guarantees that by this point, the conditions are now exclusive. It also bothers me that different points in the file are iterating over the 5 key types in different order, I'll clean that up in v5.

Quoted 9 lines

tests/qapi-schema/data-array-unknown.err line 1

Quoted 3 lines

+++ b/tests/qapi-schema/data-array-unknown.err

tests/qapi-schema/data-array-unknown.err +1 -0
@@ -0,0 +1 @@
+tests/qapi-schema/data-array-unknown.json:2: 'data' for command 'oops' references unknown type 'NoSuchType'

The wording "references type" somehow unduly excites my "reference type" synapses :)

Perhaps something like "Type 'NoSuchType' is unknown" would suffice. Entirely up to you; feel free to keep the wording as is.

I'll play with it.

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

PATCH v4 14/19 qapi: More rigorous checking for type safety bypass

In reply to Eric Blake

Now that we have a way to validate every type, we can also be stricter about enforcing that callers that want to bypass type safety in generated code. Prior to this patch, it didn't matter what value was associated with the key 'gen', but it looked odd that 'gen':'yes' could result in bypassing the generated code. These changes also enforce the changes made earlier in the series for documentation and consolidation of using '**' as the wildcard type.

---
 scripts/qapi.py                            | 21 ++++++++++++++++-----
 tests/qapi-schema/type-bypass-bad-gen.err  |  1 +
 tests/qapi-schema/type-bypass-bad-gen.exit |  2 +-
 tests/qapi-schema/type-bypass-bad-gen.json |  2 +-
 tests/qapi-schema/type-bypass-bad-gen.out  |  3 ---
 tests/qapi-schema/type-bypass-no-gen.err   |  1 +
 tests/qapi-schema/type-bypass-no-gen.exit  |  2 +-
 tests/qapi-schema/type-bypass-no-gen.json  |  2 +-
 tests/qapi-schema/type-bypass-no-gen.out   |  3 ---
 9 files changed, 22 insertions(+), 15 deletions(-)
scripts/qapi.py +16 -5
index 20c0ce9..15972c6 100644
@@ -256,13 +256,13 @@ def discriminator_find_enum_define(expr):
     return find_enum(discriminator_type)
 
 def check_type(expr_info, source, data, allow_array = False,
-               allowed_names = [], allow_dict = True):
+               allowed_names = [], allow_dict = True, allow_star = False):
     global all_types
 
     if data is None:
         return
 
-    if data == '**':
+    if allow_star and data == '**':
         return
 
     # Check if array type for data is okay
@@ -278,6 +278,10 @@ def check_type(expr_info, source, data, allow_array = False,
 
     # Check if type name for data is okay
     if isinstance(data, basestring):
+        if data == '**':
+            raise QAPIExprError(expr_info,
+                                "%s uses '**' but did not request 'gen':'no'"
+                                % source)
         if not data in all_types:
             raise QAPIExprError(expr_info,
                                 "%s references unknown type '%s'"
@@ -299,24 +303,27 @@ def check_type(expr_info, source, data, allow_array = False,
         check_type(expr_info, "member '%s' of %s" % (key, source), value,
                    allow_array=True,
                    allowed_names=['built-in', 'union', 'struct', 'enum'],
-                   allow_dict=True)
+                   allow_dict=True, allow_star=allow_star)
 
 def check_command(expr, expr_info):
     global commands
     name = expr['command']
+    allow_star = expr.has_key('gen')
+
     if name in commands:
         raise QAPIExprError(expr_info,
                             "command '%s' is already defined" % name)
     commands.append(name)
     check_type(expr_info, "'data' for command '%s'" % name,
                expr.get('data'), allow_array=True,
-               allowed_names=['union', 'struct'])
+               allowed_names=['union', 'struct'], allow_star=allow_star)
     check_type(expr_info, "'base' for command '%s'" % name,
                expr.get('base'), allowed_names=['struct'],
                allow_dict=False)
     check_type(expr_info, "'returns' for command '%s'" % name,
                expr.get('returns'), allow_array=True,
-               allowed_names=['built-in', 'union', 'struct', 'enum'])
+               allowed_names=['built-in', 'union', 'struct', 'enum'],
+               allow_star=allow_star)
 
 def check_event(expr, expr_info):
     global events
@@ -450,6 +457,10 @@ def check_keys(expr_elem, meta, required, optional=[]):
             raise QAPIExprError(info,
                                 "%s '%s' has unknown key '%s'"
                                 % (meta, name, key))
+        if (key == 'gen' or key == 'success-response') and value != 'no':
+            raise QAPIExprError(info,
+                                "'%s' of %s '%s' should only have value 'no'"
+                                % (key, meta, name))
     for key in required:
         if not expr.has_key(key):
             raise QAPIExprError(info,
tests/qapi-schema/type-bypass-bad-gen.err +1 -0
index e69de29..c408364 100644
@@ -0,0 +1 @@
+tests/qapi-schema/type-bypass-bad-gen.json:2: 'gen' of command 'foo' should only have value 'no'
tests/qapi-schema/type-bypass-bad-gen.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/type-bypass-bad-gen.json +1 -1
index 6894526..5514b80 100644
@@ -1,2 +1,2 @@
-# FIXME: 'gen' should only appear with value 'no'
+# 'gen' should only appear with value 'no'
 { 'command': 'foo', 'gen': 'whatever' }
tests/qapi-schema/type-bypass-bad-gen.out +0 -3
index e678f2c..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'foo'), ('gen', 'whatever')])]
-[]
-[]
tests/qapi-schema/type-bypass-no-gen.err +1 -0
index e69de29..294ca2e 100644
@@ -0,0 +1 @@
+tests/qapi-schema/type-bypass-no-gen.json:2: member 'arg' of 'data' for command 'unsafe' uses '**' but did not request 'gen':'no'
tests/qapi-schema/type-bypass-no-gen.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/type-bypass-no-gen.json +1 -1
index 72c817f..49b5742 100644
@@ -1,2 +1,2 @@
-# FIXME: type bypass should only work with 'gen':'no'
+# type bypass only works with 'gen':'no'
 { 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**' }
tests/qapi-schema/type-bypass-no-gen.out +0 -3
index 8b2a9ac..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**')])]
-[]
-[]
Signature · 1 line
1.9.3
#51 lore raw

Re: [Qemu-devel] [PATCH v4 14/19] qapi: More rigorous checking for type safety bypass

Quoted 8 lines · Eric Blake

Now that we have a way to validate every type, we can also be stricter about enforcing that callers that want to bypass type safety in generated code. Prior to this patch, it didn't matter what value was associated with the key 'gen', but it looked odd that 'gen':'yes' could result in bypassing the generated code. These changes also enforce the changes made earlier in the series for documentation and consolidation of using '**' as the wildcard type.

Perhaps it's worth mentioning that the schema has always used 'gen':
'no'.

That said, 'no' is silly. The natural JSON for a flag is false / true! Since you're touching it anyway, consider making it an optional boolean defaulting to false. Same for the other silly 'no': success-response.

Quoted 34 lines
---
 scripts/qapi.py                            | 21 ++++++++++++++++-----
 tests/qapi-schema/type-bypass-bad-gen.err  |  1 +
 tests/qapi-schema/type-bypass-bad-gen.exit |  2 +-
 tests/qapi-schema/type-bypass-bad-gen.json |  2 +-
 tests/qapi-schema/type-bypass-bad-gen.out  |  3 ---
 tests/qapi-schema/type-bypass-no-gen.err   |  1 +
 tests/qapi-schema/type-bypass-no-gen.exit  |  2 +-
 tests/qapi-schema/type-bypass-no-gen.json  |  2 +-
 tests/qapi-schema/type-bypass-no-gen.out   |  3 ---
 9 files changed, 22 insertions(+), 15 deletions(-)
scripts/qapi.py +2 -2
index 20c0ce9..15972c6 100644
@@ -256,13 +256,13 @@ def discriminator_find_enum_define(expr):
     return find_enum(discriminator_type)
 
 def check_type(expr_info, source, data, allow_array = False,
-               allowed_names = [], allow_dict = True):
+               allowed_names = [], allow_dict = True, allow_star = False):
     global all_types
 
     if data is None:
         return
 
-    if data == '**':
+    if allow_star and data == '**':
         return
 
     # Check if array type for data is okay

scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 287

Quoted 10 lines
scripts/qapi.py +4 -0
@@ -278,6 +278,10 @@ def check_type(expr_info, source, data, allow_array = False,
 
     # Check if type name for data is okay
     if isinstance(data, basestring):
+        if data == '**':
+            raise QAPIExprError(expr_info,
+                                "%s uses '**' but did not request 'gen':'no'"
+                                % source)
         if not data in all_types:
             raise QAPIExprError(expr_info,
                                 "%s references unknown type '%s'"

I'm blind: I can't see where this error gets suppressed when we have 'gen': 'no'.

scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 307

Quoted 7 lines
scripts/qapi.py +1 -1
@@ -299,24 +303,27 @@ def check_type(expr_info, source, data, allow_array = False,
         check_type(expr_info, "member '%s' of %s" % (key, source), value,
                    allow_array=True,
                    allowed_names=['built-in', 'union', 'struct', 'enum'],
-                   allow_dict=True)
+                   allow_dict=True, allow_star=allow_star)
 

allow_star applies recursively. Correct, because...

Quoted 12 lines
scripts/qapi.py +2 -1
 def check_command(expr, expr_info):
     global commands
     name = expr['command']
+    allow_star = expr.has_key('gen')
+
     if name in commands:
         raise QAPIExprError(expr_info,
                             "command '%s' is already defined" % name)
     commands.append(name)
     check_type(expr_info, "'data' for command '%s'" % name,
                expr.get('data'), allow_array=True,
-               allowed_names=['union', 'struct'])

scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 327

Quoted 10 lines
scripts/qapi.py +3 -1
+               allowed_names=['union', 'struct'], allow_star=allow_star)
     check_type(expr_info, "'base' for command '%s'" % name,
                expr.get('base'), allowed_names=['struct'],
                allow_dict=False)
     check_type(expr_info, "'returns' for command '%s'" % name,
                expr.get('returns'), allow_array=True,
-               allowed_names=['built-in', 'union', 'struct', 'enum'])
+               allowed_names=['built-in', 'union', 'struct', 'enum'],
+               allow_star=allow_star)
 

... it applies exactly to a command's 'data' and 'returns' when it has 'gen': 'no'. Good.

Quoted 13 lines
scripts/qapi.py +4 -0
 def check_event(expr, expr_info):
     global events
@@ -450,6 +457,10 @@ def check_keys(expr_elem, meta, required, optional=[]):
             raise QAPIExprError(info,
                                 "%s '%s' has unknown key '%s'"
                                 % (meta, name, key))
+        if (key == 'gen' or key == 'success-response') and value != 'no':
+            raise QAPIExprError(info,
+                                "'%s' of %s '%s' should only have value 'no'"
+                                % (key, meta, name))
     for key in required:
         if not expr.has_key(key):
             raise QAPIExprError(info,

[...]

author
#52 lore raw

Re: [Qemu-devel] [PATCH v4 14/19] qapi: More rigorous checking for type safety bypass

Quoted 11 lines · Markus Armbruster
Quoted 8 lines · Eric Blake

Now that we have a way to validate every type, we can also be stricter about enforcing that callers that want to bypass type safety in generated code. Prior to this patch, it didn't matter what value was associated with the key 'gen', but it looked odd that 'gen':'yes' could result in bypassing the generated code. These changes also enforce the changes made earlier in the series for documentation and consolidation of using '**' as the wildcard type.

Quoted 6 lines

Perhaps it's worth mentioning that the schema has always used 'gen':
'no'.

That said, 'no' is silly. The natural JSON for a flag is false / true! Since you're touching it anyway, consider making it an optional boolean defaulting to false. Same for the other silly 'no': success-response.

I'd love to, except that the .json parser does not yet allow literal true/false JSON keywords. Fam had a patch back in May that would fix that; maybe I'll fold in his patch to my v5 as a prereq patch:

https://lists.gnu.org/archive/html/qemu-devel/2014-05/msg03916.html

Quoted 8 lines
Quoted 8 lines
scripts/qapi.py +1 -1
@@ -256,13 +256,13 @@ def discriminator_find_enum_define(expr):
     return find_enum(discriminator_type)
 
 def check_type(expr_info, source, data, allow_array = False,
-               allowed_names = [], allow_dict = True):
+               allowed_names = [], allow_dict = True, allow_star = False):
     global all_types
 
Quoted 6 lines

scripts/qapi.py def discriminator_find_enum_define(expr): · line 266

Quoted 6 lines
scripts/qapi.py +1 -1
     if data is None:
         return
 
-    if data == '**':
+    if allow_star and data == '**':
         return

[1]

Quoted 4 lines
Quoted 4 lines
scripts/qapi.py +0 -0
     # Check if array type for data is okay
@@ -278,6 +278,10 @@ def check_type(expr_info, source, data, allow_array = False,
 
Quoted 12 lines

scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 287

Quoted 9 lines
scripts/qapi.py +4 -0
     # Check if type name for data is okay
     if isinstance(data, basestring):
+        if data == '**':
+            raise QAPIExprError(expr_info,
+                                "%s uses '**' but did not request 'gen':'no'"
+                                % source)
         if not data in all_types:
             raise QAPIExprError(expr_info,
                                 "%s references unknown type '%s'"

I'm blind: I can't see where this error gets suppressed when we have 'gen': 'no'.

'gen':'no' triggers the caller to pass allow_star=True to check_type [2]; then at point [1] we short-circuit and exit if '**' was passed. Therefore, if we get here and still have '**', then allow_star is still false, which means 'gen':'no' was not passed and it is user error.

Quoted 16 lines

scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 307

Quoted 8 lines
scripts/qapi.py +1 -1
@@ -299,24 +303,27 @@ def check_type(expr_info, source, data, allow_array = False,
         check_type(expr_info, "member '%s' of %s" % (key, source), value,
                    allow_array=True,
                    allowed_names=['built-in', 'union', 'struct', 'enum'],
-                   allow_dict=True)
+                   allow_dict=True, allow_star=allow_star)
 

allow_star applies recursively. Correct, because...

Quoted 5 lines
scripts/qapi.py +2 -0
 def check_command(expr, expr_info):
     global commands
     name = expr['command']
+    allow_star = expr.has_key('gen')
+

[2] The other trick to note here is that this only checks if 'gen' is a key; but at [3], which is run earlier, we further required that 'gen' can only appear if it has value 'no'.

Quoted 21 lines
Quoted 7 lines
scripts/qapi.py +0 -1
     if name in commands:
         raise QAPIExprError(expr_info,
                             "command '%s' is already defined" % name)
     commands.append(name)
     check_type(expr_info, "'data' for command '%s'" % name,
                expr.get('data'), allow_array=True,
-               allowed_names=['union', 'struct'])

scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 327

Quoted 10 lines
scripts/qapi.py +3 -1
+               allowed_names=['union', 'struct'], allow_star=allow_star)
     check_type(expr_info, "'base' for command '%s'" % name,
                expr.get('base'), allowed_names=['struct'],
                allow_dict=False)
     check_type(expr_info, "'returns' for command '%s'" % name,
                expr.get('returns'), allow_array=True,
-               allowed_names=['built-in', 'union', 'struct', 'enum'])
+               allowed_names=['built-in', 'union', 'struct', 'enum'],
+               allow_star=allow_star)
 

... it applies exactly to a command's 'data' and 'returns' when it has 'gen': 'no'. Good.

Quoted 10 lines

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

Quoted 10 lines
scripts/qapi.py +4 -0
 def check_event(expr, expr_info):
     global events
@@ -450,6 +457,10 @@ def check_keys(expr_elem, meta, required, optional=[]):
             raise QAPIExprError(info,
                                 "%s '%s' has unknown key '%s'"
                                 % (meta, name, key))
+        if (key == 'gen' or key == 'success-response') and value != 'no':
+            raise QAPIExprError(info,
+                                "'%s' of %s '%s' should only have value 'no'"
+                                % (key, meta, name))

[3]

Quoted 6 lines
Quoted 3 lines
scripts/qapi.py +0 -0
     for key in required:
         if not expr.has_key(key):
             raise QAPIExprError(info,

[...]

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

Re: [Qemu-devel] [PATCH v4 14/19] qapi: More rigorous checking for type safety bypass

Quoted 19 lines · Eric Blake
Quoted 11 lines · Markus Armbruster
Quoted 8 lines · Eric Blake

Now that we have a way to validate every type, we can also be stricter about enforcing that callers that want to bypass type safety in generated code. Prior to this patch, it didn't matter what value was associated with the key 'gen', but it looked odd that 'gen':'yes' could result in bypassing the generated code. These changes also enforce the changes made earlier in the series for documentation and consolidation of using '**' as the wildcard type.

Quoted 6 lines

Perhaps it's worth mentioning that the schema has always used 'gen':
'no'.

That said, 'no' is silly. The natural JSON for a flag is false / true! Since you're touching it anyway, consider making it an optional boolean defaulting to false. Same for the other silly 'no': success-response.

Quoted 5 lines

I'd love to, except that the .json parser does not yet allow literal true/false JSON keywords. Fam had a patch back in May that would fix that; maybe I'll fold in his patch to my v5 as a prereq patch:

https://lists.gnu.org/archive/html/qemu-devel/2014-05/msg03916.html

Your choice. I certainly don't want the silly 'no' block your series.

Quoted 34 lines
Quoted 8 lines
Quoted 8 lines
scripts/qapi.py +1 -1
@@ -256,13 +256,13 @@ def discriminator_find_enum_define(expr):
     return find_enum(discriminator_type)
 
 def check_type(expr_info, source, data, allow_array = False,
-               allowed_names = [], allow_dict = True):
+               allowed_names = [], allow_dict = True, allow_star = False):
     global all_types
 
Quoted 6 lines

scripts/qapi.py def discriminator_find_enum_define(expr): · line 266

Quoted 6 lines
scripts/qapi.py +1 -1
     if data is None:
         return
 
-    if data == '**':
+    if allow_star and data == '**':
         return

[1]

Quoted 4 lines
Quoted 4 lines
scripts/qapi.py +0 -0
     # Check if array type for data is okay
@@ -278,6 +278,10 @@ def check_type(expr_info, source, data, allow_array = False,
 
Quoted 12 lines

scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 287

Quoted 9 lines
scripts/qapi.py +4 -0
     # Check if type name for data is okay
     if isinstance(data, basestring):
+        if data == '**':
+            raise QAPIExprError(expr_info,
+                                "%s uses '**' but did not request 'gen':'no'"
+                                % source)
         if not data in all_types:
             raise QAPIExprError(expr_info,
                                 "%s references unknown type '%s'"

I'm blind: I can't see where this error gets suppressed when we have 'gen': 'no'.

Quoted 4 lines

'gen':'no' triggers the caller to pass allow_star=True to check_type [2]; then at point [1] we short-circuit and exit if '**' was passed. Therefore, if we get here and still have '**', then allow_star is still false, which means 'gen':'no' was not passed and it is user error.

Got it, thanks!

[...]

author
#54 lore raw

PATCH v4 15/19 qapi: Merge UserDefTwo and UserDefNested in tests

In reply to Eric Blake

In the testsuite, UserDefTwo and UserDefNested were identical types other than the member names. Reduce code duplication by having just one type, and choose names that also favor reuse. This will also make it easier for a later patch to get rid of nested inline subtypes in QAPI. When touching code to add new allocations, also convert existing allocations to consistently prefer typesafe g_new0 over g_malloc0.

Ensure that 'make check-qapi-schema check-unit' still passes.

---
 tests/qapi-schema/qapi-schema-test.json | 10 +----
 tests/qapi-schema/qapi-schema-test.out  |  6 +--
 tests/test-qmp-commands.c               | 32 +++++++--------
 tests/test-qmp-input-strict.c           | 19 +++++----
 tests/test-qmp-input-visitor.c          | 19 +++++----
 tests/test-qmp-output-visitor.c         | 50 +++++++++++------------
 tests/test-visitor-serialization.c      | 71 +++++++++++++++++----------------
 7 files changed, 103 insertions(+), 104 deletions(-)
tests/qapi-schema/qapi-schema-test.json +2 -8
index ab4d3d9..2e13f09 100644
@@ -15,16 +15,10 @@
   'data': { 'string': 'str', '*enum1': 'EnumOne' } }
 
 { 'type': 'UserDefTwo',
-  'data': { 'string': 'str',
-            'dict': { 'string': 'str',
-                      'dict': { 'userdef': 'UserDefOne', 'string': 'str' },
-                      '*dict2': { 'userdef': 'UserDefOne', 'string': 'str' } } } }
-
-{ 'type': 'UserDefNested',
   'data': { 'string0': 'str',
             'dict1': { 'string1': 'str',
-                       'dict2': { 'userdef1': 'UserDefOne', 'string2': 'str' },
-                       '*dict3': { 'userdef2': 'UserDefOne', 'string3': 'str' } } } }
+                       'dict2': { 'userdef': 'UserDefOne', 'string': 'str' },
+                       '*dict3': { 'userdef': 'UserDefOne', 'string': 'str' } } } }
 
 # for testing unions
 { 'type': 'UserDefA',
tests/qapi-schema/qapi-schema-test.out +2 -4
index 95e9899..f94bbcc 100644
@@ -2,8 +2,7 @@
  OrderedDict([('type', 'NestedEnumsOne'), ('data', OrderedDict([('enum1', 'EnumOne'), ('*enum2', 'EnumOne'), ('enum3', 'EnumOne'), ('*enum4', 'EnumOne')]))]),
  OrderedDict([('type', 'UserDefZero'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('type', 'UserDefOne'), ('base', 'UserDefZero'), ('data', OrderedDict([('string', 'str'), ('*enum1', 'EnumOne')]))]),
- OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string', 'str'), ('dict', OrderedDict([('string', 'str'), ('dict', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')])), ('*dict2', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]))]))]),
- OrderedDict([('type', 'UserDefNested'), ('data', OrderedDict([('string0', 'str'), ('dict1', OrderedDict([('string1', 'str'), ('dict2', OrderedDict([('userdef1', 'UserDefOne'), ('string2', 'str')])), ('*dict3', OrderedDict([('userdef2', 'UserDefOne'), ('string3', 'str')]))]))]))]),
+ OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', OrderedDict([('string1', 'str'), ('dict2', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')])), ('*dict3', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]))]))]),
  OrderedDict([('type', 'UserDefA'), ('data', OrderedDict([('boolean', 'bool')]))]),
  OrderedDict([('type', 'UserDefB'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('union', 'UserDefUnion'), ('base', 'UserDefZero'), ('data', OrderedDict([('a', 'UserDefA'), ('b', 'UserDefB')]))]),
@@ -28,8 +27,7 @@
 [OrderedDict([('type', 'NestedEnumsOne'), ('data', OrderedDict([('enum1', 'EnumOne'), ('*enum2', 'EnumOne'), ('enum3', 'EnumOne'), ('*enum4', 'EnumOne')]))]),
  OrderedDict([('type', 'UserDefZero'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('type', 'UserDefOne'), ('base', 'UserDefZero'), ('data', OrderedDict([('string', 'str'), ('*enum1', 'EnumOne')]))]),
- OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string', 'str'), ('dict', OrderedDict([('string', 'str'), ('dict', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')])), ('*dict2', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]))]))]),
- OrderedDict([('type', 'UserDefNested'), ('data', OrderedDict([('string0', 'str'), ('dict1', OrderedDict([('string1', 'str'), ('dict2', OrderedDict([('userdef1', 'UserDefOne'), ('string2', 'str')])), ('*dict3', OrderedDict([('userdef2', 'UserDefOne'), ('string3', 'str')]))]))]))]),
+ OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', OrderedDict([('string1', 'str'), ('dict2', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')])), ('*dict3', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]))]))]),
  OrderedDict([('type', 'UserDefA'), ('data', OrderedDict([('boolean', 'bool')]))]),
  OrderedDict([('type', 'UserDefB'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('type', 'UserDefUnionBase'), ('data', OrderedDict([('string', 'str'), ('enum1', 'EnumOne')]))]),
tests/test-qmp-commands.c +16 -16
index 554e222..9189cd2 100644
@@ -32,13 +32,13 @@ UserDefTwo *qmp_user_def_cmd2(UserDefOne *ud1a,
     ud1d->base->integer = has_udb1 ? ud1b->base->integer : 0;
 
     ret = g_malloc0(sizeof(UserDefTwo));
-    ret->string = strdup("blah1");
-    ret->dict.string = strdup("blah2");
-    ret->dict.dict.userdef = ud1c;
-    ret->dict.dict.string = strdup("blah3");
-    ret->dict.has_dict2 = true;
-    ret->dict.dict2.userdef = ud1d;
-    ret->dict.dict2.string = strdup("blah4");
+    ret->string0 = strdup("blah1");
+    ret->dict1.string1 = strdup("blah2");
+    ret->dict1.dict2.userdef = ud1c;
+    ret->dict1.dict2.string = strdup("blah3");
+    ret->dict1.has_dict3 = true;
+    ret->dict1.dict3.userdef = ud1d;
+    ret->dict1.dict3.string = strdup("blah4");
 
     return ret;
 }
@@ -120,15 +120,15 @@ static void test_dispatch_cmd_io(void)
 
     ret = qobject_to_qdict(test_qmp_dispatch(req));
 
-    assert(!strcmp(qdict_get_str(ret, "string"), "blah1"));
-    ret_dict = qdict_get_qdict(ret, "dict");
-    assert(!strcmp(qdict_get_str(ret_dict, "string"), "blah2"));
-    ret_dict_dict = qdict_get_qdict(ret_dict, "dict");
+    assert(!strcmp(qdict_get_str(ret, "string0"), "blah1"));
+    ret_dict = qdict_get_qdict(ret, "dict1");
+    assert(!strcmp(qdict_get_str(ret_dict, "string1"), "blah2"));
+    ret_dict_dict = qdict_get_qdict(ret_dict, "dict2");
     ret_dict_dict_userdef = qdict_get_qdict(ret_dict_dict, "userdef");
     assert(qdict_get_int(ret_dict_dict_userdef, "integer") == 42);
     assert(!strcmp(qdict_get_str(ret_dict_dict_userdef, "string"), "hello"));
     assert(!strcmp(qdict_get_str(ret_dict_dict, "string"), "blah3"));
-    ret_dict_dict2 = qdict_get_qdict(ret_dict, "dict2");
+    ret_dict_dict2 = qdict_get_qdict(ret_dict, "dict3");
     ret_dict_dict2_userdef = qdict_get_qdict(ret_dict_dict2, "userdef");
     assert(qdict_get_int(ret_dict_dict2_userdef, "integer") == 422);
     assert(!strcmp(qdict_get_str(ret_dict_dict2_userdef, "string"), "hello2"));
@@ -192,7 +192,7 @@ static void test_dealloc_partial(void)
         QmpInputVisitor *qiv;
 
         ud2_dict = qdict_new();
-        qdict_put_obj(ud2_dict, "string", QOBJECT(qstring_from_str(text)));
+        qdict_put_obj(ud2_dict, "string0", QOBJECT(qstring_from_str(text)));
 
         qiv = qmp_input_visitor_new(QOBJECT(ud2_dict));
         visit_type_UserDefTwo(qmp_input_get_visitor(qiv), &ud2, NULL, &err);
@@ -202,9 +202,9 @@ static void test_dealloc_partial(void)
 
     /* verify partial success */
     assert(ud2 != NULL);
-    assert(ud2->string != NULL);
-    assert(strcmp(ud2->string, text) == 0);
-    assert(ud2->dict.dict.userdef == NULL);
+    assert(ud2->string0 != NULL);
+    assert(strcmp(ud2->string0, text) == 0);
+    assert(ud2->dict1.dict2.userdef == NULL);
 
     /* confirm & release construction error */
     assert(err != NULL);
tests/test-qmp-input-strict.c +11 -8
index 0f77003..29d4f82 100644
@@ -1,7 +1,7 @@
 /*
  * QMP Input Visitor unit-tests (strict mode).
  *
- * Copyright (C) 2011-2012 Red Hat Inc.
+ * Copyright (C) 2011-2012, 2014 Red Hat Inc.
  *
  * Authors:
  *  Luiz Capitulino <[email protected]>
@@ -116,15 +116,18 @@ static void test_validate_struct(TestInputVisitorData *data,
 static void test_validate_struct_nested(TestInputVisitorData *data,
                                          const void *unused)
 {
-    UserDefNested *udp = NULL;
+    UserDefTwo *udp = NULL;
     Error *err = NULL;
     Visitor *v;
 
-    v = validate_test_init(data, "{ 'string0': 'string0', 'dict1': { 'string1': 'string1', 'dict2': { 'userdef1': { 'integer': 42, 'string': 'string' }, 'string2': 'string2'}}}");
+    v = validate_test_init(data, "{ 'string0': 'string0', "
+                           "'dict1': { 'string1': 'string1', "
+                           "'dict2': { 'userdef': { 'integer': 42, "
+                           "'string': 'string' }, 'string': 'string2'}}}");
 
-    visit_type_UserDefNested(v, &udp, NULL, &err);
+    visit_type_UserDefTwo(v, &udp, NULL, &err);
     g_assert(!err);
-    qapi_free_UserDefNested(udp);
+    qapi_free_UserDefTwo(udp);
 }
 
 static void test_validate_list(TestInputVisitorData *data,
@@ -207,15 +210,15 @@ static void test_validate_fail_struct(TestInputVisitorData *data,
 static void test_validate_fail_struct_nested(TestInputVisitorData *data,
                                               const void *unused)
 {
-    UserDefNested *udp = NULL;
+    UserDefTwo *udp = NULL;
     Error *err = NULL;
     Visitor *v;
 
     v = validate_test_init(data, "{ 'string0': 'string0', 'dict1': { 'string1': 'string1', 'dict2': { 'userdef1': { 'integer': 42, 'string': 'string', 'extra': [42, 23, {'foo':'bar'}] }, 'string2': 'string2'}}}");
 
-    visit_type_UserDefNested(v, &udp, NULL, &err);
+    visit_type_UserDefTwo(v, &udp, NULL, &err);
     g_assert(err);
-    qapi_free_UserDefNested(udp);
+    qapi_free_UserDefTwo(udp);
 }
 
 static void test_validate_fail_list(TestInputVisitorData *data,
tests/test-qmp-input-visitor.c +11 -8
index 1c8e872..3e1da9d 100644
@@ -1,7 +1,7 @@
 /*
  * QMP Input Visitor unit-tests.
  *
- * Copyright (C) 2011 Red Hat Inc.
+ * Copyright (C) 2011, 2014 Red Hat Inc.
  *
  * Authors:
  *  Luiz Capitulino <[email protected]>
@@ -248,23 +248,26 @@ static void check_and_free_str(char *str, const char *cmp)
 static void test_visitor_in_struct_nested(TestInputVisitorData *data,
                                           const void *unused)
 {
-    UserDefNested *udp = NULL;
+    UserDefTwo *udp = NULL;
     Error *err = NULL;
     Visitor *v;
 
-    v = visitor_input_test_init(data, "{ 'string0': 'string0', 'dict1': { 'string1': 'string1', 'dict2': { 'userdef1': { 'integer': 42, 'string': 'string' }, 'string2': 'string2'}}}");
+    v = visitor_input_test_init(data, "{ 'string0': 'string0', "
+                                "'dict1': { 'string1': 'string1', "
+                                "'dict2': { 'userdef': { 'integer': 42, "
+                                "'string': 'string' }, 'string': 'string2'}}}");
 
-    visit_type_UserDefNested(v, &udp, NULL, &err);
+    visit_type_UserDefTwo(v, &udp, NULL, &err);
     g_assert(!err);
 
     check_and_free_str(udp->string0, "string0");
     check_and_free_str(udp->dict1.string1, "string1");
-    g_assert_cmpint(udp->dict1.dict2.userdef1->base->integer, ==, 42);
-    check_and_free_str(udp->dict1.dict2.userdef1->string, "string");
-    check_and_free_str(udp->dict1.dict2.string2, "string2");
+    g_assert_cmpint(udp->dict1.dict2.userdef->base->integer, ==, 42);
+    check_and_free_str(udp->dict1.dict2.userdef->string, "string");
+    check_and_free_str(udp->dict1.dict2.string, "string2");
     g_assert(udp->dict1.has_dict3 == false);
 
-    g_free(udp->dict1.dict2.userdef1);
+    g_free(udp->dict1.dict2.userdef);
     g_free(udp);
 }
 
tests/test-qmp-output-visitor.c +25 -25

106 lines not on this page · raw message

tests/test-visitor-serialization.c +36 -35

127 lines not on this page · raw message

Signature · 1 line
1.9.3
author
#55 lore raw

PATCH v4 16/19 qapi: Drop tests for inline subtypes

In reply to Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument; but existing use of inline substructs conflicts with that goal. This patch fixes the testsuite to avoid nested subtypes, by breaking the nesting into explicit types. When touching code to add new allocations, also convert existing allocations to consistently prefer typesafe g_new0 over g_malloc0.

---
 tests/qapi-schema/qapi-schema-test.json | 12 ++++++--
 tests/qapi-schema/qapi-schema-test.out  |  8 +++--
 tests/test-qmp-commands.c               | 17 ++++++-----
 tests/test-qmp-input-visitor.c          | 14 +++++----
 tests/test-qmp-output-visitor.c         | 44 +++++++++++++++------------
 tests/test-visitor-serialization.c      | 53 ++++++++++++++++++---------------
 6 files changed, 87 insertions(+), 61 deletions(-)
tests/qapi-schema/qapi-schema-test.json +9 -3
index 2e13f09..1f922c1 100644
@@ -14,11 +14,17 @@
   'base': 'UserDefZero',
   'data': { 'string': 'str', '*enum1': 'EnumOne' } }
 
+{ 'type': 'UserDefTwoDictDict',
+  'data': { 'userdef': 'UserDefOne', 'string': 'str' } }
+
+{ 'type': 'UserDefTwoDict',
+  'data': { 'string1': 'str',
+            'dict2': 'UserDefTwoDictDict',
+            '*dict3': 'UserDefTwoDictDict' } }
+
 { 'type': 'UserDefTwo',
   'data': { 'string0': 'str',
-            'dict1': { 'string1': 'str',
-                       'dict2': { 'userdef': 'UserDefOne', 'string': 'str' },
-                       '*dict3': { 'userdef': 'UserDefOne', 'string': 'str' } } } }
+            'dict1': 'UserDefTwoDict' } }
 
 # for testing unions
 { 'type': 'UserDefA',
tests/qapi-schema/qapi-schema-test.out +6 -2
index f94bbcc..1d7b53c 100644
@@ -2,7 +2,9 @@
  OrderedDict([('type', 'NestedEnumsOne'), ('data', OrderedDict([('enum1', 'EnumOne'), ('*enum2', 'EnumOne'), ('enum3', 'EnumOne'), ('*enum4', 'EnumOne')]))]),
  OrderedDict([('type', 'UserDefZero'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('type', 'UserDefOne'), ('base', 'UserDefZero'), ('data', OrderedDict([('string', 'str'), ('*enum1', 'EnumOne')]))]),
- OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', OrderedDict([('string1', 'str'), ('dict2', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')])), ('*dict3', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]))]))]),
+ OrderedDict([('type', 'UserDefTwoDictDict'), ('data', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]),
+ OrderedDict([('type', 'UserDefTwoDict'), ('data', OrderedDict([('string1', 'str'), ('dict2', 'UserDefTwoDictDict'), ('*dict3', 'UserDefTwoDictDict')]))]),
+ OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', 'UserDefTwoDict')]))]),
  OrderedDict([('type', 'UserDefA'), ('data', OrderedDict([('boolean', 'bool')]))]),
  OrderedDict([('type', 'UserDefB'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('union', 'UserDefUnion'), ('base', 'UserDefZero'), ('data', OrderedDict([('a', 'UserDefA'), ('b', 'UserDefB')]))]),
@@ -27,7 +29,9 @@
 [OrderedDict([('type', 'NestedEnumsOne'), ('data', OrderedDict([('enum1', 'EnumOne'), ('*enum2', 'EnumOne'), ('enum3', 'EnumOne'), ('*enum4', 'EnumOne')]))]),
  OrderedDict([('type', 'UserDefZero'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('type', 'UserDefOne'), ('base', 'UserDefZero'), ('data', OrderedDict([('string', 'str'), ('*enum1', 'EnumOne')]))]),
- OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', OrderedDict([('string1', 'str'), ('dict2', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')])), ('*dict3', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]))]))]),
+ OrderedDict([('type', 'UserDefTwoDictDict'), ('data', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]),
+ OrderedDict([('type', 'UserDefTwoDict'), ('data', OrderedDict([('string1', 'str'), ('dict2', 'UserDefTwoDictDict'), ('*dict3', 'UserDefTwoDictDict')]))]),
+ OrderedDict([('type', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', 'UserDefTwoDict')]))]),
  OrderedDict([('type', 'UserDefA'), ('data', OrderedDict([('boolean', 'bool')]))]),
  OrderedDict([('type', 'UserDefB'), ('data', OrderedDict([('integer', 'int')]))]),
  OrderedDict([('type', 'UserDefUnionBase'), ('data', OrderedDict([('string', 'str'), ('enum1', 'EnumOne')]))]),
tests/test-qmp-commands.c +10 -7
index 9189cd2..dc199d3 100644
@@ -33,12 +33,15 @@ UserDefTwo *qmp_user_def_cmd2(UserDefOne *ud1a,
 
     ret = g_malloc0(sizeof(UserDefTwo));
     ret->string0 = strdup("blah1");
-    ret->dict1.string1 = strdup("blah2");
-    ret->dict1.dict2.userdef = ud1c;
-    ret->dict1.dict2.string = strdup("blah3");
-    ret->dict1.has_dict3 = true;
-    ret->dict1.dict3.userdef = ud1d;
-    ret->dict1.dict3.string = strdup("blah4");
+    ret->dict1 = g_malloc0(sizeof(UserDefTwoDict));
+    ret->dict1->string1 = strdup("blah2");
+    ret->dict1->dict2 = g_malloc0(sizeof(UserDefTwoDictDict));
+    ret->dict1->dict2->userdef = ud1c;
+    ret->dict1->dict2->string = strdup("blah3");
+    ret->dict1->dict3 = g_malloc0(sizeof(UserDefTwoDictDict));
+    ret->dict1->has_dict3 = true;
+    ret->dict1->dict3->userdef = ud1d;
+    ret->dict1->dict3->string = strdup("blah4");
 
     return ret;
 }
@@ -204,7 +207,7 @@ static void test_dealloc_partial(void)
     assert(ud2 != NULL);
     assert(ud2->string0 != NULL);
     assert(strcmp(ud2->string0, text) == 0);
-    assert(ud2->dict1.dict2.userdef == NULL);
+    assert(ud2->dict1 == NULL);
 
     /* confirm & release construction error */
     assert(err != NULL);
tests/test-qmp-input-visitor.c +8 -6
index 3e1da9d..30a5441 100644
@@ -261,13 +261,15 @@ static void test_visitor_in_struct_nested(TestInputVisitorData *data,
     g_assert(!err);
 
     check_and_free_str(udp->string0, "string0");
-    check_and_free_str(udp->dict1.string1, "string1");
-    g_assert_cmpint(udp->dict1.dict2.userdef->base->integer, ==, 42);
-    check_and_free_str(udp->dict1.dict2.userdef->string, "string");
-    check_and_free_str(udp->dict1.dict2.string, "string2");
-    g_assert(udp->dict1.has_dict3 == false);
+    check_and_free_str(udp->dict1->string1, "string1");
+    g_assert_cmpint(udp->dict1->dict2->userdef->base->integer, ==, 42);
+    check_and_free_str(udp->dict1->dict2->userdef->string, "string");
+    check_and_free_str(udp->dict1->dict2->string, "string2");
+    g_assert(udp->dict1->has_dict3 == false);
 
-    g_free(udp->dict1.dict2.userdef);
+    g_free(udp->dict1->dict2->userdef);
+    g_free(udp->dict1->dict2);
+    g_free(udp->dict1);
     g_free(udp);
 }
 
tests/test-qmp-output-visitor.c +25 -19

57 lines not on this page · raw message

tests/test-visitor-serialization.c +29 -24

65 lines not on this page · raw message

Signature · 1 line
1.9.3
author
#56 lore raw

PATCH v4 17/19 qapi: Drop inline subtype in query-version

In reply to Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument; but existing use of inline substructs conflicts with that goal. This patch fixes one of only two commands relying on nested subtypes, by breaking the nesting into an explicit type. The QMP wire format is unaffected by this change.

Prefer the safer g_new0() while making the conversion.

---
 hmp.c            |  2 +-
 qapi/common.json | 26 +++++++++++++++++++-------
 qmp.c            |  9 +++++----
 3 files changed, 25 insertions(+), 12 deletions(-)
hmp.c +1 -1
index 40a90da..23fc3da 100644
@@ -55,7 +55,7 @@ void hmp_info_version(Monitor *mon, const QDict *qdict)
     info = qmp_query_version(NULL);
 
     monitor_printf(mon, "%" PRId64 ".%" PRId64 ".%" PRId64 "%s\n",
-                   info->qemu.major, info->qemu.minor, info->qemu.micro,
+                   info->qemu->major, info->qemu->minor, info->qemu->micro,
                    info->package);
 
     qapi_free_VersionInfo(info);
qapi/common.json +19 -7
index 4e9a21f..d007095 100644
@@ -29,15 +29,28 @@
             'DeviceNotActive', 'DeviceNotFound', 'KVMMissingCap' ] }
 
 ##
+# @VersionTriple
+#
+# A three-part version number.
+#
+# @qemu.major:  The major version number.
+#
+# @qemu.minor:  The minor version number.
+#
+# @qemu.micro:  The micro version number.
+#
+# Since: 2.2
+##
+{ 'type': 'VersionTriple',
+  'data': {'major': 'int', 'minor': 'int', 'micro': 'int'} }
+
+
+##
 # @VersionInfo:
 #
 # A description of QEMU's version.
 #
-# @qemu.major:  The major version of QEMU
-#
-# @qemu.minor:  The minor version of QEMU
-#
-# @qemu.micro:  The micro version of QEMU.  By current convention, a micro
+# @qemu:        The version of QEMU.  By current convention, a micro
 #               version of 50 signifies a development branch.  A micro version
 #               greater than or equal to 90 signifies a release candidate for
 #               the next minor version.  A micro version of less than 50
@@ -51,8 +64,7 @@
 # Since: 0.14.0
 ##
 { 'type': 'VersionInfo',
-  'data': {'qemu': {'major': 'int', 'minor': 'int', 'micro': 'int'},
-           'package': 'str'} }
+  'data': {'qemu': 'VersionTriple', 'package': 'str'} }
 
 ##
 # @query-version:
qmp.c +5 -4
index c6767c4..24b658a 100644
@@ -45,15 +45,16 @@ NameInfo *qmp_query_name(Error **errp)
 
 VersionInfo *qmp_query_version(Error **errp)
 {
-    VersionInfo *info = g_malloc0(sizeof(*info));
+    VersionInfo *info = g_new0(VersionInfo, 1);
     const char *version = QEMU_VERSION;
     char *tmp;
 
-    info->qemu.major = strtol(version, &tmp, 10);
+    info->qemu = g_new0(VersionTriple, 1);
+    info->qemu->major = strtol(version, &tmp, 10);
     tmp++;
-    info->qemu.minor = strtol(tmp, &tmp, 10);
+    info->qemu->minor = strtol(tmp, &tmp, 10);
     tmp++;
-    info->qemu.micro = strtol(tmp, &tmp, 10);
+    info->qemu->micro = strtol(tmp, &tmp, 10);
     info->package = g_strdup(QEMU_PKGVERSION);
 
     return info;
Signature · 1 line
1.9.3
#57 lore raw

Re: [Qemu-devel] [PATCH v4 17/19] qapi: Drop inline subtype in query-version

Quoted 6 lines · Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument; but existing use of inline substructs conflicts with that goal. This patch fixes one of only two commands relying on nested subtypes, by breaking the nesting into an explicit type. The QMP wire format is unaffected by this change.

"subtype" makes me think of subtype polymorphism. I'd stick to "substruct", or "nested struct".

Suggest to mention nested structs are unboxed, but explicit types are boxed.

Quoted 85 lines

Prefer the safer g_new0() while making the conversion.

---
 hmp.c            |  2 +-
 qapi/common.json | 26 +++++++++++++++++++-------
 qmp.c            |  9 +++++----
 3 files changed, 25 insertions(+), 12 deletions(-)
hmp.c +1 -1
index 40a90da..23fc3da 100644
@@ -55,7 +55,7 @@ void hmp_info_version(Monitor *mon, const QDict *qdict)
     info = qmp_query_version(NULL);
 
     monitor_printf(mon, "%" PRId64 ".%" PRId64 ".%" PRId64 "%s\n",
-                   info->qemu.major, info->qemu.minor, info->qemu.micro,
+                   info->qemu->major, info->qemu->minor, info->qemu->micro,
                    info->package);
 
     qapi_free_VersionInfo(info);
qapi/common.json +19 -7
index 4e9a21f..d007095 100644
@@ -29,15 +29,28 @@
             'DeviceNotActive', 'DeviceNotFound', 'KVMMissingCap' ] }
 
 ##
+# @VersionTriple
+#
+# A three-part version number.
+#
+# @qemu.major:  The major version number.
+#
+# @qemu.minor:  The minor version number.
+#
+# @qemu.micro:  The micro version number.
+#
+# Since: 2.2
+##
+{ 'type': 'VersionTriple',
+  'data': {'major': 'int', 'minor': 'int', 'micro': 'int'} }
+
+
+##
 # @VersionInfo:
 #
 # A description of QEMU's version.
 #
-# @qemu.major:  The major version of QEMU
-#
-# @qemu.minor:  The minor version of QEMU
-#
-# @qemu.micro:  The micro version of QEMU.  By current convention, a micro
+# @qemu:        The version of QEMU.  By current convention, a micro
 #               version of 50 signifies a development branch.  A micro version
 #               greater than or equal to 90 signifies a release candidate for
 #               the next minor version.  A micro version of less than 50
@@ -51,8 +64,7 @@
 # Since: 0.14.0
 ##
 { 'type': 'VersionInfo',
-  'data': {'qemu': {'major': 'int', 'minor': 'int', 'micro': 'int'},
-           'package': 'str'} }
+  'data': {'qemu': 'VersionTriple', 'package': 'str'} }
 
 ##
 # @query-version:
qmp.c +2 -2
index c6767c4..24b658a 100644
@@ -45,15 +45,16 @@ NameInfo *qmp_query_name(Error **errp)
 
 VersionInfo *qmp_query_version(Error **errp)
 {
-    VersionInfo *info = g_malloc0(sizeof(*info));
+    VersionInfo *info = g_new0(VersionInfo, 1);
     const char *version = QEMU_VERSION;
     char *tmp;
 
-    info->qemu.major = strtol(version, &tmp, 10);
+    info->qemu = g_new0(VersionTriple, 1);

qmp.c NameInfo *qmp_query_name(Error **errp) · line 60

Quoted 10 lines
qmp.c +3 -2
+    info->qemu->major = strtol(version, &tmp, 10);
     tmp++;
-    info->qemu.minor = strtol(tmp, &tmp, 10);
+    info->qemu->minor = strtol(tmp, &tmp, 10);
     tmp++;
-    info->qemu.micro = strtol(tmp, &tmp, 10);
+    info->qemu->micro = strtol(tmp, &tmp, 10);
     info->package = g_strdup(QEMU_PKGVERSION);
 
     return info;

Here you can see the boxing.

author
#58 lore raw

PATCH v4 18/19 qapi: Drop inline subtype in query-pci

In reply to Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument; but existing use of inline substructs conflicts with that goal. This patch fixes one of only two commands relying on nested subtypes, by breaking the nesting into an explicit type. The QMP wire format is unaffected by this change.

Prefer the safer g_new0() while making the conversion, and reduce some long lines.

---
 hmp.c            | 26 ++++++++--------
 hw/pci/pci.c     | 42 ++++++++++++++------------
 qapi-schema.json | 90 ++++++++++++++++++++++++++++++++++++++------------------
 3 files changed, 98 insertions(+), 60 deletions(-)
hmp.c +13 -13
index 23fc3da..3d0c23f 100644
@@ -553,14 +553,14 @@ static void hmp_info_pci_device(Monitor *mon, const PciDeviceInfo *dev)
                    dev->slot, dev->function);
     monitor_printf(mon, "    ");
 
-    if (dev->class_info.has_desc) {
-        monitor_printf(mon, "%s", dev->class_info.desc);
+    if (dev->class_info->has_desc) {
+        monitor_printf(mon, "%s", dev->class_info->desc);
     } else {
-        monitor_printf(mon, "Class %04" PRId64, dev->class_info.q_class);
+        monitor_printf(mon, "Class %04" PRId64, dev->class_info->q_class);
     }
 
     monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
-                   dev->id.vendor, dev->id.device);
+                   dev->id->vendor, dev->id->device);
 
     if (dev->has_irq) {
         monitor_printf(mon, "      IRQ %" PRId64 ".\n", dev->irq);
@@ -568,25 +568,25 @@ static void hmp_info_pci_device(Monitor *mon, const PciDeviceInfo *dev)
 
     if (dev->has_pci_bridge) {
         monitor_printf(mon, "      BUS %" PRId64 ".\n",
-                       dev->pci_bridge->bus.number);
+                       dev->pci_bridge->bus->number);
         monitor_printf(mon, "      secondary bus %" PRId64 ".\n",
-                       dev->pci_bridge->bus.secondary);
+                       dev->pci_bridge->bus->secondary);
         monitor_printf(mon, "      subordinate bus %" PRId64 ".\n",
-                       dev->pci_bridge->bus.subordinate);
+                       dev->pci_bridge->bus->subordinate);
 
         monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
-                       dev->pci_bridge->bus.io_range->base,
-                       dev->pci_bridge->bus.io_range->limit);
+                       dev->pci_bridge->bus->io_range->base,
+                       dev->pci_bridge->bus->io_range->limit);
 
         monitor_printf(mon,
                        "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
-                       dev->pci_bridge->bus.memory_range->base,
-                       dev->pci_bridge->bus.memory_range->limit);
+                       dev->pci_bridge->bus->memory_range->base,
+                       dev->pci_bridge->bus->memory_range->limit);
 
         monitor_printf(mon, "      prefetchable memory range "
                        "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
-                       dev->pci_bridge->bus.prefetchable_range->base,
-                       dev->pci_bridge->bus.prefetchable_range->limit);
+                       dev->pci_bridge->bus->prefetchable_range->base,
+                       dev->pci_bridge->bus->prefetchable_range->limit);
     }
 
     for (region = dev->regions; region; region = region->next) {
hw/pci/pci.c +23 -19

68 lines not on this page · raw message

qapi-schema.json +62 -28

119 lines not on this page · raw message

Signature · 1 line
1.9.3
author
#59 lore raw

PATCH v4 19/19 qapi: Drop support for inline subtypes

In reply to Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument; but existing use of inline substructs conflicts with that goal. Now that all commands have been fixed to avoid inline substructs, nuke support for them, and turn it into a hard error. Update the testsuite to reflect tighter parsing rules.

---
 scripts/qapi-commands.py                     |  8 +++---
 scripts/qapi-event.py                        |  4 +--
 scripts/qapi-types.py                        |  9 ++-----
 scripts/qapi-visit.py                        | 37 ++++------------------------
 scripts/qapi.py                              | 18 +++++---------
 tests/qapi-schema/event-nest-struct.err      |  2 +-
 tests/qapi-schema/nested-struct-data.err     |  1 +
 tests/qapi-schema/nested-struct-data.exit    |  2 +-
 tests/qapi-schema/nested-struct-data.json    |  2 +-
 tests/qapi-schema/nested-struct-data.out     |  3 ---
 tests/qapi-schema/nested-struct-returns.err  |  1 +
 tests/qapi-schema/nested-struct-returns.exit |  2 +-
 tests/qapi-schema/nested-struct-returns.json |  2 +-
 tests/qapi-schema/nested-struct-returns.out  |  3 ---
 14 files changed, 26 insertions(+), 68 deletions(-)
scripts/qapi-commands.py +4 -4
index 053ba85..db81044 100644
@@ -28,7 +28,7 @@ def type_visitor(name):
 
 def generate_command_decl(name, args, ret_type):
     arglist=""
-    for argname, argtype, optional, structured in parse_args(args):
+    for argname, argtype, optional in parse_args(args):
         argtype = c_type(argtype, is_param=True)
         if optional:
             arglist += "bool has_%s, " % c_var(argname)
@@ -53,7 +53,7 @@ def gen_sync_call(name, args, ret_type, indent=0):
     retval=""
     if ret_type:
         retval = "retval = "
-    for argname, argtype, optional, structured in parse_args(args):
+    for argname, argtype, optional in parse_args(args):
         if optional:
             arglist += "has_%s, " % c_var(argname)
         arglist += "%s, " % (c_var(argname))
@@ -96,7 +96,7 @@ Visitor *v;
 def gen_visitor_input_vars_decl(args):
     ret = ""
     push_indent()
-    for argname, argtype, optional, structured in parse_args(args):
+    for argname, argtype, optional in parse_args(args):
         if optional:
             ret += mcgen('''
 bool has_%(argname)s = false;
@@ -139,7 +139,7 @@ v = qapi_dealloc_get_visitor(md);
 v = qmp_input_get_visitor(mi);
 ''')
 
-    for argname, argtype, optional, structured in parse_args(args):
+    for argname, argtype, optional in parse_args(args):
         if optional:
             ret += mcgen('''
 visit_optional(v, &has_%(c_name)s, "%(name)s", %(errp)s);
scripts/qapi-event.py +2 -2
index 601e307..47dc041 100644
@@ -21,7 +21,7 @@ def _generate_event_api_name(event_name, params):
     l = len(api_name)
 
     if params:
-        for argname, argentry, optional, structured in parse_args(params):
+        for argname, argentry, optional in parse_args(params):
             if optional:
                 api_name += "bool has_%s,\n" % c_var(argname)
                 api_name += "".ljust(l)
@@ -93,7 +93,7 @@ def generate_event_implement(api_name, event_name, params):
 """,
                 event_name = event_name)
 
-        for argname, argentry, optional, structured in parse_args(params):
+        for argname, argentry, optional in parse_args(params):
             if optional:
                 ret += mcgen("""
     if (has_%(var)s) {
scripts/qapi-types.py +2 -7
index b463232..5d0e6e7 100644
@@ -63,18 +63,13 @@ typedef struct %(name)sList
 def generate_struct_fields(members):
     ret = ''
 
-    for argname, argentry, optional, structured in parse_args(members):
+    for argname, argentry, optional in parse_args(members):
         if optional:
             ret += mcgen('''
     bool has_%(c_name)s;
 ''',
                          c_name=c_var(argname))
-        if structured:
-            push_indent()
-            ret += generate_struct({ "field": argname, "data": argentry})
-            pop_indent()
-        else:
-            ret += mcgen('''
+        ret += mcgen('''
     %(c_type)s %(c_name)s;
 ''',
                      c_type=c_type(argentry), c_name=c_var(argname))
scripts/qapi-visit.py +5 -32
index c129697..7674dd5 100644
@@ -51,27 +51,6 @@ def generate_visit_struct_fields(name, field_prefix, fn_prefix, members, base =
     else:
         full_name = "%s_%s" % (name, fn_prefix)
 
-    for argname, argentry, optional, structured in parse_args(members):
-        if structured:
-            if not fn_prefix:
-                nested_fn_prefix = argname
-            else:
-                nested_fn_prefix = "%s_%s" % (fn_prefix, argname)
-
-            nested_field_prefix = "%s%s." % (field_prefix, argname)
-            ret += generate_visit_struct_fields(name, nested_field_prefix,
-                                                nested_fn_prefix, argentry)
-            ret += mcgen('''
-
-static void visit_type_%(full_name)s_field_%(c_name)s(Visitor *m, %(name)s **obj, Error **errp)
-{
-''',
-                         name=name, full_name=full_name, c_name=c_var(argname))
-            ret += generate_visit_struct_body(full_name, argname, argentry)
-            ret += mcgen('''
-}
-''')
-
     if base:
         ret += generate_visit_implicit_struct(base)
 
@@ -94,7 +73,7 @@ if (err) {
                      c_prefix=c_var(field_prefix),
                      type=type_name(base), c_name=c_var('base'))
 
-    for argname, argentry, optional, structured in parse_args(members):
+    for argname, argentry, optional in parse_args(members):
         if optional:
             ret += mcgen('''
 visit_optional(m, &(*obj)->%(c_prefix)shas_%(c_name)s, "%(name)s", &err);
@@ -104,18 +83,12 @@ if (!err && (*obj)->%(prefix)shas_%(c_name)s) {
                          c_name=c_var(argname), name=argname)
             push_indent()
 
-        if structured:
-            ret += mcgen('''
-visit_type_%(full_name)s_field_%(c_name)s(m, obj, &err);
-''',
-                         full_name=full_name, c_name=c_var(argname))
-        else:
-            ret += mcgen('''
+        ret += mcgen('''
 visit_type_%(type)s(m, &(*obj)->%(c_prefix)s%(c_name)s, "%(name)s", &err);
 ''',
-                         c_prefix=c_var(field_prefix), prefix=field_prefix,
-                         type=type_name(argentry), c_name=c_var(argname),
-                         name=argname)
+                     c_prefix=c_var(field_prefix), prefix=field_prefix,
+                     type=type_name(argentry), c_name=c_var(argname),
+                     name=argname)
 
         if optional:
             pop_indent()
scripts/qapi.py +6 -12
index 15972c6..17fca28 100644
@@ -300,10 +300,12 @@ def check_type(expr_info, source, data, allow_array = False,
         raise QAPIExprError(expr_info,
                             "%s should be a type name" % source)
     for (key, value) in data.items():
+        # Todo: allow dictionaries to represent default values of
+        # an optional argument.
         check_type(expr_info, "member '%s' of %s" % (key, source), value,
                    allow_array=True,
                    allowed_names=['built-in', 'union', 'struct', 'enum'],
-                   allow_dict=True, allow_star=allow_star)
+                   allow_dict=False, allow_star=allow_star)
 
 def check_command(expr, expr_info):
     global commands
@@ -335,13 +337,6 @@ def check_event(expr, expr_info):
     events.append(name)
     check_type(expr_info, "'data' for event '%s'" % name,
                expr.get('data'), allowed_names=['union', 'struct'])
-    if params:
-        for argname, argentry, optional, structured in parse_args(params):
-            if structured:
-                raise QAPIExprError(expr_info,
-                                    "Nested structure define in event is not "
-                                    "supported, event '%s', argname '%s'"
-                                    % (expr['event'], argname))
 
 def check_union(expr, expr_info):
     name = expr['union']
@@ -537,13 +532,12 @@ def parse_args(typeinfo):
         argname = member
         argentry = typeinfo[member]
         optional = False
-        structured = False
         if member.startswith('*'):
             argname = member[1:]
             optional = True
-        if isinstance(argentry, OrderedDict):
-            structured = True
-        yield (argname, argentry, optional, structured)
+        # Todo: allow argentry to be OrderedDict, for providing the
+        # value of an optional argument.
+        yield (argname, argentry, optional)
 
 def de_camel_case(name):
     new_name = ''
tests/qapi-schema/event-nest-struct.err +1 -1
index 91bde1c..f17fbb7 100644
@@ -1 +1 @@
-tests/qapi-schema/event-nest-struct.json:1: Nested structure define in event is not supported, event 'EVENT_A', argname 'a'
+tests/qapi-schema/event-nest-struct.json:1: member 'a' of 'data' for event 'EVENT_A' should be a type name
tests/qapi-schema/nested-struct-data.err +1 -0
index e69de29..1fc6687 100644
@@ -0,0 +1 @@
+tests/qapi-schema/nested-struct-data.json:2: member 'a' of 'data' for command 'foo' should be a type name
tests/qapi-schema/nested-struct-data.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/nested-struct-data.json +1 -1
index 0247c8c..3d52d2b 100644
@@ -1,4 +1,4 @@
-# FIXME: inline subtypes collide with our desired future use of defaults
+# inline subtypes collide with our desired future use of defaults
 { 'command': 'foo',
   'data': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' },
   'returns': {} }
tests/qapi-schema/nested-struct-data.out +0 -3
index 999cbb8..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'foo'), ('data', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')])), ('returns', OrderedDict())])]
-[]
-[]
tests/qapi-schema/nested-struct-returns.err +1 -0
index e69de29..f34bd92 100644
@@ -0,0 +1 @@
+tests/qapi-schema/nested-struct-returns.json:2: member 'a' of 'returns' for command 'foo' should be a type name
tests/qapi-schema/nested-struct-returns.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/nested-struct-returns.json +1 -1
index 5a46840..d2cd047 100644
@@ -1,3 +1,3 @@
-# FIXME: inline subtypes collide with our desired future use of defaults
+# inline subtypes collide with our desired future use of defaults
 { 'command': 'foo',
   'returns': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' } }
tests/qapi-schema/nested-struct-returns.out +0 -3
index c53d23b..e69de29 100644
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'foo'), ('returns', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')]))])]
-[]
-[]
Signature · 1 line
1.9.3
#60 lore raw

Re: [Qemu-devel] [PATCH v4 19/19] qapi: Drop support for inline subtypes

Quoted 4 lines · Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument; but existing use of inline substructs conflicts with that goal. Now that all commands have been fixed to avoid inline substructs,

Suggest s/fixed/changed/

Quoted 4 lines

nuke support for them, and turn it into a hard error. Update the testsuite to reflect tighter parsing rules.

Patch looks good.

author
#61 lore raw
In reply to Eric Blake
Quoted 19 lines · Eric Blake

After dragging my feet due to some libvirt work, I've finally revived this patch series as promised.

v3 was here:
https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg00725.html

v4:
update commit message style [Markus]
add docs (patches 3-4 are new) [Markus]
lots of new tests (spread among 5, 7, 9, 11, 12)
add comments to all new tests [Markus]
rework check for valid expressions (patches 8, 10 are pretty much
new, later patches rebased and simplified as a result)
rebase to master
fix tests to match file name (broken test in v3 patch 7 now fixed
in patch 12)
drop expr_name (v3 patch 8); series now validates expressions
earlier (patch 8)
consolidate '**' magic, and reject 'gen':'yes' in commands (patch

Quoted 3 lines
    14 is new)

probably other stuff - it's been more than a month, so reviewers
will probably want to start from scratch anyways :)

I'll be posting a v5 to address Markus' useful feedback, but as that may take me a while to get to, I've spun off patches 1-3 into their own trivial series:
https://lists.gnu.org/archive/html/qemu-devel/2014-09/msg05357.html

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