auto merge of #1949 : Ms2ger/servo/cleanup-codegen, r=jdm

This commit is contained in:
bors-servo 2014-03-20 17:07:28 -04:00
commit 7bfb15ec62

View file

@ -92,13 +92,8 @@ class CastableObjectUnwrapper():
codeOnFailure is the code to run if unwrapping fails. codeOnFailure is the code to run if unwrapping fails.
""" """
def __init__(self, descriptor, source, target, codeOnFailure, isOptional=False, def __init__(self, descriptor, source, target, codeOnFailure, isOptional=False):
preUnwrapped=None, postUnwrapped=None):
assert descriptor.castable assert descriptor.castable
unwrappedVal = "val"
if preUnwrapped or postUnwrapped:
unwrappedVal = preUnwrapped + unwrappedVal + postUnwrapped
self.substitution = { "type" : descriptor.nativeType, self.substitution = { "type" : descriptor.nativeType,
"depth": descriptor.interface.inheritanceDepth(), "depth": descriptor.interface.inheritanceDepth(),
"prototype": "PrototypeList::id::" + descriptor.name, "prototype": "PrototypeList::id::" + descriptor.name,
@ -106,7 +101,7 @@ class CastableObjectUnwrapper():
"source" : source, "source" : source,
"target" : target, "target" : target,
"codeOnFailure" : CGIndenter(CGGeneric(codeOnFailure), 4).define(), "codeOnFailure" : CGIndenter(CGGeneric(codeOnFailure), 4).define(),
"unwrapped_val" : ("Some(%s)" % unwrappedVal) if isOptional else unwrappedVal, "unwrapped_val" : "Some(val)" if isOptional else "val",
"unwrapFn": "unwrap_jsmanaged" if 'JS' in descriptor.nativeType else "unwrap_object"} "unwrapFn": "unwrap_jsmanaged" if 'JS' in descriptor.nativeType else "unwrap_object"}
def __str__(self): def __str__(self):
@ -428,9 +423,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
isClamp=False, isClamp=False,
exceptionCode=None, exceptionCode=None,
isCallbackReturnValue=False, isCallbackReturnValue=False,
sourceDescription="value", sourceDescription="value"):
preSuccess=None,
postSuccess=None):
""" """
Get a template for converting a JS value to a native object based on the Get a template for converting a JS value to a native object based on the
given type and descriptor. If failureCode is given, then we're actually given type and descriptor. If failureCode is given, then we're actually
@ -543,14 +536,9 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
def handleDefault(template, setDefault): def handleDefault(template, setDefault):
if defaultValue is None: if defaultValue is None:
return template return template
return CGWrapper( return CGIfElseWrapper("${haveValue}",
CGIndenter(CGGeneric(template)), CGGeneric(template),
pre="if ${haveValue} {\n", CGGeneric(setDefault)).define()
post=("\n"
"} else {\n"
"%s;\n"
"}" %
CGIndenter(CGGeneric(setDefault)).define())).define()
# A helper function for handling null default values. Much like # A helper function for handling null default values. Much like
# handleDefault, but checks that the default value, if it exists, is null. # handleDefault, but checks that the default value, if it exists, is null.
@ -563,7 +551,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
# A helper function for wrapping up the template body for # A helper function for wrapping up the template body for
# possibly-nullable objecty stuff # possibly-nullable objecty stuff
def wrapObjectTemplate(templateBody, isDefinitelyObject, type, def wrapObjectTemplate(templateBody, isDefinitelyObject, type,
codeToSetNull, failureCode=None): failureCode=None):
if not isDefinitelyObject: if not isDefinitelyObject:
# Handle the non-object cases by wrapping up the whole # Handle the non-object cases by wrapping up the whole
# thing in an if cascade. # thing in an if cascade.
@ -573,13 +561,13 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
if type.nullable(): if type.nullable():
templateBody += ( templateBody += (
"} else if (${val}).is_null_or_undefined() {\n" "} else if (${val}).is_null_or_undefined() {\n"
" %s;\n" % codeToSetNull) " ${declName} = None;\n")
templateBody += ( templateBody += (
"} else {\n" + "} else {\n" +
CGIndenter(onFailureNotAnObject(failureCode)).define() + CGIndenter(onFailureNotAnObject(failureCode)).define() +
"}") "}")
if type.nullable(): if type.nullable():
templateBody = handleDefaultNull(templateBody, codeToSetNull) templateBody = handleDefaultNull(templateBody, "${declName} = None;")
else: else:
assert(defaultValue is None) assert(defaultValue is None)
@ -616,7 +604,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
templateBody) templateBody)
templateBody = handleDefaultNull(templateBody.define(), templateBody = handleDefaultNull(templateBody.define(),
"${declName} = None") "${declName} = None;")
return (templateBody, declType, None, isOptional, "None" if isOptional else None) return (templateBody, declType, None, isOptional, "None" if isOptional else None)
@ -632,7 +620,6 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
conversion = ("${declName} = Some(%s::new((${val}).to_object()));" % name) conversion = ("${declName} = Some(%s::new((${val}).to_object()));" % name)
template = wrapObjectTemplate(conversion, isDefinitelyObject, type, template = wrapObjectTemplate(conversion, isDefinitelyObject, type,
"${declName} = None",
failureCode) failureCode)
return (template, declType, None, isOptional, None) return (template, declType, None, isOptional, None)
@ -654,8 +641,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
"(${val}).to_object()", "(${val}).to_object()",
"${declName}", "${declName}",
failureCode, failureCode,
isOptional or type.nullable(), isOptional or type.nullable()))
preUnwrapped=preSuccess, postUnwrapped=postSuccess))
else: else:
templateBody += str(FailureFatalCastableObjectUnwrapper( templateBody += str(FailureFatalCastableObjectUnwrapper(
descriptor, descriptor,
@ -675,8 +661,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
"}\n") "}\n")
templateBody = wrapObjectTemplate(templateBody, isDefinitelyObject, templateBody = wrapObjectTemplate(templateBody, isDefinitelyObject,
type, "${declName} = None", type, failureCode)
failureCode)
declType = CGGeneric(typePtr) declType = CGGeneric(typePtr)
if type.nullable() or isOptional: if type.nullable() or isOptional:
@ -718,7 +703,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
if isinstance(defaultValue, IDLNullValue): if isinstance(defaultValue, IDLNullValue):
assert(type.nullable()) assert(type.nullable())
return handleDefault(conversionCode, return handleDefault(conversionCode,
"${declName}.SetNull()") "${declName}.SetNull();")
value = "str::from_utf8(data).unwrap().to_owned()" value = "str::from_utf8(data).unwrap().to_owned()"
if type.nullable(): if type.nullable():
@ -726,7 +711,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
default = ( default = (
"static data: [u8, ..%s] = [ %s ];\n" "static data: [u8, ..%s] = [ %s ];\n"
"${declName} = %s" % "${declName} = %s;" %
(len(defaultValue.value) + 1, (len(defaultValue.value) + 1,
", ".join(["'" + char + "' as u8" for char in defaultValue.value] + ["0"]), ", ".join(["'" + char + "' as u8" for char in defaultValue.value] + ["0"]),
value)) value))
@ -786,7 +771,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
assert(defaultValue.type.tag() == IDLType.Tags.domstring) assert(defaultValue.type.tag() == IDLType.Tags.domstring)
template = "" #XXXjdm unfinished template = "" #XXXjdm unfinished
#template = handleDefault(template, #template = handleDefault(template,
# ("${declName} = %sValues::%s" % # ("${declName} = %sValues::%s;" %
# (enum, # (enum,
# getEnumValueName(defaultValue.value)))) # getEnumValueName(defaultValue.value))))
return (template, CGGeneric(enum), None, isOptional, None) return (template, CGGeneric(enum), None, isOptional, None)
@ -826,7 +811,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
templateBody = "${declName} = %s;" % value.define() templateBody = "${declName} = %s;" % value.define()
templateBody = handleDefaultNull(templateBody, templateBody = handleDefaultNull(templateBody,
"${declName} = NullValue()") "${declName} = NullValue();")
return (templateBody, declType, None, isOptional, "None" if isOptional else None) return (templateBody, declType, None, isOptional, "None" if isOptional else None)
@ -886,15 +871,12 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
if failureCode is None: if failureCode is None:
failureCode = 'return 0' failureCode = 'return 0'
successVal = "v"
if preSuccess or postSuccess:
successVal = preSuccess + successVal + postSuccess
#XXXjdm support conversionBehavior here #XXXjdm support conversionBehavior here
template = ( template = (
"match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n" "match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n"
" Ok(v) => ${declName} = %s,\n" " Ok(v) => ${declName} = v,\n"
" Err(_) => { %s }\n" " Err(_) => { %s }\n"
"}" % (successVal, exceptionCode)) "}" % exceptionCode)
declType = CGGeneric(builtinNames[type.tag()]) declType = CGGeneric(builtinNames[type.tag()])
if type.nullable(): if type.nullable():
@ -918,12 +900,9 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
if type.nullable(): if type.nullable():
defaultStr = "Some(%s)" % defaultStr defaultStr = "Some(%s)" % defaultStr
template = CGWrapper(CGIndenter(CGGeneric(template)), template = CGIfElseWrapper("${haveValue}",
pre="if ${haveValue} {\n", CGGeneric(template),
post=("\n" CGGeneric("${declName} = %s;" % defaultStr)).define()
"} else {\n"
" ${declName} = %s;\n"
"}" % defaultStr)).define()
return (template, declType, None, isOptional, "None" if isOptional else None) return (template, declType, None, isOptional, "None" if isOptional else None)
@ -1216,13 +1195,11 @@ def typeNeedsCx(type, retVal=False):
def memberIsCreator(member): def memberIsCreator(member):
return member.getExtendedAttribute("Creator") is not None return member.getExtendedAttribute("Creator") is not None
# Returns a tuple consisting of a CGThing containing the type of the return # Returns a CGThing containing the type of the return value.
# value, or None if there is no need for a return value, and a boolean signaling
# whether the return value is passed in an out parameter.
def getRetvalDeclarationForType(returnType, descriptorProvider): def getRetvalDeclarationForType(returnType, descriptorProvider):
if returnType is None or returnType.isVoid(): if returnType is None or returnType.isVoid():
# Nothing to declare # Nothing to declare
return None return CGGeneric("()")
if returnType.isPrimitive() and returnType.tag() in builtinNames: if returnType.isPrimitive() and returnType.tag() in builtinNames:
result = CGGeneric(builtinNames[returnType.tag()]) result = CGGeneric(builtinNames[returnType.tag()])
if returnType.nullable(): if returnType.nullable():
@ -2407,7 +2384,7 @@ class CGCallGenerator(CGThing):
""" """
def __init__(self, errorReport, arguments, argsPre, returnType, def __init__(self, errorReport, arguments, argsPre, returnType,
extendedAttributes, descriptorProvider, nativeMethodName, extendedAttributes, descriptorProvider, nativeMethodName,
static, object="this", declareResult=True): static, object="this"):
CGThing.__init__(self) CGThing.__init__(self)
assert errorReport is None or isinstance(errorReport, CGThing) assert errorReport is None or isinstance(errorReport, CGThing)
@ -2447,19 +2424,16 @@ class CGCallGenerator(CGThing):
call = CGList([call, CGWrapper(args, pre="(", post=");")]) call = CGList([call, CGWrapper(args, pre="(", post=");")])
if isFallible: if isFallible:
self.cgRoot.prepend(CGWrapper(result if result is not None else CGGeneric("()"), self.cgRoot.prepend(CGWrapper(result,
pre="let mut result_fallible: Result<", post=",Error>;")) pre="let result_fallible: Result<", post=",Error>;"))
if result is not None and declareResult: result = CGWrapper(result, pre="let result: ", post=";")
result = CGWrapper(result, pre="let mut result: ", post=";") self.cgRoot.prepend(result)
self.cgRoot.prepend(result)
if isFallible: if isFallible:
call = CGWrapper(call, pre="result_fallible = ") call = CGWrapper(call, pre="result_fallible = ")
elif result is not None:
call = CGWrapper(call, pre="result = ")
else: else:
call = CGWrapper(call, pre="let _: () = ") call = CGWrapper(call, pre="result = ")
call = CGWrapper(call) call = CGWrapper(call)
self.cgRoot.append(call) self.cgRoot.append(call)
@ -2468,8 +2442,7 @@ class CGCallGenerator(CGThing):
self.cgRoot.append(CGGeneric("if result_fallible.is_err() {")) self.cgRoot.append(CGGeneric("if result_fallible.is_err() {"))
self.cgRoot.append(CGIndenter(errorReport)) self.cgRoot.append(CGIndenter(errorReport))
self.cgRoot.append(CGGeneric("}")) self.cgRoot.append(CGGeneric("}"))
if result is not None: self.cgRoot.append(CGGeneric("result = result_fallible.unwrap();"))
self.cgRoot.append(CGGeneric("result = result_fallible.unwrap();"))
def define(self): def define(self):
return self.cgRoot.define() return self.cgRoot.define()
@ -4820,7 +4793,6 @@ class CGBindingRoot(CGThing):
'std::vec', 'std::vec',
'std::str', 'std::str',
'std::num', 'std::num',
'std::intrinsics::uninit',
]) ])
# Add the auto-generated comment. # Add the auto-generated comment.