qapi: Schema language cleanups & doc improvements
v2 cover qapi: Schema language cleanups & doc improvements
v2:
* PATCH v1 05: Dropped
* PATCH 01,05,07-11,16: New
* PATCH 03:
- Commit message typo fixed
- Assertions tightened
* PATCH 04:
- Document member name 'u' is reserved
- Drop an accidental change to section "Enumeration types"
- Typo fixed
* PATCH 06:
- Outlaw anything but printable ASCII, not just control characters
* PATCH 15:
- Adopt more convenient terminology: directive, definition
- Explanation of grammar notation missed grouping
- Drop a more text redundant with the grammar
- Drop more text redundant with section "Naming rules and reserved names"
- Turn "boxed needs data: STRING" into syntax
- Improve section "Documentation comments" some more
- Minor phrasing tweaks
Markus Armbruster (16):
scripts/git.orderfile: Match QAPI schema more precisely
qapi: Drop check_type()'s redundant parameter @allow_optional
qapi: Drop support for boxed alternate arguments docs/devel/qapi-code-gen: Minor specification fixes tests/qapi-schema: Demonstrate bad reporting of funny characters
qapi: Restrict strings to printable ASCII
qapi: Drop support for escape sequences other than \\
qapi: Permit 'boxed' with empty type
qapi: Permit alternates with just one branch
qapi: Permit omitting all flat union branches
qapi: Adjust frontend errors to say enum value, not member docs/devel/qapi-code-gen: Reorder sections for readability docs/devel/qapi-code-gen: Rewrite compatibility considerations docs/devel/qapi-code-gen: Rewrite introduction to schema docs/devel/qapi-code-gen: Improve QAPI schema language doc
qapi: Tweak code to match docs/devel/qapi-code-gen.txt
docs/devel/qapi-code-gen.txt | 1068 ++++++++++-------
tests/test-qmp-cmds.c | 4 +
scripts/git.orderfile | 4 +-
scripts/qapi/commands.py | 4 +-
scripts/qapi/common.py | 144 +--
scripts/qapi/events.py | 10 +-
tests/Makefile.include | 7 +-
tests/qapi-schema/alternate-empty.err | 2 +-
tests/qapi-schema/alternate-empty.json | 4 +-
tests/qapi-schema/args-boxed-empty.err | 1 -
tests/qapi-schema/args-boxed-empty.json | 3 -
tests/qapi-schema/args-invalid.err | 2 +-
tests/qapi-schema/doc-missing.err | 2 +-
tests/qapi-schema/doc-no-symbol.err | 2 +-
tests/qapi-schema/enum-bad-name.err | 2 +-
tests/qapi-schema/enum-bad-name.json | 3 +-
tests/qapi-schema/enum-clash-member.err | 2 +-
.../qapi-schema/enum-dict-member-unknown.err | 2 +-
tests/qapi-schema/enum-member-case.err | 2 +-
tests/qapi-schema/escape-outside-string.err | 1 -
tests/qapi-schema/escape-outside-string.json | 3 -
tests/qapi-schema/escape-too-big.err | 1 -
tests/qapi-schema/escape-too-big.exit | 1 -
tests/qapi-schema/escape-too-big.json | 3 -
tests/qapi-schema/escape-too-big.out | 0
tests/qapi-schema/escape-too-short.err | 1 -
tests/qapi-schema/escape-too-short.exit | 1 -
tests/qapi-schema/escape-too-short.json | 3 -
tests/qapi-schema/escape-too-short.out | 0
tests/qapi-schema/flat-union-empty.err | 2 +-
tests/qapi-schema/flat-union-empty.json | 2 +-
tests/qapi-schema/ident-with-escape.err | 1 +
tests/qapi-schema/ident-with-escape.exit | 2 +-
tests/qapi-schema/ident-with-escape.json | 2 +-
tests/qapi-schema/ident-with-escape.out | 16 -
tests/qapi-schema/pragma-non-dict.err | 2 +-
tests/qapi-schema/qapi-schema-test.json | 13 +-
tests/qapi-schema/qapi-schema-test.out | 21 +-
tests/qapi-schema/string-code-point-127.err | 1 +
...-empty.exit => string-code-point-127.exit} | 0
tests/qapi-schema/string-code-point-127.json | 2 +
...ed-empty.out => string-code-point-127.out} | 0
tests/qapi-schema/string-code-point-31.err | 1 +
...-string.exit => string-code-point-31.exit} | 0
tests/qapi-schema/string-code-point-31.json | 2 +
...de-string.out => string-code-point-31.out} | 0
tests/qapi-schema/struct-data-invalid.err | 2 +-
tests/qapi-schema/unicode-str.err | 1 -
tests/qapi-schema/unicode-str.exit | 1 -
tests/qapi-schema/unicode-str.json | 2 -
tests/qapi-schema/unicode-str.out | 0
tests/qapi-schema/union-empty.err | 2 +-
tests/qapi-schema/union-empty.json | 2 +-
tests/qapi-schema/unknown-escape.json | 2 +-
54 files changed, 737 insertions(+), 624 deletions(-)
delete mode 100644 tests/qapi-schema/args-boxed-empty.err
delete mode 100644 tests/qapi-schema/args-boxed-empty.json
delete mode 100644 tests/qapi-schema/escape-outside-string.err
delete mode 100644 tests/qapi-schema/escape-outside-string.json
delete mode 100644 tests/qapi-schema/escape-too-big.err
delete mode 100644 tests/qapi-schema/escape-too-big.exit
delete mode 100644 tests/qapi-schema/escape-too-big.json
delete mode 100644 tests/qapi-schema/escape-too-big.out
delete mode 100644 tests/qapi-schema/escape-too-short.err
delete mode 100644 tests/qapi-schema/escape-too-short.exit
delete mode 100644 tests/qapi-schema/escape-too-short.json
delete mode 100644 tests/qapi-schema/escape-too-short.out
create mode 100644 tests/qapi-schema/string-code-point-127.err
rename tests/qapi-schema/{args-boxed-empty.exit => string-code-point-127.exit} (100%)
create mode 100644 tests/qapi-schema/string-code-point-127.json
rename tests/qapi-schema/{args-boxed-empty.out => string-code-point-127.out} (100%)
create mode 100644 tests/qapi-schema/string-code-point-31.err
rename tests/qapi-schema/{escape-outside-string.exit => string-code-point-31.exit} (100%)
create mode 100644 tests/qapi-schema/string-code-point-31.json
rename tests/qapi-schema/{escape-outside-string.out => string-code-point-31.out} (100%)
delete mode 100644 tests/qapi-schema/unicode-str.err
delete mode 100644 tests/qapi-schema/unicode-str.exit
delete mode 100644 tests/qapi-schema/unicode-str.json
delete mode 100644 tests/qapi-schema/unicode-str.outSignature · 1 line
2.21.0
PATCH v2 1/16 scripts/git.orderfile: Match QAPI schema more precisely
Pattern *.json also matches the tests/qapi-schema/*.json. Separates them from the tests/qapi-schema/*.{err,exit,out} in diffs. I hate that. Change the pattern to match just the "real" QAPI schemata.
--- scripts/git.orderfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
scripts/git.orderfile +2 -2
@@ -19,11 +19,11 @@ Makefile* *.mak # qapi schema -*.json +qapi/*.json +qga/*.json # headers *.h # code *.c -
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 01/16] scripts/git.orderfile: Match QAPI schema more precisely
Quoted 18 lines · Markus Armbruster
Pattern *.json also matches the tests/qapi-schema/*.json. Separates them from the tests/qapi-schema/*.{err,exit,out} in diffs. I hate that. Change the pattern to match just the "real" QAPI schemata.
Signed-off-by Markus Armbruster <[email protected]>--- scripts/git.orderfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)scripts/git.orderfile +0
-0@@ -19,11 +19,11 @@ Makefile* *.mak # qapi schema
scripts/git.orderfile Makefile* · line 29
Quoted 10 lines
scripts/git.orderfile +2
-2-*.json +qapi/*.json +qga/*.json # headers *.h # code *.c -
Re: [Qemu-devel] [PATCH v2 01/16] scripts/git.orderfile: Match QAPI schema more precisely
In reply to Markus ArmbrusterQuoted 9 lines · Markus Armbruster
Pattern *.json also matches the tests/qapi-schema/*.json. Separates them from the tests/qapi-schema/*.{err,exit,out} in diffs. I hate that. Change the pattern to match just the "real" QAPI schemata.
Signed-off-by Markus Armbruster <[email protected]>--- scripts/git.orderfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
Should we ever do a mass rename of *.json into *.qapi (since our qapi files are NOT quite JSON)? But that doesn't change the viability of this patch.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 01/16] scripts/git.orderfile: Match QAPI schema more precisely
Quoted 11 lines · Eric Blake
Quoted 9 lines · Markus Armbruster
Pattern *.json also matches the tests/qapi-schema/*.json. Separates them from the tests/qapi-schema/*.{err,exit,out} in diffs. I hate that. Change the pattern to match just the "real" QAPI schemata.
Signed-off-by Markus Armbruster <[email protected]>--- scripts/git.orderfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
Quoted 3 lines
Should we ever do a mass rename of *.json into *.qapi (since our qapi files are NOT quite JSON)? But that doesn't change the viability of this patch.
Naming them .json is misleading. We're closer to Python than to JSON. Many .json files ask Emacs for Python mode, because that works better than JavaScript mode.
Options:
* Rename to .qapi. The files that don't ask for Python mode now get Fundamental mode instead of JavaScript mode. Minor regression.
* Rename to .py, and drop the lines asking for Python mode. Still misleading, but less so.
* Likewise, and tweak the syntax so it's actually Python.
* Switch to some less egregiously ill-suited syntax. TOML, perhaps.
* Do nothing.
Right now, I'd prefer to do nothing.
PATCH v2 2/16 qapi: Drop check_type()'s redundant parameter @allow_optional
In reply to Markus Armbrustercheck_type() uses @allow_optional only when @value is a dictionary and @allow_dict is True. All callers that pass allow_dict=True also pass allow_optional=True.
Therefore, @allow_optional is always True when check_type() uses it. Drop the redundant parameter.
--- scripts/qapi/common.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
scripts/qapi/common.py +8 -9
@@ -783,9 +783,8 @@ def check_if(expr, info): check_if_str(ifcond, info) -def check_type(info, source, value, allow_array=False, - allow_dict=False, allow_optional=False, - allow_metas=[]): +def check_type(info, source, value, + allow_array=False, allow_dict=False, allow_metas=[]): global all_names if value is None:
@@ -821,7 +820,7 @@ def check_type(info, source, value, allow_array=False, # value is a dictionary, check that each member is okay for (key, arg) in value.items(): check_name(info, "Member of %s" % source, key, - allow_optional=allow_optional) + allow_optional=True) if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'): raise QAPISemError(info, "Member of %s uses reserved name '%s'" % (source, key))
@@ -843,14 +842,14 @@ def check_command(expr, info): if boxed: args_meta += ['union', 'alternate'] check_type(info, "'data' for command '%s'" % name, - expr.get('data'), allow_dict=not boxed, allow_optional=True, + expr.get('data'), allow_dict=not boxed, allow_metas=args_meta) returns_meta = ['union', 'struct'] if name in returns_whitelist: returns_meta += ['built-in', 'alternate', 'enum'] check_type(info, "'returns' for command '%s'" % name, expr.get('returns'), allow_array=True, - allow_optional=True, allow_metas=returns_meta) + allow_metas=returns_meta) def check_event(expr, info):
@@ -861,7 +860,7 @@ def check_event(expr, info): if boxed: meta += ['union', 'alternate'] check_type(info, "'data' for event '%s'" % name, - expr.get('data'), allow_dict=not boxed, allow_optional=True, + expr.get('data'), allow_dict=not boxed, allow_metas=meta)
@@ -889,7 +888,7 @@ def check_union(expr, info): else: # The object must have a string or dictionary 'base'. check_type(info, "'base' for union '%s'" % name, - base, allow_dict=True, allow_optional=True, + base, allow_dict=True, allow_metas=['struct']) if not base: raise QAPISemError(info, "Flat union '%s' must have a base"
@@ -1012,7 +1011,7 @@ def check_struct(expr, info): features = expr.get('features') check_type(info, "'data' for struct '%s'" % name, members, - allow_dict=True, allow_optional=True) + allow_dict=True) check_type(info, "'base' for struct '%s'" % name, expr.get('base'), allow_metas=['struct'])
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 02/16] qapi: Drop check_type()'s redundant parameter @allow_optional
Quoted 4 lines · Markus Armbruster
check_type()uses @allow_optional only when @value is a dictionary and @allow_dict is True. All callers that pass allow_dict=True also pass allow_optional=True.
Quoted 8 lines
Therefore, @allow_optional is always True when
check_type()uses it. Drop the redundant parameter.Signed-off-by Markus Armbruster <[email protected]>--- scripts/qapi/common.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
PATCH v2 3/16 qapi: Drop support for boxed alternate arguments
In reply to Markus ArmbrusterCommands and events can define their argument type inline (default) or by referring to another type ('boxed': true, since commit c818408e44 "qapi: Implement boxed types for commands/events", v2.7.0). The unboxed inline definition is an (anonymous) struct type. The boxed type may be a struct, union, or alternate type.
The latter is problematic: docs/interop/qemu-spec.txt requires the value of the 'data' key to be a json-object, but any non-degenerate alternate type has at least one branch that isn't.
Fortunately, we haven't made use of alternates in this context outside tests/. Drop support for them.
QAPISchemaAlternateType.is_empty() is now unused. Drop it, too.
--- docs/devel/qapi-code-gen.txt | 12 ++++++------ scripts/qapi/common.py | 15 ++++----------- tests/qapi-schema/qapi-schema-test.json | 2 +- tests/qapi-schema/qapi-schema-test.out | 2 +- 4 files changed, 12 insertions(+), 19 deletions(-)
docs/devel/qapi-code-gen.txt +6 -6
@@ -612,9 +612,9 @@ the command. Normally, 'data' is a dictionary for an anonymous type, or names a struct type (possibly empty, but not a union), and its members are passed as separate arguments to this function. If the command definition includes a key 'boxed' with the boolean value true, -then 'data' is instead the name of any non-empty complex type -(struct, union, or alternate), and a pointer to that QAPI type is -passed as a single argument. +then 'data' is instead the name of any non-empty complex type (struct +or union), and a pointer to that QAPI type is passed as a single +argument. The generator also emits a marshalling function that extracts arguments for the user's function out of an input QDict, calls the
@@ -714,9 +714,9 @@ The generator emits a function to send the event. Normally, 'data' is a dictionary for an anonymous type, or names a struct type (possibly empty, but not a union), and its members are passed as separate arguments to this function. If the event definition includes a key -'boxed' with the boolean value true, then 'data' is instead the name of -any non-empty complex type (struct, union, or alternate), and a -pointer to that QAPI type is passed as a single argument. +'boxed' with the boolean value true, then 'data' is instead the name +of any non-empty complex type (struct or union), and a pointer to that +QAPI type is passed as a single argument. === Features ===
scripts/qapi/common.py +4 -11
@@ -840,7 +840,7 @@ def check_command(expr, info): args_meta = ['struct'] if boxed: - args_meta += ['union', 'alternate'] + args_meta += ['union'] check_type(info, "'data' for command '%s'" % name, expr.get('data'), allow_dict=not boxed, allow_metas=args_meta)
@@ -858,7 +858,7 @@ def check_event(expr, info): meta = ['struct'] if boxed: - meta += ['union', 'alternate'] + meta += ['union'] check_type(info, "'data' for event '%s'" % name, expr.get('data'), allow_dict=not boxed, allow_metas=meta)
@@ -1690,9 +1690,6 @@ class QAPISchemaAlternateType(QAPISchemaType): visitor.visit_alternate_type(self.name, self.info, self.ifcond, self.variants) - def is_empty(self): - return False - class QAPISchemaCommand(QAPISchemaEntity): def __init__(self, name, info, doc, ifcond, arg_type, ret_type,
@@ -1714,15 +1711,13 @@ class QAPISchemaCommand(QAPISchemaEntity): QAPISchemaEntity.check(self, schema) if self._arg_type_name: self.arg_type = schema.lookup_type(self._arg_type_name) - assert (isinstance(self.arg_type, QAPISchemaObjectType) or - isinstance(self.arg_type, QAPISchemaAlternateType)) + assert isinstance(self.arg_type, QAPISchemaObjectType) self.arg_type.check(schema) if self.boxed: if self.arg_type.is_empty(): raise QAPISemError(self.info, "Cannot use 'boxed' with empty type") else: - assert not isinstance(self.arg_type, QAPISchemaAlternateType) assert not self.arg_type.variants elif self.boxed: raise QAPISemError(self.info, "Use of 'boxed' requires 'data'")
@@ -1750,15 +1745,13 @@ class QAPISchemaEvent(QAPISchemaEntity): QAPISchemaEntity.check(self, schema) if self._arg_type_name: self.arg_type = schema.lookup_type(self._arg_type_name) - assert (isinstance(self.arg_type, QAPISchemaObjectType) or - isinstance(self.arg_type, QAPISchemaAlternateType)) + assert isinstance(self.arg_type, QAPISchemaObjectType) self.arg_type.check(schema) if self.boxed: if self.arg_type.is_empty(): raise QAPISemError(self.info, "Cannot use 'boxed' with empty type") else: - assert not isinstance(self.arg_type, QAPISchemaAlternateType) assert not self.arg_type.variants elif self.boxed: raise QAPISemError(self.info, "Use of 'boxed' requires 'data'")
tests/qapi-schema/qapi-schema-test.json +1 -1
@@ -180,7 +180,7 @@ { 'event': 'EVENT_D', 'data': { 'a' : 'EventStructOne', 'b' : 'str', '*c': 'str', '*enum3': 'EnumOne' } } { 'event': 'EVENT_E', 'boxed': true, 'data': 'UserDefZero' } -{ 'event': 'EVENT_F', 'boxed': true, 'data': 'UserDefAlternate' } +{ 'event': 'EVENT_F', 'boxed': true, 'data': 'UserDefFlatUnion' } # test that we correctly compile downstream extensions, as well as munge # ticklish names
tests/qapi-schema/qapi-schema-test.out +1 -1
@@ -252,7 +252,7 @@ event EVENT_D q_obj_EVENT_D-arg boxed=False event EVENT_E UserDefZero boxed=True -event EVENT_F UserDefAlternate +event EVENT_F UserDefFlatUnion boxed=True enum __org.qemu_x-Enum member __org.qemu_x-value
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 03/16] qapi: Drop support for boxed alternate arguments
Quoted 9 lines · Markus Armbruster
Commands and events can define their argument type inline (default) or by referring to another type ('boxed': true, since commit
c818408e44"qapi: Implement boxed types for commands/events", v2.7.0). The unboxed inline definition is an (anonymous) struct type. The boxed type may be a struct, union, or alternate type.The latter is problematic:
docs/interop/qemu-spec.txtrequires the value of the 'data' key to be a json-object, but any non-degenerate alternate type has at least one branch that isn't.
Good catch.
Quoted 6 lines
Fortunately, we haven't made use of alternates in this context outside tests/. Drop support for them.
QAPISchemaAlternateType.is_empty()is now unused. Drop it, too.
Quoted 7 lines
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 12 ++++++------ scripts/qapi/common.py | 15 ++++----------- tests/qapi-schema/qapi-schema-test.json | 2 +- tests/qapi-schema/qapi-schema-test.out | 2 +- 4 files changed, 12 insertions(+), 19 deletions(-)
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
PATCH v2 4/16 docs/devel/qapi-code-gen: Minor specification fixes
In reply to Markus ArmbrusterThe specification claims "Each expression that isn't an include directive may be preceded by a documentation block", but the code also rejects them for pragma directives. The code is correct. Fix the specification.
The specification reserves member names starting with 'has_', but the code also reserves name 'u'. Fix the specification.
The specification claims "The string 'max' is not allowed as an enum value". Untrue. Fix the specification. While there, delete the naming advice, because it's redundant with the naming rules in section "Schema overview"
The specification claims "No branch of the union can be named 'max', as this would collide with the implicit enum". Untrue. Fix the specification.
The specification claims "It is not allowed to name an event 'MAX', since the generator also produces a C enumeration of all event names with a generated _MAX value at the end." Untrue. Fix the specification.
The specification claims "All branches of the union must be complex types", but the code permits only struct types. The code is correct. Fix the specification.
The specification claims a command's return type "must be the string name of a complex or built-in type, a one-element array containing the name of a complex or built-in type" unless the command is in pragma 'returns-whitelist'. The code does not permit built-in types. Fix the specification.
--- docs/devel/qapi-code-gen.txt | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-)
docs/devel/qapi-code-gen.txt +16 -18
@@ -117,9 +117,9 @@ Example: ==== Expression documentation ==== -Each expression that isn't an include directive may be preceded by a -documentation block. Such blocks are called expression documentation -blocks. +Expressions other than include and pragma directives may be preceded +by a documentation block. Such blocks are called expression +documentation blocks. When documentation is required (see pragma 'doc-required'), expression documentation blocks are mandatory.
@@ -243,8 +243,9 @@ underscore. Event names should be ALL_CAPS with words separated by underscore. -Member names starting with 'has-' or 'has_' are reserved for the -generator, which uses them for tracking optional members. +Member name 'u' and names starting with 'has-' or 'has_' are reserved +for the generator, which uses them for unions and for tracking +optional members. Any name (command, event, type, member, or enum value) beginning with "x-" is marked experimental, and may be withdrawn or changed
@@ -460,15 +461,14 @@ discriminator value, as in these examples: The generated C code uses a struct containing a union. Additionally, an implicit C enum 'NameKind' is created, corresponding to the union -'Name', for accessing the various branches of the union. No branch of -the union can be named 'max', as this would collide with the implicit -enum. The value for each branch can be of any type. +'Name', for accessing the various branches of the union. The value +for each branch can be of any type. A flat union definition avoids nesting on the wire, and specifies a set of common members that occur in all variants of the union. The 'base' key must specify either a type name (the type must be a struct, not a union), or a dictionary representing an anonymous type. -All branches of the union must be complex types, and the top-level +All branches of the union must be struct types, and the top-level members of the union dictionary on the wire will be combination of members from both the base type and the appropriate branch type (when merging two dictionaries, there must be no keys in common). The
@@ -578,8 +578,8 @@ The 'returns' member describes what will appear in the "return" member of a Client JSON Protocol reply on successful completion of a command. The member is optional from the command declaration; if absent, the "return" member will be an empty dictionary. If 'returns' is present, -it must be the string name of a complex or built-in type, a -one-element array containing the name of a complex or built-in type. +it must be the string name of a complex type, or a +one-element array containing the name of a complex type. To return anything else, you have to list the command in pragma 'returns-whitelist'. If you do this, the command cannot be extended to return additional information in the future. Use of
@@ -691,13 +691,11 @@ started with --preconfig. Usage: { 'event': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT, '*boxed': true } -Events are defined with the keyword 'event'. It is not allowed to -name an event 'MAX', since the generator also produces a C enumeration -of all event names with a generated _MAX value at the end. When -'data' is also specified, additional info will be included in the -event, with similar semantics to a 'struct' expression. Finally there -will be C API generated in qapi-events.h; when called by QEMU code, a -message with timestamp will be emitted on the wire. +Events are defined with the keyword 'event'. When 'data' is also +specified, additional info will be included in the event, with similar +semantics to a 'struct' expression. Finally there will be C API +generated in qapi-events.h; when called by QEMU code, a message with +timestamp will be emitted on the wire. An example event is:
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 04/16] docs/devel/qapi-code-gen: Minor specification fixes
Quoted 7 lines · Markus Armbruster
The specification claims "Each expression that isn't an include directive may be preceded by a documentation block", but the code also rejects them for pragma directives. The code is correct. Fix the specification.
The specification reserves member names starting with '
has_', but the code also reserves name 'u'. Fix the specification.
Reservation of 'u' was done in 5e59baf9 (and claimed we could add a munge to q_u in the future if we ever needed a name 'u' after all).
Quoted 5 lines
The specification claims "The string 'max' is not allowed as an enum value". Untrue. Fix the specification. While there, delete the naming advice, because it's redundant with the naming rules in section "Schema overview"
Used to be true; missed when commit 7fb1cf16 got rid of the collision.
Quoted 4 lines
The specification claims "No branch of the union can be named 'max', as this would collide with the implicit enum". Untrue. Fix the specification.
Fixed around the same time (although I didn't check if it was in the same commit)
Quoted 5 lines
The specification claims "It is not allowed to name an event 'MAX', since the generator also produces a C enumeration of all event names with a generated
_MAXvalue at the end." Untrue. Fix the specification.
And similar comment.
I don't know if you want to do exact commit ids where all of these doc problems were introduced (because of code patches that lifted the limitations).
Quoted 10 lines
The specification claims "All branches of the union must be complex types", but the code permits only struct types. The code is correct. Fix the specification.
The specification claims a command's return type "must be the string name of a complex or built-in type, a one-element array containing the name of a complex or built-in type" unless the command is in pragma 'returns-whitelist'. The code does not permit built-in types. Fix the specification.
Umm:
qapi/migration.json:{ 'command': 'query-migrate-cache-size', 'returns':
'int' }
I don't know if we use an array of a built-in-type, but we definitely have unfortunate commands that return a non-JSON-object. [1]
docs/devel/qapi-code-gen.txt discriminator value, as in these examples: · line 471
Quoted 6 lines
A flat union definition avoids nesting on the wire, and specifies a set of common members that occur in all variants of the union. The 'base' key must specify either a type name (the type must be a struct, not a union), or a dictionary representing an anonymous type.
docs/devel/qapi-code-gen.txt +1
-1-All branches of the union must be complex types, and the top-level +All branches of the union must be struct types, and the top-level
We have hit cases where it might have been nicer to permit a flat union whose branch is itself another flat union. But until we actually code that up to work, this is accurate.
docs/devel/qapi-code-gen.txt The 'returns' member describes what will appear in the "return" member · line 585
Quoted 11 lines
docs/devel/qapi-code-gen.txt +2
-2@@ -578,8 +578,8 @@ The 'returns' member describes what will appear in the "return" member of a Client JSON Protocol reply on successful completion of a command. The member is optional from the command declaration; if absent, the "return" member will be an empty dictionary. If 'returns' is present, -it must be the string name of a complex or built-in type, a -one-element array containing the name of a complex or built-in type. +it must be the string name of a complex type, or a +one-element array containing the name of a complex type. To return anything else, you have to list the command in pragma 'returns-whitelist'. If you do this, the command cannot be extended to return additional information in the future. Use of
[1] Aha - it's 'returns-whitelist' that makes the difference. Okay, your wording change here makes sense: a built-in is NOT permitted UNLESS you whitelist it.
Summary: you may want to improve the commit message with git archaeology, but the wording changes themselves make sense.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 04/16] docs/devel/qapi-code-gen: Minor specification fixes
Quoted 11 lines · Eric Blake
Quoted 7 lines · Markus Armbruster
The specification claims "Each expression that isn't an include directive may be preceded by a documentation block", but the code also rejects them for pragma directives. The code is correct. Fix the specification.
The specification reserves member names starting with '
has_', but the code also reserves name 'u'. Fix the specification.Reservation of 'u' was done in
5e59baf9(and claimed we could add a munge toq_uin the future if we ever needed a name 'u' after all).
Yes.
has_ could be munged away, too.
Quoted 6 lines
Quoted 4 lines
The specification claims "The string 'max' is not allowed as an enum value". Untrue. Fix the specification. While there, delete the naming advice, because it's redundant with the naming rules in section "Schema overview"
Used to be true; missed when commit
7fb1cf16got rid of the collision.
Correct.
Quoted 13 lines
Quoted 3 lines
The specification claims "No branch of the union can be named 'max', as this would collide with the implicit enum". Untrue. Fix the specification.
Fixed around the same time (although I didn't check if it was in the same commit)
Quoted 5 lines
The specification claims "It is not allowed to name an event 'MAX', since the generator also produces a C enumeration of all event names with a generated
_MAXvalue at the end." Untrue. Fix the specification.
Quoted 5 lines
And similar comment.
I don't know if you want to do exact commit ids where all of these doc problems were introduced (because of code patches that lifted the limitations).
I'm (overly?) fond of git archeology myself, but I found these bugs while fighting crocodiles in the swamp, so I couldn't indulge.
Quoted 46 lines
Quoted 9 lines
The specification claims "All branches of the union must be complex types", but the code permits only struct types. The code is correct. Fix the specification.
The specification claims a command's return type "must be the string name of a complex or built-in type, a one-element array containing the name of a complex or built-in type" unless the command is in pragma 'returns-whitelist'. The code does not permit built-in types. Fix the specification.
Umm:
qapi/migration.json:{ 'command': 'query-migrate-cache-size', 'returns':
'int' }I don't know if we use an array of a built-in-type, but we definitely have unfortunate commands that return a non-JSON-object. [1]
docs/devel/qapi-code-gen.txt discriminator value, as in these examples: · line 471
Quoted 6 lines
A flat union definition avoids nesting on the wire, and specifies a set of common members that occur in all variants of the union. The 'base' key must specify either a type name (the type must be a struct, not a union), or a dictionary representing an anonymous type.
docs/devel/qapi-code-gen.txt +1
-1-All branches of the union must be complex types, and the top-level +All branches of the union must be struct types, and the top-levelWe have hit cases where it might have been nicer to permit a flat union whose branch is itself another flat union. But until we actually code that up to work, this is accurate.
docs/devel/qapi-code-gen.txt The 'returns' member describes what will appear in the "return" member · line 585
Quoted 11 lines
docs/devel/qapi-code-gen.txt +2
-2@@ -578,8 +578,8 @@ The 'returns' member describes what will appear in the "return" member of a Client JSON Protocol reply on successful completion of a command. The member is optional from the command declaration; if absent, the "return" member will be an empty dictionary. If 'returns' is present, -it must be the string name of a complex or built-in type, a -one-element array containing the name of a complex or built-in type. +it must be the string name of a complex type, or a +one-element array containing the name of a complex type. To return anything else, you have to list the command in pragma 'returns-whitelist'. If you do this, the command cannot be extended to return additional information in the future. Use of[1] Aha - it's 'returns-whitelist' that makes the difference. Okay, your wording change here makes sense: a built-in is NOT permitted UNLESS you whitelist it.
Quoted 2 lines
Summary: you may want to improve the commit message with git archaeology, but the wording changes themselves make sense.
I'll see what I can do without too much effort.
Quoted 1 line
Reviewed-by Eric Blake <[email protected]>
Thanks!
PATCH v2 5/16 tests/qapi-schema: Demonstrate bad reporting of funny characters
In reply to Markus ArmbrusterInvalid name 'not\\possible' is reported as 'not\possible'. Control characters (quoted or not) are even more confusing. Mark FIXME.
--- tests/qapi-schema/enum-bad-name.err | 2 +- tests/qapi-schema/enum-bad-name.json | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-)
tests/qapi-schema/enum-bad-name.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/enum-bad-name.json:2: Member of enum 'MyEnum' uses invalid name 'not^possible' +tests/qapi-schema/enum-bad-name.json:3: Member of enum 'MyEnum' uses invalid name 'not\possible'
tests/qapi-schema/enum-bad-name.json +2 -1
@@ -1,2 +1,3 @@ # we ensure all enum names can map to C -{ 'enum': 'MyEnum', 'data': [ 'not^possible' ] } +# FIXME reports 'not\posible' instead of 'not\\possible' +{ 'enum': 'MyEnum', 'data': [ 'not\\possible' ] }
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 05/16] tests/qapi-schema: Demonstrate bad reporting of funny characters
Quoted 21 lines · Markus Armbruster
Invalid name 'not\\possible' is reported as 'not\possible'. Control characters (quoted or not) are even more confusing. Mark FIXME.
Signed-off-by Markus Armbruster <[email protected]>--- tests/qapi-schema/enum-bad-name.err | 2 +- tests/qapi-schema/enum-bad-name.json | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-)tests/qapi-schema/enum-bad-name.err +1
-1@@ -1 +1 @@ -tests/qapi-schema/enum-bad-name.json:2: Member of enum 'MyEnum' uses invalid name 'not^possible' +tests/qapi-schema/enum-bad-name.json:3: Member of enum 'MyEnum' uses invalid name 'not\possible'tests/qapi-schema/enum-bad-name.json +0
-0
tests/qapi-schema/enum-bad-name.json line 2
Quoted 3 lines
tests/qapi-schema/enum-bad-name.json +1
-1@@ -1,2 +1,3 @@ # we ensure all enum names can map to C -{ 'enum': 'MyEnum', 'data': [ 'not^possible' ] } +# FIXME reports 'not\posible' instead of 'not\\possible'
s/posible/possible/
(Is it bad when you have a typo in demonstrating that the code has a typo?)
With that fixed,
Quoted 2 lines
tests/qapi-schema/enum-bad-name.json +1
-0+{ 'enum': 'MyEnum', 'data': [ 'not\\possible' ] }
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 05/16] tests/qapi-schema: Demonstrate bad reporting of funny characters
Quoted 28 lines · Eric Blake
Quoted 21 lines · Markus Armbruster
Invalid name 'not\\possible' is reported as 'not\possible'. Control characters (quoted or not) are even more confusing. Mark FIXME.
Signed-off-by Markus Armbruster <[email protected]>--- tests/qapi-schema/enum-bad-name.err | 2 +- tests/qapi-schema/enum-bad-name.json | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-)tests/qapi-schema/enum-bad-name.err +1
-1@@ -1 +1 @@ -tests/qapi-schema/enum-bad-name.json:2: Member of enum 'MyEnum' uses invalid name 'not^possible' +tests/qapi-schema/enum-bad-name.json:3: Member of enum 'MyEnum' uses invalid name 'not\possible'tests/qapi-schema/enum-bad-name.json +0
-0tests/qapi-schema/enum-bad-name.json line 2
Quoted 3 lines
tests/qapi-schema/enum-bad-name.json +1
-1@@ -1,2 +1,3 @@ # we ensure all enum names can map to C -{ 'enum': 'MyEnum', 'data': [ 'not^possible' ] } +# FIXME reports 'not\posible' instead of 'not\\possible's/posible/possible/
Quoted 1 line
(Is it bad when you have a typo in demonstrating that the code has a typo?)
Funny, not bad %-}
Quoted 3 lines
With that fixed,
Reviewed-by Eric Blake <[email protected]>
Thanks!
Quoted 2 lines
Quoted 2 lines
tests/qapi-schema/enum-bad-name.json +1
-0+{ 'enum': 'MyEnum', 'data': [ 'not\\possible' ] }
PATCH v2 6/16 qapi: Restrict strings to printable ASCII
In reply to Markus ArmbrusterRFC 8259 on string contents:
All Unicode characters may be placed within the quotation marks, except for the characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
The QAPI schema parser accepts both less and more than JSON: it accepts only ASCII with \u (less), and accepts control characters other than LF (new line) unescaped. How it treats unescaped non-ASCII input differs between Python 2 and Python 3.
Make it accept strictly less: require printable ASCII. Drop support for \b, \f, \n, \r, \t.
---
scripts/qapi/common.py | 25 ++++++-------------
tests/Makefile.include | 3 ++-
tests/qapi-schema/string-code-point-127.err | 1 +
...de-str.exit => string-code-point-127.exit} | 0
tests/qapi-schema/string-code-point-127.json | 2 ++
...code-str.out => string-code-point-127.out} | 0
tests/qapi-schema/string-code-point-31.err | 1 +
tests/qapi-schema/string-code-point-31.exit | 1 +
tests/qapi-schema/string-code-point-31.json | 2 ++
tests/qapi-schema/string-code-point-31.out | 0
tests/qapi-schema/unicode-str.err | 1 -
tests/qapi-schema/unicode-str.json | 2 --
12 files changed, 17 insertions(+), 21 deletions(-)
create mode 100644 tests/qapi-schema/string-code-point-127.err
rename tests/qapi-schema/{unicode-str.exit => string-code-point-127.exit} (100%)
create mode 100644 tests/qapi-schema/string-code-point-127.json
rename tests/qapi-schema/{unicode-str.out => string-code-point-127.out} (100%)
create mode 100644 tests/qapi-schema/string-code-point-31.err
create mode 100644 tests/qapi-schema/string-code-point-31.exit
create mode 100644 tests/qapi-schema/string-code-point-31.json
create mode 100644 tests/qapi-schema/string-code-point-31.out
delete mode 100644 tests/qapi-schema/unicode-str.err
delete mode 100644 tests/qapi-schema/unicode-str.jsonscripts/qapi/common.py +8 -17
@@ -523,17 +523,7 @@ class QAPISchemaParser(object): if ch == '\n': raise QAPIParseError(self, 'Missing terminating "\'"') if esc: - if ch == 'b': - string += '\b' - elif ch == 'f': - string += '\f' - elif ch == 'n': - string += '\n' - elif ch == 'r': - string += '\r' - elif ch == 't': - string += '\t' - elif ch == 'u': + if ch == 'u': value = 0 for _ in range(0, 4): ch = self.src[self.cursor]
@@ -552,20 +542,21 @@ class QAPISchemaParser(object): 'For now, \\u escape ' 'only supports non-zero ' 'values up to \\u007f') - string += chr(value) - elif ch in '\\/\'"': - string += ch - else: + ch = chr(value) + elif ch not in '\\/\'"': raise QAPIParseError(self, "Unknown escape \\%s" % ch) esc = False elif ch == '\\': esc = True + continue elif ch == "'": self.val = string return - else: - string += ch + if ord(ch) < 32 or ord(ch) >= 127: + raise QAPIParseError( + self, "Funny character in string") + string += ch elif self.src.startswith('true', self.pos): self.val = True self.cursor += 3
tests/Makefile.include +2 -1
@@ -452,6 +452,8 @@ qapi-schema += returns-array-bad.json qapi-schema += returns-dict.json qapi-schema += returns-unknown.json qapi-schema += returns-whitelist.json +qapi-schema += string-code-point-31.json +qapi-schema += string-code-point-127.json qapi-schema += struct-base-clash-deep.json qapi-schema += struct-base-clash.json qapi-schema += struct-data-invalid.json
@@ -463,7 +465,6 @@ qapi-schema += type-bypass-bad-gen.json qapi-schema += unclosed-list.json qapi-schema += unclosed-object.json qapi-schema += unclosed-string.json -qapi-schema += unicode-str.json qapi-schema += union-base-empty.json qapi-schema += union-base-no-discriminator.json qapi-schema += union-branch-case.json
tests/qapi-schema/string-code-point-127.err new file +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/string-code-point-127.json:2:14: Funny character in string
tests/qapi-schema/string-code-point-127.exit renamed from tests/qapi-schema/unicode-str.exit +0 -0
tests/qapi-schema/string-code-point-127.json new file +2 -0
@@ -0,0 +1,2 @@ +# We accept printable ASCII: code points 32..126. Test code point 127: +{ 'command': '' }
tests/qapi-schema/string-code-point-127.out renamed from tests/qapi-schema/unicode-str.out +0 -0
tests/qapi-schema/string-code-point-31.err new file +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/string-code-point-31.json:2:14: Funny character in string
tests/qapi-schema/string-code-point-31.exit new file +1 -0
@@ -0,0 +1 @@ +1
tests/qapi-schema/string-code-point-31.json new file +2 -0
@@ -0,0 +1,2 @@ +# We accept printable ASCII: code points 32..126. Test code point 127: +{ 'command': '' }
tests/qapi-schema/string-code-point-31.out new file +0 -0
tests/qapi-schema/unicode-str.err deleted +0 -1
@@ -1 +0,0 @@ -tests/qapi-schema/unicode-str.json:2: 'command' uses invalid name 'é'
tests/qapi-schema/unicode-str.json deleted +0 -2
@@ -1,2 +0,0 @@ -# we don't support full Unicode strings, yet -{ 'command': 'é' }
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 06/16] qapi: Restrict strings to printable ASCII
Quoted 7 lines · Markus Armbruster
RFC 8259 on string contents:
All Unicode characters may be placed within the quotation marks, except for the characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
Quoted 7 lines
The QAPI schema parser accepts both less and more than JSON: it accepts only ASCII with \u (less), and accepts control characters other than LF (new line) unescaped. How it treats unescaped non-ASCII input differs between Python 2 and Python 3.
Make it accept strictly less: require printable ASCII. Drop support for \b, \f, \n, \r, \t.
Fair enough. It doesn't prevent QMP clients from sending strings with non-ASCII characters, merely that those strings will never match the schema because we have guaranteed our schema is limited to ASCII. (This change means we are promising to never allow { "execute": "a\tb" } as a valid QMP command, for instance.)
Quoted 5 lines
Signed-off-by Markus Armbruster <[email protected]>---
scripts/qapi/common.py class QAPISchemaParser(object): · line 531
Quoted 9 lines
scripts/qapi/common.py +0
-6@@ -523,17 +523,7 @@ class QAPISchemaParser(object): if ch == '\n': raise QAPIParseError(self, 'Missing terminating "\'"') if esc: - if ch == 'b': - string += '\b' - elif ch == 'f': - string += '\f' - elif ch == 'n': - string += '\n'
Is it worth a comment in the code that we are specifically not parsing all possible JSON escapes, because of the later requirement that QAPI strings be limited to the subset of printable ASCII?
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 06/16] qapi: Restrict strings to printable ASCII
Quoted 13 lines · Eric Blake
Quoted 12 lines · Markus Armbruster
RFC 8259 on string contents:
All Unicode characters may be placed within the quotation marks, except for the characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
The QAPI schema parser accepts both less and more than JSON: it accepts only ASCII with \u (less), and accepts control characters other than LF (new line) unescaped. How it treats unescaped non-ASCII input differs between Python 2 and Python 3.
Quoted 6 lines
Quoted 2 lines
Make it accept strictly less: require printable ASCII. Drop support for \b, \f, \n, \r, \t.
Fair enough. It doesn't prevent QMP clients from sending strings with non-ASCII characters, merely that those strings will never match the schema because we have guaranteed our schema is limited to ASCII. (This
Note that this only affects QMP commands, events, parameter and enum value names, *not* non-enum string arguments.
Quoted 2 lines
change means we are promising to never allow { "execute": "a\tb" } as a valid QMP command, for instance.)
We're not actually promising anything. We're merely making it slightly harder to do: need to revert this patch first. Feels quite unlikely, though.
Quoted 17 lines
scripts/qapi/common.py class QAPISchemaParser(object): · line 531
Quoted 13 lines
Signed-off-by Markus Armbruster <[email protected]>---
scripts/qapi/common.py +0
-6@@ -523,17 +523,7 @@ class QAPISchemaParser(object): if ch == '\n': raise QAPIParseError(self, 'Missing terminating "\'"') if esc: - if ch == 'b': - string += '\b' - elif ch == 'f': - string += '\f' - elif ch == 'n': - string += '\n'Is it worth a comment in the code that we are specifically not parsing all possible JSON escapes, because of the later requirement that QAPI strings be limited to the subset of printable ASCII?
Can't hurt.
Quoted 1 line
Reviewed-by Eric Blake <[email protected]>
Thanks!
PATCH v2 7/16 qapi: Drop support for escape sequences other than \\
In reply to Markus ArmbrusterSince the previous commit restricted strings to printable ASCII, \uXXXX's only use is obfuscation. Drop it.
This leaves \\, \/, \', and \". Since QAPI schema strings are all names, and names are restricted to ASCII letters, digits, hyphen, and underscore, none of them is useful.
The latter three have no test coverage. Drop them.
Keep \\ to avoid (more) gratuitous incompatibility with JSON.
--- scripts/qapi/common.py | 22 +------------------- tests/Makefile.include | 3 --- tests/qapi-schema/escape-outside-string.err | 1 - tests/qapi-schema/escape-outside-string.exit | 1 - tests/qapi-schema/escape-outside-string.json | 3 --- tests/qapi-schema/escape-outside-string.out | 0 tests/qapi-schema/escape-too-big.err | 1 - tests/qapi-schema/escape-too-big.exit | 1 - tests/qapi-schema/escape-too-big.json | 3 --- tests/qapi-schema/escape-too-big.out | 0 tests/qapi-schema/escape-too-short.err | 1 - tests/qapi-schema/escape-too-short.exit | 1 - tests/qapi-schema/escape-too-short.json | 3 --- tests/qapi-schema/escape-too-short.out | 0 tests/qapi-schema/ident-with-escape.err | 1 + tests/qapi-schema/ident-with-escape.exit | 2 +- tests/qapi-schema/ident-with-escape.json | 2 +- tests/qapi-schema/ident-with-escape.out | 16 -------------- tests/qapi-schema/unknown-escape.json | 2 +- 19 files changed, 5 insertions(+), 58 deletions(-) delete mode 100644 tests/qapi-schema/escape-outside-string.err delete mode 100644 tests/qapi-schema/escape-outside-string.exit delete mode 100644 tests/qapi-schema/escape-outside-string.json delete mode 100644 tests/qapi-schema/escape-outside-string.out delete mode 100644 tests/qapi-schema/escape-too-big.err delete mode 100644 tests/qapi-schema/escape-too-big.exit delete mode 100644 tests/qapi-schema/escape-too-big.json delete mode 100644 tests/qapi-schema/escape-too-big.out delete mode 100644 tests/qapi-schema/escape-too-short.err delete mode 100644 tests/qapi-schema/escape-too-short.exit delete mode 100644 tests/qapi-schema/escape-too-short.json delete mode 100644 tests/qapi-schema/escape-too-short.out
scripts/qapi/common.py +1 -21
@@ -523,27 +523,7 @@ class QAPISchemaParser(object): if ch == '\n': raise QAPIParseError(self, 'Missing terminating "\'"') if esc: - if ch == 'u': - value = 0 - for _ in range(0, 4): - ch = self.src[self.cursor] - self.cursor += 1 - if ch not in '0123456789abcdefABCDEF': - raise QAPIParseError(self, - '\\u escape needs 4 ' - 'hex digits') - value = (value << 4) + int(ch, 16) - # If Python 2 and 3 didn't disagree so much on - # how to handle Unicode, then we could allow - # Unicode string defaults. But most of QAPI is - # ASCII-only, so we aren't losing much for now. - if not value or value > 0x7f: - raise QAPIParseError(self, - 'For now, \\u escape ' - 'only supports non-zero ' - 'values up to \\u007f') - ch = chr(value) - elif ch not in '\\/\'"': + if ch != '\\': raise QAPIParseError(self, "Unknown escape \\%s" % ch) esc = False
tests/Makefile.include +0 -3
@@ -375,9 +375,6 @@ qapi-schema += enum-int-member.json qapi-schema += enum-member-case.json qapi-schema += enum-missing-data.json qapi-schema += enum-wrong-data.json -qapi-schema += escape-outside-string.json -qapi-schema += escape-too-big.json -qapi-schema += escape-too-short.json qapi-schema += event-boxed-empty.json qapi-schema += event-case.json qapi-schema += event-member-invalid-dict.json
tests/qapi-schema/escape-outside-string.err deleted +0 -1
@@ -1 +0,0 @@ -tests/qapi-schema/escape-outside-string.json:3:27: Stray "\"
tests/qapi-schema/escape-outside-string.exit deleted +0 -1
@@ -1 +0,0 @@ -1
tests/qapi-schema/escape-outside-string.json deleted +0 -3
@@ -1,3 +0,0 @@ -# escape sequences are permitted only inside strings -# { 'command': 'foo', 'data': {} } -{ 'command': 'foo', 'data'\u003a{} }
tests/qapi-schema/escape-outside-string.out deleted +0 -0
tests/qapi-schema/escape-too-big.err deleted +0 -1
@@ -1 +0,0 @@ -tests/qapi-schema/escape-too-big.json:3:14: For now, \u escape only supports non-zero values up to \u007f
tests/qapi-schema/escape-too-big.exit deleted +0 -1
@@ -1 +0,0 @@ -1
tests/qapi-schema/escape-too-big.json deleted +0 -3
@@ -1,3 +0,0 @@ -# we don't support full Unicode strings, yet -# { 'command': 'é' } -{ 'command': '\u00e9' }
tests/qapi-schema/escape-too-big.out deleted +0 -0
tests/qapi-schema/escape-too-short.err deleted +0 -1
@@ -1 +0,0 @@ -tests/qapi-schema/escape-too-short.json:3:14: \u escape needs 4 hex digits
tests/qapi-schema/escape-too-short.exit deleted +0 -1
@@ -1 +0,0 @@ -1
tests/qapi-schema/escape-too-short.json deleted +0 -3
@@ -1,3 +0,0 @@ -# the \u escape requires 4 hex digits -# { 'command': 'a' } -{ 'command': '\u61' }
tests/qapi-schema/escape-too-short.out deleted +0 -0
tests/qapi-schema/ident-with-escape.err +1 -0
@@ -0,0 +1 @@ +tests/qapi-schema/ident-with-escape.json:3:3: Unknown escape \u
tests/qapi-schema/ident-with-escape.exit +1 -1
@@ -1 +1 @@ -0 +1
tests/qapi-schema/ident-with-escape.json +1 -1
@@ -1,4 +1,4 @@ -# we allow escape sequences in strings, if they map back to ASCII +# we don't recognize any \ escapes other than \\ (tested elsewhere) # { 'command': 'fooA', 'data': { 'bar1': 'str' } } { 'c\u006fmmand': '\u0066\u006f\u006FA', 'd\u0061ta': { '\u0062\u0061\u00721': '\u0073\u0074\u0072' } }
tests/qapi-schema/ident-with-escape.out +0 -16
@@ -1,16 +0,0 @@ -module None -object q_empty -enum QType - prefix QTYPE - member none - member qnull - member qnum - member qstring - member qdict - member qlist - member qbool -module ident-with-escape.json -object q_obj_fooA-arg - member bar1: str optional=False -command fooA q_obj_fooA-arg -> None - gen=True success_response=True boxed=False oob=False preconfig=False
tests/qapi-schema/unknown-escape.json +1 -1
@@ -1,3 +1,3 @@ -# we only recognize JSON escape sequences, plus our \' extension (no \x) +# we only recognize \\ # { 'command': 'foo', 'data': {} } { 'command': 'foo', 'dat\x61':{} }
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 07/16] qapi: Drop support for escape sequences other than \\
Quoted 10 lines · Markus Armbruster
Since the previous commit restricted strings to printable ASCII, \uXXXX's only use is obfuscation. Drop it.
This leaves \\, \/, \', and \". Since QAPI schema strings are all names, and names are restricted to ASCII letters, digits, hyphen, and underscore, none of them is useful.
The latter three have no test coverage. Drop them.
Keep \\ to avoid (more) gratuitous incompatibility with JSON.
We have to parse it (to get a sane error message for someone writing "a\b" and thinking they were getting a backspace), but we can still reject "a\\b" as being a non-QAPI-name. An alternative might be to reject QAPI strings the moment \ is encountered (as the only possible use is to introduce a character that is not valid as a name), to the point that we could check for name validity at the time we parse strings rather than later on. Up to you.
tests/qapi-schema/escape-outside-string.err line 1
Quoted 9 lines
Signed-off-by Markus Armbruster <[email protected]>---
tests/qapi-schema/escape-outside-string.err deleted +0
-1@@ -1 +0,0 @@ -tests/qapi-schema/escape-outside-string.json:3:27: Stray "\"
Do we still want to test that \ is an invalid character outside of strings (whether or not \ is also made invalid inside strings)?
tests/qapi-schema/escape-outside-string.err line 3
Quoted 7 lines
+++
b/tests/qapi-schema/unknown-escape.jsontests/qapi-schema/escape-outside-string.err deleted +1
-1@@ -1,3 +1,3 @@ -# we only recognize JSON escape sequences, plus our \' extension (no \x) +# we only recognize \\ # { 'command': 'foo', 'data': {} } { 'command': 'foo', 'dat\x61':{} }
At any rate, this change seems reasonable.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 07/16] qapi: Drop support for escape sequences other than \\
Quoted 12 lines · Eric Blake
Quoted 10 lines · Markus Armbruster
Since the previous commit restricted strings to printable ASCII, \uXXXX's only use is obfuscation. Drop it.
This leaves \\, \/, \', and \". Since QAPI schema strings are all names, and names are restricted to ASCII letters, digits, hyphen, and underscore, none of them is useful.
The latter three have no test coverage. Drop them.
Keep \\ to avoid (more) gratuitous incompatibility with JSON.
Quoted 7 lines
We have to parse it (to get a sane error message for someone writing "a\b" and thinking they were getting a backspace), but we can still reject "a\\b" as being a non-QAPI-name. An alternative might be to reject QAPI strings the moment \ is encountered (as the only possible use is to introduce a character that is not valid as a name), to the point that we could check for name validity at the time we parse strings rather than later on. Up to you.
That works, too. I chose to parse \\ to keep the language a sub-language of JSON's (and Python's) at the lexical level: we reject some valid JSON (and Python) such as 'a\b'. Not treating \ special at all would accept it, but with a different meaning. Will be rejected at a higher level, so it doesn't really matter. But the reasoning involves more than just the lexical level then.
Quoted 11 lines
tests/qapi-schema/escape-outside-string.err line 1
Quoted 8 lines
Signed-off-by Markus Armbruster <[email protected]>---
tests/qapi-schema/escape-outside-string.err deleted +0
-1@@ -1 +0,0 @@ -tests/qapi-schema/escape-outside-string.json:3:27: Stray "\"Do we still want to test that \ is an invalid character outside of strings (whether or not \ is also made invalid inside strings)?
funny-char.json checks ';'. '\' is no different.
Quoted 11 lines
tests/qapi-schema/escape-outside-string.err line 3
Quoted 7 lines
+++
b/tests/qapi-schema/unknown-escape.jsontests/qapi-schema/escape-outside-string.err deleted +1
-1@@ -1,3 +1,3 @@ -# we only recognize JSON escape sequences, plus our \' extension (no \x) +# we only recognize \\ # { 'command': 'foo', 'data': {} } { 'command': 'foo', 'dat\x61':{} }At any rate, this change seems reasonable.
Reviewed-by Eric Blake <[email protected]>
Thanks!
PATCH v2 8/16 qapi: Permit 'boxed' with empty type
In reply to Markus ArmbrusterWe reject empty types with 'boxed': true. We don't really need that to work, but making it work is actually simpler than rejecting it, so do that.
--- tests/test-qmp-cmds.c | 4 ++++ scripts/qapi/commands.py | 4 ++-- scripts/qapi/common.py | 14 ++------------ scripts/qapi/events.py | 10 +++++----- tests/Makefile.include | 1 - tests/qapi-schema/args-boxed-empty.err | 1 - tests/qapi-schema/args-boxed-empty.exit | 1 - tests/qapi-schema/args-boxed-empty.json | 3 --- tests/qapi-schema/args-boxed-empty.out | 0 tests/qapi-schema/qapi-schema-test.json | 2 ++ tests/qapi-schema/qapi-schema-test.out | 4 ++++ 11 files changed, 19 insertions(+), 25 deletions(-) delete mode 100644 tests/qapi-schema/args-boxed-empty.err delete mode 100644 tests/qapi-schema/args-boxed-empty.exit delete mode 100644 tests/qapi-schema/args-boxed-empty.json delete mode 100644 tests/qapi-schema/args-boxed-empty.out
tests/test-qmp-cmds.c +4 -0
@@ -97,6 +97,10 @@ void qmp_boxed_union(UserDefListUnion *arg, Error **errp) { } +void qmp_boxed_empty (Empty1 *arg,Error **errp) +{ +} + __org_qemu_x_Union1 *qmp___org_qemu_x_command(__org_qemu_x_EnumList *a, __org_qemu_x_StructList *b, __org_qemu_x_Union2 *c,
scripts/qapi/commands.py +2 -2
@@ -30,7 +30,7 @@ def gen_call(name, arg_type, boxed, ret_type): argstr = '' if boxed: - assert arg_type and not arg_type.is_empty() + assert arg_type argstr = '&arg, ' elif arg_type: assert not arg_type.variants
@@ -96,7 +96,7 @@ def gen_marshal_decl(name): def gen_marshal(name, arg_type, boxed, ret_type): - have_args = arg_type and not arg_type.is_empty() + have_args = boxed or (arg_type and not arg_type.is_empty()) ret = mcgen('''
scripts/qapi/common.py +2 -12
@@ -1684,12 +1684,7 @@ class QAPISchemaCommand(QAPISchemaEntity): self.arg_type = schema.lookup_type(self._arg_type_name) assert isinstance(self.arg_type, QAPISchemaObjectType) self.arg_type.check(schema) - if self.boxed: - if self.arg_type.is_empty(): - raise QAPISemError(self.info, - "Cannot use 'boxed' with empty type") - else: - assert not self.arg_type.variants + assert not self.arg_type.variants or self.boxed elif self.boxed: raise QAPISemError(self.info, "Use of 'boxed' requires 'data'") if self._ret_type_name:
@@ -1718,12 +1713,7 @@ class QAPISchemaEvent(QAPISchemaEntity): self.arg_type = schema.lookup_type(self._arg_type_name) assert isinstance(self.arg_type, QAPISchemaObjectType) self.arg_type.check(schema) - if self.boxed: - if self.arg_type.is_empty(): - raise QAPISemError(self.info, - "Cannot use 'boxed' with empty type") - else: - assert not self.arg_type.variants + assert not self.arg_type.variants or self.boxed elif self.boxed: raise QAPISemError(self.info, "Use of 'boxed' requires 'data'")
scripts/qapi/events.py +5 -5
@@ -65,6 +65,8 @@ def gen_event_send(name, arg_type, boxed, event_enum_name, event_emit): # practice, we can rename our local variables with a leading _ prefix, # or split the code into a wrapper function that creates a boxed # 'param' object then calls another to do the real work. + have_args = boxed or (arg_type and not arg_type.is_empty()) + ret = mcgen(''' %(proto)s
@@ -73,15 +75,13 @@ def gen_event_send(name, arg_type, boxed, event_enum_name, event_emit): ''', proto=build_event_send_proto(name, arg_type, boxed)) - if arg_type and not arg_type.is_empty(): + if have_args: ret += mcgen(''' QObject *obj; Visitor *v; ''') if not boxed: ret += gen_param_var(arg_type) - else: - assert not boxed ret += mcgen('''
@@ -90,7 +90,7 @@ def gen_event_send(name, arg_type, boxed, event_enum_name, event_emit): ''', name=name) - if arg_type and not arg_type.is_empty(): + if have_args: ret += mcgen(''' v = qobject_output_visitor_new(&obj); ''')
@@ -121,7 +121,7 @@ def gen_event_send(name, arg_type, boxed, event_enum_name, event_emit): event_emit=event_emit, c_enum=c_enum_const(event_enum_name, name)) - if arg_type and not arg_type.is_empty(): + if have_args: ret += mcgen(''' visit_free(v); ''')
tests/Makefile.include +0 -1
@@ -312,7 +312,6 @@ qapi-schema += args-array-empty.json qapi-schema += args-array-unknown.json qapi-schema += args-bad-boxed.json qapi-schema += args-boxed-anon.json -qapi-schema += args-boxed-empty.json qapi-schema += args-boxed-string.json qapi-schema += args-int.json qapi-schema += args-invalid.json
tests/qapi-schema/args-boxed-empty.err deleted +0 -1
@@ -1 +0,0 @@ -tests/qapi-schema/args-boxed-empty.json:3: Cannot use 'boxed' with empty type
tests/qapi-schema/args-boxed-empty.exit deleted +0 -1
@@ -1 +0,0 @@ -1
tests/qapi-schema/args-boxed-empty.json deleted +0 -3
@@ -1,3 +0,0 @@ -# 'boxed' requires a non-empty type -{ 'struct': 'Empty', 'data': {} } -{ 'command': 'foo', 'boxed': true, 'data': 'Empty' }
tests/qapi-schema/args-boxed-empty.out deleted +0 -0
tests/qapi-schema/qapi-schema-test.json +2 -0
@@ -149,6 +149,7 @@ { 'command': 'guest-sync', 'data': { 'arg': 'any' }, 'returns': 'any' } { 'command': 'boxed-struct', 'boxed': true, 'data': 'UserDefZero' } { 'command': 'boxed-union', 'data': 'UserDefListUnion', 'boxed': true } +{ 'command': 'boxed-empty', 'boxed': true, 'data': 'Empty1' } # Smoke test on out-of-band and allow-preconfig-test { 'command': 'test-flags-command', 'allow-oob': true, 'allow-preconfig': true }
@@ -181,6 +182,7 @@ 'data': { 'a' : 'EventStructOne', 'b' : 'str', '*c': 'str', '*enum3': 'EnumOne' } } { 'event': 'EVENT_E', 'boxed': true, 'data': 'UserDefZero' } { 'event': 'EVENT_F', 'boxed': true, 'data': 'UserDefFlatUnion' } +{ 'event': 'EVENT_G', 'boxed': true, 'data': 'Empty1' } # test that we correctly compile downstream extensions, as well as munge # ticklish names
tests/qapi-schema/qapi-schema-test.out +4 -0
@@ -221,6 +221,8 @@ command boxed-struct UserDefZero -> None gen=True success_response=True boxed=True oob=False preconfig=False command boxed-union UserDefListUnion -> None gen=True success_response=True boxed=True oob=False preconfig=False +command boxed-empty Empty1 -> None + gen=True success_response=True boxed=True oob=False preconfig=False command test-flags-command None -> None gen=True success_response=True boxed=False oob=True preconfig=True object UserDefOptions
@@ -254,6 +256,8 @@ event EVENT_E UserDefZero boxed=True event EVENT_F UserDefFlatUnion boxed=True +event EVENT_G Empty1 + boxed=True enum __org.qemu_x-Enum member __org.qemu_x-value object __org.qemu_x-Base
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 08/16] qapi: Permit 'boxed' with empty type
Quoted 8 lines · Markus Armbruster
We reject empty types with 'boxed': true. We don't really need that to work, but making it work is actually simpler than rejecting it, so do that.
Signed-off-by Markus Armbruster <[email protected]>---
11 files changed, 19 insertions(+), 25 deletions(-)
Diffstat agrees with your assessment.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
PATCH v2 9/16 qapi: Permit alternates with just one branch
In reply to Markus ArmbrusterA union or alternate without branches makes no sense and doesn't work:
it can't be instantiated. A union or alternate with just one branch works, but is degenerate. We accept the former, but reject the latter. Weird. docs/devel/qapi-code-gen.txt doesn't mention the difference. It claims an alternate definition is "is similar to a simple union type".
Permit degenerate alternates to make them consistent with unions.
--- scripts/qapi/common.py | 6 ++---- tests/qapi-schema/alternate-empty.err | 2 +- tests/qapi-schema/alternate-empty.json | 4 ++-- tests/qapi-schema/qapi-schema-test.json | 4 +++- tests/qapi-schema/qapi-schema-test.out | 6 ++++-- 5 files changed, 12 insertions(+), 10 deletions(-)
scripts/qapi/common.py +2 -4
@@ -917,11 +917,9 @@ def check_alternate(expr, info): members = expr['data'] types_seen = {} - # Check every branch; require at least two branches - if len(members) < 2: + if len(members) == 0: raise QAPISemError(info, - "Alternate '%s' should have at least two branches " - "in 'data'" % name) + "Alternate '%s' cannot have empty 'data'" % name) for (key, value) in members.items(): check_name(info, "Member of alternate '%s'" % name, key) check_known_keys(info,
tests/qapi-schema/alternate-empty.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/alternate-empty.json:2: Alternate 'Alt' should have at least two branches in 'data' +tests/qapi-schema/alternate-empty.json:2: Alternate 'Alt' cannot have empty 'data'
tests/qapi-schema/alternate-empty.json +2 -2
@@ -1,2 +1,2 @@ -# alternates must list at least two types to be useful -{ 'alternate': 'Alt', 'data': { 'i': 'int' } } +# alternates cannot be empty +{ 'alternate': 'Alt', 'data': { } }
tests/qapi-schema/qapi-schema-test.json +3 -1
@@ -186,19 +186,21 @@ # test that we correctly compile downstream extensions, as well as munge # ticklish names +# also test union and alternate with just one branch { 'enum': '__org.qemu_x-Enum', 'data': [ '__org.qemu_x-value' ] } { 'struct': '__org.qemu_x-Base', 'data': { '__org.qemu_x-member1': '__org.qemu_x-Enum' } } { 'struct': '__org.qemu_x-Struct', 'base': '__org.qemu_x-Base', 'data': { '__org.qemu_x-member2': 'str', '*wchar-t': 'int' } } { 'union': '__org.qemu_x-Union1', 'data': { '__org.qemu_x-branch': 'str' } } +{ 'alternate': '__org.qemu_x-Alt1', 'data': { '__org.qemu_x-branch': 'str' } } { 'struct': '__org.qemu_x-Struct2', 'data': { 'array': ['__org.qemu_x-Union1'] } } { 'union': '__org.qemu_x-Union2', 'base': '__org.qemu_x-Base', 'discriminator': '__org.qemu_x-member1', 'data': { '__org.qemu_x-value': '__org.qemu_x-Struct2' } } { 'alternate': '__org.qemu_x-Alt', - 'data': { '__org.qemu_x-branch': 'str', 'b': '__org.qemu_x-Base' } } + 'data': { '__org.qemu_x-branch': '__org.qemu_x-Base' } } { 'event': '__ORG.QEMU_X-EVENT', 'data': '__org.qemu_x-Struct' } { 'command': '__org.qemu_x-command', 'data': { 'a': ['__org.qemu_x-Enum'], 'b': ['__org.qemu_x-Struct'],
tests/qapi-schema/qapi-schema-test.out +4 -2
@@ -274,6 +274,9 @@ object __org.qemu_x-Union1 member type: __org.qemu_x-Union1Kind optional=False tag type case __org.qemu_x-branch: q_obj_str-wrapper +alternate __org.qemu_x-Alt1 + tag type + case __org.qemu_x-branch: str array __org.qemu_x-Union1List __org.qemu_x-Union1 object __org.qemu_x-Struct2 member array: __org.qemu_x-Union1List optional=False
@@ -283,8 +286,7 @@ object __org.qemu_x-Union2 case __org.qemu_x-value: __org.qemu_x-Struct2 alternate __org.qemu_x-Alt tag type - case __org.qemu_x-branch: str - case b: __org.qemu_x-Base + case __org.qemu_x-branch: __org.qemu_x-Base event __ORG.QEMU_X-EVENT __org.qemu_x-Struct boxed=False array __org.qemu_x-EnumList __org.qemu_x-Enum
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 09/16] qapi: Permit alternates with just one branch
Quoted 9 lines · Markus Armbruster
A union or alternate without branches makes no sense and doesn't work:
it can't be instantiated. A union or alternate with just one branch works, but is degenerate. We accept the former, but reject the latter. Weird.docs/devel/qapi-code-gen.txtdoesn't mention the difference. It claims an alternate definition is "is similar to a simple union type".Permit degenerate alternates to make them consistent with unions.
Quoted 8 lines
Signed-off-by Markus Armbruster <[email protected]>--- scripts/qapi/common.py | 6 ++---- tests/qapi-schema/alternate-empty.err | 2 +- tests/qapi-schema/alternate-empty.json | 4 ++-- tests/qapi-schema/qapi-schema-test.json | 4 +++- tests/qapi-schema/qapi-schema-test.out | 6 ++++-- 5 files changed, 12 insertions(+), 10 deletions(-)
(Might make sense if one of the branches is conditional, where depending on compile-time options it could be a two-branch or a one-branch alternate)
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 09/16] qapi: Permit alternates with just one branch
Quoted 19 lines · Eric Blake
Quoted 9 lines · Markus Armbruster
A union or alternate without branches makes no sense and doesn't work:
it can't be instantiated. A union or alternate with just one branch works, but is degenerate. We accept the former, but reject the latter. Weird.docs/devel/qapi-code-gen.txtdoesn't mention the difference. It claims an alternate definition is "is similar to a simple union type".Permit degenerate alternates to make them consistent with unions.
Quoted 8 lines
Signed-off-by Markus Armbruster <[email protected]>--- scripts/qapi/common.py | 6 ++---- tests/qapi-schema/alternate-empty.err | 2 +- tests/qapi-schema/alternate-empty.json | 4 ++-- tests/qapi-schema/qapi-schema-test.json | 4 +++- tests/qapi-schema/qapi-schema-test.out | 6 ++++-- 5 files changed, 12 insertions(+), 10 deletions(-)
Quoted 4 lines
Reviewed-by Eric Blake <[email protected]>(Might make sense if one of the branches is conditional, where depending on compile-time options it could be a two-branch or a one-branch alternate)
The QAPI generator doesn't even try to reason about conditions. It happily lets you define a union or alternate with branches that are all conditional, and where the conditions are all false for a particular build configuration. Ensuring the QAPI schema is sane for all build configurations is the schema author's problem.
PATCH v2 10/16 qapi: Permit omitting all flat union branches
In reply to Markus ArmbrusterAbsent flat union branches default to the empty struct (since commit 800877bb16 "qapi: allow empty branches in flat unions"). But am attempt to omit all of them is rejected with "Union 'FOO' has no branches". Harmless oddity, but it's easy to avoid, so do that.
--- docs/devel/qapi-code-gen.txt | 3 +-- scripts/qapi/common.py | 16 ++++++++-------- tests/qapi-schema/flat-union-empty.err | 2 +- tests/qapi-schema/flat-union-empty.json | 2 +- tests/qapi-schema/qapi-schema-test.json | 5 +++++ tests/qapi-schema/qapi-schema-test.out | 9 +++++++++ tests/qapi-schema/union-empty.err | 2 +- tests/qapi-schema/union-empty.json | 2 +- 8 files changed, 27 insertions(+), 14 deletions(-)
docs/devel/qapi-code-gen.txt +1 -2
@@ -436,8 +436,7 @@ Union types are used to let the user choose between several different variants for an object. There are two flavors: simple (no discriminator or base), and flat (both discriminator and base). A union type is defined using a data dictionary as explained in the following -paragraphs. The data dictionary for either type of union must not -be empty. +paragraphs. Unions must have at least one branch. A simple union type defines a mapping from automatic discriminator values to data types like in this example:
scripts/qapi/common.py +8 -8
@@ -849,7 +849,7 @@ def check_union(expr, info): # With no discriminator it is a simple union. if discriminator is None: - enum_define = None + enum_values = members.keys() allow_metas = ['built-in', 'union', 'alternate', 'struct', 'enum'] if base is not None: raise QAPISemError(info, "Simple union '%s' must not have a base" %
@@ -882,16 +882,17 @@ def check_union(expr, info): 'must not be conditional' % (base, discriminator, name)) enum_define = enum_types.get(discriminator_value['type']) - allow_metas = ['struct'] # Do not allow string discriminator if not enum_define: raise QAPISemError(info, "Discriminator '%s' must be of enumeration " "type" % discriminator) + enum_values = enum_get_names(enum_define) + allow_metas = ['struct'] + + if (len(enum_values) == 0): + raise QAPISemError(info, "Union '%s' has no branches" % name) - # Check every branch; don't allow an empty union - if len(members) == 0: - raise QAPISemError(info, "Union '%s' cannot have empty 'data'" % name) for (key, value) in members.items(): check_name(info, "Member of union '%s'" % name, key)
@@ -904,8 +905,8 @@ def check_union(expr, info): # If the discriminator names an enum type, then all members # of 'data' must also be members of the enum type. - if enum_define: - if key not in enum_get_names(enum_define): + if discriminator is not None: + if key not in enum_values: raise QAPISemError(info, "Discriminator value '%s' is not found in " "enum '%s'"
@@ -1575,7 +1576,6 @@ class QAPISchemaObjectTypeVariants(object): assert bool(tag_member) != bool(tag_name) assert (isinstance(tag_name, str) or isinstance(tag_member, QAPISchemaObjectTypeMember)) - assert len(variants) > 0 for v in variants: assert isinstance(v, QAPISchemaObjectTypeVariant) self._tag_name = tag_name
tests/qapi-schema/flat-union-empty.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/flat-union-empty.json:4: Union 'Union' cannot have empty 'data' +tests/qapi-schema/flat-union-empty.json:4: Union 'Union' has no branches
tests/qapi-schema/flat-union-empty.json +1 -1
@@ -1,4 +1,4 @@ -# flat unions cannot be empty +# flat union discriminator cannot be empty { 'enum': 'Empty', 'data': [ ] } { 'struct': 'Base', 'data': { 'type': 'Empty' } } { 'union': 'Union', 'base': 'Base', 'discriminator': 'type', 'data': { } }
tests/qapi-schema/qapi-schema-test.json +5 -0
@@ -25,6 +25,11 @@ { 'struct': 'Empty1', 'data': { } } { 'struct': 'Empty2', 'base': 'Empty1', 'data': { } } +# Likewise for an empty flat union +{ 'union': 'Union', + 'base': { 'type': 'EnumOne' }, 'discriminator': 'type', + 'data': { } } + { 'command': 'user_def_cmd0', 'data': 'Empty2', 'returns': 'Empty2' } # for testing override of default naming heuristic
tests/qapi-schema/qapi-schema-test.out +9 -0
@@ -23,6 +23,15 @@ enum MyEnum object Empty1 object Empty2 base Empty1 +object q_obj_Union-base + member type: EnumOne optional=False +object Union + base q_obj_Union-base + tag type + case value1: q_empty + case value2: q_empty + case value3: q_empty + case value4: q_empty command user_def_cmd0 Empty2 -> Empty2 gen=True success_response=True boxed=False oob=False preconfig=False enum QEnumTwo
tests/qapi-schema/union-empty.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/union-empty.json:2: Union 'Union' cannot have empty 'data' +tests/qapi-schema/union-empty.json:2: Union 'Union' has no branches
tests/qapi-schema/union-empty.json +1 -1
@@ -1,2 +1,2 @@ -# unions cannot be empty +# simple unions cannot be empty { 'union': 'Union', 'data': { } }
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 10/16] qapi: Permit omitting all flat union branches
Quoted 7 lines · Markus Armbruster
Absent flat union branches default to the empty struct (since commit
800877bb16"qapi: allow empty branches in flat unions"). But am attempt to omit all of them is rejected with "Union 'FOO' has no branches". Harmless oddity, but it's easy to avoid, so do that.Signed-off-by Markus Armbruster <[email protected]>---
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
PATCH v2 11/16 qapi: Adjust frontend errors to say enum value, not member
In reply to Markus ArmbrusterFor consistency with docs/devel/qapi-code-gen.txt.
--- scripts/qapi/common.py | 11 ++++++++--- tests/qapi-schema/enum-clash-member.err | 2 +- tests/qapi-schema/enum-member-case.err | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-)
scripts/qapi/common.py +8 -3
@@ -1337,7 +1337,7 @@ class QAPISchemaEnumType(QAPISchemaType): def __init__(self, name, info, doc, ifcond, members, prefix): QAPISchemaType.__init__(self, name, info, doc, ifcond) for m in members: - assert isinstance(m, QAPISchemaMember) + assert isinstance(m, QAPISchemaEnumMember) m.set_owner(name) assert prefix is None or isinstance(prefix, str) self.members = members
@@ -1548,6 +1548,10 @@ class QAPISchemaMember(object): return "'%s' %s" % (self.name, self._pretty_owner()) +class QAPISchemaEnumMember(QAPISchemaMember): + role = 'value' + + class QAPISchemaFeature(QAPISchemaMember): role = 'feature'
@@ -1804,7 +1808,8 @@ class QAPISchema(object): return [QAPISchemaFeature(f['name'], f.get('if')) for f in features] def _make_enum_members(self, values): - return [QAPISchemaMember(v['name'], v.get('if')) for v in values] + return [QAPISchemaEnumMember(v['name'], v.get('if')) + for v in values] def _make_implicit_enum_type(self, name, info, ifcond, values): # See also QAPISchemaObjectTypeMember._pretty_owner()
@@ -2220,7 +2225,7 @@ const QEnumLookup %(c_name)s_lookup = { def gen_enum(name, members, prefix=None): # append automatically generated _MAX value - enum_members = members + [QAPISchemaMember('_MAX')] + enum_members = members + [QAPISchemaEnumMember('_MAX')] ret = mcgen('''
tests/qapi-schema/enum-clash-member.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/enum-clash-member.json:2: 'one_two' (member of MyEnum) collides with 'one-two' (member of MyEnum) +tests/qapi-schema/enum-clash-member.json:2: 'one_two' (value of MyEnum) collides with 'one-two' (value of MyEnum)
tests/qapi-schema/enum-member-case.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/enum-member-case.json:4: 'Value' (member of NoWayThisWillGetWhitelisted) should not use uppercase +tests/qapi-schema/enum-member-case.json:4: 'Value' (value of NoWayThisWillGetWhitelisted) should not use uppercase
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 11/16] qapi: Adjust frontend errors to say enum value, not member
Quoted 9 lines · Markus Armbruster
For consistency with
docs/devel/qapi-code-gen.txt.Signed-off-by Markus Armbruster <[email protected]>--- scripts/qapi/common.py | 11 ++++++++--- tests/qapi-schema/enum-clash-member.err | 2 +- tests/qapi-schema/enum-member-case.err | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-)
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
PATCH v2 12/16 docs/devel/qapi-code-gen: Reorder sections for readability
In reply to Markus ArmbrusterSection "QMP/Guest agent schema" starts with a brief introduction, then subsection "Comments", then subsection "Schema overview" (more elaborate introduction), and only then talks about schema entities like types, commands, and so forth.
Subsection "Comments" is long and tiring: almost 500 words, mostly about doc comments. Move the doc comment part to its own subsection "Documentation comments" at the very end of "QMP/Guest agent schema".
Subsection "Schema overview" explains naming rules at considerable
length: 250 words. Move this part to its own subsection "Naming rules and reserved names" right after the subsections on schema entities.
Subsection "Enumeration types" is wedged between "Struct types" and "Union types". Move it before "Struct types".
--- docs/devel/qapi-code-gen.txt | 436 ++++++++++++++++++----------------- 1 file changed, 221 insertions(+), 215 deletions(-)
docs/devel/qapi-code-gen.txt +221 -215
@@ -50,147 +50,6 @@ schema requires the use of JSON numbers or null. Comments are allowed; anything between an unquoted # and the following newline is ignored. -A multi-line comment that starts and ends with a '##' line is a -documentation comment. These are parsed by the documentation -generator, which recognizes certain markup detailed below. - - -==== Documentation markup ==== - -Comment text starting with '=' is a section title: - - # = Section title - -Double the '=' for a subsection title: - - # == Subsection title - -'|' denotes examples: - - # | Text of the example, may span - # | multiple lines - -'*' starts an itemized list: - - # * First item, may span - # multiple lines - # * Second item - -You can also use '-' instead of '*'. - -A decimal number followed by '.' starts a numbered list: - - # 1. First item, may span - # multiple lines - # 2. Second item - -The actual number doesn't matter. You could even use '*' instead of -'2.' for the second item. - -Lists can't be nested. Blank lines are currently not supported within -lists. - -Additional whitespace between the initial '#' and the comment text is -permitted. - -*foo* and _foo_ are for strong and emphasis styles respectively (they -do not work over multiple lines). @foo is used to reference a name in -the schema. - -Example: - -## -# = Section -# == Subsection -# -# Some text foo with *strong* and _emphasis_ -# 1. with a list -# 2. like that -# -# And some code: -# | $ echo foo -# | -> do this -# | <- get that -# -## - - -==== Expression documentation ==== - -Expressions other than include and pragma directives may be preceded -by a documentation block. Such blocks are called expression -documentation blocks. - -When documentation is required (see pragma 'doc-required'), expression -documentation blocks are mandatory. - -The documentation block consists of a first line naming the -expression, an optional overview, a description of each argument (for -commands and events) or member (for structs, unions and alternates), -and optional tagged sections. - -FIXME: the parser accepts these things in almost any order. - -Extensions added after the expression was first released carry a -'(since x.y.z)' comment. - -A tagged section starts with one of the following words: -"Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:". -The section ends with the start of a new section. - -A 'Since: x.y.z' tagged section lists the release that introduced the -expression. - -For example: - -## -# @BlockStats: -# -# Statistics of a virtual block device or a block backing device. -# -# @device: If the stats are for a virtual block device, the name -# corresponding to the virtual block device. -# -# @node-name: The node name of the device. (since 2.3) -# -# ... more members ... -# -# Since: 0.14.0 -## -{ 'struct': 'BlockStats', - 'data': {'*device': 'str', '*node-name': 'str', - ... more members ... } } - -## -# @query-blockstats: -# -# Query the @BlockStats for all virtual block devices. -# -# @query-nodes: If true, the command will query all the -# block nodes ... explain, explain ... (since 2.3) -# -# Returns: A list of @BlockStats for each virtual block devices. -# -# Since: 0.14.0 -# -# Example: -# -# -> { "execute": "query-blockstats" } -# <- { -# ... lots of output ... -# } -# -## -{ 'command': 'query-blockstats', - 'data': { '*query-nodes': 'bool' }, - 'returns': ['BlockStats'] } - -==== Free-form documentation ==== - -A documentation block that isn't an expression documentation block is -a free-form documentation block. These may be used to provide -additional text and structuring content. - === Schema overview ===
@@ -217,43 +76,6 @@ refers to a single-dimension array of that type; multi-dimension arrays are not directly supported (although an array of a complex struct that contains an array member is possible). -All names must begin with a letter, and contain only ASCII letters, -digits, hyphen, and underscore. There are two exceptions: enum values -may start with a digit, and names that are downstream extensions (see -section Downstream extensions) start with underscore. - -Names beginning with 'q_' are reserved for the generator, which uses -them for munging QMP names that resemble C keywords or other -problematic strings. For example, a member named "default" in qapi -becomes "q_default" in the generated C code. - -Types, commands, and events share a common namespace. Therefore, -generally speaking, type definitions should always use CamelCase for -user-defined type names, while built-in types are lowercase. - -Type names ending with 'Kind' or 'List' are reserved for the -generator, which uses them for implicit union enums and array types, -respectively. - -Command names, and member names within a type, should be all lower -case with words separated by a hyphen. However, some existing older -commands and complex types use underscore; when extending such -expressions, consistency is preferred over blindly avoiding -underscore. - -Event names should be ALL_CAPS with words separated by underscore. - -Member name 'u' and names starting with 'has-' or 'has_' are reserved -for the generator, which uses them for unions and for tracking -optional members. - -Any name (command, event, type, member, or enum value) beginning with -"x-" is marked experimental, and may be withdrawn or changed -incompatibly in a future release. - -Pragma 'name-case-whitelist' lets you violate the rules on use of -upper and lower case. Use for new code is strongly discouraged. - In the rest of this document, usage lines are given for each expression type, with literal strings written in lower case and placeholders written in capitals. If a literal string includes a
@@ -328,6 +150,43 @@ Pragma 'name-case-whitelist' takes a list of names that may violate rules on use of upper- vs. lower-case letters. Default is none. +=== Enumeration types === + +Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING } + { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING } + +An enumeration type is a dictionary containing a single 'data' key +whose value is a list of strings. An example enumeration is: + + { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] } + +Nothing prevents an empty enumeration, although it is probably not +useful. The list of strings should be lower case; if an enum name +represents multiple words, use '-' between words. The string 'max' is +not allowed as an enum value, and values should not be repeated. + +The enum constants will be named by using a heuristic to turn the +type name into a set of underscore separated words. For the example +above, 'MyEnum' will turn into 'MY_ENUM' giving a constant name +of 'MY_ENUM_VALUE1' for the first value. If the default heuristic +does not result in a desirable name, the optional 'prefix' member +can be used when defining the enum. + +The enumeration values are passed as strings over the Client JSON +Protocol, but are encoded as C enum integral values in generated code. +While the C code starts numbering at 0, it is better to use explicit +comparisons to enum values than implicit comparisons to 0; the C code +will also include a generated enum member ending in _MAX for tracking +the size of the enum, useful when using common functions for +converting between strings and enum values. Since the wire format +always passes by name, it is acceptable to reorder or add new +enumeration members in any location without breaking clients of Client +JSON Protocol; however, removing enum values would break +compatibility. For any struct that has a member that will only contain +a finite set of string values, using an enum type for that member is +better than open-coding the member to be type 'str'. + + === Struct types === Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME }
@@ -389,43 +248,6 @@ both members like this: "backing": "/some/place/my-backing-file" } -=== Enumeration types === - -Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING } - { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING } - -An enumeration type is a dictionary containing a single 'data' key -whose value is a list of strings. An example enumeration is: - - { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] } - -Nothing prevents an empty enumeration, although it is probably not -useful. The list of strings should be lower case; if an enum name -represents multiple words, use '-' between words. The string 'max' is -not allowed as an enum value, and values should not be repeated. - -The enum constants will be named by using a heuristic to turn the -type name into a set of underscore separated words. For the example -above, 'MyEnum' will turn into 'MY_ENUM' giving a constant name -of 'MY_ENUM_VALUE1' for the first value. If the default heuristic -does not result in a desirable name, the optional 'prefix' member -can be used when defining the enum. - -The enumeration values are passed as strings over the Client JSON -Protocol, but are encoded as C enum integral values in generated code. -While the C code starts numbering at 0, it is better to use explicit -comparisons to enum values than implicit comparisons to 0; the C code -will also include a generated enum member ending in _MAX for tracking -the size of the enum, useful when using common functions for -converting between strings and enum values. Since the wire format -always passes by name, it is acceptable to reorder or add new -enumeration members in any location without breaking clients of Client -JSON Protocol; however, removing enum values would break -compatibility. For any struct that has a member that will only contain -a finite set of string values, using an enum type for that member is -better than open-coding the member to be type 'str'. - - === Union types === Usage: { 'union': STRING, 'data': DICT }
@@ -744,6 +566,46 @@ This expanded form is necessary if you want to make the feature conditional (see below in "Configuring the schema"). +=== Naming rules and reserved names === + +All names must begin with a letter, and contain only ASCII letters, +digits, hyphen, and underscore. There are two exceptions: enum values +may start with a digit, and names that are downstream extensions (see +section Downstream extensions) start with underscore. + +Names beginning with 'q_' are reserved for the generator, which uses +them for munging QMP names that resemble C keywords or other +problematic strings. For example, a member named "default" in qapi +becomes "q_default" in the generated C code. + +Types, commands, and events share a common namespace. Therefore, +generally speaking, type definitions should always use CamelCase for +user-defined type names, while built-in types are lowercase. + +Type names ending with 'Kind' or 'List' are reserved for the +generator, which uses them for implicit union enums and array types, +respectively. + +Command names, and member names within a type, should be all lower +case with words separated by a hyphen. However, some existing older +commands and complex types use underscore; when extending such +expressions, consistency is preferred over blindly avoiding +underscore. + +Event names should be ALL_CAPS with words separated by underscore. + +Member name 'u' and names starting with 'has-' or 'has_' are reserved +for the generator, which uses them for unions and for tracking +optional members. + +Any name (command, event, type, member, or enum value) beginning with +"x-" is marked experimental, and may be withdrawn or changed +incompatibly in a future release. + +Pragma 'name-case-whitelist' lets you violate the rules on use of +upper and lower case. Use for new code is strongly discouraged. + + === Downstream extensions === QAPI schema names that are externally visible, say in the Client JSON
@@ -814,6 +676,150 @@ The presence of 'if' keys in the schema is reflected through to the introspection output depending on the build configuration. +=== Documentation comments === + +A multi-line comment that starts and ends with a '##' line is a +documentation comment. These are parsed by the documentation +generator, which recognizes certain markup detailed below. + + +==== Documentation markup ==== + +Comment text starting with '=' is a section title: + + # = Section title + +Double the '=' for a subsection title: + + # == Subsection title + +'|' denotes examples: + + # | Text of the example, may span + # | multiple lines + +'*' starts an itemized list: + + # * First item, may span + # multiple lines + # * Second item + +You can also use '-' instead of '*'. + +A decimal number followed by '.' starts a numbered list: + + # 1. First item, may span + # multiple lines + # 2. Second item + +The actual number doesn't matter. You could even use '*' instead of +'2.' for the second item. + +Lists can't be nested. Blank lines are currently not supported within +lists. + +Additional whitespace between the initial '#' and the comment text is +permitted. + +*foo* and _foo_ are for strong and emphasis styles respectively (they +do not work over multiple lines). @foo is used to reference a name in +the schema. + +Example: + +## +# = Section +# == Subsection +# +# Some text foo with *strong* and _emphasis_ +# 1. with a list +# 2. like that +# +# And some code: +# | $ echo foo +# | -> do this +# | <- get that +# +## + + +==== Expression documentation ==== + +Expressions other than include and pragma directives may be preceded +by a documentation block. Such blocks are called expression +documentation blocks. + +When documentation is required (see pragma 'doc-required'), expression +documentation blocks are mandatory. + +The documentation block consists of a first line naming the +expression, an optional overview, a description of each argument (for +commands and events) or member (for structs, unions and alternates), +and optional tagged sections. + +FIXME: the parser accepts these things in almost any order. + +Extensions added after the expression was first released carry a +'(since x.y.z)' comment. + +A tagged section starts with one of the following words: +"Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:". +The section ends with the start of a new section. + +A 'Since: x.y.z' tagged section lists the release that introduced the +expression. + +For example: + +## +# @BlockStats: +# +# Statistics of a virtual block device or a block backing device. +# +# @device: If the stats are for a virtual block device, the name +# corresponding to the virtual block device. +# +# @node-name: The node name of the device. (since 2.3) +# +# ... more members ... +# +# Since: 0.14.0 +## +{ 'struct': 'BlockStats', + 'data': {'*device': 'str', '*node-name': 'str', + ... more members ... } } + +## +# @query-blockstats: +# +# Query the @BlockStats for all virtual block devices. +# +# @query-nodes: If true, the command will query all the +# block nodes ... explain, explain ... (since 2.3) +# +# Returns: A list of @BlockStats for each virtual block devices. +# +# Since: 0.14.0 +# +# Example: +# +# -> { "execute": "query-blockstats" } +# <- { +# ... lots of output ... +# } +# +## +{ 'command': 'query-blockstats', + 'data': { '*query-nodes': 'bool' }, + 'returns': ['BlockStats'] } + +==== Free-form documentation ==== + +A documentation block that isn't an expression documentation block is +a free-form documentation block. These may be used to provide +additional text and structuring content. + + == Client JSON Protocol introspection == Clients of a Client JSON Protocol commonly need to figure out what
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 12/16] docs/devel/qapi-code-gen: Reorder sections for readability
Quoted 13 lines · Markus Armbruster
Section "QMP/Guest agent schema" starts with a brief introduction, then subsection "Comments", then subsection "Schema overview" (more elaborate introduction), and only then talks about schema entities like types, commands, and so forth.
Subsection "Comments" is long and tiring: almost 500 words, mostly about doc comments. Move the doc comment part to its own subsection "Documentation comments" at the very end of "QMP/Guest agent schema".
Subsection "Schema overview" explains naming rules at considerable
length: 250 words. Move this part to its own subsection "Naming rules and reserved names" right after the subsections on schema entities.
Quoted 7 lines
Subsection "Enumeration types" is wedged between "Struct types" and "Union types". Move it before "Struct types".
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 436 ++++++++++++++++++----------------- 1 file changed, 221 insertions(+), 215 deletions(-)
Large patch, but mostly just shuffling sections.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
PATCH v2 13/16 docs/devel/qapi-code-gen: Rewrite compatibility considerations
In reply to Markus ArmbrusterWe have some compatibility advice buried in sections "Enumeration types" and "Struct types". Compatibility is actually about commands and events. It devolves to the types used there. All kinds of types, not just enumerations and structs.
Replace the existing advice by a new section "Compatibility considerations".
--- docs/devel/qapi-code-gen.txt | 95 +++++++++++++++++++++++------------- 1 file changed, 60 insertions(+), 35 deletions(-)
docs/devel/qapi-code-gen.txt +60 -35
@@ -178,14 +178,11 @@ While the C code starts numbering at 0, it is better to use explicit comparisons to enum values than implicit comparisons to 0; the C code will also include a generated enum member ending in _MAX for tracking the size of the enum, useful when using common functions for -converting between strings and enum values. Since the wire format -always passes by name, it is acceptable to reorder or add new -enumeration members in any location without breaking clients of Client -JSON Protocol; however, removing enum values would break -compatibility. For any struct that has a member that will only contain -a finite set of string values, using an enum type for that member is -better than open-coding the member to be type 'str'. +converting between strings and enum values. +For any struct that has a member that will only contain a finite set +of string values, using an enum type for that member is better than +open-coding the member to be type 'str'. === Struct types ===
@@ -203,34 +200,6 @@ name. An example of a struct is: The use of '*' as a prefix to the name means the member is optional in the corresponding JSON protocol usage. -The default initialization value of an optional argument should not be changed -between versions of QEMU unless the new default maintains backward -compatibility to the user-visible behavior of the old default. - -With proper documentation, this policy still allows some flexibility; for -example, documenting that a default of 0 picks an optimal buffer size allows -one release to declare the optimal size at 512 while another release declares -the optimal size at 4096 - the user-visible behavior is not the bytes used by -the buffer, but the fact that the buffer was optimal size. - -On input structures (only mentioned in the 'data' side of a command), changing -from mandatory to optional is safe (older clients will supply the option, and -newer clients can benefit from the default); changing from optional to -mandatory is backwards incompatible (older clients may be omitting the option, -and must continue to work). - -On output structures (only mentioned in the 'returns' side of a command), -changing from mandatory to optional is in general unsafe (older clients may be -expecting the member, and could crash if it is missing), although it -can be done if the only way that the optional argument will be omitted -is when it is triggered by the presence of a new input flag to the -command that older clients don't know to send. Changing from optional -to mandatory is safe. - -A structure that is used in both input and output of various commands -must consider the backwards compatibility constraints of both directions -of use. - A struct definition can specify another struct as its base. In this case, the members of the base type are included as top-level members of the new struct's dictionary in the Client JSON Protocol wire
@@ -1037,6 +1006,62 @@ the names of built-in types. Clients should examine member "json-type" instead of hard-coding names of built-in types. +== Compatibility considerations == + +Maintaining backward compatibility at the Client JSON Protocol level +while evolving the schema requires some care. This section is about +syntactic compatibility. Necessary, but not sufficient for actual +compatibility. + +Clients send commands with argument data, and receive command +responses with return data and events with event data. + +Adding opt-in functionality to the send direction is backwards +compatible: adding commands, optional arguments, enumeration values, +union and alternate branches; turning an argument type into an +alternate of that type; making mandatory arguments optional. Clients +oblivious of the new functionality continue to work. + +Incompatible changes include removing commands, command arguments, +enumeration values, union and alternate branches, adding mandatory +command arguments, and making optional arguments mandatory. + +The specified behavior of an absent optional argument should remain +the same. With proper documentation, this policy still allows some +flexibility; for example, when an optional 'buffer-size' argument is +specified to default to a sensible buffer size, the actual default +value can still be changed. The specified default behavior is not the +exact size of the buffer, only that the default size is sensible. + +Adding functionality to the receive direction is generally backwards +compatible: adding events, adding return and event data members. +Clients are expected to ignore the ones they don't know. + +Removing "unreachable" stuff like events that can't be triggered +anymore, optional return or event data members that can't be sent +anymore, and return or event data member (enumeration) values that +can't be sent anymore makes no difference to clients, except for +introspection. The latter can conceivably confuse clients, so tread +carefully. + +Incompatible changes include removing return and event data members. + +Any change to a command definition's 'data' or one of the types used +there (recursively) needs to consider send direction compatibility. + +Any change to a command definition's 'return', an event definition's +'data', or one of the types used there (recursively) needs to consider +receive direction compatibility. + +Any change to types used in both contexts need to consider both. + +Members of enumeration types, complex types and alternate types may be +reordered freely. For enumerations and alternate types, this doesn't +affect the wire encoding. For complex types, this might make the +implementation emit JSON object members in a different order, which +the Client JSON Protocol permits. + + == Code generation == The QAPI code generator qapi-gen.py generates code and documentation
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 13/16] docs/devel/qapi-code-gen: Rewrite compatibility considerations
Quoted 15 lines · Markus Armbruster
We have some compatibility advice buried in sections "Enumeration types" and "Struct types". Compatibility is actually about commands and events. It devolves to the types used there. All kinds of types, not just enumerations and structs.
Replace the existing advice by a new section "Compatibility considerations".
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 95 +++++++++++++++++++++++------------- 1 file changed, 60 insertions(+), 35 deletions(-)+== Compatibility considerations ==
docs/devel/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 1014
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+ +Maintaining backward compatibility at the Client JSON Protocol level +while evolving the schema requires some care. This section is about +syntactic compatibility. Necessary, but not sufficient for actual +compatibility.
This last sentence no verb. Maybe:
s/compatibility. Necessary/compatibility, which is necessary/ s/sufficient/sufficient,/
Quoted 38 lines
docs/devel/qapi-code-gen.txt +38
-0+ +Clients send commands with argument data, and receive command +responses with return data and events with event data. + +Adding opt-in functionality to the send direction is backwards +compatible: adding commands, optional arguments, enumeration values, +union and alternate branches; turning an argument type into an +alternate of that type; making mandatory arguments optional. Clients +oblivious of the new functionality continue to work. + +Incompatible changes include removing commands, command arguments, +enumeration values, union and alternate branches, adding mandatory +command arguments, and making optional arguments mandatory. + +The specified behavior of an absent optional argument should remain +the same. With proper documentation, this policy still allows some +flexibility; for example, when an optional 'buffer-size' argument is +specified to default to a sensible buffer size, the actual default +value can still be changed. The specified default behavior is not the +exact size of the buffer, only that the default size is sensible. + +Adding functionality to the receive direction is generally backwards +compatible: adding events, adding return and event data members. +Clients are expected to ignore the ones they don't know. + +Removing "unreachable" stuff like events that can't be triggered +anymore, optional return or event data members that can't be sent +anymore, and return or event data member (enumeration) values that +can't be sent anymore makes no difference to clients, except for +introspection. The latter can conceivably confuse clients, so tread +carefully. + +Incompatible changes include removing return and event data members. + +Any change to a command definition's 'data' or one of the types used +there (recursively) needs to consider send direction compatibility. + +Any change to a command definition's 'return', an event definition's
docs/devel/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 1062
Quoted 10 lines
docs/devel/qapi-code-gen.txt +10
-0+'data', or one of the types used there (recursively) needs to consider +receive direction compatibility. + +Any change to types used in both contexts need to consider both. + +Members of enumeration types, complex types and alternate types may be +reordered freely. For enumerations and alternate types, this doesn't +affect the wire encoding. For complex types, this might make the +implementation emit JSON object members in a different order, which +the Client JSON Protocol permits.
Worth mentioning that type names themselves are NOT part of the interface, and may be freely renamed?
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 13/16] docs/devel/qapi-code-gen: Rewrite compatibility considerations
Quoted 24 lines · Eric Blake
Quoted 15 lines · Markus Armbruster
We have some compatibility advice buried in sections "Enumeration types" and "Struct types". Compatibility is actually about commands and events. It devolves to the types used there. All kinds of types, not just enumerations and structs.
Replace the existing advice by a new section "Compatibility considerations".
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 95 +++++++++++++++++++++++------------- 1 file changed, 60 insertions(+), 35 deletions(-)+== Compatibility considerations ==
docs/devel/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 1014
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+ +Maintaining backward compatibility at the Client JSON Protocol level +while evolving the schema requires some care. This section is about +syntactic compatibility. Necessary, but not sufficient for actual +compatibility.This last sentence no verb. Maybe:
Quoted 2 lines
s/compatibility. Necessary/compatibility, which is necessary/ s/sufficient/sufficient,/
Sold.
Quoted 43 lines
Quoted 43 lines
docs/devel/qapi-code-gen.txt +43
-0+ +Clients send commands with argument data, and receive command +responses with return data and events with event data. + +Adding opt-in functionality to the send direction is backwards +compatible: adding commands, optional arguments, enumeration values, +union and alternate branches; turning an argument type into an +alternate of that type; making mandatory arguments optional. Clients +oblivious of the new functionality continue to work. + +Incompatible changes include removing commands, command arguments, +enumeration values, union and alternate branches, adding mandatory +command arguments, and making optional arguments mandatory. + +The specified behavior of an absent optional argument should remain +the same. With proper documentation, this policy still allows some +flexibility; for example, when an optional 'buffer-size' argument is +specified to default to a sensible buffer size, the actual default +value can still be changed. The specified default behavior is not the +exact size of the buffer, only that the default size is sensible. + +Adding functionality to the receive direction is generally backwards +compatible: adding events, adding return and event data members. +Clients are expected to ignore the ones they don't know. + +Removing "unreachable" stuff like events that can't be triggered +anymore, optional return or event data members that can't be sent +anymore, and return or event data member (enumeration) values that +can't be sent anymore makes no difference to clients, except for +introspection. The latter can conceivably confuse clients, so tread +carefully. + +Incompatible changes include removing return and event data members. + +Any change to a command definition's 'data' or one of the types used +there (recursively) needs to consider send direction compatibility. + +Any change to a command definition's 'return', an event definition's +'data', or one of the types used there (recursively) needs to consider +receive direction compatibility. + +Any change to types used in both contexts need to consider both. +
Quoted 8 lines
docs/devel/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 1062
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+Members of enumeration types, complex types and alternate types may be +reordered freely. For enumerations and alternate types, this doesn't +affect the wire encoding. For complex types, this might make the +implementation emit JSON object members in a different order, which +the Client JSON Protocol permits.Worth mentioning that type names themselves are NOT part of the interface, and may be freely renamed?
Care to suggest a suitable sentence?
Quoted 1 line
Reviewed-by Eric Blake <[email protected]>
Thanks!
Re: [Qemu-devel] [PATCH v2 13/16] docs/devel/qapi-code-gen: Rewrite compatibility considerations
Quoted 18 lines · Markus Armbruster
Quoted 9 lines
Quoted 9 lines
docs/devel/qapi-code-gen.txt +9
-0+Any change to a command definition's 'data' or one of the types used +there (recursively) needs to consider send direction compatibility. + +Any change to a command definition's 'return', an event definition's +'data', or one of the types used there (recursively) needs to consider +receive direction compatibility. + +Any change to types used in both contexts need to consider both. +Quoted 8 lines
docs/devel/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 1062
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+Members of enumeration types, complex types and alternate types may be +reordered freely. For enumerations and alternate types, this doesn't +affect the wire encoding. For complex types, this might make the +implementation emit JSON object members in a different order, which +the Client JSON Protocol permits.Worth mentioning that type names themselves are NOT part of the interface, and may be freely renamed?
Quoted 1 line
Care to suggest a suitable sentence?
Although member names within a type cannot be changed without affecting compatibility, changes to type names themselves do not affect the protocol. As such, complex types may be freely renamed or refactored, such as splitting members from one type into a common base type, as long as the resulting set of members remain compatible.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 13/16] docs/devel/qapi-code-gen: Rewrite compatibility considerations
Quoted 20 lines · Eric Blake
Quoted 18 lines · Markus Armbruster
Quoted 17 lines
Quoted 4 lines
docs/devel/qapi-code-gen.txt +4
-0+Any change to a command definition's 'data' or one of the types used +there (recursively) needs to consider send direction compatibility. + +Any change to a command definition's 'return', an event definition'sdocs/devel/qapi-code-gen.txt the names of built-in types. Clients should examine member · line 1062
Quoted 10 lines
docs/devel/qapi-code-gen.txt +10
-0+'data', or one of the types used there (recursively) needs to consider +receive direction compatibility. + +Any change to types used in both contexts need to consider both. + +Members of enumeration types, complex types and alternate types may be +reordered freely. For enumerations and alternate types, this doesn't +affect the wire encoding. For complex types, this might make the +implementation emit JSON object members in a different order, which +the Client JSON Protocol permits.Worth mentioning that type names themselves are NOT part of the interface, and may be freely renamed?
Quoted 4 lines
Quoted 1 line
Care to suggest a suitable sentence?
Although member names within a type cannot be changed without affecting compatibility,
This part seems redundant with the previous paragraph.
Quoted 2 lines
changes to type names themselves do not affect the
protocol. As such, complex types may be freely renamed or refactored,
All types (enums, structs, simple & flat unions, alternates) actually, not just complex ones (structs, unions).
Quoted 2 lines
such as splitting members from one type into a common base type, as long as the resulting set of members remain compatible.
What does it mean for a set of members to be compatible? We don't actually define that...
What about:
Since type names are not visible in the Client JSON Protocol, types may be freely renamed. Even certain refactorings are invisible, such as splitting members from one type into a common base type.
Re: [Qemu-devel] [PATCH v2 13/16] docs/devel/qapi-code-gen: Rewrite compatibility considerations
Quoted 19 lines · Markus Armbruster
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
Worth mentioning that type names themselves are NOT part of the interface, and may be freely renamed?
Care to suggest a suitable sentence?
Although member names within a type cannot be changed without affecting compatibility,
This part seems redundant with the previous paragraph.
Quoted 2 lines
changes to type names themselves do not affect the
protocol. As such, complex types may be freely renamed or refactored,All types (enums, structs, simple & flat unions, alternates) actually, not just complex ones (structs, unions).
Quoted 2 lines
such as splitting members from one type into a common base type, as long as the resulting set of members remain compatible.
Quoted 8 lines
What does it mean for a set of members to be compatible? We don't actually define that...
What about:
Since type names are not visible in the Client JSON Protocol, types may be freely renamed. Even certain refactorings are invisible, such as splitting members from one type into a common base type.
Seems reasonable to me.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
PATCH v2 14/16 docs/devel/qapi-code-gen: Rewrite introduction to schema
In reply to Markus ArmbrusterThe introduction to the QAPI schema is somewhat rambling. Rewrite for clarity.
--- docs/devel/qapi-code-gen.txt | 106 ++++++++++++++++------------------- 1 file changed, 47 insertions(+), 59 deletions(-)
docs/devel/qapi-code-gen.txt +47 -59
@@ -16,65 +16,53 @@ well as the QEMU Guest Agent (QGA) for communicating with the guest. The remainder of this document uses "Client JSON Protocol" when referring to the wire contents of a QMP or QGA connection. -To map Client JSON Protocol interfaces to the native C QAPI -implementations, a JSON-based schema is used to define types and -function signatures, and a set of scripts is used to generate types, -signatures, and marshaling/dispatch code. This document will describe -how the schemas, scripts, and resulting code are used. - - -== QMP/Guest agent schema == - -A QAPI schema file is designed to be loosely based on JSON -(http://www.ietf.org/rfc/rfc8259.txt) with changes for quoting style -and the use of comments; a QAPI schema file is then parsed by a python -code generation program. A valid QAPI schema consists of a series of -top-level expressions, with no commas between them. Where -dictionaries (JSON objects) are used, they are parsed as python -OrderedDicts so that ordering is preserved (for predictable layout of -generated C structs and parameter lists). Ordering doesn't matter -between top-level expressions or the keys within an expression, but -does matter within dictionary values for 'data' and 'returns' members -of a single expression. QAPI schema input is written using 'single -quotes' instead of JSON's "double quotes" (in contrast, Client JSON -Protocol uses no comments, and while input accepts 'single quotes' as -an extension, output is strict JSON using only "double quotes"). As -in JSON, trailing commas are not permitted in arrays or dictionaries. -Input must be ASCII (although QMP supports full Unicode strings, the -QAPI parser does not). At present, there is no place where a QAPI -schema requires the use of JSON numbers or null. - - -=== Comments === - -Comments are allowed; anything between an unquoted # and the following -newline is ignored. - - -=== Schema overview === - -The schema sets up a series of types, as well as commands and events -that will use those types. Forward references are allowed: the parser -scans in two passes, where the first pass learns all type names, and -the second validates the schema and generates the code. This allows -the definition of complex structs that can have mutually recursive -types, and allows for indefinite nesting of Client JSON Protocol that -satisfies the schema. A type name should not be defined more than -once. It is permissible for the schema to contain additional types -not used by any commands or events in the Client JSON Protocol, for -the side effect of generated C code used internally. - -There are eight top-level expressions recognized by the parser: -'include', 'pragma', 'command', 'struct', 'enum', 'union', -'alternate', and 'event'. There are several groups of types: simple -types (a number of built-in types, such as 'int' and 'str'; as well as -enumerations), complex types (structs and two flavors of unions), and -alternate types (a choice between other types). The 'command' and -'event' expressions can refer to existing types by name, or list an -anonymous type as a dictionary. Listing a type name inside an array -refers to a single-dimension array of that type; multi-dimension -arrays are not directly supported (although an array of a complex -struct that contains an array member is possible). +To map between Client JSON Protocol interfaces and the native C API, +we generate C code from a QAPI schema. This document describes the +QAPI schema language, and how it gets mapped to the Client JSON +Protocol and to C. It additionally provides guidance on maintaining +Client JSON Protocol compatibility. + + +== The QAPI schema language == + +The QAPI schema defines the Client JSON Protocol's commands and +events, as well as types used by them. Forward references are +allowed. + +It is permissible for the schema to contain additional types not used +by any commands or events, for the side effect of generated C code +used internally. + +There are several kinds of types: simple types (a number of built-in +types, such as 'int' and 'str'; as well as enumerations), arrays, +complex types (structs and two flavors of unions), and alternate types +(a choice between other types). + + +=== Schema syntax === + +Syntax is loosely based on JSON (http://www.ietf.org/rfc/rfc8259.txt). +Differences: + +* Comments: start with a hash character (#) that is not part of a + string, and extend to the end of the line. + +* Strings are enclosed in 'single quotes', not "double quotes". + +* Strings are restricted to ASCII. All control characters must be + escaped, even DEL. + +* Numbers are not supported. + +A QAPI schema consists of a series of top-level expressions (JSON +objects). Their order does not matter. + +The order of keys within JSON objects does not matter unless +explicitly noted. + +There are eight kinds of top-level expressions: 'include', 'pragma', +'command', 'struct', 'enum', 'union', 'alternate', and 'event'. These +are discussed in detail below. In the rest of this document, usage lines are given for each expression type, with literal strings written in lower case and
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 14/16] docs/devel/qapi-code-gen: Rewrite introduction to schema
Quoted 2 lines · Markus Armbruster
The introduction to the QAPI schema is somewhat rambling. Rewrite for clarity.
The curse of additions over time. Thanks for tackling this.
Quoted 9 lines
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 106 ++++++++++++++++------------------- 1 file changed, 47 insertions(+), 59 deletions(-)+=== Schema syntax ===
docs/devel/qapi-code-gen.txt +1
-0+
docs/devel/qapi-code-gen.txt well as the QEMU Guest Agent (QGA) for communicating with the guest. · line 53
Quoted 10 lines
docs/devel/qapi-code-gen.txt +10
-0+Syntax is loosely based on JSON (http://www.ietf.org/rfc/rfc8259.txt). +Differences: + +* Comments: start with a hash character (#) that is not part of a + string, and extend to the end of the line. + +* Strings are enclosed in 'single quotes', not "double quotes". + +* Strings are restricted to ASCII. All control characters must be + escaped, even DEL.
Or rather, control characters are not permitted. (May affect the earlier 7/16...)
Review
Quoted 2 lines
(quoted diff) +2
-0+ +* Numbers are not supported.
Yet. But if we allow default values, it won't be much longer before we get there. (Doesn't affect this patch)
docs/devel/qapi-code-gen.txt well as the QEMU Guest Agent (QGA) for communicating with the guest. · line 58
Quoted 3 lines
docs/devel/qapi-code-gen.txt +3
-0+ +A QAPI schema consists of a series of top-level expressions (JSON +objects). Their order does not matter.
Does the order of 'include' and/or 'pragma' matter?
Touchups seem minor enough that I trust you, so you can add:
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 14/16] docs/devel/qapi-code-gen: Rewrite introduction to schema
Quoted 13 lines · Eric Blake
Quoted 2 lines · Markus Armbruster
The introduction to the QAPI schema is somewhat rambling. Rewrite for clarity.
The curse of additions over time. Thanks for tackling this.
Quoted 6 lines
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 106 ++++++++++++++++------------------- 1 file changed, 47 insertions(+), 59 deletions(-)
Quoted 15 lines
docs/devel/qapi-code-gen.txt well as the QEMU Guest Agent (QGA) for communicating with the guest. · line 53
Quoted 12 lines
+=== Schema syntax ===
docs/devel/qapi-code-gen.txt +11
-0+ +Syntax is loosely based on JSON (http://www.ietf.org/rfc/rfc8259.txt). +Differences: + +* Comments: start with a hash character (#) that is not part of a + string, and extend to the end of the line. + +* Strings are enclosed in 'single quotes', not "double quotes". + +* Strings are restricted to ASCII. All control characters must be + escaped, even DEL.Or rather, control characters are not permitted. (May affect the earlier 7/16...)
I neglected to update this for v2. Will change to "Strings are restricted to printable ASCII, and escape sequences to just '\\'.
Quoted 11 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+ +* Numbers are not supported.Yet. But if we allow default values, it won't be much longer before we get there. (Doesn't affect this patch)
docs/devel/qapi-code-gen.txt well as the QEMU Guest Agent (QGA) for communicating with the guest. · line 58
Quoted 3 lines
docs/devel/qapi-code-gen.txt +3
-0+ +A QAPI schema consists of a series of top-level expressions (JSON +objects). Their order does not matter.Does the order of 'include' and/or 'pragma' matter?
Pragma no, because their scope is the complete schema.
Include no, as long as order doesn't matter for anything else.
Hmm, there's one thing that cares for order: generated documentation is in source order.
Hmm^2, subsection "Documentation comments" doesn't mention doc generation at all, and we also lack a dsubsection on it under section "Code generation".
I'll see what I can do for v3.
Quoted 2 lines
Touchups seem minor enough that I trust you, so you can add:
Reviewed-by Eric Blake <[email protected]>
Thanks!
PATCH v2 15/16 docs/devel/qapi-code-gen: Improve QAPI schema language doc
In reply to Markus ArmbrusterWe document the language by giving patterns of valid JSON objects. The patterns contain placeholders we don't define anywhere; their names have to speak for themselves. I guess they do, but I'd prefer a bit more rigor. Provide a grammar instead, and rework the text accordingly.
Documentation for QAPI schema conditionals (commit 967c885108, 6cc32b0e14, 87adbbffd4..3e270dcacc) and feature flags (commit 6a8c0b5102) was bolted on. The sections documenting types, commands and events don't mention them. Section "Features" and "Configuring the schema" then provide additional syntax for types, commands and events. I hate that. Fix the sections documenting types, commands and events to provide accurate syntax, and point to "Features" and "Configuring the schema" for details.
We talk about "(top-level) expressions other than include and pragma". Adopt more convenient terminology: a (top-level) expression is either a directive (include or pragma) or a definition (anything else).
Avoid the terms "dictionary" and "key". Stick to JSON terminology "object" and "member name" instead.
While there, make spacing more consistent.
--- docs/devel/qapi-code-gen.txt | 592 ++++++++++++++++++++++------------- 1 file changed, 369 insertions(+), 223 deletions(-)
docs/devel/qapi-code-gen.txt +369 -223
@@ -4,12 +4,12 @@ Copyright IBM Corp. 2011 Copyright (C) 2012-2016 Red Hat, Inc. This work is licensed under the terms of the GNU GPL, version 2 or -later. See the COPYING file in the top-level directory. +later. See the COPYING file in the top-level directory. == Introduction == QAPI is a native C API within QEMU which provides management-level -functionality to internal and external users. For external +functionality to internal and external users. For external users/processes, this interface is made available by a JSON-based wire format for the QEMU Monitor Protocol (QMP) for controlling qemu, as well as the QEMU Guest Agent (QGA) for communicating with the guest.
@@ -54,23 +54,46 @@ Differences: * Numbers are not supported. -A QAPI schema consists of a series of top-level expressions (JSON -objects). Their order does not matter. +A second layer of syntax defines the sequences of JSON texts that are +a correctly structured QAPI schema. We provide a grammar for this +syntax in an EBNF-like notation: -The order of keys within JSON objects does not matter unless +* Production rules look like non-terminal = expression +* Concatenation: Expression A B matches expression A, then B +* Alternation: Expression A | B matches expression A or B +* Repetition: Expression A... matches zero or more occurences of + expression A; expression A, ... likewise, but separated by , +* Grouping: Expression ( A ) matches expression A +* JSON's structural characters are terminals: { } [ ] : , +* JSON's literal names are terminals: false true null +* String literals enclosed in 'single quotes' are terminal, and match + this JSON string, with a leading '*' stripped off +* When JSON object member's name starts with '*', the member is + optional. +* The symbol STRING is a terminal, and matches any JSON string +* The symbol BOOL is a terminal, and matches JSON false or true +* ALL-CAPS words other than STRING are non-terminals + +The order of members within JSON objects does not matter unless explicitly noted. -There are eight kinds of top-level expressions: 'include', 'pragma', -'command', 'struct', 'enum', 'union', 'alternate', and 'event'. These -are discussed in detail below. - -In the rest of this document, usage lines are given for each -expression type, with literal strings written in lower case and -placeholders written in capitals. If a literal string includes a -prefix of '*', that key/value pair can be omitted from the expression. -For example, a usage statement that includes '*base':STRUCT-NAME -means that an expression has an optional key 'base', which if present -must have a value that forms a struct name. +A QAPI schema consists of a series of top-level expressions: + + SCHEMA = TOP-LEVEL-EXPR... + +The top-level expressions are all JSON objects. Their order does not +matter. + +A top-level expressions is either a directive or a definition: + + TOP-LEVEL-EXPR = DIRECTIVE | DEFINITION + +There are two kinds of directives and six kinds of definitions: + + DIRECTIVE = INCLUDE | PRAGMA + DEFINITION = ENUM | STRUCT | UNION | ALTERNATE | COMMAND | EVENT + +These are discussed in detail below. === Built-in Types ===
@@ -100,16 +123,16 @@ The following types are predefined, and map to C as follows: === Include directives === -Usage: { 'include': STRING } +Syntax: + INCLUDE = { 'include': STRING } The QAPI schema definitions can be modularized using the 'include' directive: { 'include': 'path/to/file.json' } -The directive is evaluated recursively, and include paths are relative to the -file using the directive. Multiple includes of the same file are -idempotent. No other keys should appear in the expression, and the include -value should be a string. +The directive is evaluated recursively, and include paths are relative +to the file using the directive. Multiple includes of the same file +are idempotent. As a matter of style, it is a good idea to have all files be self-contained, but at the moment, nothing prevents an included file
@@ -120,10 +143,12 @@ prevent incomplete include files. === Pragma directives === -Usage: { 'pragma': DICT } +Syntax: + PRAGMA = { 'pragma': { '*doc-required': BOOL }, + '*returns-whitelist': [ STRING, ... ], + '*name-case-whitelist': [ STRING, ... ] } The pragma directive lets you control optional generator behavior. -The dictionary's entries are pragma names and values. Pragma's scope is currently the complete schema. Setting the same pragma to different values in parts of the schema doesn't work.
@@ -140,60 +165,95 @@ rules on use of upper- vs. lower-case letters. Default is none. === Enumeration types === -Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING } - { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING } +Syntax: + ENUM = { 'enum': STRING, + 'data': [ ENUM-VALUE, ... ], + '*prefix': STRING, + '*if': COND } + ENUM-VALUE = STRING + | { 'name': STRING, '*if': COND } -An enumeration type is a dictionary containing a single 'data' key -whose value is a list of strings. An example enumeration is: +Member 'enum' names the enum type. + +Each member of the 'data' array defines a value of the enumeration +type. The form STRING is shorthand for { 'name': STRING }. The +'name' values must be be distinct. + +Example: { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] } Nothing prevents an empty enumeration, although it is probably not -useful. The list of strings should be lower case; if an enum name -represents multiple words, use '-' between words. The string 'max' is -not allowed as an enum value, and values should not be repeated. - -The enum constants will be named by using a heuristic to turn the -type name into a set of underscore separated words. For the example -above, 'MyEnum' will turn into 'MY_ENUM' giving a constant name -of 'MY_ENUM_VALUE1' for the first value. If the default heuristic -does not result in a desirable name, the optional 'prefix' member -can be used when defining the enum. - -The enumeration values are passed as strings over the Client JSON -Protocol, but are encoded as C enum integral values in generated code. -While the C code starts numbering at 0, it is better to use explicit -comparisons to enum values than implicit comparisons to 0; the C code -will also include a generated enum member ending in _MAX for tracking -the size of the enum, useful when using common functions for -converting between strings and enum values. - -For any struct that has a member that will only contain a finite set -of string values, using an enum type for that member is better than -open-coding the member to be type 'str'. +useful. + +On the wire, an enumeration type's value is represented by its +(string) name. In C, it's represented by an enumeration constant. +These are of the form PREFIX_NAME, where PREFIX is derived from the +enumeration type's name, and NAME from the value's name. For the +example above, the generator maps 'MyEnum' to MY_ENUM and 'value1' to +VALUE1, resulting in the enumeration constant MY_ENUM_VALUE1. The +optional 'prefix' member overrides PREFIX. + +The generated C enumeration constants have values 0, 1, ..., N-1 (in +QAPI schema order), where N is the number of values. There is an +additional enumeration constant PREFIX__MAX with value N. + +Do not use string or an integer type when an enumeration type can do +the job satisfactorily. + +The optional 'if' member specifies a conditional. See "Configuring +the schema" below for more on this. + + +=== Type references and array types === + +Syntax: + TYPE-REF = STRING | ARRAY-TYPE + ARRAY-TYPE = [ STRING ] + +A string denotes the type named by the string. + +A one-element array containing a string denotes an array of the type +named by the string. Example: ['int'] denotes an array of 'int'. + === Struct types === -Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME } +Syntax: + STRUCT = { 'struct': STRING, + 'data': MEMBERS, + '*base': STRING, + '*if': COND, + '*features': FEATURES } + MEMBERS = { MEMBER, ... } + MEMBER = STRING : TYPE-REF + | STRING : { 'type': TYPE-REF, '*if': COND } -A struct is a dictionary containing a single 'data' key whose value is -a dictionary; the dictionary may be empty. This corresponds to a -struct in C or an Object in JSON. Each value of the 'data' dictionary -must be the name of a type, or a one-element array containing a type -name. An example of a struct is: +Member 'struct' names the struct type. + +Each MEMBER of the 'data' object defines a member of the struct type. + +The MEMBER's STRING name consists of an optional '*' prefix and the +struct member name. If '*' is present, the member is optional. + +The MEMBER's value defines its properties, in particular its type. +The form TYPE-REF is shorthand for { 'type': TYPE-REF }. + +Example: { 'struct': 'MyType', - 'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } } + 'data': { 'member1': 'str', 'member2': ['int'], '*member3': 'str' } } -The use of '*' as a prefix to the name means the member is optional in -the corresponding JSON protocol usage. +A struct type corresponds to a struct in C, and an object in JSON. +The C struct's members are generated in QAPI schema order. -A struct definition can specify another struct as its base. -In this case, the members of the base type are included as top-level members -of the new struct's dictionary in the Client JSON Protocol wire -format. An example definition is: +The optional 'base' member names a struct type whose members are to be +included in this type. They go first in the C struct. - { 'struct': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } } +Example: + + { 'struct': 'BlockdevOptionsGenericFormat', + 'data': { 'file': 'str' } } { 'struct': 'BlockdevOptionsGenericCOWFormat', 'base': 'BlockdevOptionsGenericFormat', 'data': { '*backing': 'str' } }
@@ -204,18 +264,40 @@ both members like this: { "file": "/some/place/my-image", "backing": "/some/place/my-backing-file" } +The optional 'if' member specifies a conditional. See "Configuring +the schema" below for more on this. + +The optional 'features' member specifies features. See "Features" +below for more on this. + === Union types === -Usage: { 'union': STRING, 'data': DICT } -or: { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME-OR-DICT, - 'discriminator': ENUM-MEMBER-OF-BASE } - -Union types are used to let the user choose between several different -variants for an object. There are two flavors: simple (no -discriminator or base), and flat (both discriminator and base). A union -type is defined using a data dictionary as explained in the following -paragraphs. Unions must have at least one branch. +Syntax: + UNION = { 'union': STRING, + 'data': BRANCHES, + '*if': COND } + | { 'union': STRING, + 'data': BRANCHES, + 'base': ( MEMBERS | STRING ), + 'discriminator': STRING, + '*if': COND } + BRANCHES = { BRANCH, ... } + BRANCH = STRING : TYPE-REF + | STRING : { 'type': TYPE-REF, '*if': COND } + +Member 'union' names the union type. + +There are two flavors of union types: simple (no discriminator or +base), and flat (both discriminator and base). + +Each BRANCH of the 'data' object defines a branch of the union. A +union must have at least one branch. + +The BRANCH's STRING name is the branch name. + +The BRANCH's value defines the branch's properties, in particular its +type. The form TYPE-REF is shorthand for { 'type': TYPE-REF }. A simple union type defines a mapping from automatic discriminator values to data types like in this example:
@@ -228,8 +310,8 @@ values to data types like in this example: 'data': { 'file': 'BlockdevOptionsFile', 'qcow2': 'BlockdevOptionsQcow2' } } -In the Client JSON Protocol, a simple union is represented by a -dictionary that contains the 'type' member as a discriminator, and a +In the Client JSON Protocol, a simple union is represented by an +object that contains the 'type' member as a discriminator, and a 'data' member that is of the specified data type corresponding to the discriminator value, as in these examples:
@@ -237,21 +319,27 @@ discriminator value, as in these examples: { "type": "qcow2", "data": { "backing": "/some/place/my-image", "lazy-refcounts": true } } -The generated C code uses a struct containing a union. Additionally, +The generated C code uses a struct containing a union. Additionally, an implicit C enum 'NameKind' is created, corresponding to the union 'Name', for accessing the various branches of the union. The value for each branch can be of any type. -A flat union definition avoids nesting on the wire, and specifies a -set of common members that occur in all variants of the union. The -'base' key must specify either a type name (the type must be a -struct, not a union), or a dictionary representing an anonymous type. -All branches of the union must be struct types, and the top-level -members of the union dictionary on the wire will be combination of -members from both the base type and the appropriate branch type (when -merging two dictionaries, there must be no keys in common). The -'discriminator' member must be the name of a non-optional enum-typed -member of the base struct. +Flat unions permit arbitrary common members that occur in all variants +of the union, not just a discriminator. Their discriminators need not +be named 'type'. They also avoid nesting on the wire. + +The 'base' member defines the common members. If it is a MEMBERS +object, it defines common members just like a struct type's 'data' +member defines struct type members. If it is a STRING, it names a +struct type whose members are the common members. + +All flat union branches must be of struct type. + +In the Client JSON Protocol, a flat union is represented by an object +with the common members (from the base type) and the selected branch's +members. The two sets of member names must be disjoint. Member +'discriminator' must name a non-optional enum-typed member of the base +struct. The following example enhances the above simple union example by adding an optional common member 'read-only', renaming the
@@ -275,12 +363,13 @@ Resulting in these JSON objects: Notice that in a flat union, the discriminator name is controlled by the user, but because it must map to a base member with enum type, the code generator ensures that branches match the existing values of the -enum. The order of the keys need not match the declaration of the enum. -The keys need not cover all possible enum values. Omitted enum values -are still valid branches that add no additional members to the data type. -In the resulting generated C data types, a flat union is -represented as a struct with the base members included directly, and -then a union of structures for each branch of the struct. +enum. The order of branches need not match the order of the enum +values. The branches need not cover all possible enum values. +Omitted enum values are still valid branches that add no additional +members to the data type. In the resulting generated C data types, a +flat union is represented as a struct with the base members in QAPI +schema order, and then a union of structures for each branch of the +struct. A simple union can always be re-written as a flat union where the base class has a single member named 'type', and where each branch of the
@@ -296,32 +385,47 @@ is identical on the wire to: { 'union': 'Flat': 'base': { 'type': 'Enum' }, 'discriminator': 'type', 'data': { 'one': 'Branch1', 'two': 'Branch2' } } +The optional 'if' member specifies a conditional. See "Configuring +the schema" below for more on this. + === Alternate types === -Usage: { 'alternate': STRING, 'data': DICT } +Syntax: + ALTERNATE = { 'alternate': STRING, + 'data': ALTERNATIVES, + '*if': COND } + ALTERNATIVES = { ALTERNATIVE, ... } + ALTERNATIVE = STRING : TYPE-REF + | STRING : { 'type': STRING, '*if': COND } -An alternate type is one that allows a choice between two or more JSON -data types (string, integer, number, or object, but currently not -array) on the wire. The definition is similar to a simple union type, -where each branch of the union names a QAPI type. For example: +Member 'alternate' names the alternate type. + +Each ALTERNATIVE of the 'data' object defines a branch of the +alternate. An alternate must have at least one branch. + +The ALTERNATIVE's STRING name is the branch name. + +The ALTERNATIVE's value defines the branch's properties, in particular +its type. The form STRING is shorthand for { 'type': STRING }. + +Example: { 'alternate': 'BlockdevRef', 'data': { 'definition': 'BlockdevOptions', 'reference': 'str' } } -Unlike a union, the discriminator string is never passed on the wire -for the Client JSON Protocol. Instead, the value's JSON type serves -as an implicit discriminator, which in turn means that an alternate -can only express a choice between types represented differently in -JSON. If a branch is typed as the 'bool' built-in, the alternate -accepts true and false; if it is typed as any of the various numeric +An alternate type is like a union type, except there is no +discriminator on the wire. Instead, the branch to use is inferred +from the value. An alternate can only express a choice between types +represented differently on the wire. + +If a branch is typed as the 'bool' built-in, the alternate accepts +true and false; if it is typed as any of the various numeric built-ins, it accepts a JSON number; if it is typed as a 'str' built-in or named enum type, it accepts a JSON string; if it is typed as the 'null' built-in, it accepts JSON null; and if it is typed as a -complex type (struct or union), it accepts a JSON object. Two -different complex types, for instance, aren't permitted, because both -are represented as a JSON object. +complex type (struct or union), it accepts a JSON object. The example alternate declaration above allows using both of the following example objects:
@@ -331,43 +435,52 @@ following example objects: "read-only": false, "filename": "/tmp/mydisk.qcow2" } } +The optional 'if' member specifies a conditional. See "Configuring +the schema" below for more on this. + === Commands === ---- General Command Layout --- +Syntax: + COMMAND = { 'command': STRING, + ( + '*data': ( MEMBERS | STRING ), + | + 'data': STRING, + 'boxed': true, + ) + '*returns': TYPE-REF, + '*success-response': false, + '*gen': false, + '*allow-oob': true, + '*allow-preconfig': true, + '*if': COND } -Usage: { 'command': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT, - '*returns': TYPE-NAME, '*boxed': true, - '*gen': false, '*success-response': false, - '*allow-oob': true, '*allow-preconfig': true } +Member 'command' names the command. -Commands are defined by using a dictionary containing several members, -where three members are most common. The 'command' member is a -mandatory string, and determines the "execute" value passed in a -Client JSON Protocol command exchange. +Member 'data' defines the arguments. It defaults to an empty MEMBERS +object. -The 'data' argument maps to the "arguments" dictionary passed in as -part of a Client JSON Protocol command. The 'data' member is optional -and defaults to {} (an empty dictionary). If present, it must be the -string name of a complex type, or a dictionary that declares an -anonymous type with the same semantics as a 'struct' expression. +If 'data' is a MEMBERS object, then MEMBERS defines arguments just +like a struct type's 'data' defines struct type members. -The 'returns' member describes what will appear in the "return" member -of a Client JSON Protocol reply on successful completion of a command. -The member is optional from the command declaration; if absent, the -"return" member will be an empty dictionary. If 'returns' is present, -it must be the string name of a complex type, or a -one-element array containing the name of a complex type. -To return anything else, you have to list the command in pragma -'returns-whitelist'. If you do this, the command cannot be extended -to return additional information in the future. Use of +If 'data' is a STRING, then STRING names a complex type whose members +are the arguments. A union type requires 'boxed': true. + +Member 'returns' defines the command's return type. It defaults to an +empty struct type. It must normally be a complex type or an array of +a complex type. To return anything else, the command must be listed +in pragma 'returns-whitelist'. If you do this, extending the command +to return additional information will be harder. Use of 'returns-whitelist' for new commands is strongly discouraged. -All commands in Client JSON Protocol use a dictionary to report -failure, with no way to specify that in QAPI. Where the error return -is different than the usual GenericError class in order to help the -client react differently to certain error conditions, it is worth -documenting this in the comments before the command declaration. +A command's error responses are not specified in the QAPI schema. +Error conditions should be documented in comments. + +In the Client JSON Protocol, the value of the "execute" or "exec-oob" +member is the command name. The value of the "arguments" member then +has to conform to the arguments, and the value of the success +response's "return" member will conform to the return type. Some example commands:
@@ -385,23 +498,24 @@ which would validate this Client JSON Protocol transaction: => { "execute": "my-second-command" } <= { "return": [ { "value": "one" }, { } ] } -The generator emits a prototype for the user's function implementing -the command. Normally, 'data' is a dictionary for an anonymous type, -or names a struct type (possibly empty, but not a union), and its -members are passed as separate arguments to this function. If the -command definition includes a key 'boxed' with the boolean value true, -then 'data' is instead the name of any non-empty complex type (struct -or union), and a pointer to that QAPI type is passed as a single -argument. +The generator emits a prototype for the C function implementing the +command. The function itself needs to be written by hand. See +section "Code generated for commands" for examples. + +The function returns the return type. When member 'boxed' is absent, +it takes the command arguments as arguments one by one, in QAPI schema +order. Else it takes them wrapped in the C struct generated for the +complex argument type. It takes an additional Error ** argument in +either case. The generator also emits a marshalling function that extracts arguments for the user's function out of an input QDict, calls the user's function, and if it succeeded, builds an output QObject from -its return value. +its return value. This is for use by the QMP monitor core. In rare cases, QAPI cannot express a type-safe representation of a corresponding Client JSON Protocol command. You then have to suppress -generation of a marshalling function by including a key 'gen' with +generation of a marshalling function by including a member 'gen' with boolean value false, and instead write your own function. For example:
@@ -415,13 +529,12 @@ use type-safe unions. Normally, the QAPI schema is used to describe synchronous exchanges, where a response is expected. But in some cases, the action of a command is expected to change state in a way that a successful -response is not possible (although the command will still return a -normal dictionary error on failure). When a successful reply is not -possible, the command expression includes the optional key -'success-response' with boolean value false. So far, only QGA makes -use of this member. +response is not possible (although the command will still return an +error object on failure). When a successful reply is not possible, +the command definition includes the optional member 'success-response' +with boolean value false. So far, only QGA makes use of this member. -Key 'allow-oob' declares whether the command supports out-of-band +Member 'allow-oob' declares whether the command supports out-of-band (OOB) execution. It defaults to false. For example: { 'command': 'migrate_recover',
@@ -454,8 +567,8 @@ other "slow" lock. When in doubt, do not implement OOB execution support. -Key 'allow-preconfig' declares whether the command is available before -the machine is built. It defaults to false. For example: +Member 'allow-preconfig' declares whether the command is available +before the machine is built. It defaults to false. For example: { 'command': 'qmp_capabilities', 'data': { '*enable': [ 'QMPCapability' ] },
@@ -464,16 +577,33 @@ the machine is built. It defaults to false. For example: QMP is available before the machine is built only when QEMU was started with --preconfig. +The optional 'if' member specifies a conditional. See "Configuring +the schema" below for more on this. + + === Events === -Usage: { 'event': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT, - '*boxed': true } - -Events are defined with the keyword 'event'. When 'data' is also -specified, additional info will be included in the event, with similar -semantics to a 'struct' expression. Finally there will be C API -generated in qapi-events.h; when called by QEMU code, a message with -timestamp will be emitted on the wire. +Syntax: + EVENT = { 'event': STRING, + ( + '*data': ( MEMBERS | STRING ), + | + 'data': STRING, + 'boxed': true, + ) + '*if': COND } + +Member 'event' names the event. This is the event name used in the +Client JSON Protocol. + +Member 'data' defines the event-specific data. It defaults to an +empty MEMBERS object. + +If 'data' is a MEMBERS object, then MEMBERS defines event-specific +data just like a struct type's 'data' defines struct type members. + +If 'data' is a STRING, then STRING names a complex type whose members +are the event-specific data. A union type requires 'boxed': true. An example event is:
@@ -486,42 +616,44 @@ Resulting in this JSON object: "data": { "b": "test string" }, "timestamp": { "seconds": 1267020223, "microseconds": 435656 } } -The generator emits a function to send the event. Normally, 'data' is -a dictionary for an anonymous type, or names a struct type (possibly -empty, but not a union), and its members are passed as separate -arguments to this function. If the event definition includes a key -'boxed' with the boolean value true, then 'data' is instead the name -of any non-empty complex type (struct or union), and a pointer to that -QAPI type is passed as a single argument. +The generator emits a function to send the event. When member 'boxed' +is absent, it takes event-specific data one by one, in QAPI schema +order. Else it takes them wrapped in the C struct generated for the +complex type. See section "Code generated for events" for examples. + +The optional 'if' member specifies a conditional. See "Configuring +the schema" below for more on this. === Features === +Syntax: + FEATURES = [ FEATURE, ... ] + FEATURE = STRING + | { 'name': STRING, '*if': COND } + Sometimes, the behaviour of QEMU changes compatibly, but without a -change in the QMP syntax (usually by allowing values or operations that -previously resulted in an error). QMP clients may still need to know -whether the extension is available. +change in the QMP syntax (usually by allowing values or operations +that previously resulted in an error). QMP clients may still need to +know whether the extension is available. For this purpose, a list of features can be specified for a struct type. This is exposed to the client as a list of string, where each string signals that this build of QEMU shows a certain behaviour. -In the schema, features can be specified as simple strings, for example: +Each member of the 'features' array defines a feature. It can either +be { 'name': STRING, '*if': COND }, or STRING, which is shorthand for +{ 'name': STRING }. + +The optional 'if' member specifies a conditional. See "Configuring +the schema" below for more on this. + +Example: { 'struct': 'TestType', 'data': { 'number': 'int' }, 'features': [ 'allow-negative-numbers' ] } -Another option is to specify features as dictionaries, where the key -'name' specifies the feature string to be exposed to clients: - -{ 'struct': 'TestType', - 'data': { 'number': 'int' }, - 'features': [ { 'name': 'allow-negative-numbers' } ] } - -This expanded form is necessary if you want to make the feature -conditional (see below in "Configuring the schema"). - === Naming rules and reserved names ===
@@ -545,9 +677,8 @@ respectively. Command names, and member names within a type, should be all lower case with words separated by a hyphen. However, some existing older -commands and complex types use underscore; when extending such -expressions, consistency is preferred over blindly avoiding -underscore. +commands and complex types use underscore; when extending them, +consistency is preferred over blindly avoiding underscore. Event names should be ALL_CAPS with words separated by underscore.
@@ -577,11 +708,14 @@ downstream command __com.redhat_drive-mirror. === Configuring the schema === -The 'struct', 'enum', 'union', 'alternate', 'command' and 'event' -top-level expressions can take an 'if' key. Its value must be a string -or a list of strings. A string is shorthand for a list containing just -that string. The code generated for the top-level expression will then -be guarded by #if COND for each COND in the list. +Syntax: + COND = STRING + | [ STRING, ... ] + +All definitions take an optional 'if' member. Its value must be a +string or a list of strings. A string is shorthand for a list +containing just that string. The code generated for the definition +will then be guarded by #if COND for each COND in the list. Example: a conditional struct
@@ -596,29 +730,33 @@ gets its generated code guarded like this: #endif /* defined(HAVE_BAR) */ #endif /* defined(CONFIG_FOO) */ -Where a member can be defined with a single string value for its type, -it is also possible to supply a dictionary instead with both 'type' -and 'if' keys. +Individual members of complex types, commands arguments, and +event-specific data can also be made conditional. This requires the +longhand form of MEMBER. -Example: a conditional 'bar' member +Example: a struct type with unconditional member 'foo' and conditional +member 'bar' { 'struct': 'IfStruct', 'data': { 'foo': 'int', 'bar': { 'type': 'int', 'if': 'defined(IFCOND)'} } } -An enum value can be replaced by a dictionary with a 'name' and a 'if' -key. +A union's discriminator may not be conditional. -Example: a conditional 'bar' enum member. +Likewise, individual enumeration values be conditional. This requires +the longhand form of ENUM-VALUE. + +Example: an enum type with unconditional value 'foo' and conditional +value 'bar' { 'enum': 'IfEnum', 'data': [ 'foo', { 'name' : 'bar', 'if': 'defined(IFCOND)' } ] } -Similarly, features can be specified as a dictionary with a 'name' and -an 'if' key. +Likewise, features can be conditional. This requires the longhand +form of FEATURE. -Example: a conditional 'allow-negative-numbers' feature +Example: a struct with conditional feature 'allow-negative-numbers' { 'struct': 'TestType', 'data': { 'number': 'int' },
@@ -627,17 +765,30 @@ Example: a conditional 'allow-negative-numbers' feature Please note that you are responsible to ensure that the C code will compile with an arbitrary combination of conditions, since the -generators are unable to check it at this point. +generator is unable to check it at this point. -The presence of 'if' keys in the schema is reflected through to the -introspection output depending on the build configuration. +The conditions apply to introspection as well, i.e. introspection +shows a conditional entity only when the condition is satisfied in +this particular build. === Documentation comments === A multi-line comment that starts and ends with a '##' line is a -documentation comment. These are parsed by the documentation -generator, which recognizes certain markup detailed below. +documentation comment. + +If the documentation comment starts like + + ## + # @SYMBOL: + +it documents the definition if SYMBOL, else it's free-form +documentation. + +See below for more on definition documentation. + +Free-form documentation may be used to provide additional text and +structuring content. ==== Documentation markup ====
@@ -700,23 +851,24 @@ Example: ## -==== Expression documentation ==== +==== Definition documentation ==== -Expressions other than include and pragma directives may be preceded -by a documentation block. Such blocks are called expression -documentation blocks. +Definition documentation, if present, must immediately precede the +definition it documents. -When documentation is required (see pragma 'doc-required'), expression -documentation blocks are mandatory. +When documentation is required (see pragma 'doc-required'), every +definition must have documentation. -The documentation block consists of a first line naming the -expression, an optional overview, a description of each argument (for -commands and events) or member (for structs, unions and alternates), -and optional tagged sections. +Definition documentation starts with a line naming the definition, +followed by an optional overview, a description of each argument (for +commands and events), member (for structs and unions), branch (for +alternates), or value (for enums), and finally optional tagged +sections. FIXME: the parser accepts these things in almost any order. +FIXME: union branches should be described, too. -Extensions added after the expression was first released carry a +Extensions added after the definition was first released carry a '(since x.y.z)' comment. A tagged section starts with one of the following words:
@@ -724,7 +876,7 @@ A tagged section starts with one of the following words: The section ends with the start of a new section. A 'Since: x.y.z' tagged section lists the release that introduced the -expression. +definition. For example:
@@ -770,12 +922,6 @@ For example: 'data': { '*query-nodes': 'bool' }, 'returns': ['BlockStats'] } -==== Free-form documentation ==== - -A documentation block that isn't an expression documentation block is -a free-form documentation block. These may be used to provide -additional text and structuring content. - == Client JSON Protocol introspection ==
@@ -861,7 +1007,7 @@ If the event carries no additional information, "arg-type" names an object type without members. The event may not have a data member on the wire then. -Each command or event defined with dictionary-valued 'data' in the +Each command or event defined with 'data' as MEMBERS object in the QAPI schema implicitly defines an object type. Example: the SchemaInfo for EVENT_C from section Events
@@ -1043,7 +1189,7 @@ receive direction compatibility. Any change to types used in both contexts need to consider both. -Members of enumeration types, complex types and alternate types may be +Enumeration type values and complex and alternate type members may be reordered freely. For enumerations and alternate types, this doesn't affect the wire encoding. For complex types, this might make the implementation emit JSON object members in a different order, which
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 15/16] docs/devel/qapi-code-gen: Improve QAPI schema language doc
Quoted 30 lines · Markus Armbruster
We document the language by giving patterns of valid JSON objects. The patterns contain placeholders we don't define anywhere; their names have to speak for themselves. I guess they do, but I'd prefer a bit more rigor. Provide a grammar instead, and rework the text accordingly.
Documentation for QAPI schema conditionals (commit
967c885108,6cc32b0e14,87adbbffd4..3e270dcacc) and feature flags (commit6a8c0b5102) was bolted on. The sections documenting types, commands and events don't mention them. Section "Features" and "Configuring the schema" then provide additional syntax for types, commands and events. I hate that. Fix the sections documenting types, commands and events to provide accurate syntax, and point to "Features" and "Configuring the schema" for details.We talk about "(top-level) expressions other than include and pragma". Adopt more convenient terminology: a (top-level) expression is either a directive (include or pragma) or a definition (anything else).
Avoid the terms "dictionary" and "key". Stick to JSON terminology "object" and "member name" instead.
While there, make spacing more consistent.
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 592 ++++++++++++++++++++++------------- 1 file changed, 369 insertions(+), 223 deletions(-)
docs/devel/qapi-code-gen.txt Differences: · line 64
Quoted 5 lines
docs/devel/qapi-code-gen.txt +4
-1-The order of keys within JSON objects does not matter unless +* Production rules look like non-terminal = expression +* Concatenation: Expression A B matches expression A, then B +* Alternation: Expression A | B matches expression A or B +* Repetition: Expression A... matches zero or more occurences of
occurrences
Quoted 1 line
+ expression A; expression A, ... likewise, but separated by ,
worth calling out that trailing , are not allowed?
Is the 'expression A;' a copy-paste from RFC text, irrelevant to our usage here?
Quoted 11 lines
docs/devel/qapi-code-gen.txt +11
-0+* Grouping: Expression ( A ) matches expression A +* JSON's structural characters are terminals: { } [ ] : , +* JSON's literal names are terminals: false true null +* String literals enclosed in 'single quotes' are terminal, and match + this JSON string, with a leading '*' stripped off +* When JSON object member's name starts with '*', the member is + optional. +* The symbol STRING is a terminal, and matches any JSON string +* The symbol BOOL is a terminal, and matches JSON false or true +* ALL-CAPS words other than STRING are non-terminals +
docs/devel/qapi-code-gen.txt Differences:
Quoted 10 lines
docs/devel/qapi-code-gen.txt +7
-0+The order of members within JSON objects does not matter unless explicitly noted. +A QAPI schema consists of a series of top-level expressions: + + SCHEMA = TOP-LEVEL-EXPR... + +The top-level expressions are all JSON objects. Their order does not +matter.
Is that always true for all directives?
Would it be worth reformulating as something like:
SCHEMA = DIRECTIVE... DEFINITION...
allowing zero-or-more of either, but where directives come first?
Quoted 11 lines
docs/devel/qapi-code-gen.txt +11
-0+ +A top-level expressions is either a directive or a definition: + + TOP-LEVEL-EXPR = DIRECTIVE | DEFINITION + +There are two kinds of directives and six kinds of definitions: + + DIRECTIVE = INCLUDE | PRAGMA + DEFINITION = ENUM | STRUCT | UNION | ALTERNATE | COMMAND | EVENT + +These are discussed in detail below.
docs/devel/qapi-code-gen.txt Differences:
Quoted 10 lines
docs/devel/qapi-code-gen.txt +4
-1=== Pragma directives === -Usage: { 'pragma': DICT } +Syntax: + PRAGMA = { 'pragma': { '*doc-required': BOOL }, + '*returns-whitelist': [ STRING, ... ], + '*name-case-whitelist': [ STRING, ... ] }
This has matched {}, but looks wrong. I think you meant
PRAGMA = { 'pragma': { '*doc-required': BOOL,
'*returns-whitelist': [ STRING, ... ],
'*name-case-whitelist': [ STRING, ... ] } }Quoted 8 lines
=== Enumeration types ===
docs/devel/qapi-code-gen.txt +4
-2-Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING } - { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING } +Syntax: + ENUM = { 'enum': STRING, + 'data': [ ENUM-VALUE, ... ], + '*prefix': STRING,
docs/devel/qapi-code-gen.txt rules on use of upper- vs. lower-case letters. Default is none. · line 212
Quoted 10 lines
docs/devel/qapi-code-gen.txt +8
-0+ '*if': COND } + ENUM-VALUE = STRING + | { 'name': STRING, '*if': COND } +=== Type references and array types === + +Syntax: + TYPE-REF = STRING | ARRAY-TYPE + ARRAY-TYPE = [ STRING ]
As written (and enforced by current code), we don't allow 2-d arrays; if we ever decide we need that, we'd rewrite to ARRAY-TYPE = [ ARRAY-TYPE ]
docs/devel/qapi-code-gen.txt rules on use of upper- vs. lower-case letters. Default is none. · line 230
Quoted 12 lines
=== Struct types ===
docs/devel/qapi-code-gen.txt +9
-1-Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME } +Syntax: + STRUCT = { 'struct': STRING, + 'data': MEMBERS, + '*base': STRING, + '*if': COND, + '*features': FEATURES } + MEMBERS = { MEMBER, ... } + MEMBER = STRING : TYPE-REF + | STRING : { 'type': TYPE-REF, '*if': COND }
Down the road, we'll probably be amending this line:
| STRING : { 'type': TYPE-REF, '*if': COND, '*default': VALUE }
with appropriate documentation on how VALUE must match type.
Quoted 11 lines
=== Union types ===
docs/devel/qapi-code-gen.txt +0
-9-Usage: { 'union': STRING, 'data': DICT } -or: { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME-OR-DICT, - 'discriminator': ENUM-MEMBER-OF-BASE } - -Union types are used to let the user choose between several different -variants for an object. There are two flavors: simple (no -discriminator or base), and flat (both discriminator and base). A union -type is defined using a data dictionary as explained in the following -paragraphs. Unions must have at least one branch.
docs/devel/qapi-code-gen.txt both members like this: · line 285
Quoted 10 lines
docs/devel/qapi-code-gen.txt +10
-0+Syntax: + UNION = { 'union': STRING, + 'data': BRANCHES, + '*if': COND } + | { 'union': STRING, + 'data': BRANCHES, + 'base': ( MEMBERS | STRING ), + 'discriminator': STRING, + '*if': COND } + BRANCHES = { BRANCH, ... }
This syntactically allows zero or more branches per the intro, but in code we semantically require at least one. Is that a problem?
docs/devel/qapi-code-gen.txt both members like this: · line 295
Quoted 10 lines
docs/devel/qapi-code-gen.txt +10
-0+ BRANCH = STRING : TYPE-REF + | STRING : { 'type': TYPE-REF, '*if': COND } + +Member 'union' names the union type. + +There are two flavors of union types: simple (no discriminator or +base), and flat (both discriminator and base). + +Each BRANCH of the 'data' object defines a branch of the union. A +union must have at least one branch.
Is it worth trying to represent one-or-more in the grammar, in a different manner than zero-or-more?
docs/devel/qapi-code-gen.txt discriminator value, as in these examples: · line 337
Quoted 3 lines
docs/devel/qapi-code-gen.txt +3
-0+ +All flat union branches must be of struct type. +
We may eventually relax that to permit another union, hopefully we remember to fix the docs when doing so.
docs/devel/qapi-code-gen.txt discriminator value, as in these examples: · line 342
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+In the Client JSON Protocol, a flat union is represented by an object +with the common members (from the base type) and the selected branch's +members. The two sets of member names must be disjoint. Member +'discriminator' must name a non-optional enum-typed member of the base +struct.
We've already had patches proposed for relaxing that to allow an optional discriminator as a way to select a default branch. They'll have to be rebased on top of this.
Quoted 5 lines
=== Configuring the schema ===
docs/devel/qapi-code-gen.txt +0
-3-The 'struct', 'enum', 'union', 'alternate', 'command' and 'event' -top-level expressions can take an 'if' key. Its value must be a string -or a list of strings. A string is shorthand for a list containing just
docs/devel/qapi-code-gen.txt downstream command __com.redhat_drive-mirror. · line 718
Quoted 10 lines
docs/devel/qapi-code-gen.txt +8
-2-that string. The code generated for the top-level expression will then -be guarded by #if COND for each COND in the list. +Syntax: + COND = STRING + | [ STRING, ... ] + +All definitions take an optional 'if' member. Its value must be a +string or a list of strings. A string is shorthand for a list +containing just that string. The code generated for the definition +will then be guarded by #if COND for each COND in the list.
Should this read 'guarded by #if STRING for each STRING in the COND list'?
Quoted 20 lines
-==== Expression documentation ====
+==== Definition documentation ====docs/devel/qapi-code-gen.txt +6
-9-Expressions other than include and pragma directives may be preceded -by a documentation block. Such blocks are called expression -documentation blocks. +Definition documentation, if present, must immediately precede the +definition it documents. -When documentation is required (see pragma 'doc-required'), expression -documentation blocks are mandatory. +When documentation is required (see pragma 'doc-required'), every +definition must have documentation. -The documentation block consists of a first line naming the -expression, an optional overview, a description of each argument (for -commands and events) or member (for structs, unions and alternates), -and optional tagged sections. +Definition documentation starts with a line naming the definition, +followed by an optional overview, a description of each argument (for
docs/devel/qapi-code-gen.txt Example: · line 872
Quoted 10 lines
docs/devel/qapi-code-gen.txt +5
-1+commands and events), member (for structs and unions), branch (for +alternates), or value (for enums), and finally optional tagged +sections. FIXME: the parser accepts these things in almost any order. +FIXME: union branches should be described, too. -Extensions added after the expression was first released carry a +Extensions added after the definition was first released carry a '(since x.y.z)' comment.
Not this patch's problem - but we are inconsistent between x.y and x.y.z.
There are a couple of typo or grammar fixes worth fixing, but I'm comfortable enough giving:
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 15/16] docs/devel/qapi-code-gen: Improve QAPI schema language doc
Quoted 31 lines · Eric Blake
Quoted 30 lines · Markus Armbruster
We document the language by giving patterns of valid JSON objects. The patterns contain placeholders we don't define anywhere; their names have to speak for themselves. I guess they do, but I'd prefer a bit more rigor. Provide a grammar instead, and rework the text accordingly.
Documentation for QAPI schema conditionals (commit
967c885108,6cc32b0e14,87adbbffd4..3e270dcacc) and feature flags (commit6a8c0b5102) was bolted on. The sections documenting types, commands and events don't mention them. Section "Features" and "Configuring the schema" then provide additional syntax for types, commands and events. I hate that. Fix the sections documenting types, commands and events to provide accurate syntax, and point to "Features" and "Configuring the schema" for details.We talk about "(top-level) expressions other than include and pragma". Adopt more convenient terminology: a (top-level) expression is either a directive (include or pragma) or a definition (anything else).
Avoid the terms "dictionary" and "key". Stick to JSON terminology "object" and "member name" instead.
While there, make spacing more consistent.
Signed-off-by Markus Armbruster <[email protected]>--- docs/devel/qapi-code-gen.txt | 592 ++++++++++++++++++++++------------- 1 file changed, 369 insertions(+), 223 deletions(-)
Quoted 7 lines
docs/devel/qapi-code-gen.txt Differences: · line 64
Quoted 5 lines
docs/devel/qapi-code-gen.txt +4
-1-The order of keys within JSON objects does not matter unless +* Production rules look like non-terminal = expression +* Concatenation: Expression A B matches expression A, then B +* Alternation: Expression A | B matches expression A or B +* Repetition: Expression A... matches zero or more occurences ofoccurrences
Will fix.
Quoted 3 lines
Quoted 1 line
+ expression A; expression A, ... likewise, but separated by ,
worth calling out that trailing , are not allowed?
Doesn't "separated by" imply that?
Quoted 2 lines
Is the 'expression A;' a copy-paste from RFC text, irrelevant to our usage here?
What about
* Repetition: Expression A... matches zero or more occurences of expression A
* Repetition: Expression A, ... matches zero or more occurences of expression A separated by ,
Quoted 15 lines
Quoted 14 lines
docs/devel/qapi-code-gen.txt +12
-0+* Grouping: Expression ( A ) matches expression A +* JSON's structural characters are terminals: { } [ ] : , +* JSON's literal names are terminals: false true null +* String literals enclosed in 'single quotes' are terminal, and match + this JSON string, with a leading '*' stripped off +* When JSON object member's name starts with '*', the member is + optional. +* The symbol STRING is a terminal, and matches any JSON string +* The symbol BOOL is a terminal, and matches JSON false or true +* ALL-CAPS words other than STRING are non-terminals + +The order of members within JSON objects does not matter unless explicitly noted.
Quoted 8 lines
docs/devel/qapi-code-gen.txt Differences: · line 85
Quoted 6 lines
docs/devel/qapi-code-gen.txt +6
-0+A QAPI schema consists of a series of top-level expressions: + + SCHEMA = TOP-LEVEL-EXPR... + +The top-level expressions are all JSON objects. Their order does not +matter.Is that always true for all directives?
Yes from a purely semantic point of view.
No when you look at the generated text: that's in source order. Should not matter for C. Does matter for documentation.
See also discussion of previous patch.
Quoted 5 lines
Would it be worth reformulating as something like:
SCHEMA = DIRECTIVE... DEFINITION...
allowing zero-or-more of either, but where directives come first?
Language change. Not sure anything outside tests would break. But why bother?
Quoted 24 lines
Quoted 11 lines
docs/devel/qapi-code-gen.txt +11
-0+ +A top-level expressions is either a directive or a definition: + + TOP-LEVEL-EXPR = DIRECTIVE | DEFINITION + +There are two kinds of directives and six kinds of definitions: + + DIRECTIVE = INCLUDE | PRAGMA + DEFINITION = ENUM | STRUCT | UNION | ALTERNATE | COMMAND | EVENT + +These are discussed in detail below.docs/devel/qapi-code-gen.txt Differences:
Quoted 10 lines
docs/devel/qapi-code-gen.txt +4
-1=== Pragma directives === -Usage: { 'pragma': DICT } +Syntax: + PRAGMA = { 'pragma': { '*doc-required': BOOL }, + '*returns-whitelist': [ STRING, ... ], + '*name-case-whitelist': [ STRING, ... ] }This has matched {}, but looks wrong. I think you meant
Quoted 3 lines
PRAGMA = { 'pragma': { '*doc-required': BOOL,
'*returns-whitelist': [ STRING, ... ], '*name-case-whitelist': [ STRING, ... ] } }
Good catch.
Quoted 37 lines
Quoted 8 lines
=== Enumeration types ===
docs/devel/qapi-code-gen.txt +4
-2-Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING } - { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING } +Syntax: + ENUM = { 'enum': STRING, + 'data': [ ENUM-VALUE, ... ], + '*prefix': STRING,docs/devel/qapi-code-gen.txt rules on use of upper- vs. lower-case letters. Default is none. · line 212
Quoted 10 lines
docs/devel/qapi-code-gen.txt +8
-0+ '*if': COND } + ENUM-VALUE = STRING + | { 'name': STRING, '*if': COND } +=== Type references and array types === + +Syntax: + TYPE-REF = STRING | ARRAY-TYPE + ARRAY-TYPE = [ STRING ]As written (and enforced by current code), we don't allow 2-d arrays; if we ever decide we need that, we'd rewrite to ARRAY-TYPE = [ ARRAY-TYPE ]
docs/devel/qapi-code-gen.txt rules on use of upper- vs. lower-case letters. Default is none. · line 230
Quoted 12 lines
=== Struct types ===
docs/devel/qapi-code-gen.txt +9
-1-Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME } +Syntax: + STRUCT = { 'struct': STRING, + 'data': MEMBERS, + '*base': STRING, + '*if': COND, + '*features': FEATURES } + MEMBERS = { MEMBER, ... } + MEMBER = STRING : TYPE-REF + | STRING : { 'type': TYPE-REF, '*if': COND }Down the road, we'll probably be amending this line:
Quoted 3 lines
| STRING : { 'type': TYPE-REF, '*if': COND, '*default': VALUE }
with appropriate documentation on how VALUE must match type.
We've wanted that for a while. Max has patches:
[PATCH v4 00/14] block: Try to create well-typed json:{} filenames
They need review.
Quoted 16 lines
Quoted 16 lines
=== Union types ===
docs/devel/qapi-code-gen.txt +5
-9-Usage: { 'union': STRING, 'data': DICT } -or: { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME-OR-DICT, - 'discriminator': ENUM-MEMBER-OF-BASE } - -Union types are used to let the user choose between several different -variants for an object. There are two flavors: simple (no -discriminator or base), and flat (both discriminator and base). A union -type is defined using a data dictionary as explained in the following -paragraphs. Unions must have at least one branch. +Syntax: + UNION = { 'union': STRING, + 'data': BRANCHES, + '*if': COND } + | { 'union': STRING,
Quoted 8 lines
docs/devel/qapi-code-gen.txt both members like this: · line 285
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+ 'data': BRANCHES, + 'base': ( MEMBERS | STRING ), + 'discriminator': STRING, + '*if': COND } + BRANCHES = { BRANCH, ... }This syntactically allows zero or more branches per the intro, but in code we semantically require at least one. Is that a problem?
A flat union with *no* branches is actually valid as long as the discriminator enum has values.
Not possible for simple unions and alternates, where the enum is inferred. Could turn the semantic constraint into syntax just for them, but I feel it's too much notational overhead.
Besides, I'm sitting on patches that separate checking this second layer of syntax from checking semantics, and "unions need branches" ends up in the semantics part. That's another reason for not doing it in syntax here.
Quoted 5 lines
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+ BRANCH = STRING : TYPE-REF + | STRING : { 'type': TYPE-REF, '*if': COND } + +Member 'union' names the union type. +
Quoted 8 lines
docs/devel/qapi-code-gen.txt both members like this: · line 295
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+There are two flavors of union types: simple (no discriminator or +base), and flat (both discriminator and base). + +Each BRANCH of the 'data' object defines a branch of the union. A +union must have at least one branch.Is it worth trying to represent one-or-more in the grammar, in a different manner than zero-or-more?
If we needed it multiple times, then something like
* Repetition: Expression A * matches zero or more occurences of expression A
* Repetition: Expression A, * matches zero or more occurences of expression A separated by ,
* Repetition: Expression A + matches one or more occurences of expression A
* Repetition: Expression A, + matches one or more occurences of expression A separated by ,
could be helpful. But I can't see the need right now.
Quoted 7 lines
docs/devel/qapi-code-gen.txt discriminator value, as in these examples: · line 337
Quoted 3 lines
docs/devel/qapi-code-gen.txt +3
-0+ +All flat union branches must be of struct type. +We may eventually relax that to permit another union, hopefully we remember to fix the docs when doing so.
Quoted 9 lines
docs/devel/qapi-code-gen.txt discriminator value, as in these examples: · line 342
Quoted 5 lines
docs/devel/qapi-code-gen.txt +5
-0+In the Client JSON Protocol, a flat union is represented by an object +with the common members (from the base type) and the selected branch's +members. The two sets of member names must be disjoint. Member +'discriminator' must name a non-optional enum-typed member of the base +struct.We've already had patches proposed for relaxing that to allow an optional discriminator as a way to select a default branch. They'll have to be rebased on top of this.
*If* we decide we the benefit is worth the complexity.
Quoted 17 lines
Quoted 5 lines
=== Configuring the schema ===
docs/devel/qapi-code-gen.txt +0
-3-The 'struct', 'enum', 'union', 'alternate', 'command' and 'event' -top-level expressions can take an 'if' key. Its value must be a string -or a list of strings. A string is shorthand for a list containing justdocs/devel/qapi-code-gen.txt downstream command __com.redhat_drive-mirror. · line 718
Quoted 10 lines
docs/devel/qapi-code-gen.txt +8
-2-that string. The code generated for the top-level expression will then -be guarded by #if COND for each COND in the list. +Syntax: + COND = STRING + | [ STRING, ... ] + +All definitions take an optional 'if' member. Its value must be a +string or a list of strings. A string is shorthand for a list +containing just that string. The code generated for the definition +will then be guarded by #if COND for each COND in the list.Should this read 'guarded by #if STRING for each STRING in the COND list'?
Yes, that's better.
Quoted 33 lines
Quoted 20 lines
-==== Expression documentation ====
+==== Definition documentation ====docs/devel/qapi-code-gen.txt +6
-9-Expressions other than include and pragma directives may be preceded -by a documentation block. Such blocks are called expression -documentation blocks. +Definition documentation, if present, must immediately precede the +definition it documents. -When documentation is required (see pragma 'doc-required'), expression -documentation blocks are mandatory. +When documentation is required (see pragma 'doc-required'), every +definition must have documentation. -The documentation block consists of a first line naming the -expression, an optional overview, a description of each argument (for -commands and events) or member (for structs, unions and alternates), -and optional tagged sections. +Definition documentation starts with a line naming the definition, +followed by an optional overview, a description of each argument (fordocs/devel/qapi-code-gen.txt Example: · line 872
Quoted 10 lines
docs/devel/qapi-code-gen.txt +5
-1+commands and events), member (for structs and unions), branch (for +alternates), or value (for enums), and finally optional tagged +sections. FIXME: the parser accepts these things in almost any order. +FIXME: union branches should be described, too. -Extensions added after the expression was first released carry a +Extensions added after the definition was first released carry a '(since x.y.z)' comment.Not this patch's problem - but we are inconsistent between x.y and x.y.z.
Quoted 4 lines
There are a couple of typo or grammar fixes worth fixing, but I'm comfortable enough giving:
Reviewed-by Eric Blake <[email protected]>
Thanks!
Re: [Qemu-devel] [PATCH v2 15/16] docs/devel/qapi-code-gen: Improve QAPI schema language doc
Quoted 9 lines · Markus Armbruster
Quoted 3 lines
Quoted 1 line
+ expression A; expression A, ... likewise, but separated by ,
worth calling out that trailing , are not allowed?
Doesn't "separated by" imply that?
Quoted 2 lines
Is the 'expression A;' a copy-paste from RFC text, irrelevant to our usage here?
Quoted 6 lines
What about
* Repetition: Expression A... matches zero or more occurences of expression A
* Repetition: Expression A, ... matches zero or more occurences of expression A separated by ,
With the spelling of 'occurrences' fixed, that works.
Quoted 12 lines
Quoted 4 lines
docs/devel/qapi-code-gen.txt Differences: · line 85
Quoted 2 lines
docs/devel/qapi-code-gen.txt +2
-0+The top-level expressions are all JSON objects. Their order does not +matter.Is that always true for all directives?
Yes from a purely semantic point of view.
No when you look at the generated text: that's in source order. Should not matter for C. Does matter for documentation.
See also discussion of previous patch.
Quoted 8 lines
Quoted 5 lines
Would it be worth reformulating as something like:
SCHEMA = DIRECTIVE... DEFINITION...
allowing zero-or-more of either, but where directives come first?
Language change. Not sure anything outside tests would break. But why bother?
Fair enough.
Quoted 17 lines
Quoted 5 lines
docs/devel/qapi-code-gen.txt both members like this: · line 295
Quoted 2 lines
docs/devel/qapi-code-gen.txt +2
-0+Each BRANCH of the 'data' object defines a branch of the union. A +union must have at least one branch.Is it worth trying to represent one-or-more in the grammar, in a different manner than zero-or-more?
If we needed it multiple times, then something like
* Repetition: Expression A * matches zero or more occurences of expression A
* Repetition: Expression A, * matches zero or more occurences of expression A separated by ,
* Repetition: Expression A + matches one or more occurences of expression A
* Repetition: Expression A, + matches one or more occurences of expression A separated by ,
Quoted 1 line
could be helpful. But I can't see the need right now.
Again with the typo. But I also agree that it's not needed right now.
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Re: [Qemu-devel] [PATCH v2 15/16] docs/devel/qapi-code-gen: Improve QAPI schema language doc
Quoted 11 lines · Eric Blake
Quoted 9 lines · Markus Armbruster
Quoted 3 lines
Quoted 1 line
+ expression A; expression A, ... likewise, but separated by ,
worth calling out that trailing , are not allowed?
Doesn't "separated by" imply that?
Quoted 2 lines
Is the 'expression A;' a copy-paste from RFC text, irrelevant to our usage here?
Quoted 8 lines
Quoted 6 lines
What about
* Repetition: Expression A... matches zero or more occurences of expression A
* Repetition: Expression A, ... matches zero or more occurences of expression A separated by ,With the spelling of 'occurrences' fixed, that works.
Repeat offender...
Will fix, thanks!
[...]
PATCH v2 16/16 qapi: Tweak code to match docs/devel/qapi-code-gen.txt
In reply to Markus ArmbrusterThe previous commit made qapi-code-gen.txt define "(top-level) expression" as either "directive" or "definition". The code still uses "expression" when it really means "definition". Tidy up.
The previous commit made qapi-code-gen.txt use "object" rather than "dictionary". The code still uses "dictionary". Tidy up.
--- scripts/qapi/common.py | 24 +++++++++---------- tests/qapi-schema/args-invalid.err | 2 +- tests/qapi-schema/doc-missing.err | 2 +- tests/qapi-schema/doc-no-symbol.err | 2 +- .../qapi-schema/enum-dict-member-unknown.err | 2 +- tests/qapi-schema/pragma-non-dict.err | 2 +- tests/qapi-schema/struct-data-invalid.err | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-)
scripts/qapi/common.py +12 -12
@@ -103,11 +103,11 @@ class QAPISemError(QAPIError): class QAPIDoc(object): """ - A documentation comment block, either expression or free-form + A documentation comment block, either definition or free-form - Expression documentation blocks consist of + Definition documentation blocks consist of - * a body section: one line naming the expression, followed by an + * a body section: one line naming the definition, followed by an overview (any number of lines) * argument sections: a description of each argument (for commands
@@ -200,9 +200,9 @@ class QAPIDoc(object): Process a line of documentation text in the body section. If this a symbol line and it is the section's first line, this - is an expression documentation block for that symbol. + is a definition documentation block for that symbol. - If it's an expression documentation block, another symbol line + If it's a definition documentation block, another symbol line begins the argument section for the argument named by it, and a section tag begins an additional section. Start that section and append the line to it.
@@ -220,7 +220,7 @@ class QAPIDoc(object): if not self.symbol: raise QAPIParseError(self._parser, "Invalid name") elif self.symbol: - # This is an expression documentation block + # This is a definition documentation block if name.startswith('@') and name.endswith(':'): self._append_line = self._append_args_line self._append_args_line(line)
@@ -428,7 +428,7 @@ class QAPISchemaParser(object): pragma = expr['pragma'] if not isinstance(pragma, dict): raise QAPISemError( - info, "Value of 'pragma' must be a dictionary") + info, "Value of 'pragma' must be an object") for name, value in pragma.items(): self._pragma(name, value, info) else:
@@ -437,7 +437,7 @@ class QAPISchemaParser(object): if cur_doc: if not cur_doc.symbol: raise QAPISemError( - cur_doc.info, "Expression documentation required") + cur_doc.info, "Definition documentation required") expr_elem['doc'] = cur_doc self.exprs.append(expr_elem) cur_doc = None
@@ -786,7 +786,7 @@ def check_type(info, source, value, if not isinstance(value, OrderedDict): raise QAPISemError(info, - "%s should be a dictionary or type name" % source) + "%s should be an object or type name" % source) # value is a dictionary, check that each member is okay for (key, arg) in value.items():
@@ -968,8 +968,8 @@ def check_enum(expr, info): "Enum '%s' requires a string for 'prefix'" % name) for member in members: - source = "dictionary member of enum '%s'" % name - check_known_keys(info, source, member, ['name'], ['if']) + check_known_keys(info, "member of enum '%s'" % name, member, + ['name'], ['if']) check_if(member, info) check_name(info, "Member of enum '%s'" % name, member['name'], enum_member=True)
@@ -1078,7 +1078,7 @@ def check_exprs(exprs): if not doc and doc_required: raise QAPISemError(info, - "Expression missing documentation comment") + "Definition missing documentation comment") if 'enum' in expr: meta = 'enum'
tests/qapi-schema/args-invalid.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/args-invalid.json:1: 'data' for command 'foo' should be a dictionary or type name +tests/qapi-schema/args-invalid.json:1: 'data' for command 'foo' should be an object or type name
tests/qapi-schema/doc-missing.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/doc-missing.json:5: Expression missing documentation comment +tests/qapi-schema/doc-missing.json:5: Definition missing documentation comment
tests/qapi-schema/doc-no-symbol.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/doc-no-symbol.json:3: Expression documentation required +tests/qapi-schema/doc-no-symbol.json:3: Definition documentation required
tests/qapi-schema/enum-dict-member-unknown.err +1 -1
@@ -1,2 +1,2 @@ -tests/qapi-schema/enum-dict-member-unknown.json:2: Unknown key 'bad-key' in dictionary member of enum 'MyEnum' +tests/qapi-schema/enum-dict-member-unknown.json:2: Unknown key 'bad-key' in member of enum 'MyEnum' Valid keys are 'if', 'name'.
tests/qapi-schema/pragma-non-dict.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/pragma-non-dict.json:3: Value of 'pragma' must be a dictionary +tests/qapi-schema/pragma-non-dict.json:3: Value of 'pragma' must be an object
tests/qapi-schema/struct-data-invalid.err +1 -1
@@ -1 +1 @@ -tests/qapi-schema/struct-data-invalid.json:1: 'data' for struct 'foo' should be a dictionary or type name +tests/qapi-schema/struct-data-invalid.json:1: 'data' for struct 'foo' should be an object or type name
Signature · 1 line
2.21.0
Re: [Qemu-devel] [PATCH v2 16/16] qapi: Tweak code to match docs/devel/qapi-code-gen.txt
Quoted 9 lines · Markus Armbruster
The previous commit made qapi-code-gen.txt define "(top-level) expression" as either "directive" or "definition". The code still uses "expression" when it really means "definition". Tidy up.
The previous commit made qapi-code-gen.txt use "object" rather than "dictionary". The code still uses "dictionary". Tidy up.
Signed-off-by Markus Armbruster <[email protected]>---
Signature · 3 lines
Eric Blake, Principal Software Engineer Red Hat, Inc. +1-919-301-3226 Virtualization: qemu.org | libvirt.org
Patchew URL: https://patchew.org/QEMU/[email protected]/
Patchew URL: https://patchew.org/QEMU/[email protected]/
Hi,
This series seems to have some coding style problems. See output below for more information:
Subject: [Qemu-devel] [PATCH v2 00/16] qapi: Schema language cleanups & doc improvements
Message-id: [email protected]
Type: series
=== TEST SCRIPT BEGIN ===
#!/bin/bash
git rev-parse base > /dev/null || exit 0
git config --local diff.renamelimit 0
git config --local diff.renames True
git config --local diff.algorithm histogram./scripts/checkpatch.pl --mailback base..
=== TEST SCRIPT END ===
Updating 3c8cf5a9c21ff8782164d1def7f44bd888713384
From https://github.com/patchew-project/qemu
- [tag update] patchew/[email protected] -> patchew/[email protected]
Switched to a new branch 'test'
446351c qapi: Tweak code to match docs/devel/qapi-code-gen.txt 16bdba8 docs/devel/qapi-code-gen: Improve QAPI schema language doc cb81f1d docs/devel/qapi-code-gen: Rewrite introduction to schema 1536401 docs/devel/qapi-code-gen: Rewrite compatibility considerations 4d82648 docs/devel/qapi-code-gen: Reorder sections for readability 9ac7ecd qapi: Adjust frontend errors to say enum value, not member e106b86 qapi: Permit omitting all flat union branches 81dc6c5 qapi: Permit alternates with just one branch
bf905ed qapi: Permit 'boxed' with empty type
312a323 qapi: Drop support for escape sequences other than \\
2a77c2f qapi: Restrict strings to printable ASCII
f6aaeaa tests/qapi-schema: Demonstrate bad reporting of funny characters bd4e9cc docs/devel/qapi-code-gen: Minor specification fixes 88cff11 qapi: Drop support for boxed alternate arguments b9e08ee qapi: Drop check_type()'s redundant parameter @allow_optional 6860186 scripts/git.orderfile: Match QAPI schema more precisely
=== OUTPUT BEGIN ===
1/16 Checking commit 6860186b207b (scripts/git.orderfile: Match QAPI schema more precisely) 2/16 Checking commit b9e08eee03e3 (qapi: Drop check_type()'s redundant parameter @allow_optional) 3/16 Checking commit 88cff11d85d8 (qapi: Drop support for boxed alternate arguments) 4/16 Checking commit bd4e9cc1f433 (docs/devel/qapi-code-gen: Minor specification fixes) 5/16 Checking commit f6aaeaa74c63 (tests/qapi-schema: Demonstrate bad reporting of funny characters) 6/16 Checking commit 2a77c2f2e0ec (qapi: Restrict strings to printable ASCII)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating?
#98:
new file mode 100644
ERROR: Invalid UTF-8, patch and commit message should be encoded in UTF-8 #115: FILE: tests/qapi-schema/string-code-point-127.json:2:
+{ 'command': '⌦' }
^
ERROR: Invalid UTF-8, patch and commit message should be encoded in UTF-8 #141: FILE: tests/qapi-schema/string-code-point-31.json:2:
+{ 'command': '␟' }
^
total: 2 errors, 1 warnings, 67 lines checked
Patch 6/16 has style problems, please review. If any of these errors are false positives report them to the maintainer, see CHECKPATCH in MAINTAINERS.
7/16 Checking commit 312a323451bc (qapi: Drop support for escape sequences other than \\)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating? #69:
deleted file mode 100644
total: 0 errors, 1 warnings, 49 lines checked
Patch 7/16 has style problems, please review. If any of these errors are false positives report them to the maintainer, see CHECKPATCH in MAINTAINERS.
8/16 Checking commit bf905eda09c9 (qapi: Permit 'boxed' with empty type)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating? #129:
deleted file mode 100644
total: 0 errors, 1 warnings, 129 lines checked
Patch 8/16 has style problems, please review. If any of these errors
are false positives report them to the maintainer, see
CHECKPATCH in MAINTAINERS.
9/16 Checking commit 81dc6c516180 (qapi: Permit alternates with just one branch) 10/16 Checking commit e106b8638164 (qapi: Permit omitting all flat union branches) 11/16 Checking commit 9ac7ecd2cc24 (qapi: Adjust frontend errors to say enum value, not member) 12/16 Checking commit 4d8264892e00 (docs/devel/qapi-code-gen: Reorder sections for readability) 13/16 Checking commit 1536401f46a4 (docs/devel/qapi-code-gen: Rewrite compatibility considerations) 14/16 Checking commit cb81f1def7f2 (docs/devel/qapi-code-gen: Rewrite introduction to schema) 15/16 Checking commit 16bdba8b8274 (docs/devel/qapi-code-gen: Improve QAPI schema language doc) 16/16 Checking commit 446351ca29ad (qapi: Tweak code to match docs/devel/qapi-code-gen.txt) === OUTPUT END ===
Test command exited with code: 1
The full log is available at
http://patchew.org/logs/[email protected]/testing.checkpatch/?type=message.
---
Email generated automatically by Patchew [https://patchew.org/].
Please send your feedback to [email protected]
Patchew URL: https://patchew.org/QEMU/[email protected]/
Patchew URL: https://patchew.org/QEMU/[email protected]/
Hi,
This series seems to have some coding style problems. See output below for more information:
Subject: [Qemu-devel] [PATCH v2 00/16] qapi: Schema language cleanups & doc improvements
Message-id: [email protected]
Type: series
=== TEST SCRIPT BEGIN ===
#!/bin/bash
git rev-parse base > /dev/null || exit 0
git config --local diff.renamelimit 0
git config --local diff.renames True
git config --local diff.algorithm histogram./scripts/checkpatch.pl --mailback base..
=== TEST SCRIPT END ===
Switched to a new branch 'test'
a1653d5 qapi: Tweak code to match docs/devel/qapi-code-gen.txt 099aa0e docs/devel/qapi-code-gen: Improve QAPI schema language doc 831ceca docs/devel/qapi-code-gen: Rewrite introduction to schema b2d2173 docs/devel/qapi-code-gen: Rewrite compatibility considerations e3fee5f docs/devel/qapi-code-gen: Reorder sections for readability 5a3026a qapi: Adjust frontend errors to say enum value, not member da3e5ce qapi: Permit omitting all flat union branches 29a78dc qapi: Permit alternates with just one branch
1690f90 qapi: Permit 'boxed' with empty type
4db101b qapi: Drop support for escape sequences other than \\
226a021 qapi: Restrict strings to printable ASCII
b7bf351 tests/qapi-schema: Demonstrate bad reporting of funny characters e4bbc54 docs/devel/qapi-code-gen: Minor specification fixes afba881 qapi: Drop support for boxed alternate arguments 1988fff qapi: Drop check_type()'s redundant parameter @allow_optional 2f4a210 scripts/git.orderfile: Match QAPI schema more precisely
=== OUTPUT BEGIN ===
1/16 Checking commit 2f4a2105c5e3 (scripts/git.orderfile: Match QAPI schema more precisely) 2/16 Checking commit 1988fff693a1 (qapi: Drop check_type()'s redundant parameter @allow_optional) 3/16 Checking commit afba881b77d4 (qapi: Drop support for boxed alternate arguments) 4/16 Checking commit e4bbc5479810 (docs/devel/qapi-code-gen: Minor specification fixes) 5/16 Checking commit b7bf3512c9eb (tests/qapi-schema: Demonstrate bad reporting of funny characters) 6/16 Checking commit 226a021e435b (qapi: Restrict strings to printable ASCII)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating?
#98:
new file mode 100644
ERROR: Invalid UTF-8, patch and commit message should be encoded in UTF-8 #115: FILE: tests/qapi-schema/string-code-point-127.json:2:
+{ 'command': '⌦' }
^
ERROR: Invalid UTF-8, patch and commit message should be encoded in UTF-8 #141: FILE: tests/qapi-schema/string-code-point-31.json:2:
+{ 'command': '␟' }
^
total: 2 errors, 1 warnings, 67 lines checked
Patch 6/16 has style problems, please review. If any of these errors are false positives report them to the maintainer, see CHECKPATCH in MAINTAINERS.
7/16 Checking commit 4db101b60dce (qapi: Drop support for escape sequences other than \\)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating? #69:
deleted file mode 100644
total: 0 errors, 1 warnings, 49 lines checked
Patch 7/16 has style problems, please review. If any of these errors are false positives report them to the maintainer, see CHECKPATCH in MAINTAINERS.
8/16 Checking commit 1690f908e9c9 (qapi: Permit 'boxed' with empty type)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating? #129:
deleted file mode 100644
total: 0 errors, 1 warnings, 129 lines checked
Patch 8/16 has style problems, please review. If any of these errors
are false positives report them to the maintainer, see
CHECKPATCH in MAINTAINERS.
9/16 Checking commit 29a78dc3574f (qapi: Permit alternates with just one branch) 10/16 Checking commit da3e5ce8445d (qapi: Permit omitting all flat union branches) 11/16 Checking commit 5a3026a89b6c (qapi: Adjust frontend errors to say enum value, not member) 12/16 Checking commit e3fee5f2aebc (docs/devel/qapi-code-gen: Reorder sections for readability) 13/16 Checking commit b2d2173f6812 (docs/devel/qapi-code-gen: Rewrite compatibility considerations) 14/16 Checking commit 831cecae22b1 (docs/devel/qapi-code-gen: Rewrite introduction to schema) 15/16 Checking commit 099aa0e26496 (docs/devel/qapi-code-gen: Improve QAPI schema language doc) 16/16 Checking commit a1653d5a7388 (qapi: Tweak code to match docs/devel/qapi-code-gen.txt) === OUTPUT END ===
Test command exited with code: 1
The full log is available at
http://patchew.org/logs/[email protected]/testing.checkpatch/?type=message.
---
Email generated automatically by Patchew [https://patchew.org/].
Please send your feedback to [email protected]