qapi: static typing conversion, pt1.5
PATCH v2 12/12 qapi: enable strict-optional checks
In reply to John SnowIn the modules that we are checking so far, we can be stricter about the difference between Optional[T] and T types. Enable that check.
Enabling it now will assist review on further typing and cleanup work.
--- scripts/qapi/mypy.ini | 1 - 1 file changed, 1 deletion(-)
scripts/qapi/mypy.ini +0 -1
@@ -1,6 +1,5 @@ [mypy] strict = True -strict_optional = False disallow_untyped_calls = False python_version = 3.6
Signature · 1 line
2.26.2
PATCH v2 1/12 qapi/commands: assert arg_type is not None
In reply to John Snowwhen boxed is true, expr.py asserts that we must have arguments. Ultimately, this should mean that if boxed is True, that arg_type should be defined. Mypy cannot infer this, and does not support 'stateful' type inference, e.g.:
```
if x:
assert y is not None
...
if x:
y.etc()
```does not work, because mypy does not statefully remember the conditional assertion in the second block. Help mypy out by creating a new local that it can track more easily.
--- scripts/qapi/commands.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
scripts/qapi/commands.py +6 -3
@@ -126,6 +126,9 @@ def gen_marshal(name: str, boxed: bool, ret_type: Optional[QAPISchemaType]) -> str: have_args = boxed or (arg_type and not arg_type.is_empty()) + if have_args: + assert arg_type is not None + arg_type_c_name = arg_type.c_name() ret = mcgen('''
@@ -147,7 +150,7 @@ def gen_marshal(name: str, ret += mcgen(''' %(c_name)s arg = {0}; ''', - c_name=arg_type.c_name()) + c_name=arg_type_c_name) ret += mcgen('''
@@ -163,7 +166,7 @@ def gen_marshal(name: str, ok = visit_check_struct(v, errp); } ''', - c_arg_type=arg_type.c_name()) + c_arg_type=arg_type_c_name) else: ret += mcgen(''' ok = visit_check_struct(v, errp);
@@ -193,7 +196,7 @@ def gen_marshal(name: str, ret += mcgen(''' visit_type_%(c_arg_type)s_members(v, &arg, NULL); ''', - c_arg_type=arg_type.c_name()) + c_arg_type=arg_type_c_name) ret += mcgen(''' visit_end_struct(v, NULL);
Signature · 1 line
2.26.2
PATCH v2 2/12 qapi/events: fix visit_event typing
In reply to John SnowActually, the arg_type can indeed be Optional.
--- scripts/qapi/events.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
scripts/qapi/events.py +7 -5
@@ -12,7 +12,7 @@ See the COPYING file in the top-level directory. """ -from typing import List +from typing import List, Optional from .common import c_enum_const, c_name, mcgen from .gen import QAPISchemaModularCVisitor, build_params, ifcontext
@@ -27,7 +27,7 @@ def build_event_send_proto(name: str, - arg_type: QAPISchemaObjectType, + arg_type: Optional[QAPISchemaObjectType], boxed: bool) -> str: return 'void qapi_event_send_%(c_name)s(%(param)s)' % { 'c_name': c_name(name.lower()),
@@ -35,7 +35,7 @@ def build_event_send_proto(name: str, def gen_event_send_decl(name: str, - arg_type: QAPISchemaObjectType, + arg_type: Optional[QAPISchemaObjectType], boxed: bool) -> str: return mcgen('''
@@ -78,7 +78,7 @@ def gen_param_var(typ: QAPISchemaObjectType) -> str: def gen_event_send(name: str, - arg_type: QAPISchemaObjectType, + arg_type: Optional[QAPISchemaObjectType], boxed: bool, event_enum_name: str, event_emit: str) -> str:
@@ -99,6 +99,7 @@ def gen_event_send(name: str, proto=build_event_send_proto(name, arg_type, boxed)) if have_args: + assert arg_type is not None ret += mcgen(''' QObject *obj; Visitor *v;
@@ -114,6 +115,7 @@ def gen_event_send(name: str, name=name) if have_args: + assert arg_type is not None ret += mcgen(''' v = qobject_output_visitor_new(&obj); ''')
@@ -214,7 +216,7 @@ def visit_event(self, info: QAPISourceInfo, ifcond: List[str], features: List[QAPISchemaFeature], - arg_type: QAPISchemaObjectType, + arg_type: Optional[QAPISchemaObjectType], boxed: bool) -> None: with ifcontext(ifcond, self._genh, self._genc): self._genh.add(gen_event_send_decl(name, arg_type, boxed))
Signature · 1 line
2.26.2
PATCH v2 4/12 qapi/gen: assert that _start_if is not None in _wrap_ifcond
In reply to John SnowWe already assert this in end_if, but that's opaque to mypy. Do it in _wrap_ifcond instead. Same effect at runtime, but mypy can now infer the type in _wrap_ifcond's body.
--- scripts/qapi/gen.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/qapi/gen.py +1 -1
@@ -130,11 +130,11 @@ def start_if(self, ifcond: List[str]) -> None: self._start_if = (ifcond, self._body, self._preamble) def end_if(self) -> None: - assert self._start_if self._wrap_ifcond() self._start_if = None def _wrap_ifcond(self) -> None: + assert self._start_if self._body = _wrap_ifcond(self._start_if[0], self._start_if[1], self._body) self._preamble = _wrap_ifcond(self._start_if[0],
Signature · 1 line
2.26.2
PATCH v2 3/12 qapi/main: handle theoretical None-return from re.match()
In reply to John SnowMypy cannot understand that this match can never be None, so help it along.
--- scripts/qapi/main.py | 2 ++ 1 file changed, 2 insertions(+)
scripts/qapi/main.py +2 -0
@@ -23,6 +23,8 @@ def invalid_prefix_char(prefix: str) -> Optional[str]: match = re.match(r'([A-Za-z_.-][A-Za-z0-9_.-]*)?', prefix) + # match cannot be None, but mypy cannot infer that. + assert match is not None if match.end() != len(prefix): return prefix[match.end()] return None
Signature · 1 line
2.26.2
v2 cover qapi: static typing conversion, pt1.5
Hi, this patchset enables strict optional checking in mypy for everything we have typed so far.
In general, this patchset seeks to eliminate Optional[T] in favor of T wherever possible. Optional types used for object properties, function/method parameters and return values where we expect, in most cases, to be non-None is troublesome as it requires peppering the code with assertions about state. If and whenever possible, prefer using non-Optional types.
Ironing out these issues allows us to be even stricter with our type checking, which improves consistency in subclass interface types and should make review a little nicer.
This series is based on (but does not require) the 'qapi: sphinx-autodoc for qapi module' series.
V2:
001/12:[----] [--] 'qapi/commands: assert arg_type is not None' 002/12:[----] [--] 'qapi/events: fix visit_event typing' 003/12:[0003] [FC] 'qapi/main: handle theoretical None-return from re.match()' 004/12:[----] [--] 'qapi/gen: assert that _start_if is not None in _wrap_ifcond' 005/12:[0003] [FC] 'qapi/gen: use './builtin' for the built-in module name' 006/12:[0004] [FC] 'qapi/source: Add builtin null-object sentinel' 007/12:[0024] [FC] 'qapi/schema: make QAPISourceInfo mandatory' 008/12:[----] [--] 'qapi/gen: write _genc/_genh access shims' 009/12:[----] [--] 'qapi/gen: move write method to QAPIGenC, make fname a str' 010/12:[----] [--] 'tests/qapi-schema: Add quotes to module name in test output' 011/12:[0004] [FC] 'qapi/schema: Name the builtin module "" instead of None' 012/12:[----] [--] 'qapi: enable strict-optional checks'
- This revision isn't quite complete, but due to deadlines and timezones, opted to send the "revision so far". It keeps some imperfect fixes that Markus is devising better alternatives for.
John Snow (12):
qapi/commands: assert arg_type is not None qapi/events: fix visit_event typing
qapi/main: handle theoretical None-return from re.match() qapi/gen: assert that _start_if is not None in _wrap_ifcond qapi/gen: use './builtin' for the built-in module name qapi/source: Add builtin null-object sentinel qapi/schema: make QAPISourceInfo mandatory qapi/gen: write _genc/_genh access shims qapi/gen: move write method to QAPIGenC, make fname a str tests/qapi-schema: Add quotes to module name in test output qapi/schema: Name the builtin module "" instead of None
qapi: enable strict-optional checks
scripts/qapi/commands.py | 11 ++- scripts/qapi/events.py | 14 +-- scripts/qapi/gen.py | 108 ++++++++++++----------- scripts/qapi/main.py | 2 + scripts/qapi/mypy.ini | 1 - scripts/qapi/schema.py | 35 ++++---- scripts/qapi/source.py | 20 ++++- scripts/qapi/types.py | 11 +-- scripts/qapi/visit.py | 8 +- tests/qapi-schema/comments.out | 4 +- tests/qapi-schema/doc-good.out | 4 +- tests/qapi-schema/empty.out | 4 +- tests/qapi-schema/event-case.out | 4 +- tests/qapi-schema/include-repetition.out | 8 +- tests/qapi-schema/include-simple.out | 6 +- tests/qapi-schema/indented-expr.out | 4 +- tests/qapi-schema/qapi-schema-test.out | 8 +- tests/qapi-schema/test-qapi.py | 2 +- 18 files changed, 145 insertions(+), 109 deletions(-)
Signature · 1 line
2.26.2
PATCH v2 8/12 qapi/gen: write _genc/_genh access shims
Many places assume they can access these fields without checking them first to ensure they are defined. Eliminating the _genc and _genh fields and replacing them with functional properties that check for correct state can ease the typing overhead by eliminating the Optional[T] return type.
--- scripts/qapi/gen.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-)
scripts/qapi/gen.py +13 -5
@@ -243,11 +243,20 @@ def __init__(self, self._user_blurb = user_blurb self._builtin_blurb = builtin_blurb self._pydoc = pydoc - self._genc: Optional[QAPIGenC] = None - self._genh: Optional[QAPIGenH] = None + self._current_module: Optional[str] = None self._module: Dict[str, Tuple[QAPIGenC, QAPIGenH]] = {} self._main_module: Optional[str] = None + @property + def _genc(self) -> QAPIGenC: + assert self._current_module is not None + return self._module[self._current_module][0] + + @property + def _genh(self) -> QAPIGenH: + assert self._current_module is not None + return self._module[self._current_module][1] + @staticmethod def _is_user_module(name: str) -> bool: return not name.startswith('./')
@@ -282,7 +291,7 @@ def _add_module(self, name: str, blurb: str) -> None: genc = QAPIGenC(basename + '.c', blurb, self._pydoc) genh = QAPIGenH(basename + '.h', blurb, self._pydoc) self._module[name] = (genc, genh) - self._genc, self._genh = self._module[name] + self._current_module = name def _add_user_module(self, name: str, blurb: str) -> None: assert self._is_user_module(name)
@@ -315,8 +324,7 @@ def visit_module(self, name: Optional[str]) -> None: else: # The built-in module has not been created. No code may # be generated. - self._genc = None - self._genh = None + self._current_module = None else: self._add_user_module(name, self._user_blurb) self._begin_user_module(name)
Signature · 1 line
2.26.2
PATCH v2 7/12 qapi/schema: make QAPISourceInfo mandatory
In reply to John Snow---
The event_enum_members change might become irrelevant after a forthcoming (?) patch by Markus, but didn't have it in-hand at time of publishing.
--- scripts/qapi/events.py | 2 +- scripts/qapi/schema.py | 25 ++++++++++++++----------- scripts/qapi/types.py | 9 +++++---- scripts/qapi/visit.py | 6 +++--- 4 files changed, 23 insertions(+), 19 deletions(-)
scripts/qapi/events.py +1 -1
@@ -225,7 +225,7 @@ def visit_event(self, self._event_emit_name)) # Note: we generate the enum member regardless of @ifcond, to # keep the enumeration usable in target-independent code. - self._event_enum_members.append(QAPISchemaEnumMember(name, None)) + self._event_enum_members.append(QAPISchemaEnumMember(name, info)) def gen_events(schema: QAPISchema,
scripts/qapi/schema.py +14 -11
@@ -23,6 +23,7 @@ from .error import QAPIError, QAPISemError from .expr import check_exprs from .parser import QAPISchemaParser +from .source import QAPISourceInfo class QAPISchemaEntity:
@@ -36,10 +37,10 @@ def __init__(self, name, info, doc, ifcond=None, features=None): self.name = name self._module = None # For explicitly defined entities, info points to the (explicit) - # definition. For builtins (and their arrays), info is None. - # For implicitly defined entities, info points to a place that - # triggered the implicit definition (there may be more than one - # such place). + # definition. For built-in types (and their arrays), info is a + # special object that evaluates to False. For implicitly defined + # entities, info points to a place that triggered the implicit + # definition (there may be more than one such place). self.info = info self.doc = doc self._ifcond = ifcond or []
@@ -68,7 +69,7 @@ def check_doc(self): def _set_module(self, schema, info): assert self._checked - self._module = schema.module_by_fname(info and info.fname) + self._module = schema.module_by_fname(info.fname if info else None) self._module.add_entity(self) def set_module(self, schema):
@@ -209,7 +210,7 @@ class QAPISchemaBuiltinType(QAPISchemaType): meta = 'built-in' def __init__(self, name, json_type, c_type): - super().__init__(name, None, None) + super().__init__(name, QAPISourceInfo.builtin(), None) assert not c_type or isinstance(c_type, str) assert json_type in ('string', 'number', 'int', 'boolean', 'null', 'value')
@@ -897,7 +898,7 @@ def _def_builtin_type(self, name, json_type, c_type): # be nice, but we can't as long as their generated code # (qapi-builtin-types.[ch]) may be shared by some other # schema. - self._make_array_type(name, None) + self._make_array_type(name, QAPISourceInfo.builtin()) def _def_predefineds(self): for t in [('str', 'string', 'char' + POINTER_SUFFIX),
@@ -917,16 +918,18 @@ def _def_predefineds(self): ('null', 'null', 'QNull' + POINTER_SUFFIX)]: self._def_builtin_type(*t) self.the_empty_object_type = QAPISchemaObjectType( - 'q_empty', None, None, None, None, None, [], None) + 'q_empty', QAPISourceInfo.builtin(), + None, None, None, None, [], None) self._def_entity(self.the_empty_object_type) qtypes = ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist', 'qbool'] qtype_values = self._make_enum_members( - [{'name': n} for n in qtypes], None) + [{'name': n} for n in qtypes], QAPISourceInfo.builtin()) - self._def_entity(QAPISchemaEnumType('QType', None, None, None, None, - qtype_values, 'QTYPE')) + self._def_entity(QAPISchemaEnumType( + 'QType', QAPISourceInfo.builtin(), None, + None, None, qtype_values, 'QTYPE')) def _make_features(self, features, info): if features is None:
scripts/qapi/types.py +5 -4
@@ -71,7 +71,8 @@ def gen_enum(name: str, members: List[QAPISchemaEnumMember], prefix: Optional[str] = None) -> str: # append automatically generated _MAX value - enum_members = members + [QAPISchemaEnumMember('_MAX', None)] + enum_members = members + [ + QAPISchemaEnumMember('_MAX', QAPISourceInfo.builtin())] ret = mcgen('''
@@ -306,7 +307,7 @@ def _gen_type_cleanup(self, name: str) -> None: def visit_enum_type(self, name: str, - info: Optional[QAPISourceInfo], + info: QAPISourceInfo, ifcond: List[str], features: List[QAPISchemaFeature], members: List[QAPISchemaEnumMember],
@@ -317,7 +318,7 @@ def visit_enum_type(self, def visit_array_type(self, name: str, - info: Optional[QAPISourceInfo], + info: QAPISourceInfo, ifcond: List[str], element_type: QAPISchemaType) -> None: with ifcontext(ifcond, self._genh, self._genc):
@@ -327,7 +328,7 @@ def visit_array_type(self, def visit_object_type(self, name: str, - info: Optional[QAPISourceInfo], + info: QAPISourceInfo, ifcond: List[str], features: List[QAPISchemaFeature], base: Optional[QAPISchemaObjectType],
scripts/qapi/visit.py +3 -3
@@ -336,7 +336,7 @@ def _begin_user_module(self, name: str) -> None: def visit_enum_type(self, name: str, - info: QAPISourceInfo, + info: Optional[QAPISourceInfo], ifcond: List[str], features: List[QAPISchemaFeature], members: List[QAPISchemaEnumMember],
@@ -347,7 +347,7 @@ def visit_enum_type(self, def visit_array_type(self, name: str, - info: Optional[QAPISourceInfo], + info: QAPISourceInfo, ifcond: List[str], element_type: QAPISchemaType) -> None: with ifcontext(ifcond, self._genh, self._genc):
@@ -356,7 +356,7 @@ def visit_array_type(self, def visit_object_type(self, name: str, - info: Optional[QAPISourceInfo], + info: QAPISourceInfo, ifcond: List[str], features: List[QAPISchemaFeature], base: Optional[QAPISchemaObjectType],
Signature · 1 line
2.26.2
PATCH v2 5/12 qapi/gen: use './builtin' for the built-in module name
In reply to John SnowUse this in preference to 'None', which helps remove some edge cases in the typing.
--- scripts/qapi/gen.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-)
scripts/qapi/gen.py +14 -14
@@ -245,23 +245,23 @@ def __init__(self, self._pydoc = pydoc self._genc: Optional[QAPIGenC] = None self._genh: Optional[QAPIGenH] = None - self._module: Dict[Optional[str], Tuple[QAPIGenC, QAPIGenH]] = {} + self._module: Dict[str, Tuple[QAPIGenC, QAPIGenH]] = {} self._main_module: Optional[str] = None @staticmethod - def _is_user_module(name: Optional[str]) -> bool: - return bool(name and not name.startswith('./')) + def _is_user_module(name: str) -> bool: + return not name.startswith('./') @staticmethod - def _is_builtin_module(name: Optional[str]) -> bool: - return not name + def _is_builtin_module(name: str) -> bool: + return name == './builtin' - def _module_dirname(self, name: Optional[str]) -> str: + def _module_dirname(self, name: str) -> str: if self._is_user_module(name): return os.path.dirname(name) return '' - def _module_basename(self, what: str, name: Optional[str]) -> str: + def _module_basename(self, what: str, name: str) -> str: ret = '' if self._is_builtin_module(name) else self._prefix if self._is_user_module(name): basename = os.path.basename(name)
@@ -269,15 +269,15 @@ def _module_basename(self, what: str, name: Optional[str]) -> str: if name != self._main_module: ret += '-' + os.path.splitext(basename)[0] else: - name = name[2:] if name else 'builtin' - ret += re.sub(r'-', '-' + name + '-', what) + assert name.startswith('./') + ret += re.sub(r'-', '-' + name[2:] + '-', what) return ret - def _module_filename(self, what: str, name: Optional[str]) -> str: + def _module_filename(self, what: str, name: str) -> str: return os.path.join(self._module_dirname(name), self._module_basename(what, name)) - def _add_module(self, name: Optional[str], blurb: str) -> None: + def _add_module(self, name: str, blurb: str) -> None: basename = self._module_filename(self._what, name) genc = QAPIGenC(basename + '.c', blurb, self._pydoc) genh = QAPIGenH(basename + '.h', blurb, self._pydoc)
@@ -290,8 +290,8 @@ def _add_user_module(self, name: str, blurb: str) -> None: self._main_module = name self._add_module(name, blurb) - def _add_system_module(self, name: Optional[str], blurb: str) -> None: - self._add_module(name and './' + name, blurb) + def _add_system_module(self, name: str, blurb: str) -> None: + self._add_module('./' + name, blurb) def write(self, output_dir: str, opt_builtins: bool = False) -> None: for name in self._module:
@@ -310,7 +310,7 @@ def _begin_user_module(self, name: str) -> None: def visit_module(self, name: Optional[str]) -> None: if name is None: if self._builtin_blurb: - self._add_system_module(None, self._builtin_blurb) + self._add_system_module('builtin', self._builtin_blurb) self._begin_system_module(name) else: # The built-in module has not been created. No code may
Signature · 1 line
2.26.2
PATCH v2 10/12 tests/qapi-schema: Add quotes to module name in test output
In reply to John SnowA forthcoming patch is going to allow the empty string as a name for the builtin module, and quotes will help us see that in test output. Without this, git will be upset about trailing empty spaces in test output, so the quotes are necessary.
--- tests/qapi-schema/comments.out | 4 ++-- tests/qapi-schema/doc-good.out | 4 ++-- tests/qapi-schema/empty.out | 4 ++-- tests/qapi-schema/event-case.out | 4 ++-- tests/qapi-schema/include-repetition.out | 8 ++++---- tests/qapi-schema/include-simple.out | 6 +++--- tests/qapi-schema/indented-expr.out | 4 ++-- tests/qapi-schema/qapi-schema-test.out | 8 ++++---- tests/qapi-schema/test-qapi.py | 2 +- 9 files changed, 22 insertions(+), 22 deletions(-)
tests/qapi-schema/comments.out +2 -2
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,7 +9,7 @@ enum QType member qdict member qlist member qbool -module comments.json +module "comments.json" enum Status member good member bad
tests/qapi-schema/doc-good.out +2 -2
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,7 +9,7 @@ enum QType member qdict member qlist member qbool -module doc-good.json +module "doc-good.json" enum Enum member one if ['defined(IFONE)']
tests/qapi-schema/empty.out +2 -2
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,4 +9,4 @@ enum QType member qdict member qlist member qbool -module empty.json +module "empty.json"
tests/qapi-schema/event-case.out +2 -2
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,6 +9,6 @@ enum QType member qdict member qlist member qbool -module event-case.json +module "event-case.json" event oops None boxed=False
tests/qapi-schema/include-repetition.out +4 -4
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,15 +9,15 @@ enum QType member qdict member qlist member qbool -module include-repetition.json +module "include-repetition.json" include comments.json include include-repetition-sub.json include comments.json -module comments.json +module "comments.json" enum Status member good member bad member ugly -module include-repetition-sub.json +module "include-repetition-sub.json" include comments.json include comments.json
tests/qapi-schema/include-simple.out +3 -3
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,9 +9,9 @@ enum QType member qdict member qlist member qbool -module include-simple.json +module "include-simple.json" include include-simple-sub.json -module include-simple-sub.json +module "include-simple-sub.json" enum Status member good member bad
tests/qapi-schema/indented-expr.out +2 -2
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,7 +9,7 @@ enum QType member qdict member qlist member qbool -module indented-expr.json +module "indented-expr.json" command eins None -> None gen=True success_response=True boxed=False oob=False preconfig=False command zwei None -> None
tests/qapi-schema/qapi-schema-test.out +4 -4
@@ -1,4 +1,4 @@ -module None +module "None" object q_empty enum QType prefix QTYPE
@@ -9,7 +9,7 @@ enum QType member qdict member qlist member qbool -module qapi-schema-test.json +module "qapi-schema-test.json" object TestStruct member integer: int optional=False member boolean: bool optional=False
@@ -443,11 +443,11 @@ command test-command-cond-features3 None -> None event TEST-EVENT-FEATURES1 None boxed=False feature deprecated -module include/sub-module.json +module "include/sub-module.json" include sub-sub-module.json object SecondArrayRef member s: StatusList optional=False -module sub-sub-module.json +module "sub-sub-module.json" array StatusList Status enum Status member good
tests/qapi-schema/test-qapi.py +1 -1
@@ -25,7 +25,7 @@ class QAPISchemaTestVisitor(QAPISchemaVisitor): def visit_module(self, name): - print('module %s' % name) + print('module "%s"' % name) def visit_include(self, name, info): print('include %s' % name)
Signature · 1 line
2.26.2
PATCH v2 11/12 qapi/schema: Name the builtin module "" instead of None
In reply to John SnowInstead of using None as the built-in module filename, use an empty string instead. This allows us to clarify the type of various interfaces dealing with module names as always taking a string, which saves us from having to use Optional[str] everywhere.
--- scripts/qapi/gen.py | 6 +++--- scripts/qapi/schema.py | 12 ++++++------ scripts/qapi/types.py | 2 +- scripts/qapi/visit.py | 2 +- tests/qapi-schema/comments.out | 2 +- tests/qapi-schema/doc-good.out | 2 +- tests/qapi-schema/empty.out | 2 +- tests/qapi-schema/event-case.out | 2 +- tests/qapi-schema/include-repetition.out | 2 +- tests/qapi-schema/include-simple.out | 2 +- tests/qapi-schema/indented-expr.out | 2 +- tests/qapi-schema/qapi-schema-test.out | 2 +- 12 files changed, 19 insertions(+), 19 deletions(-)
scripts/qapi/gen.py +3 -3
@@ -310,14 +310,14 @@ def write(self, output_dir: str, opt_builtins: bool = False) -> None: genc.write(output_dir) genh.write(output_dir) - def _begin_system_module(self, name: None) -> None: + def _begin_system_module(self, name: str) -> None: pass def _begin_user_module(self, name: str) -> None: pass - def visit_module(self, name: Optional[str]) -> None: - if name is None: + def visit_module(self, name: str) -> None: + if not name: if self._builtin_blurb: self._add_system_module('builtin', self._builtin_blurb) self._begin_system_module(name)
scripts/qapi/schema.py +6 -6
@@ -69,7 +69,7 @@ def check_doc(self): def _set_module(self, schema, info): assert self._checked - self._module = schema.module_by_fname(info.fname if info else None) + self._module = schema.module_by_fname(info.fname) self._module.add_entity(self) def set_module(self, schema):
@@ -826,7 +826,7 @@ def __init__(self, fname): self._entity_dict = {} self._module_dict = OrderedDict() self._schema_dir = os.path.dirname(fname) - self._make_module(None) # built-ins + self._make_module(QAPISourceInfo.builtin().fname) # built-ins self._make_module(fname) self._predefining = True self._def_predefineds()
@@ -871,10 +871,10 @@ def resolve_type(self, name, info, what): info, "%s uses unknown type '%s'" % (what, name)) return typ - def _module_name(self, fname): - if fname is None: - return None - return os.path.relpath(fname, self._schema_dir) + def _module_name(self, fname: str) -> str: + if fname: + return os.path.relpath(fname, self._schema_dir) + return fname def _make_module(self, fname): name = self._module_name(fname)
scripts/qapi/types.py +1 -1
@@ -272,7 +272,7 @@ def __init__(self, prefix: str): prefix, 'qapi-types', ' * Schema-defined QAPI types', ' * Built-in QAPI types', __doc__) - def _begin_system_module(self, name: None) -> None: + def _begin_system_module(self, name: str) -> None: self._genc.preamble_add(mcgen(''' #include "qemu/osdep.h" #include "qapi/dealloc-visitor.h"
scripts/qapi/visit.py +1 -1
@@ -305,7 +305,7 @@ def __init__(self, prefix: str): prefix, 'qapi-visit', ' * Schema-defined QAPI visitors', ' * Built-in QAPI visitors', __doc__) - def _begin_system_module(self, name: None) -> None: + def _begin_system_module(self, name: str) -> None: self._genc.preamble_add(mcgen(''' #include "qemu/osdep.h" #include "qapi/error.h"
tests/qapi-schema/comments.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
tests/qapi-schema/doc-good.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
tests/qapi-schema/empty.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
tests/qapi-schema/event-case.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
tests/qapi-schema/include-repetition.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
tests/qapi-schema/include-simple.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
tests/qapi-schema/indented-expr.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
tests/qapi-schema/qapi-schema-test.out +1 -1
@@ -1,4 +1,4 @@ -module "None" +module "" object q_empty enum QType prefix QTYPE
Signature · 1 line
2.26.2
PATCH v2 6/12 qapi/source: Add builtin null-object sentinel
In reply to John SnowWe use None to represent an object that has no source information because it's a builtin. This complicates interface typing, since many interfaces expect that there is an info object available to print errors with.
Introduce a special QAPISourceInfo that represents these built-ins so that if an error should so happen to occur relating to one of these builtins that we will be able to print its information, and interface typing becomes simpler: you will always have a source info object.
This object will evaluate as False, so "if info" remains a valid idiomatic construct.
NB: It was intentional to not allow empty constructors or similar to create "empty" source info objects; callers must explicitly invoke 'builtin()' to pro-actively opt into using the sentinel. This should prevent use-by-accident.
--- scripts/qapi/source.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
scripts/qapi/source.py +19 -1
@@ -11,7 +11,12 @@ import copy import sys -from typing import List, Optional, TypeVar +from typing import ( + List, + Optional, + Type, + TypeVar, +) class QAPISchemaPragma:
@@ -41,6 +46,17 @@ def __init__(self, fname: str, line: int, self.defn_meta: Optional[str] = None self.defn_name: Optional[str] = None + @classmethod + def builtin(cls: Type[T]) -> T: + """ + Create an instance corresponding to a built-in definition. + """ + return cls('', -1, None) + + def __bool__(self) -> bool: + # "if info" is false if @info corresponds to a built-in definition. + return bool(self.fname) + def set_defn(self, meta: str, name: str) -> None: self.defn_meta = meta self.defn_name = name
@@ -73,4 +89,6 @@ def include_path(self) -> str: return ret def __str__(self) -> str: + if not bool(self): + return '[builtin]' return self.include_path() + self.in_defn() + self.loc()
Signature · 1 line
2.26.2
PATCH v2 9/12 qapi/gen: move write method to QAPIGenC, make fname a str
In reply to John SnowQAPIGenC and QAPIGenH in particular depend on fname being defined, but we have a usage of QAPIGenCCode that isn't intended to be associated with a particular file.
No problem, move the write method down to the class that actually needs it, and keep QAPIGenCCode more abstract.
---
Possibly un-needed in concert with a forthcoming patch by Markus, but I didn't have it in my hands at time of publishing.
--- scripts/qapi/commands.py | 2 +- scripts/qapi/gen.py | 54 ++++++++++++++++++++-------------------- 2 files changed, 28 insertions(+), 28 deletions(-)
scripts/qapi/commands.py +1 -1
@@ -258,7 +258,7 @@ def __init__(self, prefix: str): super().__init__( prefix, 'qapi-commands', ' * Schema-defined QAPI/QMP commands', None, __doc__) - self._regy = QAPIGenCCode(None) + self._regy = QAPIGenCCode() self._visited_ret_types: Dict[QAPIGenC, Set[QAPISchemaType]] = {} def _begin_user_module(self, name: str) -> None:
scripts/qapi/gen.py +27 -27
82 lines not on this page · raw message
Signature · 1 line
2.26.2
Re: [PATCH v2 04/12] qapi/gen: assert that _start_if is not None in _wrap_ifcond
In reply to John SnowQuoted 16 lines · John Snow
We already assert this in
end_if, but that's opaque to mypy. Do it in_wrap_ifcondinstead. Same effect at runtime, but mypy can now infer the type in _wrap_ifcond's body.Signed-off-by John Snow <[email protected]>--- scripts/qapi/gen.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)scripts/qapi/gen.py +0
-0@@ -130,11 +130,11 @@ def start_if(self, ifcond: List[str]) -> None: self._start_if = (ifcond, self._body, self._preamble)
scripts/qapi/gen.py def start_if(self, ifcond: List[str]) -> None: · line 140
Quoted 10 lines
scripts/qapi/gen.py +1
-1def end_if(self) -> None: - assert self._start_if self._wrap_ifcond() self._start_if = None def _wrap_ifcond(self) -> None: + assert self._start_if self._body = _wrap_ifcond(self._start_if[0], self._start_if[1], self._body) self._preamble = _wrap_ifcond(self._start_if[0],
Let's inline ._wrap_ifcond() into .end_if(). Not a blocker, of course.
Re: [PATCH v2 06/12] qapi/source: Add builtin null-object sentinel
In reply to John SnowSpelling nitpick: s/builtin/built-in/ in the title.
Quoted 13 lines · John Snow
We use None to represent an object that has no source information because it's a builtin. This complicates interface typing, since many interfaces expect that there is an info object available to print errors with.
Introduce a special QAPISourceInfo that represents these built-ins so that if an error should so happen to occur relating to one of these builtins that we will be able to print its information, and interface typing becomes simpler: you will always have a source info object.
This object will evaluate as False, so "if info" remains a valid idiomatic construct.
Quoted 6 lines
NB: It was intentional to not allow empty constructors or similar to create "empty" source info objects; callers must explicitly invoke '
builtin()' to pro-actively opt into using the sentinel. This should prevent use-by-accident.Signed-off-by John Snow <[email protected]>
As I pointed out in review of v1, this patch has two aspects mixed up:
1. Represent "no source info" as special QAPISourceInfo instead of None
2. On error with "no source info", don't crash.
The first one is what de-complicates interface typing. It's clearly serving this patch series' stated purpose: "static typing conversion".
The second one is not. It sidetracks us into a design discussion that isn't related to static typing. Maybe it's something we should discuss. Maybe the discussion will make us conclude we want to do this. But letting the static typing work get delayed by that discussion would be stupid, and I'll do what I can to prevent that.
The stupidest possible solution that preserves the crash is adding an assertion right where it crashes before this patch: in QAPISourceInfo.__str__(). Yes, crashing in a __str__() method is not nice, but it's no worse than before. Making it better than before is a good idea, and you're quite welcome to try, but please not in this series. Add a TODO comment asking for "make it better", then sit on your hands.
The pipeline must move.
Re: [PATCH v2 07/12] qapi/schema: make QAPISourceInfo mandatory
In reply to John SnowQuoted 7 lines · John Snow
Signed-off-by John Snow <[email protected]>---
The
event_enum_memberschange might become irrelevant after a forthcoming (?) patch by Markus, but didn't have it in-hand at time of publishing.
It's in my "[PATCH 00/11] Drop support for QAPIGen without a file name", which includes parts of your v1. The parts that are new should be injected into your series so they replace your "[PATCH v2 09/12] qapi/gen: move write method to QAPIGenC, make fname a str". Holler if you need help.
Quoted 13 lines
Signed-off-by John Snow <[email protected]>--- scripts/qapi/events.py | 2 +- scripts/qapi/schema.py | 25 ++++++++++++++----------- scripts/qapi/types.py | 9 +++++---- scripts/qapi/visit.py | 6 +++--- 4 files changed, 23 insertions(+), 19 deletions(-)scripts/qapi/events.py +0
-0
scripts/qapi/events.py def visit_event(self, · line 228
Quoted 5 lines
scripts/qapi/events.py +1
-1@@ -225,7 +225,7 @@ def visit_event(self, self._event_emit_name)) # Note: we generate the enum member regardless of @ifcond, to # keep the enumeration usable in target-independent code. - self._event_enum_members.append(QAPISchemaEnumMember(name, None)) + self._event_enum_members.append(QAPISchemaEnumMember(name, info))
This "enum" is not supposed to be erroneous. If it is, it's a bug.
Your patch changes how the code behaves should such a bug bite here. Before, we crash. Afterwards, we report the bug using @info, which I'd expect to produce utterly confusing error messages.
My comments on PATCH 06 apply: how the code should behave here is a design issue that should be kept out of this patch series.
If you need to pass a value other than None to help with static typing, then pass a suitable poison info that will crash right where None crashes now.
Quoted 29 lines
scripts/qapi/events.py +0
-0def gen_events(schema: QAPISchema,scripts/qapi/schema.py +5
-4@@ -23,6 +23,7 @@ from .error import QAPIError, QAPISemError from .expr import check_exprs from .parser import QAPISchemaParser +from .source import QAPISourceInfo class QAPISchemaEntity:@@ -36,10 +37,10 @@ def __init__(self, name, info, doc, ifcond=None, features=None): self.name = name self._module = None # For explicitly defined entities, info points to the (explicit) - # definition. For builtins (and their arrays), info is None. - # For implicitly defined entities, info points to a place that - # triggered the implicit definition (there may be more than one - # such place). + # definition. For built-in types (and their arrays), info is a + # special object that evaluates to False. For implicitly defined + # entities, info points to a place that triggered the implicit + # definition (there may be more than one such place). self.info = info self.doc = doc self._ifcond = ifcond or []
scripts/qapi/schema.py def check_doc(self): · line 72
Quoted 5 lines
scripts/qapi/schema.py +1
-1@@ -68,7 +69,7 @@ def check_doc(self): def _set_module(self, schema, info): assert self._checked - self._module = schema.module_by_fname(info and info.fname) + self._module = schema.module_by_fname(info.fname if info else None)
Looks unrelated.
Quoted 3 lines
scripts/qapi/schema.py +0
-0self._module.add_entity(self) def set_module(self, schema):
[...]
Quoted 10 lines · John Snow
Hi, this patchset enables strict optional checking in mypy for everything we have typed so far.
In general, this patchset seeks to eliminate Optional[T] in favor of T wherever possible. Optional types used for object properties, function/method parameters and return values where we expect, in most cases, to be non-None is troublesome as it requires peppering the code with assertions about state. If and whenever possible, prefer using non-Optional types.
Quoted 6 lines
Ironing out these issues allows us to be even stricter with our type checking, which improves consistency in subclass interface types and should make review a little nicer.
This series is based on (but does not require) the 'qapi: sphinx-autodoc for qapi module' series.
Just two issues left that aren't entirely trivial: 1. mission creep [PATCH 6+7], 2. integrating my "[PATCH 00/11] Drop support for QAPIGen without a file name".
Re: [PATCH v2 04/12] qapi/gen: assert that _start_if is not None in _wrap_ifcond
In reply to Markus ArmbrusterQuoted 23 lines · Markus Armbruster
Quoted 21 lines · John Snow
We already assert this in
end_if, but that's opaque to mypy. Do it in_wrap_ifcondinstead. Same effect at runtime, but mypy can now infer the type in _wrap_ifcond's body.Signed-off-by John Snow <[email protected]>--- scripts/qapi/gen.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)scripts/qapi/gen.py +0
-1@@ -130,11 +130,11 @@ def start_if(self, ifcond: List[str]) -> None: self._start_if = (ifcond, self._body, self._preamble) def end_if(self) -> None: - assert self._start_if self._wrap_ifcond() self._start_if = None
Quoted 8 lines
scripts/qapi/gen.py def start_if(self, ifcond: List[str]) -> None: · line 140
Quoted 5 lines
scripts/qapi/gen.py +1
-0def _wrap_ifcond(self) -> None: + assert self._start_if self._body = _wrap_ifcond(self._start_if[0], self._start_if[1], self._body) self._preamble = _wrap_ifcond(self._start_if[0],Let's inline ._wrap_ifcond() into .end_if(). Not a blocker, of course.
I thought I did do this, but I guess it didn't make it out to list. I'll look into that.
I was planning on taking your series and trying to splice it into this one here and sending it back out as a conjoined thing.
Re: [PATCH v2 06/12] qapi/source: Add builtin null-object sentinel
In reply to Markus ArmbrusterQuoted 2 lines · Markus Armbruster
Spelling nitpick: s/builtin/built-in/ in the title.
Sure.
Quoted 29 lines
Quoted 13 lines · John Snow
We use None to represent an object that has no source information because it's a builtin. This complicates interface typing, since many interfaces expect that there is an info object available to print errors with.
Introduce a special QAPISourceInfo that represents these built-ins so that if an error should so happen to occur relating to one of these builtins that we will be able to print its information, and interface typing becomes simpler: you will always have a source info object.
This object will evaluate as False, so "if info" remains a valid idiomatic construct.
Quoted 6 lines
NB: It was intentional to not allow empty constructors or similar to create "empty" source info objects; callers must explicitly invoke '
builtin()' to pro-actively opt into using the sentinel. This should prevent use-by-accident.Signed-off-by John Snow <[email protected]>As I pointed out in review of v1, this patch has two aspects mixed up:
1. Represent "no source info" as special QAPISourceInfo instead of None
2. On error with "no source info", don't crash.
Quoted 9 lines
The first one is what de-complicates interface typing. It's clearly serving this patch series' stated purpose: "static typing conversion".
The second one is not. It sidetracks us into a design discussion that isn't related to static typing. Maybe it's something we should discuss. Maybe the discussion will make us conclude we want to do this. But letting the static typing work get delayed by that discussion would be stupid, and I'll do what I can to prevent that.
It's not unrelated. It's about finding the most tactical incision to make the types as we actually use them correct from a static analysis context.
Maybe there's another tactical incision to make that's "smaller", for some perception of "smaller", but it's not unrelated.
Quoted 7 lines
The stupidest possible solution that preserves the crash is adding an assertion right where it crashes before this patch: in
QAPISourceInfo.__str__(). Yes, crashing in a__str__()method is not nice, but it's no worse than before. Making it better than before is a good idea, and you're quite welcome to try, but please not in this series. Add a TODO comment asking for "make it better", then sit on your hands.
I'm recently back from a fairly long PTO, so forgive me if I am forgetting something, but I am not really sure I fundamentally understand the nature of this critique.
Making functions not "crash" is a side-effect of making the types correct. I don't see it as scope-creep, it's a solution to a problem under active consideration.
In my reply to your earlier critique, I (think) I mentioned that I didn't understand the difference between:
1. An exception handler itself crashes because it received a value of unexpected type, or
2. The exception handler printed a message that indicates a problem with a built-in source definition.
In either case, QAPI didn't get built and it printed some kind of error spaghetti to the screen. In both cases, something much more seriously wrong has happened and the error message likely does not prepare the human user to really genuinely understand what that seriously wrong thing is.
I think this is an on-mission patch that improves circumstances; with regards to matters of taste I would see it as a lateral move at worst (one weird error for another weird error).
I'm left a little confused by the pushback, so I don't feel equipped to try and write code that addresses it.
Let's chat on IRC?
--js
Re: [PATCH v2 07/12] qapi/schema: make QAPISourceInfo mandatory
In reply to Markus ArmbrusterQuoted 37 lines · Markus Armbruster
Quoted 7 lines · John Snow
Signed-off-by John Snow <[email protected]>---
The
event_enum_memberschange might become irrelevant after a forthcoming (?) patch by Markus, but didn't have it in-hand at time of publishing.It's in my "[PATCH 00/11] Drop support for QAPIGen without a file name", which includes parts of your v1. The parts that are new should be injected into your series so they replace your "[PATCH v2 09/12] qapi/gen: move write method to QAPIGenC, make fname a str". Holler if you need help.
Quoted 13 lines
Signed-off-by John Snow <[email protected]>--- scripts/qapi/events.py | 2 +- scripts/qapi/schema.py | 25 ++++++++++++++----------- scripts/qapi/types.py | 9 +++++---- scripts/qapi/visit.py | 6 +++--- 4 files changed, 23 insertions(+), 19 deletions(-)scripts/qapi/events.py +0
-0scripts/qapi/events.py def visit_event(self, · line 228
Quoted 5 lines
scripts/qapi/events.py +1
-1@@ -225,7 +225,7 @@ def visit_event(self, self._event_emit_name)) # Note: we generate the enum member regardless of @ifcond, to # keep the enumeration usable in target-independent code. - self._event_enum_members.append(QAPISchemaEnumMember(name, None)) + self._event_enum_members.append(QAPISchemaEnumMember(name, info))This "enum" is not supposed to be erroneous. If it is, it's a bug.
Quoted 4 lines
Your patch changes how the code behaves should such a bug bite here. Before, we crash. Afterwards, we report the bug using @info, which I'd expect to produce utterly confusing error messages.
It doesn't change the behavior *here*, though. It changes it whenever this info object is used in another context. ... and who knows when or where or why it is being used, or by whom.
I'll have to play with this. I'm not sure there's any way to coax a bug to happen here that I am aware of right away. Can you think of how to will one into existence?
Quoted 7 lines
My comments on PATCH 06 apply: how the code should behave here is a design issue that should be kept out of this patch series.
If you need to pass a value other than None to help with static typing, then pass a suitable poison info that will crash right where None crashes now.
I think we need to, yes; or we probably really, really want to. Making the info parameter optional really adds a lot of unidiomatic type-checking confetti when we go to use info, and in many more contexts than just this sorta-built-in-enum; it will creep badly.
So, I gotta pass ...something here. but what? You want poison, but I think it's not right to fundamentally poison all built-ins.
Mmmmmmm. Maybe per-instance poison can be done? We actually share info objects, but I can make poisoned copies. Using next_line() as a basis:
def poison(self: T) -> T:
info = copy.copy(self)
info.poisoned = True
return info
probably almost anything I do is not going to make a lot of sense unless I can actually replicate and test the different error scenarios to prove that we didn't make the error spaghetti unknowably worse. I see it as functionally inevitable that I have to audit this and make sure we get good error messages anyway, so ... maybe I just ought to do that now anyway.
Quoted 30 lines
Quoted 30 lines
scripts/qapi/events.py +0
-0def gen_events(schema: QAPISchema,scripts/qapi/schema.py +5
-4@@ -23,6 +23,7 @@ from .error import QAPIError, QAPISemError from .expr import check_exprs from .parser import QAPISchemaParser +from .source import QAPISourceInfo class QAPISchemaEntity:@@ -36,10 +37,10 @@ def __init__(self, name, info, doc, ifcond=None, features=None): self.name = name self._module = None # For explicitly defined entities, info points to the (explicit) - # definition. For builtins (and their arrays), info is None. - # For implicitly defined entities, info points to a place that - # triggered the implicit definition (there may be more than one - # such place). + # definition. For built-in types (and their arrays), info is a + # special object that evaluates to False. For implicitly defined + # entities, info points to a place that triggered the implicit + # definition (there may be more than one such place). self.info = info self.doc = doc self._ifcond = ifcond or []@@ -68,7 +69,7 @@ def check_doc(self):
Quoted 7 lines
scripts/qapi/schema.py def check_doc(self): · line 72
Quoted 4 lines
scripts/qapi/schema.py +1
-1def _set_module(self, schema, info): assert self._checked - self._module = schema.module_by_fname(info and info.fname) + self._module = schema.module_by_fname(info.fname if info else None)Looks unrelated.
Hmm, it sorta is. I have apparently edited this patch since I sent it, but there was some tomfoolery over how "x and y" statements behave and this edit was necessary at the time.
"info and info.fname" returned None when info could actually be None, but when it was updated to be a special source object, we could accidentally pass that special source object as the name -- instead of None. Not good.
I think I re-ordered some patches such that I can just pass in "info.fname" unconditionally instead as of this patch.
Quoted 5 lines
Quoted 3 lines
scripts/qapi/schema.py +0
-0self._module.add_entity(self) def set_module(self, schema):[...]
Re: [PATCH v2 07/12] qapi/schema: make QAPISourceInfo mandatory
Quoted 43 lines · John Snow
Quoted 37 lines · Markus Armbruster
Quoted 7 lines · John Snow
Signed-off-by John Snow <[email protected]>---
The
event_enum_memberschange might become irrelevant after a forthcoming (?) patch by Markus, but didn't have it in-hand at time of publishing.It's in my "[PATCH 00/11] Drop support for QAPIGen without a file name", which includes parts of your v1. The parts that are new should be injected into your series so they replace your "[PATCH v2 09/12] qapi/gen: move write method to QAPIGenC, make fname a str". Holler if you need help.
Quoted 13 lines
Signed-off-by John Snow <[email protected]>--- scripts/qapi/events.py | 2 +- scripts/qapi/schema.py | 25 ++++++++++++++----------- scripts/qapi/types.py | 9 +++++---- scripts/qapi/visit.py | 6 +++--- 4 files changed, 23 insertions(+), 19 deletions(-)scripts/qapi/events.py +0
-0scripts/qapi/events.py def visit_event(self, · line 228
Quoted 5 lines
scripts/qapi/events.py +1
-1@@ -225,7 +225,7 @@ def visit_event(self, self._event_emit_name)) # Note: we generate the enum member regardless of @ifcond, to # keep the enumeration usable in target-independent code. - self._event_enum_members.append(QAPISchemaEnumMember(name, None)) + self._event_enum_members.append(QAPISchemaEnumMember(name, info))This "enum" is not supposed to be erroneous. If it is, it's a bug.
Quoted 4 lines
Your patch changes how the code behaves should such a bug bite here. Before, we crash. Afterwards, we report the bug using @info, which I'd expect to produce utterly confusing error messages.
Quoted 14 lines
It doesn't change the behavior *here*, though. It changes it whenever this info object is used in another context. ... and who knows when or where or why it is being used, or by whom.
I'll have to play with this. I'm not sure there's any way to coax a bug to happen here that I am aware of right away. Can you think of how to will one into existence?
Quoted 6 lines
My comments on PATCH 06 apply: how the code should behave here is a design issue that should be kept out of this patch series.
If you need to pass a value other than None to help with static typing, then pass a suitable poison info that will crash right where None crashes now.
I don't understand what would be the point of inventing something that behaves exactly like None but makes type checking less useful.
With None/Optional, mypy gives us a way to be 100% sure the object isn't going to invalid. With a poison value, mypy can't tell us anymore if the code risks crashing at runtime.
Quoted 6 lines
Quoted 1 line
I think we need to, yes; or we probably really, really want to. Making the info parameter optional really adds a lot of unidiomatic type-checking confetti when we go to use info, and in many more contexts than just this sorta-built-in-enum; it will creep badly.
Which methods would require unidiomatic type-checking because of None/Optional?
Quoted 69 lines
So, I gotta pass ...something here. but what? You want poison, but I think it's not right to fundamentally poison all built-ins.
Mmmmmmm. Maybe per-instance poison can be done? We actually share info objects, but I can make poisoned copies. Using
next_line()as a basis:def poison(self: T) -> T:
info =copy.copy(self)
info.poisoned = True
return infoprobably almost anything I do is not going to make a lot of sense unless I can actually replicate and test the different error scenarios to prove that we didn't make the error spaghetti unknowably worse. I see it as functionally inevitable that I have to audit this and make sure we get good error messages anyway, so ... maybe I just ought to do that now anyway.
Quoted 25 lines
Quoted 25 lines
scripts/qapi/events.py +0
-0def gen_events(schema: QAPISchema,scripts/qapi/schema.py +5
-4@@ -23,6 +23,7 @@ from .error import QAPIError, QAPISemError from .expr import check_exprs from .parser import QAPISchemaParser +from .source import QAPISourceInfo class QAPISchemaEntity:@@ -36,10 +37,10 @@ def __init__(self, name, info, doc, ifcond=None, features=None): self.name = name self._module = None # For explicitly defined entities, info points to the (explicit) - # definition. For builtins (and their arrays), info is None. - # For implicitly defined entities, info points to a place that - # triggered the implicit definition (there may be more than one - # such place). + # definition. For built-in types (and their arrays), info is a + # special object that evaluates to False. For implicitly defined + # entities, info points to a place that triggered the implicit + # definition (there may be more than one such place). self.info = info self.doc = docQuoted 9 lines
scripts/qapi/schema.py def check_doc(self): · line 71
Quoted 6 lines
scripts/qapi/schema.py +1
-1self._ifcond = ifcond or []@@ -68,7 +69,7 @@ def check_doc(self): def _set_module(self, schema, info): assert self._checked - self._module = schema.module_by_fname(info and info.fname) + self._module = schema.module_by_fname(info.fname if info else None)Looks unrelated.
Hmm, it sorta is. I have apparently edited this patch since I sent it, but there was some tomfoolery over how "x and y" statements behave and this edit was necessary at the time.
"info and info.fname" returned None when info could actually be None, but when it was updated to be a special source object, we could accidentally pass that special source object as the name -- instead of None. Not good.
I think I re-ordered some patches such that I can just pass in "info.fname" unconditionally instead as of this patch.
Quoted 4 lines
Quoted 2 lines
scripts/qapi/schema.py +0
-0self._module.add_entity(self) def set_module(self, schema):[...]
Signature · 1 line
Eduardo
Re: [PATCH v2 07/12] qapi/schema: make QAPISourceInfo mandatory
Quoted 3 lines · Eduardo Habkost
Quoted 2 lines · John Snow
Quoted 1 line · Markus Armbruster
John Snow <[email protected]> writes:
...
Quoted 9 lines
Quoted 5 lines
I think we need to, yes; or we probably really, really want to. Making the info parameter optional really adds a lot of unidiomatic type-checking confetti when we go to use info, and in many more contexts than just this sorta-built-in-enum; it will creep badly.
Which methods would require unidiomatic type-checking because of None/Optional?
Virtually everything that accepts a QAPISourceInfo has to do something like this:
def foo(info: Optional[QAPISourceInfo]):
if info is None:
raise Exception("Something very bad has happened!")
...
...
Since the great majority of cases *will* have an info, and we take careful pains to make sure this info is preserved, it's less invasive to just assert that info isn't Optional.
This is especially true for the QAPISchemaMember initializer, which several other classes inherit -- if this is allowed to be Optional[QAPISourceInfo], any and all users of a QAPISchemaMember or any derived classes will have to check -- on every access -- to see if 'member.info' is set or not.
Since we expect it to be set 100% of the time for all user-defined code, it's a lot less "if member.info is not None" checks everywhere.
Adding a special "built-in" source info object to make this claim helps avoid making confusing type signatures for the visitors; i.e.
def visit_thing(info: Optional[QAPISourceInfo]): ...
is misleading, because we actually expect thing to *always* have a SourceInfo. To make the documentation be a little more ... statistically truthful, it's easier to bend the rules in the other direction and just fill in the scant few cases where we don't have a QAPISourceInfo.
--js
Re: [PATCH v2 06/12] qapi/source: Add builtin null-object sentinel
In reply to John SnowQuoted 45 lines · John Snow
Quoted 2 lines · Markus Armbruster
Spelling nitpick: s/builtin/built-in/ in the title.
Sure.
Quoted 29 lines
Quoted 13 lines · John Snow
We use None to represent an object that has no source information because it's a builtin. This complicates interface typing, since many interfaces expect that there is an info object available to print errors with.
Introduce a special QAPISourceInfo that represents these built-ins so that if an error should so happen to occur relating to one of these builtins that we will be able to print its information, and interface typing becomes simpler: you will always have a source info object.
This object will evaluate as False, so "if info" remains a valid idiomatic construct.
Quoted 6 lines
NB: It was intentional to not allow empty constructors or similar to create "empty" source info objects; callers must explicitly invoke '
builtin()' to pro-actively opt into using the sentinel. This should prevent use-by-accident.Signed-off-by John Snow <[email protected]>As I pointed out in review of v1, this patch has two aspects mixed up:
1. Represent "no source info" as special QAPISourceInfo instead of None
2. On error with "no source info", don't crash.
Quoted 9 lines
The first one is what de-complicates interface typing. It's clearly serving this patch series' stated purpose: "static typing conversion".
The second one is not. It sidetracks us into a design discussion that isn't related to static typing. Maybe it's something we should discuss. Maybe the discussion will make us conclude we want to do this. But letting the static typing work get delayed by that discussion would be stupid, and I'll do what I can to prevent that.
Quoted 6 lines
It's not unrelated. It's about finding the most tactical incision to make the types as we actually use them correct from a static analysis context.
Maybe there's another tactical incision to make that's "smaller", for some perception of "smaller", but it's not unrelated.
We don't have to debate, let alone agree on relatedness.
Quoted 8 lines
Quoted 7 lines
The stupidest possible solution that preserves the crash is adding an assertion right where it crashes before this patch: in
QAPISourceInfo.__str__(). Yes, crashing in a__str__()method is not nice, but it's no worse than before. Making it better than before is a good idea, and you're quite welcome to try, but please not in this series. Add a TODO comment asking for "make it better", then sit on your hands.
Quoted 7 lines
I'm recently back from a fairly long PTO, so forgive me if I am forgetting something, but I am not really sure I fundamentally understand the nature of this critique.
Making functions not "crash" is a side-effect of making the types correct. I don't see it as scope-creep, it's a solution to a problem under active consideration.
I disagree.
The crash you "fix" is *intentional*. I was too lazy to write something like
assert self.info
and instead relied in self.info.whatever to crash. I don't care how it crashes, as long as it does crash.
I *like* qapi-gen to crash on such internal errors. It's easy, and makes "this is a bug, go report it" perfectly clear.
I'd also be fine with reporting "internal error, this is a bug, go report it". Not in this series, unless it's utterly trivial, which I doubt.
I'm *not* fine with feeding made-up info objects to the user error reporting machinery without proof that it'll actually produce a useful error message. Definitely not trivial, thus not in this series.
Quoted 15 lines
In my reply to your earlier critique, I (think) I mentioned that I didn't understand the difference between:
1. An exception handler itself crashes because it received a value of unexpected type, or
2. The exception handler printed a message that indicates a problem with a built-in source definition.
In either case, QAPI didn't get built and it printed some kind of error spaghetti to the screen. In both cases, something much more seriously wrong has happened and the error message likely does not prepare the human user to really genuinely understand what that seriously wrong thing is.
Quoted 8 lines
I think this is an on-mission patch that improves circumstances; with regards to matters of taste I would see it as a lateral move at worst (one weird error for another weird error).
I'm left a little confused by the pushback, so I don't feel equipped to try and write code that addresses it.
Let's chat on IRC?
Gladly. If we can make out work days intersect...
Re: [PATCH v2 06/12] qapi/source: Add builtin null-object sentinel
Quoted 85 lines · Markus Armbruster
Quoted 45 lines · John Snow
Quoted 2 lines · Markus Armbruster
Spelling nitpick: s/builtin/built-in/ in the title.
Sure.
Quoted 29 lines
Quoted 13 lines · John Snow
We use None to represent an object that has no source information because it's a builtin. This complicates interface typing, since many interfaces expect that there is an info object available to print errors with.
Introduce a special QAPISourceInfo that represents these built-ins so that if an error should so happen to occur relating to one of these builtins that we will be able to print its information, and interface typing becomes simpler: you will always have a source info object.
This object will evaluate as False, so "if info" remains a valid idiomatic construct.
Quoted 6 lines
NB: It was intentional to not allow empty constructors or similar to create "empty" source info objects; callers must explicitly invoke '
builtin()' to pro-actively opt into using the sentinel. This should prevent use-by-accident.Signed-off-by John Snow <[email protected]>As I pointed out in review of v1, this patch has two aspects mixed up:
1. Represent "no source info" as special QAPISourceInfo instead of None
2. On error with "no source info", don't crash.
Quoted 9 lines
The first one is what de-complicates interface typing. It's clearly serving this patch series' stated purpose: "static typing conversion".
The second one is not. It sidetracks us into a design discussion that isn't related to static typing. Maybe it's something we should discuss. Maybe the discussion will make us conclude we want to do this. But letting the static typing work get delayed by that discussion would be stupid, and I'll do what I can to prevent that.
Quoted 6 lines
It's not unrelated. It's about finding the most tactical incision to make the types as we actually use them correct from a static analysis context.
Maybe there's another tactical incision to make that's "smaller", for some perception of "smaller", but it's not unrelated.
We don't have to debate, let alone agree on relatedness.
Quoted 8 lines
Quoted 7 lines
The stupidest possible solution that preserves the crash is adding an assertion right where it crashes before this patch: in
QAPISourceInfo.__str__(). Yes, crashing in a__str__()method is not nice, but it's no worse than before. Making it better than before is a good idea, and you're quite welcome to try, but please not in this series. Add a TODO comment asking for "make it better", then sit on your hands.Quoted 7 lines
I'm recently back from a fairly long PTO, so forgive me if I am forgetting something, but I am not really sure I fundamentally understand the nature of this critique.
Making functions not "crash" is a side-effect of making the types correct. I don't see it as scope-creep, it's a solution to a problem under active consideration.
I disagree.
The crash you "fix" is *intentional*. I was too lazy to write something like
assert self.info
and instead relied in self.info.whatever to crash. I don't care how it crashes, as long as it does crash.
I *like* qapi-gen to crash on such internal errors. It's easy, and makes "this is a bug, go report it" perfectly clear.
Quoted 7 lines
I'd also be fine with reporting "internal error, this is a bug, go report it". Not in this series, unless it's utterly trivial, which I doubt.
I'm *not* fine with feeding made-up info objects to the user error reporting machinery without proof that it'll actually produce a useful error message. Definitely not trivial, thus not in this series.
If you really don't want to change the existing behavior of the code, I believe we have only two options:
1) Annotate self.info as QAPISourceInfo (not Optional), and add a hack to make the expression self.info crash if the argument to __init__() was None.
2) Annotate self.info as Optional[QAPISourceInfo], and adding manual asserts everywhere self.info is used.
Which of those two options do you find acceptable, Markus?
Signature · 1 line
Eduardo
Re: [PATCH v2 06/12] qapi/source: Add builtin null-object sentinel
Quoted 94 lines · Eduardo Habkost
Quoted 85 lines · Markus Armbruster
Quoted 45 lines · John Snow
Quoted 2 lines · Markus Armbruster
Spelling nitpick: s/builtin/built-in/ in the title.
Sure.
Quoted 29 lines
Quoted 13 lines · John Snow
We use None to represent an object that has no source information because it's a builtin. This complicates interface typing, since many interfaces expect that there is an info object available to print errors with.
Introduce a special QAPISourceInfo that represents these built-ins so that if an error should so happen to occur relating to one of these builtins that we will be able to print its information, and interface typing becomes simpler: you will always have a source info object.
This object will evaluate as False, so "if info" remains a valid idiomatic construct.
Quoted 6 lines
NB: It was intentional to not allow empty constructors or similar to create "empty" source info objects; callers must explicitly invoke '
builtin()' to pro-actively opt into using the sentinel. This should prevent use-by-accident.Signed-off-by John Snow <[email protected]>As I pointed out in review of v1, this patch has two aspects mixed up:
1. Represent "no source info" as special QAPISourceInfo instead of None
2. On error with "no source info", don't crash.
Quoted 9 lines
The first one is what de-complicates interface typing. It's clearly serving this patch series' stated purpose: "static typing conversion".
The second one is not. It sidetracks us into a design discussion that isn't related to static typing. Maybe it's something we should discuss. Maybe the discussion will make us conclude we want to do this. But letting the static typing work get delayed by that discussion would be stupid, and I'll do what I can to prevent that.
Quoted 6 lines
It's not unrelated. It's about finding the most tactical incision to make the types as we actually use them correct from a static analysis context.
Maybe there's another tactical incision to make that's "smaller", for some perception of "smaller", but it's not unrelated.
We don't have to debate, let alone agree on relatedness.
Quoted 8 lines
Quoted 7 lines
The stupidest possible solution that preserves the crash is adding an assertion right where it crashes before this patch: in
QAPISourceInfo.__str__(). Yes, crashing in a__str__()method is not nice, but it's no worse than before. Making it better than before is a good idea, and you're quite welcome to try, but please not in this series. Add a TODO comment asking for "make it better", then sit on your hands.Quoted 7 lines
I'm recently back from a fairly long PTO, so forgive me if I am forgetting something, but I am not really sure I fundamentally understand the nature of this critique.
Making functions not "crash" is a side-effect of making the types correct. I don't see it as scope-creep, it's a solution to a problem under active consideration.
I disagree.
The crash you "fix" is *intentional*. I was too lazy to write something like
assert self.info
and instead relied in self.info.whatever to crash. I don't care how it crashes, as long as it does crash.
I *like* qapi-gen to crash on such internal errors. It's easy, and makes "this is a bug, go report it" perfectly clear.
Quoted 7 lines
I'd also be fine with reporting "internal error, this is a bug, go report it". Not in this series, unless it's utterly trivial, which I doubt.
I'm *not* fine with feeding made-up info objects to the user error reporting machinery without proof that it'll actually produce a useful error message. Definitely not trivial, thus not in this series.
Quoted 6 lines
If you really don't want to change the existing behavior of the code, I believe we have only two options:
1) Annotate self.info as QAPISourceInfo (not Optional), and add a hack to make the expression
self.infocrash if the argument to__init__()was None.
I figure you mean
* Represent "no info" as a special QAPISourceInfo (instead of None), so we can annotate .info as QAPISourceInfo (not Optional).
* When we report a QAPIError, assert .info is not this special value.
This preserves the existing (and intentional) behavior: we crash when we dot into QAPISourceInfo, and we do that only when we report a QAPIError with that info.
The only change in behavior is AssertionError instead of AttributeError. Minor improvement.
We could replace the AssertionError crash by a fatal error with suitably worded error message. I'd prefer not to, because I'd rather keep the stack backtrace. Admittedly not something I'd fight for.
Quoted 4 lines
2) Annotate self.info as Optional[QAPISourceInfo], and adding manual asserts everywhere self.info is used.
Which of those two options do you find acceptable, Markus?
I think John prefers (1), because the typing gets simpler. I'm inclined to leave the decision to him.
Re: [PATCH v2 06/12] qapi/source: Add builtin null-object sentinel
Quoted 103 lines · Markus Armbruster
Quoted 94 lines · Eduardo Habkost
Quoted 85 lines · Markus Armbruster
Quoted 45 lines · John Snow
Quoted 2 lines · Markus Armbruster
Spelling nitpick: s/builtin/built-in/ in the title.
Sure.
Quoted 29 lines
Quoted 13 lines · John Snow
We use None to represent an object that has no source information because it's a builtin. This complicates interface typing, since many interfaces expect that there is an info object available to print errors with.
Introduce a special QAPISourceInfo that represents these built-ins so that if an error should so happen to occur relating to one of these builtins that we will be able to print its information, and interface typing becomes simpler: you will always have a source info object.
This object will evaluate as False, so "if info" remains a valid idiomatic construct.
Quoted 6 lines
NB: It was intentional to not allow empty constructors or similar to create "empty" source info objects; callers must explicitly invoke '
builtin()' to pro-actively opt into using the sentinel. This should prevent use-by-accident.Signed-off-by John Snow <[email protected]>As I pointed out in review of v1, this patch has two aspects mixed up:
1. Represent "no source info" as special QAPISourceInfo instead of None
2. On error with "no source info", don't crash.
Quoted 9 lines
The first one is what de-complicates interface typing. It's clearly serving this patch series' stated purpose: "static typing conversion".
The second one is not. It sidetracks us into a design discussion that isn't related to static typing. Maybe it's something we should discuss. Maybe the discussion will make us conclude we want to do this. But letting the static typing work get delayed by that discussion would be stupid, and I'll do what I can to prevent that.
Quoted 6 lines
It's not unrelated. It's about finding the most tactical incision to make the types as we actually use them correct from a static analysis context.
Maybe there's another tactical incision to make that's "smaller", for some perception of "smaller", but it's not unrelated.
We don't have to debate, let alone agree on relatedness.
Quoted 8 lines
Quoted 7 lines
The stupidest possible solution that preserves the crash is adding an assertion right where it crashes before this patch: in
QAPISourceInfo.__str__(). Yes, crashing in a__str__()method is not nice, but it's no worse than before. Making it better than before is a good idea, and you're quite welcome to try, but please not in this series. Add a TODO comment asking for "make it better", then sit on your hands.Quoted 7 lines
I'm recently back from a fairly long PTO, so forgive me if I am forgetting something, but I am not really sure I fundamentally understand the nature of this critique.
Making functions not "crash" is a side-effect of making the types correct. I don't see it as scope-creep, it's a solution to a problem under active consideration.
I disagree.
The crash you "fix" is *intentional*. I was too lazy to write something like
assert self.info
and instead relied in self.info.whatever to crash. I don't care how it crashes, as long as it does crash.
I *like* qapi-gen to crash on such internal errors. It's easy, and makes "this is a bug, go report it" perfectly clear.
Quoted 7 lines
I'd also be fine with reporting "internal error, this is a bug, go report it". Not in this series, unless it's utterly trivial, which I doubt.
I'm *not* fine with feeding made-up info objects to the user error reporting machinery without proof that it'll actually produce a useful error message. Definitely not trivial, thus not in this series.
Quoted 6 lines
If you really don't want to change the existing behavior of the code, I believe we have only two options:
1) Annotate self.info as QAPISourceInfo (not Optional), and add a hack to make the expression
self.infocrash if the argument to__init__()was None.
Quoted 6 lines
I figure you mean
* Represent "no info" as a special QAPISourceInfo (instead of None), so we can annotate .info as QAPISourceInfo (not Optional).
* When we report a QAPIError, assert .info is not this special value.
Not necessarily. Creating a special QAPISourceInfo would be one solution to let us annotate self.info as non-Optional, but not the only one.
Possibly the simplest way to declare self.info as non-Optional is to make it a property that hides an Optional attribute. e.g.:
class ...:
_info: Optional[QAPISourceInfo]
@property
def info(self) -> QAPISourceInfo:
assert self._info is not None
return self._infoQuoted 4 lines
This preserves the existing (and intentional) behavior: we crash when we dot into QAPISourceInfo, and we do that only when we report a QAPIError with that info.
I'm not sure about the "only when we report a QAPIError" part. We seem to have multiple places in the code where self.info is assumed to never be None, and I'm not sure all of them involve QAPIError.
Quoted 15 lines
The only change in behavior is AssertionError instead of AttributeError. Minor improvement.
We could replace the AssertionError crash by a fatal error with suitably worded error message. I'd prefer not to, because I'd rather keep the stack backtrace. Admittedly not something I'd fight for.
Quoted 4 lines
2) Annotate self.info as Optional[QAPISourceInfo], and adding manual asserts everywhere self.info is used.
Which of those two options do you find acceptable, Markus?
I think John prefers (1), because the typing gets simpler. I'm inclined to leave the decision to him.
Signature · 1 line
Eduardo