<commit_before>/* 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/. */

//! Various utilities to glue JavaScript and the DOM implementation together.

use dom::bindings::codegen::PrototypeList;
use dom::bindings::codegen::PrototypeList::MAX_PROTO_CHAIN_LENGTH;
use dom::bindings::conversions::{unwrap_jsmanaged, is_dom_class};
use dom::bindings::error::throw_type_error;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{Temporary, Root};
use dom::browsercontext;
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;
use js::glue::{IsWrapper, RUST_JSID_IS_INT, RUST_JSID_TO_INT};
use js::jsapi::{JS_AlreadyHasOwnProperty, JS_NewFunction};
use js::jsapi::{JS_DefineProperties, JS_ForwardGetPropertyTo};
use js::jsapi::{JS_GetClass, JS_LinkConstructorAndPrototype, JS_GetStringCharsAndLength};
use js::jsapi::{JS_ObjectIsRegExp, JS_ObjectIsDate, JSHandleObject};
use js::jsapi::JS_GetFunctionObject;
use js::jsapi::{JS_HasPropertyById, JS_GetPrototype};
use js::jsapi::{JS_GetProperty, JS_HasProperty};
use js::jsapi::{JS_DefineFunctions, JS_DefineProperty};
use js::jsapi::{JS_ValueToString, JS_GetReservedSlot, JS_SetReservedSlot};
use js::jsapi::{JSContext, JSObject, JSBool, jsid, JSClass};
use js::jsapi::{JSFunctionSpec, JSPropertySpec};
use js::jsapi::{JS_NewGlobalObject, JS_InitStandardClasses};
use js::jsapi::JS_DeletePropertyById2;
use js::jsfriendapi::JS_ObjectToOuterObject;
use js::jsfriendapi::bindgen::JS_NewObjectWithUniqueType;
use js::jsval::JSVal;
use js::jsval::{PrivateValue, ObjectValue, NullValue};
use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue};
use js::rust::with_compartment;
use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT};
use js::JSFUN_CONSTRUCTOR;
use js;

/// Proxy handler for a WindowProxy.
pub struct WindowProxyHandler(pub *const libc::c_void);

#[allow(raw_pointer_derive)]
#[jstraceable]
/// Static data associated with a global object.
pub struct GlobalStaticData {
    /// The WindowProxy proxy handler for this global.
    pub windowproxy_handler: WindowProxyHandler,
}

impl GlobalStaticData {
    /// Creates a new GlobalStaticData.
    pub fn new() -> GlobalStaticData {
        GlobalStaticData {
            windowproxy_handler: browsercontext::new_window_proxy_handler(),
        }
    }
}

/// Leak the given pointer.
pub unsafe fn squirrel_away_unique<T>(x: Box<T>) -> *const T {
    mem::transmute(x)
}

// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
const DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0;

/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;

/// The flag set on the `JSClass`es for DOM global objects.
// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;

/// Representation of an IDL constant value.
#[derive(Clone)]
pub enum ConstantVal {
    /// `long` constant.
    IntVal(i32),
    /// `unsigned long` constant.
    UintVal(u32),
    /// `double` constant.
    DoubleVal(f64),
    /// `boolean` constant.
    BoolVal(bool),
    /// `null` constant.
    NullVal,
}

/// Representation of an IDL constant.
#[derive(Clone)]
pub struct ConstantSpec {
    /// name of the constant.
    pub name: &'static [u8],
    /// value of the constant.
    pub value: ConstantVal
}

impl ConstantSpec {
    /// Returns a `JSVal` that represents the value of this `ConstantSpec`.
    pub fn get_value(&self) -> JSVal {
        match self.value {
            ConstantVal::NullVal => NullValue(),
            ConstantVal::IntVal(i) => Int32Value(i),
            ConstantVal::UintVal(u) => UInt32Value(u),
            ConstantVal::DoubleVal(d) => DoubleValue(d),
            ConstantVal::BoolVal(b) => BooleanValue(b),
        }
    }
}

/// Helper structure for cross-origin wrappers for DOM binding objects.
pub struct NativePropertyHooks {
    /// The property arrays for this interface.
    pub native_properties: &'static NativeProperties,

    /// The NativePropertyHooks instance for the parent interface, if any.
    pub proto_hooks: Option<&'static NativePropertyHooks>,
}

