Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Option<T> to return from getters #13100

Merged
merged 6 commits into from Aug 31, 2016
Merged

Compile WebIDL return type "object" to NonZero<*mut JSObject>

  • Loading branch information
nox committed Aug 30, 2016
commit 6e1523f4ae61c16578a462c2e5335cbc95a6ef04
@@ -1349,7 +1349,10 @@ def getRetvalDeclarationForType(returnType, descriptorProvider):
if returnType.isAny():
return CGGeneric("JSVal")
if returnType.isObject() or returnType.isSpiderMonkeyInterface():
return CGGeneric("*mut JSObject")
result = CGGeneric("NonZero<*mut JSObject>")
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isSequence():
result = getRetvalDeclarationForType(innerSequenceType(returnType), descriptorProvider)
result = CGWrapper(result, pre="Vec<", post=">")
@@ -5323,6 +5326,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries
enums = []

return CGImports(cgthings, descriptors, callbacks, dictionaries, enums, [
'core::nonzero::NonZero',
'js',
'js::JSCLASS_GLOBAL_SLOT_COUNT',
'js::JSCLASS_IS_DOMJSCLASS',
@@ -6,6 +6,7 @@

//! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations.

use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult;
use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult;
use dom::bindings::error::Fallible;
@@ -95,38 +96,41 @@ impl<T: Reflectable + JSTraceable + Iterable> IterableIterator<T> {

/// Return the next value from the iterable object.
#[allow(non_snake_case)]
pub fn Next(&self, cx: *mut JSContext) -> Fallible<*mut JSObject> {
pub fn Next(&self, cx: *mut JSContext) -> Fallible<NonZero<*mut JSObject>> {
let index = self.index.get();
rooted!(in(cx) let mut value = UndefinedValue());
rooted!(in(cx) let mut rval = ptr::null_mut());
if index >= self.iterable.get_iterable_length() {
return dict_return(cx, rval.handle_mut(), true, value.handle())
.map(|_| rval.handle().get());
}
let result = match self.type_ {
IteratorType::Keys => {
unsafe {
self.iterable.get_key_at_index(index).to_jsval(cx, value.handle_mut());
let result = if index >= self.iterable.get_iterable_length() {
dict_return(cx, rval.handle_mut(), true, value.handle())
} else {
match self.type_ {
IteratorType::Keys => {
unsafe {
self.iterable.get_key_at_index(index).to_jsval(cx, value.handle_mut());
}
dict_return(cx, rval.handle_mut(), false, value.handle())
}
dict_return(cx, rval.handle_mut(), false, value.handle())
}
IteratorType::Values => {
unsafe {
self.iterable.get_value_at_index(index).to_jsval(cx, value.handle_mut());
IteratorType::Values => {
unsafe {
self.iterable.get_value_at_index(index).to_jsval(cx, value.handle_mut());
}
dict_return(cx, rval.handle_mut(), false, value.handle())
}
dict_return(cx, rval.handle_mut(), false, value.handle())
}
IteratorType::Entries => {
rooted!(in(cx) let mut key = UndefinedValue());
unsafe {
self.iterable.get_key_at_index(index).to_jsval(cx, key.handle_mut());
self.iterable.get_value_at_index(index).to_jsval(cx, value.handle_mut());
IteratorType::Entries => {
rooted!(in(cx) let mut key = UndefinedValue());
unsafe {
self.iterable.get_key_at_index(index).to_jsval(cx, key.handle_mut());
self.iterable.get_value_at_index(index).to_jsval(cx, value.handle_mut());
}
key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle())
}
key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle())
}
};
self.index.set(index + 1);
result.map(|_| rval.handle().get())
result.map(|_| {
assert!(!rval.is_null());
unsafe { NonZero::new(rval.get()) }
})
}
}

@@ -2,6 +2,7 @@
* 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/. */

use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods;
@@ -43,7 +44,8 @@ impl CryptoMethods for Crypto {
fn GetRandomValues(&self,
_cx: *mut JSContext,
input: *mut JSObject)
-> Fallible<*mut JSObject> {
-> Fallible<NonZero<*mut JSObject>> {
assert!(!input.is_null());
let mut data = match unsafe { array_buffer_view_data::<u8>(input) } {
Some(data) => data,
None => {
@@ -62,7 +64,7 @@ impl CryptoMethods for Crypto {

self.rng.borrow_mut().fill_bytes(&mut data);

Ok(input)
Ok(unsafe { NonZero::new(input) })
}
}

@@ -2,6 +2,7 @@
* 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/. */

use core::nonzero::NonZero;
use document_loader::{DocumentLoader, LoadType};
use dom::activation::{ActivationSource, synthetic_click_activation};
use dom::attr::Attr;
@@ -90,7 +91,7 @@ use euclid::point::Point2D;
use html5ever::tree_builder::{LimitedQuirks, NoQuirks, Quirks, QuirksMode};
use ipc_channel::ipc::{self, IpcSender};
use js::jsapi::JS_GetRuntime;
use js::jsapi::{JSContext, JSObject, JSRuntime};
use js::jsapi::{JSContext, JSObject, JSRuntime, JS_NewPlainObject};
use msg::constellation_msg::{ALT, CONTROL, SHIFT, SUPER};
use msg::constellation_msg::{Key, KeyModifiers, KeyState};
use msg::constellation_msg::{PipelineId, ReferrerPolicy, SubpageId};
@@ -116,7 +117,6 @@ use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::default::Default;
use std::iter::once;
use std::mem;
use std::ptr;
use std::rc::Rc;
use std::sync::Arc;
use string_cache::{Atom, QualName};
@@ -2689,8 +2689,10 @@ impl DocumentMethods for Document {
self.set_body_attribute(&atom!("text"), value)
}

#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString, found: &mut bool) -> *mut JSObject {
fn NamedGetter(&self, cx: *mut JSContext, name: DOMString, found: &mut bool)
-> NonZero<*mut JSObject> {
#[derive(JSTraceable, HeapSizeOf)]
struct NamedElementFilter {
name: Atom,
@@ -2759,11 +2761,15 @@ impl DocumentMethods for Document {
*found = true;
// TODO: Step 2.
// Step 3.
return first.reflector().get_jsobject().get();
return unsafe {
NonZero::new(first.reflector().get_jsobject().get())
};
}
} else {
*found = false;
return ptr::null_mut();
return unsafe {
NonZero::new(JS_NewPlainObject(cx))
};
}
}
// Step 4.
@@ -2772,7 +2778,9 @@ impl DocumentMethods for Document {
name: name,
};
let collection = HTMLCollection::create(self.window(), root, box filter);
collection.reflector().get_jsobject().get()
unsafe {
NonZero::new(collection.reflector().get_jsobject().get())
}
}

// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names
@@ -2,6 +2,7 @@
* 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/. */

use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::ImageDataBinding;
use dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods;
use dom::bindings::global::GlobalRef;
@@ -82,9 +83,10 @@ impl ImageDataMethods for ImageData {
self.height
}

#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-imagedata-data
fn Data(&self, _: *mut JSContext) -> *mut JSObject {
fn Data(&self, _: *mut JSContext) -> NonZero<*mut JSObject> {
assert!(!self.data.get().is_null());
self.data.get()
unsafe { NonZero::new(self.data.get()) }
}
}
@@ -4,6 +4,7 @@

// check-tidy: no specs after this line

use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::TestBindingBinding;
@@ -139,21 +140,21 @@ impl TestBindingMethods for TestBinding {
}
fn SetUnion9Attribute(&self, _: ByteStringOrLong) {}
#[allow(unsafe_code)]
fn ArrayAttribute(&self, cx: *mut JSContext) -> *mut JSObject {
fn ArrayAttribute(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> {
unsafe {
rooted!(in(cx) let array = JS_NewUint8ClampedArray(cx, 16));
assert!(!array.is_null());
array.get()
NonZero::new(array.get())
}
}
fn AnyAttribute(&self, _: *mut JSContext) -> JSVal { NullValue() }
fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {}
#[allow(unsafe_code)]
fn ObjectAttribute(&self, cx: *mut JSContext) -> *mut JSObject {
fn ObjectAttribute(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> {
unsafe {
rooted!(in(cx) let obj = JS_NewPlainObject(cx));
assert!(!obj.is_null());
obj.get()
NonZero::new(obj.get())
}
}
fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {}
@@ -208,7 +209,7 @@ impl TestBindingMethods for TestBinding {
fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) {
self.url.set(url);
}
fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> *mut JSObject { ptr::null_mut() }
fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option<NonZero<*mut JSObject>> { None }
fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {}
fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> {
Some(HTMLElementOrLong::Long(0))
@@ -257,7 +258,7 @@ impl TestBindingMethods for TestBinding {
Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned())
}
fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() }
fn ReceiveObject(&self, cx: *mut JSContext) -> *mut JSObject {
fn ReceiveObject(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> {
self.ObjectAttribute(cx)
}
fn ReceiveUnion(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) }
@@ -300,7 +301,7 @@ impl TestBindingMethods for TestBinding {
fn ReceiveNullableInterface(&self) -> Option<Root<Blob>> {
Some(Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned()))
}
fn ReceiveNullableObject(&self, cx: *mut JSContext) -> *mut JSObject {
fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option<NonZero<*mut JSObject>> {
self.GetObjectAttributeNullable(cx)
}
fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> {
@@ -2,6 +2,7 @@
* 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/. */

use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::TextEncoderBinding;
use dom::bindings::codegen::Bindings::TextEncoderBinding::TextEncoderMethods;
use dom::bindings::error::{Error, Fallible};
@@ -70,7 +71,7 @@ impl TextEncoderMethods for TextEncoder {

#[allow(unsafe_code)]
// https://encoding.spec.whatwg.org/#dom-textencoder-encode
fn Encode(&self, cx: *mut JSContext, input: USVString) -> *mut JSObject {
fn Encode(&self, cx: *mut JSContext, input: USVString) -> NonZero<*mut JSObject> {
unsafe {
let encoded = self.encoder.encode(&input.0, EncoderTrap::Strict).unwrap();
let length = encoded.len() as u32;
@@ -80,7 +81,7 @@ impl TextEncoderMethods for TextEncoder {
let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object.get(), &mut is_shared, ptr::null());
assert!(!is_shared);
ptr::copy_nonoverlapping(encoded.as_ptr(), js_object_data, length as usize);
js_object.get()
NonZero::new(js_object.get())
}
}
}
@@ -3,6 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use canvas_traits::{CanvasCommonMsg, CanvasMsg, byte_swap};
use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextMethods;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::{self, WebGLContextAttributes};
@@ -631,8 +632,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
}

// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14
fn GetExtension(&self, _cx: *mut JSContext, _name: DOMString) -> *mut JSObject {
0 as *mut JSObject
fn GetExtension(&self, _cx: *mut JSContext, _name: DOMString)
-> Option<NonZero<*mut JSObject>> {
None
}

// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
@@ -2,6 +2,7 @@
* 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/. */

use core::nonzero::NonZero;
use document_loader::DocumentLoader;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::XMLDocumentBinding::{self, XMLDocumentMethods};
@@ -87,7 +88,8 @@ impl XMLDocumentMethods for XMLDocument {
}

// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString, found: &mut bool) -> *mut JSObject {
fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString, found: &mut bool)
-> NonZero<*mut JSObject> {
self.upcast::<Document>().NamedGetter(_cx, name, found)
}
}

Some generated files are not rendered by default. Learn more.

Some generated files are not rendered by default. Learn more.

ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.