/* This Source Code Form is subject to the terms of the Mozilla Public * 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/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `JSRef`: a freely-copyable reference to a rooted DOM object. //! - `Root`: a stack-based reference to a rooted DOM object. //! - `JS`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! - `Temporary`: a reference to a DOM object that will remain rooted for //! the duration of its lifetime. //! //! The rule of thumb is as follows: //! //! - All methods return `Temporary`, to ensure the value remains alive //! until it is stored somewhere that is reachable by the GC. //! - All functions take `JSRef` arguments, to ensure that they will remain //! uncollected for the duration of their usage. //! - All DOM structs contain `JS` fields and derive the `JSTraceable` //! trait, to ensure that they are transitively marked as reachable by the GC //! if the enclosing value is reachable. //! - All methods for type `T` are implemented for `JSRef`, to ensure that //! the self value will not be collected for the duration of the method call. //! //! Both `Temporary` and `JS` do not allow access to their inner value //! without explicitly creating a stack-based root via the `root` method. This //! returns a `Root`, which causes the JS-owned value to be uncollectable //! for the duration of the `Root` object's lifetime. A `JSRef` can be //! obtained from a `Root` by calling the `r` method. These `JSRef` //! values are not allowed to outlive their originating `Root`, to ensure //! that all interactions with the enclosed value only occur when said value is //! uncollectable, and will cause static lifetime errors if misused. //! //! Other miscellaneous helper traits: //! //! - `OptionalRootable` and `OptionalRootedRootable`: make rooting `Option` //! values easy via a `root` method //! - `ResultRootable`: make rooting successful `Result` values easy //! - `TemporaryPushable`: allows mutating vectors of `JS` with new elements //! of `JSRef`/`Temporary` //! - `RootedReference`: makes obtaining an `Option>` from an //! `Option>` easy use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflector, Reflectable}; use dom::node::Node; use js::jsapi::JSObject; use js::jsval::JSVal; use layout_interface::TrustedNodeAddress; use script_task::STACK_ROOTS; use util::smallvec::{SmallVec, SmallVec16}; use core::nonzero::NonZero; use std::cell::{Cell, UnsafeCell}; use std::default::Default; use std::marker::ContravariantLifetime; use std::mem; use std::ops::Deref; /// An unrooted, JS-owned value. Must not be held across a GC. /// /// This is used in particular to wrap pointers extracted from a reflector. #[must_root] pub struct Unrooted { ptr: NonZero<*const T> } impl Unrooted { /// Create a new JS-owned value wrapped from a raw Rust pointer. pub unsafe fn from_raw(raw: *const T) -> Unrooted { assert!(!raw.is_null()); Unrooted { ptr: NonZero::new(raw) } } /// Create a new unrooted value from a `JS`. #[allow(unrooted_must_root)] pub fn from_js(ptr: JS) -> Unrooted { Unrooted { ptr: ptr.ptr } } /// Get the `Reflector` for this pointer. pub fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { (**self.ptr).reflector() } } /// Returns an unsafe pointer to the interior of this object. pub unsafe fn unsafe_get(&self) -> *const T { *self.ptr } /// Create a stack-bounded root for this value. pub fn root(self) -> Root { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { Root::new(&*collection, self.ptr) } }) } } impl Copy for Unrooted {} /// 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. Can be assigned into JS-owned member fields (i.e. /// `JS` types) safely via the `JS::assign` method or /// `OptionalSettable::assign` (for `Option>` fields). #[allow(unrooted_must_root)] pub struct Temporary { inner: JS, /// On-stack JS pointer to assuage conservative stack scanner _js_ptr: *mut JSObject, } impl Clone for Temporary { fn clone(&self) -> Temporary { Temporary { inner: self.inner, _js_ptr: self._js_ptr, } } } impl PartialEq for Temporary { fn eq(&self, other: &Temporary) -> bool { self.inner == other.inner } } impl Temporary { /// Create a new `Temporary` value from a JS-owned value. pub fn new(inner: JS) -> Temporary { Temporary { inner: inner, _js_ptr: inner.reflector().get_jsobject(), } } /// Create a new `Temporary` value from an unrooted value. #[allow(unrooted_must_root)] pub fn from_unrooted(unrooted: Unrooted) -> Temporary { Temporary { inner: JS { ptr: unrooted.ptr }, _js_ptr: unrooted.reflector().get_jsobject(), } } /// Create a new `Temporary` value from a rooted value. pub fn from_rooted<'a>(root: JSRef<'a, T>) -> Temporary { Temporary::new(JS::from_rooted(root)) } /// Create a stack-bounded root for this value. pub fn root(self) -> Root { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { Root::new(&*collection, self.inner.ptr) } }) } unsafe fn inner(&self) -> JS { self.inner.clone() } /// Returns `self` as a `Temporary` of another type. For use by /// `InheritTypes` only. //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute(self) -> Temporary { mem::transmute(self) } } /// A traced reference to a DOM object. Must only be used as a field in other /// DOM objects. #[must_root] pub struct JS { ptr: NonZero<*const T> } impl JS { /// Returns `LayoutJS` containing the same pointer. pub unsafe fn to_layout(self) -> LayoutJS { LayoutJS { ptr: self.ptr.clone() } } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. pub struct LayoutJS { ptr: NonZero<*const T> } impl LayoutJS { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { (**self.ptr).reflector().get_jsobject() } } impl Copy for JS {} impl Copy for LayoutJS {} impl PartialEq for JS { #[allow(unrooted_must_root)] fn eq(&self, other: &JS) -> bool { self.ptr == other.ptr } } impl PartialEq for LayoutJS { #[allow(unrooted_must_root)] fn eq(&self, other: &LayoutJS) -> bool { self.ptr == other.ptr } } impl Clone for JS { #[inline] fn clone(&self) -> JS { JS { ptr: self.ptr.clone() } } } impl Clone for LayoutJS { #[inline] fn clone(&self) -> LayoutJS { LayoutJS { ptr: self.ptr.clone() } } } impl LayoutJS { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutJS { let TrustedNodeAddress(addr) = inner; LayoutJS { ptr: NonZero::new(addr as *const Node) } } } impl JS { /// Root this JS-owned value to prevent its collection as garbage. pub fn root(&self) -> Root { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { Root::new(&*collection, self.ptr) } }) } } impl JS { /// Create a `JS` from any JS-managed pointer. pub fn from_rooted>(root: T) -> JS { unsafe { root.get_js() } } } //XXXjdm This is disappointing. This only gets called from trace hooks, in theory, // so it's safe to assume that self is rooted and thereby safe to access. impl Reflectable for JS { fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { (**self.ptr).reflector() } } } /// A trait to be implemented for JS-managed types that can be stored in /// mutable member fields. /// /// Do not implement this trait yourself. pub trait HeapGCValue: JSTraceable { } impl HeapGCValue for JSVal { } impl HeapGCValue for JS { } /// A holder that provides interior mutability for GC-managed values such as /// `JSVal` and `JS`. /// /// Must be used in place of traditional interior mutability to ensure proper /// GC barriers are enforced. #[must_root] #[jstraceable] pub struct MutHeap { val: Cell, } impl MutHeap { /// Create a new `MutHeap`. pub fn new(initial: T) -> MutHeap { MutHeap { val: Cell::new(initial), } } /// Set this `MutHeap` to the given value, calling write barriers as /// appropriate. pub fn set(&self, val: T) { self.val.set(val) } /// Set the value in this `MutHeap`, calling read barriers as appropriate. pub fn get(&self) -> T { self.val.get() } } /// A mutable `JS` value, with nullability represented by an enclosing /// Option wrapper. Must be used in place of traditional internal mutability /// to ensure that the proper GC barriers are enforced. #[must_root] #[jstraceable] pub struct MutNullableJS { ptr: Cell>> } impl MutNullableJS { /// Create a new `MutNullableJS` pub fn new>(initial: Option) -> MutNullableJS { MutNullableJS { ptr: Cell::new(initial.map(|initial| { unsafe { initial.get_js() } })) } } } impl Default for MutNullableJS { fn default() -> MutNullableJS { MutNullableJS { ptr: Cell::new(None) } } } impl MutNullableJS { /// Store an unrooted value in this field. This is safe under the /// assumption that `MutNullableJS` values are only used as fields in /// DOM types that are reachable in the GC graph, so this unrooted value /// becomes transitively rooted for the lifetime of its new owner. pub fn assign>(&self, val: Option) { self.ptr.set(val.map(|val| { unsafe { val.get_js() } })); } /// Set the inner value to null, without making API users jump through /// useless type-ascription hoops. pub fn clear(&self) { self.assign(None::>); } /// Retrieve a copy of the current optional inner value. pub fn get(&self) -> Option> { self.ptr.get().map(Temporary::new) } /// Retrieve a copy of the inner optional `JS` as `LayoutJS`. /// For use by layout, which can't use safe types like Temporary. pub unsafe fn get_inner_as_layout(&self) -> Option> { self.ptr.get().map(|js| js.to_layout()) } /// 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: F) -> Temporary where F: FnOnce() -> Temporary { match self.get() { Some(inner) => inner, None => { let inner = cb(); self.assign(Some(inner.clone())); inner }, } } } impl JS { /// Store an unrooted value in this field. This is safe under the /// assumption that JS values are only used as fields in DOM types that /// are reachable in the GC graph, so this unrooted value becomes /// transitively rooted for the lifetime of its new owner. pub fn assign(&mut self, val: Temporary) { *self = unsafe { val.inner() }; } } impl LayoutJS { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { *self.ptr } } impl JS { /// Return `self` as a `JS` of another type. pub unsafe fn transmute_copy(&self) -> JS { mem::transmute_copy(self) } } impl LayoutJS { /// Return `self` as a `LayoutJS` of another type. pub unsafe fn transmute_copy(&self) -> LayoutJS { mem::transmute_copy(self) } } /// Get an `Option>` out of an `Option>` pub trait RootedReference { /// Obtain a safe optional reference to the wrapped JS owned-value that /// cannot outlive the lifetime of this root. fn r<'a>(&'a self) -> Option>; } impl RootedReference for Option> { fn r<'a>(&'a self) -> Option> { self.as_ref().map(|root| root.r()) } } /// Get an `Option>>` out of an `Option>>` pub trait OptionalRootedReference { /// Obtain a safe optional optional reference to the wrapped JS owned-value /// that cannot outlive the lifetime of this root. fn r<'a>(&'a self) -> Option>>; } impl OptionalRootedReference for Option>> { fn r<'a>(&'a self) -> Option>> { self.as_ref().map(|inner| inner.r()) } } /// Trait that allows extracting a `JS` value from a variety of /// rooting-related containers, which in general is an unsafe operation since /// they can outlive the rooted lifetime of the original value. pub trait Assignable { /// Extract an unrooted `JS`. unsafe fn get_js(&self) -> JS; } impl Assignable for JS { unsafe fn get_js(&self) -> JS { self.clone() } } impl<'a, T: Reflectable> Assignable for JSRef<'a, T> { unsafe fn get_js(&self) -> JS { self.unrooted() } } impl Assignable for Temporary { unsafe fn get_js(&self) -> JS { self.inner() } } /// Root a rootable `Option` type (used for `Option>`) pub trait OptionalRootable { /// Root the inner value, if it exists. fn root(self) -> Option>; } impl OptionalRootable for Option> { fn root(self) -> Option> { self.map(|inner| inner.root()) } } /// Return an unrooted type for storing in optional DOM fields pub trait OptionalUnrootable { /// Returns a `JS` for the inner value, if it exists. fn unrooted(&self) -> Option>; } impl<'a, T: Reflectable> OptionalUnrootable for Option> { fn unrooted(&self) -> Option> { self.as_ref().map(|inner| JS::from_rooted(*inner)) } } /// Root a rootable `Option` type (used for `Option>`) pub trait OptionalRootedRootable { /// Root the inner value, if it exists. fn root(&self) -> Option>; } impl OptionalRootedRootable for Option> { fn root(&self) -> Option> { self.as_ref().map(|inner| inner.root()) } } impl OptionalRootedRootable for Option> { fn root(&self) -> Option> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Option