drop qapi nested structs
Re: [Qemu-devel] [PATCH v5 17/28] qapi: Allow true, false and null in schema json
In reply to Kevin WolfQuoted 61 lines · Kevin Wolf
Am 01.04.2015 um 11:33 hat Markus Armbruster geschrieben:
Quoted 60 lines
Quoted 38 lines · Kevin Wolf
Am 31.03.2015 um 22:09 hat Markus Armbruster geschrieben:
Quoted 30 lines
Quoted 14 lines · Kevin Wolf
Am 24.03.2015 um 21:03 hat Eric Blake geschrieben:
Quoted 6 lines
From: Fam Zheng <[email protected]>
In the near term, we will use it for a sensible-looking 'gen':false inside command declarations, instead of the current ugly 'gen':'no'.
Quoted 6 lines
In the long term, it will allow conversion from shorthand with defaults mentioned only in side-band documentation:
'data':{'*flag':'bool', '*string':'str'}
into an explicit default value documentation, as in:
'data':{'flag':{'type':'bool', 'optional':true, 'default':true},'string':{'type':'str', 'optional':true, 'default':null}}Quoted 2 lines
FWIW, I don't think that's a very friendly syntax for humans, it's a bit verbose. But that's no reason not to allow true/false/null, of course.
Here's my current thinking.
Longhand:
# mandatory 'name': { 'type': 'str' } # optional, with a default 'flag': { 'type': 'bool', 'default': true } # optional, no default 'string': { 'type': 'str', 'default': null }Quoted 6 lines
Presence of 'default' implies optional.
Equivalent shorthand, if any:
'name': 'str' '*string': 'str'Quoted 7 lines
A nice shorthand for defaults would be:
'*name': 'str' = 'default'Though that would be neither valid JSON nor Python any more. Do we actually rely on this property anywhere or is it only parsed by the QAPI generator anyway and we can extend the language in such ways?
I guess JSON / Python was chosen as QAPI schema language to save us the bother of defining a syntax and building the tools to work with it, like an Emacs mode. JSON's not exactly my favourite choice, but at least it's not XML.
What we have now isn't JSON, but it's still a subset of Python, and the Python tools work. If we go beyond Python, they'll break.
If we decide to sacrifice these tools for readability, then we can just as well replace the syntax entirely. Preferably by something where I don't have to put every identifier in quotes.
Quoted 5 lines
Quoted 3 lines
In short, you're welcome to hack up
qapi.pysome more for schema readability, but either keep Emacs Python mode working, or provide a replacement :)What features does this Python mode provide that you use?
Syntax highlighting, automatic indentation, possibly more I rely on without noticing. My fingers know, but they don't talk.
Quoted 10 lines
For the JSON schema, the only thing I really use from the editor is syntax highlighting, and that shouldn't be bothered by an addition like this (in vim it doesn't hurt anyway). I also don't use any other Python tools, though I'm not sure that none exist that would make sense with the schema.
So if there are practically relevant advantages in being real Python code, then we need to consider that, of course. That's why I was asking. But if there aren't, it's just an arbitrary restriction that could be removed.
If we decide to revise the decision to borrow existing syntax and roll our own instead, let's 'make' 'our' 'own' 'syntax' 'not' 'suck'.
Anyway, we got bigger fish to fry right now.
Re: [Qemu-devel] [PATCH v5 17/28] qapi: Allow true, false and null in schema json
Am 01.04.2015 um 13:03 hat Markus Armbruster geschrieben:
Quoted 83 lines
Quoted 61 lines · Kevin Wolf
Am 01.04.2015 um 11:33 hat Markus Armbruster geschrieben:
Quoted 60 lines
Quoted 38 lines · Kevin Wolf
Am 31.03.2015 um 22:09 hat Markus Armbruster geschrieben:
Quoted 30 lines
Quoted 14 lines · Kevin Wolf
Am 24.03.2015 um 21:03 hat Eric Blake geschrieben:
Quoted 6 lines
From: Fam Zheng <[email protected]>
In the near term, we will use it for a sensible-looking 'gen':false inside command declarations, instead of the current ugly 'gen':'no'.
Quoted 6 lines
In the long term, it will allow conversion from shorthand with defaults mentioned only in side-band documentation:
'data':{'*flag':'bool', '*string':'str'}
into an explicit default value documentation, as in:
'data':{'flag':{'type':'bool', 'optional':true, 'default':true},'string':{'type':'str', 'optional':true, 'default':null}}Quoted 2 lines
FWIW, I don't think that's a very friendly syntax for humans, it's a bit verbose. But that's no reason not to allow true/false/null, of course.
Here's my current thinking.
Longhand:
# mandatory 'name': { 'type': 'str' } # optional, with a default 'flag': { 'type': 'bool', 'default': true } # optional, no default 'string': { 'type': 'str', 'default': null }Quoted 6 lines
Presence of 'default' implies optional.
Equivalent shorthand, if any:
'name': 'str' '*string': 'str'Quoted 7 lines
A nice shorthand for defaults would be:
'*name': 'str' = 'default'Though that would be neither valid JSON nor Python any more. Do we actually rely on this property anywhere or is it only parsed by the QAPI generator anyway and we can extend the language in such ways?
I guess JSON / Python was chosen as QAPI schema language to save us the bother of defining a syntax and building the tools to work with it, like an Emacs mode. JSON's not exactly my favourite choice, but at least it's not XML.
What we have now isn't JSON, but it's still a subset of Python, and the Python tools work. If we go beyond Python, they'll break.
If we decide to sacrifice these tools for readability, then we can just as well replace the syntax entirely. Preferably by something where I don't have to put every identifier in quotes.
Quoted 5 lines
Quoted 3 lines
In short, you're welcome to hack up
qapi.pysome more for schema readability, but either keep Emacs Python mode working, or provide a replacement :)What features does this Python mode provide that you use?
Syntax highlighting, automatic indentation, possibly more I rely on without noticing. My fingers know, but they don't talk.
Quoted 10 lines
For the JSON schema, the only thing I really use from the editor is syntax highlighting, and that shouldn't be bothered by an addition like this (in vim it doesn't hurt anyway). I also don't use any other Python tools, though I'm not sure that none exist that would make sense with the schema.
So if there are practically relevant advantages in being real Python code, then we need to consider that, of course. That's why I was asking. But if there aren't, it's just an arbitrary restriction that could be removed.
Quoted 4 lines
If we decide to revise the decision to borrow existing syntax and roll our own instead, let's 'make' 'our' 'own' 'syntax' 'not' 'suck'.
Anyway, we got bigger fish to fry right now.
Okay, I got it. Asking me to create a completely new syntax and the generator for it is the longhand version for "no".
Kevin
Re: [Qemu-devel] [PATCH v5 17/28] qapi: Allow true, false and null in schema json
Quoted 85 lines · Kevin Wolf
Am 01.04.2015 um 13:03 hat Markus Armbruster geschrieben:
Quoted 84 lines
Quoted 62 lines · Kevin Wolf
Am 01.04.2015 um 11:33 hat Markus Armbruster geschrieben:
Quoted 61 lines
Quoted 39 lines · Kevin Wolf
Am 31.03.2015 um 22:09 hat Markus Armbruster geschrieben:
Quoted 31 lines
Quoted 14 lines · Kevin Wolf
Am 24.03.2015 um 21:03 hat Eric Blake geschrieben:
Quoted 6 lines
From: Fam Zheng <[email protected]>
In the near term, we will use it for a sensible-looking 'gen':false inside command declarations, instead of the current ugly 'gen':'no'.
Quoted 6 lines
In the long term, it will allow conversion from shorthand with defaults mentioned only in side-band documentation:
'data':{'*flag':'bool', '*string':'str'}
into an explicit default value documentation, as in:
'data':{'flag':{'type':'bool', 'optional':true, 'default':true},'string':{'type':'str', 'optional':true, 'default':null}}Quoted 3 lines
FWIW, I don't think that's a very friendly syntax for humans, it's a bit
verbose. But that's no reason not to allow true/false/null, of course.Here's my current thinking.
Longhand:
# mandatory 'name': { 'type': 'str' } # optional, with a default 'flag': { 'type': 'bool', 'default': true } # optional, no default 'string': { 'type': 'str', 'default': null }Quoted 6 lines
Presence of 'default' implies optional.
Equivalent shorthand, if any:
'name': 'str' '*string': 'str'Quoted 7 lines
A nice shorthand for defaults would be:
'*name': 'str' = 'default'Though that would be neither valid JSON nor Python any more. Do we actually rely on this property anywhere or is it only parsed by the QAPI generator anyway and we can extend the language in such ways?
I guess JSON / Python was chosen as QAPI schema language to save us the bother of defining a syntax and building the tools to work with it, like an Emacs mode. JSON's not exactly my favourite choice, but at least it's not XML.
What we have now isn't JSON, but it's still a subset of Python, and the Python tools work. If we go beyond Python, they'll break.
If we decide to sacrifice these tools for readability, then we can just as well replace the syntax entirely. Preferably by something where I don't have to put every identifier in quotes.
Quoted 5 lines
Quoted 3 lines
In short, you're welcome to hack up
qapi.pysome more for schema readability, but either keep Emacs Python mode working, or provide a replacement :)What features does this Python mode provide that you use?
Syntax highlighting, automatic indentation, possibly more I rely on without noticing. My fingers know, but they don't talk.
Quoted 10 lines
For the JSON schema, the only thing I really use from the editor is syntax highlighting, and that shouldn't be bothered by an addition like this (in vim it doesn't hurt anyway). I also don't use any other Python tools, though I'm not sure that none exist that would make sense with the schema.
So if there are practically relevant advantages in being real Python code, then we need to consider that, of course. That's why I was asking. But if there aren't, it's just an arbitrary restriction that could be removed.
Quoted 7 lines
Quoted 4 lines
If we decide to revise the decision to borrow existing syntax and roll our own instead, let's 'make' 'our' 'own' 'syntax' 'not' 'suck'.
Anyway, we got bigger fish to fry right now.
Okay, I got it. Asking me to create a completely new syntax and the generator for it is the longhand version for "no".
It's advice, not a proactive NAK.
Anyway, let's get Eric's series in, and crack the introspection problem before we start even more QAPI generator projects.
Re: [Qemu-devel] [PATCH v5 17/28] qapi: Allow true, false and null in schema json
In reply to Markus ArmbrusterQuoted 24 lines · Markus Armbruster
Quoted 16 lines
Quoted 9 lines
Longhand:
# mandatory 'name': { 'type': 'str' } # optional, with a default 'flag': { 'type': 'bool', 'default': true } # optional, no default 'string': { 'type': 'str', 'default': null }Quoted 6 lines
Presence of 'default' implies optional.
Equivalent shorthand, if any:
'name': 'str' '*string': 'str'Quoted 7 lines
A nice shorthand for defaults would be:
'*name': 'str' = 'default'Though that would be neither valid JSON nor Python any more. Do we actually rely on this property anywhere or is it only parsed by the QAPI generator anyway and we can extend the language in such ways?
Quoted 7 lines
I guess JSON / Python was chosen as QAPI schema language to save us the bother of defining a syntax and building the tools to work with it, like an Emacs mode. JSON's not exactly my favourite choice, but at least it's not XML.
What we have now isn't JSON, but it's still a subset of Python, and the Python tools work. If we go beyond Python, they'll break.
Well, we were a subset of Python, until this patch added true, false, and null (the Python way would have been True, False, and None). We are also similar to JSON5, http://json5.org/
Among other things, JSON5 allows trailing commas, allows unquoted keys in a dictionary, allows single-quoted strings, and allows C-style comments.
Quoted 8 lines
If we decide to sacrifice these tools for readability, then we can just as well replace the syntax entirely. Preferably by something where I don't have to put every identifier in quotes.
In short, you're welcome to hack up
qapi.pysome more for schema readability, but either keep Emacs Python mode working, or provide a replacement :)
Since we're not quite python or JSON, we've already rolled our own parser; so rewriting QAPI to use a syntax of our own choosing is not that much of a leap. But not for this series.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v5 17/28] qapi: Allow true, false and null in schema json
Quoted 34 lines · Eric Blake
Quoted 24 lines · Markus Armbruster
Quoted 16 lines
Quoted 9 lines
Longhand:
# mandatory 'name': { 'type': 'str' } # optional, with a default 'flag': { 'type': 'bool', 'default': true } # optional, no default 'string': { 'type': 'str', 'default': null }Quoted 6 lines
Presence of 'default' implies optional.
Equivalent shorthand, if any:
'name': 'str' '*string': 'str'Quoted 7 lines
A nice shorthand for defaults would be:
'*name': 'str' = 'default'Though that would be neither valid JSON nor Python any more. Do we actually rely on this property anywhere or is it only parsed by the QAPI generator anyway and we can extend the language in such ways?
Quoted 7 lines
I guess JSON / Python was chosen as QAPI schema language to save us the bother of defining a syntax and building the tools to work with it, like an Emacs mode. JSON's not exactly my favourite choice, but at least it's not XML.
What we have now isn't JSON, but it's still a subset of Python, and the Python tools work. If we go beyond Python, they'll break.
Quoted 6 lines
Well, we were a subset of Python, until this patch added true, false, and null (the Python way would have been True, False, and None). We are also similar to JSON5, http://json5.org/
Among other things, JSON5 allows trailing commas, allows unquoted keys in a dictionary, allows single-quoted strings, and allows C-style comments.
I'm open to consider adopting it once the dust settles.
Quoted 11 lines
Quoted 7 lines
If we decide to sacrifice these tools for readability, then we can just as well replace the syntax entirely. Preferably by something where I don't have to put every identifier in quotes.
In short, you're welcome to hack up
qapi.pysome more for schema readability, but either keep Emacs Python mode working, or provide a replacement :)Since we're not quite python or JSON, we've already rolled our own parser; so rewriting QAPI to use a syntax of our own choosing is not that much of a leap.
Point taken.
Quoted 1 line
But not for this series.
Certainly.
Re: [Qemu-devel] [PATCH v5 17/28] qapi: Allow true, false and null in schema json
In reply to Eric BlakeQuoted 8 lines · Eric Blake
Quoted 7 lines
I guess JSON / Python was chosen as QAPI schema language to save us the bother of defining a syntax and building the tools to work with it, like an Emacs mode. JSON's not exactly my favourite choice, but at least it's not XML.
What we have now isn't JSON, but it's still a subset of Python, and the Python tools work. If we go beyond Python, they'll break.
Quoted 6 lines
Well, we were a subset of Python, until this patch added true, false, and null (the Python way would have been True, False, and None). We are also similar to JSON5, http://json5.org/
Among other things, JSON5 allows trailing commas, allows unquoted keys in a dictionary, allows single-quoted strings, and allows C-style comments.
Another thing I just noticed: JSON allows '\u0061' as a synonym for the one-byte string 'a', but our parser does not (instead, our parser treats it like the five bytes 'u0061'). I guess we haven't noticed, since qapi has never needed non-ascii names...
Quoted 3 lines
Since we're not quite python or JSON, we've already rolled our own parser; so rewriting QAPI to use a syntax of our own choosing is not that much of a leap. But not for this series.
So of course this still holds, and I won't stall my v6 posting because of it.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH v5 18/28 qapi: Unify type bypass and add tests
In reply to Eric BlakeFor 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 '**'.
Meanwhile, for both 'gen' and 'success-response' keys, we have been ignoring the value, although the schema consistently used "'no'". But now that we can support a literal "false" in the schema, we might as well use that rather than ignoring the value or special-casing a random string.
There is no difference to the generated code. As these features were previously undocumented before this series, add some tests and documentation on what we'd like to guarantee, although it will take later patches to clean up test results and actually enforce the use of a bool parameter.
--- qapi-schema.json | 14 +++++++------- qga/qapi-schema.json | 8 ++++---- 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 +++ 15 files changed, 30 insertions(+), 11 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 +7 -7
@@ -1561,8 +1561,8 @@ ## { 'command': 'qom-get', 'data': { 'path': 'str', 'property': 'str' }, - 'returns': 'visitor', - 'gen': 'no' } + 'returns': '**', + 'gen': false } ## # @qom-set:
@@ -1579,8 +1579,8 @@ # Since: 1.2 ## { 'command': 'qom-set', - 'data': { 'path': 'str', 'property': 'str', 'value': 'visitor' }, - 'gen': 'no' } + 'data': { 'path': 'str', 'property': 'str', 'value': '**' }, + 'gen': false } ## # @set_password:
@@ -1943,7 +1943,7 @@ ## { 'command': 'netdev_add', 'data': {'type': 'str', 'id': 'str', '*props': '**'}, - 'gen': 'no' } + 'gen': false } ## # @netdev_del:
@@ -1976,8 +1976,8 @@ # Since: 2.0 ## { 'command': 'object-add', - 'data': {'qom-type': 'str', 'id': 'str', '*props': 'dict'}, - 'gen': 'no' } + 'data': {'qom-type': 'str', 'id': 'str', '*props': '**'}, + 'gen': false } ## # @object-del:
qga/qapi-schema.json +4 -4
@@ -195,7 +195,7 @@ # Since: 0.15.0 ## { 'command': 'guest-shutdown', 'data': { '*mode': 'str' }, - 'success-response': 'no' } + 'success-response': false } ## # @guest-file-open:
@@ -470,7 +470,7 @@ # # Since: 1.1 ## -{ 'command': 'guest-suspend-disk', 'success-response': 'no' } +{ 'command': 'guest-suspend-disk', 'success-response': false } ## # @guest-suspend-ram
@@ -502,7 +502,7 @@ # # Since: 1.1 ## -{ 'command': 'guest-suspend-ram', 'success-response': 'no' } +{ 'command': 'guest-suspend-ram', 'success-response': false } ## # @guest-suspend-hybrid
@@ -529,7 +529,7 @@ # # Since: 1.1 ## -{ 'command': 'guest-suspend-hybrid', 'success-response': 'no' } +{ 'command': 'guest-suspend-hybrid', 'success-response': false } ## # @GuestIpAddressType:
tests/Makefile +1 -0
@@ -215,6 +215,7 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \ bad-type-dict.json double-data.json unknown-expr-key.json \ redefined-type.json redefined-command.json redefined-builtin.json \ redefined-event.json command-int.json event-max.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
tests/qapi-schema/type-bypass-bad-gen.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/type-bypass-bad-gen.json new file +2 -0
@@ -0,0 +1,2 @@ +# FIXME: 'gen' should only appear with value false +{ 'command': 'foo', 'gen': 'whatever' }
tests/qapi-schema/type-bypass-bad-gen.out new file +3 -0
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'foo'), ('gen', 'whatever')])] +[] +[]
tests/qapi-schema/type-bypass-no-gen.err new file +0 -0
tests/qapi-schema/type-bypass-no-gen.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/type-bypass-no-gen.json new file +2 -0
@@ -0,0 +1,2 @@ +# FIXME: type bypass should only work with 'gen':false +{ 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**' }
tests/qapi-schema/type-bypass-no-gen.out new file +3 -0
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**')])] +[] +[]
tests/qapi-schema/type-bypass.err new file +0 -0
tests/qapi-schema/type-bypass.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/type-bypass.json new file +2 -0
@@ -0,0 +1,2 @@ +# Use of 'gen':false allows bypassing type system +{ 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**', 'gen': false }
tests/qapi-schema/type-bypass.out new file +3 -0
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**'), ('gen', False)])] +[] +[]
Signature · 1 line
2.1.0
Re: [Qemu-devel] [PATCH v5 18/28] qapi: Unify type bypass and add tests
Quoted 11 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 '**'.
Meanwhile, for both 'gen' and 'success-response' keys, we have been ignoring the value, although the schema consistently used "'no'". But now that we can support a literal "false" in the schema, we might as well use that rather than ignoring the value or special-casing a random string.
Quoted 5 lines
There is no difference to the generated code. As these features were previously undocumented before this series, add some tests and documentation on what we'd like to guarantee, although it will take later patches to clean up test results and actually enforce the use of a bool parameter.
You don't actually add documentation in this patch.
Aside: 'gen': false is required when '**' is used anywhere in the command. If it was permitted only then, it would be redundant. I think we happily accept 'gen': false without '**' so far, although we don't use it. That's okay.
Quoted 1 line
Signed-off-by Eric Blake <[email protected]>
Re: [Qemu-devel] [PATCH v5 18/28] qapi: Unify type bypass and add tests
Quoted 13 lines · Markus Armbruster
Quoted 11 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 '**'.
Meanwhile, for both 'gen' and 'success-response' keys, we have been ignoring the value, although the schema consistently used "'no'". But now that we can support a literal "false" in the schema, we might as well use that rather than ignoring the value or special-casing a random string.
Quoted 7 lines
Quoted 5 lines
There is no difference to the generated code. As these features were previously undocumented before this series, add some tests and documentation on what we'd like to guarantee, although it will take later patches to clean up test results and actually enforce the use of a bool parameter.
You don't actually add documentation in this patch.
Hmm, more evidence that I waffled about per-commit doc fixes, vs. lumping it all in patch 1, and I obviously failed to scrub the commit messages after changing my mind.
Quoted 5 lines
Aside: 'gen': false is required when '**' is used anywhere in the command. If it was permitted only then, it would be redundant. I think we happily accept 'gen': false without '**' so far, although we don't use it. That's okay.
Also, even though the code accepts 'gen':false, it rejects 'gen':true ('gen' is only a one-way switch away from the default). Also something I didn't think worth worrying about.
Quoted 6 lines
Quoted 2 lines
Signed-off-by Eric Blake <[email protected]>Reviewed-by Markus Armbruster <[email protected]>
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v5 18/28] qapi: Unify type bypass and add tests
Quoted 20 lines · Eric Blake
Quoted 19 lines · Markus Armbruster
Quoted 16 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 '**'.
Meanwhile, for both 'gen' and 'success-response' keys, we have been ignoring the value, although the schema consistently used "'no'". But now that we can support a literal "false" in the schema, we might as well use that rather than ignoring the value or special-casing a random string.
There is no difference to the generated code. As these features were previously undocumented before this series, add some tests and documentation on what we'd like to guarantee, although it will take later patches to clean up test results and actually enforce the use of a bool parameter.
Quoted 5 lines
Quoted 1 line
You don't actually add documentation in this patch.
Hmm, more evidence that I waffled about per-commit doc fixes, vs. lumping it all in patch 1, and I obviously failed to scrub the commit messages after changing my mind.
Fortunately, commit messages don't need testing, so this is easy enough to fix in a respin :)
Quoted 8 lines
Quoted 4 lines
Aside: 'gen': false is required when '**' is used anywhere in the command. If it was permitted only then, it would be redundant. I think we happily accept 'gen': false without '**' so far, although we don't use it. That's okay.
Also, even though the code accepts 'gen':false, it rejects 'gen':true ('gen' is only a one-way switch away from the default). Also something I didn't think worth worrying about.
Agree.
Quoted 5 lines
Quoted 5 lines
Quoted 1 line
Signed-off-by Eric Blake <[email protected]>Reviewed-by Markus Armbruster <[email protected]>
PATCH v5 19/28 qapi: Add some type check tests
In reply to Eric BlakeDemonstrate 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-alternate.err | 0 tests/qapi-schema/returns-alternate.exit | 1 + tests/qapi-schema/returns-alternate.json | 3 +++ tests/qapi-schema/returns-alternate.out | 4 ++++ 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 +++ tests/qapi-schema/returns-whitelist.err | 0 tests/qapi-schema/returns-whitelist.exit | 1 + tests/qapi-schema/returns-whitelist.json | 11 +++++++++++ tests/qapi-schema/returns-whitelist.out | 7 +++++++ 57 files changed, 112 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-alternate.err create mode 100644 tests/qapi-schema/returns-alternate.exit create mode 100644 tests/qapi-schema/returns-alternate.json create mode 100644 tests/qapi-schema/returns-alternate.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/returns-whitelist.err create mode 100644 tests/qapi-schema/returns-whitelist.exit create mode 100644 tests/qapi-schema/returns-whitelist.json create mode 100644 tests/qapi-schema/returns-whitelist.out
tests/Makefile +6 -2
@@ -216,8 +216,12 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \ redefined-type.json redefined-command.json redefined-builtin.json \ redefined-event.json command-int.json event-max.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 returns-alternate.json returns-whitelist.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
tests/qapi-schema/data-array-empty.exit new file +1 -0
@@ -0,0 +1 @@ +0
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': { 'empty': [ ] } }
tests/qapi-schema/data-array-empty.out new file +3 -0
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('data', OrderedDict([('empty', [])]))])] +[] +[]
tests/qapi-schema/data-array-unknown.err new file +0 -0
tests/qapi-schema/data-array-unknown.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/data-array-unknown.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': { 'array': [ 'NoSuchType' ] } }
tests/qapi-schema/data-array-unknown.out new file +3 -0
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('data', OrderedDict([('array', ['NoSuchType'])]))])] +[] +[]
tests/qapi-schema/data-int.err new file +0 -0
tests/qapi-schema/data-int.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/data-int.json new file +2 -0
@@ -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
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('data', 'int')])] +[] +[]
tests/qapi-schema/data-member-array-bad.err new file +0 -0
tests/qapi-schema/data-member-array-bad.exit new file +1 -0
@@ -0,0 +1 @@ +0
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' } ] } }
tests/qapi-schema/data-member-array-bad.out new file +3 -0
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', [OrderedDict([('nested', 'str')])])]))])] +[] +[]
tests/qapi-schema/data-member-array.err new file +0 -0
tests/qapi-schema/data-member-array.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/data-member-array.json new file +4 -0
@@ -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
@@ -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
tests/qapi-schema/data-member-unknown.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/data-member-unknown.json new file +2 -0
@@ -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
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', 'NoSuchType')]))])] +[] +[]
tests/qapi-schema/data-unknown.err new file +0 -0
tests/qapi-schema/data-unknown.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/data-unknown.json new file +2 -0
@@ -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
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('data', 'NoSuchType')])] +[] +[]
tests/qapi-schema/nested-struct-data.err new file +0 -0
tests/qapi-schema/nested-struct-data.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/nested-struct-data.json new file +4 -0
@@ -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
@@ -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
tests/qapi-schema/nested-struct-returns.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/nested-struct-returns.json new file +3 -0
@@ -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
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'foo'), ('returns', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')]))])] +[] +[]
tests/qapi-schema/returns-alternate.err new file +0 -0
tests/qapi-schema/returns-alternate.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/returns-alternate.json new file +3 -0
@@ -0,0 +1,3 @@ +# FIXME: we should reject returns if it is an alternate type +{ 'alternate': 'Alt', 'data': { 'a': 'int', 'b': 'str' } } +{ 'command': 'oops', 'returns': 'Alt' }
tests/qapi-schema/returns-alternate.out new file +4 -0
@@ -0,0 +1,4 @@ +[OrderedDict([('alternate', 'Alt'), ('data', OrderedDict([('a', 'int'), ('b', 'str')]))]), + OrderedDict([('command', 'oops'), ('returns', 'Alt')])] +[{'enum_name': 'AltKind', 'enum_values': None}] +[]
tests/qapi-schema/returns-array-bad.err new file +0 -0
tests/qapi-schema/returns-array-bad.exit new file +1 -0
@@ -0,0 +1 @@ +0
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' ] }
tests/qapi-schema/returns-array-bad.out new file +3 -0
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('returns', ['str', 'str'])])] +[] +[]
tests/qapi-schema/returns-int.err new file +0 -0
tests/qapi-schema/returns-int.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/returns-int.json new file +2 -0
@@ -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
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'okay'), ('returns', 'int')])] +[] +[]
tests/qapi-schema/returns-unknown.err new file +0 -0
tests/qapi-schema/returns-unknown.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/returns-unknown.json new file +2 -0
@@ -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
@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('returns', 'NoSuchType')])] +[] +[]
tests/qapi-schema/returns-whitelist.err new file +0 -0
tests/qapi-schema/returns-whitelist.exit new file +1 -0
@@ -0,0 +1 @@ +0
tests/qapi-schema/returns-whitelist.json new file +11 -0
@@ -0,0 +1,11 @@ +# FIXME: we should enforce that 'returns' be a dict or array of dict unless whitelisted +{ 'command': 'human-monitor-command', + 'data': {'command-line': 'str', '*cpu-index': 'int'}, + 'returns': 'str' } +{ 'enum': 'TpmModel', 'data': [ 'tpm-tis' ] } +{ 'command': 'query-tpm-models', 'returns': ['TpmModel'] } +{ 'command': 'guest-get-time', + 'returns': 'int' } + +{ 'command': 'no-way-this-will-get-whitelisted', + 'returns': [ 'int' ] }
tests/qapi-schema/returns-whitelist.out new file +7 -0
@@ -0,0 +1,7 @@ +[OrderedDict([('command', 'human-monitor-command'), ('data', OrderedDict([('command-line', 'str'), ('*cpu-index', 'int')])), ('returns', 'str')]), + OrderedDict([('enum', 'TpmModel'), ('data', ['tpm-tis'])]), + OrderedDict([('command', 'query-tpm-models'), ('returns', ['TpmModel'])]), + OrderedDict([('command', 'guest-get-time'), ('returns', 'int')]), + OrderedDict([('command', 'no-way-this-will-get-whitelisted'), ('returns', ['int'])])] +[{'enum_name': 'TpmModel', 'enum_values': ['tpm-tis']}] +[]
Signature · 1 line
2.1.0
Re: [Qemu-devel] [PATCH v5 19/28] qapi: Add some type check tests
Quoted 6 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.
Signed-off-by Eric Blake <[email protected]>---
[...]
Quoted 16 lines
tests/qapi-schema/data-array-empty.err new file +0
-0tests/qapi-schema/data-array-empty.exit new file +1
-0@@ -0,0 +1 @@ +0tests/qapi-schema/data-array-empty.json new file +0
-0
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': { 'empty': [ ] } }
v4 tested
{ 'command': 'oops', 'data': [ ] }Is that still covered somewhere else?
Quoted 9 lines
tests/qapi-schema/data-array-empty.out new file +3
-0@@ -0,0 +1,3 @@ +[OrderedDict([('command', 'oops'), ('data', OrderedDict([('empty', [])]))])] +[] +[]
[...]
Quoted 17 lines
tests/qapi-schema/returns-whitelist.err new file +0
-0tests/qapi-schema/returns-whitelist.exit new file +1
-0@@ -0,0 +1 @@ +0tests/qapi-schema/returns-whitelist.json new file +1
-0@@ -0,0 +1,11 @@ +# FIXME: we should enforce that 'returns' be a dict or array of dict unless whitelisted
tests/qapi-schema/returns-whitelist.json line 11
Quoted 10 lines
tests/qapi-schema/returns-whitelist.json new file +10
-0+{ 'command': 'human-monitor-command', + 'data': {'command-line': 'str', '*cpu-index': 'int'}, + 'returns': 'str' } +{ 'enum': 'TpmModel', 'data': [ 'tpm-tis' ] } +{ 'command': 'query-tpm-models', 'returns': ['TpmModel'] } +{ 'command': 'guest-get-time', + 'returns': 'int' } + +{ 'command': 'no-way-this-will-get-whitelisted', + 'returns': [ 'int' ] }
I like the pattern "add tests to demonstrate issues, then code to address the issues". But this test appears too much out of the blue for my taste.
You could use the commit message to prepare the reader.
Or you could deviate from the pattern and add this test together with the actual whitelist. That's what I'd try.
tests/qapi-schema/returns-whitelist.out line 7
Quoted 13 lines
tests/qapi-schema/returns-whitelist.out new file +7
-0@@ -0,0 +1,7 @@ +[OrderedDict([('command', 'human-monitor-command'), ('data', OrderedDict([('command-line', 'str'), ('*cpu-index', 'int')])), ('returns', 'str')]), + OrderedDict([('enum', 'TpmModel'), ('data', ['tpm-tis'])]), + OrderedDict([('command', 'query-tpm-models'), ('returns', ['TpmModel'])]), + OrderedDict([('command', 'guest-get-time'), ('returns', 'int')]), + OrderedDict([('command', 'no-way-this-will-get-whitelisted'), ('returns', ['int'])])] +[{'enum_name': 'TpmModel', 'enum_values': ['tpm-tis']}] +[]
Since I found nothing that's actually wrong:
Re: [Qemu-devel] [PATCH v5 19/28] qapi: Add some type check tests
Quoted 30 lines · Markus Armbruster
Quoted 6 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.
Signed-off-by Eric Blake <[email protected]>---
[...]
Quoted 16 lines
tests/qapi-schema/data-array-empty.err new file +0
-0tests/qapi-schema/data-array-empty.exit new file +1
-0@@ -0,0 +1 @@ +0tests/qapi-schema/data-array-empty.json new file +0
-0tests/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': { 'empty': [ ] } }v4 tested
Quoted 3 lines
{ 'command': 'oops', 'data': [ ] }Is that still covered somewhere else?
Probably not. Sounds like a good test case to add, presumably on top if I don't have to respin.
Quoted 8 lines
tests/qapi-schema/data-array-empty.json
Quoted 3 lines
tests/qapi-schema/data-array-empty.json new file +3
-0+ +{ 'command': 'no-way-this-will-get-whitelisted', + 'returns': [ 'int' ] }I like the pattern "add tests to demonstrate issues, then code to address the issues". But this test appears too much out of the blue for my taste.
Quoted 4 lines
You could use the commit message to prepare the reader.
Or you could deviate from the pattern and add this test together with the actual whitelist. That's what I'd try.
Of course, if I do need to respin, I can shuffle and split patches as needed to make the resubmission prettier.
Quoted 20 lines
Quoted 7 lines
tests/qapi-schema/returns-whitelist.out new file +0
-0tests/qapi-schema/returns-whitelist.out line 7
Quoted 7 lines
tests/qapi-schema/returns-whitelist.out new file +7
-0@@ -0,0 +1,7 @@ +[OrderedDict([('command', 'human-monitor-command'), ('data', OrderedDict([('command-line', 'str'), ('*cpu-index', 'int')])), ('returns', 'str')]), + OrderedDict([('enum', 'TpmModel'), ('data', ['tpm-tis'])]), + OrderedDict([('command', 'query-tpm-models'), ('returns', ['TpmModel'])]), + OrderedDict([('command', 'guest-get-time'), ('returns', 'int')]), + OrderedDict([('command', 'no-way-this-will-get-whitelisted'), ('returns', ['int'])])] +[{'enum_name': 'TpmModel', 'enum_values': ['tpm-tis']}] +[]Since I found nothing that's actually wrong:
Reviewed-by Markus Armbruster <[email protected]>
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH v5 20/28 qapi: More rigourous checking of types
In reply to Eric BlakeNow 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 uses of a type (the 'data':
of command, type, union, alternate, and event; the 'returns':
of command; the 'base': of type and union) must resolve to an appropriate subset of metatypes declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested anonymous structs will be done in later patches.
Update the testsuite to match improved output.
--- scripts/qapi.py | 94 +++++++++++++++++++++++++--- tests/qapi-schema/alternate-array.err | 2 +- tests/qapi-schema/alternate-nested.err | 2 +- tests/qapi-schema/alternate-unknown.err | 2 +- tests/qapi-schema/bad-base.err | 1 + tests/qapi-schema/bad-base.exit | 2 +- tests/qapi-schema/bad-base.json | 2 +- tests/qapi-schema/bad-base.out | 4 -- 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 - tests/qapi-schema/union-unknown.err | 1 + tests/qapi-schema/union-unknown.exit | 2 +- tests/qapi-schema/union-unknown.json | 2 +- tests/qapi-schema/union-unknown.out | 3 - 44 files changed, 118 insertions(+), 63 deletions(-)
scripts/qapi.py +85 -9
@@ -276,6 +276,63 @@ def discriminator_find_enum_define(expr): return find_enum(discriminator_type) +def check_type(expr_info, source, data, allow_array = False, + allowed_metas = [], allow_dict = True): + global all_names + + 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], str): + 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, str): + if not data in all_names: + raise QAPIExprError(expr_info, + "%s uses unknown type '%s'" + % (source, data)) + if not all_names[data] in allowed_metas: + raise QAPIExprError(expr_info, + "%s cannot use %s type '%s'" + % (source, all_names[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_metas=['built-in', 'union', 'alternate', 'struct', + 'enum'], + allow_dict=True) + +def check_command(expr, expr_info): + name = expr['command'] + check_type(expr_info, "'data' for command '%s'" % name, + expr.get('data'), + allowed_metas=['union', 'struct']) + check_type(expr_info, "'returns' for command '%s'" % name, + expr.get('returns'), allow_array=True, + allowed_metas=['built-in', 'union', 'alternate', 'struct', + 'enum']) + def check_event(expr, expr_info): global events name = expr['event']
@@ -287,7 +344,8 @@ def check_event(expr, expr_info): raise QAPIExprError(expr_info, "Event name '%s' should be upper case" % name) events.append(name) - + check_type(expr_info, "'data' for event '%s'" % name, + expr.get('data'), allowed_metas=['union', 'struct']) if params: for argname, argentry, optional, structured in parse_args(params): if structured:
@@ -348,6 +406,13 @@ def check_union(expr, expr_info): # Check every branch for (key, value) in members.items(): + # Each value must name a known type + check_type(expr_info, "Member '%s' of union '%s'" % (key, name), + value, allow_array=True, + allowed_metas=['built-in', 'union', 'alternate', 'struct', + 'enum'], + allow_dict=False) + # If the discriminator names an enum type, then all members # of 'data' must also be members of the enum type. if enum_define:
@@ -383,15 +448,12 @@ def check_alternate(expr, expr_info): values[c_key] = key # Ensure alternates have no type conflicts. - if isinstance(value, list): - raise QAPIExprError(expr_info, - "Alternate '%s' member '%s' must " - "not be array type" % (name, key)) + check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name), + value, + allowed_metas=['built-in', 'union', 'struct', 'enum'], + allow_dict=False) qtype = find_alternate_member_qtype(value) - if not qtype: - raise QAPIExprError(expr_info, - "Alternate '%s' member '%s' has " - "invalid type '%s'" % (name, key, value)) + assert qtype if qtype in types_seen: raise QAPIExprError(expr_info, "Alternate '%s' member '%s' has "
@@ -419,6 +481,14 @@ 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) + check_type(expr_info, "'base' for type '%s'" % name, expr.get('base'), + allowed_metas=['struct'], allow_dict=False) + def check_exprs(schema): for expr_elem in schema.exprs: expr = expr_elem['expr']
@@ -430,8 +500,14 @@ def check_exprs(schema): check_union(expr, info) elif expr.has_key('alternate'): check_alternate(expr, info) + elif expr.has_key('type'): + check_struct(expr, info) + elif expr.has_key('command'): + check_command(expr, info) elif expr.has_key('event'): check_event(expr, info) + else: + assert False, 'unexpected meta type' def check_keys(expr_elem, meta, required, optional=[]): expr = expr_elem['expr']
tests/qapi-schema/alternate-array.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/alternate-array.json:4: Alternate 'Alt' member 'two' must not be array type +tests/qapi-schema/alternate-array.json:4: Member 'two' of alternate 'Alt' cannot be an array
tests/qapi-schema/alternate-nested.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/alternate-nested.json:4: Alternate 'Alt2' member 'nested' has invalid type 'Alt1' +tests/qapi-schema/alternate-nested.json:4: Member 'nested' of alternate 'Alt2' cannot use alternate type 'Alt1'
tests/qapi-schema/alternate-unknown.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/alternate-unknown.json:2: Alternate 'Alt' member 'unknown' has invalid type 'MissingType' +tests/qapi-schema/alternate-unknown.json:2: Member 'unknown' of alternate 'Alt' uses unknown type 'MissingType'
tests/qapi-schema/bad-base.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/bad-base.json:3: 'base' for type 'MyType' cannot use union type 'Union'
tests/qapi-schema/bad-base.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/bad-base.json +1 -1
@@ -1,3 +1,3 @@ -# FIXME: we should reject a base that is not a struct +# we reject a base that is not a struct { 'union': 'Union', 'data': { 'a': 'int', 'b': 'str' } } { 'type': 'MyType', 'base': 'Union', 'data': { 'c': 'int' } }
tests/qapi-schema/bad-base.out +0 -4
@@ -1,4 +0,0 @@ -[OrderedDict([('union', 'Union'), ('data', OrderedDict([('a', 'int'), ('b', 'str')]))]), - OrderedDict([('type', 'MyType'), ('base', 'Union'), ('data', OrderedDict([('c', 'int')]))])] -[{'enum_name': 'UnionKind', 'enum_values': None}] -[OrderedDict([('type', 'MyType'), ('base', 'Union'), ('data', OrderedDict([('c', 'int')]))])]
tests/qapi-schema/data-array-empty.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/data-array-empty.json:2: Member 'empty' of 'data' for command 'oops': array type must contain single type name
tests/qapi-schema/data-array-empty.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/data-array-empty.json +1 -1
@@ -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': { 'empty': [ ] } }
tests/qapi-schema/data-array-empty.out +0 -3
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('data', OrderedDict([('empty', [])]))])] -[] -[]
tests/qapi-schema/data-array-unknown.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/data-array-unknown.json:2: Member 'array' of 'data' for command 'oops' uses unknown type 'NoSuchType'
tests/qapi-schema/data-array-unknown.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/data-array-unknown.json +1 -1
@@ -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': { 'array': [ 'NoSuchType' ] } }
tests/qapi-schema/data-array-unknown.out +0 -3
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('data', OrderedDict([('array', ['NoSuchType'])]))])] -[] -[]
tests/qapi-schema/data-int.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/data-int.json:2: 'data' for command 'oops' cannot use built-in type 'int'
tests/qapi-schema/data-int.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/data-int.json +1 -1
@@ -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
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('data', 'int')])] -[] -[]
tests/qapi-schema/data-member-array-bad.err +1 -0
@@ -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
@@ -1 +1 @@ -0 +1
tests/qapi-schema/data-member-array-bad.json +1 -1
@@ -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
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', [OrderedDict([('nested', 'str')])])]))])] -[] -[]
tests/qapi-schema/data-member-unknown.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/data-member-unknown.json:2: Member 'member' of 'data' for command 'oops' uses unknown type 'NoSuchType'
tests/qapi-schema/data-member-unknown.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/data-member-unknown.json +1 -1
@@ -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
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('data', OrderedDict([('member', 'NoSuchType')]))])] -[] -[]
tests/qapi-schema/data-unknown.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/data-unknown.json:2: 'data' for command 'oops' uses unknown type 'NoSuchType'
tests/qapi-schema/data-unknown.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/data-unknown.json +1 -1
@@ -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
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('data', 'NoSuchType')])] -[] -[]
tests/qapi-schema/returns-array-bad.err +1 -0
@@ -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
@@ -1 +1 @@ -0 +1
tests/qapi-schema/returns-array-bad.json +1 -1
@@ -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
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('returns', ['str', 'str'])])] -[] -[]
tests/qapi-schema/returns-unknown.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/returns-unknown.json:2: 'returns' for command 'oops' uses unknown type 'NoSuchType'
tests/qapi-schema/returns-unknown.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/returns-unknown.json +1 -1
@@ -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
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'oops'), ('returns', 'NoSuchType')])] -[] -[]
tests/qapi-schema/union-unknown.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/union-unknown.json:2: Member 'unknown' of union 'Union' uses unknown type 'MissingType'
tests/qapi-schema/union-unknown.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/union-unknown.json +1 -1
@@ -1,3 +1,3 @@ -# FIXME: we should reject a union with unknown type in branch +# we reject a union with unknown type in branch { 'union': 'Union', 'data': { 'unknown': 'MissingType' } }
tests/qapi-schema/union-unknown.out +0 -3
@@ -1,3 +0,0 @@ -[OrderedDict([('union', 'Union'), ('data', OrderedDict([('unknown', 'MissingType')]))])] -[{'enum_name': 'UnionKind', 'enum_values': None}] -[]
Signature · 1 line
2.1.0
Re: [Qemu-devel] [PATCH v5 20/28] qapi: More rigourous checking of types
Quoted 14 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 uses of a type (the 'data':
of command, type, union, alternate, and event; the 'returns':
of command; the 'base': of type and union) must resolve to an appropriate subset of metatypes declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested anonymous structs will be done in later patches.Update the testsuite to match improved output.
Signed-off-by Eric Blake <[email protected]>---
[...]
scripts/qapi.py def discriminator_find_enum_define(expr): · line 280
Quoted 10 lines
scripts/qapi.py +2
-0@@ -276,6 +276,63 @@ def discriminator_find_enum_define(expr): return find_enum(discriminator_type) +def check_type(expr_info, source, data, allow_array = False, + allowed_metas = [], allow_dict = True):
I'd allow_dict = False here, because I like defaulting to false. Matter of taste.
I'd name the third parameter def rather than data. Matter of taste again.
Quoted 30 lines
scripts/qapi.py +30
-0+ global all_names + + 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], str): + 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, str): + if not data in all_names: + raise QAPIExprError(expr_info, + "%s uses unknown type '%s'" + % (source, data)) + if not all_names[data] in allowed_metas: + raise QAPIExprError(expr_info, + "%s cannot use %s type '%s'" + % (source, all_names[data], data)) + return
scripts/qapi.py def discriminator_find_enum_define(expr): · line 320
Quoted 10 lines
scripts/qapi.py +10
-0+ + # 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,
This can produce messages like
Member 'inner' of Member 'outer' of ...
I figure the problem will go away when you ditch nested structs. Not worth worrying about it then.
Quoted 64 lines
scripts/qapi.py +29
-9+ allow_array=True, + allowed_metas=['built-in', 'union', 'alternate', 'struct', + 'enum'], + allow_dict=True) + +def check_command(expr, expr_info): + name = expr['command'] + check_type(expr_info, "'data' for command '%s'" % name, + expr.get('data'), + allowed_metas=['union', 'struct']) + check_type(expr_info, "'returns' for command '%s'" % name, + expr.get('returns'), allow_array=True, + allowed_metas=['built-in', 'union', 'alternate', 'struct', + 'enum']) + def check_event(expr, expr_info): global events name = expr['event']@@ -287,7 +344,8 @@ def check_event(expr, expr_info): raise QAPIExprError(expr_info, "Event name '%s' should be upper case" % name) events.append(name) - + check_type(expr_info, "'data' for event '%s'" % name, + expr.get('data'), allowed_metas=['union', 'struct']) if params: for argname, argentry, optional, structured in parse_args(params): if structured:@@ -348,6 +406,13 @@ def check_union(expr, expr_info): # Check every branch for (key, value) in members.items(): + # Each value must name a known type + check_type(expr_info, "Member '%s' of union '%s'" % (key, name), + value, allow_array=True, + allowed_metas=['built-in', 'union', 'alternate', 'struct', + 'enum'], + allow_dict=False) + # If the discriminator names an enum type, then all members # of 'data' must also be members of the enum type. if enum_define:@@ -383,15 +448,12 @@ def check_alternate(expr, expr_info): values[c_key] = key # Ensure alternates have no type conflicts. - if isinstance(value, list): - raise QAPIExprError(expr_info, - "Alternate '%s' member '%s' must " - "not be array type" % (name, key)) + check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name), + value, + allowed_metas=['built-in', 'union', 'struct', 'enum'], + allow_dict=False) qtype = find_alternate_member_qtype(value) - if not qtype: - raise QAPIExprError(expr_info, - "Alternate '%s' member '%s' has " - "invalid type '%s'" % (name, key, value)) + assert qtype if qtype in types_seen: raise QAPIExprError(expr_info, "Alternate '%s' member '%s' has "
scripts/qapi.py def check_enum(expr, expr_info): · line 488
Quoted 8 lines
scripts/qapi.py +5
-0@@ -419,6 +481,14 @@ 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)
This one gave me pause, until I realized that allowed_metas=[], allow_dict=True accepts exactly dictionary members, which is what we want.
Quoted 21 lines
scripts/qapi.py +9
-0+ check_type(expr_info, "'base' for type '%s'" % name, expr.get('base'), + allowed_metas=['struct'], allow_dict=False) + def check_exprs(schema): for expr_elem in schema.exprs: expr = expr_elem['expr']@@ -430,8 +500,14 @@ def check_exprs(schema): check_union(expr, info) elif expr.has_key('alternate'): check_alternate(expr, info) + elif expr.has_key('type'): + check_struct(expr, info) + elif expr.has_key('command'): + check_command(expr, info) elif expr.has_key('event'): check_event(expr, info) + else: + assert False, 'unexpected meta type' def check_keys(expr_elem, meta, required, optional=[]): expr = expr_elem['expr']
[...]
Re: [Qemu-devel] [PATCH v5 20/28] qapi: More rigourous checking of types
Quoted 23 lines · Markus Armbruster
Quoted 14 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 uses of a type (the 'data':
of command, type, union, alternate, and event; the 'returns':
of command; the 'base': of type and union) must resolve to an appropriate subset of metatypes declared by the current qapi parse; this includes recursing into each member of a data dictionary. Dealing with '**' and nested anonymous structs will be done in later patches.Update the testsuite to match improved output.
Signed-off-by Eric Blake <[email protected]>---
[...]
Quoted 6 lines
scripts/qapi.py +0
-0@@ -276,6 +276,63 @@ def discriminator_find_enum_define(expr):
Quoted 7 lines
scripts/qapi.py def discriminator_find_enum_define(expr): · line 280
Quoted 4 lines
scripts/qapi.py +2
-0return find_enum(discriminator_type) +def check_type(expr_info, source, data, allow_array = False, + allowed_metas = [], allow_dict = True):I'd
allow_dict= False here, because I like defaulting to false. Matter of taste.
Not too hard.
Quoted 4 lines
I'd name the third parameter def rather than data. Matter of taste again.
Oh, definitely a better name. When I first prototyped the function, I was only crawling the 'data' member, but since I now also use it to crawl 'returns' and 'base' it does make a difference.
Quoted 9 lines
scripts/qapi.py def discriminator_find_enum_define(expr): · line 320
Quoted 2 lines
scripts/qapi.py +2
-0+ for (key, value) in data.items(): + check_type(expr_info, "Member '%s' of %s" % (key, source), value,This can produce messages like
Member 'inner' of Member 'outer' of ...
I figure the problem will go away when you ditch nested structs. Not worth worrying about it then.
Yep, it disappears quite nicely. (I was torn on whether to make the message start with lower-case, to avoid the mid-sentence Cap, but the prevailing practice in this file before my patches was to start all QAPIExprError with a capital)
Quoted 10 lines
scripts/qapi.py def check_enum(expr, expr_info): · line 488
Quoted 6 lines
scripts/qapi.py +5
-0+def check_struct(expr, expr_info): + name = expr['type'] + members = expr['data'] + + check_type(expr_info, "'data' for type '%s'" % name, members)This one gave me pause, until I realized that allowed_metas=[], allow_dict=True accepts exactly dictionary members, which is what we want.
And your idea of having allow_dict default to False in the prototype to make it explicit here might make it easier to understand (where the default allows nothing, and then callers add the pieces that they want).
Indeed, just typing this email, that sounds nicer than the current case
of defaults cater to the majority, but force some callers to have to explicitly opt out.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH v5 21/28 qapi: Require valid names
In reply to Eric BlakePrevious commits demonstrated that the generator overlooked various bad naming situations:
- types, commands, and events need a valid name
- union and alternate branches cannot be marked optional
The set of valid names includes [a-zA-Z0-9._-] (where '.' is useful only in downstream extensions).
--- scripts/qapi.py | 57 ++++++++++++++++------ tests/qapi-schema/bad-ident.err | 1 + tests/qapi-schema/bad-ident.exit | 2 +- tests/qapi-schema/bad-ident.json | 2 +- tests/qapi-schema/bad-ident.out | 3 -- tests/qapi-schema/flat-union-bad-discriminator.err | 2 +- .../flat-union-optional-discriminator.err | 1 + .../flat-union-optional-discriminator.exit | 2 +- .../flat-union-optional-discriminator.json | 2 +- .../flat-union-optional-discriminator.out | 5 -- tests/qapi-schema/union-optional-branch.err | 1 + tests/qapi-schema/union-optional-branch.exit | 2 +- tests/qapi-schema/union-optional-branch.json | 2 +- tests/qapi-schema/union-optional-branch.out | 3 -- 14 files changed, 53 insertions(+), 32 deletions(-)
scripts/qapi.py +43 -14
@@ -15,6 +15,7 @@ import re from ordereddict import OrderedDict import os import sys +import string builtin_types = { 'str': 'QTYPE_QSTRING',
@@ -276,8 +277,27 @@ def discriminator_find_enum_define(expr): return find_enum(discriminator_type) +valid_characters = set(string.ascii_letters + string.digits + '.' + '-' + '_') +def check_name(expr_info, source, name, allow_optional = False): + membername = name + + if not isinstance(name, str): + raise QAPIExprError(expr_info, + "%s requires a string name" % source) + if name == '**': + return + if name.startswith('*'): + membername = name[1:] + if not allow_optional: + raise QAPIExprError(expr_info, + "%s does not allow optional name '%s'" + % (source, name)) + if not set(membername) <= valid_characters: + raise QAPIExprError(expr_info, + "%s uses invalid name '%s'" % (source, name)) + def check_type(expr_info, source, data, allow_array = False, - allowed_metas = [], allow_dict = True): + allowed_metas = [], allow_dict = True, allow_optional = False): global all_names if data is None:
@@ -317,21 +337,23 @@ 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(): + check_name(expr_info, "Member of %s" % source, key, + allow_optional=allow_optional) check_type(expr_info, "Member '%s' of %s" % (key, source), value, allow_array=True, allowed_metas=['built-in', 'union', 'alternate', 'struct', 'enum'], - allow_dict=True) + allow_dict=True, allow_optional=True) def check_command(expr, expr_info): name = expr['command'] check_type(expr_info, "'data' for command '%s'" % name, expr.get('data'), - allowed_metas=['union', 'struct']) + allowed_metas=['union', 'struct'], allow_optional=True) check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, allowed_metas=['built-in', 'union', 'alternate', 'struct', - 'enum']) + 'enum'], allow_optional=True) def check_event(expr, expr_info): global events
@@ -345,7 +367,8 @@ def check_event(expr, expr_info): % name) events.append(name) check_type(expr_info, "'data' for event '%s'" % name, - expr.get('data'), allowed_metas=['union', 'struct']) + expr.get('data'), allowed_metas=['union', 'struct'], + allow_optional=True) if params: for argname, argentry, optional, structured in parse_args(params): if structured:
@@ -385,12 +408,10 @@ def check_union(expr, expr_info): "Base '%s' is not a valid base type" % base) - # The value of member 'discriminator' must name a member of the - # base type. - if not isinstance(discriminator, str): - raise QAPIExprError(expr_info, - "Flat union '%s' must have a string " - "discriminator field" % name) + # The value of member 'discriminator' must name a non-optional + # member of the base type. + check_name(expr_info, "Discriminator of flat union '%s'" % name, + discriminator) discriminator_type = base_fields.get(discriminator) if not discriminator_type: raise QAPIExprError(expr_info,
@@ -406,6 +427,8 @@ def check_union(expr, expr_info): # Check every branch for (key, value) in members.items(): + check_name(expr_info, "Member of union '%s'" % name, key) + # Each value must name a known type check_type(expr_info, "Member '%s' of union '%s'" % (key, name), value, allow_array=True,
@@ -439,6 +462,8 @@ def check_alternate(expr, expr_info): # Check every branch for (key, value) in members.items(): + check_name(expr_info, "Member of alternate '%s'" % name, key) + # Check for conflicts in the generated enum c_key = _generate_enum_string(key) if c_key in values:
@@ -485,7 +510,8 @@ def check_struct(expr, expr_info): name = expr['type'] members = expr['data'] - check_type(expr_info, "'data' for type '%s'" % name, members) + check_type(expr_info, "'data' for type '%s'" % name, members, + allow_optional=True) check_type(expr_info, "'base' for type '%s'" % name, expr.get('base'), allowed_metas=['struct'], allow_dict=False)
@@ -676,8 +702,11 @@ def type_name(name): return c_list_type(name[0]) return name -def add_name(name, info, meta, implicit = False): +def add_name(name, info, meta, implicit = False, source = None): global all_names + if not source: + source = "'%s'" % meta + check_name(info, source, name) if name in all_names: raise QAPIExprError(info, "%s '%s' is already defined"
@@ -691,7 +720,7 @@ def add_name(name, info, meta, implicit = False): def add_struct(definition, info): global struct_types name = definition['type'] - add_name(name, info, 'struct') + add_name(name, info, 'struct', source="'type'") struct_types.append(definition) def find_struct(name):
tests/qapi-schema/bad-ident.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/bad-ident.json:2: 'type' does not allow optional name '*oops'
tests/qapi-schema/bad-ident.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/bad-ident.json +1 -1
@@ -1,3 +1,3 @@ -# FIXME: we should reject creating a type name with bad name +# we reject creating a type name with bad name { 'type': '*oops', 'data': { 'i': 'int' } }
tests/qapi-schema/bad-ident.out +0 -3
@@ -1,3 +0,0 @@ -[OrderedDict([('type', '*oops'), ('data', OrderedDict([('i', 'int')]))])] -[] -[OrderedDict([('type', '*oops'), ('data', OrderedDict([('i', 'int')]))])]
tests/qapi-schema/flat-union-bad-discriminator.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/flat-union-bad-discriminator.json:11: Flat union 'TestUnion' must have a string discriminator field +tests/qapi-schema/flat-union-bad-discriminator.json:11: Discriminator of flat union 'TestUnion' requires a string name
tests/qapi-schema/flat-union-optional-discriminator.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/flat-union-optional-discriminator.json:5: Discriminator of flat union 'MyUnion' does not allow optional name '*switch'
tests/qapi-schema/flat-union-optional-discriminator.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/flat-union-optional-discriminator.json +1 -1
@@ -1,4 +1,4 @@ -# FIXME: we should require the discriminator to be non-optional +# we require the discriminator to be non-optional { 'enum': 'Enum', 'data': [ 'one', 'two' ] } { 'type': 'Base', 'data': { '*switch': 'Enum' } }
tests/qapi-schema/flat-union-optional-discriminator.out +0 -5
@@ -1,5 +0,0 @@ -[OrderedDict([('enum', 'Enum'), ('data', ['one', 'two'])]), - OrderedDict([('type', 'Base'), ('data', OrderedDict([('*switch', 'Enum')]))]), - OrderedDict([('union', 'MyUnion'), ('base', 'Base'), ('discriminator', '*switch'), ('data', OrderedDict([('one', 'int'), ('two', 'str')]))])] -[{'enum_name': 'Enum', 'enum_values': ['one', 'two']}] -[OrderedDict([('type', 'Base'), ('data', OrderedDict([('*switch', 'Enum')]))])]
tests/qapi-schema/union-optional-branch.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/union-optional-branch.json:2: Member of union 'Union' does not allow optional name '*a'
tests/qapi-schema/union-optional-branch.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/union-optional-branch.json +1 -1
@@ -1,2 +1,2 @@ -# FIXME: union branches cannot be optional +# union branches cannot be optional { 'union': 'Union', 'data': { '*a': 'int', 'b': 'str' } }
tests/qapi-schema/union-optional-branch.out +0 -3
@@ -1,3 +0,0 @@ -[OrderedDict([('union', 'Union'), ('data', OrderedDict([('*a', 'int'), ('b', 'str')]))])] -[{'enum_name': 'UnionKind', 'enum_values': None}] -[]
Signature · 1 line
2.1.0
Re: [Qemu-devel] [PATCH v5 21/28] qapi: Require valid names
Quoted 39 lines · Eric Blake
Previous commits demonstrated that the generator overlooked various bad naming situations:
- types, commands, and events need a valid name
- union and alternate branches cannot be marked optionalThe set of valid names includes [a-zA-Z0-9._-] (where '.' is useful only in downstream extensions).
Signed-off-by Eric Blake <[email protected]>--- scripts/qapi.py | 57 ++++++++++++++++------ tests/qapi-schema/bad-ident.err | 1 + tests/qapi-schema/bad-ident.exit | 2 +- tests/qapi-schema/bad-ident.json | 2 +- tests/qapi-schema/bad-ident.out | 3 -- tests/qapi-schema/flat-union-bad-discriminator.err | 2 +- .../flat-union-optional-discriminator.err | 1 + .../flat-union-optional-discriminator.exit | 2 +- .../flat-union-optional-discriminator.json | 2 +- .../flat-union-optional-discriminator.out | 5 -- tests/qapi-schema/union-optional-branch.err | 1 + tests/qapi-schema/union-optional-branch.exit | 2 +- tests/qapi-schema/union-optional-branch.json | 2 +- tests/qapi-schema/union-optional-branch.out | 3 -- 14 files changed, 53 insertions(+), 32 deletions(-)scripts/qapi.py +1
-0@@ -15,6 +15,7 @@ import re from ordereddict import OrderedDict import os import sys +import string builtin_types = { 'str': 'QTYPE_QSTRING',
scripts/qapi.py def discriminator_find_enum_define(expr): · line 280
Quoted 4 lines
scripts/qapi.py +1
-0@@ -276,8 +277,27 @@ def discriminator_find_enum_define(expr): return find_enum(discriminator_type) +valid_characters = set(string.ascii_letters + string.digits + '.' + '-' + '_')
strings.ascii_letters depends on the locale...
scripts/qapi.py def discriminator_find_enum_define(expr): · line 288
Quoted 8 lines
scripts/qapi.py +8
-0+def check_name(expr_info, source, name, allow_optional = False): + membername = name + + if not isinstance(name, str): + raise QAPIExprError(expr_info, + "%s requires a string name" % source) + if name == '**': + return
Doesn't this permit '**' anywhere, not just as pseudo-type in command arguments and results?
scripts/qapi.py def discriminator_find_enum_define(expr): · line 295
Quoted 7 lines
scripts/qapi.py +7
-0+ if name.startswith('*'): + membername = name[1:] + if not allow_optional: + raise QAPIExprError(expr_info, + "%s does not allow optional name '%s'" + % (source, name)) + if not set(membername) <= valid_characters:
... so this check would break if we called locale.setlocale() in this program. While I don't think we need to worry about it, I think you could just as well use something like
valid_name = re.compile(r"^[A-Za-z0-9-._]+$")
if not valid_name.match(membername):
Quoted 53 lines
scripts/qapi.py +11
-8+ raise QAPIExprError(expr_info, + "%s uses invalid name '%s'" % (source, name)) + def check_type(expr_info, source, data, allow_array = False, - allowed_metas = [], allow_dict = True): + allowed_metas = [], allow_dict = True, allow_optional = False): global all_names if data is None:@@ -317,21 +337,23 @@ 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(): + check_name(expr_info, "Member of %s" % source, key, + allow_optional=allow_optional) check_type(expr_info, "Member '%s' of %s" % (key, source), value, allow_array=True, allowed_metas=['built-in', 'union', 'alternate', 'struct', 'enum'], - allow_dict=True) + allow_dict=True, allow_optional=True) def check_command(expr, expr_info): name = expr['command'] check_type(expr_info, "'data' for command '%s'" % name, expr.get('data'), - allowed_metas=['union', 'struct']) + allowed_metas=['union', 'struct'], allow_optional=True) check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, allowed_metas=['built-in', 'union', 'alternate', 'struct', - 'enum']) + 'enum'], allow_optional=True) def check_event(expr, expr_info): global events@@ -345,7 +367,8 @@ def check_event(expr, expr_info): % name) events.append(name) check_type(expr_info, "'data' for event '%s'" % name, - expr.get('data'), allowed_metas=['union', 'struct']) + expr.get('data'), allowed_metas=['union', 'struct'], + allow_optional=True) if params: for argname, argentry, optional, structured in parse_args(params): if structured:@@ -385,12 +408,10 @@ def check_union(expr, expr_info): "Base '%s' is not a valid base type" % base) - # The value of member 'discriminator' must name a member of the - # base type. - if not isinstance(discriminator, str):
scripts/qapi.py def check_union(expr, expr_info): · line 417
Quoted 10 lines
scripts/qapi.py +4
-3- raise QAPIExprError(expr_info, - "Flat union '%s' must have a string " - "discriminator field" % name) + # The value of member 'discriminator' must name a non-optional + # member of the base type. + check_name(expr_info, "Discriminator of flat union '%s'" % name, + discriminator) discriminator_type = base_fields.get(discriminator) if not discriminator_type: raise QAPIExprError(expr_info,
What happens when I try 'discriminator': '**'?
Quoted 50 lines
scripts/qapi.py +11
-3@@ -406,6 +427,8 @@ def check_union(expr, expr_info): # Check every branch for (key, value) in members.items(): + check_name(expr_info, "Member of union '%s'" % name, key) + # Each value must name a known type check_type(expr_info, "Member '%s' of union '%s'" % (key, name), value, allow_array=True,@@ -439,6 +462,8 @@ def check_alternate(expr, expr_info): # Check every branch for (key, value) in members.items(): + check_name(expr_info, "Member of alternate '%s'" % name, key) + # Check for conflicts in the generated enum c_key = _generate_enum_string(key) if c_key in values:@@ -485,7 +510,8 @@ def check_struct(expr, expr_info): name = expr['type'] members = expr['data'] - check_type(expr_info, "'data' for type '%s'" % name, members) + check_type(expr_info, "'data' for type '%s'" % name, members, + allow_optional=True) check_type(expr_info, "'base' for type '%s'" % name, expr.get('base'), allowed_metas=['struct'], allow_dict=False)@@ -676,8 +702,11 @@ def type_name(name): return c_list_type(name[0]) return name -def add_name(name, info, meta, implicit = False): +def add_name(name, info, meta, implicit = False, source = None): global all_names + if not source: + source = "'%s'" % meta + check_name(info, source, name) if name in all_names: raise QAPIExprError(info, "%s '%s' is already defined"@@ -691,7 +720,7 @@ def add_name(name, info, meta, implicit = False): def add_struct(definition, info): global struct_types name = definition['type'] - add_name(name, info, 'struct') + add_name(name, info, 'struct', source="'type'") struct_types.append(definition) def find_struct(name):
[...]
Re: [Qemu-devel] [PATCH v5 21/28] qapi: Require valid names
Quoted 7 lines · Markus Armbruster
Quoted 5 lines · Eric Blake
Previous commits demonstrated that the generator overlooked various bad naming situations:
- types, commands, and events need a valid name
- union and alternate branches cannot be marked optional
Quoted 7 lines
Quoted 5 lines
The set of valid names includes [a-zA-Z0-9._-] (where '.' is useful only in downstream extensions).
+valid_characters =
set(string.ascii_letters + string.digits + '.' + '-' + '_')strings.ascii_letters depends on the locale...
https://docs.python.org/2/library/string.html
string.ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase
constants described below. This value is not locale-dependent.
You are thinking of string.letters, which IS locale-dependent. I intentionally used ascii_letters.
Quoted 12 lines
scripts/qapi.py def discriminator_find_enum_define(expr): · line 288
Quoted 9 lines
scripts/qapi.py +8
-0+def check_name(expr_info, source, name, allow_optional = False): + membername = name + + if not isinstance(name, str): + raise QAPIExprError(expr_info, + "%s requires a string name" % source) + if name == '**': + returnDoesn't this permit '**' anywhere, not just as pseudo-type in command arguments and results?
Yes, on the grounds that check_type then filters it appropriately. But worthy of a comment (probably both in the commit message AND in the code base). Grounds for a v6 respin.
Quoted 9 lines
scripts/qapi.py def discriminator_find_enum_define(expr): · line 295
Quoted 8 lines
scripts/qapi.py +7
-0+ if name.startswith('*'): + membername = name[1:] + if not allow_optional: + raise QAPIExprError(expr_info, + "%s does not allow optional name '%s'" + % (source, name)) + if not set(membername) <= valid_characters:
Quoted 7 lines
... so this check would break if we called
locale.setlocale()in this program. While I don't think we need to worry about it, I think you could just as well use something like
valid_name=re.compile(r"^[A-Za-z0-9-._]+$")if not
valid_name.match(membername):
regex is slightly slower than string matching _if the regex is precompiled_, and MUCH slower than string matching if the regex is compiled every time. In turn, string matching is slower than open-coding things, but has the benefit of being more compact and maintainable (open-coded loops are the worst on that front). Here's where I got my inspiration:
But I may just go with the regex after all (I don't know how efficient python is about reusing a regex when a function is called multiple times, rather than recompiling the regex every time. Personal side
note: back in 2009 or so, I was able to make 'm4' significantly faster in the context of 'autoconf' when I taught it to cache the compilation of the 8 most-recently-encountered regex, rather than recompiling every time; and then made 'autoconf' even faster when I taught it to do actions that didn't require regex use from 'm4' in the first place.)
The nice thing, though, is that I factored things so that the implementation of this one function can change without having to hunt down all call-sites, if I keep the contract the same.
Quoted 5 lines
Quoted 3 lines
discriminator_type=base_fields.get(discriminator)if notdiscriminator_type:
raise QAPIExprError(expr_info,What happens when I try 'discriminator': '**'?
No clue. Good thing for me to add somewhere in my series. However, I did manage to have this series at least think about a base type with '*switch':'Enum', then use 'discriminator':'*switch', which got past the generator (who knows what the C code would have done if have_switch was false?), so I plugged that hole; but in the process of testing it, I noticed that '*switch':'Enum' paired with 'discriminator':'switch' complained that 'switch' was not a member of the base class (which is a lie; it is present in the base class, but as an optional member). Proof that the generator is a bunch of hacks strung together :)
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v5 21/28] qapi: Require valid names
Quoted 19 lines · Eric Blake
Quoted 7 lines · Markus Armbruster
Quoted 5 lines · Eric Blake
Previous commits demonstrated that the generator overlooked various bad naming situations:
- types, commands, and events need a valid name
- union and alternate branches cannot be marked optionalQuoted 8 lines
Quoted 6 lines
The set of valid names includes [a-zA-Z0-9._-] (where '.' is useful only in downstream extensions).
+valid_characters = set(string.ascii_letters + string.digits + '.'
+ '-' + '_')strings.ascii_letters depends on the locale...
Quoted 7 lines
string.ascii_letters
The concatenation of the
ascii_lowercaseandascii_uppercase
constants described below. This value is not locale-dependent.You are thinking of string.letters, which IS locale-dependent. I intentionally used
ascii_letters.
You're right, I misread the docs.
Quoted 42 lines
Quoted 11 lines
scripts/qapi.py def discriminator_find_enum_define(expr): · line 288
Quoted 8 lines
scripts/qapi.py +8
-0+def check_name(expr_info, source, name, allow_optional = False): + membername = name + + if not isinstance(name, str): + raise QAPIExprError(expr_info, + "%s requires a string name" % source) + if name == '**': + returnDoesn't this permit '**' anywhere, not just as pseudo-type in command arguments and results?
Yes, on the grounds that
check_typethen filters it appropriately. But worthy of a comment (probably both in the commit message AND in the code base). Grounds for a v6 respin.Quoted 9 lines
scripts/qapi.py def discriminator_find_enum_define(expr): · line 295
Quoted 8 lines
scripts/qapi.py +7
-0+ if name.startswith('*'): + membername = name[1:] + if not allow_optional: + raise QAPIExprError(expr_info, + "%s does not allow optional name '%s'" + % (source, name)) + if not set(membername) <= valid_characters:Quoted 7 lines
... so this check would break if we called
locale.setlocale()in this program. While I don't think we need to worry about it, I think you could just as well use something like
valid_name=re.compile(r"^[A-Za-z0-9-._]+$")if not
valid_name.match(membername):regex is slightly slower than string matching
_ifthe regex isprecompiled_, and MUCH slower than string matching if the regex is compiled every time. In turn, string matching is slower than open-coding things, but has the benefit of being more compact and maintainable (open-coded loops are the worst on that front). Here's where I got my inspiration:
Quoted 8 lines
But I may just go with the regex after all (I don't know how efficient python is about reusing a regex when a function is called multiple times, rather than recompiling the regex every time. Personal side
note: back in 2009 or so, I was able to make 'm4' significantly faster in the context of 'autoconf' when I taught it to cache the compilation of the 8 most-recently-encountered regex, rather than recompiling every time; and then made 'autoconf' even faster when I taught it to do actions that didn't require regex use from 'm4' in the first place.)
Neat.
Quoted 3 lines
The nice thing, though, is that I factored things so that the implementation of this one function can change without having to hunt down all call-sites, if I keep the contract the same.
I don't care for matching performance here, I do care for readability. Please pick the solution you find easiest to understand.
Quoted 7 lines
Quoted 5 lines
Quoted 3 lines
discriminator_type=base_fields.get(discriminator)if notdiscriminator_type:
raise QAPIExprError(expr_info,What happens when I try 'discriminator': '**'?
No clue. Good thing for me to add somewhere in my series. However, I
I had a second look. I think the generator accepting '**' in exactly the right places relies on:
(1) check_name() accepts only proper names, not '**'.
(2) All names get checked with check_name().
(3) Except check_type() accepts special type name '**' when allow_star.
(4) allow_star is set for exactly the right places.
With check_name()'s superfluous / incorrect '**' check gone, (1) obviously holds. (2) isn't obvious, thus food for code review. (3) is trivial. (4) is trivial except for "exactly the right places". qapi-code-gen.txt:
In rare cases, QAPI cannot express a type-safe representation of a corresponding Client JSON Protocol command. In these cases, if the command expression includes the key 'gen' with boolean value false, 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.
Unfortunately, "the 'data' or 'returns' member that intends to bypass [...] should use '**' rather than a valid type name" can be read in (at least) two ways:
1. It applies to the 'data', 'returns' members of the command object.
2. It applies to members of 'data', 'returns' members of the command object.
The schema uses both readings: qom-get has 'returns': '**', and qom-set, netdev_add, object_add have 'data' members of the form KEY: '**'.
Note that neither code nor tests have 'data': '**' or KEY: '**' in 'returns'.
qapi.py appears to implement a third way: '**' may appear as type name anywhere within 'data' or 'returns'. May well make sense, and may well work, but we have no test coverage for it.
We can extend tests to cover what the generator accepts (separate series recommended), or restrict the generator to what we actually use and test. I'm leaning towards the latter.
Further note that '**' can only be used right in a command declaration. Factoring out the right hand side of 'data' or 'returns' into a separate struct type declaration isn't possible when it contains '**'.
Quoted 8 lines
did manage to have this series at least think about a base type with '*switch':'Enum', then use 'discriminator':'*switch', which got past the generator (who knows what the C code would have done if
have_switchwas false?), so I plugged that hole; but in the process of testing it, I noticed that '*switch':'Enum' paired with 'discriminator':'switch' complained that 'switch' was not a member of the base class (which is a lie; it is present in the base class, but as an optional member). Proof that the generator is a bunch of hacks strung together :)
Indeed!
Re: [Qemu-devel] [PATCH v5 21/28] qapi: Require valid names
Markus Armbruster <[email protected]> writes:
[...]
Quoted 29 lines
I had a second look. I think the generator accepting '**' in exactly the right places relies on:
(1)
check_name()accepts only proper names, not '**'.(2) All names get checked with
check_name().(3) Except
check_type()accepts special type name '**' whenallow_star.(4)
allow_staris set for exactly the right places.With check_name()'s superfluous / incorrect '**' check gone, (1) obviously holds. (2) isn't obvious, thus food for code review. (3) is trivial. (4) is trivial except for "exactly the right places". qapi-code-gen.txt:
In rare cases, QAPI cannot express a type-safe representation of a corresponding Client JSON Protocol command. In these cases, if the command expression includes the key 'gen' with boolean value false, 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.
Unfortunately, "the 'data' or 'returns' member that intends to bypass [...] should use '**' rather than a valid type name" can be read in (at least) two ways:
1. It applies to the 'data', 'returns' members of the command object.
Quoted 8 lines
2. It applies to members of 'data', 'returns' members of the command object.
The schema uses both readings: qom-get has 'returns': '**', and qom-set,
netdev_add,object_addhave 'data' members of the form KEY: '**'.Note that neither code nor tests have 'data': '**' or KEY: '**' in 'returns'.
Type '**' generally means "any JSON value". However, a command's 'data' must be a JSON object (see docs/qmp/qmp-spec.txt). Ways to deal with this:
A. Ignore. Conforming to the schema is necessary but not sufficient for
a command being accepted anyway.
B. The meaning of type '**' depends on context: it's "any JSON object"
for a command's 'data', else "any JSON value".
C. Outlaw 'data': '**' for now.
I prefer C, I can accept A, I dislike B.
Quoted 11 lines
qapi.pyappears to implement a third way: '**' may appear as type name anywhere within 'data' or 'returns'. May well make sense, and may well work, but we have no test coverage for it.We can extend tests to cover what the generator accepts (separate series recommended), or restrict the generator to what we actually use and test. I'm leaning towards the latter.
Further note that '**' can only be used right in a command declaration. Factoring out the right hand side of 'data' or 'returns' into a separate struct type declaration isn't possible when it contains '**'.
We could treat '**' as top type rather than as hack for a few commands. Conceptually clean, but hard to justify without users.
[...]
Re: [Qemu-devel] [PATCH v5 21/28] qapi: Require valid names
In reply to Eric BlakeQuoted 41 lines · Eric Blake
Previous commits demonstrated that the generator overlooked various bad naming situations:
- types, commands, and events need a valid name
- union and alternate branches cannot be marked optionalThe set of valid names includes [a-zA-Z0-9._-] (where '.' is useful only in downstream extensions).
Signed-off-by Eric Blake <[email protected]>--- scripts/qapi.py | 57 ++++++++++++++++------ tests/qapi-schema/bad-ident.err | 1 + tests/qapi-schema/bad-ident.exit | 2 +- tests/qapi-schema/bad-ident.json | 2 +- tests/qapi-schema/bad-ident.out | 3 -- tests/qapi-schema/flat-union-bad-discriminator.err | 2 +- .../flat-union-optional-discriminator.err | 1 + .../flat-union-optional-discriminator.exit | 2 +- .../flat-union-optional-discriminator.json | 2 +- .../flat-union-optional-discriminator.out | 5 -- tests/qapi-schema/union-optional-branch.err | 1 + tests/qapi-schema/union-optional-branch.exit | 2 +- tests/qapi-schema/union-optional-branch.json | 2 +- tests/qapi-schema/union-optional-branch.out | 3 -- 14 files changed, 53 insertions(+), 32 deletions(-)scripts/qapi.py +1
-0@@ -15,6 +15,7 @@ import re from ordereddict import OrderedDict import os import sys +import string builtin_types = { 'str': 'QTYPE_QSTRING',@@ -276,8 +277,27 @@ def discriminator_find_enum_define(expr): return find_enum(discriminator_type)
scripts/qapi.py def discriminator_find_enum_define(expr): · line 288
Quoted 10 lines
scripts/qapi.py +9
-0+valid_characters = set(string.ascii_letters + string.digits + '.' + '-' + '_') +def check_name(expr_info, source, name, allow_optional = False): + membername = name + + if not isinstance(name, str): + raise QAPIExprError(expr_info, + "%s requires a string name" % source) + if name == '**': + return
I'm afraid this conditional is superfluous or wrong. Our schemata don't trigger it.
As far as I know, '**' may occur as pseudo-type in a command's 'data' or 'returns', and nowhere else.
Example 1 (qom-get):
'returns': '**'
Example 2 (qom-set):
'data': { 'path': 'str', 'property': 'str', 'value': '**' },
Example 3 (hypothetical)
'returns': { 'frob': '**' }
Both 'data' and 'returns' are checked by check_type().
Example 1 takes the early exit on data = '**' there.
Example 2 goes through this loop
for (key, value) in data.items():
check_name(expr_info, "Member of %s" % source, key,
allow_optional=allow_optional)
check_type(expr_info, "Member '%s' of %s" % (key, source), value,
allow_array=True,
allowed_metas=['built-in', 'union', 'alternate', 'struct',
'enum'],
allow_dict=True, allow_optional=True)
The '**' is fed to check_type(), *not* to check_name(). check_type() takes the same early exit.
[...]
Re: [Qemu-devel] [PATCH v5 21/28] qapi: Require valid names
Quoted 12 lines · Markus Armbruster
Quoted 10 lines · Eric Blake
Previous commits demonstrated that the generator overlooked various bad naming situations:
- types, commands, and events need a valid name
- union and alternate branches cannot be marked optionalThe set of valid names includes [a-zA-Z0-9._-] (where '.' is useful only in downstream extensions).
Quoted 12 lines
scripts/qapi.py def discriminator_find_enum_define(expr): · line 288
Quoted 9 lines
scripts/qapi.py +9
-0+valid_characters = set(string.ascii_letters + string.digits + '.' + '-' + '_') +def check_name(expr_info, source, name, allow_optional = False): + membername = name + + if not isinstance(name, str): + raise QAPIExprError(expr_info, + "%s requires a string name" % source) + if name == '**': + returnI'm afraid this conditional is superfluous or wrong. Our schemata don't trigger it.
Hmm, you're right. Given a 'name':'type' pair in a dictionary, check_name is used on the 'name' portion; but we only use 'name':'**' (and NOT '**':'type') in the schemata. I'll drop it in the respin.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v5 21/28] qapi: Require valid names
In reply to Eric BlakeEric Blake <[email protected]> writes:
[...]
Quoted 9 lines
scripts/qapi.py +9
-0+valid_characters = set(string.ascii_letters + string.digits + '.' + '-' + '_') +def check_name(expr_info, source, name, allow_optional = False): + membername = name + + if not isinstance(name, str): + raise QAPIExprError(expr_info, + "%s requires a string name" % source) + if name == '**': + return
scripts/qapi.py def discriminator_find_enum_define(expr): · line 298
Quoted 10 lines
scripts/qapi.py +10
-0+ if name.startswith('*'): + membername = name[1:] + if not allow_optional: + raise QAPIExprError(expr_info, + "%s does not allow optional name '%s'" + % (source, name)) + if not set(membername) <= valid_characters: + raise QAPIExprError(expr_info, + "%s uses invalid name '%s'" % (source, name)) +
This accepts names starting with a digit. Sure we generate valid C identifiers for such beauties?
qapi-code-gen.txt:
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.
One, I think "all command, type, and field names" is too narrow, what about event names, or enumeration value names? Suggest say just "all names".
Two, "letters, digits, dash, and underscore", please.
Three, I think check_name() should enforce "starts with letter or '_'".
[...]
PATCH v5 22/28 qapi: Whitelist commands that don't return dictionary
In reply to Eric Blake...or an array of dictionaries. Although we have to cater to existing commands, returning a non-dictionary means the command is not extensible (no new name/value pairs can be added if more information must be returned in parallel). By making the whitelist explicit, any new command that falls foul of this practice will have to be self-documenting, which will encourage developers to either justify the action or rework the design to use a dictionary after all.
--- scripts/qapi.py | 30 ++++++++++++++++++++++++++++-- tests/qapi-schema/returns-alternate.err | 1 + tests/qapi-schema/returns-alternate.exit | 2 +- tests/qapi-schema/returns-alternate.json | 2 +- tests/qapi-schema/returns-alternate.out | 4 ---- tests/qapi-schema/returns-int.json | 3 ++- tests/qapi-schema/returns-int.out | 2 +- tests/qapi-schema/returns-whitelist.err | 1 + tests/qapi-schema/returns-whitelist.exit | 2 +- tests/qapi-schema/returns-whitelist.json | 2 +- tests/qapi-schema/returns-whitelist.out | 7 ------- 11 files changed, 37 insertions(+), 19 deletions(-)
scripts/qapi.py +28 -2
@@ -33,6 +33,30 @@ builtin_types = { 'size': 'QTYPE_QINT', } +# Whitelist of commands allowed to return a non-dictionary +returns_whitelist = [ + # From QMP: + 'human-monitor-command', + 'query-migrate-cache-size', + 'query-tpm-models', + 'query-tpm-types', + 'ringbuf-read', + + # From QGA: + 'guest-file-open', + 'guest-fsfreeze-freeze', + 'guest-fsfreeze-freeze-list', + 'guest-fsfreeze-status', + 'guest-fsfreeze-thaw', + 'guest-get-time', + 'guest-set-vcpus', + 'guest-sync', + 'guest-sync-delimited', + + # From qapi-schema-test: + 'user_def_cmd3', +] + enum_types = [] struct_types = [] union_types = []
@@ -350,10 +374,12 @@ def check_command(expr, expr_info): check_type(expr_info, "'data' for command '%s'" % name, expr.get('data'), allowed_metas=['union', 'struct'], allow_optional=True) + returns_meta = ['union', 'struct'] + if name in returns_whitelist: + returns_meta += ['built-in', 'alternate', 'enum'] check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, - allowed_metas=['built-in', 'union', 'alternate', 'struct', - 'enum'], allow_optional=True) + allowed_metas=returns_meta, allow_optional=True) def check_event(expr, expr_info): global events
tests/qapi-schema/returns-alternate.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/returns-alternate.json:3: 'returns' for command 'oops' cannot use alternate type 'Alt'
tests/qapi-schema/returns-alternate.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/returns-alternate.json +1 -1
@@ -1,3 +1,3 @@ -# FIXME: we should reject returns if it is an alternate type +# we reject returns if it is an alternate type { 'alternate': 'Alt', 'data': { 'a': 'int', 'b': 'str' } } { 'command': 'oops', 'returns': 'Alt' }
tests/qapi-schema/returns-alternate.out +0 -4
@@ -1,4 +0,0 @@ -[OrderedDict([('alternate', 'Alt'), ('data', OrderedDict([('a', 'int'), ('b', 'str')]))]), - OrderedDict([('command', 'oops'), ('returns', 'Alt')])] -[{'enum_name': 'AltKind', 'enum_values': None}] -[]
tests/qapi-schema/returns-int.json +2 -1
@@ -1,2 +1,3 @@ # It is okay (although not extensible) to return a non-dictionary -{ 'command': 'okay', 'returns': 'int' } +# But to make it work, the name must be in a whitelist +{ 'command': 'guest-get-time', 'returns': 'int' }
tests/qapi-schema/returns-int.out +1 -1
@@ -1,3 +1,3 @@ -[OrderedDict([('command', 'okay'), ('returns', 'int')])] +[OrderedDict([('command', 'guest-get-time'), ('returns', 'int')])] [] []
tests/qapi-schema/returns-whitelist.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/returns-whitelist.json:10: 'returns' for command 'no-way-this-will-get-whitelisted' cannot use built-in type 'int'
tests/qapi-schema/returns-whitelist.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/returns-whitelist.json +1 -1
@@ -1,4 +1,4 @@ -# FIXME: we should enforce that 'returns' be a dict or array of dict unless whitelisted +# we enforce that 'returns' be a dict or array of dict unless whitelisted { 'command': 'human-monitor-command', 'data': {'command-line': 'str', '*cpu-index': 'int'}, 'returns': 'str' }
tests/qapi-schema/returns-whitelist.out +0 -7
@@ -1,7 +0,0 @@ -[OrderedDict([('command', 'human-monitor-command'), ('data', OrderedDict([('command-line', 'str'), ('*cpu-index', 'int')])), ('returns', 'str')]), - OrderedDict([('enum', 'TpmModel'), ('data', ['tpm-tis'])]), - OrderedDict([('command', 'query-tpm-models'), ('returns', ['TpmModel'])]), - OrderedDict([('command', 'guest-get-time'), ('returns', 'int')]), - OrderedDict([('command', 'no-way-this-will-get-whitelisted'), ('returns', ['int'])])] -[{'enum_name': 'TpmModel', 'enum_values': ['tpm-tis']}] -[]
Signature · 1 line
2.1.0
Re: [Qemu-devel] [PATCH v5 22/28] qapi: Whitelist commands that don't return dictionary
Quoted 46 lines · Eric Blake
...or an array of dictionaries. Although we have to cater to existing commands, returning a non-dictionary means the command is not extensible (no new name/value pairs can be added if more information must be returned in parallel). By making the whitelist explicit, any new command that falls foul of this practice will have to be self-documenting, which will encourage developers to either justify the action or rework the design to use a dictionary after all.
Signed-off-by Eric Blake <[email protected]>--- scripts/qapi.py | 30 ++++++++++++++++++++++++++++-- tests/qapi-schema/returns-alternate.err | 1 + tests/qapi-schema/returns-alternate.exit | 2 +- tests/qapi-schema/returns-alternate.json | 2 +- tests/qapi-schema/returns-alternate.out | 4 ---- tests/qapi-schema/returns-int.json | 3 ++- tests/qapi-schema/returns-int.out | 2 +- tests/qapi-schema/returns-whitelist.err | 1 + tests/qapi-schema/returns-whitelist.exit | 2 +- tests/qapi-schema/returns-whitelist.json | 2 +- tests/qapi-schema/returns-whitelist.out | 7 ------- 11 files changed, 37 insertions(+), 19 deletions(-)scripts/qapi.py +14
-0@@ -33,6 +33,30 @@ builtin_types = { 'size': 'QTYPE_QINT', } +# Whitelist of commands allowed to return a non-dictionary +returns_whitelist = [ + # From QMP: + 'human-monitor-command', + 'query-migrate-cache-size', + 'query-tpm-models', + 'query-tpm-types', + 'ringbuf-read', + + # From QGA: + 'guest-file-open', + 'guest-fsfreeze-freeze', + 'guest-fsfreeze-freeze-list', + 'guest-fsfreeze-status',
scripts/qapi.py builtin_types = { · line 59
Quoted 10 lines
scripts/qapi.py +10
-0+ 'guest-fsfreeze-thaw', + 'guest-get-time', + 'guest-set-vcpus', + 'guest-sync', + 'guest-sync-delimited', + + # From qapi-schema-test: + 'user_def_cmd3', +] +
Since there's just one whitelist, all schemata share it, and that means it's too permissive for each of them. Sloppy, but good enough.
If the sloppiness bothers us, here are two alternatives:
* Program takes the whitelist as argument, say
scripts/qapi-commands.py --legacy-returns qmp-legacy-returns ...
* Leave enforcing to C
If a command 'frobnicate' returns a non-dictionary, generate something like
#ifndef FROBNICATE_LEGACY_RETURN_OK
#error Command 'frobnicate' should return a dictionary
#endifThen manually define the macros necessary to keep the current use working in a suitable header.
Quoted 18 lines
scripts/qapi.py +4
-2enum_types = [] struct_types = [] union_types = []@@ -350,10 +374,12 @@ def check_command(expr, expr_info): check_type(expr_info, "'data' for command '%s'" % name, expr.get('data'), allowed_metas=['union', 'struct'], allow_optional=True) + returns_meta = ['union', 'struct'] + if name in returns_whitelist: + returns_meta += ['built-in', 'alternate', 'enum'] check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, - allowed_metas=['built-in', 'union', 'alternate', 'struct', - 'enum'], allow_optional=True) + allowed_metas=returns_meta, allow_optional=True) def check_event(expr, expr_info): global events
[...]
Re: [Qemu-devel] [PATCH v5 22/28] qapi: Whitelist commands that don't return dictionary
Quoted 11 lines · Markus Armbruster
Quoted 9 lines · Eric Blake
...or an array of dictionaries. Although we have to cater to existing commands, returning a non-dictionary means the command is not extensible (no new name/value pairs can be added if more information must be returned in parallel). By making the whitelist explicit, any new command that falls foul of this practice will have to be self-documenting, which will encourage developers to either justify the action or rework the design to use a dictionary after all.
Quoted 7 lines
Quoted 2 lines
Signed-off-by Eric Blake <[email protected]>---
Since there's just one whitelist, all schemata share it, and that means it's too permissive for each of them. Sloppy, but good enough.
If the sloppiness bothers us, here are two alternatives:
Doesn't bother me enough to use either alternative, but I _will_ update the commit message to at least remind someone of the potential for tightening things, should the need arise in the future.
Quoted 4 lines
* Program takes the whitelist as argument, say
scripts/qapi-commands.py--legacy-returns qmp-legacy-returns ...
Early exit (generator fails if you don't whitelist), but noisy (have to touch a Makefile in addition to the .json schema).
Quoted 6 lines
* Leave enforcing to C
If a command 'frobnicate' returns a non-dictionary, generate something like
Quoted 6 lines
#ifndef FROBNICATE_LEGACY_RETURN_OK #error Command 'frobnicate' should return a dictionary #endifThen manually define the macros necessary to keep the current use working in a suitable header.
Late exit (failure does not occur at python generation time, but only at C compilation time) - and the point of this series was to promote several late exits into early exits. But slightly cleaner than having to touch Makefiles to add in the whitelist.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v5 22/28] qapi: Whitelist commands that don't return dictionary
In reply to Eric BlakeQuoted 64 lines · Eric Blake
...or an array of dictionaries. Although we have to cater to existing commands, returning a non-dictionary means the command is not extensible (no new name/value pairs can be added if more information must be returned in parallel). By making the whitelist explicit, any new command that falls foul of this practice will have to be self-documenting, which will encourage developers to either justify the action or rework the design to use a dictionary after all.
Signed-off-by Eric Blake <[email protected]>--- scripts/qapi.py | 30 ++++++++++++++++++++++++++++-- tests/qapi-schema/returns-alternate.err | 1 + tests/qapi-schema/returns-alternate.exit | 2 +- tests/qapi-schema/returns-alternate.json | 2 +- tests/qapi-schema/returns-alternate.out | 4 ---- tests/qapi-schema/returns-int.json | 3 ++- tests/qapi-schema/returns-int.out | 2 +- tests/qapi-schema/returns-whitelist.err | 1 + tests/qapi-schema/returns-whitelist.exit | 2 +- tests/qapi-schema/returns-whitelist.json | 2 +- tests/qapi-schema/returns-whitelist.out | 7 ------- 11 files changed, 37 insertions(+), 19 deletions(-)scripts/qapi.py +25
-0@@ -33,6 +33,30 @@ builtin_types = { 'size': 'QTYPE_QINT', } +# Whitelist of commands allowed to return a non-dictionary +returns_whitelist = [ + # From QMP: + 'human-monitor-command', + 'query-migrate-cache-size', + 'query-tpm-models', + 'query-tpm-types', + 'ringbuf-read', + + # From QGA: + 'guest-file-open', + 'guest-fsfreeze-freeze', + 'guest-fsfreeze-freeze-list', + 'guest-fsfreeze-status', + 'guest-fsfreeze-thaw', + 'guest-get-time', + 'guest-set-vcpus', + 'guest-sync', + 'guest-sync-delimited', + + # From qapi-schema-test: + 'user_def_cmd3', +] + enum_types = [] struct_types = [] union_types = []@@ -350,10 +374,12 @@ def check_command(expr, expr_info): check_type(expr_info, "'data' for command '%s'" % name, expr.get('data'), allowed_metas=['union', 'struct'], allow_optional=True) + returns_meta = ['union', 'struct']
scripts/qapi.py def check_command(expr, expr_info): · line 385
Quoted 10 lines
scripts/qapi.py +3
-2+ if name in returns_whitelist: + returns_meta += ['built-in', 'alternate', 'enum'] check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, - allowed_metas=['built-in', 'union', 'alternate', 'struct', - 'enum'], allow_optional=True) + allowed_metas=returns_meta, allow_optional=True) def check_event(expr, expr_info): global events
[...]
Thinking on introspection, I started to wonder whether there's actually a command returning a union, yet. So I applied the appended stupid patch on top, and found the following commands returning (list of) non-struct type:
* qapi-schema.json:
'ringbuf-read' built-in type 'str' 'human-monitor-command' built-in type 'str' 'query-migrate-cache-size' built-in type 'int' 'query-tpm-models' enum type 'TpmModel' 'query-tpm-types' enum type 'TpmType' 'query-memory-devices' union type 'MemoryDeviceInfo'
* qga/qapi-schema.json:
'guest-sync-delimited' built-in type 'int' 'guest-sync' built-in type 'int' 'guest-get-time' built-in type 'int' 'guest-file-open' built-in type 'int' 'guest-fsfreeze-status' enum type 'GuestFsfreezeStatus' 'guest-fsfreeze-freeze' built-in type 'int' 'guest-fsfreeze-freeze-list' built-in type 'int' 'guest-fsfreeze-thaw' built-in type 'int' 'guest-set-vcpus' built-in type 'int'
The sole example for union is 'MemoryDeviceInfo'. It has one case %-}
scripts/qapi.py +7 -3
@@ -353,9 +353,12 @@ def check_type(expr_info, source, data, allow_array = False, "%s uses unknown type '%s'" % (source, data)) if not all_names[data] in allowed_metas: - raise QAPIExprError(expr_info, - "%s cannot use %s type '%s'" - % (source, all_names[data], data)) +# raise QAPIExprError(expr_info, +# "%s cannot use %s type '%s'" +# % (source, all_names[data], data)) + print >>sys.stderr, QAPIExprError(expr_info, + "%s cannot use %s type '%s'" + % (source, all_names[data], data)) return # data is a dictionary, check that each member is okay
@@ -387,6 +390,7 @@ def check_command(expr, expr_info): returns_meta = ['union', 'struct'] if name in returns_whitelist: returns_meta += ['built-in', 'alternate', 'enum'] + returns_meta = ['struct'] check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, allowed_metas=returns_meta, allow_optional=True,
Re: [Qemu-devel] [PATCH v5 22/28] qapi: Whitelist commands that don't return dictionary
Quoted 21 lines · Markus Armbruster
Quoted 11 lines · Eric Blake
...or an array of dictionaries. Although we have to cater to existing commands, returning a non-dictionary means the command is not extensible (no new name/value pairs can be added if more information must be returned in parallel). By making the whitelist explicit, any new command that falls foul of this practice will have to be self-documenting, which will encourage developers to either justify the action or rework the design to use a dictionary after all.
Signed-off-by Eric Blake <[email protected]>---
Thinking on introspection, I started to wonder whether there's actually a command returning a union, yet. So I applied the appended stupid patch on top, and found the following commands returning (list of) non-struct type:
Quoted 6 lines
* qapi-schema.json:
'ringbuf-read' built-in type 'str' 'human-monitor-command' built-in type 'str' 'query-migrate-cache-size' built-in type 'int' 'query-tpm-models' enum type 'TpmModel'
More precisely, "array of enum type 'TpmModel'" (or "list", depending on whether we go with JSON array/object terminology, or QObject dict/list).
I wonder if it is worth trying to tweak the error message to more
precisely track when I strip away the [] earlier in check_type to still report sane messages about 'array of ...' if a later check fails.
Quoted 5 lines
'query-tpm-types' enum type 'TpmType'
'query-memory-devices' union type 'MemoryDeviceInfo'*
qga/qapi-schema.json:
Quoted 9 lines
'guest-sync-delimited' built-in type 'int' 'guest-sync' built-in type 'int' 'guest-get-time' built-in type 'int' 'guest-file-open' built-in type 'int' 'guest-fsfreeze-status' enum type 'GuestFsfreezeStatus' 'guest-fsfreeze-freeze' built-in type 'int' 'guest-fsfreeze-freeze-list' built-in type 'int' 'guest-fsfreeze-thaw' built-in type 'int' 'guest-set-vcpus' built-in type 'int'
Good - your patch found all of my whitelists, plus...
Quoted 2 lines
The sole example for union is 'MemoryDeviceInfo'. It has one case %-}
Yeah, MemoryDeviceInfo as a union currently has only one type, but it was done that way in case we add other memory devices. So it was actually quite forward-thinking.
...one additional thing. But returning (an array of) a union should be okay (it is a dictionary, and therefore extensible); this patch was only about flagging non-dictionaries.
[side note: again, my idea of renaming 'type' into 'struct' in the .json files would make it easier to talk about "complex types" as the set of "struct" and "union" types, rather than the current confusion of deciding if "type" means all meta-types or just struct meta-types.]
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
Re: [Qemu-devel] [PATCH v5 22/28] qapi: Whitelist commands that don't return dictionary
Quoted 29 lines · Eric Blake
Quoted 21 lines · Markus Armbruster
Quoted 11 lines · Eric Blake
...or an array of dictionaries. Although we have to cater to existing commands, returning a non-dictionary means the command is not extensible (no new name/value pairs can be added if more information must be returned in parallel). By making the whitelist explicit, any new command that falls foul of this practice will have to be self-documenting, which will encourage developers to either justify the action or rework the design to use a dictionary after all.
Signed-off-by Eric Blake <[email protected]>---
Thinking on introspection, I started to wonder whether there's actually a command returning a union, yet. So I applied the appended stupid patch on top, and found the following commands returning (list of) non-struct type:
Quoted 6 lines
* qapi-schema.json:
'ringbuf-read' built-in type 'str' 'human-monitor-command' built-in type 'str' 'query-migrate-cache-size' built-in type 'int' 'query-tpm-models' enum type 'TpmModel'
Quoted 5 lines
More precisely, "array of enum type 'TpmModel'" (or "list", depending on whether we go with JSON array/object terminology, or QObject dict/list).
I wonder if it is worth trying to tweak the error message to more
precisely track when I strip away the [] earlier incheck_typeto still report sane messages about 'array of ...' if a later check fails.
I figure the error message is understandable enough as is. But if it improving it would be easy, then why not. Could be done on top.
Quoted 24 lines
Quoted 5 lines
'query-tpm-types' enum type 'TpmType'
'query-memory-devices' union type 'MemoryDeviceInfo'*
qga/qapi-schema.json:Quoted 9 lines
'guest-sync-delimited' built-in type 'int' 'guest-sync' built-in type 'int' 'guest-get-time' built-in type 'int' 'guest-file-open' built-in type 'int' 'guest-fsfreeze-status' enum type 'GuestFsfreezeStatus' 'guest-fsfreeze-freeze' built-in type 'int' 'guest-fsfreeze-freeze-list' built-in type 'int' 'guest-fsfreeze-thaw' built-in type 'int' 'guest-set-vcpus' built-in type 'int'Good - your patch found all of my whitelists, plus...
Quoted 2 lines
The sole example for union is 'MemoryDeviceInfo'. It has one case %-}
Yeah, MemoryDeviceInfo as a union currently has only one type, but it was done that way in case we add other memory devices. So it was actually quite forward-thinking.
Quoted 8 lines
...one additional thing. But returning (an array of) a union should be okay (it is a dictionary, and therefore extensible); this patch was only about flagging non-dictionaries.
[side note: again, my idea of renaming 'type' into 'struct' in the .json files would make it easier to talk about "complex types" as the set of "struct" and "union" types, rather than the current confusion of deciding if "type" means all meta-types or just struct meta-types.]
Yes.
PATCH v5 23/28 qapi: More rigorous checking for type safety bypass
In reply to Eric BlakeNow 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, as well as 'gen':false as the canonical spelling for requesting type bypass.
--- scripts/qapi.py | 23 ++++++++++++++++++----- 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, 24 insertions(+), 15 deletions(-)
scripts/qapi.py +18 -5
@@ -321,13 +321,14 @@ def check_name(expr_info, source, name, allow_optional = False): "%s uses invalid name '%s'" % (source, name)) def check_type(expr_info, source, data, allow_array = False, - allowed_metas = [], allow_dict = True, allow_optional = False): + allowed_metas = [], allow_dict = True, allow_optional = False, + allow_star = False): global all_names if data is None: return - if data == '**': + if allow_star and data == '**': return # Check if array type for data is okay
@@ -343,6 +344,10 @@ def check_type(expr_info, source, data, allow_array = False, # Check if type name for data is okay if isinstance(data, str): + if data == '**': + raise QAPIExprError(expr_info, + "%s uses '**' but did not request 'gen':false" + % source) if not data in all_names: raise QAPIExprError(expr_info, "%s uses unknown type '%s'"
@@ -367,19 +372,23 @@ def check_type(expr_info, source, data, allow_array = False, allow_array=True, allowed_metas=['built-in', 'union', 'alternate', 'struct', 'enum'], - allow_dict=True, allow_optional=True) + allow_dict=True, allow_optional=True, allow_star=allow_star) def check_command(expr, expr_info): name = expr['command'] + allow_star = expr.has_key('gen') + check_type(expr_info, "'data' for command '%s'" % name, expr.get('data'), - allowed_metas=['union', 'struct'], allow_optional=True) + allowed_metas=['union', 'struct'], allow_optional=True, + allow_star=allow_star) returns_meta = ['union', 'struct'] if name in returns_whitelist: returns_meta += ['built-in', 'alternate', 'enum'] check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, - allowed_metas=returns_meta, allow_optional=True) + allowed_metas=returns_meta, allow_optional=True, + allow_star=allow_star) def check_event(expr, expr_info): global events
@@ -574,6 +583,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 != False: + raise QAPIExprError(info, + "'%s' of %s '%s' should only use false value" + % (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
@@ -0,0 +1 @@ +tests/qapi-schema/type-bypass-bad-gen.json:2: 'gen' of command 'foo' should only use false value
tests/qapi-schema/type-bypass-bad-gen.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/type-bypass-bad-gen.json +1 -1
@@ -1,2 +1,2 @@ -# FIXME: 'gen' should only appear with value false +# 'gen' should only appear with value false { 'command': 'foo', 'gen': 'whatever' }
tests/qapi-schema/type-bypass-bad-gen.out +0 -3
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'foo'), ('gen', 'whatever')])] -[] -[]
tests/qapi-schema/type-bypass-no-gen.err +1 -0
@@ -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':false
tests/qapi-schema/type-bypass-no-gen.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/type-bypass-no-gen.json +1 -1
@@ -1,2 +1,2 @@ -# FIXME: type bypass should only work with 'gen':false +# type bypass only works with 'gen':'no' { 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**' }
tests/qapi-schema/type-bypass-no-gen.out +0 -3
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**')])] -[] -[]
Signature · 1 line
2.1.0
Re: [Qemu-devel] [PATCH v5 23/28] qapi: More rigorous checking for type safety bypass
Quoted 34 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, as well as 'gen':false as the canonical spelling for requesting type bypass.
Signed-off-by Eric Blake <[email protected]>--- scripts/qapi.py | 23 ++++++++++++++++++----- 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, 24 insertions(+), 15 deletions(-)scripts/qapi.py +2
-1@@ -321,13 +321,14 @@ def check_name(expr_info, source, name, allow_optional = False): "%s uses invalid name '%s'" % (source, name)) def check_type(expr_info, source, data, allow_array = False, - allowed_metas = [], allow_dict = True, allow_optional = False): + allowed_metas = [], allow_dict = True, allow_optional = False, + allow_star = False):
scripts/qapi.py def check_name(expr_info, source, name, allow_optional = False): · line 334
Quoted 10 lines
scripts/qapi.py +1
-1global all_names if data is None: return - if data == '**': + if allow_star and data == '**': return # Check if array type for data is okay
Aha! Takes us back to my question on PATCH 21.
State so far: check_name() accepts '**', but some of its callers reject it. Whether it's rejected everywhere we don't want it isn't obvious, even if we add rejects that are currently missing.
Perhaps we should try to do this the other way round: require extra code in places where we want to accept it.
I can accept this as is, because it's an improvement, and we can plug remaining holes on top.
Quoted 96 lines
scripts/qapi.py +15
-3@@ -343,6 +344,10 @@ def check_type(expr_info, source, data, allow_array = False, # Check if type name for data is okay if isinstance(data, str): + if data == '**': + raise QAPIExprError(expr_info, + "%s uses '**' but did not request 'gen':false" + % source) if not data in all_names: raise QAPIExprError(expr_info, "%s uses unknown type '%s'"@@ -367,19 +372,23 @@ def check_type(expr_info, source, data, allow_array = False, allow_array=True, allowed_metas=['built-in', 'union', 'alternate', 'struct', 'enum'], - allow_dict=True, allow_optional=True) + allow_dict=True, allow_optional=True, allow_star=allow_star) def check_command(expr, expr_info): name = expr['command'] + allow_star = expr.has_key('gen') + check_type(expr_info, "'data' for command '%s'" % name, expr.get('data'), - allowed_metas=['union', 'struct'], allow_optional=True) + allowed_metas=['union', 'struct'], allow_optional=True, + allow_star=allow_star) returns_meta = ['union', 'struct'] if name in returns_whitelist: returns_meta += ['built-in', 'alternate', 'enum'] check_type(expr_info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, - allowed_metas=returns_meta, allow_optional=True) + allowed_metas=returns_meta, allow_optional=True, + allow_star=allow_star) def check_event(expr, expr_info): global events@@ -574,6 +583,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 != False: + raise QAPIExprError(info, + "'%s' of %s '%s' should only use false value" + % (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@@ -0,0 +1 @@ +tests/qapi-schema/type-bypass-bad-gen.json:2: 'gen' of command 'foo' should only use false valuetests/qapi-schema/type-bypass-bad-gen.exit +1
-1@@ -1 +1 @@ -0 +1tests/qapi-schema/type-bypass-bad-gen.json +1
-1@@ -1,2 +1,2 @@ -# FIXME: 'gen' should only appear with value false +# 'gen' should only appear with value false { 'command': 'foo', 'gen': 'whatever' }tests/qapi-schema/type-bypass-bad-gen.out +0
-3@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'foo'), ('gen', 'whatever')])] -[] -[]tests/qapi-schema/type-bypass-no-gen.err +1
-0@@ -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':falsetests/qapi-schema/type-bypass-no-gen.exit +1
-1@@ -1 +1 @@ -0 +1tests/qapi-schema/type-bypass-no-gen.json +0
-0
tests/qapi-schema/type-bypass-no-gen.json line 1
Quoted 2 lines
tests/qapi-schema/type-bypass-no-gen.json +1
-1@@ -1,2 +1,2 @@ -# FIXME: type bypass should only work with 'gen':false +# type bypass only works with 'gen':'no'
'gen': false
tests/qapi-schema/type-bypass-no-gen.out line 3
Quoted 9 lines
tests/qapi-schema/type-bypass-no-gen.json +0
-0{ 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**' }tests/qapi-schema/type-bypass-no-gen.out +0
-3@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**')])] -[] -[]
With the trivial fix in type-bypass-no-gen.json:
PATCH v5 24/28 qapi: Merge UserDefTwo and UserDefNested in tests
In reply to Eric BlakeIn 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 inline nested types in QAPI; it means that the type is now boxed instead of unboxed in C code, but has no difference to the QMP wire protocol. 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 | 17 ++++---- tests/test-qmp-input-visitor.c | 17 ++++---- tests/test-qmp-output-visitor.c | 48 +++++++++++----------- tests/test-visitor-serialization.c | 71 +++++++++++++++++---------------- 7 files changed, 100 insertions(+), 101 deletions(-)
tests/qapi-schema/qapi-schema-test.json +2 -8
@@ -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
@@ -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([('type', 'UserDefC'), ('data', OrderedDict([('string1', 'str'), ('string2', 'str')]))]),
@@ -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', 'UserDefC'), ('data', OrderedDict([('string1', 'str'), ('string2', 'str')]))]),
tests/test-qmp-commands.c +16 -16
@@ -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 +10 -7
@@ -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 +10 -7
@@ -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 +24 -24
98 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
2.1.0
Re: [Qemu-devel] [PATCH v5 24/28] qapi: Merge UserDefTwo and UserDefNested in tests
Quoted 7 lines · 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 inline nested types in QAPI; it means that the type is now boxed instead of unboxed in C code, but has no difference to the QMP wire protocol.
I can't see a change from boxed to unboxed in this patch. Does the remark apply to the elimination of nested types? If yes, it's premature here.
Quoted 3 lines
When touching code to add new allocations, also
convert existing allocations to consistently prefer typesafeg_new0overg_malloc0.
I can't see any change from g_malloc0() to g_new0(). Is this stale?
Quoted 4 lines
Ensure that 'make check-qapi-schema check-unit' still passes.
Signed-off-by Eric Blake <[email protected]>
Re: [Qemu-devel] [PATCH v5 24/28] qapi: Merge UserDefTwo and UserDefNested in tests
Quoted 10 lines · Markus Armbruster
Quoted 7 lines · 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 inline nested types in QAPI; it means that the type is now boxed instead of unboxed in C code, but has no difference to the QMP wire protocol.
Quoted 3 lines
I can't see a change from boxed to unboxed in this patch. Does the remark apply to the elimination of nested types? If yes, it's premature here.
May be a stale comment; either as the result of too much copy-and-paste between similar patches 25 and 26, or as the result of begin first written last September and several of your tree cleanups hitting the git repo in the meantime. I'll clean up the commit wording in v6.
Quoted 13 lines
Quoted 4 lines
When touching code to add new allocations, also
convert existing allocations to consistently prefer typesafeg_new0overg_malloc0.I can't see any change from
g_malloc0()tog_new0(). Is this stale?Quoted 4 lines
Ensure that 'make check-qapi-schema check-unit' still passes.
Signed-off-by Eric Blake <[email protected]>
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
PATCH v5 25/28 qapi: Drop tests for inline nested structs
In reply to Eric BlakeA 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 nested structs conflicts with that goal. This patch fixes the testsuite to avoid inline nested types, by breaking the nesting into explicit types; it means that the type is now boxed instead of unboxed in C code, but makes no difference on the wire. 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
@@ -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
@@ -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([('type', 'UserDefC'), ('data', OrderedDict([('string1', 'str'), ('string2', 'str')]))]),
@@ -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', 'UserDefC'), ('data', OrderedDict([('string1', 'str'), ('string2', 'str')]))]),
tests/test-qmp-commands.c +10 -7
@@ -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
@@ -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
2.1.0
Re: [Qemu-devel] [PATCH v5 25/28] qapi: Drop tests for inline nested structs
Quoted 3 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 nested structs conflicts with that goal.
I'm okay with this rationale as is, just want to mention the more general motivation again: we want to make the schema language extensible.
A definition in the schema associates a name with a set of properties in a certain lexical environment.
Example 1: { 'type': 'Foo', 'data': { MEMBERS... } }
at the top level associates global name 'Foo' with properties (meta-type struct) and MEMBERS...
Example 2: 'mumble': TYPE
within the MEMBERS... above associates 'mumble' with properties (type TYPE) and (optional false) within type Foo.
The syntax in example 1 is extensible: when we need another property, we can add another member, just like we added 'base'.
The syntax in example 2 isn't extensible that way, because the right hand side can only be a type.
Property optional is encoded in the name: "'*mumble': 'int'" associates 'mumble' with (type int) and (optional true). Convenient, but won't scale.
What we want to do is change the core syntax to
NAME: { 'type': TYPE }with syntactic sugar
NAME: TYPE --> NAME: { 'type': TYPE, 'optional': false }
*ONAME: TYPE --> ONAME: { 'type': TYPE, 'optional': true }where *ONAME is a string starting with '*', and ONAME its tail.
Now we can extend by adding another member.
Naturally, the schema will mostly be written in the sugared form.
Adding optional defaults is an instance of this general "extend the schema language" pattern.
Feel free to crib from the above if you want more of the motivation in the commit log,
Quoted 4 lines
This patch fixes the testsuite to avoid inline nested types, by breaking the nesting into explicit types; it means that the type is now boxed instead of unboxed in C code, but makes no difference on the wire.
Yes, this patch actually adds boxing.
The QAPI code generator boxes too much for my taste, but this series is not the place to mess with that.
Quoted 3 lines
When touching code to add new allocations, also
convert existing allocations to consistently prefer typesafeg_new0overg_malloc0.
Again, I can't see new uses of g_new0().
Quoted 35 lines
Signed-off-by Eric Blake <[email protected]>--- 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@@ -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',
[...]
Quoted 5 lines
tests/test-qmp-commands.c +0
-0
tests/test-qmp-commands.c UserDefTwo *qmp_user_def_cmd2(UserDefOne *ud1a, · line 36
Quoted 10 lines
tests/test-qmp-commands.c +1
-6@@ -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));
Hmm, you could g_new0(UserDefTwoDict) here. More of the same below, and in the previous patch.
tests/test-qmp-commands.c UserDefTwo *qmp_user_def_cmd2(UserDefOne *ud1a, · line 47
Quoted 11 lines
tests/test-qmp-commands.c +8
-0+ 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; }
[...]
With either the commit message corrected not to claim use of g_new0(), or the patch updated to actually do it:
PATCH v5 26/28 qapi: Drop inline nested type in query-version
In reply to Eric BlakeA 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 nested structs conflicts with that goal. This patch fixes one of only two commands relying on nested types, by breaking the nesting into an explicit type; it means that the type is now boxed instead of unboxed in C code, but 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
@@ -60,7 +60,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
@@ -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.4 +## +{ '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
@@ -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
2.1.0
Re: [Qemu-devel] [PATCH v5 26/28] qapi: Drop inline nested type in query-version
Quoted 11 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 nested structs conflicts with that goal. This patch fixes one of only two commands relying on nested types, by breaking the nesting into an explicit type; it means that the type is now boxed instead of unboxed in C code, but the QMP wire format is unaffected by this change.
Prefer the safer
g_new0()while making the conversion.Signed-off-by Eric Blake <[email protected]>
PATCH v5 27/28 qapi: Drop inline nested types in query-pci
In reply to Eric BlakeA 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 nested structs conflicts with that goal. This patch fixes one of only two commands relying on nested types, by breaking the nesting into an explicit type; it means that the type is now boxed instead of unboxed in C code, but 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
@@ -648,14 +648,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);
@@ -663,25 +663,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
2.1.0
Re: [Qemu-devel] [PATCH v5 27/28] qapi: Drop inline nested types in query-pci
Quoted 8 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 nested structs conflicts with that goal. This patch fixes one of only two commands relying on nested types, by breaking the nesting into an explicit type; it means that the type is now boxed instead of unboxed in C code, but the QMP wire format is unaffected by this change.
Quoted 4 lines
Prefer the safer
g_new0()while making the conversion, and reduce some long lines.Signed-off-by Eric Blake <[email protected]>
PATCH v5 28/28 qapi: Drop support for inline nested types
In reply to Eric BlakeA 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 nested structs conflicts with that goal. Now that all commands have been changed to avoid inline nested structs, 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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -368,11 +368,13 @@ def check_type(expr_info, source, data, allow_array = False, for (key, value) in data.items(): check_name(expr_info, "Member of %s" % source, key, allow_optional=allow_optional) + # 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_metas=['built-in', 'union', 'alternate', 'struct', 'enum'], - allow_dict=True, allow_optional=True, allow_star=allow_star) + allow_dict=False, allow_star=allow_star) def check_command(expr, expr_info): name = expr['command']
@@ -404,13 +406,6 @@ def check_event(expr, expr_info): check_type(expr_info, "'data' for event '%s'" % name, expr.get('data'), allowed_metas=['union', 'struct'], allow_optional=True) - 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']
@@ -667,13 +662,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
@@ -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
@@ -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
@@ -1 +1 @@ -0 +1
tests/qapi-schema/nested-struct-data.json +1 -1
@@ -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
@@ -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
@@ -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
@@ -1 +1 @@ -0 +1
tests/qapi-schema/nested-struct-returns.json +1 -1
@@ -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
@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'foo'), ('returns', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')]))])] -[] -[]
Signature · 1 line
2.1.0
Re: [Qemu-devel] [PATCH v5 28/28] qapi: Drop support for inline nested types
Quoted 182 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 nested structs conflicts with that goal. Now that all commands have been changed to avoid inline nested structs, nuke support for them, and turn it into a hard error. Update the testsuite to reflect tighter parsing rules.
Signed-off-by Eric Blake <[email protected]>--- 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@@ -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@@ -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@@ -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@@ -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 +0
-0@@ -368,11 +368,13 @@ def check_type(expr_info, source, data, allow_array = False, for (key, value) in data.items():
scripts/qapi.py def check_type(expr_info, source, data, allow_array = False, · line 377
Quoted 10 lines
scripts/qapi.py +3
-1check_name(expr_info, "Member of %s" % source, key, allow_optional=allow_optional) + # 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_metas=['built-in', 'union', 'alternate', 'struct', 'enum'], - allow_dict=True, allow_optional=True, allow_star=allow_star) + allow_dict=False, allow_star=allow_star)
check_type() uses allow_optional only when allow_dict. Okay.
Quoted 59 lines
scripts/qapi.py +3
-11def check_command(expr, expr_info): name = expr['command']@@ -404,13 +406,6 @@ def check_event(expr, expr_info): check_type(expr_info, "'data' for event '%s'" % name, expr.get('data'), allowed_metas=['union', 'struct'], allow_optional=True) - 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']@@ -667,13 +662,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@@ -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 nametests/qapi-schema/nested-struct-data.err +1
-0@@ -0,0 +1 @@ +tests/qapi-schema/nested-struct-data.json:2: Member 'a' of 'data' for command 'foo' should be a type nametests/qapi-schema/nested-struct-data.exit +1
-1@@ -1 +1 @@ -0 +1tests/qapi-schema/nested-struct-data.json +0
-0
tests/qapi-schema/nested-struct-data.json line 1
Quoted 1 line
tests/qapi-schema/nested-struct-data.json +0
-1@@ -1,4 +1,4 @@ -# FIXME: inline subtypes collide with our desired future use of defaults
Seen only now: I'd mark this TODO rather than FIXME in PATCH 19, because it's not actually broken. Only if you respin anyway, of course.
Quoted 39 lines
tests/qapi-schema/nested-struct-data.json +1
-0+# 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@@ -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@@ -0,0 +1 @@ +tests/qapi-schema/nested-struct-returns.json:2: Member 'a' of 'returns' for command 'foo' should be a type nametests/qapi-schema/nested-struct-returns.exit +1
-1@@ -1 +1 @@ -0 +1tests/qapi-schema/nested-struct-returns.json +1
-1@@ -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
-0
tests/qapi-schema/nested-struct-returns.out line 3
Quoted 3 lines
tests/qapi-schema/nested-struct-returns.out +0
-3@@ -1,3 +0,0 @@ -[OrderedDict([('command', 'foo'), ('returns', OrderedDict([('a', OrderedDict([('string', 'str'), ('integer', 'int')])), ('b', 'str')]))])] -[] -[]
Quoted 22 lines · Eric Blake
After several months of sitting on this, I finally made progress on it. Let's get it in 2.4, and I promise to kick out a v6 (if needed) with much less delay.
We want to eventually allow qapi defaults, by making:
'data':{'*flag':'bool'}
shorthand for:
'data':{'flag':{'type':'bool', 'optional':true}}
so that the default can be specified:
'data':{'flag':{'type':'bool', 'optional':true, 'default':true}}This series does not quite get us there, but it DOES do a number of other things. It gets rid of the three uses of nested inline structs, changes anonymous unions to use a specific 'alternate' metatype rather than abusing 'union', and fixes lots of other parser bugs found while designing the testsuite. The testsuite changes make the bulk of this series, with a repeating pattern of writing tests that expose weaknesses in the old parser, then beefing up the generator to catch the problem during the initial parse rather than choking with an obscure python message or even causing a C compilation failure.
Quoted 8 lines
v4 was here:
https://lists.gnu.org/archive/html/qemu-devel/2014-09/msg04022.htmlChanges since then: lots of refactoring; 8 new commits; lots of testsuite additions; address Markus' review comments where I could. However, so much has changed, and so much time elapsed, that it is probably easier to just review this series fresh than to try and compare it to earlier versions.
Okay, I'm through. I like it well, and I think it's really close. There are a few questions / ideas you haven't replied to already in PATCH 21ff. With those conversations wrapped up, I may well agree to taking the series as is, but I think I'd prefer a *conservative* respin addressing stuff that doesn't need new testing, like commit messages and comments, and *selected* (by you) improvments that do need new testing.
What happens when I define a member key multiple times in a struct or union type?
If I do it directly, the parser rejects the duplicate key in get_members(). Covered by tests/qapi-schema/duplicate-key.json.
What if I hide the duplicate in a base type?
If I stick this into qapi-schema-test.json:
{ 'type': 'Base', 'data': { 'foo': 'str', 'bar': 'str' } }
{ 'type': 'Clash', 'base': 'Base', 'data': { 'foo': 'int' } }
{ 'command': 'clash', 'data': 'Clash' }the resulting test-qmp-commands.h declares qmp_clash(), but test-qmp-marshal.c doesn't define it. WTF?!?
Quoted 8 lines · Markus Armbruster
What happens when I define a member key multiple times in a struct or union type?
If I do it directly, the parser rejects the duplicate key in
get_members(). Covered bytests/qapi-schema/duplicate-key.json.What if I hide the duplicate in a base type?
Quoted 8 lines
If I stick this into qapi-schema-test.json:
{ 'type': 'Base', 'data': { 'foo': 'str', 'bar': 'str' } } { 'type': 'Clash', 'base': 'Base', 'data': { 'foo': 'int' } } { 'command': 'clash', 'data': 'Clash' }the resulting
test-qmp-commands.hdeclaresqmp_clash(), buttest-qmp-marshal.cdoesn't define it. WTF?!?
Nice test; I'll see if I can add a patch on to the end of the series to flag it. I suspect flat unions have potential for the same issue.
Signature · 2 lines
Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org