From 43ca26068935e014b1a41a6a02f45d05436577b4 Mon Sep 17 00:00:00 2001 From: Alan Jeffrey Date: Fri, 12 May 2017 15:02:35 -0500 Subject: Renamed BrowsingContext to WindowProxy in script. --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e7a0541c4da..102c1a17d57 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5638,7 +5638,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::weakref::DOM_WEAK_SLOT', 'dom::bindings::weakref::WeakBox', 'dom::bindings::weakref::WeakReferenceable', - 'dom::browsingcontext::BrowsingContext', + 'dom::windowproxy::WindowProxy', 'dom::globalscope::GlobalScope', 'mem::heap_size_of_raw_self_and_children', 'libc', -- cgit v1.2.3 From e566bc7b1c65e54601f5420bfa071bab9c1b83a3 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Fri, 9 Jun 2017 13:57:30 +0200 Subject: Update the WebIDL parser --- .../script/dom/bindings/codegen/CodegenRust.py | 175 +++++++++++---------- 1 file changed, 95 insertions(+), 80 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 102c1a17d57..bf6ca70e6c0 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -17,11 +17,12 @@ import functools from WebIDL import ( BuiltinTypes, IDLBuiltinType, - IDLNullValue, + IDLInterfaceMember, IDLNullableType, + IDLNullValue, IDLObject, + IDLPromiseType, IDLType, - IDLInterfaceMember, IDLUndefinedValue, IDLWrapperType, ) @@ -94,14 +95,14 @@ def stripTrailingWhitespace(text): def innerContainerType(type): - assert type.isSequence() or type.isMozMap() + assert type.isSequence() or type.isRecord() return type.inner.inner if type.nullable() else type.inner def wrapInNativeContainerType(type, inner): if type.isSequence(): containerType = "Vec" - elif type.isMozMap(): + elif type.isRecord(): containerType = "MozMap" else: raise TypeError("Unexpected container type %s", type) @@ -697,7 +698,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, assert not (isEnforceRange and isClamp) # These are mutually exclusive - if type.isSequence() or type.isMozMap(): + if type.isSequence() or type.isRecord(): innerInfo = getJSToNativeConversionInfo(innerContainerType(type), descriptorProvider, isMember=isMember) @@ -754,6 +755,56 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, return handleOptional(templateBody, declType, default) + if type.isPromise(): + assert not type.nullable() + # Per spec, what we're supposed to do is take the original + # Promise.resolve and call it with the original Promise as this + # value to make a Promise out of whatever value we actually have + # here. The question is which global we should use. There are + # a couple cases to consider: + # + # 1) Normal call to API with a Promise argument. This is a case the + # spec covers, and we should be using the current Realm's + # Promise. That means the current compartment. + # 2) Promise return value from a callback or callback interface. + # This is in theory a case the spec covers but in practice it + # really doesn't define behavior here because it doesn't define + # what Realm we're in after the callback returns, which is when + # the argument conversion happens. We will use the current + # compartment, which is the compartment of the callable (which + # may itself be a cross-compartment wrapper itself), which makes + # as much sense as anything else. In practice, such an API would + # once again be providing a Promise to signal completion of an + # operation, which would then not be exposed to anyone other than + # our own implementation code. + templateBody = fill( + """ + { // Scope for our JSAutoCompartment. + + rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); + let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get()); + + rooted!(in(cx) let mut valueToResolve = $${val}.get()); + if !JS_WrapValue(cx, valueToResolve.handle_mut()) { + $*{exceptionCode} + } + match Promise::Resolve(&promiseGlobal, cx, valueToResolve.handle()) { + Ok(value) => value, + Err(error) => { + throw_dom_exception(cx, &promiseGlobal, error); + $*{exceptionCode} + } + } + } + """, + exceptionCode=exceptionCode) + + if isArgument: + declType = CGGeneric("&Promise") + else: + declType = CGGeneric("Rc") + return handleOptional(templateBody, declType, handleDefaultNull("None")) + if type.isGeckoInterface(): assert not isEnforceRange and not isClamp @@ -780,79 +831,34 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, elif isArgument: descriptorType = descriptor.argumentType - templateBody = "" - isPromise = descriptor.interface.identifier.name == "Promise" - if isPromise: - # Per spec, what we're supposed to do is take the original - # Promise.resolve and call it with the original Promise as this - # value to make a Promise out of whatever value we actually have - # here. The question is which global we should use. There are - # a couple cases to consider: - # - # 1) Normal call to API with a Promise argument. This is a case the - # spec covers, and we should be using the current Realm's - # Promise. That means the current compartment. - # 2) Promise return value from a callback or callback interface. - # This is in theory a case the spec covers but in practice it - # really doesn't define behavior here because it doesn't define - # what Realm we're in after the callback returns, which is when - # the argument conversion happens. We will use the current - # compartment, which is the compartment of the callable (which - # may itself be a cross-compartment wrapper itself), which makes - # as much sense as anything else. In practice, such an API would - # once again be providing a Promise to signal completion of an - # operation, which would then not be exposed to anyone other than - # our own implementation code. - templateBody = fill( - """ - { // Scope for our JSAutoCompartment. - - rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); - let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get()); + if descriptor.interface.isConsequential(): + raise TypeError("Consequential interface %s being used as an " + "argument" % descriptor.interface.identifier.name) - rooted!(in(cx) let mut valueToResolve = $${val}.get()); - if !JS_WrapValue(cx, valueToResolve.handle_mut()) { - $*{exceptionCode} - } - match Promise::Resolve(&promiseGlobal, cx, valueToResolve.handle()) { - Ok(value) => value, - Err(error) => { - throw_dom_exception(cx, &promiseGlobal, error); - $*{exceptionCode} - } - } - } - """, - exceptionCode=exceptionCode) + if failureCode is None: + substitutions = { + "sourceDescription": sourceDescription, + "interface": descriptor.interface.identifier.name, + "exceptionCode": exceptionCode, + } + unwrapFailureCode = string.Template( + 'throw_type_error(cx, "${sourceDescription} does not ' + 'implement interface ${interface}.");\n' + '${exceptionCode}').substitute(substitutions) else: - if descriptor.interface.isConsequential(): - raise TypeError("Consequential interface %s being used as an " - "argument" % descriptor.interface.identifier.name) - - if failureCode is None: - substitutions = { - "sourceDescription": sourceDescription, - "interface": descriptor.interface.identifier.name, - "exceptionCode": exceptionCode, - } - unwrapFailureCode = string.Template( - 'throw_type_error(cx, "${sourceDescription} does not ' - 'implement interface ${interface}.");\n' - '${exceptionCode}').substitute(substitutions) - else: - unwrapFailureCode = failureCode + unwrapFailureCode = failureCode - templateBody = fill( - """ - match ${function}($${val}) { - Ok(val) => val, - Err(()) => { - $*{failureCode} - } + templateBody = fill( + """ + match ${function}($${val}) { + Ok(val) => val, + Err(()) => { + $*{failureCode} } - """, - failureCode=unwrapFailureCode + "\n", - function=conversionFunction) + } + """, + failureCode=unwrapFailureCode + "\n", + function=conversionFunction) declType = CGGeneric(descriptorType) if type.nullable(): @@ -1323,7 +1329,7 @@ def typeNeedsCx(type, retVal=False): # Returns a conversion behavior suitable for a type def getConversionConfigForType(type, isEnforceRange, isClamp, treatNullAs): - if type.isSequence() or type.isMozMap(): + if type.isSequence() or type.isRecord(): return getConversionConfigForType(innerContainerType(type), isEnforceRange, isClamp, treatNullAs) if type.isDOMString(): assert not isEnforceRange and not isClamp @@ -1381,6 +1387,9 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): if returnType.nullable(): result = CGWrapper(result, pre="Option<", post=">") return result + if returnType.isPromise(): + assert not returnType.nullable() + return CGGeneric("Rc") if returnType.isGeckoInterface(): descriptor = descriptorProvider.getDescriptor( returnType.unroll().inner.identifier.name) @@ -1408,7 +1417,7 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): if returnType.nullable(): result = CGWrapper(result, pre="Option<", post=">") return result - if returnType.isSequence() or returnType.isMozMap(): + if returnType.isSequence() or returnType.isRecord(): result = getRetvalDeclarationForType(innerContainerType(returnType), descriptorProvider) result = wrapInNativeContainerType(returnType, result) if returnType.nullable(): @@ -1946,8 +1955,10 @@ class CGImports(CGWrapper): if parentName: descriptor = descriptorProvider.getDescriptor(parentName) extras += [descriptor.path, descriptor.bindingPath] - elif t.isType() and t.isMozMap(): + elif t.isType() and t.isRecord(): extras += ['dom::bindings::mozmap::MozMap'] + elif isinstance(t, IDLPromiseType): + extras += ["dom::promise::Promise"] else: if t.isEnum(): extras += [getModuleFromObject(t) + '::' + getIdentifier(t).name + 'Values'] @@ -3819,7 +3830,9 @@ class CGMemberJITInfo(CGThing): return "JSVAL_TYPE_UNDEFINED" if t.isSequence(): return "JSVAL_TYPE_OBJECT" - if t.isMozMap(): + if t.isRecord(): + return "JSVAL_TYPE_OBJECT" + if t.isPromise(): return "JSVAL_TYPE_OBJECT" if t.isGeckoInterface(): return "JSVAL_TYPE_OBJECT" @@ -4055,7 +4068,7 @@ def getUnionTypeTemplateVars(type, descriptorProvider): elif type.isDictionary(): name = type.name typeName = name - elif type.isSequence() or type.isMozMap(): + elif type.isSequence() or type.isRecord(): name = type.name inner = getUnionTypeTemplateVars(innerContainerType(type), descriptorProvider) typeName = wrapInNativeContainerType(type, CGGeneric(inner["typeName"])).define() @@ -4208,7 +4221,7 @@ class CGUnionConversionStruct(CGThing): else: object = None - mozMapMemberTypes = filter(lambda t: t.isMozMap(), memberTypes) + mozMapMemberTypes = filter(lambda t: t.isRecord(), memberTypes) if len(mozMapMemberTypes) > 0: assert len(mozMapMemberTypes) == 1 typeName = mozMapMemberTypes[0].name @@ -6870,6 +6883,8 @@ def process_arg(expr, arg): expr += ".r()" else: expr = "&" + expr + elif isinstance(arg.type, IDLPromiseType): + expr = "&" + expr return expr -- cgit v1.2.3 From 0713257adde476cc0a0f74365acf52f19fcd9440 Mon Sep 17 00:00:00 2001 From: Connor Brewster Date: Mon, 12 Jun 2017 21:50:53 -0600 Subject: Generate GetConstructorObject for all interfaces --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index bf6ca70e6c0..130d2008448 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2863,7 +2863,7 @@ create_noncallback_interface_object(cx, %(length)s, interface.handle_mut()); assert!(!interface.is_null());""" % properties)) - if self.descriptor.hasDescendants(): + if self.descriptor.shouldCacheConstructor(): code.append(CGGeneric("""\ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); (*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.get(); -- cgit v1.2.3 From 2333b39569a0cc598289c948aefea64aa9aa4858 Mon Sep 17 00:00:00 2001 From: Connor Brewster Date: Wed, 7 Jun 2017 13:55:42 -0600 Subject: Implement HTMLConstructor --- .../script/dom/bindings/codegen/CodegenRust.py | 84 ++++++++++++++++++++-- 1 file changed, 78 insertions(+), 6 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 130d2008448..5f60a9fc5fa 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5301,11 +5301,79 @@ class CGClassConstructHook(CGAbstractExternMethod): preamble += "let global = Root::downcast::(global).unwrap();\n" % list(self.exposureSet)[0] preamble += """let args = CallArgs::from_vp(vp, argc);\n""" preamble = CGGeneric(preamble) - name = self.constructor.identifier.name - nativeName = MakeNativeName(self.descriptor.binaryNameFor(name)) - callGenerator = CGMethodCall(["&global"], nativeName, True, - self.descriptor, self.constructor) - return CGList([preamble, callGenerator]) + if self.constructor.isHTMLConstructor(): + signatures = self.constructor.signatures() + assert len(signatures) == 1 + constructorCall = CGGeneric("""\ +// Step 2 https://html.spec.whatwg.org/multipage/#htmlconstructor +// The custom element definition cannot use an element interface as its constructor + +// The new_target might be a cross-compartment wrapper. Get the underlying object +// so we can do the spec's object-identity checks. +rooted!(in(cx) let new_target = UnwrapObject(args.new_target().to_object(), 1)); +if new_target.is_null() { + throw_dom_exception(cx, global.upcast::(), Error::Type("new.target is null".to_owned())); + return false; +} + +if args.callee() == new_target.get() { + throw_dom_exception(cx, global.upcast::(), + Error::Type("new.target must not be the active function object".to_owned())); + return false; +} + +// Step 6 +rooted!(in(cx) let mut prototype = ptr::null_mut()); +{ + rooted!(in(cx) let mut proto_val = UndefinedValue()); + let _ac = JSAutoCompartment::new(cx, new_target.get()); + if !JS_GetProperty(cx, new_target.handle(), b"prototype\\0".as_ptr() as *const _, proto_val.handle_mut()) { + return false; + } + + if !proto_val.is_object() { + // Step 7 of https://html.spec.whatwg.org/multipage/#htmlconstructor. + // This fallback behavior is designed to match analogous behavior for the + // JavaScript built-ins. So we enter the compartment of our underlying + // newTarget object and fall back to the prototype object from that global. + // XXX The spec says to use GetFunctionRealm(), which is not actually + // the same thing as what we have here (e.g. in the case of scripted callable proxies + // whose target is not same-compartment with the proxy, or bound functions, etc). + // https://bugzilla.mozilla.org/show_bug.cgi?id=1317658 + + rooted!(in(cx) let global_object = CurrentGlobalOrNull(cx)); + GetProtoObject(cx, global_object.handle(), prototype.handle_mut()); + } else { + // Step 6 + prototype.set(proto_val.to_object()); + }; +} + +// Wrap prototype in this context since it is from the newTarget compartment +if !JS_WrapObject(cx, prototype.handle_mut()) { + return false; +} + +let result: Result, Error> = html_constructor(&global, &args); +let result = match result { + Ok(result) => result, + Err(e) => { + throw_dom_exception(cx, global.upcast::(), e); + return false; + }, +}; + +JS_SetPrototype(cx, result.reflector().get_jsobject(), prototype.handle()); + +(result).to_jsval(cx, args.rval()); +return true; +""" % self.descriptor.name) + else: + name = self.constructor.identifier.name + nativeName = MakeNativeName(self.descriptor.binaryNameFor(name)) + constructorCall = CGMethodCall(["&global"], nativeName, True, + self.descriptor, self.constructor) + return CGList([preamble, constructorCall]) class CGClassFinalizeHook(CGAbstractClassHook): @@ -5517,9 +5585,11 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JS_ObjectIsDate', 'js::jsapi::JS_SetImmutablePrototype', 'js::jsapi::JS_SetProperty', + 'js::jsapi::JS_SetPrototype', 'js::jsapi::JS_SetReservedSlot', 'js::jsapi::JS_SplicePrototype', 'js::jsapi::JS_WrapValue', + 'js::jsapi::JS_WrapObject', 'js::jsapi::MutableHandle', 'js::jsapi::MutableHandleObject', 'js::jsapi::MutableHandleValue', @@ -5547,6 +5617,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::glue::RUST_JSID_IS_STRING', 'js::glue::RUST_SYMBOL_TO_JSID', 'js::glue::int_to_jsid', + 'js::glue::UnwrapObject', 'js::panic::maybe_resume_unwind', 'js::panic::wrap_panic', 'js::rust::GCMethods', @@ -5561,14 +5632,15 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::InterfaceConstructorBehavior', 'dom::bindings::interface::NonCallbackInterfaceObjectClass', - 'dom::bindings::interface::create_callback_interface_object', 'dom::bindings::interface::create_global_object', + 'dom::bindings::interface::create_callback_interface_object', 'dom::bindings::interface::create_interface_prototype_object', 'dom::bindings::interface::create_named_constructors', 'dom::bindings::interface::create_noncallback_interface_object', 'dom::bindings::interface::define_guarded_constants', 'dom::bindings::interface::define_guarded_methods', 'dom::bindings::interface::define_guarded_properties', + 'dom::bindings::interface::html_constructor', 'dom::bindings::interface::is_exposed_in', 'dom::bindings::iterable::Iterable', 'dom::bindings::iterable::IteratorType', -- cgit v1.2.3 From 438191e0b207fd6294a465149a37c63f32ce9161 Mon Sep 17 00:00:00 2001 From: Connor Brewster Date: Mon, 10 Jul 2017 10:45:26 -0600 Subject: Implement CEReactions codegen --- components/script/dom/bindings/codegen/CodegenRust.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 5f60a9fc5fa..efb39208b44 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3152,7 +3152,7 @@ class CGCallGenerator(CGThing): """ def __init__(self, errorResult, arguments, argsPre, returnType, extendedAttributes, descriptor, nativeMethodName, - static, object="this"): + static, object="this", hasCEReactions=False): CGThing.__init__(self) assert errorResult is None or isinstance(errorResult, str) @@ -3185,6 +3185,9 @@ class CGCallGenerator(CGThing): call = CGWrapper(call, pre="%s." % object) call = CGList([call, CGWrapper(args, pre="(", post=")")]) + if hasCEReactions: + self.cgRoot.append(CGGeneric("push_new_element_queue();\n")) + self.cgRoot.append(CGList([ CGGeneric("let result: "), result, @@ -3193,6 +3196,9 @@ class CGCallGenerator(CGThing): CGGeneric(";"), ])) + if hasCEReactions: + self.cgRoot.append(CGGeneric("pop_current_element_queue();\n")) + if isFallible: if static: glob = "global.upcast::()" @@ -3267,11 +3273,12 @@ class CGPerSignatureCall(CGThing): idlNode.maplikeOrSetlikeOrIterable, idlNode.identifier.name)) else: + hasCEReactions = idlNode.getExtendedAttribute("CEReactions") cgThings.append(CGCallGenerator( errorResult, self.getArguments(), self.argsPre, returnType, self.extendedAttributes, descriptor, nativeMethodName, - static)) + static, hasCEReactions=hasCEReactions)) self.cgRoot = CGList(cgThings, "\n") @@ -5642,6 +5649,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::interface::define_guarded_properties', 'dom::bindings::interface::html_constructor', 'dom::bindings::interface::is_exposed_in', + 'dom::bindings::interface::pop_current_element_queue', + 'dom::bindings::interface::push_new_element_queue', 'dom::bindings::iterable::Iterable', 'dom::bindings::iterable::IteratorType', 'dom::bindings::js::JS', -- cgit v1.2.3 From 354d94059b7071d4164e01affd0f643940e3c50b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Jim=C3=A9nez=20Moreno?= Date: Wed, 2 Aug 2017 11:48:49 +0200 Subject: Generate DOM bindings imports for webidl typedefs --- .../script/dom/bindings/codegen/CodegenRust.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index efb39208b44..482b713e10c 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1848,7 +1848,8 @@ class CGImports(CGWrapper): """ Generates the appropriate import/use statements. """ - def __init__(self, child, descriptors, callbacks, dictionaries, enums, imports, config, ignored_warnings=None): + def __init__(self, child, descriptors, callbacks, dictionaries, enums, typedefs, imports, config, + ignored_warnings=None): """ Adds a set of imports. """ @@ -1937,6 +1938,11 @@ class CGImports(CGWrapper): for d in dictionaries: types += componentTypes(d) + # Import the type names used in the typedefs that are being defined. + for t in typedefs: + if not t.innerType.isCallback(): + types += componentTypes(t.innerType) + # Normalize the types we've collected and remove any ones which can't be imported. types = removeWrapperAndNullableTypes(types) @@ -2292,6 +2298,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): callbacks=[], dictionaries=[], enums=[], + typedefs=[], imports=imports, config=config, ignored_warnings=[]) @@ -5507,15 +5514,17 @@ class CGWeakReferenceableTrait(CGThing): return self.code -def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries=None, enums=None): +def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries=None, enums=None, typedefs=None): if not callbacks: callbacks = [] if not dictionaries: dictionaries = [] if not enums: enums = [] + if not typedefs: + typedefs = [] - return CGImports(cgthings, descriptors, callbacks, dictionaries, enums, [ + return CGImports(cgthings, descriptors, callbacks, dictionaries, enums, typedefs, [ 'core::nonzero::NonZero', 'js', 'js::JSCLASS_GLOBAL_SLOT_COUNT', @@ -6220,7 +6229,7 @@ class CGBindingRoot(CGThing): # Do codegen for all the enums. cgthings = [CGEnum(e) for e in enums] - # Do codegen for all the typdefs + # Do codegen for all the typedefs for t in typedefs: typeName = getRetvalDeclarationForType(t.innerType, config.getDescriptorProvider()) substs = { @@ -6258,7 +6267,7 @@ class CGBindingRoot(CGThing): # Add imports curr = generate_imports(config, curr, callbackDescriptors, mainCallbacks, - dictionaries, enums) + dictionaries, enums, typedefs) # Add the auto-generated comment. curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT) @@ -7060,7 +7069,7 @@ class GlobalGenRoots(): CGRegisterProxyHandlers(config), ], "\n") - return CGImports(code, descriptors=[], callbacks=[], dictionaries=[], enums=[], imports=[ + return CGImports(code, descriptors=[], callbacks=[], dictionaries=[], enums=[], typedefs=[], imports=[ 'dom::bindings::codegen::Bindings', 'dom::bindings::codegen::PrototypeList::Proxies', 'libc', -- cgit v1.2.3 From 1a9f4cad0871bcde9420f633c527b933ac288057 Mon Sep 17 00:00:00 2001 From: Connor Brewster Date: Thu, 20 Jul 2017 16:35:46 -0600 Subject: Fix compartment mismatch issue --- components/script/dom/bindings/codegen/CodegenRust.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 482b713e10c..7f97868a378 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5377,7 +5377,12 @@ let result = match result { }, }; -JS_SetPrototype(cx, result.reflector().get_jsobject(), prototype.handle()); +rooted!(in(cx) let mut element = result.reflector().get_jsobject().get()); +if !JS_WrapObject(cx, element.handle_mut()) { + return false; +} + +JS_SetPrototype(cx, element.handle(), prototype.handle()); (result).to_jsval(cx, args.rval()); return true; -- cgit v1.2.3 From b29e56eefcf0710bec318781de9bce5aabb5348a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Sun, 17 Sep 2017 07:32:01 +0200 Subject: script: Fix code generation for named getters. Fixes part of #18535 --- components/script/dom/bindings/codegen/CodegenRust.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7f97868a378..0ad87747a12 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4938,8 +4938,6 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): set += ("if RUST_JSID_IS_STRING(id) {\n" + CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + " return (*opresult).succeed();\n" + - "} else {\n" + - " return false;\n" + "}\n") else: set += ("if RUST_JSID_IS_STRING(id) {\n" + @@ -4948,7 +4946,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): " return (*opresult).failNoNamedSetter();\n" " }\n" "}\n") - set += "return proxyhandler::define_property(%s);" % ", ".join(a.name for a in self.args) + set += "return proxyhandler::define_property(%s);" % ", ".join(a.name for a in self.args) return set def definition_body(self): -- cgit v1.2.3 From f5d16fc069533b810a76a2fa611882e1b9c8743c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Sun, 17 Sep 2017 19:25:58 +0200 Subject: script: Fix integer-JSID handling in named getters. Fixes #10686 --- components/script/dom/bindings/codegen/CodegenRust.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 0ad87747a12..c42ec783716 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4750,7 +4750,7 @@ class CGProxyNamedOperation(CGProxySpecialOperation): def define(self): # Our first argument is the id we're getting. argName = self.arguments[0].identifier.name - return ("let %s = string_jsid_to_string(cx, id);\n" + return ("let %s = jsid_to_string(cx, id).expect(\"Not a string-convertible JSID?\");\n" "let this = UnwrapProxy(proxy);\n" "let this = &*this;\n" % argName + CGProxySpecialOperation.define(self)) @@ -4868,7 +4868,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): # ResolveOwnProperty or EnumerateOwnProperties filter out named # properties that shadow prototype properties. namedGet = """ -if RUST_JSID_IS_STRING(id) { +if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) { let mut has_on_proto = false; if !has_property_on_prototype(cx, proxy, id, &mut has_on_proto) { return false; @@ -4935,12 +4935,12 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): if self.descriptor.hasUnforgeableMembers: raise TypeError("Can't handle a named setter on an interface that has " "unforgeables. Figure out how that should work!") - set += ("if RUST_JSID_IS_STRING(id) {\n" + + set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + " return (*opresult).succeed();\n" + "}\n") else: - set += ("if RUST_JSID_IS_STRING(id) {\n" + + set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + " if result.is_some() {\n" " return (*opresult).failNoNamedSetter();\n" @@ -5095,7 +5095,7 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: named = """\ -if RUST_JSID_IS_STRING(id) { +if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) { let mut has_on_proto = false; if !has_property_on_prototype(cx, proxy, id, &mut has_on_proto) { return false; @@ -5175,7 +5175,7 @@ if !expando.is_null() { namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: - getNamed = ("if RUST_JSID_IS_STRING(id) {\n" + + getNamed = ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + "}\n") else: @@ -5633,6 +5633,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::glue::GetProxyPrivate', 'js::glue::NewProxyObject', 'js::glue::ProxyTraps', + 'js::glue::RUST_JSID_IS_INT', 'js::glue::RUST_JSID_IS_STRING', 'js::glue::RUST_SYMBOL_TO_JSID', 'js::glue::int_to_jsid', @@ -5720,6 +5721,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::conversions::root_from_handlevalue', 'dom::bindings::conversions::root_from_object', 'dom::bindings::conversions::string_jsid_to_string', + 'dom::bindings::conversions::jsid_to_string', 'dom::bindings::codegen::PrototypeList', 'dom::bindings::codegen::RegisterBindings', 'dom::bindings::codegen::UnionTypes', -- cgit v1.2.3 From 6edefb829c2417b763478cde3fbbc483ed196b04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Sun, 17 Sep 2017 19:33:11 +0200 Subject: script: remove unused function. --- components/script/dom/bindings/codegen/CodegenRust.py | 1 - 1 file changed, 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c42ec783716..afb189ec795 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5720,7 +5720,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::conversions::root_from_handleobject', 'dom::bindings::conversions::root_from_handlevalue', 'dom::bindings::conversions::root_from_object', - 'dom::bindings::conversions::string_jsid_to_string', 'dom::bindings::conversions::jsid_to_string', 'dom::bindings::codegen::PrototypeList', 'dom::bindings::codegen::RegisterBindings', -- cgit v1.2.3 From 90fb2847207678e7feee06eaf17d75ac359d6a07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Mon, 18 Sep 2017 06:55:08 +0200 Subject: script: Properly implement LegacyPlatformGetOwnProperty in WebIDL. We were missing the "ignoreNamedProperties" bit, which my previous patch uncovers. --- .../script/dom/bindings/codegen/CodegenRust.py | 33 ++++++++++++++++------ 1 file changed, 24 insertions(+), 9 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index afb189ec795..174bda2b0ca 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4817,15 +4817,14 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): "bool", args) self.descriptor = descriptor + # https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty def getBody(self): indexedGetter = self.descriptor.operations['IndexedGetter'] - indexedSetter = self.descriptor.operations['IndexedSetter'] get = "" - if indexedGetter or indexedSetter: + if indexedGetter: get = "let index = get_array_index_from_id(cx, id);\n" - if indexedGetter: attrs = "JSPROP_ENUMERATE" if self.descriptor.operations['IndexedSetter'] is None: attrs += " | JSPROP_READONLY" @@ -4864,11 +4863,16 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): 'successCode': fillDescriptor, 'pre': 'rooted!(in(cx) let mut result_root = UndefinedValue());' } + + # See the similar-looking in CGDOMJSProxyHandler_get for the spec quote. + condition = "RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id)" + if indexedGetter: + condition = "index.is_none() && (%s)" % condition # Once we start supporting OverrideBuiltins we need to make # ResolveOwnProperty or EnumerateOwnProperties filter out named # properties that shadow prototype properties. namedGet = """ -if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) { +if %s { let mut has_on_proto = false; if !has_property_on_prototype(cx, proxy, id, &mut has_on_proto) { return false; @@ -4877,7 +4881,7 @@ if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) { %s } } -""" % CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues), 8).define() +""" % (condition, CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues), 8).define()) else: namedGet = "" @@ -5093,9 +5097,12 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): indexed = "" namedGetter = self.descriptor.operations['NamedGetter'] + condition = "RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id)" + if indexedGetter: + condition = "index.is_none() && (%s)" % condition if namedGetter: named = """\ -if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) { +if %s { let mut has_on_proto = false; if !has_property_on_prototype(cx, proxy, id, &mut has_on_proto) { return false; @@ -5107,7 +5114,7 @@ if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) { } } -""" % CGIndenter(CGProxyNamedGetter(self.descriptor), 8).define() +""" % (condition, CGIndenter(CGProxyNamedGetter(self.descriptor), 8).define()) else: named = "" @@ -5136,6 +5143,7 @@ class CGDOMJSProxyHandler_get(CGAbstractExternMethod): CGAbstractExternMethod.__init__(self, descriptor, "get", "bool", args) self.descriptor = descriptor + # https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty def getBody(self): getFromExpando = """\ rooted!(in(cx) let mut expando = ptr::null_mut()); @@ -5175,9 +5183,16 @@ if !expando.is_null() { namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: - getNamed = ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + + condition = "RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id)" + # From step 1: + # If O supports indexed properties and P is an array index, then: + # + # 3. Set ignoreNamedProps to true. + if indexedGetter: + condition = "index.is_none() && (%s)" % condition + getNamed = ("if %s {\n" + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + - "}\n") + "}\n") % condition else: getNamed = "" -- cgit v1.2.3 From 658dc8a5013973ceff3c91291d5536043b2e8e58 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Thu, 21 Sep 2017 15:35:04 +0200 Subject: Rename a couple of Promise methods --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 174bda2b0ca..9a98848108b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -788,7 +788,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if !JS_WrapValue(cx, valueToResolve.handle_mut()) { $*{exceptionCode} } - match Promise::Resolve(&promiseGlobal, cx, valueToResolve.handle()) { + match Promise::new_resolved(&promiseGlobal, cx, valueToResolve.handle()) { Ok(value) => value, Err(error) => { throw_dom_exception(cx, &promiseGlobal, error); -- cgit v1.2.3 From e481e8934a0c37a4b1eba19862ff732ec9bf19c9 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Fri, 26 May 2017 12:40:50 -0400 Subject: Don't generate union conversion functions for object variants. --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 9a98848108b..208d4b1d923 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4313,10 +4313,14 @@ class CGUnionConversionStruct(CGThing): returnType = "Result, ()>" % templateVars["typeName"] jsConversion = templateVars["jsConversion"] + # Any code to convert to Object is unused, since we're already converting + # from an Object value. + if t.name == 'Object': + return CGGeneric('') + return CGWrapper( CGIndenter(jsConversion, 4), - # TryConvertToObject is unused, but not generating it while generating others is tricky. - pre="#[allow(dead_code)] unsafe fn TryConvertTo%s(cx: *mut JSContext, value: HandleValue) -> %s {\n" + pre="unsafe fn TryConvertTo%s(cx: *mut JSContext, value: HandleValue) -> %s {\n" % (t.name, returnType), post="\n}") -- cgit v1.2.3 From da65698c5c5934220b82493b3f7bb2ab05a2e512 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Fri, 26 May 2017 12:29:31 -0400 Subject: Be more conservative about safety of dictionary and union values. Mark dictionaries containing GC values as must_root, and wrap them in RootedTraceableBox in automatically-generated APIs. To accommodate union variants that are now flagged as unsafe, add RootedTraceableBox to union variants that need to be rooted, rather than wrapping the entire union value. --- .../script/dom/bindings/codegen/CodegenRust.py | 43 ++++++++++++++++++---- 1 file changed, 35 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 208d4b1d923..4d31da25efe 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -723,9 +723,6 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type.nullable(): declType = CGWrapper(declType, pre="Option<", post=" >") - if isMember != "Dictionary" and type_needs_tracing(type): - declType = CGTemplatedType("RootedTraceableBox", declType) - templateBody = ("match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" " Ok(ConversionResult::Success(value)) => value,\n" " Ok(ConversionResult::Failure(error)) => {\n" @@ -1427,6 +1424,8 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): nullable = returnType.nullable() dictName = returnType.inner.name if nullable else returnType.name result = CGGeneric(dictName) + if type_needs_tracing(returnType): + result = CGWrapper(result, pre="RootedTraceableBox<", post=">") if nullable: result = CGWrapper(result, pre="Option<", post=">") return result @@ -2262,6 +2261,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::str::ByteString', 'dom::bindings::str::DOMString', 'dom::bindings::str::USVString', + 'dom::bindings::trace::RootedTraceableBox', 'dom::types::*', 'js::error::throw_type_error', 'js::jsapi::HandleValue', @@ -4132,15 +4132,23 @@ class CGUnionStruct(CGThing): self.type = type self.descriptorProvider = descriptorProvider + def membersNeedTracing(self): + for t in self.type.flatMemberTypes: + if type_needs_tracing(t): + return True + return False + def define(self): - templateVars = map(lambda t: getUnionTypeTemplateVars(t, self.descriptorProvider), + templateVars = map(lambda t: (getUnionTypeTemplateVars(t, self.descriptorProvider), + type_needs_tracing(t)), self.type.flatMemberTypes) enumValues = [ - " %s(%s)," % (v["name"], v["typeName"]) for v in templateVars + " %s(%s)," % (v["name"], "RootedTraceableBox<%s>" % v["typeName"] if trace else v["typeName"]) + for (v, trace) in templateVars ] enumConversions = [ " %s::%s(ref inner) => inner.to_jsval(cx, rval)," - % (self.type, v["name"]) for v in templateVars + % (self.type, v["name"]) for (v, _) in templateVars ] return ("""\ #[derive(JSTraceable)] @@ -4167,6 +4175,12 @@ class CGUnionConversionStruct(CGThing): self.type = type self.descriptorProvider = descriptorProvider + def membersNeedTracing(self): + for t in self.type.flatMemberTypes: + if type_needs_tracing(t): + return True + return False + def from_jsval(self): memberTypes = self.type.flatMemberTypes names = [] @@ -4310,7 +4324,10 @@ class CGUnionConversionStruct(CGThing): def try_method(self, t): templateVars = getUnionTypeTemplateVars(t, self.descriptorProvider) - returnType = "Result, ()>" % templateVars["typeName"] + actualType = templateVars["typeName"] + if type_needs_tracing(t): + actualType = "RootedTraceableBox<%s>" % actualType + returnType = "Result, ()>" % actualType jsConversion = templateVars["jsConversion"] # Any code to convert to Object is unused, since we're already converting @@ -6022,13 +6039,17 @@ class CGDictionary(CGThing): (self.makeMemberName(m[0].identifier.name), self.getMemberType(m)) for m in self.memberInfo] + mustRoot = "#[must_root]\n" if self.membersNeedTracing() else "" + return (string.Template( "#[derive(JSTraceable)]\n" + "${mustRoot}" + "pub struct ${selfName} {\n" + "${inheritance}" + "\n".join(memberDecls) + "\n" + "}").substitute({"selfName": self.makeClassName(d), - "inheritance": inheritance})) + "inheritance": inheritance, + "mustRoot": mustRoot})) def impl(self): d = self.dictionary @@ -6120,6 +6141,12 @@ class CGDictionary(CGThing): "insertMembers": CGIndenter(memberInserts, indentLevel=8).define(), }) + def membersNeedTracing(self): + for member, _ in self.memberInfo: + if type_needs_tracing(member.type): + return True + return False + @staticmethod def makeDictionaryName(dictionary): return dictionary.identifier.name -- cgit v1.2.3 From b169689f32db6d497b04f3a5b173cba4acd33e93 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Fri, 26 May 2017 13:25:05 -0400 Subject: Store rootable dictionary members of dictionaries in RootedTraceableBox. --- .../script/dom/bindings/codegen/CodegenRust.py | 27 +++++++++++++++------- 1 file changed, 19 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 4d31da25efe..5b2b987c233 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1096,9 +1096,8 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, declType = CGGeneric(typeName) empty = "%s::empty(cx)" % typeName - if isMember != "Dictionary" and type_needs_tracing(type): + if type_needs_tracing(type): declType = CGTemplatedType("RootedTraceableBox", declType) - empty = "RootedTraceableBox::new(%s)" % empty template = ("match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" " Ok(ConversionResult::Success(dictionary)) => dictionary,\n" @@ -6094,16 +6093,24 @@ class CGDictionary(CGThing): memberInits = CGList([memberInit(m) for m in self.memberInfo]) memberInserts = CGList([memberInsert(m) for m in self.memberInfo]) + actualType = self.makeClassName(d) + preInitial = "" + postInitial = "" + if self.membersNeedTracing(): + actualType = "RootedTraceableBox<%s>" % actualType + preInitial = "RootedTraceableBox::new(" + postInitial = ")" + return string.Template( "impl ${selfName} {\n" - " pub unsafe fn empty(cx: *mut JSContext) -> ${selfName} {\n" + " pub unsafe fn empty(cx: *mut JSContext) -> ${actualType} {\n" " match ${selfName}::new(cx, HandleValue::null()) {\n" " Ok(ConversionResult::Success(v)) => v,\n" " _ => unreachable!(),\n" " }\n" " }\n" " pub unsafe fn new(cx: *mut JSContext, val: HandleValue) \n" - " -> Result, ()> {\n" + " -> Result, ()> {\n" " let object = if val.get().is_null_or_undefined() {\n" " ptr::null_mut()\n" " } else if val.get().is_object() {\n" @@ -6113,17 +6120,18 @@ class CGDictionary(CGThing): " return Err(());\n" " };\n" " rooted!(in(cx) let object = object);\n" - " Ok(ConversionResult::Success(${selfName} {\n" + " let dictionary = ${preInitial}${selfName} {\n" "${initParent}" "${initMembers}" - " }))\n" + " }${postInitial};\n" + " Ok(ConversionResult::Success(dictionary))\n" " }\n" "}\n" "\n" - "impl FromJSValConvertible for ${selfName} {\n" + "impl FromJSValConvertible for ${actualType} {\n" " type Config = ();\n" " unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, _option: ())\n" - " -> Result, ()> {\n" + " -> Result, ()> {\n" " ${selfName}::new(cx, value)\n" " }\n" "}\n" @@ -6136,9 +6144,12 @@ class CGDictionary(CGThing): " }\n" "}\n").substitute({ "selfName": self.makeClassName(d), + "actualType": actualType, "initParent": CGIndenter(CGGeneric(initParent), indentLevel=12).define(), "initMembers": CGIndenter(memberInits, indentLevel=12).define(), "insertMembers": CGIndenter(memberInserts, indentLevel=8).define(), + "preInitial": CGGeneric(preInitial).define(), + "postInitial": CGGeneric(postInitial).define(), }) def membersNeedTracing(self): -- cgit v1.2.3 From 16166d66731d7040a91ddbed6ffd05d4fc64c97b Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Fri, 26 May 2017 13:46:13 -0400 Subject: Derive the Default trait for dictionaries containing GC values. --- components/script/dom/bindings/codegen/CodegenRust.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 5b2b987c233..aa58afe1913 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4028,12 +4028,18 @@ impl super::%s { } } +impl Default for super::%s { + fn default() -> super::%s { + pairs[0].1 + } +} + impl ToJSValConvertible for super::%s { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { pairs[*self as usize].0.to_jsval(cx, rval); } } - """ % (ident, pairs, ident, ident) + """ % (ident, pairs, ident, ident, ident, ident) self.cgRoot = CGList([ CGGeneric(decl), CGNamespace.build([ident + "Values"], @@ -6038,17 +6044,22 @@ class CGDictionary(CGThing): (self.makeMemberName(m[0].identifier.name), self.getMemberType(m)) for m in self.memberInfo] - mustRoot = "#[must_root]\n" if self.membersNeedTracing() else "" + derive = ["JSTraceable"] + mustRoot = "" + if self.membersNeedTracing(): + mustRoot = "#[must_root]\n" + derive += ["Default"] return (string.Template( - "#[derive(JSTraceable)]\n" + "#[derive(${derive})]\n" "${mustRoot}" + "pub struct ${selfName} {\n" + "${inheritance}" + "\n".join(memberDecls) + "\n" + "}").substitute({"selfName": self.makeClassName(d), "inheritance": inheritance, - "mustRoot": mustRoot})) + "mustRoot": mustRoot, + "derive": ', '.join(derive)})) def impl(self): d = self.dictionary -- cgit v1.2.3 From f5eb8445b05d892b432d769f5e036f786e223fd4 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Fri, 26 May 2017 14:27:05 -0400 Subject: Initialize rooted dictionaries to a stable value before setting fields. --- .../script/dom/bindings/codegen/CodegenRust.py | 52 +++++++++++++--------- 1 file changed, 30 insertions(+), 22 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index aa58afe1913..05db89f3766 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1045,12 +1045,12 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if defaultValue is None: default = None elif isinstance(defaultValue, IDLNullValue): - default = "Heap::new(NullValue())" + default = "NullValue()" elif isinstance(defaultValue, IDLUndefinedValue): - default = "Heap::new(UndefinedValue())" + default = "UndefinedValue()" else: raise TypeError("Can't handle non-null, non-undefined default value here") - return handleOptional("Heap::new(${val}.get())", declType, default) + return handleOptional("${val}.get()", declType, default) declType = CGGeneric("HandleValue") @@ -1077,8 +1077,6 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if isMember in ("Dictionary", "Union"): declType = CGGeneric("Heap<*mut JSObject>") - templateBody = "Heap::new(%s)" % templateBody - default = "Heap::new(%s)" % default else: # TODO: Need to root somehow # https://github.com/servo/servo/issues/6382 @@ -5708,6 +5706,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::iterable::Iterable', 'dom::bindings::iterable::IteratorType', 'dom::bindings::js::JS', + 'dom::bindings::js::OptionalHeapSetter', 'dom::bindings::js::Root', 'dom::bindings::js::RootedReference', 'dom::bindings::namespace::NamespaceObjectClass', @@ -6064,7 +6063,7 @@ class CGDictionary(CGThing): def impl(self): d = self.dictionary if d.parent: - initParent = ("parent: {\n" + initParent = ("{\n" " match try!(%s::%s::new(cx, val)) {\n" " ConversionResult::Success(v) => v,\n" " ConversionResult::Failure(error) => {\n" @@ -6072,16 +6071,20 @@ class CGDictionary(CGThing): " return Err(());\n" " }\n" " }\n" - "},\n" % (self.makeModuleName(d.parent), - self.makeClassName(d.parent))) + "}" % (self.makeModuleName(d.parent), + self.makeClassName(d.parent))) else: initParent = "" - def memberInit(memberInfo): + def memberInit(memberInfo, isInitial): member, _ = memberInfo name = self.makeMemberName(member.identifier.name) conversion = self.getMemberConversion(memberInfo, member.type) - return CGGeneric("%s: %s,\n" % (name, conversion.define())) + if isInitial: + return CGGeneric("%s: %s,\n" % (name, conversion.define())) + if member.type.isAny() or member.type.isObject(): + return CGGeneric("dictionary.%s.set(%s);\n" % (name, conversion.define())) + return CGGeneric("dictionary.%s = %s;\n" % (name, conversion.define())) def varInsert(varName, dictionaryName): insertion = ("rooted!(in(cx) let mut %s_js = UndefinedValue());\n" @@ -6101,16 +6104,21 @@ class CGDictionary(CGThing): (name, name, varInsert(name, member.identifier.name).define())) return CGGeneric("%s\n" % insertion.define()) - memberInits = CGList([memberInit(m) for m in self.memberInfo]) memberInserts = CGList([memberInsert(m) for m in self.memberInfo]) - actualType = self.makeClassName(d) - preInitial = "" - postInitial = "" + selfName = self.makeClassName(d) if self.membersNeedTracing(): - actualType = "RootedTraceableBox<%s>" % actualType - preInitial = "RootedTraceableBox::new(" - postInitial = ")" + actualType = "RootedTraceableBox<%s>" % selfName + preInitial = "let mut dictionary = RootedTraceableBox::new(%s::default());\n" % selfName + initParent = initParent = ("dictionary.parent = %s;\n" % initParent) if initParent else "" + memberInits = CGList([memberInit(m, False) for m in self.memberInfo]) + postInitial = "" + else: + actualType = selfName + preInitial = "let dictionary = %s {\n" % selfName + postInitial = "};\n" + initParent = ("parent: %s,\n" % initParent) if initParent else "" + memberInits = CGList([memberInit(m, True) for m in self.memberInfo]) return string.Template( "impl ${selfName} {\n" @@ -6131,10 +6139,10 @@ class CGDictionary(CGThing): " return Err(());\n" " };\n" " rooted!(in(cx) let object = object);\n" - " let dictionary = ${preInitial}${selfName} {\n" + "${preInitial}" "${initParent}" "${initMembers}" - " }${postInitial};\n" + "${postInitial}" " Ok(ConversionResult::Success(dictionary))\n" " }\n" "}\n" @@ -6154,13 +6162,13 @@ class CGDictionary(CGThing): " rval.set(ObjectOrNullValue(obj.get()))\n" " }\n" "}\n").substitute({ - "selfName": self.makeClassName(d), + "selfName": selfName, "actualType": actualType, "initParent": CGIndenter(CGGeneric(initParent), indentLevel=12).define(), "initMembers": CGIndenter(memberInits, indentLevel=12).define(), "insertMembers": CGIndenter(memberInserts, indentLevel=8).define(), - "preInitial": CGGeneric(preInitial).define(), - "postInitial": CGGeneric(postInitial).define(), + "preInitial": CGIndenter(CGGeneric(preInitial), indentLevel=12).define(), + "postInitial": CGIndenter(CGGeneric(postInitial), indentLevel=12).define(), }) def membersNeedTracing(self): -- cgit v1.2.3 From 77b3e911c11b2472efa4d7aea944f6aee56171c4 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Fri, 26 May 2017 10:47:09 -0400 Subject: Remove almost all uses of Heap::new. --- components/script/dom/bindings/codegen/CodegenRust.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 05db89f3766..30d847da19f 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6699,7 +6699,7 @@ class CallbackMember(CGNativeMember): replacements["argCount"] = self.argCountStr replacements["argvDecl"] = string.Template( "rooted_vec!(let mut argv);\n" - "argv.extend((0..${argCount}).map(|_| Heap::new(UndefinedValue())));\n" + "argv.extend((0..${argCount}).map(|_| Heap::default()));\n" ).substitute(replacements) else: # Avoid weird 0-sized arrays @@ -6774,7 +6774,11 @@ class CallbackMember(CGNativeMember): conversion = wrapForType( "argv_root.handle_mut()", result=argval, - successCode="argv[%s] = Heap::new(argv_root.get());" % jsvalIndex, + successCode=("{\n" + + "let arg = &mut argv[%s];\n" + + "*arg = Heap::default();\n" + + "arg.set(argv_root.get());\n" + + "}") % jsvalIndex, pre="rooted!(in(cx) let mut argv_root = UndefinedValue());") if arg.variadic: conversion = string.Template( @@ -6790,7 +6794,7 @@ class CallbackMember(CGNativeMember): " // This is our current trailing argument; reduce argc\n" " argc -= 1;\n" "} else {\n" - " argv[%d] = Heap::new(UndefinedValue());\n" + " argv[%d] = Heap::default();\n" "}" % (i + 1, i)) return conversion -- cgit v1.2.3 From 44822c364c2f1970705834fb0f95df1411089f9d Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Mon, 26 Jun 2017 07:46:19 -0400 Subject: Use more named string interpolation. --- .../script/dom/bindings/codegen/CodegenRust.py | 23 ++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 30d847da19f..68ab0a33c18 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4011,33 +4011,36 @@ pub enum %s { pairs = ",\n ".join(['("%s", super::%s::%s)' % (val, ident, getEnumValueName(val)) for val in enum.values()]) - inner = """\ + inner = string.Template("""\ use dom::bindings::conversions::ToJSValConvertible; use js::jsapi::{JSContext, MutableHandleValue}; use js::jsval::JSVal; -pub const pairs: &'static [(&'static str, super::%s)] = &[ - %s, +pub const pairs: &'static [(&'static str, super::${ident})] = &[ + ${pairs}, ]; -impl super::%s { +impl super::${ident} { pub fn as_str(&self) -> &'static str { pairs[*self as usize].0 } } -impl Default for super::%s { - fn default() -> super::%s { - pairs[0].1 - } +impl Default for super::${ident} { + fn default() -> super::${ident} { + pairs[0].1 + } } -impl ToJSValConvertible for super::%s { +impl ToJSValConvertible for super::${ident} { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { pairs[*self as usize].0.to_jsval(cx, rval); } } - """ % (ident, pairs, ident, ident, ident, ident) + """).substitute({ + 'ident': ident, + 'pairs': pairs + }) self.cgRoot = CGList([ CGGeneric(decl), CGNamespace.build([ident + "Values"], -- cgit v1.2.3 From 0e3c54c1911ba2c3bf305ee04f04fcd9bf2fc2fe Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 25 Sep 2017 23:30:24 +0200 Subject: Rename dom::bindings::js to dom::bindings::root --- components/script/dom/bindings/codegen/CodegenRust.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 68ab0a33c18..03c2076951b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2253,8 +2253,8 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::conversions::StringificationBehavior', 'dom::bindings::conversions::root_from_handlevalue', 'dom::bindings::error::throw_not_in_union', - 'dom::bindings::js::Root', 'dom::bindings::mozmap::MozMap', + 'dom::bindings::root::Root', 'dom::bindings::str::ByteString', 'dom::bindings::str::DOMString', 'dom::bindings::str::USVString', @@ -5708,14 +5708,14 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::interface::push_new_element_queue', 'dom::bindings::iterable::Iterable', 'dom::bindings::iterable::IteratorType', - 'dom::bindings::js::JS', - 'dom::bindings::js::OptionalHeapSetter', - 'dom::bindings::js::Root', - 'dom::bindings::js::RootedReference', 'dom::bindings::namespace::NamespaceObjectClass', 'dom::bindings::namespace::create_namespace_object', 'dom::bindings::reflector::MutDomObject', 'dom::bindings::reflector::DomObject', + 'dom::bindings::root::JS', + 'dom::bindings::root::OptionalHeapSetter', + 'dom::bindings::root::Root', + 'dom::bindings::root::RootedReference', 'dom::bindings::utils::AsVoidPtr', 'dom::bindings::utils::DOMClass', 'dom::bindings::utils::DOMJSClass', @@ -7195,7 +7195,7 @@ class GlobalGenRoots(): imports = [CGGeneric("use dom::types::*;\n"), CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), CGGeneric("use dom::bindings::inheritance::Castable;\n"), - CGGeneric("use dom::bindings::js::{JS, LayoutJS, Root};\n"), + CGGeneric("use dom::bindings::root::{JS, LayoutJS, Root};\n"), CGGeneric("use dom::bindings::trace::JSTraceable;\n"), CGGeneric("use dom::bindings::reflector::DomObject;\n"), CGGeneric("use js::jsapi::JSTracer;\n\n"), -- cgit v1.2.3 From 7be32fb2371a14ba61b008a37e79761f66c073c7 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 25 Sep 2017 23:56:32 +0200 Subject: Rename JS to Dom --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 03c2076951b..3f99ea37a41 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1272,7 +1272,7 @@ class CGArgumentConverter(CGThing): arg = "arg%d" % index if argument.type.isGeckoInterface(): init = "rooted_vec!(let mut %s)" % arg - innerConverter.append(CGGeneric("%s.push(JS::from_ref(&*slot));" % arg)) + innerConverter.append(CGGeneric("%s.push(Dom::from_ref(&*slot));" % arg)) else: init = "let mut %s = vec![]" % arg innerConverter.append(CGGeneric("%s.push(slot);" % arg)) @@ -5712,7 +5712,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::namespace::create_namespace_object', 'dom::bindings::reflector::MutDomObject', 'dom::bindings::reflector::DomObject', - 'dom::bindings::root::JS', + 'dom::bindings::root::Dom', 'dom::bindings::root::OptionalHeapSetter', 'dom::bindings::root::Root', 'dom::bindings::root::RootedReference', @@ -6961,7 +6961,7 @@ class CallbackGetter(CallbackMember): needThisHandling=False) def getRvalDecl(self): - return "JS::Rooted rval(cx, JS::UndefinedValue());\n" + return "Dom::Rooted rval(cx, JS::UndefinedValue());\n" def getCall(self): replacements = { @@ -7195,7 +7195,7 @@ class GlobalGenRoots(): imports = [CGGeneric("use dom::types::*;\n"), CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), CGGeneric("use dom::bindings::inheritance::Castable;\n"), - CGGeneric("use dom::bindings::root::{JS, LayoutJS, Root};\n"), + CGGeneric("use dom::bindings::root::{Dom, LayoutJS, Root};\n"), CGGeneric("use dom::bindings::trace::JSTraceable;\n"), CGGeneric("use dom::bindings::reflector::DomObject;\n"), CGGeneric("use js::jsapi::JSTracer;\n\n"), -- cgit v1.2.3 From e2dac78d3600cb4b2b4474f1db4f0fcaadbe24ea Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 26 Sep 2017 01:30:06 +0200 Subject: Rename LayoutJS to LayoutDom --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3f99ea37a41..888a17a3a8c 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -7195,7 +7195,7 @@ class GlobalGenRoots(): imports = [CGGeneric("use dom::types::*;\n"), CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), CGGeneric("use dom::bindings::inheritance::Castable;\n"), - CGGeneric("use dom::bindings::root::{Dom, LayoutJS, Root};\n"), + CGGeneric("use dom::bindings::root::{Dom, LayoutDom, Root};\n"), CGGeneric("use dom::bindings::trace::JSTraceable;\n"), CGGeneric("use dom::bindings::reflector::DomObject;\n"), CGGeneric("use js::jsapi::JSTracer;\n\n"), -- cgit v1.2.3 From f87c2a8d7616112ca924e30292db2d244cf87eec Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 26 Sep 2017 01:53:40 +0200 Subject: Rename Root to DomRoot In a later PR, DomRoot will become a type alias of Root>, where Root will be able to handle all the things that need to be rooted that have a stable traceable address that doesn't move for the whole lifetime of the root. Stay tuned. --- .../script/dom/bindings/codegen/CodegenRust.py | 26 +++++++++++++--------- 1 file changed, 15 insertions(+), 11 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 888a17a3a8c..8880707f7d5 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2254,7 +2254,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::conversions::root_from_handlevalue', 'dom::bindings::error::throw_not_in_union', 'dom::bindings::mozmap::MozMap', - 'dom::bindings::root::Root', + 'dom::bindings::root::DomRoot', 'dom::bindings::str::ByteString', 'dom::bindings::str::DOMString', 'dom::bindings::str::USVString', @@ -2558,7 +2558,7 @@ class CGWrapMethod(CGAbstractMethod): args = [Argument('*mut JSContext', 'cx'), Argument('&GlobalScope', 'scope'), Argument("Box<%s>" % descriptor.concreteType, 'object')] - retval = 'Root<%s>' % descriptor.concreteType + retval = 'DomRoot<%s>' % descriptor.concreteType CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, pub=True, unsafe=True) @@ -2580,7 +2580,7 @@ assert!(!proto.is_null()); %(copyUnforgeable)s (*raw).init_reflector(obj.get()); -Root::from_ref(&*raw)""" % {'copyUnforgeable': unforgeable, 'createObject': create}) +DomRoot::from_ref(&*raw)""" % {'copyUnforgeable': unforgeable, 'createObject': create}) class CGWrapGlobalMethod(CGAbstractMethod): @@ -2592,7 +2592,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): assert descriptor.isGlobal() args = [Argument('*mut JSContext', 'cx'), Argument("Box<%s>" % descriptor.concreteType, 'object')] - retval = 'Root<%s>' % descriptor.concreteType + retval = 'DomRoot<%s>' % descriptor.concreteType CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, pub=True, unsafe=True) self.properties = properties @@ -2638,7 +2638,7 @@ assert!(immutable); %(unforgeable)s -Root::from_ref(&*raw)\ +DomRoot::from_ref(&*raw)\ """ % values) @@ -3421,7 +3421,9 @@ class CGAbstractStaticBindingMethod(CGAbstractMethod): def definition_body(self): preamble = "let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n" if len(self.exposureSet) == 1: - preamble += "let global = Root::downcast::(global).unwrap();\n" % list(self.exposureSet)[0] + preamble += """ +let global = DomRoot::downcast::(global).unwrap(); +""" % list(self.exposureSet)[0] return CGList([CGGeneric(preamble), self.generate_code()]) def generate_code(self): @@ -5352,7 +5354,9 @@ class CGClassConstructHook(CGAbstractExternMethod): def definition_body(self): preamble = """let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n""" if len(self.exposureSet) == 1: - preamble += "let global = Root::downcast::(global).unwrap();\n" % list(self.exposureSet)[0] + preamble += """\ +let global = DomRoot::downcast::(global).unwrap(); +""" % list(self.exposureSet)[0] preamble += """let args = CallArgs::from_vp(vp, argc);\n""" preamble = CGGeneric(preamble) if self.constructor.isHTMLConstructor(): @@ -5408,7 +5412,7 @@ if !JS_WrapObject(cx, prototype.handle_mut()) { return false; } -let result: Result, Error> = html_constructor(&global, &args); +let result: Result, Error> = html_constructor(&global, &args); let result = match result { Ok(result) => result, Err(e) => { @@ -5713,8 +5717,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::reflector::MutDomObject', 'dom::bindings::reflector::DomObject', 'dom::bindings::root::Dom', + 'dom::bindings::root::DomRoot', 'dom::bindings::root::OptionalHeapSetter', - 'dom::bindings::root::Root', 'dom::bindings::root::RootedReference', 'dom::bindings::utils::AsVoidPtr', 'dom::bindings::utils::DOMClass', @@ -6281,7 +6285,7 @@ class CGRegisterProxyHandlers(CGThing): class CGBindingRoot(CGThing): """ - Root codegen class for binding generation. Instantiate the class, and call + DomRoot codegen class for binding generation. Instantiate the class, and call declare or define to generate header or cpp code (respectively). """ def __init__(self, config, prefix, webIDLFile): @@ -7195,7 +7199,7 @@ class GlobalGenRoots(): imports = [CGGeneric("use dom::types::*;\n"), CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), CGGeneric("use dom::bindings::inheritance::Castable;\n"), - CGGeneric("use dom::bindings::root::{Dom, LayoutDom, Root};\n"), + CGGeneric("use dom::bindings::root::{Dom, DomRoot, LayoutDom};\n"), CGGeneric("use dom::bindings::trace::JSTraceable;\n"), CGGeneric("use dom::bindings::reflector::DomObject;\n"), CGGeneric("use js::jsapi::JSTracer;\n\n"), -- cgit v1.2.3 From 3d0b7fbc413f975d6302428947132366f0e339d5 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 4 Jun 2016 15:20:04 +0200 Subject: Implement EventListenerOptions for EventTarget For now, only "capture" is supported. --- components/script/dom/bindings/codegen/CodegenRust.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 8880707f7d5..a82ad040041 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6142,8 +6142,7 @@ class CGDictionary(CGThing): " } else if val.get().is_object() {\n" " val.get().to_object()\n" " } else {\n" - " throw_type_error(cx, \"Value not an object.\");\n" - " return Err(());\n" + " return Ok(ConversionResult::Failure(\"Value is not an object.\".into()));\n" " };\n" " rooted!(in(cx) let object = object);\n" "${preInitial}" -- cgit v1.2.3 From e2fafd2dfc7a1b66fb224c83e15042d8f6d595c0 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Sat, 14 Oct 2017 12:54:57 +0200 Subject: Replace NonZero<*mut JSObject> with a wrapper to enable local trait impls. --- components/script/dom/bindings/codegen/CodegenRust.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index a82ad040041..084945fad6b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1407,7 +1407,7 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): if returnType.isAny(): return CGGeneric("JSVal") if returnType.isObject() or returnType.isSpiderMonkeyInterface(): - result = CGGeneric("NonZero<*mut JSObject>") + result = CGGeneric("NonNullJSObjectPtr") if returnType.nullable(): result = CGWrapper(result, pre="Option<", post=">") return result @@ -2253,6 +2253,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::conversions::StringificationBehavior', 'dom::bindings::conversions::root_from_handlevalue', 'dom::bindings::error::throw_not_in_union', + 'dom::bindings::nonnull::NonNullJSObjectPtr', 'dom::bindings::mozmap::MozMap', 'dom::bindings::root::DomRoot', 'dom::bindings::str::ByteString', @@ -5785,6 +5786,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::proxyhandler::get_expando_object', 'dom::bindings::proxyhandler::get_property_descriptor', 'dom::bindings::mozmap::MozMap', + 'dom::bindings::nonnull::NonNullJSObjectPtr', 'dom::bindings::num::Finite', 'dom::bindings::str::ByteString', 'dom::bindings::str::DOMString', -- cgit v1.2.3 From 99b052d3a6d59ad17ed2bf3d3c54af2bb40d926a Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Sat, 14 Oct 2017 13:05:28 +0200 Subject: Move remaining uses of NonZero to our nonzero crate --- components/script/dom/bindings/codegen/CodegenRust.py | 1 - 1 file changed, 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 084945fad6b..5d4e66f71f4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5575,7 +5575,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries typedefs = [] return CGImports(cgthings, descriptors, callbacks, dictionaries, enums, typedefs, [ - 'core::nonzero::NonZero', 'js', 'js::JSCLASS_GLOBAL_SLOT_COUNT', 'js::JSCLASS_IS_DOMJSCLASS', -- cgit v1.2.3 From 3bb76a5be590a40451ead6c926d19ea2d705ad03 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Thu, 12 Oct 2017 20:27:10 +0200 Subject: =?UTF-8?q?Don=E2=80=99t=20rely=20on=20unstable=20'const=20fn's=20?= =?UTF-8?q?in=20rust-mozjs,=20so=20we=20can=20remove=20them.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../script/dom/bindings/codegen/CodegenRust.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 5d4e66f71f4..feb39a532f6 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3661,18 +3661,16 @@ class CGMemberJITInfo(CGThing): protoID: PrototypeList::ID::${name} as u16, depth: ${depth}, _bitfield_1: - JSJitInfo::new_bitfield_1( - JSJitInfo_OpType::${opType} as u8, - JSJitInfo_AliasSet::${aliasSet} as u8, - JSValueType::${returnType} as u8, - ${isInfallible}, - ${isMovable}, - ${isEliminatable}, - ${isAlwaysInSlot}, - ${isLazilyCachedInSlot}, - ${isTypedMethod}, - ${slotIndex} as u16, - ) + ((JSJitInfo_OpType::${opType} as u8 as u32) << 0) | + ((JSJitInfo_AliasSet::${aliasSet} as u8 as u32) << 4) | + ((JSValueType::${returnType} as u8 as u32) << 8) | + ((${isInfallible} as u32) << 16) | + ((${isMovable} as u32) << 17) | + ((${isEliminatable} as u32) << 18) | + ((${isAlwaysInSlot} as u32) << 19) | + ((${isLazilyCachedInSlot} as u32) << 20) | + ((${isTypedMethod} as u32) << 21) | + ((${slotIndex} as u32) << 22) } """, opName=opName, -- cgit v1.2.3 From 49e4540ece8641afcb6534a9c3b74e88895f5447 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Sat, 14 Oct 2017 14:05:05 +0200 Subject: Update rust-mozjs --- .../script/dom/bindings/codegen/CodegenRust.py | 23 +++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index feb39a532f6..d0b5e678db8 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3660,17 +3660,18 @@ class CGMemberJITInfo(CGThing): call: ${opName} as *const os::raw::c_void, protoID: PrototypeList::ID::${name} as u16, depth: ${depth}, - _bitfield_1: - ((JSJitInfo_OpType::${opType} as u8 as u32) << 0) | - ((JSJitInfo_AliasSet::${aliasSet} as u8 as u32) << 4) | - ((JSValueType::${returnType} as u8 as u32) << 8) | - ((${isInfallible} as u32) << 16) | - ((${isMovable} as u32) << 17) | - ((${isEliminatable} as u32) << 18) | - ((${isAlwaysInSlot} as u32) << 19) | - ((${isLazilyCachedInSlot} as u32) << 20) | - ((${isTypedMethod} as u32) << 21) | - ((${slotIndex} as u32) << 22) + _bitfield_1: new_jsjitinfo_bitfield_1!( + JSJitInfo_OpType::${opType} as u8, + JSJitInfo_AliasSet::${aliasSet} as u8, + JSValueType::${returnType} as u8, + ${isInfallible}, + ${isMovable}, + ${isEliminatable}, + ${isAlwaysInSlot}, + ${isLazilyCachedInSlot}, + ${isTypedMethod}, + ${slotIndex}, + ), } """, opName=opName, -- cgit v1.2.3 From 4506f0d30cbbb02df32e9c16135ef288ad6b7e2e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 18 Oct 2017 10:42:01 +1100 Subject: Replace all uses of the `heapsize` crate with `malloc_size_of`. Servo currently uses `heapsize`, but Stylo/Gecko use `malloc_size_of`. `malloc_size_of` is better -- it handles various cases that `heapsize` does not -- so this patch changes Servo to use `malloc_size_of`. This patch makes the following changes to the `malloc_size_of` crate. - Adds `MallocSizeOf` trait implementations for numerous types, some built-in (e.g. `VecDeque`), some external and Servo-only (e.g. `string_cache`). - Makes `enclosing_size_of_op` optional, because vanilla jemalloc doesn't support that operation. - For `HashSet`/`HashMap`, falls back to a computed estimate when `enclosing_size_of_op` isn't available. - Adds an extern "C" `malloc_size_of` function that does the actual heap measurement; this is based on the same functions from the `heapsize` crate. This patch makes the following changes elsewhere. - Converts all the uses of `heapsize` to instead use `malloc_size_of`. - Disables the "heapsize"/"heap_size" feature for the external crates that provide it. - Removes the `HeapSizeOf` implementation from `hashglobe`. - Adds `ignore` annotations to a few `Rc`/`Arc`, because `malloc_size_of` doesn't derive those types, unlike `heapsize`. --- components/script/dom/bindings/codegen/CodegenRust.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index d0b5e678db8..3251290f398 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2029,7 +2029,7 @@ def DOMClass(descriptor): # padding. protoList.extend(['PrototypeList::ID::Last'] * (descriptor.config.maxProtoChainLength - len(protoList))) prototypeChainString = ', '.join(protoList) - heapSizeOf = 'heap_size_of_raw_self_and_children::<%s>' % descriptor.concreteType + mallocSizeOf = 'malloc_size_of_including_raw_self::<%s>' % descriptor.concreteType if descriptor.isGlobal(): globals_ = camel_to_upper_snake(descriptor.name) else: @@ -2038,9 +2038,9 @@ def DOMClass(descriptor): DOMClass { interface_chain: [ %s ], type_id: %s, - heap_size_of: %s as unsafe fn(_) -> _, + malloc_size_of: %s as unsafe fn(&mut _, _) -> _, global: InterfaceObjectMap::%s, -}""" % (prototypeChainString, DOMClassTypeId(descriptor), heapSizeOf, globals_) +}""" % (prototypeChainString, DOMClassTypeId(descriptor), mallocSizeOf, globals_) class CGDOMJSClass(CGThing): @@ -4005,7 +4005,7 @@ class CGEnum(CGThing): ident = enum.identifier.name decl = """\ #[repr(usize)] -#[derive(JSTraceable, PartialEq, Copy, Clone, HeapSizeOf, Debug)] +#[derive(Copy, Clone, Debug, JSTraceable, MallocSizeOf, PartialEq)] pub enum %s { %s } @@ -5794,7 +5794,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::weakref::WeakReferenceable', 'dom::windowproxy::WindowProxy', 'dom::globalscope::GlobalScope', - 'mem::heap_size_of_raw_self_and_children', + 'mem::malloc_size_of_including_raw_self', 'libc', 'servo_config::prefs::PREFS', 'std::borrow::ToOwned', -- cgit v1.2.3 From e8e2d0a4b24475b018dbc7e59ea46fdceaf20815 Mon Sep 17 00:00:00 2001 From: Bastien Orivel Date: Mon, 9 Oct 2017 17:03:40 +0200 Subject: Update bitflags to 1.0 in every servo crate It still needs dependencies update to remove all the other bitflags versions. --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3251290f398..859e98931a5 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2039,7 +2039,7 @@ DOMClass { interface_chain: [ %s ], type_id: %s, malloc_size_of: %s as unsafe fn(&mut _, _) -> _, - global: InterfaceObjectMap::%s, + global: InterfaceObjectMap::Globals::%s, }""" % (prototypeChainString, DOMClassTypeId(descriptor), mallocSizeOf, globals_) @@ -2445,7 +2445,7 @@ class CGConstructorEnabled(CGAbstractMethod): iface = self.descriptor.interface bits = " | ".join(sorted( - "InterfaceObjectMap::" + camel_to_upper_snake(i) for i in iface.exposureSet + "InterfaceObjectMap::Globals::" + camel_to_upper_snake(i) for i in iface.exposureSet )) conditions.append("is_exposed_in(aObj, %s)" % bits) @@ -7092,9 +7092,9 @@ class GlobalGenRoots(): for (idx, d) in enumerate(global_descriptors) ) global_flags = CGWrapper(CGIndenter(CGList([ - CGGeneric("const %s = %#x," % args) + CGGeneric("const %s = %#x;" % args) for args in flags - ], "\n")), pre="pub flags Globals: u8 {\n", post="\n}") + ], "\n")), pre="pub struct Globals: u8 {\n", post="\n}") globals_ = CGWrapper(CGIndenter(global_flags), pre="bitflags! {\n", post="\n}") phf = CGGeneric("include!(concat!(env!(\"OUT_DIR\"), \"/InterfaceObjectMapPhf.rs\"));") -- cgit v1.2.3 From 11c64178d86979e8d50f11cff66c2b0e8fe666c1 Mon Sep 17 00:00:00 2001 From: Gecko Backout Date: Thu, 19 Oct 2017 21:26:51 +0000 Subject: Backed out changeset e64e659c077d: servo PR #18809 and revendor for reftest failures, e.g. in layout/reftests/bugs/392435-1.html. r=backout on a CLOSED TREE Backs out https://github.com/servo/servo/pull/18809 --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 859e98931a5..3251290f398 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2039,7 +2039,7 @@ DOMClass { interface_chain: [ %s ], type_id: %s, malloc_size_of: %s as unsafe fn(&mut _, _) -> _, - global: InterfaceObjectMap::Globals::%s, + global: InterfaceObjectMap::%s, }""" % (prototypeChainString, DOMClassTypeId(descriptor), mallocSizeOf, globals_) @@ -2445,7 +2445,7 @@ class CGConstructorEnabled(CGAbstractMethod): iface = self.descriptor.interface bits = " | ".join(sorted( - "InterfaceObjectMap::Globals::" + camel_to_upper_snake(i) for i in iface.exposureSet + "InterfaceObjectMap::" + camel_to_upper_snake(i) for i in iface.exposureSet )) conditions.append("is_exposed_in(aObj, %s)" % bits) @@ -7092,9 +7092,9 @@ class GlobalGenRoots(): for (idx, d) in enumerate(global_descriptors) ) global_flags = CGWrapper(CGIndenter(CGList([ - CGGeneric("const %s = %#x;" % args) + CGGeneric("const %s = %#x," % args) for args in flags - ], "\n")), pre="pub struct Globals: u8 {\n", post="\n}") + ], "\n")), pre="pub flags Globals: u8 {\n", post="\n}") globals_ = CGWrapper(CGIndenter(global_flags), pre="bitflags! {\n", post="\n}") phf = CGGeneric("include!(concat!(env!(\"OUT_DIR\"), \"/InterfaceObjectMapPhf.rs\"));") -- cgit v1.2.3 From 3ed5899a64e2e386b3ed94954c5d41048c02335b Mon Sep 17 00:00:00 2001 From: Imanol Fernandez Date: Tue, 24 Oct 2017 18:44:18 +0200 Subject: Fix Const IDL value compilation errors in codegen --- components/script/dom/bindings/codegen/CodegenRust.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3251290f398..b7438e6be0a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1198,12 +1198,12 @@ def convertConstIDLValueToJSVal(value): if tag == IDLType.Tags.uint32: return "ConstantVal::UintVal(%s)" % (value.value) if tag in [IDLType.Tags.int64, IDLType.Tags.uint64]: - return "ConstantVal::DoubleVal(%s)" % (value.value) + return "ConstantVal::DoubleVal(%s as f64)" % (value.value) if tag == IDLType.Tags.bool: return "ConstantVal::BoolVal(true)" if value.value else "ConstantVal::BoolVal(false)" if tag in [IDLType.Tags.unrestricted_float, IDLType.Tags.float, IDLType.Tags.unrestricted_double, IDLType.Tags.double]: - return "ConstantVal::DoubleVal(%s)" % (value.value) + return "ConstantVal::DoubleVal(%s as f64)" % (value.value) raise TypeError("Const value of unhandled type: " + value.type) @@ -4077,7 +4077,17 @@ class CGConstant(CGThing): def define(self): name = self.constant.identifier.name value = convertConstIDLValueToRust(self.constant.value) - return "pub const %s: %s = %s;\n" % (name, builtinNames[self.constant.value.type.tag()], value) + + tag = self.constant.value.type.tag() + const_type = builtinNames[self.constant.value.type.tag()] + # Finite or Finite cannot be used un a constant declaration. + # Remote the Finite type from restricted float and double tag declarations. + if tag == IDLType.Tags.float: + const_type = "f32" + elif tag == IDLType.Tags.double: + const_type = "f64" + + return "pub const %s: %s = %s;\n" % (name, const_type, value) def getUnionTypeTemplateVars(type, descriptorProvider): -- cgit v1.2.3 From 29b4eec14187c96a1518af6a954bd00194375382 Mon Sep 17 00:00:00 2001 From: Bastien Orivel Date: Mon, 30 Oct 2017 12:15:30 +0100 Subject: Bump bitflags to 1.0 in every servo crate --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b7438e6be0a..c32c8f2c090 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2039,7 +2039,7 @@ DOMClass { interface_chain: [ %s ], type_id: %s, malloc_size_of: %s as unsafe fn(&mut _, _) -> _, - global: InterfaceObjectMap::%s, + global: InterfaceObjectMap::Globals::%s, }""" % (prototypeChainString, DOMClassTypeId(descriptor), mallocSizeOf, globals_) @@ -2445,7 +2445,7 @@ class CGConstructorEnabled(CGAbstractMethod): iface = self.descriptor.interface bits = " | ".join(sorted( - "InterfaceObjectMap::" + camel_to_upper_snake(i) for i in iface.exposureSet + "InterfaceObjectMap::Globals::" + camel_to_upper_snake(i) for i in iface.exposureSet )) conditions.append("is_exposed_in(aObj, %s)" % bits) @@ -7102,9 +7102,9 @@ class GlobalGenRoots(): for (idx, d) in enumerate(global_descriptors) ) global_flags = CGWrapper(CGIndenter(CGList([ - CGGeneric("const %s = %#x," % args) + CGGeneric("const %s = %#x;" % args) for args in flags - ], "\n")), pre="pub flags Globals: u8 {\n", post="\n}") + ], "\n")), pre="pub struct Globals: u8 {\n", post="\n}") globals_ = CGWrapper(CGIndenter(global_flags), pre="bitflags! {\n", post="\n}") phf = CGGeneric("include!(concat!(env!(\"OUT_DIR\"), \"/InterfaceObjectMapPhf.rs\"));") -- cgit v1.2.3 From 2974dae4315420d1e7252029c2c30198ea62ac61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Jim=C3=A9nez=20Moreno?= Date: Fri, 10 Nov 2017 17:57:02 +0100 Subject: Fix binding generation for overloaded functions with optionals and default values --- components/script/dom/bindings/codegen/CodegenRust.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c32c8f2c090..b408d0a670f 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -483,7 +483,8 @@ class CGMethodCall(CGThing): else: # Just throw; we have no idea what we're supposed to # do with this. - caseBody.append(CGGeneric("return Throw(cx, NS_ERROR_XPC_BAD_CONVERT_JS);")) + caseBody.append(CGGeneric("throw_internal_error(cx, \"Could not convert JavaScript argument\");\n" + "return false;")) argCountCases.append(CGCase(str(argCount), CGList(caseBody, "\n"))) @@ -5591,6 +5592,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::JSCLASS_RESERVED_SLOTS_MASK', 'js::JS_CALLEE', 'js::error::throw_type_error', + 'js::error::throw_internal_error', 'js::jsapi::AutoIdVector', 'js::jsapi::Call', 'js::jsapi::CallArgs', -- cgit v1.2.3 From d71ff786c65bc9183824620a11607a4cbd06a7b3 Mon Sep 17 00:00:00 2001 From: olmanz Date: Thu, 16 Nov 2017 13:06:50 +0100 Subject: Moved function html_constructor() from interface.rs to new file htmlconstructor.rs --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b408d0a670f..8d91f84a6e4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5717,7 +5717,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::interface::define_guarded_constants', 'dom::bindings::interface::define_guarded_methods', 'dom::bindings::interface::define_guarded_properties', - 'dom::bindings::interface::html_constructor', + 'dom::bindings::htmlconstructor::html_constructor', 'dom::bindings::interface::is_exposed_in', 'dom::bindings::interface::pop_current_element_queue', 'dom::bindings::interface::push_new_element_queue', -- cgit v1.2.3 From 83adc7b769902a56935f84450ab891c03f0efc3e Mon Sep 17 00:00:00 2001 From: olmanz Date: Thu, 16 Nov 2017 19:14:12 +0100 Subject: Moved pop_current_element_queue() and push_new_element_queue() to htmlconstructor.rs --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 8d91f84a6e4..a0b73b40985 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5719,8 +5719,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::interface::define_guarded_properties', 'dom::bindings::htmlconstructor::html_constructor', 'dom::bindings::interface::is_exposed_in', - 'dom::bindings::interface::pop_current_element_queue', - 'dom::bindings::interface::push_new_element_queue', + 'dom::bindings::htmlconstructor::pop_current_element_queue', + 'dom::bindings::htmlconstructor::push_new_element_queue', 'dom::bindings::iterable::Iterable', 'dom::bindings::iterable::IteratorType', 'dom::bindings::namespace::NamespaceObjectClass', -- cgit v1.2.3 From a01d1eabefeb9ec6a65c518234647ddbf15e7f92 Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Sun, 24 Dec 2017 20:44:41 +0100 Subject: Root sequence<{any,object}> IDL arguments using CustomAutoRooter Also pulls in mozjs 0.1.10 to support the change. --- .../script/dom/bindings/codegen/CodegenRust.py | 43 +++++++++++++++++++--- 1 file changed, 38 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index a0b73b40985..6f0dd003e8d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -562,6 +562,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, isDefinitelyObject=False, isMember=False, isArgument=False, + isAutoRooted=False, invalidEnumValueFatal=True, defaultValue=None, treatNullAs="Default", @@ -702,7 +703,8 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type.isSequence() or type.isRecord(): innerInfo = getJSToNativeConversionInfo(innerContainerType(type), descriptorProvider, - isMember=isMember) + isMember=isMember, + isAutoRooted=isAutoRooted) declType = wrapInNativeContainerType(type, innerInfo.declType) config = getConversionConfigForType(type, isEnforceRange, isClamp, treatNullAs) @@ -1038,10 +1040,14 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, assert not isEnforceRange and not isClamp assert isMember != "Union" - if isMember == "Dictionary": + if isMember == "Dictionary" or isAutoRooted: # TODO: Need to properly root dictionaries # https://github.com/servo/servo/issues/6381 - declType = CGGeneric("Heap") + if isMember == "Dictionary": + declType = CGGeneric("Heap") + # AutoRooter can trace properly inner raw GC thing pointers + else: + declType = CGGeneric("JSVal") if defaultValue is None: default = None @@ -1238,6 +1244,7 @@ class CGArgumentConverter(CGThing): isEnforceRange=argument.enforceRange, isClamp=argument.clamp, isMember="Variadic" if argument.variadic else False, + isAutoRooted=type_needs_auto_root(argument.type), allowTreatNonObjectAsNull=argument.allowTreatNonCallableAsNull()) template = info.template default = info.default @@ -1260,8 +1267,15 @@ class CGArgumentConverter(CGThing): else: assert not default + arg = "arg%d" % index + self.converter = instantiateJSToNativeConversionTemplate( - template, replacementVariables, declType, "arg%d" % index) + template, replacementVariables, declType, arg) + + # The auto rooting is done only after the conversion is performed + if type_needs_auto_root(argument.type): + self.converter.append(CGGeneric("auto_root!(in(cx) let %s = %s);" % (arg, arg))) + else: assert argument.optional variadicConversion = { @@ -5698,6 +5712,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::panic::maybe_resume_unwind', 'js::panic::wrap_panic', 'js::rust::GCMethods', + 'js::rust::CustomAutoRooterGuard', 'js::rust::define_methods', 'js::rust::define_properties', 'js::rust::get_object_class', @@ -6421,9 +6436,24 @@ def type_needs_tracing(t): assert False, (t, type(t)) +def type_needs_auto_root(t): + """ + Certain IDL types, such as `sequence` or `sequence` need to be + traced and wrapped via (Custom)AutoRooter + """ + assert isinstance(t, IDLObject), (t, type(t)) + + if t.isType(): + if t.isSequence() and (t.inner.isAny() or t.inner.isObject()): + return True + + return False + + def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, variadic=False): info = getJSToNativeConversionInfo( - ty, descriptorProvider, isArgument=True) + ty, descriptorProvider, isArgument=True, + isAutoRooted=type_needs_auto_root(ty)) declType = info.declType if variadic: @@ -6437,6 +6467,9 @@ def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, var if ty.isDictionary() and not type_needs_tracing(ty): declType = CGWrapper(declType, pre="&") + if type_needs_auto_root(ty): + declType = CGTemplatedType("CustomAutoRooterGuard", declType) + return declType.define() -- cgit v1.2.3 From 4d459bce32a48e040399b3e05e66ba5ea26dd7f1 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Thu, 4 Jan 2018 18:13:44 +0100 Subject: Fix tyvar_behind_raw_pointer warnings https://github.com/rust-lang/rust/issues/46906 --- .../script/dom/bindings/codegen/CodegenRust.py | 42 +++++++++++----------- 1 file changed, 21 insertions(+), 21 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 6f0dd003e8d..4a377aa351f 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2539,7 +2539,7 @@ def CopyUnforgeablePropertiesToInstance(descriptor): # reflector, so we can make sure we don't get confused by named getters. if descriptor.proxy: copyCode += """\ -rooted!(in(cx) let mut expando = ptr::null_mut()); +rooted!(in(cx) let mut expando = ptr::null_mut::()); ensure_expando_object(cx, obj.handle(), expando.handle_mut()); """ obj = "expando" @@ -2554,7 +2554,7 @@ ensure_expando_object(cx, obj.handle(), expando.handle_mut()); else: copyFunc = "JS_InitializePropertiesFromCompatibleNativeObject" copyCode += """\ -rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut()); +rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut::()); unforgeable_holder.handle_mut().set( JS_GetReservedSlot(proto.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT).to_object()); assert!(%(copyFunc)s(cx, %(obj)s.handle(), unforgeable_holder.handle())); @@ -2586,7 +2586,7 @@ let scope = scope.reflector().get_jsobject(); assert!(!scope.get().is_null()); assert!(((*get_object_class(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0); -rooted!(in(cx) let mut proto = ptr::null_mut()); +rooted!(in(cx) let mut proto = ptr::null_mut::()); let _ac = JSAutoCompartment::new(cx, scope.get()); GetProtoObject(cx, scope, proto.handle_mut()); assert!(!proto.is_null()); @@ -2631,7 +2631,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): let raw = Box::into_raw(object); let _rt = RootedTraceable::new(&*raw); -rooted!(in(cx) let mut obj = ptr::null_mut()); +rooted!(in(cx) let mut obj = ptr::null_mut::()); create_global_object( cx, &Class.base, @@ -2643,7 +2643,7 @@ assert!(!obj.is_null()); (*raw).init_reflector(obj.get()); let _ac = JSAutoCompartment::new(cx, obj.get()); -rooted!(in(cx) let mut proto = ptr::null_mut()); +rooted!(in(cx) let mut proto = ptr::null_mut::()); GetProtoObject(cx, obj.handle(), proto.handle_mut()); assert!(JS_SplicePrototype(cx, obj.handle(), proto.handle())); let mut immutable = false; @@ -2771,7 +2771,7 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): return CGGeneric("""\ rooted!(in(cx) let proto = %(proto)s); assert!(!proto.is_null()); -rooted!(in(cx) let mut namespace = ptr::null_mut()); +rooted!(in(cx) let mut namespace = ptr::null_mut::()); create_namespace_object(cx, global, proto.handle(), &NAMESPACE_OBJECT_CLASS, %(methods)s, %(name)s, namespace.handle_mut()); assert!(!namespace.is_null()); @@ -2784,7 +2784,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); if self.descriptor.interface.isCallback(): assert not self.descriptor.interface.ctor() and self.descriptor.interface.hasConstants() return CGGeneric("""\ -rooted!(in(cx) let mut interface = ptr::null_mut()); +rooted!(in(cx) let mut interface = ptr::null_mut::()); create_callback_interface_object(cx, global, sConstants, %(name)s, interface.handle_mut()); assert!(!interface.is_null()); assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); @@ -2807,7 +2807,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); toBindingNamespace(parentName)) code = [CGGeneric("""\ -rooted!(in(cx) let mut prototype_proto = ptr::null_mut()); +rooted!(in(cx) let mut prototype_proto = ptr::null_mut::()); %s; assert!(!prototype_proto.is_null());""" % getPrototypeProto)] @@ -2835,7 +2835,7 @@ assert!(!prototype_proto.is_null());""" % getPrototypeProto)] proto_properties = properties code.append(CGGeneric(""" -rooted!(in(cx) let mut prototype = ptr::null_mut()); +rooted!(in(cx) let mut prototype = ptr::null_mut::()); create_interface_prototype_object(cx, prototype_proto.handle(), &PrototypeClass, @@ -2862,7 +2862,7 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); if parentName: parentName = toBindingNamespace(parentName) code.append(CGGeneric(""" -rooted!(in(cx) let mut interface_proto = ptr::null_mut()); +rooted!(in(cx) let mut interface_proto = ptr::null_mut::()); %s::GetConstructorObject(cx, global, interface_proto.handle_mut());""" % parentName)) else: code.append(CGGeneric(""" @@ -2870,7 +2870,7 @@ rooted!(in(cx) let interface_proto = JS_GetFunctionPrototype(cx, global));""")) code.append(CGGeneric("""\ assert!(!interface_proto.is_null()); -rooted!(in(cx) let mut interface = ptr::null_mut()); +rooted!(in(cx) let mut interface = ptr::null_mut::()); create_noncallback_interface_object(cx, global, interface_proto.handle(), @@ -2973,7 +2973,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); holderClass = "&Class.base as *const JSClass" holderProto = "prototype.handle()" code.append(CGGeneric(""" -rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut()); +rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut::()); unforgeable_holder.handle_mut().set( JS_NewObjectWithoutMetadata(cx, %(holderClass)s, %(holderProto)s)); assert!(!unforgeable_holder.is_null()); @@ -3151,7 +3151,7 @@ if !ConstructorEnabled(cx, global) { return; } -rooted!(in(cx) let mut proto = ptr::null_mut()); +rooted!(in(cx) let mut proto = ptr::null_mut::()); %s(cx, global, proto.handle_mut()); assert!(!proto.is_null());""" % (function,)) @@ -4941,7 +4941,7 @@ if %s { # FIXME(#11868) Should assign to desc.obj, desc.get() is a copy. return get + """\ -rooted!(in(cx) let mut expando = ptr::null_mut()); +rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); //if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) { if !expando.is_null() { @@ -5071,7 +5071,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): body += dedent( """ - rooted!(in(cx) let mut expando = ptr::null_mut()); + rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { GetPropertyKeys(cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); @@ -5114,7 +5114,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): body += dedent( """ - rooted!(in(cx) let mut expando = ptr::null_mut()); + rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { GetPropertyKeys(cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); @@ -5173,7 +5173,7 @@ if %s { named = "" return indexed + """\ -rooted!(in(cx) let mut expando = ptr::null_mut()); +rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { let ok = JS_HasPropertyById(cx, expando.handle(), id, bp); @@ -5200,7 +5200,7 @@ class CGDOMJSProxyHandler_get(CGAbstractExternMethod): # https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty def getBody(self): getFromExpando = """\ -rooted!(in(cx) let mut expando = ptr::null_mut()); +rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { let mut hasProp = false; @@ -5406,7 +5406,7 @@ if args.callee() == new_target.get() { } // Step 6 -rooted!(in(cx) let mut prototype = ptr::null_mut()); +rooted!(in(cx) let mut prototype = ptr::null_mut::()); { rooted!(in(cx) let mut proto_val = UndefinedValue()); let _ac = JSAutoCompartment::new(cx, new_target.get()); @@ -6594,7 +6594,7 @@ class CGCallback(CGClass): bodyWithThis = string.Template( setupCall + - "rooted!(in(s.get_context()) let mut thisObjJS = ptr::null_mut());\n" + "rooted!(in(s.get_context()) let mut thisObjJS = ptr::null_mut::());\n" "wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n" "if thisObjJS.is_null() {\n" " return Err(JSFailed);\n" @@ -6605,7 +6605,7 @@ class CGCallback(CGClass): }) bodyWithoutThis = string.Template( setupCall + - "rooted!(in(s.get_context()) let thisObjJS = ptr::null_mut());\n" + "rooted!(in(s.get_context()) let thisObjJS = ptr::null_mut::());\n" "return ${methodName}(${callArgs});").substitute({ "callArgs": ", ".join(argnamesWithoutThis), "methodName": 'self.' + method.name, -- cgit v1.2.3 From 52eda6082fd32d3e28f3600858afd8f5bbc918fe Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Mon, 22 Jan 2018 12:42:05 +0100 Subject: Replace NonNullJSObjectPtr with std::ptr::NonNull --- components/script/dom/bindings/codegen/CodegenRust.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 4a377aa351f..92f6b3a71b6 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1422,7 +1422,7 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): if returnType.isAny(): return CGGeneric("JSVal") if returnType.isObject() or returnType.isSpiderMonkeyInterface(): - result = CGGeneric("NonNullJSObjectPtr") + result = CGGeneric("NonNull") if returnType.nullable(): result = CGWrapper(result, pre="Option<", post=">") return result @@ -2268,7 +2268,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::conversions::StringificationBehavior', 'dom::bindings::conversions::root_from_handlevalue', 'dom::bindings::error::throw_not_in_union', - 'dom::bindings::nonnull::NonNullJSObjectPtr', + 'std::ptr::NonNull', 'dom::bindings::mozmap::MozMap', 'dom::bindings::root::DomRoot', 'dom::bindings::str::ByteString', @@ -5811,7 +5811,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::proxyhandler::get_expando_object', 'dom::bindings::proxyhandler::get_property_descriptor', 'dom::bindings::mozmap::MozMap', - 'dom::bindings::nonnull::NonNullJSObjectPtr', + 'std::ptr::NonNull', 'dom::bindings::num::Finite', 'dom::bindings::str::ByteString', 'dom::bindings::str::DOMString', -- cgit v1.2.3 From f903da0a7bba2806e3a200eee8414a629d27ffa8 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Thu, 25 Jan 2018 11:25:23 +0100 Subject: Make callbacks' new methods unsafe They take raw pointers to contexts and objects. --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 92f6b3a71b6..cc9a37a5ecc 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4549,7 +4549,7 @@ class ClassConstructor(ClassItem): "});\n" "// Note: callback cannot be moved after calling init.\n" "match Rc::get_mut(&mut ret) {\n" - " Some(ref mut callback) => unsafe { callback.parent.init(%s, %s) },\n" + " Some(ref mut callback) => callback.parent.init(%s, %s),\n" " None => unreachable!(),\n" "};\n" "ret") % (cgClass.name, '\n'.join(initializers), @@ -4564,7 +4564,7 @@ class ClassConstructor(ClassItem): body = ' {\n' + body + '}' return string.Template("""\ -pub fn ${decorators}new(${args}) -> Rc<${className}>${body} +pub unsafe fn ${decorators}new(${args}) -> Rc<${className}>${body} """).substitute({'decorators': self.getDecorators(True), 'className': cgClass.getNameString(), 'args': args, -- cgit v1.2.3 From 74dabbdc62b49862c115eccb38fb9e010041cf28 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Thu, 25 Jan 2018 11:37:24 +0100 Subject: Kill dead callback codegen code --- .../script/dom/bindings/codegen/CodegenRust.py | 65 ++-------------------- 1 file changed, 4 insertions(+), 61 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index cc9a37a5ecc..00ba2ce2148 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6529,8 +6529,7 @@ class CGNativeMember(ClassMethod): class CGCallback(CGClass): - def __init__(self, idlObject, descriptorProvider, baseName, methods, - getters=[], setters=[]): + def __init__(self, idlObject, descriptorProvider, baseName, methods): self.baseName = baseName self._deps = idlObject.getDeps() name = idlObject.identifier.name @@ -6549,7 +6548,7 @@ class CGCallback(CGClass): CGClass.__init__(self, name, bases=[ClassBase(baseName)], constructors=self.getConstructors(), - methods=realMethods + getters + setters, + methods=realMethods, decorators="#[derive(JSTraceable, PartialEq)]\n#[allow_unrooted_interior]") def getConstructors(self): @@ -6672,16 +6671,13 @@ class CGCallbackInterface(CGCallback): def __init__(self, descriptor): iface = descriptor.interface attrs = [m for m in iface.members if m.isAttr() and not m.isStatic()] - getters = [CallbackGetter(a, descriptor) for a in attrs] - setters = [CallbackSetter(a, descriptor) for a in attrs - if not a.readonly] + assert not attrs methods = [m for m in iface.members if m.isMethod() and not m.isStatic() and not m.isIdentifierLess()] methods = [CallbackOperation(m, sig, descriptor) for m in methods for sig in m.signatures()] assert not iface.isJSImplemented() or not iface.ctor() - CGCallback.__init__(self, iface, descriptor, "CallbackInterface", - methods, getters=getters, setters=setters) + CGCallback.__init__(self, iface, descriptor, "CallbackInterface", methods) class FakeMember(): @@ -6998,59 +6994,6 @@ class CallbackOperation(CallbackOperationBase): descriptor, descriptor.interface.isSingleOperationInterface()) -class CallbackGetter(CallbackMember): - def __init__(self, attr, descriptor): - self.ensureASCIIName(attr) - self.attrName = attr.identifier.name - CallbackMember.__init__(self, - (attr.type, []), - callbackGetterName(attr), - descriptor, - needThisHandling=False) - - def getRvalDecl(self): - return "Dom::Rooted rval(cx, JS::UndefinedValue());\n" - - def getCall(self): - replacements = { - "attrName": self.attrName - } - return string.Template( - 'if (!JS_GetProperty(cx, mCallback, "${attrName}", &rval)) {\n' - ' return Err(JSFailed);\n' - '}\n').substitute(replacements) - - -class CallbackSetter(CallbackMember): - def __init__(self, attr, descriptor): - self.ensureASCIIName(attr) - self.attrName = attr.identifier.name - CallbackMember.__init__(self, - (BuiltinTypes[IDLBuiltinType.Types.void], - [FakeArgument(attr.type, attr)]), - callbackSetterName(attr), - descriptor, - needThisHandling=False) - - def getRvalDecl(self): - # We don't need an rval - return "" - - def getCall(self): - replacements = { - "attrName": self.attrName, - "argv": "argv.handleAt(0)", - } - return string.Template( - 'MOZ_ASSERT(argv.length() == 1);\n' - 'if (!JS_SetProperty(cx, mCallback, "${attrName}", ${argv})) {\n' - ' return Err(JSFailed);\n' - '}\n').substitute(replacements) - - def getArgcDecl(self): - return None - - class CGIterableMethodGenerator(CGGeneric): """ Creates methods for iterable interfaces. Unwrapping/wrapping -- cgit v1.2.3 From de426baeccfecb5a02e5db876d9a127ee9379c2e Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Thu, 25 Jan 2018 12:07:13 +0100 Subject: Make the private callback methods taking a raw this pointer unsafe --- .../script/dom/bindings/codegen/CodegenRust.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 00ba2ce2148..d2d090f8350 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4417,7 +4417,7 @@ class ClassMethod(ClassItem): def __init__(self, name, returnType, args, inline=False, static=False, virtual=False, const=False, bodyInHeader=False, templateArgs=None, visibility='public', body=None, - breakAfterReturnDecl="\n", + breakAfterReturnDecl="\n", unsafe=False, breakAfterSelf="\n", override=False): """ override indicates whether to flag the method as MOZ_OVERRIDE @@ -4436,6 +4436,7 @@ class ClassMethod(ClassItem): self.breakAfterReturnDecl = breakAfterReturnDecl self.breakAfterSelf = breakAfterSelf self.override = override + self.unsafe = unsafe ClassItem.__init__(self, name, visibility) def getDecorators(self, declaring): @@ -4468,7 +4469,7 @@ class ClassMethod(ClassItem): return string.Template( "${decorators}%s" - "${visibility}fn ${name}${templateClause}(${args})${returnType}${const}${override}${body}%s" % + "${visibility}${unsafe}fn ${name}${templateClause}(${args})${returnType}${const}${override}${body}%s" % (self.breakAfterReturnDecl, self.breakAfterSelf) ).substitute({ 'templateClause': templateClause, @@ -4479,7 +4480,8 @@ class ClassMethod(ClassItem): 'override': ' MOZ_OVERRIDE' if self.override else '', 'args': args, 'body': body, - 'visibility': self.visibility + ' ' if self.visibility != 'priv' else '' + 'visibility': self.visibility + ' ' if self.visibility != 'priv' else '', + 'unsafe': "unsafe " if self.unsafe else "", }) def define(self, cgClass): @@ -6495,7 +6497,8 @@ def return_type(descriptorProvider, rettype, infallible): class CGNativeMember(ClassMethod): def __init__(self, descriptorProvider, member, name, signature, extendedAttrs, - breakAfter=True, passJSBitsAsNeeded=True, visibility="public"): + breakAfter=True, passJSBitsAsNeeded=True, visibility="public", + unsafe=False): """ If passJSBitsAsNeeded is false, we don't automatically pass in a JSContext* or a JSObject* based on the return and argument types. @@ -6514,6 +6517,7 @@ class CGNativeMember(ClassMethod): const=(not member.isStatic() and member.isAttr() and not signature[0].isVoid()), breakAfterSelf=breakAfterSelf, + unsafe=unsafe, visibility=visibility) def getReturnType(self, type): @@ -6598,14 +6602,14 @@ class CGCallback(CGClass): "if thisObjJS.is_null() {\n" " return Err(JSFailed);\n" "}\n" - "return ${methodName}(${callArgs});").substitute({ + "unsafe { ${methodName}(${callArgs}) }").substitute({ "callArgs": ", ".join(argnamesWithThis), "methodName": 'self.' + method.name, }) bodyWithoutThis = string.Template( setupCall + "rooted!(in(s.get_context()) let thisObjJS = ptr::null_mut::());\n" - "return ${methodName}(${callArgs});").substitute({ + "unsafe { ${methodName}(${callArgs}) }").substitute({ "callArgs": ", ".join(argnamesWithoutThis), "methodName": 'self.' + method.name, }) @@ -6728,6 +6732,7 @@ class CallbackMember(CGNativeMember): name, (self.retvalType, args), extendedAttrs={}, passJSBitsAsNeeded=False, + unsafe=needThisHandling, visibility=visibility) # We have to do all the generation of our body now, because # the caller relies on us throwing if we can't manage it. @@ -6761,10 +6766,7 @@ class CallbackMember(CGNativeMember): "${convertArgs}" "${doCall}" "${returnResult}").substitute(replacements) - return CGWrapper(CGIndenter(CGList([ - CGGeneric(pre), - CGGeneric(body), - ], "\n"), 4), pre="unsafe {\n", post="\n}").define() + return pre + "\n" + body def getResultConversion(self): replacements = { -- cgit v1.2.3 From 17ecbaf8ff9ee6987f17cf00a243c136b1b0610e Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Sat, 10 Mar 2018 14:35:09 +0100 Subject: Support objects in WebIDL unions Fixes #17011 --- .../script/dom/bindings/codegen/CodegenRust.py | 25 +++++++++++----------- 1 file changed, 13 insertions(+), 12 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index d2d090f8350..55e72086f12 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1075,20 +1075,24 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type.isObject(): assert not isEnforceRange and not isClamp - # TODO: Need to root somehow - # https://github.com/servo/servo/issues/6382 + templateBody = "${val}.get().to_object()" default = "ptr::null_mut()" - templateBody = wrapObjectTemplate("${val}.get().to_object()", - default, - isDefinitelyObject, type, failureCode) - if isMember in ("Dictionary", "Union"): + # TODO: Do we need to do the same for dictionaries? + if isMember == "Union": + templateBody = "RootedTraceableBox::from_box(Heap::boxed(%s))" % templateBody + default = "RootedTraceableBox::new(Heap::default())" + declType = CGGeneric("RootedTraceableBox>") + elif isMember == "Dictionary": declType = CGGeneric("Heap<*mut JSObject>") else: # TODO: Need to root somehow # https://github.com/servo/servo/issues/6382 declType = CGGeneric("*mut JSObject") + templateBody = wrapObjectTemplate(templateBody, default, + isDefinitelyObject, type, failureCode) + return handleOptional(templateBody, declType, handleDefaultNull(default)) @@ -4291,11 +4295,13 @@ class CGUnionConversionStruct(CGThing): else: mozMapObject = None - hasObjectTypes = interfaceObject or arrayObject or dateObject or object or mozMapObject + hasObjectTypes = object or interfaceObject or arrayObject or dateObject or mozMapObject if hasObjectTypes: # "object" is not distinguishable from other types assert not object or not (interfaceObject or arrayObject or dateObject or callbackObject or mozMapObject) templateBody = CGList([], "\n") + if object: + templateBody.append(object) if interfaceObject: templateBody.append(interfaceObject) if arrayObject: @@ -4363,11 +4369,6 @@ class CGUnionConversionStruct(CGThing): returnType = "Result, ()>" % actualType jsConversion = templateVars["jsConversion"] - # Any code to convert to Object is unused, since we're already converting - # from an Object value. - if t.name == 'Object': - return CGGeneric('') - return CGWrapper( CGIndenter(jsConversion, 4), pre="unsafe fn TryConvertTo%s(cx: *mut JSContext, value: HandleValue) -> %s {\n" -- cgit v1.2.3 From e025bbb07964eb64317d9a6d63d4a55ba79cd8ae Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Sun, 4 Mar 2018 20:32:08 +0100 Subject: WIP: Accept typed array arguments in codegen --- .../script/dom/bindings/codegen/CodegenRust.py | 58 +++++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 55e72086f12..3e39bc231d4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -870,8 +870,50 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, return handleOptional(templateBody, declType, handleDefaultNull("None")) - if type.isSpiderMonkeyInterface(): - raise TypeError("Can't handle SpiderMonkey interface arguments yet") + if type.isTypedArray() or type.isArrayBuffer() or type.isArrayBufferView() or type.isSharedArrayBuffer(): + if failureCode is None: + substitutions = { + "sourceDescription": sourceDescription, + "exceptionCode": exceptionCode, + } + unwrapFailureCode = string.Template( + 'throw_type_error(cx, "${sourceDescription} is not a typed array.");\n' + '${exceptionCode}').substitute(substitutions) + else: + unwrapFailureCode = failureCode + + typeName = type.name + if isMember == "Union": + typeName = "Heap" + typeName + + templateBody = fill( + """ + match typedarray::${ty}::from($${val}.get().to_object()) { + Ok(val) => val, + Err(()) => { + $*{failureCode} + } + } + """, + ty=typeName, + failureCode=unwrapFailureCode + "\n", + ) + + if isMember == "Union": + templateBody = "RootedTraceableBox::new(%s)" % templateBody + + declType = CGGeneric("typedarray::%s" % type.name) + if type.nullable(): + templateBody = "Some(%s)" % templateBody + declType = CGWrapper(declType, pre="Option<", post=">") + + templateBody = wrapObjectTemplate(templateBody, "None", + isDefinitelyObject, type, failureCode) + + return handleOptional(templateBody, declType, handleDefaultNull("None")) + + elif type.isSpiderMonkeyInterface(): + raise TypeError("Can't handle SpiderMonkey interface arguments other than typed arrays yet") if type.isDOMString(): nullBehavior = getConversionConfigForType(type, isEnforceRange, isClamp, treatNullAs) @@ -2287,6 +2329,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'js::jsapi::JSObject', 'js::jsapi::MutableHandleValue', 'js::jsval::JSVal', + 'js::typedarray' ] # Now find all the things we'll need as arguments and return values because @@ -4138,6 +4181,9 @@ def getUnionTypeTemplateVars(type, descriptorProvider): elif type.isObject(): name = type.name typeName = "Heap<*mut JSObject>" + elif type.isTypedArray() or type.isArrayBuffer() or type.isArrayBufferView() or type.isSharedArrayBuffer(): + name = type.name + typeName = "typedarray::Heap" + name else: raise TypeError("Can't handle %s in unions yet" % type) @@ -5688,6 +5734,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::MutableHandleValue', 'js::jsapi::ObjectOpResult', 'js::jsapi::PropertyDescriptor', + 'js::jsapi::Rooted', 'js::jsapi::RootedId', 'js::jsapi::RootedObject', 'js::jsapi::RootedString', @@ -5719,6 +5766,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::rust::define_methods', 'js::rust::define_properties', 'js::rust::get_object_class', + 'js::typedarray', 'dom', 'dom::bindings', 'dom::bindings::codegen::InterfaceObjectMap', @@ -6419,6 +6467,9 @@ def type_needs_tracing(t): if t.isUnion(): return any(type_needs_tracing(member) for member in t.flatMemberTypes) + if t.isTypedArray() or t.isArrayBuffer() or t.isArrayBufferView() or t.isSharedArrayBuffer(): + return True + return False if t.isDictionary(): @@ -6449,6 +6500,9 @@ def type_needs_auto_root(t): if t.isType(): if t.isSequence() and (t.inner.isAny() or t.inner.isObject()): return True + # SpiderMonkey interfaces + if t.isTypedArray() or t.isArrayBuffer() or t.isArrayBufferView() or t.isSharedArrayBuffer(): + return True return False -- cgit v1.2.3 From 6beb32e28e8652027a28bc8400dbe2d6e78cb286 Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Tue, 13 Mar 2018 13:05:04 +0100 Subject: Support nullable typed arrays in codegen --- components/script/dom/bindings/codegen/CodegenRust.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3e39bc231d4..6ab7dd8b1d3 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -882,7 +882,8 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, else: unwrapFailureCode = failureCode - typeName = type.name + typeName = type.unroll().name # unroll because it may be nullable + if isMember == "Union": typeName = "Heap" + typeName @@ -902,7 +903,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if isMember == "Union": templateBody = "RootedTraceableBox::new(%s)" % templateBody - declType = CGGeneric("typedarray::%s" % type.name) + declType = CGGeneric("typedarray::%s" % typeName) if type.nullable(): templateBody = "Some(%s)" % templateBody declType = CGWrapper(declType, pre="Option<", post=">") -- cgit v1.2.3 From c29fcb80f3051ed9f315d736179d95282e57729c Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Tue, 13 Mar 2018 13:23:01 +0100 Subject: Use helper `is_typed_array` function --- components/script/dom/bindings/codegen/CodegenRust.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 6ab7dd8b1d3..1207b050797 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -870,7 +870,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, return handleOptional(templateBody, declType, handleDefaultNull("None")) - if type.isTypedArray() or type.isArrayBuffer() or type.isArrayBufferView() or type.isSharedArrayBuffer(): + if is_typed_array(type): if failureCode is None: substitutions = { "sourceDescription": sourceDescription, @@ -4182,7 +4182,7 @@ def getUnionTypeTemplateVars(type, descriptorProvider): elif type.isObject(): name = type.name typeName = "Heap<*mut JSObject>" - elif type.isTypedArray() or type.isArrayBuffer() or type.isArrayBufferView() or type.isSharedArrayBuffer(): + elif is_typed_array(type): name = type.name typeName = "typedarray::Heap" + name else: @@ -6468,7 +6468,7 @@ def type_needs_tracing(t): if t.isUnion(): return any(type_needs_tracing(member) for member in t.flatMemberTypes) - if t.isTypedArray() or t.isArrayBuffer() or t.isArrayBufferView() or t.isSharedArrayBuffer(): + if is_typed_array(t): return True return False @@ -6491,6 +6491,12 @@ def type_needs_tracing(t): assert False, (t, type(t)) +def is_typed_array(t): + assert isinstance(t, IDLObject), (t, type(t)) + + return t.isTypedArray() or t.isArrayBuffer() or t.isArrayBufferView() or t.isSharedArrayBuffer() + + def type_needs_auto_root(t): """ Certain IDL types, such as `sequence` or `sequence` need to be @@ -6501,8 +6507,8 @@ def type_needs_auto_root(t): if t.isType(): if t.isSequence() and (t.inner.isAny() or t.inner.isObject()): return True - # SpiderMonkey interfaces - if t.isTypedArray() or t.isArrayBuffer() or t.isArrayBufferView() or t.isSharedArrayBuffer(): + # SpiderMonkey interfaces, we currently don't support any other except typed arrays + if is_typed_array(t): return True return False -- cgit v1.2.3 From 760e0a5b5792fb3c8967aee53cc41e1e25adf07d Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Tue, 13 Mar 2018 14:57:09 +0100 Subject: Root JS object members in dictionaries --- components/script/dom/bindings/codegen/CodegenRust.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 1207b050797..916c8770d34 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1121,13 +1121,10 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, templateBody = "${val}.get().to_object()" default = "ptr::null_mut()" - # TODO: Do we need to do the same for dictionaries? - if isMember == "Union": + if isMember in ("Dictionary", "Union"): templateBody = "RootedTraceableBox::from_box(Heap::boxed(%s))" % templateBody default = "RootedTraceableBox::new(Heap::default())" declType = CGGeneric("RootedTraceableBox>") - elif isMember == "Dictionary": - declType = CGGeneric("Heap<*mut JSObject>") else: # TODO: Need to root somehow # https://github.com/servo/servo/issues/6382 @@ -6168,7 +6165,8 @@ class CGDictionary(CGThing): conversion = self.getMemberConversion(memberInfo, member.type) if isInitial: return CGGeneric("%s: %s,\n" % (name, conversion.define())) - if member.type.isAny() or member.type.isObject(): + # TODO: Root Heap using RootedTraceableBox + if member.type.isAny(): return CGGeneric("dictionary.%s.set(%s);\n" % (name, conversion.define())) return CGGeneric("dictionary.%s = %s;\n" % (name, conversion.define())) -- cgit v1.2.3 From 64dc0c4b9eeba6f5c56a917a0d32125df9248ed2 Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Fri, 16 Mar 2018 15:54:36 +0100 Subject: Root `any` members in dictionaries --- .../script/dom/bindings/codegen/CodegenRust.py | 23 +++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 916c8770d34..24054de8e95 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1084,13 +1084,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, assert isMember != "Union" if isMember == "Dictionary" or isAutoRooted: - # TODO: Need to properly root dictionaries - # https://github.com/servo/servo/issues/6381 - if isMember == "Dictionary": - declType = CGGeneric("Heap") - # AutoRooter can trace properly inner raw GC thing pointers - else: - declType = CGGeneric("JSVal") + templateBody = "${val}.get()" if defaultValue is None: default = None @@ -1100,7 +1094,17 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, default = "UndefinedValue()" else: raise TypeError("Can't handle non-null, non-undefined default value here") - return handleOptional("${val}.get()", declType, default) + + if isMember == "Dictionary": + templateBody = "RootedTraceableBox::from_box(Heap::boxed(%s))" % templateBody + if default is not None: + default = "RootedTraceableBox::from_box(Heap::boxed(%s))" % default + declType = CGGeneric("RootedTraceableBox>") + # AutoRooter can trace properly inner raw GC thing pointers + else: + declType = CGGeneric("JSVal") + + return handleOptional(templateBody, declType, default) declType = CGGeneric("HandleValue") @@ -6165,9 +6169,6 @@ class CGDictionary(CGThing): conversion = self.getMemberConversion(memberInfo, member.type) if isInitial: return CGGeneric("%s: %s,\n" % (name, conversion.define())) - # TODO: Root Heap using RootedTraceableBox - if member.type.isAny(): - return CGGeneric("dictionary.%s.set(%s);\n" % (name, conversion.define())) return CGGeneric("dictionary.%s = %s;\n" % (name, conversion.define())) def varInsert(varName, dictionaryName): -- cgit v1.2.3 From 20f21cb5f85c48e7106177db6aa41fa54365d6cc Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Thu, 22 Mar 2018 20:38:26 +0100 Subject: Adapt uniform[fv] and similar to accept typed array args --- components/script/dom/bindings/codegen/CodegenRust.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 24054de8e95..6e0632fe97d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -418,11 +418,15 @@ class CGMethodCall(CGThing): template = info.template declType = info.declType + argName = "arg%d" % distinguishingIndex + testCode = instantiateJSToNativeConversionTemplate( template, {"val": distinguishingArg}, declType, - "arg%d" % distinguishingIndex) + argName) + if type_needs_auto_root(type): + testCode.append(CGGeneric("auto_root!(in(cx) let %s = %s);" % (argName, argName))) # Indent by 4, since we need to indent further than our "do" statement caseBody.append(CGIndenter(testCode, 4)) -- cgit v1.2.3 From 2437a8472e3c2f9201fa4fc3fca06537ebf52d62 Mon Sep 17 00:00:00 2001 From: Igor Matuszewski Date: Fri, 23 Mar 2018 18:06:55 +0100 Subject: Unify argument auto rooting in codegen --- components/script/dom/bindings/codegen/CodegenRust.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 6e0632fe97d..de991f35ed9 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -418,15 +418,12 @@ class CGMethodCall(CGThing): template = info.template declType = info.declType - argName = "arg%d" % distinguishingIndex - testCode = instantiateJSToNativeConversionTemplate( template, {"val": distinguishingArg}, declType, - argName) - if type_needs_auto_root(type): - testCode.append(CGGeneric("auto_root!(in(cx) let %s = %s);" % (argName, argName))) + "arg%d" % distinguishingIndex, + needsAutoRoot=type_needs_auto_root(type)) # Indent by 4, since we need to indent further than our "do" statement caseBody.append(CGIndenter(testCode, 4)) @@ -1215,7 +1212,8 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, def instantiateJSToNativeConversionTemplate(templateBody, replacements, - declType, declName): + declType, declName, + needsAutoRoot=False): """ Take the templateBody and declType as returned by getJSToNativeConversionInfo, a set of replacements as required by the @@ -1240,6 +1238,8 @@ def instantiateJSToNativeConversionTemplate(templateBody, replacements, else: result.append(conversion) + if needsAutoRoot: + result.append(CGGeneric("auto_root!(in(cx) let %s = %s);" % (declName, declName))) # Add an empty CGGeneric to get an extra newline after the argument # conversion. result.append(CGGeneric("")) @@ -1322,11 +1322,8 @@ class CGArgumentConverter(CGThing): arg = "arg%d" % index self.converter = instantiateJSToNativeConversionTemplate( - template, replacementVariables, declType, arg) - - # The auto rooting is done only after the conversion is performed - if type_needs_auto_root(argument.type): - self.converter.append(CGGeneric("auto_root!(in(cx) let %s = %s);" % (arg, arg))) + template, replacementVariables, declType, arg, + needsAutoRoot=type_needs_auto_root(argument.type)) else: assert argument.optional -- cgit v1.2.3 From 356c57e628255ed338b32246ce5e7de75da621f0 Mon Sep 17 00:00:00 2001 From: Marcin Mielniczuk Date: Wed, 28 Mar 2018 21:28:30 +0200 Subject: Adapt Servo for mozjs 0.6 and the changes introduced in servo/rust-mozjs#393 --- .../script/dom/bindings/codegen/CodegenRust.py | 159 ++++++++++++--------- 1 file changed, 88 insertions(+), 71 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index de991f35ed9..5b286394051 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2326,11 +2326,11 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::trace::RootedTraceableBox', 'dom::types::*', 'js::error::throw_type_error', - 'js::jsapi::HandleValue', + 'js::rust::HandleValue', 'js::jsapi::Heap', 'js::jsapi::JSContext', 'js::jsapi::JSObject', - 'js::jsapi::MutableHandleValue', + 'js::rust::MutableHandleValue', 'js::jsval::JSVal', 'js::typedarray' ] @@ -2590,7 +2590,7 @@ def CopyUnforgeablePropertiesToInstance(descriptor): if descriptor.proxy: copyCode += """\ rooted!(in(cx) let mut expando = ptr::null_mut::()); -ensure_expando_object(cx, obj.handle(), expando.handle_mut()); +ensure_expando_object(cx, obj.handle().into(), expando.handle_mut()); """ obj = "expando" else: @@ -2887,13 +2887,13 @@ assert!(!prototype_proto.is_null());""" % getPrototypeProto)] code.append(CGGeneric(""" rooted!(in(cx) let mut prototype = ptr::null_mut::()); create_interface_prototype_object(cx, - prototype_proto.handle(), + prototype_proto.handle().into(), &PrototypeClass, %(methods)s, %(attrs)s, %(consts)s, %(unscopables)s, - prototype.handle_mut()); + prototype.handle_mut().into()); assert!(!prototype.is_null()); assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); (*cache)[PrototypeList::ID::%(id)s as usize] = prototype.get(); @@ -2922,7 +2922,7 @@ assert!(!interface_proto.is_null()); rooted!(in(cx) let mut interface = ptr::null_mut::()); create_noncallback_interface_object(cx, - global, + global.into(), interface_proto.handle(), &INTERFACE_OBJECT_CLASS, %(static_methods)s, @@ -3044,7 +3044,7 @@ class CGGetPerInterfaceObject(CGAbstractMethod): def __init__(self, descriptor, name, idPrefix="", pub=False): args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'global'), - Argument('MutableHandleObject', 'rval')] + Argument('MutableHandleObject', 'mut rval')] CGAbstractMethod.__init__(self, descriptor, name, 'void', args, pub=pub, unsafe=True) self.id = idPrefix + "::" + MakeNativeName(self.descriptor.name) @@ -4080,7 +4080,8 @@ pub enum %s { inner = string.Template("""\ use dom::bindings::conversions::ToJSValConvertible; -use js::jsapi::{JSContext, MutableHandleValue}; +use js::jsapi::JSContext; +use js::rust::MutableHandleValue; use js::jsval::JSVal; pub const pairs: &'static [(&'static str, super::${ident})] = &[ @@ -4856,7 +4857,7 @@ class CGProxyNamedOperation(CGProxySpecialOperation): def define(self): # Our first argument is the id we're getting. argName = self.arguments[0].identifier.name - return ("let %s = jsid_to_string(cx, id).expect(\"Not a string-convertible JSID?\");\n" + return ("let %s = jsid_to_string(cx, Handle::from_raw(id)).expect(\"Not a string-convertible JSID?\");\n" "let this = UnwrapProxy(proxy);\n" "let this = &*this;\n" % argName + CGProxySpecialOperation.define(self)) @@ -4899,7 +4900,7 @@ class CGProxyNamedDeleter(CGProxyNamedOperation): class CGProxyUnwrap(CGAbstractMethod): def __init__(self, descriptor): - args = [Argument('HandleObject', 'obj')] + args = [Argument('RawHandleObject', 'obj')] CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", '*const ' + descriptor.concreteType, args, alwaysInline=True, unsafe=True) @@ -4916,9 +4917,9 @@ return box_;""" % self.descriptor.concreteType) class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), - Argument('MutableHandle', 'desc')] + args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), + Argument('RawHandleId', 'id'), + Argument('RawMutableHandle', 'desc')] CGAbstractExternMethod.__init__(self, descriptor, "getOwnPropertyDescriptor", "bool", args) self.descriptor = descriptor @@ -4929,14 +4930,14 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): get = "" if indexedGetter: - get = "let index = get_array_index_from_id(cx, id);\n" + get = "let index = get_array_index_from_id(cx, Handle::from_raw(id));\n" attrs = "JSPROP_ENUMERATE" if self.descriptor.operations['IndexedSetter'] is None: attrs += " | JSPROP_READONLY" # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. fillDescriptor = ("desc.get().value = result_root.get();\n" - "fill_property_descriptor(desc, proxy.get(), %s);\n" + "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), %s);\n" "return true;" % attrs) templateValues = { 'jsvalRef': 'result_root.handle_mut()', @@ -4962,7 +4963,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): attrs = "0" # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. fillDescriptor = ("desc.get().value = result_root.get();\n" - "fill_property_descriptor(desc, proxy.get(), %s);\n" + "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), %s);\n" "return true;" % attrs) templateValues = { 'jsvalRef': 'result_root.handle_mut()', @@ -4980,7 +4981,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): namedGet = """ if %s { let mut has_on_proto = false; - if !has_property_on_prototype(cx, proxy, id, &mut has_on_proto) { + if !has_property_on_prototype(cx, proxy_lt, id_lt, &mut has_on_proto) { return false; } if !has_on_proto { @@ -4996,8 +4997,10 @@ if %s { rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); //if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) { +let proxy_lt = Handle::from_raw(proxy); +let id_lt = Handle::from_raw(id); if !expando.is_null() { - if !JS_GetPropertyDescriptorById(cx, expando.handle(), id, desc) { + if !JS_GetPropertyDescriptorById(cx, expando.handle().into(), id, desc) { return false; } if !desc.obj.is_null() { @@ -5016,9 +5019,9 @@ return true;""" class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), - Argument('Handle', 'desc'), + args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), + Argument('RawHandleId', 'id'), + Argument('RawHandle', 'desc'), Argument('*mut ObjectOpResult', 'opresult')] CGAbstractExternMethod.__init__(self, descriptor, "defineProperty", "bool", args) self.descriptor = descriptor @@ -5028,7 +5031,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): indexedSetter = self.descriptor.operations['IndexedSetter'] if indexedSetter: - set += ("let index = get_array_index_from_id(cx, id);\n" + + set += ("let index = get_array_index_from_id(cx, Handle::from_raw(id));\n" + "if let Some(index) = index {\n" + " let this = UnwrapProxy(proxy);\n" + " let this = &*this;\n" + @@ -5036,7 +5039,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): " return (*opresult).succeed();\n" + "}\n") elif self.descriptor.operations['IndexedGetter']: - set += ("if get_array_index_from_id(cx, id).is_some() {\n" + + set += ("if get_array_index_from_id(cx, Handle::from_raw(id)).is_some() {\n" + " return (*opresult).failNoIndexedSetter();\n" + "}\n") @@ -5065,8 +5068,8 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): class CGDOMJSProxyHandler_delete(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), + args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), + Argument('RawHandleId', 'id'), Argument('*mut ObjectOpResult', 'res')] CGAbstractExternMethod.__init__(self, descriptor, "delete", "bool", args) self.descriptor = descriptor @@ -5088,7 +5091,7 @@ class CGDOMJSProxyHandler_delete(CGAbstractExternMethod): class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): def __init__(self, descriptor): args = [Argument('*mut JSContext', 'cx'), - Argument('HandleObject', 'proxy'), + Argument('RawHandleObject', 'proxy'), Argument('*mut AutoIdVector', 'props')] CGAbstractExternMethod.__init__(self, descriptor, "own_property_keys", "bool", args) self.descriptor = descriptor @@ -5143,7 +5146,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): assert (descriptor.operations["IndexedGetter"] and descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties")) args = [Argument('*mut JSContext', 'cx'), - Argument('HandleObject', 'proxy'), + Argument('RawHandleObject', 'proxy'), Argument('*mut AutoIdVector', 'props')] CGAbstractExternMethod.__init__(self, descriptor, "getOwnEnumerablePropertyKeys", "bool", args) @@ -5183,15 +5186,15 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), Argument('*mut bool', 'bp')] + args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), + Argument('RawHandleId', 'id'), Argument('*mut bool', 'bp')] CGAbstractExternMethod.__init__(self, descriptor, "hasOwn", "bool", args) self.descriptor = descriptor def getBody(self): indexedGetter = self.descriptor.operations['IndexedGetter'] if indexedGetter: - indexed = ("let index = get_array_index_from_id(cx, id);\n" + + indexed = ("let index = get_array_index_from_id(cx, Handle::from_raw(id));\n" + "if let Some(index) = index {\n" + " let this = UnwrapProxy(proxy);\n" + " let this = &*this;\n" + @@ -5210,7 +5213,7 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): named = """\ if %s { let mut has_on_proto = false; - if !has_property_on_prototype(cx, proxy, id, &mut has_on_proto) { + if !has_property_on_prototype(cx, proxy_lt, id_lt, &mut has_on_proto) { return false; } if !has_on_proto { @@ -5226,9 +5229,11 @@ if %s { return indexed + """\ rooted!(in(cx) let mut expando = ptr::null_mut::()); +let proxy_lt = Handle::from_raw(proxy); +let id_lt = Handle::from_raw(id); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { - let ok = JS_HasPropertyById(cx, expando.handle(), id, bp); + let ok = JS_HasPropertyById(cx, expando.handle().into(), id, bp); if !ok || *bp { return ok; } @@ -5243,9 +5248,9 @@ return true;""" class CGDOMJSProxyHandler_get(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleValue', 'receiver'), Argument('HandleId', 'id'), - Argument('MutableHandleValue', 'vp')] + args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), + Argument('RawHandleValue', 'receiver'), Argument('RawHandleId', 'id'), + Argument('RawMutableHandleValue', 'vp')] CGAbstractExternMethod.__init__(self, descriptor, "get", "bool", args) self.descriptor = descriptor @@ -5256,23 +5261,23 @@ rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { let mut hasProp = false; - if !JS_HasPropertyById(cx, expando.handle(), id, &mut hasProp) { + if !JS_HasPropertyById(cx, expando.handle().into(), id, &mut hasProp) { return false; } if hasProp { - return JS_ForwardGetPropertyTo(cx, expando.handle(), id, receiver, vp); + return JS_ForwardGetPropertyTo(cx, expando.handle().into(), id, receiver, vp); } }""" templateValues = { - 'jsvalRef': 'vp', + 'jsvalRef': 'vp_lt', 'successCode': 'return true;', } indexedGetter = self.descriptor.operations['IndexedGetter'] if indexedGetter: - getIndexedOrExpando = ("let index = get_array_index_from_id(cx, id);\n" + + getIndexedOrExpando = ("let index = get_array_index_from_id(cx, id_lt);\n" + "if let Some(index) = index {\n" + " let this = UnwrapProxy(proxy);\n" + " let this = &*this;\n" + @@ -5305,10 +5310,14 @@ if !expando.is_null() { return """\ //MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy), //"Should not have a XrayWrapper here"); +let proxy_lt = Handle::from_raw(proxy); +let vp_lt = MutableHandle::from_raw(vp); +let id_lt = Handle::from_raw(id); +let receiver_lt = Handle::from_raw(receiver); %s let mut found = false; -if !get_property_on_prototype(cx, proxy, receiver, id, &mut found, vp) { +if !get_property_on_prototype(cx, proxy_lt, receiver_lt, id_lt, &mut found, vp_lt) { return false; } @@ -5325,7 +5334,7 @@ return true;""" % (getIndexedOrExpando, getNamed) class CGDOMJSProxyHandler_className(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', '_proxy')] + args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', '_proxy')] CGAbstractExternMethod.__init__(self, descriptor, "className", "*const i8", args, doesNotPanic=True) self.descriptor = descriptor @@ -5660,16 +5669,20 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::error::throw_type_error', 'js::error::throw_internal_error', 'js::jsapi::AutoIdVector', - 'js::jsapi::Call', + 'js::rust::wrappers::Call', 'js::jsapi::CallArgs', 'js::jsapi::CurrentGlobalOrNull', 'js::jsapi::FreeOp', - 'js::jsapi::GetPropertyKeys', + 'js::rust::wrappers::GetPropertyKeys', 'js::jsapi::GetWellKnownSymbol', - 'js::jsapi::Handle', - 'js::jsapi::HandleId', - 'js::jsapi::HandleObject', - 'js::jsapi::HandleValue', + 'js::rust::Handle', + 'js::jsapi::Handle as RawHandle', + 'js::rust::HandleId', + 'js::jsapi::HandleId as RawHandleId', + 'js::rust::HandleObject', + 'js::jsapi::HandleObject as RawHandleObject', + 'js::rust::HandleValue', + 'js::jsapi::HandleValue as RawHandleValue', 'js::jsapi::HandleValueArray', 'js::jsapi::Heap', 'js::jsapi::INTERNED_STRING_TO_JSID', @@ -5704,37 +5717,40 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JSTypedMethodJitInfo', 'js::jsapi::JSValueType', 'js::jsapi::JS_AtomizeAndPinString', - 'js::jsapi::JS_CallFunctionValue', - 'js::jsapi::JS_CopyPropertiesFrom', - 'js::jsapi::JS_DefineProperty', - 'js::jsapi::JS_DefinePropertyById2', + 'js::rust::wrappers::JS_CallFunctionValue', + 'js::rust::wrappers::JS_CopyPropertiesFrom', + 'js::rust::wrappers::JS_DefineProperty', + 'js::rust::wrappers::JS_DefinePropertyById2', 'js::jsapi::JS_ForwardGetPropertyTo', 'js::jsapi::JS_GetErrorPrototype', - 'js::jsapi::JS_GetFunctionPrototype', + 'js::rust::wrappers::JS_GetFunctionPrototype', 'js::jsapi::JS_GetGlobalForObject', 'js::jsapi::JS_GetIteratorPrototype', - 'js::jsapi::JS_GetObjectPrototype', - 'js::jsapi::JS_GetProperty', + 'js::rust::wrappers::JS_GetObjectPrototype', + 'js::rust::wrappers::JS_GetProperty', 'js::jsapi::JS_GetPropertyById', 'js::jsapi::JS_GetPropertyDescriptorById', 'js::jsapi::JS_GetReservedSlot', 'js::jsapi::JS_HasProperty', 'js::jsapi::JS_HasPropertyById', - 'js::jsapi::JS_InitializePropertiesFromCompatibleNativeObject', + 'js::rust::wrappers::JS_InitializePropertiesFromCompatibleNativeObject', 'js::jsapi::JS_NewObject', - 'js::jsapi::JS_NewObjectWithGivenProto', - 'js::jsapi::JS_NewObjectWithoutMetadata', - 'js::jsapi::JS_ObjectIsDate', - 'js::jsapi::JS_SetImmutablePrototype', - 'js::jsapi::JS_SetProperty', - 'js::jsapi::JS_SetPrototype', + 'js::rust::wrappers::JS_NewObjectWithGivenProto', + 'js::rust::wrappers::JS_NewObjectWithoutMetadata', + 'js::rust::wrappers::JS_ObjectIsDate', + 'js::rust::wrappers::JS_SetImmutablePrototype', + 'js::rust::wrappers::JS_SetProperty', + 'js::rust::wrappers::JS_SetPrototype', 'js::jsapi::JS_SetReservedSlot', - 'js::jsapi::JS_SplicePrototype', - 'js::jsapi::JS_WrapValue', - 'js::jsapi::JS_WrapObject', - 'js::jsapi::MutableHandle', - 'js::jsapi::MutableHandleObject', - 'js::jsapi::MutableHandleValue', + 'js::rust::wrappers::JS_SplicePrototype', + 'js::rust::wrappers::JS_WrapValue', + 'js::rust::wrappers::JS_WrapObject', + 'js::rust::MutableHandle', + 'js::jsapi::MutableHandle as RawMutableHandle', + 'js::rust::MutableHandleObject', + 'js::jsapi::MutableHandleObject as RawMutableHandleObject', + 'js::rust::MutableHandleValue', + 'js::jsapi::MutableHandleValue as RawMutableHandleValue', 'js::jsapi::ObjectOpResult', 'js::jsapi::PropertyDescriptor', 'js::jsapi::Rooted', @@ -5755,7 +5771,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::glue::CallJitSetterOp', 'js::glue::CreateProxyHandler', 'js::glue::GetProxyPrivate', - 'js::glue::NewProxyObject', + 'js::rust::wrappers::NewProxyObject', 'js::glue::ProxyTraps', 'js::glue::RUST_JSID_IS_INT', 'js::glue::RUST_JSID_IS_STRING', @@ -6241,7 +6257,7 @@ class CGDictionary(CGThing): "}\n" "\n" "impl ToJSValConvertible for ${selfName} {\n" - " unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {\n" + " unsafe fn to_jsval(&self, cx: *mut JSContext, mut rval: MutableHandleValue) {\n" " rooted!(in(cx) let obj = JS_NewObject(cx, ptr::null()));\n" "${insertMembers}" " rval.set(ObjectOrNullValue(obj.get()))\n" @@ -7132,7 +7148,8 @@ class GlobalGenRoots(): def InterfaceObjectMap(config): mods = [ "dom::bindings::codegen", - "js::jsapi::{HandleObject, JSContext}", + "js::jsapi::JSContext", + "js::rust::HandleObject", "phf", ] imports = CGList([CGGeneric("use %s;" % mod) for mod in mods], "\n") @@ -7166,7 +7183,7 @@ class GlobalGenRoots(): pairs.append((ctor.identifier.name, binding, binding)) pairs.sort(key=operator.itemgetter(0)) mappings = [ - CGGeneric('"%s": "codegen::Bindings::%s::%s::DefineDOMInterface as unsafe fn(_, _)"' % pair) + CGGeneric('"%s": "codegen::Bindings::%s::%s::DefineDOMInterface"' % pair) for pair in pairs ] return CGWrapper( -- cgit v1.2.3 From 938f1362e7f1b1f8a121eacc36e24c9ac6236e13 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 3 Apr 2018 14:06:07 +0200 Subject: Update the WebIDL parser --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 5b286394051..e7423c670eb 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4800,7 +4800,7 @@ class CGProxySpecialOperation(CGPerSignatureCall): False, descriptor, operation, len(arguments)) - if operation.isSetter() or operation.isCreator(): + if operation.isSetter(): # arguments[0] is the index or name of the item that we're setting. argument = arguments[1] info = getJSToNativeConversionInfo( -- cgit v1.2.3 From d0cc9d2cd56a197fdfb72d8c0168d4cf2bb23bdb Mon Sep 17 00:00:00 2001 From: Alan Jeffrey Date: Wed, 30 May 2018 14:44:47 -0500 Subject: Updated to mozjs v0.7.1. --- components/script/dom/bindings/codegen/CodegenRust.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e7423c670eb..01b52d916ae 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -361,7 +361,7 @@ class CGMethodCall(CGThing): for i in range(0, distinguishingIndex)] # Select the right overload from our set. - distinguishingArg = "args.get(%d)" % distinguishingIndex + distinguishingArg = "HandleValue::from_raw(args.get(%d))" % distinguishingIndex def pickFirstSignature(condition, filterLambda): sigs = filter(filterLambda, possibleSignatures) @@ -1284,7 +1284,7 @@ class CGArgumentConverter(CGThing): } replacementVariables = { - "val": string.Template("${args}.get(${index})").substitute(replacer), + "val": string.Template("HandleValue::from_raw(${args}.get(${index}))").substitute(replacer), } info = getJSToNativeConversionInfo( @@ -1328,7 +1328,7 @@ class CGArgumentConverter(CGThing): else: assert argument.optional variadicConversion = { - "val": string.Template("${args}.get(variadicArg)").substitute(replacer), + "val": string.Template("HandleValue::from_raw(${args}.get(variadicArg))").substitute(replacer), } innerConverter = [instantiateJSToNativeConversionTemplate( template, variadicConversion, declType, "slot")] @@ -3365,7 +3365,7 @@ class CGPerSignatureCall(CGThing): return 'infallible' not in self.extendedAttributes def wrap_return_value(self): - return wrapForType('args.rval()') + return wrapForType('MutableHandleValue::from_raw(args.rval())') def define(self): return (self.cgRoot.define() + "\n" + self.wrap_return_value()) @@ -3516,7 +3516,7 @@ class CGSpecializedMethod(CGAbstractExternMethod): self.descriptor, self.method), pre="let this = &*this;\n" "let args = &*args;\n" - "let argc = args._base.argc_;\n") + "let argc = args.argc_;\n") @staticmethod def makeNativeName(descriptor, method): @@ -3675,7 +3675,7 @@ if !v.is_object() { return false; } rooted!(in(cx) let target_obj = v.to_object()); -JS_SetProperty(cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, args.get(0)) +JS_SetProperty(cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, HandleValue::from_raw(args.get(0))) """ % (str_to_const_array(attrName), attrName, str_to_const_array(forwardToAttrName))) @@ -3693,7 +3693,7 @@ class CGSpecializedReplaceableSetter(CGSpecializedSetter): assert all(ord(c) < 128 for c in name) return CGGeneric("""\ JS_DefineProperty(cx, obj, %s as *const u8 as *const libc::c_char, - args.get(0), JSPROP_ENUMERATE, None, None)""" % name) + HandleValue::from_raw(args.get(0)), JSPROP_ENUMERATE, None, None)""" % name) class CGMemberJITInfo(CGThing): @@ -5514,7 +5514,7 @@ if !JS_WrapObject(cx, element.handle_mut()) { JS_SetPrototype(cx, element.handle(), prototype.handle()); -(result).to_jsval(cx, args.rval()); +(result).to_jsval(cx, MutableHandleValue::from_raw(args.rval())); return true; """ % self.descriptor.name) else: -- cgit v1.2.3 From ad198993b127ef87f129add8336f8bb7dfd30e4d Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Fri, 29 Jun 2018 10:34:09 -0700 Subject: Assert that DOM structs have the correct first field DOM structs embed their parent type as their first field. This introduces a `.parent()` method to the DOM struct that returns its first field, and codegens a type assert that ensures that `.parent()` returns the parent struct. This generates: On `#[dom_struct]`: ```rust impl HasParent for Type { type Parent = ParentType; fn as_parent(&self) -> ParentType { &self.first_field } } ``` In the codegen files: ```rust impl Type { fn __assert_parent_type(&self) { let _: &ParentType = self.as_parent(); } } ```` --- .../script/dom/bindings/codegen/CodegenRust.py | 52 +++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 01b52d916ae..ae76667707e 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2116,6 +2116,10 @@ class CGDOMJSClass(CGThing): self.descriptor = descriptor def define(self): + parentName = self.descriptor.getParentName() + if not parentName: + parentName = "::dom::bindings::reflector::Reflector" + args = { "domClass": DOMClass(self.descriptor), "enumerateHook": "None", @@ -2161,7 +2165,51 @@ static Class: DOMJSClass = DOMJSClass { reserved: [0 as *mut _; 3], }, dom_class: %(domClass)s -};""" % args +}; +""" % args + + +class CGAssertInheritance(CGThing): + """ + Generate a type assertion for inheritance + """ + def __init__(self, descriptor): + CGThing.__init__(self) + self.descriptor = descriptor + + def define(self): + parent = self.descriptor.interface.parent + parentName = "" + if parent: + parentName = parent.identifier.name + else: + parentName = "::dom::bindings::reflector::Reflector" + + selfName = self.descriptor.interface.identifier.name + + if selfName == "PaintRenderingContext2D": + # PaintRenderingContext2D embeds a CanvasRenderingContext2D + # instead of a Reflector as an optimization, + # but this is fine since CanvasRenderingContext2D + # also has a reflector + # + # FIXME *RenderingContext2D should use Inline + parentName = "::dom::canvasrenderingcontext2d::CanvasRenderingContext2D" + args = { + "parentName": parentName, + "selfName": selfName, + } + + return """\ +impl %(selfName)s { + fn __assert_parent_type(&self) { + use dom::bindings::inheritance::HasParent; + // If this type assertion fails, make sure the first field of your + // DOM struct is of the correct type -- it must be the parent class. + let _: &%(parentName)s = self.as_parent(); + } +} +""" % args def str_to_const_array(s): @@ -6011,6 +6059,8 @@ class CGDescriptor(CGThing): pass else: cgThings.append(CGDOMJSClass(descriptor)) + if not descriptor.interface.isIteratorInterface(): + cgThings.append(CGAssertInheritance(descriptor)) pass if descriptor.isGlobal(): -- cgit v1.2.3 From cceaede96a18e67d93c087d6d499f27eda022025 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Fri, 6 Jul 2018 11:14:44 -0700 Subject: Make (dictionary)::empty() safe It currently works by constructing from null (which will throw a runtime error if there are non-defaultable members). This changes it so that we no longer need a JSContext to construct this, so it can be safely constructed. In the case of non-defaultable members, this method simply does not exist. --- .../script/dom/bindings/codegen/CodegenRust.py | 56 ++++++++++++++++++---- 1 file changed, 48 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ae76667707e..6015a4b126a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -744,7 +744,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if defaultValue: assert isinstance(defaultValue, IDLNullValue) dictionary, = dictionaries - default = "%s::%s(%s::%s::empty(cx))" % ( + default = "%s::%s(%s::%s::empty())" % ( union_native_type(type), dictionary.name, CGDictionary.makeModuleName(dictionary.inner), @@ -1148,7 +1148,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, typeName = "%s::%s" % (CGDictionary.makeModuleName(type.inner), CGDictionary.makeDictionaryName(type.inner)) declType = CGGeneric(typeName) - empty = "%s::empty(cx)" % typeName + empty = "%s::empty()" % typeName if type_needs_tracing(type): declType = CGTemplatedType("RootedTraceableBox", declType) @@ -6274,12 +6274,7 @@ class CGDictionary(CGThing): return string.Template( "impl ${selfName} {\n" - " pub unsafe fn empty(cx: *mut JSContext) -> ${actualType} {\n" - " match ${selfName}::new(cx, HandleValue::null()) {\n" - " Ok(ConversionResult::Success(v)) => v,\n" - " _ => unreachable!(),\n" - " }\n" - " }\n" + "${empty}\n" " pub unsafe fn new(cx: *mut JSContext, val: HandleValue) \n" " -> Result, ()> {\n" " let object = if val.get().is_null_or_undefined() {\n" @@ -6315,6 +6310,7 @@ class CGDictionary(CGThing): "}\n").substitute({ "selfName": selfName, "actualType": actualType, + "empty": CGIndenter(CGGeneric(self.makeEmpty()), indentLevel=4).define(), "initParent": CGIndenter(CGGeneric(initParent), indentLevel=12).define(), "initMembers": CGIndenter(memberInits, indentLevel=12).define(), "insertMembers": CGIndenter(memberInserts, indentLevel=8).define(), @@ -6380,6 +6376,50 @@ class CGDictionary(CGThing): return CGGeneric(conversion) + def makeEmpty(self): + if self.hasRequiredFields(self.dictionary): + return "" + parentTemplate = "parent: %s::%s::empty(),\n" + fieldTemplate = "%s: %s,\n" + functionTemplate = ( + "pub fn empty() -> Self {\n" + " Self {\n" + "%s" + " }\n" + "}" + ) + if self.membersNeedTracing(): + parentTemplate = "dictionary.parent = %s::%s::empty();\n" + fieldTemplate = "dictionary.%s = %s;\n" + functionTemplate = ( + "pub fn empty() -> RootedTraceableBox {\n" + " let mut dictionary = RootedTraceableBox::new(Self::default());\n" + "%s" + " dictionary\n" + "}" + ) + s = "" + if self.dictionary.parent: + s += parentTemplate % (self.makeModuleName(self.dictionary.parent), + self.makeClassName(self.dictionary.parent)) + for member, info in self.memberInfo: + if not member.optional: + return "" + default = info.default + if not default: + default = "None" + s += fieldTemplate % (self.makeMemberName(member.identifier.name), default) + return functionTemplate % CGIndenter(CGGeneric(s), 12).define() + + def hasRequiredFields(self, dictionary): + if dictionary.parent: + if self.hasRequiredFields(dictionary.parent): + return True + for member in dictionary.members: + if not member.optional: + return True + return False + @staticmethod def makeMemberName(name): # Can't use Rust keywords as member names. -- cgit v1.2.3 From 74c1e00d8163f255bb4141ff3549bbdedd7ea766 Mon Sep 17 00:00:00 2001 From: Alan Jeffrey Date: Fri, 1 Jun 2018 17:24:25 -0500 Subject: Upgraded to SM 60 --- .../script/dom/bindings/codegen/CodegenRust.py | 86 +++++++++++++--------- 1 file changed, 52 insertions(+), 34 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 6015a4b126a..449fda3b7ea 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1775,7 +1775,7 @@ class AttrDefiner(PropertyDefiner): if len(array) == 0: return "" - flags = "JSPROP_ENUMERATE | JSPROP_SHARED" + flags = "JSPROP_ENUMERATE" if self.unforgeable: flags += " | JSPROP_PERMANENT" @@ -1822,15 +1822,18 @@ class AttrDefiner(PropertyDefiner): ' JSPropertySpec {\n' ' name: %s as *const u8 as *const libc::c_char,\n' ' flags: (%s) as u8,\n' - ' getter: %s,\n' - ' setter: %s\n' - ' }', - ' JSPropertySpec {\n' - ' name: 0 as *const libc::c_char,\n' - ' flags: 0,\n' - ' getter: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo },\n' - ' setter: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo }\n' + ' __bindgen_anon_1: JSPropertySpec__bindgen_ty_1 {\n' + ' accessors: JSPropertySpec__bindgen_ty_1__bindgen_ty_1 {\n' + ' getter: JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {\n' + ' native: %s,\n' + ' },\n' + ' setter: JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_2 {\n' + ' native: %s,\n' + ' }\n' + ' }\n' + ' }\n' ' }', + ' JSPropertySpec::ZERO', 'JSPropertySpec', PropertyDefiner.getControllingCondition, specData) @@ -2124,7 +2127,7 @@ class CGDOMJSClass(CGThing): "domClass": DOMClass(self.descriptor), "enumerateHook": "None", "finalizeHook": FINALIZE_HOOK_NAME, - "flags": "0", + "flags": "JSCLASS_FOREGROUND_FINALIZE", "name": str_to_const_array(self.descriptor.interface.identifier.name), "resolveHook": "None", "slots": "1", @@ -2133,7 +2136,7 @@ class CGDOMJSClass(CGThing): if self.descriptor.isGlobal(): assert not self.descriptor.weakReferenceable args["enumerateHook"] = "Some(enumerate_global)" - args["flags"] = "JSCLASS_IS_GLOBAL | JSCLASS_DOM_GLOBAL" + args["flags"] = "JSCLASS_IS_GLOBAL | JSCLASS_DOM_GLOBAL | JSCLASS_FOREGROUND_FINALIZE" args["slots"] = "JSCLASS_GLOBAL_SLOT_COUNT + 1" args["resolveHook"] = "Some(resolve_global)" args["traceHook"] = "js::jsapi::JS_GlobalObjectTraceHook" @@ -2143,9 +2146,8 @@ class CGDOMJSClass(CGThing): static CLASS_OPS: js::jsapi::JSClassOps = js::jsapi::JSClassOps { addProperty: None, delProperty: None, - getProperty: None, - setProperty: None, enumerate: %(enumerateHook)s, + newEnumerate: None, resolve: %(resolveHook)s, mayResolve: None, finalize: Some(%(finalizeHook)s), @@ -2583,10 +2585,11 @@ def CreateBindingJSObject(descriptor, parent=None): let handler = RegisterBindings::PROXY_HANDLERS[PrototypeList::Proxies::%s as usize]; rooted!(in(cx) let private = PrivateValue(raw as *const libc::c_void)); let obj = NewProxyObject(cx, handler, - private.handle(), + Handle::from_raw(UndefinedHandleValue), proto.get(), %s.get(), ptr::null_mut(), ptr::null_mut()); assert!(!obj.is_null()); +SetProxyReservedSlot(obj, 0, &private.get()); rooted!(in(cx) let obj = obj);\ """ % (descriptor.name, parent) else: @@ -2594,11 +2597,13 @@ rooted!(in(cx) let obj = obj);\ " cx, &Class.base as *const JSClass, proto.handle()));\n" "assert!(!obj.is_null());\n" "\n" - "JS_SetReservedSlot(obj.get(), DOM_OBJECT_SLOT,\n" - " PrivateValue(raw as *const libc::c_void));") + "let val = PrivateValue(raw as *const libc::c_void);\n" + "\n" + "JS_SetReservedSlot(obj.get(), DOM_OBJECT_SLOT, &val);") if descriptor.weakReferenceable: create += """ -JS_SetReservedSlot(obj.get(), DOM_WEAK_SLOT, PrivateValue(ptr::null()));""" +let val = PrivateValue(ptr::null()); +JS_SetReservedSlot(obj.get(), DOM_WEAK_SLOT, &val);""" return create @@ -2652,9 +2657,10 @@ ensure_expando_object(cx, obj.handle().into(), expando.handle_mut()); else: copyFunc = "JS_InitializePropertiesFromCompatibleNativeObject" copyCode += """\ +let mut slot = UndefinedValue(); +JS_GetReservedSlot(proto.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT, &mut slot); rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut::()); -unforgeable_holder.handle_mut().set( - JS_GetReservedSlot(proto.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT).to_object()); +unforgeable_holder.handle_mut().set(slot.to_object()); assert!(%(copyFunc)s(cx, %(obj)s.handle(), unforgeable_holder.handle())); """ % {'copyFunc': copyFunc, 'obj': obj} @@ -3013,7 +3019,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); CGGeneric(fill( """ assert!(${defineFn}(cx, prototype.handle(), ${prop}, aliasedVal.handle(), - JSPROP_ENUMERATE, None, None)); + JSPROP_ENUMERATE as u32)); """, defineFn=defineFn, prop=prop)) @@ -3078,8 +3084,8 @@ assert!(!unforgeable_holder.is_null()); """ % {'holderClass': holderClass, 'holderProto': holderProto})) code.append(InitUnforgeablePropertiesOnHolder(self.descriptor, self.properties)) code.append(CGGeneric("""\ -JS_SetReservedSlot(prototype.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT, - ObjectValue(unforgeable_holder.get()))""")) +let val = ObjectValue(unforgeable_holder.get()); +JS_SetReservedSlot(prototype.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT, &val)""")) return CGList(code, "\n") @@ -3533,11 +3539,13 @@ class CGAbstractStaticBindingMethod(CGAbstractMethod): self.exposureSet = descriptor.interface.exposureSet def definition_body(self): - preamble = "let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n" + preamble = """\ +let args = CallArgs::from_vp(vp, argc); +let global = GlobalScope::from_object(args.callee()); +""" if len(self.exposureSet) == 1: - preamble += """ -let global = DomRoot::downcast::(global).unwrap(); -""" % list(self.exposureSet)[0] + preamble += ("let global = DomRoot::downcast::(global).unwrap();\n" % + list(self.exposureSet)[0]) return CGList([CGGeneric(preamble), self.generate_code()]) def generate_code(self): @@ -3741,7 +3749,7 @@ class CGSpecializedReplaceableSetter(CGSpecializedSetter): assert all(ord(c) < 128 for c in name) return CGGeneric("""\ JS_DefineProperty(cx, obj, %s as *const u8 as *const libc::c_char, - HandleValue::from_raw(args.get(0)), JSPROP_ENUMERATE, None, None)""" % name) + HandleValue::from_raw(args.get(0)), JSPROP_ENUMERATE as u32)""" % name) class CGMemberJITInfo(CGThing): @@ -4959,7 +4967,9 @@ class CGProxyUnwrap(CGAbstractMethod): obj = js::UnwrapObject(obj); }*/ //MOZ_ASSERT(IsProxy(obj)); -let box_ = GetProxyPrivate(obj.get()).to_private() as *const %s; + let mut slot = UndefinedValue(); + GetProxyReservedSlot(obj.get(), 0, &mut slot); + let box_ = slot.to_private() as *const %s; return box_;""" % self.descriptor.concreteType) @@ -4985,7 +4995,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): attrs += " | JSPROP_READONLY" # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. fillDescriptor = ("desc.get().value = result_root.get();\n" - "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), %s);\n" + "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), (%s) as u32);\n" "return true;" % attrs) templateValues = { 'jsvalRef': 'result_root.handle_mut()', @@ -5011,7 +5021,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): attrs = "0" # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. fillDescriptor = ("desc.get().value = result_root.get();\n" - "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), %s);\n" + "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), (%s) as u32);\n" "return true;" % attrs) templateValues = { 'jsvalRef': 'result_root.handle_mut()', @@ -5425,7 +5435,9 @@ finalize_global(obj); """ elif descriptor.weakReferenceable: release += """\ -let weak_box_ptr = JS_GetReservedSlot(obj, DOM_WEAK_SLOT).to_private() as *mut WeakBox<%s>; +let mut slot = UndefinedValue(); +JS_GetReservedSlot(obj, DOM_WEAK_SLOT, &mut slot); +let weak_box_ptr = slot.to_private() as *mut WeakBox<%s>; if !weak_box_ptr.is_null() { let count = { let weak_box = &*weak_box_ptr; @@ -5736,6 +5748,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::INTERNED_STRING_TO_JSID', 'js::jsapi::IsCallable', 'js::jsapi::JSAutoCompartment', + 'js::jsapi::JSCLASS_FOREGROUND_FINALIZE', 'js::jsapi::JSCLASS_RESERVED_SLOTS_SHIFT', 'js::jsapi::JSClass', 'js::jsapi::JSContext', @@ -5757,8 +5770,11 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JSPROP_ENUMERATE', 'js::jsapi::JSPROP_PERMANENT', 'js::jsapi::JSPROP_READONLY', - 'js::jsapi::JSPROP_SHARED', 'js::jsapi::JSPropertySpec', + 'js::jsapi::JSPropertySpec__bindgen_ty_1', + 'js::jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1', + 'js::jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1', + 'js::jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_2', 'js::jsapi::JSString', 'js::jsapi::JSTracer', 'js::jsapi::JSType', @@ -5778,7 +5794,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::rust::wrappers::JS_GetProperty', 'js::jsapi::JS_GetPropertyById', 'js::jsapi::JS_GetPropertyDescriptorById', - 'js::jsapi::JS_GetReservedSlot', + 'js::glue::JS_GetReservedSlot', 'js::jsapi::JS_HasProperty', 'js::jsapi::JS_HasPropertyById', 'js::rust::wrappers::JS_InitializePropertiesFromCompatibleNativeObject', @@ -5813,12 +5829,14 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsval::ObjectOrNullValue', 'js::jsval::PrivateValue', 'js::jsval::UndefinedValue', + 'js::jsapi::UndefinedHandleValue', 'js::glue::AppendToAutoIdVector', 'js::glue::CallJitGetterOp', 'js::glue::CallJitMethodOp', 'js::glue::CallJitSetterOp', 'js::glue::CreateProxyHandler', - 'js::glue::GetProxyPrivate', + 'js::glue::GetProxyReservedSlot', + 'js::glue::SetProxyReservedSlot', 'js::rust::wrappers::NewProxyObject', 'js::glue::ProxyTraps', 'js::glue::RUST_JSID_IS_INT', -- cgit v1.2.3 From 900a19058e5f282fdb914ac16801d11f4a2c0159 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 27 Aug 2018 12:08:17 +0200 Subject: Support unions of objects in overloads Part of #20513, implementing the parts useful for WebGL. --- .../script/dom/bindings/codegen/CodegenRust.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 449fda3b7ea..6da269d61cb 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -344,12 +344,17 @@ class CGMethodCall(CGThing): distinguishingIndex = method.distinguishingIndexForArgCount(argCount) - # We can't handle unions at the distinguishing index. + # We can't handle unions of non-object values at the distinguishing index. for (returnType, args) in possibleSignatures: - if args[distinguishingIndex].type.isUnion(): - raise TypeError("No support for unions as distinguishing " - "arguments yet: %s", - args[distinguishingIndex].location) + type = args[distinguishingIndex].type + if type.isUnion(): + if type.nullable(): + type = type.inner + for type in type.flatMemberTypes: + if not (type.isObject() or type.isNonCallbackInterface()): + raise TypeError("No support for unions with non-object variants " + "as distinguishing arguments yet: %s", + args[distinguishingIndex].location) # Convert all our arguments up to the distinguishing index. # Doesn't matter which of the possible signatures we use, since @@ -388,6 +393,7 @@ class CGMethodCall(CGThing): interfacesSigs = [ s for s in possibleSignatures if (s[1][distinguishingIndex].type.isObject() or + s[1][distinguishingIndex].type.isUnion() or s[1][distinguishingIndex].type.isNonCallbackInterface())] # There might be more than one of these; we need to check # which ones we unwrap to. @@ -2366,7 +2372,6 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::conversions::ConversionBehavior', 'dom::bindings::conversions::StringificationBehavior', 'dom::bindings::conversions::root_from_handlevalue', - 'dom::bindings::error::throw_not_in_union', 'std::ptr::NonNull', 'dom::bindings::mozmap::MozMap', 'dom::bindings::root::DomRoot', @@ -4450,8 +4455,8 @@ class CGUnionConversionStruct(CGThing): other.append(booleanConversion[0]) conversions.append(CGList(other, "\n\n")) conversions.append(CGGeneric( - "throw_not_in_union(cx, \"%s\");\n" - "Err(())" % ", ".join(names))) + "Ok(ConversionResult::Failure(\"argument could not be converted to any of: %s\".into()))" % ", ".join(names) + )) method = CGWrapper( CGIndenter(CGList(conversions, "\n\n")), pre="unsafe fn from_jsval(cx: *mut JSContext,\n" -- cgit v1.2.3 From baa94702e4a19ff1c1f8c448ae3feb83445b4e01 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Sep 2018 13:57:10 +0200 Subject: Properly set desc.obj in CodegenRust.py (fixes #11868) --- components/script/dom/bindings/codegen/CodegenRust.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 6da269d61cb..39409e7deaa 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4982,7 +4982,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): def __init__(self, descriptor): args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawHandleId', 'id'), - Argument('RawMutableHandle', 'desc')] + Argument('RawMutableHandle', 'mut desc')] CGAbstractExternMethod.__init__(self, descriptor, "getOwnPropertyDescriptor", "bool", args) self.descriptor = descriptor @@ -5055,7 +5055,6 @@ if %s { else: namedGet = "" - # FIXME(#11868) Should assign to desc.obj, desc.get() is a copy. return get + """\ rooted!(in(cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); @@ -5068,7 +5067,7 @@ if !expando.is_null() { } if !desc.obj.is_null() { // Pretend the property lives on the wrapper. - desc.get().obj = proxy.get(); + desc.obj = proxy.get(); return true; } } -- cgit v1.2.3 From a846ed1654fb16ca8505f5290613bdc8bd17bb26 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Fri, 5 Oct 2018 14:25:53 +0200 Subject: Upgrade to rustc 1.31.0-nightly (8c4ad4e9e 2018-10-04) CC https://github.com/rust-lang/rust/issues/54846 --- components/script/dom/bindings/codegen/CodegenRust.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 39409e7deaa..fd2df0799c6 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2278,7 +2278,14 @@ static NAMESPACE_OBJECT_CLASS: NamespaceObjectClass = unsafe { return """\ static INTERFACE_OBJECT_CLASS: NonCallbackInterfaceObjectClass = NonCallbackInterfaceObjectClass::new( - &%(constructorBehavior)s, + { + // Intermediate `const` because as of nightly-2018-10-05, + // rustc is conservative in promotion to `'static` of the return values of `const fn`s: + // https://github.com/rust-lang/rust/issues/54846 + // https://github.com/rust-lang/rust/pull/53851 + const BEHAVIOR: InterfaceConstructorBehavior = %(constructorBehavior)s; + &BEHAVIOR + }, %(representation)s, PrototypeList::ID::%(id)s, %(depth)s); -- cgit v1.2.3 From 8b2892113693e6d2eddfc29dd49bbf7d54954912 Mon Sep 17 00:00:00 2001 From: CYBAI Date: Mon, 7 May 2018 20:31:29 +0800 Subject: Make expectionCode of Promise have newline character automatically In the `fill` method, it will check if the exception code is empty string or has newline character in the end of string or not. However, we didn't do any change to exceptionCode when type is Promise. Thus, we add the newline character to make it pass the checking in `fill` method. See more detail from the log of IRC: https://mozilla.logbot.info/servo/20180501#c14692647 --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index fd2df0799c6..c9271bb03dc 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6207,7 +6207,7 @@ class CGDictionary(CGThing): descriptorProvider, isMember="Dictionary", defaultValue=member.defaultValue, - exceptionCode="return Err(());")) + exceptionCode="return Err(());\n")) for member in dictionary.members] def define(self): -- cgit v1.2.3 From 99589d2f2ae2c9fc87eaa23dcd2ea1bdf74a45a6 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 1 Nov 2018 14:54:23 -0700 Subject: Handle default empty sequence values --- .../script/dom/bindings/codegen/CodegenRust.py | 33 ++++++++++++---------- 1 file changed, 18 insertions(+), 15 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c9271bb03dc..8d0b68003c5 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -17,6 +17,7 @@ import functools from WebIDL import ( BuiltinTypes, IDLBuiltinType, + IDLEmptySequenceValue, IDLInterfaceMember, IDLNullableType, IDLNullValue, @@ -673,17 +674,19 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, ('throw_type_error(cx, \"%s is not callable.\");\n' '%s' % (firstCap(sourceDescription), exceptionCode))) - # A helper function for handling null default values. Checks that the - # default value, if it exists, is null. - def handleDefaultNull(nullValue): + # A helper function for handling default values. + def handleDefault(nullValue): if defaultValue is None: return None - if not isinstance(defaultValue, IDLNullValue): - raise TypeError("Can't handle non-null default value here") + if isinstance(defaultValue, IDLNullValue): + assert type.nullable() or type.isDictionary() + return nullValue + elif isinstance(defaultValue, IDLEmptySequenceValue): + assert type.isSequence() + return "Vec::new()" - assert type.nullable() or type.isDictionary() - return nullValue + raise TypeError("Can't handle non-null or non-empty sequence default value here") # A helper function for wrapping up the template body for # possibly-nullable objecty stuff @@ -726,7 +729,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, " _ => { %s },\n" "}" % (config, indent(failOrPropagate, 8), exceptionCode)) - return handleOptional(templateBody, declType, handleDefaultNull("None")) + return handleOptional(templateBody, declType, handleDefault("None")) if type.isUnion(): declType = CGGeneric(union_native_type(type)) @@ -758,7 +761,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, else: default = None else: - default = handleDefaultNull("None") + default = handleDefault("None") return handleOptional(templateBody, declType, default) @@ -810,7 +813,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, declType = CGGeneric("&Promise") else: declType = CGGeneric("Rc") - return handleOptional(templateBody, declType, handleDefaultNull("None")) + return handleOptional(templateBody, declType, handleDefault("None")) if type.isGeckoInterface(): assert not isEnforceRange and not isClamp @@ -828,7 +831,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, isDefinitelyObject, type, failureCode) - return handleOptional(template, declType, handleDefaultNull("None")) + return handleOptional(template, declType, handleDefault("None")) conversionFunction = "root_from_handlevalue" descriptorType = descriptor.returnType @@ -875,7 +878,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, templateBody = wrapObjectTemplate(templateBody, "None", isDefinitelyObject, type, failureCode) - return handleOptional(templateBody, declType, handleDefaultNull("None")) + return handleOptional(templateBody, declType, handleDefault("None")) if is_typed_array(type): if failureCode is None: @@ -918,7 +921,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, templateBody = wrapObjectTemplate(templateBody, "None", isDefinitelyObject, type, failureCode) - return handleOptional(templateBody, declType, handleDefaultNull("None")) + return handleOptional(templateBody, declType, handleDefault("None")) elif type.isSpiderMonkeyInterface(): raise TypeError("Can't handle SpiderMonkey interface arguments other than typed arrays yet") @@ -1145,7 +1148,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, isDefinitelyObject, type, failureCode) return handleOptional(templateBody, declType, - handleDefaultNull(default)) + handleDefault(default)) if type.isDictionary(): # There are no nullable dictionaries @@ -1167,7 +1170,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, " _ => { %s },\n" "}" % (indent(failOrPropagate, 8), exceptionCode)) - return handleOptional(template, declType, handleDefaultNull(empty)) + return handleOptional(template, declType, handleDefault(empty)) if type.isVoid(): # This one only happens for return values, and its easy: Just -- cgit v1.2.3 From acabd50f037837c2dc75233988690e0184cd511c Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Thu, 1 Nov 2018 14:38:55 +0100 Subject: Use 2018-style paths in generated DOM bindings --- .../script/dom/bindings/codegen/CodegenRust.py | 286 ++++++++++----------- 1 file changed, 143 insertions(+), 143 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 8d0b68003c5..da0d27ce764 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2034,9 +2034,9 @@ class CGImports(CGWrapper): descriptor = descriptorProvider.getDescriptor(parentName) extras += [descriptor.path, descriptor.bindingPath] elif t.isType() and t.isRecord(): - extras += ['dom::bindings::mozmap::MozMap'] + extras += ['crate::dom::bindings::mozmap::MozMap'] elif isinstance(t, IDLPromiseType): - extras += ["dom::promise::Promise"] + extras += ['crate::dom::promise::Promise'] else: if t.isEnum(): extras += [getModuleFromObject(t) + '::' + getIdentifier(t).name + 'Values'] @@ -2086,15 +2086,15 @@ def DOMClassTypeId(desc): inner = "" if desc.hasDescendants(): if desc.interface.getExtendedAttribute("Abstract"): - return "::dom::bindings::codegen::InheritTypes::TopTypeId { abstract_: () }" + return "crate::dom::bindings::codegen::InheritTypes::TopTypeId { abstract_: () }" name = desc.interface.identifier.name - inner = "(::dom::bindings::codegen::InheritTypes::%sTypeId::%s)" % (name, name) + inner = "(crate::dom::bindings::codegen::InheritTypes::%sTypeId::%s)" % (name, name) elif len(protochain) == 1: - return "::dom::bindings::codegen::InheritTypes::TopTypeId { alone: () }" + return "crate::dom::bindings::codegen::InheritTypes::TopTypeId { alone: () }" reversed_protochain = list(reversed(protochain)) for (child, parent) in zip(reversed_protochain, reversed_protochain[1:]): - inner = "(::dom::bindings::codegen::InheritTypes::%sTypeId::%s%s)" % (parent, child, inner) - return "::dom::bindings::codegen::InheritTypes::TopTypeId { %s: %s }" % (protochain[0].lower(), inner) + inner = "(crate::dom::bindings::codegen::InheritTypes::%sTypeId::%s%s)" % (parent, child, inner) + return "crate::dom::bindings::codegen::InheritTypes::TopTypeId { %s: %s }" % (protochain[0].lower(), inner) def DOMClass(descriptor): @@ -2130,7 +2130,7 @@ class CGDOMJSClass(CGThing): def define(self): parentName = self.descriptor.getParentName() if not parentName: - parentName = "::dom::bindings::reflector::Reflector" + parentName = "crate::dom::bindings::reflector::Reflector" args = { "domClass": DOMClass(self.descriptor), @@ -2194,7 +2194,7 @@ class CGAssertInheritance(CGThing): if parent: parentName = parent.identifier.name else: - parentName = "::dom::bindings::reflector::Reflector" + parentName = "crate::dom::bindings::reflector::Reflector" selfName = self.descriptor.interface.identifier.name @@ -2205,7 +2205,7 @@ class CGAssertInheritance(CGThing): # also has a reflector # # FIXME *RenderingContext2D should use Inline - parentName = "::dom::canvasrenderingcontext2d::CanvasRenderingContext2D" + parentName = "crate::dom::canvasrenderingcontext2d::CanvasRenderingContext2D" args = { "parentName": parentName, "selfName": selfName, @@ -2214,7 +2214,7 @@ class CGAssertInheritance(CGThing): return """\ impl %(selfName)s { fn __assert_parent_type(&self) { - use dom::bindings::inheritance::HasParent; + use crate::dom::bindings::inheritance::HasParent; // If this type assertion fails, make sure the first field of your // DOM struct is of the correct type -- it must be the parent class. let _: &%(parentName)s = self.as_parent(); @@ -2374,22 +2374,22 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): """ imports = [ - 'dom', - 'dom::bindings::codegen::PrototypeList', - 'dom::bindings::conversions::ConversionResult', - 'dom::bindings::conversions::FromJSValConvertible', - 'dom::bindings::conversions::ToJSValConvertible', - 'dom::bindings::conversions::ConversionBehavior', - 'dom::bindings::conversions::StringificationBehavior', - 'dom::bindings::conversions::root_from_handlevalue', + 'crate::dom', + 'crate::dom::bindings::codegen::PrototypeList', + 'crate::dom::bindings::conversions::ConversionResult', + 'crate::dom::bindings::conversions::FromJSValConvertible', + 'crate::dom::bindings::conversions::ToJSValConvertible', + 'crate::dom::bindings::conversions::ConversionBehavior', + 'crate::dom::bindings::conversions::StringificationBehavior', + 'crate::dom::bindings::conversions::root_from_handlevalue', 'std::ptr::NonNull', - 'dom::bindings::mozmap::MozMap', - 'dom::bindings::root::DomRoot', - 'dom::bindings::str::ByteString', - 'dom::bindings::str::DOMString', - 'dom::bindings::str::USVString', - 'dom::bindings::trace::RootedTraceableBox', - 'dom::types::*', + 'crate::dom::bindings::mozmap::MozMap', + 'crate::dom::bindings::root::DomRoot', + 'crate::dom::bindings::str::ByteString', + 'crate::dom::bindings::str::DOMString', + 'crate::dom::bindings::str::USVString', + 'crate::dom::bindings::trace::RootedTraceableBox', + 'crate::dom::types::*', 'js::error::throw_type_error', 'js::rust::HandleValue', 'js::jsapi::Heap', @@ -4150,7 +4150,7 @@ pub enum %s { pairs = ",\n ".join(['("%s", super::%s::%s)' % (val, ident, getEnumValueName(val)) for val in enum.values()]) inner = string.Template("""\ -use dom::bindings::conversions::ToJSValConvertible; +use crate::dom::bindings::conversions::ToJSValConvertible; use js::jsapi::JSContext; use js::rust::MutableHandleValue; use js::jsval::JSVal; @@ -5866,112 +5866,112 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::rust::define_properties', 'js::rust::get_object_class', 'js::typedarray', - 'dom', - 'dom::bindings', - 'dom::bindings::codegen::InterfaceObjectMap', - 'dom::bindings::constant::ConstantSpec', - 'dom::bindings::constant::ConstantVal', - 'dom::bindings::interface::ConstructorClassHook', - 'dom::bindings::interface::InterfaceConstructorBehavior', - 'dom::bindings::interface::NonCallbackInterfaceObjectClass', - 'dom::bindings::interface::create_global_object', - 'dom::bindings::interface::create_callback_interface_object', - 'dom::bindings::interface::create_interface_prototype_object', - 'dom::bindings::interface::create_named_constructors', - 'dom::bindings::interface::create_noncallback_interface_object', - 'dom::bindings::interface::define_guarded_constants', - 'dom::bindings::interface::define_guarded_methods', - 'dom::bindings::interface::define_guarded_properties', - 'dom::bindings::htmlconstructor::html_constructor', - 'dom::bindings::interface::is_exposed_in', - 'dom::bindings::htmlconstructor::pop_current_element_queue', - 'dom::bindings::htmlconstructor::push_new_element_queue', - 'dom::bindings::iterable::Iterable', - 'dom::bindings::iterable::IteratorType', - 'dom::bindings::namespace::NamespaceObjectClass', - 'dom::bindings::namespace::create_namespace_object', - 'dom::bindings::reflector::MutDomObject', - 'dom::bindings::reflector::DomObject', - 'dom::bindings::root::Dom', - 'dom::bindings::root::DomRoot', - 'dom::bindings::root::OptionalHeapSetter', - 'dom::bindings::root::RootedReference', - 'dom::bindings::utils::AsVoidPtr', - 'dom::bindings::utils::DOMClass', - 'dom::bindings::utils::DOMJSClass', - 'dom::bindings::utils::DOM_PROTO_UNFORGEABLE_HOLDER_SLOT', - 'dom::bindings::utils::JSCLASS_DOM_GLOBAL', - 'dom::bindings::utils::ProtoOrIfaceArray', - 'dom::bindings::utils::enumerate_global', - 'dom::bindings::utils::finalize_global', - 'dom::bindings::utils::find_enum_value', - 'dom::bindings::utils::generic_getter', - 'dom::bindings::utils::generic_lenient_getter', - 'dom::bindings::utils::generic_lenient_setter', - 'dom::bindings::utils::generic_method', - 'dom::bindings::utils::generic_setter', - 'dom::bindings::utils::get_array_index_from_id', - 'dom::bindings::utils::get_dictionary_property', - 'dom::bindings::utils::get_property_on_prototype', - 'dom::bindings::utils::get_proto_or_iface_array', - 'dom::bindings::utils::has_property_on_prototype', - 'dom::bindings::utils::is_platform_object', - 'dom::bindings::utils::resolve_global', - 'dom::bindings::utils::set_dictionary_property', - 'dom::bindings::utils::trace_global', - 'dom::bindings::trace::JSTraceable', - 'dom::bindings::trace::RootedTraceable', - 'dom::bindings::trace::RootedTraceableBox', - 'dom::bindings::callback::CallSetup', - 'dom::bindings::callback::CallbackContainer', - 'dom::bindings::callback::CallbackInterface', - 'dom::bindings::callback::CallbackFunction', - 'dom::bindings::callback::CallbackObject', - 'dom::bindings::callback::ExceptionHandling', - 'dom::bindings::callback::wrap_call_this_object', - 'dom::bindings::conversions::ConversionBehavior', - 'dom::bindings::conversions::ConversionResult', - 'dom::bindings::conversions::DOM_OBJECT_SLOT', - 'dom::bindings::conversions::FromJSValConvertible', - 'dom::bindings::conversions::IDLInterface', - 'dom::bindings::conversions::StringificationBehavior', - 'dom::bindings::conversions::ToJSValConvertible', - 'dom::bindings::conversions::is_array_like', - 'dom::bindings::conversions::native_from_handlevalue', - 'dom::bindings::conversions::native_from_object', - 'dom::bindings::conversions::private_from_object', - 'dom::bindings::conversions::root_from_handleobject', - 'dom::bindings::conversions::root_from_handlevalue', - 'dom::bindings::conversions::root_from_object', - 'dom::bindings::conversions::jsid_to_string', - 'dom::bindings::codegen::PrototypeList', - 'dom::bindings::codegen::RegisterBindings', - 'dom::bindings::codegen::UnionTypes', - 'dom::bindings::error::Error', - 'dom::bindings::error::ErrorResult', - 'dom::bindings::error::Fallible', - 'dom::bindings::error::Error::JSFailed', - 'dom::bindings::error::throw_dom_exception', - 'dom::bindings::guard::Condition', - 'dom::bindings::guard::Guard', - 'dom::bindings::inheritance::Castable', - 'dom::bindings::proxyhandler', - 'dom::bindings::proxyhandler::ensure_expando_object', - 'dom::bindings::proxyhandler::fill_property_descriptor', - 'dom::bindings::proxyhandler::get_expando_object', - 'dom::bindings::proxyhandler::get_property_descriptor', - 'dom::bindings::mozmap::MozMap', + 'crate::dom', + 'crate::dom::bindings', + 'crate::dom::bindings::codegen::InterfaceObjectMap', + 'crate::dom::bindings::constant::ConstantSpec', + 'crate::dom::bindings::constant::ConstantVal', + 'crate::dom::bindings::interface::ConstructorClassHook', + 'crate::dom::bindings::interface::InterfaceConstructorBehavior', + 'crate::dom::bindings::interface::NonCallbackInterfaceObjectClass', + 'crate::dom::bindings::interface::create_global_object', + 'crate::dom::bindings::interface::create_callback_interface_object', + 'crate::dom::bindings::interface::create_interface_prototype_object', + 'crate::dom::bindings::interface::create_named_constructors', + 'crate::dom::bindings::interface::create_noncallback_interface_object', + 'crate::dom::bindings::interface::define_guarded_constants', + 'crate::dom::bindings::interface::define_guarded_methods', + 'crate::dom::bindings::interface::define_guarded_properties', + 'crate::dom::bindings::htmlconstructor::html_constructor', + 'crate::dom::bindings::interface::is_exposed_in', + 'crate::dom::bindings::htmlconstructor::pop_current_element_queue', + 'crate::dom::bindings::htmlconstructor::push_new_element_queue', + 'crate::dom::bindings::iterable::Iterable', + 'crate::dom::bindings::iterable::IteratorType', + 'crate::dom::bindings::namespace::NamespaceObjectClass', + 'crate::dom::bindings::namespace::create_namespace_object', + 'crate::dom::bindings::reflector::MutDomObject', + 'crate::dom::bindings::reflector::DomObject', + 'crate::dom::bindings::root::Dom', + 'crate::dom::bindings::root::DomRoot', + 'crate::dom::bindings::root::OptionalHeapSetter', + 'crate::dom::bindings::root::RootedReference', + 'crate::dom::bindings::utils::AsVoidPtr', + 'crate::dom::bindings::utils::DOMClass', + 'crate::dom::bindings::utils::DOMJSClass', + 'crate::dom::bindings::utils::DOM_PROTO_UNFORGEABLE_HOLDER_SLOT', + 'crate::dom::bindings::utils::JSCLASS_DOM_GLOBAL', + 'crate::dom::bindings::utils::ProtoOrIfaceArray', + 'crate::dom::bindings::utils::enumerate_global', + 'crate::dom::bindings::utils::finalize_global', + 'crate::dom::bindings::utils::find_enum_value', + 'crate::dom::bindings::utils::generic_getter', + 'crate::dom::bindings::utils::generic_lenient_getter', + 'crate::dom::bindings::utils::generic_lenient_setter', + 'crate::dom::bindings::utils::generic_method', + 'crate::dom::bindings::utils::generic_setter', + 'crate::dom::bindings::utils::get_array_index_from_id', + 'crate::dom::bindings::utils::get_dictionary_property', + 'crate::dom::bindings::utils::get_property_on_prototype', + 'crate::dom::bindings::utils::get_proto_or_iface_array', + 'crate::dom::bindings::utils::has_property_on_prototype', + 'crate::dom::bindings::utils::is_platform_object', + 'crate::dom::bindings::utils::resolve_global', + 'crate::dom::bindings::utils::set_dictionary_property', + 'crate::dom::bindings::utils::trace_global', + 'crate::dom::bindings::trace::JSTraceable', + 'crate::dom::bindings::trace::RootedTraceable', + 'crate::dom::bindings::trace::RootedTraceableBox', + 'crate::dom::bindings::callback::CallSetup', + 'crate::dom::bindings::callback::CallbackContainer', + 'crate::dom::bindings::callback::CallbackInterface', + 'crate::dom::bindings::callback::CallbackFunction', + 'crate::dom::bindings::callback::CallbackObject', + 'crate::dom::bindings::callback::ExceptionHandling', + 'crate::dom::bindings::callback::wrap_call_this_object', + 'crate::dom::bindings::conversions::ConversionBehavior', + 'crate::dom::bindings::conversions::ConversionResult', + 'crate::dom::bindings::conversions::DOM_OBJECT_SLOT', + 'crate::dom::bindings::conversions::FromJSValConvertible', + 'crate::dom::bindings::conversions::IDLInterface', + 'crate::dom::bindings::conversions::StringificationBehavior', + 'crate::dom::bindings::conversions::ToJSValConvertible', + 'crate::dom::bindings::conversions::is_array_like', + 'crate::dom::bindings::conversions::native_from_handlevalue', + 'crate::dom::bindings::conversions::native_from_object', + 'crate::dom::bindings::conversions::private_from_object', + 'crate::dom::bindings::conversions::root_from_handleobject', + 'crate::dom::bindings::conversions::root_from_handlevalue', + 'crate::dom::bindings::conversions::root_from_object', + 'crate::dom::bindings::conversions::jsid_to_string', + 'crate::dom::bindings::codegen::PrototypeList', + 'crate::dom::bindings::codegen::RegisterBindings', + 'crate::dom::bindings::codegen::UnionTypes', + 'crate::dom::bindings::error::Error', + 'crate::dom::bindings::error::ErrorResult', + 'crate::dom::bindings::error::Fallible', + 'crate::dom::bindings::error::Error::JSFailed', + 'crate::dom::bindings::error::throw_dom_exception', + 'crate::dom::bindings::guard::Condition', + 'crate::dom::bindings::guard::Guard', + 'crate::dom::bindings::inheritance::Castable', + 'crate::dom::bindings::proxyhandler', + 'crate::dom::bindings::proxyhandler::ensure_expando_object', + 'crate::dom::bindings::proxyhandler::fill_property_descriptor', + 'crate::dom::bindings::proxyhandler::get_expando_object', + 'crate::dom::bindings::proxyhandler::get_property_descriptor', + 'crate::dom::bindings::mozmap::MozMap', 'std::ptr::NonNull', - 'dom::bindings::num::Finite', - 'dom::bindings::str::ByteString', - 'dom::bindings::str::DOMString', - 'dom::bindings::str::USVString', - 'dom::bindings::weakref::DOM_WEAK_SLOT', - 'dom::bindings::weakref::WeakBox', - 'dom::bindings::weakref::WeakReferenceable', - 'dom::windowproxy::WindowProxy', - 'dom::globalscope::GlobalScope', - 'mem::malloc_size_of_including_raw_self', + 'crate::dom::bindings::num::Finite', + 'crate::dom::bindings::str::ByteString', + 'crate::dom::bindings::str::DOMString', + 'crate::dom::bindings::str::USVString', + 'crate::dom::bindings::weakref::DOM_WEAK_SLOT', + 'crate::dom::bindings::weakref::WeakBox', + 'crate::dom::bindings::weakref::WeakReferenceable', + 'crate::dom::windowproxy::WindowProxy', + 'crate::dom::globalscope::GlobalScope', + 'crate::mem::malloc_size_of_including_raw_self', 'libc', 'servo_config::prefs::PREFS', 'std::borrow::ToOwned', @@ -7269,7 +7269,7 @@ class GlobalGenRoots(): @staticmethod def InterfaceObjectMap(config): mods = [ - "dom::bindings::codegen", + "crate::dom::bindings::codegen", "js::jsapi::JSContext", "js::rust::HandleObject", "phf", @@ -7351,8 +7351,8 @@ class GlobalGenRoots(): ], "\n") return CGImports(code, descriptors=[], callbacks=[], dictionaries=[], enums=[], typedefs=[], imports=[ - 'dom::bindings::codegen::Bindings', - 'dom::bindings::codegen::PrototypeList::Proxies', + 'crate::dom::bindings::codegen::Bindings', + 'crate::dom::bindings::codegen::PrototypeList::Proxies', 'libc', ], config=config, ignored_warnings=[]) @@ -7362,8 +7362,8 @@ class GlobalGenRoots(): for d in config.getDescriptors(register=True, isCallback=False, isIteratorInterface=False)]) - curr = CGList([CGGeneric("pub use dom::%s::%s;\n" % (name.lower(), - MakeNativeName(name))) + curr = CGList([CGGeneric("pub use crate::dom::%s::%s;\n" % (name.lower(), + MakeNativeName(name))) for name in descriptors]) curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT) return curr @@ -7386,12 +7386,12 @@ class GlobalGenRoots(): def InheritTypes(config): descriptors = config.getDescriptors(register=True, isCallback=False) - imports = [CGGeneric("use dom::types::*;\n"), - CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), - CGGeneric("use dom::bindings::inheritance::Castable;\n"), - CGGeneric("use dom::bindings::root::{Dom, DomRoot, LayoutDom};\n"), - CGGeneric("use dom::bindings::trace::JSTraceable;\n"), - CGGeneric("use dom::bindings::reflector::DomObject;\n"), + imports = [CGGeneric("use crate::dom::types::*;\n"), + CGGeneric("use crate::dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), + CGGeneric("use crate::dom::bindings::inheritance::Castable;\n"), + CGGeneric("use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom};\n"), + CGGeneric("use crate::dom::bindings::trace::JSTraceable;\n"), + CGGeneric("use crate::dom::bindings::reflector::DomObject;\n"), CGGeneric("use js::jsapi::JSTracer;\n\n"), CGGeneric("use std::mem;\n\n")] allprotos = [] -- cgit v1.2.3 From 9f9bf8f6bc1897aa7c637a4a0d4021ec6b6c2819 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Thu, 1 Nov 2018 19:15:13 +0100 Subject: Switch most crates to the 2018 edition --- components/script/dom/bindings/codegen/CodegenRust.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index da0d27ce764..b50efc90207 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5686,7 +5686,11 @@ class CGInterfaceTrait(CGThing): yield name, arguments, rettype def fmt(arguments): - return "".join(", %s: %s" % argument for argument in arguments) + keywords = {"async"} + return "".join( + ", %s: %s" % (name if name not in keywords else "r#" + name, type_) + for name, type_ in arguments + ) def contains_unsafe_arg(arguments): if not arguments or len(arguments) == 0: @@ -6250,7 +6254,7 @@ class CGDictionary(CGThing): d = self.dictionary if d.parent: initParent = ("{\n" - " match try!(%s::%s::new(cx, val)) {\n" + " match r#try!(%s::%s::new(cx, val)) {\n" " ConversionResult::Success(v) => v,\n" " ConversionResult::Failure(error) => {\n" " throw_type_error(cx, &error);\n" @@ -6396,7 +6400,7 @@ class CGDictionary(CGThing): conversion = ( "{\n" " rooted!(in(cx) let mut rval = UndefinedValue());\n" - " match try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n" + " match r#try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n" " true => {\n" "%s\n" " },\n" @@ -7167,7 +7171,7 @@ class CallbackOperationBase(CallbackMethod): "methodName": self.methodName } getCallableFromProp = string.Template( - 'try!(self.parent.get_callable_property(cx, "${methodName}"))' + 'r#try!(self.parent.get_callable_property(cx, "${methodName}"))' ).substitute(replacements) if not self.singleOperation: return 'rooted!(in(cx) let callable =\n' + getCallableFromProp + ');\n' -- cgit v1.2.3 From a1a14459c141afc6ac6771b8a6c9ca374537edf2 Mon Sep 17 00:00:00 2001 From: Jan Andre Ikenmeyer Date: Mon, 19 Nov 2018 14:47:12 +0100 Subject: Update MPL license to https (part 3) --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b50efc90207..e82beb913bc 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1,6 +1,6 @@ # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# file, You can obtain one at https://mozilla.org/MPL/2.0/. # Common codegen classes. -- cgit v1.2.3 From 644101e1e42a98996ff98c4cb8fb3cb6dd18be94 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Sun, 2 Dec 2018 14:23:09 -0500 Subject: Update to new JS runtime creation APIs. --- components/script/dom/bindings/codegen/CodegenRust.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e82beb913bc..e7399d66307 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2592,7 +2592,7 @@ class CGConstructorEnabled(CGAbstractMethod): return CGList((CGGeneric(cond) for cond in conditions), " &&\n") -def CreateBindingJSObject(descriptor, parent=None): +def CreateBindingJSObject(descriptor): assert not descriptor.isGlobal() create = "let raw = Box::into_raw(object);\nlet _rt = RootedTraceable::new(&*raw);\n" if descriptor.proxy: @@ -2601,12 +2601,11 @@ let handler = RegisterBindings::PROXY_HANDLERS[PrototypeList::Proxies::%s as usi rooted!(in(cx) let private = PrivateValue(raw as *const libc::c_void)); let obj = NewProxyObject(cx, handler, Handle::from_raw(UndefinedHandleValue), - proto.get(), %s.get(), - ptr::null_mut(), ptr::null_mut()); + proto.get()); assert!(!obj.is_null()); SetProxyReservedSlot(obj, 0, &private.get()); rooted!(in(cx) let obj = obj);\ -""" % (descriptor.name, parent) +""" % (descriptor.name) else: create += ("rooted!(in(cx) let obj = JS_NewObjectWithGivenProto(\n" " cx, &Class.base as *const JSClass, proto.handle()));\n" @@ -2699,7 +2698,7 @@ class CGWrapMethod(CGAbstractMethod): def definition_body(self): unforgeable = CopyUnforgeablePropertiesToInstance(self.descriptor) - create = CreateBindingJSObject(self.descriptor, "scope") + create = CreateBindingJSObject(self.descriptor) return CGGeneric("""\ let scope = scope.reflector().get_jsobject(); assert!(!scope.get().is_null()); -- cgit v1.2.3 From abd577bfd4583de268aff26e70b480e397504d70 Mon Sep 17 00:00:00 2001 From: Piotr Szpetkowski Date: Wed, 30 Jan 2019 20:54:12 +0100 Subject: Update bool pattern matching into if-else --- components/script/dom/bindings/codegen/CodegenRust.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e7399d66307..1db23e50992 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6399,13 +6399,10 @@ class CGDictionary(CGThing): conversion = ( "{\n" " rooted!(in(cx) let mut rval = UndefinedValue());\n" - " match r#try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n" - " true => {\n" + " if r#try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n" "%s\n" - " },\n" - " false => {\n" + " } else {\n" "%s\n" - " },\n" " }\n" "}") % (member.identifier.name, indent(conversion), indent(default)) -- cgit v1.2.3 From 7b48df53a142507f6f11b9645b605be816db5ab1 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Sat, 2 Mar 2019 11:48:31 +0530 Subject: Update WebIDL.py to 4166cae81546 https://hg.mozilla.org/integration/autoland/rev/4166cae81546f54accae807413f806d20bf30920 Pulls in changes from https://bugzilla.mozilla.org/show_bug.cgi?id=1359269 --- .../script/dom/bindings/codegen/CodegenRust.py | 26 ++++++++-------------- 1 file changed, 9 insertions(+), 17 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 1db23e50992..dea6e104213 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -573,9 +573,6 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, isAutoRooted=False, invalidEnumValueFatal=True, defaultValue=None, - treatNullAs="Default", - isEnforceRange=False, - isClamp=False, exceptionCode=None, allowTreatNonObjectAsNull=False, isCallbackReturnValue=False, @@ -603,12 +600,6 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, If defaultValue is not None, it's the IDL default value for this conversion - If isEnforceRange is true, we're converting an integer and throwing if the - value is out of range. - - If isClamp is true, we're converting an integer and clamping if the - value is out of range. - If allowTreatNonObjectAsNull is true, then [TreatNonObjectAsNull] extended attributes on nullable callback functions will be honored. @@ -631,6 +622,13 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, # We should not have a defaultValue if we know we're an object assert not isDefinitelyObject or defaultValue is None + isEnforceRange = type.enforceRange + isClamp = type.clamp + if type.treatNullAsEmpty: + treatNullAs = "EmptyString" + else: + treatNullAs = "Default" + # If exceptionCode is not set, we'll just rethrow the exception we got. # Note that we can't just set failureCode to exceptionCode, because setting # failureCode will prevent pending exceptions from being set in cases when @@ -1301,9 +1299,6 @@ class CGArgumentConverter(CGThing): descriptorProvider, invalidEnumValueFatal=invalidEnumValueFatal, defaultValue=argument.defaultValue, - treatNullAs=argument.treatNullAs, - isEnforceRange=argument.enforceRange, - isClamp=argument.clamp, isMember="Variadic" if argument.variadic else False, isAutoRooted=type_needs_auto_root(argument.type), allowTreatNonObjectAsNull=argument.allowTreatNonCallableAsNull()) @@ -3508,9 +3503,6 @@ class FakeArgument(): self.variadic = False self.defaultValue = None self._allowTreatNonObjectAsNull = allowTreatNonObjectAsNull - self.treatNullAs = interfaceMember.treatNullAs - self.enforceRange = False - self.clamp = False def allowTreatNonCallableAsNull(self): return self._allowTreatNonObjectAsNull @@ -4874,7 +4866,7 @@ class CGProxySpecialOperation(CGPerSignatureCall): # arguments[0] is the index or name of the item that we're setting. argument = arguments[1] info = getJSToNativeConversionInfo( - argument.type, descriptor, treatNullAs=argument.treatNullAs, + argument.type, descriptor, exceptionCode="return false;") template = info.template declType = info.declType @@ -6886,7 +6878,7 @@ class CGCallbackInterface(CGCallback): class FakeMember(): def __init__(self): - self.treatNullAs = "Default" + pass def isStatic(self): return False -- cgit v1.2.3 From caa05948bf250944b259a5a95a8e6ef1db6a947b Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 12 Feb 2019 18:24:44 -0800 Subject: Add aspect/frameRate/sampleRate parameters --- components/script/dom/bindings/codegen/CodegenRust.py | 1 + 1 file changed, 1 insertion(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index dea6e104213..1bd01651e76 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2379,6 +2379,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::conversions::root_from_handlevalue', 'std::ptr::NonNull', 'crate::dom::bindings::mozmap::MozMap', + 'crate::dom::bindings::num::Finite', 'crate::dom::bindings::root::DomRoot', 'crate::dom::bindings::str::ByteString', 'crate::dom::bindings::str::DOMString', -- cgit v1.2.3 From ce635b715bc61d82e3d5bafb2964c960e7cc5f9c Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 12 Feb 2019 18:38:38 -0800 Subject: Add support for default dict values being boolean, use in MediaStreamConstraints --- components/script/dom/bindings/codegen/CodegenRust.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 1bd01651e76..fe88275bf20 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -747,7 +747,15 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, for memberType in type.unroll().flatMemberTypes if memberType.isDictionary() ] - if dictionaries: + if defaultValue and not isinstance(defaultValue, IDLNullValue): + tag = defaultValue.type.tag() + if tag is IDLType.Tags.bool: + default = "%s::Boolean(%s)" % ( + union_native_type(type), + "true" if defaultValue.value else "false") + else: + raise("We don't currently support default values that aren't null or boolean") + elif dictionaries: if defaultValue: assert isinstance(defaultValue, IDLNullValue) dictionary, = dictionaries -- cgit v1.2.3 From 5fe5e5d6debef5adf234b650ee1b758e683a5230 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 10 Mar 2019 13:20:07 +0100 Subject: Remove most RootedReference uses We can replace all uses of RootedReference for Option by Option::deref calls. --- components/script/dom/bindings/codegen/CodegenRust.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index fe88275bf20..9c5e4864dab 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -7250,8 +7250,10 @@ def camel_to_upper_snake(s): def process_arg(expr, arg): if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback(): - if arg.type.nullable() or arg.type.isSequence() or arg.optional: + if arg.variadic or arg.type.isSequence() or arg.type.nullable() and arg.optional: expr += ".r()" + elif arg.type.nullable() or arg.optional: + expr += ".deref()" else: expr = "&" + expr elif isinstance(arg.type, IDLPromiseType): -- cgit v1.2.3 From 1744a42dad62a4051ab56f109393850c8aafe961 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 10 Mar 2019 18:24:35 +0100 Subject: Don't use RootedReference for Option in codegen anymore --- components/script/dom/bindings/codegen/CodegenRust.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 9c5e4864dab..3f15a316af3 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -7250,9 +7250,11 @@ def camel_to_upper_snake(s): def process_arg(expr, arg): if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback(): - if arg.variadic or arg.type.isSequence() or arg.type.nullable() and arg.optional: + if arg.variadic or arg.type.isSequence(): expr += ".r()" - elif arg.type.nullable() or arg.optional: + elif arg.type.nullable() and arg.optional and not arg.defaultValue: + expr += ".as_ref().map(Option::deref)" + elif arg.type.nullable() or arg.optional and not arg.defaultValue: expr += ".deref()" else: expr = "&" + expr -- cgit v1.2.3 From 4d527b20eef23422d52e8f097a98b9ae00723fc3 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 10 Mar 2019 18:37:14 +0100 Subject: Simplify RootedReference and make it specifically about slicesIt's now called DomSlice. --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3f15a316af3..df156fb0eb7 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5899,7 +5899,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::root::Dom', 'crate::dom::bindings::root::DomRoot', 'crate::dom::bindings::root::OptionalHeapSetter', - 'crate::dom::bindings::root::RootedReference', + 'crate::dom::bindings::root::DomSlice', 'crate::dom::bindings::utils::AsVoidPtr', 'crate::dom::bindings::utils::DOMClass', 'crate::dom::bindings::utils::DOMJSClass', -- cgit v1.2.3 From 8bfd4dc1e2f9c71ff3d1f9964565c43a6ae02278 Mon Sep 17 00:00:00 2001 From: Peter Hall Date: Thu, 14 Feb 2019 12:53:59 +0000 Subject: #8539 Config preferences backend restructure --- components/script/dom/bindings/codegen/CodegenRust.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index df156fb0eb7..ea21989178b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2586,7 +2586,7 @@ class CGConstructorEnabled(CGAbstractMethod): pref = iface.getExtendedAttribute("Pref") if pref: assert isinstance(pref, list) and len(pref) == 1 - conditions.append('PREFS.get("%s").as_boolean().unwrap_or(false)' % pref[0]) + conditions.append('prefs::pref_map().get("%s").as_bool().unwrap_or(false)' % pref[0]) func = iface.getExtendedAttribute("Func") if func: @@ -5977,7 +5977,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::globalscope::GlobalScope', 'crate::mem::malloc_size_of_including_raw_self', 'libc', - 'servo_config::prefs::PREFS', + 'servo_config::pref', + 'servo_config::prefs', 'std::borrow::ToOwned', 'std::cmp', 'std::mem', -- cgit v1.2.3 From 4328713f71d5bc389ecd47e78bfe9b8087b8c104 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Mon, 6 May 2019 11:38:34 -0400 Subject: Update to SpiderMonkey 66. --- .../script/dom/bindings/codegen/CodegenRust.py | 37 +++++++++++----------- 1 file changed, 18 insertions(+), 19 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ea21989178b..27bfdce71b4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -458,7 +458,7 @@ class CGMethodCall(CGThing): pickFirstSignature("%s.get().is_object() && " "{ rooted!(in(cx) let obj = %s.get().to_object()); " "let mut is_date = false; " - "assert!(JS_ObjectIsDate(cx, obj.handle(), &mut is_date)); " + "assert!(ObjectIsDate(cx, obj.handle(), &mut is_date)); " "is_date }" % (distinguishingArg, distinguishingArg), lambda s: (s[1][distinguishingIndex].type.isDate() or @@ -795,7 +795,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, # our own implementation code. templateBody = fill( """ - { // Scope for our JSAutoCompartment. + { // Scope for our JSAutoRealm. rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get()); @@ -2709,7 +2709,7 @@ assert!(!scope.get().is_null()); assert!(((*get_object_class(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0); rooted!(in(cx) let mut proto = ptr::null_mut::()); -let _ac = JSAutoCompartment::new(cx, scope.get()); +let _ac = JSAutoRealm::new(cx, scope.get()); GetProtoObject(cx, scope, proto.handle_mut()); assert!(!proto.is_null()); @@ -2764,7 +2764,7 @@ assert!(!obj.is_null()); (*raw).init_reflector(obj.get()); -let _ac = JSAutoCompartment::new(cx, obj.get()); +let _ac = JSAutoRealm::new(cx, obj.get()); rooted!(in(cx) let mut proto = ptr::null_mut::()); GetProtoObject(cx, obj.handle(), proto.handle_mut()); assert!(JS_SplicePrototype(cx, obj.handle(), proto.handle())); @@ -2883,7 +2883,7 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): name = self.descriptor.interface.identifier.name if self.descriptor.interface.isNamespace(): if self.descriptor.interface.getExtendedAttribute("ProtoObjectHack"): - proto = "JS_GetObjectPrototype(cx, global)" + proto = "GetRealmObjectPrototype(cx)" else: proto = "JS_NewPlainObject(cx)" if self.properties.static_methods.length(): @@ -2919,11 +2919,12 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); parentName = self.descriptor.getParentName() if not parentName: if self.descriptor.interface.getExtendedAttribute("ExceptionClass"): - getPrototypeProto = "prototype_proto.set(JS_GetErrorPrototype(cx))" + protoGetter = "GetRealmErrorPrototype" elif self.descriptor.interface.isIteratorInterface(): - getPrototypeProto = "prototype_proto.set(JS_GetIteratorPrototype(cx))" + protoGetter = "GetRealmIteratorPrototype" else: - getPrototypeProto = "prototype_proto.set(JS_GetObjectPrototype(cx, global))" + protoGetter = "GetRealmObjectPrototype" + getPrototypeProto = "prototype_proto.set(%s(cx))" % protoGetter else: getPrototypeProto = ("%s::GetProtoObject(cx, global, prototype_proto.handle_mut())" % toBindingNamespace(parentName)) @@ -2981,14 +2982,13 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); else: properties["length"] = 0 parentName = self.descriptor.getParentName() + code.append(CGGeneric("rooted!(in(cx) let mut interface_proto = ptr::null_mut::());")) if parentName: parentName = toBindingNamespace(parentName) code.append(CGGeneric(""" -rooted!(in(cx) let mut interface_proto = ptr::null_mut::()); %s::GetConstructorObject(cx, global, interface_proto.handle_mut());""" % parentName)) else: - code.append(CGGeneric(""" -rooted!(in(cx) let interface_proto = JS_GetFunctionPrototype(cx, global));""")) + code.append(CGGeneric("interface_proto.set(GetRealmFunctionPrototype(cx));")) code.append(CGGeneric("""\ assert!(!interface_proto.is_null()); @@ -5544,7 +5544,7 @@ if args.callee() == new_target.get() { rooted!(in(cx) let mut prototype = ptr::null_mut::()); { rooted!(in(cx) let mut proto_val = UndefinedValue()); - let _ac = JSAutoCompartment::new(cx, new_target.get()); + let _ac = JSAutoRealm::new(cx, new_target.get()); if !JS_GetProperty(cx, new_target.handle(), b"prototype\\0".as_ptr() as *const _, proto_val.handle_mut()) { return false; } @@ -5765,7 +5765,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::Heap', 'js::jsapi::INTERNED_STRING_TO_JSID', 'js::jsapi::IsCallable', - 'js::jsapi::JSAutoCompartment', + 'js::jsapi::JSAutoRealm', 'js::jsapi::JSCLASS_FOREGROUND_FINALIZE', 'js::jsapi::JSCLASS_RESERVED_SLOTS_SHIFT', 'js::jsapi::JSClass', @@ -5804,11 +5804,10 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::rust::wrappers::JS_DefineProperty', 'js::rust::wrappers::JS_DefinePropertyById2', 'js::jsapi::JS_ForwardGetPropertyTo', - 'js::jsapi::JS_GetErrorPrototype', - 'js::rust::wrappers::JS_GetFunctionPrototype', - 'js::jsapi::JS_GetGlobalForObject', - 'js::jsapi::JS_GetIteratorPrototype', - 'js::rust::wrappers::JS_GetObjectPrototype', + 'js::jsapi::GetRealmErrorPrototype', + 'js::jsapi::GetRealmFunctionPrototype', + 'js::jsapi::GetRealmIteratorPrototype', + 'js::jsapi::GetRealmObjectPrototype', 'js::rust::wrappers::JS_GetProperty', 'js::jsapi::JS_GetPropertyById', 'js::jsapi::JS_GetPropertyDescriptorById', @@ -5819,7 +5818,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JS_NewObject', 'js::rust::wrappers::JS_NewObjectWithGivenProto', 'js::rust::wrappers::JS_NewObjectWithoutMetadata', - 'js::rust::wrappers::JS_ObjectIsDate', + 'js::rust::wrappers::ObjectIsDate', 'js::rust::wrappers::JS_SetImmutablePrototype', 'js::rust::wrappers::JS_SetProperty', 'js::rust::wrappers::JS_SetPrototype', -- cgit v1.2.3 From 7dbff6efb7ce93ecfb04883cd1dffa24a03ed0ad Mon Sep 17 00:00:00 2001 From: Bastien Orivel Date: Fri, 24 May 2019 22:24:41 +0200 Subject: Add an inCompartments config for bindings --- components/script/dom/bindings/codegen/CodegenRust.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 27bfdce71b4..9032012dea7 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3316,6 +3316,8 @@ class CGCallGenerator(CGThing): if "cx" not in argsPre and needsCx: args.prepend(CGGeneric("cx")) + if nativeMethodName in descriptor.inCompartmentMethods: + args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(cx))")); # Build up our actual call self.cgRoot = CGList([], "\n") @@ -5640,7 +5642,7 @@ class CGInterfaceTrait(CGThing): name = CGSpecializedMethod.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m) for idx, (rettype, arguments) in enumerate(m.signatures()): - arguments = method_arguments(descriptor, rettype, arguments) + arguments = method_arguments(descriptor, rettype, arguments, inCompartment=name in descriptor.inCompartmentMethods) rettype = return_type(descriptor, rettype, infallible) yield name + ('_' * idx), arguments, rettype elif m.isAttr() and not m.isStatic(): @@ -5671,7 +5673,7 @@ class CGInterfaceTrait(CGThing): if operation.isGetter(): if not rettype.nullable(): rettype = IDLNullableType(rettype.location, rettype) - arguments = method_arguments(descriptor, rettype, arguments) + arguments = method_arguments(descriptor, rettype, arguments, inCompartment=name in descriptor.inCompartmentMethods) # If this interface 'supports named properties', then we # should be able to access 'supported property names' @@ -5681,7 +5683,7 @@ class CGInterfaceTrait(CGThing): if operation.isNamed(): yield "SupportedPropertyNames", [], "Vec" else: - arguments = method_arguments(descriptor, rettype, arguments) + arguments = method_arguments(descriptor, rettype, arguments, inCompartment=name in descriptor.inCompartmentMethods) rettype = return_type(descriptor, rettype, infallible) yield name, arguments, rettype @@ -5975,6 +5977,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::windowproxy::WindowProxy', 'crate::dom::globalscope::GlobalScope', 'crate::mem::malloc_size_of_including_raw_self', + 'crate::compartments::InCompartment', + 'crate::compartments::AlreadyInCompartment', 'libc', 'servo_config::pref', 'servo_config::prefs', @@ -6676,7 +6680,7 @@ def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, var return declType.define() -def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None): +def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None, inCompartment=False): if needCx(returnType, arguments, passJSBits): yield "cx", "*mut JSContext" @@ -6688,6 +6692,9 @@ def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, if trailing: yield trailing + if inCompartment: + yield "_comp", "InCompartment" + def return_type(descriptorProvider, rettype, infallible): result = getRetvalDeclarationForType(rettype, descriptorProvider) -- cgit v1.2.3 From 0b29caa5548b0e307f2a891f5082b940c10d5762 Mon Sep 17 00:00:00 2001 From: Bastien Orivel Date: Sat, 25 May 2019 14:43:44 +0200 Subject: Add support for attributes to the inCompartments binding parameter --- components/script/dom/bindings/codegen/CodegenRust.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 9032012dea7..a4a74cff753 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5627,13 +5627,16 @@ class CGInterfaceTrait(CGThing): def __init__(self, descriptor): CGThing.__init__(self) - def attribute_arguments(needCx, argument=None): + def attribute_arguments(needCx, argument=None, inCompartment=False): if needCx: yield "cx", "*mut JSContext" if argument: yield "value", argument_type(descriptor, argument) + if inCompartment: + yield "_comp", "InCompartment" + def members(): for m in descriptor.interface.members: if (m.isMethod() and not m.isStatic() and @@ -5649,7 +5652,7 @@ class CGInterfaceTrait(CGThing): name = CGSpecializedGetter.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m, getter=True) yield (name, - attribute_arguments(typeNeedsCx(m.type, True)), + attribute_arguments(typeNeedsCx(m.type, True), inCompartment=name in descriptor.inCompartmentMethods), return_type(descriptor, m.type, infallible)) if not m.readonly: @@ -5659,7 +5662,7 @@ class CGInterfaceTrait(CGThing): rettype = "()" else: rettype = "ErrorResult" - yield name, attribute_arguments(typeNeedsCx(m.type, False), m.type), rettype + yield name, attribute_arguments(typeNeedsCx(m.type, False), m.type, inCompartment=name in descriptor.inCompartmentMethods), rettype if descriptor.proxy: for name, operation in descriptor.operations.iteritems(): -- cgit v1.2.3 From b7e10a82247545c2f9894e9fb61540caf0b7f157 Mon Sep 17 00:00:00 2001 From: Bastien Orivel Date: Sat, 25 May 2019 23:23:42 +0200 Subject: Make tidy happy --- .../script/dom/bindings/codegen/CodegenRust.py | 28 +++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index a4a74cff753..d365537e464 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3317,7 +3317,7 @@ class CGCallGenerator(CGThing): if "cx" not in argsPre and needsCx: args.prepend(CGGeneric("cx")) if nativeMethodName in descriptor.inCompartmentMethods: - args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(cx))")); + args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(cx))")) # Build up our actual call self.cgRoot = CGList([], "\n") @@ -5634,8 +5634,8 @@ class CGInterfaceTrait(CGThing): if argument: yield "value", argument_type(descriptor, argument) - if inCompartment: - yield "_comp", "InCompartment" + if inCompartment: + yield "_comp", "InCompartment" def members(): for m in descriptor.interface.members: @@ -5645,14 +5645,18 @@ class CGInterfaceTrait(CGThing): name = CGSpecializedMethod.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m) for idx, (rettype, arguments) in enumerate(m.signatures()): - arguments = method_arguments(descriptor, rettype, arguments, inCompartment=name in descriptor.inCompartmentMethods) + arguments = method_arguments(descriptor, rettype, arguments, + inCompartment=name in descriptor.inCompartmentMethods) rettype = return_type(descriptor, rettype, infallible) yield name + ('_' * idx), arguments, rettype elif m.isAttr() and not m.isStatic(): name = CGSpecializedGetter.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m, getter=True) yield (name, - attribute_arguments(typeNeedsCx(m.type, True), inCompartment=name in descriptor.inCompartmentMethods), + attribute_arguments( + typeNeedsCx(m.type, True), + inCompartment=name in descriptor.inCompartmentMethods + ), return_type(descriptor, m.type, infallible)) if not m.readonly: @@ -5662,7 +5666,13 @@ class CGInterfaceTrait(CGThing): rettype = "()" else: rettype = "ErrorResult" - yield name, attribute_arguments(typeNeedsCx(m.type, False), m.type, inCompartment=name in descriptor.inCompartmentMethods), rettype + yield (name, + attribute_arguments( + typeNeedsCx(m.type, False), + m.type, + inCompartment=name in descriptor.inCompartmentMethods + ), + rettype) if descriptor.proxy: for name, operation in descriptor.operations.iteritems(): @@ -5676,7 +5686,8 @@ class CGInterfaceTrait(CGThing): if operation.isGetter(): if not rettype.nullable(): rettype = IDLNullableType(rettype.location, rettype) - arguments = method_arguments(descriptor, rettype, arguments, inCompartment=name in descriptor.inCompartmentMethods) + arguments = method_arguments(descriptor, rettype, arguments, + inCompartment=name in descriptor.inCompartmentMethods) # If this interface 'supports named properties', then we # should be able to access 'supported property names' @@ -5686,7 +5697,8 @@ class CGInterfaceTrait(CGThing): if operation.isNamed(): yield "SupportedPropertyNames", [], "Vec" else: - arguments = method_arguments(descriptor, rettype, arguments, inCompartment=name in descriptor.inCompartmentMethods) + arguments = method_arguments(descriptor, rettype, arguments, + inCompartment=name in descriptor.inCompartmentMethods) rettype = return_type(descriptor, rettype, infallible) yield name, arguments, rettype -- cgit v1.2.3 From 63714c90fb5bbad86f28fc188120b2ecfd3337ab Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Sun, 2 Jun 2019 23:38:12 -0400 Subject: Upgrade to Spidermonkey 67. --- .../script/dom/bindings/codegen/CodegenRust.py | 23 +++++++++------------- 1 file changed, 9 insertions(+), 14 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index d365537e464..dcbdea765d4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -466,7 +466,7 @@ class CGMethodCall(CGThing): # Check for vanilla JS objects # XXXbz Do we need to worry about security wrappers? - pickFirstSignature("%s.get().is_object() && !is_platform_object(%s.get().to_object())" % + pickFirstSignature("%s.get().is_object() && !is_platform_object(%s.get().to_object(), cx)" % (distinguishingArg, distinguishingArg), lambda s: (s[1][distinguishingIndex].type.isCallback() or s[1][distinguishingIndex].type.isCallbackInterface() or @@ -798,7 +798,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, { // Scope for our JSAutoRealm. rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); - let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get()); + let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get(), cx); rooted!(in(cx) let mut valueToResolve = $${val}.get()); if !JS_WrapValue(cx, valueToResolve.handle_mut()) { @@ -866,7 +866,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, templateBody = fill( """ - match ${function}($${val}) { + match ${function}($${val}, cx) { Ok(val) => val, Err(()) => { $*{failureCode} @@ -2158,8 +2158,8 @@ class CGDOMJSClass(CGThing): static CLASS_OPS: js::jsapi::JSClassOps = js::jsapi::JSClassOps { addProperty: None, delProperty: None, - enumerate: %(enumerateHook)s, - newEnumerate: None, + enumerate: None, + newEnumerate: %(enumerateHook)s, resolve: %(resolveHook)s, mayResolve: None, finalize: Some(%(finalizeHook)s), @@ -3223,7 +3223,6 @@ let traps = ProxyTraps { set: None, call: None, construct: None, - getPropertyDescriptor: Some(get_property_descriptor), hasOwn: Some(hasOwn), getOwnEnumerablePropertyKeys: Some(%(getOwnEnumerablePropertyKeys)s), nativeCall: None, @@ -4980,10 +4979,6 @@ class CGProxyUnwrap(CGAbstractMethod): def definition_body(self): return CGGeneric("""\ -/*if (xpc::WrapperFactory::IsXrayWrapper(obj)) { - obj = js::UnwrapObject(obj); -}*/ -//MOZ_ASSERT(IsProxy(obj)); let mut slot = UndefinedValue(); GetProxyReservedSlot(obj.get(), 0, &mut slot); let box_ = slot.to_private() as *const %s; @@ -5430,7 +5425,7 @@ class CGAbstractClassHook(CGAbstractExternMethod): def definition_body_prologue(self): return CGGeneric(""" -let this = native_from_object::<%s>(obj).unwrap(); +let this = native_from_object_static::<%s>(obj).unwrap(); """ % self.descriptor.concreteType) def definition_body(self): @@ -5530,7 +5525,7 @@ let global = DomRoot::downcast::(global).unwrap(); // The new_target might be a cross-compartment wrapper. Get the underlying object // so we can do the spec's object-identity checks. -rooted!(in(cx) let new_target = UnwrapObject(args.new_target().to_object(), 1)); +rooted!(in(cx) let new_target = UnwrapObjectDynamic(args.new_target().to_object(), cx, 1)); if new_target.is_null() { throw_dom_exception(cx, global.upcast::(), Error::Type("new.target is null".to_owned())); return false; @@ -5877,7 +5872,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::glue::RUST_JSID_IS_STRING', 'js::glue::RUST_SYMBOL_TO_JSID', 'js::glue::int_to_jsid', - 'js::glue::UnwrapObject', + 'js::glue::UnwrapObjectDynamic', 'js::panic::maybe_resume_unwind', 'js::panic::wrap_panic', 'js::rust::GCMethods', @@ -5959,6 +5954,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::conversions::is_array_like', 'crate::dom::bindings::conversions::native_from_handlevalue', 'crate::dom::bindings::conversions::native_from_object', + 'crate::dom::bindings::conversions::native_from_object_static', 'crate::dom::bindings::conversions::private_from_object', 'crate::dom::bindings::conversions::root_from_handleobject', 'crate::dom::bindings::conversions::root_from_handlevalue', @@ -5979,7 +5975,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::proxyhandler::ensure_expando_object', 'crate::dom::bindings::proxyhandler::fill_property_descriptor', 'crate::dom::bindings::proxyhandler::get_expando_object', - 'crate::dom::bindings::proxyhandler::get_property_descriptor', 'crate::dom::bindings::mozmap::MozMap', 'std::ptr::NonNull', 'crate::dom::bindings::num::Finite', -- cgit v1.2.3 From 40dbb2c1008f9629e6794d980fdc9374a8bbbb59 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 5 Jul 2019 11:03:34 +0900 Subject: Implement DOMPoint.fromPoint --- components/script/dom/bindings/codegen/CodegenRust.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index dcbdea765d4..114b403d077 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6414,7 +6414,8 @@ class CGDictionary(CGThing): conversion = ( "{\n" " rooted!(in(cx) let mut rval = UndefinedValue());\n" - " if r#try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n" + " if r#try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut()))" + " && !rval.is_undefined() {\n" "%s\n" " } else {\n" "%s\n" -- cgit v1.2.3 From 01151274f1487e630852680ba38ab5a651db44ec Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Sat, 6 Jul 2019 16:20:50 +0900 Subject: Require default dictionary value for optional dicts --- components/script/dom/bindings/codegen/CodegenRust.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 114b403d077..98df7a8b51f 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -17,6 +17,7 @@ import functools from WebIDL import ( BuiltinTypes, IDLBuiltinType, + IDLDefaultDictionaryValue, IDLEmptySequenceValue, IDLInterfaceMember, IDLNullableType, @@ -678,13 +679,16 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, return None if isinstance(defaultValue, IDLNullValue): - assert type.nullable() or type.isDictionary() + assert type.nullable() + return nullValue + elif isinstance(defaultValue, IDLDefaultDictionaryValue): + assert type.isDictionary() return nullValue elif isinstance(defaultValue, IDLEmptySequenceValue): assert type.isSequence() return "Vec::new()" - raise TypeError("Can't handle non-null or non-empty sequence default value here") + raise TypeError("Can't handle non-null, non-empty sequence or non-empty dictionary default value here") # A helper function for wrapping up the template body for # possibly-nullable objecty stuff @@ -747,17 +751,19 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, for memberType in type.unroll().flatMemberTypes if memberType.isDictionary() ] - if defaultValue and not isinstance(defaultValue, IDLNullValue): + if (defaultValue and + not isinstance(defaultValue, IDLNullValue) and + not isinstance(defaultValue, IDLDefaultDictionaryValue)): tag = defaultValue.type.tag() if tag is IDLType.Tags.bool: default = "%s::Boolean(%s)" % ( union_native_type(type), "true" if defaultValue.value else "false") else: - raise("We don't currently support default values that aren't null or boolean") + raise("We don't currently support default values that aren't null, boolean or default dictionary") elif dictionaries: if defaultValue: - assert isinstance(defaultValue, IDLNullValue) + assert isinstance(defaultValue, IDLDefaultDictionaryValue) dictionary, = dictionaries default = "%s::%s(%s::%s::empty())" % ( union_native_type(type), -- cgit v1.2.3 From 871239a3e302d4aefdbbad1b0141511dcd66afc4 Mon Sep 17 00:00:00 2001 From: sreeise Date: Tue, 28 May 2019 03:23:47 -0400 Subject: Change bindings generation to make Exposed annotation aware of members/partial interfaces --- .../script/dom/bindings/codegen/CodegenRust.py | 28 +++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 98df7a8b51f..e0c7725fa52 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1513,7 +1513,7 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): returnType) -def MemberCondition(pref, func): +def MemberCondition(pref, func, exposed): """ A string representing the condition for a member to actually be exposed. Any of the arguments can be None. If not None, they should have the @@ -1521,14 +1521,18 @@ def MemberCondition(pref, func): pref: The name of the preference. func: The name of the function. + exposed: One or more names of an exposed global. """ assert pref is None or isinstance(pref, str) assert func is None or isinstance(func, str) - assert func is None or pref is None + assert exposed is None or isinstance(exposed, set) + assert func is None or pref is None or exposed is None if pref: return 'Condition::Pref("%s")' % pref if func: return 'Condition::Func(%s)' % func + if exposed: + return ["Condition::Exposed(InterfaceObjectMap::Globals::%s)" % camel_to_upper_snake(i) for i in exposed] return "Condition::Satisfied" @@ -1571,7 +1575,8 @@ class PropertyDefiner: PropertyDefiner.getStringAttr(interfaceMember, "Pref"), PropertyDefiner.getStringAttr(interfaceMember, - "Func")) + "Func"), + interfaceMember.exposedSet()) def generateGuardedArray(self, array, name, specTemplate, specTerminator, specType, getCondition, getDataTuple): @@ -1609,8 +1614,13 @@ class PropertyDefiner: if specTerminator: currentSpecs.append(specTerminator) specs.append("&[\n" + ",\n".join(currentSpecs) + "]\n") - prefableSpecs.append( - prefableTemplate % (cond, name + "_specs", len(specs) - 1)) + if isinstance(cond, list): + for i in cond: + prefableSpecs.append( + prefableTemplate % (i, name + "_specs", len(specs) - 1)) + else: + prefableSpecs.append( + prefableTemplate % (cond, name + "_specs", len(specs) - 1)) specsArray = ("const %s_specs: &'static [&'static[%s]] = &[\n" + ",\n".join(specs) + "\n" + @@ -2640,8 +2650,8 @@ def InitUnforgeablePropertiesOnHolder(descriptor, properties): """ unforgeables = [] - defineUnforgeableAttrs = "define_guarded_properties(cx, unforgeable_holder.handle(), %s);" - defineUnforgeableMethods = "define_guarded_methods(cx, unforgeable_holder.handle(), %s);" + defineUnforgeableAttrs = "define_guarded_properties(cx, unforgeable_holder.handle(), %s, global);" + defineUnforgeableMethods = "define_guarded_methods(cx, unforgeable_holder.handle(), %s, global);" unforgeableMembers = [ (defineUnforgeableAttrs, properties.unforgeable_attrs), @@ -2751,7 +2761,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): ("define_guarded_methods", self.properties.methods), ("define_guarded_constants", self.properties.consts) ] - members = ["%s(cx, obj.handle(), %s);" % (function, array.variableName()) + members = ["%s(cx, obj.handle(), %s, obj.handle());" % (function, array.variableName()) for (function, array) in pairs if array.length() > 0] values["members"] = "\n".join(members) @@ -2966,6 +2976,7 @@ assert!(!prototype_proto.is_null());""" % getPrototypeProto)] code.append(CGGeneric(""" rooted!(in(cx) let mut prototype = ptr::null_mut::()); create_interface_prototype_object(cx, + global.into(), prototype_proto.handle().into(), &PrototypeClass, %(methods)s, @@ -7543,6 +7554,7 @@ impl %(base)s { for m in descriptor.interface.members: if PropertyDefiner.getStringAttr(m, 'Pref') or \ PropertyDefiner.getStringAttr(m, 'Func') or \ + PropertyDefiner.getStringAttr(m, 'Exposed') or \ (m.isMethod() and m.isIdentifierLess()): continue display = m.identifier.name + ('()' if m.isMethod() else '') -- cgit v1.2.3 From cd0eb88a3e4077590ff9419399d8226c1694de5b Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 20 Jul 2019 15:34:26 +0100 Subject: ConstructorEnabled now takes a SafeJSContext instead of a JSContext a first argument. The function cannot be made safe because of call to unsafe function is_exposed_in. --- components/script/dom/bindings/codegen/CodegenRust.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e0c7725fa52..6f70e5e64f1 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2586,7 +2586,7 @@ class CGConstructorEnabled(CGAbstractMethod): def __init__(self, descriptor): CGAbstractMethod.__init__(self, descriptor, 'ConstructorEnabled', 'bool', - [Argument("*mut JSContext", "aCx"), + [Argument("SafeJSContext", "aCx"), Argument("HandleObject", "aObj")], unsafe=True) @@ -3285,7 +3285,7 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod): return CGGeneric("""\ assert!(!global.get().is_null()); -if !ConstructorEnabled(cx, global) { +if !ConstructorEnabled(SafeJSContext::from_ptr(cx), global) { return; } @@ -6006,6 +6006,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::mem::malloc_size_of_including_raw_self', 'crate::compartments::InCompartment', 'crate::compartments::AlreadyInCompartment', + 'crate::script_runtime::JSContext as SafeJSContext', 'libc', 'servo_config::pref', 'servo_config::prefs', -- cgit v1.2.3 From 35dc5320ab1a9e71db8212304f44969efa3c342b Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 20 Jul 2019 17:30:10 +0100 Subject: Wrap(Global)Method now takes a SafeJSContext instead of a JSContext as first argument. --- .../script/dom/bindings/codegen/CodegenRust.py | 45 +++++++++++----------- 1 file changed, 23 insertions(+), 22 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 6f70e5e64f1..3f3dafdf357 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2618,17 +2618,17 @@ def CreateBindingJSObject(descriptor): if descriptor.proxy: create += """ let handler = RegisterBindings::PROXY_HANDLERS[PrototypeList::Proxies::%s as usize]; -rooted!(in(cx) let private = PrivateValue(raw as *const libc::c_void)); -let obj = NewProxyObject(cx, handler, +rooted!(in(*cx) let private = PrivateValue(raw as *const libc::c_void)); +let obj = NewProxyObject(*cx, handler, Handle::from_raw(UndefinedHandleValue), proto.get()); assert!(!obj.is_null()); SetProxyReservedSlot(obj, 0, &private.get()); -rooted!(in(cx) let obj = obj);\ +rooted!(in(*cx) let obj = obj);\ """ % (descriptor.name) else: - create += ("rooted!(in(cx) let obj = JS_NewObjectWithGivenProto(\n" - " cx, &Class.base as *const JSClass, proto.handle()));\n" + create += ("rooted!(in(*cx) let obj = JS_NewObjectWithGivenProto(\n" + " *cx, &Class.base as *const JSClass, proto.handle()));\n" "assert!(!obj.is_null());\n" "\n" "let val = PrivateValue(raw as *const libc::c_void);\n" @@ -2676,8 +2676,8 @@ def CopyUnforgeablePropertiesToInstance(descriptor): # reflector, so we can make sure we don't get confused by named getters. if descriptor.proxy: copyCode += """\ -rooted!(in(cx) let mut expando = ptr::null_mut::()); -ensure_expando_object(cx, obj.handle().into(), expando.handle_mut()); +rooted!(in(*cx) let mut expando = ptr::null_mut::()); +ensure_expando_object(*cx, obj.handle().into(), expando.handle_mut()); """ obj = "expando" else: @@ -2693,9 +2693,9 @@ ensure_expando_object(cx, obj.handle().into(), expando.handle_mut()); copyCode += """\ let mut slot = UndefinedValue(); JS_GetReservedSlot(proto.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT, &mut slot); -rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut::()); +rooted!(in(*cx) let mut unforgeable_holder = ptr::null_mut::()); unforgeable_holder.handle_mut().set(slot.to_object()); -assert!(%(copyFunc)s(cx, %(obj)s.handle(), unforgeable_holder.handle())); +assert!(%(copyFunc)s(*cx, %(obj)s.handle(), unforgeable_holder.handle())); """ % {'copyFunc': copyFunc, 'obj': obj} return copyCode @@ -2709,7 +2709,7 @@ class CGWrapMethod(CGAbstractMethod): def __init__(self, descriptor): assert not descriptor.interface.isCallback() assert not descriptor.isGlobal() - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('SafeJSContext', 'cx'), Argument('&GlobalScope', 'scope'), Argument("Box<%s>" % descriptor.concreteType, 'object')] retval = 'DomRoot<%s>' % descriptor.concreteType @@ -2724,9 +2724,9 @@ let scope = scope.reflector().get_jsobject(); assert!(!scope.get().is_null()); assert!(((*get_object_class(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0); -rooted!(in(cx) let mut proto = ptr::null_mut::()); -let _ac = JSAutoRealm::new(cx, scope.get()); -GetProtoObject(cx, scope, proto.handle_mut()); +rooted!(in(*cx) let mut proto = ptr::null_mut::()); +let _ac = JSAutoRealm::new(*cx, scope.get()); +GetProtoObject(*cx, scope, proto.handle_mut()); assert!(!proto.is_null()); %(createObject)s @@ -2744,7 +2744,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): def __init__(self, descriptor, properties): assert not descriptor.interface.isCallback() assert descriptor.isGlobal() - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('SafeJSContext', 'cx'), Argument("Box<%s>" % descriptor.concreteType, 'object')] retval = 'DomRoot<%s>' % descriptor.concreteType CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, @@ -2761,7 +2761,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): ("define_guarded_methods", self.properties.methods), ("define_guarded_constants", self.properties.consts) ] - members = ["%s(cx, obj.handle(), %s, obj.handle());" % (function, array.variableName()) + members = ["%s(*cx, obj.handle(), %s, obj.handle());" % (function, array.variableName()) for (function, array) in pairs if array.length() > 0] values["members"] = "\n".join(members) @@ -2769,9 +2769,9 @@ class CGWrapGlobalMethod(CGAbstractMethod): let raw = Box::into_raw(object); let _rt = RootedTraceable::new(&*raw); -rooted!(in(cx) let mut obj = ptr::null_mut::()); +rooted!(in(*cx) let mut obj = ptr::null_mut::()); create_global_object( - cx, + *cx, &Class.base, raw as *const libc::c_void, _trace, @@ -2780,12 +2780,12 @@ assert!(!obj.is_null()); (*raw).init_reflector(obj.get()); -let _ac = JSAutoRealm::new(cx, obj.get()); -rooted!(in(cx) let mut proto = ptr::null_mut::()); -GetProtoObject(cx, obj.handle(), proto.handle_mut()); -assert!(JS_SplicePrototype(cx, obj.handle(), proto.handle())); +let _ac = JSAutoRealm::new(*cx, obj.get()); +rooted!(in(*cx) let mut proto = ptr::null_mut::()); +GetProtoObject(*cx, obj.handle(), proto.handle_mut()); +assert!(JS_SplicePrototype(*cx, obj.handle(), proto.handle())); let mut immutable = false; -assert!(JS_SetImmutablePrototype(cx, obj.handle(), &mut immutable)); +assert!(JS_SetImmutablePrototype(*cx, obj.handle(), &mut immutable)); assert!(immutable); %(members)s @@ -6022,6 +6022,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'std::rc::Rc', 'std::default::Default', 'std::ffi::CString', + 'std::ops::Deref', ], config) -- cgit v1.2.3 From 0a5a9bc7bca487cb2712b6b77a1936be276cd1e1 Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 20 Jul 2019 18:21:49 +0100 Subject: CreateInterfaceObjects now takes a SafeJSContext instead of a JSContext as first argument. --- .../script/dom/bindings/codegen/CodegenRust.py | 58 +++++++++++----------- 1 file changed, 29 insertions(+), 29 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3f3dafdf357..12f6b61a533 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2650,8 +2650,8 @@ def InitUnforgeablePropertiesOnHolder(descriptor, properties): """ unforgeables = [] - defineUnforgeableAttrs = "define_guarded_properties(cx, unforgeable_holder.handle(), %s, global);" - defineUnforgeableMethods = "define_guarded_methods(cx, unforgeable_holder.handle(), %s, global);" + defineUnforgeableAttrs = "define_guarded_properties(*cx, unforgeable_holder.handle(), %s, global);" + defineUnforgeableMethods = "define_guarded_methods(*cx, unforgeable_holder.handle(), %s, global);" unforgeableMembers = [ (defineUnforgeableAttrs, properties.unforgeable_attrs), @@ -2888,7 +2888,7 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): properties should be a PropertyArrays instance. """ def __init__(self, descriptor, properties, haveUnscopables): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'global'), + args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', 'global'), Argument('*mut ProtoOrIfaceArray', 'cache')] CGAbstractMethod.__init__(self, descriptor, 'CreateInterfaceObjects', 'void', args, unsafe=True) @@ -2899,18 +2899,18 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): name = self.descriptor.interface.identifier.name if self.descriptor.interface.isNamespace(): if self.descriptor.interface.getExtendedAttribute("ProtoObjectHack"): - proto = "GetRealmObjectPrototype(cx)" + proto = "GetRealmObjectPrototype(*cx)" else: - proto = "JS_NewPlainObject(cx)" + proto = "JS_NewPlainObject(*cx)" if self.properties.static_methods.length(): methods = self.properties.static_methods.variableName() else: methods = "&[]" return CGGeneric("""\ -rooted!(in(cx) let proto = %(proto)s); +rooted!(in(*cx) let proto = %(proto)s); assert!(!proto.is_null()); -rooted!(in(cx) let mut namespace = ptr::null_mut::()); -create_namespace_object(cx, global, proto.handle(), &NAMESPACE_OBJECT_CLASS, +rooted!(in(*cx) let mut namespace = ptr::null_mut::()); +create_namespace_object(*cx, global, proto.handle(), &NAMESPACE_OBJECT_CLASS, %(methods)s, %(name)s, namespace.handle_mut()); assert!(!namespace.is_null()); assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); @@ -2922,8 +2922,8 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); if self.descriptor.interface.isCallback(): assert not self.descriptor.interface.ctor() and self.descriptor.interface.hasConstants() return CGGeneric("""\ -rooted!(in(cx) let mut interface = ptr::null_mut::()); -create_callback_interface_object(cx, global, sConstants, %(name)s, interface.handle_mut()); +rooted!(in(*cx) let mut interface = ptr::null_mut::()); +create_callback_interface_object(*cx, global, sConstants, %(name)s, interface.handle_mut()); assert!(!interface.is_null()); assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); (*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.get(); @@ -2940,13 +2940,13 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); protoGetter = "GetRealmIteratorPrototype" else: protoGetter = "GetRealmObjectPrototype" - getPrototypeProto = "prototype_proto.set(%s(cx))" % protoGetter + getPrototypeProto = "prototype_proto.set(%s(*cx))" % protoGetter else: - getPrototypeProto = ("%s::GetProtoObject(cx, global, prototype_proto.handle_mut())" % + getPrototypeProto = ("%s::GetProtoObject(*cx, global, prototype_proto.handle_mut())" % toBindingNamespace(parentName)) code = [CGGeneric("""\ -rooted!(in(cx) let mut prototype_proto = ptr::null_mut::()); +rooted!(in(*cx) let mut prototype_proto = ptr::null_mut::()); %s; assert!(!prototype_proto.is_null());""" % getPrototypeProto)] @@ -2974,8 +2974,8 @@ assert!(!prototype_proto.is_null());""" % getPrototypeProto)] proto_properties = properties code.append(CGGeneric(""" -rooted!(in(cx) let mut prototype = ptr::null_mut::()); -create_interface_prototype_object(cx, +rooted!(in(*cx) let mut prototype = ptr::null_mut::()); +create_interface_prototype_object(*cx, global.into(), prototype_proto.handle().into(), &PrototypeClass, @@ -2999,18 +2999,18 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); else: properties["length"] = 0 parentName = self.descriptor.getParentName() - code.append(CGGeneric("rooted!(in(cx) let mut interface_proto = ptr::null_mut::());")) + code.append(CGGeneric("rooted!(in(*cx) let mut interface_proto = ptr::null_mut::());")) if parentName: parentName = toBindingNamespace(parentName) code.append(CGGeneric(""" -%s::GetConstructorObject(cx, global, interface_proto.handle_mut());""" % parentName)) +%s::GetConstructorObject(*cx, global, interface_proto.handle_mut());""" % parentName)) else: - code.append(CGGeneric("interface_proto.set(GetRealmFunctionPrototype(cx));")) + code.append(CGGeneric("interface_proto.set(GetRealmFunctionPrototype(*cx));")) code.append(CGGeneric("""\ assert!(!interface_proto.is_null()); -rooted!(in(cx) let mut interface = ptr::null_mut::()); -create_noncallback_interface_object(cx, +rooted!(in(*cx) let mut interface = ptr::null_mut::()); +create_noncallback_interface_object(*cx, global.into(), interface_proto.handle(), &INTERFACE_OBJECT_CLASS, @@ -3035,8 +3035,8 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); if aliasedMembers: def defineAlias(alias): if alias == "@@iterator": - symbolJSID = "RUST_SYMBOL_TO_JSID(GetWellKnownSymbol(cx, SymbolCode::iterator))" - getSymbolJSID = CGGeneric(fill("rooted!(in(cx) let iteratorId = ${symbolJSID});", + symbolJSID = "RUST_SYMBOL_TO_JSID(GetWellKnownSymbol(*cx, SymbolCode::iterator))" + getSymbolJSID = CGGeneric(fill("rooted!(in(*cx) let iteratorId = ${symbolJSID});", symbolJSID=symbolJSID)) defineFn = "JS_DefinePropertyById2" prop = "iteratorId.handle()" @@ -3053,7 +3053,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); # match the enumerability of the property being aliased. CGGeneric(fill( """ - assert!(${defineFn}(cx, prototype.handle(), ${prop}, aliasedVal.handle(), + assert!(${defineFn}(*cx, prototype.handle(), ${prop}, aliasedVal.handle(), JSPROP_ENUMERATE as u32)); """, defineFn=defineFn, @@ -3064,7 +3064,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); return CGList([ CGGeneric(fill( """ - assert!(JS_GetProperty(cx, prototype.handle(), + assert!(JS_GetProperty(*cx, prototype.handle(), ${prop} as *const u8 as *const _, aliasedVal.handle_mut())); """, @@ -3076,7 +3076,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); // Set up aliases on the interface prototype object we just created. """)), - CGGeneric("rooted!(in(cx) let mut aliasedVal = UndefinedValue());\n\n") + CGGeneric("rooted!(in(*cx) let mut aliasedVal = UndefinedValue());\n\n") ] + [defineAliasesFor(m) for m in sorted(aliasedMembers)]) code.append(defineAliases) @@ -3091,7 +3091,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); specs.append(CGGeneric("(%s as ConstructorClassHook, %s, %d)" % (hook, name, length))) values = CGIndenter(CGList(specs, "\n"), 4) code.append(CGWrapper(values, pre="%s = [\n" % decl, post="\n];")) - code.append(CGGeneric("create_named_constructors(cx, global, &named_constructors, prototype.handle());")) + code.append(CGGeneric("create_named_constructors(*cx, global, &named_constructors, prototype.handle());")) if self.descriptor.hasUnforgeableMembers: # We want to use the same JSClass and prototype as the object we'll @@ -3112,9 +3112,9 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); holderClass = "&Class.base as *const JSClass" holderProto = "prototype.handle()" code.append(CGGeneric(""" -rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut::()); +rooted!(in(*cx) let mut unforgeable_holder = ptr::null_mut::()); unforgeable_holder.handle_mut().set( - JS_NewObjectWithoutMetadata(cx, %(holderClass)s, %(holderProto)s)); + JS_NewObjectWithoutMetadata(*cx, %(holderClass)s, %(holderProto)s)); assert!(!unforgeable_holder.is_null()); """ % {'holderClass': holderClass, 'holderProto': holderProto})) code.append(InitUnforgeablePropertiesOnHolder(self.descriptor, self.properties)) @@ -3149,7 +3149,7 @@ if !rval.get().is_null() { return; } -CreateInterfaceObjects(cx, global, proto_or_iface_array); +CreateInterfaceObjects(SafeJSContext::from_ptr(cx), global, proto_or_iface_array); rval.set((*proto_or_iface_array)[%(id)s as usize]); assert!(!rval.get().is_null()); """ % {"id": self.id}) -- cgit v1.2.3 From aa0e4f5c76ceed459e3d53df47802ba9b388d913 Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sun, 21 Jul 2019 01:01:22 +0100 Subject: GetPerInterfaceObject methods now takes a SafeJSContext instead of a JSContext as first argument. --- components/script/dom/bindings/codegen/CodegenRust.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 12f6b61a533..e656a7ab3ce 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2726,7 +2726,7 @@ assert!(((*get_object_class(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0); rooted!(in(*cx) let mut proto = ptr::null_mut::()); let _ac = JSAutoRealm::new(*cx, scope.get()); -GetProtoObject(*cx, scope, proto.handle_mut()); +GetProtoObject(cx, scope, proto.handle_mut()); assert!(!proto.is_null()); %(createObject)s @@ -2782,7 +2782,7 @@ assert!(!obj.is_null()); let _ac = JSAutoRealm::new(*cx, obj.get()); rooted!(in(*cx) let mut proto = ptr::null_mut::()); -GetProtoObject(*cx, obj.handle(), proto.handle_mut()); +GetProtoObject(cx, obj.handle(), proto.handle_mut()); assert!(JS_SplicePrototype(*cx, obj.handle(), proto.handle())); let mut immutable = false; assert!(JS_SetImmutablePrototype(*cx, obj.handle(), &mut immutable)); @@ -2942,7 +2942,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); protoGetter = "GetRealmObjectPrototype" getPrototypeProto = "prototype_proto.set(%s(*cx))" % protoGetter else: - getPrototypeProto = ("%s::GetProtoObject(*cx, global, prototype_proto.handle_mut())" % + getPrototypeProto = ("%s::GetProtoObject(cx, global, prototype_proto.handle_mut())" % toBindingNamespace(parentName)) code = [CGGeneric("""\ @@ -3003,7 +3003,7 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); if parentName: parentName = toBindingNamespace(parentName) code.append(CGGeneric(""" -%s::GetConstructorObject(*cx, global, interface_proto.handle_mut());""" % parentName)) +%s::GetConstructorObject(cx, global, interface_proto.handle_mut());""" % parentName)) else: code.append(CGGeneric("interface_proto.set(GetRealmFunctionPrototype(*cx));")) code.append(CGGeneric("""\ @@ -3131,7 +3131,7 @@ class CGGetPerInterfaceObject(CGAbstractMethod): constructor object). """ def __init__(self, descriptor, name, idPrefix="", pub=False): - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', 'global'), Argument('MutableHandleObject', 'mut rval')] CGAbstractMethod.__init__(self, descriptor, name, @@ -3149,7 +3149,7 @@ if !rval.get().is_null() { return; } -CreateInterfaceObjects(SafeJSContext::from_ptr(cx), global, proto_or_iface_array); +CreateInterfaceObjects(cx, global, proto_or_iface_array); rval.set((*proto_or_iface_array)[%(id)s as usize]); assert!(!rval.get().is_null()); """ % {"id": self.id}) @@ -3290,7 +3290,7 @@ if !ConstructorEnabled(SafeJSContext::from_ptr(cx), global) { } rooted!(in(cx) let mut proto = ptr::null_mut::()); -%s(cx, global, proto.handle_mut()); +%s(SafeJSContext::from_ptr(cx), global, proto.handle_mut()); assert!(!proto.is_null());""" % (function,)) @@ -5574,7 +5574,7 @@ rooted!(in(cx) let mut prototype = ptr::null_mut::()); // https://bugzilla.mozilla.org/show_bug.cgi?id=1317658 rooted!(in(cx) let global_object = CurrentGlobalOrNull(cx)); - GetProtoObject(cx, global_object.handle(), prototype.handle_mut()); + GetProtoObject(SafeJSContext::from_ptr(cx), global_object.handle(), prototype.handle_mut()); } else { // Step 6 prototype.set(proto_val.to_object()); -- cgit v1.2.3 From 6e4caf11537cb8db83405afe461b74470f3a7e5a Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sun, 21 Jul 2019 01:25:29 +0100 Subject: DefineDOMInterfaceMethod now takes a SafeJSContext instead of a JSContext as first argument. --- components/script/dom/bindings/codegen/CodegenRust.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e656a7ab3ce..d4c606183ca 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3268,7 +3268,7 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod): def __init__(self, descriptor): assert descriptor.interface.hasInterfaceObject() args = [ - Argument('*mut JSContext', 'cx'), + Argument('SafeJSContext', 'cx'), Argument('HandleObject', 'global'), ] CGAbstractMethod.__init__(self, descriptor, 'DefineDOMInterface', @@ -3285,12 +3285,12 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod): return CGGeneric("""\ assert!(!global.get().is_null()); -if !ConstructorEnabled(SafeJSContext::from_ptr(cx), global) { +if !ConstructorEnabled(cx, global) { return; } -rooted!(in(cx) let mut proto = ptr::null_mut::()); -%s(SafeJSContext::from_ptr(cx), global, proto.handle_mut()); +rooted!(in(*cx) let mut proto = ptr::null_mut::()); +%s(cx, global, proto.handle_mut()); assert!(!proto.is_null());""" % (function,)) @@ -7312,7 +7312,7 @@ class GlobalGenRoots(): def InterfaceObjectMap(config): mods = [ "crate::dom::bindings::codegen", - "js::jsapi::JSContext", + "crate::script_runtime::JSContext", "js::rust::HandleObject", "phf", ] -- cgit v1.2.3 From 2fb3f1f98327ee1de698dfed83124350f58ff52a Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sun, 21 Jul 2019 16:05:04 +0100 Subject: Callbacks now uses safe JSContext instead of raw JSContext --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index d4c606183ca..71b7a279b7a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -836,7 +836,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if descriptor.interface.isCallback(): name = descriptor.nativeType declType = CGWrapper(CGGeneric(name), pre="Rc<", post=">") - template = "%s::new(cx, ${val}.get().to_object())" % name + template = "%s::new(SafeJSContext::from_ptr(cx), ${val}.get().to_object())" % name if type.nullable(): declType = CGWrapper(declType, pre="Option<", post=">") template = wrapObjectTemplate("Some(%s)" % template, "None", @@ -2364,7 +2364,7 @@ class CGGeneric(CGThing): class CGCallbackTempRoot(CGGeneric): def __init__(self, name): - CGGeneric.__init__(self, "%s::new(cx, ${val}.get().to_object())" % name) + CGGeneric.__init__(self, "%s::new(SafeJSContext::from_ptr(cx), ${val}.get().to_object())" % name) def getAllTypes(descriptors, dictionaries, callbacks, typedefs): @@ -6795,7 +6795,7 @@ class CGCallback(CGClass): def getConstructors(self): return [ClassConstructor( - [Argument("*mut JSContext", "aCx"), Argument("*mut JSObject", "aCallback")], + [Argument("SafeJSContext", "aCx"), Argument("*mut JSObject", "aCallback")], bodyInHeader=True, visibility="pub", explicit=False, @@ -6891,7 +6891,7 @@ class CGCallbackFunctionImpl(CGGeneric): def __init__(self, callback): impl = string.Template("""\ impl CallbackContainer for ${type} { - unsafe fn new(cx: *mut JSContext, callback: *mut JSObject) -> Rc<${type}> { + unsafe fn new(cx: SafeJSContext, callback: *mut JSObject) -> Rc<${type}> { ${type}::new(cx, callback) } -- cgit v1.2.3 From 808fa65aef163879b82baddc4af0a5445f806c81 Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sun, 21 Jul 2019 22:22:44 +0100 Subject: Convert internal methods to handle safe JSContext instead of raw JSContext --- .../script/dom/bindings/codegen/CodegenRust.py | 280 +++++++++++---------- 1 file changed, 144 insertions(+), 136 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 71b7a279b7a..70da52b765e 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -323,7 +323,7 @@ class CGMethodCall(CGThing): if requiredArgs > 0: code = ( "if argc < %d {\n" - " throw_type_error(cx, \"Not enough arguments to %s.\");\n" + " throw_type_error(*cx, \"Not enough arguments to %s.\");\n" " return false;\n" "}" % (requiredArgs, methodName)) self.cgRoot.prepend( @@ -448,7 +448,7 @@ class CGMethodCall(CGThing): # XXXbz Now we're supposed to check for distinguishingArg being # an array or a platform object that supports indexed # properties... skip that last for now. It's a bit of a pain. - pickFirstSignature("%s.get().is_object() && is_array_like(cx, %s)" % + pickFirstSignature("%s.get().is_object() && is_array_like(*cx, %s)" % (distinguishingArg, distinguishingArg), lambda s: (s[1][distinguishingIndex].type.isSequence() or @@ -457,9 +457,9 @@ class CGMethodCall(CGThing): # Check for Date objects # XXXbz Do we need to worry about security wrappers around the Date? pickFirstSignature("%s.get().is_object() && " - "{ rooted!(in(cx) let obj = %s.get().to_object()); " + "{ rooted!(in(*cx) let obj = %s.get().to_object()); " "let mut is_date = false; " - "assert!(ObjectIsDate(cx, obj.handle(), &mut is_date)); " + "assert!(ObjectIsDate(*cx, obj.handle(), &mut is_date)); " "is_date }" % (distinguishingArg, distinguishingArg), lambda s: (s[1][distinguishingIndex].type.isDate() or @@ -467,7 +467,7 @@ class CGMethodCall(CGThing): # Check for vanilla JS objects # XXXbz Do we need to worry about security wrappers? - pickFirstSignature("%s.get().is_object() && !is_platform_object(%s.get().to_object(), cx)" % + pickFirstSignature("%s.get().is_object() && !is_platform_object(%s.get().to_object(), *cx)" % (distinguishingArg, distinguishingArg), lambda s: (s[1][distinguishingIndex].type.isCallback() or s[1][distinguishingIndex].type.isCallbackInterface() or @@ -492,7 +492,7 @@ class CGMethodCall(CGThing): else: # Just throw; we have no idea what we're supposed to # do with this. - caseBody.append(CGGeneric("throw_internal_error(cx, \"Could not convert JavaScript argument\");\n" + caseBody.append(CGGeneric("throw_internal_error(*cx, \"Could not convert JavaScript argument\");\n" "return false;")) argCountCases.append(CGCase(str(argCount), @@ -505,7 +505,7 @@ class CGMethodCall(CGThing): overloadCGThings.append( CGSwitch("argcount", argCountCases, - CGGeneric("throw_type_error(cx, \"Not enough arguments to %s.\");\n" + CGGeneric("throw_type_error(*cx, \"Not enough arguments to %s.\");\n" "return false;" % methodName))) # XXXjdm Avoid unreachable statement warnings # overloadCGThings.append( @@ -638,7 +638,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, exceptionCode = "return false;\n" if failureCode is None: - failOrPropagate = "throw_type_error(cx, &error);\n%s" % exceptionCode + failOrPropagate = "throw_type_error(*cx, &error);\n%s" % exceptionCode else: failOrPropagate = failureCode @@ -657,20 +657,20 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, return CGWrapper( CGGeneric( failureCode or - ('throw_type_error(cx, "%s is not an object.");\n' + ('throw_type_error(*cx, "%s is not an object.");\n' '%s' % (firstCap(sourceDescription), exceptionCode))), post="\n") def onFailureInvalidEnumValue(failureCode, passedVarName): return CGGeneric( failureCode or - ('throw_type_error(cx, &format!("\'{}\' is not a valid enum value for enumeration \'%s\'.", %s)); %s' + ('throw_type_error(*cx, &format!("\'{}\' is not a valid enum value for enumeration \'%s\'.", %s)); %s' % (type.name, passedVarName, exceptionCode))) def onFailureNotCallable(failureCode): return CGGeneric( failureCode or - ('throw_type_error(cx, \"%s is not callable.\");\n' + ('throw_type_error(*cx, \"%s is not callable.\");\n' '%s' % (firstCap(sourceDescription), exceptionCode))) # A helper function for handling default values. @@ -723,7 +723,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type.nullable(): declType = CGWrapper(declType, pre="Option<", post=" >") - templateBody = ("match FromJSValConvertible::from_jsval(cx, ${val}, %s) {\n" + templateBody = ("match FromJSValConvertible::from_jsval(*cx, ${val}, %s) {\n" " Ok(ConversionResult::Success(value)) => value,\n" " Ok(ConversionResult::Failure(error)) => {\n" "%s\n" @@ -738,7 +738,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type.nullable(): declType = CGWrapper(declType, pre="Option<", post=" >") - templateBody = ("match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" + templateBody = ("match FromJSValConvertible::from_jsval(*cx, ${val}, ()) {\n" " Ok(ConversionResult::Success(value)) => value,\n" " Ok(ConversionResult::Failure(error)) => {\n" "%s\n" @@ -803,17 +803,17 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, """ { // Scope for our JSAutoRealm. - rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); - let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get(), cx); + rooted!(in(*cx) let globalObj = CurrentGlobalOrNull(*cx)); + let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get(), *cx); - rooted!(in(cx) let mut valueToResolve = $${val}.get()); - if !JS_WrapValue(cx, valueToResolve.handle_mut()) { + rooted!(in(*cx) let mut valueToResolve = $${val}.get()); + if !JS_WrapValue(*cx, valueToResolve.handle_mut()) { $*{exceptionCode} } - match Promise::new_resolved(&promiseGlobal, cx, valueToResolve.handle()) { + match Promise::new_resolved(&promiseGlobal, *cx, valueToResolve.handle()) { Ok(value) => value, Err(error) => { - throw_dom_exception(cx, &promiseGlobal, error); + throw_dom_exception(*cx, &promiseGlobal, error); $*{exceptionCode} } } @@ -836,7 +836,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if descriptor.interface.isCallback(): name = descriptor.nativeType declType = CGWrapper(CGGeneric(name), pre="Rc<", post=">") - template = "%s::new(SafeJSContext::from_ptr(cx), ${val}.get().to_object())" % name + template = "%s::new(cx, ${val}.get().to_object())" % name if type.nullable(): declType = CGWrapper(declType, pre="Option<", post=">") template = wrapObjectTemplate("Some(%s)" % template, "None", @@ -864,7 +864,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, "exceptionCode": exceptionCode, } unwrapFailureCode = string.Template( - 'throw_type_error(cx, "${sourceDescription} does not ' + 'throw_type_error(*cx, "${sourceDescription} does not ' 'implement interface ${interface}.");\n' '${exceptionCode}').substitute(substitutions) else: @@ -872,7 +872,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, templateBody = fill( """ - match ${function}($${val}, cx) { + match ${function}($${val}, *cx) { Ok(val) => val, Err(()) => { $*{failureCode} @@ -899,7 +899,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, "exceptionCode": exceptionCode, } unwrapFailureCode = string.Template( - 'throw_type_error(cx, "${sourceDescription} is not a typed array.");\n' + 'throw_type_error(*cx, "${sourceDescription} is not a typed array.");\n' '${exceptionCode}').substitute(substitutions) else: unwrapFailureCode = failureCode @@ -942,7 +942,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, nullBehavior = getConversionConfigForType(type, isEnforceRange, isClamp, treatNullAs) conversionCode = ( - "match FromJSValConvertible::from_jsval(cx, ${val}, %s) {\n" + "match FromJSValConvertible::from_jsval(*cx, ${val}, %s) {\n" " Ok(ConversionResult::Success(strval)) => strval,\n" " Ok(ConversionResult::Failure(error)) => {\n" "%s\n" @@ -971,7 +971,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, assert not isEnforceRange and not isClamp conversionCode = ( - "match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" + "match FromJSValConvertible::from_jsval(*cx, ${val}, ()) {\n" " Ok(ConversionResult::Success(strval)) => strval,\n" " Ok(ConversionResult::Failure(error)) => {\n" "%s\n" @@ -1000,7 +1000,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, assert not isEnforceRange and not isClamp conversionCode = ( - "match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" + "match FromJSValConvertible::from_jsval(*cx, ${val}, ()) {\n" " Ok(ConversionResult::Success(strval)) => strval,\n" " Ok(ConversionResult::Failure(error)) => {\n" "%s\n" @@ -1038,7 +1038,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, handleInvalidEnumValueCode = "return true;" template = ( - "match find_enum_value(cx, ${val}, %(pairs)s) {\n" + "match find_enum_value(*cx, ${val}, %(pairs)s) {\n" " Err(_) => { %(exceptionCode)s },\n" " Ok((None, search)) => { %(handleInvalidEnumValueCode)s },\n" " Ok((Some(&value), _)) => value,\n" @@ -1174,7 +1174,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type_needs_tracing(type): declType = CGTemplatedType("RootedTraceableBox", declType) - template = ("match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" + template = ("match FromJSValConvertible::from_jsval(*cx, ${val}, ()) {\n" " Ok(ConversionResult::Success(dictionary)) => dictionary,\n" " Ok(ConversionResult::Failure(error)) => {\n" "%s\n" @@ -1202,7 +1202,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, declType = CGWrapper(declType, pre="Option<", post=">") template = ( - "match FromJSValConvertible::from_jsval(cx, ${val}, %s) {\n" + "match FromJSValConvertible::from_jsval(*cx, ${val}, %s) {\n" " Ok(ConversionResult::Success(v)) => v,\n" " Ok(ConversionResult::Failure(error)) => {\n" "%s\n" @@ -1260,7 +1260,7 @@ def instantiateJSToNativeConversionTemplate(templateBody, replacements, result.append(conversion) if needsAutoRoot: - result.append(CGGeneric("auto_root!(in(cx) let %s = %s);" % (declName, declName))) + result.append(CGGeneric("auto_root!(in(*cx) let %s = %s);" % (declName, declName))) # Add an empty CGGeneric to get an extra newline after the argument # conversion. result.append(CGGeneric("")) @@ -1383,7 +1383,7 @@ def wrapForType(jsvalRef, result='result', successCode='return true;', pre=''): * 'successCode': the code to run once we have done the conversion. * 'pre': code to run before the conversion if rooting is necessary """ - wrap = "%s\n(%s).to_jsval(cx, %s);" % (pre, result, jsvalRef) + wrap = "%s\n(%s).to_jsval(*cx, %s);" % (pre, result, jsvalRef) if successCode: wrap += "\n%s" % successCode return wrap @@ -2364,7 +2364,7 @@ class CGGeneric(CGThing): class CGCallbackTempRoot(CGGeneric): def __init__(self, name): - CGGeneric.__init__(self, "%s::new(SafeJSContext::from_ptr(cx), ${val}.get().to_object())" % name) + CGGeneric.__init__(self, "%s::new(cx, ${val}.get().to_object())" % name) def getAllTypes(descriptors, dictionaries, callbacks, typedefs): @@ -2410,6 +2410,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::str::USVString', 'crate::dom::bindings::trace::RootedTraceableBox', 'crate::dom::types::*', + 'crate::script_runtime::JSContext as SafeJSContext', 'js::error::throw_type_error', 'js::rust::HandleValue', 'js::jsapi::Heap', @@ -3331,9 +3332,9 @@ class CGCallGenerator(CGThing): needsCx = needCx(returnType, (a for (a, _) in arguments), True) if "cx" not in argsPre and needsCx: - args.prepend(CGGeneric("cx")) + args.prepend(CGGeneric("*cx")) if nativeMethodName in descriptor.inCompartmentMethods: - args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(cx))")) + args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(*cx))")) # Build up our actual call self.cgRoot = CGList([], "\n") @@ -3369,7 +3370,7 @@ class CGCallGenerator(CGThing): "let result = match result {\n" " Ok(result) => result,\n" " Err(e) => {\n" - " throw_dom_exception(cx, %s, e);\n" + " throw_dom_exception(*cx, %s, e);\n" " return%s;\n" " },\n" "};" % (glob, errorResult))) @@ -3593,7 +3594,7 @@ class CGSpecializedMethod(CGAbstractExternMethod): def __init__(self, descriptor, method): self.method = method name = method.identifier.name - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', '_obj'), + args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', '_obj'), Argument('*const %s' % descriptor.concreteType, 'this'), Argument('*const JSJitMethodCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, 'bool', args) @@ -3628,9 +3629,10 @@ class CGStaticMethod(CGAbstractStaticBindingMethod): def generate_code(self): nativeName = CGSpecializedMethod.makeNativeName(self.descriptor, self.method) + safeContext = CGGeneric("let cx = SafeJSContext::from_ptr(cx);\n") setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") call = CGMethodCall(["&global"], nativeName, True, self.descriptor, self.method) - return CGList([setupArgs, call]) + return CGList([safeContext, setupArgs, call]) class CGSpecializedGetter(CGAbstractExternMethod): @@ -3641,7 +3643,7 @@ class CGSpecializedGetter(CGAbstractExternMethod): def __init__(self, descriptor, attr): self.attr = attr name = 'get_' + descriptor.internalNameFor(attr.identifier.name) - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', '_obj'), Argument('*const %s' % descriptor.concreteType, 'this'), Argument('JSJitGetterCallArgs', 'args')] @@ -3682,10 +3684,11 @@ class CGStaticGetter(CGAbstractStaticBindingMethod): def generate_code(self): nativeName = CGSpecializedGetter.makeNativeName(self.descriptor, self.attr) + safeContext = CGGeneric("let cx = SafeJSContext::from_ptr(cx);\n") setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") call = CGGetterCall(["&global"], self.attr.type, nativeName, self.descriptor, self.attr) - return CGList([setupArgs, call]) + return CGList([safeContext, setupArgs, call]) class CGSpecializedSetter(CGAbstractExternMethod): @@ -3696,7 +3699,7 @@ class CGSpecializedSetter(CGAbstractExternMethod): def __init__(self, descriptor, attr): self.attr = attr name = 'set_' + descriptor.internalNameFor(attr.identifier.name) - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', 'obj'), Argument('*const %s' % descriptor.concreteType, 'this'), Argument('JSJitSetterCallArgs', 'args')] @@ -3730,15 +3733,16 @@ class CGStaticSetter(CGAbstractStaticBindingMethod): def generate_code(self): nativeName = CGSpecializedSetter.makeNativeName(self.descriptor, self.attr) + safeContext = CGGeneric("let cx = SafeJSContext::from_ptr(cx);\n") checkForArg = CGGeneric( "let args = CallArgs::from_vp(vp, argc);\n" "if argc == 0 {\n" - " throw_type_error(cx, \"Not enough arguments to %s setter.\");\n" + " throw_type_error(*cx, \"Not enough arguments to %s setter.\");\n" " return false;\n" "}" % self.attr.identifier.name) call = CGSetterCall(["&global"], self.attr.type, nativeName, self.descriptor, self.attr) - return CGList([checkForArg, call]) + return CGList([safeContext, checkForArg, call]) class CGSpecializedForwardingSetter(CGSpecializedSetter): @@ -3755,16 +3759,16 @@ class CGSpecializedForwardingSetter(CGSpecializedSetter): assert all(ord(c) < 128 for c in attrName) assert all(ord(c) < 128 for c in forwardToAttrName) return CGGeneric("""\ -rooted!(in(cx) let mut v = UndefinedValue()); -if !JS_GetProperty(cx, obj, %s as *const u8 as *const libc::c_char, v.handle_mut()) { +rooted!(in(*cx) let mut v = UndefinedValue()); +if !JS_GetProperty(*cx, obj, %s as *const u8 as *const libc::c_char, v.handle_mut()) { return false; } if !v.is_object() { - throw_type_error(cx, "Value.%s is not an object."); + throw_type_error(*cx, "Value.%s is not an object."); return false; } -rooted!(in(cx) let target_obj = v.to_object()); -JS_SetProperty(cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, HandleValue::from_raw(args.get(0))) +rooted!(in(*cx) let target_obj = v.to_object()); +JS_SetProperty(*cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, HandleValue::from_raw(args.get(0))) """ % (str_to_const_array(attrName), attrName, str_to_const_array(forwardToAttrName))) @@ -3781,7 +3785,7 @@ class CGSpecializedReplaceableSetter(CGSpecializedSetter): # JS_DefineProperty can only deal with ASCII. assert all(ord(c) < 128 for c in name) return CGGeneric("""\ -JS_DefineProperty(cx, obj, %s as *const u8 as *const libc::c_char, +JS_DefineProperty(*cx, obj, %s as *const u8 as *const libc::c_char, HandleValue::from_raw(args.get(0)), JSPROP_ENUMERATE as u32)""" % name) @@ -4370,7 +4374,7 @@ class CGUnionConversionStruct(CGThing): def get_match(name): return ( - "match %s::TryConvertTo%s(cx, value) {\n" + "match %s::TryConvertTo%s(SafeJSContext::from_ptr(cx), value) {\n" " Err(_) => return Err(()),\n" " Ok(Some(value)) => return Ok(ConversionResult::Success(%s::%s(value))),\n" " Ok(None) => (),\n" @@ -4510,7 +4514,7 @@ class CGUnionConversionStruct(CGThing): return CGWrapper( CGIndenter(jsConversion, 4), - pre="unsafe fn TryConvertTo%s(cx: *mut JSContext, value: HandleValue) -> %s {\n" + pre="unsafe fn TryConvertTo%s(cx: SafeJSContext, value: HandleValue) -> %s {\n" % (t.name, returnType), post="\n}") @@ -4903,7 +4907,7 @@ class CGProxySpecialOperation(CGPerSignatureCall): } self.cgRoot.prepend(instantiateJSToNativeConversionTemplate( template, templateValues, declType, argument.identifier.name)) - self.cgRoot.prepend(CGGeneric("rooted!(in(cx) let value = desc.value);")) + self.cgRoot.prepend(CGGeneric("rooted!(in(*cx) let value = desc.value);")) def getArguments(self): args = [(a, process_arg(a.identifier.name, a)) for a in self.arguments] @@ -4946,7 +4950,7 @@ class CGProxyNamedOperation(CGProxySpecialOperation): def define(self): # Our first argument is the id we're getting. argName = self.arguments[0].identifier.name - return ("let %s = jsid_to_string(cx, Handle::from_raw(id)).expect(\"Not a string-convertible JSID?\");\n" + return ("let %s = jsid_to_string(*cx, Handle::from_raw(id)).expect(\"Not a string-convertible JSID?\");\n" "let this = UnwrapProxy(proxy);\n" "let this = &*this;\n" % argName + CGProxySpecialOperation.define(self)) @@ -5015,9 +5019,9 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): def getBody(self): indexedGetter = self.descriptor.operations['IndexedGetter'] - get = "" + get = "let cx = SafeJSContext::from_ptr(cx);\n" if indexedGetter: - get = "let index = get_array_index_from_id(cx, Handle::from_raw(id));\n" + get += "let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" attrs = "JSPROP_ENUMERATE" if self.descriptor.operations['IndexedSetter'] is None: @@ -5029,7 +5033,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): templateValues = { 'jsvalRef': 'result_root.handle_mut()', 'successCode': fillDescriptor, - 'pre': 'rooted!(in(cx) let mut result_root = UndefinedValue());' + 'pre': 'rooted!(in(*cx) let mut result_root = UndefinedValue());' } get += ("if let Some(index) = index {\n" + " let this = UnwrapProxy(proxy);\n" + @@ -5055,7 +5059,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): templateValues = { 'jsvalRef': 'result_root.handle_mut()', 'successCode': fillDescriptor, - 'pre': 'rooted!(in(cx) let mut result_root = UndefinedValue());' + 'pre': 'rooted!(in(*cx) let mut result_root = UndefinedValue());' } # See the similar-looking in CGDOMJSProxyHandler_get for the spec quote. @@ -5068,7 +5072,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): namedGet = """ if %s { let mut has_on_proto = false; - if !has_property_on_prototype(cx, proxy_lt, id_lt, &mut has_on_proto) { + if !has_property_on_prototype(*cx, proxy_lt, id_lt, &mut has_on_proto) { return false; } if !has_on_proto { @@ -5080,13 +5084,13 @@ if %s { namedGet = "" return get + """\ -rooted!(in(cx) let mut expando = ptr::null_mut::()); +rooted!(in(*cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); //if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) { let proxy_lt = Handle::from_raw(proxy); let id_lt = Handle::from_raw(id); if !expando.is_null() { - if !JS_GetPropertyDescriptorById(cx, expando.handle().into(), id, desc) { + if !JS_GetPropertyDescriptorById(*cx, expando.handle().into(), id, desc) { return false; } if !desc.obj.is_null() { @@ -5113,11 +5117,11 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): self.descriptor = descriptor def getBody(self): - set = "" + set = "let cx = SafeJSContext::from_ptr(cx);\n" indexedSetter = self.descriptor.operations['IndexedSetter'] if indexedSetter: - set += ("let index = get_array_index_from_id(cx, Handle::from_raw(id));\n" + + set += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + "if let Some(index) = index {\n" + " let this = UnwrapProxy(proxy);\n" + " let this = &*this;\n" + @@ -5125,7 +5129,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): " return (*opresult).succeed();\n" + "}\n") elif self.descriptor.operations['IndexedGetter']: - set += ("if get_array_index_from_id(cx, Handle::from_raw(id)).is_some() {\n" + + set += ("if get_array_index_from_id(*cx, Handle::from_raw(id)).is_some() {\n" + " return (*opresult).failNoIndexedSetter();\n" + "}\n") @@ -5145,7 +5149,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): " return (*opresult).failNoNamedSetter();\n" " }\n" "}\n") - set += "return proxyhandler::define_property(%s);" % ", ".join(a.name for a in self.args) + set += "return proxyhandler::define_property(*cx, %s);" % ", ".join(a.name for a in self.args[1:]) return set def definition_body(self): @@ -5161,13 +5165,13 @@ class CGDOMJSProxyHandler_delete(CGAbstractExternMethod): self.descriptor = descriptor def getBody(self): - set = "" + set = "let cx = SafeJSContext::from_ptr(cx);\n" if self.descriptor.operations['NamedDeleter']: if self.descriptor.hasUnforgeableMembers: raise TypeError("Can't handle a deleter on an interface that has " "unforgeables. Figure out how that should work!") set += CGProxyNamedDeleter(self.descriptor).define() - set += "return proxyhandler::delete(%s);" % ", ".join(a.name for a in self.args) + set += "return proxyhandler::delete(*cx, %s);" % ", ".join(a.name for a in self.args[1:]) return set def definition_body(self): @@ -5185,6 +5189,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): def getBody(self): body = dedent( """ + let cx = SafeJSContext::from_ptr(cx); let unwrapped_proxy = UnwrapProxy(proxy); """) @@ -5192,7 +5197,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): body += dedent( """ for i in 0..(*unwrapped_proxy).Length() { - rooted!(in(cx) let rooted_jsid = int_to_jsid(i as i32)); + rooted!(in(*cx) let rooted_jsid = int_to_jsid(i as i32)); AppendToAutoIdVector(props, rooted_jsid.handle().get()); } """) @@ -5202,20 +5207,20 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): """ for name in (*unwrapped_proxy).SupportedPropertyNames() { let cstring = CString::new(name).unwrap(); - let jsstring = JS_AtomizeAndPinString(cx, cstring.as_ptr()); - rooted!(in(cx) let rooted = jsstring); - let jsid = INTERNED_STRING_TO_JSID(cx, rooted.handle().get()); - rooted!(in(cx) let rooted_jsid = jsid); + let jsstring = JS_AtomizeAndPinString(*cx, cstring.as_ptr()); + rooted!(in(*cx) let rooted = jsstring); + let jsid = INTERNED_STRING_TO_JSID(*cx, rooted.handle().get()); + rooted!(in(*cx) let rooted_jsid = jsid); AppendToAutoIdVector(props, rooted_jsid.handle().get()); } """) body += dedent( """ - rooted!(in(cx) let mut expando = ptr::null_mut::()); + rooted!(in(*cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { - GetPropertyKeys(cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); + GetPropertyKeys(*cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); } return true; @@ -5241,6 +5246,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): def getBody(self): body = dedent( """ + let cx = SafeJSContext::from_ptr(cx); let unwrapped_proxy = UnwrapProxy(proxy); """) @@ -5248,17 +5254,17 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): body += dedent( """ for i in 0..(*unwrapped_proxy).Length() { - rooted!(in(cx) let rooted_jsid = int_to_jsid(i as i32)); + rooted!(in(*cx) let rooted_jsid = int_to_jsid(i as i32)); AppendToAutoIdVector(props, rooted_jsid.handle().get()); } """) body += dedent( """ - rooted!(in(cx) let mut expando = ptr::null_mut::()); + rooted!(in(*cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { - GetPropertyKeys(cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); + GetPropertyKeys(*cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); } return true; @@ -5279,17 +5285,16 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): def getBody(self): indexedGetter = self.descriptor.operations['IndexedGetter'] + indexed = "let cx = SafeJSContext::from_ptr(cx);\n" if indexedGetter: - indexed = ("let index = get_array_index_from_id(cx, Handle::from_raw(id));\n" + - "if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" + - " *bp = result.is_some();\n" + - " return true;\n" + - "}\n\n") - else: - indexed = "" + indexed += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + + "if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" + + " *bp = result.is_some();\n" + + " return true;\n" + + "}\n\n") namedGetter = self.descriptor.operations['NamedGetter'] condition = "RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id)" @@ -5299,7 +5304,7 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): named = """\ if %s { let mut has_on_proto = false; - if !has_property_on_prototype(cx, proxy_lt, id_lt, &mut has_on_proto) { + if !has_property_on_prototype(*cx, proxy_lt, id_lt, &mut has_on_proto) { return false; } if !has_on_proto { @@ -5314,12 +5319,12 @@ if %s { named = "" return indexed + """\ -rooted!(in(cx) let mut expando = ptr::null_mut::()); +rooted!(in(*cx) let mut expando = ptr::null_mut::()); let proxy_lt = Handle::from_raw(proxy); let id_lt = Handle::from_raw(id); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { - let ok = JS_HasPropertyById(cx, expando.handle().into(), id, bp); + let ok = JS_HasPropertyById(*cx, expando.handle().into(), id, bp); if !ok || *bp { return ok; } @@ -5343,16 +5348,16 @@ class CGDOMJSProxyHandler_get(CGAbstractExternMethod): # https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty def getBody(self): getFromExpando = """\ -rooted!(in(cx) let mut expando = ptr::null_mut::()); +rooted!(in(*cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { let mut hasProp = false; - if !JS_HasPropertyById(cx, expando.handle().into(), id, &mut hasProp) { + if !JS_HasPropertyById(*cx, expando.handle().into(), id, &mut hasProp) { return false; } if hasProp { - return JS_ForwardGetPropertyTo(cx, expando.handle().into(), id, receiver, vp); + return JS_ForwardGetPropertyTo(*cx, expando.handle().into(), id, receiver, vp); } }""" @@ -5363,7 +5368,7 @@ if !expando.is_null() { indexedGetter = self.descriptor.operations['IndexedGetter'] if indexedGetter: - getIndexedOrExpando = ("let index = get_array_index_from_id(cx, id_lt);\n" + + getIndexedOrExpando = ("let index = get_array_index_from_id(*cx, id_lt);\n" + "if let Some(index) = index {\n" + " let this = UnwrapProxy(proxy);\n" + " let this = &*this;\n" + @@ -5396,6 +5401,7 @@ if !expando.is_null() { return """\ //MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy), //"Should not have a XrayWrapper here"); +let cx = SafeJSContext::from_ptr(cx); let proxy_lt = Handle::from_raw(proxy); let vp_lt = MutableHandle::from_raw(vp); let id_lt = Handle::from_raw(id); @@ -5403,7 +5409,7 @@ let receiver_lt = Handle::from_raw(receiver); %s let mut found = false; -if !get_property_on_prototype(cx, proxy_lt, receiver_lt, id_lt, &mut found, vp_lt) { +if !get_property_on_prototype(*cx, proxy_lt, receiver_lt, id_lt, &mut found, vp_lt) { return false; } @@ -5526,7 +5532,9 @@ class CGClassConstructHook(CGAbstractExternMethod): self.exposureSet = descriptor.interface.exposureSet def definition_body(self): - preamble = """let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n""" + preamble = """let cx = SafeJSContext::from_ptr(cx); +let global = GlobalScope::from_object(JS_CALLEE(*cx, vp).to_object()); +""" if len(self.exposureSet) == 1: preamble += """\ let global = DomRoot::downcast::(global).unwrap(); @@ -5542,24 +5550,24 @@ let global = DomRoot::downcast::(global).unwrap(); // The new_target might be a cross-compartment wrapper. Get the underlying object // so we can do the spec's object-identity checks. -rooted!(in(cx) let new_target = UnwrapObjectDynamic(args.new_target().to_object(), cx, 1)); +rooted!(in(*cx) let new_target = UnwrapObjectDynamic(args.new_target().to_object(), *cx, 1)); if new_target.is_null() { - throw_dom_exception(cx, global.upcast::(), Error::Type("new.target is null".to_owned())); + throw_dom_exception(*cx, global.upcast::(), Error::Type("new.target is null".to_owned())); return false; } if args.callee() == new_target.get() { - throw_dom_exception(cx, global.upcast::(), + throw_dom_exception(*cx, global.upcast::(), Error::Type("new.target must not be the active function object".to_owned())); return false; } // Step 6 -rooted!(in(cx) let mut prototype = ptr::null_mut::()); +rooted!(in(*cx) let mut prototype = ptr::null_mut::()); { - rooted!(in(cx) let mut proto_val = UndefinedValue()); - let _ac = JSAutoRealm::new(cx, new_target.get()); - if !JS_GetProperty(cx, new_target.handle(), b"prototype\\0".as_ptr() as *const _, proto_val.handle_mut()) { + rooted!(in(*cx) let mut proto_val = UndefinedValue()); + let _ac = JSAutoRealm::new(*cx, new_target.get()); + if !JS_GetProperty(*cx, new_target.handle(), b"prototype\\0".as_ptr() as *const _, proto_val.handle_mut()) { return false; } @@ -5573,8 +5581,8 @@ rooted!(in(cx) let mut prototype = ptr::null_mut::()); // whose target is not same-compartment with the proxy, or bound functions, etc). // https://bugzilla.mozilla.org/show_bug.cgi?id=1317658 - rooted!(in(cx) let global_object = CurrentGlobalOrNull(cx)); - GetProtoObject(SafeJSContext::from_ptr(cx), global_object.handle(), prototype.handle_mut()); + rooted!(in(*cx) let global_object = CurrentGlobalOrNull(*cx)); + GetProtoObject(cx, global_object.handle(), prototype.handle_mut()); } else { // Step 6 prototype.set(proto_val.to_object()); @@ -5582,7 +5590,7 @@ rooted!(in(cx) let mut prototype = ptr::null_mut::()); } // Wrap prototype in this context since it is from the newTarget compartment -if !JS_WrapObject(cx, prototype.handle_mut()) { +if !JS_WrapObject(*cx, prototype.handle_mut()) { return false; } @@ -5590,19 +5598,19 @@ let result: Result, Error> = html_constructor(&global, &args); let result = match result { Ok(result) => result, Err(e) => { - throw_dom_exception(cx, global.upcast::(), e); + throw_dom_exception(*cx, global.upcast::(), e); return false; }, }; -rooted!(in(cx) let mut element = result.reflector().get_jsobject().get()); -if !JS_WrapObject(cx, element.handle_mut()) { +rooted!(in(*cx) let mut element = result.reflector().get_jsobject().get()); +if !JS_WrapObject(*cx, element.handle_mut()) { return false; } -JS_SetPrototype(cx, element.handle(), prototype.handle()); +JS_SetPrototype(*cx, element.handle(), prototype.handle()); -(result).to_jsval(cx, MutableHandleValue::from_raw(args.rval())); +(result).to_jsval(*cx, MutableHandleValue::from_raw(args.rval())); return true; """ % self.descriptor.name) else: @@ -6290,7 +6298,7 @@ class CGDictionary(CGThing): " match r#try!(%s::%s::new(cx, val)) {\n" " ConversionResult::Success(v) => v,\n" " ConversionResult::Failure(error) => {\n" - " throw_type_error(cx, &error);\n" + " throw_type_error(*cx, &error);\n" " return Err(());\n" " }\n" " }\n" @@ -6344,7 +6352,7 @@ class CGDictionary(CGThing): return string.Template( "impl ${selfName} {\n" "${empty}\n" - " pub unsafe fn new(cx: *mut JSContext, val: HandleValue) \n" + " pub unsafe fn new(cx: SafeJSContext, val: HandleValue) \n" " -> Result, ()> {\n" " let object = if val.get().is_null_or_undefined() {\n" " ptr::null_mut()\n" @@ -6353,7 +6361,7 @@ class CGDictionary(CGThing): " } else {\n" " return Ok(ConversionResult::Failure(\"Value is not an object.\".into()));\n" " };\n" - " rooted!(in(cx) let object = object);\n" + " rooted!(in(*cx) let object = object);\n" "${preInitial}" "${initParent}" "${initMembers}" @@ -6366,7 +6374,7 @@ class CGDictionary(CGThing): " type Config = ();\n" " unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, _option: ())\n" " -> Result, ()> {\n" - " ${selfName}::new(cx, value)\n" + " ${selfName}::new(SafeJSContext::from_ptr(cx), value)\n" " }\n" "}\n" "\n" @@ -6424,7 +6432,7 @@ class CGDictionary(CGThing): assert (member.defaultValue is None) == (default is None) if not member.optional: assert default is None - default = ("throw_type_error(cx, \"Missing required member \\\"%s\\\".\");\n" + default = ("throw_type_error(*cx, \"Missing required member \\\"%s\\\".\");\n" "return Err(());") % member.identifier.name elif not default: default = "None" @@ -6432,8 +6440,8 @@ class CGDictionary(CGThing): conversion = ( "{\n" - " rooted!(in(cx) let mut rval = UndefinedValue());\n" - " if r#try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut()))" + " rooted!(in(*cx) let mut rval = UndefinedValue());\n" + " if r#try!(get_dictionary_property(*cx, object.handle(), \"%s\", rval.handle_mut()))" " && !rval.is_undefined() {\n" "%s\n" " } else {\n" @@ -6808,14 +6816,14 @@ class CGCallback(CGClass): args = list(method.args) # Strip out the JSContext*/JSObject* args # that got added. - assert args[0].name == "cx" and args[0].argType == "*mut JSContext" + assert args[0].name == "cx" and args[0].argType == "SafeJSContext" assert args[1].name == "aThisObj" and args[1].argType == "HandleObject" args = args[2:] # Record the names of all the arguments, so we can use them when we call # the private method. argnames = [arg.name for arg in args] - argnamesWithThis = ["s.get_context()", "thisObjJS.handle()"] + argnames - argnamesWithoutThis = ["s.get_context()", "thisObjJS.handle()"] + argnames + argnamesWithThis = ["SafeJSContext::from_ptr(s.get_context())", "thisObjJS.handle()"] + argnames + argnamesWithoutThis = ["SafeJSContext::from_ptr(s.get_context())", "thisObjJS.handle()"] + argnames # Now that we've recorded the argnames for our call to our private # method, insert our optional argument for deciding whether the # CallSetup should re-throw exceptions on aRv. @@ -7066,7 +7074,7 @@ class CallbackMember(CGNativeMember): "*arg = Heap::default();\n" + "arg.set(argv_root.get());\n" + "}") % jsvalIndex, - pre="rooted!(in(cx) let mut argv_root = UndefinedValue());") + pre="rooted!(in(*cx) let mut argv_root = UndefinedValue());") if arg.variadic: conversion = string.Template( "for idx in 0..${arg}.len() {\n" + @@ -7095,7 +7103,7 @@ class CallbackMember(CGNativeMember): return args # We want to allow the caller to pass in a "this" object, as # well as a JSContext. - return [Argument("*mut JSContext", "cx"), + return [Argument("SafeJSContext", "cx"), Argument("HandleObject", "aThisObj")] + args def getCallSetup(self): @@ -7136,7 +7144,7 @@ class CallbackMethod(CallbackMember): needThisHandling) def getRvalDecl(self): - return "rooted!(in(cx) let mut rval = UndefinedValue());\n" + return "rooted!(in(*cx) let mut rval = UndefinedValue());\n" def getCall(self): replacements = { @@ -7152,9 +7160,9 @@ class CallbackMethod(CallbackMember): replacements["argc"] = "0" return string.Template( "${getCallable}" - "rooted!(in(cx) let rootedThis = ${thisObj});\n" + "rooted!(in(*cx) let rootedThis = ${thisObj});\n" "let ok = ${callGuard}JS_CallFunctionValue(\n" - " cx, rootedThis.handle(), callable.handle(),\n" + " *cx, rootedThis.handle(), callable.handle(),\n" " &HandleValueArray {\n" " length_: ${argc} as ::libc::size_t,\n" " elements_: ${argv}\n" @@ -7175,7 +7183,7 @@ class CallCallback(CallbackMethod): return "aThisObj.get()" def getCallableDecl(self): - return "rooted!(in(cx) let callable = ObjectValue(self.callback()));\n" + return "rooted!(in(*cx) let callable = ObjectValue(self.callback()));\n" def getCallGuard(self): if self.callback._treatNonObjectAsNull: @@ -7205,13 +7213,13 @@ class CallbackOperationBase(CallbackMethod): "methodName": self.methodName } getCallableFromProp = string.Template( - 'r#try!(self.parent.get_callable_property(cx, "${methodName}"))' + 'r#try!(self.parent.get_callable_property(*cx, "${methodName}"))' ).substitute(replacements) if not self.singleOperation: - return 'rooted!(in(cx) let callable =\n' + getCallableFromProp + ');\n' + return 'rooted!(in(*cx) let callable =\n' + getCallableFromProp + ');\n' return ( 'let isCallable = IsCallable(self.callback());\n' - 'rooted!(in(cx) let callable =\n' + + 'rooted!(in(*cx) let callable =\n' + CGIndenter( CGIfElseWrapper('isCallable', CGGeneric('ObjectValue(self.callback())'), @@ -7246,21 +7254,21 @@ class CGIterableMethodGenerator(CGGeneric): CGGeneric.__init__(self, fill( """ if !IsCallable(arg0) { - throw_type_error(cx, "Argument 1 of ${ifaceName}.forEach is not callable."); + throw_type_error(*cx, "Argument 1 of ${ifaceName}.forEach is not callable."); return false; } - rooted!(in(cx) let arg0 = ObjectValue(arg0)); - rooted!(in(cx) let mut call_arg1 = UndefinedValue()); - rooted!(in(cx) let mut call_arg2 = UndefinedValue()); + rooted!(in(*cx) let arg0 = ObjectValue(arg0)); + rooted!(in(*cx) let mut call_arg1 = UndefinedValue()); + rooted!(in(*cx) let mut call_arg2 = UndefinedValue()); let mut call_args = vec![UndefinedValue(), UndefinedValue(), ObjectValue(*_obj)]; - rooted!(in(cx) let mut ignoredReturnVal = UndefinedValue()); + rooted!(in(*cx) let mut ignoredReturnVal = UndefinedValue()); for i in 0..(*this).get_iterable_length() { - (*this).get_value_at_index(i).to_jsval(cx, call_arg1.handle_mut()); - (*this).get_key_at_index(i).to_jsval(cx, call_arg2.handle_mut()); + (*this).get_value_at_index(i).to_jsval(*cx, call_arg1.handle_mut()); + (*this).get_key_at_index(i).to_jsval(*cx, call_arg2.handle_mut()); call_args[0] = call_arg1.handle().get(); call_args[1] = call_arg2.handle().get(); let call_args = HandleValueArray { length_: 3, elements_: call_args.as_ptr() }; - if !Call(cx, arg1, arg0.handle(), &call_args, + if !Call(*cx, arg1, arg0.handle(), &call_args, ignoredReturnVal.handle_mut()) { return false; } -- cgit v1.2.3 From 2c5d0a6ebc39ad263e2bbe623e357a11b4cec5aa Mon Sep 17 00:00:00 2001 From: marmeladema Date: Mon, 22 Jul 2019 01:09:24 +0100 Subject: Convert CGTraitInterface to use safe JSContext instead of raw JSContext --- components/script/dom/bindings/codegen/CodegenRust.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 70da52b765e..343b8e6596d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3332,7 +3332,7 @@ class CGCallGenerator(CGThing): needsCx = needCx(returnType, (a for (a, _) in arguments), True) if "cx" not in argsPre and needsCx: - args.prepend(CGGeneric("*cx")) + args.prepend(CGGeneric("cx")) if nativeMethodName in descriptor.inCompartmentMethods: args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(*cx))")) @@ -5649,7 +5649,7 @@ class CGInterfaceTrait(CGThing): def attribute_arguments(needCx, argument=None, inCompartment=False): if needCx: - yield "cx", "*mut JSContext" + yield "cx", "SafeJSContext" if argument: yield "value", argument_type(descriptor, argument) @@ -6720,7 +6720,7 @@ def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, var def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None, inCompartment=False): if needCx(returnType, arguments, passJSBits): - yield "cx", "*mut JSContext" + yield "cx", "SafeJSContext" for argument in arguments: ty = argument_type(descriptorProvider, argument.type, argument.optional, -- cgit v1.2.3 From 16b4e3446bc466c87327fac3402736d3636a5f73 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Wed, 24 Jul 2019 17:11:44 +0900 Subject: Support default toJSON in WebIDL --- .../script/dom/bindings/codegen/CodegenRust.py | 96 +++++++++++++++++++++- 1 file changed, 94 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e0c7725fa52..159ca3652b9 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2881,6 +2881,49 @@ class PropertyArrays(): return define +class CGCollectJSONAttributesMethod(CGAbstractMethod): + """ + Generate the CollectJSONAttributes method for an interface descriptor + """ + def __init__(self, descriptor, toJSONMethod): + args = [Argument('*mut JSContext', 'cx'), + Argument('HandleObject', 'obj'), + Argument('*const %s' % descriptor.concreteType, 'this'), + Argument('&RootedGuard<*mut JSObject>', 'result')] + CGAbstractMethod.__init__(self, descriptor, 'CollectJSONAttributes', + 'bool', args, pub=True, unsafe=True) + self.toJSONMethod = toJSONMethod + + def definition_body(self): + ret = '' + interface = self.descriptor.interface + for m in interface.members: + if m.isAttr() and not m.isStatic() and m.type.isJSONType(): + name = m.identifier.name + getAndDefine = fill( + """ + rooted!(in(cx) let mut temp = UndefinedValue()); + if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { + return false; + } + if !JS_DefineProperty(cx, result.handle().into(), + ${nameAsArray} as *const u8 as *const libc::c_char, + temp.handle(), JSPROP_ENUMERATE as u32) { + return false; + } + """, + name=name, nameAsArray=str_to_const_array(name)) + ret += fill( + """ + { // scope for "temp" + $*{getAndDefine} + } + """, + getAndDefine=getAndDefine) + ret += 'return true;\n' + return CGGeneric(ret) + + class CGCreateInterfaceObjectsMethod(CGAbstractMethod): """ Generate the CreateInterfaceObjects method for an interface descriptor. @@ -3616,6 +3659,42 @@ class CGSpecializedMethod(CGAbstractExternMethod): return MakeNativeName(nativeName) +class CGDefaultToJSONMethod(CGSpecializedMethod): + def __init__(self, descriptor, method): + assert method.isDefaultToJSON() + CGSpecializedMethod.__init__(self, descriptor, method) + + def definition_body(self): + ret = dedent(""" + rooted!(in(cx) let result = JS_NewPlainObject(cx)); + if result.is_null() { + return false; + } + """) + + jsonDescriptors = [self.descriptor] + interface = self.descriptor.interface.parent + while interface: + descriptor = self.descriptor.getDescriptor(interface.identifier.name) + if descriptor.hasDefaultToJSON: + jsonDescriptors.append(descriptor) + interface = interface.parent + + form = """ + if !${parentclass}CollectJSONAttributes(cx, _obj, this, &result) { + return false; + } + """ + + # Iterate the array in reverse: oldest ancestor first + for descriptor in jsonDescriptors[:0:-1]: + ret += fill(form, parentclass=toBindingNamespace(descriptor.name) + "::") + ret += fill(form, parentclass="") + ret += ('(*args).rval().set(ObjectValue(*result));\n' + 'return true;\n') + return CGGeneric(ret) + + class CGStaticMethod(CGAbstractStaticBindingMethod): """ A class for generating the Rust code for an IDL static method. @@ -5653,7 +5732,8 @@ class CGInterfaceTrait(CGThing): for m in descriptor.interface.members: if (m.isMethod() and not m.isStatic() and not m.isMaplikeOrSetlikeOrIterableMethod() and - (not m.isIdentifierLess() or m.isStringifier())): + (not m.isIdentifierLess() or m.isStringifier()) and + not m.isDefaultToJSON()): name = CGSpecializedMethod.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m) for idx, (rettype, arguments) in enumerate(m.signatures()): @@ -5844,7 +5924,9 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JS_HasProperty', 'js::jsapi::JS_HasPropertyById', 'js::rust::wrappers::JS_InitializePropertiesFromCompatibleNativeObject', + 'js::jsapi::JS_NewPlainObject', 'js::jsapi::JS_NewObject', + 'js::rust::RootedGuard', 'js::rust::wrappers::JS_NewObjectWithGivenProto', 'js::rust::wrappers::JS_NewObjectWithoutMetadata', 'js::rust::wrappers::ObjectIsDate', @@ -6041,6 +6123,7 @@ class CGDescriptor(CGThing): cgThings = [] + defaultToJSONMethod = None unscopableNames = [] for m in descriptor.interface.members: if (m.isMethod() and @@ -6048,7 +6131,9 @@ class CGDescriptor(CGThing): if m.getExtendedAttribute("Unscopable"): assert not m.isStatic() unscopableNames.append(m.identifier.name) - if m.isStatic(): + if m.isDefaultToJSON(): + defaultToJSONMethod = m + elif m.isStatic(): assert descriptor.interface.hasInterfaceObject() cgThings.append(CGStaticMethod(descriptor, m)) elif not descriptor.interface.isCallback(): @@ -6082,6 +6167,10 @@ class CGDescriptor(CGThing): if (not m.isStatic() and not descriptor.interface.isCallback()): cgThings.append(CGMemberJITInfo(descriptor, m)) + if defaultToJSONMethod: + cgThings.append(CGDefaultToJSONMethod(descriptor, defaultToJSONMethod)) + cgThings.append(CGMemberJITInfo(descriptor, defaultToJSONMethod)) + if descriptor.concrete: cgThings.append(CGClassFinalizeHook(descriptor)) cgThings.append(CGClassTraceHook(descriptor)) @@ -6099,6 +6188,9 @@ class CGDescriptor(CGThing): properties = PropertyArrays(descriptor) + if defaultToJSONMethod: + cgThings.append(CGCollectJSONAttributesMethod(descriptor, defaultToJSONMethod)) + if descriptor.concrete: if descriptor.proxy: # cgThings.append(CGProxyIsProxy(descriptor)) -- cgit v1.2.3 From 87cc409579a1ccdc81da8ceecf41125a302a39bc Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 25 Jul 2019 11:14:21 +0900 Subject: use SafeJSContext --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 9700cb68191..5548bbdc07c 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2887,7 +2887,7 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): Generate the CollectJSONAttributes method for an interface descriptor """ def __init__(self, descriptor, toJSONMethod): - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', 'obj'), Argument('*const %s' % descriptor.concreteType, 'this'), Argument('&RootedGuard<*mut JSObject>', 'result')] @@ -2903,11 +2903,11 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): name = m.identifier.name getAndDefine = fill( """ - rooted!(in(cx) let mut temp = UndefinedValue()); + rooted!(in(*cx) let mut temp = UndefinedValue()); if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { return false; } - if !JS_DefineProperty(cx, result.handle().into(), + if !JS_DefineProperty(*cx, result.handle().into(), ${nameAsArray} as *const u8 as *const libc::c_char, temp.handle(), JSPROP_ENUMERATE as u32) { return false; @@ -3667,7 +3667,7 @@ class CGDefaultToJSONMethod(CGSpecializedMethod): def definition_body(self): ret = dedent(""" - rooted!(in(cx) let result = JS_NewPlainObject(cx)); + rooted!(in(*cx) let result = JS_NewPlainObject(*cx)); if result.is_null() { return false; } -- cgit v1.2.3 From bf70decdd308f24bfe58cebb8f529fbc9cd22001 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 25 Jul 2019 12:43:43 +0900 Subject: remove redundant extra scoping --- components/script/dom/bindings/codegen/CodegenRust.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 5548bbdc07c..df2f90742c9 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2901,7 +2901,7 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): for m in interface.members: if m.isAttr() and not m.isStatic() and m.type.isJSONType(): name = m.identifier.name - getAndDefine = fill( + ret += fill( """ rooted!(in(*cx) let mut temp = UndefinedValue()); if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { @@ -2914,13 +2914,6 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): } """, name=name, nameAsArray=str_to_const_array(name)) - ret += fill( - """ - { // scope for "temp" - $*{getAndDefine} - } - """, - getAndDefine=getAndDefine) ret += 'return true;\n' return CGGeneric(ret) -- cgit v1.2.3 From 410d5bc772e0ad851692efe2a2131833312d3dd0 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Thu, 25 Jul 2019 12:12:33 -0400 Subject: Update SpiderMonkey bindings for Windows arm64 crash fix. --- .../script/dom/bindings/codegen/CodegenRust.py | 29 ++++++++++++---------- 1 file changed, 16 insertions(+), 13 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 343b8e6596d..c7b2c1fe5ef 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3036,8 +3036,9 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); if aliasedMembers: def defineAlias(alias): if alias == "@@iterator": - symbolJSID = "RUST_SYMBOL_TO_JSID(GetWellKnownSymbol(*cx, SymbolCode::iterator))" - getSymbolJSID = CGGeneric(fill("rooted!(in(*cx) let iteratorId = ${symbolJSID});", + symbolJSID = "RUST_SYMBOL_TO_JSID(GetWellKnownSymbol(*cx, SymbolCode::iterator), \ + iteratorId.handle_mut())" + getSymbolJSID = CGGeneric(fill("rooted!(in(*cx) let mut iteratorId: jsid);\n${symbolJSID};\n", symbolJSID=symbolJSID)) defineFn = "JS_DefinePropertyById2" prop = "iteratorId.handle()" @@ -5197,8 +5198,9 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): body += dedent( """ for i in 0..(*unwrapped_proxy).Length() { - rooted!(in(*cx) let rooted_jsid = int_to_jsid(i as i32)); - AppendToAutoIdVector(props, rooted_jsid.handle().get()); + rooted!(in(*cx) let mut rooted_jsid: jsid); + int_to_jsid(i as i32, rooted_jsid.handle_mut()); + AppendToAutoIdVector(props, rooted_jsid.handle()); } """) @@ -5209,9 +5211,9 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): let cstring = CString::new(name).unwrap(); let jsstring = JS_AtomizeAndPinString(*cx, cstring.as_ptr()); rooted!(in(*cx) let rooted = jsstring); - let jsid = INTERNED_STRING_TO_JSID(*cx, rooted.handle().get()); - rooted!(in(*cx) let rooted_jsid = jsid); - AppendToAutoIdVector(props, rooted_jsid.handle().get()); + rooted!(in(*cx) let mut rooted_jsid: jsid); + RUST_INTERNED_STRING_TO_JSID(*cx, rooted.handle().get(), rooted_jsid.handle_mut()); + AppendToAutoIdVector(props, rooted_jsid.handle()); } """) @@ -5254,8 +5256,9 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): body += dedent( """ for i in 0..(*unwrapped_proxy).Length() { - rooted!(in(*cx) let rooted_jsid = int_to_jsid(i as i32)); - AppendToAutoIdVector(props, rooted_jsid.handle().get()); + rooted!(in(*cx) let mut rooted_jsid: jsid); + int_to_jsid(i as i32, rooted_jsid.handle_mut()); + AppendToAutoIdVector(props, rooted_jsid.handle()); } """) @@ -5800,7 +5803,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::HandleValue as RawHandleValue', 'js::jsapi::HandleValueArray', 'js::jsapi::Heap', - 'js::jsapi::INTERNED_STRING_TO_JSID', + 'js::rust::wrappers::RUST_INTERNED_STRING_TO_JSID', 'js::jsapi::IsCallable', 'js::jsapi::JSAutoRealm', 'js::jsapi::JSCLASS_FOREGROUND_FINALIZE', @@ -5884,7 +5887,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsval::PrivateValue', 'js::jsval::UndefinedValue', 'js::jsapi::UndefinedHandleValue', - 'js::glue::AppendToAutoIdVector', + 'js::rust::wrappers::AppendToAutoIdVector', 'js::glue::CallJitGetterOp', 'js::glue::CallJitMethodOp', 'js::glue::CallJitSetterOp', @@ -5895,8 +5898,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::glue::ProxyTraps', 'js::glue::RUST_JSID_IS_INT', 'js::glue::RUST_JSID_IS_STRING', - 'js::glue::RUST_SYMBOL_TO_JSID', - 'js::glue::int_to_jsid', + 'js::rust::wrappers::RUST_SYMBOL_TO_JSID', + 'js::rust::wrappers::int_to_jsid', 'js::glue::UnwrapObjectDynamic', 'js::panic::maybe_resume_unwind', 'js::panic::wrap_panic', -- cgit v1.2.3 From 0215d09ccbfed85c91605dedbb175dc9a96ba0ab Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Mon, 29 Jul 2019 18:57:20 +0200 Subject: =?UTF-8?q?Generate=20apis.html=20and=20css-properties.json=20for?= =?UTF-8?q?=20docs=20as=20part=20of=20crates=E2=80=99=20build=20scripts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit … rather than as an extra step after `cargo doc`. This helps always using the correct set of CSS properties (for layout 2013 v.s. 2020). --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c7b2c1fe5ef..72f13335ac0 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -7550,7 +7550,7 @@ impl %(base)s { def SupportedDomApis(config): descriptors = config.getDescriptors(isExposedConditionally=False) - base_path = os.path.join('dom', 'bindings', 'codegen') + base_path = os.path.dirname(__file__) with open(os.path.join(base_path, 'apis.html.template')) as f: base_template = f.read() with open(os.path.join(base_path, 'api.html.template')) as f: -- cgit v1.2.3 From c38c964f1b1d2614f50863be0b896e1700b5fea8 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Wed, 31 Jul 2019 13:34:01 +0200 Subject: Upgrade to rustc 1.38.0-nightly (dddb7fca0 2019-07-30) --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 72f13335ac0..ca041fdddeb 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -7301,9 +7301,9 @@ def process_arg(expr, arg): if arg.variadic or arg.type.isSequence(): expr += ".r()" elif arg.type.nullable() and arg.optional and not arg.defaultValue: - expr += ".as_ref().map(Option::deref)" + expr += ".as_ref().map(Option::as_deref)" elif arg.type.nullable() or arg.optional and not arg.defaultValue: - expr += ".deref()" + expr += ".as_deref()" else: expr = "&" + expr elif isinstance(arg.type, IDLPromiseType): -- cgit v1.2.3 From 51e22fbc2617dc0b8ccc98cc2b19c95c83daa652 Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 27 Jul 2019 15:20:51 +0100 Subject: Remove some usage of unsafe code in Promise --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ca041fdddeb..ef3beafb3f1 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -810,7 +810,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if !JS_WrapValue(*cx, valueToResolve.handle_mut()) { $*{exceptionCode} } - match Promise::new_resolved(&promiseGlobal, *cx, valueToResolve.handle()) { + match Promise::new_resolved(&promiseGlobal, cx, valueToResolve.handle()) { Ok(value) => value, Err(error) => { throw_dom_exception(*cx, &promiseGlobal, error); -- cgit v1.2.3 From 8968286aa17ab413c072231aaebbd21428245e3e Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 27 Jul 2019 17:05:35 +0100 Subject: Don't mark new methods as unsafe in code generation --- .../script/dom/bindings/codegen/CodegenRust.py | 30 ++++++++++++---------- 1 file changed, 16 insertions(+), 14 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ef3beafb3f1..49402ade3c7 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6355,21 +6355,23 @@ class CGDictionary(CGThing): return string.Template( "impl ${selfName} {\n" "${empty}\n" - " pub unsafe fn new(cx: SafeJSContext, val: HandleValue) \n" + " pub fn new(cx: SafeJSContext, val: HandleValue) \n" " -> Result, ()> {\n" - " let object = if val.get().is_null_or_undefined() {\n" - " ptr::null_mut()\n" - " } else if val.get().is_object() {\n" - " val.get().to_object()\n" - " } else {\n" - " return Ok(ConversionResult::Failure(\"Value is not an object.\".into()));\n" - " };\n" - " rooted!(in(*cx) let object = object);\n" + " unsafe {\n" + " let object = if val.get().is_null_or_undefined() {\n" + " ptr::null_mut()\n" + " } else if val.get().is_object() {\n" + " val.get().to_object()\n" + " } else {\n" + " return Ok(ConversionResult::Failure(\"Value is not an object.\".into()));\n" + " };\n" + " rooted!(in(*cx) let object = object);\n" "${preInitial}" "${initParent}" "${initMembers}" "${postInitial}" - " Ok(ConversionResult::Success(dictionary))\n" + " Ok(ConversionResult::Success(dictionary))\n" + " }\n" " }\n" "}\n" "\n" @@ -6391,11 +6393,11 @@ class CGDictionary(CGThing): "selfName": selfName, "actualType": actualType, "empty": CGIndenter(CGGeneric(self.makeEmpty()), indentLevel=4).define(), - "initParent": CGIndenter(CGGeneric(initParent), indentLevel=12).define(), - "initMembers": CGIndenter(memberInits, indentLevel=12).define(), + "initParent": CGIndenter(CGGeneric(initParent), indentLevel=16).define(), + "initMembers": CGIndenter(memberInits, indentLevel=16).define(), "insertMembers": CGIndenter(memberInserts, indentLevel=8).define(), - "preInitial": CGIndenter(CGGeneric(preInitial), indentLevel=12).define(), - "postInitial": CGIndenter(CGGeneric(postInitial), indentLevel=12).define(), + "preInitial": CGIndenter(CGGeneric(preInitial), indentLevel=16).define(), + "postInitial": CGIndenter(CGGeneric(postInitial), indentLevel=16).define(), }) def membersNeedTracing(self): -- cgit v1.2.3 From b18fa8b8a78a32eb578bb53e7a48de8d371702a1 Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 27 Jul 2019 17:30:36 +0100 Subject: Use safe JSContext in compartments --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 49402ade3c7..7daa7c2fd68 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3335,7 +3335,7 @@ class CGCallGenerator(CGThing): if "cx" not in argsPre and needsCx: args.prepend(CGGeneric("cx")) if nativeMethodName in descriptor.inCompartmentMethods: - args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(*cx))")) + args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(cx))")) # Build up our actual call self.cgRoot = CGList([], "\n") -- cgit v1.2.3 From 78034a90d07470d50202b01457c4e18cf7c305fb Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 27 Jul 2019 18:52:12 +0100 Subject: Use safe JSContext when possible in interface.rs --- components/script/dom/bindings/codegen/CodegenRust.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7daa7c2fd68..144a392b28d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2651,8 +2651,8 @@ def InitUnforgeablePropertiesOnHolder(descriptor, properties): """ unforgeables = [] - defineUnforgeableAttrs = "define_guarded_properties(*cx, unforgeable_holder.handle(), %s, global);" - defineUnforgeableMethods = "define_guarded_methods(*cx, unforgeable_holder.handle(), %s, global);" + defineUnforgeableAttrs = "define_guarded_properties(cx, unforgeable_holder.handle(), %s, global);" + defineUnforgeableMethods = "define_guarded_methods(cx, unforgeable_holder.handle(), %s, global);" unforgeableMembers = [ (defineUnforgeableAttrs, properties.unforgeable_attrs), @@ -2762,7 +2762,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): ("define_guarded_methods", self.properties.methods), ("define_guarded_constants", self.properties.consts) ] - members = ["%s(*cx, obj.handle(), %s, obj.handle());" % (function, array.variableName()) + members = ["%s(cx, obj.handle(), %s, obj.handle());" % (function, array.variableName()) for (function, array) in pairs if array.length() > 0] values["members"] = "\n".join(members) @@ -2772,7 +2772,7 @@ let _rt = RootedTraceable::new(&*raw); rooted!(in(*cx) let mut obj = ptr::null_mut::()); create_global_object( - *cx, + cx, &Class.base, raw as *const libc::c_void, _trace, @@ -2911,7 +2911,7 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): rooted!(in(*cx) let proto = %(proto)s); assert!(!proto.is_null()); rooted!(in(*cx) let mut namespace = ptr::null_mut::()); -create_namespace_object(*cx, global, proto.handle(), &NAMESPACE_OBJECT_CLASS, +create_namespace_object(cx, global, proto.handle(), &NAMESPACE_OBJECT_CLASS, %(methods)s, %(name)s, namespace.handle_mut()); assert!(!namespace.is_null()); assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); @@ -2924,7 +2924,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); assert not self.descriptor.interface.ctor() and self.descriptor.interface.hasConstants() return CGGeneric("""\ rooted!(in(*cx) let mut interface = ptr::null_mut::()); -create_callback_interface_object(*cx, global, sConstants, %(name)s, interface.handle_mut()); +create_callback_interface_object(cx, global, sConstants, %(name)s, interface.handle_mut()); assert!(!interface.is_null()); assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); (*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.get(); @@ -2976,7 +2976,7 @@ assert!(!prototype_proto.is_null());""" % getPrototypeProto)] code.append(CGGeneric(""" rooted!(in(*cx) let mut prototype = ptr::null_mut::()); -create_interface_prototype_object(*cx, +create_interface_prototype_object(cx, global.into(), prototype_proto.handle().into(), &PrototypeClass, @@ -3011,7 +3011,7 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); assert!(!interface_proto.is_null()); rooted!(in(*cx) let mut interface = ptr::null_mut::()); -create_noncallback_interface_object(*cx, +create_noncallback_interface_object(cx, global.into(), interface_proto.handle(), &INTERFACE_OBJECT_CLASS, @@ -3093,7 +3093,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); specs.append(CGGeneric("(%s as ConstructorClassHook, %s, %d)" % (hook, name, length))) values = CGIndenter(CGList(specs, "\n"), 4) code.append(CGWrapper(values, pre="%s = [\n" % decl, post="\n];")) - code.append(CGGeneric("create_named_constructors(*cx, global, &named_constructors, prototype.handle());")) + code.append(CGGeneric("create_named_constructors(cx, global, &named_constructors, prototype.handle());")) if self.descriptor.hasUnforgeableMembers: # We want to use the same JSClass and prototype as the object we'll -- cgit v1.2.3 From 6c26518f61f016bf2a0bac9dced9d222880fbaec Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 27 Jul 2019 19:15:38 +0100 Subject: Remove usage of various unsafe keyword --- .../script/dom/bindings/codegen/CodegenRust.py | 29 +++++++++++----------- 1 file changed, 15 insertions(+), 14 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 144a392b28d..63a72cbec9e 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2588,8 +2588,7 @@ class CGConstructorEnabled(CGAbstractMethod): CGAbstractMethod.__init__(self, descriptor, 'ConstructorEnabled', 'bool', [Argument("SafeJSContext", "aCx"), - Argument("HandleObject", "aObj")], - unsafe=True) + Argument("HandleObject", "aObj")]) def definition_body(self): conditions = [] @@ -3137,23 +3136,25 @@ class CGGetPerInterfaceObject(CGAbstractMethod): Argument('HandleObject', 'global'), Argument('MutableHandleObject', 'mut rval')] CGAbstractMethod.__init__(self, descriptor, name, - 'void', args, pub=pub, unsafe=True) + 'void', args, pub=pub) self.id = idPrefix + "::" + MakeNativeName(self.descriptor.name) def definition_body(self): return CGGeneric(""" -assert!(((*get_object_class(global.get())).flags & JSCLASS_DOM_GLOBAL) != 0); +unsafe { + assert!(((*get_object_class(global.get())).flags & JSCLASS_DOM_GLOBAL) != 0); + + /* Check to see whether the interface objects are already installed */ + let proto_or_iface_array = get_proto_or_iface_array(global.get()); + rval.set((*proto_or_iface_array)[%(id)s as usize]); + if !rval.get().is_null() { + return; + } -/* Check to see whether the interface objects are already installed */ -let proto_or_iface_array = get_proto_or_iface_array(global.get()); -rval.set((*proto_or_iface_array)[%(id)s as usize]); -if !rval.get().is_null() { - return; + CreateInterfaceObjects(cx, global, proto_or_iface_array); + rval.set((*proto_or_iface_array)[%(id)s as usize]); + assert!(!rval.get().is_null()); } - -CreateInterfaceObjects(cx, global, proto_or_iface_array); -rval.set((*proto_or_iface_array)[%(id)s as usize]); -assert!(!rval.get().is_null()); """ % {"id": self.id}) @@ -3274,7 +3275,7 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod): Argument('HandleObject', 'global'), ] CGAbstractMethod.__init__(self, descriptor, 'DefineDOMInterface', - 'void', args, pub=True, unsafe=True) + 'void', args, pub=True) def define(self): return CGAbstractMethod.define(self) -- cgit v1.2.3 From 0703a1ad6d736796d467f5a028e5ab3c6d876268 Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 27 Jul 2019 19:36:21 +0100 Subject: Use safe JSContext as first argument for throw_dom_exception --- components/script/dom/bindings/codegen/CodegenRust.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 63a72cbec9e..ea27af3b5b6 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -813,7 +813,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, match Promise::new_resolved(&promiseGlobal, cx, valueToResolve.handle()) { Ok(value) => value, Err(error) => { - throw_dom_exception(*cx, &promiseGlobal, error); + throw_dom_exception(cx, &promiseGlobal, error); $*{exceptionCode} } } @@ -3372,7 +3372,7 @@ class CGCallGenerator(CGThing): "let result = match result {\n" " Ok(result) => result,\n" " Err(e) => {\n" - " throw_dom_exception(*cx, %s, e);\n" + " throw_dom_exception(cx, %s, e);\n" " return%s;\n" " },\n" "};" % (glob, errorResult))) @@ -5556,12 +5556,12 @@ let global = DomRoot::downcast::(global).unwrap(); // so we can do the spec's object-identity checks. rooted!(in(*cx) let new_target = UnwrapObjectDynamic(args.new_target().to_object(), *cx, 1)); if new_target.is_null() { - throw_dom_exception(*cx, global.upcast::(), Error::Type("new.target is null".to_owned())); + throw_dom_exception(cx, global.upcast::(), Error::Type("new.target is null".to_owned())); return false; } if args.callee() == new_target.get() { - throw_dom_exception(*cx, global.upcast::(), + throw_dom_exception(cx, global.upcast::(), Error::Type("new.target must not be the active function object".to_owned())); return false; } @@ -5602,7 +5602,7 @@ let result: Result, Error> = html_constructor(&global, &args); let result = match result { Ok(result) => result, Err(e) => { - throw_dom_exception(*cx, global.upcast::(), e); + throw_dom_exception(cx, global.upcast::(), e); return false; }, }; -- cgit v1.2.3 From 357b6c54ff053fdd9e17832c06d7acdcbcb07991 Mon Sep 17 00:00:00 2001 From: marmeladema Date: Sat, 27 Jul 2019 20:03:16 +0100 Subject: Use safe JSContext in callbacks --- components/script/dom/bindings/codegen/CodegenRust.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ea27af3b5b6..4bea65388b6 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6828,8 +6828,8 @@ class CGCallback(CGClass): # Record the names of all the arguments, so we can use them when we call # the private method. argnames = [arg.name for arg in args] - argnamesWithThis = ["SafeJSContext::from_ptr(s.get_context())", "thisObjJS.handle()"] + argnames - argnamesWithoutThis = ["SafeJSContext::from_ptr(s.get_context())", "thisObjJS.handle()"] + argnames + argnamesWithThis = ["s.get_context()", "thisObjJS.handle()"] + argnames + argnamesWithoutThis = ["s.get_context()", "thisObjJS.handle()"] + argnames # Now that we've recorded the argnames for our call to our private # method, insert our optional argument for deciding whether the # CallSetup should re-throw exceptions on aRv. @@ -6849,7 +6849,7 @@ class CGCallback(CGClass): bodyWithThis = string.Template( setupCall + - "rooted!(in(s.get_context()) let mut thisObjJS = ptr::null_mut::());\n" + "rooted!(in(*s.get_context()) let mut thisObjJS = ptr::null_mut::());\n" "wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n" "if thisObjJS.is_null() {\n" " return Err(JSFailed);\n" @@ -6860,7 +6860,7 @@ class CGCallback(CGClass): }) bodyWithoutThis = string.Template( setupCall + - "rooted!(in(s.get_context()) let thisObjJS = ptr::null_mut::());\n" + "rooted!(in(*s.get_context()) let thisObjJS = ptr::null_mut::());\n" "unsafe { ${methodName}(${callArgs}) }").substitute({ "callArgs": ", ".join(argnamesWithoutThis), "methodName": 'self.' + method.name, @@ -7118,7 +7118,7 @@ class CallbackMember(CGNativeMember): return "" return ( "CallSetup s(CallbackPreserveColor(), aRv, aExceptionHandling);\n" - "JSContext* cx = s.get_context();\n" + "JSContext* cx = *s.get_context();\n" "if (!cx) {\n" " return Err(JSFailed);\n" "}\n") @@ -7219,7 +7219,7 @@ class CallbackOperationBase(CallbackMethod): "methodName": self.methodName } getCallableFromProp = string.Template( - 'r#try!(self.parent.get_callable_property(*cx, "${methodName}"))' + 'r#try!(self.parent.get_callable_property(cx, "${methodName}"))' ).substitute(replacements) if not self.singleOperation: return 'rooted!(in(*cx) let callable =\n' + getCallableFromProp + ');\n' -- cgit v1.2.3 From 1806b9ede2f7e2b6d621900aa841a535c03a433a Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 16 Aug 2019 21:13:29 +0900 Subject: Update WebIDL parser --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 4bea65388b6..8b4e903d909 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1576,7 +1576,7 @@ class PropertyDefiner: "Pref"), PropertyDefiner.getStringAttr(interfaceMember, "Func"), - interfaceMember.exposedSet()) + interfaceMember.exposureSet) def generateGuardedArray(self, array, name, specTemplate, specTerminator, specType, getCondition, getDataTuple): -- cgit v1.2.3 From 98e4a53b7241d562d127e0f7005ffb38f21d1380 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Fri, 16 Aug 2019 13:53:01 +0200 Subject: Upgrade to rustc 1.39.0-nightly (f7af19c27 2019-08-15) --- components/script/dom/bindings/codegen/CodegenRust.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 93856508e6e..4a8cc573416 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6384,7 +6384,7 @@ class CGDictionary(CGThing): d = self.dictionary if d.parent: initParent = ("{\n" - " match r#try!(%s::%s::new(cx, val)) {\n" + " match %s::%s::new(cx, val)? {\n" " ConversionResult::Success(v) => v,\n" " ConversionResult::Failure(error) => {\n" " throw_type_error(*cx, &error);\n" @@ -6532,7 +6532,7 @@ class CGDictionary(CGThing): conversion = ( "{\n" " rooted!(in(*cx) let mut rval = UndefinedValue());\n" - " if r#try!(get_dictionary_property(*cx, object.handle(), \"%s\", rval.handle_mut()))" + " if get_dictionary_property(*cx, object.handle(), \"%s\", rval.handle_mut())?" " && !rval.is_undefined() {\n" "%s\n" " } else {\n" @@ -7304,7 +7304,7 @@ class CallbackOperationBase(CallbackMethod): "methodName": self.methodName } getCallableFromProp = string.Template( - 'r#try!(self.parent.get_callable_property(cx, "${methodName}"))' + 'self.parent.get_callable_property(cx, "${methodName}")?' ).substitute(replacements) if not self.singleOperation: return 'rooted!(in(*cx) let callable =\n' + getCallableFromProp + ');\n' -- cgit v1.2.3 From 5695ee94a570a41d34a69b396db042922f63f516 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 29 Aug 2019 21:33:03 +0900 Subject: Add [Default] toJSON() to performance interfaces --- components/script/dom/bindings/codegen/CodegenRust.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 4a8cc573416..d5b70f6c3d7 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2049,9 +2049,10 @@ class CGImports(CGWrapper): if name != 'GlobalScope': extras += [descriptor.path] parentName = descriptor.getParentName() - if parentName: + while parentName: descriptor = descriptorProvider.getDescriptor(parentName) extras += [descriptor.path, descriptor.bindingPath] + parentName = descriptor.getParentName() elif t.isType() and t.isRecord(): extras += ['crate::dom::bindings::mozmap::MozMap'] elif isinstance(t, IDLPromiseType): @@ -3662,6 +3663,7 @@ class CGDefaultToJSONMethod(CGSpecializedMethod): def definition_body(self): ret = dedent(""" + use crate::dom::bindings::inheritance::HasParent; rooted!(in(*cx) let result = JS_NewPlainObject(*cx)); if result.is_null() { return false; @@ -3676,16 +3678,19 @@ class CGDefaultToJSONMethod(CGSpecializedMethod): jsonDescriptors.append(descriptor) interface = interface.parent + parents = len(jsonDescriptors) - 1 form = """ - if !${parentclass}CollectJSONAttributes(cx, _obj, this, &result) { + if !${parentclass}CollectJSONAttributes(cx, _obj, this${asparent}, &result) { return false; } """ # Iterate the array in reverse: oldest ancestor first for descriptor in jsonDescriptors[:0:-1]: - ret += fill(form, parentclass=toBindingNamespace(descriptor.name) + "::") - ret += fill(form, parentclass="") + ret += fill(form, parentclass=toBindingNamespace(descriptor.name) + "::", + asparent=".as_ref().unwrap()" + ".as_parent()" * parents) + parents -= 1 + ret += fill(form, parentclass="", asparent="") ret += ('(*args).rval().set(ObjectValue(*result));\n' 'return true;\n') return CGGeneric(ret) -- cgit v1.2.3 From 5149aefd856042c70ca5034adad0bcf7def67e37 Mon Sep 17 00:00:00 2001 From: Gregory Terzian Date: Thu, 5 Sep 2019 00:18:58 +0800 Subject: codegen: throw type error when encountering an unknown argument --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 4a8cc573416..46b48885c4b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -492,7 +492,7 @@ class CGMethodCall(CGThing): else: # Just throw; we have no idea what we're supposed to # do with this. - caseBody.append(CGGeneric("throw_internal_error(*cx, \"Could not convert JavaScript argument\");\n" + caseBody.append(CGGeneric("throw_type_error(*cx, \"Could not convert JavaScript argument\");\n" "return false;")) argCountCases.append(CGCase(str(argCount), -- cgit v1.2.3 From 5c60023cb8ad6f07927bd53f30c90873d07b300f Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Fri, 27 Sep 2019 06:37:54 +0200 Subject: WebIDL codegen: Replace cmake with a single Python script MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When playing around with Cargo’s new timing visualization: https://internals.rust-lang.org/t/exploring-crate-graph-build-times-with-cargo-build-ztimings/10975/21 … I was surprised to see the `script` crate’s build script take 76 seconds. I did not expect WebIDL bindings generation to be *that* computationally intensive. It turns out almost all of this time is overhead. The build script uses CMake to generate bindings for each WebIDL file in parallel, but that causes a lot of work to be repeated 366 times: * Starting up a Python VM * Importing (parts of) the Python standard library * Importing ~16k lines of our Python code * Recompiling the latter to bytecode, since we used `python -B` to disable writing `.pyc` file * Deserializing with `cPickle` and recreating in memory the results of parsing all WebIDL files ---- This commit remove the use of CMake and cPickle for the `script` crate. Instead, all WebIDL bindings generation is done sequentially in a single Python process. This takes 2 to 3 seconds. --- .../script/dom/bindings/codegen/CodegenRust.py | 26 ---------------------- 1 file changed, 26 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3cd4078814b..c02499f222f 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -54,32 +54,6 @@ RUST_KEYWORDS = {"abstract", "alignof", "as", "become", "box", "break", "const", "use", "virtual", "where", "while", "yield"} -def replaceFileIfChanged(filename, newContents): - """ - Read a copy of the old file, so that we don't touch it if it hasn't changed. - Returns True if the file was updated, false otherwise. - """ - # XXXjdm This doesn't play well with make right now. - # Force the file to always be updated, or else changing CodegenRust.py - # will cause many autogenerated bindings to be regenerated perpetually - # until the result is actually different. - - # oldFileContents = "" - # try: - # with open(filename, 'rb') as oldFile: - # oldFileContents = ''.join(oldFile.readlines()) - # except: - # pass - - # if newContents == oldFileContents: - # return False - - with open(filename, 'wb') as f: - f.write(newContents) - - return True - - def toStringBool(arg): return str(not not arg).lower() -- cgit v1.2.3 From 2660f359254e7543b7c91d14728b44ac01e438e5 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Wed, 2 Oct 2019 18:21:34 +0900 Subject: Remove [PrimaryGlobal] --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ---- 1 file changed, 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c02499f222f..103450f78f3 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -827,10 +827,6 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, elif isArgument: descriptorType = descriptor.argumentType - if descriptor.interface.isConsequential(): - raise TypeError("Consequential interface %s being used as an " - "argument" % descriptor.interface.identifier.name) - if failureCode is None: substitutions = { "sourceDescription": sourceDescription, -- cgit v1.2.3 From 764f1a3724aa73755e6021aeddbba8a465b32423 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Sat, 12 Oct 2019 18:57:05 +0900 Subject: Return false when GetPropertyKeys fails --- components/script/dom/bindings/codegen/CodegenRust.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 103450f78f3..b9b86a45a91 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5269,8 +5269,9 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): """ rooted!(in(*cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); - if !expando.is_null() { - GetPropertyKeys(*cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); + if !expando.is_null() && + !GetPropertyKeys(*cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props) { + return false; } return true; @@ -5314,8 +5315,9 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): """ rooted!(in(*cx) let mut expando = ptr::null_mut::()); get_expando_object(proxy, expando.handle_mut()); - if !expando.is_null() { - GetPropertyKeys(*cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); + if !expando.is_null() && + !GetPropertyKeys(*cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props) { + return false; } return true; -- cgit v1.2.3 From b697621b05d5c0b741d377637cb9c16ef31986b9 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Tue, 15 Oct 2019 17:14:00 +0900 Subject: Support WebIDL `record<>` --- .../script/dom/bindings/codegen/CodegenRust.py | 37 ++++++++++++++++++---- 1 file changed, 30 insertions(+), 7 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 103450f78f3..01b7fc698ba 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -77,14 +77,13 @@ def innerContainerType(type): def wrapInNativeContainerType(type, inner): if type.isSequence(): - containerType = "Vec" + return CGWrapper(inner, pre="Vec<", post=">") elif type.isRecord(): - containerType = "MozMap" + key = type.inner.keyType if type.nullable() else type.keyType + return CGRecord(key, inner) else: raise TypeError("Unexpected container type %s", type) - return CGWrapper(inner, pre=containerType + "<", post=">") - builtinNames = { IDLType.Tags.bool: 'bool', @@ -1905,6 +1904,30 @@ class CGWrapper(CGThing): return self.pre + defn + self.post +class CGRecord(CGThing): + """ + CGThing that wraps value CGThing in record with key type equal to keyType parameter + """ + def __init__(self, keyType, value): + CGThing.__init__(self) + assert keyType.isString() + self.keyType = keyType + self.value = value + + def define(self): + if self.keyType.isByteString(): + keyDef = "ByteString" + elif self.keyType.isDOMString(): + keyDef = "DOMString" + elif self.keyType.isUSVString(): + keyDef = "USVString" + else: + assert False + + defn = keyDef + ", " + self.value.define() + return "Record<" + defn + ">" + + class CGImports(CGWrapper): """ Generates the appropriate import/use statements. @@ -2024,7 +2047,7 @@ class CGImports(CGWrapper): extras += [descriptor.path, descriptor.bindingPath] parentName = descriptor.getParentName() elif t.isType() and t.isRecord(): - extras += ['crate::dom::bindings::mozmap::MozMap'] + extras += ['crate::dom::bindings::record::Record'] elif isinstance(t, IDLPromiseType): extras += ['crate::dom::promise::Promise'] else: @@ -2373,7 +2396,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::conversions::StringificationBehavior', 'crate::dom::bindings::conversions::root_from_handlevalue', 'std::ptr::NonNull', - 'crate::dom::bindings::mozmap::MozMap', + 'crate::dom::bindings::record::Record', 'crate::dom::bindings::num::Finite', 'crate::dom::bindings::root::DomRoot', 'crate::dom::bindings::str::ByteString', @@ -6054,7 +6077,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::proxyhandler::ensure_expando_object', 'crate::dom::bindings::proxyhandler::fill_property_descriptor', 'crate::dom::bindings::proxyhandler::get_expando_object', - 'crate::dom::bindings::mozmap::MozMap', + 'crate::dom::bindings::record::Record', 'std::ptr::NonNull', 'crate::dom::bindings::num::Finite', 'crate::dom::bindings::str::ByteString', -- cgit v1.2.3 From e905a4606a089055be0f87afb62c1f4ccf2961c3 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 17 Oct 2019 12:06:41 +0900 Subject: Support USVString as default value of a union argument --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 01b7fc698ba..5a6c453e0ce 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -732,6 +732,10 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, default = "%s::Boolean(%s)" % ( union_native_type(type), "true" if defaultValue.value else "false") + elif tag is IDLType.Tags.usvstring: + default = '%s::USVString(USVString("%s".to_owned()))' % ( + union_native_type(type), + defaultValue.value) else: raise("We don't currently support default values that aren't null, boolean or default dictionary") elif dictionaries: -- cgit v1.2.3 From 1c717bc086c7f464c743a8f054461b8c88b03444 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 17 Oct 2019 20:35:21 +0900 Subject: Mark @@iterator as nonenumerable --- .../script/dom/bindings/codegen/CodegenRust.py | 23 ++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 01b7fc698ba..fe436940e13 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1633,6 +1633,7 @@ class MethodDefiner(PropertyDefiner): self.regular = [{"name": m.identifier.name, "methodInfo": not m.isStatic(), "length": methodLength(m), + "flags": "JSPROP_ENUMERATE", "condition": PropertyDefiner.getControllingCondition(m, descriptor)} for m in methods] @@ -1642,6 +1643,7 @@ class MethodDefiner(PropertyDefiner): "methodInfo": False, "selfHostedName": "ArrayValues", "length": 0, + "flags": "0", # Not enumerable, per spec. "condition": "Condition::Satisfied"}) # Generate the keys/values/entries aliases for value iterables. @@ -1656,6 +1658,7 @@ class MethodDefiner(PropertyDefiner): "methodInfo": False, "selfHostedName": "ArrayKeys", "length": 0, + "flags": "JSPROP_ENUMERATE", "condition": PropertyDefiner.getControllingCondition(m, descriptor) }) @@ -1664,6 +1667,7 @@ class MethodDefiner(PropertyDefiner): "methodInfo": False, "selfHostedName": "ArrayValues", "length": 0, + "flags": "JSPROP_ENUMERATE", "condition": PropertyDefiner.getControllingCondition(m, descriptor) }) @@ -1672,6 +1676,7 @@ class MethodDefiner(PropertyDefiner): "methodInfo": False, "selfHostedName": "ArrayEntries", "length": 0, + "flags": "JSPROP_ENUMERATE", "condition": PropertyDefiner.getControllingCondition(m, descriptor) }) @@ -1680,6 +1685,7 @@ class MethodDefiner(PropertyDefiner): "methodInfo": False, "selfHostedName": "ArrayForEach", "length": 1, + "flags": "JSPROP_ENUMERATE", "condition": PropertyDefiner.getControllingCondition(m, descriptor) }) @@ -1692,6 +1698,7 @@ class MethodDefiner(PropertyDefiner): "name": "toString", "nativeName": stringifier.identifier.name, "length": 0, + "flags": "JSPROP_ENUMERATE", "condition": PropertyDefiner.getControllingCondition(stringifier, descriptor) }) self.unforgeable = unforgeable @@ -1703,13 +1710,10 @@ class MethodDefiner(PropertyDefiner): def condition(m, d): return m["condition"] - flags = "JSPROP_ENUMERATE" - if self.unforgeable: - flags += " | JSPROP_PERMANENT | JSPROP_READONLY" - def specData(m): - # TODO: Use something like JS_FNSPEC - # https://github.com/servo/servo/issues/6391 + flags = m["flags"] + if self.unforgeable: + flags += " | JSPROP_PERMANENT | JSPROP_READONLY" if "selfHostedName" in m: selfHostedName = '%s as *const u8 as *const libc::c_char' % str_to_const_array(m["selfHostedName"]) assert not m.get("methodInfo", True) @@ -3071,12 +3075,14 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); symbolJSID=symbolJSID)) defineFn = "JS_DefinePropertyById2" prop = "iteratorId.handle()" + enumFlags = "0" # Not enumerable, per spec. elif alias.startswith("@@"): raise TypeError("Can't handle any well-known Symbol other than @@iterator") else: getSymbolJSID = None defineFn = "JS_DefineProperty" prop = '"%s"' % alias + enumFlags = "JSPROP_ENUMERATE" return CGList([ getSymbolJSID, # XXX If we ever create non-enumerable properties that can @@ -3085,10 +3091,11 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); CGGeneric(fill( """ assert!(${defineFn}(*cx, prototype.handle(), ${prop}, aliasedVal.handle(), - JSPROP_ENUMERATE as u32)); + ${enumFlags} as u32)); """, defineFn=defineFn, - prop=prop)) + prop=prop, + enumFlags=enumFlags)) ], "\n") def defineAliasesFor(m): -- cgit v1.2.3 From e81b6786457b076a06c945835a3080fa33fa81ca Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 17 Oct 2019 19:41:47 +0900 Subject: Support [LegacyWindowAlias] --- .../script/dom/bindings/codegen/CodegenRust.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ad76ef5d8d3..a644e352e7a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2925,13 +2925,14 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): properties should be a PropertyArrays instance. """ - def __init__(self, descriptor, properties, haveUnscopables): + def __init__(self, descriptor, properties, haveUnscopables, haveLegacyWindowAliases): args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', 'global'), Argument('*mut ProtoOrIfaceArray', 'cache')] CGAbstractMethod.__init__(self, descriptor, 'CreateInterfaceObjects', 'void', args, unsafe=True) self.properties = properties self.haveUnscopables = haveUnscopables + self.haveLegacyWindowAliases = haveLegacyWindowAliases def definition_body(self): name = self.descriptor.interface.identifier.name @@ -2990,7 +2991,8 @@ assert!(!prototype_proto.is_null());""" % getPrototypeProto)] properties = { "id": name, - "unscopables": "unscopable_names" if self.haveUnscopables else "&[]" + "unscopables": "unscopable_names" if self.haveUnscopables else "&[]", + "legacyWindowAliases": "legacy_window_aliases" if self.haveLegacyWindowAliases else "&[]" } for arrayName in self.properties.arrayNames(): array = getattr(self.properties, arrayName) @@ -3058,6 +3060,7 @@ create_noncallback_interface_object(cx, prototype.handle(), %(name)s, %(length)s, + %(legacyWindowAliases)s, interface.handle_mut()); assert!(!interface.is_null());""" % properties)) if self.descriptor.shouldCacheConstructor(): @@ -6266,6 +6269,15 @@ class CGDescriptor(CGThing): if descriptor.weakReferenceable: cgThings.append(CGWeakReferenceableTrait(descriptor)) + legacyWindowAliases = descriptor.interface.legacyWindowAliases + haveLegacyWindowAliases = len(legacyWindowAliases) != 0 + if haveLegacyWindowAliases: + cgThings.append( + CGList([CGGeneric("const legacy_window_aliases: &'static [&'static [u8]] = &["), + CGIndenter(CGList([CGGeneric(str_to_const_array(name)) for + name in legacyWindowAliases], ",\n")), + CGGeneric("];\n")], "\n")) + cgThings.append(CGGeneric(str(properties))) if not descriptor.interface.getExtendedAttribute("Inline"): @@ -6287,7 +6299,8 @@ class CGDescriptor(CGThing): cgThings.append(CGDefineDOMInterfaceMethod(descriptor)) reexports.append('DefineDOMInterface') cgThings.append(CGConstructorEnabled(descriptor)) - cgThings.append(CGCreateInterfaceObjectsMethod(descriptor, properties, haveUnscopables)) + cgThings.append(CGCreateInterfaceObjectsMethod(descriptor, properties, haveUnscopables, + haveLegacyWindowAliases)) cgThings = generate_imports(config, CGList(cgThings, '\n'), [descriptor]) cgThings = CGWrapper(CGNamespace(toBindingNamespace(descriptor.name), @@ -7453,6 +7466,8 @@ class GlobalGenRoots(): for d in config.getDescriptors(hasInterfaceObject=True, isInline=False): binding = toBindingNamespace(d.name) pairs.append((d.name, binding, binding)) + for alias in d.interface.legacyWindowAliases: + pairs.append((alias, binding, binding)) for ctor in d.interface.namedConstructors: pairs.append((ctor.identifier.name, binding, binding)) pairs.sort(key=operator.itemgetter(0)) -- cgit v1.2.3 From 40ee701283310a505770023594f1f9d64b31e2a2 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 17 Oct 2019 16:10:39 +0900 Subject: Support enum value as a union default value --- .../script/dom/bindings/codegen/CodegenRust.py | 31 +++++++++++++++------- 1 file changed, 21 insertions(+), 10 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ad76ef5d8d3..6e75460559e 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -736,6 +736,13 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, default = '%s::USVString(USVString("%s".to_owned()))' % ( union_native_type(type), defaultValue.value) + elif defaultValue.type.isEnum(): + enum = defaultValue.type.inner.identifier.name + default = "%s::%s(%s::%s)" % ( + union_native_type(type), + enum, + enum, + getEnumValueName(defaultValue.value)) else: raise("We don't currently support default values that aren't null, boolean or default dictionary") elif dictionaries: @@ -2373,20 +2380,19 @@ def getAllTypes(descriptors, dictionaries, callbacks, typedefs): """ Generate all the types we're dealing with. For each type, a tuple containing type, descriptor, dictionary is yielded. The - descriptor and dictionary can be None if the type does not come - from a descriptor or dictionary; they will never both be non-None. + descriptor can be None if the type does not come from a descriptor. """ for d in descriptors: for t in getTypesFromDescriptor(d): - yield (t, d, None) + yield (t, d) for dictionary in dictionaries: for t in getTypesFromDictionary(dictionary): - yield (t, None, dictionary) + yield (t, None) for callback in callbacks: for t in getTypesFromCallback(callback): - yield (t, None, None) + yield (t, None) for typedef in typedefs: - yield (typedef.innerType, None, None) + yield (typedef.innerType, None) def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): @@ -2411,6 +2417,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::str::DOMString', 'crate::dom::bindings::str::USVString', 'crate::dom::bindings::trace::RootedTraceableBox', + 'crate::dom::bindings::utils::find_enum_value', 'crate::dom::types::*', 'crate::script_runtime::JSContext as SafeJSContext', 'js::error::throw_type_error', @@ -2426,13 +2433,17 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): # Now find all the things we'll need as arguments and return values because # we need to wrap or unwrap them. unionStructs = dict() - for (t, descriptor, dictionary) in getAllTypes(descriptors, dictionaries, callbacks, typedefs): - if dictionary: - imports.append("%s::%s" % (CGDictionary.makeModuleName(dictionary), - CGDictionary.makeDictionaryName(dictionary))) + for (t, descriptor) in getAllTypes(descriptors, dictionaries, callbacks, typedefs): t = t.unroll() if not t.isUnion(): continue + for memberType in t.flatMemberTypes: + if memberType.isDictionary() or memberType.isEnum(): + memberModule = getModuleFromObject(memberType) + memberName = memberType.inner.identifier.name + imports.append("%s::%s" % (memberModule, memberName)) + if memberType.isEnum(): + imports.append("%s::%sValues" % (memberModule, memberName)) name = str(t) if name not in unionStructs: provider = descriptor or config.getDescriptorProvider() -- cgit v1.2.3 From 691af0e98b95cb39a836319ecd10a35ce75b8db2 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 25 Oct 2019 15:46:52 +0900 Subject: Support stringifier attributes --- components/script/dom/bindings/codegen/CodegenRust.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index bb02119c406..86ee03d7ddd 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3667,6 +3667,8 @@ class CGSpecializedMethod(CGAbstractExternMethod): @staticmethod def makeNativeName(descriptor, method): + if method.underlyingAttr: + return CGSpecializedGetter.makeNativeName(descriptor, method.underlyingAttr) name = method.identifier.name nativeName = descriptor.binaryNameFor(name) if nativeName == name: @@ -5762,7 +5764,7 @@ class CGInterfaceTrait(CGThing): for m in descriptor.interface.members: if (m.isMethod() and not m.isStatic() and not m.isMaplikeOrSetlikeOrIterableMethod() and - (not m.isIdentifierLess() or m.isStringifier()) and + (not m.isIdentifierLess() or (m.isStringifier() and not m.underlyingAttr)) and not m.isDefaultToJSON()): name = CGSpecializedMethod.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m) @@ -6172,10 +6174,6 @@ class CGDescriptor(CGThing): cgThings.append(CGSpecializedMethod(descriptor, m)) cgThings.append(CGMemberJITInfo(descriptor, m)) elif m.isAttr(): - if m.stringifier: - raise TypeError("Stringifier attributes not supported yet. " - "See https://github.com/servo/servo/issues/7590\n" - "%s" % m.location) if m.getExtendedAttribute("Unscopable"): assert not m.isStatic() unscopableNames.append(m.identifier.name) -- cgit v1.2.3 From f8b61c031549cf9897451cadf3fb51804eaf98f7 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Sun, 3 Nov 2019 23:14:23 +0900 Subject: Use MessageEventSource on MessageEvent IDL --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 86ee03d7ddd..7841fb48b7d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -836,6 +836,8 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, descriptorType = descriptor.nativeType elif isArgument: descriptorType = descriptor.argumentType + elif descriptor.interface.identifier.name == "WindowProxy": + conversionFunction = "windowproxy_from_handlevalue" if failureCode is None: substitutions = { @@ -2409,6 +2411,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::conversions::ConversionBehavior', 'crate::dom::bindings::conversions::StringificationBehavior', 'crate::dom::bindings::conversions::root_from_handlevalue', + 'crate::dom::bindings::conversions::windowproxy_from_handlevalue', 'std::ptr::NonNull', 'crate::dom::bindings::record::Record', 'crate::dom::bindings::num::Finite', @@ -2419,6 +2422,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::trace::RootedTraceableBox', 'crate::dom::bindings::utils::find_enum_value', 'crate::dom::types::*', + 'crate::dom::windowproxy::WindowProxy', 'crate::script_runtime::JSContext as SafeJSContext', 'js::error::throw_type_error', 'js::rust::HandleValue', -- cgit v1.2.3 From 01e0b2cb5e47c28f7b85483f5ed82a09beb60bb5 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Mon, 4 Nov 2019 22:42:10 +0900 Subject: Use IDL sequence default value --- components/script/dom/bindings/codegen/CodegenRust.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 86ee03d7ddd..77c3c776c3e 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6388,8 +6388,11 @@ class CGDictionary(CGThing): def struct(self): d = self.dictionary if d.parent: - inheritance = " pub parent: %s::%s,\n" % (self.makeModuleName(d.parent), - self.makeClassName(d.parent)) + typeName = "%s::%s" % (self.makeModuleName(d.parent), + self.makeClassName(d.parent)) + if type_needs_tracing(d.parent): + typeName = "RootedTraceableBox<%s>" % typeName + inheritance = " pub parent: %s,\n" % typeName else: inheritance = "" memberDecls = [" pub %s: %s," % @@ -6520,10 +6523,7 @@ class CGDictionary(CGThing): }) def membersNeedTracing(self): - for member, _ in self.memberInfo: - if type_needs_tracing(member.type): - return True - return False + return type_needs_tracing(self.dictionary) @staticmethod def makeDictionaryName(dictionary): -- cgit v1.2.3 From 1b22c10483d6c81fe9d186c9b50523ed55d5cfff Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Tue, 5 Nov 2019 23:55:15 +0900 Subject: Use TimerHandler IDL union type --- .../script/dom/bindings/codegen/CodegenRust.py | 32 +++++++++++++++++----- 1 file changed, 25 insertions(+), 7 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 86ee03d7ddd..62e0d7935a9 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2410,6 +2410,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::conversions::StringificationBehavior', 'crate::dom::bindings::conversions::root_from_handlevalue', 'std::ptr::NonNull', + 'std::rc::Rc', 'crate::dom::bindings::record::Record', 'crate::dom::bindings::num::Finite', 'crate::dom::bindings::root::DomRoot', @@ -2423,6 +2424,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'js::error::throw_type_error', 'js::rust::HandleValue', 'js::jsapi::Heap', + 'js::jsapi::IsCallable', 'js::jsapi::JSContext', 'js::jsapi::JSObject', 'js::rust::MutableHandleValue', @@ -2438,9 +2440,10 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): if not t.isUnion(): continue for memberType in t.flatMemberTypes: - if memberType.isDictionary() or memberType.isEnum(): + if memberType.isDictionary() or memberType.isEnum() or memberType.isCallback(): memberModule = getModuleFromObject(memberType) - memberName = memberType.inner.identifier.name + memberName = (memberType.callback.identifier.name + if memberType.isCallback() else memberType.inner.identifier.name) imports.append("%s::%s" % (memberModule, memberName)) if memberType.isEnum(): imports.append("%s::%sValues" % (memberModule, memberName)) @@ -4380,6 +4383,9 @@ def getUnionTypeTemplateVars(type, descriptorProvider): elif is_typed_array(type): name = type.name typeName = "typedarray::Heap" + name + elif type.isCallback(): + name = type.name + typeName = name else: raise TypeError("Can't handle %s in unions yet" % type) @@ -4418,12 +4424,19 @@ class CGUnionStruct(CGThing): return False def define(self): + def getTypeWrapper(t): + if type_needs_tracing(t): + return "RootedTraceableBox" + if t.isCallback(): + return "Rc" + return "" + templateVars = map(lambda t: (getUnionTypeTemplateVars(t, self.descriptorProvider), - type_needs_tracing(t)), + getTypeWrapper(t)), self.type.flatMemberTypes) enumValues = [ - " %s(%s)," % (v["name"], "RootedTraceableBox<%s>" % v["typeName"] if trace else v["typeName"]) - for (v, trace) in templateVars + " %s(%s)," % (v["name"], "%s<%s>" % (wrapper, v["typeName"]) if wrapper else v["typeName"]) + for (v, wrapper) in templateVars ] enumConversions = [ " %s::%s(ref inner) => inner.to_jsval(cx, rval)," @@ -4506,7 +4519,8 @@ class CGUnionConversionStruct(CGThing): callbackMemberTypes = filter(lambda t: t.isCallback() or t.isCallbackInterface(), memberTypes) if len(callbackMemberTypes) > 0: assert len(callbackMemberTypes) == 1 - raise TypeError("Can't handle callbacks in unions.") + typeName = callbackMemberTypes[0].name + callbackObject = CGGeneric(get_match(typeName)) else: callbackObject = None @@ -4537,7 +4551,7 @@ class CGUnionConversionStruct(CGThing): else: mozMapObject = None - hasObjectTypes = object or interfaceObject or arrayObject or dateObject or mozMapObject + hasObjectTypes = object or interfaceObject or arrayObject or dateObject or callbackObject or mozMapObject if hasObjectTypes: # "object" is not distinguishable from other types assert not object or not (interfaceObject or arrayObject or dateObject or callbackObject or mozMapObject) @@ -4548,6 +4562,8 @@ class CGUnionConversionStruct(CGThing): templateBody.append(interfaceObject) if arrayObject: templateBody.append(arrayObject) + if callbackObject: + templateBody.append(callbackObject) if mozMapObject: templateBody.append(mozMapObject) conversions.append(CGIfWrapper("value.get().is_object()", templateBody)) @@ -4608,6 +4624,8 @@ class CGUnionConversionStruct(CGThing): actualType = templateVars["typeName"] if type_needs_tracing(t): actualType = "RootedTraceableBox<%s>" % actualType + if t.isCallback(): + actualType = "Rc<%s>" % actualType returnType = "Result, ()>" % actualType jsConversion = templateVars["jsConversion"] -- cgit v1.2.3 From bea73951db5a758f78842a0056daccba9d89a9c0 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Tue, 12 Nov 2019 22:16:08 +0100 Subject: Use `#![register_tool]` instead of `#![register_attr]` CC https://github.com/rust-lang/rust/issues/66079 --- components/script/dom/bindings/codegen/CodegenRust.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e660471364e..0a1df6553fa 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6406,7 +6406,7 @@ class CGDictionary(CGThing): derive = ["JSTraceable"] mustRoot = "" if self.membersNeedTracing(): - mustRoot = "#[must_root]\n" + mustRoot = "#[unrooted_must_root_lint::must_root]\n" derive += ["Default"] return (string.Template( @@ -6927,7 +6927,8 @@ class CGCallback(CGClass): bases=[ClassBase(baseName)], constructors=self.getConstructors(), methods=realMethods, - decorators="#[derive(JSTraceable, PartialEq)]\n#[allow_unrooted_interior]") + decorators="#[derive(JSTraceable, PartialEq)]\n" + "#[unrooted_must_root_lint::allow_unrooted_interior]") def getConstructors(self): return [ClassConstructor( -- cgit v1.2.3 From 22278a88953c4d7225de60e3c3c2a297273fe2d9 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Tue, 12 Nov 2019 12:04:00 +0900 Subject: Require PromiseRejectionEventInit dictionary --- components/script/dom/bindings/codegen/CodegenRust.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7610b8442b4..fe3398417b2 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6425,7 +6425,8 @@ class CGDictionary(CGThing): mustRoot = "" if self.membersNeedTracing(): mustRoot = "#[unrooted_must_root_lint::must_root]\n" - derive += ["Default"] + if not self.hasRequiredFields(self.dictionary): + derive += ["Default"] return (string.Template( "#[derive(${derive})]\n" @@ -6485,16 +6486,14 @@ class CGDictionary(CGThing): selfName = self.makeClassName(d) if self.membersNeedTracing(): actualType = "RootedTraceableBox<%s>" % selfName - preInitial = "let mut dictionary = RootedTraceableBox::new(%s::default());\n" % selfName - initParent = initParent = ("dictionary.parent = %s;\n" % initParent) if initParent else "" - memberInits = CGList([memberInit(m, False) for m in self.memberInfo]) - postInitial = "" + preInitial = "let dictionary = RootedTraceableBox::new(%s {\n" % selfName + postInitial = "});\n" else: actualType = selfName preInitial = "let dictionary = %s {\n" % selfName postInitial = "};\n" - initParent = ("parent: %s,\n" % initParent) if initParent else "" - memberInits = CGList([memberInit(m, True) for m in self.memberInfo]) + initParent = ("parent: %s,\n" % initParent) if initParent else "" + memberInits = CGList([memberInit(m, True) for m in self.memberInfo]) return string.Template( "impl ${selfName} {\n" @@ -6540,8 +6539,8 @@ class CGDictionary(CGThing): "initParent": CGIndenter(CGGeneric(initParent), indentLevel=16).define(), "initMembers": CGIndenter(memberInits, indentLevel=16).define(), "insertMembers": CGIndenter(memberInserts, indentLevel=8).define(), - "preInitial": CGIndenter(CGGeneric(preInitial), indentLevel=16).define(), - "postInitial": CGIndenter(CGGeneric(postInitial), indentLevel=16).define(), + "preInitial": CGIndenter(CGGeneric(preInitial), indentLevel=8).define(), + "postInitial": CGIndenter(CGGeneric(postInitial), indentLevel=8).define(), }) def membersNeedTracing(self): -- cgit v1.2.3 From d233558b9b2e33eaa236714a6c6c486e893a94d6 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 25 Nov 2019 16:37:48 -0800 Subject: Fix iterator invalidation in our forEach implementation. --- components/script/dom/bindings/codegen/CodegenRust.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index fe3398417b2..39e8bfa275d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -7408,7 +7408,16 @@ class CGIterableMethodGenerator(CGGeneric): rooted!(in(*cx) let mut call_arg2 = UndefinedValue()); let mut call_args = vec![UndefinedValue(), UndefinedValue(), ObjectValue(*_obj)]; rooted!(in(*cx) let mut ignoredReturnVal = UndefinedValue()); - for i in 0..(*this).get_iterable_length() { + + // This has to be a while loop since get_iterable_length() may change during + // the callback, and we need to avoid iterator invalidation. + // + // It is possible for this to loop infinitely, but that matches the spec + // and other browsers. + // + // https://heycam.github.io/webidl/#es-forEach + let mut i = 0; + while i < (*this).get_iterable_length() { (*this).get_value_at_index(i).to_jsval(*cx, call_arg1.handle_mut()); (*this).get_key_at_index(i).to_jsval(*cx, call_arg2.handle_mut()); call_args[0] = call_arg1.handle().get(); @@ -7418,6 +7427,8 @@ class CGIterableMethodGenerator(CGGeneric): ignoredReturnVal.handle_mut()) { return false; } + + i += 1; } let result = (); -- cgit v1.2.3 From 7b5fabe8552b9245a70961db9ec592a55102bb0e Mon Sep 17 00:00:00 2001 From: marmeladema Date: Tue, 10 Dec 2019 23:56:12 +0000 Subject: Fix tidiness errors for Python3 compatibility across whole repo --- components/script/dom/bindings/codegen/CodegenRust.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 39e8bfa275d..ec29a59c9d4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3943,8 +3943,8 @@ class CGMemberJITInfo(CGThing): depth=self.descriptor.interface.inheritanceDepth(), opType=opType, aliasSet=aliasSet, - returnType=reduce(CGMemberJITInfo.getSingleReturnType, returnTypes, - ""), + returnType=functools.reduce(CGMemberJITInfo.getSingleReturnType, returnTypes, + ""), isInfallible=toStringBool(infallible), isMovable=toStringBool(movable), # FIXME(nox): https://github.com/servo/servo/issues/10991 @@ -4131,8 +4131,8 @@ class CGMemberJITInfo(CGThing): if u.hasNullableType: # Might be null or not return "JSVAL_TYPE_UNKNOWN" - return reduce(CGMemberJITInfo.getSingleReturnType, - u.flatMemberTypes, "") + return functools.reduce(CGMemberJITInfo.getSingleReturnType, + u.flatMemberTypes, "") if t.isDictionary(): return "JSVAL_TYPE_OBJECT" if t.isDate(): @@ -4202,8 +4202,8 @@ class CGMemberJITInfo(CGThing): if t.isUnion(): u = t.unroll() type = "JSJitInfo::Null as i32" if u.hasNullableType else "" - return reduce(CGMemberJITInfo.getSingleArgType, - u.flatMemberTypes, type) + return functools.reduce(CGMemberJITInfo.getSingleArgType, + u.flatMemberTypes, type) if t.isDictionary(): return "JSJitInfo_ArgType::Object as i32" if t.isDate(): @@ -5858,7 +5858,7 @@ class CGInterfaceTrait(CGThing): def contains_unsafe_arg(arguments): if not arguments or len(arguments) == 0: return False - return reduce((lambda x, y: x or y[1] == '*mut JSContext'), arguments, False) + return functools.reduce((lambda x, y: x or y[1] == '*mut JSContext'), arguments, False) methods = [] for name, arguments, rettype in members(): -- cgit v1.2.3 From c1b71fcc4d842aa1df38d6ed36b73dc331508703 Mon Sep 17 00:00:00 2001 From: Patrick Shaughnessy Date: Mon, 6 Jan 2020 20:14:36 -0500 Subject: Implement HTMLSelectElement.add() and indexed setter, fix test that was relying on add to be a stub --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ec29a59c9d4..e0a5df68882 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5263,7 +5263,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + " return (*opresult).succeed();\n" + "}\n") - else: + elif self.descriptor.operations['NamedGetter']: set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + " if result.is_some() {\n" -- cgit v1.2.3 From 111ede9c77a41ab353f12683a62cd4b4dabb65da Mon Sep 17 00:00:00 2001 From: Patrick Shaughnessy Date: Mon, 6 Jan 2020 14:20:51 -0500 Subject: Make property descriptors hold named/indexed property values --- components/script/dom/bindings/codegen/CodegenRust.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ec29a59c9d4..9cdda2f3bf2 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5147,8 +5147,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): attrs = "JSPROP_ENUMERATE" if self.descriptor.operations['IndexedSetter'] is None: attrs += " | JSPROP_READONLY" - # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. - fillDescriptor = ("desc.get().value = result_root.get();\n" + fillDescriptor = ("desc.value = result_root.get();\n" "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), (%s) as u32);\n" "return true;" % attrs) templateValues = { @@ -5173,8 +5172,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): attrs = " | ".join(attrs) else: attrs = "0" - # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. - fillDescriptor = ("desc.get().value = result_root.get();\n" + fillDescriptor = ("desc.value = result_root.get();\n" "fill_property_descriptor(MutableHandle::from_raw(desc), proxy.get(), (%s) as u32);\n" "return true;" % attrs) templateValues = { @@ -5221,7 +5219,7 @@ if !expando.is_null() { } } """ + namedGet + """\ -desc.get().obj = ptr::null_mut(); +desc.obj = ptr::null_mut(); return true;""" def definition_body(self): -- cgit v1.2.3 From 5a3e1b8e6903c825e50597a218532d417f1dfef9 Mon Sep 17 00:00:00 2001 From: Kunal Mohan Date: Fri, 24 Jan 2020 13:29:09 +0530 Subject: rename compartment to realm --- .../script/dom/bindings/codegen/CodegenRust.py | 44 +++++++++++----------- 1 file changed, 22 insertions(+), 22 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index d79bc073e76..ce1487d5fa6 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -771,14 +771,14 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, # # 1) Normal call to API with a Promise argument. This is a case the # spec covers, and we should be using the current Realm's - # Promise. That means the current compartment. + # Promise. That means the current realm. # 2) Promise return value from a callback or callback interface. # This is in theory a case the spec covers but in practice it # really doesn't define behavior here because it doesn't define # what Realm we're in after the callback returns, which is when # the argument conversion happens. We will use the current - # compartment, which is the compartment of the callable (which - # may itself be a cross-compartment wrapper itself), which makes + # realm, which is the realm of the callable (which + # may itself be a cross-realm wrapper itself), which makes # as much sense as anything else. In practice, such an API would # once again be providing a Promise to signal completion of an # operation, which would then not be exposed to anyone other than @@ -3397,8 +3397,8 @@ class CGCallGenerator(CGThing): if "cx" not in argsPre and needsCx: args.prepend(CGGeneric("cx")) - if nativeMethodName in descriptor.inCompartmentMethods: - args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(cx))")) + if nativeMethodName in descriptor.inRealmMethods: + args.append(CGGeneric("InRealm::in_realm(&AlreadyInRealm::assert_for_cx(cx))")) # Build up our actual call self.cgRoot = CGList([], "\n") @@ -5671,7 +5671,7 @@ let global = DomRoot::downcast::(global).unwrap(); // Step 2 https://html.spec.whatwg.org/multipage/#htmlconstructor // The custom element definition cannot use an element interface as its constructor -// The new_target might be a cross-compartment wrapper. Get the underlying object +// The new_target might be a cross-realm wrapper. Get the underlying object // so we can do the spec's object-identity checks. rooted!(in(*cx) let new_target = UnwrapObjectDynamic(args.new_target().to_object(), *cx, 1)); if new_target.is_null() { @@ -5697,11 +5697,11 @@ rooted!(in(*cx) let mut prototype = ptr::null_mut::()); if !proto_val.is_object() { // Step 7 of https://html.spec.whatwg.org/multipage/#htmlconstructor. // This fallback behavior is designed to match analogous behavior for the - // JavaScript built-ins. So we enter the compartment of our underlying + // JavaScript built-ins. So we enter the realm of our underlying // newTarget object and fall back to the prototype object from that global. // XXX The spec says to use GetFunctionRealm(), which is not actually // the same thing as what we have here (e.g. in the case of scripted callable proxies - // whose target is not same-compartment with the proxy, or bound functions, etc). + // whose target is not same-realm with the proxy, or bound functions, etc). // https://bugzilla.mozilla.org/show_bug.cgi?id=1317658 rooted!(in(*cx) let global_object = CurrentGlobalOrNull(*cx)); @@ -5712,7 +5712,7 @@ rooted!(in(*cx) let mut prototype = ptr::null_mut::()); }; } -// Wrap prototype in this context since it is from the newTarget compartment +// Wrap prototype in this context since it is from the newTarget realm if !JS_WrapObject(*cx, prototype.handle_mut()) { return false; } @@ -5770,15 +5770,15 @@ class CGInterfaceTrait(CGThing): def __init__(self, descriptor): CGThing.__init__(self) - def attribute_arguments(needCx, argument=None, inCompartment=False): + def attribute_arguments(needCx, argument=None, inRealm=False): if needCx: yield "cx", "SafeJSContext" if argument: yield "value", argument_type(descriptor, argument) - if inCompartment: - yield "_comp", "InCompartment" + if inRealm: + yield "_comp", "InRealm" def members(): for m in descriptor.interface.members: @@ -5790,7 +5790,7 @@ class CGInterfaceTrait(CGThing): infallible = 'infallible' in descriptor.getExtendedAttributes(m) for idx, (rettype, arguments) in enumerate(m.signatures()): arguments = method_arguments(descriptor, rettype, arguments, - inCompartment=name in descriptor.inCompartmentMethods) + inRealm=name in descriptor.inRealmMethods) rettype = return_type(descriptor, rettype, infallible) yield name + ('_' * idx), arguments, rettype elif m.isAttr() and not m.isStatic(): @@ -5799,7 +5799,7 @@ class CGInterfaceTrait(CGThing): yield (name, attribute_arguments( typeNeedsCx(m.type, True), - inCompartment=name in descriptor.inCompartmentMethods + inRealm=name in descriptor.inRealmMethods ), return_type(descriptor, m.type, infallible)) @@ -5814,7 +5814,7 @@ class CGInterfaceTrait(CGThing): attribute_arguments( typeNeedsCx(m.type, False), m.type, - inCompartment=name in descriptor.inCompartmentMethods + inRealm=name in descriptor.inRealmMethods ), rettype) @@ -5831,7 +5831,7 @@ class CGInterfaceTrait(CGThing): if not rettype.nullable(): rettype = IDLNullableType(rettype.location, rettype) arguments = method_arguments(descriptor, rettype, arguments, - inCompartment=name in descriptor.inCompartmentMethods) + inRealm=name in descriptor.inRealmMethods) # If this interface 'supports named properties', then we # should be able to access 'supported property names' @@ -5842,7 +5842,7 @@ class CGInterfaceTrait(CGThing): yield "SupportedPropertyNames", [], "Vec" else: arguments = method_arguments(descriptor, rettype, arguments, - inCompartment=name in descriptor.inCompartmentMethods) + inRealm=name in descriptor.inRealmMethods) rettype = return_type(descriptor, rettype, infallible) yield name, arguments, rettype @@ -6138,8 +6138,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::windowproxy::WindowProxy', 'crate::dom::globalscope::GlobalScope', 'crate::mem::malloc_size_of_including_raw_self', - 'crate::compartments::InCompartment', - 'crate::compartments::AlreadyInCompartment', + 'crate::realms::InRealm', + 'crate::realms::AlreadyInRealm', 'crate::script_runtime::JSContext as SafeJSContext', 'libc', 'servo_config::pref', @@ -6861,7 +6861,7 @@ def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, var return declType.define() -def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None, inCompartment=False): +def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None, inRealm=False): if needCx(returnType, arguments, passJSBits): yield "cx", "SafeJSContext" @@ -6873,8 +6873,8 @@ def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, if trailing: yield trailing - if inCompartment: - yield "_comp", "InCompartment" + if inRealm: + yield "_comp", "InRealm" def return_type(descriptorProvider, rettype, infallible): -- cgit v1.2.3 From 14846d0567583d58510565c2223f81883f152262 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 17 Feb 2020 10:17:47 +0100 Subject: Introduce a new type MaybeUnreflectedDom (fixes #25701) --- .../script/dom/bindings/codegen/CodegenRust.py | 89 ++++++++++++---------- 1 file changed, 50 insertions(+), 39 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ce1487d5fa6..7f56c3b2f15 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2632,35 +2632,6 @@ class CGConstructorEnabled(CGAbstractMethod): return CGList((CGGeneric(cond) for cond in conditions), " &&\n") -def CreateBindingJSObject(descriptor): - assert not descriptor.isGlobal() - create = "let raw = Box::into_raw(object);\nlet _rt = RootedTraceable::new(&*raw);\n" - if descriptor.proxy: - create += """ -let handler = RegisterBindings::PROXY_HANDLERS[PrototypeList::Proxies::%s as usize]; -rooted!(in(*cx) let private = PrivateValue(raw as *const libc::c_void)); -let obj = NewProxyObject(*cx, handler, - Handle::from_raw(UndefinedHandleValue), - proto.get()); -assert!(!obj.is_null()); -SetProxyReservedSlot(obj, 0, &private.get()); -rooted!(in(*cx) let obj = obj);\ -""" % (descriptor.name) - else: - create += ("rooted!(in(*cx) let obj = JS_NewObjectWithGivenProto(\n" - " *cx, &Class.base as *const JSClass, proto.handle()));\n" - "assert!(!obj.is_null());\n" - "\n" - "let val = PrivateValue(raw as *const libc::c_void);\n" - "\n" - "JS_SetReservedSlot(obj.get(), DOM_OBJECT_SLOT, &val);") - if descriptor.weakReferenceable: - create += """ -let val = PrivateValue(ptr::null()); -JS_SetReservedSlot(obj.get(), DOM_WEAK_SLOT, &val);""" - return create - - def InitUnforgeablePropertiesOnHolder(descriptor, properties): """ Define the unforgeable properties on the unforgeable holder for @@ -2738,23 +2709,62 @@ class CGWrapMethod(CGAbstractMethod): def definition_body(self): unforgeable = CopyUnforgeablePropertiesToInstance(self.descriptor) - create = CreateBindingJSObject(self.descriptor) + if self.descriptor.proxy: + create = """ +let handler = RegisterBindings::PROXY_HANDLERS[PrototypeList::Proxies::%(concreteType)s as usize]; +rooted!(in(*cx) let obj = NewProxyObject( + *cx, + handler, + Handle::from_raw(UndefinedHandleValue), + proto.get(), +)); +assert!(!obj.is_null()); +SetProxyReservedSlot( + obj.get(), + 0, + &PrivateValue(&*raw as *const %(concreteType)s as *const libc::c_void), +); +""" + else: + create = """ +rooted!(in(*cx) let obj = JS_NewObjectWithGivenProto( + *cx, + &Class.base, + proto.handle(), +)); +assert!(!obj.is_null()); +JS_SetReservedSlot( + obj.get(), + DOM_OBJECT_SLOT, + &PrivateValue(&*raw as *const %(concreteType)s as *const libc::c_void), +); +""" + create = create % {"concreteType": self.descriptor.concreteType} + if self.descriptor.weakReferenceable: + create += """ +let val = PrivateValue(ptr::null()); +JS_SetReservedSlot(obj.get(), DOM_WEAK_SLOT, &val); +""" + return CGGeneric("""\ +let raw = Root::new(MaybeUnreflectedDom::from_box(object)); + let scope = scope.reflector().get_jsobject(); assert!(!scope.get().is_null()); assert!(((*get_object_class(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0); +let _ac = JSAutoRealm::new(*cx, scope.get()); rooted!(in(*cx) let mut proto = ptr::null_mut::()); -let _ac = JSAutoRealm::new(*cx, scope.get()); GetProtoObject(cx, scope, proto.handle_mut()); assert!(!proto.is_null()); %(createObject)s +raw.init_reflector(obj.get()); %(copyUnforgeable)s -(*raw).init_reflector(obj.get()); -DomRoot::from_ref(&*raw)""" % {'copyUnforgeable': unforgeable, 'createObject': create}) +DomRoot::from_ref(&*raw)\ +""" % {'copyUnforgeable': unforgeable, 'createObject': create}) class CGWrapGlobalMethod(CGAbstractMethod): @@ -2773,6 +2783,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): def definition_body(self): values = { + "concreteType": self.descriptor.concreteType, "unforgeable": CopyUnforgeablePropertiesToInstance(self.descriptor) } @@ -2786,19 +2797,18 @@ class CGWrapGlobalMethod(CGAbstractMethod): values["members"] = "\n".join(members) return CGGeneric("""\ -let raw = Box::into_raw(object); -let _rt = RootedTraceable::new(&*raw); +let raw = Root::new(MaybeUnreflectedDom::from_box(object)); rooted!(in(*cx) let mut obj = ptr::null_mut::()); create_global_object( cx, &Class.base, - raw as *const libc::c_void, + &*raw as *const %(concreteType)s as *const libc::c_void, _trace, obj.handle_mut()); assert!(!obj.is_null()); -(*raw).init_reflector(obj.get()); +raw.init_reflector(obj.get()); let _ac = JSAutoRealm::new(*cx, obj.get()); rooted!(in(*cx) let mut proto = ptr::null_mut::()); @@ -6060,8 +6070,10 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::reflector::DomObject', 'crate::dom::bindings::root::Dom', 'crate::dom::bindings::root::DomRoot', - 'crate::dom::bindings::root::OptionalHeapSetter', 'crate::dom::bindings::root::DomSlice', + 'crate::dom::bindings::root::MaybeUnreflectedDom', + 'crate::dom::bindings::root::OptionalHeapSetter', + 'crate::dom::bindings::root::Root', 'crate::dom::bindings::utils::AsVoidPtr', 'crate::dom::bindings::utils::DOMClass', 'crate::dom::bindings::utils::DOMJSClass', @@ -6086,7 +6098,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::utils::set_dictionary_property', 'crate::dom::bindings::utils::trace_global', 'crate::dom::bindings::trace::JSTraceable', - 'crate::dom::bindings::trace::RootedTraceable', 'crate::dom::bindings::trace::RootedTraceableBox', 'crate::dom::bindings::callback::CallSetup', 'crate::dom::bindings::callback::CallbackContainer', -- cgit v1.2.3 From 5a4f8cf93f9f674a164a0a3cfc586accef3d06f9 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 2 Mar 2020 11:16:46 +0100 Subject: Update SpiderMonkey --- .../script/dom/bindings/codegen/CodegenRust.py | 157 ++++++++++++--------- 1 file changed, 88 insertions(+), 69 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7f56c3b2f15..a06414c306e 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1654,7 +1654,7 @@ class MethodDefiner(PropertyDefiner): if any(m.isGetter() and m.isIndexed() for m in methods): self.regular.append({"name": '@@iterator', "methodInfo": False, - "selfHostedName": "ArrayValues", + "selfHostedName": "$ArrayValues", "length": 0, "flags": "0", # Not enumerable, per spec. "condition": "Condition::Satisfied"}) @@ -1678,7 +1678,7 @@ class MethodDefiner(PropertyDefiner): self.regular.append({ "name": "values", "methodInfo": False, - "selfHostedName": "ArrayValues", + "selfHostedName": "$ArrayValues", "length": 0, "flags": "JSPROP_ENUMERATE", "condition": PropertyDefiner.getControllingCondition(m, @@ -1731,7 +1731,7 @@ class MethodDefiner(PropertyDefiner): selfHostedName = '%s as *const u8 as *const libc::c_char' % str_to_const_array(m["selfHostedName"]) assert not m.get("methodInfo", True) accessor = "None" - jitinfo = "0 as *const JSJitInfo" + jitinfo = "ptr::null()" else: selfHostedName = "0 as *const libc::c_char" if m.get("methodInfo", True): @@ -1743,28 +1743,30 @@ class MethodDefiner(PropertyDefiner): jitinfo = "&%s_methodinfo as *const _ as *const JSJitInfo" % identifier accessor = "Some(generic_method)" else: - jitinfo = "0 as *const JSJitInfo" + jitinfo = "ptr::null()" accessor = 'Some(%s)' % m.get("nativeName", m["name"]) if m["name"].startswith("@@"): - return ('(SymbolCode::%s as i32 + 1)' - % m["name"][2:], accessor, jitinfo, m["length"], flags, selfHostedName) - return (str_to_const_array(m["name"]), accessor, jitinfo, m["length"], flags, selfHostedName) + name = 'JSPropertySpec_Name { symbol_: SymbolCode::%s as usize + 1 }' % m["name"][2:] + else: + name = ('JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char }' + % str_to_const_array(m["name"])) + return (name, accessor, jitinfo, m["length"], flags, selfHostedName) return self.generateGuardedArray( array, name, ' JSFunctionSpec {\n' - ' name: %s as *const u8 as *const libc::c_char,\n' + ' name: %s,\n' ' call: JSNativeWrapper { op: %s, info: %s },\n' ' nargs: %s,\n' ' flags: (%s) as u16,\n' ' selfHostedName: %s\n' ' }', ' JSFunctionSpec {\n' - ' name: 0 as *const libc::c_char,\n' - ' call: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo },\n' + ' name: JSPropertySpec_Name { string_: ptr::null() },\n' + ' call: JSNativeWrapper { op: None, info: ptr::null() },\n' ' nargs: 0,\n' ' flags: 0,\n' - ' selfHostedName: 0 as *const libc::c_char\n' + ' selfHostedName: ptr::null()\n' ' }', 'JSFunctionSpec', condition, specData) @@ -1834,14 +1836,14 @@ class AttrDefiner(PropertyDefiner): return self.generateGuardedArray( array, name, ' JSPropertySpec {\n' - ' name: %s as *const u8 as *const libc::c_char,\n' + ' name: JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char },\n' ' flags: (%s) as u8,\n' - ' __bindgen_anon_1: JSPropertySpec__bindgen_ty_1 {\n' - ' accessors: JSPropertySpec__bindgen_ty_1__bindgen_ty_1 {\n' - ' getter: JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {\n' + ' u: JSPropertySpec_AccessorsOrValue {\n' + ' accessors: JSPropertySpec_AccessorsOrValue_Accessors {\n' + ' getter: JSPropertySpec_Accessor {\n' ' native: %s,\n' ' },\n' - ' setter: JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_2 {\n' + ' setter: JSPropertySpec_Accessor {\n' ' native: %s,\n' ' }\n' ' }\n' @@ -2203,7 +2205,9 @@ static Class: DOMJSClass = DOMJSClass { (((%(slots)s) & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT) /* JSCLASS_HAS_RESERVED_SLOTS(%(slots)s) */, cOps: &CLASS_OPS, - reserved: [0 as *mut _; 3], + spec: ptr::null(), + ext: ptr::null(), + oOps: ptr::null(), }, dom_class: %(domClass)s }; @@ -2274,7 +2278,9 @@ static PrototypeClass: JSClass = JSClass { // JSCLASS_HAS_RESERVED_SLOTS(%(slotCount)s) (%(slotCount)s & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT, cOps: 0 as *const _, - reserved: [0 as *mut os::raw::c_void; 3] + spec: ptr::null(), + ext: ptr::null(), + oOps: ptr::null(), }; """ % {'name': name, 'slotCount': slotCount} @@ -2916,9 +2922,9 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): Generate the CollectJSONAttributes method for an interface descriptor """ def __init__(self, descriptor, toJSONMethod): - args = [Argument('SafeJSContext', 'cx'), - Argument('HandleObject', 'obj'), - Argument('*const %s' % descriptor.concreteType, 'this'), + args = [Argument('*mut JSContext', 'cx'), + Argument('RawHandleObject', 'obj'), + Argument('*mut libc::c_void', 'this'), Argument('&RootedGuard<*mut JSObject>', 'result')] CGAbstractMethod.__init__(self, descriptor, 'CollectJSONAttributes', 'bool', args, pub=True, unsafe=True) @@ -2932,11 +2938,11 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): name = m.identifier.name ret += fill( """ - rooted!(in(*cx) let mut temp = UndefinedValue()); + rooted!(in(cx) let mut temp = UndefinedValue()); if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { return false; } - if !JS_DefineProperty(*cx, result.handle().into(), + if !JS_DefineProperty(cx, result.handle().into(), ${nameAsArray} as *const u8 as *const libc::c_char, temp.handle(), JSPROP_ENUMERATE as u32) { return false; @@ -3668,8 +3674,9 @@ class CGSpecializedMethod(CGAbstractExternMethod): def __init__(self, descriptor, method): self.method = method name = method.identifier.name - args = [Argument('SafeJSContext', 'cx'), Argument('HandleObject', '_obj'), - Argument('*const %s' % descriptor.concreteType, 'this'), + args = [Argument('*mut JSContext', 'cx'), + Argument('RawHandleObject', '_obj'), + Argument('*mut libc::c_void', 'this'), Argument('*const JSJitMethodCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, 'bool', args) @@ -3678,7 +3685,8 @@ class CGSpecializedMethod(CGAbstractExternMethod): self.method) return CGWrapper(CGMethodCall([], nativeName, self.method.isStatic(), self.descriptor, self.method), - pre="let this = &*this;\n" + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType) + "let args = &*args;\n" "let argc = args.argc_;\n") @@ -3701,7 +3709,7 @@ class CGDefaultToJSONMethod(CGSpecializedMethod): def definition_body(self): ret = dedent(""" use crate::dom::bindings::inheritance::HasParent; - rooted!(in(*cx) let result = JS_NewPlainObject(*cx)); + rooted!(in(cx) let result = JS_NewPlainObject(cx)); if result.is_null() { return false; } @@ -3717,17 +3725,16 @@ class CGDefaultToJSONMethod(CGSpecializedMethod): parents = len(jsonDescriptors) - 1 form = """ - if !${parentclass}CollectJSONAttributes(cx, _obj, this${asparent}, &result) { + if !${parentclass}CollectJSONAttributes(cx, _obj, this, &result) { return false; } """ # Iterate the array in reverse: oldest ancestor first for descriptor in jsonDescriptors[:0:-1]: - ret += fill(form, parentclass=toBindingNamespace(descriptor.name) + "::", - asparent=".as_ref().unwrap()" + ".as_parent()" * parents) + ret += fill(form, parentclass=toBindingNamespace(descriptor.name) + "::") parents -= 1 - ret += fill(form, parentclass="", asparent="") + ret += fill(form, parentclass="") ret += ('(*args).rval().set(ObjectValue(*result));\n' 'return true;\n') return CGGeneric(ret) @@ -3759,9 +3766,9 @@ class CGSpecializedGetter(CGAbstractExternMethod): def __init__(self, descriptor, attr): self.attr = attr name = 'get_' + descriptor.internalNameFor(attr.identifier.name) - args = [Argument('SafeJSContext', 'cx'), - Argument('HandleObject', '_obj'), - Argument('*const %s' % descriptor.concreteType, 'this'), + args = [Argument('*mut JSContext', 'cx'), + Argument('RawHandleObject', '_obj'), + Argument('*mut libc::c_void', 'this'), Argument('JSJitGetterCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, "bool", args) @@ -3771,7 +3778,8 @@ class CGSpecializedGetter(CGAbstractExternMethod): return CGWrapper(CGGetterCall([], self.attr.type, nativeName, self.descriptor, self.attr), - pre="let this = &*this;\n") + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) @staticmethod def makeNativeName(descriptor, attr): @@ -3815,9 +3823,9 @@ class CGSpecializedSetter(CGAbstractExternMethod): def __init__(self, descriptor, attr): self.attr = attr name = 'set_' + descriptor.internalNameFor(attr.identifier.name) - args = [Argument('SafeJSContext', 'cx'), - Argument('HandleObject', 'obj'), - Argument('*const %s' % descriptor.concreteType, 'this'), + args = [Argument('*mut JSContext', 'cx'), + Argument('RawHandleObject', 'obj'), + Argument('*mut libc::c_void', 'this'), Argument('JSJitSetterCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, "bool", args) @@ -3826,7 +3834,8 @@ class CGSpecializedSetter(CGAbstractExternMethod): self.attr) return CGWrapper(CGSetterCall([], self.attr.type, nativeName, self.descriptor, self.attr), - pre="let this = &*this;\n") + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) @staticmethod def makeNativeName(descriptor, attr): @@ -3875,8 +3884,9 @@ class CGSpecializedForwardingSetter(CGSpecializedSetter): assert all(ord(c) < 128 for c in attrName) assert all(ord(c) < 128 for c in forwardToAttrName) return CGGeneric("""\ +let cx = SafeJSContext::from_ptr(cx); rooted!(in(*cx) let mut v = UndefinedValue()); -if !JS_GetProperty(*cx, obj, %s as *const u8 as *const libc::c_char, v.handle_mut()) { +if !JS_GetProperty(*cx, HandleObject::from_raw(obj), %s as *const u8 as *const libc::c_char, v.handle_mut()) { return false; } if !v.is_object() { @@ -3901,7 +3911,7 @@ class CGSpecializedReplaceableSetter(CGSpecializedSetter): # JS_DefineProperty can only deal with ASCII. assert all(ord(c) < 128 for c in name) return CGGeneric("""\ -JS_DefineProperty(*cx, obj, %s as *const u8 as *const libc::c_char, +JS_DefineProperty(cx, HandleObject::from_raw(obj), %s as *const u8 as *const libc::c_char, HandleValue::from_raw(args.get(0)), JSPROP_ENUMERATE as u32)""" % name) @@ -3931,27 +3941,34 @@ class CGMemberJITInfo(CGThing): initializer = fill( """ JSJitInfo { - call: ${opName} as *const os::raw::c_void, - protoID: PrototypeList::ID::${name} as u16, - depth: ${depth}, - _bitfield_1: new_jsjitinfo_bitfield_1!( - JSJitInfo_OpType::${opType} as u8, - JSJitInfo_AliasSet::${aliasSet} as u8, - JSValueType::${returnType} as u8, - ${isInfallible}, - ${isMovable}, - ${isEliminatable}, - ${isAlwaysInSlot}, - ${isLazilyCachedInSlot}, - ${isTypedMethod}, - ${slotIndex}, - ), + __bindgen_anon_1: JSJitInfo__bindgen_ty_1 { + ${opKind}: Some(${opName}) + }, + __bindgen_anon_2: JSJitInfo__bindgen_ty_2 { + protoID: PrototypeList::ID::${name} as u16, + }, + __bindgen_anon_3: JSJitInfo__bindgen_ty_3 { depth: ${depth} }, + _bitfield_1: unsafe { + mem::transmute(new_jsjitinfo_bitfield_1!( + JSJitInfo_OpType::${opType} as u8, + JSJitInfo_AliasSet::${aliasSet} as u8, + JSValueType::${returnType} as u8, + ${isInfallible}, + ${isMovable}, + ${isEliminatable}, + ${isAlwaysInSlot}, + ${isLazilyCachedInSlot}, + ${isTypedMethod}, + ${slotIndex}, + )) + }, } """, opName=opName, name=self.descriptor.name, depth=self.descriptor.interface.inheritanceDepth(), opType=opType, + opKind=opType.lower(), aliasSet=aliasSet, returnType=functools.reduce(CGMemberJITInfo.getSingleReturnType, returnTypes, ""), @@ -4211,7 +4228,7 @@ class CGMemberJITInfo(CGThing): return "JSJitInfo_ArgType::Object as i32" if t.isUnion(): u = t.unroll() - type = "JSJitInfo::Null as i32" if u.hasNullableType else "" + type = "JSJitInfo_ArgType::Null as i32" if u.hasNullableType else "" return functools.reduce(CGMemberJITInfo.getSingleArgType, u.flatMemberTypes, type) if t.isDictionary(): @@ -5311,7 +5328,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): def __init__(self, descriptor): args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), - Argument('*mut AutoIdVector', 'props')] + Argument('RawMutableHandleIdVector', 'props')] CGAbstractExternMethod.__init__(self, descriptor, "own_property_keys", "bool", args) self.descriptor = descriptor @@ -5328,7 +5345,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): for i in 0..(*unwrapped_proxy).Length() { rooted!(in(*cx) let mut rooted_jsid: jsid); int_to_jsid(i as i32, rooted_jsid.handle_mut()); - AppendToAutoIdVector(props, rooted_jsid.handle()); + AppendToIdVector(props, rooted_jsid.handle()); } """) @@ -5341,7 +5358,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): rooted!(in(*cx) let rooted = jsstring); rooted!(in(*cx) let mut rooted_jsid: jsid); RUST_INTERNED_STRING_TO_JSID(*cx, rooted.handle().get(), rooted_jsid.handle_mut()); - AppendToAutoIdVector(props, rooted_jsid.handle()); + AppendToIdVector(props, rooted_jsid.handle()); } """) @@ -5369,7 +5386,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties")) args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), - Argument('*mut AutoIdVector', 'props')] + Argument('RawMutableHandleIdVector', 'props')] CGAbstractExternMethod.__init__(self, descriptor, "getOwnEnumerablePropertyKeys", "bool", args) self.descriptor = descriptor @@ -5387,7 +5404,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): for i in 0..(*unwrapped_proxy).Length() { rooted!(in(*cx) let mut rooted_jsid: jsid); int_to_jsid(i as i32, rooted_jsid.handle_mut()); - AppendToAutoIdVector(props, rooted_jsid.handle()); + AppendToIdVector(props, rooted_jsid.handle()); } """) @@ -5917,11 +5934,9 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::JS_CALLEE', 'js::error::throw_type_error', 'js::error::throw_internal_error', - 'js::jsapi::AutoIdVector', 'js::rust::wrappers::Call', 'js::jsapi::CallArgs', 'js::jsapi::CurrentGlobalOrNull', - 'js::jsapi::FreeOp', 'js::rust::wrappers::GetPropertyKeys', 'js::jsapi::GetWellKnownSymbol', 'js::rust::Handle', @@ -5948,6 +5963,9 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JSITER_SYMBOLS', 'js::jsapi::JSJitGetterCallArgs', 'js::jsapi::JSJitInfo', + 'js::jsapi::JSJitInfo__bindgen_ty_1', + 'js::jsapi::JSJitInfo__bindgen_ty_2', + 'js::jsapi::JSJitInfo__bindgen_ty_3', 'js::jsapi::JSJitInfo_AliasSet', 'js::jsapi::JSJitInfo_ArgType', 'js::jsapi::JSJitInfo_OpType', @@ -5960,10 +5978,10 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JSPROP_PERMANENT', 'js::jsapi::JSPROP_READONLY', 'js::jsapi::JSPropertySpec', - 'js::jsapi::JSPropertySpec__bindgen_ty_1', - 'js::jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1', - 'js::jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1', - 'js::jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_2', + 'js::jsapi::JSPropertySpec_Accessor', + 'js::jsapi::JSPropertySpec_AccessorsOrValue', + 'js::jsapi::JSPropertySpec_AccessorsOrValue_Accessors', + 'js::jsapi::JSPropertySpec_Name', 'js::jsapi::JSString', 'js::jsapi::JSTracer', 'js::jsapi::JSType', @@ -6005,6 +6023,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::MutableHandleObject as RawMutableHandleObject', 'js::rust::MutableHandleValue', 'js::jsapi::MutableHandleValue as RawMutableHandleValue', + 'js::jsapi::MutableHandleIdVector as RawMutableHandleIdVector', 'js::jsapi::ObjectOpResult', 'js::jsapi::PropertyDescriptor', 'js::jsapi::Rooted', @@ -6020,7 +6039,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsval::PrivateValue', 'js::jsval::UndefinedValue', 'js::jsapi::UndefinedHandleValue', - 'js::rust::wrappers::AppendToAutoIdVector', + 'js::rust::wrappers::AppendToIdVector', 'js::glue::CallJitGetterOp', 'js::glue::CallJitMethodOp', 'js::glue::CallJitSetterOp', -- cgit v1.2.3 From 05077d31c8083644d004c559a4cf8423dbd48d66 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Fri, 6 Mar 2020 18:45:29 +0100 Subject: Change how we reflect DOM objects in codegen We now go through >>::reflect_with, to decrease the amount of bad stuff we can end up doing. This avoids a source of vtable pointer instability that could cause issues down the road. --- components/script/dom/bindings/codegen/CodegenRust.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index a06414c306e..f7ce60cc80c 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2728,7 +2728,7 @@ assert!(!obj.is_null()); SetProxyReservedSlot( obj.get(), 0, - &PrivateValue(&*raw as *const %(concreteType)s as *const libc::c_void), + &PrivateValue(raw.as_ptr() as *const %(concreteType)s as *const libc::c_void), ); """ else: @@ -2742,7 +2742,7 @@ assert!(!obj.is_null()); JS_SetReservedSlot( obj.get(), DOM_OBJECT_SLOT, - &PrivateValue(&*raw as *const %(concreteType)s as *const libc::c_void), + &PrivateValue(raw.as_ptr() as *const %(concreteType)s as *const libc::c_void), ); """ create = create % {"concreteType": self.descriptor.concreteType} @@ -2765,11 +2765,11 @@ GetProtoObject(cx, scope, proto.handle_mut()); assert!(!proto.is_null()); %(createObject)s -raw.init_reflector(obj.get()); +let root = raw.reflect_with(obj.get()); %(copyUnforgeable)s -DomRoot::from_ref(&*raw)\ +DomRoot::from_ref(&*root)\ """ % {'copyUnforgeable': unforgeable, 'createObject': create}) @@ -2809,12 +2809,12 @@ rooted!(in(*cx) let mut obj = ptr::null_mut::()); create_global_object( cx, &Class.base, - &*raw as *const %(concreteType)s as *const libc::c_void, + raw.as_ptr() as *const %(concreteType)s as *const libc::c_void, _trace, obj.handle_mut()); assert!(!obj.is_null()); -raw.init_reflector(obj.get()); +let root = raw.reflect_with(obj.get()); let _ac = JSAutoRealm::new(*cx, obj.get()); rooted!(in(*cx) let mut proto = ptr::null_mut::()); @@ -2828,7 +2828,7 @@ assert!(immutable); %(unforgeable)s -DomRoot::from_ref(&*raw)\ +DomRoot::from_ref(&*root)\ """ % values) -- cgit v1.2.3 From 4930479ac813775a26acc21f7175bd06d10f5647 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 14 Mar 2020 10:54:04 +0100 Subject: Update the WebIDL parser Upstream doesn't allow downloading .tar.gz archives so update.sh was changed to use unzip. --- .../script/dom/bindings/codegen/CodegenRust.py | 32 ++++------------------ 1 file changed, 5 insertions(+), 27 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index f7ce60cc80c..a9515fb099d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -427,17 +427,6 @@ class CGMethodCall(CGThing): (s[1][distinguishingIndex].type.isSequence() or s[1][distinguishingIndex].type.isObject())) - # Check for Date objects - # XXXbz Do we need to worry about security wrappers around the Date? - pickFirstSignature("%s.get().is_object() && " - "{ rooted!(in(*cx) let obj = %s.get().to_object()); " - "let mut is_date = false; " - "assert!(ObjectIsDate(*cx, obj.handle(), &mut is_date)); " - "is_date }" % - (distinguishingArg, distinguishingArg), - lambda s: (s[1][distinguishingIndex].type.isDate() or - s[1][distinguishingIndex].type.isObject())) - # Check for vanilla JS objects # XXXbz Do we need to worry about security wrappers? pickFirstSignature("%s.get().is_object() && !is_platform_object(%s.get().to_object(), *cx)" % @@ -596,8 +585,8 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, # We should not have a defaultValue if we know we're an object assert not isDefinitelyObject or defaultValue is None - isEnforceRange = type.enforceRange - isClamp = type.clamp + isEnforceRange = type.hasEnforceRange() + isClamp = type.hasClamp() if type.treatNullAsEmpty: treatNullAs = "EmptyString" else: @@ -4162,8 +4151,6 @@ class CGMemberJITInfo(CGThing): u.flatMemberTypes, "") if t.isDictionary(): return "JSVAL_TYPE_OBJECT" - if t.isDate(): - return "JSVAL_TYPE_OBJECT" if not t.isPrimitive(): raise TypeError("No idea what type " + str(t) + " is.") tag = t.tag() @@ -4233,8 +4220,6 @@ class CGMemberJITInfo(CGThing): u.flatMemberTypes, type) if t.isDictionary(): return "JSJitInfo_ArgType::Object as i32" - if t.isDate(): - return "JSJitInfo_ArgType::Object as i32" if not t.isPrimitive(): raise TypeError("No idea what type " + str(t) + " is.") tag = t.tag() @@ -4540,13 +4525,6 @@ class CGUnionConversionStruct(CGThing): else: arrayObject = None - dateObjectMemberTypes = filter(lambda t: t.isDate(), memberTypes) - if len(dateObjectMemberTypes) > 0: - assert len(dateObjectMemberTypes) == 1 - raise TypeError("Can't handle dates in unions.") - else: - dateObject = None - callbackMemberTypes = filter(lambda t: t.isCallback() or t.isCallbackInterface(), memberTypes) if len(callbackMemberTypes) > 0: assert len(callbackMemberTypes) == 1 @@ -4582,10 +4560,10 @@ class CGUnionConversionStruct(CGThing): else: mozMapObject = None - hasObjectTypes = object or interfaceObject or arrayObject or dateObject or callbackObject or mozMapObject + hasObjectTypes = object or interfaceObject or arrayObject or callbackObject or mozMapObject if hasObjectTypes: # "object" is not distinguishable from other types - assert not object or not (interfaceObject or arrayObject or dateObject or callbackObject or mozMapObject) + assert not object or not (interfaceObject or arrayObject or callbackObject or mozMapObject) templateBody = CGList([], "\n") if object: templateBody.append(object) @@ -6848,7 +6826,7 @@ def type_needs_tracing(t): def is_typed_array(t): assert isinstance(t, IDLObject), (t, type(t)) - return t.isTypedArray() or t.isArrayBuffer() or t.isArrayBufferView() or t.isSharedArrayBuffer() + return t.isTypedArray() or t.isArrayBuffer() or t.isArrayBufferView() def type_needs_auto_root(t): -- cgit v1.2.3 From 3f30c7d8be0c64d003a7e06ca044913801f2b1e0 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 14 Mar 2020 12:09:17 +0100 Subject: Do not do weird scope things in MethodDefiner Variable `m` comes from a previous list comprehension earlier in the function is not actually properly defined. --- components/script/dom/bindings/codegen/CodegenRust.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index a9515fb099d..fab5e1e713a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1654,6 +1654,8 @@ class MethodDefiner(PropertyDefiner): (maplikeOrSetlikeOrIterable and maplikeOrSetlikeOrIterable.isIterable() and maplikeOrSetlikeOrIterable.isValueIterator())): + m = maplikeOrSetlikeOrIterable + # Add our keys/values/entries/forEach self.regular.append({ "name": "keys", -- cgit v1.2.3 From 3ea6d87bcc37167464e856949a4b9b77d0e9318a Mon Sep 17 00:00:00 2001 From: YUAN LYU Date: Fri, 20 Mar 2020 22:14:18 -0400 Subject: Add trait DomObjectWrap to provide WRAP function --- .../script/dom/bindings/codegen/CodegenRust.py | 54 ++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index fab5e1e713a..8f0281be802 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2858,6 +2858,50 @@ impl PartialEq for %(name)s { """ % {'check': check, 'name': name} +class CGDomObjectWrap(CGThing): + """ + Class for codegen of an implementation of the DomObjectWrap trait. + """ + def __init__(self, descriptor): + CGThing.__init__(self) + self.descriptor = descriptor + + def define(self): + name = self.descriptor.concreteType + name = "dom::%s::%s" % (name.lower(), name) + return """\ +impl DomObjectWrap for %s { + const WRAP: unsafe fn( + SafeJSContext, + &GlobalScope, + Box, + ) -> Root> = Wrap; +} +""" % (name) + + +class CGDomObjectIteratorWrap(CGThing): + """ + Class for codegen of an implementation of the DomObjectIteratorWrap trait. + """ + def __init__(self, descriptor): + CGThing.__init__(self) + self.descriptor = descriptor + + def define(self): + assert self.descriptor.interface.isIteratorInterface() + name = self.descriptor.interface.iterableInterface.identifier.name + return """\ +impl DomObjectIteratorWrap for %s { + const ITER_WRAP: unsafe fn( + SafeJSContext, + &GlobalScope, + Box>, + ) -> Root>> = Wrap; +} +""" % (name) + + class CGAbstractExternMethod(CGAbstractMethod): """ Abstract base class for codegen of implementation-only (no @@ -6067,6 +6111,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::namespace::create_namespace_object', 'crate::dom::bindings::reflector::MutDomObject', 'crate::dom::bindings::reflector::DomObject', + 'crate::dom::bindings::reflector::DomObjectWrap', + 'crate::dom::bindings::reflector::DomObjectIteratorWrap', 'crate::dom::bindings::root::Dom', 'crate::dom::bindings::root::DomRoot', 'crate::dom::bindings::root::DomSlice', @@ -6286,6 +6332,10 @@ class CGDescriptor(CGThing): cgThings.append(CGWrapGlobalMethod(descriptor, properties)) else: cgThings.append(CGWrapMethod(descriptor)) + if descriptor.interface.isIteratorInterface(): + cgThings.append(CGDomObjectIteratorWrap(descriptor)) + else: + cgThings.append(CGDomObjectWrap(descriptor)) reexports.append('Wrap') haveUnscopables = False @@ -7445,9 +7495,7 @@ class CGIterableMethodGenerator(CGGeneric): return CGGeneric.__init__(self, fill( """ - let result = ${iterClass}::new(&*this, - IteratorType::${itrMethod}, - super::${ifaceName}IteratorBinding::Wrap); + let result = ${iterClass}::new(&*this, IteratorType::${itrMethod}); """, iterClass=iteratorNativeType(descriptor, True), ifaceName=descriptor.interface.identifier.name, -- cgit v1.2.3 From 80b2a87be718d81032a14bc96d94bb37318c31d8 Mon Sep 17 00:00:00 2001 From: Shinichi Morimoto Date: Sat, 28 Mar 2020 20:17:16 +0900 Subject: fixed #25281 --- components/script/dom/bindings/codegen/CodegenRust.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 8f0281be802..3191a7acc4d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2968,12 +2968,19 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): def definition_body(self): ret = '' interface = self.descriptor.interface + for m in interface.members: if m.isAttr() and not m.isStatic() and m.type.isJSONType(): name = m.identifier.name + conditions = MemberCondition(None, None, m.exposureSet) + ret_conditions = 'vec![' + ",".join(conditions) + "]" ret += fill( """ - rooted!(in(cx) let mut temp = UndefinedValue()); + let conditions = ${conditions}; + if !conditions.iter().any(|c| c.is_satisfied(SafeJSContext::from_ptr(cx), HandleObject::from_raw(obj), HandleObject::from_raw(obj))) { + return false; + } + rooted!(in(cx) let mut temp = UndefinedValue()); if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { return false; } @@ -2983,7 +2990,7 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): return false; } """, - name=name, nameAsArray=str_to_const_array(name)) + name=name, nameAsArray=str_to_const_array(name), conditions=ret_conditions) ret += 'return true;\n' return CGGeneric(ret) -- cgit v1.2.3 From f7d4a37f784ad8ce5d904e125167e4e4ef6a2e2a Mon Sep 17 00:00:00 2001 From: Shinichi Morimoto Date: Sat, 28 Mar 2020 23:21:35 +0900 Subject: fixed fmt --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3191a7acc4d..30c33f47077 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2977,10 +2977,14 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): ret += fill( """ let conditions = ${conditions}; - if !conditions.iter().any(|c| c.is_satisfied(SafeJSContext::from_ptr(cx), HandleObject::from_raw(obj), HandleObject::from_raw(obj))) { + if !conditions.iter().any(|c| + c.is_satisfied( + SafeJSContext::from_ptr(cx), + HandleObject::from_raw(obj), + HandleObject::from_raw(obj))) { return false; } - rooted!(in(cx) let mut temp = UndefinedValue()); + rooted!(in(cx) let mut temp = UndefinedValue()); if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { return false; } -- cgit v1.2.3 From d8c1dc60e8f48f05ecd3ec01fbc91d7743734460 Mon Sep 17 00:00:00 2001 From: Shinichi Morimoto Date: Mon, 30 Mar 2020 02:32:46 +0900 Subject: fixed is_satisfied condition --- .../script/dom/bindings/codegen/CodegenRust.py | 26 ++++++++++++---------- 1 file changed, 14 insertions(+), 12 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 30c33f47077..ed0e1223e72 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2976,22 +2976,24 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): ret_conditions = 'vec![' + ",".join(conditions) + "]" ret += fill( """ + let incumbent_global = GlobalScope::incumbent().expect("no incumbent global"); + let global = incumbent_global.reflector().get_jsobject(); let conditions = ${conditions}; - if !conditions.iter().any(|c| + let is_satisfied = conditions.iter().any(|c| c.is_satisfied( SafeJSContext::from_ptr(cx), HandleObject::from_raw(obj), - HandleObject::from_raw(obj))) { - return false; - } - rooted!(in(cx) let mut temp = UndefinedValue()); - if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { - return false; - } - if !JS_DefineProperty(cx, result.handle().into(), - ${nameAsArray} as *const u8 as *const libc::c_char, - temp.handle(), JSPROP_ENUMERATE as u32) { - return false; + global)); + if is_satisfied { + rooted!(in(cx) let mut temp = UndefinedValue()); + if !get_${name}(cx, obj, this, JSJitGetterCallArgs { _base: temp.handle_mut().into() }) { + return false; + } + if !JS_DefineProperty(cx, result.handle().into(), + ${nameAsArray} as *const u8 as *const libc::c_char, + temp.handle(), JSPROP_ENUMERATE as u32) { + return false; + } } """, name=name, nameAsArray=str_to_const_array(name), conditions=ret_conditions) -- cgit v1.2.3 From 74995a5287dc0af8afe62e9b537db5141b854765 Mon Sep 17 00:00:00 2001 From: Shinichi Morimoto Date: Tue, 31 Mar 2020 09:37:07 +0900 Subject: fixed CGCollectJSONAttributesMethod --- components/script/dom/bindings/codegen/CodegenRust.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index ed0e1223e72..96947d83ec7 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2966,18 +2966,16 @@ class CGCollectJSONAttributesMethod(CGAbstractMethod): self.toJSONMethod = toJSONMethod def definition_body(self): - ret = '' + ret = """let incumbent_global = GlobalScope::incumbent().expect("no incumbent global"); +let global = incumbent_global.reflector().get_jsobject();\n""" interface = self.descriptor.interface - for m in interface.members: if m.isAttr() and not m.isStatic() and m.type.isJSONType(): name = m.identifier.name conditions = MemberCondition(None, None, m.exposureSet) - ret_conditions = 'vec![' + ",".join(conditions) + "]" + ret_conditions = '&[' + ", ".join(conditions) + "]" ret += fill( """ - let incumbent_global = GlobalScope::incumbent().expect("no incumbent global"); - let global = incumbent_global.reflector().get_jsobject(); let conditions = ${conditions}; let is_satisfied = conditions.iter().any(|c| c.is_satisfied( -- cgit v1.2.3 From c24481ab9c9a7e7e944c91673532578f8c121e0f Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Wed, 8 Apr 2020 23:13:59 -0700 Subject: Do not filter out platform objects when doing dictionary conversions https://heycam.github.io/webidl/#es-overloads In step 12, the platform object check is for substep 4, but importantly it only matters if `V` implements the matching interface. If not, it should be able to fall back to substep 10 and attempt conversion to a dictionary. --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 96947d83ec7..d4b103cc21b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -429,8 +429,8 @@ class CGMethodCall(CGThing): # Check for vanilla JS objects # XXXbz Do we need to worry about security wrappers? - pickFirstSignature("%s.get().is_object() && !is_platform_object(%s.get().to_object(), *cx)" % - (distinguishingArg, distinguishingArg), + pickFirstSignature("%s.get().is_object()" % + distinguishingArg, lambda s: (s[1][distinguishingIndex].type.isCallback() or s[1][distinguishingIndex].type.isCallbackInterface() or s[1][distinguishingIndex].type.isDictionary() or -- cgit v1.2.3 From 10a13ffa2016cb81419ae4aa622815f8645ad7f1 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Fri, 10 Apr 2020 15:46:28 -0700 Subject: Implement FromJSValConvertible on enums --- .../script/dom/bindings/codegen/CodegenRust.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 96947d83ec7..a9642250770 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4347,8 +4347,12 @@ pub enum %s { pairs = ",\n ".join(['("%s", super::%s::%s)' % (val, ident, getEnumValueName(val)) for val in enum.values()]) inner = string.Template("""\ +use crate::dom::bindings::conversions::ConversionResult; +use crate::dom::bindings::conversions::FromJSValConvertible; use crate::dom::bindings::conversions::ToJSValConvertible; +use crate::dom::bindings::utils::find_enum_value; use js::jsapi::JSContext; +use js::rust::HandleValue; use js::rust::MutableHandleValue; use js::jsval::JSVal; @@ -4373,6 +4377,22 @@ impl ToJSValConvertible for super::${ident} { pairs[*self as usize].0.to_jsval(cx, rval); } } + +impl FromJSValConvertible for super::${ident} { + type Config = (); + unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, _option: ()) + -> Result, ()> { + match find_enum_value(cx, value, pairs) { + Err(_) => Err(()), + Ok((None, search)) => { + Ok(ConversionResult::Failure( + format!("'{}' is not a valid enum value for enumeration '${ident}'.", search).into() + )) + } + Ok((Some(&value), _)) => Ok(ConversionResult::Success(value)), + } + } +} """).substitute({ 'ident': ident, 'pairs': pairs -- cgit v1.2.3 From 242b7f8fdc58ec7388edaadc2e94bf2a110f4315 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Fri, 10 Apr 2020 16:10:14 -0700 Subject: Use FromJSValConvertible impls when converting arguments --- components/script/dom/bindings/codegen/CodegenRust.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index a9642250770..b32fcd03439 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1004,17 +1004,16 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, "yet") enum = type.inner.identifier.name if invalidEnumValueFatal: - handleInvalidEnumValueCode = onFailureInvalidEnumValue(failureCode, 'search').define() + handleInvalidEnumValueCode = failureCode or "throw_type_error(*cx, &error); %s" % exceptionCode else: handleInvalidEnumValueCode = "return true;" template = ( - "match find_enum_value(*cx, ${val}, %(pairs)s) {\n" + "match FromJSValConvertible::from_jsval(*cx, ${val}, ()) {" " Err(_) => { %(exceptionCode)s },\n" - " Ok((None, search)) => { %(handleInvalidEnumValueCode)s },\n" - " Ok((Some(&value), _)) => value,\n" - "}" % {"pairs": enum + "Values::pairs", - "exceptionCode": exceptionCode, + " Ok(ConversionResult::Success(v)) => v,\n" + " Ok(ConversionResult::Failure(error)) => { %(handleInvalidEnumValueCode)s },\n" + "}" % {"exceptionCode": exceptionCode, "handleInvalidEnumValueCode": handleInvalidEnumValueCode}) if defaultValue is not None: @@ -2418,7 +2417,6 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'crate::dom::bindings::str::DOMString', 'crate::dom::bindings::str::USVString', 'crate::dom::bindings::trace::RootedTraceableBox', - 'crate::dom::bindings::utils::find_enum_value', 'crate::dom::types::*', 'crate::dom::windowproxy::WindowProxy', 'crate::script_runtime::JSContext as SafeJSContext', @@ -6158,7 +6156,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::utils::ProtoOrIfaceArray', 'crate::dom::bindings::utils::enumerate_global', 'crate::dom::bindings::utils::finalize_global', - 'crate::dom::bindings::utils::find_enum_value', 'crate::dom::bindings::utils::generic_getter', 'crate::dom::bindings::utils::generic_lenient_getter', 'crate::dom::bindings::utils::generic_lenient_setter', -- cgit v1.2.3 From 6175a68c102218d0de18b67343ad14cfc193b18d Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Wed, 15 Apr 2020 17:54:04 +0200 Subject: Replace a `transmute` with `.to_ne_bytes()` + constructor --- components/script/dom/bindings/codegen/CodegenRust.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3c9555ba659..021757a4ad1 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3992,8 +3992,8 @@ class CGMemberJITInfo(CGThing): protoID: PrototypeList::ID::${name} as u16, }, __bindgen_anon_3: JSJitInfo__bindgen_ty_3 { depth: ${depth} }, - _bitfield_1: unsafe { - mem::transmute(new_jsjitinfo_bitfield_1!( + _bitfield_1: __BindgenBitfieldUnit::new( + new_jsjitinfo_bitfield_1!( JSJitInfo_OpType::${opType} as u8, JSJitInfo_AliasSet::${aliasSet} as u8, JSValueType::${returnType} as u8, @@ -4004,8 +4004,8 @@ class CGMemberJITInfo(CGThing): ${isLazilyCachedInSlot}, ${isTypedMethod}, ${slotIndex}, - )) - }, + ).to_ne_bytes() + ), } """, opName=opName, @@ -5988,6 +5988,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::error::throw_type_error', 'js::error::throw_internal_error', 'js::rust::wrappers::Call', + 'js::jsapi::__BindgenBitfieldUnit', 'js::jsapi::CallArgs', 'js::jsapi::CurrentGlobalOrNull', 'js::rust::wrappers::GetPropertyKeys', -- cgit v1.2.3 From d103e06ba945030d2e5bfdb5a9f0f4b848cbf274 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Mon, 25 May 2020 20:29:18 +0200 Subject: Use dynamic dispatch in `mozjs::panic::wrap_panic` Pick up https://github.com/servo/rust-mozjs/pull/512 Fixes https://github.com/servo/servo/issues/26585 This diff is best viewed with "ignore whitespace changes", because of indentation change. --- components/script/dom/bindings/codegen/CodegenRust.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 021757a4ad1..d4ded28f397 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2573,9 +2573,19 @@ class CGAbstractMethod(CGThing): body = self.definition_body() if self.catchPanic: - body = CGWrapper(CGIndenter(body), - pre="return wrap_panic(panic::AssertUnwindSafe(|| {\n", - post=("""\n}), %s);""" % ("()" if self.returnType == "void" else "false"))) + if self.returnType == "void": + pre = "wrap_panic(&mut || {\n" + post = "\n})" + else: + pre = ( + "let mut result = false;\n" + "wrap_panic(&mut || result = (|| {\n" + ) + post = ( + "\n})());\n" + "return result" + ) + body = CGWrapper(CGIndenter(body), pre=pre, post=post) return CGWrapper(CGIndenter(body), pre=self.definition_prologue(), -- cgit v1.2.3 From c4f8167b6fa0d01c60deb9bb491a3565173db961 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Fri, 29 May 2020 15:16:55 -0400 Subject: dom: Improve precision of sequence types for WebIDL codegen. --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 021757a4ad1..9247a0c0243 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -677,7 +677,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type.isSequence() or type.isRecord(): innerInfo = getJSToNativeConversionInfo(innerContainerType(type), descriptorProvider, - isMember=isMember, + isMember="Sequence", isAutoRooted=isAutoRooted) declType = wrapInNativeContainerType(type, innerInfo.declType) config = getConversionConfigForType(type, isEnforceRange, isClamp, treatNullAs) @@ -1075,7 +1075,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, assert not isEnforceRange and not isClamp assert isMember != "Union" - if isMember == "Dictionary" or isAutoRooted: + if isMember in ("Dictionary", "Sequence") or isAutoRooted: templateBody = "${val}.get()" if defaultValue is None: @@ -1087,7 +1087,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, else: raise TypeError("Can't handle non-null, non-undefined default value here") - if isMember == "Dictionary": + if not isAutoRooted: templateBody = "RootedTraceableBox::from_box(Heap::boxed(%s))" % templateBody if default is not None: default = "RootedTraceableBox::from_box(Heap::boxed(%s))" % default @@ -1117,7 +1117,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, templateBody = "${val}.get().to_object()" default = "ptr::null_mut()" - if isMember in ("Dictionary", "Union"): + if isMember in ("Dictionary", "Union", "Sequence") and not isAutoRooted: templateBody = "RootedTraceableBox::from_box(Heap::boxed(%s))" % templateBody default = "RootedTraceableBox::new(Heap::default())" declType = CGGeneric("RootedTraceableBox>") -- cgit v1.2.3 From f014f15d4eaeb52e38faee15dc9a4d0f700d1d7c Mon Sep 17 00:00:00 2001 From: Kunal Mohan Date: Fri, 29 May 2020 19:46:35 +0530 Subject: Allow sequence of nullable dictionary items in webidl of type "sequence x" --- components/script/dom/bindings/codegen/CodegenRust.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 597e5611f74..de97e2c9ea9 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1134,7 +1134,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if type.isDictionary(): # There are no nullable dictionaries - assert not type.nullable() + assert not type.nullable() or (isMember and isMember != "Dictionary") typeName = "%s::%s" % (CGDictionary.makeModuleName(type.inner), CGDictionary.makeDictionaryName(type.inner)) @@ -6645,7 +6645,10 @@ class CGDictionary(CGThing): @staticmethod def makeDictionaryName(dictionary): - return dictionary.identifier.name + if isinstance(dictionary, IDLWrapperType): + return CGDictionary.makeDictionaryName(dictionary.inner) + else: + return dictionary.identifier.name def makeClassName(self, dictionary): return self.makeDictionaryName(dictionary) -- cgit v1.2.3 From d9db350df528628b1f7f2f1da711fc2da790ec49 Mon Sep 17 00:00:00 2001 From: Kunal Mohan Date: Mon, 1 Jun 2020 19:19:41 +0530 Subject: Improve webidl precision Allow enum variants staring with digit --- .../script/dom/bindings/codegen/CodegenRust.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index de97e2c9ea9..8c7eb3e7400 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4328,7 +4328,7 @@ def getEnumValueName(value): if re.match("[^\x20-\x7E]", value): raise SyntaxError('Enum value "' + value + '" contains non-ASCII characters') if re.match("^[0-9]", value): - raise SyntaxError('Enum value "' + value + '" starts with a digit') + value = '_' + value value = re.sub(r'[^0-9A-Za-z_]', '_', value) if re.match("^_[A-Z]|__", value): raise SyntaxError('Enum value "' + value + '" is reserved by the C++ spec') @@ -4650,20 +4650,24 @@ class CGUnionConversionStruct(CGThing): # "object" is not distinguishable from other types assert not object or not (interfaceObject or arrayObject or callbackObject or mozMapObject) templateBody = CGList([], "\n") - if object: - templateBody.append(object) + if arrayObject or callbackObject: + # An object can be both an sequence object and a callback or + # dictionary, but we shouldn't have both in the union's members + # because they are not distinguishable. + assert not (arrayObject and callbackObject) + templateBody.append(arrayObject if arrayObject else callbackObject) if interfaceObject: + assert not object templateBody.append(interfaceObject) - if arrayObject: - templateBody.append(arrayObject) - if callbackObject: - templateBody.append(callbackObject) + elif object: + templateBody.append(object) if mozMapObject: templateBody.append(mozMapObject) + conversions.append(CGIfWrapper("value.get().is_object()", templateBody)) if dictionaryObject: - assert not hasObjectTypes + assert not object conversions.append(dictionaryObject) stringTypes = [t for t in memberTypes if t.isString() or t.isEnum()] -- cgit v1.2.3 From 2da07ed164b71c679813b4c319a6e069a2910b25 Mon Sep 17 00:00:00 2001 From: Warren Fisher Date: Tue, 14 Jan 2020 19:21:08 -0400 Subject: Reduce code duplication. Move some of CodegenRust.py to htmlconstructor.rs --- .../script/dom/bindings/codegen/CodegenRust.py | 76 ++-------------------- 1 file changed, 6 insertions(+), 70 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 021757a4ad1..47c7e925cb6 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5747,75 +5747,12 @@ let global = DomRoot::downcast::(global).unwrap(); if self.constructor.isHTMLConstructor(): signatures = self.constructor.signatures() assert len(signatures) == 1 - constructorCall = CGGeneric("""\ -// Step 2 https://html.spec.whatwg.org/multipage/#htmlconstructor -// The custom element definition cannot use an element interface as its constructor - -// The new_target might be a cross-realm wrapper. Get the underlying object -// so we can do the spec's object-identity checks. -rooted!(in(*cx) let new_target = UnwrapObjectDynamic(args.new_target().to_object(), *cx, 1)); -if new_target.is_null() { - throw_dom_exception(cx, global.upcast::(), Error::Type("new.target is null".to_owned())); - return false; -} - -if args.callee() == new_target.get() { - throw_dom_exception(cx, global.upcast::(), - Error::Type("new.target must not be the active function object".to_owned())); - return false; -} - -// Step 6 -rooted!(in(*cx) let mut prototype = ptr::null_mut::()); -{ - rooted!(in(*cx) let mut proto_val = UndefinedValue()); - let _ac = JSAutoRealm::new(*cx, new_target.get()); - if !JS_GetProperty(*cx, new_target.handle(), b"prototype\\0".as_ptr() as *const _, proto_val.handle_mut()) { - return false; - } - - if !proto_val.is_object() { - // Step 7 of https://html.spec.whatwg.org/multipage/#htmlconstructor. - // This fallback behavior is designed to match analogous behavior for the - // JavaScript built-ins. So we enter the realm of our underlying - // newTarget object and fall back to the prototype object from that global. - // XXX The spec says to use GetFunctionRealm(), which is not actually - // the same thing as what we have here (e.g. in the case of scripted callable proxies - // whose target is not same-realm with the proxy, or bound functions, etc). - // https://bugzilla.mozilla.org/show_bug.cgi?id=1317658 - - rooted!(in(*cx) let global_object = CurrentGlobalOrNull(*cx)); - GetProtoObject(cx, global_object.handle(), prototype.handle_mut()); - } else { - // Step 6 - prototype.set(proto_val.to_object()); - }; -} - -// Wrap prototype in this context since it is from the newTarget realm -if !JS_WrapObject(*cx, prototype.handle_mut()) { - return false; -} - -let result: Result, Error> = html_constructor(&global, &args); -let result = match result { - Ok(result) => result, - Err(e) => { - throw_dom_exception(cx, global.upcast::(), e); - return false; - }, -}; - -rooted!(in(*cx) let mut element = result.reflector().get_jsobject().get()); -if !JS_WrapObject(*cx, element.handle_mut()) { - return false; -} - -JS_SetPrototype(*cx, element.handle(), prototype.handle()); - -(result).to_jsval(*cx, MutableHandleValue::from_raw(args.rval())); -return true; -""" % self.descriptor.name) + constructorCall = CGGeneric("""dom::bindings::htmlconstructor::call_html_constructor::( + cx, + &args, + &*global, + GetProtoObject, + )""" % self.descriptor.name) else: name = self.constructor.identifier.name nativeName = MakeNativeName(self.descriptor.binaryNameFor(name)) @@ -6131,7 +6068,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::interface::define_guarded_constants', 'crate::dom::bindings::interface::define_guarded_methods', 'crate::dom::bindings::interface::define_guarded_properties', - 'crate::dom::bindings::htmlconstructor::html_constructor', 'crate::dom::bindings::interface::is_exposed_in', 'crate::dom::bindings::htmlconstructor::pop_current_element_queue', 'crate::dom::bindings::htmlconstructor::push_new_element_queue', -- cgit v1.2.3 From bd5796c90b8e8e066a32e7da9cfa5251d1559046 Mon Sep 17 00:00:00 2001 From: Gregory Terzian Date: Sat, 29 Feb 2020 11:59:10 +0800 Subject: integrate readablestream with fetch and blob --- .../script/dom/bindings/codegen/CodegenRust.py | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b486806e562..0b1187a07fb 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -906,6 +906,40 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, return handleOptional(templateBody, declType, handleDefault("None")) + if type.isReadableStream(): + assert not isEnforceRange and not isClamp + + if failureCode is None: + unwrapFailureCode = '''throw_type_error(*cx, "This object is not \ + an instance of ReadableStream.");\n''' + else: + unwrapFailureCode = failureCode + + templateBody = fill( + """ + { + use crate::realms::{AlreadyInRealm, InRealm}; + let in_realm_proof = AlreadyInRealm::assert_for_cx(cx); + match ReadableStream::from_js(cx, $${val}.get().to_object(), InRealm::Already(&in_realm_proof)) { + Ok(val) => val, + Err(()) => { + $*{failureCode} + } + } + + } + """, + failureCode=unwrapFailureCode + "\n", + ) + + templateBody = wrapObjectTemplate(templateBody, "None", + isDefinitelyObject, type, failureCode) + + declType = CGGeneric("DomRoot") + + return handleOptional(templateBody, declType, + handleDefault("None")) + elif type.isSpiderMonkeyInterface(): raise TypeError("Can't handle SpiderMonkey interface arguments other than typed arrays yet") @@ -4481,6 +4515,9 @@ def getUnionTypeTemplateVars(type, descriptorProvider): elif type.isObject(): name = type.name typeName = "Heap<*mut JSObject>" + elif type.isReadableStream(): + name = type.name + typeName = "DomRoot" elif is_typed_array(type): name = type.name typeName = "typedarray::Heap" + name -- cgit v1.2.3 From 3367db6067a8d76061e7884e54cc61ce44012442 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Fri, 5 Jun 2020 00:04:47 +0200 Subject: Keep DOM proxy handlers as separate named items rather than in one array --- .../script/dom/bindings/codegen/CodegenRust.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 0b1187a07fb..5440884ab16 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2750,7 +2750,7 @@ class CGWrapMethod(CGAbstractMethod): unforgeable = CopyUnforgeablePropertiesToInstance(self.descriptor) if self.descriptor.proxy: create = """ -let handler = RegisterBindings::PROXY_HANDLERS[PrototypeList::Proxies::%(concreteType)s as usize]; +let handler = RegisterBindings::proxy_handlers::%(concreteType)s; rooted!(in(*cx) let obj = NewProxyObject( *cx, handler, @@ -6744,7 +6744,7 @@ class CGRegisterProxyHandlersMethod(CGAbstractMethod): def definition_body(self): return CGList([ - CGGeneric("PROXY_HANDLERS[Proxies::%s as usize] = Bindings::%s::DefineProxyHandler();" + CGGeneric("proxy_handlers::%s = Bindings::%s::DefineProxyHandler();" % (desc.name, '::'.join([desc.name + 'Binding'] * 2))) for desc in self.descriptors ], "\n") @@ -6753,10 +6753,17 @@ class CGRegisterProxyHandlersMethod(CGAbstractMethod): class CGRegisterProxyHandlers(CGThing): def __init__(self, config): descriptors = config.getDescriptors(proxy=True) - length = len(descriptors) self.root = CGList([ - CGGeneric("pub static mut PROXY_HANDLERS: [*const libc::c_void; %d] = [0 as *const libc::c_void; %d];" - % (length, length)), + CGGeneric( + "#[allow(non_upper_case_globals)]\n" + + "pub mod proxy_handlers {\n" + + "".join( + " pub static mut %s: *const libc::c_void = std::ptr::null();\n" + % desc.name + for desc in descriptors + ) + + "}\n" + ), CGRegisterProxyHandlersMethod(descriptors), ], "\n") @@ -7606,8 +7613,6 @@ class GlobalGenRoots(): for d in config.getDescriptors(hasInterfaceObject=True) if d.shouldHaveGetConstructorObjectMethod()]) - proxies = [d.name for d in config.getDescriptors(proxy=True)] - return CGList([ CGGeneric(AUTOGENERATED_WARNING_COMMENT), CGGeneric("pub const PROTO_OR_IFACE_LENGTH: usize = %d;\n" % (len(protos) + len(constructors))), @@ -7624,7 +7629,6 @@ class GlobalGenRoots(): " debug_assert!(proto_id < ID::Last as u16);\n" " INTERFACES[proto_id as usize]\n" "}\n\n"), - CGNonNamespacedEnum('Proxies', proxies, 0, deriving="PartialEq, Copy, Clone"), ]) @staticmethod @@ -7636,8 +7640,6 @@ class GlobalGenRoots(): return CGImports(code, descriptors=[], callbacks=[], dictionaries=[], enums=[], typedefs=[], imports=[ 'crate::dom::bindings::codegen::Bindings', - 'crate::dom::bindings::codegen::PrototypeList::Proxies', - 'libc', ], config=config, ignored_warnings=[]) @staticmethod -- cgit v1.2.3 From 57d89675b01b49c573b14c1fd0be413d52b8ccdd Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Fri, 5 Jun 2020 00:10:14 +0200 Subject: Use atomic pointers instead of `static mut` for DOM proxy handlers --- components/script/dom/bindings/codegen/CodegenRust.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 5440884ab16..b0361d6ca47 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2750,7 +2750,9 @@ class CGWrapMethod(CGAbstractMethod): unforgeable = CopyUnforgeablePropertiesToInstance(self.descriptor) if self.descriptor.proxy: create = """ -let handler = RegisterBindings::proxy_handlers::%(concreteType)s; +let handler: *const libc::c_void = + RegisterBindings::proxy_handlers::%(concreteType)s + .load(std::sync::atomic::Ordering::Acquire); rooted!(in(*cx) let obj = NewProxyObject( *cx, handler, @@ -6744,7 +6746,10 @@ class CGRegisterProxyHandlersMethod(CGAbstractMethod): def definition_body(self): return CGList([ - CGGeneric("proxy_handlers::%s = Bindings::%s::DefineProxyHandler();" + CGGeneric("proxy_handlers::%s.store(\n" + " Bindings::%s::DefineProxyHandler() as *mut _,\n" + " std::sync::atomic::Ordering::Release,\n" + ");" % (desc.name, '::'.join([desc.name + 'Binding'] * 2))) for desc in self.descriptors ], "\n") @@ -6758,7 +6763,8 @@ class CGRegisterProxyHandlers(CGThing): "#[allow(non_upper_case_globals)]\n" + "pub mod proxy_handlers {\n" + "".join( - " pub static mut %s: *const libc::c_void = std::ptr::null();\n" + " pub static %s: std::sync::atomic::AtomicPtr =\n" + " std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());\n" % desc.name for desc in descriptors ) + -- cgit v1.2.3 From edf86d1bdcd501fc0f3c024f7296fbb3540cdfa6 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Mon, 15 Jun 2020 17:27:47 -0400 Subject: dom: Convert parent dictionary values when converting dictionaries to JS. --- components/script/dom/bindings/codegen/CodegenRust.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b0361d6ca47..1f0e09639c8 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6557,7 +6557,10 @@ class CGDictionary(CGThing): (name, name, varInsert(name, member.identifier.name).define())) return CGGeneric("%s\n" % insertion.define()) - memberInserts = CGList([memberInsert(m) for m in self.memberInfo]) + memberInserts = [memberInsert(m) for m in self.memberInfo] + + if d.parent: + memberInserts = [CGGeneric("self.parent.to_jsobject(cx, obj);\n")] + memberInserts selfName = self.makeClassName(d) if self.membersNeedTracing(): @@ -6602,10 +6605,16 @@ class CGDictionary(CGThing): " }\n" "}\n" "\n" + "impl ${selfName} {\n" + " pub(crate) unsafe fn to_jsobject(&self, cx: *mut JSContext, mut obj: MutableHandleObject) {\n" + "${insertMembers}" + " }\n" + "}\n" + "\n" "impl ToJSValConvertible for ${selfName} {\n" " unsafe fn to_jsval(&self, cx: *mut JSContext, mut rval: MutableHandleValue) {\n" - " rooted!(in(cx) let obj = JS_NewObject(cx, ptr::null()));\n" - "${insertMembers}" + " rooted!(in(cx) let mut obj = JS_NewObject(cx, ptr::null()));\n" + " self.to_jsobject(cx, obj.handle_mut());\n" " rval.set(ObjectOrNullValue(obj.get()))\n" " }\n" "}\n").substitute({ @@ -6614,7 +6623,7 @@ class CGDictionary(CGThing): "empty": CGIndenter(CGGeneric(self.makeEmpty()), indentLevel=4).define(), "initParent": CGIndenter(CGGeneric(initParent), indentLevel=16).define(), "initMembers": CGIndenter(memberInits, indentLevel=16).define(), - "insertMembers": CGIndenter(memberInserts, indentLevel=8).define(), + "insertMembers": CGIndenter(CGList(memberInserts), indentLevel=8).define(), "preInitial": CGIndenter(CGGeneric(preInitial), indentLevel=8).define(), "postInitial": CGIndenter(CGGeneric(postInitial), indentLevel=8).define(), }) -- cgit v1.2.3 From d01648d637a350af0cb81470f956cc5edd18a9a4 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Sun, 21 Jun 2020 03:34:22 +0200 Subject: Fix remaining flake8 warnings --- .../script/dom/bindings/codegen/CodegenRust.py | 337 +++++++++++---------- 1 file changed, 169 insertions(+), 168 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 1f0e09639c8..610da4abdbd 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -359,17 +359,17 @@ class CGMethodCall(CGThing): # First check for null or undefined pickFirstSignature("%s.get().is_null_or_undefined()" % distinguishingArg, - lambda s: (s[1][distinguishingIndex].type.nullable() or - s[1][distinguishingIndex].type.isDictionary())) + lambda s: (s[1][distinguishingIndex].type.nullable() + or s[1][distinguishingIndex].type.isDictionary())) # Now check for distinguishingArg being an object that implements a # non-callback interface. That includes typed arrays and # arraybuffers. interfacesSigs = [ s for s in possibleSignatures - if (s[1][distinguishingIndex].type.isObject() or - s[1][distinguishingIndex].type.isUnion() or - s[1][distinguishingIndex].type.isNonCallbackInterface())] + if (s[1][distinguishingIndex].type.isObject() + or s[1][distinguishingIndex].type.isUnion() + or s[1][distinguishingIndex].type.isNonCallbackInterface())] # There might be more than one of these; we need to check # which ones we unwrap to. @@ -424,24 +424,24 @@ class CGMethodCall(CGThing): pickFirstSignature("%s.get().is_object() && is_array_like(*cx, %s)" % (distinguishingArg, distinguishingArg), lambda s: - (s[1][distinguishingIndex].type.isSequence() or - s[1][distinguishingIndex].type.isObject())) + (s[1][distinguishingIndex].type.isSequence() + or s[1][distinguishingIndex].type.isObject())) # Check for vanilla JS objects # XXXbz Do we need to worry about security wrappers? pickFirstSignature("%s.get().is_object()" % distinguishingArg, - lambda s: (s[1][distinguishingIndex].type.isCallback() or - s[1][distinguishingIndex].type.isCallbackInterface() or - s[1][distinguishingIndex].type.isDictionary() or - s[1][distinguishingIndex].type.isObject())) + lambda s: (s[1][distinguishingIndex].type.isCallback() + or s[1][distinguishingIndex].type.isCallbackInterface() + or s[1][distinguishingIndex].type.isDictionary() + or s[1][distinguishingIndex].type.isObject())) # The remaining cases are mutually exclusive. The # pickFirstSignature calls are what change caseBody # Check for strings or enums if pickFirstSignature(None, - lambda s: (s[1][distinguishingIndex].type.isString() or - s[1][distinguishingIndex].type.isEnum())): + lambda s: (s[1][distinguishingIndex].type.isString() + or s[1][distinguishingIndex].type.isEnum())): pass # Check for primitives elif pickFirstSignature(None, @@ -482,9 +482,9 @@ class CGMethodCall(CGThing): def dictionaryHasSequenceMember(dictionary): return (any(typeIsSequenceOrHasSequenceMember(m.type) for m in - dictionary.members) or - (dictionary.parent and - dictionaryHasSequenceMember(dictionary.parent))) + dictionary.members) + or (dictionary.parent + and dictionaryHasSequenceMember(dictionary.parent))) def typeIsSequenceOrHasSequenceMember(type): @@ -618,22 +618,22 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, def onFailureNotAnObject(failureCode): return CGWrapper( CGGeneric( - failureCode or - ('throw_type_error(*cx, "%s is not an object.");\n' - '%s' % (firstCap(sourceDescription), exceptionCode))), + failureCode + or ('throw_type_error(*cx, "%s is not an object.");\n' + '%s' % (firstCap(sourceDescription), exceptionCode))), post="\n") def onFailureInvalidEnumValue(failureCode, passedVarName): return CGGeneric( - failureCode or - ('throw_type_error(*cx, &format!("\'{}\' is not a valid enum value for enumeration \'%s\'.", %s)); %s' - % (type.name, passedVarName, exceptionCode))) + failureCode + or ('throw_type_error(*cx, &format!("\'{}\' is not a valid enum value for enumeration \'%s\'.", %s)); %s' + % (type.name, passedVarName, exceptionCode))) def onFailureNotCallable(failureCode): return CGGeneric( - failureCode or - ('throw_type_error(*cx, \"%s is not callable.\");\n' - '%s' % (firstCap(sourceDescription), exceptionCode))) + failureCode + or ('throw_type_error(*cx, \"%s is not callable.\");\n' + '%s' % (firstCap(sourceDescription), exceptionCode))) # A helper function for handling default values. def handleDefault(nullValue): @@ -660,16 +660,16 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, # Handle the non-object cases by wrapping up the whole # thing in an if cascade. templateBody = ( - "if ${val}.get().is_object() {\n" + - CGIndenter(CGGeneric(templateBody)).define() + "\n") + "if ${val}.get().is_object() {\n" + + CGIndenter(CGGeneric(templateBody)).define() + "\n") if type.nullable(): templateBody += ( "} else if ${val}.get().is_null_or_undefined() {\n" " %s\n") % nullValue templateBody += ( - "} else {\n" + - CGIndenter(onFailureNotAnObject(failureCode)).define() + - "}") + "} else {\n" + + CGIndenter(onFailureNotAnObject(failureCode)).define() + + "}") return templateBody assert not (isEnforceRange and isClamp) # These are mutually exclusive @@ -713,9 +713,9 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, for memberType in type.unroll().flatMemberTypes if memberType.isDictionary() ] - if (defaultValue and - not isinstance(defaultValue, IDLNullValue) and - not isinstance(defaultValue, IDLDefaultDictionaryValue)): + if (defaultValue + and not isinstance(defaultValue, IDLNullValue) + and not isinstance(defaultValue, IDLDefaultDictionaryValue)): tag = defaultValue.type.tag() if tag is IDLType.Tags.bool: default = "%s::Boolean(%s)" % ( @@ -1626,13 +1626,13 @@ class PropertyDefiner: prefableSpecs.append( prefableTemplate % (cond, name + "_specs", len(specs) - 1)) - specsArray = ("const %s_specs: &'static [&'static[%s]] = &[\n" + - ",\n".join(specs) + "\n" + - "];\n") % (name, specType) + specsArray = ("const %s_specs: &'static [&'static[%s]] = &[\n" + + ",\n".join(specs) + "\n" + + "];\n") % (name, specType) - prefArray = ("const %s: &'static [Guard<&'static [%s]>] = &[\n" + - ",\n".join(prefableSpecs) + "\n" + - "];\n") % (name, specType) + prefArray = ("const %s: &'static [Guard<&'static [%s]>] = &[\n" + + ",\n".join(prefableSpecs) + "\n" + + "];\n") % (name, specType) return specsArray + prefArray @@ -1660,9 +1660,9 @@ class MethodDefiner(PropertyDefiner): # Ignore non-static methods for callback interfaces if not descriptor.interface.isCallback() or static: methods = [m for m in descriptor.interface.members if - m.isMethod() and m.isStatic() == static and - not m.isIdentifierLess() and - MemberIsUnforgeable(m, descriptor) == unforgeable] + m.isMethod() and m.isStatic() == static + and not m.isIdentifierLess() + and MemberIsUnforgeable(m, descriptor) == unforgeable] else: methods = [] self.regular = [{"name": m.identifier.name, @@ -1683,10 +1683,10 @@ class MethodDefiner(PropertyDefiner): # Generate the keys/values/entries aliases for value iterables. maplikeOrSetlikeOrIterable = descriptor.interface.maplikeOrSetlikeOrIterable - if (not static and not unforgeable and - (maplikeOrSetlikeOrIterable and - maplikeOrSetlikeOrIterable.isIterable() and - maplikeOrSetlikeOrIterable.isValueIterator())): + if (not static and not unforgeable + and maplikeOrSetlikeOrIterable + and maplikeOrSetlikeOrIterable.isIterable() + and maplikeOrSetlikeOrIterable.isValueIterator()): m = maplikeOrSetlikeOrIterable # Add our keys/values/entries/forEach @@ -1805,8 +1805,8 @@ class AttrDefiner(PropertyDefiner): self.regular = [ m for m in descriptor.interface.members if - m.isAttr() and m.isStatic() == static and - MemberIsUnforgeable(m, descriptor) == unforgeable + m.isAttr() and m.isStatic() == static + and MemberIsUnforgeable(m, descriptor) == unforgeable ] self.static = static self.unforgeable = unforgeable @@ -1902,6 +1902,7 @@ class ConstDefiner(PropertyDefiner): 'ConstantSpec', PropertyDefiner.getControllingCondition, specData) + # We'll want to insert the indent at the beginnings of lines, but we # don't want to indent empty lines. So only indent lines that have a # non-newline character on them. @@ -2003,8 +2004,8 @@ class CGImports(CGWrapper): def isImportable(type): if not type.isType(): - assert (type.isInterface() or type.isDictionary() or - type.isEnum() or type.isNamespace()) + assert (type.isInterface() or type.isDictionary() + or type.isEnum() or type.isNamespace()) return True return not (type.builtin or type.isSequence() or type.isUnion()) @@ -2878,8 +2879,8 @@ class CGIDLInterface(CGThing): def define(self): interface = self.descriptor.interface name = self.descriptor.concreteType - if (interface.getUserData("hasConcreteDescendant", False) or - interface.getUserData("hasProxyDescendant", False)): + if (interface.getUserData("hasConcreteDescendant", False) + or interface.getUserData("hasProxyDescendant", False)): depth = self.descriptor.prototypeDepth check = "class.interface_chain[%s] == PrototypeList::ID::%s" % (depth, name) elif self.descriptor.proxy: @@ -3466,9 +3467,9 @@ assert!(!proto.is_null());""" % (function,)) def needCx(returnType, arguments, considerTypes): - return (considerTypes and - (typeNeedsCx(returnType, True) or - any(typeNeedsCx(a.type) for a in arguments))) + return (considerTypes + and (typeNeedsCx(returnType, True) + or any(typeNeedsCx(a.type) for a in arguments))) class CGCallGenerator(CGThing): @@ -3775,10 +3776,10 @@ class CGSpecializedMethod(CGAbstractExternMethod): self.method) return CGWrapper(CGMethodCall([], nativeName, self.method.isStatic(), self.descriptor, self.method), - pre="let cx = SafeJSContext::from_ptr(cx);\n" + - ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType) + - "let args = &*args;\n" - "let argc = args.argc_;\n") + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType) + + "let args = &*args;\n" + "let argc = args.argc_;\n") @staticmethod def makeNativeName(descriptor, method): @@ -3868,8 +3869,8 @@ class CGSpecializedGetter(CGAbstractExternMethod): return CGWrapper(CGGetterCall([], self.attr.type, nativeName, self.descriptor, self.attr), - pre="let cx = SafeJSContext::from_ptr(cx);\n" + - ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) @staticmethod def makeNativeName(descriptor, attr): @@ -3924,8 +3925,8 @@ class CGSpecializedSetter(CGAbstractExternMethod): self.attr) return CGWrapper(CGSetterCall([], self.attr.type, nativeName, self.descriptor, self.attr), - pre="let cx = SafeJSContext::from_ptr(cx);\n" + - ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) + pre="let cx = SafeJSContext::from_ptr(cx);\n" + + ("let this = &*(this as *const %s);\n" % self.descriptor.concreteType)) @staticmethod def makeNativeName(descriptor, attr): @@ -4191,8 +4192,8 @@ class CGMemberJITInfo(CGThing): # don't want them coalesced with each other or loop-hoisted, since # their return value can change even if nothing is going on from our # point of view. - return (affects == "Nothing" and - (dependsOn != "Everything" and dependsOn != "DeviceState")) + return (affects == "Nothing" + and (dependsOn != "Everything" and dependsOn != "DeviceState")) def aliasSet(self): """Returns the alias set to store in the jitinfo. This may not be the @@ -4282,10 +4283,10 @@ class CGMemberJITInfo(CGThing): if type == existingType: return existingType - if ((type == "JSVAL_TYPE_DOUBLE" and - existingType == "JSVAL_TYPE_INT32") or - (existingType == "JSVAL_TYPE_DOUBLE" and - type == "JSVAL_TYPE_INT32")): + if ((type == "JSVAL_TYPE_DOUBLE" + and existingType == "JSVAL_TYPE_INT32") + or (existingType == "JSVAL_TYPE_DOUBLE" + and type == "JSVAL_TYPE_INT32")): # Promote INT32 to DOUBLE as needed return "JSVAL_TYPE_DOUBLE" # Different types @@ -5206,8 +5207,8 @@ class CGProxyNamedOperation(CGProxySpecialOperation): argName = self.arguments[0].identifier.name return ("let %s = jsid_to_string(*cx, Handle::from_raw(id)).expect(\"Not a string-convertible JSID?\");\n" "let this = UnwrapProxy(proxy);\n" - "let this = &*this;\n" % argName + - CGProxySpecialOperation.define(self)) + "let this = &*this;\n" % argName + + CGProxySpecialOperation.define(self)) class CGProxyNamedGetter(CGProxyNamedOperation): @@ -5288,11 +5289,11 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): 'successCode': fillDescriptor, 'pre': 'rooted!(in(*cx) let mut result_root = UndefinedValue());' } - get += ("if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define() + "\n" + - "}\n") + get += ("if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define() + "\n" + + "}\n") namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: @@ -5373,16 +5374,16 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): indexedSetter = self.descriptor.operations['IndexedSetter'] if indexedSetter: - set += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + - "if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedSetter(self.descriptor)).define() + - " return (*opresult).succeed();\n" + - "}\n") + set += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + + "if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedSetter(self.descriptor)).define() + + " return (*opresult).succeed();\n" + + "}\n") elif self.descriptor.operations['IndexedGetter']: - set += ("if get_array_index_from_id(*cx, Handle::from_raw(id)).is_some() {\n" + - " return (*opresult).failNoIndexedSetter();\n" + + set += ("if get_array_index_from_id(*cx, Handle::from_raw(id)).is_some() {\n" + " return (*opresult).failNoIndexedSetter();\n" "}\n") namedSetter = self.descriptor.operations['NamedSetter'] @@ -5390,17 +5391,17 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): if self.descriptor.hasUnforgeableMembers: raise TypeError("Can't handle a named setter on an interface that has " "unforgeables. Figure out how that should work!") - set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + - CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + - " return (*opresult).succeed();\n" + - "}\n") + set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + + CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + + " return (*opresult).succeed();\n" + + "}\n") elif self.descriptor.operations['NamedGetter']: - set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + - CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + - " if result.is_some() {\n" - " return (*opresult).failNoNamedSetter();\n" - " }\n" - "}\n") + set += ("if RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id) {\n" + + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + + " if result.is_some() {\n" + " return (*opresult).failNoNamedSetter();\n" + " }\n" + "}\n") set += "return proxyhandler::define_property(*cx, %s);" % ", ".join(a.name for a in self.args[1:]) return set @@ -5488,8 +5489,8 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): def __init__(self, descriptor): - assert (descriptor.operations["IndexedGetter"] and - descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties")) + assert (descriptor.operations["IndexedGetter"] + and descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties")) args = [Argument('*mut JSContext', 'cx'), Argument('RawHandleObject', 'proxy'), Argument('RawMutableHandleIdVector', 'props')] @@ -5543,14 +5544,14 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): indexedGetter = self.descriptor.operations['IndexedGetter'] indexed = "let cx = SafeJSContext::from_ptr(cx);\n" if indexedGetter: - indexed += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + - "if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" + - " *bp = result.is_some();\n" + - " return true;\n" + - "}\n\n") + indexed += ("let index = get_array_index_from_id(*cx, Handle::from_raw(id));\n" + + "if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" + + " *bp = result.is_some();\n" + + " return true;\n" + + "}\n\n") namedGetter = self.descriptor.operations['NamedGetter'] condition = "RUST_JSID_IS_STRING(id) || RUST_JSID_IS_INT(id)" @@ -5624,11 +5625,11 @@ if !expando.is_null() { indexedGetter = self.descriptor.operations['IndexedGetter'] if indexedGetter: - getIndexedOrExpando = ("let index = get_array_index_from_id(*cx, id_lt);\n" + - "if let Some(index) = index {\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + - CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define()) + getIndexedOrExpando = ("let index = get_array_index_from_id(*cx, id_lt);\n" + + "if let Some(index) = index {\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = &*this;\n" + + CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define()) getIndexedOrExpando += """\ // Even if we don't have this index, we don't forward the // get on to our expando object. @@ -5648,9 +5649,9 @@ if !expando.is_null() { # 3. Set ignoreNamedProps to true. if indexedGetter: condition = "index.is_none() && (%s)" % condition - getNamed = ("if %s {\n" + - CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + - "}\n") % condition + getNamed = ("if %s {\n" + + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + + "}\n") % condition else: getNamed = "" @@ -5852,10 +5853,10 @@ class CGInterfaceTrait(CGThing): def members(): for m in descriptor.interface.members: - if (m.isMethod() and not m.isStatic() and - not m.isMaplikeOrSetlikeOrIterableMethod() and - (not m.isIdentifierLess() or (m.isStringifier() and not m.underlyingAttr)) and - not m.isDefaultToJSON()): + if (m.isMethod() and not m.isStatic() + and not m.isMaplikeOrSetlikeOrIterableMethod() + and (not m.isIdentifierLess() or (m.isStringifier() and not m.underlyingAttr)) + and not m.isDefaultToJSON()): name = CGSpecializedMethod.makeNativeName(descriptor, m) infallible = 'infallible' in descriptor.getExtendedAttributes(m) for idx, (rettype, arguments) in enumerate(m.signatures()): @@ -6254,8 +6255,8 @@ class CGDescriptor(CGThing): defaultToJSONMethod = None unscopableNames = [] for m in descriptor.interface.members: - if (m.isMethod() and - (not m.isIdentifierLess() or m == descriptor.operations["Stringifier"])): + if (m.isMethod() + and (not m.isIdentifierLess() or m == descriptor.operations["Stringifier"])): if m.getExtendedAttribute("Unscopable"): assert not m.isStatic() unscopableNames.append(m.identifier.name) @@ -6506,14 +6507,14 @@ class CGDictionary(CGThing): return (string.Template( "#[derive(${derive})]\n" - "${mustRoot}" + - "pub struct ${selfName} {\n" + - "${inheritance}" + - "\n".join(memberDecls) + "\n" + - "}").substitute({"selfName": self.makeClassName(d), - "inheritance": inheritance, - "mustRoot": mustRoot, - "derive": ', '.join(derive)})) + + "${mustRoot}" + + "pub struct ${selfName} {\n" + + "${inheritance}" + + "\n".join(memberDecls) + "\n" + + "}").substitute({"selfName": self.makeClassName(d), + "inheritance": inheritance, + "mustRoot": mustRoot, + "derive": ', '.join(derive)})) def impl(self): d = self.dictionary @@ -6769,15 +6770,15 @@ class CGRegisterProxyHandlers(CGThing): descriptors = config.getDescriptors(proxy=True) self.root = CGList([ CGGeneric( - "#[allow(non_upper_case_globals)]\n" + - "pub mod proxy_handlers {\n" + + "#[allow(non_upper_case_globals)]\n" + "pub mod proxy_handlers {\n" "".join( " pub static %s: std::sync::atomic::AtomicPtr =\n" " std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());\n" % desc.name for desc in descriptors - ) + - "}\n" + ) + + "}\n" ), CGRegisterProxyHandlersMethod(descriptors), ], "\n") @@ -7004,8 +7005,8 @@ class CGNativeMember(ClassMethod): static=member.isStatic(), # Mark our getters, which are attrs that # have a non-void return type, as const. - const=(not member.isStatic() and member.isAttr() and - not signature[0].isVoid()), + const=(not member.isStatic() and member.isAttr() + and not signature[0].isVoid()), breakAfterSelf=breakAfterSelf, unsafe=unsafe, visibility=visibility) @@ -7087,23 +7088,23 @@ class CGCallback(CGClass): setupCall = "let s = CallSetup::new(self, aExceptionHandling);\n" bodyWithThis = string.Template( - setupCall + - "rooted!(in(*s.get_context()) let mut thisObjJS = ptr::null_mut::());\n" - "wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n" - "if thisObjJS.is_null() {\n" - " return Err(JSFailed);\n" - "}\n" - "unsafe { ${methodName}(${callArgs}) }").substitute({ - "callArgs": ", ".join(argnamesWithThis), - "methodName": 'self.' + method.name, - }) + setupCall + + "rooted!(in(*s.get_context()) let mut thisObjJS = ptr::null_mut::());\n" + "wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n" + "if thisObjJS.is_null() {\n" + " return Err(JSFailed);\n" + "}\n" + "unsafe { ${methodName}(${callArgs}) }").substitute({ + "callArgs": ", ".join(argnamesWithThis), + "methodName": 'self.' + method.name, + }) bodyWithoutThis = string.Template( - setupCall + - "rooted!(in(*s.get_context()) let thisObjJS = ptr::null_mut::());\n" - "unsafe { ${methodName}(${callArgs}) }").substitute({ - "callArgs": ", ".join(argnamesWithoutThis), - "methodName": 'self.' + method.name, - }) + setupCall + + "rooted!(in(*s.get_context()) let thisObjJS = ptr::null_mut::());\n" + "unsafe { ${methodName}(${callArgs}) }").substitute({ + "callArgs": ", ".join(argnamesWithoutThis), + "methodName": 'self.' + method.name, + }) return [ClassMethod(method.name + '_', method.returnType, args, bodyInHeader=True, templateArgs=["T: DomObject"], @@ -7314,28 +7315,28 @@ class CallbackMember(CGNativeMember): conversion = wrapForType( "argv_root.handle_mut()", result=argval, - successCode=("{\n" + - "let arg = &mut argv[%s];\n" + - "*arg = Heap::default();\n" + - "arg.set(argv_root.get());\n" + + successCode=("{\n" + "let arg = &mut argv[%s];\n" + "*arg = Heap::default();\n" + "arg.set(argv_root.get());\n" "}") % jsvalIndex, pre="rooted!(in(*cx) let mut argv_root = UndefinedValue());") if arg.variadic: conversion = string.Template( - "for idx in 0..${arg}.len() {\n" + - CGIndenter(CGGeneric(conversion)).define() + "\n" - "}" + "for idx in 0..${arg}.len() {\n" + + CGIndenter(CGGeneric(conversion)).define() + "\n" + + "}" ).substitute({"arg": arg.identifier.name}) elif arg.optional and not arg.defaultValue: conversion = ( CGIfWrapper("%s.is_some()" % arg.identifier.name, - CGGeneric(conversion)).define() + - " else if argc == %d {\n" - " // This is our current trailing argument; reduce argc\n" - " argc -= 1;\n" - "} else {\n" - " argv[%d] = Heap::default();\n" - "}" % (i + 1, i)) + CGGeneric(conversion)).define() + + " else if argc == %d {\n" + " // This is our current trailing argument; reduce argc\n" + " argc -= 1;\n" + "} else {\n" + " argv[%d] = Heap::default();\n" + "}" % (i + 1, i)) return conversion def getArgs(self, returnType, argList): @@ -7464,8 +7465,8 @@ class CallbackOperationBase(CallbackMethod): return 'rooted!(in(*cx) let callable =\n' + getCallableFromProp + ');\n' return ( 'let isCallable = IsCallable(self.callback());\n' - 'rooted!(in(*cx) let callable =\n' + - CGIndenter( + 'rooted!(in(*cx) let callable =\n' + + CGIndenter( CGIfElseWrapper('isCallable', CGGeneric('ObjectValue(self.callback())'), CGGeneric(getCallableFromProp))).define() + ');\n') @@ -7676,9 +7677,9 @@ class GlobalGenRoots(): return getModuleFromObject(d).split('::')[-1] descriptors = config.getDescriptors(register=True, isIteratorInterface=False) - descriptors = (set(toBindingNamespace(d.name) for d in descriptors) | - set(leafModule(d) for d in config.callbacks) | - set(leafModule(d) for d in config.getDictionaries())) + descriptors = (set(toBindingNamespace(d.name) for d in descriptors) + | set(leafModule(d) for d in config.callbacks) + | set(leafModule(d) for d in config.getDictionaries())) curr = CGList([CGGeneric("pub mod %s;\n" % name) for name in sorted(descriptors)]) curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT) return curr -- cgit v1.2.3 From 2a2e037a4d559c5c98420da3b6eeefa6c3d5037c Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Sun, 21 Jun 2020 05:42:42 +0200 Subject: Fix incorrect string joining --- components/script/dom/bindings/codegen/CodegenRust.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 610da4abdbd..b078a8dac8a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6771,8 +6771,8 @@ class CGRegisterProxyHandlers(CGThing): self.root = CGList([ CGGeneric( "#[allow(non_upper_case_globals)]\n" - "pub mod proxy_handlers {\n" - "".join( + + "pub mod proxy_handlers {\n" + + "".join( " pub static %s: std::sync::atomic::AtomicPtr =\n" " std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());\n" % desc.name -- cgit v1.2.3 From aa80f9139909b451d434093e0ef38266f56bda3e Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Thu, 9 Jul 2020 20:01:01 -0400 Subject: dom: Use pref macro for IDL conditional guards. --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b078a8dac8a..c80fec57b5b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2662,7 +2662,7 @@ class CGConstructorEnabled(CGAbstractMethod): pref = iface.getExtendedAttribute("Pref") if pref: assert isinstance(pref, list) and len(pref) == 1 - conditions.append('prefs::pref_map().get("%s").as_bool().unwrap_or(false)' % pref[0]) + conditions.append('pref!(%s)' % pref[0]) func = iface.getExtendedAttribute("Func") if func: -- cgit v1.2.3 From 63528f6fdf192542cd811a2a3ef5f0cb2fecbc6b Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Thu, 9 Jul 2020 20:03:03 -0400 Subject: dom: Generate iterator symbol for interfaces with indexed getters. --- .../script/dom/bindings/codegen/CodegenRust.py | 23 ++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c80fec57b5b..4d1a3972d7b 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1672,8 +1672,27 @@ class MethodDefiner(PropertyDefiner): "condition": PropertyDefiner.getControllingCondition(m, descriptor)} for m in methods] - # FIXME Check for an existing iterator on the interface first. - if any(m.isGetter() and m.isIndexed() for m in methods): + # TODO: Once iterable is implemented, use tiebreak rules instead of + # failing. Also, may be more tiebreak rules to implement once spec bug + # is resolved. + # https://www.w3.org/Bugs/Public/show_bug.cgi?id=28592 + def hasIterator(methods, regular): + return (any("@@iterator" in m.aliases for m in methods) + or any("@@iterator" == r["name"] for r in regular)) + + # Check whether we need to output an @@iterator due to having an indexed + # getter. We only do this while outputting non-static and + # non-unforgeable methods, since the @@iterator function will be + # neither. + if (not static + and not unforgeable + and descriptor.supportsIndexedProperties()): # noqa + if hasIterator(methods, self.regular): # noqa + raise TypeError("Cannot have indexed getter/attr on " + "interface %s with other members " + "that generate @@iterator, such as " + "maplike/setlike or aliased functions." % + self.descriptor.interface.identifier.name) self.regular.append({"name": '@@iterator', "methodInfo": False, "selfHostedName": "$ArrayValues", -- cgit v1.2.3 From f8c9ee4eff1ae7a72037e16f2aa97ad6bb69da4e Mon Sep 17 00:00:00 2001 From: Sudarsan Date: Fri, 28 Aug 2020 20:54:18 +0800 Subject: Update mozjs to 0.14.1 This update pulls in improvements on mozjs that now removes the need to pass pointers to CompileOptionsWraper::new(), allows NewProxyObject to now accept a Singleton bool and JSClass and removes an unsafe Handle::new usage. --- components/script/dom/bindings/codegen/CodegenRust.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 4d1a3972d7b..83e68cdce76 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2778,6 +2778,8 @@ rooted!(in(*cx) let obj = NewProxyObject( handler, Handle::from_raw(UndefinedHandleValue), proto.get(), + ptr::null(), + false, )); assert!(!obj.is_null()); SetProxyReservedSlot( -- cgit v1.2.3 From 0e1479cc847333c81a37d11f0f65f0304972ba3c Mon Sep 17 00:00:00 2001 From: Jonathan Kingston Date: Tue, 24 Nov 2020 02:06:08 +0000 Subject: Add creation url and Secure Contexts --- components/script/dom/bindings/codegen/CodegenRust.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 83e68cdce76..13c295ef1a2 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1517,7 +1517,7 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): returnType) -def MemberCondition(pref, func, exposed): +def MemberCondition(pref, func, exposed, secure): """ A string representing the condition for a member to actually be exposed. Any of the arguments can be None. If not None, they should have the @@ -1526,11 +1526,14 @@ def MemberCondition(pref, func, exposed): pref: The name of the preference. func: The name of the function. exposed: One or more names of an exposed global. + secure: Requires secure context. """ assert pref is None or isinstance(pref, str) assert func is None or isinstance(func, str) assert exposed is None or isinstance(exposed, set) - assert func is None or pref is None or exposed is None + assert func is None or pref is None or exposed is None or secure is None + if secure: + return 'Condition::SecureContext()' if pref: return 'Condition::Pref("%s")' % pref if func: @@ -1580,7 +1583,8 @@ class PropertyDefiner: "Pref"), PropertyDefiner.getStringAttr(interfaceMember, "Func"), - interfaceMember.exposureSet) + interfaceMember.exposureSet, + interfaceMember.getExtendedAttribute("SecureContext")) def generateGuardedArray(self, array, name, specTemplate, specTerminator, specType, getCondition, getDataTuple): @@ -3038,7 +3042,7 @@ let global = incumbent_global.reflector().get_jsobject();\n""" for m in interface.members: if m.isAttr() and not m.isStatic() and m.type.isJSONType(): name = m.identifier.name - conditions = MemberCondition(None, None, m.exposureSet) + conditions = MemberCondition(None, None, m.exposureSet, None) ret_conditions = '&[' + ", ".join(conditions) + "]" ret += fill( """ @@ -7838,6 +7842,7 @@ impl %(base)s { if PropertyDefiner.getStringAttr(m, 'Pref') or \ PropertyDefiner.getStringAttr(m, 'Func') or \ PropertyDefiner.getStringAttr(m, 'Exposed') or \ + m.getExtendedAttribute('SecureContext') or \ (m.isMethod() and m.isIdentifierLess()): continue display = m.identifier.name + ('()' if m.isMethod() else '') -- cgit v1.2.3 From 823cca30d65f58eaa80085ff2e40e99ba7bcb8ba Mon Sep 17 00:00:00 2001 From: Sean Joseph Date: Thu, 26 Nov 2020 18:30:52 -0500 Subject: Added is_platform_obj_static --- components/script/dom/bindings/codegen/CodegenRust.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 13c295ef1a2..7d2cfcdd31e 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -6182,7 +6182,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'crate::dom::bindings::utils::get_property_on_prototype', 'crate::dom::bindings::utils::get_proto_or_iface_array', 'crate::dom::bindings::utils::has_property_on_prototype', - 'crate::dom::bindings::utils::is_platform_object', + 'crate::dom::bindings::utils::is_platform_object_dynamic', + 'crate::dom::bindings::utils::is_platform_object_static', 'crate::dom::bindings::utils::resolve_global', 'crate::dom::bindings::utils::set_dictionary_property', 'crate::dom::bindings::utils::trace_global', -- cgit v1.2.3 From 5c4939599e2793154569b19db87be8cc05ca9269 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Sun, 24 Jan 2021 14:07:10 -0500 Subject: Update mozjs. --- components/script/dom/bindings/codegen/CodegenRust.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7d2cfcdd31e..88ed2a2f456 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1884,7 +1884,7 @@ class AttrDefiner(PropertyDefiner): array, name, ' JSPropertySpec {\n' ' name: JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char },\n' - ' flags: (%s) as u8,\n' + ' flags_: (%s) as u8,\n' ' u: JSPropertySpec_AccessorsOrValue {\n' ' accessors: JSPropertySpec_AccessorsOrValue_Accessors {\n' ' getter: JSPropertySpec_Accessor {\n' @@ -2741,7 +2741,7 @@ ensure_expando_object(*cx, obj.handle().into(), expando.handle_mut()); # unforgeable holder for those with the right JSClass. Luckily, there # aren't too many globals being created. if descriptor.isGlobal(): - copyFunc = "JS_CopyPropertiesFrom" + copyFunc = "JS_CopyOwnPropertiesAndPrivateFields" else: copyFunc = "JS_InitializePropertiesFromCompatibleNativeObject" copyCode += """\ @@ -2783,7 +2783,6 @@ rooted!(in(*cx) let obj = NewProxyObject( Handle::from_raw(UndefinedHandleValue), proto.get(), ptr::null(), - false, )); assert!(!obj.is_null()); SetProxyReservedSlot( @@ -6059,7 +6058,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JSValueType', 'js::jsapi::JS_AtomizeAndPinString', 'js::rust::wrappers::JS_CallFunctionValue', - 'js::rust::wrappers::JS_CopyPropertiesFrom', + 'js::rust::wrappers::JS_CopyOwnPropertiesAndPrivateFields', 'js::rust::wrappers::JS_DefineProperty', 'js::rust::wrappers::JS_DefinePropertyById2', 'js::jsapi::JS_ForwardGetPropertyTo', -- cgit v1.2.3 From 397b9b2601eec94059f2b6f61510eb42c0bc264f Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Sun, 31 Jan 2021 19:30:40 -0500 Subject: Implement toStringTag symbol for DOM objects. This symbol is now required for the expected stringification behaviour in WPT. --- .../script/dom/bindings/codegen/CodegenRust.py | 91 ++++++++++++++++------ 1 file changed, 69 insertions(+), 22 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 88ed2a2f456..dbf363d0fbc 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1616,9 +1616,12 @@ class PropertyDefiner: specs = [] prefableSpecs = [] prefableTemplate = ' Guard::new(%s, %s[%d])' + origTemplate = specTemplate + if isinstance(specTemplate, str): + specTemplate = lambda _: origTemplate # noqa for cond, members in groupby(array, lambda m: getCondition(m, self.descriptor)): - currentSpecs = [specTemplate % getDataTuple(m) for m in members] + currentSpecs = [specTemplate(m) % getDataTuple(m) for m in members] if specTerminator: currentSpecs.append(specTerminator) specs.append("&[\n" + ",\n".join(currentSpecs) + "]\n") @@ -1826,7 +1829,11 @@ class AttrDefiner(PropertyDefiner): self.name = name self.descriptor = descriptor self.regular = [ - m + { + "name": m.identifier.name, + "attr": m, + "flags": "JSPROP_ENUMERATE", + } for m in descriptor.interface.members if m.isAttr() and m.isStatic() == static and MemberIsUnforgeable(m, descriptor) == unforgeable @@ -1834,15 +1841,21 @@ class AttrDefiner(PropertyDefiner): self.static = static self.unforgeable = unforgeable + if not static and not unforgeable and not ( + descriptor.interface.isNamespace() or descriptor.interface.isCallback() + ): + self.regular.append({ + "name": "@@toStringTag", + "attr": None, + "flags": "JSPROP_READONLY | JSPROP_INTERNAL_USE_BIT" + }) + def generateArray(self, array, name): if len(array) == 0: return "" - flags = "JSPROP_ENUMERATE" - if self.unforgeable: - flags += " | JSPROP_PERMANENT" - def getter(attr): + attr = attr['attr'] if self.static: accessor = 'get_' + self.descriptor.internalNameFor(attr.identifier.name) jitinfo = "0 as *const JSJitInfo" @@ -1858,6 +1871,7 @@ class AttrDefiner(PropertyDefiner): "native": accessor}) def setter(attr): + attr = attr['attr'] if (attr.readonly and not attr.getExtendedAttribute("PutForwards") and not attr.getExtendedAttribute("Replaceable")): return "JSNativeWrapper { op: None, info: 0 as *const JSJitInfo }" @@ -1876,29 +1890,59 @@ class AttrDefiner(PropertyDefiner): % {"info": jitinfo, "native": accessor}) + def condition(m, d): + if m["name"] == "@@toStringTag": + return MemberCondition(pref=None, func=None, exposed=None, secure=None) + return PropertyDefiner.getControllingCondition(m["attr"], d) + def specData(attr): - return (str_to_const_array(attr.identifier.name), flags, getter(attr), + if attr["name"] == "@@toStringTag": + return (attr["name"][2:], attr["flags"], + str_to_const_array(self.descriptor.interface.getClassName())) + + flags = attr["flags"] + if self.unforgeable: + flags += " | JSPROP_PERMANENT" + return (str_to_const_array(attr["attr"].identifier.name), flags, getter(attr), setter(attr)) + def template(m): + if m["name"] == "@@toStringTag": + return """ JSPropertySpec { + name: JSPropertySpec_Name { symbol_: SymbolCode::%s as usize + 1 }, + flags_: (%s) as u8, + u: JSPropertySpec_AccessorsOrValue { + value: JSPropertySpec_ValueWrapper { + type_: JSValueType::JSVAL_TYPE_STRING as _, + __bindgen_anon_1: JSPropertySpec_ValueWrapper__bindgen_ty_1 { + string: %s as *const u8 as *const libc::c_char, + } + } + } + } +""" + return """ JSPropertySpec { + name: JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char }, + flags_: (%s) as u8, + u: JSPropertySpec_AccessorsOrValue { + accessors: JSPropertySpec_AccessorsOrValue_Accessors { + getter: JSPropertySpec_Accessor { + native: %s, + }, + setter: JSPropertySpec_Accessor { + native: %s, + } + } + } + } +""" + return self.generateGuardedArray( array, name, - ' JSPropertySpec {\n' - ' name: JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char },\n' - ' flags_: (%s) as u8,\n' - ' u: JSPropertySpec_AccessorsOrValue {\n' - ' accessors: JSPropertySpec_AccessorsOrValue_Accessors {\n' - ' getter: JSPropertySpec_Accessor {\n' - ' native: %s,\n' - ' },\n' - ' setter: JSPropertySpec_Accessor {\n' - ' native: %s,\n' - ' }\n' - ' }\n' - ' }\n' - ' }', + template, ' JSPropertySpec::ZERO', 'JSPropertySpec', - PropertyDefiner.getControllingCondition, specData) + condition, specData) class ConstDefiner(PropertyDefiner): @@ -6046,11 +6090,14 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JSPROP_ENUMERATE', 'js::jsapi::JSPROP_PERMANENT', 'js::jsapi::JSPROP_READONLY', + 'js::jsapi::JSPROP_INTERNAL_USE_BIT', 'js::jsapi::JSPropertySpec', 'js::jsapi::JSPropertySpec_Accessor', 'js::jsapi::JSPropertySpec_AccessorsOrValue', 'js::jsapi::JSPropertySpec_AccessorsOrValue_Accessors', 'js::jsapi::JSPropertySpec_Name', + 'js::jsapi::JSPropertySpec_ValueWrapper', + 'js::jsapi::JSPropertySpec_ValueWrapper__bindgen_ty_1', 'js::jsapi::JSString', 'js::jsapi::JSTracer', 'js::jsapi::JSType', -- cgit v1.2.3 From a627dde0d01e35a1cbdb62ca19ee0349757c34b0 Mon Sep 17 00:00:00 2001 From: Vincent Ricard Date: Mon, 28 Dec 2020 22:31:49 +0100 Subject: Port some code to Python3 --- .../script/dom/bindings/codegen/CodegenRust.py | 40 +++++++++++----------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index dbf363d0fbc..8573998ebb3 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -344,7 +344,7 @@ class CGMethodCall(CGThing): distinguishingArg = "HandleValue::from_raw(args.get(%d))" % distinguishingIndex def pickFirstSignature(condition, filterLambda): - sigs = filter(filterLambda, possibleSignatures) + sigs = list(filter(filterLambda, possibleSignatures)) assert len(sigs) < 2 if len(sigs) > 0: call = getPerSignatureCall(sigs[0], distinguishingIndex) @@ -2117,7 +2117,7 @@ class CGImports(CGWrapper): members += [constructor] if d.proxy: - members += [o for o in d.operations.values() if o] + members += [o for o in list(d.operations.values()) if o] for m in members: if m.isMethod(): @@ -2557,7 +2557,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): ]) # Sort unionStructs by key, retrieve value - unionStructs = (i[1] for i in sorted(unionStructs.items(), key=operator.itemgetter(0))) + unionStructs = (i[1] for i in sorted(list(unionStructs.items()), key=operator.itemgetter(0))) return CGImports(CGList(unionStructs, "\n\n"), descriptors=[], @@ -4455,9 +4455,10 @@ class CGEnum(CGThing): pub enum %s { %s } -""" % (ident, ",\n ".join(map(getEnumValueName, enum.values()))) +""" % (ident, ",\n ".join(map(getEnumValueName, list(enum.values())))) - pairs = ",\n ".join(['("%s", super::%s::%s)' % (val, ident, getEnumValueName(val)) for val in enum.values()]) + pairs = ",\n ".join(['("%s", super::%s::%s)' % (val, ident, getEnumValueName(val)) + for val in list(enum.values())]) inner = string.Template("""\ use crate::dom::bindings::conversions::ConversionResult; @@ -4640,9 +4641,8 @@ class CGUnionStruct(CGThing): return "Rc" return "" - templateVars = map(lambda t: (getUnionTypeTemplateVars(t, self.descriptorProvider), - getTypeWrapper(t)), - self.type.flatMemberTypes) + templateVars = [(getUnionTypeTemplateVars(t, self.descriptorProvider), + getTypeWrapper(t)) for t in self.type.flatMemberTypes] enumValues = [ " %s(%s)," % (v["name"], "%s<%s>" % (wrapper, v["typeName"]) if wrapper else v["typeName"]) for (v, wrapper) in templateVars @@ -4701,7 +4701,7 @@ class CGUnionConversionStruct(CGThing): " Ok(None) => (),\n" "}\n") % (self.type, name, self.type, name) - interfaceMemberTypes = filter(lambda t: t.isNonCallbackInterface(), memberTypes) + interfaceMemberTypes = [t for t in memberTypes if t.isNonCallbackInterface()] if len(interfaceMemberTypes) > 0: typeNames = [get_name(memberType) for memberType in interfaceMemberTypes] interfaceObject = CGList(CGGeneric(get_match(typeName)) for typeName in typeNames) @@ -4709,7 +4709,7 @@ class CGUnionConversionStruct(CGThing): else: interfaceObject = None - arrayObjectMemberTypes = filter(lambda t: t.isSequence(), memberTypes) + arrayObjectMemberTypes = [t for t in memberTypes if t.isSequence()] if len(arrayObjectMemberTypes) > 0: assert len(arrayObjectMemberTypes) == 1 typeName = arrayObjectMemberTypes[0].name @@ -4718,7 +4718,7 @@ class CGUnionConversionStruct(CGThing): else: arrayObject = None - callbackMemberTypes = filter(lambda t: t.isCallback() or t.isCallbackInterface(), memberTypes) + callbackMemberTypes = [t for t in memberTypes if t.isCallback() or t.isCallbackInterface()] if len(callbackMemberTypes) > 0: assert len(callbackMemberTypes) == 1 typeName = callbackMemberTypes[0].name @@ -4726,7 +4726,7 @@ class CGUnionConversionStruct(CGThing): else: callbackObject = None - dictionaryMemberTypes = filter(lambda t: t.isDictionary(), memberTypes) + dictionaryMemberTypes = [t for t in memberTypes if t.isDictionary()] if len(dictionaryMemberTypes) > 0: assert len(dictionaryMemberTypes) == 1 typeName = dictionaryMemberTypes[0].name @@ -4735,7 +4735,7 @@ class CGUnionConversionStruct(CGThing): else: dictionaryObject = None - objectMemberTypes = filter(lambda t: t.isObject(), memberTypes) + objectMemberTypes = [t for t in memberTypes if t.isObject()] if len(objectMemberTypes) > 0: assert len(objectMemberTypes) == 1 typeName = objectMemberTypes[0].name @@ -4744,7 +4744,7 @@ class CGUnionConversionStruct(CGThing): else: object = None - mozMapMemberTypes = filter(lambda t: t.isRecord(), memberTypes) + mozMapMemberTypes = [t for t in memberTypes if t.isRecord()] if len(mozMapMemberTypes) > 0: assert len(mozMapMemberTypes) == 1 typeName = mozMapMemberTypes[0].name @@ -4790,9 +4790,9 @@ class CGUnionConversionStruct(CGThing): typename = get_name(memberType) return CGGeneric(get_match(typename)) other = [] - stringConversion = map(getStringOrPrimitiveConversion, stringTypes) - numericConversion = map(getStringOrPrimitiveConversion, numericTypes) - booleanConversion = map(getStringOrPrimitiveConversion, booleanTypes) + stringConversion = list(map(getStringOrPrimitiveConversion, stringTypes)) + numericConversion = list(map(getStringOrPrimitiveConversion, numericTypes)) + booleanConversion = list(map(getStringOrPrimitiveConversion, booleanTypes)) if stringConversion: if booleanConversion: other.append(CGIfWrapper("value.get().is_boolean()", booleanConversion[0])) @@ -5958,7 +5958,7 @@ class CGInterfaceTrait(CGThing): rettype) if descriptor.proxy: - for name, operation in descriptor.operations.iteritems(): + for name, operation in descriptor.operations.items(): if not operation or operation.isStringifier(): continue @@ -6488,7 +6488,7 @@ class CGDescriptor(CGThing): post='\n') if reexports: - reexports = ', '.join(map(lambda name: reexportedName(name), reexports)) + reexports = ', '.join([reexportedName(name) for name in reexports]) cgThings = CGList([CGGeneric('pub use self::%s::{%s};' % (toBindingNamespace(descriptor.name), reexports)), cgThings], '\n') @@ -7824,7 +7824,7 @@ impl Clone for TopTypeId { # TypeId enum. return "%s(%sTypeId)" % (name, name) if name in hierarchy else name - for base, derived in hierarchy.iteritems(): + for base, derived in hierarchy.items(): variants = [] if config.getDescriptor(base).concrete: variants.append(CGGeneric(base)) -- cgit v1.2.3 From 19be2cd3fa4b8fe2560dda9a62f1c2271f9fb41e Mon Sep 17 00:00:00 2001 From: sagudev Date: Wed, 14 Apr 2021 09:20:58 +0200 Subject: Update mozjs to 88 --- .../script/dom/bindings/codegen/CodegenRust.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 8573998ebb3..c1f79b1362d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1833,6 +1833,7 @@ class AttrDefiner(PropertyDefiner): "name": m.identifier.name, "attr": m, "flags": "JSPROP_ENUMERATE", + "is_accessor": "true", } for m in descriptor.interface.members if m.isAttr() and m.isStatic() == static @@ -1847,7 +1848,8 @@ class AttrDefiner(PropertyDefiner): self.regular.append({ "name": "@@toStringTag", "attr": None, - "flags": "JSPROP_READONLY | JSPROP_INTERNAL_USE_BIT" + "flags": "JSPROP_READONLY", + "is_accessor": "false", }) def generateArray(self, array, name): @@ -1897,23 +1899,24 @@ class AttrDefiner(PropertyDefiner): def specData(attr): if attr["name"] == "@@toStringTag": - return (attr["name"][2:], attr["flags"], + return (attr["name"][2:], attr["flags"], attr["is_accessor"], str_to_const_array(self.descriptor.interface.getClassName())) flags = attr["flags"] if self.unforgeable: flags += " | JSPROP_PERMANENT" - return (str_to_const_array(attr["attr"].identifier.name), flags, getter(attr), + return (str_to_const_array(attr["attr"].identifier.name), flags, attr["is_accessor"], getter(attr), setter(attr)) def template(m): if m["name"] == "@@toStringTag": return """ JSPropertySpec { name: JSPropertySpec_Name { symbol_: SymbolCode::%s as usize + 1 }, - flags_: (%s) as u8, + attributes_: (%s) as u8, + isAccessor_: (%s), u: JSPropertySpec_AccessorsOrValue { value: JSPropertySpec_ValueWrapper { - type_: JSValueType::JSVAL_TYPE_STRING as _, + type_: JSPropertySpec_ValueWrapper_Type::String, __bindgen_anon_1: JSPropertySpec_ValueWrapper__bindgen_ty_1 { string: %s as *const u8 as *const libc::c_char, } @@ -1923,7 +1926,8 @@ class AttrDefiner(PropertyDefiner): """ return """ JSPropertySpec { name: JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char }, - flags_: (%s) as u8, + attributes_: (%s) as u8, + isAccessor_: (%s), u: JSPropertySpec_AccessorsOrValue { accessors: JSPropertySpec_AccessorsOrValue_Accessors { getter: JSPropertySpec_Accessor { @@ -2923,7 +2927,7 @@ let root = raw.reflect_with(obj.get()); let _ac = JSAutoRealm::new(*cx, obj.get()); rooted!(in(*cx) let mut proto = ptr::null_mut::()); GetProtoObject(cx, obj.handle(), proto.handle_mut()); -assert!(JS_SplicePrototype(*cx, obj.handle(), proto.handle())); +assert!(JS_SetPrototype(*cx, obj.handle(), proto.handle())); let mut immutable = false; assert!(JS_SetImmutablePrototype(*cx, obj.handle(), &mut immutable)); assert!(immutable); @@ -6090,13 +6094,13 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::jsapi::JSPROP_ENUMERATE', 'js::jsapi::JSPROP_PERMANENT', 'js::jsapi::JSPROP_READONLY', - 'js::jsapi::JSPROP_INTERNAL_USE_BIT', 'js::jsapi::JSPropertySpec', 'js::jsapi::JSPropertySpec_Accessor', 'js::jsapi::JSPropertySpec_AccessorsOrValue', 'js::jsapi::JSPropertySpec_AccessorsOrValue_Accessors', 'js::jsapi::JSPropertySpec_Name', 'js::jsapi::JSPropertySpec_ValueWrapper', + 'js::jsapi::JSPropertySpec_ValueWrapper_Type', 'js::jsapi::JSPropertySpec_ValueWrapper__bindgen_ty_1', 'js::jsapi::JSString', 'js::jsapi::JSTracer', @@ -6130,7 +6134,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::rust::wrappers::JS_SetProperty', 'js::rust::wrappers::JS_SetPrototype', 'js::jsapi::JS_SetReservedSlot', - 'js::rust::wrappers::JS_SplicePrototype', 'js::rust::wrappers::JS_WrapValue', 'js::rust::wrappers::JS_WrapObject', 'js::rust::MutableHandle', -- cgit v1.2.3 From 13095741c577114b203d15910f19488ec3b7d3ed Mon Sep 17 00:00:00 2001 From: sagudev Date: Sat, 17 Apr 2021 17:53:11 +0200 Subject: Fix for bindgen --- components/script/dom/bindings/codegen/CodegenRust.py | 1 + 1 file changed, 1 insertion(+) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c1f79b1362d..24f62ebe486 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4111,6 +4111,7 @@ class CGMemberJITInfo(CGThing): protoID: PrototypeList::ID::${name} as u16, }, __bindgen_anon_3: JSJitInfo__bindgen_ty_3 { depth: ${depth} }, + _bitfield_align_1: Default::default(), _bitfield_1: __BindgenBitfieldUnit::new( new_jsjitinfo_bitfield_1!( JSJitInfo_OpType::${opType} as u8, -- cgit v1.2.3 From fd3bbc7ec928b13aff408665b6af7c163db07767 Mon Sep 17 00:00:00 2001 From: sagudev Date: Sat, 17 Apr 2021 18:19:02 +0200 Subject: Fix error --- components/script/dom/bindings/codegen/CodegenRust.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'components/script/dom/bindings/codegen/CodegenRust.py') diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 24f62ebe486..1f7a43ba831 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4111,7 +4111,7 @@ class CGMemberJITInfo(CGThing): protoID: PrototypeList::ID::${name} as u16, }, __bindgen_anon_3: JSJitInfo__bindgen_ty_3 { depth: ${depth} }, - _bitfield_align_1: Default::default(), + _bitfield_align_1: [], _bitfield_1: __BindgenBitfieldUnit::new( new_jsjitinfo_bitfield_1!( JSJitInfo_OpType::${opType} as u8, -- cgit v1.2.3