Update rustc to 00b112c45a604fa6f4b59af2a40c9deeadfdb7c6/rustc-1.0.0-dev.

This commit is contained in:
Josh Matthews 2015-01-15 13:26:44 -05:00 committed by Glenn Watson
parent ff8cbff810
commit 95fc29fa0d
255 changed files with 3550 additions and 3362 deletions

View file

@ -14,10 +14,11 @@ use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException
use js::jsval::{JSVal, UndefinedValue};
use js::rust::with_compartment;
use std::ffi::CString;
use std::ptr;
/// The exception handling used for a call.
#[deriving(Copy, PartialEq)]
#[derive(Copy, PartialEq)]
pub enum ExceptionHandling {
/// Report any exception and don't throw it to the caller code.
Report,
@ -26,7 +27,7 @@ pub enum ExceptionHandling {
}
/// A common base class for representing IDL callback function types.
#[deriving(Copy, Clone,PartialEq)]
#[derive(Copy, Clone,PartialEq)]
#[jstraceable]
pub struct CallbackFunction {
object: CallbackObject
@ -44,7 +45,7 @@ impl CallbackFunction {
}
/// A common base class for representing IDL callback interface types.
#[deriving(Copy, Clone,PartialEq)]
#[derive(Copy, Clone,PartialEq)]
#[jstraceable]
pub struct CallbackInterface {
object: CallbackObject
@ -53,7 +54,7 @@ pub struct CallbackInterface {
/// A common base class for representing IDL callback function and
/// callback interface types.
#[allow(raw_pointer_deriving)]
#[deriving(Copy, Clone,PartialEq)]
#[derive(Copy, Clone,PartialEq)]
#[jstraceable]
struct CallbackObject {
/// The underlying `JSObject`.
@ -99,7 +100,7 @@ impl CallbackInterface {
pub fn GetCallableProperty(&self, cx: *mut JSContext, name: &str) -> Result<JSVal, ()> {
let mut callable = UndefinedValue();
unsafe {
let name = name.to_c_str();
let name = CString::from_slice(name.as_bytes());
if JS_GetProperty(cx, self.callback(), name.as_ptr(), &mut callable) == 0 {
return Err(());
}

View file

@ -15,7 +15,7 @@
DOMInterfaces = {
'Window': {
'outerObjectHook': 'Some(bindings::utils::outerize_global)',
'outerObjectHook': 'Some(bindings::utils::outerize_global as extern fn(*mut JSContext, JSHandleObject) -> *mut JSObject)',
},
#FIXME(jdm): This should be 'register': False, but then we don't generate enum types

View file

@ -679,7 +679,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
value = "Some(%s)" % value
default = (
"const data: [u8, ..%s] = [ %s ];\n"
"const data: [u8; %s] = [ %s ];\n"
"%s" %
(len(defaultValue.value) + 1,
", ".join(["'" + char + "' as u8" for char in defaultValue.value] + ["0"]),
@ -1189,14 +1189,16 @@ class MethodDefiner(PropertyDefiner):
def specData(m):
if m.get("methodInfo", True):
jitinfo = ("&%s_methodinfo" % m["name"])
accessor = "genericMethod"
accessor = "genericMethod as NonNullJSNative"
else:
jitinfo = "0 as *const JSJitInfo"
accessor = m.get("nativeName", m["name"])
if accessor[0:3] != 'JS_':
accessor = "%s as NonNullJSNative" % accessor
return (m["name"], accessor, jitinfo, m["length"], m["flags"])
def stringDecl(m):
return "const %s_name: [u8, ..%i] = %s;\n" % (m["name"], len(m["name"]) + 1,
return "const %s_name: [u8; %i] = %s;\n" % (m["name"], len(m["name"]) + 1,
str_to_const_array(m["name"]))
decls = ''.join([stringDecl(m) for m in array])
@ -1236,7 +1238,7 @@ class AttrDefiner(PropertyDefiner):
accessor = "genericGetter"
jitinfo = "&%s_getterinfo" % attr.identifier.name
return ("JSPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *const JSJitInfo}"
return ("JSPropertyOpWrapper {op: Some(%(native)s as NonNullJSNative), info: %(info)s as *const JSJitInfo}"
% {"info" : jitinfo,
"native" : accessor})
@ -1254,7 +1256,7 @@ class AttrDefiner(PropertyDefiner):
accessor = "genericSetter"
jitinfo = "&%s_setterinfo" % attr.identifier.name
return ("JSStrictPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *const JSJitInfo}"
return ("JSStrictPropertyOpWrapper {op: Some(%(native)s as NonNullJSNative), info: %(info)s as *const JSJitInfo}"
% {"info" : jitinfo,
"native" : accessor})
@ -1264,7 +1266,7 @@ class AttrDefiner(PropertyDefiner):
def stringDecl(attr):
name = attr.identifier.name
return "const %s_name: [u8, ..%i] = %s;\n" % (name, len(name) + 1,
return "const %s_name: [u8; %i] = %s;\n" % (name, len(name) + 1,
str_to_const_array(name))
decls = ''.join([stringDecl(m) for m in array])
@ -1434,7 +1436,7 @@ class CGDOMJSClass(CGThing):
self.descriptor = descriptor
def define(self):
traceHook = "Some(%s)" % TRACE_HOOK_NAME
traceHook = 'Some(%s as unsafe extern "C" fn(*mut JSTracer, *mut JSObject))' % TRACE_HOOK_NAME
if self.descriptor.isGlobal():
flags = "JSCLASS_IS_GLOBAL | JSCLASS_DOM_GLOBAL"
slots = "JSCLASS_GLOBAL_SLOT_COUNT + 1"
@ -1442,7 +1444,7 @@ class CGDOMJSClass(CGThing):
flags = "0"
slots = "1"
return """\
const Class_name: [u8, ..%i] = %s;
const Class_name: [u8; %i] = %s;
static Class: DOMJSClass = DOMJSClass {
base: js::Class {
name: &Class_name as *const u8 as *const libc::c_char,
@ -1454,7 +1456,7 @@ static Class: DOMJSClass = DOMJSClass {
enumerate: Some(JS_EnumerateStub),
resolve: Some(JS_ResolveStub),
convert: Some(JS_ConvertStub),
finalize: Some(%s),
finalize: Some(%s as unsafe extern "C" fn(*mut JSFreeOp, *mut JSObject)),
checkAccess: None,
call: None,
hasInstance: None,
@ -1526,7 +1528,7 @@ class CGPrototypeJSClass(CGThing):
def define(self):
return """\
const PrototypeClassName__: [u8, ..%s] = %s;
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)
@ -1543,7 +1545,7 @@ static PrototypeClass: JSClass = JSClass {
hasInstance: None,
construct: None,
trace: None,
reserved: [0 as *mut libc::c_void, ..40]
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"))
@ -1992,7 +1994,7 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod):
constructHook = "ThrowingConstructor"
constructArgs = 0
constructor = 'Some((%s, "%s", %d))' % (
constructor = 'Some((%s as NonNullJSNative, "%s", %d))' % (
constructHook, self.descriptor.interface.identifier.name,
constructArgs)
else:
@ -2096,16 +2098,16 @@ 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_),
getPropertyDescriptor: Some(getPropertyDescriptor as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, bool, *mut JSPropertyDescriptor) -> bool),
getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, bool, *mut JSPropertyDescriptor) -> bool),
defineProperty: Some(%s as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut JSPropertyDescriptor) -> bool),
getOwnPropertyNames: Some(getOwnPropertyNames_ as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut AutoIdVector) -> bool),
delete_: Some(%s as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut bool) -> bool),
enumerate: Some(enumerate_ as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut AutoIdVector) -> bool),
has: None,
hasOwn: Some(hasOwn),
get: Some(get),
hasOwn: Some(hasOwn as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut bool) -> bool),
get: Some(get as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut JSObject, jsid, *mut JSVal) -> bool),
set: None,
keys: None,
iterate: None,
@ -2116,15 +2118,15 @@ let traps = ProxyTraps {
hasInstance: None,
typeOf: None,
objectClassIs: None,
obj_toString: Some(obj_toString),
obj_toString: Some(obj_toString as unsafe extern "C" fn(*mut JSContext, *mut JSObject) -> *mut js::jsapi::JSString),
fun_toString: None,
//regexp_toShared: ptr::null(),
defaultValue: None,
iteratorNext: None,
finalize: Some(%s),
finalize: Some(%s as unsafe extern "C" fn(*mut JSFreeOp, *mut JSObject)),
getElementIfPresent: None,
getPrototypeOf: None,
trace: Some(%s)
trace: Some(%s as unsafe extern "C" fn(*mut JSTracer, *mut JSObject))
};
CreateProxyHandler(&traps, &Class as *const _ as *const _)\
@ -2763,7 +2765,7 @@ class CGEnum(CGThing):
decl = """\
#[repr(uint)]
#[deriving(PartialEq, Copy)]
#[derive(PartialEq, Copy)]
#[jstraceable]
pub enum %s {
%s
@ -4256,7 +4258,7 @@ class CGNonNamespacedEnum(CGThing):
# Build the enum body.
enumstr = comment + 'pub enum %s {\n%s\n}\n' % (enumName, ',\n'.join(entries))
if deriving:
enumstr = ('#[deriving(%s)]\n' % deriving) + enumstr
enumstr = ('#[derive(%s)]\n' % deriving) + enumstr
curr = CGGeneric(enumstr)
# Add some whitespace padding.
@ -4458,7 +4460,7 @@ class CGRegisterProxyHandlers(CGThing):
descriptors = config.getDescriptors(proxy=True)
length = len(descriptors)
self.root = CGList([
CGGeneric("pub static mut proxy_handlers: [*const libc::c_void, ..%d] = [0 as *const libc::c_void, ..%d];" % (length, length)),
CGGeneric("pub static mut proxy_handlers: [*const libc::c_void; %d] = [0 as *const libc::c_void; %d];" % (length, length)),
CGRegisterProxyHandlersMethod(descriptors),
], "\n")
@ -4530,11 +4532,12 @@ class CGBindingRoot(CGThing):
'js::jsapi::{JSPropertyOpWrapper, JSPropertySpec, JS_PropertyStub}',
'js::jsapi::{JSStrictPropertyOpWrapper, JSString, JSTracer, JS_ConvertStub}',
'js::jsapi::{JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub}',
'js::jsapi::{JSMutableHandleValue, JSHandleId, JSType}',
'js::jsval::JSVal',
'js::jsval::{ObjectValue, ObjectOrNullValue, PrivateValue}',
'js::jsval::{NullValue, UndefinedValue}',
'js::glue::{CallJitMethodOp, CallJitPropertyOp, CreateProxyHandler}',
'js::glue::{GetProxyPrivate, NewProxyObject, ProxyTraps}',
'js::glue::{GetProxyPrivate, NewProxyObject, ProxyTraps, AutoIdVector}',
'js::glue::{RUST_FUNCTION_VALUE_TO_JITINFO}',
'js::glue::{RUST_JS_NumberValue, RUST_JSID_IS_STRING}',
'js::rust::with_compartment',
@ -4559,6 +4562,7 @@ class CGBindingRoot(CGThing):
'dom::bindings::utils::get_dictionary_property',
'dom::bindings::utils::{NativeProperties, NativePropertyHooks}',
'dom::bindings::utils::ConstantVal::{IntVal, UintVal}',
'dom::bindings::utils::NonNullJSNative',
'dom::bindings::trace::JSTraceable',
'dom::bindings::callback::{CallbackContainer,CallbackInterface,CallbackFunction}',
'dom::bindings::callback::{CallSetup,ExceptionHandling}',
@ -4696,7 +4700,7 @@ class CGCallback(CGClass):
bases=[ClassBase(baseName)],
constructors=self.getConstructors(),
methods=realMethods+getters+setters,
decorators="#[deriving(PartialEq,Copy,Clone)]#[jstraceable]")
decorators="#[derive(PartialEq,Copy,Clone)]#[jstraceable]")
def getConstructors(self):
return [ClassConstructor(
@ -5225,11 +5229,11 @@ class GlobalGenRoots():
CGGeneric("use std::mem;\n\n")]
for descriptor in descriptors:
name = descriptor.name
protos = [CGGeneric('pub trait %s {}\n' % (name + 'Base'))]
protos = [CGGeneric('pub trait %s : Sized {}\n' % (name + 'Base'))]
for proto in descriptor.prototypeChain:
protos += [CGGeneric('impl %s for %s {}\n' % (proto + 'Base',
descriptor.concreteType))]
derived = [CGGeneric('pub trait %s { fn %s(&self) -> bool; }\n' %
derived = [CGGeneric('pub trait %s : Sized { fn %s(&self) -> bool; }\n' %
(name + 'Derived', 'is_' + name.lower()))]
for protoName in descriptor.prototypeChain[1:-1]:
protoDescriptor = config.getDescriptor(protoName)
@ -5237,7 +5241,8 @@ class GlobalGenRoots():
impl ${selfName} for ${baseName} {
#[inline]
fn ${fname}(&self) -> bool {
${parentName}Cast::from_actual(self).${fname}()
let base: &${parentName} = ${parentName}Cast::from_actual(self);
base.${fname}()
}
}\
""").substitute({'fname': 'is_' + name.lower(),
@ -5248,7 +5253,7 @@ impl ${selfName} for ${baseName} {
derived += [CGGeneric('\n')]
cast = [CGGeneric(string.Template("""\
pub trait ${castTraitName} {
pub trait ${castTraitName} : Sized {
#[inline(always)]
fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, Self>> {
match base.${checkFn}() {

View file

@ -45,7 +45,7 @@ pub trait IDLInterface {
}
/// A trait to convert Rust types to `JSVal`s.
pub trait ToJSValConvertible for Sized? {
pub trait ToJSValConvertible {
/// Convert `self` to a `JSVal`. JSAPI failure causes a task failure.
fn to_jsval(&self, cx: *mut JSContext) -> JSVal;
}
@ -253,7 +253,7 @@ impl ToJSValConvertible for DOMString {
}
/// Behavior for stringification of `JSVal`s.
#[deriving(PartialEq)]
#[derive(PartialEq)]
pub enum StringificationBehavior {
/// Convert `null` to the string `"null"`.
Default,
@ -498,6 +498,7 @@ impl<T: ToJSValConvertible> ToJSValConvertible for Option<T> {
}
}
#[old_impl_check]
impl<X: default::Default, T: FromJSValConvertible<X>> FromJSValConvertible<()> for Option<T> {
fn from_jsval(cx: *mut JSContext, value: JSVal, _: ()) -> Result<Option<T>, ()> {
if value.is_null_or_undefined() {

View file

@ -18,10 +18,11 @@ use js::glue::{ReportError};
use js::rust::with_compartment;
use libc;
use std::ffi::CString;
use std::ptr;
/// DOM exceptions that can be thrown by a native DOM method.
#[deriving(Show, Clone)]
#[derive(Show, Clone)]
pub enum Error {
/// IndexSizeError
IndexSize,
@ -95,14 +96,13 @@ pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) {
pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) -> JSBool {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let message = format!("argument could not be converted to any of: {}", names);
message.with_c_str(|string| {
unsafe { ReportError(cx, string) };
});
let string = CString::from_slice(message.as_bytes());
unsafe { ReportError(cx, string.as_ptr()) };
return 0;
}
/// Format string used to throw `TypeError`s.
static ERROR_FORMAT_STRING_STRING: [libc::c_char, ..4] = [
const ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [
'{' as libc::c_char,
'0' as libc::c_char,
'}' as libc::c_char,
@ -110,7 +110,7 @@ static ERROR_FORMAT_STRING_STRING: [libc::c_char, ..4] = [
];
/// Format string struct used to throw `TypeError`s.
static ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
const ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSEXN_TYPEERR as i16,
@ -127,8 +127,12 @@ unsafe extern fn get_error_message(_user_ref: *mut libc::c_void,
/// Throw a `TypeError` with the given message.
pub fn throw_type_error(cx: *mut JSContext, error: &str) {
let error = error.to_c_str();
let error = CString::from_slice(error.as_bytes());
unsafe {
JS_ReportErrorNumber(cx, Some(get_error_message), ptr::null_mut(), 0, error.as_ptr());
JS_ReportErrorNumber(cx,
Some(get_error_message as
unsafe extern "C" fn(*mut libc::c_void, *const libc::c_char,
libc::c_uint) -> *const JSErrorFormatString),
ptr::null_mut(), 0, error.as_ptr());
}
}

View file

@ -28,7 +28,7 @@ use url::Url;
use std::ptr;
/// A freely-copyable reference to a rooted global object.
#[deriving(Copy)]
#[derive(Copy)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),

View file

@ -57,8 +57,9 @@ use script_task::STACK_ROOTS;
use servo_util::smallvec::{SmallVec, SmallVec16};
use std::cell::{Cell, UnsafeCell};
use std::default::Default;
use std::kinds::marker::ContravariantLifetime;
use std::marker::ContravariantLifetime;
use std::mem;
use std::ops::Deref;
/// A type that represents a JS-owned value that is rooted for the lifetime of this value.
/// Importantly, it requires explicit rooting in order to interact with the inner value.
@ -176,6 +177,7 @@ impl<T: Reflectable> JS<T> {
}
}
#[old_impl_check]
impl<T: Assignable<U>, U: Reflectable> JS<U> {
/// Create a `JS<T>` from any JS-managed pointer.
pub fn from_rooted(root: T) -> JS<U> {
@ -246,6 +248,7 @@ pub struct MutNullableJS<T: Reflectable> {
ptr: Cell<Option<JS<T>>>
}
#[old_impl_check]
impl<T: Assignable<U>, U: Reflectable> MutNullableJS<U> {
/// Create a new `MutNullableJS`
pub fn new(initial: Option<T>) -> MutNullableJS<U> {
@ -295,7 +298,9 @@ impl<T: Reflectable> MutNullableJS<T> {
/// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first.
pub fn or_init(&self, cb: || -> Temporary<T>) -> Temporary<T> {
pub fn or_init<F>(&self, cb: F) -> Temporary<T>
where F: FnOnce() -> Temporary<T>
{
match self.get() {
Some(inner) => inner,
None => {
@ -323,6 +328,7 @@ impl<T: Reflectable> JS<T> {
}
}
#[old_impl_check]
impl<From, To> JS<From> {
/// Return `self` as a `JS` of another type.
//XXXjdm It would be lovely if this could be private.
@ -500,7 +506,7 @@ impl RootCollection {
unsafe {
let roots = self.roots.get();
(*roots).push(untracked.js_ptr);
debug!(" rooting {}", untracked.js_ptr);
debug!(" rooting {:?}", untracked.js_ptr);
}
}
@ -508,7 +514,7 @@ impl RootCollection {
fn unroot<'b, T: Reflectable>(&self, rooted: &Root<T>) {
unsafe {
let roots = self.roots.get();
debug!("unrooting {} (expecting {}",
debug!("unrooting {:?} (expecting {:?}",
(*roots).as_slice().last().unwrap(),
rooted.js_ptr);
assert!(*(*roots).as_slice().last().unwrap() == rooted.js_ptr);
@ -565,13 +571,15 @@ impl<T: Reflectable> Drop for Root<T> {
}
}
impl<'b, T: Reflectable> Deref<JSRef<'b, T>> for Root<T> {
impl<'b, T: Reflectable> Deref for Root<T> {
type Target = JSRef<'b, T>;
fn deref<'c>(&'c self) -> &'c JSRef<'b, T> {
&self.jsref
}
}
impl<'a, T: Reflectable> Deref<T> for JSRef<'a, T> {
impl<'a, T: Reflectable> Deref for JSRef<'a, T> {
type Target = T;
fn deref<'b>(&'b self) -> &'b T {
unsafe {
&*self.ptr

View file

@ -32,15 +32,17 @@ use js::jsapi::{JS_AddObjectRoot, JS_RemoveObjectRoot, JSContext};
use libc;
use std::cell::RefCell;
use std::collections::hash_map::{HashMap, Vacant, Occupied};
use std::collections::hash_map::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None)))
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None)));
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
@ -55,6 +57,8 @@ pub struct Trusted<T> {
owner_thread: *const libc::c_void,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
@ -91,7 +95,7 @@ impl<T: Reflectable> Trusted<T> {
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock();
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
@ -107,7 +111,7 @@ impl<T: Reflectable> Clone for Trusted<T> {
#[unsafe_destructor]
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock();
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
@ -139,7 +143,7 @@ impl LiveDOMReferences {
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock() += 1;
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
@ -148,7 +152,7 @@ impl LiveDOMReferences {
JS_AddObjectRoot(cx, rootable);
}
let refcount = Arc::new(Mutex::new(1));
entry.set(refcount.clone());
entry.insert(refcount.clone());
refcount
}
}
@ -164,7 +168,7 @@ impl LiveDOMReferences {
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock() != 0 {
if *entry.get().lock().unwrap() != 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
@ -173,7 +177,7 @@ impl LiveDOMReferences {
unsafe {
JS_RemoveObjectRoot(cx, (*reflectable).rootable());
}
let _ = entry.take();
let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new

View file

@ -7,12 +7,12 @@
//! The `ByteString` struct.
use std::borrow::ToOwned;
use std::hash::{Hash, sip};
use std::hash::{Hash, SipHasher};
use std::str;
use std::str::FromStr;
/// Encapsulates the IDL `ByteString` type.
#[deriving(Clone,Eq,PartialEq)]
#[derive(Clone,Eq,PartialEq)]
#[jstraceable]
pub struct ByteString(Vec<u8>);
@ -26,7 +26,7 @@ impl ByteString {
/// otherwise.
pub fn as_str<'a>(&'a self) -> Option<&'a str> {
let ByteString(ref vec) = *self;
str::from_utf8(vec.as_slice())
str::from_utf8(vec.as_slice()).ok()
}
/// Returns the underlying vector as a slice.
@ -84,7 +84,7 @@ impl ByteString {
/// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-32).
pub fn is_field_value(&self) -> bool {
// Classifications of characters necessary for the [CRLF] (SP|HT) rule
#[deriving(PartialEq)]
#[derive(PartialEq)]
enum PreviousCharacter {
Other,
CR,
@ -146,8 +146,8 @@ impl ByteString {
}
}
impl Hash for ByteString {
fn hash(&self, state: &mut sip::SipState) {
impl Hash<SipHasher> for ByteString {
fn hash(&self, state: &mut SipHasher) {
let ByteString(ref vec) = *self;
vec.hash(state);
}

View file

@ -60,3 +60,5 @@ impl StructuredCloneData {
message
}
}
unsafe impl Send for StructuredCloneData {}

View file

@ -33,7 +33,6 @@ use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler};
use dom::node::{Node, TrustedNodeAddress};
use script_task::ScriptChan;
use collections::hash::{Hash, Hasher};
use cssparser::RGBA;
use geom::rect::Rect;
use html5ever::tree_builder::QuirksMode;
@ -54,9 +53,12 @@ use servo_util::smallvec::{SmallVec1, SmallVec};
use servo_util::str::{LengthOrPercentageOrAuto};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::comm::{Receiver, Sender};
use std::collections::hash_state::HashState;
use std::ffi::CString;
use std::hash::{Hash, Hasher};
use std::io::timer::Timer;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender};
use string_cache::{Atom, Namespace};
use style::PropertyDeclarationBlock;
use url::Url;
@ -74,7 +76,7 @@ impl<T: Reflectable> JSTraceable for JS<T> {
}
}
no_jsmanaged_fields!(Reflector)
no_jsmanaged_fields!(Reflector);
/// Trace a `JSVal`.
pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
@ -83,7 +85,7 @@ pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
}
unsafe {
let name = description.to_c_str();
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
@ -101,7 +103,7 @@ pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Ref
/// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
unsafe {
let name = description.to_c_str();
let name = CString::from_slice(description.as_bytes());
(*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
@ -175,14 +177,17 @@ impl<T: JSTraceable> JSTraceable for Option<T> {
}
}
impl<K,V,S,H> JSTraceable for HashMap<K, V, H> where K: Eq + Hash<S> + JSTraceable,
V: JSTraceable,
H: Hasher<S> {
impl<K,V,S> JSTraceable for HashMap<K, V, S>
where K: Hash<<S as HashState>::Hasher> + Eq + JSTraceable,
V: JSTraceable,
S: HashState,
<S as HashState>::Hasher: Hasher<Output=u64>,
{
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.val0().trace(trc);
e.val1().trace(trc);
for (k, v) in self.iter() {
k.trace(trc);
v.trace(trc);
}
}
}
@ -197,28 +202,28 @@ impl<A: JSTraceable, B: JSTraceable> JSTraceable for (A, B) {
}
no_jsmanaged_fields!(bool, f32, f64, String, Url)
no_jsmanaged_fields!(uint, u8, u16, u32, u64)
no_jsmanaged_fields!(int, i8, i16, i32, i64)
no_jsmanaged_fields!(Sender<T>)
no_jsmanaged_fields!(Receiver<T>)
no_jsmanaged_fields!(Rect<T>)
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan)
no_jsmanaged_fields!(Atom, Namespace, Timer)
no_jsmanaged_fields!(Trusted<T>)
no_jsmanaged_fields!(PropertyDeclarationBlock)
no_jsmanaged_fields!(bool, f32, f64, String, Url);
no_jsmanaged_fields!(uint, u8, u16, u32, u64);
no_jsmanaged_fields!(int, i8, i16, i32, i64);
no_jsmanaged_fields!(Sender<T>);
no_jsmanaged_fields!(Receiver<T>);
no_jsmanaged_fields!(Rect<T>);
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan);
no_jsmanaged_fields!(Atom, Namespace, Timer);
no_jsmanaged_fields!(Trusted<T>);
no_jsmanaged_fields!(PropertyDeclarationBlock);
// These three are interdependent, if you plan to put jsmanaged data
// in one of these make sure it is propagated properly to containing structs
no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId)
no_jsmanaged_fields!(QuirksMode)
no_jsmanaged_fields!(Cx)
no_jsmanaged_fields!(Headers, Method)
no_jsmanaged_fields!(ConstellationChan)
no_jsmanaged_fields!(LayoutChan)
no_jsmanaged_fields!(WindowProxyHandler)
no_jsmanaged_fields!(UntrustedNodeAddress)
no_jsmanaged_fields!(LengthOrPercentageOrAuto)
no_jsmanaged_fields!(RGBA)
no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId);
no_jsmanaged_fields!(QuirksMode);
no_jsmanaged_fields!(Cx);
no_jsmanaged_fields!(Headers, Method);
no_jsmanaged_fields!(ConstellationChan);
no_jsmanaged_fields!(LayoutChan);
no_jsmanaged_fields!(WindowProxyHandler);
no_jsmanaged_fields!(UntrustedNodeAddress);
no_jsmanaged_fields!(LengthOrPercentageOrAuto);
no_jsmanaged_fields!(RGBA);
impl JSTraceable for Box<ScriptChan+Send> {
#[inline]

View file

@ -18,6 +18,7 @@ use dom::window;
use libc;
use libc::c_uint;
use std::cell::Cell;
use std::ffi::CString;
use std::mem;
use std::ptr;
use js::glue::UnwrapObject;
@ -84,7 +85,7 @@ pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
/// Representation of an IDL constant value.
#[deriving(Clone)]
#[derive(Clone)]
pub enum ConstantVal {
/// `long` constant.
IntVal(i32),
@ -99,7 +100,7 @@ pub enum ConstantVal {
}
/// Representation of an IDL constant.
#[deriving(Clone)]
#[derive(Clone)]
pub struct ConstantSpec {
/// name of the constant.
pub name: &'static [u8],
@ -130,24 +131,26 @@ pub struct NativePropertyHooks {
}
/// The struct that holds inheritance information for DOM object reflectors.
#[deriving(Copy)]
#[derive(Copy)]
pub struct DOMClass {
/// A list of interfaces that this object implements, in order of decreasing
/// derivedness.
pub interface_chain: [PrototypeList::ID, ..MAX_PROTO_CHAIN_LENGTH],
pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
/// The NativePropertyHooks for the interface associated with this class.
pub native_hooks: &'static NativePropertyHooks,
}
unsafe impl Sync for DOMClass {}
/// The JSClass used for DOM object reflectors.
#[deriving(Copy)]
#[derive(Copy)]
pub struct DOMJSClass {
/// The actual JSClass.
pub base: js::Class,
/// Associated data for DOM object reflectors.
pub dom_class: DOMClass
}
unsafe impl Sync for DOMJSClass {}
/// Returns the ProtoOrIfaceArray for the given global object.
/// Fails if `global` is not a DOM global object.
@ -172,6 +175,7 @@ pub struct NativeProperties {
/// Static attributes for the interface.
pub staticAttrs: Option<&'static [JSPropertySpec]>,
}
unsafe impl Sync for NativeProperties {}
/// A JSNative that cannot be null.
pub type NonNullJSNative =
@ -196,7 +200,7 @@ pub fn CreateInterfaceObjects2(cx: *mut JSContext, global: *mut JSObject, receiv
match constructor {
Some((native, name, nargs)) => {
let s = name.to_c_str();
let s = CString::from_slice(name.as_bytes());
CreateInterfaceObject(cx, global, receiver,
native, nargs, proto,
members, s.as_ptr())
@ -322,7 +326,7 @@ pub unsafe extern fn ThrowingConstructor(cx: *mut JSContext, _argc: c_uint, _vp:
/// Construct and cache the ProtoOrIfaceArray for the given global.
/// Fails if the argument is not a DOM global.
pub fn initialize_global(global: *mut JSObject) {
let protoArray = box () ([0 as *mut JSObject, ..PrototypeList::ID::Count as uint]);
let protoArray = box () ([0 as *mut JSObject; PrototypeList::ID::Count as uint]);
unsafe {
assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0);
let box_ = squirrel_away_unique(protoArray);
@ -351,7 +355,7 @@ pub fn reflect_dom_object<T: Reflectable>
/// A struct to store a reference to the reflector of a DOM object.
// Allowing unused_attribute because the lint sometimes doesn't run in order
#[allow(raw_pointer_deriving, unrooted_must_root, unused_attributes)]
#[deriving(PartialEq)]
#[derive(PartialEq)]
#[must_root]
#[servo_lang = "reflector"]
// If you're renaming or moving this field, update the path in plugins::reflector as well
@ -495,7 +499,7 @@ pub fn IsPlatformObject(obj: *mut JSObject) -> bool {
pub fn get_dictionary_property(cx: *mut JSContext,
object: *mut JSObject,
property: &str) -> Result<Option<JSVal>, ()> {
use std::c_str::CString;
use std::ffi::CString;
fn has_property(cx: *mut JSContext, object: *mut JSObject, property: &CString,
found: &mut JSBool) -> bool {
unsafe {
@ -509,7 +513,7 @@ pub fn get_dictionary_property(cx: *mut JSContext,
}
}
let property = property.to_c_str();
let property = CString::from_slice(property.as_bytes());
if object.is_null() {
return Ok(None);
}
@ -594,7 +598,7 @@ pub unsafe fn delete_property_by_id(cx: *mut JSContext, object: *mut JSObject,
}
/// Results of `xml_name_type`.
#[deriving(PartialEq)]
#[derive(PartialEq)]
#[allow(missing_docs)]
pub enum XMLName {
QName,