Skip to contentSkip to conversation

drop qapi nested structs

PATCH Superseded Eric Blake 2 participants 49 messages Apr 29, 2015 – May 4, 2015 Page 2 of 2

v7 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
author
#38 lore raw

PATCH v7 34/39 qapi: Drop inline nested struct in query-version

In reply to Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument (see previous commit message for more details why); but existing use of inline nested structs conflicts with that goal. This patch fixes one of only two commands relying on nested types, by breaking the nesting into an explicit type; it means that the type is now boxed instead of unboxed in C code, but the QMP wire format is unaffected by this change.

Prefer the safer g_new0() while making the conversion.

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

PATCH v7 35/39 qapi: Drop inline nested structs in query-pci

In reply to Eric Blake

A future patch will be using a 'name':{dictionary} entry in the QAPI schema to specify a default value for an optional argument (see previous commit message for more details why); but existing use of inline nested structs conflicts with that goal. This patch fixes one of only two commands relying on nested types, by breaking the nesting into an explicit type; it means that the type is now boxed instead of unboxed in C code, but the QMP wire format is unaffected by this change.

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

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

68 lines not on this page · raw message

qapi-schema.json +62 -28

119 lines not on this page · raw message

Signature · 1 line
2.1.0
author
#40 lore raw

PATCH v7 36/39 qapi: Drop support for inline nested types

In reply to Eric Blake

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

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

Re: [Qemu-devel] [PATCH v7 36/39] qapi: Drop support for inline nested types

Quoted 22 lines · Eric Blake

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

---
 scripts/qapi-commands.py                     |  8 +++---
 scripts/qapi-event.py                        |  4 +--
 scripts/qapi-types.py                        |  9 ++-----
 scripts/qapi-visit.py                        | 37 ++++------------------------
 scripts/qapi.py                              | 20 ++++++---------

+++ b/scripts/qapi-visit.py