/// The struct that holds inheritance information for DOM object reflectors.
#[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],

    /// 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.
#[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.
pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut *mut JSObject {
    unsafe {
        assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0);
        JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT).to_private() as *mut *mut JSObject
    }
}

/// Contains references to lists of methods, attributes, and constants for a
/// given interface.
pub struct NativeProperties {
    /// Instance methods for the interface.
    pub methods: Option<&'static [JSFunctionSpec]>,
    /// Instance attributes for the interface.
    pub attrs: Option<&'static [JSPropertySpec]>,
    /// Constants for the interface.
    pub consts: Option<&'static [ConstantSpec]>,
    /// Static methods for the interface.
    pub static_methods: Option<&'static [JSFunctionSpec]>,
    /// Static attributes for the interface.
    pub static_attrs: Option<&'static [JSPropertySpec]>,
}
unsafe impl Sync for NativeProperties {}

/// A JSNative that cannot be null.
pub type NonNullJSNative =
    unsafe extern "C" fn (arg1: *mut JSContext, arg2: c_uint, arg3: *mut JSVal) -> JSBool;

/// Creates the *interface prototype object* and the *interface object* (if
/// needed).
/// Fails on JSAPI failure.
pub fn do_create_interface_objects(cx: *mut JSContext, global: *mut JSObject,
                                   receiver: *mut JSObject,
                                   proto_proto: *mut JSObject,
                                   proto_class: &'static JSClass,
                                   constructor: Option<(NonNullJSNative, &'static str, u32)>,
                                   dom_class: *const DOMClass,
                                   members: &'static NativeProperties)
                                   -> *mut JSObject {
    let proto = create_interface_prototype_object(cx, global, proto_proto,
                                                  proto_class, members);

    unsafe {
        JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT,
                           PrivateValue(dom_class as *const libc::c_void));
    }

    match constructor {
        Some((native, name, nargs)) => {
            let s = CString::from_slice(name.as_bytes());
            create_interface_object(cx, global, receiver,
                                    native, nargs, proto,
                                    members, s.as_ptr())
        },
        None => (),
    }

    proto
}

/// Creates the *interface object*.
/// Fails on JSAPI failure.
fn create_interface_object(cx: *mut JSContext, global: *mut JSObject,
                           receiver: *mut JSObject,
                           constructor_native: NonNullJSNative,
                           ctor_nargs: u32, proto: *mut JSObject,
                           members: &'static NativeProperties,
                           name: *const libc::c_char) {
    unsafe {
        let fun = JS_NewFunction(cx, Some(constructor_native), ctor_nargs,
                                 JSFUN_CONSTRUCTOR, global, name);
        assert!(!fun.is_null());

        let constructor = JS_GetFunctionObject(fun);
        assert!(!constructor.is_null());

        match members.static_methods {
            Some(static_methods) => {
                define_methods(cx, constructor, static_methods)
            },
            _ => (),
        }

        match members.static_attrs {
            Some(static_properties) => {
                define_properties(cx, constructor, static_properties)
            },
            _ => (),
        }

        match members.consts {
            Some(constants) => define_constants(cx, constructor, constants),
            _ => (),
        }

        if !proto.is_null() {
            assert!(JS_LinkConstructorAndPrototype(cx, constructor, proto) != 0);
        }

        let mut already_defined = 0;
        assert!(JS_AlreadyHasOwnProperty(cx, receiver, name, &mut already_defined) != 0);

        if already_defined == 0 {
            assert!(JS_DefineProperty(cx, receiver, name,
                                      ObjectValue(&*constructor),
                                      None, None, 0) != 0);
        }
    }
}

/// Defines constants on `obj`.
/// Fails on JSAPI failure.
fn define_constants(cx: *mut JSContext, obj: *mut JSObject,
                    constants: &'static [ConstantSpec]) {
    for spec in constants.iter() {
        unsafe {
            assert!(JS_DefineProperty(cx, obj, spec.name.as_ptr() as *const libc::c_char,
                                      spec.get_value(), None, None,
                                      JSPROP_ENUMERATE | JSPROP_READONLY |
                                      JSPROP_PERMANENT) != 0);
        }
    }
}

/// Defines methods on `obj`. The last entry of `methods` must contain zeroed
/// memory.
/// Fails on JSAPI failure.
fn define_methods(cx: *mut JSContext, obj: *mut JSObject,
                  methods: &'static [JSFunctionSpec]) {
    unsafe {
        assert!(JS_DefineFunctions(cx, obj, methods.as_ptr()) != 0);
    }
}

/// Defines attributes on `obj`. The last entry of `properties` must contain
/// zeroed memory.
/// Fails on JSAPI failure.
fn define_properties(cx: *mut JSContext, obj: *mut JSObject,
                     properties: &'static [JSPropertySpec]) {
    unsafe {
        assert!(JS_DefineProperties(cx, obj, properties.as_ptr()) != 0);
    }
}

/// Creates the *interface prototype object*.
/// Fails on JSAPI failure.
fn create_interface_prototype_object(cx: *mut JSContext, global: *mut JSObject,
                                     parent_proto: *mut JSObject,
                                     proto_class: &'static JSClass,
                                     members: &'static NativeProperties)
                                     -> *mut JSObject {
    unsafe {
        let our_proto = JS_NewObjectWithUniqueType(cx, proto_class,
                                                   &*parent_proto, &*global);
        assert!(!our_proto.is_null());

        match members.methods {
            Some(methods) => define_methods(cx, our_proto, methods),
            _ => (),
        }

        match members.attrs {
            Some(properties) => define_properties(cx, our_proto, properties),
            _ => (),
        }

        match members.consts {
            Some(constants) => define_constants(cx, our_proto, constants),
            _ => (),
        }

        return our_proto;
    }
}

/// A throwing constructor, for those interfaces that have neither
/// `NoInterfaceObject` nor `Constructor`.
pub unsafe extern fn throwing_constructor(cx: *mut JSContext, _argc: c_uint,
                                          _vp: *mut JSVal) -> JSBool {
    throw_type_error(cx, "Illegal constructor.");
    return 0;
}

/// 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]);
    unsafe {
        assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0);
        let box_ = squirrel_away_unique(protoArray);
        JS_SetReservedSlot(global,
                           DOM_PROTOTYPE_SLOT,
                           PrivateValue(box_ as *const libc::c_void));
    }
}
<commit_msg>Use snake case for the local in initialize_global.<commit_after>/* 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/. */

