diff --git a/components/script_bindings/codegen/codegen.py b/components/script_bindings/codegen/codegen.py index a0b7e47a901..4329f04b421 100644 --- a/components/script_bindings/codegen/codegen.py +++ b/components/script_bindings/codegen/codegen.py @@ -782,7 +782,7 @@ def getJSToNativeConversionInfo(type: IDLType, descriptorProvider: DescriptorPro # Helper functions for dealing with failures due to the JS value being the # wrong type of value. - def onFailureNotAnObject(failureCode: str | None) -> CGWrapper: + def onFailureNotAnObject(failureCode: str | None) -> CGThing: return CGWrapper( CGGeneric( failureCode @@ -4207,9 +4207,17 @@ class CGPerSignatureCall(CGThing): # have ways of flagging things like JSContext* or optional_argc in # there. - def __init__(self, returnType: IDLType | None, argsPre: list[str], arguments: list[IDLArgument | FakeArgument], nativeMethodName: str, static: bool, - descriptor: Descriptor, idlNode: IDLMethod, argConversionStartsAt: int = 0, - getter: bool = False, setter: bool = False) -> None: + def __init__(self, + returnType: IDLType | None, + argsPre: list[str], + arguments: list[IDLArgument | FakeArgument], + nativeMethodName: str, + static: bool, + descriptor: Descriptor, + idlNode: IDLInterfaceMember, + argConversionStartsAt: int = 0, + getter: bool = False, + setter: bool = False) -> None: CGThing.__init__(self) self.returnType = returnType self.descriptor = descriptor @@ -4230,7 +4238,7 @@ class CGPerSignatureCall(CGThing): if self.isFallible(): errorResult = " false" - if idlNode.isMethod() and idlNode.isMaplikeOrSetlikeOrIterableMethod(): + if isinstance(idlNode, IDLMethod) and idlNode.isMethod() and idlNode.isMaplikeOrSetlikeOrIterableMethod(): assert idlNode.maplikeOrSetlikeOrIterable is not None if idlNode.maplikeOrSetlikeOrIterable.isMaplike() or \ idlNode.maplikeOrSetlikeOrIterable.isSetlike(): @@ -4269,7 +4277,7 @@ class CGPerSignatureCall(CGThing): # use stronger types so we need to exclude them from being handled like other # generated code. if returnTypeNeedsOutparam(self.returnType) and ( - not (self.idlNode.isMethod() and self.idlNode.isMaplikeOrSetlikeOrIterableMethod())): + not (isinstance(self.idlNode, IDLMethod) and self.idlNode.isMethod() and self.idlNode.isMaplikeOrSetlikeOrIterableMethod())): resultName = "retval" return wrapForType( 'MutableHandleValue::from_raw(args.rval())', @@ -4333,7 +4341,7 @@ class CGGetterCall(CGPerSignatureCall): A class to generate a native object getter call for a particular IDL getter. """ - def __init__(self, argsPre: list[str], returnType: IDLType | None, nativeMethodName: str, descriptor: Descriptor, attr: IDLMethod) -> None: + def __init__(self, argsPre: list[str], returnType: IDLType | None, nativeMethodName: str, descriptor: Descriptor, attr: IDLAttribute) -> None: CGPerSignatureCall.__init__(self, returnType, argsPre, [], nativeMethodName, attr.isStatic(), descriptor, attr, getter=True) @@ -4363,7 +4371,7 @@ class CGSetterCall(CGPerSignatureCall): A class to generate a native object setter call for a particular IDL setter. """ - def __init__(self, argsPre: list[str], argType: IDLType, nativeMethodName: str, descriptor: Descriptor, attr: IDLMethod) -> None: + def __init__(self, argsPre: list[str], argType: IDLType, nativeMethodName: str, descriptor: Descriptor, attr: IDLAttribute) -> None: CGPerSignatureCall.__init__(self, None, argsPre, [FakeArgument(argType, attr, allowTreatNonObjectAsNull=True)], nativeMethodName, attr.isStatic(), descriptor, attr, @@ -4518,11 +4526,11 @@ class CGGetterPromiseWrapper(CGAbstractExternMethod): )) @staticmethod - def makeOrigName(descriptor: Descriptor, m: IDLMethod) -> str: + def makeOrigName(descriptor: Descriptor, m: IDLInterfaceMember) -> str: return f'get_{descriptor.internalNameFor(m.identifier.name)}' @staticmethod - def makeNativeName(descriptor: Descriptor, m: IDLMethod) -> str: + def makeNativeName(descriptor: Descriptor, m: IDLInterfaceMember) -> str: return f"{CGGetterPromiseWrapper.makeOrigName(descriptor, m)}_promise_wrapper" @@ -4588,7 +4596,7 @@ class CGSpecializedGetter(CGAbstractExternMethod): A class for generating the code for a specialized attribute getter that the JIT can call with lower overhead. """ - def __init__(self, descriptor, attr): + def __init__(self, descriptor: Descriptor, attr: IDLAttribute) -> None: self.attr = attr name = f'get_{descriptor.internalNameFor(attr.identifier.name)}' args = [Argument('*mut JSContext', 'cx'), @@ -4597,7 +4605,7 @@ class CGSpecializedGetter(CGAbstractExternMethod): Argument('JSJitGetterCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, "bool", args, templateArgs=["D: DomTypes"]) - def definition_body(self): + def definition_body(self) -> CGThing: nativeName = CGSpecializedGetter.makeNativeName(self.descriptor, self.attr) @@ -4607,7 +4615,7 @@ class CGSpecializedGetter(CGAbstractExternMethod): f"let this = &*(this as *const {self.descriptor.concreteType});\n") @staticmethod - def makeNativeName(descriptor, attr): + def makeNativeName(descriptor: Descriptor, attr: IDLAttribute) -> str: name = attr.identifier.name nativeName = descriptor.binaryNameFor(name, attr.isStatic()) if nativeName == name: @@ -4625,12 +4633,12 @@ class CGStaticGetter(CGAbstractStaticBindingMethod): """ A class for generating the C++ code for an IDL static attribute getter. """ - def __init__(self, descriptor, attr): + def __init__(self, descriptor: Descriptor, attr: IDLAttribute) -> None: self.attr = attr name = f'get_{attr.identifier.name}' CGAbstractStaticBindingMethod.__init__(self, descriptor, name, templateArgs=["D: DomTypes"]) - def generate_code(self): + def generate_code(self) -> CGThing: nativeName = CGSpecializedGetter.makeNativeName(self.descriptor, self.attr) safeContext = CGGeneric("let cx = SafeJSContext::from_ptr(cx);\n") @@ -4645,7 +4653,7 @@ class CGSpecializedSetter(CGAbstractExternMethod): A class for generating the code for a specialized attribute setter that the JIT can call with lower overhead. """ - def __init__(self, descriptor, attr): + def __init__(self, descriptor: Descriptor, attr: IDLAttribute) -> None: self.attr = attr name = f'set_{descriptor.internalNameFor(attr.identifier.name)}' args = [Argument('*mut JSContext', 'cx'), @@ -4664,7 +4672,7 @@ class CGSpecializedSetter(CGAbstractExternMethod): ) @staticmethod - def makeNativeName(descriptor, attr): + def makeNativeName(descriptor: Descriptor, attr: IDLAttribute) -> str: name = attr.identifier.name nativeName = descriptor.binaryNameFor(name, attr.isStatic()) if nativeName == name: @@ -4676,12 +4684,12 @@ class CGStaticSetter(CGAbstractStaticBindingMethod): """ A class for generating the C++ code for an IDL static attribute setter. """ - def __init__(self, descriptor, attr): + def __init__(self, descriptor: Descriptor, attr: IDLAttribute) -> None: self.attr = attr name = f'set_{attr.identifier.name}' CGAbstractStaticBindingMethod.__init__(self, descriptor, name, templateArgs=["D: DomTypes"]) - def generate_code(self): + def generate_code(self) -> CGThing: nativeName = CGSpecializedSetter.makeNativeName(self.descriptor, self.attr) safeContext = CGGeneric("let cx = SafeJSContext::from_ptr(cx);\n") @@ -4700,12 +4708,14 @@ class CGSpecializedForwardingSetter(CGSpecializedSetter): """ A class for generating the code for an IDL attribute forwarding setter. """ - def __init__(self, descriptor, attr): + def __init__(self, descriptor: Descriptor, attr: IDLAttribute) -> None: CGSpecializedSetter.__init__(self, descriptor, attr) - def definition_body(self): + def definition_body(self) -> CGThing: attrName = self.attr.identifier.name - forwardToAttrName = self.attr.getExtendedAttribute("PutForwards")[0] + forwardToAttr = self.attr.getExtendedAttribute("PutForwards") + assert forwardToAttr is not None + forwardToAttrName = forwardToAttr[0] # JS_GetProperty and JS_SetProperty can only deal with ASCII assert all(ord(c) < 128 for c in attrName) assert all(ord(c) < 128 for c in forwardToAttrName) @@ -4728,10 +4738,10 @@ class CGSpecializedReplaceableSetter(CGSpecializedSetter): """ A class for generating the code for an IDL replaceable attribute setter. """ - def __init__(self, descriptor, attr): + def __init__(self, descriptor: Descriptor, attr: IDLAttribute) -> None: CGSpecializedSetter.__init__(self, descriptor, attr) - def definition_body(self): + def definition_body(self) -> CGThing: assert self.attr.readonly name = str_to_cstr_ptr(self.attr.identifier.name) # JS_DefineProperty can only deal with ASCII. @@ -4746,13 +4756,13 @@ class CGMemberJITInfo(CGThing): A class for generating the JITInfo for a property that points to our specialized getter and setter. """ - def __init__(self, descriptor, member): + def __init__(self, descriptor: Descriptor, member: IDLInterfaceMember) -> None: self.member = member self.descriptor = descriptor - def defineJitInfo(self, infoName, opName, opType, infallible, movable, - aliasSet, alwaysInSlot, lazilyInSlot, slotIndex, - returnTypes, args): + def defineJitInfo(self, infoName: str, opName: str, opType: str, infallible: bool, movable: bool, + aliasSet: str, alwaysInSlot: bool, lazilyInSlot: bool, slotIndex: str, + returnTypes: list[IDLType], args: list[IDLArgument] | None) -> str: """ aliasSet is a JSJitInfo_AliasSet value, without the "JSJitInfo_AliasSet::" bit. @@ -4763,7 +4773,7 @@ class CGMemberJITInfo(CGThing): assert not movable or aliasSet != "AliasEverything" # Can't move write-aliasing things assert not alwaysInSlot or movable # Things always in slots had better be movable - def jitInfoInitializer(isTypedMethod): + def jitInfoInitializer(isTypedMethod: bool) -> str: initializer = fill( """ JSJitInfo { @@ -4793,7 +4803,7 @@ class CGMemberJITInfo(CGThing): """, opValue=f"Some({opName}::)", name=self.descriptor.name, - depth=self.descriptor.interface.inheritanceDepth(), + depth=str(self.descriptor.interface.inheritanceDepth()), opType=opType, opKind=opType.lower(), aliasSet=aliasSet, @@ -4810,10 +4820,10 @@ class CGMemberJITInfo(CGThing): return initializer.rstrip() if args is not None: - argTypes = f"{infoName}_argTypes" - args = [CGMemberJITInfo.getJSArgType(arg.type) for arg in args] - args.append("JSJitInfo_ArgType::ArgTypeListEnd as i32") - argTypesDecl = f"const {argTypes}: [i32; {len(args)}] = [ {', '.join(args)} ];\n" + argTypesArray = f"{infoName}_argTypes" + argTypes = [CGMemberJITInfo.getJSArgType(arg.type) for arg in args] + argTypes.append("JSJitInfo_ArgType::ArgTypeListEnd as i32") + argTypesDecl = f"const {argTypesArray}: [i32; {len(argTypes)}] = [ {', '.join(argTypes)} ];\n" return fill( """ $*{argTypesDecl} @@ -4829,7 +4839,7 @@ class CGMemberJITInfo(CGThing): argTypesDecl=argTypesDecl, infoName=infoName, jitInfoInit=indent(jitInfoInitializer(True)), - argTypes=argTypes) + argTypes=argTypesArray) return f""" static {infoName}: ThreadUnsafeOnceLock = ThreadUnsafeOnceLock::new(); @@ -4838,8 +4848,9 @@ pub(crate) fn init_{infoName}() {{ {infoName}.set({jitInfoInitializer(False)}); }}""" - def define(self): + def define(self) -> str: if self.member.isAttr(): + assert isinstance(self.member, IDLAttribute) internalMemberName = self.descriptor.internalNameFor(self.member.identifier.name) getterinfo = f"{internalMemberName}_getterinfo" getter = f"get_{internalMemberName}" @@ -4850,7 +4861,7 @@ pub(crate) fn init_{infoName}() {{ movable = self.mayBeMovable() and getterinfal aliasSet = self.aliasSet() - isAlwaysInSlot = self.member.getExtendedAttribute("StoreInSlot") + isAlwaysInSlot = self.member.getExtendedAttribute("StoreInSlot") or False if self.member.slotIndices is not None: assert isAlwaysInSlot or self.member.getExtendedAttribute("Cached") isLazilyCachedInSlot = not isAlwaysInSlot @@ -4881,6 +4892,7 @@ pub(crate) fn init_{infoName}() {{ None) return result if self.member.isMethod(): + assert isinstance(self.member, IDLMethod) methodinfo = f"{self.member.identifier.name}_methodinfo" method = f"{self.member.identifier.name}" if self.member.returnsPromise(): @@ -4926,7 +4938,7 @@ pub(crate) fn init_{infoName}() {{ return result raise TypeError("Illegal member type to CGPropertyJITInfo") - def mayBeMovable(self): + def mayBeMovable(self) -> bool: """ Returns whether this attribute or method may be movable, just based on Affects/DependsOn annotations. @@ -4942,7 +4954,7 @@ pub(crate) fn init_{infoName}() {{ return (affects == "Nothing" and (dependsOn != "Everything" and dependsOn != "DeviceState")) - def aliasSet(self): + def aliasSet(self) -> str: """Returns the alias set to store in the jitinfo. This may not be the effective alias set the JIT uses, depending on whether we have enough information about our args to allow the JIT to prove that effectful @@ -4963,7 +4975,7 @@ pub(crate) fn init_{infoName}() {{ return "AliasEverything" @staticmethod - def getJSReturnTypeTag(t): + def getJSReturnTypeTag(t: IDLType) -> str: if t.nullable(): # Sometimes it might return null, sometimes not return "JSVAL_TYPE_UNKNOWN" @@ -4993,9 +5005,11 @@ pub(crate) fn init_{infoName}() {{ return "JSVAL_TYPE_OBJECT" if t.isUnion(): u = t.unroll() + assert isinstance(u, IDLUnionType) if u.hasNullableType: # Might be null or not return "JSVAL_TYPE_UNKNOWN" + assert u.flatMemberTypes is not None return functools.reduce(CGMemberJITInfo.getSingleReturnType, u.flatMemberTypes, "") if t.isDictionary(): @@ -5022,7 +5036,7 @@ pub(crate) fn init_{infoName}() {{ return "JSVAL_TYPE_DOUBLE" @staticmethod - def getSingleReturnType(existingType, t): + def getSingleReturnType(existingType: str, t: IDLType) -> str: type = CGMemberJITInfo.getJSReturnTypeTag(t) if existingType == "": # First element of the list; just return its type @@ -5040,10 +5054,11 @@ pub(crate) fn init_{infoName}() {{ return "JSVAL_TYPE_UNKNOWN" @staticmethod - def getJSArgType(t): + def getJSArgType(t: IDLType) -> str: assert not t.isUndefined() if t.nullable(): # Sometimes it might return null, sometimes not + assert isinstance(t, IDLNullableType) return f"JSJitInfo_ArgType::Null as i32 | {CGMemberJITInfo.getJSArgType(t.inner)}" if t.isSequence(): return "JSJitInfo_ArgType::Object as i32" @@ -5064,6 +5079,7 @@ pub(crate) fn init_{infoName}() {{ return "JSJitInfo_ArgType::Object as i32" if t.isUnion(): u = t.unroll() + assert isinstance(u, IDLUnionType) and u.flatMemberTypes is not None type = "JSJitInfo_ArgType::Null as i32" if u.hasNullableType else "" return functools.reduce(CGMemberJITInfo.getSingleArgType, u.flatMemberTypes, type) @@ -5091,7 +5107,7 @@ pub(crate) fn init_{infoName}() {{ return "JSJitInfo_ArgType::Double as i32" @staticmethod - def getSingleArgType(existingType, t): + def getSingleArgType(existingType: str, t: IDLType) -> str: type = CGMemberJITInfo.getJSArgType(t) if existingType == "": # First element of the list; just return its type @@ -5108,7 +5124,7 @@ class CGStaticMethodJitinfo(CGGeneric): A class for generating the JITInfo for a promise-returning static method. """ - def __init__(self, method): + def __init__(self, method: IDLMethod) -> None: CGGeneric.__init__( self, f""" @@ -5166,7 +5182,7 @@ def getEnumValueName(value: str) -> str: class CGEnum(CGThing): - def __init__(self, enum, config): + def __init__(self, enum: IDLEnum, config: Configuration) -> None: CGThing.__init__(self) ident = enum.identifier.name @@ -5252,7 +5268,7 @@ impl FromJSValConvertible for super::{ident} {{ CGIndenter(CGGeneric(inner)), public=True), ]) - def define(self): + def define(self) -> str: return self.cgRoot.define() @@ -5273,11 +5289,11 @@ def convertConstIDLValueToRust(value: IDLConst) -> str: class CGConstant(CGThing): - def __init__(self, constant): + def __init__(self, constant: IDLConst) -> None: CGThing.__init__(self) self.constant = constant - def define(self): + def define(self) -> str: name = self.constant.identifier.name value = convertConstIDLValueToRust(self.constant.value) @@ -5365,7 +5381,7 @@ def traitRequiresManualImpl(name: str, ty: IDLObject) -> bool: class CGUnionStruct(CGThing): - def __init__(self, type, descriptorProvider, config): + def __init__(self, type: IDLUnionType, descriptorProvider: DescriptorProvider, config: Configuration) -> None: assert not type.nullable() assert not type.hasNullableType @@ -5378,13 +5394,14 @@ class CGUnionStruct(CGThing): self.generic, self.genericSuffix = genericsForType(self.type) - def membersNeedTracing(self): + def membersNeedTracing(self) -> bool: + assert self.type.flatMemberTypes is not None for t in self.type.flatMemberTypes: if type_needs_tracing(t): return True return False - def manualImplClone(self, templateVars): + def manualImplClone(self, templateVars: list[tuple[dict[str, Any], str]]) -> str: arms = [f" {self.type}::{v['name']}(inner) => " f"{self.type}::{v['name']}(inner.clone())," for (v, _) in templateVars] @@ -5400,19 +5417,20 @@ impl{self.generic} Clone for {self.type}{self.genericSuffix} {{ }} """ - def manualImpl(self, t, templateVars): + def manualImpl(self, t: str, templateVars: list[tuple[dict[str, Any], str]]) -> str: if t == "Clone": return self.manualImplClone(templateVars) raise ValueError(f"Don't know how to impl {t} for union") - def define(self): - def getTypeWrapper(t): + def define(self) -> str: + def getTypeWrapper(t: IDLType) -> str: if type_needs_tracing(t): return "RootedTraceableBox" if t.isCallback(): return "Rc" return "" + assert self.type.flatMemberTypes is not None templateVars = [(getUnionTypeTemplateVars(t, self.descriptorProvider), getTypeWrapper(t)) for t in self.type.flatMemberTypes] enumValues = [ @@ -5446,7 +5464,7 @@ impl{self.generic} ToJSValConvertible for {self.type}{self.genericSuffix} {{ class CGUnionConversionStruct(CGThing): - def __init__(self, type, descriptorProvider): + def __init__(self, type, descriptorProvider) -> None: assert not type.nullable() assert not type.hasNullableType @@ -5454,13 +5472,13 @@ class CGUnionConversionStruct(CGThing): self.type = type self.descriptorProvider = descriptorProvider - def membersNeedTracing(self): + def membersNeedTracing(self) -> bool: for t in self.type.flatMemberTypes: if type_needs_tracing(t): return True return False - def from_jsval(self): + def from_jsval(self) -> CGThing: memberTypes = self.type.flatMemberTypes names = [] conversions = [] @@ -5471,7 +5489,7 @@ class CGUnionConversionStruct(CGThing): return memberType.name - def get_match(name) -> str: + def get_match(name: str) -> str: generic = "::" if containsDomInterface(self.type) else "" return ( f"match {self.type}{generic}::TryConvertTo{name}(SafeJSContext::from_ptr(cx), value) {{\n" @@ -5567,7 +5585,7 @@ class CGUnionConversionStruct(CGThing): assert len(booleanTypes) <= 1 assert numUndefinedVariants <= 1 - def getStringOrPrimitiveConversion(memberType): + def getStringOrPrimitiveConversion(memberType) -> CGThing: typename = get_name(memberType) return CGGeneric(get_match(typename)) @@ -5618,7 +5636,7 @@ class CGUnionConversionStruct(CGThing): pre=f"impl{generic} FromJSValConvertible for {self.type}{genericSuffix} {{\n", post="\n}") - def try_method(self, t): + def try_method(self, t) -> CGThing | CGWrapper: if t.isUndefined(): # undefined does not require a conversion method, so we don't generate one return CGGeneric("") @@ -5637,7 +5655,7 @@ class CGUnionConversionStruct(CGThing): pre=f"unsafe fn TryConvertTo{t.name}(cx: SafeJSContext, value: HandleValue) -> {returnType} {{\n", post="\n}") - def define(self): + def define(self) -> str: from_jsval = self.from_jsval() methods = CGIndenter(CGList([ self.try_method(t) for t in self.type.flatMemberTypes @@ -5654,7 +5672,7 @@ impl{generic} {self.type}{genericSuffix} {{ class ClassItem: """ Use with CGClass """ - def __init__(self, name, visibility): + def __init__(self, name, visibility) -> None: self.name = name self.visibility = visibility @@ -5666,10 +5684,10 @@ class ClassItem: class ClassBase(ClassItem): - def __init__(self, name, visibility='pub'): + def __init__(self, name, visibility='pub') -> None: ClassItem.__init__(self, name, visibility) - def declare(self, cgClass): + def declare(self, cgClass) -> str: return f'{self.visibility} {self.name}' def define(self, cgClass) -> str | None: @@ -5754,7 +5772,7 @@ class ClassMethod(ClassItem): f"{returnType}{const}{override}{body}{self.breakAfterSelf}" ) - def define(self, cgClass): + def define(self, cgClass) -> None: pass @@ -5782,7 +5800,7 @@ class ClassConstructor(ClassItem): """ def __init__(self, args, inline=False, bodyInHeader=False, visibility="priv", explicit=False, baseConstructors=None, - body=""): + body="") -> None: self.args = args self.inline = False self.bodyInHeader = bodyInHeader @@ -5791,7 +5809,7 @@ class ClassConstructor(ClassItem): self.body = body ClassItem.__init__(self, None, visibility) - def getDecorators(self, declaring): + def getDecorators(self, declaring: bool) -> str: decorators = [] if self.explicit: decorators.append('explicit') @@ -5801,7 +5819,7 @@ class ClassConstructor(ClassItem): return f'{" ".join(decorators)} ' return '' - def getInitializationList(self, cgClass): + def getInitializationList(self, cgClass) -> str: items = [str(c) for c in self.baseConstructors] for m in cgClass.members: if not m.static: @@ -5814,7 +5832,7 @@ class ClassConstructor(ClassItem): return f'\n : {joinedItems}' return '' - def getBody(self, cgClass): + def getBody(self, cgClass) -> str: initializers = [f" parent: {self.baseConstructors[0]}"] joinedInitializers = '\n'.join(initializers) return ( @@ -5830,7 +5848,7 @@ class ClassConstructor(ClassItem): "ret" ) - def declare(self, cgClass): + def declare(self, cgClass) -> str: args = ', '.join([a.declare() for a in self.args]) body = f' {self.getBody(cgClass)}' body = stripTrailingWhitespace(body.replace('\n', '\n ')) @@ -5843,7 +5861,7 @@ class ClassConstructor(ClassItem): pub unsafe fn {self.getDecorators(True)}new({args}) -> Rc<{name}>{body} """ - def define(self, cgClass): + def define(self, cgClass) -> str: if self.bodyInHeader: return '' @@ -5865,16 +5883,16 @@ pub unsafe fn {self.getDecorators(True)}new({args}) -> Rc<{name}>{body} class ClassMember(ClassItem): def __init__(self, name, type, visibility="priv", static=False, - body=None): + body=None) -> None: self.type = type self.static = static self.body = body ClassItem.__init__(self, name, visibility) - def declare(self, cgClass): + def declare(self, cgClass) -> str: return f'{self.visibility} {self.name}: {self.type},\n' - def define(self, cgClass): + def define(self, cgClass) -> str: if not self.static: return '' if self.body: @@ -5886,12 +5904,12 @@ class ClassMember(ClassItem): class CGClass(CGThing): def __init__(self, name, bases=[], members=[], constructors=[], - destructor=None, methods=[], + destructor: ClassItem | None=None, methods=[], typedefs=[], enums=[], unions=[], templateArgs=[], templateSpecialization=[], disallowCopyConstruction=False, indent='', decorators='', - extradeclarations=''): + extradeclarations='') -> None: CGThing.__init__(self) self.name = name self.bases = bases @@ -5917,7 +5935,7 @@ class CGClass(CGThing): className = f"{className}<{', '.join([str(a) for a in self.templateSpecialization])}>" return className - def define(self): + def define(self) -> str: result = '' if self.templateArgs: templateArgs = [a.declare() for a in self.templateArgs] @@ -5945,7 +5963,7 @@ class CGClass(CGThing): result += CGIndenter(CGGeneric(self.extradeclarations), len(self.indent)).define() - def declareMembers(cgClass, memberList): + def declareMembers(cgClass, memberList) -> str: result = '' for member in memberList: @@ -5956,10 +5974,10 @@ class CGClass(CGThing): if self.disallowCopyConstruction: class DisallowedCopyConstructor(object): - def __init__(self): + def __init__(self) -> None: self.visibility = "private" - def declare(self, cgClass): + def declare(self, cgClass) -> str: name = cgClass.getNameString() return (f"{name}(const {name}&) MOZ_DELETE;\n" f"void operator=(const {name}) MOZ_DELETE;\n") @@ -5999,7 +6017,7 @@ class CGProxySpecialOperation(CGPerSignatureCall): (don't use this directly, use the derived classes below). """ templateValues: dict[str, Any] | None - def __init__(self, descriptor, operation): + def __init__(self, descriptor, operation) -> None: nativeName = MakeNativeName(descriptor.binaryNameFor(operation, False)) operation = descriptor.operations[operation] assert len(operation.signatures()) == 1 @@ -6031,12 +6049,12 @@ class CGProxySpecialOperation(CGPerSignatureCall): template, templateValues, declType, argument.identifier.name)) self.cgRoot.prepend(CGGeneric("rooted!(in(*cx) let value = desc.value_);")) - def getArguments(self): + def getArguments(self) -> list[tuple[FakeArgument | IDLArgument, str]]: args = [(a, process_arg(a.identifier.name, a)) for a in self.arguments] return args - def wrap_return_value(self): - if not self.idlNode.isGetter() or self.templateValues is None: + def wrap_return_value(self) -> str: + if isinstance(self.idlNode, IDLMethod) and not self.idlNode.isGetter() or self.templateValues is None: return "" wrap = CGGeneric(wrapForType(**self.templateValues)) @@ -6049,7 +6067,7 @@ class CGProxyIndexedGetter(CGProxySpecialOperation): Class to generate a call to an indexed getter. If templateValues is not None the returned value will be wrapped with wrapForType using templateValues. """ - def __init__(self, descriptor, templateValues=None): + def __init__(self, descriptor, templateValues=None) -> None: self.templateValues = templateValues CGProxySpecialOperation.__init__(self, descriptor, 'IndexedGetter') @@ -6058,7 +6076,7 @@ class CGProxyIndexedSetter(CGProxySpecialOperation): """ Class to generate a call to an indexed setter. """ - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: CGProxySpecialOperation.__init__(self, descriptor, 'IndexedSetter') @@ -6066,10 +6084,10 @@ class CGProxyNamedOperation(CGProxySpecialOperation): """ Class to generate a call to a named operation. """ - def __init__(self, descriptor, name): + def __init__(self, descriptor, name) -> None: CGProxySpecialOperation.__init__(self, descriptor, name) - def define(self): + def define(self) -> str: # Our first argument is the id we're getting. argName = self.arguments[0].identifier.name return (f'let {argName} = jsid_to_string(*cx, Handle::from_raw(id)).expect("Not a string-convertible JSID?");\n' @@ -6083,7 +6101,7 @@ class CGProxyNamedGetter(CGProxyNamedOperation): Class to generate a call to an named getter. If templateValues is not None the returned value will be wrapped with wrapForType using templateValues. """ - def __init__(self, descriptor, templateValues=None): + def __init__(self, descriptor, templateValues=None) -> None: self.templateValues = templateValues CGProxySpecialOperation.__init__(self, descriptor, 'NamedGetter') @@ -6093,7 +6111,7 @@ class CGProxyNamedPresenceChecker(CGProxyNamedGetter): Class to generate a call that checks whether a named property exists. For now, we just delegate to CGProxyNamedGetter """ - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: CGProxyNamedGetter.__init__(self, descriptor) @@ -6101,7 +6119,7 @@ class CGProxyNamedSetter(CGProxyNamedOperation): """ Class to generate a call to a named setter. """ - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: CGProxySpecialOperation.__init__(self, descriptor, 'NamedSetter') @@ -6109,10 +6127,10 @@ class CGProxyNamedDeleter(CGProxyNamedOperation): """ Class to generate a call to a named deleter. """ - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: CGProxySpecialOperation.__init__(self, descriptor, 'NamedDeleter') - def define(self): + def define(self) -> str: # Our first argument is the id we're getting. argName = self.arguments[0].identifier.name return ("if !id.is_symbol() {\n" @@ -6130,14 +6148,14 @@ class CGProxyNamedDeleter(CGProxyNamedOperation): class CGProxyUnwrap(CGAbstractMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('RawHandleObject', 'obj')] CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", f'*const {descriptor.concreteType}', args, alwaysInline=True, unsafe=True, templateArgs=['D: DomTypes']) - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(f""" let mut slot = UndefinedValue(); GetProxyReservedSlot(obj.get(), 0, &mut slot); @@ -6146,7 +6164,7 @@ return box_;""") class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawHandleId', 'id'), Argument('RawMutableHandle', 'mut desc'), @@ -6156,7 +6174,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): self.descriptor = descriptor # https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty - def getBody(self): + def getBody(self) -> str: indexedGetter = self.descriptor.operations['IndexedGetter'] get = "let cx = SafeJSContext::from_ptr(cx);\n" @@ -6267,12 +6285,12 @@ if !expando.is_null() {{ {namedGet}\ true""" - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawHandleId', 'id'), Argument('RawHandle', 'desc'), @@ -6280,7 +6298,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): CGAbstractExternMethod.__init__(self, descriptor, "defineProperty", "bool", args, templateArgs=['D: DomTypes']) self.descriptor = descriptor - def getBody(self): + def getBody(self) -> str: set = "let cx = SafeJSContext::from_ptr(cx);\n" if self.descriptor.isMaybeCrossOriginObject(): @@ -6327,19 +6345,19 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): set += f"return proxyhandler::define_property(*cx, {', '.join(a.name for a in self.args[1:])});" return set - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_delete(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawHandleId', 'id'), Argument('*mut ObjectOpResult', 'res')] CGAbstractExternMethod.__init__(self, descriptor, "delete", "bool", args, templateArgs=['D: DomTypes']) self.descriptor = descriptor - def getBody(self): + def getBody(self) -> str: set = "let cx = SafeJSContext::from_ptr(cx);\n" if self.descriptor.isMaybeCrossOriginObject(): @@ -6361,12 +6379,12 @@ class CGDOMJSProxyHandler_delete(CGAbstractExternMethod): set += f"return proxyhandler::delete(*cx, {', '.join(a.name for a in self.args[1:])});" return set - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawMutableHandleIdVector', 'props')] @@ -6374,7 +6392,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): templateArgs=['D: DomTypes']) self.descriptor = descriptor - def getBody(self): + def getBody(self) -> str: body = dedent( """ let cx = SafeJSContext::from_ptr(cx); @@ -6431,12 +6449,12 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): return body - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: assert (descriptor.operations["IndexedGetter"] and descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties") or descriptor.isMaybeCrossOriginObject()) @@ -6447,7 +6465,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): "getOwnEnumerablePropertyKeys", "bool", args, templateArgs=['D: DomTypes']) self.descriptor = descriptor - def getBody(self): + def getBody(self) -> str: body = dedent( """ let cx = SafeJSContext::from_ptr(cx); @@ -6490,18 +6508,18 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): return body - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawHandleId', 'id'), Argument('*mut bool', 'bp')] CGAbstractExternMethod.__init__(self, descriptor, "hasOwn", "bool", args, templateArgs=['D: DomTypes']) self.descriptor = descriptor - def getBody(self): + def getBody(self) -> str: indexedGetter = self.descriptor.operations['IndexedGetter'] indexed = "let cx = SafeJSContext::from_ptr(cx);\n" @@ -6564,12 +6582,12 @@ if !expando.is_null() {{ *bp = false; true""" - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_get(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawHandleValue', 'receiver'), Argument('RawHandleId', 'id'), Argument('RawMutableHandleValue', 'vp')] @@ -6577,7 +6595,7 @@ class CGDOMJSProxyHandler_get(CGAbstractExternMethod): self.descriptor = descriptor # https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty - def getBody(self): + def getBody(self) -> str: if self.descriptor.isMaybeCrossOriginObject(): maybeCrossOriginGet = dedent( """ @@ -6665,39 +6683,39 @@ if found {{ vp.set(UndefinedValue()); true""" - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_getPrototype(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawMutableHandleObject', 'proto')] CGAbstractExternMethod.__init__(self, descriptor, "getPrototype", "bool", args, templateArgs=["D: DomTypes"]) assert descriptor.isMaybeCrossOriginObject() self.descriptor = descriptor - def getBody(self): + def getBody(self) -> str: return dedent( """ let cx = SafeJSContext::from_ptr(cx); proxyhandler::maybe_cross_origin_get_prototype::(cx, proxy, GetProtoObject::, proto) """) - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) class CGDOMJSProxyHandler_className(CGAbstractExternMethod): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', '_proxy')] CGAbstractExternMethod.__init__(self, descriptor, "className", "*const libc::c_char", args, doesNotPanic=True) self.descriptor = descriptor - def getBody(self): + def getBody(self) -> str: return str_to_cstr_ptr(self.descriptor.name) - def definition_body(self): + def definition_body(self) -> CGThing: return CGGeneric(self.getBody()) @@ -6739,13 +6757,13 @@ class CGClassTraceHook(CGAbstractClassHook): """ A hook to trace through our native object; used for GC and CC """ - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut JSTracer', 'trc'), Argument('*mut JSObject', 'obj')] CGAbstractClassHook.__init__(self, descriptor, TRACE_HOOK_NAME, 'void', args, doesNotPanic=True) self.traceGlobal = descriptor.isGlobal() - def generate_code(self): + def generate_code(self) -> CGThing: body = [CGGeneric("if this.is_null() { return; } // GC during obj creation\n" f"(*this).trace({self.args[0].name});")] if self.traceGlobal: @@ -6757,7 +6775,7 @@ class CGClassConstructHook(CGAbstractExternMethod): """ JS-visible constructor for our objects """ - def __init__(self, descriptor, constructor=None): + def __init__(self, descriptor, constructor=None) -> None: args = [Argument('*mut JSContext', 'cx'), Argument('u32', 'argc'), Argument('*mut JSVal', 'vp')] name = CONSTRUCT_HOOK_NAME if constructor: @@ -6769,7 +6787,7 @@ class CGClassConstructHook(CGAbstractExternMethod): self.constructor = constructor self.exposureSet = descriptor.interface.exposureSet - def definition_body(self): + def definition_body(self) -> CGThing: preamble = """let cx = SafeJSContext::from_ptr(cx); let args = CallArgs::from_vp(vp, argc); let global = D::GlobalScope::from_object(JS_CALLEE(*cx, vp).to_object()); @@ -6826,21 +6844,21 @@ class CGClassFinalizeHook(CGAbstractClassHook): """ A hook for finalize, used to release our native object. """ - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: args = [Argument('*mut GCContext', '_cx'), Argument('*mut JSObject', 'obj')] CGAbstractClassHook.__init__(self, descriptor, FINALIZE_HOOK_NAME, 'void', args) - def generate_code(self): + def generate_code(self) -> CGThing: return CGGeneric(finalizeHook(self.descriptor, self.name, self.args[0].name)) class CGDOMJSProxyHandlerDOMClass(CGThing): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: CGThing.__init__(self) self.descriptor = descriptor - def define(self): + def define(self) -> str: return f""" pub static Class: ThreadUnsafeOnceLock = ThreadUnsafeOnceLock::new(); @@ -6851,7 +6869,7 @@ pub(crate) fn init_proxy_handler_dom_class() {{ class CGInterfaceTrait(CGThing): - def __init__(self, descriptor: Descriptor, descriptorProvider: DescriptorProvider): + def __init__(self, descriptor: Descriptor, descriptorProvider: DescriptorProvider) -> None: CGThing.__init__(self) def attribute_arguments(attribute_type, argument=None, inRealm=False, canGc=False, retval=False): @@ -6947,7 +6965,7 @@ class CGInterfaceTrait(CGThing): rettype = return_type(descriptor, rettype, infallible) yield name, arguments, rettype, False - def fmt(arguments, leadingComma=True): + def fmt(arguments, leadingComma=True) -> str: prefix = "" if not leadingComma else ", " return prefix + ", ".join( f"r#{name}: {type_}" @@ -6980,7 +6998,7 @@ class CGInterfaceTrait(CGThing): f"{fmt(arguments, leadingComma=not isStatic)}){returnType};\n" )) - def ctorMethod(ctor, baseName=None): + def ctorMethod(ctor, baseName: str | None=None): infallible = 'infallible' in descriptor.getExtendedAttributes(ctor) for (i, (rettype, arguments)) in enumerate(ctor.signatures()): name = (baseName or ctor.identifier.name) + ('_' * i) @@ -7015,22 +7033,22 @@ class CGInterfaceTrait(CGThing): post="}") self.empty = not methods - def define(self): + def define(self) -> str: return self.cgRoot.define() class CGWeakReferenceableTrait(CGThing): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: CGThing.__init__(self) assert descriptor.weakReferenceable self.code = f"impl WeakReferenceable for {descriptor.interface.identifier.name} {{}}" - def define(self): + def define(self) -> str: return self.code class CGInitStatics(CGThing): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: CGThing.__init__(self) def internal(method): @@ -7114,12 +7132,12 @@ class CGInitStatics(CGThing): }} """ - def define(self): + def define(self) -> str: return self.code class CGDescriptor(CGThing): - def __init__(self, descriptor, config, soleDescriptor): + def __init__(self, descriptor, config, soleDescriptor) -> None: CGThing.__init__(self) assert not descriptor.concrete or not descriptor.interface.isCallback() @@ -7323,12 +7341,12 @@ class CGDescriptor(CGThing): self.cgRoot = cgThings - def define(self): + def define(self) -> str: return self.cgRoot.define() class CGNonNamespacedEnum(CGThing): - def __init__(self, enumName, names, first, comment="", deriving="", repr=""): + def __init__(self, enumName, names, first, comment="", deriving="", repr="") -> None: # Account for first value entries = [f"{names[0]} = {first}"] + names[1:] @@ -7357,12 +7375,12 @@ class CGNonNamespacedEnum(CGThing): # Save the result. self.node = curr - def define(self): + def define(self) -> str: return self.node.define() class CGDictionary(CGThing): - def __init__(self, dictionary, descriptorProvider, config): + def __init__(self, dictionary, descriptorProvider, config) -> None: self.dictionary = dictionary derivesList = config.getDictConfig(dictionary.identifier.name).get('derives', []) self.manualImpls = list(filter(lambda t: traitRequiresManualImpl(t, self.dictionary), derivesList)) @@ -7386,12 +7404,12 @@ class CGDictionary(CGThing): exceptionCode="return Err(());\n")) for member in dictionary.members] - def define(self): + def define(self) -> str: if not self.generatable: return "" return f"{self.struct()}\n{self.impl()}" - def manualImplClone(self): + def manualImplClone(self) -> str: members = [] for m in self.memberInfo: memberName = self.makeMemberName(m[0].identifier.name) @@ -7410,12 +7428,12 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS }} """ - def manualImpl(self, t): + def manualImpl(self, t) -> str: if t == "Clone": return self.manualImplClone() raise ValueError(f"Don't know how to impl {t} for dicts.") - def struct(self): + def struct(self) -> str: d = self.dictionary if d.parent: typeName = f"{self.makeModuleName(d.parent)}::{self.makeClassName(d.parent)}" @@ -7476,7 +7494,7 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS f"{default}" ) - def impl(self): + def impl(self) -> str: d = self.dictionary if d.parent: initParent = ( @@ -7493,20 +7511,20 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS else: initParent = "" - def memberInit(memberInfo): + def memberInit(memberInfo) -> CGThing: member, _ = memberInfo name = self.makeMemberName(member.identifier.name) conversion = self.getMemberConversion(memberInfo, member.type) return CGGeneric(f"{name}: {conversion.define()},\n") - def varInsert(varName, dictionaryName): + def varInsert(varName: str, dictionaryName) -> CGThing: insertion = ( f"rooted!(in(cx) let mut {varName}_js = UndefinedValue());\n" f"{varName}.to_jsval(cx, {varName}_js.handle_mut());\n" f'set_dictionary_property(cx, obj.handle(), "{dictionaryName}", {varName}_js.handle()).unwrap();') return CGGeneric(insertion) - def memberInsert(memberInfo): + def memberInsert(memberInfo) -> CGThing: member, _ = memberInfo name = self.makeMemberName(member.identifier.name) if member.optional and not member.defaultValue: @@ -7583,7 +7601,7 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS "}\n" ) - def membersNeedTracing(self): + def membersNeedTracing(self) -> bool: return type_needs_tracing(self.dictionary) @staticmethod @@ -7597,7 +7615,7 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS return self.makeDictionaryName(dictionary) @staticmethod - def makeModuleName(dictionary): + def makeModuleName(dictionary) -> str: return getModuleFromObject(dictionary) def getMemberType(self, memberInfo): @@ -7607,8 +7625,8 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS declType = CGWrapper(info.declType, pre="Option<", post=">") return declType.define() - def getMemberConversion(self, memberInfo, memberType): - def indent(s): + def getMemberConversion(self, memberInfo, memberType) -> CGThing: + def indent(s) -> str: return CGIndenter(CGGeneric(s), 12).define() member, info = memberInfo @@ -7640,7 +7658,7 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS return CGGeneric(conversion) - def makeEmpty(self): + def makeEmpty(self) -> str: if self.hasRequiredFields(self.dictionary): return "" parentTemplate = "parent: %s::%s::empty(),\n" @@ -7675,7 +7693,7 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS s += fieldTemplate % (self.makeMemberName(member.identifier.name), default) return functionTemplate % CGIndenter(CGGeneric(s), 12).define() - def hasRequiredFields(self, dictionary): + def hasRequiredFields(self, dictionary) -> bool: if dictionary.parent: if self.hasRequiredFields(dictionary.parent): return True @@ -7685,7 +7703,7 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS return False @staticmethod - def makeMemberName(name): + def makeMemberName(name: str) -> str: # Can't use Rust keywords as member names. if name in RUST_KEYWORDS: return f"{name}_" @@ -7703,7 +7721,7 @@ impl{self.generic} Clone for {self.makeClassName(self.dictionary)}{self.genericS class CGInitAllStatics(CGAbstractMethod): - def __init__(self, config): + def __init__(self, config) -> None: docs = "Initialize the static data used by the SpiderMonkey DOM bindings to implement JS interfaces." descriptors = (config.getDescriptors(isCallback=False, register=True) + config.getDescriptors(isCallback=True, hasInterfaceObject=True, register=True)) @@ -7713,7 +7731,7 @@ class CGInitAllStatics(CGAbstractMethod): pub=True, docs=docs, templateArgs=["D: DomTypes"]) self.descriptors = descriptors - def definition_body(self): + def definition_body(self) -> CGThing: return CGList([ CGGeneric(f" GenericBindings::{toBindingModuleFileFromDescriptor(desc)}::{toBindingNamespace(desc.name)}" "::init_statics::();") @@ -7722,7 +7740,7 @@ class CGInitAllStatics(CGAbstractMethod): class CGRegisterProxyHandlersMethod(CGAbstractMethod): - def __init__(self, descriptors): + def __init__(self, descriptors) -> None: docs = "Create the global vtables used by the generated DOM bindings to implement JS proxies." # FIXME: pass in a valid descriptor somehow # pyrefly: ignore # bad-argument-type @@ -7730,7 +7748,7 @@ class CGRegisterProxyHandlersMethod(CGAbstractMethod): pub=True, docs=docs, templateArgs=["D: DomTypes"]) self.descriptors = descriptors - def definition_body(self): + def definition_body(self) -> CGThing: body = [CGGeneric("unsafe {")] body += [ CGGeneric(f"proxy_handlers::{desc.name}.store(\n" @@ -7745,7 +7763,7 @@ class CGRegisterProxyHandlersMethod(CGAbstractMethod): class CGRegisterProxyHandlers(CGThing): - def __init__(self, config): + def __init__(self, config) -> None: descriptors = config.getDescriptors(proxy=True) body = "".join( f" pub(crate) static {desc.name}: std::sync::atomic::AtomicPtr =\n" @@ -7761,7 +7779,7 @@ class CGRegisterProxyHandlers(CGThing): CGRegisterProxyHandlersMethod(descriptors), ], "\n") - def define(self): + def define(self) -> str: return self.root.define() @@ -7769,13 +7787,13 @@ class CGStructuredCloneMarker(CGThing): """ Generate a type assertion for inheritance """ - def __init__(self, descriptor, marker): + def __init__(self, descriptor, marker) -> None: CGThing.__init__(self) self.descriptor = descriptor self.marker = marker self.marker_lower = marker.lower() - def define(self): + def define(self) -> str: ifaceName = self.descriptor.interface.identifier.name return f""" impl script_bindings::structuredclone::MarkedAs{self.marker}InIdl for {ifaceName} {{ @@ -7794,7 +7812,7 @@ class CGConcreteBindingRoot(CGThing): the generic bindings with type specialization applied. """ root: CGThing | None - def __init__(self, config, prefix, webIDLFile): + def __init__(self, config, prefix, webIDLFile) -> None: descriptors = config.getDescriptors(webIDLFile=webIDLFile, hasInterfaceObject=True) # We also want descriptors that have an interface prototype object @@ -7924,7 +7942,7 @@ pub(crate) fn GetConstructorObject( # Store the final result. self.root = curr - def define(self): + def define(self) -> str: if not self.root: return "" return stripTrailingWhitespace(self.root.define()) @@ -7936,7 +7954,7 @@ class CGBindingRoot(CGThing): declare or define to generate header or cpp code (respectively). """ root: CGThing | None - def __init__(self, config, prefix, webIDLFile): + def __init__(self, config, prefix, webIDLFile) -> None: descriptors = config.getDescriptors(webIDLFile=webIDLFile, hasInterfaceObject=True) # We also want descriptors that have an interface prototype object @@ -8012,7 +8030,7 @@ class CGBindingRoot(CGThing): # Store the final result. self.root = curr - def define(self): + def define(self) -> str: if not self.root: return "" return stripTrailingWhitespace(self.root.define()) @@ -8295,17 +8313,17 @@ def callbackSetterName(attr: IDLAttribute, descriptor: Descriptor) -> str: class CGCallbackFunction(CGCallback): - def __init__(self, callback, descriptorProvider): + def __init__(self, callback, descriptorProvider) -> None: CGCallback.__init__(self, callback, descriptorProvider, "CallbackFunction", methods=[CallCallback(callback, descriptorProvider)]) - def getConstructors(self): + def getConstructors(self) -> list[ClassConstructor]: return CGCallback.getConstructors(self) class CGCallbackFunctionImpl(CGGeneric): - def __init__(self, callback): + def __init__(self, callback) -> None: type = f"{callback.identifier.name}" impl = (f""" impl CallbackContainer for {type} {{ @@ -8328,7 +8346,7 @@ impl ToJSValConvertible for {type} {{ class CGCallbackInterface(CGCallback): - def __init__(self, descriptor): + def __init__(self, descriptor) -> None: iface = descriptor.interface attrs = [m for m in iface.members if m.isAttr() and not m.isStatic()] assert not attrs @@ -8403,7 +8421,7 @@ class CallbackMember(CGNativeMember): def getCall(self) -> str: raise NotImplementedError - def getImpl(self): + def getImpl(self) -> str: argvDecl = ( "rooted_vec!(let mut argv);\n" f"argv.extend((0..{self.argCountStr}).map(|_| Heap::default()));\n" @@ -8422,7 +8440,7 @@ class CallbackMember(CGNativeMember): ) return f"{pre}\n{body}" - def getResultConversion(self): + def getResultConversion(self) -> str: replacements = { "val": "rval.handle()", } @@ -8449,7 +8467,7 @@ class CallbackMember(CGNativeMember): return f"{convertType.define()}\nOk({retval})\n" - def getArgConversions(self): + def getArgConversions(self) -> str: # Just reget the arglist from self.originalSig, because our superclasses # just have way to many members they like to clobber, so I can't find a # safe member name to store it in. @@ -8459,7 +8477,7 @@ class CallbackMember(CGNativeMember): # Do them back to front, so our argc modifications will work # correctly, because we examine trailing arguments first. argConversions.reverse() - argConversionsCG = [CGGeneric(c) for c in argConversions] + argConversionsCG: list[CGThing] = [CGGeneric(c) for c in argConversions] # If arg count is only 1 but it's optional and not default value, # argc should be mutable. if self.argCount == 1 and not (arglist[0].optional and not arglist[0].defaultValue): @@ -8469,7 +8487,7 @@ class CallbackMember(CGNativeMember): # And slap them together. return CGList(argConversionsCG, "\n\n").define() + "\n\n" - def getArgConversion(self, i, arg): + def getArgConversion(self, i: int, arg: IDLArgument) -> str: argval = arg.identifier.name if arg.variadic: @@ -8503,7 +8521,7 @@ class CallbackMember(CGNativeMember): ) return conversion - def getArgs(self, returnType, argList): + def getArgs(self, returnType, argList) -> list[Argument]: args = CGNativeMember.getArgs(self, returnType, argList) if not self.needThisHandling: # Since we don't need this handling, we're the actual method that @@ -8516,7 +8534,7 @@ class CallbackMember(CGNativeMember): return [Argument("SafeJSContext", "cx"), Argument("HandleValue", "aThisObj")] + args - def getCallSetup(self): + def getCallSetup(self) -> str: if self.needThisHandling: # It's been done for us already return "" @@ -8527,13 +8545,13 @@ class CallbackMember(CGNativeMember): " return Err(JSFailed);\n" "}\n") - def getArgcDecl(self, immutable): + def getArgcDecl(self, immutable: bool) -> CGThing: if immutable: return CGGeneric(f"let argc = {self.argCountStr};") return CGGeneric(f"let mut argc = {self.argCountStr};") @staticmethod - def ensureASCIIName(idlObject): + def ensureASCIIName(idlObject) -> None: type = "attribute" if idlObject.isAttr() else "operation" if re.match("[^\x20-\x7E]", idlObject.identifier.name): raise SyntaxError(f'Callback {type} name "{idlObject.identifier.name}" contains non-ASCII ' @@ -8643,7 +8661,7 @@ class CallbackOperation(CallbackOperationBase): """ Codegen actual WebIDL operations on callback interfaces. """ - def __init__(self, method, signature, descriptor): + def __init__(self, method, signature, descriptor) -> None: self.ensureASCIIName(method) jsName = method.identifier.name CallbackOperationBase.__init__(self, signature, @@ -8659,7 +8677,7 @@ class CGMaplikeOrSetlikeMethodGenerator(CGGeneric): CGMethodCall/CGPerSignatureCall. Functionality is filled in here instead of using CGCallGenerator. """ - def __init__(self, descriptor, likeable, methodName): + def __init__(self, descriptor, likeable, methodName) -> None: trait: str if likeable.isSetlike(): trait = "Setlike" @@ -8730,7 +8748,7 @@ class CGIterableMethodGenerator(CGGeneric): CGMethodCall/CGPerSignatureCall. Functionality is filled in here instead of using CGCallGenerator. """ - def __init__(self, descriptor, iterable, methodName): + def __init__(self, descriptor, iterable, methodName) -> None: if methodName == "forEach": CGGeneric.__init__(self, fill( """ @@ -8811,7 +8829,7 @@ class GlobalGenRoots(): """ @staticmethod - def Globals(config): + def Globals(config) -> CGThing: global_descriptors = config.getDescriptors(isGlobal=True) flags = [("EMPTY", 0)] flags.extend( @@ -8830,7 +8848,7 @@ class GlobalGenRoots(): ]) @staticmethod - def InterfaceObjectMap(config): + def InterfaceObjectMap(config) -> CGThing: mods = [ "crate::dom::bindings::codegen", "script_bindings::interfaces::Interface", @@ -8845,7 +8863,7 @@ class GlobalGenRoots(): ]) @staticmethod - def InterfaceObjectMapData(config): + def InterfaceObjectMapData(config) -> CGThing: pairs = [] for d in config.getDescriptors(hasInterfaceObject=True, isInline=False): binding_mod = toBindingModuleFileFromDescriptor(d) @@ -8857,7 +8875,7 @@ class GlobalGenRoots(): pairs.append((ctor.identifier.name, binding_mod, binding_ns)) pairs.sort(key=operator.itemgetter(0)) - def bindingPath(pair): + def bindingPath(pair) -> str: return f'codegen::Bindings::{pair[1]}::{pair[2]}' mappings = [ @@ -8871,7 +8889,7 @@ class GlobalGenRoots(): post="\n}\n") @staticmethod - def PrototypeList(config): + def PrototypeList(config) -> CGThing: # Prototype ID enum. interfaces = config.getDescriptors(isCallback=False, isNamespace=False) protos = [d.name for d in interfaces] @@ -8899,7 +8917,7 @@ class GlobalGenRoots(): ]) @staticmethod - def RegisterBindings(config): + def RegisterBindings(config) -> CGThing: # TODO - Generate the methods we want code = CGList([ CGRegisterProxyHandlers(config), @@ -8912,7 +8930,7 @@ class GlobalGenRoots(): ], config=config) @staticmethod - def InterfaceTypes(config): + def InterfaceTypes(config) -> CGThing: descriptors = sorted([MakeNativeName(d.name) for d in config.getDescriptors(register=True, isCallback=False, @@ -8923,9 +8941,9 @@ class GlobalGenRoots(): return curr @staticmethod - def Bindings(config): + def Bindings(config) -> CGThing: - def leafModule(d): + def leafModule(d) -> str: return getModuleFromObject(d).split('::')[-1] descriptors = config.getDescriptors(register=True, isIteratorInterface=False) @@ -8940,7 +8958,7 @@ class GlobalGenRoots(): return curr @staticmethod - def ConcreteInheritTypes(config): + def ConcreteInheritTypes(config) -> CGThing: descriptors = config.getDescriptors(register=True, isCallback=False) imports = [CGGeneric("use crate::dom::types::*;\n"), CGGeneric("use script_bindings::codegen::InheritTypes::*;\n"), @@ -8999,7 +9017,7 @@ impl {base} {{ return curr @staticmethod - def InheritTypes(config): + def InheritTypes(config) -> CGThing: descriptors = config.getDescriptors(register=True, isCallback=False) topTypes = [] hierarchy = defaultdict(list) @@ -9057,7 +9075,7 @@ impl Clone for TopTypeId { return curr @staticmethod - def ConcreteUnionTypes(config): + def ConcreteUnionTypes(config) -> CGThing: unions = set() cgthings = [] allTypes = getAllTypes( @@ -9077,7 +9095,7 @@ impl Clone for TopTypeId { return curr @staticmethod - def UnionTypes(config): + def UnionTypes(config) -> CGThing: curr = UnionTypes(config.getDescriptors(), config.getDictionaries(), @@ -9092,7 +9110,7 @@ impl Clone for TopTypeId { return curr @staticmethod - def DomTypes(config): + def DomTypes(config) -> CGThing: curr = DomTypes(config.getDescriptors(), config.getDescriptorProvider(), config.getDictionaries(), @@ -9107,7 +9125,7 @@ impl Clone for TopTypeId { return curr @staticmethod - def DomTypeHolder(config): + def DomTypeHolder(config) -> CGThing: curr = DomTypeHolder(config.getDescriptors(), config.getDescriptorProvider(), config.getDictionaries(), @@ -9122,7 +9140,7 @@ impl Clone for TopTypeId { return curr @staticmethod - def SupportedDomApis(config): + def SupportedDomApis(config) -> CGThing: descriptors = config.getDescriptors(isExposedConditionally=False) base_path = os.path.dirname(__file__) diff --git a/components/script_bindings/codegen/configuration.py b/components/script_bindings/codegen/configuration.py index a74d9de19a8..d15a23e220b 100644 --- a/components/script_bindings/codegen/configuration.py +++ b/components/script_bindings/codegen/configuration.py @@ -25,6 +25,7 @@ from WebIDL import ( IDLCallback, IDLAttribute, IDLMethod, + IDLInterfaceMember, ) TargetType = TypeVar('TargetType') @@ -448,7 +449,7 @@ class Descriptor(DescriptorProvider): def supportsNamedProperties(self) -> bool: return self.operations['NamedGetter'] is not None - def getExtendedAttributes(self, member: IDLMethod, getter: bool = False, setter: bool = False) -> list[str]: + def getExtendedAttributes(self, member: IDLInterfaceMember, getter: bool = False, setter: bool = False) -> list[str]: def maybeAppendInfallibleToAttrs(attrs: list[str], throws: bool | None) -> None: if throws is None: attrs.append("infallible")