qapi: generalize special features
v2 cover qapi: generalize special features
This series is a spin-off from
https://lists.nongnu.org/archive/html/qemu-devel/2024-06/msg00807.html
That series introduced a pragma allowing a schema to declare extra features that would be exposed to code.
Following Markus' suggestion:
https://lists.nongnu.org/archive/html/qemu-devel/2024-07/msg03765.html
I've changed impl such that we expose all features to the code regardless of whether they are special, and don't require any pragma.
I've split it from the QGA patches since it makes more sense to work on this bit in isolation.
Changed in v2:
* Reference QapiSpecialFeature enums constants when defining QapiFeature enums constants for deprecated & unstable
* Don't expose qapi-features.h in qapi-types.h, to avoid global namespace pollution, instead pull it into only the .c files that need it. This avoids the need to add a 'prefix' to enum constants
* Collect all features during parse time, rather than generate time, to allow earlier error reporting of the 64 feature limit
Daniel P. Berrangé (4):
qapi: cope with feature names containing a '-'
qapi: change 'unsigned special_features' to 'uint64_t features'
qapi: rename 'special_features' to 'features'
qapi: expose all schema features to code
include/qapi/compat-policy.h | 2 +- include/qapi/qmp/dispatch.h | 4 +-- include/qapi/util.h | 2 +- include/qapi/visitor-impl.h | 4 +-- include/qapi/visitor.h | 12 +++---- meson.build | 1 + qapi/qapi-forward-visitor.c | 8 ++--- qapi/qapi-util.c | 6 ++-- qapi/qapi-visit-core.c | 12 +++---- qapi/qmp-dispatch.c | 2 +- qapi/qmp-registry.c | 4 +-- qapi/qobject-input-visitor.c | 4 +-- qapi/qobject-output-visitor.c | 6 ++-- scripts/qapi/commands.py | 5 +-- scripts/qapi/features.py | 62 +++++++++++++++++++++++++++++++++++ scripts/qapi/gen.py | 9 ++--- scripts/qapi/main.py | 2 ++ scripts/qapi/schema.py | 19 ++++++++++- scripts/qapi/types.py | 18 +++++----- scripts/qapi/visit.py | 17 +++++----- 20 files changed, 143 insertions(+), 56 deletions(-) create mode 100644 scripts/qapi/features.py
Signature · 1 line
2.46.0
PATCH v2 1/4 qapi: cope with feature names containing a '-'
When we shortly expose all feature names to code, it will be valid to include a '-', which must be translated to a '_' for the enum constants.
--- scripts/qapi/gen.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
scripts/qapi/gen.py +2 -1
@@ -24,6 +24,7 @@ ) from .common import ( + c_enum_const, c_fname, c_name, guardend,
@@ -41,7 +42,7 @@ def gen_special_features(features: Sequence[QAPISchemaFeature]) -> str: - special_features = [f"1u << QAPI_{feat.name.upper()}" + special_features = [f"1u << {c_enum_const('qapi', feat.name)}" for feat in features if feat.is_special()] return ' | '.join(special_features) or '0'
Signature · 1 line
2.46.0
PATCH v2 2/4 qapi: change 'unsigned special_features' to 'uint64_t features'
In reply to Daniel P. BerrangéThe "special_features" field / parameter holds the subset of schema features that are for internal code use. Specifically 'DEPRECATED' and 'UNSTABLE'.
This special casing of internal features is going to be removed, so prepare for that by renaming to 'features'. Using a fixed size type is also best practice for bit fields.
--- include/qapi/compat-policy.h | 2 +- include/qapi/qmp/dispatch.h | 4 ++-- include/qapi/util.h | 2 +- include/qapi/visitor-impl.h | 4 ++-- include/qapi/visitor.h | 12 ++++++------ qapi/qapi-forward-visitor.c | 8 ++++---- qapi/qapi-util.c | 6 +++--- qapi/qapi-visit-core.c | 12 ++++++------ qapi/qmp-dispatch.c | 2 +- qapi/qmp-registry.c | 4 ++-- qapi/qobject-input-visitor.c | 4 ++-- qapi/qobject-output-visitor.c | 6 +++--- scripts/qapi/types.py | 2 +- 13 files changed, 34 insertions(+), 34 deletions(-)
include/qapi/compat-policy.h +1 -1
@@ -18,7 +18,7 @@extern CompatPolicy compat_policy; -bool compat_policy_input_ok(unsigned special_features, +bool compat_policy_input_ok(uint64_t features, const CompatPolicy *policy, ErrorClass error_class, const char *kind, const char *name,
include/qapi/qmp/dispatch.h +2 -2
@@ -33,7 +33,7 @@ typedef struct QmpCommand/* Runs in coroutine context if QCO_COROUTINE is set */ QmpCommandFunc *fn;QmpCommandOptions options; -unsigned special_features; +uint64_t features;QTAILQ_ENTRY (QmpCommand) node;bool enabled;const char *disable_reason;
@@ -43,7 +43,7 @@ typedef QTAILQ_HEAD(QmpCommandList, QmpCommand) QmpCommandList;void qmp_register_command (QmpCommandList *cmds,const char *name,QmpCommandFunc *fn,QmpCommandOptions options, -unsigned special_features); +uint64_t features);const QmpCommand *qmp_find_command (const QmpCommandList *cmds,const char *name); void qmp_disable_command(QmpCommandList *cmds, const char *name,
include/qapi/util.h +1 -1
@@ -18,7 +18,7 @@ typedef enum {typedef struct QEnumLookup {const char *const *array; -const unsigned char *const special_features; +const uint64_t *const features;const int size; }QEnumLookup ;
include/qapi/visitor-impl.h +2 -2
@@ -115,11 +115,11 @@ struct Visitor/* Optional */ bool (*policy_reject)(Visitor *v,const char *name, -unsigned special_features,Error **errp); +uint64_t features,Error **errp);/* Optional */ bool (*policy_skip)(Visitor *v,const char *name, -unsigned special_features); +uint64_t features);/* Must be set */ VisitorType type;
include/qapi/visitor.h +6 -6
@@ -463,29 +463,29 @@ bool visit_optional(Visitor *v, const char *name, bool *present);/* * Should we reject member @name due to policy? * -* @special_features is the member's special features encoded as a -* bitset of QapiSpecialFeature. +* @features is the member's special features encoded as a +* bitset of QapiFeature. * * @name must not be NULL. This function is only useful between * visit_start_struct() and visit_end_struct(), since only objects * have deprecated members. */ bool visit_policy_reject (Visitor *v,const char *name, -unsigned special_features,Error **errp); +uint64_t features,Error **errp);/* * * Should we skip member @name due to policy? * -* @special_features is the member's special features encoded as a -* bitset of QapiSpecialFeature. +* @features is the member's special features encoded as a +* bitset of QapiFeature. * * @name must not be NULL. This function is only useful between * visit_start_struct() and visit_end_struct(), since only objects * have deprecated members. */ bool visit_policy_skip (Visitor *v,const char *name, -unsigned special_features); +uint64_t features);/* * Set policy for handling deprecated management interfaces.
qapi/qapi-forward-visitor.c +4 -4
@@ -246,7 +246,7 @@ static void forward_field_optional(Visitor *v, const char *name, bool *present) }static bool forward_field_policy_reject (Visitor *v,const char *name, -unsigned special_features, +uint64_t features,Error **errp) {ForwardFieldVisitor *ffv =to_ffv (v);
@@ -254,18 +254,18 @@ static bool forward_field_policy_reject(Visitor *v, const char *name,if (!forward_field_translate_name (ffv, &name, errp)) {return true; } -return visit_policy_reject (ffv->target, name, special_features, errp); +return visit_policy_reject (ffv->target, name, features, errp); }static bool forward_field_policy_skip (Visitor *v,const char *name, -unsigned special_features) +uint64_t features) {ForwardFieldVisitor *ffv =to_ffv (v);if (!forward_field_translate_name (ffv, &name,NULL )) {return true; } -return visit_policy_skip (ffv->target, name, special_features); +return visit_policy_skip (ffv->target, name, features); }static void forward_field_complete (Visitor *v,void *opaque)
qapi/qapi-util.c +3 -3
@@ -37,19 +37,19 @@ static bool compat_policy_input_ok1(const char *adjective, } } -bool compat_policy_input_ok (unsigned special_features, +bool compat_policy_input_ok (uint64_t features,const CompatPolicy *policy,ErrorClass error_class,const char *kind,const char *name,Error **errp) { -if ((special_features &1u <<QAPI_DEPRECATED ) +if ((features &1u <<QAPI_DEPRECATED ) && !compat_policy_input_ok1 ("Deprecated" , policy->deprecated_input, error_class, kind, name, errp)) {return false; } -if ((special_features & (1u <<QAPI_UNSTABLE )) +if ((features & (1u <<QAPI_UNSTABLE )) && !compat_policy_input_ok1 ("Unstable" , policy->unstable_input, error_class, kind, name, errp)) {
qapi/qapi-visit-core.c +6 -6
@@ -141,21 +141,21 @@ bool visit_optional(Visitor *v, const char *name, bool *present) }bool visit_policy_reject (Visitor *v,const char *name, -unsigned special_features,Error **errp) +uint64_t features,Error **errp) {trace_visit_policy_reject (v, name);if (v->policy_reject) { -return v->policy_reject (v, name, special_features, errp); +return v->policy_reject (v, name, features, errp); }return false; }bool visit_policy_skip (Visitor *v,const char *name, -unsigned special_features) +uint64_t features) {trace_visit_policy_skip (v, name);if (v->policy_skip) { -return v->policy_skip (v, name, special_features); +return v->policy_skip (v, name, features); }return false; }
@@ -409,8 +409,8 @@ static bool input_type_enum(Visitor *v, const char *name, int *obj,return false; } -if (lookup->special_features - && !compat_policy_input_ok (lookup->special_features[value], +if (lookup->features + && !compat_policy_input_ok (lookup->features[value], &v->compat_policy,ERROR_CLASS_GENERIC_ERROR ,"value" , enum_str, errp)) {
qapi/qmp-dispatch.c +1 -1
@@ -173,7 +173,7 @@ QDict *coroutine_mixed_fn qmp_dispatch(const QmpCommandList *cmds, QObject *requ "The command %s has not been found", command); goto out; } -if (!compat_policy_input_ok (cmd->special_features, &compat_policy, +if (!compat_policy_input_ok (cmd->features, &compat_policy,ERROR_CLASS_COMMAND_NOT_FOUND ,"command" , command, &err)) { goto out;
qapi/qmp-registry.c +2 -2
@@ -17,7 +17,7 @@void qmp_register_command (QmpCommandList *cmds,const char *name,QmpCommandFunc *fn,QmpCommandOptions options, -unsigned special_features) +uint64_t features) {QmpCommand *cmd =g_malloc0 (sizeof (*cmd));
@@ -28,7 +28,7 @@ void qmp_register_command(QmpCommandList *cmds, const char *name, cmd->fn = fn; cmd->enabled = true; cmd->options = options; - cmd->special_features = special_features; + cmd->features = features;QTAILQ_INSERT_TAIL (cmds, cmd, node); }
qapi/qobject-input-visitor.c +2 -2
@@ -664,10 +664,10 @@ static void qobject_input_optional(Visitor *v, const char *name, bool *present) }static bool qobject_input_policy_reject (Visitor *v,const char *name, -unsigned special_features, +uint64_t features,Error **errp) { -return !compat_policy_input_ok (special_features, &v->compat_policy, +return !compat_policy_input_ok (features, &v->compat_policy,ERROR_CLASS_GENERIC_ERROR ,"parameter" , name, errp); }
qapi/qobject-output-visitor.c +3 -3
@@ -210,13 +210,13 @@ static bool qobject_output_type_null(Visitor *v, const char *name, }static bool qobject_output_policy_skip (Visitor *v,const char *name, -unsigned special_features) +uint64_t features) {CompatPolicy *pol = &v->compat_policy; -return ((special_features &1u <<QAPI_DEPRECATED ) +return ((features &1u <<QAPI_DEPRECATED ) && pol->deprecated_output ==COMPAT_POLICY_OUTPUT_HIDE ) - || ((special_features &1u <<QAPI_UNSTABLE ) + || ((features &1u <<QAPI_UNSTABLE ) && pol->unstable_output ==COMPAT_POLICY_OUTPUT_HIDE ); }
scripts/qapi/types.py +1 -1
@@ -71,7 +71,7 @@ def gen_enum_lookup(name: str, if feats: ret += mcgen(''' }, - .special_features = (const unsigned char[%(max_index)s]) { + .features = (const uint64_t[%(max_index)s]) { ''', max_index=max_index) ret += feats
Signature · 1 line
2.46.0
Re: [PATCH v2 2/4] qapi: change 'unsigned special_features' to 'uint64_t features'
Quoted 9 lines · Daniel P. Berrangé
The "
special_features" field / parameter holds the subset of schema features that are for internal code use. Specifically 'DEPRECATED' and 'UNSTABLE'.This special casing of internal features is going to be removed, so prepare for that by renaming to 'features'. Using a fixed size type is also best practice for bit fields.
Signed-off-by Daniel P. Berrangé <[email protected]>
Quoted 15 lines
--- include/qapi/compat-policy.h | 2 +- include/qapi/qmp/dispatch.h | 4 ++-- include/qapi/util.h | 2 +- include/qapi/visitor-impl.h | 4 ++-- include/qapi/visitor.h | 12 ++++++------ qapi/qapi-forward-visitor.c | 8 ++++---- qapi/qapi-util.c | 6 +++--- qapi/qapi-visit-core.c | 12 ++++++------ qapi/qmp-dispatch.c | 2 +- qapi/qmp-registry.c | 4 ++-- qapi/qobject-input-visitor.c | 4 ++-- qapi/qobject-output-visitor.c | 6 +++--- scripts/qapi/types.py | 2 +- 13 files changed, 34 insertions(+), 34 deletions(-)
PATCH v2 3/4 qapi: rename 'special_features' to 'features'
In reply to Daniel P. BerrangéThis updates the QAPI code generation to refer to 'features' instead of 'special_features', in preparation for generalizing their exposure.
--- scripts/qapi/commands.py | 4 ++-- scripts/qapi/gen.py | 6 +++--- scripts/qapi/types.py | 10 +++++----- scripts/qapi/visit.py | 14 +++++++------- 4 files changed, 17 insertions(+), 17 deletions(-)
scripts/qapi/commands.py +2 -2
@@ -25,7 +25,7 @@ QAPIGenC, QAPISchemaModularCVisitor, build_params, - gen_special_features, + gen_features, ifcontext, ) from .schema import (
@@ -298,7 +298,7 @@ def gen_register_command(name: str, ''', name=name, c_name=c_name(name), opts=' | '.join(options) or 0, - feats=gen_special_features(features)) + feats=gen_features(features)) return ret
scripts/qapi/gen.py +3 -3
@@ -41,10 +41,10 @@ from .source import QAPISourceInfo -def gen_special_features(features: Sequence[QAPISchemaFeature]) -> str: - special_features = [f"1u << {c_enum_const('qapi', feat.name)}" +def gen_features(features: Sequence[QAPISchemaFeature]) -> str: + features = [f"1u << {c_enum_const('qapi', feat.name)}" for feat in features if feat.is_special()] - return ' | '.join(special_features) or '0' + return ' | '.join(features) or '0' class QAPIGen:
scripts/qapi/types.py +5 -5
@@ -18,7 +18,7 @@ from .common import c_enum_const, c_name, mcgen from .gen import ( QAPISchemaModularCVisitor, - gen_special_features, + gen_features, ifcontext, ) from .schema import (
@@ -61,12 +61,12 @@ def gen_enum_lookup(name: str, index=index, name=memb.name) ret += memb.ifcond.gen_endif() - special_features = gen_special_features(memb.features) - if special_features != '0': + features = gen_features(memb.features) + if features != '0': feats += mcgen(''' - [%(index)s] = %(special_features)s, + [%(index)s] = %(features)s, ''', - index=index, special_features=special_features) + index=index, features=features) if feats: ret += mcgen('''
scripts/qapi/visit.py +7 -7
@@ -23,7 +23,7 @@ ) from .gen import ( QAPISchemaModularCVisitor, - gen_special_features, + gen_features, ifcontext, ) from .schema import (
@@ -103,15 +103,15 @@ def gen_visit_object_members(name: str, ''', name=memb.name, has=has) indent.increase() - special_features = gen_special_features(memb.features) - if special_features != '0': + features = gen_features(memb.features) + if features != '0': ret += mcgen(''' - if (visit_policy_reject(v, "%(name)s", %(special_features)s, errp)) { + if (visit_policy_reject(v, "%(name)s", %(features)s, errp)) { return false; } - if (!visit_policy_skip(v, "%(name)s", %(special_features)s)) { + if (!visit_policy_skip(v, "%(name)s", %(features)s)) { ''', - name=memb.name, special_features=special_features) + name=memb.name, features=features) indent.increase() ret += mcgen(''' if (!visit_type_%(c_type)s(v, "%(name)s", &obj->%(c_name)s, errp)) {
@@ -120,7 +120,7 @@ def gen_visit_object_members(name: str, ''', c_type=memb.type.c_name(), name=memb.name, c_name=c_name(memb.name)) - if special_features != '0': + if features != '0': indent.decrease() ret += mcgen(''' }
Signature · 1 line
2.46.0
Re: [PATCH v2 3/4] qapi: rename 'special_features' to 'features'
Quoted 10 lines · Daniel P. Berrangé
This updates the QAPI code generation to refer to 'features' instead of '
special_features', in preparation for generalizing their exposure.Signed-off-by Daniel P. Berrangé <[email protected]>--- scripts/qapi/commands.py | 4 ++-- scripts/qapi/gen.py | 6 +++--- scripts/qapi/types.py | 10 +++++----- scripts/qapi/visit.py | 14 +++++++------- 4 files changed, 17 insertions(+), 17 deletions(-)
Re: [PATCH v2 3/4] qapi: rename 'special_features' to 'features'
In reply to Daniel P. BerrangéQuoted 38 lines · Daniel P. Berrangé
This updates the QAPI code generation to refer to 'features' instead of '
special_features', in preparation for generalizing their exposure.Signed-off-by Daniel P. Berrangé <[email protected]>--- scripts/qapi/commands.py | 4 ++-- scripts/qapi/gen.py | 6 +++--- scripts/qapi/types.py | 10 +++++----- scripts/qapi/visit.py | 14 +++++++------- 4 files changed, 17 insertions(+), 17 deletions(-)scripts/qapi/commands.py +2
-2@@ -25,7 +25,7 @@ QAPIGenC, QAPISchemaModularCVisitor, build_params, - gen_special_features, + gen_features, ifcontext, ) from .schema import (@@ -298,7 +298,7 @@ def gen_register_command(name: str, ''', name=name, c_name=c_name(name), opts=' | '.join(options) or 0, - feats=gen_special_features(features)) + feats=gen_features(features)) return retscripts/qapi/gen.py +0
-0
scripts/qapi/gen.py line 46
Quoted 8 lines
scripts/qapi/gen.py +2
-2@@ -41,10 +41,10 @@ from .source import QAPISourceInfo -def gen_special_features(features: Sequence[QAPISchemaFeature]) -> str: - special_features = [f"1u << {c_enum_const('qapi', feat.name)}" +def gen_features(features: Sequence[QAPISchemaFeature]) -> str: + features = [f"1u << {c_enum_const('qapi', feat.name)}" for feat in features if feat.is_special()]
pycodestyle gripes
scripts/qapi/gen.py:46:25: E127 continuation line over-indented for visual indent
More seriously, mypy gripes
scripts/qapi/gen.py:45: error: List comprehension has incompatible type List[str]; expected List[QAPISchemaFeature] [misc]
here, and ...
scripts/qapi/gen.py line 47
Quoted 2 lines
scripts/qapi/gen.py +1
-1- return ' | '.join(special_features) or '0' + return ' | '.join(features) or '0'
scripts/qapi/gen.py:47: error: Argument 1 to "join" of "str" has incompatible type "List[QAPISchemaFeature]"; expected "Iterable[str]" [arg-type]
This is due to your assignment to parameter @feature. Use a new variable instead.
Quoted 3 lines
scripts/qapi/gen.py +0
-0class QAPIGen:
[...]
PATCH v2 4/4 qapi: expose all schema features to code
In reply to Daniel P. BerrangéThis replaces use of the constants from the QapiSpecialFeatures enum, with constants from the auto-generate QapiFeatures enum in qapi-features.h
The 'deprecated' and 'unstable' features still have a little bit of special handling, being force defined to be the 1st + 2nd features in the enum, regardless of whether they're used in the schema. This retains compatibility with common code that references the features via the QapiSpecialFeatures constants.
--- meson.build | 1 + scripts/qapi/commands.py | 1 + scripts/qapi/features.py | 62 ++++++++++++++++++++++++++++++++++++++++ scripts/qapi/gen.py | 4 +-- scripts/qapi/main.py | 2 ++ scripts/qapi/schema.py | 19 +++++++++++- scripts/qapi/types.py | 6 ++-- scripts/qapi/visit.py | 3 +- 8 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 scripts/qapi/features.py
meson.build +1 -0
@@ -3332,6 +3332,7 @@ qapi_gen_depends = [ meson.current_source_dir() / 'scripts/qapi/__init__.py', meson.current_source_dir() / 'scripts/qapi/schema.py', meson.current_source_dir() / 'scripts/qapi/source.py', meson.current_source_dir() / 'scripts/qapi/types.py', + meson.current_source_dir() / 'scripts/qapi/features.py', meson.current_source_dir() / 'scripts/qapi/visit.py', meson.current_source_dir() / 'scripts/qapi-gen.py' ]
scripts/qapi/commands.py +1 -0
@@ -355,6 +355,7 @@ def visit_begin(self, schema: QAPISchema) -> None: #include "qemu/osdep.h" #include "%(prefix)sqapi-commands.h" #include "%(prefix)sqapi-init-commands.h" +#include "%(prefix)sqapi-features.h" void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds) {
scripts/qapi/features.py new file +62 -0
62 lines not on this page · raw message
scripts/qapi/gen.py +2 -2
@@ -42,8 +42,8 @@ def gen_features(features: Sequence[QAPISchemaFeature]) -> str: - features = [f"1u << {c_enum_const('qapi', feat.name)}" - for feat in features if feat.is_special()] + features = [f"1u << {c_enum_const('qapi_feature', feat.name)}" + for feat in features] return ' | '.join(features) or '0'
scripts/qapi/main.py +2 -0
@@ -18,6 +18,7 @@ from .introspect import gen_introspect from .schema import QAPISchema from .types import gen_types +from .features import gen_features from .visit import gen_visit
@@ -49,6 +50,7 @@ def generate(schema_file: str, schema = QAPISchema(schema_file) gen_types(schema, output_dir, prefix, builtins) + gen_features(schema, output_dir, prefix) gen_visit(schema, output_dir, prefix, builtins) gen_commands(schema, output_dir, prefix, gen_tracing) gen_events(schema, output_dir, prefix)
scripts/qapi/schema.py +18 -1
@@ -933,8 +933,11 @@ def connect_doc(self, doc: Optional[QAPIDoc]) -> None: class QAPISchemaFeature(QAPISchemaMember): role = 'feature' + # Features which are standardized across all schemas + SPECIAL_NAMES = ['deprecated', 'unstable'] + def is_special(self) -> bool: - return self.name in ('deprecated', 'unstable') + return self.name in QAPISchemaFeature.SPECIAL_NAMES class QAPISchemaObjectTypeMember(QAPISchemaMember):
@@ -1138,6 +1141,11 @@ def __init__(self, fname: str): self._entity_list: List[QAPISchemaEntity] = [] self._entity_dict: Dict[str, QAPISchemaDefinition] = {} self._module_dict: Dict[str, QAPISchemaModule] = OrderedDict() + self._feature_dict: Dict[str, QAPISchemaFeature] = {} + + for f in QAPISchemaFeature.SPECIAL_NAMES: + self._feature_dict[f] = QAPISchemaFeature(f, "special feature") + self._schema_dir = os.path.dirname(fname) self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME) self._make_module(fname)
@@ -1258,6 +1266,15 @@ def _make_features( ) -> List[QAPISchemaFeature]: if features is None: return [] + + for f in features: + feat = QAPISchemaFeature(f['name'], info) + if feat.name not in self._feature_dict: + if len(self._feature_dict) == 64: + raise Exception("Maximum of 64 schema features is permitted") + + self._feature_dict[feat.name] = feat + return [QAPISchemaFeature(f['name'], info, QAPISchemaIfCond(f.get('if'))) for f in features]
scripts/qapi/types.py +4 -2
@@ -308,11 +308,13 @@ def _begin_user_module(self, name: str) -> None: #include "qapi/dealloc-visitor.h" #include "%(types)s.h" #include "%(visit)s.h" +#include "%(prefix)sqapi-features.h" ''', - types=types, visit=visit)) + types=types, visit=visit, prefix=self._prefix)) self._genh.preamble_add(mcgen(''' #include "qapi/qapi-builtin-types.h" -''')) +''', + prefix=self._prefix)) def visit_begin(self, schema: QAPISchema) -> None: # gen_object() is recursive, ensure it doesn't visit the empty type
scripts/qapi/visit.py +2 -1
@@ -360,8 +360,9 @@ def _begin_user_module(self, name: str) -> None: #include "qemu/osdep.h" #include "qapi/error.h" #include "%(visit)s.h" +#include "%(prefix)sqapi-features.h" ''', - visit=visit)) + visit=visit, prefix=self._prefix)) self._genh.preamble_add(mcgen(''' #include "qapi/qapi-builtin-visit.h" #include "%(types)s.h"
Signature · 1 line
2.46.0
Re: [PATCH v2 4/4] qapi: expose all schema features to code
Quoted 53 lines · Daniel P. Berrangé
This replaces use of the constants from the QapiSpecialFeatures enum, with constants from the auto-generate QapiFeatures enum in
qapi-features.hThe 'deprecated' and 'unstable' features still have a little bit of special handling, being force defined to be the 1st + 2nd features in the enum, regardless of whether they're used in the schema. This retains compatibility with common code that references the features via the QapiSpecialFeatures constants.
Signed-off-by Daniel P. Berrangé <[email protected]>--- meson.build | 1 + scripts/qapi/commands.py | 1 + scripts/qapi/features.py | 62 ++++++++++++++++++++++++++++++++++++++++ scripts/qapi/gen.py | 4 +-- scripts/qapi/main.py | 2 ++ scripts/qapi/schema.py | 19 +++++++++++- scripts/qapi/types.py | 6 ++-- scripts/qapi/visit.py | 3 +- 8 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 scripts/qapi/features.pymeson.build +1
-0@@ -3332,6 +3332,7 @@ qapi_gen_depends = [ meson.current_source_dir() / 'scripts/qapi/__init__.py', meson.current_source_dir() / 'scripts/qapi/schema.py', meson.current_source_dir() / 'scripts/qapi/source.py', meson.current_source_dir() / 'scripts/qapi/types.py', + meson.current_source_dir() / 'scripts/qapi/features.py', meson.current_source_dir() / 'scripts/qapi/visit.py', meson.current_source_dir() / 'scripts/qapi-gen.py' ]scripts/qapi/commands.py +1
-0@@ -355,6 +355,7 @@ def visit_begin(self, schema: QAPISchema) -> None: #include "qemu/osdep.h" #include "%(prefix)sqapi-commands.h" #include "%(prefix)sqapi-init-commands.h" +#include "%(prefix)sqapi-features.h" void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds) {scripts/qapi/features.py new file +0
-0
scripts/qapi/features.py line 2
Quoted 2 lines
scripts/qapi/features.py new file +2
-0@@ -0,0 +1,62 @@ +""" +QAPI types generator
QAPI features generator
scripts/qapi/features.py line 10
Quoted 8 lines
scripts/qapi/features.py new file +8
-0+ +Copyright 2024 Red Hat + +This work is licensed under the terms of the GNU GPL, version 2. +# See the COPYING file in the top-level directory. +""" + +from typing import List, Optional
pylint gripes
scripts/qapi/features.py:10:0: W0611: Unused List imported from typing (unused- import)
scripts/qapi/features.py:10:0: W0611: Unused Optional imported from typing (unused-import)
scripts/qapi/features.py line 12
Quoted 2 lines
scripts/qapi/features.py new file +2
-0+ +from .common import c_enum_const, mcgen, c_name
scripts/qapi/features.py:12:0: W0611: Unused mcgen imported from common (unused-import)
scripts/qapi/features.py line 18
Quoted 6 lines
scripts/qapi/features.py new file +6
-0+from .gen import QAPISchemaMonolithicCVisitor +from .schema import ( + QAPISchema, + QAPISchemaFeature, +) +from .source import QAPISourceInfo
scripts/qapi/features.py:18:0: W0611: Unused QAPISourceInfo imported from source (unused-import)
scripts/qapi/features.py line 29
Quoted 11 lines
scripts/qapi/features.py new file +11
-0+ + +class QAPISchemaGenFeatureVisitor(QAPISchemaMonolithicCVisitor): + + def __init__(self, prefix: str): + super().__init__( + prefix, 'qapi-features', + ' * Schema-defined QAPI features', + __doc__) + + self.features = {}
mypy gripes
scripts/qapi/features.py:29: error: Need type annotation for "features" (hint: "features: Dict[<type>, <type>] = ...") [var-annotated]
Elsewhere, we avoid rummaging in QAPISchema's innards by defining suitable visit. If that's too much trouble for you now, I can take this as is an clean up on top.
scripts/qapi/features.py line 31
Quoted 2 lines
scripts/qapi/features.py new file +2
-0+ + def visit_begin(self, schema: QAPISchema):
mypy gripes
scripts/qapi/features.py:31: error: Function is missing a return type annotation [no-untyped-def]
scripts/qapi/features.py line 32
Quoted 1 line
scripts/qapi/features.py new file +1
-0+ self.features = schema._feature_dict
pylint gripes
scripts/qapi/features.py:32:24: W0212: Access to a protected member _feature_dict of a client class (protected-access)
scripts/qapi/features.py line 45
Quoted 13 lines
scripts/qapi/features.py new file +13
-0+ + def visit_end(self) -> None: + features = [ + self.features[f] + for f in QAPISchemaFeature.SPECIAL_NAMES + ] + + features.extend( + sorted( + filter(lambda f: not f.is_special(), + self.features.values()), + key=lambda f: f.name) + )
@features is schema._feature_dict.values() sorted by name in a certain way, namely first the .SPECIAL_NAMES in order, then all the others in alphabetical order.
Why you do this is not immediately obvious. I guess it's to make the generated enum a compatible extension of enum QapiSpecialFeature. That one exists for use by schema-independent support code such compat_policy_input_ok() and qobject_output_policy_skip().
I further guess you sort the non-special features just to make the generated code easier for humans to navigate.
Correct?
scripts/qapi/features.py line 51
Quoted 6 lines
scripts/qapi/features.py new file +6
-0+ + self._genh.add("typedef enum {\n") + for f in features: + self._genh.add(f" {c_enum_const('qapi_feature', f.name)}") + if f.name in QAPISchemaFeature.SPECIAL_NAMES: + self._genh.add(f" = {c_enum_const('qapi', f.name)},\n" )
pycodestyle gripes
scripts/qapi/features.py:51:71: E202 whitespace before ')'
scripts/qapi/features.py line 56
Quoted 5 lines
scripts/qapi/features.py new file +5
-0+ else: + self._genh.add(",\n") + + self._genh.add("} " + c_name('QapiFeature') + ";\n") +
pycodestyle gripes
scripts/qapi/features.py:57:1: E302 expected 2 blank lines, found 1
This part generates a C enum. It's similar to gen_enum() from types.py, except we work with a list of QAPISchemaFeature here, and a list of QAPISchemaEnumMember there.
To reuse gen_enum() here, we'd have to make up a member list, like we do in events.py for enum QAPIEvent.
Quoted 59 lines
scripts/qapi/features.py new file +6
-0+def gen_features(schema: QAPISchema, + output_dir: str, + prefix: str) -> None: + vis = QAPISchemaGenFeatureVisitor(prefix) + schema.visit(vis) + vis.write(output_dir)scripts/qapi/gen.py +2
-2@@ -42,8 +42,8 @@ def gen_features(features: Sequence[QAPISchemaFeature]) -> str: - features = [f"1u << {c_enum_const('qapi', feat.name)}" - for feat in features if feat.is_special()] + features = [f"1u << {c_enum_const('qapi_feature', feat.name)}" + for feat in features] return ' | '.join(features) or '0'scripts/qapi/main.py +2
-0@@ -18,6 +18,7 @@ from .introspect import gen_introspect from .schema import QAPISchema from .types import gen_types +from .features import gen_features from .visit import gen_visit@@ -49,6 +50,7 @@ def generate(schema_file: str, schema = QAPISchema(schema_file) gen_types(schema, output_dir, prefix, builtins) + gen_features(schema, output_dir, prefix) gen_visit(schema, output_dir, prefix, builtins) gen_commands(schema, output_dir, prefix, gen_tracing) gen_events(schema, output_dir, prefix)scripts/qapi/schema.py +4
-1@@ -933,8 +933,11 @@ def connect_doc(self, doc: Optional[QAPIDoc]) -> None: class QAPISchemaFeature(QAPISchemaMember): role = 'feature' + # Features which are standardized across all schemas + SPECIAL_NAMES = ['deprecated', 'unstable'] + def is_special(self) -> bool: - return self.name in ('deprecated', 'unstable') + return self.name in QAPISchemaFeature.SPECIAL_NAMES class QAPISchemaObjectTypeMember(QAPISchemaMember):
scripts/qapi/schema.py def __init__(self, fname: str): · line 1147
Quoted 7 lines
scripts/qapi/schema.py +4
-0@@ -1138,6 +1141,11 @@ def __init__(self, fname: str): self._entity_list: List[QAPISchemaEntity] = [] self._entity_dict: Dict[str, QAPISchemaDefinition] = {} self._module_dict: Dict[str, QAPISchemaModule] = OrderedDict() + self._feature_dict: Dict[str, QAPISchemaFeature] = {} + + for f in QAPISchemaFeature.SPECIAL_NAMES: + self._feature_dict[f] = QAPISchemaFeature(f, "special feature")
mypy gripes
scripts/qapi/schema.py:1147: error: Argument 2 to "QAPISchemaFeature" has incompatible type "str"; expected "Optional[QAPISourceInfo]" [arg-type]
We commonly use None as info value for built-in stuff, and that's why it's Optional[QAPISourceInfo], not just QAPISourceInfo.
But do we really need to make up some QAPISchemaFeature? Hmm. The appended patch dumbs down ._feature_dict to a set.
Quoted 5 lines
scripts/qapi/schema.py +1
-0+ self._schema_dir = os.path.dirname(fname) self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME) self._make_module(fname)
scripts/qapi/schema.py def _make_features( · line 1274
Quoted 9 lines
scripts/qapi/schema.py +6
-0@@ -1258,6 +1266,15 @@ def _make_features( ) -> List[QAPISchemaFeature]: if features is None: return [] + + for f in features: + feat = QAPISchemaFeature(f['name'], info) + if feat.name not in self._feature_dict: + if len(self._feature_dict) == 64: + raise Exception("Maximum of 64 schema features is permitted")
The limit is an implementation restriction. Okay, we can lift it when it bites us.
However, the reporting is less than nice:
$ python scripts/qapi-gen.py -o $$ tests/qapi-schema/features-too-many.json
Traceback (most recent call last):
File "/work/armbru/qemu/scripts/qapi-gen.py", line 19, in <module>
sys.exit(main.main())
^^^^^^^^^^^
File "/work/armbru/qemu/scripts/qapi/main.py", line 96, in main
generate(args.schema,
File "/work/armbru/qemu/scripts/qapi/main.py", line 51, in generate
schema = QAPISchema(schema_file)
^^^^^^^^^^^^^^^^^^^^^^^
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1155, in __init__
self._def_exprs(exprs)
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1482, in _def_exprs
self._def_struct_type(expr)
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1377, in _def_struct_type
features = self._make_features(expr.get('features'), info)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1274, in _make_features
raise Exception("Maximum of 64 schema features is permitted")
Exception: Maximum of 64 schema features is permittedQuoted 11 lines
scripts/qapi/schema.py +3
-0+ + self._feature_dict[feat.name] = feat + return [QAPISchemaFeature(f['name'], info, QAPISchemaIfCond(f.get('if'))) for f in features]scripts/qapi/types.py +0
-0
scripts/qapi/types.py def _begin_user_module(self, name: str) -> None: · line 313
Quoted 7 lines
scripts/qapi/types.py +2
-1@@ -308,11 +308,13 @@ def _begin_user_module(self, name: str) -> None: #include "qapi/dealloc-visitor.h" #include "%(types)s.h" #include "%(visit)s.h" +#include "%(prefix)sqapi-features.h" ''', - types=types, visit=visit)) + types=types, visit=visit, prefix=self._prefix))
Long line, easy to break:
types=types, visit=visit, prefix=self._prefix))
Quoted 13 lines
scripts/qapi/types.py +2
-1self._genh.preamble_add(mcgen(''' #include "qapi/qapi-builtin-types.h" -''')) +''', + prefix=self._prefix)) def visit_begin(self, schema: QAPISchema) -> None: # gen_object() is recursive, ensure it doesn't visit the empty typescripts/qapi/visit.py +0
-0
scripts/qapi/visit.py def _begin_user_module(self, name: str) -> None: · line 368
Quoted 10 lines
scripts/qapi/visit.py +2
-1@@ -360,8 +360,9 @@ def _begin_user_module(self, name: str) -> None: #include "qemu/osdep.h" #include "qapi/error.h" #include "%(visit)s.h" +#include "%(prefix)sqapi-features.h" ''', - visit=visit)) + visit=visit, prefix=self._prefix)) self._genh.preamble_add(mcgen(''' #include "qapi/qapi-builtin-visit.h" #include "%(types)s.h"
scripts/qapi/features.py +10 -14
@@ -7,7 +7,7 @@ # See the COPYING file in the top-level directory. """ -from typing import List, Optional +from typing import List, Optional, Set from .common import c_enum_const, mcgen, c_name from .gen import QAPISchemaMonolithicCVisitor
@@ -26,29 +26,25 @@ def __init__(self, prefix: str): ' * Schema-defined QAPI features', __doc__) - self.features = {} + self.features: Set['str'] - def visit_begin(self, schema: QAPISchema): - self.features = schema._feature_dict + def visit_begin(self, schema: QAPISchema) -> None: + self.features = schema._features def visit_end(self) -> None: - features = [ - self.features[f] - for f in QAPISchemaFeature.SPECIAL_NAMES - ] + features = QAPISchemaFeature.SPECIAL_NAMES.copy() features.extend( sorted( - filter(lambda f: not f.is_special(), - self.features.values()), - key=lambda f: f.name) + filter(lambda f: f not in QAPISchemaFeature.SPECIAL_NAMES, + self.features)) ) self._genh.add("typedef enum {\n") for f in features: - self._genh.add(f" {c_enum_const('qapi_feature', f.name)}") - if f.name in QAPISchemaFeature.SPECIAL_NAMES: - self._genh.add(f" = {c_enum_const('qapi', f.name)},\n" ) + self._genh.add(f" {c_enum_const('qapi_feature', f)}") + if f in QAPISchemaFeature.SPECIAL_NAMES: + self._genh.add(f" = {c_enum_const('qapi', f)},\n" ) else: self._genh.add(",\n")
scripts/qapi/gen.py +2 -2
@@ -42,9 +42,9 @@ def gen_features(features: Sequence[QAPISchemaFeature]) -> str: - features = [f"1u << {c_enum_const('qapi_feature', feat.name)}" + feats = [f"1u << {c_enum_const('qapi_feature', feat.name)}" for feat in features] - return ' | '.join(features) or '0' + return ' | '.join(feats) or '0' class QAPIGen:
scripts/qapi/schema.py +5 -7
@@ -28,6 +28,7 @@ Dict, List, Optional, + Set, Union, cast, )
@@ -1141,10 +1142,7 @@ def __init__(self, fname: str): self._entity_list: List[QAPISchemaEntity] = [] self._entity_dict: Dict[str, QAPISchemaDefinition] = {} self._module_dict: Dict[str, QAPISchemaModule] = OrderedDict() - self._feature_dict: Dict[str, QAPISchemaFeature] = {} - - for f in QAPISchemaFeature.SPECIAL_NAMES: - self._feature_dict[f] = QAPISchemaFeature(f, "special feature") + self._features: Set[str] = set(QAPISchemaFeature.SPECIAL_NAMES) self._schema_dir = os.path.dirname(fname) self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME)
@@ -1269,11 +1267,11 @@ def _make_features( for f in features: feat = QAPISchemaFeature(f['name'], info) - if feat.name not in self._feature_dict: - if len(self._feature_dict) == 64: + if feat.name not in self._features: + if len(self._features) == 64: raise Exception("Maximum of 64 schema features is permitted") - self._feature_dict[feat.name] = feat + self._features.add(feat.name) return [QAPISchemaFeature(f['name'], info, QAPISchemaIfCond(f.get('if')))
Re: [PATCH v2 4/4] qapi: expose all schema features to code
Quoted 60 lines · Markus Armbruster
Quoted 53 lines · Daniel P. Berrangé
This replaces use of the constants from the QapiSpecialFeatures enum, with constants from the auto-generate QapiFeatures enum in
qapi-features.hThe 'deprecated' and 'unstable' features still have a little bit of special handling, being force defined to be the 1st + 2nd features in the enum, regardless of whether they're used in the schema. This retains compatibility with common code that references the features via the QapiSpecialFeatures constants.
Signed-off-by Daniel P. Berrangé <[email protected]>--- meson.build | 1 + scripts/qapi/commands.py | 1 + scripts/qapi/features.py | 62 ++++++++++++++++++++++++++++++++++++++++ scripts/qapi/gen.py | 4 +-- scripts/qapi/main.py | 2 ++ scripts/qapi/schema.py | 19 +++++++++++- scripts/qapi/types.py | 6 ++-- scripts/qapi/visit.py | 3 +- 8 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 scripts/qapi/features.pymeson.build +1
-0@@ -3332,6 +3332,7 @@ qapi_gen_depends = [ meson.current_source_dir() / 'scripts/qapi/__init__.py', meson.current_source_dir() / 'scripts/qapi/schema.py', meson.current_source_dir() / 'scripts/qapi/source.py', meson.current_source_dir() / 'scripts/qapi/types.py', + meson.current_source_dir() / 'scripts/qapi/features.py', meson.current_source_dir() / 'scripts/qapi/visit.py', meson.current_source_dir() / 'scripts/qapi-gen.py' ]scripts/qapi/commands.py +1
-0@@ -355,6 +355,7 @@ def visit_begin(self, schema: QAPISchema) -> None: #include "qemu/osdep.h" #include "%(prefix)sqapi-commands.h" #include "%(prefix)sqapi-init-commands.h" +#include "%(prefix)sqapi-features.h" void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds) {scripts/qapi/features.py new file +0
-0scripts/qapi/features.py line 2
Quoted 2 lines
scripts/qapi/features.py new file +2
-0@@ -0,0 +1,62 @@ +""" +QAPI types generatorQAPI features generator
Quoted 10 lines
scripts/qapi/features.py line 10
Quoted 8 lines
scripts/qapi/features.py new file +8
-0+ +Copyright 2024 Red Hat + +This work is licensed under the terms of the GNU GPL, version 2. +# See the COPYING file in the top-level directory. +""" + +from typing import List, Optionalpylint gripes
Sigh, I really wish we had pylint/mypy/pycodestyle being run as part of 'make check' by default. I don't like making the mistake of sending patches which fail extra non-default checks maintainers need compliance with.
Quoted 70 lines
scripts/qapi/features.py:10:0: W0611: Unused List imported from typing (unused- import)
scripts/qapi/features.py:10:0: W0611: Unused Optional imported from typing (unused-import)scripts/qapi/features.py line 12
Quoted 2 lines
scripts/qapi/features.py new file +2
-0+ +from .common import c_enum_const, mcgen, c_name
scripts/qapi/features.py:12:0: W0611: Unused mcgen imported from common (unused-import)scripts/qapi/features.py line 18
Quoted 6 lines
scripts/qapi/features.py new file +6
-0+from .gen import QAPISchemaMonolithicCVisitor +from .schema import ( + QAPISchema, + QAPISchemaFeature, +) +from .source import QAPISourceInfo
scripts/qapi/features.py:18:0: W0611: Unused QAPISourceInfo imported from source (unused-import)scripts/qapi/features.py line 29
Quoted 11 lines
scripts/qapi/features.py new file +11
-0+ + +class QAPISchemaGenFeatureVisitor(QAPISchemaMonolithicCVisitor): + + def __init__(self, prefix: str): + super().__init__( + prefix, 'qapi-features', + ' * Schema-defined QAPI features', + __doc__) + + self.features = {}mypy gripes
scripts/qapi/features.py:29: error: Need type annotation for "features" (hint: "features: Dict[<type>, <type>] = ...") [var-annotated]Elsewhere, we avoid rummaging in QAPISchema's innards by defining suitable visit. If that's too much trouble for you now, I can take this as is an clean up on top.
scripts/qapi/features.py line 31
Quoted 2 lines
scripts/qapi/features.py new file +2
-0+ + def visit_begin(self, schema: QAPISchema):mypy gripes
scripts/qapi/features.py:31: error: Function is missing a return type annotation [no-untyped-def]scripts/qapi/features.py line 32
Quoted 1 line
scripts/qapi/features.py new file +1
-0+ self.features = schema._feature_dictpylint gripes
scripts/qapi/features.py:32:24: W0212: Access to a protected member_feature_dictof a client class (protected-access)scripts/qapi/features.py line 45
Quoted 13 lines
scripts/qapi/features.py new file +13
-0+ + def visit_end(self) -> None: + features = [ + self.features[f] + for f in QAPISchemaFeature.SPECIAL_NAMES + ] + + features.extend( + sorted( + filter(lambda f: not f.is_special(), + self.features.values()), + key=lambda f: f.name) + )@features is
schema._feature_dict.values()sorted by name in a certain way, namely first the .SPECIAL_NAMES in order, then all the others in alphabetical order.
Quoted 4 lines
Why you do this is not immediately obvious. I guess it's to make the generated enum a compatible extension of enum QapiSpecialFeature. That one exists for use by schema-independent support code such
compat_policy_input_ok()andqobject_output_policy_skip().
Yes, I wanted the overlapping enums vaules to match.
Quoted 4 lines
I further guess you sort the non-special features just to make the generated code easier for humans to navigate.
Correct?
The remaining sort was just to give a predictable stable output, should QAPI usage of features be reordered.
Quoted 19 lines
scripts/qapi/features.py line 51
Quoted 6 lines
scripts/qapi/features.py new file +6
-0+ + self._genh.add("typedef enum {\n") + for f in features: + self._genh.add(f" {c_enum_const('qapi_feature', f.name)}") + if f.name in QAPISchemaFeature.SPECIAL_NAMES: + self._genh.add(f" = {c_enum_const('qapi', f.name)},\n" )pycodestyle gripes
scripts/qapi/features.py:51:71: E202 whitespace before ')'scripts/qapi/features.py line 56
Quoted 5 lines
scripts/qapi/features.py new file +5
-0+ else: + self._genh.add(",\n") + + self._genh.add("} " + c_name('QapiFeature') + ";\n") +pycodestyle gripes
Quoted 8 lines
scripts/qapi/features.py:57:1: E302 expected 2 blank lines, found 1This part generates a C enum. It's similar to
gen_enum()fromtypes.py, except we work with a list of QAPISchemaFeature here, and a list of QAPISchemaEnumMember there.To reuse
gen_enum()here, we'd have to make up a member list, like we do inevents.pyfor enum QAPIEvent.
I'll have a look at that.
Quoted 28 lines
Quoted 18 lines
scripts/qapi/schema.py +4
-1@@ -933,8 +933,11 @@ def connect_doc(self, doc: Optional[QAPIDoc]) -> None: class QAPISchemaFeature(QAPISchemaMember): role = 'feature' + # Features which are standardized across all schemas + SPECIAL_NAMES = ['deprecated', 'unstable'] + def is_special(self) -> bool: - return self.name in ('deprecated', 'unstable') + return self.name in QAPISchemaFeature.SPECIAL_NAMES class QAPISchemaObjectTypeMember(QAPISchemaMember):scripts/qapi/schema.py def __init__(self, fname: str): · line 1147
Quoted 7 lines
scripts/qapi/schema.py +4
-0@@ -1138,6 +1141,11 @@ def __init__(self, fname: str): self._entity_list: List[QAPISchemaEntity] = [] self._entity_dict: Dict[str, QAPISchemaDefinition] = {} self._module_dict: Dict[str, QAPISchemaModule] = OrderedDict() + self._feature_dict: Dict[str, QAPISchemaFeature] = {} + + for f in QAPISchemaFeature.SPECIAL_NAMES: + self._feature_dict[f] = QAPISchemaFeature(f, "special feature")mypy gripes
Quoted 4 lines
scripts/qapi/schema.py:1147: error: Argument 2 to "QAPISchemaFeature" has incompatible type "str"; expected "Optional[QAPISourceInfo]" [arg-type]We commonly use None as info value for built-in stuff, and that's why it's Optional[QAPISourceInfo], not just QAPISourceInfo.
Yeah, not sure what I was thinking here, looking again I should have passed "None"
Quoted 2 lines
But do we really need to make up some QAPISchemaFeature? Hmm. The appended patch dumbs down ._feature_dict to a set.
I was following the same pattern as self._entity_dict and self._module_dict, rather than dumbing down to the bare minimum needed by my current use case. I don't mind which strategy we take.
Quoted 33 lines
Quoted 6 lines
scripts/qapi/schema.py +1
-0+ self._schema_dir = os.path.dirname(fname) self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME) self._make_module(fname)scripts/qapi/schema.py def _make_features( · line 1274
Quoted 9 lines
scripts/qapi/schema.py +6
-0@@ -1258,6 +1266,15 @@ def _make_features( ) -> List[QAPISchemaFeature]: if features is None: return [] + + for f in features: + feat = QAPISchemaFeature(f['name'], info) + if feat.name not in self._feature_dict: + if len(self._feature_dict) == 64: + raise Exception("Maximum of 64 schema features is permitted")The limit is an implementation restriction. Okay, we can lift it when it bites us.
However, the reporting is less than nice:
$ python scripts/qapi-gen.py -o $$ tests/qapi-schema/features-too-many.json Traceback (most recent call last): File "/work/armbru/qemu/scripts/qapi-gen.py", line 19, in <module> sys.exit(main.main()) ^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/main.py", line 96, in main generate(args.schema, File "/work/armbru/qemu/scripts/qapi/main.py", line 51, in generate schema = QAPISchema(schema_file) ^^^^^^^^^^^^^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/schema.py", line 1155, in __init__ self._def_exprs(exprs)
Quoted 8 lines
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1482, in _def_exprs
self._def_struct_type(expr)
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1377, in _def_struct_type
features = self._make_features(expr.get('features'), info)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1274, in _make_features
raise Exception("Maximum of 64 schema features is permitted")
Exception: Maximum of 64 schema features is permittedIs there any better way to approach this error reporting ?
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v2 4/4] qapi: expose all schema features to code
Quoted 72 lines · Daniel P. Berrangé
Quoted 60 lines · Markus Armbruster
Quoted 53 lines · Daniel P. Berrangé
This replaces use of the constants from the QapiSpecialFeatures enum, with constants from the auto-generate QapiFeatures enum in
qapi-features.hThe 'deprecated' and 'unstable' features still have a little bit of special handling, being force defined to be the 1st + 2nd features in the enum, regardless of whether they're used in the schema. This retains compatibility with common code that references the features via the QapiSpecialFeatures constants.
Signed-off-by Daniel P. Berrangé <[email protected]>--- meson.build | 1 + scripts/qapi/commands.py | 1 + scripts/qapi/features.py | 62 ++++++++++++++++++++++++++++++++++++++++ scripts/qapi/gen.py | 4 +-- scripts/qapi/main.py | 2 ++ scripts/qapi/schema.py | 19 +++++++++++- scripts/qapi/types.py | 6 ++-- scripts/qapi/visit.py | 3 +- 8 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 scripts/qapi/features.pymeson.build +1
-0@@ -3332,6 +3332,7 @@ qapi_gen_depends = [ meson.current_source_dir() / 'scripts/qapi/__init__.py', meson.current_source_dir() / 'scripts/qapi/schema.py', meson.current_source_dir() / 'scripts/qapi/source.py', meson.current_source_dir() / 'scripts/qapi/types.py', + meson.current_source_dir() / 'scripts/qapi/features.py', meson.current_source_dir() / 'scripts/qapi/visit.py', meson.current_source_dir() / 'scripts/qapi-gen.py' ]scripts/qapi/commands.py +1
-0@@ -355,6 +355,7 @@ def visit_begin(self, schema: QAPISchema) -> None: #include "qemu/osdep.h" #include "%(prefix)sqapi-commands.h" #include "%(prefix)sqapi-init-commands.h" +#include "%(prefix)sqapi-features.h" void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds) {scripts/qapi/features.py new file +0
-0scripts/qapi/features.py line 2
Quoted 2 lines
scripts/qapi/features.py new file +2
-0@@ -0,0 +1,62 @@ +""" +QAPI types generatorQAPI features generator
Quoted 10 lines
scripts/qapi/features.py line 10
Quoted 8 lines
scripts/qapi/features.py new file +8
-0+ +Copyright 2024 Red Hat + +This work is licensed under the terms of the GNU GPL, version 2. +# See the COPYING file in the top-level directory. +""" + +from typing import List, Optionalpylint gripes
Quoted 4 lines
Sigh, I really wish we had pylint/mypy/pycodestyle being run as part of 'make check' by default. I don't like making the mistake of sending patches which fail extra non-default checks maintainers need compliance with.
We've made some progress towards running these checkers, but we're not there, yet.
Quoted 69 lines
Quoted 69 lines
scripts/qapi/features.py:10:0: W0611: Unused List imported from typing (unused- import)
scripts/qapi/features.py:10:0: W0611: Unused Optional imported from typing (unused-import)scripts/qapi/features.py line 12
Quoted 2 lines
scripts/qapi/features.py new file +2
-0+ +from .common import c_enum_const, mcgen, c_name
scripts/qapi/features.py:12:0: W0611: Unused mcgen imported from common (unused-import)scripts/qapi/features.py line 18
Quoted 6 lines
scripts/qapi/features.py new file +6
-0+from .gen import QAPISchemaMonolithicCVisitor +from .schema import ( + QAPISchema, + QAPISchemaFeature, +) +from .source import QAPISourceInfo
scripts/qapi/features.py:18:0: W0611: Unused QAPISourceInfo imported from source (unused-import)scripts/qapi/features.py line 29
Quoted 11 lines
scripts/qapi/features.py new file +11
-0+ + +class QAPISchemaGenFeatureVisitor(QAPISchemaMonolithicCVisitor): + + def __init__(self, prefix: str): + super().__init__( + prefix, 'qapi-features', + ' * Schema-defined QAPI features', + __doc__) + + self.features = {}mypy gripes
scripts/qapi/features.py:29: error: Need type annotation for "features" (hint: "features: Dict[<type>, <type>] = ...") [var-annotated]Elsewhere, we avoid rummaging in QAPISchema's innards by defining suitable visit. If that's too much trouble for you now, I can take this as is an clean up on top.
scripts/qapi/features.py line 31
Quoted 2 lines
scripts/qapi/features.py new file +2
-0+ + def visit_begin(self, schema: QAPISchema):mypy gripes
scripts/qapi/features.py:31: error: Function is missing a return type annotation [no-untyped-def]scripts/qapi/features.py line 32
Quoted 1 line
scripts/qapi/features.py new file +1
-0+ self.features = schema._feature_dictpylint gripes
scripts/qapi/features.py:32:24: W0212: Access to a protected member_feature_dictof a client class (protected-access)scripts/qapi/features.py line 45
Quoted 13 lines
scripts/qapi/features.py new file +13
-0+ + def visit_end(self) -> None: + features = [ + self.features[f] + for f in QAPISchemaFeature.SPECIAL_NAMES + ] + + features.extend( + sorted( + filter(lambda f: not f.is_special(), + self.features.values()), + key=lambda f: f.name) + )@features is
schema._feature_dict.values()sorted by name in a certain way, namely first the .SPECIAL_NAMES in order, then all the others in alphabetical order.
Quoted 6 lines
Quoted 4 lines
Why you do this is not immediately obvious. I guess it's to make the generated enum a compatible extension of enum QapiSpecialFeature. That one exists for use by schema-independent support code such
compat_policy_input_ok()andqobject_output_policy_skip().Yes, I wanted the overlapping enums vaules to match.
Needs a comment.
Quoted 7 lines
Quoted 4 lines
I further guess you sort the non-special features just to make the generated code easier for humans to navigate.
Correct?
The remaining sort was just to give a predictable stable output, should QAPI usage of features be reordered.
We don't do that for enum QAPIEvent, and it hasn't inconvenienced us as far as I can tell. No big deal, I just like consistency.
Quoted 21 lines
Quoted 21 lines
scripts/qapi/features.py line 51
Quoted 6 lines
scripts/qapi/features.py new file +6
-0+ + self._genh.add("typedef enum {\n") + for f in features: + self._genh.add(f" {c_enum_const('qapi_feature', f.name)}") + if f.name in QAPISchemaFeature.SPECIAL_NAMES: + self._genh.add(f" = {c_enum_const('qapi', f.name)},\n" )pycodestyle gripes
scripts/qapi/features.py:51:71: E202 whitespace before ')'scripts/qapi/features.py line 56
Quoted 5 lines
scripts/qapi/features.py new file +5
-0+ else: + self._genh.add(",\n") + + self._genh.add("} " + c_name('QapiFeature') + ";\n") +pycodestyle gripes
scripts/qapi/features.py:57:1: E302 expected 2 blank lines, found 1
Quoted 8 lines
Quoted 6 lines
This part generates a C enum. It's similar to
gen_enum()fromtypes.py, except we work with a list of QAPISchemaFeature here, and a list of QAPISchemaEnumMember there.To reuse
gen_enum()here, we'd have to make up a member list, like we do inevents.pyfor enum QAPIEvent.I'll have a look at that.
Reuse it only if it's easy for you. We can always improve on top.
Quoted 28 lines
Quoted 28 lines
Quoted 18 lines
scripts/qapi/schema.py +4
-1@@ -933,8 +933,11 @@ def connect_doc(self, doc: Optional[QAPIDoc]) -> None: class QAPISchemaFeature(QAPISchemaMember): role = 'feature' + # Features which are standardized across all schemas + SPECIAL_NAMES = ['deprecated', 'unstable'] + def is_special(self) -> bool: - return self.name in ('deprecated', 'unstable') + return self.name in QAPISchemaFeature.SPECIAL_NAMES class QAPISchemaObjectTypeMember(QAPISchemaMember):scripts/qapi/schema.py def __init__(self, fname: str): · line 1147
Quoted 7 lines
scripts/qapi/schema.py +4
-0@@ -1138,6 +1141,11 @@ def __init__(self, fname: str): self._entity_list: List[QAPISchemaEntity] = [] self._entity_dict: Dict[str, QAPISchemaDefinition] = {} self._module_dict: Dict[str, QAPISchemaModule] = OrderedDict() + self._feature_dict: Dict[str, QAPISchemaFeature] = {} + + for f in QAPISchemaFeature.SPECIAL_NAMES: + self._feature_dict[f] = QAPISchemaFeature(f, "special feature")mypy gripes
Quoted 10 lines
Quoted 4 lines
scripts/qapi/schema.py:1147: error: Argument 2 to "QAPISchemaFeature" has incompatible type "str"; expected "Optional[QAPISourceInfo]" [arg-type]We commonly use None as info value for built-in stuff, and that's why it's Optional[QAPISourceInfo], not just QAPISourceInfo.
Yeah, not sure what I was thinking here, looking again I should have passed "None"
Quoted 2 lines
But do we really need to make up some QAPISchemaFeature? Hmm. The appended patch dumbs down ._feature_dict to a set.
See below for a possible reason to keep .feature_dict.
Quoted 4 lines
I was following the same pattern as self._entity_dict and self._module_dict, rather than dumbing down to the bare minimum needed by my current use case. I don't mind which strategy we take.
.entity_dict maps the name to the one entity. Likewise .module_dict. .feature_dict, however, maps it to the first of possibly many. That's not wrong, just peculiar and possibly less than obvious to readers who aren't familiar with how we represent features internally. Worth a comment?
Quoted 41 lines
Quoted 32 lines
Quoted 5 lines
scripts/qapi/schema.py +1
-0+ self._schema_dir = os.path.dirname(fname) self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME) self._make_module(fname)scripts/qapi/schema.py def _make_features( · line 1274
Quoted 9 lines
scripts/qapi/schema.py +6
-0@@ -1258,6 +1266,15 @@ def _make_features( ) -> List[QAPISchemaFeature]: if features is None: return [] + + for f in features: + feat = QAPISchemaFeature(f['name'], info) + if feat.name not in self._feature_dict: + if len(self._feature_dict) == 64: + raise Exception("Maximum of 64 schema features is permitted")The limit is an implementation restriction. Okay, we can lift it when it bites us.
However, the reporting is less than nice:
$ python scripts/qapi-gen.py -o $$ tests/qapi-schema/features-too-many.json Traceback (most recent call last): File "/work/armbru/qemu/scripts/qapi-gen.py", line 19, in <module> sys.exit(main.main()) ^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/main.py", line 96, in main generate(args.schema, File "/work/armbru/qemu/scripts/qapi/main.py", line 51, in generate schema = QAPISchema(schema_file) ^^^^^^^^^^^^^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/schema.py", line 1155, in __init__ self._def_exprs(exprs)Quoted 8 lines
File "/work/armbru/qemu/scripts/qapi/schema.py", line 1482, in _def_exprs self._def_struct_type(expr) File "/work/armbru/qemu/scripts/qapi/schema.py", line 1377, in _def_struct_type features = self._make_features(expr.get('features'), info) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/schema.py", line 1274, in _make_features raise Exception("Maximum of 64 schema features is permitted") Exception: Maximum of 64 schema features is permitted
Quoted 1 line
Is there any better way to approach this error reporting ?
Raise QAPISemError in .check().
Hmm, then you need a QAPISourceInfo to pass. .feature_dict will give you one: the .info of the feature added last.
Re: [PATCH v2 4/4] qapi: expose all schema features to code
Quoted 31 lines · Markus Armbruster
Quoted 29 lines · Daniel P. Berrangé
Quoted 28 lines · Markus Armbruster
Quoted 11 lines · Daniel P. Berrangé
This replaces use of the constants from the QapiSpecialFeatures enum, with constants from the auto-generate QapiFeatures enum in
qapi-features.hThe 'deprecated' and 'unstable' features still have a little bit of special handling, being force defined to be the 1st + 2nd features in the enum, regardless of whether they're used in the schema. This retains compatibility with common code that references the features via the QapiSpecialFeatures constants.
Signed-off-by Daniel P. Berrangé <[email protected]>Quoted 11 lines
--- meson.build | 1 + scripts/qapi/commands.py | 1 + scripts/qapi/features.py | 62 ++++++++++++++++++++++++++++++++++++++++ scripts/qapi/gen.py | 4 +-- scripts/qapi/main.py | 2 ++ scripts/qapi/schema.py | 19 +++++++++++- scripts/qapi/types.py | 6 ++-- scripts/qapi/visit.py | 3 +- 8 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 scripts/qapi/features.pyI further guess you sort the non-special features just to make the generated code easier for humans to navigate.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
Correct?
The remaining sort was just to give a predictable stable output, should QAPI usage of features be reordered.
We don't do that for enum QAPIEvent, and it hasn't inconvenienced us as far as I can tell. No big deal, I just like consistency.
Sure, I'll removethe sorting
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
pycodestyle gripes
scripts/qapi/features.py:57:1: E302 expected 2 blank lines, found 1This part generates a C enum. It's similar to
gen_enum()fromtypes.py, except we work with a list of QAPISchemaFeature here, and a list of QAPISchemaEnumMember there.
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
To reuse
gen_enum()here, we'd have to make up a member list, like we do inevents.pyfor enum QAPIEvent.I'll have a look at that.
Reuse it only if it's easy for you. We can always improve on top.
Using gen_enum will create the enum <-> string conversion table,
and I'm not sure we need/want that for the special features ?
Quoted 16 lines
Quoted 8 lines
Quoted 2 lines
We commonly use None as info value for built-in stuff, and that's why it's Optional[QAPISourceInfo], not just QAPISourceInfo.
Yeah, not sure what I was thinking here, looking again I should have passed "None"
Quoted 2 lines
But do we really need to make up some QAPISchemaFeature? Hmm. The appended patch dumbs down ._feature_dict to a set.
See below for a possible reason to keep .feature_dict.
Quoted 4 lines
I was following the same pattern as self._entity_dict and self._module_dict, rather than dumbing down to the bare minimum needed by my current use case. I don't mind which strategy we take.
Quoted 5 lines
.entity_dict maps the name to the one entity. Likewise .module_dict. .feature_dict, however, maps it to the first of possibly many. That's not wrong, just peculiar and possibly less than obvious to readers who aren't familiar with how we represent features internally. Worth a comment?
I'll comment it.
Quoted 23 lines
Quoted 23 lines
Quoted 22 lines
However, the reporting is less than nice:
$ python scripts/qapi-gen.py -o $$ tests/qapi-schema/features-too-many.json Traceback (most recent call last): File "/work/armbru/qemu/scripts/qapi-gen.py", line 19, in <module> sys.exit(main.main()) ^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/main.py", line 96, in main generate(args.schema, File "/work/armbru/qemu/scripts/qapi/main.py", line 51, in generate schema = QAPISchema(schema_file) ^^^^^^^^^^^^^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/schema.py", line 1155, in __init__ self._def_exprs(exprs) File "/work/armbru/qemu/scripts/qapi/schema.py", line 1482, in _def_exprs self._def_struct_type(expr) File "/work/armbru/qemu/scripts/qapi/schema.py", line 1377, in _def_struct_type features = self._make_features(expr.get('features'), info) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/work/armbru/qemu/scripts/qapi/schema.py", line 1274, in _make_features raise Exception("Maximum of 64 schema features is permitted") Exception: Maximum of 64 schema features is permitted
Quoted 6 lines
Quoted 1 line
Is there any better way to approach this error reporting ?
Raise QAPISemError in .check().
Hmm, then you need a QAPISourceInfo to pass. .feature_dict will give you one: the .info of the feature added last.
This also points out that I failed to add a test case for this "too many features' scenario, which I'll fix too.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|