//! Various utilities to glue JavaScript and the DOM implementation together.

use dom::bindings::codegen::PrototypeList;
use dom::bindings::codegen::PrototypeList::MAX_PROTO_CHAIN_LENGTH;
use dom::bindings::conversions::{unwrap_jsmanaged, is_dom_class};
use dom::bindings::error::throw_type_error;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{Temporary, Root};
use dom::browsercontext;
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;
use js::glue::{IsWrapper, RUST_JSID_IS_INT, RUST_JSID_TO_INT};
use js::jsapi::{JS_AlreadyHasOwnProperty, JS_NewFunction};
use js::jsapi::{JS_DefineProperties, JS_ForwardGetPropertyTo};
use js::jsapi::{JS_GetClass, JS_LinkConstructorAndPrototype, JS_GetStringCharsAndLength};
use js::jsapi::{JS_ObjectIsRegExp, JS_ObjectIsDate, JSHandleObject};
use js::jsapi::JS_GetFunctionObject;
use js::jsapi::{JS_HasPropertyById, JS_GetPrototype};
use js::jsapi::{JS_GetProperty, JS_HasProperty};
use js::jsapi::{JS_DefineFunctions, JS_DefineProperty};
use js::jsapi::{JS_ValueToString, JS_GetReservedSlot, JS_SetReservedSlot};
use js::jsapi::{JSContext, JSObject, JSBool, jsid, JSClass};
use js::jsapi::{JSFunctionSpec, JSPropertySpec};
use js::jsapi::{JS_NewGlobalObject, JS_InitStandardClasses};
use js::jsapi::JS_DeletePropertyById2;
use js::jsfriendapi::JS_ObjectToOuterObject;
use js::jsfriendapi::bindgen::JS_NewObjectWithUniqueType;
use js::jsval::JSVal;
use js::jsval::{PrivateValue, ObjectValue, NullValue};
use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue};
use js::rust::with_compartment;
use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT};
use js::JSFUN_CONSTRUCTOR;
use js;

/// Proxy handler for a WindowProxy.
pub struct WindowProxyHandler(pub *const libc::c_void);

