mirror of
https://github.com/servo/servo.git
synced 2025-08-04 13:10:20 +01:00
auto merge of #4515 : brunoabinader/servo/codegen-cleanup, r=Ms2ger
Main changes: - Whitespace (indent) fixes; - CGIndent-related fixes; - Removed consecutive empty lines; - Removed empty lines before closing brackets; - Codegen style fixes; Tests: We don't have a static code style analyzer yet, so I've checked using the following (together with manual lookup at some selected generated bindings): 1. Check for lines with wrong indentation (1 to 3 whitespaces at the beginning) Command: ```$ pcregrep -r "^[ ]{1,3}[^ ]" components/script/dom/bindings/codegen/Bindings``` Expected: None Actual: None 2. Check for lines with wrong indentation (5 to 7 whitespaces at the beginning) Command: ```$ pcregrep -r "^[ ]{5,7}[^ ]" components/script/dom/bindings/codegen/Bindings``` Expected: None Actual: None 3. Check for lonely semicolons Command: ```$ pcregrep -r " \{0,\};" components/script/dom/bindings/codegen/Bindings``` Expected: None Actual: None 4. Check for empty lines before closing brackets Command: ```$ pcregrep -r -M "^$\n {0,}\}" components/script/dom/bindings/codegen/Bindings``` Expected: None Actual: None 5. Check for consecutive empty lines Command: ```$ pcregrep -r -M "^$\n^$\n" components/script/dom/bindings/codegen/Bindings``` Expected: None Actual: ```components/script/dom/bindings/codegen/Bindings/ChildNodeBinding.rs components/script/dom/bindings/codegen/Bindings/ElementCSSInlineStyleBinding.rs components/script/dom/bindings/codegen/Bindings/ParentNodeBinding.rs components/script/dom/bindings/codegen/Bindings/URLUtilsBinding.rs components/script/dom/bindings/codegen/Bindings/URLUtilsReadOnlyBinding.rs ``` All of the above are ```[NoInterfaceObject]```, thus providing only imports. We shouldn’t, however, generate empty lines (investigate this later on).
This commit is contained in:
commit
37a97f3273
1 changed files with 442 additions and 435 deletions
|
@ -103,12 +103,12 @@ class CastableObjectUnwrapper():
|
||||||
def __init__(self, descriptor, source, codeOnFailure):
|
def __init__(self, descriptor, source, codeOnFailure):
|
||||||
self.substitution = {
|
self.substitution = {
|
||||||
"source": source,
|
"source": source,
|
||||||
"codeOnFailure": CGIndenter(CGGeneric(codeOnFailure), 4).define(),
|
"codeOnFailure": CGIndenter(CGGeneric(codeOnFailure), 8).define(),
|
||||||
}
|
}
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return string.Template(
|
return string.Template("""\
|
||||||
"""match unwrap_jsmanaged(${source}) {
|
match unwrap_jsmanaged(${source}) {
|
||||||
Ok(val) => val,
|
Ok(val) => val,
|
||||||
Err(()) => {
|
Err(()) => {
|
||||||
${codeOnFailure}
|
${codeOnFailure}
|
||||||
|
@ -374,7 +374,7 @@ class CGMethodCall(CGThing):
|
||||||
CGSwitch("argcount",
|
CGSwitch("argcount",
|
||||||
argCountCases,
|
argCountCases,
|
||||||
CGGeneric("throw_type_error(cx, \"Not enough arguments to %s.\");\n"
|
CGGeneric("throw_type_error(cx, \"Not enough arguments to %s.\");\n"
|
||||||
"return 0;\n" % methodName)))
|
"return 0;" % methodName)))
|
||||||
#XXXjdm Avoid unreachable statement warnings
|
#XXXjdm Avoid unreachable statement warnings
|
||||||
#overloadCGThings.append(
|
#overloadCGThings.append(
|
||||||
# CGGeneric('panic!("We have an always-returning default case");\n'
|
# CGGeneric('panic!("We have an always-returning default case");\n'
|
||||||
|
@ -509,9 +509,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
|
||||||
return string[0].upper() + string[1:]
|
return string[0].upper() + string[1:]
|
||||||
|
|
||||||
# Helper functions for dealing with failures due to the JS value being the
|
# Helper functions for dealing with failures due to the JS value being the
|
||||||
# wrong type of value
|
# wrong type of value.
|
||||||
# Helper functions for dealing with failures due to the JS value being the
|
|
||||||
# wrong type of value
|
|
||||||
def onFailureNotAnObject(failureCode):
|
def onFailureNotAnObject(failureCode):
|
||||||
return CGWrapper(
|
return CGWrapper(
|
||||||
CGGeneric(
|
CGGeneric(
|
||||||
|
@ -532,9 +530,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
|
||||||
CGGeneric(
|
CGGeneric(
|
||||||
failureCode or
|
failureCode or
|
||||||
('throw_type_error(cx, \"%s is not callable.\");\n'
|
('throw_type_error(cx, \"%s is not callable.\");\n'
|
||||||
'%s' % (firstCap(sourceDescription), exceptionCode))),
|
'%s' % (firstCap(sourceDescription), exceptionCode))))
|
||||||
post="\n")
|
|
||||||
|
|
||||||
|
|
||||||
# A helper function for handling null default values. Checks that the
|
# A helper function for handling null default values. Checks that the
|
||||||
# default value, if it exists, is null.
|
# default value, if it exists, is null.
|
||||||
|
@ -565,8 +561,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
|
||||||
templateBody += (
|
templateBody += (
|
||||||
"} else {\n" +
|
"} else {\n" +
|
||||||
CGIndenter(onFailureNotAnObject(failureCode)).define() +
|
CGIndenter(onFailureNotAnObject(failureCode)).define() +
|
||||||
"}\n")
|
"}")
|
||||||
|
|
||||||
return templateBody
|
return templateBody
|
||||||
|
|
||||||
assert not (isEnforceRange and isClamp) # These are mutually exclusive
|
assert not (isEnforceRange and isClamp) # These are mutually exclusive
|
||||||
|
@ -1017,7 +1012,10 @@ def wrapForType(jsvalRef, result='result', successCode='return 1;'):
|
||||||
* 'result': the name of the variable in which the Rust value is stored;
|
* 'result': the name of the variable in which the Rust value is stored;
|
||||||
* 'successCode': the code to run once we have done the conversion.
|
* 'successCode': the code to run once we have done the conversion.
|
||||||
"""
|
"""
|
||||||
return "%s = (%s).to_jsval(cx);\n%s" % (jsvalRef, result, successCode)
|
wrap = "%s = (%s).to_jsval(cx);" % (jsvalRef, result)
|
||||||
|
if successCode:
|
||||||
|
wrap += "\n%s" % successCode
|
||||||
|
return wrap
|
||||||
|
|
||||||
|
|
||||||
def typeNeedsCx(type, retVal=False):
|
def typeNeedsCx(type, retVal=False):
|
||||||
|
@ -1149,7 +1147,7 @@ class PropertyDefiner:
|
||||||
|
|
||||||
return (("const %s: &'static [%s] = &[\n" +
|
return (("const %s: &'static [%s] = &[\n" +
|
||||||
",\n".join(specs) + "\n" +
|
",\n".join(specs) + "\n" +
|
||||||
"];\n\n") % (name, specType))
|
"];\n") % (name, specType))
|
||||||
|
|
||||||
# The length of a method is the maximum of the lengths of the
|
# The length of a method is the maximum of the lengths of the
|
||||||
# argument lists of all its overloads.
|
# argument lists of all its overloads.
|
||||||
|
@ -1317,7 +1315,7 @@ class CGIndenter(CGThing):
|
||||||
A class that takes another CGThing and generates code that indents that
|
A class that takes another CGThing and generates code that indents that
|
||||||
CGThing by some number of spaces. The default indent is two spaces.
|
CGThing by some number of spaces. The default indent is two spaces.
|
||||||
"""
|
"""
|
||||||
def __init__(self, child, indentLevel=2):
|
def __init__(self, child, indentLevel=4):
|
||||||
CGThing.__init__(self)
|
CGThing.__init__(self)
|
||||||
self.child = child
|
self.child = child
|
||||||
self.indent = " " * indentLevel
|
self.indent = " " * indentLevel
|
||||||
|
@ -1400,7 +1398,7 @@ class CGTemplatedType(CGWrapper):
|
||||||
class CGNamespace(CGWrapper):
|
class CGNamespace(CGWrapper):
|
||||||
def __init__(self, namespace, child, public=False):
|
def __init__(self, namespace, child, public=False):
|
||||||
pre = "%smod %s {\n" % ("pub " if public else "", namespace)
|
pre = "%smod %s {\n" % ("pub " if public else "", namespace)
|
||||||
post = "} // mod %s\n" % namespace
|
post = "} // mod %s" % namespace
|
||||||
CGWrapper.__init__(self, child, pre=pre, post=post)
|
CGWrapper.__init__(self, child, pre=pre, post=post)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
@ -1421,7 +1419,8 @@ def DOMClass(descriptor):
|
||||||
# padding.
|
# padding.
|
||||||
protoList.extend(['PrototypeList::ID::Count'] * (descriptor.config.maxProtoChainLength - len(protoList)))
|
protoList.extend(['PrototypeList::ID::Count'] * (descriptor.config.maxProtoChainLength - len(protoList)))
|
||||||
prototypeChainString = ', '.join(protoList)
|
prototypeChainString = ', '.join(protoList)
|
||||||
return """DOMClass {
|
return """\
|
||||||
|
DOMClass {
|
||||||
interface_chain: [ %s ],
|
interface_chain: [ %s ],
|
||||||
native_hooks: &sNativePropertyHooks,
|
native_hooks: &sNativePropertyHooks,
|
||||||
}""" % prototypeChainString
|
}""" % prototypeChainString
|
||||||
|
@ -1442,7 +1441,7 @@ class CGDOMJSClass(CGThing):
|
||||||
else:
|
else:
|
||||||
flags = "0"
|
flags = "0"
|
||||||
slots = "1"
|
slots = "1"
|
||||||
return """
|
return """\
|
||||||
const Class_name: [u8, ..%i] = %s;
|
const Class_name: [u8, ..%i] = %s;
|
||||||
static Class: DOMJSClass = DOMJSClass {
|
static Class: DOMJSClass = DOMJSClass {
|
||||||
base: js::Class {
|
base: js::Class {
|
||||||
|
@ -1526,7 +1525,7 @@ class CGPrototypeJSClass(CGThing):
|
||||||
self.descriptor = descriptor
|
self.descriptor = descriptor
|
||||||
|
|
||||||
def define(self):
|
def define(self):
|
||||||
return """
|
return """\
|
||||||
const PrototypeClassName__: [u8, ..%s] = %s;
|
const PrototypeClassName__: [u8, ..%s] = %s;
|
||||||
static PrototypeClass: JSClass = JSClass {
|
static PrototypeClass: JSClass = JSClass {
|
||||||
name: &PrototypeClassName__ as *const u8 as *const libc::c_char,
|
name: &PrototypeClassName__ as *const u8 as *const libc::c_char,
|
||||||
|
@ -1559,7 +1558,7 @@ class CGInterfaceObjectJSClass(CGThing):
|
||||||
return ""
|
return ""
|
||||||
ctorname = "0 as *const u8" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME
|
ctorname = "0 as *const u8" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME
|
||||||
hasinstance = HASINSTANCE_HOOK_NAME
|
hasinstance = HASINSTANCE_HOOK_NAME
|
||||||
return """
|
return """\
|
||||||
const InterfaceObjectClass: JSClass = {
|
const InterfaceObjectClass: JSClass = {
|
||||||
%s, 0,
|
%s, 0,
|
||||||
JS_PropertyStub,
|
JS_PropertyStub,
|
||||||
|
@ -1620,7 +1619,8 @@ class CGGeneric(CGThing):
|
||||||
class CGCallbackTempRoot(CGGeneric):
|
class CGCallbackTempRoot(CGGeneric):
|
||||||
def __init__(self, name):
|
def __init__(self, name):
|
||||||
val = "%s::new(tempRoot)" % name
|
val = "%s::new(tempRoot)" % name
|
||||||
define = """{
|
define = """\
|
||||||
|
{
|
||||||
let tempRoot = ${val}.to_object();
|
let tempRoot = ${val}.to_object();
|
||||||
%s
|
%s
|
||||||
}""" % val
|
}""" % val
|
||||||
|
@ -1778,7 +1778,7 @@ class CGAbstractMethod(CGThing):
|
||||||
def define(self):
|
def define(self):
|
||||||
body = self.definition_body()
|
body = self.definition_body()
|
||||||
if self.unsafe:
|
if self.unsafe:
|
||||||
body = CGWrapper(body, pre="unsafe {\n", post="\n}")
|
body = CGWrapper(CGIndenter(body), pre="unsafe {\n", post="\n}")
|
||||||
|
|
||||||
return CGWrapper(CGIndenter(body),
|
return CGWrapper(CGIndenter(body),
|
||||||
pre=self.definition_prologue(),
|
pre=self.definition_prologue(),
|
||||||
|
@ -1805,8 +1805,7 @@ let obj = with_compartment(aCx, proto, || {
|
||||||
proto, %s,
|
proto, %s,
|
||||||
ptr::null_mut(), ptr::null_mut())
|
ptr::null_mut(), ptr::null_mut())
|
||||||
});
|
});
|
||||||
assert!(obj.is_not_null());
|
assert!(obj.is_not_null());\
|
||||||
|
|
||||||
""" % (descriptor.name, parent)
|
""" % (descriptor.name, parent)
|
||||||
else:
|
else:
|
||||||
if descriptor.isGlobal():
|
if descriptor.isGlobal():
|
||||||
|
@ -1815,11 +1814,11 @@ assert!(obj.is_not_null());
|
||||||
create += ("let obj = with_compartment(aCx, proto, || {\n"
|
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)
|
"});\n" % parent)
|
||||||
create += """assert!(obj.is_not_null());
|
create += """\
|
||||||
|
assert!(obj.is_not_null());
|
||||||
|
|
||||||
JS_SetReservedSlot(obj, DOM_OBJECT_SLOT as u32,
|
JS_SetReservedSlot(obj, DOM_OBJECT_SLOT as u32,
|
||||||
PrivateValue(squirrel_away_unique(aObject) as *const libc::c_void));
|
PrivateValue(squirrel_away_unique(aObject) as *const libc::c_void));"""
|
||||||
"""
|
|
||||||
return create
|
return create
|
||||||
|
|
||||||
class CGWrapMethod(CGAbstractMethod):
|
class CGWrapMethod(CGAbstractMethod):
|
||||||
|
@ -1881,7 +1880,7 @@ class CGIDLInterface(CGThing):
|
||||||
'type': self.descriptor.name,
|
'type': self.descriptor.name,
|
||||||
'depth': self.descriptor.interface.inheritanceDepth(),
|
'depth': self.descriptor.interface.inheritanceDepth(),
|
||||||
}
|
}
|
||||||
return string.Template("""
|
return string.Template("""\
|
||||||
impl IDLInterface for ${type} {
|
impl IDLInterface for ${type} {
|
||||||
fn get_prototype_id(_: Option<${type}>) -> PrototypeList::ID {
|
fn get_prototype_id(_: Option<${type}>) -> PrototypeList::ID {
|
||||||
PrototypeList::ID::${type}
|
PrototypeList::ID::${type}
|
||||||
|
@ -1999,7 +1998,8 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod):
|
||||||
else:
|
else:
|
||||||
constructor = 'None'
|
constructor = 'None'
|
||||||
|
|
||||||
call = """return CreateInterfaceObjects2(aCx, aGlobal, aReceiver, parentProto,
|
call = """\
|
||||||
|
return CreateInterfaceObjects2(aCx, aGlobal, aReceiver, parentProto,
|
||||||
&PrototypeClass, %s,
|
&PrototypeClass, %s,
|
||||||
%s,
|
%s,
|
||||||
&sNativeProperties);""" % (constructor, domClass)
|
&sNativeProperties);""" % (constructor, domClass)
|
||||||
|
@ -2127,13 +2127,12 @@ let traps = ProxyTraps {
|
||||||
trace: Some(%s)
|
trace: Some(%s)
|
||||||
};
|
};
|
||||||
|
|
||||||
CreateProxyHandler(&traps, &Class as *const _ as *const _)
|
CreateProxyHandler(&traps, &Class as *const _ as *const _)\
|
||||||
""" % (customDefineProperty, customDelete, FINALIZE_HOOK_NAME,
|
""" % (customDefineProperty, customDelete, FINALIZE_HOOK_NAME,
|
||||||
TRACE_HOOK_NAME)
|
TRACE_HOOK_NAME)
|
||||||
return CGGeneric(body)
|
return CGGeneric(body)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class CGDefineDOMInterfaceMethod(CGAbstractMethod):
|
class CGDefineDOMInterfaceMethod(CGAbstractMethod):
|
||||||
"""
|
"""
|
||||||
A method for resolve hooks to try to lazily define the interface object for
|
A method for resolve hooks to try to lazily define the interface object for
|
||||||
|
@ -2226,7 +2225,7 @@ class CGCallGenerator(CGThing):
|
||||||
" throw_dom_exception(cx, global.root_ref(), e);\n"
|
" throw_dom_exception(cx, global.root_ref(), e);\n"
|
||||||
" return%s;\n"
|
" return%s;\n"
|
||||||
" },\n"
|
" },\n"
|
||||||
"};\n" % (glob, errorResult)))
|
"};" % (glob, errorResult)))
|
||||||
|
|
||||||
if typeRetValNeedsRooting(returnType):
|
if typeRetValNeedsRooting(returnType):
|
||||||
self.cgRoot.append(CGGeneric("let result = result.root();"))
|
self.cgRoot.append(CGGeneric("let result = result.root();"))
|
||||||
|
@ -2552,7 +2551,7 @@ class CGGenericGetter(CGAbstractBindingMethod):
|
||||||
def generate_code(self):
|
def generate_code(self):
|
||||||
return CGGeneric(
|
return CGGeneric(
|
||||||
"let info: *const JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n"
|
"let info: *const JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n"
|
||||||
"return CallJitPropertyOp(info, cx, obj, this.unsafe_get() as *mut libc::c_void, vp);\n")
|
"return CallJitPropertyOp(info, cx, obj, this.unsafe_get() as *mut libc::c_void, vp);")
|
||||||
|
|
||||||
class CGSpecializedGetter(CGAbstractExternMethod):
|
class CGSpecializedGetter(CGAbstractExternMethod):
|
||||||
"""
|
"""
|
||||||
|
@ -2677,7 +2676,7 @@ class CGStaticSetter(CGAbstractStaticBindingMethod):
|
||||||
"if (argc == 0) {\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 0;\n"
|
" return 0;\n"
|
||||||
"}\n" % self.attr.identifier.name)
|
"}" % self.attr.identifier.name)
|
||||||
call = CGSetterCall([], self.attr.type, nativeName, self.descriptor,
|
call = CGSetterCall([], self.attr.type, nativeName, self.descriptor,
|
||||||
self.attr)
|
self.attr)
|
||||||
return CGList([checkForArg, call])
|
return CGList([checkForArg, call])
|
||||||
|
@ -2696,8 +2695,7 @@ class CGMemberJITInfo(CGThing):
|
||||||
protoID = "PrototypeList::ID::%s as u32" % self.descriptor.name
|
protoID = "PrototypeList::ID::%s as u32" % self.descriptor.name
|
||||||
depth = self.descriptor.interface.inheritanceDepth()
|
depth = self.descriptor.interface.inheritanceDepth()
|
||||||
failstr = "true" if infallible else "false"
|
failstr = "true" if infallible else "false"
|
||||||
return ("\n"
|
return ("const %s: JSJitInfo = JSJitInfo {\n"
|
||||||
"const %s: JSJitInfo = JSJitInfo {\n"
|
|
||||||
" op: %s as *const u8,\n"
|
" op: %s as *const u8,\n"
|
||||||
" protoID: %s,\n"
|
" protoID: %s,\n"
|
||||||
" depth: %s,\n"
|
" depth: %s,\n"
|
||||||
|
@ -2715,7 +2713,7 @@ class CGMemberJITInfo(CGThing):
|
||||||
setterinfo = ("%s_setterinfo" % self.member.identifier.name)
|
setterinfo = ("%s_setterinfo" % self.member.identifier.name)
|
||||||
setter = ("set_%s" % self.member.identifier.name)
|
setter = ("set_%s" % self.member.identifier.name)
|
||||||
# Setters are always fallible, since they have to do a typed unwrap.
|
# Setters are always fallible, since they have to do a typed unwrap.
|
||||||
result += self.defineJitInfo(setterinfo, setter, False)
|
result += "\n" + self.defineJitInfo(setterinfo, setter, False)
|
||||||
return result
|
return result
|
||||||
if self.member.isMethod():
|
if self.member.isMethod():
|
||||||
methodinfo = ("%s_methodinfo" % self.member.identifier.name)
|
methodinfo = ("%s_methodinfo" % self.member.identifier.name)
|
||||||
|
@ -2763,7 +2761,7 @@ class CGEnum(CGThing):
|
||||||
def __init__(self, enum):
|
def __init__(self, enum):
|
||||||
CGThing.__init__(self)
|
CGThing.__init__(self)
|
||||||
|
|
||||||
decl = """
|
decl = """\
|
||||||
#[repr(uint)]
|
#[repr(uint)]
|
||||||
#[deriving(PartialEq)]
|
#[deriving(PartialEq)]
|
||||||
#[jstraceable]
|
#[jstraceable]
|
||||||
|
@ -2772,7 +2770,7 @@ pub enum %s {
|
||||||
}
|
}
|
||||||
""" % (enum.identifier.name, ",\n ".join(map(getEnumValueName, enum.values())))
|
""" % (enum.identifier.name, ",\n ".join(map(getEnumValueName, enum.values())))
|
||||||
|
|
||||||
inner = """
|
inner = """\
|
||||||
use dom::bindings::conversions::ToJSValConvertible;
|
use dom::bindings::conversions::ToJSValConvertible;
|
||||||
use js::jsapi::JSContext;
|
use js::jsapi::JSContext;
|
||||||
use js::jsval::JSVal;
|
use js::jsval::JSVal;
|
||||||
|
@ -2890,7 +2888,8 @@ class CGUnionStruct(CGThing):
|
||||||
]
|
]
|
||||||
# XXXManishearth The following should be #[must_root],
|
# XXXManishearth The following should be #[must_root],
|
||||||
# however we currently allow it till #2661 is fixed
|
# however we currently allow it till #2661 is fixed
|
||||||
return ("""#[allow(unrooted_must_root)]
|
return ("""\
|
||||||
|
#[allow(unrooted_must_root)]
|
||||||
pub enum %s {
|
pub enum %s {
|
||||||
%s
|
%s
|
||||||
}
|
}
|
||||||
|
@ -3147,7 +3146,8 @@ class ClassUsingDeclaration(ClassItem):
|
||||||
ClassItem.__init__(self, name, visibility)
|
ClassItem.__init__(self, name, visibility)
|
||||||
|
|
||||||
def declare(self, cgClass):
|
def declare(self, cgClass):
|
||||||
return string.Template("""using ${baseClass}::${name};
|
return string.Template("""\
|
||||||
|
using ${baseClass}::${name};
|
||||||
""").substitute({ 'baseClass': self.baseClass,
|
""").substitute({ 'baseClass': self.baseClass,
|
||||||
'name': self.name })
|
'name': self.name })
|
||||||
|
|
||||||
|
@ -3224,7 +3224,8 @@ class ClassConstructor(ClassItem):
|
||||||
body += '\n'
|
body += '\n'
|
||||||
body = ' {\n' + body + '}'
|
body = ' {\n' + body + '}'
|
||||||
|
|
||||||
return string.Template("""pub fn ${decorators}new(${args}) -> ${className}${body}
|
return string.Template("""\
|
||||||
|
pub fn ${decorators}new(${args}) -> ${className}${body}
|
||||||
""").substitute({ 'decorators': self.getDecorators(True),
|
""").substitute({ 'decorators': self.getDecorators(True),
|
||||||
'className': cgClass.getNameString(),
|
'className': cgClass.getNameString(),
|
||||||
'args': args,
|
'args': args,
|
||||||
|
@ -3241,7 +3242,8 @@ class ClassConstructor(ClassItem):
|
||||||
if len(body) > 0:
|
if len(body) > 0:
|
||||||
body += '\n'
|
body += '\n'
|
||||||
|
|
||||||
return string.Template("""${decorators}
|
return string.Template("""\
|
||||||
|
${decorators}
|
||||||
${className}::${className}(${args})${initializationList}
|
${className}::${className}(${args})${initializationList}
|
||||||
{${body}}
|
{${body}}
|
||||||
""").substitute({ 'decorators': self.getDecorators(False),
|
""").substitute({ 'decorators': self.getDecorators(False),
|
||||||
|
@ -3297,7 +3299,8 @@ class ClassDestructor(ClassItem):
|
||||||
else:
|
else:
|
||||||
body = ';'
|
body = ';'
|
||||||
|
|
||||||
return string.Template("""${decorators}~${className}()${body}
|
return string.Template("""\
|
||||||
|
${decorators}~${className}()${body}
|
||||||
""").substitute({ 'decorators': self.getDecorators(True),
|
""").substitute({ 'decorators': self.getDecorators(True),
|
||||||
'className': cgClass.getNameString(),
|
'className': cgClass.getNameString(),
|
||||||
'body': body })
|
'body': body })
|
||||||
|
@ -3311,7 +3314,8 @@ class ClassDestructor(ClassItem):
|
||||||
if len(body) > 0:
|
if len(body) > 0:
|
||||||
body += '\n'
|
body += '\n'
|
||||||
|
|
||||||
return string.Template("""${decorators}
|
return string.Template("""\
|
||||||
|
${decorators}
|
||||||
${className}::~${className}()
|
${className}::~${className}()
|
||||||
{${body}}
|
{${body}}
|
||||||
""").substitute({ 'decorators': self.getDecorators(False),
|
""").substitute({ 'decorators': self.getDecorators(False),
|
||||||
|
@ -3444,7 +3448,7 @@ class CGClass(CGThing):
|
||||||
|
|
||||||
assert len(self.bases) == 1 #XXjdm Can we support multiple inheritance?
|
assert len(self.bases) == 1 #XXjdm Can we support multiple inheritance?
|
||||||
|
|
||||||
result += '{\n%s\n' % self.indent
|
result += ' {\n'
|
||||||
|
|
||||||
if self.bases:
|
if self.bases:
|
||||||
self.members = [ClassMember("parent", self.bases[0].name, "pub")] + self.members
|
self.members = [ClassMember("parent", self.bases[0].name, "pub")] + self.members
|
||||||
|
@ -3599,7 +3603,8 @@ class CGProxyUnwrap(CGAbstractMethod):
|
||||||
CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", '*const ' + descriptor.concreteType, args, alwaysInline=True)
|
CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", '*const ' + descriptor.concreteType, args, alwaysInline=True)
|
||||||
|
|
||||||
def definition_body(self):
|
def definition_body(self):
|
||||||
return CGGeneric("""/*if (xpc::WrapperFactory::IsXrayWrapper(obj)) {
|
return CGGeneric("""\
|
||||||
|
/*if (xpc::WrapperFactory::IsXrayWrapper(obj)) {
|
||||||
obj = js::UnwrapObject(obj);
|
obj = js::UnwrapObject(obj);
|
||||||
}*/
|
}*/
|
||||||
//MOZ_ASSERT(IsProxy(obj));
|
//MOZ_ASSERT(IsProxy(obj));
|
||||||
|
@ -3683,7 +3688,8 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod):
|
||||||
else:
|
else:
|
||||||
namedGet = ""
|
namedGet = ""
|
||||||
|
|
||||||
return setOrIndexedGet + """let expando: *mut JSObject = GetExpandoObject(proxy);
|
return setOrIndexedGet + """\
|
||||||
|
let expando: *mut JSObject = GetExpandoObject(proxy);
|
||||||
//if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) {
|
//if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) {
|
||||||
if expando.is_not_null() {
|
if expando.is_not_null() {
|
||||||
let flags = if set { JSRESOLVE_ASSIGNING } else { 0 } | JSRESOLVE_QUALIFIED;
|
let flags = if set { JSRESOLVE_ASSIGNING } else { 0 } | JSRESOLVE_QUALIFIED;
|
||||||
|
@ -3696,7 +3702,7 @@ if expando.is_not_null() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
""" + namedGet + """
|
""" + namedGet + """\
|
||||||
(*desc).obj = ptr::null_mut();
|
(*desc).obj = ptr::null_mut();
|
||||||
return true;"""
|
return true;"""
|
||||||
|
|
||||||
|
@ -3741,7 +3747,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod):
|
||||||
" let this = UnwrapProxy(proxy);\n" +
|
" let this = UnwrapProxy(proxy);\n" +
|
||||||
" let this = JS::from_raw(this);\n" +
|
" let this = JS::from_raw(this);\n" +
|
||||||
" let this = this.root();\n" +
|
" let this = this.root();\n" +
|
||||||
CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + "\n" +
|
CGIndenter(CGProxyNamedSetter(self.descriptor)).define() +
|
||||||
"}\n")
|
"}\n")
|
||||||
elif self.descriptor.operations['NamedGetter']:
|
elif self.descriptor.operations['NamedGetter']:
|
||||||
set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" +
|
set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" +
|
||||||
|
@ -3820,7 +3826,8 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod):
|
||||||
else:
|
else:
|
||||||
named = ""
|
named = ""
|
||||||
|
|
||||||
return indexed + """let expando: *mut JSObject = GetExpandoObject(proxy);
|
return indexed + """\
|
||||||
|
let expando: *mut JSObject = GetExpandoObject(proxy);
|
||||||
if expando.is_not_null() {
|
if expando.is_not_null() {
|
||||||
let mut b: JSBool = 1;
|
let mut b: JSBool = 1;
|
||||||
let ok = JS_HasPropertyById(cx, expando, id, &mut b) != 0;
|
let ok = JS_HasPropertyById(cx, expando, id, &mut b) != 0;
|
||||||
|
@ -3829,8 +3836,8 @@ if expando.is_not_null() {
|
||||||
return ok;
|
return ok;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
""" + named + """\
|
||||||
""" + named + """*bp = false;
|
*bp = false;
|
||||||
return true;"""
|
return true;"""
|
||||||
|
|
||||||
def definition_body(self):
|
def definition_body(self):
|
||||||
|
@ -3844,7 +3851,8 @@ class CGDOMJSProxyHandler_get(CGAbstractExternMethod):
|
||||||
CGAbstractExternMethod.__init__(self, descriptor, "get", "bool", args)
|
CGAbstractExternMethod.__init__(self, descriptor, "get", "bool", args)
|
||||||
self.descriptor = descriptor
|
self.descriptor = descriptor
|
||||||
def getBody(self):
|
def getBody(self):
|
||||||
getFromExpando = """let expando = GetExpandoObject(proxy);
|
getFromExpando = """\
|
||||||
|
let expando = GetExpandoObject(proxy);
|
||||||
if expando.is_not_null() {
|
if expando.is_not_null() {
|
||||||
let mut hasProp = 0;
|
let mut hasProp = 0;
|
||||||
if JS_HasPropertyById(cx, expando, id, &mut hasProp) == 0 {
|
if JS_HasPropertyById(cx, expando, id, &mut hasProp) == 0 {
|
||||||
|
@ -3870,7 +3878,7 @@ if expando.is_not_null() {
|
||||||
" let this = JS::from_raw(this);\n" +
|
" let this = JS::from_raw(this);\n" +
|
||||||
" let this = this.root();\n" +
|
" let this = this.root();\n" +
|
||||||
CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define())
|
CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define())
|
||||||
getIndexedOrExpando += """
|
getIndexedOrExpando += """\
|
||||||
// Even if we don't have this index, we don't forward the
|
// Even if we don't have this index, we don't forward the
|
||||||
// get on to our expando object.
|
// get on to our expando object.
|
||||||
} else {
|
} else {
|
||||||
|
@ -3892,7 +3900,8 @@ if expando.is_not_null() {
|
||||||
else:
|
else:
|
||||||
getNamed = ""
|
getNamed = ""
|
||||||
|
|
||||||
return """//MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
|
return """\
|
||||||
|
//MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
|
||||||
//"Should not have a XrayWrapper here");
|
//"Should not have a XrayWrapper here");
|
||||||
|
|
||||||
%s
|
%s
|
||||||
|
@ -3931,8 +3940,7 @@ class CGDOMJSProxyHandler_obj_toString(CGAbstractExternMethod):
|
||||||
else:
|
else:
|
||||||
error = None
|
error = None
|
||||||
call = CGCallGenerator(error, [], "", returnType, extendedAttributes, self.descriptor, nativeName, False, object="UnwrapProxy(proxy)")
|
call = CGCallGenerator(error, [], "", returnType, extendedAttributes, self.descriptor, nativeName, False, object="UnwrapProxy(proxy)")
|
||||||
return call.define() + """
|
return call.define() + """\
|
||||||
|
|
||||||
JSString* jsresult;
|
JSString* jsresult;
|
||||||
return xpc_qsStringToJsstring(cx, result, &jsresult) ? jsresult : NULL;"""
|
return xpc_qsStringToJsstring(cx, result, &jsresult) ? jsresult : NULL;"""
|
||||||
|
|
||||||
|
@ -3966,9 +3974,10 @@ let this: *const %s = unwrap::<%s>(obj);
|
||||||
assert(False)
|
assert(False)
|
||||||
|
|
||||||
def finalizeHook(descriptor, hookName, context):
|
def finalizeHook(descriptor, hookName, context):
|
||||||
release = """let value = unwrap::<%s>(obj);
|
release = """\
|
||||||
|
let value = unwrap::<%s>(obj);
|
||||||
let _: Box<%s> = mem::transmute(value);
|
let _: Box<%s> = mem::transmute(value);
|
||||||
debug!("%s finalize: {:p}", this);
|
debug!("%s finalize: {:p}", this);\
|
||||||
""" % (descriptor.concreteType, descriptor.concreteType, descriptor.concreteType)
|
""" % (descriptor.concreteType, descriptor.concreteType, descriptor.concreteType)
|
||||||
return release
|
return release
|
||||||
|
|
||||||
|
@ -4027,10 +4036,7 @@ class CGDOMJSProxyHandlerDOMClass(CGThing):
|
||||||
self.descriptor = descriptor
|
self.descriptor = descriptor
|
||||||
|
|
||||||
def define(self):
|
def define(self):
|
||||||
return """
|
return "static Class: DOMClass = " + DOMClass(self.descriptor) + ";\n"
|
||||||
static Class: DOMClass = """ + DOMClass(self.descriptor) + """;
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
class CGInterfaceTrait(CGThing):
|
class CGInterfaceTrait(CGThing):
|
||||||
|
@ -4218,7 +4224,6 @@ class CGDescriptor(CGThing):
|
||||||
cgThings.append(CGInterfaceTrait(descriptor))
|
cgThings.append(CGInterfaceTrait(descriptor))
|
||||||
|
|
||||||
cgThings = CGList(cgThings, "\n")
|
cgThings = CGList(cgThings, "\n")
|
||||||
cgThings = CGWrapper(cgThings, pre='\n', post='\n')
|
|
||||||
#self.cgRoot = CGWrapper(CGNamespace(toBindingNamespace(descriptor.name),
|
#self.cgRoot = CGWrapper(CGNamespace(toBindingNamespace(descriptor.name),
|
||||||
# cgThings),
|
# cgThings),
|
||||||
# post='\n')
|
# post='\n')
|
||||||
|
@ -4350,8 +4355,8 @@ class CGDictionary(CGThing):
|
||||||
" }\n"
|
" }\n"
|
||||||
"}").substitute({
|
"}").substitute({
|
||||||
"selfName": self.makeClassName(d),
|
"selfName": self.makeClassName(d),
|
||||||
"initParent": CGIndenter(CGGeneric(initParent), indentLevel=6).define(),
|
"initParent": CGIndenter(CGGeneric(initParent), indentLevel=12).define(),
|
||||||
"initMembers": CGIndenter(memberInits, indentLevel=6).define(),
|
"initMembers": CGIndenter(memberInits, indentLevel=12).define(),
|
||||||
})
|
})
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
@ -4652,7 +4657,6 @@ class CGNativeMember(ClassMethod):
|
||||||
# have a non-void return type, as const.
|
# have a non-void return type, as const.
|
||||||
const=(not member.isStatic() and member.isAttr() and
|
const=(not member.isStatic() and member.isAttr() and
|
||||||
not signature[0].isVoid()),
|
not signature[0].isVoid()),
|
||||||
breakAfterReturnDecl=" ",
|
|
||||||
breakAfterSelf=breakAfterSelf,
|
breakAfterSelf=breakAfterSelf,
|
||||||
visibility=visibility)
|
visibility=visibility)
|
||||||
|
|
||||||
|
@ -4785,7 +4789,8 @@ class CGCallbackFunction(CGCallback):
|
||||||
|
|
||||||
class CGCallbackFunctionImpl(CGGeneric):
|
class CGCallbackFunctionImpl(CGGeneric):
|
||||||
def __init__(self, callback):
|
def __init__(self, callback):
|
||||||
impl = string.Template("""impl CallbackContainer for ${type} {
|
impl = string.Template("""\
|
||||||
|
impl CallbackContainer for ${type} {
|
||||||
fn new(callback: *mut JSObject) -> ${type} {
|
fn new(callback: *mut JSObject) -> ${type} {
|
||||||
${type}::new(callback)
|
${type}::new(callback)
|
||||||
}
|
}
|
||||||
|
@ -4799,7 +4804,7 @@ impl ToJSValConvertible for ${type} {
|
||||||
fn to_jsval(&self, cx: *mut JSContext) -> JSVal {
|
fn to_jsval(&self, cx: *mut JSContext) -> JSVal {
|
||||||
self.callback().to_jsval(cx)
|
self.callback().to_jsval(cx)
|
||||||
}
|
}
|
||||||
}
|
}\
|
||||||
""").substitute({"type": callback.name})
|
""").substitute({"type": callback.name})
|
||||||
CGGeneric.__init__(self, impl)
|
CGGeneric.__init__(self, impl)
|
||||||
|
|
||||||
|
@ -4867,7 +4872,7 @@ class CallbackMember(CGNativeMember):
|
||||||
jsObjectsArePtr=True)
|
jsObjectsArePtr=True)
|
||||||
# We have to do all the generation of our body now, because
|
# We have to do all the generation of our body now, because
|
||||||
# the caller relies on us throwing if we can't manage it.
|
# the caller relies on us throwing if we can't manage it.
|
||||||
self.exceptionCode= "return Err(FailureUnknown);\n"
|
self.exceptionCode= "return Err(FailureUnknown);"
|
||||||
self.body = self.getImpl()
|
self.body = self.getImpl()
|
||||||
|
|
||||||
def getImpl(self):
|
def getImpl(self):
|
||||||
|
@ -4959,7 +4964,7 @@ class CallbackMember(CGNativeMember):
|
||||||
conversion = string.Template(
|
conversion = string.Template(
|
||||||
"for idx in range(0, ${arg}.len()) {\n" +
|
"for idx in range(0, ${arg}.len()) {\n" +
|
||||||
CGIndenter(CGGeneric(conversion)).define() + "\n"
|
CGIndenter(CGGeneric(conversion)).define() + "\n"
|
||||||
"}\n"
|
"}"
|
||||||
).substitute({ "arg": arg.identifier.name })
|
).substitute({ "arg": arg.identifier.name })
|
||||||
elif arg.optional and not arg.defaultValue:
|
elif arg.optional and not arg.defaultValue:
|
||||||
conversion = (
|
conversion = (
|
||||||
|
@ -5064,7 +5069,7 @@ class CallCallback(CallbackMethod):
|
||||||
return "aThisObj"
|
return "aThisObj"
|
||||||
|
|
||||||
def getCallableDecl(self):
|
def getCallableDecl(self):
|
||||||
return "let callable = ObjectValue(unsafe {&*self.parent.callback()});\n";
|
return "let callable = ObjectValue(unsafe {&*self.parent.callback()});\n"
|
||||||
|
|
||||||
class CallbackOperationBase(CallbackMethod):
|
class CallbackOperationBase(CallbackMethod):
|
||||||
"""
|
"""
|
||||||
|
@ -5243,20 +5248,22 @@ class GlobalGenRoots():
|
||||||
(name + 'Derived', 'is_' + name.lower()))]
|
(name + 'Derived', 'is_' + name.lower()))]
|
||||||
for protoName in descriptor.prototypeChain[1:-1]:
|
for protoName in descriptor.prototypeChain[1:-1]:
|
||||||
protoDescriptor = config.getDescriptor(protoName)
|
protoDescriptor = config.getDescriptor(protoName)
|
||||||
delegate = string.Template('''impl ${selfName} for ${baseName} {
|
delegate = string.Template("""\
|
||||||
|
impl ${selfName} for ${baseName} {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn ${fname}(&self) -> bool {
|
fn ${fname}(&self) -> bool {
|
||||||
${parentName}Cast::from_actual(self).${fname}()
|
${parentName}Cast::from_actual(self).${fname}()
|
||||||
}
|
}
|
||||||
}
|
}\
|
||||||
''').substitute({'fname': 'is_' + name.lower(),
|
""").substitute({'fname': 'is_' + name.lower(),
|
||||||
'selfName': name + 'Derived',
|
'selfName': name + 'Derived',
|
||||||
'baseName': protoDescriptor.concreteType,
|
'baseName': protoDescriptor.concreteType,
|
||||||
'parentName': protoDescriptor.prototypeChain[-2]})
|
'parentName': protoDescriptor.prototypeChain[-2]})
|
||||||
derived += [CGGeneric(delegate)]
|
derived += [CGGeneric(delegate)]
|
||||||
derived += [CGGeneric('\n')]
|
derived += [CGGeneric('\n')]
|
||||||
|
|
||||||
cast = [CGGeneric(string.Template('''pub trait ${castTraitName} {
|
cast = [CGGeneric(string.Template("""\
|
||||||
|
pub trait ${castTraitName} {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, Self>> {
|
fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, Self>> {
|
||||||
match base.${checkFn}() {
|
match base.${checkFn}() {
|
||||||
|
@ -5304,7 +5311,7 @@ class GlobalGenRoots():
|
||||||
unsafe { mem::transmute(derived) }
|
unsafe { mem::transmute(derived) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
''').substitute({'checkFn': 'is_' + name.lower(),
|
""").substitute({'checkFn': 'is_' + name.lower(),
|
||||||
'castTraitName': name + 'Cast',
|
'castTraitName': name + 'Cast',
|
||||||
'fromBound': name + 'Base',
|
'fromBound': name + 'Base',
|
||||||
'toBound': name + 'Derived'})),
|
'toBound': name + 'Derived'})),
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue