diff options
author | Bruno de Oliveira Abinader <bruno.d@partner.samsung.com> | 2014-12-30 11:24:54 -0400 |
---|---|---|
committer | Bruno de Oliveira Abinader <bruno.d@partner.samsung.com> | 2014-12-30 11:28:59 -0400 |
commit | c950e3d61e089184369cfecd4a265d963d5c5bad (patch) | |
tree | d27383916e066cb4869e5af690a19f731c8b5c6a /components/script/dom/bindings/codegen/CodegenRust.py | |
parent | de3cff0e08bb93bad0c317ba4fe130a8a89cdb55 (diff) | |
download | servo-c950e3d61e089184369cfecd4a265d963d5c5bad.tar.gz servo-c950e3d61e089184369cfecd4a265d963d5c5bad.zip |
Codegen whitespace fixes
Diffstat (limited to 'components/script/dom/bindings/codegen/CodegenRust.py')
-rw-r--r-- | components/script/dom/bindings/codegen/CodegenRust.py | 724 |
1 files changed, 362 insertions, 362 deletions
diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index a0ea1a0e3f0..018e97c7e0a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -109,10 +109,10 @@ class CastableObjectUnwrapper(): def __str__(self): return string.Template( """match unwrap_jsmanaged(${source}) { - Ok(val) => val, - Err(()) => { + Ok(val) => val, + Err(()) => { ${codeOnFailure} - } + } }""").substitute(self.substitution) @@ -194,8 +194,8 @@ class CGMethodCall(CGThing): if requiredArgs > 0: code = ( "if argc < %d {\n" - " throw_type_error(cx, \"Not enough arguments to %s.\");\n" - " return 0;\n" + " throw_type_error(cx, \"Not enough arguments to %s.\");\n" + " return 0;\n" "}" % (requiredArgs, methodName)) self.cgRoot.prepend( CGWrapper(CGGeneric(code), pre="\n", post="\n")) @@ -405,7 +405,7 @@ def typeIsSequenceOrHasSequenceMember(type): type = type.inner if type.isSequence(): return True - if type.isArray(): + if type.isArray(): elementType = type.inner return typeIsSequenceOrHasSequenceMember(elementType) if type.isDictionary(): @@ -561,7 +561,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, if type.nullable(): templateBody += ( "} else if (${val}).is_null_or_undefined() {\n" - " None\n") + " None\n") templateBody += ( "} else {\n" + CGIndenter(onFailureNotAnObject(failureCode)).define() + @@ -668,8 +668,8 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, conversionCode = ( "match FromJSValConvertible::from_jsval(cx, ${val}, %s) {\n" - " Ok(strval) => strval,\n" - " Err(_) => { %s },\n" + " Ok(strval) => strval,\n" + " Err(_) => { %s },\n" "}" % (nullBehavior, exceptionCode)) if defaultValue is None: @@ -701,8 +701,8 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, conversionCode = ( "match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" - " Ok(strval) => strval,\n" - " Err(_) => { %s },\n" + " Ok(strval) => strval,\n" + " Err(_) => { %s },\n" "}" % exceptionCode) declType = CGGeneric("ByteString") @@ -725,12 +725,12 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, template = ( "match FindEnumStringIndex(cx, ${val}, %(values)s) {\n" - " Err(_) => { %(exceptionCode)s },\n" - " Ok(None) => { %(handleInvalidEnumValueCode)s },\n" - " Ok(Some(index)) => {\n" - " //XXXjdm need some range checks up in here.\n" - " unsafe { mem::transmute(index) }\n" - " },\n" + " Err(_) => { %(exceptionCode)s },\n" + " Ok(None) => { %(handleInvalidEnumValueCode)s },\n" + " Ok(Some(index)) => {\n" + " //XXXjdm need some range checks up in here.\n" + " unsafe { mem::transmute(index) }\n" + " },\n" "}" % { "values" : enum + "Values::strings", "exceptionCode" : exceptionCode, "handleInvalidEnumValueCode" : handleInvalidEnumValueCode }) @@ -814,8 +814,8 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, typeName = CGDictionary.makeDictionaryName(type.inner) declType = CGGeneric(typeName) template = ("match %s::new(cx, ${val}) {\n" - " Ok(dictionary) => dictionary,\n" - " Err(_) => return 0,\n" + " Ok(dictionary) => dictionary,\n" + " Err(_) => return 0,\n" "}" % typeName) return handleOptional(template, declType, handleDefaultNull("%s::empty()" % typeName)) @@ -840,8 +840,8 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, #XXXjdm support conversionBehavior here template = ( "match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" - " Ok(v) => v,\n" - " Err(_) => { %s }\n" + " Ok(v) => v,\n" + " Err(_) => { %s }\n" "}" % exceptionCode) if defaultValue is not None: @@ -1204,8 +1204,8 @@ class MethodDefiner(PropertyDefiner): decls = ''.join([stringDecl(m) for m in array]) return decls + self.generatePrefableArray( array, name, - ' JSFunctionSpec {name: &%s_name as *const u8 as *const libc::c_char, call: JSNativeWrapper {op: Some(%s), info: %s}, nargs: %s, flags: %s as u16, selfHostedName: 0 as *const libc::c_char }', - ' JSFunctionSpec {name: 0 as *const libc::c_char, call: JSNativeWrapper {op: None, info: 0 as *const JSJitInfo}, nargs: 0, flags: 0, selfHostedName: 0 as *const libc::c_char }', + ' JSFunctionSpec { name: &%s_name as *const u8 as *const libc::c_char, call: JSNativeWrapper {op: Some(%s), info: %s}, nargs: %s, flags: %s as u16, selfHostedName: 0 as *const libc::c_char }', + ' JSFunctionSpec { name: 0 as *const libc::c_char, call: JSNativeWrapper {op: None, info: 0 as *const JSJitInfo}, nargs: 0, flags: 0, selfHostedName: 0 as *const libc::c_char }', 'JSFunctionSpec', specData) @@ -1267,14 +1267,14 @@ class AttrDefiner(PropertyDefiner): def stringDecl(attr): name = attr.identifier.name return "const %s_name: [u8, ..%i] = %s;\n" % (name, len(name) + 1, - str_to_const_array(name)) + str_to_const_array(name)) decls = ''.join([stringDecl(m) for m in array]) return decls + self.generatePrefableArray( array, name, - ' JSPropertySpec { name: &%s_name as *const u8 as *const libc::c_char, tinyid: 0, flags: ((%s) & 0xFF) as u8, getter: %s, setter: %s }', - ' JSPropertySpec { name: 0 as *const libc::c_char, tinyid: 0, flags: 0, getter: JSPropertyOpWrapper {op: None, info: 0 as *const JSJitInfo}, setter: JSStrictPropertyOpWrapper {op: None, info: 0 as *const JSJitInfo} }', + ' JSPropertySpec { name: &%s_name as *const u8 as *const libc::c_char, tinyid: 0, flags: ((%s) & 0xFF) as u8, getter: %s, setter: %s }', + ' JSPropertySpec { name: 0 as *const libc::c_char, tinyid: 0, flags: 0, getter: JSPropertyOpWrapper {op: None, info: 0 as *const JSJitInfo}, setter: JSStrictPropertyOpWrapper {op: None, info: 0 as *const JSJitInfo} }', 'JSPropertySpec', specData) @@ -1303,7 +1303,7 @@ class ConstDefiner(PropertyDefiner): return decls + self.generatePrefableArray( array, name, - ' ConstantSpec { name: %s_name, value: %s }', + ' ConstantSpec { name: %s_name, value: %s }', None, 'ConstantSpec', specData) @@ -1422,8 +1422,8 @@ def DOMClass(descriptor): protoList.extend(['PrototypeList::ID::Count'] * (descriptor.config.maxProtoChainLength - len(protoList))) prototypeChainString = ', '.join(protoList) return """DOMClass { - interface_chain: [ %s ], - native_hooks: &sNativePropertyHooks, + interface_chain: [ %s ], + native_hooks: &sNativePropertyHooks, }""" % prototypeChainString class CGDOMJSClass(CGThing): @@ -1445,69 +1445,69 @@ class CGDOMJSClass(CGThing): return """ const Class_name: [u8, ..%i] = %s; static Class: DOMJSClass = DOMJSClass { - base: js::Class { - name: &Class_name as *const u8 as *const libc::c_char, - flags: JSCLASS_IS_DOMJSCLASS | %s | (((%s) & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT as uint), //JSCLASS_HAS_RESERVED_SLOTS(%s), - addProperty: Some(JS_PropertyStub), - delProperty: Some(JS_PropertyStub), - getProperty: Some(JS_PropertyStub), - setProperty: Some(JS_StrictPropertyStub), - enumerate: Some(JS_EnumerateStub), - resolve: Some(JS_ResolveStub), - convert: Some(JS_ConvertStub), - finalize: Some(%s), - checkAccess: None, - call: None, - hasInstance: None, - construct: None, - trace: %s, - - ext: js::ClassExtension { - equality: 0 as *const u8, - outerObject: %s, - innerObject: None, - iteratorObject: 0 as *const u8, - unused: 0 as *const u8, - isWrappedNative: 0 as *const u8, - }, - - ops: js::ObjectOps { - lookupGeneric: 0 as *const u8, - lookupProperty: 0 as *const u8, - lookupElement: 0 as *const u8, - lookupSpecial: 0 as *const u8, - defineGeneric: 0 as *const u8, - defineProperty: 0 as *const u8, - defineElement: 0 as *const u8, - defineSpecial: 0 as *const u8, - getGeneric: 0 as *const u8, - getProperty: 0 as *const u8, - getElement: 0 as *const u8, - getElementIfPresent: 0 as *const u8, - getSpecial: 0 as *const u8, - setGeneric: 0 as *const u8, - setProperty: 0 as *const u8, - setElement: 0 as *const u8, - setSpecial: 0 as *const u8, - getGenericAttributes: 0 as *const u8, - getPropertyAttributes: 0 as *const u8, - getElementAttributes: 0 as *const u8, - getSpecialAttributes: 0 as *const u8, - setGenericAttributes: 0 as *const u8, - setPropertyAttributes: 0 as *const u8, - setElementAttributes: 0 as *const u8, - setSpecialAttributes: 0 as *const u8, - deleteProperty: 0 as *const u8, - deleteElement: 0 as *const u8, - deleteSpecial: 0 as *const u8, - - enumerate: 0 as *const u8, - typeOf: 0 as *const u8, - thisObject: %s, - clear: 0 as *const u8, + base: js::Class { + name: &Class_name as *const u8 as *const libc::c_char, + flags: JSCLASS_IS_DOMJSCLASS | %s | (((%s) & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT as uint), //JSCLASS_HAS_RESERVED_SLOTS(%s), + addProperty: Some(JS_PropertyStub), + delProperty: Some(JS_PropertyStub), + getProperty: Some(JS_PropertyStub), + setProperty: Some(JS_StrictPropertyStub), + enumerate: Some(JS_EnumerateStub), + resolve: Some(JS_ResolveStub), + convert: Some(JS_ConvertStub), + finalize: Some(%s), + checkAccess: None, + call: None, + hasInstance: None, + construct: None, + trace: %s, + + ext: js::ClassExtension { + equality: 0 as *const u8, + outerObject: %s, + innerObject: None, + iteratorObject: 0 as *const u8, + unused: 0 as *const u8, + isWrappedNative: 0 as *const u8, + }, + + ops: js::ObjectOps { + lookupGeneric: 0 as *const u8, + lookupProperty: 0 as *const u8, + lookupElement: 0 as *const u8, + lookupSpecial: 0 as *const u8, + defineGeneric: 0 as *const u8, + defineProperty: 0 as *const u8, + defineElement: 0 as *const u8, + defineSpecial: 0 as *const u8, + getGeneric: 0 as *const u8, + getProperty: 0 as *const u8, + getElement: 0 as *const u8, + getElementIfPresent: 0 as *const u8, + getSpecial: 0 as *const u8, + setGeneric: 0 as *const u8, + setProperty: 0 as *const u8, + setElement: 0 as *const u8, + setSpecial: 0 as *const u8, + getGenericAttributes: 0 as *const u8, + getPropertyAttributes: 0 as *const u8, + getElementAttributes: 0 as *const u8, + getSpecialAttributes: 0 as *const u8, + setGenericAttributes: 0 as *const u8, + setPropertyAttributes: 0 as *const u8, + setElementAttributes: 0 as *const u8, + setSpecialAttributes: 0 as *const u8, + deleteProperty: 0 as *const u8, + deleteElement: 0 as *const u8, + deleteSpecial: 0 as *const u8, + + enumerate: 0 as *const u8, + typeOf: 0 as *const u8, + thisObject: %s, + clear: 0 as *const u8, + }, }, - }, - dom_class: %s + dom_class: %s }; """ % (len(self.descriptor.interface.identifier.name) + 1, str_to_const_array(self.descriptor.interface.identifier.name), @@ -1529,22 +1529,22 @@ class CGPrototypeJSClass(CGThing): return """ const PrototypeClassName__: [u8, ..%s] = %s; static PrototypeClass: JSClass = JSClass { - name: &PrototypeClassName__ as *const u8 as *const libc::c_char, - flags: (1 & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT as uint, //JSCLASS_HAS_RESERVED_SLOTS(1) - addProperty: Some(JS_PropertyStub), - delProperty: Some(JS_PropertyStub), - getProperty: Some(JS_PropertyStub), - setProperty: Some(JS_StrictPropertyStub), - enumerate: Some(JS_EnumerateStub), - resolve: Some(JS_ResolveStub), - convert: Some(JS_ConvertStub), - finalize: None, - checkAccess: None, - call: None, - hasInstance: None, - construct: None, - trace: None, - reserved: [0 as *mut libc::c_void, ..40] + name: &PrototypeClassName__ as *const u8 as *const libc::c_char, + flags: (1 & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT as uint, //JSCLASS_HAS_RESERVED_SLOTS(1) + addProperty: Some(JS_PropertyStub), + delProperty: Some(JS_PropertyStub), + getProperty: Some(JS_PropertyStub), + setProperty: Some(JS_StrictPropertyStub), + enumerate: Some(JS_EnumerateStub), + resolve: Some(JS_ResolveStub), + convert: Some(JS_ConvertStub), + finalize: None, + checkAccess: None, + call: None, + hasInstance: None, + construct: None, + trace: None, + reserved: [0 as *mut libc::c_void, ..40] }; """ % (len(self.descriptor.interface.identifier.name + "Prototype") + 1, str_to_const_array(self.descriptor.interface.identifier.name + "Prototype")) @@ -1561,21 +1561,21 @@ class CGInterfaceObjectJSClass(CGThing): hasinstance = HASINSTANCE_HOOK_NAME return """ const InterfaceObjectClass: JSClass = { - %s, 0, - JS_PropertyStub, - JS_PropertyStub, - JS_PropertyStub, - JS_StrictPropertyStub, - JS_EnumerateStub, - JS_ResolveStub, - JS_ConvertStub, - 0 as *const u8, - 0 as *const u8, - %s, - %s, - %s, - 0 as *const u8, - JSCLASS_NO_INTERNAL_MEMBERS + %s, 0, + JS_PropertyStub, + JS_PropertyStub, + JS_PropertyStub, + JS_StrictPropertyStub, + JS_EnumerateStub, + JS_ResolveStub, + JS_ConvertStub, + 0 as *const u8, + 0 as *const u8, + %s, + %s, + %s, + 0 as *const u8, + JSCLASS_NO_INTERNAL_MEMBERS }; """ % (str_to_const_array("Function"), ctorname, hasinstance, ctorname) @@ -1621,8 +1621,8 @@ class CGCallbackTempRoot(CGGeneric): def __init__(self, name): val = "%s::new(tempRoot)" % name define = """{ - let tempRoot = ${val}.to_object(); - %s + let tempRoot = ${val}.to_object(); + %s }""" % val CGGeneric.__init__(self, define) @@ -1800,10 +1800,10 @@ def CreateBindingJSObject(descriptor, parent=None): let handler = RegisterBindings::proxy_handlers[PrototypeList::Proxies::%s as uint]; let mut private = PrivateValue(squirrel_away_unique(aObject) as *const libc::c_void); let obj = with_compartment(aCx, proto, || { - NewProxyObject(aCx, handler, - &private, - proto, %s, - ptr::null_mut(), ptr::null_mut()) + NewProxyObject(aCx, handler, + &private, + proto, %s, + ptr::null_mut(), ptr::null_mut()) }); assert!(obj.is_not_null()); @@ -1813,7 +1813,7 @@ assert!(obj.is_not_null()); create += "let obj = CreateDOMGlobal(aCx, &Class.base as *const js::Class as *const JSClass);\n" else: create += ("let obj = with_compartment(aCx, proto, || {\n" - " JS_NewObject(aCx, &Class.base as *const js::Class as *const JSClass, &*proto, &*%s)\n" + " JS_NewObject(aCx, &Class.base as *const js::Class as *const JSClass, &*proto, &*%s)\n" "});\n" % parent) create += """assert!(obj.is_not_null()); @@ -1857,12 +1857,12 @@ Temporary::new(raw)""" % CreateBindingJSObject(self.descriptor, "scope")) return CGGeneric("""\ %s with_compartment(aCx, obj, || { - let proto = GetProtoObject(aCx, obj, obj); - JS_SetPrototype(aCx, obj, proto); + let proto = GetProtoObject(aCx, obj, obj); + JS_SetPrototype(aCx, obj, proto); - raw.reflector().set_jsobject(obj); + raw.reflector().set_jsobject(obj); - RegisterBindings::Register(aCx, obj); + RegisterBindings::Register(aCx, obj); }); Temporary::new(raw)""" % CreateBindingJSObject(self.descriptor)) @@ -2035,12 +2035,12 @@ assert!(((*JS_GetClass(aGlobal)).flags & JSCLASS_DOM_GLOBAL) != 0); let protoOrIfaceArray = GetProtoOrIfaceArray(aGlobal); let cachedObject: *mut JSObject = *protoOrIfaceArray.offset(%s as int); if cachedObject.is_null() { - let tmp: *mut JSObject = CreateInterfaceObjects(aCx, aGlobal, aReceiver); - assert!(tmp.is_not_null()); - *protoOrIfaceArray.offset(%s as int) = tmp; - tmp + let tmp: *mut JSObject = CreateInterfaceObjects(aCx, aGlobal, aReceiver); + assert!(tmp.is_not_null()); + *protoOrIfaceArray.offset(%s as int) = tmp; + tmp } else { - cachedObject + cachedObject }""" % (self.id, self.id)) class CGGetProtoObjectMethod(CGGetPerInterfaceObject): @@ -2096,35 +2096,35 @@ class CGDefineProxyHandler(CGAbstractMethod): body = """\ let traps = ProxyTraps { - getPropertyDescriptor: Some(getPropertyDescriptor), - getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), - defineProperty: Some(%s), - getOwnPropertyNames: Some(getOwnPropertyNames_), - delete_: Some(%s), - enumerate: Some(enumerate_), - - has: None, - hasOwn: Some(hasOwn), - get: Some(get), - set: None, - keys: None, - iterate: None, - - call: None, - construct: None, - nativeCall: ptr::null(), - hasInstance: None, - typeOf: None, - objectClassIs: None, - obj_toString: Some(obj_toString), - fun_toString: None, - //regexp_toShared: ptr::null(), - defaultValue: None, - iteratorNext: None, - finalize: Some(%s), - getElementIfPresent: None, - getPrototypeOf: None, - trace: Some(%s) + getPropertyDescriptor: Some(getPropertyDescriptor), + getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), + defineProperty: Some(%s), + getOwnPropertyNames: Some(getOwnPropertyNames_), + delete_: Some(%s), + enumerate: Some(enumerate_), + + has: None, + hasOwn: Some(hasOwn), + get: Some(get), + set: None, + keys: None, + iterate: None, + + call: None, + construct: None, + nativeCall: ptr::null(), + hasInstance: None, + typeOf: None, + objectClassIs: None, + obj_toString: Some(obj_toString), + fun_toString: None, + //regexp_toShared: ptr::null(), + defaultValue: None, + iteratorNext: None, + finalize: Some(%s), + getElementIfPresent: None, + getPrototypeOf: None, + trace: Some(%s) }; CreateProxyHandler(&traps, &Class as *const _ as *const _) @@ -2443,7 +2443,7 @@ class CGAbstractBindingMethod(CGAbstractExternMethod): unwrapThis = CGGeneric( "let obj: *mut JSObject = JS_THIS_OBJECT(cx, vp as *mut JSVal);\n" "if obj.is_null() {\n" - " return false as JSBool;\n" + " return false as JSBool;\n" "}\n" "\n" "let this: JS<%s> = %s;\n" % (self.descriptor.concreteType, unwrapThis)) @@ -2628,7 +2628,7 @@ class CGGenericSetter(CGAbstractBindingMethod): "let argv: *mut JSVal = if argc != 0 { JS_ARGV(cx, vp) } else { &mut undef as *mut JSVal };\n" "let info: *const JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n" "if CallJitPropertyOp(info, cx, obj, this.unsafe_get() as *mut libc::c_void, argv) == 0 {\n" - " return 0;\n" + " return 0;\n" "}\n" "*vp = UndefinedValue();\n" "return 1;") @@ -2675,8 +2675,8 @@ class CGStaticSetter(CGAbstractStaticBindingMethod): checkForArg = CGGeneric( "let argv = JS_ARGV(cx, vp);\n" "if (argc == 0) {\n" - " throw_type_error(cx, \"Not enough arguments to %s setter.\");\n" - " return 0;\n" + " throw_type_error(cx, \"Not enough arguments to %s setter.\");\n" + " return 0;\n" "}\n" % self.attr.identifier.name) call = CGSetterCall([], self.attr.type, nativeName, self.descriptor, self.attr) @@ -2693,16 +2693,16 @@ class CGMemberJITInfo(CGThing): self.descriptor = descriptor def defineJitInfo(self, infoName, opName, infallible): - protoID = "PrototypeList::ID::%s as u32" % self.descriptor.name + protoID = "PrototypeList::ID::%s as u32" % self.descriptor.name depth = self.descriptor.interface.inheritanceDepth() failstr = "true" if infallible else "false" return ("\n" "const %s: JSJitInfo = JSJitInfo {\n" - " op: %s as *const u8,\n" - " protoID: %s,\n" - " depth: %s,\n" - " isInfallible: %s, /* False in setters. */\n" - " isConstant: false /* Only relevant for getters. */\n" + " op: %s as *const u8,\n" + " protoID: %s,\n" + " depth: %s,\n" + " isInfallible: %s, /* False in setters. */\n" + " isConstant: false /* Only relevant for getters. */\n" "};\n" % (infoName, opName, protoID, depth, failstr)) def define(self): @@ -2768,9 +2768,9 @@ class CGEnum(CGThing): #[deriving(PartialEq)] #[jstraceable] pub enum %s { - %s + %s } -""" % (enum.identifier.name, ",\n ".join(map(getEnumValueName, enum.values()))) +""" % (enum.identifier.name, ",\n ".join(map(getEnumValueName, enum.values()))) inner = """ use dom::bindings::conversions::ToJSValConvertible; @@ -2778,15 +2778,15 @@ use js::jsapi::JSContext; use js::jsval::JSVal; pub const strings: &'static [&'static str] = &[ - %s, + %s, ]; impl ToJSValConvertible for super::%s { - fn to_jsval(&self, cx: *mut JSContext) -> JSVal { - strings[*self as uint].into_string().to_jsval(cx) - } + fn to_jsval(&self, cx: *mut JSContext) -> JSVal { + strings[*self as uint].into_string().to_jsval(cx) + } } -""" % (",\n ".join(['"%s"' % val for val in enum.values()]), enum.identifier.name) +""" % (",\n ".join(['"%s"' % val for val in enum.values()]), enum.identifier.name) self.cgRoot = CGList([ CGGeneric(decl), @@ -2900,7 +2900,7 @@ impl ToJSValConvertible for %s { match *self { %s } - } + } } """) % (self.type, "\n".join(enumValues), self.type, "\n".join(enumConversions)) @@ -3210,7 +3210,7 @@ class ClassConstructor(ClassItem): return '' def getBody(self, cgClass): - initializers = [" parent: %s" % str(self.baseConstructors[0])] + initializers = [" parent: %s" % str(self.baseConstructors[0])] return (self.body + ( "%s {\n" "%s\n" @@ -3218,8 +3218,8 @@ class ClassConstructor(ClassItem): def declare(self, cgClass): args = ', '.join([a.declare() for a in self.args]) - body = ' ' + self.getBody(cgClass); - body = stripTrailingWhitespace(body.replace('\n', '\n ')) + body = ' ' + self.getBody(cgClass); + body = stripTrailingWhitespace(body.replace('\n', '\n ')) if len(body) > 0: body += '\n' body = ' {\n' + body + '}' @@ -3236,8 +3236,8 @@ class ClassConstructor(ClassItem): args = ', '.join([a.define() for a in self.args]) - body = ' ' + self.getBody() - body = '\n' + stripTrailingWhitespace(body.replace('\n', '\n ')) + body = ' ' + self.getBody() + body = '\n' + stripTrailingWhitespace(body.replace('\n', '\n ')) if len(body) > 0: body += '\n' @@ -3289,8 +3289,8 @@ class ClassDestructor(ClassItem): def declare(self, cgClass): if self.bodyInHeader: - body = ' ' + self.getBody(); - body = stripTrailingWhitespace(body.replace('\n', '\n ')) + body = ' ' + self.getBody(); + body = stripTrailingWhitespace(body.replace('\n', '\n ')) if len(body) > 0: body += '\n' body = '\n{\n' + body + '}' @@ -3306,8 +3306,8 @@ class ClassDestructor(ClassItem): if self.bodyInHeader: return '' - body = ' ' + self.getBody() - body = '\n' + stripTrailingWhitespace(body.replace('\n', '\n ')) + body = ' ' + self.getBody() + body = '\n' + stripTrailingWhitespace(body.replace('\n', '\n ')) if len(body) > 0: body += '\n' @@ -3366,7 +3366,7 @@ class ClassEnum(ClassItem): entry = '%s = %s' % (self.entries[i], self.values[i]) entries.append(entry) name = '' if not self.name else ' ' + self.name - return 'enum%s\n{\n %s\n};\n' % (name, ',\n '.join(entries)) + return 'enum%s\n{\n%s\n};\n' % (name, ',\n '.join(entries)) def define(self, cgClass): # Only goes in the header @@ -3378,7 +3378,7 @@ class ClassUnion(ClassItem): ClassItem.__init__(self, name, visibility) def declare(self, cgClass): - return 'union %s\n{\n %s\n};\n' % (self.name, '\n '.join(self.entries)) + return 'union %s\n{\n%s\n};\n' % (self.name, '\n '.join(self.entries)) def define(self, cgClass): # Only goes in the header @@ -3600,7 +3600,7 @@ class CGProxyUnwrap(CGAbstractMethod): def definition_body(self): return CGGeneric("""/*if (xpc::WrapperFactory::IsXrayWrapper(obj)) { - obj = js::UnwrapObject(obj); + obj = js::UnwrapObject(obj); }*/ //MOZ_ASSERT(IsProxy(obj)); let box_ = GetProxyPrivate(obj).to_private() as *const %s; @@ -3627,32 +3627,32 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): fillDescriptor = "FillPropertyDescriptor(&mut *desc, proxy, %s);\nreturn true;" % readonly templateValues = {'jsvalRef': '(*desc).value', 'successCode': fillDescriptor} get = ("if index.is_some() {\n" + - " let index = index.unwrap();\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let index = index.unwrap();\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define() + "\n" + "}\n") if indexedSetter or self.descriptor.operations['NamedSetter']: setOrIndexedGet += "if set {\n" if indexedSetter: - setOrIndexedGet += (" if index.is_some() {\n" + - " let index = index.unwrap();\n") + setOrIndexedGet += (" if index.is_some() {\n" + + " let index = index.unwrap();\n") if not 'IndexedCreator' in self.descriptor.operations: # FIXME need to check that this is a 'supported property index' assert False - setOrIndexedGet += (" FillPropertyDescriptor(&mut *desc, proxy, false);\n" + - " return true;\n" + - " }\n") + setOrIndexedGet += (" FillPropertyDescriptor(&mut *desc, proxy, false);\n" + + " return true;\n" + + " }\n") if self.descriptor.operations['NamedSetter']: - setOrIndexedGet += " if RUST_JSID_IS_STRING(id) != 0 {\n" + setOrIndexedGet += " if RUST_JSID_IS_STRING(id) != 0 {\n" if not 'NamedCreator' in self.descriptor.operations: # FIXME need to check that this is a 'supported property name' assert False - setOrIndexedGet += (" FillPropertyDescriptor(&mut *desc, proxy, false);\n" + - " return true;\n" + - " }\n") + setOrIndexedGet += (" FillPropertyDescriptor(&mut *desc, proxy, false);\n" + + " return true;\n" + + " }\n") setOrIndexedGet += "}" if indexedGetter: setOrIndexedGet += (" else {\n" + @@ -3674,10 +3674,10 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): # properties that shadow prototype properties. namedGet = ("\n" + "if !set && RUST_JSID_IS_STRING(id) != 0 && !HasPropertyOnPrototype(cx, proxy, id) {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let name = jsid_to_str(cx, id);\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + "\n" + "}\n") else: @@ -3686,15 +3686,15 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): return setOrIndexedGet + """let expando: *mut JSObject = GetExpandoObject(proxy); //if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) { if expando.is_not_null() { - let flags = if set { JSRESOLVE_ASSIGNING } else { 0 } | JSRESOLVE_QUALIFIED; - if JS_GetPropertyDescriptorById(cx, expando, id, flags, desc) == 0 { - return false; - } - if (*desc).obj.is_not_null() { - // Pretend the property lives on the wrapper. - (*desc).obj = proxy; - return true; - } + let flags = if set { JSRESOLVE_ASSIGNING } else { 0 } | JSRESOLVE_QUALIFIED; + if JS_GetPropertyDescriptorById(cx, expando, id, flags, desc) == 0 { + return false; + } + if (*desc).obj.is_not_null() { + // Pretend the property lives on the wrapper. + (*desc).obj = proxy; + return true; + } } """ + namedGet + """ (*desc).obj = ptr::null_mut(); @@ -3719,17 +3719,17 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): raise TypeError("Can't handle creator that's different from the setter") set += ("let index = GetArrayIndexFromId(cx, id);\n" + "if index.is_some() {\n" + - " let index = index.unwrap();\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let index = index.unwrap();\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyIndexedSetter(self.descriptor)).define() + - " return true;\n" + + " return true;\n" + "}\n") elif self.descriptor.operations['IndexedGetter']: set += ("if GetArrayIndexFromId(cx, id).is_some() {\n" + - " return false;\n" + - " //return ThrowErrorMessage(cx, MSG_NO_PROPERTY_SETTER, \"%s\");\n" + + " return false;\n" + + " //return ThrowErrorMessage(cx, MSG_NO_PROPERTY_SETTER, \"%s\");\n" + "}\n") % self.descriptor.name namedSetter = self.descriptor.operations['NamedSetter'] @@ -3737,24 +3737,24 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): if not self.descriptor.operations['NamedCreator'] is namedSetter: raise TypeError("Can't handle creator that's different from the setter") set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let name = jsid_to_str(cx, id);\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + "\n" + "}\n") elif self.descriptor.operations['NamedGetter']: set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let name = jsid_to_str(cx, id);\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + - " if (found) {\n" - " return false;\n" + - " //return ThrowErrorMessage(cx, MSG_NO_PROPERTY_SETTER, \"%s\");\n" + - " }\n" + - " return true;\n" + " if (found) {\n" + " return false;\n" + + " //return ThrowErrorMessage(cx, MSG_NO_PROPERTY_SETTER, \"%s\");\n" + + " }\n" + + " return true;\n" "}\n") % (self.descriptor.name) return set + """return proxyhandler::defineProperty_(%s);""" % ", ".join(a.name for a in self.args) @@ -3794,13 +3794,13 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): if indexedGetter: indexed = ("let index = GetArrayIndexFromId(cx, id);\n" + "if index.is_some() {\n" + - " let index = index.unwrap();\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let index = index.unwrap();\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" + - " *bp = found;\n" + - " return true;\n" + + " *bp = found;\n" + + " return true;\n" + "}\n\n") else: indexed = "" @@ -3808,13 +3808,13 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: named = ("if RUST_JSID_IS_STRING(id) != 0 && !HasPropertyOnPrototype(cx, proxy, id) {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let name = jsid_to_str(cx, id);\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + "\n" + - " *bp = found;\n" - " return true;\n" + " *bp = found;\n" + " return true;\n" "}\n" + "\n") else: @@ -3822,12 +3822,12 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): return indexed + """let expando: *mut JSObject = GetExpandoObject(proxy); if expando.is_not_null() { - let mut b: JSBool = 1; - let ok = JS_HasPropertyById(cx, expando, id, &mut b) != 0; - *bp = b != 0; - if !ok || *bp { - return ok; - } + let mut b: JSBool = 1; + let ok = JS_HasPropertyById(cx, expando, id, &mut b) != 0; + *bp = b != 0; + if !ok || *bp { + return ok; + } } """ + named + """*bp = false; @@ -3846,14 +3846,14 @@ class CGDOMJSProxyHandler_get(CGAbstractExternMethod): def getBody(self): getFromExpando = """let expando = GetExpandoObject(proxy); if expando.is_not_null() { - let mut hasProp = 0; - if JS_HasPropertyById(cx, expando, id, &mut hasProp) == 0 { - return false; - } + let mut hasProp = 0; + if JS_HasPropertyById(cx, expando, id, &mut hasProp) == 0 { + return false; + } - if hasProp != 0 { - return JS_GetPropertyById(cx, expando, id, vp) != 0; - } + if hasProp != 0 { + return JS_GetPropertyById(cx, expando, id, vp) != 0; + } }""" templateValues = { @@ -3865,44 +3865,44 @@ if expando.is_not_null() { if indexedGetter: getIndexedOrExpando = ("let index = GetArrayIndexFromId(cx, id);\n" + "if index.is_some() {\n" + - " let index = index.unwrap();\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let index = index.unwrap();\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\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. + // Even if we don't have this index, we don't forward the + // get on to our expando object. } else { - %s + %s } -""" % (stripTrailingWhitespace(getFromExpando.replace('\n', '\n '))) +""" % (stripTrailingWhitespace(getFromExpando.replace('\n', '\n '))) else: getIndexedOrExpando = getFromExpando + "\n" namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: getNamed = ("if (RUST_JSID_IS_STRING(id) != 0) {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = JS::from_raw(this);\n" + - " let this = this.root();\n" + + " let name = jsid_to_str(cx, id);\n" + + " let this = UnwrapProxy(proxy);\n" + + " let this = JS::from_raw(this);\n" + + " let this = this.root();\n" + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + "}\n") else: getNamed = "" return """//MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy), - //"Should not have a XrayWrapper here"); +//"Should not have a XrayWrapper here"); %s let mut found = false; if !GetPropertyOnPrototype(cx, proxy, id, &mut found, vp) { - return false; + return false; } if found { - return true; + return true; } %s *vp = UndefinedValue(); @@ -4246,7 +4246,7 @@ class CGNonNamespacedEnum(CGThing): entries.append('Count = ' + str(len(entries))) # Indent. - entries = [' ' + e for e in entries] + entries = [' ' + e for e in entries] # Build the enum body. enumstr = comment + 'pub enum %s {\n%s\n}\n' % (enumName, ',\n'.join(entries)) @@ -4295,11 +4295,11 @@ class CGDictionary(CGThing): def struct(self): d = self.dictionary if d.parent: - inheritance = " pub parent: %s::%s<'a, 'b>,\n" % (self.makeModuleName(d.parent), - self.makeClassName(d.parent)) + inheritance = " pub parent: %s::%s<'a, 'b>,\n" % (self.makeModuleName(d.parent), + self.makeClassName(d.parent)) else: inheritance = "" - memberDecls = [" pub %s: %s," % + memberDecls = [" pub %s: %s," % (self.makeMemberName(m[0].identifier.name), self.getMemberType(m)) for m in self.memberInfo] @@ -4314,8 +4314,8 @@ class CGDictionary(CGThing): d = self.dictionary if d.parent: initParent = ("parent: match %s::%s::new(cx, val) {\n" - " Ok(parent) => parent,\n" - " Err(_) => return Err(()),\n" + " Ok(parent) => parent,\n" + " Err(_) => return Err(()),\n" "},\n") % (self.makeModuleName(d.parent), self.makeClassName(d.parent)) else: @@ -4331,23 +4331,23 @@ class CGDictionary(CGThing): return string.Template( "impl<'a, 'b> ${selfName}<'a, 'b> {\n" - " pub fn empty() -> ${selfName}<'a, 'b> {\n" - " ${selfName}::new(ptr::null_mut(), NullValue()).unwrap()\n" - " }\n" - " pub fn new(cx: *mut JSContext, val: JSVal) -> Result<${selfName}<'a, 'b>, ()> {\n" - " let object = if val.is_null_or_undefined() {\n" - " ptr::null_mut()\n" - " } else if val.is_object() {\n" - " val.to_object()\n" - " } else {\n" - " throw_type_error(cx, \"Value not an object.\");\n" - " return Err(());\n" - " };\n" - " Ok(${selfName} {\n" + " pub fn empty() -> ${selfName}<'a, 'b> {\n" + " ${selfName}::new(ptr::null_mut(), NullValue()).unwrap()\n" + " }\n" + " pub fn new(cx: *mut JSContext, val: JSVal) -> Result<${selfName}<'a, 'b>, ()> {\n" + " let object = if val.is_null_or_undefined() {\n" + " ptr::null_mut()\n" + " } else if val.is_object() {\n" + " val.to_object()\n" + " } else {\n" + " throw_type_error(cx, \"Value not an object.\");\n" + " return Err(());\n" + " };\n" + " Ok(${selfName} {\n" "${initParent}" "${initMembers}" - " })\n" - " }\n" + " })\n" + " }\n" "}").substitute({ "selfName": self.makeClassName(d), "initParent": CGIndenter(CGGeneric(initParent), indentLevel=6).define(), @@ -4734,14 +4734,14 @@ class CGCallback(CGClass): setupCall = ("let s = CallSetup::new(self, aExceptionHandling);\n" "if s.GetContext().is_null() {\n" - " return Err(FailureUnknown);\n" + " return Err(FailureUnknown);\n" "}\n") bodyWithThis = string.Template( setupCall+ "let thisObjJS = WrapCallThisObject(s.GetContext(), thisObj);\n" "if thisObjJS.is_null() {\n" - " return Err(FailureUnknown);\n" + " return Err(FailureUnknown);\n" "}\n" "return ${methodName}(${callArgs});").substitute({ "callArgs" : ", ".join(argnamesWithThis), @@ -4966,10 +4966,10 @@ class CallbackMember(CGNativeMember): CGIfWrapper(CGGeneric(conversion), "%s.is_some()" % arg.identifier.name).define() + " else if (argc == %d) {\n" - " // This is our current trailing argument; reduce argc\n" - " argc -= 1;\n" + " // This is our current trailing argument; reduce argc\n" + " argc -= 1;\n" "} else {\n" - " argv[%d] = UndefinedValue();\n" + " argv[%d] = UndefinedValue();\n" "}" % (i+1, i)) return conversion @@ -5005,7 +5005,7 @@ class CallbackMember(CGNativeMember): "${callSetup}\n" "JSContext* cx = s.GetContext();\n" "if (!cx) {\n" - " return Err(FailureUnknown);\n" + " return Err(FailureUnknown);\n" "}\n").substitute({ "callSetup": callSetup, }) @@ -5048,11 +5048,11 @@ class CallbackMethod(CallbackMember): replacements["argc"] = "0" return string.Template("${getCallable}" "let ok = unsafe {\n" - " JS_CallFunctionValue(cx, ${thisObj}, callable,\n" - " ${argc}, ${argv}, &mut rval)\n" + " JS_CallFunctionValue(cx, ${thisObj}, callable,\n" + " ${argc}, ${argv}, &mut rval)\n" "};\n" "if ok == 0 {\n" - " return Err(FailureUnknown);\n" + " return Err(FailureUnknown);\n" "}\n").substitute(replacements) class CallCallback(CallbackMethod): @@ -5089,8 +5089,8 @@ class CallbackOperationBase(CallbackMethod): } getCallableFromProp = string.Template( 'match self.parent.GetCallableProperty(cx, "${methodName}") {\n' - ' Err(_) => return Err(FailureUnknown),\n' - ' Ok(callable) => callable,\n' + ' Err(_) => return Err(FailureUnknown),\n' + ' Ok(callable) => callable,\n' '}').substitute(replacements) if not self.singleOperation: return 'JS::Rooted<JS::Value> callable(cx);\n' + getCallableFromProp @@ -5134,7 +5134,7 @@ class CallbackGetter(CallbackMember): } return string.Template( 'if (!JS_GetProperty(cx, mCallback, "${attrName}", &rval)) {\n' - ' return Err(FailureUnknown);\n' + ' return Err(FailureUnknown);\n' '}\n').substitute(replacements); class CallbackSetter(CallbackMember): @@ -5161,7 +5161,7 @@ class CallbackSetter(CallbackMember): return string.Template( 'MOZ_ASSERT(argv.length() == 1);\n' 'if (!JS_SetProperty(cx, mCallback, "${attrName}", ${argv})) {\n' - ' return Err(FailureUnknown);\n' + ' return Err(FailureUnknown);\n' '}\n').substitute(replacements) def getArgcDecl(self): @@ -5244,10 +5244,10 @@ class GlobalGenRoots(): for protoName in descriptor.prototypeChain[1:-1]: protoDescriptor = config.getDescriptor(protoName) delegate = string.Template('''impl ${selfName} for ${baseName} { - #[inline] - fn ${fname}(&self) -> bool { - ${parentName}Cast::from_actual(self).${fname}() - } + #[inline] + fn ${fname}(&self) -> bool { + ${parentName}Cast::from_actual(self).${fname}() + } } ''').substitute({'fname': 'is_' + name.lower(), 'selfName': name + 'Derived', @@ -5257,52 +5257,52 @@ class GlobalGenRoots(): derived += [CGGeneric('\n')] cast = [CGGeneric(string.Template('''pub trait ${castTraitName} { - #[inline(always)] - fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, Self>> { - match base.${checkFn}() { - true => unsafe { Some(base.transmute()) }, - false => None + #[inline(always)] + fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, Self>> { + match base.${checkFn}() { + true => unsafe { Some(base.transmute()) }, + false => None + } } - } - #[inline(always)] - fn to_borrowed_ref<'a, 'b, T: ${toBound}+Reflectable>(base: &'a JSRef<'b, T>) -> Option<&'a JSRef<'b, Self>> { - match base.${checkFn}() { - true => unsafe { Some(base.transmute_borrowed()) }, - false => None - } - } - - #[inline(always)] - #[allow(unrooted_must_root)] - fn to_js<T: ${toBound}+Reflectable>(base: &JS<T>) -> Option<JS<Self>> { - unsafe { - match (*base.unsafe_get()).${checkFn}() { - true => Some(base.transmute_copy()), + #[inline(always)] + fn to_borrowed_ref<'a, 'b, T: ${toBound}+Reflectable>(base: &'a JSRef<'b, T>) -> Option<&'a JSRef<'b, Self>> { + match base.${checkFn}() { + true => unsafe { Some(base.transmute_borrowed()) }, false => None } } - } - - #[inline(always)] - fn from_ref<'a, T: ${fromBound}+Reflectable>(derived: JSRef<'a, T>) -> JSRef<'a, Self> { - unsafe { derived.transmute() } - } - - #[inline(always)] - fn from_borrowed_ref<'a, 'b, T: ${fromBound}+Reflectable>(derived: &'a JSRef<'b, T>) -> &'a JSRef<'b, Self> { - unsafe { derived.transmute_borrowed() } - } - - #[inline(always)] - fn from_temporary<T: ${fromBound}+Reflectable>(derived: Temporary<T>) -> Temporary<Self> { - unsafe { derived.transmute() } - } - - #[inline(always)] - fn from_actual<'a, T: ${fromBound}+Reflectable>(derived: &T) -> &'a Self { - unsafe { mem::transmute(derived) } - } + + #[inline(always)] + #[allow(unrooted_must_root)] + fn to_js<T: ${toBound}+Reflectable>(base: &JS<T>) -> Option<JS<Self>> { + unsafe { + match (*base.unsafe_get()).${checkFn}() { + true => Some(base.transmute_copy()), + false => None + } + } + } + + #[inline(always)] + fn from_ref<'a, T: ${fromBound}+Reflectable>(derived: JSRef<'a, T>) -> JSRef<'a, Self> { + unsafe { derived.transmute() } + } + + #[inline(always)] + fn from_borrowed_ref<'a, 'b, T: ${fromBound}+Reflectable>(derived: &'a JSRef<'b, T>) -> &'a JSRef<'b, Self> { + unsafe { derived.transmute_borrowed() } + } + + #[inline(always)] + fn from_temporary<T: ${fromBound}+Reflectable>(derived: Temporary<T>) -> Temporary<Self> { + unsafe { derived.transmute() } + } + + #[inline(always)] + fn from_actual<'a, T: ${fromBound}+Reflectable>(derived: &T) -> &'a Self { + unsafe { mem::transmute(derived) } + } } ''').substitute({'checkFn': 'is_' + name.lower(), 'castTraitName': name + 'Cast', |