#[allow(raw_pointer_derive)]
#[jstraceable]
/// Static data associated with a global object.
pub struct GlobalStaticData {
    /// The WindowProxy proxy handler for this global.
    pub windowproxy_handler: WindowProxyHandler,
}

impl GlobalStaticData {
    /// Creates a new GlobalStaticData.
    pub fn new() -> GlobalStaticData {
        GlobalStaticData {
            windowproxy_handler: browsercontext::new_window_proxy_handler(),
        }
    }
}

/// Leak the given pointer.
pub unsafe fn squirrel_away_unique<T>(x: Box<T>) -> *const T {
    mem::transmute(x)
}

// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
const DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0;

/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;

/// The flag set on the `JSClass`es for DOM global objects.
// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;

/// Representation of an IDL constant value.
#[derive(Clone)]
pub enum ConstantVal {
    /// `long` constant.
    IntVal(i32),
    /// `unsigned long` constant.
    UintVal(u32),
    /// `double` constant.
    DoubleVal(f64),
    /// `boolean` constant.
    BoolVal(bool),
    /// `null` constant.
    NullVal,
}

/// Representation of an IDL constant.
#[derive(Clone)]
pub struct ConstantSpec {
    /// name of the constant.
    pub name: &'static [u8],
    /// value of the constant.
    pub value: ConstantVal
}

impl ConstantSpec {
    /// Returns a `JSVal` that represents the value of this `ConstantSpec`.
    pub fn get_value(&self) -> JSVal {
        match self.value {
            ConstantVal::NullVal => NullValue(),
            ConstantVal::IntVal(i) => Int32Value(i),
            ConstantVal::UintVal(u) => UInt32Value(u),
            ConstantVal::DoubleVal(d) => DoubleValue(d),
            ConstantVal::BoolVal(b) => BooleanValue(b),
        }
    }
}

/// Helper structure for cross-origin wrappers for DOM binding objects.
pub struct NativePropertyHooks {
    /// The property arrays for this interface.
    pub native_properties: &'static NativeProperties,

    /// The NativePropertyHooks instance for the parent interface, if any.
    pub proto_hooks: Option<&'static NativePropertyHooks>,
}

/// The struct that holds inheritance information for DOM object reflectors.
#[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],

    /// 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.
#[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.
pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut *mut JSObject {
    unsafe {
        assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0);
        JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT).to_private() as *mut *mut JSObject
    }
}

/// Contains references to lists of methods, attributes, and constants for a
/// given interface.
pub struct NativeProperties {
    /// Instance methods for the interface.
    pub methods: Option<&'static [JSFunctionSpec]>,
    /// Instance attributes for the interface.
    pub attrs: Option<&'static [JSPropertySpec]>,
    /// Constants for the interface.
    pub consts: Option<&'static [ConstantSpec]>,
    /// Static methods for the interface.
    pub static_methods: Option<&'static [JSFunctionSpec]>,
    /// Static attributes for the interface.
    pub static_attrs: Option<&'static [JSPropertySpec]>,
}
unsafe impl Sync for NativeProperties {}

/// A JSNative that cannot be null.
pub type NonNullJSNative =
    unsafe extern "C" fn (arg1: *mut JSContext, arg2: c_uint, arg3: *mut JSVal) -> JSBool;