scripts/qapi-visit.py +0 -0
@@ -51,27 +51,6 @@ def generate_visit_struct_fields(name, field_prefix, fn_prefix, members, base =
     else:
         full_name = "%s_%s" % (name, fn_prefix)
 

scripts/qapi-visit.py def generate_visit_struct_fields(name, field_prefix, fn_prefix, members, base = · line 63

Quoted 10 lines
scripts/qapi-visit.py +0 -10
-    for argname, argentry, optional, structured in parse_args(members):
-        if structured:
-            if not fn_prefix:
-                nested_fn_prefix = argname
-            else:
-                nested_fn_prefix = "%s_%s" % (fn_prefix, argname)
-
-            nested_field_prefix = "%s%s." % (field_prefix, argname)
-            ret += generate_visit_struct_fields(name, nested_field_prefix,
-                                                nested_fn_prefix, argentry)

This is the only place that calls generate_visit_struct_fields with a non-empty string for prefix arguments; I've got a cleanup patch that we can either squash into this patch or leave as standalone.

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

Re: [Qemu-devel] [PATCH v7 36/39] qapi: Drop support for inline nested types

Quoted 23 lines · Eric Blake
Quoted 22 lines · Eric Blake

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

---
 scripts/qapi-commands.py                     |  8 +++---
 scripts/qapi-event.py                        |  4 +--
 scripts/qapi-types.py                        |  9 ++-----
 scripts/qapi-visit.py                        | 37 ++++------------------------
 scripts/qapi.py                              | 20 ++++++---------

+++ b/scripts/qapi-visit.py

scripts/qapi-visit.py +0 -0
@@ -51,27 +51,6 @@ def generate_visit_struct_fields(name, field_prefix, fn_prefix, members, base =
     else:
         full_name = "%s_%s" % (name, fn_prefix)
 
Quoted 14 lines

scripts/qapi-visit.py def generate_visit_struct_fields(name, field_prefix, fn_prefix, members, base = · line 63

Quoted 10 lines
scripts/qapi-visit.py +0 -10
-    for argname, argentry, optional, structured in parse_args(members):
-        if structured:
-            if not fn_prefix:
-                nested_fn_prefix = argname
-            else:
-                nested_fn_prefix = "%s_%s" % (fn_prefix, argname)
-
-            nested_field_prefix = "%s%s." % (field_prefix, argname)
-            ret += generate_visit_struct_fields(name, nested_field_prefix,
-                                                nested_fn_prefix, argentry)

This is the only place that calls generate_visit_struct_fields with a non-empty string for prefix arguments; I've got a cleanup patch that we can either squash into this patch or leave as standalone.

Squash vs. separate patch: your choice.

author
#43 lore raw

PATCH v7 1/1 squash: qapi: Drop dead visitor code related to nested structs

In reply to Eric Blake

Now that we no longer have nested structs to visit, the use of prefix strings is no longer required. Remove the code that is no longer reachable.

---
 scripts/qapi-visit.py | 49 ++++++++++++-------------------------------------
 1 file changed, 12 insertions(+), 37 deletions(-)
scripts/qapi-visit.py +12 -37
index 6156162..0e67b33 100644
@@ -43,50 +43,43 @@ static void visit_type_implicit_%(c_type)s(Visitor *m, %(c_type)s **obj, Error *
 ''',
                  c_type=type_name(type))
 
-def generate_visit_struct_fields(name, field_prefix, fn_prefix, members, base = None):
+def generate_visit_struct_fields(name, members, base = None):
     substructs = []
     ret = ''
-    if not fn_prefix:
-        full_name = name
-    else:
-        full_name = "%s_%s" % (name, fn_prefix)
 
     if base:
         ret += generate_visit_implicit_struct(base)
 
     ret += mcgen('''
 
-static void visit_type_%(full_name)s_fields(Visitor *m, %(name)s **obj, Error **errp)
+static void visit_type_%(name)s_fields(Visitor *m, %(name)s **obj, Error **errp)
 {
     Error *err = NULL;
 ''',
-        name=name, full_name=full_name)
+                 name=name)
     push_indent()
 
     if base:
         ret += mcgen('''
-visit_type_implicit_%(type)s(m, &(*obj)->%(c_prefix)s%(c_name)s, &err);
+visit_type_implicit_%(type)s(m, &(*obj)->%(c_name)s, &err);
 if (err) {
     goto out;
 }
 ''',
-                     c_prefix=c_var(field_prefix),
                      type=type_name(base), c_name=c_var('base'))
 
     for argname, argentry, optional in parse_args(members):
         if optional:
             ret += mcgen('''
-visit_optional(m, &(*obj)->%(c_prefix)shas_%(c_name)s, "%(name)s", &err);
-if (!err && (*obj)->%(prefix)shas_%(c_name)s) {
+visit_optional(m, &(*obj)->has_%(c_name)s, "%(name)s", &err);
+if (!err && (*obj)->has_%(c_name)s) {
 ''',
-                         c_prefix=c_var(field_prefix), prefix=field_prefix,
                          c_name=c_var(argname), name=argname)
             push_indent()
 
         ret += mcgen('''
-visit_type_%(type)s(m, &(*obj)->%(c_prefix)s%(c_name)s, "%(name)s", &err);
+visit_type_%(type)s(m, &(*obj)->%(c_name)s, "%(name)s", &err);
 ''',
-                     c_prefix=c_var(field_prefix), prefix=field_prefix,
                      type=type_name(argentry), c_name=c_var(argname),
                      name=argname)
 
@@ -114,29 +107,11 @@ out:
     return ret
 
 
-def generate_visit_struct_body(field_prefix, name, members):
+def generate_visit_struct_body(name, members):
     ret = mcgen('''
     Error *err = NULL;
 
-''')
-
-    if not field_prefix:
-        full_name = name
-    else:
-        full_name = "%s_%s" % (field_prefix, name)
-
-    if len(field_prefix):
-        ret += mcgen('''
-    visit_start_struct(m, NULL, "", "%(name)s", 0, &err);
-''',
-                name=name)
-    else:
-        ret += mcgen('''
     visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
-''',
-                name=name)
-
-    ret += mcgen('''
     if (!err) {
         if (*obj) {
             visit_type_%(name)s_fields(m, obj, errp);
@@ -145,7 +120,7 @@ def generate_visit_struct_body(field_prefix, name, members):
     }
     error_propagate(errp, err);
 ''',
-        name=full_name)
+                name=name)
 
     return ret
 
@@ -155,7 +130,7 @@ def generate_visit_struct(expr):
     members = expr['data']
     base = expr.get('base')
 
-    ret = generate_visit_struct_fields(name, "", "", members, base)
+    ret = generate_visit_struct_fields(name, members, base)
 
     ret += mcgen('''
 
@@ -164,7 +139,7 @@ void visit_type_%(name)s(Visitor *m, %(name)s **obj, const char *name, Error **e
 ''',
                 name=name)
 
-    ret += generate_visit_struct_body("", name, members)
+    ret += generate_visit_struct_body(name, members)
 
     ret += mcgen('''
 }
@@ -288,7 +263,7 @@ def generate_visit_union(expr):
         assert discriminator
         base_fields = find_struct(base)['data'].copy()
         del base_fields[discriminator]
-        ret += generate_visit_struct_fields(name, "", "", base_fields)
+        ret += generate_visit_struct_fields(name, base_fields)
 
     if discriminator:
         for key in members:
Signature · 1 line
2.1.0
author
#44 lore raw

PATCH v7 37/39 qapi: Tweak doc references to QMP when QGA is also meant

In reply to Eric Blake

We have more than one qapi schema in use by more than one protocol. Add a new term 'Client JSON Protocol' for use throughout the document, to avoid confusion on whether something refers only to QMP and not QGA.

---

v7: rebase to earlier changes

---
 docs/qapi-code-gen.txt | 157 +++++++++++++++++++++++++------------------------
 1 file changed, 81 insertions(+), 76 deletions(-)
docs/qapi-code-gen.txt +81 -76
index a874a6d..269a1f3 100644
@@ -13,12 +13,14 @@ 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.
+The remainder of this document uses "Client JSON Protocol" when
+referring to the wire contents of a QMP or QGA connection.
 
-To map QMP and QGA 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.
+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 ==
@@ -34,13 +36,13 @@ 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, QMP 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.
+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 are allowed; anything between an unquoted # and the following
 newline is ignored.  Although there is not yet a documentation
@@ -82,8 +84,11 @@ that will use those types.  Forward references are allowed: the parser
 scans in two passes, where the first pass learns all type names, and
 the second validates the schema and generates the code.  This allows
 the definition of complex structs that can have mutually recursive
-types, and allows for indefinite nesting of QMP that satisfies the
-schema.  A type name should not be defined more than once.
+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 seven top-level expressions recognized by the parser:
 'include', 'command', 'struct', 'enum', 'union', 'alternate', and
@@ -182,7 +187,7 @@ struct is:
    'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
 
 The use of '*' as a prefix to the name means the member is optional in
-the corresponding QMP usage.
+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
@@ -213,8 +218,8 @@ of use.
 
 A struct definition can specify another struct as its base.
 In this case, the fields of the base type are included as top-level fields
-of the new struct's dictionary in the QMP wire format. An example
-definition is:
+of the new struct's dictionary in the Client JSON Protocol wire
+format. An example definition is:
 
  { 'struct': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
  { 'struct': 'BlockdevOptionsGenericCOWFormat',
@@ -242,19 +247,19 @@ useful.  The list of strings should be lower case; if an enum name
 represents multiple words, use '-' between words.  The string 'max' is
 not allowed as an enum value, and values should not be repeated.
 
-The enumeration values are passed as strings over the QMP protocol,
-but are encoded as C enum integral values in generated code.  While
-the C code starts numbering at 0, it is better to use explicit
+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 QMP clients;
-however, removing enum values would break compatibility.  For any
-struct that has a field that will only contain a finite set of
-string values, using an enum type for that field is better than
-open-coding the field to be type 'str'.
+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 field that will only contain
+a finite set of string values, using an enum type for that field is
+better than open-coding the field to be type 'str'.
 
 
 === Union types ===
@@ -280,10 +285,10 @@ values to data types like in this example:
    'data': { 'file': 'FileOptions',
              'qcow2': 'Qcow2Options' } }
 
-In the QMP wire format, a simple union is represented by a dictionary
-that contains the 'type' field as a discriminator, and a 'data' field
-that is of the specified data type corresponding to the discriminator
-value, as in these examples:
+In the Client JSON Protocol, a simple union is represented by a
+dictionary that contains the 'type' field as a discriminator, and a
+'data' field that is of the specified data type corresponding to the
+discriminator value, as in these examples:
 
  { "type": "file", "data" : { "filename": "/some/place/my-image" } }
  { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
@@ -366,16 +371,16 @@ Just like for a simple union, an implicit C enum 'NameKind' is created
 to enumerate the branches for the alternate 'Name'.
 
 Unlike a union, the discriminator string is never passed on the wire
-for QMP.  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 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; 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.
+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
+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; 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.
 
 The example alternate declaration above allows using both of the
 following example objects:
@@ -394,37 +399,37 @@ Usage: { 'command': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT,
 
 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 QMP
-command exchange.
+mandatory string, and determines the "execute" value passed in a
+Client JSON Protocol command exchange.
 
 The 'data' argument maps to the "arguments" dictionary passed in as
-part of a QMP command.  The 'data' member is optional and defaults to
-{} (an empty dictionary).  If present, it must be the string name of a
-complex type, a one-element array containing the name of a complex
-type, or a dictionary that declares an anonymous type with the same
-semantics as a 'struct' expression, with one exception noted below when
-'gen' is used.
+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, a one-element array containing the name
+of a complex type, or a dictionary that declares an anonymous type
+with the same semantics as a 'struct' expression, with one exception
+noted below when 'gen' is used.
 
 The 'returns' member describes what will appear in the "return" field
-of a QMP reply on successful completion of a command.  The member is
-optional from the command declaration; if absent, the "return" field
-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, or a dictionary
-that declares an anonymous type with the same semantics as a 'struct'
-expression, with one exception noted below when 'gen' is used.
-Although it is permitted to have the 'returns' member name a built-in
-type or an array of built-in types, any command that does this cannot
-be extended to return additional information in the future; thus, new
-commands should strongly consider returning a dictionary-based type or
-an array of dictionaries, even if the dictionary only contains one
-field at the present.
+of a Client JSON Protocol reply on successful completion of a command.
+The member is optional from the command declaration; if absent, the
+"return" field 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,
+or a dictionary that declares an anonymous type with the same
+semantics as a 'struct' expression, with one exception noted below
+when 'gen' is used.  Although it is permitted to have the 'returns'
+member name a built-in type or an array of built-in types, any command
+that does this cannot be extended to return additional information in
+the future; thus, new commands should strongly consider returning a
+dictionary-based type or an array of dictionaries, even if the
+dictionary only contains one field at the present.
 
-All commands 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.
+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.
 
 Some example commands:
 
@@ -434,7 +439,7 @@ Some example commands:
  { 'command': 'my-second-command',
    'returns': [ 'MyType' ] }
 
-which would validate this QMP transaction:
+which would validate this Client JSON Protocol transaction:
 
  => { "execute": "my-first-command",
       "arguments": { "arg1": "hello" } }
@@ -443,14 +448,14 @@ which would validate this QMP transaction:
  <= { "return": [ { "value": "one" }, { } ] }
 
 In rare cases, QAPI cannot express a type-safe representation of a
-corresponding QMP command.  In these cases, if the command expression
-includes the key 'gen' with boolean value false, then the 'data' or
-'returns' member that intends to bypass generated type-safety and do
-its own manual validation should use an inline dictionary definition,
-with a value of '**' rather than a valid type name for the keys that
-the generated code will not validate.  Please try to avoid adding new
-commands that rely on this, and instead use type-safe unions.  For an
-example of bypass usage:
+corresponding Client JSON Protocol command.  In these cases, if the
+command expression includes the key 'gen' with boolean value false,
+then the 'data' or 'returns' member that intends to bypass generated
+type-safety and do its own manual validation should use an inline
+dictionary definition, with a value of '**' rather than a valid type
+name for the keys that the generated code will not validate.  Please
+try to avoid adding new commands that rely on this, and instead use
+type-safe unions.  For an example of bypass usage:
 
  { 'command': 'netdev_add',
    'data': {'type': 'str', 'id': 'str', '*props': '**'},
@@ -494,9 +499,9 @@ Resulting in this JSON object:
 
 Schemas are fed into 3 scripts to generate all the code/files that, paired
 with the core QAPI libraries, comprise everything required to take JSON
-commands read in by a QMP/guest agent server, unmarshal the arguments into
+commands read in by a Client JSON Protocol server, unmarshal the arguments into
 the underlying C types, call into the corresponding C function, and map the
-response back to a QMP/guest agent response to be returned to the user.
+response back to a Client JSON Protocol response to be returned to the user.
 
 As an example, we'll use the following schema, which describes a single
 complex user-defined type (which will produce a C struct, along with a list
Signature · 1 line
2.1.0
author
#45 lore raw

PATCH v7 38/39 qapi: Support (subset of) \u escapes in strings

In reply to Eric Blake

The handling of \ inside QAPI strings was less than ideal, and really only worked JSON's \/, \\, \", and our extension of \' (an obvious extension, when you realize we use '' instead of "" for strings). For other things, like '\n', it resulted in a literal 'n' instead of a newline.

Of course, at the moment, we really have no use for escaped characters, as QAPI has to map to C identifiers, and we currently support ASCII only for that. But down the road, we may add support for default values for string parameters to a command or struct; if that happens, it would be nice to correctly support all JSON escape sequences, such as \n or \uXXXX. This gets us closer, by supporting Unicode escapes in the ASCII range.

Since JSON does not require \OCTAL or \xXX escapes, and our QMP implementation does not understand them either, I intentionally reject it here, but it would be an easy addition if we desired it. Likewise, intentionally refusing the NUL byte means we don't have to worry about C strings being shorter than the qapi input.

---

v7: add escape-outside-string, unknown-escape, and tighten parser to reject unknown escapes and \u0000

---
 scripts/qapi.py                              | 36 +++++++++++++++++++++++++++-
 tests/Makefile                               |  2 ++
 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      |  3 +++
 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/unknown-escape.err         |  1 +
 tests/qapi-schema/unknown-escape.exit        |  1 +
 tests/qapi-schema/unknown-escape.json        |  3 +++
 tests/qapi-schema/unknown-escape.out         |  0
 26 files changed, 66 insertions(+), 4 deletions(-)
 create mode 100644 tests/qapi-schema/escape-outside-string.err
 create mode 100644 tests/qapi-schema/escape-outside-string.exit
 create mode 100644 tests/qapi-schema/escape-outside-string.json
 create mode 100644 tests/qapi-schema/escape-outside-string.out
 create mode 100644 tests/qapi-schema/escape-too-big.err
 create mode 100644 tests/qapi-schema/escape-too-big.exit
 create mode 100644 tests/qapi-schema/escape-too-big.json
 create mode 100644 tests/qapi-schema/escape-too-big.out
 create mode 100644 tests/qapi-schema/escape-too-short.err
 create mode 100644 tests/qapi-schema/escape-too-short.exit
 create mode 100644 tests/qapi-schema/escape-too-short.json
 create mode 100644 tests/qapi-schema/escape-too-short.out
 create mode 100644 tests/qapi-schema/unicode-str.err
 create mode 100644 tests/qapi-schema/unicode-str.exit
 create mode 100644 tests/qapi-schema/unicode-str.json
 create mode 100644 tests/qapi-schema/unicode-str.out
 create mode 100644 tests/qapi-schema/unknown-escape.err
 create mode 100644 tests/qapi-schema/unknown-escape.exit
 create mode 100644 tests/qapi-schema/unknown-escape.json
 create mode 100644 tests/qapi-schema/unknown-escape.out
scripts/qapi.py +35 -1
index 91c39d2..6f7ff0e 100644
@@ -173,7 +173,41 @@ class QAPISchema:
                         raise QAPISchemaError(self,
                                               'Missing terminating "\'"')
                     if esc:
-                        string += ch
+                        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':
+                            value = 0
+                            for x in range(0, 4):
+                                ch = self.src[self.cursor]
+                                self.cursor += 1
+                                if ch not in "0123456789abcdefABCDEF":
+                                    raise QAPISchemaError(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 QAPISchemaError(self,
+                                                      'For now, \\u escape '
+                                                      'only supports non-zero '
+                                                      'values up to \\u007f')
+                            string += chr(value)
+                        elif ch in "\\/'\"":
+                            string += ch
+                        else:
+                            raise QAPISchemaError(self,
+                                                  "Unknown escape \\%s" %ch)
                         esc = False
                     elif ch == "\\":
                         esc = True
tests/Makefile +2 -0
index 45c205e..57d8987 100644
@@ -212,6 +212,8 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
 	enum-clash-member.json enum-max-member.json enum-union-clash.json \
 	enum-bad-name.json funny-char.json indented-expr.json \
 	missing-type.json bad-ident.json ident-with-escape.json \
+	escape-outside-string.json unknown-escape.json \
+	escape-too-short.json escape-too-big.json unicode-str.json \
 	double-type.json bad-base.json bad-type-bool.json bad-type-int.json \
 	bad-type-dict.json double-data.json unknown-expr-key.json \
 	redefined-type.json redefined-command.json redefined-builtin.json \
tests/qapi-schema/escape-outside-string.err new file +1 -0
new file mode 100644
index 0000000..b9b8837
@@ -0,0 +1 @@
+tests/qapi-schema/escape-outside-string.json:3:27: Stray "\"
tests/qapi-schema/escape-outside-string.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/escape-outside-string.json new file +3 -0
new file mode 100644
index 0000000..482f795
@@ -0,0 +1,3 @@
+# escape sequences are permitted only inside strings
+# { 'command': 'foo', 'data': {} }
+{ 'command': 'foo', 'data'\u003a{} }
tests/qapi-schema/escape-outside-string.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/escape-too-big.err new file +1 -0
new file mode 100644
index 0000000..d9aeb5d
@@ -0,0 +1 @@
+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 new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/escape-too-big.json new file +3 -0
new file mode 100644
index 0000000..62bcecd
@@ -0,0 +1,3 @@
+# we don't support full Unicode strings, yet
+# { 'command': 'é' }
+{ 'command': '\u00e9' }
tests/qapi-schema/escape-too-big.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/escape-too-short.err new file +1 -0
new file mode 100644
index 0000000..934de59
@@ -0,0 +1 @@
+tests/qapi-schema/escape-too-short.json:3:14: \u escape needs 4 hex digits
tests/qapi-schema/escape-too-short.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/escape-too-short.json new file +3 -0
new file mode 100644
index 0000000..6cb1dec
@@ -0,0 +1,3 @@
+# the \u escape requires 4 hex digits
+# { 'command': 'a' }
+{ 'command': '\u61' }
tests/qapi-schema/escape-too-short.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/ident-with-escape.err +0 -1
index f7d1c55..e69de29 100644
@@ -1 +0,0 @@
-tests/qapi-schema/ident-with-escape.json:3: Expression is missing metatype
tests/qapi-schema/ident-with-escape.exit +1 -1
index d00491f..573541a 100644
@@ -1 +1 @@
-1
+0
tests/qapi-schema/ident-with-escape.json +1 -1
index cfb2050..5661750 100644
@@ -1,4 +1,4 @@
-# FIXME: we should allow escape sequences in strings, if they map back to ASCII
+# we allow escape sequences in strings, if they map back to ASCII
 # { '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 +3 -0
index e69de29..4028430 100644
@@ -0,0 +1,3 @@
+[OrderedDict([('command', 'fooA'), ('data', OrderedDict([('bar1', 'str')]))])]
+[]
+[]
tests/qapi-schema/unicode-str.err new file +1 -0
new file mode 100644
index 0000000..f621cd6
@@ -0,0 +1 @@
+tests/qapi-schema/unicode-str.json:2: 'command' uses invalid name 'é'
tests/qapi-schema/unicode-str.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/unicode-str.json new file +2 -0
new file mode 100644
index 0000000..5253a1b
@@ -0,0 +1,2 @@
+# we don't support full Unicode strings, yet
+{ 'command': 'é' }
tests/qapi-schema/unicode-str.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/unknown-escape.err new file +1 -0
new file mode 100644
index 0000000..000e30d
@@ -0,0 +1 @@
+tests/qapi-schema/unknown-escape.json:3:21: Unknown escape \x
tests/qapi-schema/unknown-escape.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/unknown-escape.json new file +3 -0
new file mode 100644
index 0000000..8e6891e
@@ -0,0 +1,3 @@
+# we only recognize JSON escape sequences, plus our \' extension (no \x)
+# { 'command': 'foo', 'data': {} }
+{ 'command': 'foo', 'dat\x61':{} }
tests/qapi-schema/unknown-escape.out new file +0 -0
new file mode 100644
index 0000000..e69de29
Signature · 1 line
2.1.0
author
#46 lore raw

PATCH v7 39/39 qapi: Check for member name conflicts with a base class

In reply to Eric Blake

Our type inheritance for both 'struct' and for flat 'union' merges key/value pairs from the base class with those from the type in question. Although the C code currently boxes things so that there is a distinction between which member is referred to, the QMP wire format does not allow passing a key more than once in a single object. Besides, if we ever change the generated C code to not be quite so boxy, we'd want to avoid duplicate member names there, too.

Fix a testsuite entry added in an earlier patch, as well as adding a couple more tests to ensure we have appropriate coverage.

---

v7: rebase to earlier changes, reuse base instead of expr['base']

---
 scripts/qapi.py                                | 21 ++++++++++++++++++++-
 tests/Makefile                                 |  3 ++-
 tests/qapi-schema/flat-union-branch-clash.err  |  1 +
 tests/qapi-schema/flat-union-branch-clash.exit |  2 +-
 tests/qapi-schema/flat-union-branch-clash.json |  2 +-
 tests/qapi-schema/flat-union-branch-clash.out  |  9 ---------
 tests/qapi-schema/struct-base-clash-deep.err   |  1 +
 tests/qapi-schema/struct-base-clash-deep.exit  |  1 +
 tests/qapi-schema/struct-base-clash-deep.json  |  9 +++++++++
 tests/qapi-schema/struct-base-clash-deep.out   |  0
 tests/qapi-schema/struct-base-clash.err        |  1 +
 tests/qapi-schema/struct-base-clash.exit       |  1 +
 tests/qapi-schema/struct-base-clash.json       |  6 ++++++
 tests/qapi-schema/struct-base-clash.out        |  0
 14 files changed, 44 insertions(+), 13 deletions(-)
 create mode 100644 tests/qapi-schema/struct-base-clash-deep.err
 create mode 100644 tests/qapi-schema/struct-base-clash-deep.exit
 create mode 100644 tests/qapi-schema/struct-base-clash-deep.json
 create mode 100644 tests/qapi-schema/struct-base-clash-deep.out
 create mode 100644 tests/qapi-schema/struct-base-clash.err
 create mode 100644 tests/qapi-schema/struct-base-clash.exit
 create mode 100644 tests/qapi-schema/struct-base-clash.json
 create mode 100644 tests/qapi-schema/struct-base-clash.out
scripts/qapi.py +20 -1
index 6f7ff0e..4ec8646 100644
@@ -414,6 +414,18 @@ def check_type(expr_info, source, value, allow_array = False,
                    allow_metas=['built-in', 'union', 'alternate', 'struct',
                                 'enum'])
 
+def check_member_clash(expr_info, base_name, data, source = ""):
+    base = find_struct(base_name)
+    assert base
+    base_members = base['data']
+    for key in data.keys():
+        if key in base_members:
+            raise QAPIExprError(expr_info,
+                                "Member name '%s'%s clashes with base '%s'"
+                                %(key, source, base_name))
+    if base.get('base'):
+        check_member_clash(expr_info, base['base'], data, source)
+
 def check_command(expr, expr_info):
     name = expr['command']
     allow_star = expr.has_key('gen')
@@ -503,9 +515,14 @@ def check_union(expr, expr_info):
         check_name(expr_info, "Member of union '%s'" % name, key)
 
         # Each value must name a known type; furthermore, in flat unions,
-        # branches must be a struct
+        # branches must be a struct with no overlapping member names
         check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
                    value, allow_array=True, allow_metas=allow_metas)
+        if base:
+            branch_struct = find_struct(value)
+            assert branch_struct
+            check_member_clash(expr_info, base, branch_struct['data'],
+                               " of branch '%s'" %key)
 
         # If the discriminator names an enum type, then all members
         # of 'data' must also be members of the enum type.
@@ -582,6 +599,8 @@ def check_struct(expr, expr_info):
                allow_dict=True, allow_optional=True)
     check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
                allow_metas=['struct'])
+    if expr.get('base'):
+        check_member_clash(expr_info, expr['base'], expr['data'])
 
 def check_exprs(schema):
     for expr_elem in schema.exprs:
tests/Makefile +2 -1
index 57d8987..bf69be9 100644
@@ -243,7 +243,8 @@ check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
 	include-simple.json include-relpath.json include-format-err.json \
 	include-non-file.json include-no-file.json include-before-err.json \
 	include-nested-err.json include-self-cycle.json include-cycle.json \
-	include-repetition.json event-nest-struct.json event-case.json)
+	include-repetition.json event-nest-struct.json event-case.json \
+	struct-base-clash.json struct-base-clash-deep.json )
 
 GENERATED_HEADERS += tests/test-qapi-types.h tests/test-qapi-visit.h \
 		     tests/test-qmp-commands.h tests/test-qapi-event.h
tests/qapi-schema/flat-union-branch-clash.err +1 -0
index e69de29..f112766 100644
@@ -0,0 +1 @@
+tests/qapi-schema/flat-union-branch-clash.json:10: Member name 'name' of branch 'value1' clashes with base 'Base'
tests/qapi-schema/flat-union-branch-clash.exit +1 -1
index 573541a..d00491f 100644
@@ -1 +1 @@
-0
+1
tests/qapi-schema/flat-union-branch-clash.json +1 -1
index 8b0b807..b3c6ffe 100644
@@ -1,4 +1,4 @@
-# FIXME: we should check for no duplicate keys between branches and base
+# we check for no duplicate keys between branches and base
 { 'enum': 'TestEnum',
   'data': [ 'value1', 'value2' ] }
 { 'struct': 'Base',
tests/qapi-schema/flat-union-branch-clash.out +0 -9
index 04c2395..e69de29 100644
@@ -1,9 +0,0 @@
-[OrderedDict([('enum', 'TestEnum'), ('data', ['value1', 'value2'])]),
- OrderedDict([('struct', 'Base'), ('data', OrderedDict([('enum1', 'TestEnum'), ('name', 'str')]))]),
- OrderedDict([('struct', 'Branch1'), ('data', OrderedDict([('name', 'str')]))]),
- OrderedDict([('struct', 'Branch2'), ('data', OrderedDict([('value', 'int')]))]),
- OrderedDict([('union', 'TestUnion'), ('base', 'Base'), ('discriminator', 'enum1'), ('data', OrderedDict([('value1', 'Branch1'), ('value2', 'Branch2')]))])]
-[{'enum_name': 'TestEnum', 'enum_values': ['value1', 'value2']}]
-[OrderedDict([('struct', 'Base'), ('data', OrderedDict([('enum1', 'TestEnum'), ('name', 'str')]))]),
- OrderedDict([('struct', 'Branch1'), ('data', OrderedDict([('name', 'str')]))]),
- OrderedDict([('struct', 'Branch2'), ('data', OrderedDict([('value', 'int')]))])]
tests/qapi-schema/struct-base-clash-deep.err new file +1 -0
new file mode 100644
index 0000000..e3e9f8d
@@ -0,0 +1 @@
+tests/qapi-schema/struct-base-clash-deep.json:7: Member name 'name' clashes with base 'Base'
tests/qapi-schema/struct-base-clash-deep.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/struct-base-clash-deep.json new file +9 -0
new file mode 100644
index 0000000..08c8c9c
@@ -0,0 +1,9 @@
+# we check for no duplicate keys with indirect base
+{ 'struct': 'Base',
+  'data': { 'name': 'str' } }
+{ 'struct': 'Mid',
+  'base': 'Base',
+  'data': { 'value': 'int' } }
+{ 'struct': 'Sub',
+  'base': 'Mid',
+  'data': { 'name': 'str' } }
tests/qapi-schema/struct-base-clash-deep.out new file +0 -0
new file mode 100644
index 0000000..e69de29
tests/qapi-schema/struct-base-clash.err new file +1 -0
new file mode 100644
index 0000000..3ac37fb
@@ -0,0 +1 @@
+tests/qapi-schema/struct-base-clash.json:4: Member name 'name' clashes with base 'Base'
tests/qapi-schema/struct-base-clash.exit new file +1 -0
new file mode 100644
index 0000000..d00491f
@@ -0,0 +1 @@
+1
tests/qapi-schema/struct-base-clash.json new file +6 -0
new file mode 100644
index 0000000..f2afc9b
@@ -0,0 +1,6 @@
+# we check for no duplicate keys with base
+{ 'struct': 'Base',
+  'data': { 'name': 'str' } }
+{ 'struct': 'Sub',
+  'base': 'Base',
+  'data': { 'name': 'str' } }
tests/qapi-schema/struct-base-clash.out new file +0 -0
new file mode 100644
index 0000000..e69de29
Signature · 1 line
2.1.0
author
#47 lore raw

Re: [Qemu-devel] [PATCH v7 39/39] qapi: Check for member name conflicts with a base class

Quoted 20 lines · Eric Blake

Our type inheritance for both 'struct' and for flat 'union' merges key/value pairs from the base class with those from the type in question. Although the C code currently boxes things so that there is a distinction between which member is referred to, the QMP wire format does not allow passing a key more than once in a single object. Besides, if we ever change the generated C code to not be quite so boxy, we'd want to avoid duplicate member names there, too.

Fix a testsuite entry added in an earlier patch, as well as adding a couple more tests to ensure we have appropriate coverage.

---

+++ b/scripts/qapi.py

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

Quoted 9 lines
scripts/qapi.py +6 -0
@@ -414,6 +414,18 @@ def check_type(expr_info, source, value, allow_array = False,
                    allow_metas=['built-in', 'union', 'alternate', 'struct',
                                 'enum'])
 
+def check_member_clash(expr_info, base_name, data, source = ""):
+    base = find_struct(base_name)
+    assert base
+    base_members = base['data']
+    for key in data.keys():
+        if key in base_members:

Fails to consider what happens when one but not both of the dictionaries being compared marked the member as optional (that is, the key '*name' must be treated as conflicting with 'name'). Followup on the way; it's not a regression, so you can either squash into this or leave as standalone. Again, let me know if you'd rather me post a v8 with all my squashes folded in.

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

PATCH v7 1/1 squash: qapi: Check for member name conflicts with a base class

In reply to Eric Blake

A conflict must be marked even when the two dictionaries being compared differ on whether the key is marked optional.

---
 scripts/qapi.py                                | 4 +++-
 tests/qapi-schema/flat-union-branch-clash.json | 2 +-
 tests/qapi-schema/struct-base-clash-deep.json  | 2 +-
 3 files changed, 5 insertions(+), 3 deletions(-)
scripts/qapi.py +3 -1
index 4ec8646..ad20d3e 100644
@@ -419,7 +419,9 @@ def check_member_clash(expr_info, base_name, data, source = ""):
     assert base
     base_members = base['data']
     for key in data.keys():
-        if key in base_members:
+        if key.startswith('*'):
+            key = key[1:]
+        if key in base_members or "*%s" %key in base_members:
             raise QAPIExprError(expr_info,
                                 "Member name '%s'%s clashes with base '%s'"
                                 %(key, source, base_name))
tests/qapi-schema/flat-union-branch-clash.json +1 -1
index b3c6ffe..8fb054f 100644
@@ -2,7 +2,7 @@
 { 'enum': 'TestEnum',
   'data': [ 'value1', 'value2' ] }
 { 'struct': 'Base',
-  'data': { 'enum1': 'TestEnum', 'name': 'str' } }
+  'data': { 'enum1': 'TestEnum', '*name': 'str' } }
 { 'struct': 'Branch1',
   'data': { 'name': 'str' } }
 { 'struct': 'Branch2',
tests/qapi-schema/struct-base-clash-deep.json +1 -1
index 08c8c9c..552fe94 100644
@@ -6,4 +6,4 @@
   'data': { 'value': 'int' } }
 { 'struct': 'Sub',
   'base': 'Mid',
-  'data': { 'name': 'str' } }
+  'data': { '*name': 'str' } }
Signature · 1 line
2.1.0