From b372e7c98f4148eda720faf343547404e4fd8d61 Mon Sep 17 00:00:00 2001 From: "Abelardo E. Mendoza" Date: Fri, 3 Jun 2016 12:11:35 -0600 Subject: [PATCH] script creates methods taking '*mut JSContext' unsafe rebase + marked the necessary new code as unsafe --- .../dom/bindings/codegen/CodegenRust.py | 37 +++-- components/script/dom/bindings/iterable.rs | 2 +- components/script/dom/bindings/reflector.rs | 6 +- components/script/dom/crypto.rs | 6 +- components/script/dom/customevent.rs | 6 +- .../script/dom/dedicatedworkerglobalscope.rs | 8 +- components/script/dom/document.rs | 10 +- components/script/dom/errorevent.rs | 3 +- components/script/dom/eventtarget.rs | 3 +- .../script/dom/extendablemessageevent.rs | 3 +- components/script/dom/filereader.rs | 6 +- components/script/dom/htmlcanvaselement.rs | 6 +- components/script/dom/imagedata.rs | 4 +- components/script/dom/messageevent.rs | 3 +- components/script/dom/node.rs | 2 +- components/script/dom/popstateevent.rs | 3 +- components/script/dom/serviceworker.rs | 3 +- .../script/dom/serviceworkerglobalscope.rs | 5 +- components/script/dom/testbinding.rs | 86 ++++++----- components/script/dom/textdecoder.rs | 4 +- components/script/dom/textencoder.rs | 22 ++- .../script/dom/webglrenderingcontext.rs | 142 +++++++++--------- components/script/dom/window.rs | 28 +++- components/script/dom/worker.rs | 3 +- components/script/dom/workerglobalscope.rs | 16 +- components/script/dom/xmldocument.rs | 3 +- components/script/dom/xmlhttprequest.rs | 72 +++++---- components/script/lib.rs | 8 +- 28 files changed, 274 insertions(+), 226 deletions(-) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 246d155d1e0..b67ab0bd716 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -2316,10 +2316,13 @@ class CGAbstractMethod(CGThing): arguments. docs is None or documentation for the method in a string. + + unsafe is used to add the decorator 'unsafe' to a function, giving as a result + an 'unsafe fn()' declaration. """ def __init__(self, descriptor, name, returnType, args, inline=False, - alwaysInline=False, extern=False, unsafe_fn=False, pub=False, - templateArgs=None, unsafe=False, docs=None, doesNotPanic=False): + alwaysInline=False, extern=False, unsafe=False, pub=False, + templateArgs=None, docs=None, doesNotPanic=False): CGThing.__init__(self) self.descriptor = descriptor self.name = name @@ -2327,10 +2330,9 @@ class CGAbstractMethod(CGThing): self.args = args self.alwaysInline = alwaysInline self.extern = extern - self.unsafe_fn = extern or unsafe_fn + self.unsafe = extern or unsafe self.templateArgs = templateArgs self.pub = pub - self.unsafe = unsafe self.docs = docs self.catchPanic = self.extern and not doesNotPanic @@ -2357,7 +2359,7 @@ class CGAbstractMethod(CGThing): if self.pub: decorators.append('pub') - if self.unsafe_fn: + if self.unsafe: decorators.append('unsafe') if self.extern: @@ -2373,10 +2375,6 @@ class CGAbstractMethod(CGThing): def define(self): body = self.definition_body() - # Method will already be marked `unsafe` if `self.extern == True` - if self.unsafe and not self.extern: - body = CGWrapper(CGIndenter(body), pre="unsafe {\n", post="\n}") - if self.catchPanic: body = CGWrapper(CGIndenter(body), pre="return wrap_panic(|| {\n", @@ -2409,7 +2407,7 @@ class CGConstructorEnabled(CGAbstractMethod): 'ConstructorEnabled', 'bool', [Argument("*mut JSContext", "aCx"), Argument("HandleObject", "aObj")], - unsafe_fn=True) + unsafe=True) def definition_body(self): conditions = [] @@ -3089,7 +3087,7 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod): Argument('HandleObject', 'global'), ] CGAbstractMethod.__init__(self, descriptor, 'DefineDOMInterface', - 'void', args, pub=True, unsafe_fn=True) + 'void', args, pub=True, unsafe=True) def define(self): return CGAbstractMethod.define(self) @@ -5349,10 +5347,19 @@ class CGInterfaceTrait(CGThing): def fmt(arguments): return "".join(", %s: %s" % argument for argument in arguments) - methods = [ - CGGeneric("fn %s(&self%s) -> %s;\n" % (name, fmt(arguments), rettype)) - for name, arguments, rettype in members() - ] + def contains_unsafe_arg(arguments): + if not arguments or len(arguments) == 0: + return False + return reduce((lambda x, y: x or y[1] == '*mut JSContext'), arguments, False) + + methods = [] + for name, arguments, rettype in members(): + arguments = list(arguments) + methods.append(CGGeneric("%sfn %s(&self%s) -> %s;\n" % ( + 'unsafe ' if contains_unsafe_arg(arguments) else '', + name, fmt(arguments), rettype)) + ) + if methods: self.cgRoot = CGWrapper(CGIndenter(CGList(methods, "")), pre="pub trait %sMethods {\n" % descriptor.interface.identifier.name, diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index 3e6febeeb5d..a0d281a0afc 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -85,7 +85,7 @@ impl IterableIterator { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new(iterable: &T, type_: IteratorType, - wrap: fn(*mut JSContext, &GlobalScope, Box>) + wrap: unsafe fn(*mut JSContext, &GlobalScope, Box>) -> Root) -> Root { let iterator = box IterableIterator { reflector: Reflector::new(), diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 737268bf7d0..05f262dab01 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -16,12 +16,14 @@ use std::ptr; pub fn reflect_dom_object( obj: Box, global: &U, - wrap_fn: fn(*mut JSContext, &GlobalScope, Box) -> Root) + wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box) -> Root) -> Root where T: Reflectable, U: DerivedFrom { let global_scope = global.upcast(); - wrap_fn(global_scope.get_cx(), global_scope, obj) + unsafe { + wrap_fn(global_scope.get_cx(), global_scope, obj) + } } /// A struct to store a reference to the reflector of a DOM object. diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index 45c1c4639d5..22466f3f14c 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -41,12 +41,12 @@ impl Crypto { impl CryptoMethods for Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues - fn GetRandomValues(&self, + unsafe fn GetRandomValues(&self, _cx: *mut JSContext, input: *mut JSObject) -> Fallible> { assert!(!input.is_null()); - let mut data = match unsafe { array_buffer_view_data::(input) } { + let mut data = match array_buffer_view_data::(input) { Some(data) => data, None => { return Err(Error::Type("Argument to Crypto.getRandomValues is not an ArrayBufferView" @@ -64,7 +64,7 @@ impl CryptoMethods for Crypto { self.rng.borrow_mut().fill_bytes(&mut data); - Ok(unsafe { NonZero::new(input) }) + Ok(NonZero::new(input)) } } diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index a70aa096e43..f4346280cb7 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -76,13 +76,15 @@ impl CustomEvent { } impl CustomEventMethods for CustomEvent { + #[allow(unsafe_code)] // https://dom.spec.whatwg.org/#dom-customevent-detail - fn Detail(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Detail(&self, _cx: *mut JSContext) -> JSVal { self.detail.get() } + #[allow(unsafe_code)] // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent - fn InitCustomEvent(&self, + unsafe fn InitCustomEvent(&self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 86aac32df1b..859657b3b57 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -117,6 +117,7 @@ impl DedicatedWorkerGlobalScope { } } + #[allow(unsafe_code)] pub fn new(init: WorkerGlobalScopeInit, worker_url: Url, from_devtools_receiver: Receiver, @@ -139,7 +140,9 @@ impl DedicatedWorkerGlobalScope { timer_event_chan, timer_event_port, closing); - DedicatedWorkerGlobalScopeBinding::Wrap(cx, scope) + unsafe { + DedicatedWorkerGlobalScopeBinding::Wrap(cx, scope) + } } #[allow(unsafe_code)] @@ -366,8 +369,9 @@ unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { } impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage - fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let worker = self.worker.borrow().as_ref().unwrap().clone(); self.parent_sender diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 5b1f4cfe404..7d1af84fee9 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -2802,7 +2802,7 @@ impl DocumentMethods for Document { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option> { + unsafe fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option> { #[derive(JSTraceable, HeapSizeOf)] struct NamedElementFilter { name: Atom, @@ -2870,9 +2870,7 @@ impl DocumentMethods for Document { if elements.peek().is_none() { // TODO: Step 2. // Step 3. - return unsafe { - Some(NonZero::new(first.reflector().get_jsobject().get())) - }; + return Some(NonZero::new(first.reflector().get_jsobject().get())); } } else { return None; @@ -2883,9 +2881,7 @@ impl DocumentMethods for Document { name: name, }; let collection = HTMLCollection::create(self.window(), root, box filter); - unsafe { - Some(NonZero::new(collection.reflector().get_jsobject().get())) - } + Some(NonZero::new(collection.reflector().get_jsobject().get())) } // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index 65f3be9e32b..3739d5732f3 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -130,8 +130,9 @@ impl ErrorEventMethods for ErrorEvent { self.filename.borrow().clone() } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-errorevent-error - fn Error(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Error(&self, _cx: *mut JSContext) -> JSVal { self.error.get() } diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 48ba920ad60..7acb8cfd8e6 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -140,6 +140,7 @@ pub enum CompiledEventListener { } impl CompiledEventListener { + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#the-event-handler-processing-algorithm pub fn call_or_handle_event(&self, object: &T, @@ -155,7 +156,7 @@ impl CompiledEventListener { CommonEventHandler::ErrorEventHandler(ref handler) => { if let Some(event) = event.downcast::() { let cx = object.global().get_cx(); - rooted!(in(cx) let error = event.Error(cx)); + rooted!(in(cx) let error = unsafe { event.Error(cx) }); let return_value = handler.Call_(object, EventOrString::String(event.Message()), Some(event.Filename()), diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index b3f3a5318f7..fbbdd59cbd3 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -74,8 +74,9 @@ impl ExtendableMessageEvent { } impl ExtendableMessageEventMethods for ExtendableMessageEvent { + #[allow(unsafe_code)] // https://w3c.github.io/ServiceWorker/#extendablemessage-event-data-attribute - fn Data(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { self.data.get() } diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 2594b196918..7197de9a2fa 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -339,14 +339,12 @@ impl FileReaderMethods for FileReader { #[allow(unsafe_code)] // https://w3c.github.io/FileAPI/#dfn-result - fn GetResult(&self, _: *mut JSContext) -> Option { + unsafe fn GetResult(&self, _: *mut JSContext) -> Option { self.result.borrow().as_ref().map(|r| match *r { FileReaderResult::String(ref string) => StringOrObject::String(string.clone()), FileReaderResult::ArrayBuffer(ref arr_buffer) => { - unsafe { - StringOrObject::Object((*arr_buffer.ptr.get()).to_object()) - } + StringOrObject::Object((*arr_buffer.ptr.get()).to_object()) } }) } diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 326b1804ddf..5710b703ea6 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -235,8 +235,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT); + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext - fn GetContext(&self, + unsafe fn GetContext(&self, cx: *mut JSContext, id: DOMString, attributes: Vec) @@ -254,8 +255,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { } } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl - fn ToDataURL(&self, + unsafe fn ToDataURL(&self, _context: *mut JSContext, _mime_type: Option, _arguments: Vec) -> Fallible { diff --git a/components/script/dom/imagedata.rs b/components/script/dom/imagedata.rs index 5f99fb9db57..877510c7d9a 100644 --- a/components/script/dom/imagedata.rs +++ b/components/script/dom/imagedata.rs @@ -85,8 +85,8 @@ impl ImageDataMethods for ImageData { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data - fn Data(&self, _: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn Data(&self, _: *mut JSContext) -> NonZero<*mut JSObject> { assert!(!self.data.get().is_null()); - unsafe { NonZero::new(self.data.get()) } + NonZero::new(self.data.get()) } } diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index f3d2aa79ba4..b457461723c 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -95,8 +95,9 @@ impl MessageEvent { } impl MessageEventMethods for MessageEvent { + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-messageevent-data - fn Data(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { self.data.get() } diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 5fcfd74f1f6..9da2ccf6432 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -1364,7 +1364,7 @@ impl Node { pub fn reflect_node( node: Box, document: &Document, - wrap_fn: extern "Rust" fn(*mut JSContext, &GlobalScope, Box) -> Root) + wrap_fn: unsafe extern "Rust" fn(*mut JSContext, &GlobalScope, Box) -> Root) -> Root where N: DerivedFrom + Reflectable { diff --git a/components/script/dom/popstateevent.rs b/components/script/dom/popstateevent.rs index 153c30531fe..44183f7483f 100644 --- a/components/script/dom/popstateevent.rs +++ b/components/script/dom/popstateevent.rs @@ -67,8 +67,9 @@ impl PopStateEvent { } impl PopStateEventMethods for PopStateEvent { + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state - fn State(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn State(&self, _cx: *mut JSContext) -> JSVal { self.state.get() } diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index f61dcc4e41c..306b5316adf 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -80,8 +80,9 @@ impl ServiceWorkerMethods for ServiceWorker { USVString(self.script_url.borrow().clone()) } + #[allow(unsafe_code)] // https://w3c.github.io/ServiceWorker/#service-worker-postmessage - fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { // Step 1 if let ServiceWorkerState::Redundant = self.state.get() { return Err(Error::InvalidState); diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 6a39aad418f..c5012637c80 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -110,6 +110,7 @@ impl ServiceWorkerGlobalScope { } } + #[allow(unsafe_code)] pub fn new(init: WorkerGlobalScopeInit, worker_url: Url, from_devtools_receiver: Receiver, @@ -132,7 +133,9 @@ impl ServiceWorkerGlobalScope { timer_event_port, swmanager_sender, scope_url); - ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) + unsafe { + ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) + } } #[allow(unsafe_code)] diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index fe76ddccab9..08daf6eefa7 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -149,24 +149,23 @@ impl TestBindingMethods for TestBinding { } fn SetUnion9Attribute(&self, _: ByteStringOrLong) {} #[allow(unsafe_code)] - fn ArrayAttribute(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { - unsafe { - rooted!(in(cx) let array = JS_NewUint8ClampedArray(cx, 16)); - assert!(!array.is_null()); - NonZero::new(array.get()) - } + unsafe fn ArrayAttribute(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { + rooted!(in(cx) let array = JS_NewUint8ClampedArray(cx, 16)); + assert!(!array.is_null()); + 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) -> NonZero<*mut JSObject> { - unsafe { - rooted!(in(cx) let obj = JS_NewPlainObject(cx)); - assert!(!obj.is_null()); - NonZero::new(obj.get()) - } + unsafe fn AnyAttribute(&self, _: *mut JSContext) -> JSVal { NullValue() } + #[allow(unsafe_code)] + unsafe fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {} + #[allow(unsafe_code)] + unsafe fn ObjectAttribute(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { + rooted!(in(cx) let obj = JS_NewPlainObject(cx)); + assert!(!obj.is_null()); + NonZero::new(obj.get()) } - fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {} + #[allow(unsafe_code)] + unsafe fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {} fn GetBooleanAttributeNullable(&self) -> Option { Some(false) } fn SetBooleanAttributeNullable(&self, _: Option) {} @@ -218,8 +217,10 @@ impl TestBindingMethods for TestBinding { fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) { self.url.set(url); } - fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option> { None } - fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {} + #[allow(unsafe_code)] + unsafe fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option> { None } + #[allow(unsafe_code)] + unsafe fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {} fn GetUnionAttributeNullable(&self) -> Option { Some(HTMLElementOrLong::Long(0)) } @@ -266,8 +267,10 @@ impl TestBindingMethods for TestBinding { fn ReceiveInterface(&self) -> Root { Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } - fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } - fn ReceiveObject(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { + #[allow(unsafe_code)] + unsafe fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } + #[allow(unsafe_code)] + unsafe fn ReceiveObject(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { self.ObjectAttribute(cx) } fn ReceiveUnion(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) } @@ -310,7 +313,8 @@ impl TestBindingMethods for TestBinding { fn ReceiveNullableInterface(&self) -> Option> { Some(Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } - fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option> { + #[allow(unsafe_code)] + unsafe fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option> { self.GetObjectAttributeNullable(cx) } fn ReceiveNullableUnion(&self) -> Option { @@ -432,8 +436,10 @@ impl TestBindingMethods for TestBinding { fn PassUnion8(&self, _: ByteStringSequenceOrLong) {} fn PassUnionWithTypedef(&self, _: DocumentOrTestTypedef) {} fn PassUnionWithTypedef2(&self, _: LongSequenceOrTestTypedef) {} - fn PassAny(&self, _: *mut JSContext, _: HandleValue) {} - fn PassObject(&self, _: *mut JSContext, _: *mut JSObject) {} + #[allow(unsafe_code)] + unsafe fn PassAny(&self, _: *mut JSContext, _: HandleValue) {} + #[allow(unsafe_code)] + unsafe fn PassObject(&self, _: *mut JSContext, _: *mut JSObject) {} fn PassCallbackFunction(&self, _: Rc) {} fn PassCallbackInterface(&self, _: Rc) {} fn PassSequence(&self, _: Vec) {} @@ -458,7 +464,8 @@ impl TestBindingMethods for TestBinding { fn PassNullableByteString(&self, _: Option) {} // fn PassNullableEnum(self, _: Option) {} fn PassNullableInterface(&self, _: Option<&Blob>) {} - fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {} + #[allow(unsafe_code)] + unsafe fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {} fn PassNullableUnion(&self, _: Option) {} fn PassNullableUnion2(&self, _: Option) {} fn PassNullableUnion3(&self, _: Option) {} @@ -493,8 +500,10 @@ impl TestBindingMethods for TestBinding { fn PassOptionalUnion4(&self, _: Option) {} fn PassOptionalUnion5(&self, _: Option) {} fn PassOptionalUnion6(&self, _: Option) {} - fn PassOptionalAny(&self, _: *mut JSContext, _: HandleValue) {} - fn PassOptionalObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + #[allow(unsafe_code)] + unsafe fn PassOptionalAny(&self, _: *mut JSContext, _: HandleValue) {} + #[allow(unsafe_code)] + unsafe fn PassOptionalObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} fn PassOptionalCallbackFunction(&self, _: Option>) {} fn PassOptionalCallbackInterface(&self, _: Option>) {} fn PassOptionalSequence(&self, _: Option>) {} @@ -517,7 +526,8 @@ impl TestBindingMethods for TestBinding { fn PassOptionalNullableByteString(&self, _: Option>) {} // fn PassOptionalNullableEnum(self, _: Option>) {} fn PassOptionalNullableInterface(&self, _: Option>) {} - fn PassOptionalNullableObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + #[allow(unsafe_code)] + unsafe fn PassOptionalNullableObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} fn PassOptionalNullableUnion(&self, _: Option>) {} fn PassOptionalNullableUnion2(&self, _: Option>) {} fn PassOptionalNullableUnion3(&self, _: Option>) {} @@ -560,12 +570,14 @@ impl TestBindingMethods for TestBinding { fn PassOptionalNullableByteStringWithDefault(&self, _: Option) {} // fn PassOptionalNullableEnumWithDefault(self, _: Option) {} fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {} - fn PassOptionalNullableObjectWithDefault(&self, _: *mut JSContext, _: *mut JSObject) {} + #[allow(unsafe_code)] + unsafe fn PassOptionalNullableObjectWithDefault(&self, _: *mut JSContext, _: *mut JSObject) {} fn PassOptionalNullableUnionWithDefault(&self, _: Option) {} fn PassOptionalNullableUnion2WithDefault(&self, _: Option) {} // fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option) {} fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option>) {} - fn PassOptionalAnyWithDefault(&self, _: *mut JSContext, _: HandleValue) {} + #[allow(unsafe_code)] + unsafe fn PassOptionalAnyWithDefault(&self, _: *mut JSContext, _: HandleValue) {} fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option) {} fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option) {} @@ -610,8 +622,10 @@ impl TestBindingMethods for TestBinding { fn PassVariadicUnion5(&self, _: Vec) {} fn PassVariadicUnion6(&self, _: Vec) {} fn PassVariadicUnion7(&self, _: Vec) {} - fn PassVariadicAny(&self, _: *mut JSContext, _: Vec) {} - fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {} + #[allow(unsafe_code)] + unsafe fn PassVariadicAny(&self, _: *mut JSContext, _: Vec) {} + #[allow(unsafe_code)] + unsafe fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {} fn BooleanMozPreference(&self, pref_name: DOMString) -> bool { PREFS.get(pref_name.as_ref()).as_boolean().unwrap_or(false) } @@ -654,20 +668,24 @@ impl TestBindingMethods for TestBinding { fn ReceiveAnyMozMap(&self) -> MozMap { MozMap::new() } #[allow(unrooted_must_root)] - fn ReturnResolvedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { + #[allow(unsafe_code)] + unsafe fn ReturnResolvedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { Promise::Resolve(&self.global(), cx, v) } #[allow(unrooted_must_root)] - fn ReturnRejectedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { + #[allow(unsafe_code)] + unsafe fn ReturnRejectedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { Promise::Reject(&self.global(), cx, v) } - fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { + #[allow(unsafe_code)] + unsafe fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { p.resolve(cx, v); } - fn PromiseRejectNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { + #[allow(unsafe_code)] + unsafe fn PromiseRejectNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { p.reject(cx, v); } diff --git a/components/script/dom/textdecoder.rs b/components/script/dom/textdecoder.rs index db18d9a5be4..abb2f0c4195 100644 --- a/components/script/dom/textdecoder.rs +++ b/components/script/dom/textdecoder.rs @@ -78,14 +78,14 @@ impl TextDecoderMethods for TextDecoder { #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textdecoder-decode - fn Decode(&self, _cx: *mut JSContext, input: Option<*mut JSObject>) + unsafe fn Decode(&self, _cx: *mut JSContext, input: Option<*mut JSObject>) -> Fallible { let input = match input { Some(input) => input, None => return Ok(USVString("".to_owned())), }; - let data = match unsafe { array_buffer_view_data::(input) } { + let data = match array_buffer_view_data::(input) { Some(data) => data, None => { return Err(Error::Type("Argument to TextDecoder.decode is not an ArrayBufferView".to_owned())); diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index 9c8ad647080..1bb35418714 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -50,17 +50,15 @@ impl TextEncoderMethods for TextEncoder { #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textencoder-encode - fn Encode(&self, cx: *mut JSContext, input: USVString) -> NonZero<*mut JSObject> { - unsafe { - let encoded = UTF_8.encode(&input.0, EncoderTrap::Strict).unwrap(); - let length = encoded.len() as u32; - rooted!(in(cx) let js_object = JS_NewUint8Array(cx, length)); - assert!(!js_object.is_null()); - let mut is_shared = false; - 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); - NonZero::new(js_object.get()) - } + unsafe fn Encode(&self, cx: *mut JSContext, input: USVString) -> NonZero<*mut JSObject> { + let encoded = UTF_8.encode(&input.0, EncoderTrap::Strict).unwrap(); + let length = encoded.len() as u32; + rooted!(in(cx) let js_object = JS_NewUint8Array(cx, length)); + assert!(!js_object.is_null()); + let mut is_shared = false; + 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); + NonZero::new(js_object.get()) } } diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index c5af5f4c39d..5428fc794fa 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -94,9 +94,7 @@ macro_rules! object_binding_to_js_or_null { { rooted!(in($cx) let mut rval = NullValue()); if let Some(bound_object) = $binding.get() { - unsafe { - bound_object.to_jsval($cx, rval.handle_mut()); - } + bound_object.to_jsval($cx, rval.handle_mut()); } rval.get() } @@ -624,8 +622,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { receiver.recv().unwrap() } + #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { + unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { let (sender, receiver) = ipc::channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::GetBufferParameter(target, parameter, sender))) @@ -642,7 +641,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { + unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { // Handle the GL_*_BINDING without going all the way // to the GL, since we would just need to map back from GL's // returned ID to the WebGL* object we're tracking. @@ -693,9 +692,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { WebGLParameter::FloatArray(_) => panic!("Parameter should not be float array"), WebGLParameter::String(val) => { rooted!(in(cx) let mut rval = UndefinedValue()); - unsafe { - val.to_jsval(cx, rval.handle_mut()); - } + val.to_jsval(cx, rval.handle_mut()); rval.get() } WebGLParameter::Invalid => NullValue(), @@ -748,8 +745,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { Some(vec![]) } + #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 - fn GetExtension(&self, _cx: *mut JSContext, _name: DOMString) + unsafe fn GetExtension(&self, _cx: *mut JSContext, _name: DOMString) -> Option> { None } @@ -927,17 +925,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn BufferData(&self, _cx: *mut JSContext, target: u32, data: *mut JSObject, usage: u32) -> Fallible<()> { + unsafe fn BufferData(&self, _cx: *mut JSContext, target: u32, data: *mut JSObject, usage: u32) -> Fallible<()> { if data.is_null() { return Ok(self.webgl_error(InvalidValue)); } - let data_vec = unsafe { - match array_buffer_to_vec::(data) { - Some(data) => data, - // Not an ArrayBuffer object, maybe an ArrayBufferView? - None => try!(fallible_array_buffer_view_to_vec::(data)), - } + let data_vec = match array_buffer_to_vec::(data) { + Some(data) => data, + // Not an ArrayBuffer object, maybe an ArrayBufferView? + None => try!(fallible_array_buffer_view_to_vec::(data)), }; let bound_buffer = match target { @@ -965,17 +961,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn BufferSubData(&self, _cx: *mut JSContext, target: u32, offset: i64, data: *mut JSObject) -> Fallible<()> { + unsafe fn BufferSubData(&self, _cx: *mut JSContext, target: u32, offset: i64, data: *mut JSObject) -> Fallible<()> { if data.is_null() { return Ok(self.webgl_error(InvalidValue)); } - let data_vec = unsafe { - match array_buffer_to_vec::(data) { - Some(data) => data, - // Not an ArrayBuffer object, maybe an ArrayBufferView? - None => try!(fallible_array_buffer_view_to_vec::(data)), - } + let data_vec = match array_buffer_to_vec::(data) { + Some(data) => data, + // Not an ArrayBuffer object, maybe an ArrayBufferView? + None => try!(fallible_array_buffer_view_to_vec::(data)), }; let bound_buffer = match target { @@ -1005,9 +999,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CompressedTexImage2D(&self, _cx: *mut JSContext, _target: u32, _level: i32, _internal_format: u32, + unsafe fn CompressedTexImage2D(&self, _cx: *mut JSContext, _target: u32, _level: i32, _internal_format: u32, _width: i32, _height: i32, _border: i32, pixels: *mut JSObject) -> Fallible<()> { - let _data = try!(unsafe { fallible_array_buffer_view_to_vec::(pixels) }); + let _data = try!(fallible_array_buffer_view_to_vec::(pixels) ); // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT self.webgl_error(InvalidEnum); @@ -1016,10 +1010,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CompressedTexSubImage2D(&self, _cx: *mut JSContext, _target: u32, _level: i32, + unsafe fn CompressedTexSubImage2D(&self, _cx: *mut JSContext, _target: u32, _level: i32, _xoffset: i32, _yoffset: i32, _width: i32, _height: i32, _format: u32, pixels: *mut JSObject) -> Fallible<()> { - let _data = try!(unsafe { fallible_array_buffer_view_to_vec::(pixels) }); + let _data = try!(fallible_array_buffer_view_to_vec::(pixels)); // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT self.webgl_error(InvalidEnum); @@ -1568,8 +1562,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } } + #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetProgramParameter(&self, _: *mut JSContext, program: Option<&WebGLProgram>, param_id: u32) -> JSVal { + unsafe fn GetProgramParameter(&self, _: *mut JSContext, program: Option<&WebGLProgram>, param_id: u32) -> JSVal { if let Some(program) = program { match handle_potential_webgl_error!(self, program.parameter(param_id), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), @@ -1591,8 +1586,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { shader.and_then(|s| s.info_log()).map(DOMString::from) } + #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetShaderParameter(&self, _: *mut JSContext, shader: Option<&WebGLShader>, param_id: u32) -> JSVal { + unsafe fn GetShaderParameter(&self, _: *mut JSContext, shader: Option<&WebGLShader>, param_id: u32) -> JSVal { if let Some(shader) = shader { match handle_potential_webgl_error!(self, shader.parameter(param_id), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), @@ -1621,14 +1617,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, pname: u32) -> JSVal { + unsafe fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, pname: u32) -> JSVal { if index == 0 && pname == constants::CURRENT_VERTEX_ATTRIB { rooted!(in(cx) let mut result = UndefinedValue()); let (x, y, z, w) = self.current_vertex_attrib_0.get(); let attrib = vec![x, y, z, w]; - unsafe { - attrib.to_jsval(cx, result.handle_mut()); - } + attrib.to_jsval(cx, result.handle_mut()); return result.get() } @@ -1642,9 +1636,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { WebGLParameter::Float(_) => panic!("Vertex attrib should not be float"), WebGLParameter::FloatArray(val) => { rooted!(in(cx) let mut result = UndefinedValue()); - unsafe { - val.to_jsval(cx, result.handle_mut()); - } + val.to_jsval(cx, result.handle_mut()); result.get() } WebGLParameter::Invalid => NullValue(), @@ -1787,13 +1779,13 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12 - fn ReadPixels(&self, _cx: *mut JSContext, x: i32, y: i32, width: i32, height: i32, + unsafe fn ReadPixels(&self, _cx: *mut JSContext, x: i32, y: i32, width: i32, height: i32, format: u32, pixel_type: u32, pixels: *mut JSObject) -> Fallible<()> { if pixels.is_null() { return Ok(self.webgl_error(InvalidValue)); } - let mut data = match unsafe { array_buffer_view_data::(pixels) } { + let mut data = match { array_buffer_view_data::(pixels) } { Some(data) => data, None => return Err(Error::Type("Not an ArrayBufferView".to_owned())), }; @@ -1802,7 +1794,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return Ok(()); } - match unsafe { JS_GetArrayBufferViewType(pixels) } { + match { JS_GetArrayBufferViewType(pixels) } { Type::Uint8 => (), _ => return Ok(self.webgl_error(InvalidOperation)), } @@ -2035,12 +2027,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform1iv(&self, + unsafe fn Uniform1iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::Int, &data_vec) { self.ipc_renderer @@ -2053,12 +2045,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform1fv(&self, + unsafe fn Uniform1fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::Float, &data_vec) { self.ipc_renderer @@ -2082,12 +2074,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform2fv(&self, + unsafe fn Uniform2fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec2, @@ -2115,12 +2107,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform2iv(&self, + unsafe fn Uniform2iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec2, @@ -2148,12 +2140,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform3fv(&self, + unsafe fn Uniform3fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec3, @@ -2181,12 +2173,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform3iv(&self, + unsafe fn Uniform3iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec3, @@ -2215,12 +2207,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform4iv(&self, + unsafe fn Uniform4iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec4, @@ -2248,12 +2240,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn Uniform4fv(&self, + unsafe fn Uniform4fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec4, @@ -2268,13 +2260,13 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn UniformMatrix2fv(&self, + unsafe fn UniformMatrix2fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatMat2, &data_vec) { @@ -2288,13 +2280,13 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn UniformMatrix3fv(&self, + unsafe fn UniformMatrix3fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatMat3, &data_vec) { @@ -2308,13 +2300,13 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn UniformMatrix4fv(&self, + unsafe fn UniformMatrix4fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatMat4, &data_vec) { @@ -2352,9 +2344,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn VertexAttrib1fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib1fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if data_vec.len() < 1 { return Ok(self.webgl_error(InvalidOperation)); } @@ -2369,9 +2361,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn VertexAttrib2fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib2fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if data_vec.len() < 2 { return Ok(self.webgl_error(InvalidOperation)); } @@ -2386,9 +2378,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn VertexAttrib3fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib3fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if data_vec.len() < 3 { return Ok(self.webgl_error(InvalidOperation)); } @@ -2403,9 +2395,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - fn VertexAttrib4fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib4fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); - let data_vec = try!(unsafe { typed_array_or_sequence_to_vec::(cx, data, ()) }); + let data_vec = try!(typed_array_or_sequence_to_vec::(cx, data, ())); if data_vec.len() < 4 { return Ok(self.webgl_error(InvalidOperation)); } @@ -2468,7 +2460,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 #[allow(unsafe_code)] - fn TexImage2D(&self, + unsafe fn TexImage2D(&self, _cx: *mut JSContext, target: u32, level: i32, @@ -2482,7 +2474,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let data = if data_ptr.is_null() { None } else { - Some(try!(unsafe { fallible_array_buffer_view_to_vec::(data_ptr) })) + Some(try!(fallible_array_buffer_view_to_vec::(data_ptr))) }; let validator = TexImage2DValidator::new(self, target, level, @@ -2504,7 +2496,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { }; let expected_byte_length = - match unsafe { self.validate_tex_image_2d_data(width, height, + match { self.validate_tex_image_2d_data(width, height, format, data_type, data_ptr) } { Ok(byte_length) => byte_length, @@ -2574,7 +2566,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 #[allow(unsafe_code)] - fn TexSubImage2D(&self, + unsafe fn TexSubImage2D(&self, _cx: *mut JSContext, target: u32, level: i32, @@ -2588,7 +2580,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let data = if data_ptr.is_null() { None } else { - Some(try!(unsafe { fallible_array_buffer_view_to_vec::(data_ptr) })) + Some(try!(fallible_array_buffer_view_to_vec::(data_ptr))) }; @@ -2610,7 +2602,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { }; let expected_byte_length = - match unsafe { self.validate_tex_image_2d_data(width, height, + match { self.validate_tex_image_2d_data(width, height, format, data_type, data_ptr) } { Ok(byte_length) => byte_length, diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 63485e45dfc..cb252cae7b0 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -483,8 +483,10 @@ impl WindowMethods for Window { self.navigator.or_init(|| Navigator::new(self)) } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + unsafe fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, + args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -492,8 +494,10 @@ impl WindowMethods for Window { IsInterval::NonInterval) } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + unsafe fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, @@ -506,8 +510,10 @@ impl WindowMethods for Window { self.upcast::().clear_timeout_or_interval(handle); } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -515,8 +521,10 @@ impl WindowMethods for Window { IsInterval::Interval) } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, @@ -610,8 +618,9 @@ impl WindowMethods for Window { doc.cancel_animation_frame(ident); } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-window-postmessage - fn PostMessage(&self, + unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue, origin: DOMString) @@ -670,8 +679,8 @@ impl WindowMethods for Window { } #[allow(unsafe_code)] - fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) { - let rv = unsafe { jsval_to_webdriver(cx, val) }; + unsafe fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) { + let rv = jsval_to_webdriver(cx, val); let opt_chan = self.webdriver_script_chan.borrow_mut().take(); if let Some(chan) = opt_chan { chan.send(rv).unwrap(); @@ -1511,6 +1520,7 @@ impl Window { } impl Window { + #[allow(unsafe_code)] pub fn new(runtime: Rc, script_chan: MainThreadScriptChan, dom_task_source: DOMManipulationTaskSource, @@ -1598,7 +1608,9 @@ impl Window { test_runner: Default::default(), }; - WindowBinding::Wrap(runtime.cx(), win) + unsafe { + WindowBinding::Wrap(runtime.cx(), win) + } } } diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 42c0d1e553d..011159715f8 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -164,8 +164,9 @@ impl Worker { } impl WorkerMethods for Worker { + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage - fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let address = Trusted::new(self); diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 041ce8448de..d794a9c453a 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -268,8 +268,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { base64_atob(atob) } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + unsafe fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -277,8 +279,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { IsInterval::NonInterval) } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + unsafe fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, @@ -291,8 +295,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { self.upcast::().clear_timeout_or_interval(handle); } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -300,8 +306,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { IsInterval::Interval) } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, diff --git a/components/script/dom/xmldocument.rs b/components/script/dom/xmldocument.rs index 87038d3aa45..9ed694c84e9 100644 --- a/components/script/dom/xmldocument.rs +++ b/components/script/dom/xmldocument.rs @@ -86,8 +86,9 @@ impl XMLDocumentMethods for XMLDocument { self.upcast::().SupportedPropertyNames() } + #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option> { + unsafe fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option> { self.upcast::().NamedGetter(_cx, name) } } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index c07f445a27b..4dc1b644cd6 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -761,47 +761,45 @@ impl XMLHttpRequestMethods for XMLHttpRequest { #[allow(unsafe_code)] // https://xhr.spec.whatwg.org/#the-response-attribute - fn Response(&self, cx: *mut JSContext) -> JSVal { - unsafe { - rooted!(in(cx) let mut rval = UndefinedValue()); - match self.response_type.get() { - XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { - let ready_state = self.ready_state.get(); - // Step 2 - if ready_state == XMLHttpRequestState::Done || ready_state == XMLHttpRequestState::Loading { - self.text_response().to_jsval(cx, rval.handle_mut()); - } else { - // Step 1 - "".to_jsval(cx, rval.handle_mut()); - } - }, - // Step 1 - _ if self.ready_state.get() != XMLHttpRequestState::Done => { - return NullValue(); - }, + unsafe fn Response(&self, cx: *mut JSContext) -> JSVal { + rooted!(in(cx) let mut rval = UndefinedValue()); + match self.response_type.get() { + XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { + let ready_state = self.ready_state.get(); // Step 2 - XMLHttpRequestResponseType::Document => { - let op_doc = self.document_response(); - if let Some(doc) = op_doc { - doc.to_jsval(cx, rval.handle_mut()); - } else { - // Substep 1 - return NullValue(); - } - }, - XMLHttpRequestResponseType::Json => { - self.json_response(cx).to_jsval(cx, rval.handle_mut()); - }, - XMLHttpRequestResponseType::Blob => { - self.blob_response().to_jsval(cx, rval.handle_mut()); - }, - _ => { - // XXXManishearth handle other response types - self.response.borrow().to_jsval(cx, rval.handle_mut()); + if ready_state == XMLHttpRequestState::Done || ready_state == XMLHttpRequestState::Loading { + self.text_response().to_jsval(cx, rval.handle_mut()); + } else { + // Step 1 + "".to_jsval(cx, rval.handle_mut()); } + }, + // Step 1 + _ if self.ready_state.get() != XMLHttpRequestState::Done => { + return NullValue(); + }, + // Step 2 + XMLHttpRequestResponseType::Document => { + let op_doc = self.document_response(); + if let Some(doc) = op_doc { + doc.to_jsval(cx, rval.handle_mut()); + } else { + // Substep 1 + return NullValue(); + } + }, + XMLHttpRequestResponseType::Json => { + self.json_response(cx).to_jsval(cx, rval.handle_mut()); + }, + XMLHttpRequestResponseType::Blob => { + self.blob_response().to_jsval(cx, rval.handle_mut()); + }, + _ => { + // XXXManishearth handle other response types + self.response.borrow().to_jsval(cx, rval.handle_mut()); } - rval.get() } + rval.get() } // https://xhr.spec.whatwg.org/#the-responsetext-attribute diff --git a/components/script/lib.rs b/components/script/lib.rs index ed3283868d5..8ac3669ad88 100644 --- a/components/script/lib.rs +++ b/components/script/lib.rs @@ -173,11 +173,11 @@ pub fn init_service_workers(sw_senders: SWManagerSenders) { pub fn init() { unsafe { proxyhandler::init(); - } - // Create the global vtables used by the (generated) DOM - // bindings to implement JS proxies. - RegisterBindings::RegisterProxyHandlers(); + // Create the global vtables used by the (generated) DOM + // bindings to implement JS proxies. + RegisterBindings::RegisterProxyHandlers(); + } perform_platform_specific_initialization(); }