/// Creates the *interface prototype object* and the *interface object* (if
/// needed).
/// Fails on JSAPI failure.
pub fn do_create_interface_objects(cx: *mut JSContext, global: *mut JSObject,
                                   receiver: *mut JSObject,
                                   proto_proto: *mut JSObject,
                                   proto_class: &'static JSClass,
                                   constructor: Option<(NonNullJSNative, &'static str, u32)>,
                                   dom_class: *const DOMClass,
                                   members: &'static NativeProperties)
                                   -> *mut JSObject {
    let proto = create_interface_prototype_object(cx, global, proto_proto,
                                                  proto_class, members);

    unsafe {
        JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT,
                           PrivateValue(dom_class as *const libc::c_void));
    }

    match constructor {
        Some((native, name, nargs)) => {
            let s = CString::from_slice(name.as_bytes());
            create_interface_object(cx, global, receiver,
                                    native, nargs, proto,
                                    members, s.as_ptr())
        },
        None => (),
    }

    proto
}

/// Creates the *interface object*.
/// Fails on JSAPI failure.
fn create_interface_object(cx: *mut JSContext, global: *mut JSObject,
                           receiver: *mut JSObject,
                           constructor_native: NonNullJSNative,
                           ctor_nargs: u32, proto: *mut JSObject,
                           members: &'static NativeProperties,
                           name: *const libc::c_char) {
    unsafe {
        let fun = JS_NewFunction(cx, Some(constructor_native), ctor_nargs,
                                 JSFUN_CONSTRUCTOR, global, name);
        assert!(!fun.is_null());

        let constructor = JS_GetFunctionObject(fun);
        assert!(!constructor.is_null());

        match members.static_methods {
            Some(static_methods) => {
                define_methods(cx, constructor, static_methods)
            },
            _ => (),
        }

        match members.static_attrs {
            Some(static_properties) => {
                define_properties(cx, constructor, static_properties)
            },
            _ => (),
        }

        match members.consts {
            Some(constants) => define_constants(cx, constructor, constants),
            _ => (),
        }

        if !proto.is_null() {
            assert!(JS_LinkConstructorAndPrototype(cx, constructor, proto) != 0);
        }

        let mut already_defined = 0;
        assert!(JS_AlreadyHasOwnProperty(cx, receiver, name, &mut already_defined) != 0);

        if already_defined == 0 {
            assert!(JS_DefineProperty(cx, receiver, name,
                                      ObjectValue(&*constructor),
                                      None, None, 0) != 0);
        }
    }
}

/// Defines constants on `obj`.
/// Fails on JSAPI failure.
fn define_constants(cx: *mut JSContext, obj: *mut JSObject,
                    constants: &'static [ConstantSpec]) {
    for spec in constants.iter() {
        unsafe {
            assert!(JS_DefineProperty(cx, obj, spec.name.as_ptr() as *const libc::c_char,
                                      spec.get_value(), None, None,
                                      JSPROP_ENUMERATE | JSPROP_READONLY |
                                      JSPROP_PERMANENT) != 0);
        }
    }
}

/// Defines methods on `obj`. The last entry of `methods` must contain zeroed
/// memory.
/// Fails on JSAPI failure.
fn define_methods(cx: *mut JSContext, obj: *mut JSObject,
                  methods: &'static [JSFunctionSpec]) {
    unsafe {
        assert!(JS_DefineFunctions(cx, obj, methods.as_ptr()) != 0);
    }
}

/// Defines attributes on `obj`. The last entry of `properties` must contain
/// zeroed memory.
/// Fails on JSAPI failure.
fn define_properties(cx: *mut JSContext, obj: *mut JSObject,
                     properties: &'static [JSPropertySpec]) {
    unsafe {
        assert!(JS_DefineProperties(cx, obj, properties.as_ptr()) != 0);
    }
}

/// Creates the *interface prototype object*.
/// Fails on JSAPI failure.
fn create_interface_prototype_object(cx: *mut JSContext, global: *mut JSObject,
                                     parent_proto: *mut JSObject,
                                     proto_class: &'static JSClass,
                                     members: &'static NativeProperties)
                                     -> *mut JSObject {
    unsafe {
        let our_proto = JS_NewObjectWithUniqueType(cx, proto_class,
                                                   &*parent_proto, &*global);
        assert!(!our_proto.is_null());

        match members.methods {
            Some(methods) => define_methods(cx, our_proto, methods),
            _ => (),
        }

        match members.attrs {
            Some(properties) => define_properties(cx, our_proto, properties),
            _ => (),
        }

        match members.consts {
            Some(constants) => define_constants(cx, our_proto, constants),
            _ => (),
        }

        return our_proto;
    }
}

/// A throwing constructor, for those interfaces that have neither
/// `NoInterfaceObject` nor `Constructor`.
pub unsafe extern fn throwing_constructor(cx: *mut JSContext, _argc: c_uint,
                                          _vp: *mut JSVal) -> JSBool {
    throw_type_error(cx, "Illegal constructor.");
    return 0;
}

/// 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 proto_array = 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(proto_array);
        JS_SetReservedSlot(global,
                           DOM_PROTOTYPE_SLOT,
                           PrivateValue(box_ as *const libc::c_void));
    }
}

{'fraction_non_alphanumeric': 0.10896261354333164, 'fraction_numerical': 0.0038984834899224202, 'mean_word_length': 2.5260481099656356, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 54, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5202633', 'n_tokens_mistral': 7374, 'n_tokens_neox': 7263, 'n_words': 2047}