Replace jsval_to_str and jsval_to_domstring with a FromJSValConvertible implementation.

This commit is contained in:
Ms2ger 2014-03-06 10:56:35 +01:00
parent 17411db8ca
commit 58382471d5
3 changed files with 49 additions and 56 deletions

View file

@ -1020,30 +1020,29 @@ for (uint32_t i = 0; i < length; ++i) {
} }
if treatNullAs not in treatAs: if treatNullAs not in treatAs:
raise TypeError("We don't support [TreatNullAs=%s]" % treatNullAs) raise TypeError("We don't support [TreatNullAs=%s]" % treatNullAs)
nullBehavior = treatAs[treatNullAs] if type.nullable():
nullBehavior = "()"
else:
nullBehavior = treatAs[treatNullAs]
def getConversionCode(varName, isOptional=False): def getConversionCode(isOptional=False):
strval = "strval" strval = "strval"
if isOptional: if isOptional:
strval = "Some(%s)" % strval strval = "Some(%s)" % strval
if type.nullable():
call = "jsval_to_domstring(cx, ${val})"
else:
call = "jsval_to_str(cx, ${val}, %s)" % nullBehavior
conversionCode = ( conversionCode = (
"let strval = %s;\n" "match FromJSValConvertible::from_jsval(cx, ${val}, %s) {\n"
"if strval.is_err() {\n" " Ok(strval) => ${declName} = %s,\n"
" return 0;\n" " Err(_) => return 0,\n"
"}\n" "}" % (nullBehavior, strval))
"let strval = strval.unwrap();\n"
"%s = %s;" % (call, varName, strval))
if defaultValue is None: if defaultValue is None:
return conversionCode return conversionCode
if isinstance(defaultValue, IDLNullValue): if isinstance(defaultValue, IDLNullValue):
assert(type.nullable()) assert(type.nullable())
return handleDefault(conversionCode, return handleDefault(conversionCode,
"%s.SetNull()" % varName) "${declName}.SetNull()")
value = "str::from_utf8(data).to_owned()" value = "str::from_utf8(data).to_owned()"
if type.nullable(): if type.nullable():
@ -1051,10 +1050,10 @@ for (uint32_t i = 0; i < length; ++i) {
default = ( default = (
"static data: [u8, ..%s] = [ %s ];\n" "static data: [u8, ..%s] = [ %s ];\n"
"%s = %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"]),
varName, value)) value))
return handleDefault(conversionCode, default) return handleDefault(conversionCode, default)
@ -1062,7 +1061,7 @@ for (uint32_t i = 0; i < length; ++i) {
# We have to make a copy, because our jsval may well not # We have to make a copy, because our jsval may well not
# live as long as our string needs to. # live as long as our string needs to.
declType = CGGeneric("DOMString") declType = CGGeneric("DOMString")
return ("%s\n" % getConversionCode("${declName}"), return ("%s\n" % getConversionCode(),
declType, None, isOptional, None) declType, None, isOptional, None)
declType = "DOMString" declType = "DOMString"
@ -1076,8 +1075,7 @@ for (uint32_t i = 0; i < length; ++i) {
return ( return (
"%s\n" % "%s\n" %
#"const_cast<%s&>(${declName}) = &${holderName};" % (getConversionCode(isOptional)),
(getConversionCode("${declName}", isOptional)),
CGGeneric(declType), None, #CGGeneric("FakeDependentString"), CGGeneric(declType), None, #CGGeneric("FakeDependentString"),
False, False,
initialValue) initialValue)
@ -5255,11 +5253,11 @@ class CGBindingRoot(CGThing):
'dom::bindings::utils::{CreateDOMGlobal, CreateInterfaceObjects2}', 'dom::bindings::utils::{CreateDOMGlobal, CreateInterfaceObjects2}',
'dom::bindings::utils::{ConstantSpec, cx_for_dom_object, Default}', 'dom::bindings::utils::{ConstantSpec, cx_for_dom_object, Default}',
'dom::bindings::utils::{dom_object_slot, DOM_OBJECT_SLOT, DOMClass}', 'dom::bindings::utils::{dom_object_slot, DOM_OBJECT_SLOT, DOMClass}',
'dom::bindings::utils::{DOMJSClass, Empty}', 'dom::bindings::utils::{DOMJSClass}',
'dom::bindings::utils::{FindEnumStringIndex, GetArrayIndexFromId}', 'dom::bindings::utils::{FindEnumStringIndex, GetArrayIndexFromId}',
'dom::bindings::utils::{GetPropertyOnPrototype, GetProtoOrIfaceArray}', 'dom::bindings::utils::{GetPropertyOnPrototype, GetProtoOrIfaceArray}',
'dom::bindings::utils::{GetReflector, HasPropertyOnPrototype, IntVal}', 'dom::bindings::utils::{GetReflector, HasPropertyOnPrototype, IntVal}',
'dom::bindings::utils::{jsid_to_str, jsval_to_domstring, jsval_to_str}', 'dom::bindings::utils::{jsid_to_str}',
'dom::bindings::utils::{NativePropertyHooks}', 'dom::bindings::utils::{NativePropertyHooks}',
'dom::bindings::utils::global_object_for_js_object', 'dom::bindings::utils::global_object_for_js_object',
'dom::bindings::utils::{Reflectable}', 'dom::bindings::utils::{Reflectable}',
@ -5272,6 +5270,7 @@ class CGBindingRoot(CGThing):
'dom::bindings::callback::{CallSetup,ExceptionHandling}', 'dom::bindings::callback::{CallSetup,ExceptionHandling}',
'dom::bindings::callback::{WrapCallThisObject}', 'dom::bindings::callback::{WrapCallThisObject}',
'dom::bindings::conversions::{FromJSValConvertible, ToJSValConvertible}', 'dom::bindings::conversions::{FromJSValConvertible, ToJSValConvertible}',
'dom::bindings::conversions::{Default, Empty}',
'dom::bindings::codegen::*', 'dom::bindings::codegen::*',
'dom::bindings::codegen::UnionTypes::*', 'dom::bindings::codegen::UnionTypes::*',
'dom::bindings::codegen::UnionConversions::*', 'dom::bindings::codegen::UnionConversions::*',

View file

@ -2,13 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::jsstring_to_str;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use js::jsapi::{JSBool, JSContext}; use js::jsapi::{JSBool, JSContext};
use js::jsapi::{JS_ValueToUint64, JS_ValueToInt64}; use js::jsapi::{JS_ValueToUint64, JS_ValueToInt64};
use js::jsapi::{JS_ValueToECMAUint32, JS_ValueToECMAInt32}; use js::jsapi::{JS_ValueToECMAUint32, JS_ValueToECMAInt32};
use js::jsapi::{JS_ValueToUint16, JS_ValueToNumber, JS_ValueToBoolean}; use js::jsapi::{JS_ValueToUint16, JS_ValueToNumber, JS_ValueToBoolean};
use js::jsapi::{JS_NewUCStringCopyN}; use js::jsapi::{JS_NewUCStringCopyN, JS_ValueToString};
use js::jsval::JSVal; use js::jsval::JSVal;
use js::jsval::{NullValue, BooleanValue, Int32Value, UInt32Value, StringValue}; use js::jsval::{NullValue, BooleanValue, Int32Value, UInt32Value, StringValue};
use js::glue::RUST_JS_NumberValue; use js::glue::RUST_JS_NumberValue;
@ -193,6 +194,34 @@ impl ToJSValConvertible for DOMString {
} }
} }
#[deriving(Eq)]
pub enum StringificationBehavior {
Default,
Empty,
}
impl Default for StringificationBehavior {
fn default() -> StringificationBehavior {
Default
}
}
impl FromJSValConvertible<StringificationBehavior> for DOMString {
fn from_jsval(cx: *JSContext, value: JSVal, nullBehavior: StringificationBehavior) -> Result<DOMString, ()> {
if nullBehavior == Empty && value.is_null() {
Ok(~"")
} else {
let jsstr = unsafe { JS_ValueToString(cx, value) };
if jsstr.is_null() {
debug!("JS_ValueToString failed");
Err(())
} else {
Ok(jsstring_to_str(cx, jsstr))
}
}
}
}
impl<T: ToJSValConvertible> ToJSValConvertible for Option<T> { impl<T: ToJSValConvertible> ToJSValConvertible for Option<T> {
fn to_jsval(&self, cx: *JSContext) -> JSVal { fn to_jsval(&self, cx: *JSContext) -> JSVal {
match self { match self {

View file

@ -161,41 +161,6 @@ pub fn jsid_to_str(cx: *JSContext, id: jsid) -> DOMString {
} }
} }
#[deriving(Eq)]
pub enum StringificationBehavior {
Default,
Empty,
}
pub fn jsval_to_str(cx: *JSContext, v: JSVal,
nullBehavior: StringificationBehavior) -> Result<DOMString, ()> {
if v.is_null() && nullBehavior == Empty {
Ok(~"")
} else {
let jsstr = unsafe { JS_ValueToString(cx, v) };
if jsstr.is_null() {
debug!("JS_ValueToString failed");
Err(())
} else {
Ok(jsstring_to_str(cx, jsstr))
}
}
}
pub fn jsval_to_domstring(cx: *JSContext, v: JSVal) -> Result<Option<DOMString>, ()> {
if v.is_null_or_undefined() {
Ok(None)
} else {
let jsstr = unsafe { JS_ValueToString(cx, v) };
if jsstr.is_null() {
debug!("JS_ValueToString failed");
Err(())
} else {
Ok(Some(jsstring_to_str(cx, jsstr)))
}
}
}
// We use slot 0 for holding the raw object. This is safe for both // We use slot 0 for holding the raw object. This is safe for both
// globals and non-globals. // globals and non-globals.
pub static DOM_OBJECT_SLOT: uint = 0; pub static DOM_OBJECT_SLOT: uint = 0;