diff options
author | Josh Matthews <josh@joshmatthews.net> | 2015-01-15 13:26:44 -0500 |
---|---|---|
committer | Glenn Watson <gw@intuitionlibrary.com> | 2015-01-28 10:16:49 +1000 |
commit | 95fc29fa0db21959df99d81cdbb9561226321d2f (patch) | |
tree | a48e171165ec155062ef13c550b2c0f72d127425 /components | |
parent | ff8cbff81016c157373c1675f3eee69dd70ae544 (diff) | |
download | servo-95fc29fa0db21959df99d81cdbb9561226321d2f.tar.gz servo-95fc29fa0db21959df99d81cdbb9561226321d2f.zip |
Update rustc to 00b112c45a604fa6f4b59af2a40c9deeadfdb7c6/rustc-1.0.0-dev.
Diffstat (limited to 'components')
210 files changed, 2716 insertions, 2655 deletions
diff --git a/components/canvas/canvas_paint_task.rs b/components/canvas/canvas_paint_task.rs index b5cdd3be777..73941e03343 100644 --- a/components/canvas/canvas_paint_task.rs +++ b/components/canvas/canvas_paint_task.rs @@ -9,9 +9,9 @@ use geom::size::Size2D; use servo_util::task::spawn_named; use std::borrow::ToOwned; -use std::comm; +use std::sync::mpsc::{channel, Sender}; -#[deriving(Clone)] +#[derive(Clone)] pub enum CanvasMsg { FillRect(Rect<f32>), ClearRect(Rect<f32>), @@ -39,12 +39,12 @@ impl CanvasPaintTask { } pub fn start(size: Size2D<i32>) -> Sender<CanvasMsg> { - let (chan, port) = comm::channel::<CanvasMsg>(); - spawn_named("CanvasTask".to_owned(), proc() { + let (chan, port) = channel::<CanvasMsg>(); + spawn_named("CanvasTask".to_owned(), move || { let mut painter = CanvasPaintTask::new(size); loop { - match port.recv() { + match port.recv().unwrap() { CanvasMsg::FillRect(ref rect) => painter.fill_rect(rect), CanvasMsg::StrokeRect(ref rect) => painter.stroke_rect(rect), CanvasMsg::ClearRect(ref rect) => painter.clear_rect(rect), @@ -81,7 +81,7 @@ impl CanvasPaintTask { fn send_pixel_contents(&mut self, chan: Sender<Vec<u8>>) { self.drawtarget.snapshot().get_data_surface().with_data(|element| { - chan.send(element.to_vec()); + chan.send(element.to_vec()).unwrap(); }) } } diff --git a/components/compositing/Cargo.toml b/components/compositing/Cargo.toml index 6fb0ed57ca1..6c8864b4e8c 100644 --- a/components/compositing/Cargo.toml +++ b/components/compositing/Cargo.toml @@ -43,9 +43,6 @@ git = "https://github.com/servo/rust-layers" [dependencies.png] git = "https://github.com/servo/rust-png" -[dependencies.url] -git = "https://github.com/servo/rust-url" - [dependencies.core_graphics] git = "https://github.com/servo/rust-core-graphics" @@ -55,5 +52,6 @@ git = "https://github.com/servo/rust-core-text" [dependencies.gleam] git = "https://github.com/servo/gleam" -[dependencies.time] -git = "https://github.com/rust-lang/time" +[dependencies] +url = "*" +time = "*"
\ No newline at end of file diff --git a/components/compositing/compositor.rs b/components/compositing/compositor.rs index d10e0c29703..ceee0b2f869 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -41,11 +41,12 @@ use servo_util::opts; use servo_util::time::{TimeProfilerCategory, profile, TimeProfilerChan}; use servo_util::{memory, time}; use std::collections::HashMap; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::path::Path; -use std::num::FloatMath; +use std::num::Float; use std::rc::Rc; use std::slice::bytes::copy_memory; +use std::sync::mpsc::Sender; use time::{precise_time_ns, precise_time_s}; use url::Url; @@ -71,7 +72,7 @@ pub struct IOCompositor<Window: WindowMethods> { scene: Scene<CompositorData>, /// The application window size. - window_size: TypedSize2D<DevicePixel, uint>, + window_size: TypedSize2D<DevicePixel, u32>, /// "Mobile-style" zoom that does not reflow the page. viewport_zoom: ScaleFactor<PagePx, ViewportPx, f32>, @@ -134,14 +135,14 @@ pub struct ScrollEvent { cursor: TypedPoint2D<DevicePixel,i32>, } -#[deriving(PartialEq)] +#[derive(PartialEq)] enum CompositionRequest { NoCompositingNecessary, CompositeOnScrollTimeout(u64), CompositeNow, } -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] enum ShutdownState { NotShuttingDown, ShuttingDown, @@ -250,8 +251,8 @@ impl<Window: WindowMethods> IOCompositor<Window> { (Msg::Exit(chan), _) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; - con_chan.send(ConstellationMsg::Exit); - chan.send(()); + con_chan.send(ConstellationMsg::Exit).unwrap(); + chan.send(()).unwrap(); self.shutdown_state = ShutdownState::ShuttingDown; } @@ -292,13 +293,13 @@ impl<Window: WindowMethods> IOCompositor<Window> { (Msg::ChangeLayerPipelineAndRemoveChildren(old_pipeline, new_pipeline, response_channel), ShutdownState::NotShuttingDown) => { self.handle_change_layer_pipeline_and_remove_children(old_pipeline, new_pipeline); - response_channel.send(()); + response_channel.send(()).unwrap(); } (Msg::CreateRootLayerForPipeline(parent_pipeline, pipeline, rect, response_channel), ShutdownState::NotShuttingDown) => { self.handle_create_root_layer_for_pipeline(parent_pipeline, pipeline, rect); - response_channel.send(()); + response_channel.send(()).unwrap(); } (Msg::CreateOrUpdateBaseLayer(layer_properties), ShutdownState::NotShuttingDown) => { @@ -311,7 +312,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { } (Msg::GetGraphicsMetadata(chan), ShutdownState::NotShuttingDown) => { - chan.send(Some(self.window.native_metadata())); + chan.send(Some(self.window.native_metadata())).unwrap(); } (Msg::SetLayerOrigin(pipeline_id, layer_id, origin), @@ -419,12 +420,12 @@ impl<Window: WindowMethods> IOCompositor<Window> { Some(ref details) => { match details.pipeline { Some(ref pipeline) => pipeline, - None => panic!("Compositor layer has an unitialized pipeline ({}).", + None => panic!("Compositor layer has an unitialized pipeline ({:?}).", pipeline_id), } } - None => panic!("Compositor layer has an unknown pipeline ({}).", pipeline_id), + None => panic!("Compositor layer has an unknown pipeline ({:?}).", pipeline_id), } } @@ -459,7 +460,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { if !self.has_paint_msg_tracking() { return; } - debug!("add_outstanding_paint_msg {}", self.outstanding_paint_msgs); + debug!("add_outstanding_paint_msg {:?}", self.outstanding_paint_msgs); self.outstanding_paint_msgs += count; } @@ -478,7 +479,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { frame_tree: &SendableFrameTree, response_chan: Sender<()>, new_constellation_chan: ConstellationChan) { - response_chan.send(()); + response_chan.send(()).unwrap(); self.root_pipeline = Some(frame_tree.pipeline.clone()); @@ -546,7 +547,8 @@ impl<Window: WindowMethods> IOCompositor<Window> { let root_layer = match self.find_pipeline_root_layer(old_pipeline.id) { Some(root_layer) => root_layer, None => { - debug!("Ignoring ChangeLayerPipelineAndRemoveChildren message for pipeline ({}) shutting down.", + debug!("Ignoring ChangeLayerPipelineAndRemoveChildren message \ + for pipeline ({:?}) shutting down.", old_pipeline.id); return; } @@ -581,7 +583,8 @@ impl<Window: WindowMethods> IOCompositor<Window> { let parent_layer = match self.find_pipeline_root_layer(pipeline_id) { Some(root_layer) => root_layer, None => { - debug!("Ignoring FrameTreeUpdate message for pipeline ({}) shutting down.", + debug!("Ignoring FrameTreeUpdate message for pipeline ({:?}) \ + shutting down.", pipeline_id); return; } @@ -611,7 +614,8 @@ impl<Window: WindowMethods> IOCompositor<Window> { let root_layer = match self.find_pipeline_root_layer(pipeline_id) { Some(root_layer) => root_layer, None => { - debug!("Ignoring CreateOrUpdateBaseLayer message for pipeline ({}) shutting down.", + debug!("Ignoring CreateOrUpdateBaseLayer message for pipeline \ + ({:?}) shutting down.", pipeline_id); return; } @@ -669,7 +673,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { device_pixel_ratio: dppx, initial_viewport: initial_viewport, visible_viewport: visible_viewport, - })); + })).unwrap() } pub fn move_layer(&self, @@ -723,7 +727,8 @@ impl<Window: WindowMethods> IOCompositor<Window> { Some(ref layer) => { layer.bounds.borrow_mut().origin = Point2D::from_untyped(&new_origin) } - None => panic!("Compositor received SetLayerOrigin for nonexistent layer: {}", pipeline_id), + None => panic!("Compositor received SetLayerOrigin for nonexistent \ + layer: {:?}", pipeline_id), }; self.send_buffer_requests_for_all_layers(); @@ -744,14 +749,14 @@ impl<Window: WindowMethods> IOCompositor<Window> { let pipeline = self.get_pipeline(pipeline_id); let message = PaintMsg::UnusedBuffer(new_layer_buffer_set.buffers); - let _ = pipeline.paint_chan.send_opt(message); + let _ = pipeline.paint_chan.send(message); } fn assign_painted_buffers_to_layer(&mut self, layer: Rc<Layer<CompositorData>>, new_layer_buffer_set: Box<LayerBufferSet>, epoch: Epoch) { - debug!("compositor received new frame at size {}x{}", + debug!("compositor received new frame at size {:?}x{:?}", self.window_size.width.get(), self.window_size.height.get()); @@ -829,14 +834,14 @@ impl<Window: WindowMethods> IOCompositor<Window> { WindowEvent::Quit => { debug!("shutting down the constellation for WindowEvent::Quit"); let ConstellationChan(ref chan) = self.constellation_chan; - chan.send(ConstellationMsg::Exit); + chan.send(ConstellationMsg::Exit).unwrap(); self.shutdown_state = ShutdownState::ShuttingDown; } } } - fn on_resize_window_event(&mut self, new_size: TypedSize2D<DevicePixel, uint>) { - debug!("compositor resizing to {}", new_size.to_untyped()); + fn on_resize_window_event(&mut self, new_size: TypedSize2D<DevicePixel, u32>) { + debug!("compositor resizing to {:?}", new_size.to_untyped()); // A size change could also mean a resolution change. let new_hidpi_factor = self.window.hidpi_factor(); @@ -867,7 +872,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { let msg = ConstellationMsg::LoadUrl(root_pipeline_id, LoadData::new(Url::parse(url_string.as_slice()).unwrap())); let ConstellationChan(ref chan) = self.constellation_chan; - chan.send(msg); + chan.send(msg).unwrap() } fn on_mouse_window_event_class(&self, mouse_window_event: MouseWindowEvent) { @@ -986,12 +991,12 @@ impl<Window: WindowMethods> IOCompositor<Window> { windowing::WindowNavigateMsg::Back => NavigationDirection::Back, }; let ConstellationChan(ref chan) = self.constellation_chan; - chan.send(ConstellationMsg::Navigate(direction)) + chan.send(ConstellationMsg::Navigate(direction)).unwrap() } fn on_key_event(&self, key: Key, state: KeyState, modifiers: KeyModifiers) { let ConstellationChan(ref chan) = self.constellation_chan; - chan.send(ConstellationMsg::KeyEvent(key, state, modifiers)) + chan.send(ConstellationMsg::KeyEvent(key, state, modifiers)).unwrap() } fn convert_buffer_requests_to_pipeline_requests_map(&self, @@ -1008,7 +1013,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { entry.into_mut() } Vacant(entry) => { - entry.set(Vec::new()) + entry.insert(Vec::new()) } }; @@ -1035,7 +1040,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { let unused_buffers = self.scene.collect_unused_buffers(); if unused_buffers.len() != 0 { let message = PaintMsg::UnusedBuffer(unused_buffers); - let _ = pipeline.paint_chan.send_opt(message); + let _ = pipeline.paint_chan.send(message); } }, None => {} @@ -1048,7 +1053,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { layer.bounds.borrow().size.to_untyped()); let pipeline = self.get_pipeline(layer.get_pipeline_id()); let ScriptControlChan(ref chan) = pipeline.script_chan; - chan.send(ConstellationControlMsg::Viewport(pipeline.id.clone(), layer_rect)); + chan.send(ConstellationControlMsg::Viewport(pipeline.id.clone(), layer_rect)).unwrap(); } for kid in layer.children().iter() { @@ -1084,7 +1089,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { let mut num_paint_msgs_sent = 0; for (pipeline_id, requests) in pipeline_requests.into_iter() { num_paint_msgs_sent += 1; - let _ = self.get_pipeline(pipeline_id).paint_chan.send_opt(PaintMsg::Paint(requests)); + let _ = self.get_pipeline(pipeline_id).paint_chan.send(PaintMsg::Paint(requests)); } self.add_outstanding_paint_msg(num_paint_msgs_sent); @@ -1125,7 +1130,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { let mut framebuffer_ids = vec!(); let mut texture_ids = vec!(); - let (width, height) = (self.window_size.width.get(), self.window_size.height.get()); + let (width, height) = (self.window_size.width.get() as usize, self.window_size.height.get() as usize); if output_image { framebuffer_ids = gl::gen_framebuffers(1); @@ -1169,8 +1174,8 @@ impl<Window: WindowMethods> IOCompositor<Window> { }); if output_image { - let path = - from_str::<Path>(opts::get().output_file.as_ref().unwrap().as_slice()).unwrap(); + let path: Path = + opts::get().output_file.as_ref().unwrap().as_slice().parse().unwrap(); let mut pixels = gl::read_pixels(0, 0, width as gl::GLsizei, height as gl::GLsizei, @@ -1201,7 +1206,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { debug!("shutting down the constellation after generating an output file"); let ConstellationChan(ref chan) = self.constellation_chan; - chan.send(ConstellationMsg::Exit); + chan.send(ConstellationMsg::Exit).unwrap(); self.shutdown_state = ShutdownState::ShuttingDown; } @@ -1393,10 +1398,10 @@ impl<Window> CompositorEventListener for IOCompositor<Window> where Window: Wind // Tell the profiler, memory profiler, and scrolling timer to shut down. let TimeProfilerChan(ref time_profiler_chan) = self.time_profiler_chan; - time_profiler_chan.send(time::TimeProfilerMsg::Exit); + time_profiler_chan.send(time::TimeProfilerMsg::Exit).unwrap(); let MemoryProfilerChan(ref memory_profiler_chan) = self.memory_profiler_chan; - memory_profiler_chan.send(memory::MemoryProfilerMsg::Exit); + memory_profiler_chan.send(memory::MemoryProfilerMsg::Exit).unwrap(); self.scrolling_timer.shutdown(); } @@ -1411,6 +1416,6 @@ impl<Window> CompositorEventListener for IOCompositor<Window> where Window: Wind Some(ref root_pipeline) => root_pipeline.id, }; let ConstellationChan(ref chan) = self.constellation_chan; - chan.send(ConstellationMsg::GetPipelineTitle(root_pipeline_id)); + chan.send(ConstellationMsg::GetPipelineTitle(root_pipeline_id)).unwrap(); } } diff --git a/components/compositing/compositor_layer.rs b/components/compositing/compositor_layer.rs index 1510ea51fb4..d9f5ba21ca2 100644 --- a/components/compositing/compositor_layer.rs +++ b/components/compositing/compositor_layer.rs @@ -21,7 +21,6 @@ use script_traits::{ScriptControlChan, ConstellationControlMsg}; use servo_msg::compositor_msg::{Epoch, LayerId, ScrollPolicy}; use servo_msg::constellation_msg::PipelineId; use std::num::Float; -use std::num::FloatMath; use std::rc::Rc; pub struct CompositorData { @@ -68,24 +67,25 @@ impl CompositorData { } } -pub trait CompositorLayer<Window: WindowMethods> { +pub trait CompositorLayer { fn update_layer_except_bounds(&self, layer_properties: LayerProperties); fn update_layer(&self, layer_properties: LayerProperties); - fn add_buffers(&self, - compositor: &IOCompositor<Window>, - new_buffers: Box<LayerBufferSet>, - epoch: Epoch) - -> bool; + fn add_buffers<Window>(&self, + compositor: &IOCompositor<Window>, + new_buffers: Box<LayerBufferSet>, + epoch: Epoch) + -> bool + where Window: WindowMethods; /// Destroys all layer tiles, sending the buffers back to the painter to be destroyed or /// reused. - fn clear(&self, compositor: &IOCompositor<Window>); + fn clear<Window>(&self, compositor: &IOCompositor<Window>) where Window: WindowMethods; /// Destroys tiles for this layer and all descendent layers, sending the buffers back to the /// painter to be destroyed or reused. - fn clear_all_tiles(&self, compositor: &IOCompositor<Window>); + fn clear_all_tiles<Window>(&self, compositor: &IOCompositor<Window>) where Window: WindowMethods; /// Destroys all tiles of all layers, including children, *without* sending them back to the /// painter. You must call this only when the paint task is destined to be going down; @@ -107,14 +107,16 @@ pub trait CompositorLayer<Window: WindowMethods> { // Takes in a MouseWindowEvent, determines if it should be passed to children, and // sends the event off to the appropriate pipeline. NB: the cursor position is in // page coordinates. - fn send_mouse_event(&self, - compositor: &IOCompositor<Window>, - event: MouseWindowEvent, - cursor: TypedPoint2D<LayerPixel, f32>); + fn send_mouse_event<Window>(&self, + compositor: &IOCompositor<Window>, + event: MouseWindowEvent, + cursor: TypedPoint2D<LayerPixel, f32>) + where Window: WindowMethods; - fn send_mouse_move_event(&self, - compositor: &IOCompositor<Window>, - cursor: TypedPoint2D<LayerPixel, f32>); + fn send_mouse_move_event<Window>(&self, + compositor: &IOCompositor<Window>, + cursor: TypedPoint2D<LayerPixel, f32>) + where Window: WindowMethods; fn clamp_scroll_offset_and_scroll_layer(&self, new_offset: TypedPoint2D<LayerPixel, f32>) @@ -131,7 +133,7 @@ pub trait CompositorLayer<Window: WindowMethods> { fn get_pipeline_id(&self) -> PipelineId; } -#[deriving(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone)] pub enum WantsScrollEventsFlag { WantsScrollEvents, DoesntWantScrollEvents, @@ -167,14 +169,14 @@ fn calculate_content_size_for_layer(layer: &Layer<CompositorData>) }).size } -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum ScrollEventResult { ScrollEventUnhandled, ScrollPositionChanged, ScrollPositionUnchanged, } -impl<Window: WindowMethods> CompositorLayer<Window> for Layer<CompositorData> { +impl CompositorLayer for Layer<CompositorData> { fn update_layer_except_bounds(&self, layer_properties: LayerProperties) { self.extra_data.borrow_mut().epoch = layer_properties.epoch; self.extra_data.borrow_mut().scroll_policy = layer_properties.scroll_policy; @@ -199,18 +201,19 @@ impl<Window: WindowMethods> CompositorLayer<Window> for Layer<CompositorData> { // // If the epoch of the message does not match the layer's epoch, the message is ignored, the // layer buffer set is consumed, and None is returned. - fn add_buffers(&self, - compositor: &IOCompositor<Window>, - new_buffers: Box<LayerBufferSet>, - epoch: Epoch) - -> bool { + fn add_buffers<Window>(&self, + compositor: &IOCompositor<Window>, + new_buffers: Box<LayerBufferSet>, + epoch: Epoch) + -> bool + where Window: WindowMethods { if self.extra_data.borrow().epoch != epoch { - debug!("add_buffers: compositor epoch mismatch: {} != {}, id: {}", + debug!("add_buffers: compositor epoch mismatch: {:?} != {:?}, id: {:?}", self.extra_data.borrow().epoch, epoch, self.get_pipeline_id()); let pipeline = compositor.get_pipeline(self.get_pipeline_id()); - let _ = pipeline.paint_chan.send_opt(PaintMsg::UnusedBuffer(new_buffers.buffers)); + let _ = pipeline.paint_chan.send(PaintMsg::UnusedBuffer(new_buffers.buffers)); return false; } @@ -221,13 +224,13 @@ impl<Window: WindowMethods> CompositorLayer<Window> for Layer<CompositorData> { let unused_buffers = self.collect_unused_buffers(); if !unused_buffers.is_empty() { // send back unused buffers let pipeline = compositor.get_pipeline(self.get_pipeline_id()); - let _ = pipeline.paint_chan.send_opt(PaintMsg::UnusedBuffer(unused_buffers)); + let _ = pipeline.paint_chan.send(PaintMsg::UnusedBuffer(unused_buffers)); } return true; } - fn clear(&self, compositor: &IOCompositor<Window>) { + fn clear<Window>(&self, compositor: &IOCompositor<Window>) where Window: WindowMethods { let mut buffers = self.collect_buffers(); if !buffers.is_empty() { @@ -239,13 +242,15 @@ impl<Window: WindowMethods> CompositorLayer<Window> for Layer<CompositorData> { } let pipeline = compositor.get_pipeline(self.get_pipeline_id()); - let _ = pipeline.paint_chan.send_opt(PaintMsg::UnusedBuffer(buffers)); + let _ = pipeline.paint_chan.send(PaintMsg::UnusedBuffer(buffers)); } } /// Destroys tiles for this layer and all descendent layers, sending the buffers back to the /// painter to be destroyed or reused. - fn clear_all_tiles(&self, compositor: &IOCompositor<Window>) { + fn clear_all_tiles<Window>(&self, + compositor: &IOCompositor<Window>) + where Window: WindowMethods { self.clear(compositor); for kid in self.children().iter() { kid.clear_all_tiles(compositor); @@ -325,10 +330,11 @@ impl<Window: WindowMethods> CompositorLayer<Window> for Layer<CompositorData> { } } - fn send_mouse_event(&self, - compositor: &IOCompositor<Window>, - event: MouseWindowEvent, - cursor: TypedPoint2D<LayerPixel, f32>) { + fn send_mouse_event<Window>(&self, + compositor: &IOCompositor<Window>, + event: MouseWindowEvent, + cursor: TypedPoint2D<LayerPixel, f32>) + where Window: WindowMethods { let event_point = cursor.to_untyped(); let message = match event { MouseWindowEvent::Click(button, _) => @@ -341,16 +347,17 @@ impl<Window: WindowMethods> CompositorLayer<Window> for Layer<CompositorData> { let pipeline = compositor.get_pipeline(self.get_pipeline_id()); let ScriptControlChan(ref chan) = pipeline.script_chan; - let _ = chan.send_opt(ConstellationControlMsg::SendEvent(pipeline.id.clone(), message)); + let _ = chan.send(ConstellationControlMsg::SendEvent(pipeline.id.clone(), message)); } - fn send_mouse_move_event(&self, - compositor: &IOCompositor<Window>, - cursor: TypedPoint2D<LayerPixel, f32>) { + fn send_mouse_move_event<Window>(&self, + compositor: &IOCompositor<Window>, + cursor: TypedPoint2D<LayerPixel, f32>) + where Window: WindowMethods { let message = MouseMoveEvent(cursor.to_untyped()); let pipeline = compositor.get_pipeline(self.get_pipeline_id()); let ScriptControlChan(ref chan) = pipeline.script_chan; - let _ = chan.send_opt(ConstellationControlMsg::SendEvent(pipeline.id.clone(), message)); + let _ = chan.send(ConstellationControlMsg::SendEvent(pipeline.id.clone(), message)); } fn scroll_layer_and_all_child_layers(&self, new_offset: TypedPoint2D<LayerPixel, f32>) diff --git a/components/compositing/compositor_task.rs b/components/compositing/compositor_task.rs index 3ff651da281..2fba8bfa0f6 100644 --- a/components/compositing/compositor_task.rs +++ b/components/compositing/compositor_task.rs @@ -26,7 +26,7 @@ use servo_util::cursor::Cursor; use servo_util::geometry::PagePx; use servo_util::memory::MemoryProfilerChan; use servo_util::time::TimeProfilerChan; -use std::comm::{channel, Sender, Receiver}; +use std::sync::mpsc::{channel, Sender, Receiver}; use std::fmt::{Error, Formatter, Show}; use std::rc::Rc; @@ -42,7 +42,7 @@ pub trait CompositorProxy : 'static + Send { /// The port that the compositor receives messages on. As above, this is a trait supplied by the /// Servo port. -pub trait CompositorReceiver for Sized? : 'static { +pub trait CompositorReceiver : 'static { /// Receives the next message inbound for the compositor. This must not block. fn try_recv_compositor_msg(&mut self) -> Option<Msg>; /// Synchronously waits for, and returns, the next message inbound for the compositor. @@ -58,7 +58,7 @@ impl CompositorReceiver for Receiver<Msg> { } } fn recv_compositor_msg(&mut self) -> Msg { - self.recv() + self.recv().unwrap() } } @@ -79,7 +79,7 @@ impl ScriptListener for Box<CompositorProxy+'static+Send> { fn close(&mut self) { let (chan, port) = channel(); self.send(Msg::Exit(chan)); - port.recv(); + port.recv().unwrap(); } fn dup(&mut self) -> Box<ScriptListener+'static> { @@ -98,7 +98,7 @@ impl ScriptListener for Box<CompositorProxy+'static+Send> { } /// Information about each layer that the compositor keeps. -#[deriving(Copy)] +#[derive(Copy)] pub struct LayerProperties { pub pipeline_id: PipelineId, pub epoch: Epoch, @@ -129,7 +129,7 @@ impl PaintListener for Box<CompositorProxy+'static+Send> { fn get_graphics_metadata(&mut self) -> Option<NativeGraphicsMetadata> { let (chan, port) = channel(); self.send(Msg::GetGraphicsMetadata(chan)); - port.recv() + port.recv().unwrap() } fn assign_painted_buffers(&mut self, diff --git a/components/compositing/constellation.rs b/components/compositing/constellation.rs index 2aa1b9688ee..981fde200ce 100644 --- a/components/compositing/constellation.rs +++ b/components/compositing/constellation.rs @@ -17,7 +17,7 @@ use libc; use script_traits::{CompositorEvent, ConstellationControlMsg}; use script_traits::{ScriptControlChan, ScriptTaskFactory}; use servo_msg::compositor_msg::LayerId; -use servo_msg::constellation_msg::{mod, ConstellationChan, Failure}; +use servo_msg::constellation_msg::{self, ConstellationChan, Failure}; use servo_msg::constellation_msg::{IFrameSandboxState, NavigationDirection}; use servo_msg::constellation_msg::{Key, KeyState, KeyModifiers}; use servo_msg::constellation_msg::{LoadData, NavigationType}; @@ -39,6 +39,7 @@ use std::collections::{HashMap, HashSet}; use std::io; use std::mem::replace; use std::rc::Rc; +use std::sync::mpsc::{Receiver, channel}; use url::Url; /// Maintains the pipelines and navigation context and grants permission to composite. @@ -91,7 +92,7 @@ pub struct Constellation<LTF, STF> { } /// A unique ID used to identify a frame. -#[deriving(Copy)] +#[derive(Copy)] pub struct FrameId(u32); /// One frame in the hierarchy. @@ -125,7 +126,7 @@ impl FrameTree { } } -#[deriving(Clone)] +#[derive(Clone)] struct ChildFrameTree { frame_tree: Rc<FrameTree>, /// Clipping rect representing the size and position, in page coordinates, of the visible @@ -234,7 +235,8 @@ struct FrameTreeIterator { stack: Vec<Rc<FrameTree>>, } -impl Iterator<Rc<FrameTree>> for FrameTreeIterator { +impl Iterator for FrameTreeIterator { + type Item = Rc<FrameTree>; fn next(&mut self) -> Option<Rc<FrameTree>> { match self.stack.pop() { Some(next) => { @@ -294,7 +296,7 @@ impl NavigationContext { /// Loads a new set of page frames, returning all evicted frame trees fn load(&mut self, frame_tree: Rc<FrameTree>, compositor_proxy: &mut CompositorProxy) -> Vec<Rc<FrameTree>> { - debug!("navigating to {}", frame_tree.pipeline.borrow().id); + debug!("navigating to {:?}", frame_tree.pipeline.borrow().id); let evicted = replace(&mut self.next, vec!()); match self.current.take() { Some(current) => self.previous.push(current), @@ -350,7 +352,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { -> ConstellationChan { let (constellation_port, constellation_chan) = ConstellationChan::new(); let constellation_chan_clone = constellation_chan.clone(); - spawn_named("Constellation".to_owned(), proc() { + spawn_named("Constellation".to_owned(), move || { let mut constellation: Constellation<LTF, STF> = Constellation { chan: constellation_chan_clone, request_port: constellation_port, @@ -380,7 +382,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { fn run(&mut self) { loop { - let request = self.request_port.recv(); + let request = self.request_port.recv().unwrap(); if !self.handle_request(request) { break; } @@ -517,17 +519,17 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { pipeline.exit(PipelineExitType::Complete); } self.image_cache_task.exit(); - self.resource_task.send(resource_task::ControlMsg::Exit); + self.resource_task.send(resource_task::ControlMsg::Exit).unwrap(); self.devtools_chan.as_ref().map(|chan| { - chan.send(devtools_traits::ServerExitMsg); + chan.send(devtools_traits::ServerExitMsg).unwrap(); }); - self.storage_task.send(StorageTaskMsg::Exit); + self.storage_task.send(StorageTaskMsg::Exit).unwrap(); self.font_cache_task.exit(); self.compositor_proxy.send(CompositorMsg::ShutdownComplete); } fn handle_failure_msg(&mut self, pipeline_id: PipelineId, subpage_id: Option<SubpageId>) { - debug!("handling failure message from pipeline {}, {}", pipeline_id, subpage_id); + debug!("handling failure message from pipeline {:?}, {:?}", pipeline_id, subpage_id); if opts::get().hard_fail { // It's quite difficult to make Servo exit cleanly if some tasks have failed. @@ -604,11 +606,11 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { fn handle_frame_rect_msg(&mut self, pipeline_id: PipelineId, subpage_id: SubpageId, rect: TypedRect<PagePx, f32>) { - debug!("Received frame rect {} from {}, {}", rect, pipeline_id, subpage_id); + debug!("Received frame rect {:?} from {:?}, {:?}", rect, pipeline_id, subpage_id); let mut already_sent = HashSet::new(); // Returns true if a child frame tree's subpage id matches the given subpage id - let subpage_eq = |child_frame_tree: & &mut ChildFrameTree| { + let subpage_eq = |&:child_frame_tree: & &mut ChildFrameTree| { child_frame_tree.frame_tree.pipeline.borrow(). subpage_id.expect("Constellation: child frame does not have a subpage id. This should not be possible.") @@ -679,7 +681,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { visible_viewport: rect.size, initial_viewport: rect.size * ScaleFactor(1.0), device_pixel_ratio: device_pixel_ratio, - })); + })).unwrap(); compositor_proxy.send(CompositorMsg::SetLayerOrigin( pipeline.id, LayerId::null(), @@ -697,7 +699,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { old_subpage_id: SubpageId) { let existing_tree = match frame_tree.find_with_subpage_id(Some(old_subpage_id)) { Some(existing_tree) => existing_tree.clone(), - None => panic!("Tried to update non-existing frame tree with pipeline={} subpage={}", + None => panic!("Tried to update non-existing frame tree with pipeline={:?} subpage={:?}", new_pipeline.id, old_subpage_id), }; @@ -716,7 +718,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { old_pipeline.to_sendable(), new_pipeline.to_sendable(), chan)); - let _ = port.recv_opt(); + let _ = port.recv(); } fn create_or_update_child_pipeline(&mut self, @@ -770,10 +772,10 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { // FIXME(tkuehn): Need to follow the standardized spec for checking same-origin // Reuse the script task if the URL is same-origin let script_pipeline = if same_script { - debug!("Constellation: loading same-origin iframe at {}", url); + debug!("Constellation: loading same-origin iframe at {:?}", url); Some(source_pipeline.clone()) } else { - debug!("Constellation: loading cross-origin iframe at {}", url); + debug!("Constellation: loading cross-origin iframe at {:?}", url); None }; @@ -801,7 +803,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { fn handle_load_url_msg(&mut self, source_id: PipelineId, load_data: LoadData) { let url = load_data.url.to_string(); - debug!("Constellation: received message to load {}", url); + debug!("Constellation: received message to load {:?}", url); // Make sure no pending page would be overridden. let source_frame = self.current_frame().as_ref().unwrap().find(source_id).expect( "Constellation: received a LoadUrl message from a pipeline_id associated @@ -837,7 +839,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { } fn handle_navigate_msg(&mut self, direction: constellation_msg::NavigationDirection) { - debug!("received message to navigate {}", direction); + debug!("received message to navigate {:?}", direction); // TODO(tkuehn): what is the "critical point" beyond which pending frames // should not be cleared? Currently, the behavior is that forward/back @@ -886,7 +888,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { self.current_frame().as_ref().map(|frame| { let ScriptControlChan(ref chan) = frame.pipeline.borrow().script_chan; chan.send(ConstellationControlMsg::SendEvent( - frame.pipeline.borrow().id, CompositorEvent::KeyEvent(key, state, mods))); + frame.pipeline.borrow().id, CompositorEvent::KeyEvent(key, state, mods))).unwrap(); }); } @@ -895,13 +897,13 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { None => self.compositor_proxy.send(CompositorMsg::ChangePageTitle(pipeline_id, None)), Some(pipeline) => { let ScriptControlChan(ref script_channel) = pipeline.script_chan; - script_channel.send(ConstellationControlMsg::GetTitle(pipeline_id)); + script_channel.send(ConstellationControlMsg::GetTitle(pipeline_id)).unwrap(); } } } fn handle_painter_ready_msg(&mut self, pipeline_id: PipelineId) { - debug!("Painter {} ready to send paint msg", pipeline_id); + debug!("Painter {:?} ready to send paint msg", pipeline_id); // This message could originate from a pipeline in the navigation context or // from a pending frame. The only time that we will grant paint permission is // when the message originates from a pending frame or the current frame. @@ -921,7 +923,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { }); match pending_index { Some(pending_index) => { - let frame_change = self.pending_frames.swap_remove(pending_index).unwrap(); + let frame_change = self.pending_frames.swap_remove(pending_index); let to_add = frame_change.after.clone(); // Create the next frame tree that will be given to the compositor @@ -935,7 +937,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { // If there are frames to revoke permission from, do so now. match frame_change.before { Some(revoke_id) if self.current_frame().is_some() => { - debug!("Constellation: revoking permission from {}", revoke_id); + debug!("Constellation: revoking permission from {:?}", revoke_id); let current_frame = self.current_frame().as_ref().unwrap(); let to_revoke = current_frame.find(revoke_id).expect( @@ -952,7 +954,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { let mut flag = false; { if to_add.parent.borrow().is_some() { - debug!("Constellation: replacing {} with {} in {}", + debug!("Constellation: replacing {:?} with {:?} in {:?}", revoke_id, to_add.pipeline.borrow().id, next_frame_tree.pipeline.borrow().id); flag = true; @@ -994,7 +996,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { debug!("constellation sending resize message to active frame"); let pipeline = &*frame_tree.pipeline.borrow();; let ScriptControlChan(ref chan) = pipeline.script_chan; - let _ = chan.send_opt(ConstellationControlMsg::Resize(pipeline.id, new_size)); + let _ = chan.send(ConstellationControlMsg::Resize(pipeline.id, new_size)); already_seen.insert(pipeline.id); } for frame_tree in self.navigation_context.previous.iter() @@ -1003,7 +1005,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { if !already_seen.contains(&pipeline.id) { debug!("constellation sending resize message to inactive frame"); let ScriptControlChan(ref chan) = pipeline.script_chan; - let _ = chan.send_opt(ConstellationControlMsg::ResizeInactive(pipeline.id, new_size)); + let _ = chan.send(ConstellationControlMsg::ResizeInactive(pipeline.id, new_size)); already_seen.insert(pipeline.id); } } @@ -1013,10 +1015,10 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { for change in self.pending_frames.iter() { let frame_tree = &change.after; if frame_tree.parent.borrow().is_none() { - debug!("constellation sending resize message to pending outer frame ({})", + debug!("constellation sending resize message to pending outer frame ({:?})", frame_tree.pipeline.borrow().id); let ScriptControlChan(ref chan) = frame_tree.pipeline.borrow().script_chan; - let _ = chan.send_opt(ConstellationControlMsg::Resize( + let _ = chan.send(ConstellationControlMsg::Resize( frame_tree.pipeline.borrow().id, new_size)); } } @@ -1071,7 +1073,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { self.compositor_proxy.send(CompositorMsg::SetFrameTree(frame_tree.to_sendable(), chan, self.chan.clone())); - if port.recv_opt().is_err() { + if port.recv().is_err() { debug!("Compositor has discarded SetFrameTree"); return; // Our message has been discarded, probably shutting down. } @@ -1126,12 +1128,12 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { child.frame_tree.pipeline.borrow().to_sendable(), child.rect, chan)); - match port.recv_opt() { + match port.recv() { Ok(()) => { child.frame_tree.has_compositor_layer.set(true); child.frame_tree.pipeline.borrow().grant_paint_permission(); } - Err(()) => {} // The message has been discarded, we are probably shutting down. + Err(_) => {} // The message has been discarded, we are probably shutting down. } } } diff --git a/components/compositing/headless.rs b/components/compositing/headless.rs index 86188636260..4fdfe094806 100644 --- a/components/compositing/headless.rs +++ b/components/compositing/headless.rs @@ -60,7 +60,7 @@ impl NullCompositor { initial_viewport: TypedSize2D(640_f32, 480_f32), visible_viewport: TypedSize2D(640_f32, 480_f32), device_pixel_ratio: ScaleFactor(1.0), - })); + })).unwrap(); } compositor @@ -73,8 +73,8 @@ impl CompositorEventListener for NullCompositor { Msg::Exit(chan) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; - con_chan.send(ConstellationMsg::Exit); - chan.send(()); + con_chan.send(ConstellationMsg::Exit).unwrap(); + chan.send(()).unwrap(); } Msg::ShutdownComplete => { @@ -83,19 +83,19 @@ impl CompositorEventListener for NullCompositor { } Msg::GetGraphicsMetadata(chan) => { - chan.send(None); + chan.send(None).unwrap(); } Msg::SetFrameTree(_, response_chan, _) => { - response_chan.send(()); + response_chan.send(()).unwrap(); } Msg::ChangeLayerPipelineAndRemoveChildren(_, _, response_channel) => { - response_channel.send(()); + response_channel.send(()).unwrap(); } Msg::CreateRootLayerForPipeline(_, _, _, response_channel) => { - response_channel.send(()); + response_channel.send(()).unwrap(); } // Explicitly list ignored messages so that when we add a new one, diff --git a/components/compositing/lib.rs b/components/compositing/lib.rs index fee2fbf1671..ff9a0ebcf1a 100644 --- a/components/compositing/lib.rs +++ b/components/compositing/lib.rs @@ -2,13 +2,15 @@ * 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/. */ -#![feature(globs, phase, macro_rules)] +#![feature(box_syntax, plugin)] +#![feature(int_uint)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] +#![allow(unstable)] -#[phase(plugin, link)] +#[macro_use] extern crate log; extern crate azure; @@ -21,7 +23,7 @@ extern crate png; extern crate script_traits; extern crate "msg" as servo_msg; extern crate "net" as servo_net; -#[phase(plugin, link)] +#[macro_use] extern crate "util" as servo_util; extern crate gleam; diff --git a/components/compositing/pipeline.rs b/components/compositing/pipeline.rs index c8a054d16ef..a1dd6b3c24b 100644 --- a/components/compositing/pipeline.rs +++ b/components/compositing/pipeline.rs @@ -18,6 +18,7 @@ use servo_net::resource_task::ResourceTask; use servo_net::storage_task::StorageTask; use servo_util::time::TimeProfilerChan; use std::rc::Rc; +use std::sync::mpsc::{Receiver, channel}; /// A uniquely-identifiable pipeline of script task, layout task, and paint task. pub struct Pipeline { @@ -35,7 +36,7 @@ pub struct Pipeline { } /// The subset of the pipeline that is needed for layer composition. -#[deriving(Clone)] +#[derive(Clone)] pub struct CompositionPipeline { pub id: PipelineId, pub script_chan: ScriptControlChan, @@ -99,7 +100,7 @@ impl Pipeline { }; let ScriptControlChan(ref chan) = spipe.script_chan; - chan.send(ConstellationControlMsg::AttachLayout(new_layout_info)); + chan.send(ConstellationControlMsg::AttachLayout(new_layout_info)).unwrap(); spipe.script_chan.clone() } }; @@ -161,41 +162,42 @@ impl Pipeline { pub fn load(&self) { let ScriptControlChan(ref chan) = self.script_chan; - chan.send(ConstellationControlMsg::Load(self.id, self.load_data.clone())); + chan.send(ConstellationControlMsg::Load(self.id, self.load_data.clone())).unwrap(); } pub fn grant_paint_permission(&self) { - let _ = self.paint_chan.send_opt(PaintMsg::PaintPermissionGranted); + let _ = self.paint_chan.send(PaintMsg::PaintPermissionGranted); } pub fn revoke_paint_permission(&self) { debug!("pipeline revoking paint channel paint permission"); - let _ = self.paint_chan.send_opt(PaintMsg::PaintPermissionRevoked); + let _ = self.paint_chan.send(PaintMsg::PaintPermissionRevoked); } pub fn exit(&self, exit_type: PipelineExitType) { - debug!("pipeline {} exiting", self.id); + debug!("pipeline {:?} exiting", self.id); // Script task handles shutting down layout, and layout handles shutting down the painter. // For now, if the script task has failed, we give up on clean shutdown. let ScriptControlChan(ref chan) = self.script_chan; - if chan.send_opt(ConstellationControlMsg::ExitPipeline(self.id, exit_type)).is_ok() { + if chan.send(ConstellationControlMsg::ExitPipeline(self.id, exit_type)).is_ok() { // Wait until all slave tasks have terminated and run destructors // NOTE: We don't wait for script task as we don't always own it - let _ = self.paint_shutdown_port.recv_opt(); - let _ = self.layout_shutdown_port.recv_opt(); + let _ = self.paint_shutdown_port.recv(); + let _ = self.layout_shutdown_port.recv(); } } pub fn force_exit(&self) { let ScriptControlChan(ref script_channel) = self.script_chan; - let _ = script_channel.send_opt( + let _ = script_channel.send( ConstellationControlMsg::ExitPipeline(self.id, - PipelineExitType::PipelineOnly)); - let _ = self.paint_chan.send_opt(PaintMsg::Exit(None, PipelineExitType::PipelineOnly)); + PipelineExitType::PipelineOnly)).unwrap(); + let _ = self.paint_chan.send(PaintMsg::Exit(None, PipelineExitType::PipelineOnly)); let LayoutControlChan(ref layout_channel) = self.layout_chan; - let _ = layout_channel.send_opt(LayoutControlMsg::ExitNowMsg(PipelineExitType::PipelineOnly)); + let _ = layout_channel.send( + LayoutControlMsg::ExitNowMsg(PipelineExitType::PipelineOnly)).unwrap(); } pub fn to_sendable(&self) -> CompositionPipeline { diff --git a/components/compositing/scrolling.rs b/components/compositing/scrolling.rs index 8649ac1d9a4..24b57f90449 100644 --- a/components/compositing/scrolling.rs +++ b/components/compositing/scrolling.rs @@ -7,7 +7,8 @@ use compositor_task::{CompositorProxy, Msg}; use std::io::timer; -use std::task::TaskBuilder; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::thread::Builder; use std::time::duration::Duration; use time; @@ -33,7 +34,7 @@ enum ToScrollingTimerMsg { impl ScrollingTimerProxy { pub fn new(compositor_proxy: Box<CompositorProxy+Send>) -> ScrollingTimerProxy { let (to_scrolling_timer_sender, to_scrolling_timer_receiver) = channel(); - TaskBuilder::new().spawn(proc() { + Builder::new().spawn(move || { let mut scrolling_timer = ScrollingTimer { compositor_proxy: compositor_proxy, receiver: to_scrolling_timer_receiver, @@ -46,18 +47,18 @@ impl ScrollingTimerProxy { } pub fn scroll_event_processed(&mut self, timestamp: u64) { - self.sender.send(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) + self.sender.send(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)).unwrap() } pub fn shutdown(&mut self) { - self.sender.send(ToScrollingTimerMsg::ExitMsg); + self.sender.send(ToScrollingTimerMsg::ExitMsg).unwrap() } } impl ScrollingTimer { pub fn run(&mut self) { loop { - match self.receiver.recv_opt() { + match self.receiver.recv() { Ok(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) => { let target = timestamp as i64 + TIMEOUT; let delta = target - (time::precise_time_ns() as i64); diff --git a/components/compositing/windowing.rs b/components/compositing/windowing.rs index eae46c2d5fb..50b0a0ae64a 100644 --- a/components/compositing/windowing.rs +++ b/components/compositing/windowing.rs @@ -18,21 +18,21 @@ use servo_util::geometry::ScreenPx; use std::fmt::{Error, Formatter, Show}; use std::rc::Rc; -#[deriving(Clone)] +#[derive(Clone)] pub enum MouseWindowEvent { Click(uint, TypedPoint2D<DevicePixel, f32>), MouseDown(uint, TypedPoint2D<DevicePixel, f32>), MouseUp(uint, TypedPoint2D<DevicePixel, f32>), } -#[deriving(Clone)] +#[derive(Clone)] pub enum WindowNavigateMsg { Forward, Back, } /// Events that the windowing system sends to Servo. -#[deriving(Clone)] +#[derive(Clone)] pub enum WindowEvent { /// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps /// by another Servo subsystem). @@ -48,7 +48,7 @@ pub enum WindowEvent { /// context when this message is sent. InitializeCompositing, /// Sent when the window is resized. - Resize(TypedSize2D<DevicePixel, uint>), + Resize(TypedSize2D<DevicePixel, u32>), /// Sent when a new URL is to be loaded. LoadUrl(String), /// Sent when a mouse hit test is to be performed. @@ -92,7 +92,7 @@ impl Show for WindowEvent { pub trait WindowMethods { /// Returns the size of the window in hardware pixels. - fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint>; + fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, u32>; /// Returns the size of the window in density-independent "px" units. fn size(&self) -> TypedSize2D<ScreenPx, f32>; /// Presents the window to the screen (perhaps by page flipping). diff --git a/components/devtools/actor.rs b/components/devtools/actor.rs index 87c3d45f139..2b4f408cd45 100644 --- a/components/devtools/actor.rs +++ b/components/devtools/actor.rs @@ -4,13 +4,11 @@ /// General actor system infrastructure. -use std::any::{Any, AnyRefExt, AnyMutRefExt}; +use std::any::Any; use std::collections::HashMap; use std::cell::{Cell, RefCell}; -use std::intrinsics::TypeId; use std::io::TcpStream; -use std::mem::{transmute, transmute_copy, replace}; -use std::raw::TraitObject; +use std::mem::replace; use serialize::json; /// A common trait for all devtools actors that encompasses an immutable name @@ -25,46 +23,6 @@ pub trait Actor : Any { fn name(&self) -> String; } -impl<'a> AnyMutRefExt<'a> for &'a mut (Actor + 'a) { - fn downcast_mut<T: 'static>(self) -> Option<&'a mut T> { - if self.is::<T>() { - unsafe { - // Get the raw representation of the trait object - let to: TraitObject = transmute_copy(&self); - - // Extract the data pointer - Some(transmute(to.data)) - } - } else { - None - } - } -} - -impl<'a> AnyRefExt<'a> for &'a (Actor + 'a) { - fn is<T: 'static>(self) -> bool { - // This implementation is only needed so long as there's a Rust bug that - // prevents downcast_ref from giving realistic return values. - let t = TypeId::of::<T>(); - let boxed: TypeId = (*self).get_type_id(); - t == boxed - } - - fn downcast_ref<T: 'static>(self) -> Option<&'a T> { - if self.is::<T>() { - unsafe { - // Get the raw representation of the trait object - let to: TraitObject = transmute_copy(&self); - - // Extract the data pointer - Some(transmute(to.data)) - } - } else { - None - } - } -} - /// A list of known, owned actors. pub struct ActorRegistry { actors: HashMap<String, Box<Actor+Send+Sized>>, @@ -130,20 +88,14 @@ impl ActorRegistry { /// Find an actor by registered name pub fn find<'a, T: 'static>(&'a self, name: &str) -> &'a T { - //FIXME: Rust bug forces us to implement bogus Any for Actor since downcast_ref currently - // fails for unknown reasons. - /*let actor: &Actor+Send+Sized = *self.actors.find(&name.to_string()).unwrap(); - (actor as &Any).downcast_ref::<T>().unwrap()*/ - self.actors.get(&name.to_string()).unwrap().downcast_ref::<T>().unwrap() + let actor: &Any = self.actors.get(&name.to_string()).unwrap(); + actor.downcast_ref::<T>().unwrap() } /// Find an actor by registered name pub fn find_mut<'a, T: 'static>(&'a mut self, name: &str) -> &'a mut T { - //FIXME: Rust bug forces us to implement bogus Any for Actor since downcast_ref currently - // fails for unknown reasons. - /*let actor: &mut Actor+Send+Sized = *self.actors.find_mut(&name.to_string()).unwrap(); - (actor as &mut Any).downcast_mut::<T>().unwrap()*/ - self.actors.get_mut(&name.to_string()).unwrap().downcast_mut::<T>().unwrap() + let actor: &mut Any = self.actors.get_mut(&name.to_string()).unwrap(); + actor.downcast_mut::<T>().unwrap() } /// Attempt to process a message as directed by its `to` property. If the actor is not diff --git a/components/devtools/actors/console.rs b/components/devtools/actors/console.rs index 5628506d5af..d8e88cdba8b 100644 --- a/components/devtools/actors/console.rs +++ b/components/devtools/actors/console.rs @@ -13,18 +13,19 @@ use devtools_traits::{EvaluateJS, NullValue, VoidValue, NumberValue, StringValue use devtools_traits::{ActorValue, DevtoolScriptControlMsg}; use servo_msg::constellation_msg::PipelineId; -use collections::TreeMap; +use collections::BTreeMap; use core::cell::RefCell; use serialize::json::{mod, Json, ToJson}; use std::io::TcpStream; use std::num::Float; +use std::sync::mpsc::{channel, Sender}; -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct StartedListenersTraits { customNetworkRequest: bool, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct StartedListenersReply { from: String, nativeConsoleAPI: bool, @@ -32,13 +33,13 @@ struct StartedListenersReply { traits: StartedListenersTraits, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] #[allow(dead_code)] struct ConsoleAPIMessage { _type: String, //FIXME: should this be __type__ instead? } -#[deriving(Encodable)] +#[derive(RustcEncodable)] #[allow(dead_code)] struct PageErrorMessage { _type: String, //FIXME: should this be __type__ instead? @@ -56,7 +57,7 @@ struct PageErrorMessage { private: bool, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] #[allow(dead_code)] struct LogMessage { _type: String, //FIXME: should this be __type__ instead? @@ -64,7 +65,7 @@ struct LogMessage { message: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] #[allow(dead_code)] enum ConsoleMessageType { ConsoleAPIType(ConsoleAPIMessage), @@ -72,26 +73,26 @@ enum ConsoleMessageType { LogMessageType(LogMessage), } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct GetCachedMessagesReply { from: String, messages: Vec<json::Object>, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct StopListenersReply { from: String, stoppedListeners: Vec<String>, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct AutocompleteReply { from: String, matches: Vec<String>, matchProp: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct EvaluateJSReply { from: String, input: String, @@ -220,28 +221,28 @@ impl Actor for ConsoleActor { "evaluateJS" => { let input = msg.get(&"text".to_string()).unwrap().as_string().unwrap().to_string(); let (chan, port) = channel(); - self.script_chan.send(EvaluateJS(self.pipeline, input.clone(), chan)); + self.script_chan.send(EvaluateJS(self.pipeline, input.clone(), chan)).unwrap(); //TODO: extract conversion into protocol module or some other useful place - let result = match try!(port.recv_opt()) { + let result = match try!(port.recv().map_err(|_| ())) { VoidValue => { - let mut m = TreeMap::new(); + let mut m = BTreeMap::new(); m.insert("type".to_string(), "undefined".to_string().to_json()); Json::Object(m) } NullValue => { - let mut m = TreeMap::new(); + let mut m = BTreeMap::new(); m.insert("type".to_string(), "null".to_string().to_json()); Json::Object(m) } BooleanValue(val) => val.to_json(), NumberValue(val) => { if val.is_nan() { - let mut m = TreeMap::new(); + let mut m = BTreeMap::new(); m.insert("type".to_string(), "NaN".to_string().to_json()); Json::Object(m) } else if val.is_infinite() { - let mut m = TreeMap::new(); + let mut m = BTreeMap::new(); if val < 0. { m.insert("type".to_string(), "-Infinity".to_string().to_json()); } else { @@ -249,7 +250,7 @@ impl Actor for ConsoleActor { } Json::Object(m) } else if val == Float::neg_zero() { - let mut m = TreeMap::new(); + let mut m = BTreeMap::new(); m.insert("type".to_string(), "-0".to_string().to_json()); Json::Object(m) } else { @@ -259,7 +260,7 @@ impl Actor for ConsoleActor { StringValue(s) => s.to_json(), ActorValue(s) => { //TODO: make initial ActorValue message include these properties. - let mut m = TreeMap::new(); + let mut m = BTreeMap::new(); m.insert("type".to_string(), "object".to_string().to_json()); m.insert("class".to_string(), "???".to_string().to_json()); m.insert("actor".to_string(), s.to_json()); @@ -276,9 +277,9 @@ impl Actor for ConsoleActor { input: input, result: result, timestamp: 0, - exception: Json::Object(TreeMap::new()), + exception: Json::Object(BTreeMap::new()), exceptionMessage: "".to_string(), - helperResult: Json::Object(TreeMap::new()), + helperResult: Json::Object(BTreeMap::new()), }; stream.write_json_packet(&msg); true diff --git a/components/devtools/actors/inspector.rs b/components/devtools/actors/inspector.rs index ac3b51cf34f..20611226edc 100644 --- a/components/devtools/actors/inspector.rs +++ b/components/devtools/actors/inspector.rs @@ -10,11 +10,12 @@ use devtools_traits::{GetLayout, NodeInfo, ModifyAttribute}; use actor::{Actor, ActorRegistry}; use protocol::JsonPacketStream; -use collections::TreeMap; +use collections::BTreeMap; use servo_msg::constellation_msg::PipelineId; use serialize::json::{mod, Json, ToJson}; use std::cell::RefCell; use std::io::TcpStream; +use std::sync::mpsc::{channel, Sender}; use std::num::Float; pub struct InspectorActor { @@ -26,13 +27,13 @@ pub struct InspectorActor { pub pipeline: PipelineId, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct GetHighlighterReply { highligter: HighlighterMsg, // sic. from: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct HighlighterMsg { actor: String, } @@ -47,12 +48,12 @@ pub struct NodeActor { pipeline: PipelineId, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ShowBoxModelReply { from: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct HideBoxModelReply { from: String, } @@ -89,7 +90,7 @@ impl Actor for HighlighterActor { } } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ModifyAttributeReply{ from: String, } @@ -114,7 +115,8 @@ impl Actor for NodeActor { self.script_chan.send(ModifyAttribute(self.pipeline, registry.actor_to_script(target.to_string()), - modifications)); + modifications)) + .unwrap(); let reply = ModifyAttributeReply{ from: self.name(), }; @@ -127,26 +129,26 @@ impl Actor for NodeActor { } } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct GetWalkerReply { from: String, walker: WalkerMsg, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct WalkerMsg { actor: String, root: NodeActorMsg, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct AttrMsg { namespace: String, name: String, value: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct NodeActorMsg { actor: String, baseURI: String, @@ -243,23 +245,23 @@ struct WalkerActor { pipeline: PipelineId, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct QuerySelectorReply { from: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct DocumentElementReply { from: String, node: NodeActorMsg, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ClearPseudoclassesReply { from: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ChildrenReply { hasFirst: bool, hasLast: bool, @@ -288,8 +290,8 @@ impl Actor for WalkerActor { "documentElement" => { let (tx, rx) = channel(); - self.script_chan.send(GetDocumentElement(self.pipeline, tx)); - let doc_elem_info = rx.recv(); + self.script_chan.send(GetDocumentElement(self.pipeline, tx)).unwrap(); + let doc_elem_info = rx.recv().unwrap(); let node = doc_elem_info.encode(registry, true, self.script_chan.clone(), self.pipeline); let msg = DocumentElementReply { @@ -313,8 +315,9 @@ impl Actor for WalkerActor { let (tx, rx) = channel(); self.script_chan.send(GetChildren(self.pipeline, registry.actor_to_script(target.to_string()), - tx)); - let children = rx.recv(); + tx)) + .unwrap(); + let children = rx.recv().unwrap(); let msg = ChildrenReply { hasFirst: true, @@ -333,13 +336,13 @@ impl Actor for WalkerActor { } } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct GetPageStyleReply { from: String, pageStyle: PageStyleMsg, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct PageStyleMsg { actor: String, } @@ -350,7 +353,7 @@ struct PageStyleActor { pipeline: PipelineId, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct GetAppliedReply { entries: Vec<AppliedEntry>, rules: Vec<AppliedRule>, @@ -358,13 +361,13 @@ struct GetAppliedReply { from: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct GetComputedReply { computed: Vec<uint>, //XXX all css props from: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct AppliedEntry { rule: String, pseudoElement: Json, @@ -372,7 +375,7 @@ struct AppliedEntry { matchedSelectors: Vec<String>, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct AppliedRule { actor: String, __type__: uint, @@ -383,7 +386,7 @@ struct AppliedRule { parentStyleSheet: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct AppliedSheet { actor: String, href: String, @@ -395,7 +398,7 @@ struct AppliedSheet { ruleCount: uint, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct GetLayoutReply { width: int, height: int, @@ -403,7 +406,7 @@ struct GetLayoutReply { from: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] #[allow(dead_code)] struct AutoMargins { top: String, @@ -450,9 +453,10 @@ impl Actor for PageStyleActor { let target = msg.get(&"node".to_string()).unwrap().as_string().unwrap(); let (tx, rx) = channel(); self.script_chan.send(GetLayout(self.pipeline, - registry.actor_to_script(target.to_string()), - tx)); - let (width, height) = rx.recv(); + registry.actor_to_script(target.to_string()), + tx)) + .unwrap(); + let (width, height) = rx.recv().unwrap(); let auto_margins = msg.get(&"autoMargins".to_string()).unwrap().as_boolean().unwrap(); @@ -463,7 +467,7 @@ impl Actor for PageStyleActor { height: height.round() as int, autoMargins: if auto_margins { //TODO: real values like processMargins in http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/styles.js - let mut m = TreeMap::new(); + let mut m = BTreeMap::new(); m.insert("top".to_string(), "auto".to_string().to_json()); m.insert("bottom".to_string(), "auto".to_string().to_json()); m.insert("left".to_string(), "auto".to_string().to_json()); @@ -507,8 +511,8 @@ impl Actor for InspectorActor { } let (tx, rx) = channel(); - self.script_chan.send(GetRootNode(self.pipeline, tx)); - let root_info = rx.recv(); + self.script_chan.send(GetRootNode(self.pipeline, tx)).unwrap(); + let root_info = rx.recv().unwrap(); let node = root_info.encode(registry, false, self.script_chan.clone(), self.pipeline); diff --git a/components/devtools/actors/root.rs b/components/devtools/actors/root.rs index da0e33d7c7d..cd9084c0282 100644 --- a/components/devtools/actors/root.rs +++ b/components/devtools/actors/root.rs @@ -13,28 +13,28 @@ use protocol::JsonPacketStream; use serialize::json; use std::io::TcpStream; -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ActorTraits { sources: bool, highlightable: bool, customHighlighters: Vec<String>, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ErrorReply { from: String, error: String, message: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ListTabsReply { from: String, selected: uint, tabs: Vec<TabActorMsg>, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct RootActorMsg { from: String, applicationType: String, diff --git a/components/devtools/actors/tab.rs b/components/devtools/actors/tab.rs index 519e3e48128..69450cd4b32 100644 --- a/components/devtools/actors/tab.rs +++ b/components/devtools/actors/tab.rs @@ -13,10 +13,10 @@ use protocol::JsonPacketStream; use serialize::json; use std::io::TcpStream; -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct TabTraits; -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct TabAttachedReply { from: String, __type__: String, @@ -26,24 +26,24 @@ struct TabAttachedReply { traits: TabTraits, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct TabDetachedReply { from: String, __type__: String, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ReconfigureReply { from: String } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ListFramesReply { from: String, frames: Vec<FrameMsg>, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct FrameMsg { id: uint, url: String, @@ -51,7 +51,7 @@ struct FrameMsg { parentID: uint, } -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct TabActorMsg { actor: String, title: String, diff --git a/components/devtools/lib.rs b/components/devtools/lib.rs index fd4b57aa0d6..f653dd289ce 100644 --- a/components/devtools/lib.rs +++ b/components/devtools/lib.rs @@ -10,17 +10,19 @@ #![crate_name = "devtools"] #![crate_type = "rlib"] +#![feature(int_uint, box_syntax)] + #![allow(non_snake_case)] #![allow(missing_copy_implementations)] +#![allow(unstable)] -#![feature(phase)] - -#[phase(plugin, link)] +#[macro_use] extern crate log; extern crate collections; extern crate core; extern crate devtools_traits; +extern crate "serialize" as rustc_serialize; extern crate serialize; extern crate "msg" as servo_msg; extern crate "util" as servo_util; @@ -39,8 +41,8 @@ use servo_util::task::spawn_named; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; -use std::comm; -use std::comm::{Disconnected, Empty}; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::mpsc::TryRecvError::{Disconnected, Empty}; use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener, TimedOut}; use std::sync::{Arc, Mutex}; @@ -57,8 +59,8 @@ mod protocol; /// Spin up a devtools server that listens for connections on the specified port. pub fn start_server(port: u16) -> Sender<DevtoolsControlMsg> { - let (sender, receiver) = comm::channel(); - spawn_named("Devtools".to_owned(), proc() { + let (sender, receiver) = channel(); + spawn_named("Devtools".to_owned(), move || { run_server(receiver, port) }); sender @@ -92,7 +94,7 @@ fn run_server(receiver: Receiver<DevtoolsControlMsg>, port: u16) { fn handle_client(actors: Arc<Mutex<ActorRegistry>>, mut stream: TcpStream) { println!("connection established to {}", stream.peer_name().unwrap()); { - let actors = actors.lock(); + let actors = actors.lock().unwrap(); let msg = actors.find::<RootActor>("root").encodable(); stream.write_json_packet(&msg); } @@ -100,8 +102,9 @@ fn run_server(receiver: Receiver<DevtoolsControlMsg>, port: u16) { 'outer: loop { match stream.read_json_packet() { Ok(json_packet) => { - match actors.lock().handle_message(json_packet.as_object().unwrap(), - &mut stream) { + let mut actors = actors.lock().unwrap(); + match actors.handle_message(json_packet.as_object().unwrap(), + &mut stream) { Ok(()) => {}, Err(()) => { println!("error: devtools actor stopped responding"); @@ -127,7 +130,7 @@ fn run_server(receiver: Receiver<DevtoolsControlMsg>, port: u16) { sender: Sender<DevtoolScriptControlMsg>, actor_pipelines: &mut HashMap<PipelineId, String>, page_info: DevtoolsPageInfo) { - let mut actors = actors.lock(); + let mut actors = actors.lock().unwrap(); //TODO: move all this actor creation into a constructor method on TabActor let (tab, console, inspector) = { @@ -185,7 +188,7 @@ fn run_server(receiver: Receiver<DevtoolsControlMsg>, port: u16) { Ok(stream) => { let actors = actors.clone(); accepted_connections.push(stream.clone()); - spawn_named("DevtoolsClientHandler".to_owned(), proc() { + spawn_named("DevtoolsClientHandler".to_owned(), move || { // connection succeeded handle_client(actors, stream.clone()) }) diff --git a/components/devtools/protocol.rs b/components/devtools/protocol.rs index df9078c7bf1..149c3a301d2 100644 --- a/components/devtools/protocol.rs +++ b/components/devtools/protocol.rs @@ -12,12 +12,12 @@ use std::io::{IoError, OtherIoError, EndOfFile, TcpStream, IoResult}; use std::num; pub trait JsonPacketStream { - fn write_json_packet<'a, T: Encodable<json::Encoder<'a>,IoError>>(&mut self, obj: &T); + fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T); fn read_json_packet(&mut self) -> IoResult<Json>; } impl JsonPacketStream for TcpStream { - fn write_json_packet<'a, T: Encodable<json::Encoder<'a>,IoError>>(&mut self, obj: &T) { + fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T) { let s = json::encode(obj).replace("__type__", "type"); println!("<- {}", s); self.write_str(s.len().to_string().as_slice()).unwrap(); diff --git a/components/devtools_traits/lib.rs b/components/devtools_traits/lib.rs index 158a01272f6..14c6c59b56c 100644 --- a/components/devtools_traits/lib.rs +++ b/components/devtools_traits/lib.rs @@ -9,9 +9,10 @@ #![crate_name = "devtools_traits"] #![crate_type = "rlib"] +#![feature(int_uint)] + #![allow(non_snake_case)] #![allow(missing_copy_implementations)] -#![feature(globs)] extern crate "msg" as servo_msg; extern crate serialize; @@ -27,6 +28,8 @@ use servo_msg::constellation_msg::PipelineId; use servo_util::str::DOMString; use url::Url; +use std::sync::mpsc::{Sender, Receiver}; + pub type DevtoolsControlChan = Sender<DevtoolsControlMsg>; pub type DevtoolsControlPort = Receiver<DevtoolScriptControlMsg>; @@ -99,14 +102,14 @@ pub enum ScriptDevtoolControlMsg { ReportConsoleMsg(String), } -#[deriving(Encodable)] +#[derive(Encodable)] pub struct Modification{ pub attributeName: String, pub newValue: Option<String>, } -impl<D:Decoder<E>, E> Decodable<D, E> for Modification { - fn decode(d: &mut D) -> Result<Modification, E> { +impl Decodable for Modification { + fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> { d.read_struct("Modification", 2u, |d| Ok(Modification { attributeName: try!(d.read_struct_field("attributeName", 0u, |d| Decodable::decode(d))), diff --git a/components/gfx/Cargo.toml b/components/gfx/Cargo.toml index dbdd1246897..a0d0c47670f 100644 --- a/components/gfx/Cargo.toml +++ b/components/gfx/Cargo.toml @@ -38,9 +38,6 @@ git = "https://github.com/servo/rust-stb-image" [dependencies.png] git = "https://github.com/servo/rust-png" -[dependencies.url] -git = "https://github.com/servo/rust-url" - [dependencies.harfbuzz] git = "https://github.com/servo/rust-harfbuzz" @@ -62,5 +59,6 @@ git = "https://github.com/servo/rust-core-text" [dependencies.script_traits] path = "../script_traits" -[dependencies.time] -git = "https://github.com/rust-lang/time" +[dependencies] +url = "*" +time = "*"
\ No newline at end of file diff --git a/components/gfx/buffer_map.rs b/components/gfx/buffer_map.rs index 9c1197ec8b2..c33617a7c9e 100644 --- a/components/gfx/buffer_map.rs +++ b/components/gfx/buffer_map.rs @@ -3,12 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::HashMap; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; use layers::platform::surface::NativePaintingGraphicsContext; use layers::layers::LayerBuffer; -use std::hash::Hash; -use std::hash::sip::SipState; +use std::hash::{Hash, Hasher, Writer}; use std::mem; /// This is a struct used to store buffers when they are not in use. @@ -27,11 +26,11 @@ pub struct BufferMap { } /// A key with which to store buffers. It is based on the size of the buffer. -#[deriving(Eq, Copy)] -struct BufferKey([uint, ..2]); +#[derive(Eq, Copy)] +struct BufferKey([uint; 2]); -impl Hash for BufferKey { - fn hash(&self, state: &mut SipState) { +impl<H: Hasher+Writer> Hash<H> for BufferKey { + fn hash(&self, state: &mut H) { let BufferKey(ref bytes) = *self; bytes.as_slice().hash(state); } @@ -91,7 +90,7 @@ impl BufferMap { entry.into_mut().buffers.push(new_buffer); } Vacant(entry) => { - entry.set(BufferValue { + entry.insert(BufferValue { buffers: vec!(new_buffer), last_action: *counter, }); diff --git a/components/gfx/display_list/mod.rs b/components/gfx/display_list/mod.rs index 6ede4546b6b..7bd8187728e 100644 --- a/components/gfx/display_list/mod.rs +++ b/components/gfx/display_list/mod.rs @@ -38,7 +38,7 @@ use servo_util::geometry::{mod, Au, MAX_RECT, ZERO_RECT}; use servo_util::range::Range; use servo_util::smallvec::{SmallVec, SmallVec8}; use std::fmt; -use std::slice::Items; +use std::slice::Iter; use std::sync::Arc; use style::ComputedValues; use style::computed_values::{border_style, cursor, filter, mix_blend_mode, pointer_events}; @@ -60,7 +60,7 @@ pub static BOX_SHADOW_INFLATION_FACTOR: i32 = 3; /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// locality reasons. Using `OpaqueNode` enforces this invariant. -#[deriving(Clone, PartialEq, Copy)] +#[derive(Clone, PartialEq, Copy)] pub struct OpaqueNode(pub uintptr_t); impl OpaqueNode { @@ -356,7 +356,7 @@ impl StackingContext { result: &mut Vec<DisplayItemMetadata>, topmost_only: bool, mut iterator: I) - where I: Iterator<&'a DisplayItem> { + where I: Iterator<Item=&'a DisplayItem> { for item in iterator { // TODO(pcwalton): Use a precise algorithm here. This will allow us to properly hit // test elements with `border-radius`, for example. @@ -473,7 +473,7 @@ pub fn find_stacking_context_with_layer_id(this: &Arc<StackingContext>, layer_id } /// One drawing command in the list. -#[deriving(Clone)] +#[derive(Clone)] pub enum DisplayItem { SolidColorClass(Box<SolidColorDisplayItem>), TextClass(Box<TextDisplayItem>), @@ -485,7 +485,7 @@ pub enum DisplayItem { } /// Information common to all display items. -#[deriving(Clone)] +#[derive(Clone)] pub struct BaseDisplayItem { /// The boundaries of the display item, in layer coordinates. pub bounds: Rect<Au>, @@ -512,7 +512,7 @@ impl BaseDisplayItem { /// A clipping region for a display item. Currently, this can describe rectangles, rounded /// rectangles (for `border-radius`), or arbitrary intersections of the two. Arbitrary transforms /// are not supported because those are handled by the higher-level `StackingContext` abstraction. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct ClippingRegion { /// The main rectangular region. This does not include any corners. pub main: Rect<Au>, @@ -526,7 +526,7 @@ pub struct ClippingRegion { /// A complex clipping region. These don't as easily admit arbitrary intersection operations, so /// they're stored in a list over to the side. Currently a complex clipping region is just a /// rounded rectangle, but the CSS WGs will probably make us throw more stuff in here eventually. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct ComplexClippingRegion { /// The boundaries of the rectangle. pub rect: Rect<Au>, @@ -637,7 +637,7 @@ impl ClippingRegion { /// Metadata attached to each display item. This is useful for performing auxiliary tasks with /// the display list involving hit testing: finding the originating DOM node and determining the /// cursor to use when the element is hovered over. -#[deriving(Clone, Copy)] +#[derive(Clone, Copy)] pub struct DisplayItemMetadata { /// The DOM node from which this display item originated. pub node: OpaqueNode, @@ -666,14 +666,14 @@ impl DisplayItemMetadata { } /// Paints a solid color. -#[deriving(Clone)] +#[derive(Clone)] pub struct SolidColorDisplayItem { pub base: BaseDisplayItem, pub color: Color, } /// Paints text. -#[deriving(Clone)] +#[derive(Clone)] pub struct TextDisplayItem { /// Fields common to all display items. pub base: BaseDisplayItem, @@ -691,7 +691,7 @@ pub struct TextDisplayItem { pub orientation: TextOrientation, } -#[deriving(Clone, Eq, PartialEq)] +#[derive(Clone, Eq, PartialEq)] pub enum TextOrientation { Upright, SidewaysLeft, @@ -699,7 +699,7 @@ pub enum TextOrientation { } /// Paints an image. -#[deriving(Clone)] +#[derive(Clone)] pub struct ImageDisplayItem { pub base: BaseDisplayItem, pub image: Arc<Box<Image>>, @@ -711,7 +711,7 @@ pub struct ImageDisplayItem { } /// Paints a gradient. -#[deriving(Clone)] +#[derive(Clone)] pub struct GradientDisplayItem { /// Fields common to all display items. pub base: BaseDisplayItem, @@ -727,7 +727,7 @@ pub struct GradientDisplayItem { } /// Paints a border. -#[deriving(Clone)] +#[derive(Clone)] pub struct BorderDisplayItem { /// Fields common to all display items. pub base: BaseDisplayItem, @@ -750,7 +750,7 @@ pub struct BorderDisplayItem { /// Information about the border radii. /// /// TODO(pcwalton): Elliptical radii. -#[deriving(Clone, Default, PartialEq, Show, Copy)] +#[derive(Clone, Default, PartialEq, Show, Copy)] pub struct BorderRadii<T> { pub top_left: T, pub top_right: T, @@ -768,7 +768,7 @@ impl<T> BorderRadii<T> where T: PartialEq + Zero { } /// Paints a line segment. -#[deriving(Clone)] +#[derive(Clone)] pub struct LineDisplayItem { pub base: BaseDisplayItem, @@ -780,7 +780,7 @@ pub struct LineDisplayItem { } /// Paints a box shadow per CSS-BACKGROUNDS. -#[deriving(Clone)] +#[derive(Clone)] pub struct BoxShadowDisplayItem { /// Fields common to all display items. pub base: BaseDisplayItem, @@ -806,10 +806,11 @@ pub struct BoxShadowDisplayItem { pub enum DisplayItemIterator<'a> { Empty, - Parent(dlist::Items<'a,DisplayItem>), + Parent(dlist::Iter<'a,DisplayItem>), } -impl<'a> Iterator<&'a DisplayItem> for DisplayItemIterator<'a> { +impl<'a> Iterator for DisplayItemIterator<'a> { + type Item = &'a DisplayItem; #[inline] fn next(&mut self) -> Option<&'a DisplayItem> { match *self { @@ -836,14 +837,14 @@ impl DisplayItem { } DisplayItem::TextClass(ref text) => { - debug!("Drawing text at {}.", text.base.bounds); + debug!("Drawing text at {:?}.", text.base.bounds); paint_context.draw_text(&**text); } DisplayItem::ImageClass(ref image_item) => { // FIXME(pcwalton): This is a really inefficient way to draw a tiled image; use a // brush instead. - debug!("Drawing image at {}.", image_item.base.bounds); + debug!("Drawing image at {:?}.", image_item.base.bounds); let mut y_offset = Au(0); while y_offset < image_item.base.bounds.size.height { @@ -926,13 +927,13 @@ impl DisplayItem { for _ in range(0, level) { indent.push_str("| ") } - println!("{}+ {}", indent, self); + println!("{}+ {:?}", indent, self); } } impl fmt::Show for DisplayItem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{} @ {} ({:x})", + write!(f, "{} @ {:?} ({:x})", match *self { DisplayItem::SolidColorClass(_) => "SolidColor", DisplayItem::TextClass(_) => "Text", diff --git a/components/gfx/display_list/optimizer.rs b/components/gfx/display_list/optimizer.rs index f9b738a1d73..dddf31c66d7 100644 --- a/components/gfx/display_list/optimizer.rs +++ b/components/gfx/display_list/optimizer.rs @@ -44,7 +44,7 @@ impl DisplayListOptimizer { fn add_in_bounds_display_items<'a,I>(&self, result_list: &mut DList<DisplayItem>, mut display_items: I) - where I: Iterator<&'a DisplayItem> { + where I: Iterator<Item=&'a DisplayItem> { for display_item in display_items { if self.visible_rect.intersects(&display_item.base().bounds) && display_item.base().clip.might_intersect_rect(&self.visible_rect) { @@ -57,7 +57,7 @@ impl DisplayListOptimizer { fn add_in_bounds_stacking_contexts<'a,I>(&self, result_list: &mut DList<Arc<StackingContext>>, mut stacking_contexts: I) - where I: Iterator<&'a Arc<StackingContext>> { + where I: Iterator<Item=&'a Arc<StackingContext>> { for stacking_context in stacking_contexts { let overflow = stacking_context.overflow.translate(&stacking_context.bounds.origin); if self.visible_rect.intersects(&overflow) { diff --git a/components/gfx/filters.rs b/components/gfx/filters.rs index a1cc25d2bd0..948f2cdfc3d 100644 --- a/components/gfx/filters.rs +++ b/components/gfx/filters.rs @@ -9,7 +9,7 @@ use azure::azure_hl::{ColorMatrixAttribute, ColorMatrixInput, CompositeInput, Dr use azure::azure_hl::{FilterNode, FilterType, LinearTransferAttribute, LinearTransferInput}; use azure::azure_hl::{Matrix5x4, TableTransferAttribute, TableTransferInput}; -use std::num::FloatMath; +use std::num::Float; use style::computed_values::filter; /// Creates a filter pipeline from a set of CSS filters. Returns the destination end of the filter diff --git a/components/gfx/font.rs b/components/gfx/font.rs index 653eff5e5f3..cfc79b6248c 100644 --- a/components/gfx/font.rs +++ b/components/gfx/font.rs @@ -8,13 +8,13 @@ use std::mem; use std::slice; use std::rc::Rc; use std::cell::RefCell; -use servo_util::cache::{Cache, HashCache}; +use servo_util::cache::HashCache; use servo_util::smallvec::{SmallVec, SmallVec8}; use style::computed_values::{font_variant, font_weight}; use style::style_structs::Font as FontStyle; use std::sync::Arc; -use collections::hash::Hash; +use std::hash::Hash; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use servo_util::geometry::Au; @@ -66,10 +66,10 @@ impl FontTableTagConversions for FontTableTag { } pub trait FontTableMethods { - fn with_buffer(&self, |*const u8, uint|); + fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, uint); } -#[deriving(Clone, Show)] +#[derive(Clone, Show)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, @@ -101,7 +101,6 @@ pub struct Font { } bitflags! { - #[deriving(Copy)] flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, @@ -113,7 +112,7 @@ bitflags! { } /// Various options that control text shaping. -#[deriving(Clone, Eq, PartialEq, Hash, Copy)] +#[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. @@ -125,36 +124,25 @@ pub struct ShapingOptions { } /// An entry in the shape cache. -#[deriving(Clone, Eq, PartialEq, Hash)] +#[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } -#[deriving(Clone, Eq, PartialEq, Hash)] -struct ShapeCacheEntryRef<'a> { - text: &'a str, - options: &'a ShapingOptions, -} - -impl<'a> Equiv<ShapeCacheEntry> for ShapeCacheEntryRef<'a> { - fn equiv(&self, other: &ShapeCacheEntry) -> bool { - self.text == other.text.as_slice() && *self.options == other.options - } -} - impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); + //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; - let lookup_key = ShapeCacheEntryRef { - text: text, - options: options, + let lookup_key = ShapeCacheEntry { + text: text.to_owned(), + options: options.clone(), }; - match self.shape_cache.find_equiv(&lookup_key) { + match self.shape_cache.find(&lookup_key) { None => {} - Some(glyphs) => return (*glyphs).clone(), + Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count() as int, diff --git a/components/gfx/font_cache_task.rs b/components/gfx/font_cache_task.rs index 5bb3a209d68..ac7648e1821 100644 --- a/components/gfx/font_cache_task.rs +++ b/components/gfx/font_cache_task.rs @@ -12,6 +12,7 @@ use collections::str::Str; use std::borrow::ToOwned; use std::collections::HashMap; use std::sync::Arc; +use std::sync::mpsc::{Sender, Receiver, channel}; use font_template::{FontTemplate, FontTemplateDescriptor}; use platform::font_template::FontTemplateData; use servo_net::resource_task::{ResourceTask, load_whole_resource}; @@ -80,11 +81,15 @@ pub enum Command { Exit(Sender<()>), } +unsafe impl Send for Command {} + /// Reply messages sent from the font cache task to the FontContext caller. pub enum Reply { GetFontTemplateReply(Option<Arc<FontTemplateData>>), } +unsafe impl Send for Reply {} + /// The font cache task itself. It maintains a list of reference counted /// font templates that are currently in use. struct FontCache { @@ -109,7 +114,7 @@ fn add_generic_font(generic_fonts: &mut HashMap<LowercaseString, LowercaseString impl FontCache { fn run(&mut self) { loop { - let msg = self.port.recv(); + let msg = self.port.recv().unwrap(); match msg { Command::GetFontTemplate(family, descriptor, result) => { @@ -138,13 +143,13 @@ impl FontCache { family.add_template(url.to_string().as_slice(), Some(bytes)); }, Err(_) => { - debug!("Failed to load web font: family={} url={}", family_name, url); + debug!("Failed to load web font: family={:?} url={}", family_name, url); } } } Source::Local(ref local_family_name) => { let family = &mut self.web_families[family_name]; - get_variations_for_family(local_family_name.as_slice(), |path| { + get_variations_for_family(local_family_name.as_slice(), |&mut:path| { family.add_template(path.as_slice(), None); }); } @@ -186,7 +191,7 @@ impl FontCache { let s = &mut self.local_families[*family_name]; if s.templates.len() == 0 { - get_variations_for_family(family_name.as_slice(), |path| { + get_variations_for_family(family_name.as_slice(), |&mut:path| { s.add_template(path.as_slice(), None); }); } @@ -244,7 +249,7 @@ impl FontCache { /// The public interface to the font cache task, used exclusively by /// the per-thread/task FontContext structures. -#[deriving(Clone)] +#[derive(Clone)] pub struct FontCacheTask { chan: Sender<Command>, } @@ -253,7 +258,7 @@ impl FontCacheTask { pub fn new(resource_task: ResourceTask) -> FontCacheTask { let (chan, port) = channel(); - spawn_named("FontCacheTask".to_owned(), proc() { + spawn_named("FontCacheTask".to_owned(), move || { // TODO: Allow users to specify these. let mut generic_fonts = HashMap::with_capacity(5); add_generic_font(&mut generic_fonts, "serif", "Times New Roman"); @@ -286,7 +291,7 @@ impl FontCacheTask { let (response_chan, response_port) = channel(); self.chan.send(Command::GetFontTemplate(family, desc, response_chan)); - let reply = response_port.recv(); + let reply = response_port.recv().unwrap(); match reply { Reply::GetFontTemplateReply(data) => { @@ -301,7 +306,7 @@ impl FontCacheTask { let (response_chan, response_port) = channel(); self.chan.send(Command::GetLastResortFontTemplate(desc, response_chan)); - let reply = response_port.recv(); + let reply = response_port.recv().unwrap(); match reply { Reply::GetFontTemplateReply(data) => { diff --git a/components/gfx/font_template.rs b/components/gfx/font_template.rs index 833495d2177..d90df2b3bdb 100644 --- a/components/gfx/font_template.rs +++ b/components/gfx/font_template.rs @@ -15,7 +15,7 @@ use font::FontHandleMethods; /// This is very basic at the moment and needs to be /// expanded or refactored when we support more of the /// font styling parameters. -#[deriving(Clone, Copy)] +#[derive(Clone, Copy)] pub struct FontTemplateDescriptor { pub weight: font_weight::T, pub italic: bool, diff --git a/components/gfx/lib.rs b/components/gfx/lib.rs index d90a7185d8a..5f1eae371df 100644 --- a/components/gfx/lib.rs +++ b/components/gfx/lib.rs @@ -2,14 +2,14 @@ * 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/. */ -#![feature(globs, macro_rules, phase, unsafe_destructor, default_type_params)] +#![feature(unsafe_destructor, int_uint, plugin, box_syntax)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] +#![allow(unstable)] -#![feature(phase)] -#[phase(plugin, link)] +#[macro_use] extern crate log; extern crate azure; @@ -17,16 +17,15 @@ extern crate collections; extern crate geom; extern crate layers; extern crate libc; -extern crate rustrt; extern crate stb_image; extern crate png; extern crate script_traits; -extern crate serialize; +extern crate "serialize" as rustc_serialize; extern crate unicode; -#[phase(plugin)] +#[no_link] #[plugin] extern crate "plugins" as servo_plugins; extern crate "net" as servo_net; -#[phase(plugin, link)] +#[macro_use] extern crate "util" as servo_util; extern crate "msg" as servo_msg; extern crate style; diff --git a/components/gfx/paint_context.rs b/components/gfx/paint_context.rs index fc8834c5239..2a4925beb83 100644 --- a/components/gfx/paint_context.rs +++ b/components/gfx/paint_context.rs @@ -32,7 +32,7 @@ use servo_util::range::Range; use std::default::Default; use std::f32; use std::mem; -use std::num::{Float, FloatMath}; +use std::num::Float; use std::ptr; use style::computed_values::{border_style, filter, mix_blend_mode}; use std::sync::Arc; @@ -54,7 +54,7 @@ pub struct PaintContext<'a> { pub transient_clip: Option<ClippingRegion>, } -#[deriving(Copy)] +#[derive(Copy)] enum Direction { Top, Left, @@ -62,7 +62,7 @@ enum Direction { Bottom } -#[deriving(Copy)] +#[derive(Copy)] enum DashSize { DottedBorder = 1, DashedBorder = 3 @@ -608,7 +608,7 @@ impl<'a> PaintContext<'a> { let rect = bounds.to_azure_rect(); let draw_opts = DrawOptions::new(1u as AzFloat, 0 as uint16_t); let mut stroke_opts = StrokeOptions::new(0u as AzFloat, 10u as AzFloat); - let mut dash: [AzFloat, ..2] = [0u as AzFloat, 0u as AzFloat]; + let mut dash: [AzFloat; 2] = [0u as AzFloat, 0u as AzFloat]; stroke_opts.set_cap_style(AZ_CAP_BUTT as u8); diff --git a/components/gfx/paint_task.rs b/components/gfx/paint_task.rs index efb1182a795..95909f42e67 100644 --- a/components/gfx/paint_task.rs +++ b/components/gfx/paint_task.rs @@ -31,13 +31,13 @@ use servo_util::smallvec::SmallVec; use servo_util::task::spawn_named_with_send_on_failure; use servo_util::task_state; use servo_util::time::{TimeProfilerChan, TimeProfilerCategory, profile}; -use std::comm::{Receiver, Sender, channel}; use std::mem; -use std::task::TaskBuilder; +use std::thread::Builder; use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, channel}; /// Information about a hardware graphics layer that layout sends to the painting task. -#[deriving(Clone)] +#[derive(Clone)] pub struct PaintLayer { /// A per-pipeline ID describing this layer that should be stable across reflows. pub id: LayerId, @@ -74,7 +74,7 @@ pub enum Msg { Exit(Option<Sender<()>>, PipelineExitType), } -#[deriving(Clone)] +#[derive(Clone)] pub struct PaintChan(Sender<Msg>); impl PaintChan { @@ -84,13 +84,12 @@ impl PaintChan { } pub fn send(&self, msg: Msg) { - let &PaintChan(ref chan) = self; - assert!(chan.send_opt(msg).is_ok(), "PaintChan.send: paint port closed") + assert!(self.send_opt(msg).is_ok(), "PaintChan.send: paint port closed") } pub fn send_opt(&self, msg: Msg) -> Result<(), Msg> { let &PaintChan(ref chan) = self; - chan.send_opt(msg) + chan.send(msg).map_err(|e| e.0) } } @@ -132,7 +131,7 @@ macro_rules! native_graphics_context( ($task:expr) => ( $task.native_graphics_context.as_ref().expect("Need a graphics context to do painting") ) -) +); impl<C> PaintTask<C> where C: PaintListener + Send { pub fn create(id: PipelineId, @@ -144,7 +143,7 @@ impl<C> PaintTask<C> where C: PaintListener + Send { time_profiler_chan: TimeProfilerChan, shutdown_chan: Sender<()>) { let ConstellationChan(c) = constellation_chan.clone(); - spawn_named_with_send_on_failure("PaintTask", task_state::PAINT, proc() { + spawn_named_with_send_on_failure("PaintTask", task_state::PAINT, move |:| { { // Ensures that the paint task and graphics context are destroyed before the // shutdown message. @@ -196,7 +195,7 @@ impl<C> PaintTask<C> where C: PaintListener + Send { let mut exit_response_channel : Option<Sender<()>> = None; let mut waiting_for_compositor_buffers_to_exit = false; loop { - match self.port.recv() { + match self.port.recv().unwrap() { Msg::PaintInit(stacking_context) => { self.root_stacking_context = Some(stacking_context.clone()); @@ -226,7 +225,7 @@ impl<C> PaintTask<C> where C: PaintListener + Send { if self.epoch == epoch { self.paint(&mut replies, buffer_requests, scale, layer_id); } else { - debug!("painter epoch mismatch: {} != {}", self.epoch, epoch); + debug!("painter epoch mismatch: {:?} != {:?}", self.epoch, epoch); } } @@ -336,7 +335,7 @@ impl<C> PaintTask<C> where C: PaintListener + Send { mut tiles: Vec<BufferRequest>, scale: f32, layer_id: LayerId) { - profile(TimeProfilerCategory::Painting, None, self.time_profiler_chan.clone(), || { + profile(TimeProfilerCategory::Painting, None, self.time_profiler_chan.clone(), |:| { // Bail out if there is no appropriate stacking context. let stacking_context = if let Some(ref stacking_context) = self.root_stacking_context { match display_list::find_stacking_context_with_layer_id(stacking_context, @@ -360,10 +359,10 @@ impl<C> PaintTask<C> where C: PaintListener + Send { stacking_context.clone(), scale); } - let new_buffers = Vec::from_fn(tile_count, |i| { + let new_buffers = (0..tile_count).map(|&mut :i| { let thread_id = i % self.worker_threads.len(); self.worker_threads[thread_id].get_painted_tile_buffer() - }); + }).collect(); let layer_buffer_set = box LayerBufferSet { buffers: new_buffers, @@ -425,13 +424,13 @@ impl WorkerThreadProxy { } else { opts::get().layout_threads }; - Vec::from_fn(thread_count, |_| { + (0..thread_count).map(|&:_| { let (from_worker_sender, from_worker_receiver) = channel(); let (to_worker_sender, to_worker_receiver) = channel(); let native_graphics_metadata = native_graphics_metadata.clone(); let font_cache_task = font_cache_task.clone(); let time_profiler_chan = time_profiler_chan.clone(); - TaskBuilder::new().spawn(proc() { + Builder::new().spawn(move || { let mut worker_thread = WorkerThread::new(from_worker_sender, to_worker_receiver, native_graphics_metadata, @@ -443,7 +442,7 @@ impl WorkerThreadProxy { receiver: from_worker_receiver, sender: to_worker_sender, } - }) + }).collect() } fn paint_tile(&mut self, @@ -451,17 +450,17 @@ impl WorkerThreadProxy { layer_buffer: Option<Box<LayerBuffer>>, stacking_context: Arc<StackingContext>, scale: f32) { - self.sender.send(MsgToWorkerThread::PaintTile(tile, layer_buffer, stacking_context, scale)) + self.sender.send(MsgToWorkerThread::PaintTile(tile, layer_buffer, stacking_context, scale)).unwrap() } fn get_painted_tile_buffer(&mut self) -> Box<LayerBuffer> { - match self.receiver.recv() { + match self.receiver.recv().unwrap() { MsgFromWorkerThread::PaintedTile(layer_buffer) => layer_buffer, } } fn exit(&mut self) { - self.sender.send(MsgToWorkerThread::Exit) + self.sender.send(MsgToWorkerThread::Exit).unwrap() } } @@ -493,7 +492,7 @@ impl WorkerThread { fn main(&mut self) { loop { - match self.receiver.recv() { + match self.receiver.recv().unwrap() { MsgToWorkerThread::Exit => break, MsgToWorkerThread::PaintTile(tile, layer_buffer, stacking_context, scale) => { let draw_target = self.optimize_and_paint_tile(&tile, stacking_context, scale); @@ -501,7 +500,7 @@ impl WorkerThread { layer_buffer, draw_target, scale); - self.sender.send(MsgFromWorkerThread::PaintedTile(buffer)) + self.sender.send(MsgFromWorkerThread::PaintedTile(buffer)).unwrap() } } } @@ -582,7 +581,7 @@ impl WorkerThread { // GPU painting mode, so that it doesn't have to recreate it. if !opts::get().gpu_painting { let mut buffer = layer_buffer.unwrap(); - draw_target.snapshot().get_data_surface().with_data(|data| { + draw_target.snapshot().get_data_surface().with_data(|&mut:data| { buffer.native_surface.upload(native_graphics_context!(self), data); debug!("painting worker thread uploading to native surface {}", buffer.native_surface.get_id()); diff --git a/components/gfx/platform/freetype/font.rs b/components/gfx/platform/freetype/font.rs index f34f158c39d..2e13a4f39aa 100644 --- a/components/gfx/platform/freetype/font.rs +++ b/components/gfx/platform/freetype/font.rs @@ -8,6 +8,7 @@ use font::{FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel}; use servo_util::geometry::Au; use servo_util::geometry; +use servo_util::str::c_str_to_string; use platform::font_context::FontContextHandle; use text::glyph::GlyphId; use text::util::{float_to_fixed, fixed_to_float}; @@ -25,11 +26,10 @@ use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics, struct_FT_Vector_ use freetype::freetype::{ft_sfnt_os2}; use freetype::tt_os2::TT_OS2; +use libc::c_char; use std::mem; use std::num::Float; use std::ptr; -use std::string::String; - use std::sync::Arc; fn float_to_fixed_ft(f: f64) -> i32 { @@ -43,7 +43,7 @@ fn fixed_to_float_ft(f: i32) -> f64 { pub struct FontTable; impl FontTableMethods for FontTable { - fn with_buffer(&self, _blk: |*const u8, uint|) { + fn with_buffer<F>(&self, _blk: F) where F: FnOnce(*const u8, uint) { panic!() } } @@ -121,10 +121,14 @@ impl FontHandleMethods for FontHandle { self.font_data.clone() } fn family_name(&self) -> String { - unsafe { String::from_raw_buf(&*(*self.face).family_name as *const i8 as *const u8) } + unsafe { + c_str_to_string((*self.face).family_name as *const c_char) + } } fn face_name(&self) -> String { - unsafe { String::from_raw_buf(&*FT_Get_Postscript_Name(self.face) as *const i8 as *const u8) } + unsafe { + c_str_to_string(FT_Get_Postscript_Name(self.face) as *const c_char) + } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC != 0 } @@ -253,7 +257,7 @@ impl FontHandleMethods for FontHandle { line_gap: height, }; - debug!("Font metrics (@{} pt): {}", geometry::to_pt(em_size), metrics); + debug!("Font metrics (@{} pt): {:?}", geometry::to_pt(em_size), metrics); return metrics; } diff --git a/components/gfx/platform/freetype/font_context.rs b/components/gfx/platform/freetype/font_context.rs index e978cfd48cd..1c58233f0f7 100644 --- a/components/gfx/platform/freetype/font_context.rs +++ b/components/gfx/platform/freetype/font_context.rs @@ -37,12 +37,12 @@ extern fn ft_realloc(_mem: FT_Memory, _cur_size: c_long, new_size: c_long, block } } -#[deriving(Clone)] +#[derive(Clone)] pub struct FreeTypeLibraryHandle { pub ctx: FT_Library, } -#[deriving(Clone)] +#[derive(Clone)] pub struct FontContextHandle { pub ctx: Rc<FreeTypeLibraryHandle>, } diff --git a/components/gfx/platform/freetype/font_list.rs b/components/gfx/platform/freetype/font_list.rs index 31f7bc6aeb1..fbe354556c4 100644 --- a/components/gfx/platform/freetype/font_list.rs +++ b/components/gfx/platform/freetype/font_list.rs @@ -20,17 +20,19 @@ use fontconfig::fontconfig::{ FcObjectSetAdd, FcPatternGetInteger }; +use servo_util::str::c_str_to_string; + use libc; -use libc::c_int; +use libc::{c_int, c_char}; use std::borrow::ToOwned; +use std::ffi::CString; use std::ptr; -use std::string::String; static FC_FAMILY: &'static [u8] = b"family\0"; static FC_FILE: &'static [u8] = b"file\0"; static FC_INDEX: &'static [u8] = b"index\0"; -pub fn get_available_families(callback: |String|) { +pub fn get_available_families<F>(mut callback: F) where F: FnMut(String) { unsafe { let config = FcConfigGetCurrent(); let fontSet = FcConfigGetFonts(config, FcSetSystem); @@ -38,8 +40,8 @@ pub fn get_available_families(callback: |String|) { let font = (*fontSet).fonts.offset(i); let mut family: *mut FcChar8 = ptr::null_mut(); let mut v: c_int = 0; - while FcPatternGetString(*font, FC_FAMILY.as_ptr() as *mut i8, v, &mut family) == FcResultMatch { - let family_name = String::from_raw_buf(family as *const i8 as *const u8); + while FcPatternGetString(*font, FC_FAMILY.as_ptr() as *mut c_char, v, &mut family) == FcResultMatch { + let family_name = c_str_to_string(family as *const c_char); callback(family_name); v += 1; } @@ -47,7 +49,9 @@ pub fn get_available_families(callback: |String|) { } } -pub fn get_variations_for_family(family_name: &str, callback: |String|) { +pub fn get_variations_for_family<F>(family_name: &str, mut callback: F) + where F: FnMut(String) +{ debug!("getting variations for {}", family_name); unsafe { let config = FcConfigGetCurrent(); @@ -55,16 +59,16 @@ pub fn get_variations_for_family(family_name: &str, callback: |String|) { let font_set_array_ptr = &mut font_set; let pattern = FcPatternCreate(); assert!(!pattern.is_null()); - let mut family_name_c = family_name.to_c_str(); - let family_name = family_name_c.as_mut_ptr(); - let ok = FcPatternAddString(pattern, FC_FAMILY.as_ptr() as *mut i8, family_name as *mut FcChar8); + let family_name_c = CString::from_slice(family_name.as_bytes()); + let family_name = family_name_c.as_ptr(); + let ok = FcPatternAddString(pattern, FC_FAMILY.as_ptr() as *mut c_char, family_name as *mut FcChar8); assert!(ok != 0); let object_set = FcObjectSetCreate(); assert!(!object_set.is_null()); - FcObjectSetAdd(object_set, FC_FILE.as_ptr() as *mut i8); - FcObjectSetAdd(object_set, FC_INDEX.as_ptr() as *mut i8); + FcObjectSetAdd(object_set, FC_FILE.as_ptr() as *mut c_char); + FcObjectSetAdd(object_set, FC_INDEX.as_ptr() as *mut c_char); let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set); @@ -73,13 +77,13 @@ pub fn get_variations_for_family(family_name: &str, callback: |String|) { for i in range(0, (*matches).nfont as int) { let font = (*matches).fonts.offset(i); let mut file: *mut FcChar8 = ptr::null_mut(); - let file = if FcPatternGetString(*font, FC_FILE.as_ptr() as *mut i8, 0, &mut file) == FcResultMatch { - String::from_raw_buf(file as *const i8 as *const u8) + let file = if FcPatternGetString(*font, FC_FILE.as_ptr() as *mut c_char, 0, &mut file) == FcResultMatch { + c_str_to_string(file as *const c_char) } else { panic!(); }; let mut index: libc::c_int = 0; - let index = if FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut i8, 0, &mut index) == FcResultMatch { + let index = if FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut c_char, 0, &mut index) == FcResultMatch { index } else { panic!(); @@ -98,8 +102,8 @@ pub fn get_variations_for_family(family_name: &str, callback: |String|) { } pub fn get_system_default_family(generic_name: &str) -> Option<String> { - let mut generic_name_c = generic_name.to_c_str(); - let generic_name_ptr = generic_name_c.as_mut_ptr(); + let generic_name_c = CString::from_slice(generic_name.as_bytes()); + let generic_name_ptr = generic_name_c.as_ptr(); unsafe { let pattern = FcNameParse(generic_name_ptr as *mut FcChar8); @@ -112,8 +116,8 @@ pub fn get_system_default_family(generic_name: &str) -> Option<String> { let family_name = if result == FcResultMatch { let mut match_string: *mut FcChar8 = ptr::null_mut(); - FcPatternGetString(family_match, FC_FAMILY.as_ptr() as *mut i8, 0, &mut match_string); - let result = String::from_raw_buf(match_string as *const i8 as *const u8); + FcPatternGetString(family_match, FC_FAMILY.as_ptr() as *mut c_char, 0, &mut match_string); + let result = c_str_to_string(match_string as *const c_char); FcPatternDestroy(family_match); Some(result) } else { diff --git a/components/gfx/platform/macos/font.rs b/components/gfx/platform/macos/font.rs index 2e3aae29dc7..db168c657e6 100644 --- a/components/gfx/platform/macos/font.rs +++ b/components/gfx/platform/macos/font.rs @@ -47,7 +47,7 @@ impl FontTable { } impl FontTableMethods for FontTable { - fn with_buffer(&self, blk: |*const u8, uint|) { + fn with_buffer<F>(&self, blk: F) where F: FnOnce(*const u8, uint) { blk(self.data.bytes().as_ptr(), self.data.len() as uint); } } @@ -112,8 +112,8 @@ impl FontHandleMethods for FontHandle { } fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { - let characters: [UniChar, ..1] = [codepoint as UniChar]; - let mut glyphs: [CGGlyph, ..1] = [0 as CGGlyph]; + let characters: [UniChar; 1] = [codepoint as UniChar]; + let mut glyphs: [CGGlyph; 1] = [0 as CGGlyph]; let count: CFIndex = 1; let result = self.ctfont.get_glyphs_for_characters(&characters[0], @@ -179,7 +179,7 @@ impl FontHandleMethods for FontHandle { average_advance: average_advance, line_gap: Au::from_frac_px(line_gap), }; - debug!("Font metrics (@{} pt): {}", self.ctfont.pt_size() as f64, metrics); + debug!("Font metrics (@{} pt): {:?}", self.ctfont.pt_size() as f64, metrics); return metrics; } diff --git a/components/gfx/platform/macos/font_context.rs b/components/gfx/platform/macos/font_context.rs index e65381c3bbc..e35aadb9910 100644 --- a/components/gfx/platform/macos/font_context.rs +++ b/components/gfx/platform/macos/font_context.rs @@ -2,7 +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/. */ -#[deriving(Clone)] +#[derive(Clone)] pub struct FontContextHandle { ctx: () } diff --git a/components/gfx/platform/macos/font_list.rs b/components/gfx/platform/macos/font_list.rs index 832db9d947a..4e327cea1b8 100644 --- a/components/gfx/platform/macos/font_list.rs +++ b/components/gfx/platform/macos/font_list.rs @@ -10,7 +10,7 @@ use core_text; use std::borrow::ToOwned; use std::mem; -pub fn get_available_families(callback: |String|) { +pub fn get_available_families<F>(mut callback: F) where F: FnMut(String) { let family_names = core_text::font_collection::get_family_names(); for strref in family_names.iter() { let family_name_ref: CFStringRef = unsafe { mem::transmute(strref) }; @@ -20,7 +20,7 @@ pub fn get_available_families(callback: |String|) { } } -pub fn get_variations_for_family(family_name: &str, callback: |String|) { +pub fn get_variations_for_family<F>(family_name: &str, mut callback: F) where F: FnMut(String) { debug!("Looking for faces of family: {}", family_name); let family_collection = diff --git a/components/gfx/platform/macos/font_template.rs b/components/gfx/platform/macos/font_template.rs index 9c00c729a20..c6eb84d9746 100644 --- a/components/gfx/platform/macos/font_template.rs +++ b/components/gfx/platform/macos/font_template.rs @@ -18,6 +18,9 @@ pub struct FontTemplateData { pub identifier: String, } +unsafe impl Send for FontTemplateData {} +unsafe impl Sync for FontTemplateData {} + impl FontTemplateData { pub fn new(identifier: &str, font_data: Option<Vec<u8>>) -> FontTemplateData { let ctfont = match font_data { diff --git a/components/gfx/text/glyph.rs b/components/gfx/text/glyph.rs index 312c0692847..be4b2d3c4d4 100644 --- a/components/gfx/text/glyph.rs +++ b/components/gfx/text/glyph.rs @@ -9,8 +9,9 @@ use servo_util::geometry::Au; use std::cmp::{Ordering, PartialOrd}; use std::iter::repeat; -use std::num::NumCast; +use std::num::{ToPrimitive, NumCast}; use std::mem; +use std::ops::{Add, Sub, Mul, Neg, Div, Rem, BitAnd, BitOr, BitXor, Shl, Shr, Not}; use std::u16; use std::vec::Vec; use geom::point::Point2D; @@ -23,7 +24,7 @@ use geom::point::Point2D; /// In the uncommon case (multiple glyphs per unicode character, large glyph index/advance, or /// glyph offsets), we pack the glyph count into GlyphEntry, and store the other glyph information /// in DetailedGlyphStore. -#[deriving(Clone, Show, Copy)] +#[derive(Clone, Show, Copy)] struct GlyphEntry { value: u32, } @@ -88,7 +89,7 @@ impl GlyphEntry { pub type GlyphId = u32; // TODO: unify with bit flags? -#[deriving(PartialEq, Copy)] +#[derive(PartialEq, Copy)] pub enum BreakType { None, Normal, @@ -252,7 +253,7 @@ impl GlyphEntry { // Stores data for a detailed glyph, in the case that several glyphs // correspond to one character, or the glyph's data couldn't be packed. -#[deriving(Clone, Show, Copy)] +#[derive(Clone, Show, Copy)] struct DetailedGlyph { id: GlyphId, // glyph's advance, in the text's direction (RTL or RTL) @@ -271,7 +272,7 @@ impl DetailedGlyph { } } -#[deriving(PartialEq, Clone, Eq, Show, Copy)] +#[derive(PartialEq, Clone, Eq, Show, Copy)] struct DetailedGlyphRecord { // source string offset/GlyphEntry offset in the TextRun entry_offset: CharIndex, @@ -320,7 +321,7 @@ impl<'a> DetailedGlyphStore { detail_offset: self.detail_buffer.len() as int, }; - debug!("Adding entry[off={}] for detailed glyphs: {}", entry_offset, glyphs); + debug!("Adding entry[off={:?}] for detailed glyphs: {:?}", entry_offset, glyphs); /* TODO: don't actually assert this until asserts are compiled in/out based on severity, debug/release, etc. This assertion @@ -340,7 +341,7 @@ impl<'a> DetailedGlyphStore { fn get_detailed_glyphs_for_entry(&'a self, entry_offset: CharIndex, count: u16) -> &'a [DetailedGlyph] { - debug!("Requesting detailed glyphs[n={}] for entry[off={}]", count, entry_offset); + debug!("Requesting detailed glyphs[n={}] for entry[off={:?}]", count, entry_offset); // FIXME: Is this right? --pcwalton // TODO: should fix this somewhere else @@ -412,7 +413,7 @@ impl<'a> DetailedGlyphStore { // This struct is used by GlyphStore clients to provide new glyph data. // It should be allocated on the stack and passed by reference to GlyphStore. -#[deriving(Copy)] +#[derive(Copy)] pub struct GlyphData { id: GlyphId, advance: Au, @@ -445,7 +446,7 @@ impl GlyphData { // through glyphs (either for a particular TextRun offset, or all glyphs). // Rather than eagerly assembling and copying glyph data, it only retrieves // values as they are needed from the GlyphStore, using provided offsets. -#[deriving(Copy)] +#[derive(Copy)] pub enum GlyphInfo<'a> { Simple(&'a GlyphStore, CharIndex), Detail(&'a GlyphStore, CharIndex, u16), @@ -514,7 +515,7 @@ pub struct GlyphStore { } int_range_index! { - #[deriving(Encodable)] + #[derive(RustcEncodable)] #[doc = "An index that refers to a character in a text run. This could \ point to the middle of a glyph."] struct CharIndex(int) @@ -580,11 +581,11 @@ impl<'a> GlyphStore { let entry = match first_glyph_data.is_missing { true => GlyphEntry::missing(glyph_count), false => { - let glyphs_vec = Vec::from_fn(glyph_count as uint, |i| { + let glyphs_vec: Vec<DetailedGlyph> = (0..glyph_count as uint).map(|&:i| { DetailedGlyph::new(data_for_glyphs[i].id, data_for_glyphs[i].advance, data_for_glyphs[i].offset) - }); + }).collect(); self.detail_store.add_detailed_glyphs_for_entry(i, glyphs_vec.as_slice()); GlyphEntry::complex(first_glyph_data.cluster_start, @@ -593,7 +594,7 @@ impl<'a> GlyphStore { } }.adapt_character_flags_of_entry(self.entry_buffer[i.to_uint()]); - debug!("Adding multiple glyphs[idx={}, count={}]: {}", i, glyph_count, entry); + debug!("Adding multiple glyphs[idx={:?}, count={}]: {:?}", i, glyph_count, entry); self.entry_buffer[i.to_uint()] = entry; } @@ -603,7 +604,7 @@ impl<'a> GlyphStore { assert!(i < self.char_len()); let entry = GlyphEntry::complex(cluster_start, ligature_start, 0); - debug!("adding spacer for chracter without associated glyph[idx={}]", i); + debug!("adding spacer for chracter without associated glyph[idx={:?}]", i); self.entry_buffer[i.to_uint()] = entry; } @@ -725,7 +726,9 @@ impl<'a> GlyphIterator<'a> { } } -impl<'a> Iterator<(CharIndex, GlyphInfo<'a>)> for GlyphIterator<'a> { +impl<'a> Iterator for GlyphIterator<'a> { + type Item = (CharIndex, GlyphInfo<'a>); + // I tried to start with something simpler and apply FlatMap, but the // inability to store free variables in the FlatMap struct was problematic. // @@ -740,7 +743,7 @@ impl<'a> Iterator<(CharIndex, GlyphInfo<'a>)> for GlyphIterator<'a> { self.next_glyph_range() } else { // No glyph range. Look at next character. - self.char_range.next().and_then(|i| { + self.char_range.next().and_then(|:i| { self.char_index = i; assert!(i < self.store.char_len()); let entry = self.store.entry_buffer[i.to_uint()]; diff --git a/components/gfx/text/text_run.rs b/components/gfx/text/text_run.rs index da5b6f3435e..f98d47fe547 100644 --- a/components/gfx/text/text_run.rs +++ b/components/gfx/text/text_run.rs @@ -9,12 +9,12 @@ use servo_util::geometry::Au; use servo_util::range::Range; use servo_util::vec::{Comparator, FullBinarySearchMethods}; use std::cmp::Ordering; -use std::slice::Items; +use std::slice::Iter; use std::sync::Arc; use text::glyph::{CharIndex, GlyphStore}; /// A single "paragraph" of text in one font size and style. -#[deriving(Clone)] +#[derive(Clone)] pub struct TextRun { pub text: Arc<String>, pub font_template: Arc<FontTemplateData>, @@ -25,7 +25,7 @@ pub struct TextRun { } /// A single series of glyphs within a text run. -#[deriving(Clone)] +#[derive(Clone)] pub struct GlyphRun { /// The glyphs. pub glyph_store: Arc<GlyphStore>, @@ -34,7 +34,7 @@ pub struct GlyphRun { } pub struct NaturalWordSliceIterator<'a> { - glyph_iter: Items<'a, GlyphRun>, + glyph_iter: Iter<'a, GlyphRun>, range: Range<CharIndex>, } @@ -73,7 +73,9 @@ impl<'a> TextRunSlice<'a> { } } -impl<'a> Iterator<TextRunSlice<'a>> for NaturalWordSliceIterator<'a> { +impl<'a> Iterator for NaturalWordSliceIterator<'a> { + type Item = TextRunSlice<'a>; + // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { @@ -101,11 +103,13 @@ impl<'a> Iterator<TextRunSlice<'a>> for NaturalWordSliceIterator<'a> { pub struct CharacterSliceIterator<'a> { glyph_run: Option<&'a GlyphRun>, - glyph_run_iter: Items<'a, GlyphRun>, + glyph_run_iter: Iter<'a, GlyphRun>, range: Range<CharIndex>, } -impl<'a> Iterator<TextRunSlice<'a>> for CharacterSliceIterator<'a> { +impl<'a> Iterator for CharacterSliceIterator<'a> { + type Item = TextRunSlice<'a>; + // inline(always) due to the inefficient rt failures messing up inline heuristics, I think. #[inline(always)] fn next(&mut self) -> Option<TextRunSlice<'a>> { @@ -140,7 +144,9 @@ pub struct LineIterator<'a> { slices: NaturalWordSliceIterator<'a>, } -impl<'a> Iterator<Range<CharIndex>> for LineIterator<'a> { +impl<'a> Iterator for LineIterator<'a> { + type Item = Range<CharIndex>; + fn next(&mut self) -> Option<Range<CharIndex>> { // Loop until we hit whitespace and are in a clump. loop { @@ -311,9 +317,9 @@ impl<'a> TextRun { } pub fn min_width_for_range(&self, range: &Range<CharIndex>) -> Au { - debug!("iterating outer range {}", range); + debug!("iterating outer range {:?}", range); self.natural_word_slices_in_range(range).fold(Au(0), |max_piece_width, slice| { - debug!("iterated on {}[{}]", slice.offset, slice.range); + debug!("iterated on {:?}[{:?}]", slice.offset, slice.range); Au::max(max_piece_width, self.advance_for_range(&slice.range)) }) } diff --git a/components/gfx/text/util.rs b/components/gfx/text/util.rs index 24c916a1ba1..4b8f5041143 100644 --- a/components/gfx/text/util.rs +++ b/components/gfx/text/util.rs @@ -4,7 +4,7 @@ use text::glyph::CharIndex; -#[deriving(PartialEq, Eq, Copy)] +#[derive(PartialEq, Eq, Copy)] pub enum CompressionMode { CompressNone, CompressWhitespace, diff --git a/components/layout/Cargo.toml b/components/layout/Cargo.toml index d24261495e1..fb3796577e6 100644 --- a/components/layout/Cargo.toml +++ b/components/layout/Cargo.toml @@ -7,6 +7,9 @@ authors = ["The Servo Project Developers"] name = "layout" path = "lib.rs" +[dependencies.canvas] +path = "../canvas" + [dependencies.gfx] path = "../gfx" @@ -37,9 +40,6 @@ git = "https://github.com/servo/rust-cssparser" [dependencies.geom] git = "https://github.com/servo/rust-geom" -[dependencies.url] -git = "https://github.com/servo/rust-url" - [dependencies.string_cache] git = "https://github.com/servo/string-cache" @@ -48,3 +48,4 @@ git = "https://github.com/servo/string-cache" [dependencies] encoding = "0.2" +url = "*"
\ No newline at end of file diff --git a/components/layout/block.rs b/components/layout/block.rs index f91f079f6bf..60e56b3e1d7 100644 --- a/components/layout/block.rs +++ b/components/layout/block.rs @@ -64,7 +64,7 @@ use style::computed_values::{overflow, position}; use std::sync::Arc; /// Information specific to floated blocks. -#[deriving(Clone, Encodable)] +#[derive(Clone, Encodable)] pub struct FloatedBlockInfo { /// The amount of inline size that is available for the float. pub containing_inline_size: Au, @@ -92,7 +92,7 @@ impl FloatedBlockInfo { } /// The solutions for the block-size-and-margins constraint equation. -#[deriving(Copy)] +#[derive(Copy)] struct BSizeConstraintSolution { block_start: Au, _block_end: Au, @@ -366,7 +366,8 @@ impl CandidateBSizeIterator { } } -impl Iterator<MaybeAuto> for CandidateBSizeIterator { +impl Iterator for CandidateBSizeIterator { + type Item = MaybeAuto; fn next(&mut self) -> Option<MaybeAuto> { self.status = match self.status { CandidateBSizeIteratorStatus::Initial => CandidateBSizeIteratorStatus::Trying, @@ -487,13 +488,13 @@ pub enum BlockType { FloatNonReplaced, } -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub enum MarginsMayCollapseFlag { MarginsMayCollapse, MarginsMayNotCollapse, } -#[deriving(PartialEq)] +#[derive(PartialEq)] enum FormattingContextType { None, Block, @@ -525,7 +526,7 @@ fn propagate_layer_flag_from_child(layers_needed_for_descendants: &mut bool, kid } // A block formatting context. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct BlockFlow { /// Data common to all flows. pub base: BaseFlow, @@ -561,8 +562,8 @@ bitflags! { } } -impl<'a,E,S> Encodable<S,E> for BlockFlowFlags where S: Encoder<E> { - fn encode(&self, e: &mut S) -> Result<(),E> { +impl Encodable for BlockFlowFlags { + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { self.bits().encode(e) } } @@ -1905,7 +1906,7 @@ impl Flow for BlockFlow { impl fmt::Show for BlockFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, - "{} - {:x}: frag={} ({})", + "{:?} - {:x}: frag={:?} ({:?})", self.class(), self.base.debug_id(), self.fragment, @@ -1914,7 +1915,7 @@ impl fmt::Show for BlockFlow { } /// The inputs for the inline-sizes-and-margins constraint equation. -#[deriving(Show, Copy)] +#[derive(Show, Copy)] pub struct ISizeConstraintInput { pub computed_inline_size: MaybeAuto, pub inline_start_margin: MaybeAuto, @@ -1947,7 +1948,7 @@ impl ISizeConstraintInput { } /// The solutions for the inline-size-and-margins constraint equation. -#[deriving(Copy, Show)] +#[derive(Copy, Show)] pub struct ISizeConstraintSolution { pub inline_start: Au, pub inline_end: Au, @@ -2560,7 +2561,7 @@ impl ISizeAndMarginsComputer for FloatNonReplaced { let available_inline_size_float = available_inline_size - margin_inline_start - margin_inline_end; let shrink_to_fit = block.get_shrink_to_fit_inline_size(available_inline_size_float); let inline_size = computed_inline_size.specified_or_default(shrink_to_fit); - debug!("assign_inline_sizes_float -- inline_size: {}", inline_size); + debug!("assign_inline_sizes_float -- inline_size: {:?}", inline_size); ISizeConstraintSolution::new(inline_size, margin_inline_start, margin_inline_end) } } @@ -2580,7 +2581,7 @@ impl ISizeAndMarginsComputer for FloatReplaced { MaybeAuto::Specified(w) => w, MaybeAuto::Auto => panic!("FloatReplaced: inline_size should have been computed by now") }; - debug!("assign_inline_sizes_float -- inline_size: {}", inline_size); + debug!("assign_inline_sizes_float -- inline_size: {:?}", inline_size); ISizeConstraintSolution::new(inline_size, margin_inline_start, margin_inline_end) } diff --git a/components/layout/construct.rs b/components/layout/construct.rs index 9445eef9c04..d67d1e44753 100644 --- a/components/layout/construct.rs +++ b/components/layout/construct.rs @@ -61,7 +61,7 @@ use std::sync::Arc; use url::Url; /// The results of flow construction for a DOM node. -#[deriving(Clone)] +#[derive(Clone)] pub enum ConstructionResult { /// This node contributes nothing at all (`display: none`). Alternately, this is what newly /// created nodes have their `ConstructionResult` set to. @@ -98,7 +98,7 @@ impl ConstructionResult { /// Represents the output of flow construction for a DOM node that has not yet resulted in a /// complete flow. Construction items bubble up the tree until they find a `Flow` to be attached /// to. -#[deriving(Clone)] +#[derive(Clone)] pub enum ConstructionItem { /// Inline fragments and associated {ib} splits that have not yet found flows. InlineFragments(InlineFragmentsConstructionResult), @@ -109,7 +109,7 @@ pub enum ConstructionItem { } /// Represents inline fragments and {ib} splits that are bubbling up from an inline. -#[deriving(Clone)] +#[derive(Clone)] pub struct InlineFragmentsConstructionResult { /// Any {ib} splits that we're bubbling up. pub splits: DList<InlineBlockSplit>, @@ -147,7 +147,7 @@ pub struct InlineFragmentsConstructionResult { /// C /// ]) /// ``` -#[deriving(Clone)] +#[derive(Clone)] pub struct InlineBlockSplit { /// The inline fragments that precede the flow. pub predecessors: DList<Fragment>, @@ -1150,7 +1150,7 @@ impl<'a> PostorderNodeMutTraversal for FlowConstructor<'a> { } }; - debug!("building flow for node: {} {} {}", display, float, node.type_id()); + debug!("building flow for node: {:?} {:?} {:?}", display, float, node.type_id()); // Switch on display and floatedness. match (display, float, positioning) { diff --git a/components/layout/context.rs b/components/layout/context.rs index b329a20221d..977417e4fe9 100644 --- a/components/layout/context.rs +++ b/components/layout/context.rs @@ -28,7 +28,7 @@ struct LocalLayoutContext { style_sharing_candidate_cache: StyleSharingCandidateCache, } -thread_local!(static LOCAL_CONTEXT_KEY: Cell<*mut LocalLayoutContext> = Cell::new(ptr::null_mut())) +thread_local!(static LOCAL_CONTEXT_KEY: Cell<*mut LocalLayoutContext> = Cell::new(ptr::null_mut())); fn create_or_get_local_context(shared_layout_context: &SharedLayoutContext) -> *mut LocalLayoutContext { LOCAL_CONTEXT_KEY.with(|ref r| { @@ -80,6 +80,9 @@ pub struct SharedLayoutContext { pub generation: uint, } +pub struct SharedLayoutContextWrapper(pub *const SharedLayoutContext); +unsafe impl Send for SharedLayoutContextWrapper {} + pub struct LayoutContext<'a> { pub shared: &'a SharedLayoutContext, cached_local_layout_context: *mut LocalLayoutContext, diff --git a/components/layout/css/matching.rs b/components/layout/css/matching.rs index 44207e0b9e1..2627c592882 100644 --- a/components/layout/css/matching.rs +++ b/components/layout/css/matching.rs @@ -11,13 +11,13 @@ use wrapper::{LayoutElement, LayoutNode, TLayoutNode}; use script::dom::node::NodeTypeId; use servo_util::bloom::BloomFilter; -use servo_util::cache::{Cache, LRUCache, SimpleHashCache}; +use servo_util::cache::{LRUCache, SimpleHashCache}; use servo_util::smallvec::{SmallVec, SmallVec16}; use servo_util::arc_ptr_eq; use std::borrow::ToOwned; use std::mem; -use std::hash::{Hash, sip}; -use std::slice::Items; +use std::hash::{Hash, Hasher, Writer}; +use std::slice::Iter; use string_cache::{Atom, Namespace}; use style::{mod, PseudoElement, ComputedValues, DeclarationBlock, Stylist, TElement, TNode}; use style::{CommonStyleAffectingAttributeMode, CommonStyleAffectingAttributes, cascade}; @@ -50,7 +50,7 @@ impl ApplicableDeclarations { } } -#[deriving(Clone)] +#[derive(Clone)] pub struct ApplicableDeclarationsCacheEntry { pub declarations: Vec<DeclarationBlock>, } @@ -66,12 +66,13 @@ impl ApplicableDeclarationsCacheEntry { impl PartialEq for ApplicableDeclarationsCacheEntry { fn eq(&self, other: &ApplicableDeclarationsCacheEntry) -> bool { let this_as_query = ApplicableDeclarationsCacheQuery::new(self.declarations.as_slice()); - this_as_query.equiv(other) + this_as_query.eq(other) } } +impl Eq for ApplicableDeclarationsCacheEntry {} -impl Hash for ApplicableDeclarationsCacheEntry { - fn hash(&self, state: &mut sip::SipState) { +impl<H: Hasher+Writer> Hash<H> for ApplicableDeclarationsCacheEntry { + fn hash(&self, state: &mut H) { let tmp = ApplicableDeclarationsCacheQuery::new(self.declarations.as_slice()); tmp.hash(state); } @@ -89,8 +90,8 @@ impl<'a> ApplicableDeclarationsCacheQuery<'a> { } } -impl<'a> Equiv<ApplicableDeclarationsCacheEntry> for ApplicableDeclarationsCacheQuery<'a> { - fn equiv(&self, other: &ApplicableDeclarationsCacheEntry) -> bool { +impl<'a> PartialEq for ApplicableDeclarationsCacheQuery<'a> { + fn eq(&self, other: &ApplicableDeclarationsCacheQuery<'a>) -> bool { if self.declarations.len() != other.declarations.len() { return false } @@ -102,10 +103,17 @@ impl<'a> Equiv<ApplicableDeclarationsCacheEntry> for ApplicableDeclarationsCache return true } } +impl<'a> Eq for ApplicableDeclarationsCacheQuery<'a> {} +impl<'a> PartialEq<ApplicableDeclarationsCacheEntry> for ApplicableDeclarationsCacheQuery<'a> { + fn eq(&self, other: &ApplicableDeclarationsCacheEntry) -> bool { + let other_as_query = ApplicableDeclarationsCacheQuery::new(other.declarations.as_slice()); + self.eq(&other_as_query) + } +} -impl<'a> Hash for ApplicableDeclarationsCacheQuery<'a> { - fn hash(&self, state: &mut sip::SipState) { +impl<'a, H: Hasher+Writer> Hash<H> for ApplicableDeclarationsCacheQuery<'a> { + fn hash(&self, state: &mut H) { for declaration in self.declarations.iter() { let ptr: uint = unsafe { mem::transmute_copy(declaration) @@ -129,7 +137,7 @@ impl ApplicableDeclarationsCache { } fn find(&self, declarations: &[DeclarationBlock]) -> Option<Arc<ComputedValues>> { - match self.cache.find_equiv(&ApplicableDeclarationsCacheQuery::new(declarations)) { + match self.cache.find(&ApplicableDeclarationsCacheQuery::new(declarations)) { None => None, Some(ref values) => Some((*values).clone()), } @@ -168,7 +176,7 @@ fn create_common_style_affecting_attributes_from_element(element: &LayoutElement flags } -#[deriving(Clone)] +#[derive(Clone)] pub struct StyleSharingCandidate { pub style: Arc<ComputedValues>, pub parent_style: Arc<ComputedValues>, @@ -321,7 +329,7 @@ impl StyleSharingCandidateCache { } } - pub fn iter<'a>(&'a self) -> Items<'a,(StyleSharingCandidate,())> { + pub fn iter<'a>(&'a self) -> Iter<'a,(StyleSharingCandidate,())> { self.cache.iter() } @@ -608,8 +616,8 @@ impl<'ln> MatchMethods for LayoutNode<'ln> { let mut layout_data_ref = self.mutate_layout_data(); match &mut *layout_data_ref { - &None => panic!("no layout data"), - &Some(ref mut layout_data) => { + &mut None => panic!("no layout data"), + &mut Some(ref mut layout_data) => { match self.type_id() { Some(NodeTypeId::Text) => { // Text nodes get a copy of the parent style. This ensures diff --git a/components/layout/display_list_builder.rs b/components/layout/display_list_builder.rs index 73d0461e13d..b17355cd534 100644 --- a/components/layout/display_list_builder.rs +++ b/components/layout/display_list_builder.rs @@ -45,7 +45,7 @@ use servo_util::logical_geometry::{LogicalPoint, LogicalRect, LogicalSize}; use servo_util::opts; use std::default::Default; use std::iter::repeat; -use std::num::FloatMath; +use std::num::Float; use style::values::specified::{AngleOrCorner, HorizontalDirection, VerticalDirection}; use style::computed::{Image, LinearGradient, LengthOrPercentage}; use style::computed_values::filter::Filter; @@ -53,7 +53,9 @@ use style::computed_values::{background_attachment, background_repeat, border_st use style::computed_values::{position, visibility}; use style::style_structs::Border; use style::{ComputedValues, RGBA}; +use std::num::ToPrimitive; use std::sync::Arc; +use std::sync::mpsc::channel; use url::Url; /// The results of display list building for a single flow. @@ -689,7 +691,7 @@ impl FragmentDisplayListBuilding for Fragment { relative_containing_block_size, CoordinateSystem::Self); - debug!("Fragment::build_display_list at rel={}, abs={}, dirty={}, flow origin={}: {}", + debug!("Fragment::build_display_list at rel={:?}, abs={:?}, dirty={:?}, flow origin={:?}: {:?}", self.border_box, stacking_relative_border_box, layout_context.shared.dirty, @@ -879,8 +881,8 @@ impl FragmentDisplayListBuilding for Fragment { let (sender, receiver) = channel::<Vec<u8>>(); let canvas_data = match canvas_fragment_info.renderer { Some(ref renderer) => { - renderer.lock().send(SendPixelContents(sender)); - receiver.recv() + renderer.lock().unwrap().send(SendPixelContents(sender)); + receiver.recv().unwrap() }, None => repeat(0xFFu8).take(width * height * 4).collect(), }; @@ -916,7 +918,7 @@ impl FragmentDisplayListBuilding for Fragment { Size2D(geometry::to_frac_px(content_size.width) as f32, geometry::to_frac_px(content_size.height) as f32)); - debug!("finalizing position and size of iframe for {},{}", + debug!("finalizing position and size of iframe for {:?},{:?}", iframe_fragment.pipeline_id, iframe_fragment.subpage_id); let ConstellationChan(ref chan) = layout_context.shared.constellation_chan; @@ -1276,7 +1278,7 @@ impl ListItemFlowDisplayListBuilding for ListItemFlow { } // A helper data structure for gradients. -#[deriving(Copy)] +#[derive(Copy)] struct StopRun { start_offset: f32, end_offset: f32, @@ -1300,7 +1302,7 @@ fn position_to_offset(position: LengthOrPercentage, Au(total_length): Au) -> f32 } /// "Steps" as defined by CSS 2.1 § E.2. -#[deriving(Clone, PartialEq, Show, Copy)] +#[derive(Clone, PartialEq, Show, Copy)] pub enum StackingLevel { /// The border and backgrounds for the root of this stacking context: steps 1 and 2. BackgroundAndBorders, diff --git a/components/layout/floats.rs b/components/layout/floats.rs index 5d82014f779..10a057f172e 100644 --- a/components/layout/floats.rs +++ b/components/layout/floats.rs @@ -12,7 +12,7 @@ use std::fmt; use style::computed_values::float; /// The kind of float: left or right. -#[deriving(Clone, Encodable, Show, Copy)] +#[derive(Clone, RustcEncodable, Show, Copy)] pub enum FloatKind { Left, Right @@ -29,7 +29,7 @@ impl FloatKind { } /// The kind of clearance: left, right, or both. -#[deriving(Copy)] +#[derive(Copy)] pub enum ClearType { Left, Right, @@ -37,7 +37,7 @@ pub enum ClearType { } /// Information about a single float. -#[deriving(Clone, Copy)] +#[derive(Clone, Copy)] struct Float { /// The boundaries of this float. bounds: LogicalRect<Au>, @@ -47,12 +47,12 @@ struct Float { impl fmt::Show for Float { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "bounds={} kind={}", self.bounds, self.kind) + write!(f, "bounds={:?} kind={:?}", self.bounds, self.kind) } } /// Information about the floats next to a flow. -#[deriving(Clone)] +#[derive(Clone)] struct FloatList { /// Information about each of the floats here. floats: PersistentList<Float>, @@ -77,7 +77,7 @@ impl FloatList { impl fmt::Show for FloatList { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "max_block_start={} floats={}", self.max_block_start, self.floats.len()) + write!(f, "max_block_start={:?} floats={}", self.max_block_start, self.floats.len()) } } @@ -96,7 +96,7 @@ pub struct PlacementInfo { impl fmt::Show for PlacementInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, - "size={} ceiling={} max_inline_size={} kind={}", + "size={:?} ceiling={:?} max_inline_size={:?} kind={:?}", self.size, self.ceiling, self.max_inline_size, @@ -110,7 +110,7 @@ fn range_intersect(block_start_1: Au, block_end_1: Au, block_start_2: Au, block_ /// Encapsulates information about floats. This is optimized to avoid allocation if there are /// no floats, and to avoid copying when translating the list of floats downward. -#[deriving(Clone)] +#[derive(Clone)] pub struct Floats { /// The list of floats. list: FloatList, @@ -125,7 +125,7 @@ impl fmt::Show for Floats { if !self.list.is_present() { write!(f, "[empty]") } else { - write!(f, "offset={} floats={}", self.offset, self.list) + write!(f, "offset={:?} floats={:?}", self.offset, self.list) } } } @@ -166,7 +166,7 @@ impl Floats { let list = &self.list; let block_start = block_start - self.offset.block; - debug!("available_rect: trying to find space at {}", block_start); + debug!("available_rect: trying to find space at {:?}", block_start); // Relevant dimensions for the inline-end-most inline-start float let mut max_inline_start = Au(0) - self.offset.inline; @@ -183,7 +183,7 @@ impl Floats { let float_pos = float.bounds.start; let float_size = float.bounds.size; - debug!("float_pos: {}, float_size: {}", float_pos, float_size); + debug!("float_pos: {:?}, float_size: {:?}", float_pos, float_size); match float.kind { FloatKind::Left if float_pos.i + float_size.inline > max_inline_start && float_pos.b + float_size.block > block_start && @@ -194,7 +194,7 @@ impl Floats { l_block_end = Some(float_pos.b + float_size.block); debug!("available_rect: collision with inline_start float: new \ - max_inline_start is {}", + max_inline_start is {:?}", max_inline_start); } FloatKind::Right if float_pos.i < min_inline_end && @@ -205,7 +205,7 @@ impl Floats { r_block_start = Some(float_pos.b); r_block_end = Some(float_pos.b + float_size.block); debug!("available_rect: collision with inline_end float: new min_inline_end \ - is {}", + is {:?}", min_inline_end); } FloatKind::Left | FloatKind::Right => {} @@ -262,7 +262,7 @@ impl Floats { } } - debug!("add_float: added float with info {}", new_info); + debug!("add_float: added float with info {:?}", new_info); let new_float = Float { bounds: LogicalRect::from_point_size( @@ -303,7 +303,7 @@ impl Floats { /// Given placement information, finds the closest place a fragment can be positioned without /// colliding with any floats. pub fn place_between_floats(&self, info: &PlacementInfo) -> LogicalRect<Au> { - debug!("place_between_floats: Placing object with {}", info.size); + debug!("place_between_floats: Placing object with {:?}", info.size); // If no floats, use this fast path. if !self.list.is_present() { @@ -333,7 +333,7 @@ impl Floats { let maybe_location = self.available_rect(float_b, info.size.block, info.max_inline_size); - debug!("place_float: Got available rect: {} for y-pos: {}", maybe_location, float_b); + debug!("place_float: Got available rect: {:?} for y-pos: {:?}", maybe_location, float_b); match maybe_location { // If there are no floats blocking us, return the current location // TODO(eatkinson): integrate with overflow diff --git a/components/layout/flow.rs b/components/layout/flow.rs index 8c7588f0666..c87088bf829 100644 --- a/components/layout/flow.rs +++ b/components/layout/flow.rs @@ -55,9 +55,10 @@ use servo_util::logical_geometry::{LogicalRect, LogicalSize, WritingMode}; use std::mem; use std::fmt; use std::iter::Zip; +use std::num::FromPrimitive; use std::raw; use std::sync::atomic::{AtomicUint, Ordering}; -use std::slice::MutItems; +use std::slice::IterMut; use style::computed_values::{clear, empty_cells, float, position, text_align}; use style::ComputedValues; use std::sync::Arc; @@ -66,7 +67,7 @@ use std::sync::Arc; /// /// Note that virtual methods have a cost; we should not overuse them in Servo. Consider adding /// methods to `ImmutableFlowUtils` or `MutableFlowUtils` before adding more methods here. -pub trait Flow: fmt::Show + ToString + Sync { +pub trait Flow: fmt::Show + Sync { // RTTI // // TODO(pcwalton): Use Rust's RTTI, once that works. @@ -82,7 +83,7 @@ pub trait Flow: fmt::Show + ToString + Sync { /// If this is a block flow, returns the underlying object. Fails otherwise. fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { - debug!("called as_block() on a flow of type {}", self.class()); + debug!("called as_block() on a flow of type {:?}", self.class()); panic!("called as_block() on a non-block flow") } @@ -204,10 +205,10 @@ pub trait Flow: fmt::Show + ToString + Sync { fn assign_block_size_for_inorder_child_if_necessary<'a>(&mut self, layout_context: &'a LayoutContext<'a>) -> bool { - let impacted = base(&*self).flags.impacted_by_floats(); + let impacted = base(self).flags.impacted_by_floats(); if impacted { self.assign_block_size(layout_context); - mut_base(&mut *self).restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW); + mut_base(self).restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW); } impacted } @@ -295,7 +296,8 @@ pub trait Flow: fmt::Show + ToString + Sync { /// Returns a layer ID for the given fragment. fn layer_id(&self, fragment_id: uint) -> LayerId { unsafe { - let pointer: uint = mem::transmute(self); + let obj = mem::transmute::<&&Self, &raw::TraitObject>(&self); + let pointer: uint = mem::transmute(obj.data); LayerId(pointer, fragment_id) } } @@ -308,9 +310,9 @@ pub trait Flow: fmt::Show + ToString + Sync { // Base access #[inline(always)] -pub fn base<'a>(this: &'a Flow) -> &'a BaseFlow { +pub fn base<'a, T: ?Sized + Flow>(this: &'a T) -> &'a BaseFlow { unsafe { - let obj = mem::transmute::<&'a Flow, raw::TraitObject>(this); + let obj = mem::transmute::<&&'a T, &'a raw::TraitObject>(&this); mem::transmute::<*mut (), &'a BaseFlow>(obj.data) } } @@ -321,9 +323,9 @@ pub fn imm_child_iter<'a>(flow: &'a Flow) -> FlowListIterator<'a> { } #[inline(always)] -pub fn mut_base<'a>(this: &'a mut Flow) -> &'a mut BaseFlow { +pub fn mut_base<'a, T: ?Sized + Flow>(this: &'a mut T) -> &'a mut BaseFlow { unsafe { - let obj = mem::transmute::<&'a mut Flow, raw::TraitObject>(this); + let obj = mem::transmute::<&&'a mut T, &'a raw::TraitObject>(&this); mem::transmute::<*mut (), &'a mut BaseFlow>(obj.data) } } @@ -423,7 +425,7 @@ pub trait MutableOwnedFlowUtils { fn set_absolute_descendants(&mut self, abs_descendants: AbsDescendants); } -#[deriving(Encodable, PartialEq, Show)] +#[derive(RustcEncodable, PartialEq, Show)] pub enum FlowClass { Block, Inline, @@ -465,7 +467,6 @@ pub trait PostorderFlowTraversal { bitflags! { #[doc = "Flags used in flows."] - #[deriving(Copy)] flags FlowFlags: u16 { // floated descendants flags #[doc = "Whether this flow has descendants that float left in the same block formatting"] @@ -540,7 +541,7 @@ impl FlowFlags { #[inline] pub fn set_text_align(&mut self, value: text_align::T) { *self = (*self & !TEXT_ALIGN) | - FlowFlags::from_bits(value as u16 << TEXT_ALIGN_SHIFT).unwrap(); + FlowFlags::from_bits((value as u16) << TEXT_ALIGN_SHIFT).unwrap(); } #[inline] @@ -592,7 +593,7 @@ impl FlowFlags { /// The Descendants of a flow. /// /// Also, details about their position wrt this flow. -#[deriving(Clone)] +#[derive(Clone)] pub struct Descendants { /// Links to every descendant. This must be private because it is unsafe to leak `FlowRef`s to /// layout. @@ -650,20 +651,21 @@ impl Descendants { pub type AbsDescendants = Descendants; pub struct DescendantIter<'a> { - iter: MutItems<'a, FlowRef>, + iter: IterMut<'a, FlowRef>, } -impl<'a> Iterator<&'a mut (Flow + 'a)> for DescendantIter<'a> { +impl<'a> Iterator for DescendantIter<'a> { + type Item = &'a mut (Flow + 'a); fn next(&mut self) -> Option<&'a mut (Flow + 'a)> { self.iter.next().map(|flow| &mut **flow) } } -pub type DescendantOffsetIter<'a> = Zip<DescendantIter<'a>, MutItems<'a, Au>>; +pub type DescendantOffsetIter<'a> = Zip<DescendantIter<'a>, IterMut<'a, Au>>; /// Information needed to compute absolute (i.e. viewport-relative) flow positions (not to be /// confused with absolutely-positioned flows). -#[deriving(Encodable, Copy)] +#[derive(RustcEncodable, Copy)] pub struct AbsolutePositionInfo { /// The size of the containing block for relatively-positioned descendants. pub relative_containing_block_size: LogicalSize<Au>, @@ -776,33 +778,36 @@ pub struct BaseFlow { pub flags: FlowFlags, } +unsafe impl Send for BaseFlow {} +unsafe impl Sync for BaseFlow {} + impl fmt::Show for BaseFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, - "@ {}, CC {}, ADC {}", + "@ {:?}, CC {}, ADC {}", self.position, self.parallel.children_count.load(Ordering::SeqCst), self.abs_descendants.len()) } } -impl<E, S: Encoder<E>> Encodable<S, E> for BaseFlow { - fn encode(&self, e: &mut S) -> Result<(), E> { +impl Encodable for BaseFlow { + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_struct("base", 0, |e| { - try!(e.emit_struct_field("id", 0, |e| self.debug_id().encode(e))) + try!(e.emit_struct_field("id", 0, |e| self.debug_id().encode(e))); try!(e.emit_struct_field("stacking_relative_position", 1, - |e| self.stacking_relative_position.encode(e))) + |e| self.stacking_relative_position.encode(e))); try!(e.emit_struct_field("intrinsic_inline_sizes", 2, - |e| self.intrinsic_inline_sizes.encode(e))) - try!(e.emit_struct_field("position", 3, |e| self.position.encode(e))) + |e| self.intrinsic_inline_sizes.encode(e))); + try!(e.emit_struct_field("position", 3, |e| self.position.encode(e))); e.emit_struct_field("children", 4, |e| { e.emit_seq(self.children.len(), |e| { for (i, c) in self.children.iter().enumerate() { try!(e.emit_seq_elt(i, |e| { try!(e.emit_struct("flow", 0, |e| { - try!(e.emit_struct_field("class", 0, |e| c.class().encode(e))) + try!(e.emit_struct_field("class", 0, |e| c.class().encode(e))); e.emit_struct_field("data", 1, |e| { match c.class() { FlowClass::Block => c.as_immutable_block().encode(e), @@ -815,9 +820,9 @@ impl<E, S: Encoder<E>> Encodable<S, E> for BaseFlow { _ => { Ok(()) } // TODO: Support captions } }) - })) + })); Ok(()) - })) + })); } Ok(()) }) @@ -838,7 +843,7 @@ impl Drop for BaseFlow { /// Whether a base flow should be forced to be nonfloated. This can affect e.g. `TableFlow`, which /// is never floated because the table wrapper flow is the floated one. -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub enum ForceNonfloatedFlag { /// The flow should be floated if the node has a `float` property. FloatIfNecessary, @@ -951,7 +956,7 @@ impl BaseFlow { } if bounds.union(&paint_bounds.bounding_rect()) != bounds { - error!("DisplayList item {} outside of Flow overflow ({})", item, paint_bounds); + error!("DisplayList item {:?} outside of Flow overflow ({:?})", item, paint_bounds); } } } @@ -1125,7 +1130,8 @@ impl<'a> ImmutableFlowUtils for &'a (Flow + 'a) { indent.push_str("| ") } - println!("{}+ {}", indent, self.to_string()); + // TODO: ICE, already fixed in rustc. + //println!("{}+ {:?}", indent, self); for kid in imm_child_iter(self) { kid.dump_with_level(level + 1) diff --git a/components/layout/flow_list.rs b/components/layout/flow_list.rs index 63522a06caa..4011cd4c400 100644 --- a/components/layout/flow_list.rs +++ b/components/layout/flow_list.rs @@ -15,11 +15,11 @@ pub struct FlowList { } pub struct FlowListIterator<'a> { - it: dlist::Items<'a, FlowRef>, + it: dlist::Iter<'a, FlowRef>, } pub struct MutFlowListIterator<'a> { - it: dlist::MutItems<'a, FlowRef>, + it: dlist::IterMut<'a, FlowRef>, } impl FlowList { @@ -105,7 +105,8 @@ impl FlowList { } } -impl<'a> Iterator<&'a (Flow + 'a)> for FlowListIterator<'a> { +impl<'a> Iterator for FlowListIterator<'a> { + type Item = &'a (Flow + 'a); #[inline] fn next(&mut self) -> Option<&'a (Flow + 'a)> { self.it.next().map(|x| &**x) @@ -117,7 +118,8 @@ impl<'a> Iterator<&'a (Flow + 'a)> for FlowListIterator<'a> { } } -impl<'a> Iterator<&'a mut (Flow + 'a)> for MutFlowListIterator<'a> { +impl<'a> Iterator for MutFlowListIterator<'a> { + type Item = &'a mut (Flow + 'a); #[inline] fn next(&mut self) -> Option<&'a mut (Flow + 'a)> { self.it.next().map(|x| &mut **x) diff --git a/components/layout/flow_ref.rs b/components/layout/flow_ref.rs index 7ee600919b0..029f7fade89 100644 --- a/components/layout/flow_ref.rs +++ b/components/layout/flow_ref.rs @@ -10,6 +10,7 @@ use flow::Flow; use flow; use std::mem; +use std::ops::{Deref, DerefMut}; use std::ptr; use std::raw; use std::sync::atomic::Ordering; @@ -19,6 +20,9 @@ pub struct FlowRef { object: raw::TraitObject, } +unsafe impl Send for FlowRef {} +unsafe impl Sync for FlowRef {} + impl FlowRef { pub fn new(mut flow: Box<Flow>) -> FlowRef { unsafe { @@ -33,7 +37,8 @@ impl FlowRef { } } -impl<'a> Deref<Flow + 'a> for FlowRef { +impl<'a> Deref for FlowRef { + type Target = Flow + 'a; fn deref(&self) -> &(Flow + 'a) { unsafe { mem::transmute_copy::<raw::TraitObject, &(Flow + 'a)>(&self.object) @@ -41,7 +46,7 @@ impl<'a> Deref<Flow + 'a> for FlowRef { } } -impl<'a> DerefMut<Flow + 'a> for FlowRef { +impl<'a> DerefMut for FlowRef { fn deref_mut<'a>(&mut self) -> &mut (Flow + 'a) { unsafe { mem::transmute_copy::<raw::TraitObject, &mut (Flow + 'a)>(&self.object) diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index 2eb26244059..c9bcb487821 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -39,8 +39,10 @@ use servo_util::smallvec::SmallVec; use servo_util::str::is_whitespace; use std::cmp::{max, min}; use std::fmt; +use std::num::ToPrimitive; use std::str::FromStr; use std::sync::{Arc, Mutex}; +use std::sync::mpsc::Sender; use string_cache::Atom; use style::{ComputedValues, TElement, TNode, cascade_anonymous}; use style::computed_values::{LengthOrPercentage, LengthOrPercentageOrAuto}; @@ -75,7 +77,7 @@ use url::Url; /// /// FIXME(#2260, pcwalton): This can be slimmed down some by (at least) moving `inline_context` /// to be on `InlineFlow` only. -#[deriving(Clone)] +#[derive(Clone)] pub struct Fragment { /// An opaque reference to the DOM node that this `Fragment` originates from. pub node: OpaqueNode, @@ -111,11 +113,14 @@ pub struct Fragment { pub restyle_damage: RestyleDamage, } -impl<E, S: Encoder<E>> Encodable<S, E> for Fragment { - fn encode(&self, e: &mut S) -> Result<(), E> { +unsafe impl Send for Fragment {} +unsafe impl Sync for Fragment {} + +impl Encodable for Fragment { + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_struct("fragment", 0, |e| { - try!(e.emit_struct_field("id", 0, |e| self.debug_id().encode(e))) - try!(e.emit_struct_field("border_box", 1, |e| self.border_box.encode(e))) + try!(e.emit_struct_field("id", 0, |e| self.debug_id().encode(e))); + try!(e.emit_struct_field("border_box", 1, |e| self.border_box.encode(e))); e.emit_struct_field("margin", 2, |e| self.margin.encode(e)) }) } @@ -124,7 +129,7 @@ impl<E, S: Encoder<E>> Encodable<S, E> for Fragment { /// Info specific to the kind of fragment. /// /// Keep this enum small. As in, no more than one word. Or pcwalton will yell at you. -#[deriving(Clone)] +#[derive(Clone)] pub enum SpecificFragmentInfo { Generic, Iframe(Box<IframeFragmentInfo>), @@ -191,7 +196,7 @@ impl SpecificFragmentInfo { /// /// FIXME(pcwalton): Stop leaking this `FlowRef` to layout; that is not memory safe because layout /// can clone it. -#[deriving(Clone)] +#[derive(Clone)] pub struct InlineAbsoluteHypotheticalFragmentInfo { pub flow_ref: FlowRef, } @@ -208,7 +213,7 @@ impl InlineAbsoluteHypotheticalFragmentInfo { /// /// FIXME(pcwalton): Stop leaking this `FlowRef` to layout; that is not memory safe because layout /// can clone it. -#[deriving(Clone)] +#[derive(Clone)] pub struct InlineBlockFragmentInfo { pub flow_ref: FlowRef, } @@ -221,7 +226,7 @@ impl InlineBlockFragmentInfo { } } -#[deriving(Clone)] +#[derive(Clone)] pub struct CanvasFragmentInfo { pub replaced_image_fragment_info: ReplacedImageFragmentInfo, pub renderer: Option<Arc<Mutex<Sender<CanvasMsg>>>>, @@ -250,7 +255,7 @@ impl CanvasFragmentInfo { /// A fragment that represents a replaced content image and its accompanying borders, shadows, etc. -#[deriving(Clone)] +#[derive(Clone)] pub struct ImageFragmentInfo { /// The image held within this fragment. pub replaced_image_fragment_info: ReplacedImageFragmentInfo, @@ -309,7 +314,7 @@ impl ImageFragmentInfo { } } -#[deriving(Clone)] +#[derive(Clone)] pub struct ReplacedImageFragmentInfo { pub for_node: UntrustedNodeAddress, pub computed_inline_size: Option<Au>, @@ -479,7 +484,7 @@ impl ReplacedImageFragmentInfo { /// A fragment that represents an inline frame (iframe). This stores the pipeline ID so that the size /// of this iframe can be communicated via the constellation to the iframe's own layout task. -#[deriving(Clone)] +#[derive(Clone)] pub struct IframeFragmentInfo { /// The pipeline ID of this iframe. pub pipeline_id: PipelineId, @@ -502,7 +507,7 @@ impl IframeFragmentInfo { /// may be split into two or more fragments across line breaks. Several `TextFragment`s may /// correspond to a single DOM text node. Split text fragments are implemented by referring to /// subsets of a single `TextRun` object. -#[deriving(Clone)] +#[derive(Clone)] pub struct ScannedTextFragmentInfo { /// The text run that this represents. pub run: Arc<Box<TextRun>>, @@ -543,7 +548,7 @@ impl ScannedTextFragmentInfo { /// Describes how to split a fragment. This is used during line breaking as part of the return /// value of `find_split_info_for_inline_size()`. -#[deriving(Show, Clone)] +#[derive(Show, Clone)] pub struct SplitInfo { // TODO(bjz): this should only need to be a single character index, but both values are // currently needed for splitting in the `inline::try_append_*` functions. @@ -572,7 +577,7 @@ pub struct SplitResult { /// Data for an unscanned text fragment. Unscanned text fragments are the results of flow /// construction that have not yet had their inline-size determined. -#[deriving(Clone)] +#[derive(Clone)] pub struct UnscannedTextFragmentInfo { /// The text inside the fragment. /// @@ -600,7 +605,7 @@ impl UnscannedTextFragmentInfo { } /// A fragment that represents a table column. -#[deriving(Copy, Clone)] +#[derive(Copy, Clone)] pub struct TableColumnFragmentInfo { /// the number of columns a <col> element should span pub span: int, @@ -743,7 +748,7 @@ impl Fragment { /// if called on any other type of fragment. pub fn save_new_line_pos(&mut self) { match &mut self.specific { - &SpecificFragmentInfo::ScannedText(ref mut info) => { + &mut SpecificFragmentInfo::ScannedText(ref mut info) => { if !info.new_line_pos.is_empty() { info.original_new_line_pos = Some(info.new_line_pos.clone()); } @@ -754,7 +759,7 @@ impl Fragment { pub fn restore_new_line_pos(&mut self) { match &mut self.specific { - &SpecificFragmentInfo::ScannedText(ref mut info) => { + &mut SpecificFragmentInfo::ScannedText(ref mut info) => { match info.original_new_line_pos.take() { None => {} Some(new_line_pos) => info.new_line_pos = new_line_pos, @@ -1278,7 +1283,7 @@ impl Fragment { } SpecificFragmentInfo::ScannedText(ref text_fragment_info) => { let mut new_line_pos = text_fragment_info.new_line_pos.clone(); - let cur_new_line_pos = new_line_pos.remove(0).unwrap(); + let cur_new_line_pos = new_line_pos.remove(0); let inline_start_range = Range::new(text_fragment_info.range.begin(), cur_new_line_pos); @@ -1355,7 +1360,7 @@ impl Fragment { max_inline_size: Au, flags: SplitOptions) -> Option<SplitResult> - where I: Iterator<TextRunSlice<'a>> { + where I: Iterator<Item=TextRunSlice<'a>> { let text_fragment_info = if let SpecificFragmentInfo::ScannedText(ref text_fragment_info) = self.specific { text_fragment_info @@ -1368,15 +1373,15 @@ impl Fragment { let mut inline_start_range = Range::new(text_fragment_info.range.begin(), CharIndex(0)); let mut inline_end_range = None; - debug!("calculate_split_position: splitting text fragment (strlen={}, range={}, \ - max_inline_size={})", + debug!("calculate_split_position: splitting text fragment (strlen={}, range={:?}, \ + max_inline_size={:?})", text_fragment_info.run.text.len(), text_fragment_info.range, max_inline_size); for slice in slice_iterator { - debug!("calculate_split_position: considering slice (offset={}, slice range={}, \ - remaining_inline_size={})", + debug!("calculate_split_position: considering slice (offset={:?}, slice range={:?}, \ + remaining_inline_size={:?})", slice.offset, slice.range, remaining_inline_size); @@ -1408,7 +1413,7 @@ impl Fragment { let mut inline_end = slice.text_run_range(); inline_end.extend_to(text_fragment_info.range.end()); inline_end_range = Some(inline_end); - debug!("calculate_split_position: splitting remainder with inline-end range={}", + debug!("calculate_split_position: splitting remainder with inline-end range={:?}", inline_end); } @@ -1816,9 +1821,9 @@ impl Fragment { impl fmt::Show for Fragment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "({} {} ", self.debug_id(), self.specific.get_type())); - try!(write!(f, "bp {}", self.border_padding)); + try!(write!(f, "bp {:?}", self.border_padding)); try!(write!(f, " ")); - try!(write!(f, "m {}", self.margin)); + try!(write!(f, "m {:?}", self.margin)); write!(f, ")") } } @@ -1856,7 +1861,7 @@ pub trait FragmentBorderBoxIterator { /// The coordinate system used in `stacking_relative_border_box()`. See the documentation of that /// method for details. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub enum CoordinateSystem { /// The border box returned is relative to the fragment's parent stacking context. Parent, diff --git a/components/layout/incremental.rs b/components/layout/incremental.rs index 6949063d41b..2ce9df833c0 100644 --- a/components/layout/incremental.rs +++ b/components/layout/incremental.rs @@ -12,7 +12,6 @@ use style::ComputedValues; bitflags! { #[doc = "Individual layout actions that may be necessary after restyling."] - #[deriving(Copy)] flags RestyleDamage: u8 { #[doc = "Repaint the node itself."] #[doc = "Currently unused; need to decide how this propagates."] @@ -125,7 +124,7 @@ macro_rules! add_if_not_equal( $damage.insert($($effect)|*); } }) -) +); pub fn compute_damage(old: &Option<Arc<ComputedValues>>, new: &ComputedValues) -> RestyleDamage { let old: &ComputedValues = diff --git a/components/layout/inline.rs b/components/layout/inline.rs index 5944759f053..aadcd1b310e 100644 --- a/components/layout/inline.rs +++ b/components/layout/inline.rs @@ -31,6 +31,8 @@ use servo_util::range::{Range, RangeIndex}; use std::cmp::max; use std::fmt; use std::mem; +use std::num::ToPrimitive; +use std::ops::{Add, Sub, Mul, Div, Rem, Neg, Shl, Shr, Not, BitOr, BitAnd, BitXor}; use std::u16; use style::computed_values::{text_align, vertical_align, white_space}; use style::ComputedValues; @@ -65,7 +67,7 @@ static FONT_SUPERSCRIPT_OFFSET_RATIO: f64 = 0.34; /// with a float or a horizontal wall of the containing block. The block-start /// inline-start corner of the green zone is the same as that of the line, but /// the green zone can be taller and wider than the line itself. -#[deriving(Encodable, Show, Copy)] +#[derive(RustcEncodable, Show, Copy)] pub struct Line { /// A range of line indices that describe line breaks. /// @@ -150,7 +152,7 @@ pub struct Line { } int_range_index! { - #[deriving(Encodable)] + #[derive(RustcEncodable)] #[doc = "The index of a fragment in a flattened vector of DOM elements."] struct FragmentIndex(int) } @@ -256,7 +258,7 @@ impl LineBreaker { mut old_fragment_iter: I, flow: &'a InlineFlow, layout_context: &LayoutContext) - where I: Iterator<Fragment> { + where I: Iterator<Item=Fragment> { loop { // Acquire the next fragment to lay out from the work list or fragment list, as // appropriate. @@ -305,18 +307,18 @@ impl LineBreaker { /// Note that you probably don't want to call this method directly in order to be /// incremental-reflow-safe; try `next_unbroken_fragment` instead. fn next_fragment<I>(&mut self, old_fragment_iter: &mut I) -> Option<Fragment> - where I: Iterator<Fragment> { + where I: Iterator<Item=Fragment> { if self.work_list.is_empty() { return match old_fragment_iter.next() { None => None, Some(fragment) => { - debug!("LineBreaker: working with fragment from flow: {}", fragment); + debug!("LineBreaker: working with fragment from flow: {:?}", fragment); Some(fragment) } } } - debug!("LineBreaker: working with fragment from work list: {}", self.work_list.front()); + debug!("LineBreaker: working with fragment from work list: {:?}", self.work_list.front()); self.work_list.pop_front() } @@ -325,7 +327,7 @@ impl LineBreaker { /// fragment to lay out, undoing line break operations that any previous reflows may have /// performed. You probably want to be using this method instead of `next_fragment`. fn next_unbroken_fragment<I>(&mut self, old_fragment_iter: &mut I) -> Option<Fragment> - where I: Iterator<Fragment> { + where I: Iterator<Item=Fragment> { let mut result = match self.next_fragment(old_fragment_iter) { None => return None, Some(fragment) => fragment, @@ -342,7 +344,7 @@ impl LineBreaker { }; let need_to_merge = match (&mut result.specific, &candidate.specific) { - (&SpecificFragmentInfo::ScannedText(ref mut result_info), + (&mut SpecificFragmentInfo::ScannedText(ref mut result_info), &SpecificFragmentInfo::ScannedText(ref candidate_info)) if arc_ptr_eq(&result_info.run, &candidate_info.run) && result_info.range.end() + CharIndex(1) == candidate_info.range.begin() => { @@ -362,7 +364,7 @@ impl LineBreaker { /// Commits a line to the list. fn flush_current_line(&mut self) { - debug!("LineBreaker: flushing line {}: {}", self.lines.len(), self.pending_line); + debug!("LineBreaker: flushing line {}: {:?}", self.lines.len(), self.pending_line); self.lines.push(self.pending_line); self.cur_b = self.pending_line.bounds.start.b + self.pending_line.bounds.size.block; self.reset_line(); @@ -388,7 +390,7 @@ impl LineBreaker { first_fragment: &Fragment, ceiling: Au) -> (LogicalRect<Au>, Au) { - debug!("LineBreaker: trying to place first fragment of line {}; fragment size: {}, \ + debug!("LineBreaker: trying to place first fragment of line {}; fragment size: {:?}, \ splittable: {}", self.lines.len(), first_fragment.border_box.size, @@ -496,7 +498,7 @@ impl LineBreaker { .expect("LineBreaker: this split case makes no sense!"); let writing_mode = self.floats.writing_mode; - let split_fragment = |split: SplitInfo| { + let split_fragment = |&:split: SplitInfo| { let info = box ScannedTextFragmentInfo::new(run.clone(), split.range, (*in_fragment.newline_positions() @@ -541,7 +543,7 @@ impl LineBreaker { self.pending_line.green_zone = line_bounds.size; } - debug!("LineBreaker: trying to append to line {} (fragment size: {}, green zone: {}): {}", + debug!("LineBreaker: trying to append to line {} (fragment size: {:?}, green zone: {:?}): {:?}", self.lines.len(), fragment.border_box.size, self.pending_line.green_zone, @@ -586,13 +588,13 @@ impl LineBreaker { match fragment.calculate_split_position(available_inline_size, self.pending_line_is_empty()) { None => { - debug!("LineBreaker: fragment was unsplittable; deferring to next line: {}", + debug!("LineBreaker: fragment was unsplittable; deferring to next line: {:?}", fragment); self.work_list.push_front(fragment); return false } Some(split_result) => { - let split_fragment = |split: SplitInfo| { + let split_fragment = |&:split: SplitInfo| { let info = box ScannedTextFragmentInfo::new(split_result.text_run.clone(), split.range, Vec::new(), @@ -657,7 +659,7 @@ impl LineBreaker { } /// Represents a list of inline fragments, including element ranges. -#[deriving(Encodable, Clone)] +#[derive(RustcEncodable, Clone)] pub struct InlineFragments { /// The fragments themselves. pub fragments: Vec<Fragment>, @@ -665,7 +667,7 @@ pub struct InlineFragments { impl fmt::Show for InlineFragments { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.fragments) + write!(f, "{:?}", self.fragments) } } @@ -711,7 +713,7 @@ impl InlineFragments { } /// Flows for inline layout. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct InlineFlow { /// Data common to all flows. pub base: BaseFlow, @@ -966,7 +968,7 @@ impl Flow for InlineFlow { let mut computation = IntrinsicISizesContribution::new(); for fragment in self.fragments.fragments.iter_mut() { - debug!("Flow: measuring {}", *fragment); + debug!("Flow: measuring {:?}", *fragment); computation.union_inline(&fragment.compute_intrinsic_inline_sizes().finish()) } self.base.intrinsic_inline_sizes = computation.finish() @@ -982,7 +984,7 @@ impl Flow for InlineFlow { // TODO: Combine this with `LineBreaker`'s walk in the fragment list, or put this into // `Fragment`. - debug!("InlineFlow::assign_inline_sizes: floats in: {}", self.base.floats); + debug!("InlineFlow::assign_inline_sizes: floats in: {:?}", self.base.floats); self.base.position.size.inline = self.base.block_container_inline_size; @@ -1022,7 +1024,7 @@ impl Flow for InlineFlow { // element to determine its block-size for computing the line's own block-size. // // TODO(pcwalton): Cache the line scanner? - debug!("assign_block_size_inline: floats in: {}", self.base.floats); + debug!("assign_block_size_inline: floats in: {:?}", self.base.floats); // Assign the block-size for the inline fragments. let containing_block_block_size = @@ -1254,11 +1256,11 @@ impl Flow for InlineFlow { impl fmt::Show for InlineFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{} - {:x} - {}", self.class(), self.base.debug_id(), self.fragments) + write!(f, "{:?} - {:x} - {:?}", self.class(), self.base.debug_id(), self.fragments) } } -#[deriving(Clone)] +#[derive(Clone)] pub struct InlineFragmentContext { pub styles: Vec<Arc<ComputedValues>>, } diff --git a/components/layout/layout_debug.rs b/components/layout/layout_debug.rs index 26d2f8b3ef7..5f0851b1f36 100644 --- a/components/layout/layout_debug.rs +++ b/components/layout/layout_debug.rs @@ -14,11 +14,11 @@ use serialize::json; use std::borrow::ToOwned; use std::cell::RefCell; use std::io::File; -use std::sync::atomic::{AtomicUint, Ordering, INIT_ATOMIC_UINT}; +use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT}; -thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None)) +thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None)); -static mut DEBUG_ID_COUNTER: AtomicUint = INIT_ATOMIC_UINT; +static mut DEBUG_ID_COUNTER: AtomicUint = ATOMIC_UINT_INIT; pub struct Scope; @@ -31,9 +31,9 @@ macro_rules! layout_debug_scope( layout_debug::Scope } ) -) +); -#[deriving(Encodable)] +#[derive(RustcEncodable)] struct ScopeData { name: String, pre: String, @@ -63,12 +63,12 @@ impl Scope { pub fn new(name: String) -> Scope { STATE_KEY.with(|ref r| { match &mut *r.borrow_mut() { - &Some(ref mut state) => { + &mut Some(ref mut state) => { let flow_trace = json::encode(&flow::base(&*state.flow_root)); let data = box ScopeData::new(name.clone(), flow_trace); state.scope_stack.push(data); } - &None => {} + &mut None => {} } }); Scope @@ -80,13 +80,13 @@ impl Drop for Scope { fn drop(&mut self) { STATE_KEY.with(|ref r| { match &mut *r.borrow_mut() { - &Some(ref mut state) => { + &mut Some(ref mut state) => { let mut current_scope = state.scope_stack.pop().unwrap(); current_scope.post = json::encode(&flow::base(&*state.flow_root)); let previous_scope = state.scope_stack.last_mut().unwrap(); previous_scope.children.push(current_scope); } - &None => {} + &mut None => {} } }); } diff --git a/components/layout/layout_task.rs b/components/layout/layout_task.rs index 6d91a303ecf..acfd53d4e15 100644 --- a/components/layout/layout_task.rs +++ b/components/layout/layout_task.rs @@ -7,7 +7,7 @@ use css::node_style::StyledNode; use construct::ConstructionResult; -use context::SharedLayoutContext; +use context::{SharedLayoutContext, SharedLayoutContextWrapper}; use flow::{mod, Flow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils}; use flow_ref::FlowRef; use fragment::{Fragment, FragmentBorderBoxIterator}; @@ -61,7 +61,8 @@ use servo_util::time::{TimerMetadataFrameType, TimerMetadataReflowType, profile} use servo_util::workqueue::WorkQueue; use std::borrow::ToOwned; use std::cell::Cell; -use std::comm::{channel, Sender, Receiver, Select}; +use std::ops::{Deref, DerefMut}; +use std::sync::mpsc::{channel, Sender, Receiver, Select}; use std::mem; use std::ptr; use style::computed_values::{filter, mix_blend_mode}; @@ -89,7 +90,7 @@ pub struct LayoutTaskData { pub stylist: Box<Stylist>, /// The workers that we use for parallel operation. - pub parallel_traversal: Option<WorkQueue<*const SharedLayoutContext, UnsafeFlow>>, + pub parallel_traversal: Option<WorkQueue<SharedLayoutContextWrapper, UnsafeFlow>>, /// The dirty rect. Used during display list construction. pub dirty: Rect<Au>, @@ -153,19 +154,17 @@ struct LayoutImageResponder { } impl ImageResponder<UntrustedNodeAddress> for LayoutImageResponder { - fn respond(&self) -> proc(ImageResponseMsg, UntrustedNodeAddress):Send { + fn respond(&self) -> Box<Fn(ImageResponseMsg, UntrustedNodeAddress)+Send> { let id = self.id.clone(); let script_chan = self.script_chan.clone(); - let f: proc(ImageResponseMsg, UntrustedNodeAddress):Send = - proc(_, node_address) { - let ScriptControlChan(chan) = script_chan; - debug!("Dirtying {:x}", node_address.0 as uint); - let mut nodes = SmallVec1::new(); - nodes.vec_push(node_address); - drop(chan.send_opt(ConstellationControlMsg::SendEvent( - id.clone(), CompositorEvent::ReflowEvent(nodes)))) - }; - f + box move |&:_, node_address| { + let ScriptControlChan(ref chan) = script_chan; + debug!("Dirtying {:x}", node_address.0 as uint); + let mut nodes = SmallVec1::new(); + nodes.vec_push(node_address); + drop(chan.send(ConstellationControlMsg::SendEvent( + id, CompositorEvent::ReflowEvent(nodes)))) + } } } @@ -185,7 +184,7 @@ impl LayoutTaskFactory for LayoutTask { time_profiler_chan: TimeProfilerChan, shutdown_chan: Sender<()>) { let ConstellationChan(con_chan) = constellation_chan.clone(); - spawn_named_with_send_on_failure("LayoutTask", task_state::LAYOUT, proc() { + spawn_named_with_send_on_failure("LayoutTask", task_state::LAYOUT, move || { { // Ensures layout task is destroyed before we send shutdown message let sender = chan.sender(); let layout = @@ -219,7 +218,8 @@ enum RWGuard<'a> { Used(MutexGuard<'a, LayoutTaskData>), } -impl<'a> Deref<LayoutTaskData> for RWGuard<'a> { +impl<'a> Deref for RWGuard<'a> { + type Target = LayoutTaskData; fn deref(&self) -> &LayoutTaskData { match *self { RWGuard::Held(ref x) => &**x, @@ -228,7 +228,7 @@ impl<'a> Deref<LayoutTaskData> for RWGuard<'a> { } } -impl<'a> DerefMut<LayoutTaskData> for RWGuard<'a> { +impl<'a> DerefMut for RWGuard<'a> { fn deref_mut(&mut self) -> &mut LayoutTaskData { match *self { RWGuard::Held(ref mut x) => &mut **x, @@ -257,7 +257,7 @@ impl LayoutTask { let device = Device::new(MediaType::Screen, opts::get().initial_window_size.as_f32() * ScaleFactor(1.0)); let parallel_traversal = if opts::get().layout_threads != 1 { Some(WorkQueue::new("LayoutWorker", task_state::LAYOUT, - opts::get().layout_threads, ptr::null())) + opts::get().layout_threads, SharedLayoutContextWrapper(ptr::null()))) } else { None }; @@ -292,7 +292,7 @@ impl LayoutTask { /// Starts listening on the port. fn start(self) { - let mut possibly_locked_rw_data = Some(self.rw_data.lock()); + let mut possibly_locked_rw_data = Some((*self.rw_data).lock().unwrap()); while self.handle_request(&mut possibly_locked_rw_data) { // Loop indefinitely. } @@ -347,14 +347,14 @@ impl LayoutTask { match port_to_read { PortToRead::Pipeline => { - match self.pipeline_port.recv() { + match self.pipeline_port.recv().unwrap() { LayoutControlMsg::ExitNowMsg(exit_type) => { self.handle_script_request(Msg::ExitNow(exit_type), possibly_locked_rw_data) } } }, PortToRead::Script => { - let msg = self.port.recv(); + let msg = self.port.recv().unwrap(); self.handle_script_request(msg, possibly_locked_rw_data) } } @@ -370,7 +370,7 @@ impl LayoutTask { possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) -> RWGuard<'a> { match possibly_locked_rw_data.take() { - None => RWGuard::Used(self.rw_data.lock()), + None => RWGuard::Used((*self.rw_data).lock().unwrap()), Some(x) => RWGuard::Held(x), } } @@ -434,7 +434,7 @@ impl LayoutTask { possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) { response_chan.send(()); loop { - match self.port.recv() { + match self.port.recv().unwrap() { Msg::ReapLayoutData(dead_layout_data) => { unsafe { LayoutTask::handle_reap_layout_data(dead_layout_data) @@ -470,7 +470,7 @@ impl LayoutTask { } self.paint_chan.send(PaintMsg::Exit(Some(response_chan), exit_type)); - response_port.recv() + response_port.recv().unwrap() } fn handle_load_stylesheet<'a>(&'a self, @@ -499,7 +499,7 @@ impl LayoutTask { // Find all font-face rules and notify the font cache of them. // GWTODO: Need to handle unloading web fonts (when we handle unloading stylesheets!) let mut rw_data = self.lock_rw_data(possibly_locked_rw_data); - iter_font_face_rules(&sheet, &rw_data.stylist.device, |family, src| { + iter_font_face_rules(&sheet, &rw_data.stylist.device, &|&:family, src| { self.font_cache_task.add_web_font(family.to_owned(), (*src).clone()); }); rw_data.stylist.add_stylesheet(sheet); @@ -734,7 +734,7 @@ impl LayoutTask { { // Reset the image cache. - let mut local_image_cache = rw_data.local_image_cache.lock(); + let mut local_image_cache = rw_data.local_image_cache.lock().unwrap(); local_image_cache.next_round(self.make_on_image_available_cb()); } @@ -946,14 +946,14 @@ impl LayoutRPC for LayoutRPCImpl { // need to compare nodes for equality. Thus we can safely work only with `OpaqueNode`. fn content_box(&self) -> ContentBoxResponse { let &LayoutRPCImpl(ref rw_data) = self; - let rw_data = rw_data.lock(); + let rw_data = rw_data.lock().unwrap(); ContentBoxResponse(rw_data.content_box_response) } /// Requests the dimensions of all the content boxes, as in the `getClientRects()` call. fn content_boxes(&self) -> ContentBoxesResponse { let &LayoutRPCImpl(ref rw_data) = self; - let rw_data = rw_data.lock(); + let rw_data = rw_data.lock().unwrap(); ContentBoxesResponse(rw_data.content_boxes_response.clone()) } @@ -962,7 +962,7 @@ impl LayoutRPC for LayoutRPCImpl { let point = Point2D(Au::from_frac_px(point.x as f64), Au::from_frac_px(point.y as f64)); let resp = { let &LayoutRPCImpl(ref rw_data) = self; - let rw_data = rw_data.lock(); + let rw_data = rw_data.lock().unwrap(); match rw_data.stacking_context { None => panic!("no root stacking context!"), Some(ref stacking_context) => { @@ -989,7 +989,7 @@ impl LayoutRPC for LayoutRPCImpl { let point = Point2D(Au::from_frac_px(point.x as f64), Au::from_frac_px(point.y as f64)); { let &LayoutRPCImpl(ref rw_data) = self; - let rw_data = rw_data.lock(); + let rw_data = rw_data.lock().unwrap(); match rw_data.stacking_context { None => panic!("no root stacking context!"), Some(ref stacking_context) => { diff --git a/components/layout/lib.rs b/components/layout/lib.rs index 5fc89dbd82d..17812c262c2 100644 --- a/components/layout/lib.rs +++ b/components/layout/lib.rs @@ -2,14 +2,15 @@ * 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/. */ -#![feature(globs, macro_rules, phase, thread_local, unsafe_destructor)] +#![feature(thread_local, unsafe_destructor, box_syntax, plugin, int_uint)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(unrooted_must_root)] #![allow(missing_copy_implementations)] +#![allow(unstable)] -#[phase(plugin, link)] +#[macro_use] extern crate log; extern crate cssparser; @@ -19,17 +20,19 @@ extern crate gfx; extern crate layout_traits; extern crate script; extern crate script_traits; +extern crate "serialize" as rustc_serialize; extern crate serialize; extern crate png; extern crate style; -#[phase(plugin)] +#[macro_use] +#[no_link] #[plugin] extern crate "plugins" as servo_plugins; extern crate "net" as servo_net; extern crate "msg" as servo_msg; -#[phase(plugin, link)] +#[macro_use] extern crate "util" as servo_util; -#[phase(plugin)] +#[no_link] #[macro_use] #[plugin] extern crate string_cache_macros; extern crate string_cache; diff --git a/components/layout/list_item.rs b/components/layout/list_item.rs index 296a73454ca..3c4dc8a7fc8 100644 --- a/components/layout/list_item.rs +++ b/components/layout/list_item.rs @@ -24,7 +24,7 @@ use style::computed_values::list_style_type; use std::sync::Arc; /// A block with the CSS `display` property equal to `list-item`. -#[deriving(Show)] +#[derive(Show)] pub struct ListItemFlow { /// Data common to all block flows. pub block_flow: BlockFlow, diff --git a/components/layout/model.rs b/components/layout/model.rs index a031a5b0537..b83585906ad 100644 --- a/components/layout/model.rs +++ b/components/layout/model.rs @@ -18,7 +18,7 @@ use std::cmp::{max, min}; use std::fmt; /// A collapsible margin. See CSS 2.1 § 8.3.1. -#[deriving(Copy)] +#[derive(Copy)] pub struct AdjoiningMargins { /// The value of the greatest positive margin. pub most_positive: Au, @@ -61,7 +61,7 @@ impl AdjoiningMargins { } /// Represents the block-start and block-end margins of a flow with collapsible margins. See CSS 2.1 § 8.3.1. -#[deriving(Copy)] +#[derive(Copy)] pub enum CollapsibleMargins { /// Margins may not collapse with this flow. None(Au, Au), @@ -239,14 +239,14 @@ impl MarginCollapseInfo { } } -#[deriving(Copy)] +#[derive(Copy)] pub enum MarginCollapseState { AccumulatingCollapsibleTopMargin, AccumulatingMarginIn, } /// Intrinsic inline-sizes, which consist of minimum and preferred. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct IntrinsicISizes { /// The *minimum inline-size* of the content. pub minimum_inline_size: Au, @@ -256,7 +256,7 @@ pub struct IntrinsicISizes { impl fmt::Show for IntrinsicISizes { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "min={}, pref={}", self.minimum_inline_size, self.preferred_inline_size) + write!(f, "min={:?}, pref={:?}", self.minimum_inline_size, self.preferred_inline_size) } } @@ -325,7 +325,7 @@ impl IntrinsicISizesContribution { } /// Useful helper data type when computing values for blocks and positioned elements. -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] pub enum MaybeAuto { Auto, Specified(Au), @@ -358,7 +358,7 @@ impl MaybeAuto { } #[inline] - pub fn map(&self, mapper: |Au| -> Au) -> MaybeAuto { + pub fn map<F>(&self, mapper: F) -> MaybeAuto where F: FnOnce(Au) -> Au { match *self { MaybeAuto::Auto => MaybeAuto::Auto, MaybeAuto::Specified(value) => MaybeAuto::Specified(mapper(value)), diff --git a/components/layout/parallel.rs b/components/layout/parallel.rs index 6bd59cd8cc6..05eb9168a04 100644 --- a/components/layout/parallel.rs +++ b/components/layout/parallel.rs @@ -6,7 +6,7 @@ //! //! This code is highly unsafe. Keep this file small and easy to audit. -use context::{LayoutContext, SharedLayoutContext}; +use context::{LayoutContext, SharedLayoutContextWrapper, SharedLayoutContext}; use flow::{Flow, MutableFlowUtils, PreorderFlowTraversal, PostorderFlowTraversal}; use flow; use flow_ref::FlowRef; @@ -81,17 +81,17 @@ impl DomParallelInfo { pub trait ParallelPreorderDomTraversal : PreorderDomTraversal { fn run_parallel(&self, node: UnsafeLayoutNode, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeLayoutNode>); + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeLayoutNode>); #[inline(always)] fn run_parallel_helper(&self, unsafe_node: UnsafeLayoutNode, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeLayoutNode>, + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeLayoutNode>, top_down_func: extern "Rust" fn(UnsafeFlow, - &mut WorkerProxy<*const SharedLayoutContext, + &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeLayoutNode>), bottom_up_func: extern "Rust" fn(UnsafeFlow, - &mut WorkerProxy<*const SharedLayoutContext, + &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeFlow>)) { // Get a real layout node. let node: LayoutNode = unsafe { @@ -141,7 +141,7 @@ trait ParallelPostorderDomTraversal : PostorderDomTraversal { /// fetch-and-subtract the parent's children count. fn run_parallel(&self, mut unsafe_node: UnsafeLayoutNode, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeLayoutNode>) { + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeLayoutNode>) { loop { // Get a real layout node. let node: LayoutNode = unsafe { @@ -151,7 +151,7 @@ trait ParallelPostorderDomTraversal : PostorderDomTraversal { // Perform the appropriate traversal. self.process(node); - let shared_layout_context = unsafe { &**proxy.user_data() }; + let shared_layout_context = unsafe { &*(proxy.user_data().0) }; let layout_context = LayoutContext::new(shared_layout_context); let parent = @@ -216,7 +216,7 @@ trait ParallelPostorderFlowTraversal : PostorderFlowTraversal { /// fetch-and-subtract the parent's children count. fn run_parallel(&self, mut unsafe_flow: UnsafeFlow, - _: &mut WorkerProxy<*const SharedLayoutContext,UnsafeFlow>) { + _: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeFlow>) { loop { unsafe { // Get a real flow. @@ -261,17 +261,17 @@ trait ParallelPostorderFlowTraversal : PostorderFlowTraversal { trait ParallelPreorderFlowTraversal : PreorderFlowTraversal { fn run_parallel(&self, unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeFlow>); + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeFlow>); #[inline(always)] fn run_parallel_helper(&self, unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeFlow>, + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeFlow>, top_down_func: extern "Rust" fn(UnsafeFlow, - &mut WorkerProxy<*const SharedLayoutContext, + &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeFlow>), bottom_up_func: extern "Rust" fn(UnsafeFlow, - &mut WorkerProxy<*const SharedLayoutContext, + &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeFlow>)) { let mut had_children = false; unsafe { @@ -306,7 +306,7 @@ impl<'a> ParallelPostorderFlowTraversal for BubbleISizes<'a> {} impl<'a> ParallelPreorderFlowTraversal for AssignISizes<'a> { fn run_parallel(&self, unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeFlow>) { + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeFlow>) { self.run_parallel_helper(unsafe_flow, proxy, assign_inline_sizes, @@ -319,7 +319,7 @@ impl<'a> ParallelPostorderFlowTraversal for AssignBSizesAndStoreOverflow<'a> {} impl<'a> ParallelPreorderFlowTraversal for ComputeAbsolutePositions<'a> { fn run_parallel(&self, unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext, UnsafeFlow>) { + proxy: &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeFlow>) { self.run_parallel_helper(unsafe_flow, proxy, compute_absolute_positions, @@ -334,7 +334,7 @@ impl<'a> ParallelPostorderDomTraversal for ConstructFlows<'a> {} impl <'a> ParallelPreorderDomTraversal for RecalcStyleForNode<'a> { fn run_parallel(&self, unsafe_node: UnsafeLayoutNode, - proxy: &mut WorkerProxy<*const SharedLayoutContext, UnsafeLayoutNode>) { + proxy: &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeLayoutNode>) { self.run_parallel_helper(unsafe_node, proxy, recalc_style, @@ -343,8 +343,8 @@ impl <'a> ParallelPreorderDomTraversal for RecalcStyleForNode<'a> { } fn recalc_style(unsafe_node: UnsafeLayoutNode, - proxy: &mut WorkerProxy<*const SharedLayoutContext, UnsafeLayoutNode>) { - let shared_layout_context = unsafe { &**proxy.user_data() }; + proxy: &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeLayoutNode>) { + let shared_layout_context = unsafe { &*(proxy.user_data().0) }; let layout_context = LayoutContext::new(shared_layout_context); let recalc_style_for_node_traversal = RecalcStyleForNode { layout_context: &layout_context, @@ -353,8 +353,8 @@ fn recalc_style(unsafe_node: UnsafeLayoutNode, } fn construct_flows(unsafe_node: UnsafeLayoutNode, - proxy: &mut WorkerProxy<*const SharedLayoutContext, UnsafeLayoutNode>) { - let shared_layout_context = unsafe { &**proxy.user_data() }; + proxy: &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeLayoutNode>) { + let shared_layout_context = unsafe { &*(proxy.user_data().0) }; let layout_context = LayoutContext::new(shared_layout_context); let construct_flows_traversal = ConstructFlows { layout_context: &layout_context, @@ -363,8 +363,8 @@ fn construct_flows(unsafe_node: UnsafeLayoutNode, } fn assign_inline_sizes(unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeFlow>) { - let shared_layout_context = unsafe { &**proxy.user_data() }; + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeFlow>) { + let shared_layout_context = unsafe { &*(proxy.user_data().0) }; let layout_context = LayoutContext::new(shared_layout_context); let assign_inline_sizes_traversal = AssignISizes { layout_context: &layout_context, @@ -373,8 +373,8 @@ fn assign_inline_sizes(unsafe_flow: UnsafeFlow, } fn assign_block_sizes_and_store_overflow(unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext,UnsafeFlow>) { - let shared_layout_context = unsafe { &**proxy.user_data() }; + proxy: &mut WorkerProxy<SharedLayoutContextWrapper,UnsafeFlow>) { + let shared_layout_context = unsafe { &*(proxy.user_data().0) }; let layout_context = LayoutContext::new(shared_layout_context); let assign_block_sizes_traversal = AssignBSizesAndStoreOverflow { layout_context: &layout_context, @@ -383,8 +383,8 @@ fn assign_block_sizes_and_store_overflow(unsafe_flow: UnsafeFlow, } fn compute_absolute_positions(unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext, UnsafeFlow>) { - let shared_layout_context = unsafe { &**proxy.user_data() }; + proxy: &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeFlow>) { + let shared_layout_context = unsafe { &*(proxy.user_data().0) }; let layout_context = LayoutContext::new(shared_layout_context); let compute_absolute_positions_traversal = ComputeAbsolutePositions { layout_context: &layout_context, @@ -393,8 +393,8 @@ fn compute_absolute_positions(unsafe_flow: UnsafeFlow, } fn build_display_list(unsafe_flow: UnsafeFlow, - proxy: &mut WorkerProxy<*const SharedLayoutContext, UnsafeFlow>) { - let shared_layout_context = unsafe { &**proxy.user_data() }; + proxy: &mut WorkerProxy<SharedLayoutContextWrapper, UnsafeFlow>) { + let shared_layout_context = unsafe { &*(proxy.user_data().0) }; let layout_context = LayoutContext::new(shared_layout_context); let build_display_list_traversal = BuildDisplayList { @@ -406,8 +406,8 @@ fn build_display_list(unsafe_flow: UnsafeFlow, pub fn traverse_dom_preorder(root: LayoutNode, shared_layout_context: &SharedLayoutContext, - queue: &mut WorkQueue<*const SharedLayoutContext, UnsafeLayoutNode>) { - queue.data = shared_layout_context as *const _; + queue: &mut WorkQueue<SharedLayoutContextWrapper, UnsafeLayoutNode>) { + queue.data = SharedLayoutContextWrapper(shared_layout_context as *const _); queue.push(WorkUnit { fun: recalc_style, @@ -416,21 +416,21 @@ pub fn traverse_dom_preorder(root: LayoutNode, queue.run(); - queue.data = ptr::null(); + queue.data = SharedLayoutContextWrapper(ptr::null()); } pub fn traverse_flow_tree_preorder(root: &mut FlowRef, profiler_metadata: ProfilerMetadata, time_profiler_chan: TimeProfilerChan, shared_layout_context: &SharedLayoutContext, - queue: &mut WorkQueue<*const SharedLayoutContext,UnsafeFlow>) { + queue: &mut WorkQueue<SharedLayoutContextWrapper,UnsafeFlow>) { if opts::get().bubble_inline_sizes_separately { let layout_context = LayoutContext::new(shared_layout_context); let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context }; root.traverse_postorder(&bubble_inline_sizes); } - queue.data = shared_layout_context as *const _; + queue.data = SharedLayoutContextWrapper(shared_layout_context as *const _); profile(TimeProfilerCategory::LayoutParallelWarmup, profiler_metadata, time_profiler_chan, || { @@ -442,15 +442,15 @@ pub fn traverse_flow_tree_preorder(root: &mut FlowRef, queue.run(); - queue.data = ptr::null() + queue.data = SharedLayoutContextWrapper(ptr::null()) } pub fn build_display_list_for_subtree(root: &mut FlowRef, profiler_metadata: ProfilerMetadata, time_profiler_chan: TimeProfilerChan, shared_layout_context: &SharedLayoutContext, - queue: &mut WorkQueue<*const SharedLayoutContext,UnsafeFlow>) { - queue.data = shared_layout_context as *const _; + queue: &mut WorkQueue<SharedLayoutContextWrapper,UnsafeFlow>) { + queue.data = SharedLayoutContextWrapper(shared_layout_context as *const _); profile(TimeProfilerCategory::LayoutParallelWarmup, profiler_metadata, time_profiler_chan, || { @@ -462,5 +462,5 @@ pub fn build_display_list_for_subtree(root: &mut FlowRef, queue.run(); - queue.data = ptr::null() + queue.data = SharedLayoutContextWrapper(ptr::null()) } diff --git a/components/layout/table.rs b/components/layout/table.rs index 0dd9f9caa08..a67636a31b8 100644 --- a/components/layout/table.rs +++ b/components/layout/table.rs @@ -32,7 +32,7 @@ use std::sync::Arc; /// A table flow corresponded to the table's internal table fragment under a table wrapper flow. /// The properties `position`, `float`, and `margin-*` are used on the table wrapper fragment, /// not table fragment per CSS 2.1 § 10.5. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct TableFlow { pub block_flow: BlockFlow, @@ -399,7 +399,7 @@ impl Flow for TableFlow { impl fmt::Show for TableFlow { /// Outputs a debugging string describing this table flow. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "TableFlow: {}", self.block_flow) + write!(f, "TableFlow: {:?}", self.block_flow) } } @@ -441,7 +441,7 @@ impl ISizeAndMarginsComputer for InternalTable { /// maximum of 100 pixels and 20% of the table), the preceding constraint means that we must /// potentially store both a specified width *and* a specified percentage, so that the inline-size /// assignment phase of layout will know which one to pick. -#[deriving(Clone, Encodable, Show, Copy)] +#[derive(Clone, RustcEncodable, Show, Copy)] pub struct ColumnIntrinsicInlineSize { /// The preferred intrinsic inline size. pub preferred: Au, @@ -485,7 +485,7 @@ impl ColumnIntrinsicInlineSize { /// /// TODO(pcwalton): There will probably be some `border-collapse`-related info in here too /// eventually. -#[deriving(Encodable, Copy)] +#[derive(RustcEncodable, Copy)] pub struct ColumnComputedInlineSize { /// The computed size of this inline column. pub size: Au, diff --git a/components/layout/table_caption.rs b/components/layout/table_caption.rs index 938bfa0e0d2..d45bd50e91b 100644 --- a/components/layout/table_caption.rs +++ b/components/layout/table_caption.rs @@ -95,6 +95,6 @@ impl Flow for TableCaptionFlow { impl fmt::Show for TableCaptionFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "TableCaptionFlow: {}", self.block_flow) + write!(f, "TableCaptionFlow: {:?}", self.block_flow) } } diff --git a/components/layout/table_cell.rs b/components/layout/table_cell.rs index 89eea551c73..c80a4135f9f 100644 --- a/components/layout/table_cell.rs +++ b/components/layout/table_cell.rs @@ -22,7 +22,7 @@ use style::{UnsignedIntegerAttribute, ComputedValues}; use std::sync::Arc; /// A table formatting context. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct TableCellFlow { /// Data common to all block flows. pub block_flow: BlockFlow, @@ -176,6 +176,6 @@ impl Flow for TableCellFlow { impl fmt::Show for TableCellFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "TableCellFlow: {}", self.block_flow) + write!(f, "TableCellFlow: {:?}", self.block_flow) } } diff --git a/components/layout/table_colgroup.rs b/components/layout/table_colgroup.rs index 648c1ae125c..f828bcc658a 100644 --- a/components/layout/table_colgroup.rs +++ b/components/layout/table_colgroup.rs @@ -109,7 +109,7 @@ impl Flow for TableColGroupFlow { impl fmt::Show for TableColGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.fragment { - Some(ref rb) => write!(f, "TableColGroupFlow: {}", rb), + Some(ref rb) => write!(f, "TableColGroupFlow: {:?}", rb), None => write!(f, "TableColGroupFlow"), } } diff --git a/components/layout/table_row.rs b/components/layout/table_row.rs index 55bc3634efa..eb06b31cfec 100644 --- a/components/layout/table_row.rs +++ b/components/layout/table_row.rs @@ -27,7 +27,7 @@ use style::computed_values::LengthOrPercentageOrAuto; use std::sync::Arc; /// A single row of a table. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct TableRowFlow { pub block_flow: BlockFlow, @@ -39,7 +39,7 @@ pub struct TableRowFlow { } /// Information about the column inline size and span for each cell. -#[deriving(Encodable, Copy)] +#[derive(RustcEncodable, Copy)] pub struct CellIntrinsicInlineSize { /// Inline sizes that this cell contributes to the column. pub column_size: ColumnIntrinsicInlineSize, @@ -329,6 +329,6 @@ impl Flow for TableRowFlow { impl fmt::Show for TableRowFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "TableRowFlow: {}", self.block_flow.fragment) + write!(f, "TableRowFlow: {:?}", self.block_flow.fragment) } } diff --git a/components/layout/table_rowgroup.rs b/components/layout/table_rowgroup.rs index 80647a01a77..00a0f23c1b5 100644 --- a/components/layout/table_rowgroup.rs +++ b/components/layout/table_rowgroup.rs @@ -22,7 +22,7 @@ use style::ComputedValues; use std::sync::Arc; /// A table formatting context. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct TableRowGroupFlow { /// Fields common to all block flows. pub block_flow: BlockFlow, @@ -164,6 +164,6 @@ impl Flow for TableRowGroupFlow { impl fmt::Show for TableRowGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "TableRowGroupFlow: {}", self.block_flow.fragment) + write!(f, "TableRowGroupFlow: {:?}", self.block_flow.fragment) } } diff --git a/components/layout/table_wrapper.rs b/components/layout/table_wrapper.rs index d696de85ddc..6cb69a8b216 100644 --- a/components/layout/table_wrapper.rs +++ b/components/layout/table_wrapper.rs @@ -27,18 +27,19 @@ use geom::{Point2D, Rect}; use servo_util::geometry::Au; use std::cmp::{max, min}; use std::fmt; +use std::ops::Add; use style::{ComputedValues, CSSFloat}; use style::computed_values::{table_layout, LengthOrPercentageOrAuto}; use std::sync::Arc; -#[deriving(Copy, Encodable, Show)] +#[derive(Copy, RustcEncodable, Show)] pub enum TableLayout { Fixed, Auto } /// A table wrapper flow based on a block formatting context. -#[deriving(Encodable)] +#[derive(RustcEncodable)] pub struct TableWrapperFlow { pub block_flow: BlockFlow, @@ -144,11 +145,11 @@ impl TableWrapperFlow { // Compute all the guesses for the column sizes, and sum them. let mut total_guess = AutoLayoutCandidateGuess::new(); let guesses: Vec<AutoLayoutCandidateGuess> = - self.column_intrinsic_inline_sizes.iter().map(|column_intrinsic_inline_size| { + self.column_intrinsic_inline_sizes.iter().map(|&mut:column_intrinsic_inline_size| { let guess = AutoLayoutCandidateGuess::from_column_intrinsic_inline_size( column_intrinsic_inline_size, available_inline_size); - total_guess = total_guess + guess; + total_guess = &total_guess + &guess; guess }).collect(); @@ -383,9 +384,9 @@ impl Flow for TableWrapperFlow { impl fmt::Show for TableWrapperFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.block_flow.base.flags.is_float() { - write!(f, "TableWrapperFlow(Float): {}", self.block_flow.fragment) + write!(f, "TableWrapperFlow(Float): {:?}", self.block_flow.fragment) } else { - write!(f, "TableWrapperFlow: {}", self.block_flow.fragment) + write!(f, "TableWrapperFlow: {:?}", self.block_flow.fragment) } } } @@ -482,9 +483,10 @@ impl AutoLayoutCandidateGuess { } } -impl Add<AutoLayoutCandidateGuess,AutoLayoutCandidateGuess> for AutoLayoutCandidateGuess { +impl<'a> Add for &'a AutoLayoutCandidateGuess { + type Output = AutoLayoutCandidateGuess; #[inline] - fn add(&self, other: &AutoLayoutCandidateGuess) -> AutoLayoutCandidateGuess { + fn add(self, other: &AutoLayoutCandidateGuess) -> AutoLayoutCandidateGuess { AutoLayoutCandidateGuess { minimum_guess: self.minimum_guess + other.minimum_guess, minimum_percentage_guess: @@ -497,7 +499,7 @@ impl Add<AutoLayoutCandidateGuess,AutoLayoutCandidateGuess> for AutoLayoutCandid /// The `CSSFloat` member specifies the weight of the smaller of the two guesses, on a scale from /// 0.0 to 1.0. -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] enum SelectedAutoLayoutCandidateGuess { UseMinimumGuess, InterpolateBetweenMinimumGuessAndMinimumPercentageGuess(CSSFloat), diff --git a/components/layout/text.rs b/components/layout/text.rs index 324604281b4..fbc84dc1624 100644 --- a/components/layout/text.rs +++ b/components/layout/text.rs @@ -195,13 +195,13 @@ impl TextRunScanner { let range = *new_ranges.get(logical_offset); if range.is_empty() { debug!("Elided an `SpecificFragmentInfo::UnscannedText` because it was zero-length after \ - compression; {}", + compression; {:?}", old_fragment); continue } let text_size = old_fragment.border_box.size; - let &NewLinePositions(ref mut new_line_positions) = + let &mut NewLinePositions(ref mut new_line_positions) = new_line_positions.get_mut(logical_offset); let new_text_fragment_info = box ScannedTextFragmentInfo::new(run.clone(), diff --git a/components/layout/traversal.rs b/components/layout/traversal.rs index bafd242fc31..c76c654dcf5 100644 --- a/components/layout/traversal.rs +++ b/components/layout/traversal.rs @@ -48,7 +48,7 @@ type Generation = uint; /// Since a work-stealing queue is used for styling, sometimes, the bloom filter /// will no longer be the for the parent of the node we're currently on. When /// this happens, the task local bloom filter will be thrown away and rebuilt. -thread_local!(static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeLayoutNode, Generation)>> = RefCell::new(None)) +thread_local!(static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeLayoutNode, Generation)>> = RefCell::new(None)); /// Returns the task local bloom filter. /// @@ -74,7 +74,7 @@ fn take_task_local_bloom_filter(parent_node: Option<LayoutNode>, layout_context: // Hey, the cached parent is our parent! We can reuse the bloom filter. if old_node == layout_node_to_unsafe_layout_node(&parent) && old_generation == layout_context.shared.generation { - debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.val0()); + debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0); bloom_filter.clone() } else { // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing @@ -120,7 +120,7 @@ fn insert_ancestors_into_bloom_filter(bf: &mut Box<BloomFilter>, /// The recalc-style-for-node traversal, which styles each node and must run before /// layout computation. This computes the styles applied to each node. -#[deriving(Copy)] +#[derive(Copy)] pub struct RecalcStyleForNode<'a> { pub layout_context: &'a LayoutContext<'a>, } @@ -200,7 +200,7 @@ impl<'a> PreorderDomTraversal for RecalcStyleForNode<'a> { // Before running the children, we need to insert our nodes into the bloom // filter. - debug!("[{}] + {:X}", tid(), unsafe_layout_node.val0()); + debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); node.insert_into_bloom_filter(&mut *bf); // NB: flow construction updates the bloom filter on the way up. @@ -209,7 +209,7 @@ impl<'a> PreorderDomTraversal for RecalcStyleForNode<'a> { } /// The flow construction traversal, which builds flows for styled nodes. -#[deriving(Copy)] +#[derive(Copy)] pub struct ConstructFlows<'a> { pub layout_context: &'a LayoutContext<'a>, } @@ -258,7 +258,7 @@ impl<'a> PostorderDomTraversal for ConstructFlows<'a> { match node.layout_parent_node(self.layout_context.shared) { None => { - debug!("[{}] - {:X}, and deleting BF.", tid(), unsafe_layout_node.val0()); + debug!("[{}] - {:X}, and deleting BF.", tid(), unsafe_layout_node.0); // If this is the reflow root, eat the task-local bloom filter. } Some(parent) => { @@ -308,7 +308,7 @@ impl<'a> PostorderFlowTraversal for BubbleISizes<'a> { } /// The assign-inline-sizes traversal. In Gecko this corresponds to `Reflow`. -#[deriving(Copy)] +#[derive(Copy)] pub struct AssignISizes<'a> { pub layout_context: &'a LayoutContext<'a>, } @@ -329,7 +329,7 @@ impl<'a> PreorderFlowTraversal for AssignISizes<'a> { /// layout computation. Determines the final block-sizes for all layout objects, computes /// positions, and computes overflow regions. In Gecko this corresponds to `Reflow` and /// `FinishAndStoreOverflow`. -#[deriving(Copy)] +#[derive(Copy)] pub struct AssignBSizesAndStoreOverflow<'a> { pub layout_context: &'a LayoutContext<'a>, } @@ -354,7 +354,7 @@ impl<'a> PostorderFlowTraversal for AssignBSizesAndStoreOverflow<'a> { } } -#[deriving(Copy)] +#[derive(Copy)] pub struct ComputeAbsolutePositions<'a> { pub layout_context: &'a LayoutContext<'a>, } @@ -366,7 +366,7 @@ impl<'a> PreorderFlowTraversal for ComputeAbsolutePositions<'a> { } } -#[deriving(Copy)] +#[derive(Copy)] pub struct BuildDisplayList<'a> { pub layout_context: &'a LayoutContext<'a>, } diff --git a/components/layout/util.rs b/components/layout/util.rs index 0ba105f20fa..206590d7c23 100644 --- a/components/layout/util.rs +++ b/components/layout/util.rs @@ -64,7 +64,6 @@ impl PrivateLayoutData { } bitflags! { - #[deriving(Copy)] flags LayoutDataFlags: u8 { #[doc="Whether a flow has been newly constructed."] const HAS_NEWLY_CONSTRUCTED_FLOW = 0x01 @@ -77,6 +76,14 @@ pub struct LayoutDataWrapper { pub data: Box<PrivateLayoutData>, } +#[allow(dead_code)] +fn static_assertion(x: Option<LayoutDataWrapper>) { + unsafe { + let _: Option<::script::dom::node::LayoutData> = + ::std::intrinsics::transmute(x); + } +} + /// A trait that allows access to the layout data of a DOM node. pub trait LayoutDataAccess { /// Borrows the layout data without checks. diff --git a/components/layout/wrapper.rs b/components/layout/wrapper.rs index 6b8db9b1b98..d54af90014a 100644 --- a/components/layout/wrapper.rs +++ b/components/layout/wrapper.rs @@ -49,8 +49,8 @@ use script::dom::htmlelement::HTMLElementTypeId; use script::dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers}; use script::dom::htmliframeelement::HTMLIFrameElement; use script::dom::htmlimageelement::LayoutHTMLImageElementHelpers; -use script::dom::htmlinputelement::LayoutHTMLInputElementHelpers; -use script::dom::htmltextareaelement::LayoutHTMLTextAreaElementHelpers; +use script::dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers}; +use script::dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers}; use script::dom::node::{Node, NodeTypeId}; use script::dom::node::{LayoutNodeHelpers, RawLayoutNodeHelpers, SharedLayoutData}; use script::dom::node::{HAS_CHANGED, IS_DIRTY, HAS_DIRTY_SIBLINGS, HAS_DIRTY_DESCENDANTS}; @@ -58,8 +58,9 @@ use script::dom::text::Text; use script::layout_interface::LayoutChan; use servo_msg::constellation_msg::{PipelineId, SubpageId}; use servo_util::str::{LengthOrPercentageOrAuto, is_whitespace}; -use std::kinds::marker::ContravariantLifetime; +use std::marker::ContravariantLifetime; use std::mem; +use std::sync::mpsc::Sender; use string_cache::{Atom, Namespace}; use style::computed_values::{content, display, white_space}; use style::{NamespaceConstraint, AttrSelector, IntegerAttribute}; @@ -161,7 +162,7 @@ pub trait TLayoutNode { /// A wrapper so that layout can access only the methods that it should have access to. Layout must /// only ever see these and must never see instances of `JS`. -#[deriving(Copy)] +#[derive(Copy)] pub struct LayoutNode<'a> { /// The wrapped node. node: JS<Node>, @@ -212,15 +213,20 @@ impl<'ln> TLayoutNode for LayoutNode<'ln> { fn text(&self) -> String { unsafe { - if let Some(text) = TextCast::to_js(self.get_jsmanaged()) { - (*text.unsafe_get()).characterdata().data_for_layout().to_owned() - } else if let Some(input) = HTMLInputElementCast::to_js(self.get_jsmanaged()) { - input.get_value_for_layout() - } else if let Some(area) = HTMLTextAreaElementCast::to_js(self.get_jsmanaged()) { - area.get_value_for_layout() - } else { - panic!("not text!") + let text: Option<JS<Text>> = TextCast::to_js(self.get_jsmanaged()); + if let Some(text) = text { + return (*text.unsafe_get()).characterdata().data_for_layout().to_owned(); + } + let input: Option<JS<HTMLInputElement>> = HTMLInputElementCast::to_js(self.get_jsmanaged()); + if let Some(input) = input { + return input.get_value_for_layout(); + } + let area: Option<JS<HTMLTextAreaElement>> = HTMLTextAreaElementCast::to_js(self.get_jsmanaged()); + if let Some(area) = area { + return area.get_value_for_layout(); } + + panic!("not text!") } } } @@ -245,7 +251,7 @@ impl<'ln> LayoutNode<'ln> { } fn debug_str(self) -> String { - format!("{}: changed={} dirty={} dirty_descendants={}", + format!("{:?}: changed={} dirty={} dirty_descendants={}", self.type_id(), self.has_changed(), self.is_dirty(), self.has_dirty_descendants()) } @@ -383,8 +389,8 @@ impl<'ln> TNode<'ln, LayoutElement<'ln>> for LayoutNode<'ln> { self.node_is_document() } - fn match_attr(self, attr: &AttrSelector, test: |&str| -> bool) -> bool { - assert!(self.is_element()) + fn match_attr<F>(self, attr: &AttrSelector, test: F) -> bool where F: Fn(&str) -> bool { + assert!(self.is_element()); let name = if self.is_html_element_in_html_document() { &attr.lower_name } else { @@ -448,7 +454,8 @@ pub struct LayoutNodeChildrenIterator<'a> { current: Option<LayoutNode<'a>>, } -impl<'a> Iterator<LayoutNode<'a>> for LayoutNodeChildrenIterator<'a> { +impl<'a> Iterator for LayoutNodeChildrenIterator<'a> { + type Item = LayoutNode<'a>; fn next(&mut self) -> Option<LayoutNode<'a>> { let node = self.current; self.current = node.and_then(|node| node.next_sibling()); @@ -460,7 +467,8 @@ pub struct LayoutNodeReverseChildrenIterator<'a> { current: Option<LayoutNode<'a>>, } -impl<'a> Iterator<LayoutNode<'a>> for LayoutNodeReverseChildrenIterator<'a> { +impl<'a> Iterator for LayoutNodeReverseChildrenIterator<'a> { + type Item = LayoutNode<'a>; fn next(&mut self) -> Option<LayoutNode<'a>> { let node = self.current; self.current = node.and_then(|node| node.prev_sibling()); @@ -482,7 +490,8 @@ impl<'a> LayoutTreeIterator<'a> { } } -impl<'a> Iterator<LayoutNode<'a>> for LayoutTreeIterator<'a> { +impl<'a> Iterator for LayoutTreeIterator<'a> { + type Item = LayoutNode<'a>; fn next(&mut self) -> Option<LayoutNode<'a>> { let ret = self.stack.pop(); ret.map(|node| self.stack.extend(node.rev_children())); @@ -491,7 +500,7 @@ impl<'a> Iterator<LayoutNode<'a>> for LayoutTreeIterator<'a> { } /// A wrapper around elements that ensures layout can only ever access safe properties. -#[deriving(Copy)] +#[derive(Copy)] pub struct LayoutElement<'le> { element: &'le Element, } @@ -530,7 +539,8 @@ impl<'le> TElement<'le> for LayoutElement<'le> { fn get_link(self) -> Option<&'le str> { // FIXME: This is HTML only. - match NodeCast::from_actual(self.element).type_id_for_layout() { + let node: &Node = NodeCast::from_actual(self.element); + match node.type_id_for_layout() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/selectors.html# // selector-link NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) | @@ -547,7 +557,8 @@ impl<'le> TElement<'le> for LayoutElement<'le> { #[inline] fn get_hover_state(self) -> bool { unsafe { - NodeCast::from_actual(self.element).get_hover_state_for_layout() + let node: &Node = NodeCast::from_actual(self.element); + node.get_hover_state_for_layout() } } @@ -561,14 +572,16 @@ impl<'le> TElement<'le> for LayoutElement<'le> { #[inline] fn get_disabled_state(self) -> bool { unsafe { - NodeCast::from_actual(self.element).get_disabled_state_for_layout() + let node: &Node = NodeCast::from_actual(self.element); + node.get_disabled_state_for_layout() } } #[inline] fn get_enabled_state(self) -> bool { unsafe { - NodeCast::from_actual(self.element).get_enabled_state_for_layout() + let node: &Node = NodeCast::from_actual(self.element); + node.get_enabled_state_for_layout() } } @@ -594,7 +607,7 @@ impl<'le> TElement<'le> for LayoutElement<'le> { } #[inline(always)] - fn each_class(self, callback: |&Atom|) { + fn each_class<F>(self, mut callback: F) where F: FnMut(&Atom) { unsafe { match self.element.get_classes_for_layout() { None => {} @@ -658,7 +671,7 @@ fn get_content(content_list: &content::T) -> String { } } -#[deriving(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone)] pub enum PseudoElementType { Normal, Before(display::T), @@ -683,7 +696,7 @@ impl PseudoElementType { /// A thread-safe version of `LayoutNode`, used during flow construction. This type of layout /// node does not allow any parents or siblings of nodes to be accessed, to avoid races. -#[deriving(Copy, Clone)] +#[derive(Copy, Clone)] pub struct ThreadSafeLayoutNode<'ln> { /// The wrapped node. node: LayoutNode<'ln>, @@ -946,7 +959,8 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { pub fn get_input_value(&self) -> String { unsafe { - match HTMLInputElementCast::to_js(self.get_jsmanaged()) { + let input: Option<JS<HTMLInputElement>> = HTMLInputElementCast::to_js(self.get_jsmanaged()); + match input { Some(input) => input.get_value_for_layout(), None => panic!("not an input element!") } @@ -965,7 +979,8 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { pub fn get_unsigned_integer_attribute(self, attribute: UnsignedIntegerAttribute) -> Option<u32> { unsafe { - match ElementCast::to_js(self.get_jsmanaged()) { + let elem: Option<JS<Element>> = ElementCast::to_js(self.get_jsmanaged()); + match elem { Some(element) => { (*element.unsafe_get()).get_unsigned_integer_attribute_for_layout(attribute) } @@ -985,7 +1000,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { pub fn set_restyle_damage(self, damage: RestyleDamage) { let mut layout_data_ref = self.mutate_layout_data(); match &mut *layout_data_ref { - &Some(ref mut layout_data) => layout_data.data.restyle_damage = damage, + &mut Some(ref mut layout_data) => layout_data.data.restyle_damage = damage, _ => panic!("no layout data for this node"), } } @@ -1004,7 +1019,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { pub fn insert_flags(self, new_flags: LayoutDataFlags) { let mut layout_data_ref = self.mutate_layout_data(); match &mut *layout_data_ref { - &Some(ref mut layout_data) => layout_data.data.flags.insert(new_flags), + &mut Some(ref mut layout_data) => layout_data.data.flags.insert(new_flags), _ => panic!("no layout data for this node"), } } @@ -1013,7 +1028,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { pub fn remove_flags(self, flags: LayoutDataFlags) { let mut layout_data_ref = self.mutate_layout_data(); match &mut *layout_data_ref { - &Some(ref mut layout_data) => layout_data.data.flags.remove(flags), + &mut Some(ref mut layout_data) => layout_data.data.flags.remove(flags), _ => panic!("no layout data for this node"), } } @@ -1033,7 +1048,8 @@ pub struct ThreadSafeLayoutNodeChildrenIterator<'a> { parent_node: Option<ThreadSafeLayoutNode<'a>>, } -impl<'a> Iterator<ThreadSafeLayoutNode<'a>> for ThreadSafeLayoutNodeChildrenIterator<'a> { +impl<'a> Iterator for ThreadSafeLayoutNodeChildrenIterator<'a> { + type Item = ThreadSafeLayoutNode<'a>; fn next(&mut self) -> Option<ThreadSafeLayoutNode<'a>> { let node = self.current_node.clone(); diff --git a/components/layout_traits/lib.rs b/components/layout_traits/lib.rs index 178861d7a93..fd3ecd541f9 100644 --- a/components/layout_traits/lib.rs +++ b/components/layout_traits/lib.rs @@ -24,7 +24,7 @@ use servo_net::image_cache_task::ImageCacheTask; use servo_net::resource_task::ResourceTask; use servo_util::time::TimeProfilerChan; use script_traits::{ScriptControlChan, OpaqueScriptLayoutChannel}; -use std::comm::Sender; +use std::sync::mpsc::{Sender, Receiver}; /// Messages sent to the layout task from the constellation pub enum LayoutControlMsg { diff --git a/components/msg/Cargo.toml b/components/msg/Cargo.toml index 460a277a7a7..2bd553491d9 100644 --- a/components/msg/Cargo.toml +++ b/components/msg/Cargo.toml @@ -33,5 +33,5 @@ git = "https://github.com/servo/rust-core-foundation" [dependencies.io_surface] git = "https://github.com/servo/rust-io-surface" -[dependencies.url] -git = "https://github.com/servo/rust-url" +[dependencies] +url = "*"
\ No newline at end of file diff --git a/components/msg/compositor_msg.rs b/components/msg/compositor_msg.rs index a2e3c4d1909..111636c349c 100644 --- a/components/msg/compositor_msg.rs +++ b/components/msg/compositor_msg.rs @@ -14,13 +14,13 @@ use std::fmt; use constellation_msg::PipelineId; /// The status of the painter. -#[deriving(PartialEq, Eq, Clone, Copy)] +#[derive(PartialEq, Eq, Clone, Copy)] pub enum PaintState { Idle, Painting, } -#[deriving(Eq, Ord, PartialEq, PartialOrd, Clone, Show, Copy)] +#[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Show, Copy)] pub enum ReadyState { /// Informs the compositor that nothing has been done yet. Used for setting status Blank, @@ -33,7 +33,7 @@ pub enum ReadyState { } /// A newtype struct for denoting the age of messages; prevents race conditions. -#[deriving(PartialEq, Eq, Show, Copy)] +#[derive(PartialEq, Eq, Show, Copy)] pub struct Epoch(pub uint); impl Epoch { @@ -43,7 +43,7 @@ impl Epoch { } } -#[deriving(Clone, PartialEq, Eq, Copy)] +#[derive(Clone, PartialEq, Eq, Copy)] pub struct LayerId(pub uint, pub uint); impl Show for LayerId { @@ -61,7 +61,7 @@ impl LayerId { } /// The scrolling policy of a layer. -#[deriving(Clone, PartialEq, Eq, Copy)] +#[derive(Clone, PartialEq, Eq, Copy)] pub enum ScrollPolicy { /// These layers scroll when the parent receives a scrolling message. Scrollable, @@ -71,7 +71,7 @@ pub enum ScrollPolicy { /// All layer-specific information that the painting task sends to the compositor other than the /// buffer contents of the layer itself. -#[deriving(Copy)] +#[derive(Copy)] pub struct LayerMetadata { /// An opaque ID. This is usually the address of the flow and index of the box within it. pub id: LayerId, @@ -85,7 +85,7 @@ pub struct LayerMetadata { /// The interface used by the painter to acquire draw targets for each paint frame and /// submit them to be drawn to the display. -pub trait PaintListener for Sized? { +pub trait PaintListener { fn get_graphics_metadata(&mut self) -> Option<NativeGraphicsMetadata>; /// Informs the compositor of the layers for the given pipeline. The compositor responds by diff --git a/components/msg/constellation_msg.rs b/components/msg/constellation_msg.rs index 5cd2a0cce39..658fb6a4e71 100644 --- a/components/msg/constellation_msg.rs +++ b/components/msg/constellation_msg.rs @@ -13,10 +13,10 @@ use hyper::method::Method; use layers::geometry::DevicePixel; use servo_util::cursor::Cursor; use servo_util::geometry::{PagePx, ViewportPx}; -use std::comm::{channel, Sender, Receiver}; +use std::sync::mpsc::{channel, Sender, Receiver}; use url::Url; -#[deriving(Clone)] +#[derive(Clone)] pub struct ConstellationChan(pub Sender<Msg>); impl ConstellationChan { @@ -26,20 +26,20 @@ impl ConstellationChan { } } -#[deriving(PartialEq, Eq, Copy)] +#[derive(PartialEq, Eq, Copy)] pub enum IFrameSandboxState { IFrameSandboxed, IFrameUnsandboxed } // We pass this info to various tasks, so it lives in a separate, cloneable struct. -#[deriving(Clone, Copy)] +#[derive(Clone, Copy)] pub struct Failure { pub pipeline_id: PipelineId, pub subpage_id: Option<SubpageId>, } -#[deriving(Copy)] +#[derive(Copy)] pub struct WindowSizeData { /// The size of the initial layout viewport, before parsing an /// http://www.w3.org/TR/css-device-adapt/#initial-viewport @@ -52,7 +52,7 @@ pub struct WindowSizeData { pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>, } -#[deriving(PartialEq, Eq, Copy, Clone)] +#[derive(PartialEq, Eq, Copy, Clone)] pub enum KeyState { Pressed, Released, @@ -60,7 +60,7 @@ pub enum KeyState { } //N.B. Straight up copied from glfw-rs -#[deriving(Show, PartialEq, Eq, Copy, Clone)] +#[derive(Show, PartialEq, Eq, Copy, Clone)] pub enum Key { Space, Apostrophe, @@ -186,7 +186,6 @@ pub enum Key { } bitflags! { - #[deriving(Copy)] flags KeyModifiers: u8 { const SHIFT = 0x01, const CONTROL = 0x02, @@ -218,7 +217,7 @@ pub enum Msg { /// Similar to net::resource_task::LoadData /// can be passed to LoadUrl to load a page with GET/POST /// parameters or headers -#[deriving(Clone)] +#[derive(Clone)] pub struct LoadData { pub url: Url, pub method: Method, @@ -238,27 +237,27 @@ impl LoadData { } /// Represents the two different ways to which a page can be navigated -#[deriving(Clone, PartialEq, Eq, Copy, Hash, Show)] +#[derive(Clone, PartialEq, Eq, Copy, Hash, Show)] pub enum NavigationType { Load, // entered or clicked on a url Navigate, // browser forward/back buttons } -#[deriving(Clone, PartialEq, Eq, Copy, Hash, Show)] +#[derive(Clone, PartialEq, Eq, Copy, Hash, Show)] pub enum NavigationDirection { Forward, Back, } -#[deriving(Clone, PartialEq, Eq, Copy, Hash, Show)] +#[derive(Clone, PartialEq, Eq, Copy, Hash, Show)] pub struct PipelineId(pub uint); -#[deriving(Clone, PartialEq, Eq, Copy, Hash, Show)] +#[derive(Clone, PartialEq, Eq, Copy, Hash, Show)] pub struct SubpageId(pub uint); // The type of pipeline exit. During complete shutdowns, pipelines do not have to // release resources automatically released on process termination. -#[deriving(Copy)] +#[derive(Copy)] pub enum PipelineExitType { PipelineOnly, Complete, diff --git a/components/msg/lib.rs b/components/msg/lib.rs index 234fba05361..ba02ce8babd 100644 --- a/components/msg/lib.rs +++ b/components/msg/lib.rs @@ -2,6 +2,8 @@ * 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/. */ +#![feature(int_uint)] + #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] diff --git a/components/net/Cargo.toml b/components/net/Cargo.toml index 55d0676a71b..18672a756b9 100644 --- a/components/net/Cargo.toml +++ b/components/net/Cargo.toml @@ -23,8 +23,6 @@ git = "https://github.com/servo/rust-png" [dependencies.stb_image] git = "https://github.com/servo/rust-stb-image" -[dependencies.url] -git = "https://github.com/servo/rust-url" - -[dependencies.time] -git = "https://github.com/rust-lang/time" +[dependencies] +url = "*" +time = "*"
\ No newline at end of file diff --git a/components/net/about_loader.rs b/components/net/about_loader.rs index 4ff19586e2a..bc87727c768 100644 --- a/components/net/about_loader.rs +++ b/components/net/about_loader.rs @@ -12,6 +12,7 @@ use servo_util::resource_files::resources_dir_path; use std::borrow::ToOwned; use std::io::fs::PathExtensions; +use std::sync::mpsc::Sender; pub fn factory(mut load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { let senders = ResponseSenders { diff --git a/components/net/data_loader.rs b/components/net/data_loader.rs index b24c58e4b71..da58515a7ad 100644 --- a/components/net/data_loader.rs +++ b/components/net/data_loader.rs @@ -10,6 +10,7 @@ use serialize::base64::FromBase64; use hyper::mime::Mime; use url::{percent_decode, SchemeData}; +use std::sync::mpsc::Sender; pub fn factory(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { // NB: we don't spawn a new task. @@ -59,7 +60,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { // Parse the content type using rust-http. // FIXME: this can go into an infinite loop! (rust-http #25) - let content_type: Option<Mime> = from_str(ct_str); + let content_type: Option<Mime> = ct_str.parse(); metadata.set_content_type(content_type.as_ref()); let progress_chan = start_sending(senders, metadata); @@ -89,19 +90,19 @@ fn assert_parse(url: &'static str, content_type: Option<(String, String)>, charset: Option<String>, data: Option<Vec<u8>>) { - use std::comm; + use std::sync::mpsc::channel; use url::Url; use sniffer_task; - let (start_chan, start_port) = comm::channel(); + let (start_chan, start_port) = channel(); let sniffer_task = sniffer_task::new_sniffer_task(); load(LoadData::new(Url::parse(url).unwrap(), start_chan), sniffer_task); - let response = start_port.recv(); + let response = start_port.recv().unwrap(); assert_eq!(&response.metadata.content_type, &content_type); assert_eq!(&response.metadata.charset, &charset); - let progress = response.progress_port.recv(); + let progress = response.progress_port.recv().unwrap(); match data { None => { @@ -109,7 +110,7 @@ fn assert_parse(url: &'static str, } Some(dat) => { assert_eq!(progress, Payload(dat)); - assert_eq!(response.progress_port.recv(), Done(Ok(()))); + assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); } } } diff --git a/components/net/fetch/cors_cache.rs b/components/net/fetch/cors_cache.rs index 23a6a8450e5..e3b79b48c24 100644 --- a/components/net/fetch/cors_cache.rs +++ b/components/net/fetch/cors_cache.rs @@ -11,7 +11,7 @@ use hyper::method::Method; use std::ascii::AsciiExt; -use std::comm::{Sender, Receiver, channel}; +use std::sync::mpsc::{Sender, Receiver, channel}; use time; use time::{now, Timespec}; use url::Url; @@ -19,7 +19,7 @@ use url::Url; /// Union type for CORS cache entries /// /// Each entry might pertain to a header or method -#[deriving(Clone)] +#[derive(Clone)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method) @@ -42,7 +42,7 @@ impl HeaderOrMethod { } /// An entry in the CORS cache -#[deriving(Clone)] +#[derive(Clone)] pub struct CORSCacheEntry { pub origin: Url, pub url: Url, @@ -100,7 +100,7 @@ pub trait CORSCache { } /// A simple, vector-based CORS Cache -#[deriving(Clone)] +#[derive(Clone)] #[unstable = "This might later be replaced with a HashMap-like entity, though that requires a separate Origin struct"] pub struct BasicCORSCache(Vec<CORSCacheEntry>); @@ -207,43 +207,43 @@ impl CORSCache for CORSCacheSender { fn clear (&mut self, request: CacheRequestDetails) { let (tx, rx) = channel(); self.send(CORSCacheTaskMsg::Clear(request, tx)); - let _ = rx.recv_opt(); + let _ = rx.recv(); } fn cleanup(&mut self) { let (tx, rx) = channel(); self.send(CORSCacheTaskMsg::Cleanup(tx)); - let _ = rx.recv_opt(); + let _ = rx.recv(); } fn match_header(&mut self, request: CacheRequestDetails, header_name: &str) -> bool { let (tx, rx) = channel(); self.send(CORSCacheTaskMsg::MatchHeader(request, header_name.to_string(), tx)); - rx.recv_opt().unwrap_or(false) + rx.recv().unwrap_or(false) } fn match_header_and_update(&mut self, request: CacheRequestDetails, header_name: &str, new_max_age: uint) -> bool { let (tx, rx) = channel(); self.send(CORSCacheTaskMsg::MatchHeaderUpdate(request, header_name.to_string(), new_max_age, tx)); - rx.recv_opt().unwrap_or(false) + rx.recv().unwrap_or(false) } fn match_method(&mut self, request: CacheRequestDetails, method: Method) -> bool { let (tx, rx) = channel(); self.send(CORSCacheTaskMsg::MatchMethod(request, method, tx)); - rx.recv_opt().unwrap_or(false) + rx.recv().unwrap_or(false) } fn match_method_and_update(&mut self, request: CacheRequestDetails, method: Method, new_max_age: uint) -> bool { let (tx, rx) = channel(); self.send(CORSCacheTaskMsg::MatchMethodUpdate(request, method, new_max_age, tx)); - rx.recv_opt().unwrap_or(false) + rx.recv().unwrap_or(false) } fn insert(&mut self, entry: CORSCacheEntry) { let (tx, rx) = channel(); self.send(CORSCacheTaskMsg::Insert(entry, tx)); - let _ = rx.recv_opt(); + let _ = rx.recv(); } } @@ -254,7 +254,7 @@ impl CORSCache for CORSCacheSender { /// let task = CORSCacheTask::new(); /// let builder = TaskBuilder::new().named("XHRTask"); /// let mut sender = task.get_sender(); -/// builder.spawn(proc() { task.run() }); +/// builder.spawn(move || { task.run() }); /// sender.insert(CORSCacheEntry::new(/* parameters here */)); /// ``` pub struct CORSCacheTask { @@ -284,7 +284,7 @@ impl CORSCacheTask { /// Send ExitMsg to the associated Sender to exit pub fn run(&mut self) { loop { - match self.receiver.recv() { + match self.receiver.recv().unwrap() { CORSCacheTaskMsg::Clear(request, tx) => { self.cache.clear(request); tx.send(()); diff --git a/components/net/fetch/request.rs b/components/net/fetch/request.rs index 050ed9b892b..1c7b51566ad 100644 --- a/components/net/fetch/request.rs +++ b/components/net/fetch/request.rs @@ -11,7 +11,7 @@ use fetch::cors_cache::CORSCache; use fetch::response::Response; /// A [request context](http://fetch.spec.whatwg.org/#concept-request-context) -#[deriving(Copy)] +#[derive(Copy)] pub enum Context { Audio, Beacon, CSPreport, Download, Embed, Eventsource, Favicon, Fetch, Font, Form, Frame, Hyperlink, IFrame, Image, @@ -21,7 +21,7 @@ pub enum Context { } /// A [request context frame type](http://fetch.spec.whatwg.org/#concept-request-context-frame-type) -#[deriving(Copy)] +#[derive(Copy)] pub enum ContextFrameType { Auxiliary, TopLevel, @@ -37,7 +37,7 @@ pub enum Referer { } /// A [request mode](http://fetch.spec.whatwg.org/#concept-request-mode) -#[deriving(Copy)] +#[derive(Copy)] pub enum RequestMode { SameOrigin, NoCORS, @@ -46,7 +46,7 @@ pub enum RequestMode { } /// Request [credentials mode](http://fetch.spec.whatwg.org/#concept-request-credentials-mode) -#[deriving(Copy)] +#[derive(Copy)] pub enum CredentialsMode { Omit, CredentialsSameOrigin, @@ -54,7 +54,7 @@ pub enum CredentialsMode { } /// [Response tainting](http://fetch.spec.whatwg.org/#concept-request-response-tainting) -#[deriving(Copy)] +#[derive(Copy)] pub enum ResponseTainting { Basic, CORSTainting, diff --git a/components/net/fetch/response.rs b/components/net/fetch/response.rs index 2c1817de338..7380f3e7ad6 100644 --- a/components/net/fetch/response.rs +++ b/components/net/fetch/response.rs @@ -6,10 +6,10 @@ use url::Url; use hyper::status::StatusCode; use hyper::header::Headers; use std::ascii::AsciiExt; -use std::comm::Receiver; +use std::sync::mpsc::Receiver; /// [Response type](http://fetch.spec.whatwg.org/#concept-response-type) -#[deriving(Clone, PartialEq, Copy)] +#[derive(Clone, PartialEq, Copy)] pub enum ResponseType { Basic, CORS, @@ -19,7 +19,7 @@ pub enum ResponseType { } /// [Response termination reason](http://fetch.spec.whatwg.org/#concept-response-termination-reason) -#[deriving(Clone, Copy)] +#[derive(Clone, Copy)] pub enum TerminationReason { EndUserAbort, Fatal, @@ -29,7 +29,7 @@ pub enum TerminationReason { /// The response body can still be pushed to after fetch /// This provides a way to store unfinished response bodies #[unstable = "I haven't yet decided exactly how the interface for this will be"] -#[deriving(Clone)] +#[derive(Clone)] pub enum ResponseBody { Empty, // XXXManishearth is this necessary, or is Done(vec![]) enough? Receiving(Vec<u8>), @@ -50,7 +50,7 @@ pub struct ResponseLoader { } /// A [Response](http://fetch.spec.whatwg.org/#concept-response) as defined by the Fetch spec -#[deriving(Clone)] +#[derive(Clone)] pub struct Response { pub response_type: ResponseType, pub termination_reason: Option<TerminationReason>, @@ -110,7 +110,7 @@ impl Response { ResponseType::Default | ResponseType::Error => unreachable!(), ResponseType::Basic => { let headers = old_headers.iter().filter(|header| { - match header.name().to_ascii_lower().as_slice() { + match header.name().to_ascii_lowercase().as_slice() { "set-cookie" | "set-cookie2" => false, _ => true } @@ -120,7 +120,7 @@ impl Response { }, ResponseType::CORS => { let headers = old_headers.iter().filter(|header| { - match header.name().to_ascii_lower().as_slice() { + match header.name().to_ascii_lowercase().as_slice() { "cache-control" | "content-language" | "content-type" | "expires" | "last-modified" | "Pragma" => false, // XXXManishearth handle Access-Control-Expose-Headers diff --git a/components/net/file_loader.rs b/components/net/file_loader.rs index 73bab50c54d..a2233ff54b8 100644 --- a/components/net/file_loader.rs +++ b/components/net/file_loader.rs @@ -8,6 +8,7 @@ use resource_task::ProgressMsg::{Payload, Done}; use std::borrow::ToOwned; use std::io; use std::io::File; +use std::sync::mpsc::Sender; use servo_util::task::spawn_named; static READ_SIZE: uint = 8192; @@ -17,11 +18,11 @@ fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>) loop { let mut buf = vec!(); match reader.push_at_least(READ_SIZE, READ_SIZE, &mut buf) { - Ok(_) => progress_chan.send(Payload(buf)), + Ok(_) => progress_chan.send(Payload(buf)).unwrap(), Err(e) => match e.kind { io::EndOfFile => { if buf.len() > 0 { - progress_chan.send(Payload(buf)); + progress_chan.send(Payload(buf)).unwrap(); } return Ok(()); } @@ -39,7 +40,7 @@ pub fn factory(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { eventual_consumer: load_data.consumer, }; let progress_chan = start_sending(senders, Metadata::default(url.clone())); - spawn_named("file_loader".to_owned(), proc() { + spawn_named("file_loader".to_owned(), move || { let file_path: Result<Path, ()> = url.to_file_path(); match file_path { Ok(file_path) => { diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index c2f34a1849a..5f0877cdaa1 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -11,14 +11,16 @@ use hyper::client::Request; use hyper::header::common::{ContentLength, ContentType, Host, Location}; use hyper::method::Method; use hyper::status::StatusClass; +use std::error::Error; use std::io::Reader; +use std::sync::mpsc::Sender; use servo_util::task::spawn_named; use url::{Url, UrlParser}; use std::borrow::ToOwned; pub fn factory(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { - spawn_named("http_loader".to_owned(), proc() load(load_data, start_chan)) + spawn_named("http_loader".to_owned(), move || load(load_data, start_chan)) } fn send_error(url: Url, err: String, senders: ResponseSenders) { @@ -26,7 +28,7 @@ fn send_error(url: Url, err: String, senders: ResponseSenders) { metadata.status = None; match start_sending_opt(senders, metadata) { - Ok(p) => p.send(Done(Err(err))), + Ok(p) => p.send(Done(Err(err))).unwrap(), _ => {} }; } @@ -75,7 +77,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { let mut req = match Request::new(load_data.method.clone(), url.clone()) { Ok(req) => req, Err(e) => { - send_error(url, e.to_string(), senders); + send_error(url, e.description().to_string(), senders); return; } }; @@ -91,11 +93,11 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { //} let writer = match load_data.data { Some(ref data) => { - req.headers_mut().set(ContentLength(data.len())); + req.headers_mut().set(ContentLength(data.len() as u64)); let mut writer = match req.start() { Ok(w) => w, Err(e) => { - send_error(url, e.to_string(), senders); + send_error(url, e.description().to_string(), senders); return; } }; @@ -116,7 +118,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { match req.start() { Ok(w) => w, Err(e) => { - send_error(url, e.to_string(), senders); + send_error(url, e.description().to_string(), senders); return; } } @@ -125,7 +127,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { let mut response = match writer.send() { Ok(r) => r, Err(e) => { - send_error(url, e.to_string(), senders); + send_error(url, e.description().to_string(), senders); return; } }; @@ -189,7 +191,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { match response.read(buf.as_mut_slice()) { Ok(len) => { unsafe { buf.set_len(len); } - if progress_chan.send_opt(Payload(buf)).is_err() { + if progress_chan.send(Payload(buf)).is_err() { // The send errors when the receiver is out of scope, // which will happen if the fetch has timed out (or has been aborted) // so we don't need to continue with the loading of the file here. @@ -197,7 +199,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { } } Err(_) => { - let _ = progress_chan.send_opt(Done(Ok(()))); + let _ = progress_chan.send(Done(Ok(()))); break; } } diff --git a/components/net/image/base.rs b/components/net/image/base.rs index 8192d469fde..78e3a0f1159 100644 --- a/components/net/image/base.rs +++ b/components/net/image/base.rs @@ -11,7 +11,7 @@ use png; pub type Image = png::Image; -static TEST_IMAGE: &'static [u8] = include_bin!("test.jpeg"); +static TEST_IMAGE: &'static [u8] = include_bytes!("test.jpeg"); pub fn test_image_bin() -> Vec<u8> { TEST_IMAGE.iter().map(|&x| x).collect() diff --git a/components/net/image/holder.rs b/components/net/image/holder.rs index 216f362328a..8ec15b02940 100644 --- a/components/net/image/holder.rs +++ b/components/net/image/holder.rs @@ -16,7 +16,7 @@ use url::Url; /// A struct to store image data. The image will be loaded once the first time it is requested, /// and an Arc will be stored. Clones of this Arc are given out on demand. -#[deriving(Clone)] +#[derive(Clone)] pub struct ImageHolder<NodeAddress> { url: Url, image: Option<Arc<Box<Image>>>, @@ -41,7 +41,7 @@ impl<NodeAddress: Send> ImageHolder<NodeAddress> { // should be done as early as possible and decode only once we // are sure that the image will be used. { - let val = holder.local_image_cache.lock(); + let val = holder.local_image_cache.lock().unwrap(); let mut local_image_cache = val; local_image_cache.prefetch(&holder.url); local_image_cache.decode(&holder.url); @@ -81,11 +81,11 @@ impl<NodeAddress: Send> ImageHolder<NodeAddress> { // the image and store it for the future if self.image.is_none() { let port = { - let val = self.local_image_cache.lock(); + let val = self.local_image_cache.lock().unwrap(); let mut local_image_cache = val; local_image_cache.get_image(node_address, &self.url) }; - match port.recv() { + match port.recv().unwrap() { ImageResponseMsg::ImageReady(image) => self.image = Some(image), ImageResponseMsg::ImageNotReady => debug!("image not ready for {}", self.url.serialize()), ImageResponseMsg::ImageFailed => debug!("image decoding failed for {}", self.url.serialize()), diff --git a/components/net/image_cache_task.rs b/components/net/image_cache_task.rs index 3197389caa5..6bc4875f39a 100644 --- a/components/net/image_cache_task.rs +++ b/components/net/image_cache_task.rs @@ -10,12 +10,11 @@ use resource_task::ProgressMsg::{Payload, Done}; use servo_util::task::spawn_named; use servo_util::taskpool::TaskPool; use std::borrow::ToOwned; -use std::comm::{channel, Receiver, Sender}; use std::collections::HashMap; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::mem::replace; use std::sync::{Arc, Mutex}; -use serialize::{Encoder, Encodable}; +use std::sync::mpsc::{channel, Receiver, Sender}; use url::Url; pub enum Msg { @@ -49,7 +48,7 @@ pub enum Msg { WaitForStorePrefetched(Sender<()>), } -#[deriving(Clone)] +#[derive(Clone)] pub enum ImageResponseMsg { ImageReady(Arc<Box<Image>>), ImageNotReady, @@ -68,25 +67,17 @@ impl PartialEq for ImageResponseMsg { } } -#[deriving(Clone)] +#[derive(Clone)] pub struct ImageCacheTask { chan: Sender<Msg>, } -impl<E, S: Encoder<E>> Encodable<S, E> for ImageCacheTask { - fn encode(&self, _: &mut S) -> Result<(), E> { - Ok(()) - } -} - -type DecoderFactory = fn() -> (proc(&[u8]) : 'static -> Option<Image>); - impl ImageCacheTask { pub fn new(resource_task: ResourceTask, task_pool: TaskPool) -> ImageCacheTask { let (chan, port) = channel(); let chan_clone = chan.clone(); - spawn_named("ImageCacheTask".to_owned(), proc() { + spawn_named("ImageCacheTask".to_owned(), move || { let mut cache = ImageCache { resource_task: resource_task, port: port, @@ -107,11 +98,11 @@ impl ImageCacheTask { pub fn new_sync(resource_task: ResourceTask, task_pool: TaskPool) -> ImageCacheTask { let (chan, port) = channel(); - spawn_named("ImageCacheTask (sync)".to_owned(), proc() { + spawn_named("ImageCacheTask (sync)".to_owned(), move || { let inner_cache = ImageCacheTask::new(resource_task, task_pool); loop { - let msg: Msg = port.recv(); + let msg: Msg = port.recv().unwrap(); match msg { Msg::GetImage(url, response) => { @@ -147,7 +138,7 @@ struct ImageCache { task_pool: TaskPool, } -#[deriving(Clone)] +#[derive(Clone)] enum ImageState { Init, Prefetching(AfterPrefetch), @@ -157,7 +148,7 @@ enum ImageState { Failed } -#[deriving(Clone)] +#[derive(Clone)] enum AfterPrefetch { DoDecode, DoNotDecode @@ -169,7 +160,7 @@ impl ImageCache { let mut store_prefetched_chan: Option<Sender<()>> = None; loop { - let msg = self.port.recv(); + let msg = self.port.recv().unwrap(); match msg { Msg::Prefetch(url) => self.prefetch(url), @@ -249,7 +240,7 @@ impl ImageCache { let resource_task = self.resource_task.clone(); let url_clone = url.clone(); - spawn_named("ImageCacheTask (prefetch)".to_owned(), proc() { + spawn_named("ImageCacheTask (prefetch)".to_owned(), move || { let url = url_clone; debug!("image_cache_task: started fetch for {}", url.serialize()); @@ -313,7 +304,7 @@ impl ImageCache { let to_cache = self.chan.clone(); let url_clone = url.clone(); - self.task_pool.execute(proc() { + self.task_pool.execute(move || { let url = url_clone; debug!("image_cache_task: started image decode for {}", url.serialize()); let image = load_from_memory(data.as_slice()); @@ -358,10 +349,10 @@ impl ImageCache { } - fn purge_waiters(&mut self, url: Url, f: || -> ImageResponseMsg) { + fn purge_waiters<F>(&mut self, url: Url, f: F) where F: Fn() -> ImageResponseMsg { match self.wait_map.remove(&url) { Some(waiters) => { - let items = waiters.lock(); + let items = waiters.lock().unwrap(); for response in items.iter() { response.send(f()); } @@ -373,11 +364,11 @@ impl ImageCache { fn get_image(&self, url: Url, response: Sender<ImageResponseMsg>) { match self.get_state(&url) { ImageState::Init => panic!("request for image before prefetch"), - ImageState::Prefetching(AfterPrefetch::DoDecode) => response.send(ImageResponseMsg::ImageNotReady), + ImageState::Prefetching(AfterPrefetch::DoDecode) => response.send(ImageResponseMsg::ImageNotReady).unwrap(), ImageState::Prefetching(AfterPrefetch::DoNotDecode) | ImageState::Prefetched(..) => panic!("request for image before decode"), - ImageState::Decoding => response.send(ImageResponseMsg::ImageNotReady), - ImageState::Decoded(image) => response.send(ImageResponseMsg::ImageReady(image)), - ImageState::Failed => response.send(ImageResponseMsg::ImageFailed), + ImageState::Decoding => response.send(ImageResponseMsg::ImageNotReady).unwrap(), + ImageState::Decoded(image) => response.send(ImageResponseMsg::ImageReady(image)).unwrap(), + ImageState::Failed => response.send(ImageResponseMsg::ImageFailed).unwrap(), } } @@ -391,10 +382,10 @@ impl ImageCache { // We don't have this image yet match self.wait_map.entry(url) { Occupied(mut entry) => { - entry.get_mut().lock().push(response); + entry.get_mut().lock().unwrap().push(response); } Vacant(entry) => { - entry.set(Arc::new(Mutex::new(vec!(response)))); + entry.insert(Arc::new(Mutex::new(vec!(response)))); } } } @@ -420,7 +411,7 @@ impl ImageCacheTaskClient for ImageCacheTask { fn exit(&self) { let (response_chan, response_port) = channel(); self.send(Msg::Exit(response_chan)); - response_port.recv(); + response_port.recv().unwrap(); } } @@ -450,9 +441,9 @@ fn load_image_data(url: Url, resource_task: ResourceTask) -> Result<Vec<u8>, ()> let mut image_data = vec!(); - let progress_port = response_port.recv().progress_port; + let progress_port = response_port.recv().unwrap().progress_port; loop { - match progress_port.recv() { + match progress_port.recv().unwrap() { Payload(data) => { image_data.push_all(data.as_slice()); } @@ -467,15 +458,18 @@ fn load_image_data(url: Url, resource_task: ResourceTask) -> Result<Vec<u8>, ()> } -pub fn spawn_listener<A: Send>(f: proc(Receiver<A>):Send) -> Sender<A> { +pub fn spawn_listener<F, A>(f: F) -> Sender<A> + where F: FnOnce(Receiver<A>) + Send, + A: Send +{ let (setup_chan, setup_port) = channel(); - spawn_named("ImageCacheTask (listener)".to_owned(), proc() { + spawn_named("ImageCacheTask (listener)".to_owned(), move || { let (chan, port) = channel(); setup_chan.send(chan); f(port); }); - setup_port.recv() + setup_port.recv().unwrap() } @@ -491,7 +485,7 @@ mod tests { use sniffer_task; use image::base::test_image_bin; use servo_util::taskpool::TaskPool; - use std::comm; + use std::sync::mpsc::{Sender, channel, Receiver}; use url::Url; trait Closure { @@ -541,7 +535,7 @@ mod tests { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { // Don't send the data until after the client requests // the image - self.wait_port.recv(); + self.wait_port.recv().unwrap(); response.send(Payload(test_image_bin())); response.send(Done(Ok(()))); } @@ -554,16 +548,16 @@ mod tests { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { // Don't send the data until after the client requests // the image - self.wait_port.recv(); + self.wait_port.recv().unwrap(); response.send(Payload(test_image_bin())); response.send(Done(Err("".to_string()))); } } fn mock_resource_task<T: Closure+Send>(on_load: Box<T>) -> ResourceTask { - spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) { + spawn_listener(move |port: Receiver<resource_task::ControlMsg>| { loop { - match port.recv() { + match port.recv().unwrap() { resource_task::ControlMsg::Load(response) => { let sniffer_task = sniffer_task::new_sniffer_task(); let senders = ResponseSenders { @@ -600,7 +594,7 @@ mod tests { let (chan, port) = channel(); image_cache_task.send(Msg::GetImage(url, chan)); - port.recv(); + port.recv().unwrap(); } #[test] @@ -613,14 +607,14 @@ mod tests { let url = Url::parse("file:///").unwrap(); image_cache_task.send(Prefetch(url)); - url_requested.recv(); + url_requested.recv().unwrap(); image_cache_task.exit(); mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] fn should_not_request_url_from_resource_task_on_multiple_prefetches() { - let (url_requested_chan, url_requested) = comm::channel(); + let (url_requested_chan, url_requested) = channel(); let mock_resource_task = mock_resource_task(box JustSendOK { url_requested_chan: url_requested_chan}); @@ -629,7 +623,7 @@ mod tests { image_cache_task.send(Prefetch(url.clone())); image_cache_task.send(Prefetch(url)); - url_requested.recv(); + url_requested.recv().unwrap(); image_cache_task.exit(); mock_resource_task.send(resource_task::ControlMsg::Exit); match url_requested.try_recv() { @@ -640,7 +634,7 @@ mod tests { #[test] fn should_return_image_not_ready_if_data_has_not_arrived() { - let (wait_chan, wait_port) = comm::channel(); + let (wait_chan, wait_port) = channel(); let mock_resource_task = mock_resource_task(box WaitSendTestImage{wait_port: wait_port}); @@ -649,9 +643,9 @@ mod tests { image_cache_task.send(Prefetch(url.clone())); image_cache_task.send(Decode(url.clone())); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url, response_chan)); - assert!(response_port.recv() == ImageResponseMsg::ImageNotReady); + assert!(response_port.recv().unwrap() == ImageResponseMsg::ImageNotReady); wait_chan.send(()); image_cache_task.exit(); mock_resource_task.send(resource_task::ControlMsg::Exit); @@ -670,11 +664,11 @@ mod tests { image_cache_task.send(Decode(url.clone())); // Wait until our mock resource task has sent the image to the image cache - join_port.recv(); + join_port.recv().unwrap(); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url, response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageReady(_) => (), _ => panic!("bleh") } @@ -696,12 +690,12 @@ mod tests { image_cache_task.send(Decode(url.clone())); // Wait until our mock resource task has sent the image to the image cache - join_port.recv(); + join_port.recv().unwrap(); for _ in range(0u32, 2u32) { - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url.clone(), response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageReady(_) => (), _ => panic!("bleh") } @@ -713,13 +707,13 @@ mod tests { #[test] fn should_not_request_image_from_resource_task_if_image_is_already_available() { - let (image_bin_sent_chan, image_bin_sent) = comm::channel(); + let (image_bin_sent_chan, image_bin_sent) = channel(); - let (resource_task_exited_chan, resource_task_exited) = comm::channel(); + let (resource_task_exited_chan, resource_task_exited) = channel(); - let mock_resource_task = spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) { + let mock_resource_task = spawn_listener(move |port: Receiver<resource_task::ControlMsg>| { loop { - match port.recv() { + match port.recv().unwrap() { resource_task::ControlMsg::Load(response) => { let sniffer_task = sniffer_task::new_sniffer_task(); let senders = ResponseSenders { @@ -746,14 +740,14 @@ mod tests { image_cache_task.send(Prefetch(url.clone())); // Wait until our mock resource task has sent the image to the image cache - image_bin_sent.recv(); + image_bin_sent.recv().unwrap(); image_cache_task.send(Prefetch(url.clone())); image_cache_task.exit(); mock_resource_task.send(resource_task::ControlMsg::Exit); - resource_task_exited.recv(); + resource_task_exited.recv().unwrap(); // Our resource task should not have received another request for the image // because it's already cached @@ -765,13 +759,13 @@ mod tests { #[test] fn should_not_request_image_from_resource_task_if_image_fetch_already_failed() { - let (image_bin_sent_chan, image_bin_sent) = comm::channel(); + let (image_bin_sent_chan, image_bin_sent) = channel(); - let (resource_task_exited_chan, resource_task_exited) = comm::channel(); + let (resource_task_exited_chan, resource_task_exited) = channel(); - let mock_resource_task = spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) { + let mock_resource_task = spawn_listener(move |port: Receiver<resource_task::ControlMsg>| { loop { - match port.recv() { + match port.recv().unwrap() { resource_task::ControlMsg::Load(response) => { let sniffer_task = sniffer_task::new_sniffer_task(); let senders = ResponseSenders { @@ -799,7 +793,7 @@ mod tests { image_cache_task.send(Decode(url.clone())); // Wait until our mock resource task has sent the image to the image cache - image_bin_sent.recv(); + image_bin_sent.recv().unwrap(); image_cache_task.send(Prefetch(url.clone())); image_cache_task.send(Decode(url.clone())); @@ -807,7 +801,7 @@ mod tests { image_cache_task.exit(); mock_resource_task.send(resource_task::ControlMsg::Exit); - resource_task_exited.recv(); + resource_task_exited.recv().unwrap(); // Our resource task should not have received another request for the image // because it's already cached @@ -830,11 +824,11 @@ mod tests { image_cache_task.send(Decode(url.clone())); // Wait until our mock resource task has sent the image to the image cache - join_port.recv(); + join_port.recv().unwrap(); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url, response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageFailed => (), _ => panic!("bleh") } @@ -856,19 +850,19 @@ mod tests { image_cache_task.send(Decode(url.clone())); // Wait until our mock resource task has sent the image to the image cache - join_port.recv(); + join_port.recv().unwrap(); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url.clone(), response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageFailed => (), _ => panic!("bleh") } // And ask again, we should get the same response - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url, response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageFailed => (), _ => panic!("bleh") } @@ -890,13 +884,13 @@ mod tests { image_cache_task.send(Decode(url.clone())); // Wait until our mock resource task has sent the image to the image cache - join_port.recv(); + join_port.recv().unwrap(); // Make the request - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url, response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageFailed => (), _ => panic!("bleh") } @@ -918,11 +912,11 @@ mod tests { image_cache_task.send(Decode(url.clone())); // Wait until our mock resource task has sent the image to the image cache - join_port.recv(); + join_port.recv().unwrap(); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::WaitForImage(url, response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageReady(..) => (), _ => panic!("bleh") } @@ -933,7 +927,7 @@ mod tests { #[test] fn should_return_image_on_wait_if_image_is_not_yet_loaded() { - let (wait_chan, wait_port) = comm::channel(); + let (wait_chan, wait_port) = channel(); let mock_resource_task = mock_resource_task(box WaitSendTestImage {wait_port: wait_port}); @@ -943,12 +937,12 @@ mod tests { image_cache_task.send(Prefetch(url.clone())); image_cache_task.send(Decode(url.clone())); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::WaitForImage(url, response_chan)); wait_chan.send(()); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageReady(..) => (), _ => panic!("bleh") } @@ -959,7 +953,7 @@ mod tests { #[test] fn should_return_image_failed_on_wait_if_image_fails_to_load() { - let (wait_chan, wait_port) = comm::channel(); + let (wait_chan, wait_port) = channel(); let mock_resource_task = mock_resource_task(box WaitSendTestImageErr{wait_port: wait_port}); @@ -969,12 +963,12 @@ mod tests { image_cache_task.send(Prefetch(url.clone())); image_cache_task.send(Decode(url.clone())); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::WaitForImage(url, response_chan)); wait_chan.send(()); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageFailed => (), _ => panic!("bleh") } @@ -993,9 +987,9 @@ mod tests { image_cache_task.send(Prefetch(url.clone())); image_cache_task.send(Decode(url.clone())); - let (response_chan, response_port) = comm::channel(); + let (response_chan, response_port) = channel(); image_cache_task.send(Msg::GetImage(url, response_chan)); - match response_port.recv() { + match response_port.recv().unwrap() { ImageResponseMsg::ImageReady(_) => (), _ => panic!("bleh") } diff --git a/components/net/lib.rs b/components/net/lib.rs index de1335b5c3b..96994a81ad7 100644 --- a/components/net/lib.rs +++ b/components/net/lib.rs @@ -2,17 +2,20 @@ * 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/. */ -#![feature(default_type_params, globs, phase)] +#![feature(int_uint)] +#![feature(unboxed_closures)] +#![feature(box_syntax)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] +#![allow(unstable)] extern crate collections; extern crate geom; extern crate hyper; extern crate png; -#[phase(plugin, link)] +#[macro_use] extern crate log; extern crate serialize; extern crate "util" as servo_util; diff --git a/components/net/local_image_cache.rs b/components/net/local_image_cache.rs index 51a4ccce7c6..8e8fa8da1df 100644 --- a/components/net/local_image_cache.rs +++ b/components/net/local_image_cache.rs @@ -11,14 +11,14 @@ multiple times and thus triggering reflows multiple times. use image_cache_task::{ImageCacheTask, ImageResponseMsg, Msg}; use std::borrow::ToOwned; -use std::comm::{Receiver, channel}; use std::collections::HashMap; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::sync::mpsc::{Receiver, channel}; use servo_util::task::spawn_named; use url::Url; pub trait ImageResponder<NodeAddress: Send> { - fn respond(&self) -> proc(ImageResponseMsg, NodeAddress):Send; + fn respond(&self) -> Box<Fn(ImageResponseMsg, NodeAddress)+Send>; } pub struct LocalImageCache<NodeAddress> { @@ -39,7 +39,7 @@ impl<NodeAddress: Send> LocalImageCache<NodeAddress> { } } -#[deriving(Clone)] +#[derive(Clone)] struct ImageState { prefetched: bool, decoded: bool, @@ -118,7 +118,7 @@ impl<NodeAddress: Send> LocalImageCache<NodeAddress> { let (response_chan, response_port) = channel(); self.image_cache_task.send(Msg::GetImage((*url).clone(), response_chan)); - let response = response_port.recv(); + let response = response_port.recv().unwrap(); match response { ImageResponseMsg::ImageNotReady => { // Need to reflow when the image is available @@ -128,13 +128,13 @@ impl<NodeAddress: Send> LocalImageCache<NodeAddress> { // on the image to load and triggering layout let image_cache_task = self.image_cache_task.clone(); assert!(self.on_image_available.is_some()); - let on_image_available: proc(ImageResponseMsg, NodeAddress):Send = + let on_image_available = self.on_image_available.as_ref().unwrap().respond(); let url = (*url).clone(); - spawn_named("LocalImageCache".to_owned(), proc() { + spawn_named("LocalImageCache".to_owned(), move || { let (response_chan, response_port) = channel(); image_cache_task.send(Msg::WaitForImage(url, response_chan)); - on_image_available(response_port.recv(), node_address); + on_image_available(response_port.recv().unwrap(), node_address); }); } _ => () @@ -157,7 +157,7 @@ impl<NodeAddress: Send> LocalImageCache<NodeAddress> { match self.state_map.entry((*url).clone()) { Occupied(entry) => entry.into_mut(), Vacant(entry) => - entry.set(ImageState { + entry.insert(ImageState { prefetched: false, decoded: false, last_request_round: 0, diff --git a/components/net/resource_task.rs b/components/net/resource_task.rs index b33665ba6c8..3093df5e56a 100644 --- a/components/net/resource_task.rs +++ b/components/net/resource_task.rs @@ -21,7 +21,7 @@ use hyper::mime::{Mime, Attr}; use url::Url; use std::borrow::ToOwned; -use std::comm::{channel, Receiver, Sender}; +use std::sync::mpsc::{channel, Receiver, Sender}; pub enum ControlMsg { /// Request the data associated with a particular URL @@ -29,7 +29,7 @@ pub enum ControlMsg { Exit } -#[deriving(Clone)] +#[derive(Clone)] pub struct LoadData { pub url: Url, pub method: Method, @@ -52,7 +52,7 @@ impl LoadData { } } -#[deriving(Clone)] +#[derive(Clone)] pub struct ResourceCORSData { /// CORS Preflight flag pub preflight: bool, @@ -131,7 +131,7 @@ pub struct ResponseSenders { } /// Messages sent in response to a `Load` message -#[deriving(PartialEq,Show)] +#[derive(PartialEq,Show)] pub enum ProgressMsg { /// Binary data - there may be multiple of these Payload(Vec<u8>), @@ -147,7 +147,7 @@ pub fn start_sending(senders: ResponseSenders, metadata: Metadata) -> Sender<Pro /// For use by loaders in responding to a Load message. pub fn start_sending_opt(senders: ResponseSenders, metadata: Metadata) -> Result<Sender<ProgressMsg>, ()> { let (progress_chan, progress_port) = channel(); - let result = senders.immediate_consumer.send_opt(TargetedLoadResponse { + let result = senders.immediate_consumer.send(TargetedLoadResponse { load_response: LoadResponse { metadata: metadata, progress_port: progress_port, @@ -165,11 +165,11 @@ pub fn load_whole_resource(resource_task: &ResourceTask, url: Url) -> Result<(Metadata, Vec<u8>), String> { let (start_chan, start_port) = channel(); resource_task.send(ControlMsg::Load(LoadData::new(url, start_chan))); - let response = start_port.recv(); + let response = start_port.recv().unwrap(); let mut buf = vec!(); loop { - match response.progress_port.recv() { + match response.progress_port.recv().unwrap() { ProgressMsg::Payload(data) => buf.push_all(data.as_slice()), ProgressMsg::Done(Ok(())) => return Ok((response.metadata, buf)), ProgressMsg::Done(Err(e)) => return Err(e) @@ -184,7 +184,7 @@ pub type ResourceTask = Sender<ControlMsg>; pub fn new_resource_task(user_agent: Option<String>) -> ResourceTask { let (setup_chan, setup_port) = channel(); let sniffer_task = sniffer_task::new_sniffer_task(); - spawn_named("ResourceManager".to_owned(), proc() { + spawn_named("ResourceManager".to_owned(), move || { ResourceManager::new(setup_port, user_agent, sniffer_task).start(); }); setup_chan @@ -210,7 +210,7 @@ impl ResourceManager { impl ResourceManager { fn start(&self) { loop { - match self.from_client.recv() { + match self.from_client.recv().unwrap() { ControlMsg::Load(load_data) => { self.load(load_data) } @@ -229,21 +229,19 @@ impl ResourceManager { eventual_consumer: load_data.consumer.clone(), }; - let loader = match load_data.url.scheme.as_slice() { - "file" => file_loader::factory, - "http" | "https" => http_loader::factory, - "data" => data_loader::factory, - "about" => about_loader::factory, + debug!("resource_task: loading url: {}", load_data.url.serialize()); + match load_data.url.scheme.as_slice() { + "file" => file_loader::factory(load_data, self.sniffer_task.clone()), + "http" | "https" => http_loader::factory(load_data, self.sniffer_task.clone()), + "data" => data_loader::factory(load_data, self.sniffer_task.clone()), + "about" => about_loader::factory(load_data, self.sniffer_task.clone()), _ => { debug!("resource_task: no loader for scheme {}", load_data.url.scheme); start_sending(senders, Metadata::default(load_data.url)) .send(ProgressMsg::Done(Err("no loader for scheme".to_string()))); return } - }; - debug!("resource_task: loading url: {}", load_data.url.serialize()); - - loader(load_data, self.sniffer_task.clone()); + } } } @@ -252,7 +250,7 @@ pub fn load_bytes_iter(resource_task: &ResourceTask, url: Url) -> (Metadata, Pro let (input_chan, input_port) = channel(); resource_task.send(ControlMsg::Load(LoadData::new(url, input_chan))); - let response = input_port.recv(); + let response = input_port.recv().unwrap(); let iter = ProgressMsgPortIterator { progress_port: response.progress_port }; (response.metadata, iter) } @@ -262,9 +260,11 @@ pub struct ProgressMsgPortIterator { progress_port: Receiver<ProgressMsg> } -impl Iterator<Vec<u8>> for ProgressMsgPortIterator { +impl Iterator for ProgressMsgPortIterator { + type Item = Vec<u8>; + fn next(&mut self) -> Option<Vec<u8>> { - match self.progress_port.recv() { + match self.progress_port.recv().unwrap() { ProgressMsg::Payload(data) => Some(data), ProgressMsg::Done(Ok(())) => None, ProgressMsg::Done(Err(e)) => { @@ -287,8 +287,8 @@ fn test_bad_scheme() { let (start_chan, start) = channel(); let url = Url::parse("bogus://whatever").unwrap(); resource_task.send(ControlMsg::Load(LoadData::new(url, start_chan))); - let response = start.recv(); - match response.progress_port.recv() { + let response = start.recv().unwrap(); + match response.progress_port.recv().unwrap() { ProgressMsg::Done(result) => { assert!(result.is_err()) } _ => panic!("bleh") } diff --git a/components/net/sniffer_task.rs b/components/net/sniffer_task.rs index 2fcc0394f52..2b9b2363a0a 100644 --- a/components/net/sniffer_task.rs +++ b/components/net/sniffer_task.rs @@ -3,16 +3,16 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A task that sniffs data -use std::comm::{channel, Receiver, Sender}; -use std::task::TaskBuilder; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::thread::Builder; use resource_task::{TargetedLoadResponse}; pub type SnifferTask = Sender<TargetedLoadResponse>; pub fn new_sniffer_task() -> SnifferTask { let(sen, rec) = channel(); - let builder = TaskBuilder::new().named("SnifferManager"); - builder.spawn(proc() { + let builder = Builder::new().name("SnifferManager".to_string()); + builder.spawn(move || { SnifferManager::new(rec).start(); }); sen @@ -33,9 +33,9 @@ impl SnifferManager { impl SnifferManager { fn start(self) { loop { - match self.data_receiver.recv_opt() { + match self.data_receiver.recv() { Ok(snif_data) => { - let _ = snif_data.consumer.send_opt(snif_data.load_response); + let _ = snif_data.consumer.send(snif_data.load_response); } Err(_) => break, } diff --git a/components/net/storage_task.rs b/components/net/storage_task.rs index aafe0885992..ac65fa65bc0 100644 --- a/components/net/storage_task.rs +++ b/components/net/storage_task.rs @@ -3,9 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::ToOwned; -use std::comm::{channel, Receiver, Sender}; use std::collections::HashMap; -use std::collections::TreeMap; +use std::collections::BTreeMap; +use std::sync::mpsc::{channel, Receiver, Sender}; use url::Url; use servo_util::str::DOMString; @@ -40,14 +40,14 @@ pub enum StorageTaskMsg { pub type StorageTask = Sender<StorageTaskMsg>; pub trait StorageTaskFactory { - fn new() -> StorageTask; + fn new() -> Self; } impl StorageTaskFactory for StorageTask { /// Create a StorageTask fn new() -> StorageTask { let (chan, port) = channel(); - spawn_named("StorageManager".to_owned(), proc() { + spawn_named("StorageManager".to_owned(), move || { StorageManager::new(port).start(); }); chan @@ -56,7 +56,7 @@ impl StorageTaskFactory for StorageTask { struct StorageManager { port: Receiver<StorageTaskMsg>, - data: HashMap<String, TreeMap<DOMString, DOMString>>, + data: HashMap<String, BTreeMap<DOMString, DOMString>>, } impl StorageManager { @@ -71,7 +71,7 @@ impl StorageManager { impl StorageManager { fn start(&mut self) { loop { - match self.port.recv() { + match self.port.recv().unwrap() { StorageTaskMsg::Length(sender, url) => { self.length(sender, url) } @@ -112,7 +112,7 @@ impl StorageManager { fn set_item(&mut self, sender: Sender<bool>, url: Url, name: DOMString, value: DOMString) { let origin = self.get_origin_as_string(url); if !self.data.contains_key(&origin) { - self.data.insert(origin.clone(), TreeMap::new()); + self.data.insert(origin.clone(), BTreeMap::new()); } let updated = self.data.get_mut(&origin).map(|entry| { diff --git a/components/plugins/jstraceable.rs b/components/plugins/jstraceable.rs index fb06b6a649a..47f2c99d274 100644 --- a/components/plugins/jstraceable.rs +++ b/components/plugins/jstraceable.rs @@ -15,7 +15,7 @@ use syntax::parse::token::InternedString; pub fn expand_dom_struct(_: &mut ExtCtxt, _: Span, _: &MetaItem, item: P<Item>) -> P<Item> { let mut item2 = (*item).clone(); { - let add_attr = |s| { + let mut add_attr = |&mut :s| { item2.attrs.push(attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_word_item(InternedString::new(s)))); }; add_attr("must_root"); @@ -34,7 +34,7 @@ pub fn expand_dom_struct(_: &mut ExtCtxt, _: Span, _: &MetaItem, item: P<Item>) /// Provides the hook to expand `#[jstraceable]` into an implementation of `JSTraceable` /// /// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do not implement the method. -pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: |P<Item>|) { +pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, mut push: Box<FnMut(P<Item>)>) { let trait_def = TraitDef { span: span, attributes: Vec::new(), @@ -51,13 +51,11 @@ pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: attributes: vec!(attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_name_value_item_str(InternedString::new("inline"), InternedString::new("always")))), - combine_substructure: combine_substructure(|a, b, c| { - jstraceable_substructure(a, b, c) - }) + combine_substructure: combine_substructure(box jstraceable_substructure) } ) }; - trait_def.expand(cx, mitem, item, push) + trait_def.expand(cx, mitem, item, |:a| push(a)) } // Mostly copied from syntax::ext::deriving::hash @@ -68,7 +66,7 @@ fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substru _ => cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`") }; let trace_ident = substr.method_ident; - let call_trace = |span, thing_expr| { + let call_trace = |&:span, thing_expr| { let expr = cx.expr_method_call(span, thing_expr, trace_ident, vec!(state_expr.clone())); cx.stmt_expr(expr) }; diff --git a/components/plugins/lib.rs b/components/plugins/lib.rs index f6494eadfd3..6190114ac39 100644 --- a/components/plugins/lib.rs +++ b/components/plugins/lib.rs @@ -12,15 +12,18 @@ //! - `#[dom_struct]` : Implies `#[privatize]`,`#[jstraceable]`, and `#[must_root]`. //! Use this for structs that correspond to a DOM type -#![feature(macro_rules, plugin_registrar, quote, phase)] +#![feature(plugin_registrar, quote, plugin, box_syntax)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] +#![allow(unstable)] -#[phase(plugin,link)] +#[plugin] +#[macro_use] extern crate syntax; -#[phase(plugin, link)] +#[plugin] +#[macro_use] extern crate rustc; use rustc::lint::LintPassObject; @@ -50,23 +53,3 @@ pub fn plugin_registrar(reg: &mut Registry) { reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject); reg.register_lint_pass(box lints::ban::BanPass as LintPassObject); } - - -#[macro_export] -macro_rules! match_ignore_ascii_case { - ( $value: expr: $( $string: expr => $result: expr ),+ _ => $fallback: expr, ) => { - match_ignore_ascii_case! { $value: - $( $string => $result ),+ - _ => $fallback - } - }; - ( $value: expr: $( $string: expr => $result: expr ),+ _ => $fallback: expr ) => { - { - use std::ascii::AsciiExt; - match $value.as_slice() { - $( s if s.eq_ignore_ascii_case($string) => $result, )+ - _ => $fallback - } - } - }; -} diff --git a/components/plugins/lints/ban.rs b/components/plugins/lints/ban.rs index 78761c274f4..a4c3b7cea07 100644 --- a/components/plugins/lints/ban.rs +++ b/components/plugins/lints/ban.rs @@ -7,7 +7,7 @@ use rustc::lint::{Context, LintPass, LintArray}; use utils::match_ty_unwrap; declare_lint!(BANNED_TYPE, Deny, - "Ban various unsafe type combinations") + "Ban various unsafe type combinations"); /// Lint for banning various unsafe types /// diff --git a/components/plugins/lints/inheritance_integrity.rs b/components/plugins/lints/inheritance_integrity.rs index fa3f42770f0..d806b1cad1c 100644 --- a/components/plugins/lints/inheritance_integrity.rs +++ b/components/plugins/lints/inheritance_integrity.rs @@ -9,7 +9,7 @@ use rustc::middle::{ty, def}; use utils::match_lang_ty; declare_lint!(INHERITANCE_INTEGRITY, Deny, - "Ensures that struct fields are properly laid out for inheritance to work") + "Ensures that struct fields are properly laid out for inheritance to work"); /// Lint for ensuring proper layout of DOM structs /// diff --git a/components/plugins/lints/privatize.rs b/components/plugins/lints/privatize.rs index 379fa946b43..475338dee07 100644 --- a/components/plugins/lints/privatize.rs +++ b/components/plugins/lints/privatize.rs @@ -9,7 +9,7 @@ use rustc::lint::{Context, LintPass, LintArray}; use rustc::middle::ty; declare_lint!(PRIVATIZE, Deny, - "Allows to enforce private fields for struct definitions") + "Allows to enforce private fields for struct definitions"); /// Lint for keeping DOM fields private /// diff --git a/components/plugins/lints/str_to_string.rs b/components/plugins/lints/str_to_string.rs index d6272f4d629..d93268844e0 100644 --- a/components/plugins/lints/str_to_string.rs +++ b/components/plugins/lints/str_to_string.rs @@ -8,7 +8,7 @@ use rustc::middle::ty::expr_ty; use rustc::middle::ty; declare_lint!(STR_TO_STRING, Deny, - "Warn when a String could use to_owned() instead of to_string()") + "Warn when a String could use to_owned() instead of to_string()"); /// Prefer str.to_owned() over str.to_string() /// diff --git a/components/plugins/lints/transmute_type.rs b/components/plugins/lints/transmute_type.rs index 674f14c3c7d..6facd362108 100644 --- a/components/plugins/lints/transmute_type.rs +++ b/components/plugins/lints/transmute_type.rs @@ -9,7 +9,7 @@ use rustc::middle::ty::expr_ty; use rustc::util::ppaux::Repr; declare_lint!(TRANSMUTE_TYPE_LINT, Allow, - "Warn and report types being transmuted") + "Warn and report types being transmuted"); /// Lint for auditing transmutes /// diff --git a/components/plugins/lints/unrooted_must_root.rs b/components/plugins/lints/unrooted_must_root.rs index 636ff472fff..80b37a714ba 100644 --- a/components/plugins/lints/unrooted_must_root.rs +++ b/components/plugins/lints/unrooted_must_root.rs @@ -11,7 +11,7 @@ use rustc::util::ppaux::Repr; use utils::unsafe_context; declare_lint!(UNROOTED_MUST_ROOT, Deny, - "Warn and report usage of unrooted jsmanaged objects") + "Warn and report usage of unrooted jsmanaged objects"); /// Lint for ensuring safe usage of unrooted pointers /// @@ -84,7 +84,7 @@ impl LintPass for UnrootedPass { return; }, visit::FkItemFn(_, _, style, _) => match style { - ast::UnsafeFn => return, + ast::Unsafety::Unsafe => return, _ => () }, _ => () diff --git a/components/plugins/reflector.rs b/components/plugins/reflector.rs index 4b0681c4d39..43f2f625df4 100644 --- a/components/plugins/reflector.rs +++ b/components/plugins/reflector.rs @@ -10,7 +10,7 @@ use syntax::ast; use utils::match_ty_unwrap; -pub fn expand_reflector(cx: &mut ExtCtxt, span: Span, _: &MetaItem, item: &Item, push: |P<Item>|) { +pub fn expand_reflector(cx: &mut ExtCtxt, span: Span, _: &MetaItem, item: &Item, mut push: Box<FnMut(P<Item>) -> ()>) { if let ast::ItemStruct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time diff --git a/components/plugins/utils.rs b/components/plugins/utils.rs index 6f7f00f9109..e9db633f2d4 100644 --- a/components/plugins/utils.rs +++ b/components/plugins/utils.rs @@ -70,7 +70,7 @@ pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool { match *itm { ast::MethodImplItem(ref meth) => match meth.node { ast::MethDecl(_, _, _, _, style, _, _, _) => match style { - ast::UnsafeFn => true, + ast::Unsafety::Unsafe => true, _ => false, }, _ => false, @@ -81,7 +81,7 @@ pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool { Some(ast_map::NodeItem(itm)) => { match itm.node { ast::ItemFn(_, style, _, _, _) => match style { - ast::UnsafeFn => true, + ast::Unsafety::Unsafe => true, _ => false, }, _ => false, diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index 2a211eb52d5..08c5cc732b8 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -55,9 +55,6 @@ branch = "servo" [dependencies.js] git = "https://github.com/servo/rust-mozjs" -[dependencies.url] -git = "https://github.com/servo/rust-url" - [dependencies.uuid] git = "https://github.com/rust-lang/uuid" @@ -67,8 +64,7 @@ git = "https://github.com/servo/string-cache" [dependencies.string_cache_macros] git = "https://github.com/servo/string-cache" -[dependencies.time] -git = "https://github.com/rust-lang/time" - [dependencies] encoding = "0.2" +url = "*" +time = "*"
\ No newline at end of file diff --git a/components/script/cors.rs b/components/script/cors.rs index e7fd20d866c..a770a90e69f 100644 --- a/components/script/cors.rs +++ b/components/script/cors.rs @@ -16,7 +16,7 @@ use time; use time::{now, Timespec}; use hyper::header::{Headers, Header, HeaderFormat, HeaderView}; -use hyper::header::common::util as header_util; +use hyper::header::shared::util as header_util; use hyper::client::Request; use hyper::mime::{Mime, TopLevel, SubLevel}; use hyper::header::common::{ContentType, Host}; @@ -25,7 +25,7 @@ use hyper::status::StatusClass::Success; use url::{SchemeData, Url}; -#[deriving(Clone)] +#[derive(Clone)] pub struct CORSRequest { pub origin: Url, pub destination: Url, @@ -40,7 +40,7 @@ pub struct CORSRequest { /// http://fetch.spec.whatwg.org/#concept-request-mode /// This only covers some of the request modes. The /// `same-origin` and `no CORS` modes are unnecessary for XHR. -#[deriving(PartialEq, Copy, Clone)] +#[derive(PartialEq, Copy, Clone)] pub enum RequestMode { CORS, // CORS ForcedPreflight // CORS-with-forced-preflight @@ -126,7 +126,7 @@ impl CORSRequest { // Step 5 - 7 let mut header_names = vec!(); for header in self.headers.iter() { - header_names.push(header.name().to_ascii_lower()); + header_names.push(header.name().to_ascii_lowercase()); } header_names.sort(); preflight.headers.set(AccessControlRequestHeaders(header_names)); @@ -240,12 +240,12 @@ impl CORSResponse { // CORS Cache stuff /// A CORS cache object. Anchor it somewhere to the user agent. -#[deriving(Clone)] +#[derive(Clone)] pub struct CORSCache(Vec<CORSCacheEntry>); /// Union type for CORS cache entries /// Each entry might pertain to a header or method -#[deriving(Clone)] +#[derive(Clone)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method) @@ -268,7 +268,7 @@ impl HeaderOrMethod { } // An entry in the CORS cache -#[deriving(Clone)] +#[derive(Clone)] pub struct CORSCacheEntry { pub origin: Url, pub url: Url, @@ -361,7 +361,7 @@ impl CORSCache { fn is_simple_header(h: &HeaderView) -> bool { //FIXME: use h.is::<HeaderType>() when AcceptLanguage and //ContentLanguage headers exist - match h.name().to_ascii_lower().as_slice() { + match h.name().to_ascii_lowercase().as_slice() { "accept" | "accept-language" | "content-language" => true, "content-type" => match h.value() { Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) | @@ -383,7 +383,7 @@ fn is_simple_method(m: &Method) -> bool { } //XXX(seanmonstar): worth uplifting to Hyper? -#[deriving(Clone)] +#[derive(Clone)] struct AccessControlRequestMethod(pub Method); impl Header for AccessControlRequestMethod { @@ -404,7 +404,7 @@ impl HeaderFormat for AccessControlRequestMethod { } } -#[deriving(Clone)] +#[derive(Clone)] struct AccessControlRequestHeaders(pub Vec<String>); impl Header for AccessControlRequestHeaders { @@ -425,7 +425,7 @@ impl HeaderFormat for AccessControlRequestHeaders { } } -#[deriving(Clone)] +#[derive(Clone)] struct AccessControlAllowMethods(pub Vec<Method>); impl Header for AccessControlAllowMethods { @@ -446,7 +446,7 @@ impl HeaderFormat for AccessControlAllowMethods { } } -#[deriving(Clone)] +#[derive(Clone)] struct AccessControlAllowHeaders(pub Vec<String>); impl Header for AccessControlAllowHeaders { @@ -467,7 +467,7 @@ impl HeaderFormat for AccessControlAllowHeaders { } } -#[deriving(Clone)] +#[derive(Clone)] enum AccessControlAllowOrigin { AllowStar, AllowOrigin(Url), @@ -482,7 +482,7 @@ impl Header for AccessControlAllowOrigin { fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlAllowOrigin> { if raw.len() == 1 { - from_utf8(raw[0].as_slice()).and_then(|s| { + from_utf8(raw[0].as_slice()).ok().and_then(|s| { if s == "*" { Some(AccessControlAllowOrigin::AllowStar) } else { @@ -504,7 +504,7 @@ impl HeaderFormat for AccessControlAllowOrigin { } } -#[deriving(Clone)] +#[derive(Clone)] struct AccessControlMaxAge(pub u32); impl Header for AccessControlMaxAge { diff --git a/components/script/devtools.rs b/components/script/devtools.rs index aedff559fe8..b4e0c4f3777 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -18,6 +18,8 @@ use dom::document::DocumentHelpers; use page::Page; use servo_msg::constellation_msg::PipelineId; use script_task::get_page; + +use std::sync::mpsc::Sender; use std::rc::Rc; diff --git a/components/script/dom/attr.rs b/components/script/dom/attr.rs index 789e5f925d6..e8a66199db7 100644 --- a/components/script/dom/attr.rs +++ b/components/script/dom/attr.rs @@ -29,7 +29,7 @@ pub enum AttrSettingType { ReplacedAttr, } -#[deriving(PartialEq, Clone)] +#[derive(PartialEq, Clone)] #[jstraceable] pub enum AttrValue { String(DOMString), @@ -58,7 +58,8 @@ impl AttrValue { } pub fn from_u32(string: DOMString, default: u32) -> AttrValue { - let result: u32 = from_str(string.as_slice()).unwrap_or(default); + // XXX Is parse() correct? + let result: u32 = string.parse().unwrap_or(default); AttrValue::UInt(string, result) } diff --git a/components/script/dom/bindings/callback.rs b/components/script/dom/bindings/callback.rs index 6b8fcc09e34..3bfc0c107a4 100644 --- a/components/script/dom/bindings/callback.rs +++ b/components/script/dom/bindings/callback.rs @@ -14,10 +14,11 @@ use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException use js::jsval::{JSVal, UndefinedValue}; use js::rust::with_compartment; +use std::ffi::CString; use std::ptr; /// The exception handling used for a call. -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] pub enum ExceptionHandling { /// Report any exception and don't throw it to the caller code. Report, @@ -26,7 +27,7 @@ pub enum ExceptionHandling { } /// A common base class for representing IDL callback function types. -#[deriving(Copy, Clone,PartialEq)] +#[derive(Copy, Clone,PartialEq)] #[jstraceable] pub struct CallbackFunction { object: CallbackObject @@ -44,7 +45,7 @@ impl CallbackFunction { } /// A common base class for representing IDL callback interface types. -#[deriving(Copy, Clone,PartialEq)] +#[derive(Copy, Clone,PartialEq)] #[jstraceable] pub struct CallbackInterface { object: CallbackObject @@ -53,7 +54,7 @@ pub struct CallbackInterface { /// A common base class for representing IDL callback function and /// callback interface types. #[allow(raw_pointer_deriving)] -#[deriving(Copy, Clone,PartialEq)] +#[derive(Copy, Clone,PartialEq)] #[jstraceable] struct CallbackObject { /// The underlying `JSObject`. @@ -99,7 +100,7 @@ impl CallbackInterface { pub fn GetCallableProperty(&self, cx: *mut JSContext, name: &str) -> Result<JSVal, ()> { let mut callable = UndefinedValue(); unsafe { - let name = name.to_c_str(); + let name = CString::from_slice(name.as_bytes()); if JS_GetProperty(cx, self.callback(), name.as_ptr(), &mut callable) == 0 { return Err(()); } diff --git a/components/script/dom/bindings/codegen/Bindings.conf b/components/script/dom/bindings/codegen/Bindings.conf index 48b6067d00c..439ddfbd59e 100644 --- a/components/script/dom/bindings/codegen/Bindings.conf +++ b/components/script/dom/bindings/codegen/Bindings.conf @@ -15,7 +15,7 @@ DOMInterfaces = { 'Window': { - 'outerObjectHook': 'Some(bindings::utils::outerize_global)', + 'outerObjectHook': 'Some(bindings::utils::outerize_global as extern fn(*mut JSContext, JSHandleObject) -> *mut JSObject)', }, #FIXME(jdm): This should be 'register': False, but then we don't generate enum types diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e1e5bee2036..47dd912d700 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -679,7 +679,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, value = "Some(%s)" % value default = ( - "const data: [u8, ..%s] = [ %s ];\n" + "const data: [u8; %s] = [ %s ];\n" "%s" % (len(defaultValue.value) + 1, ", ".join(["'" + char + "' as u8" for char in defaultValue.value] + ["0"]), @@ -1189,14 +1189,16 @@ class MethodDefiner(PropertyDefiner): def specData(m): if m.get("methodInfo", True): jitinfo = ("&%s_methodinfo" % m["name"]) - accessor = "genericMethod" + accessor = "genericMethod as NonNullJSNative" else: jitinfo = "0 as *const JSJitInfo" accessor = m.get("nativeName", m["name"]) + if accessor[0:3] != 'JS_': + accessor = "%s as NonNullJSNative" % accessor return (m["name"], accessor, jitinfo, m["length"], m["flags"]) def stringDecl(m): - return "const %s_name: [u8, ..%i] = %s;\n" % (m["name"], len(m["name"]) + 1, + return "const %s_name: [u8; %i] = %s;\n" % (m["name"], len(m["name"]) + 1, str_to_const_array(m["name"])) decls = ''.join([stringDecl(m) for m in array]) @@ -1236,7 +1238,7 @@ class AttrDefiner(PropertyDefiner): accessor = "genericGetter" jitinfo = "&%s_getterinfo" % attr.identifier.name - return ("JSPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *const JSJitInfo}" + return ("JSPropertyOpWrapper {op: Some(%(native)s as NonNullJSNative), info: %(info)s as *const JSJitInfo}" % {"info" : jitinfo, "native" : accessor}) @@ -1254,7 +1256,7 @@ class AttrDefiner(PropertyDefiner): accessor = "genericSetter" jitinfo = "&%s_setterinfo" % attr.identifier.name - return ("JSStrictPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *const JSJitInfo}" + return ("JSStrictPropertyOpWrapper {op: Some(%(native)s as NonNullJSNative), info: %(info)s as *const JSJitInfo}" % {"info" : jitinfo, "native" : accessor}) @@ -1264,7 +1266,7 @@ class AttrDefiner(PropertyDefiner): def stringDecl(attr): name = attr.identifier.name - return "const %s_name: [u8, ..%i] = %s;\n" % (name, len(name) + 1, + return "const %s_name: [u8; %i] = %s;\n" % (name, len(name) + 1, str_to_const_array(name)) decls = ''.join([stringDecl(m) for m in array]) @@ -1434,7 +1436,7 @@ class CGDOMJSClass(CGThing): self.descriptor = descriptor def define(self): - traceHook = "Some(%s)" % TRACE_HOOK_NAME + traceHook = 'Some(%s as unsafe extern "C" fn(*mut JSTracer, *mut JSObject))' % TRACE_HOOK_NAME if self.descriptor.isGlobal(): flags = "JSCLASS_IS_GLOBAL | JSCLASS_DOM_GLOBAL" slots = "JSCLASS_GLOBAL_SLOT_COUNT + 1" @@ -1442,7 +1444,7 @@ class CGDOMJSClass(CGThing): flags = "0" slots = "1" return """\ -const Class_name: [u8, ..%i] = %s; +const Class_name: [u8; %i] = %s; static Class: DOMJSClass = DOMJSClass { base: js::Class { name: &Class_name as *const u8 as *const libc::c_char, @@ -1454,7 +1456,7 @@ static Class: DOMJSClass = DOMJSClass { enumerate: Some(JS_EnumerateStub), resolve: Some(JS_ResolveStub), convert: Some(JS_ConvertStub), - finalize: Some(%s), + finalize: Some(%s as unsafe extern "C" fn(*mut JSFreeOp, *mut JSObject)), checkAccess: None, call: None, hasInstance: None, @@ -1526,7 +1528,7 @@ class CGPrototypeJSClass(CGThing): def define(self): return """\ -const PrototypeClassName__: [u8, ..%s] = %s; +const PrototypeClassName__: [u8; %s] = %s; static PrototypeClass: JSClass = JSClass { name: &PrototypeClassName__ as *const u8 as *const libc::c_char, flags: (1 & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT as uint, //JSCLASS_HAS_RESERVED_SLOTS(1) @@ -1543,7 +1545,7 @@ static PrototypeClass: JSClass = JSClass { hasInstance: None, construct: None, trace: None, - reserved: [0 as *mut libc::c_void, ..40] + reserved: [0 as *mut libc::c_void; 40] }; """ % (len(self.descriptor.interface.identifier.name + "Prototype") + 1, str_to_const_array(self.descriptor.interface.identifier.name + "Prototype")) @@ -1992,7 +1994,7 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): constructHook = "ThrowingConstructor" constructArgs = 0 - constructor = 'Some((%s, "%s", %d))' % ( + constructor = 'Some((%s as NonNullJSNative, "%s", %d))' % ( constructHook, self.descriptor.interface.identifier.name, constructArgs) else: @@ -2096,16 +2098,16 @@ class CGDefineProxyHandler(CGAbstractMethod): body = """\ let traps = ProxyTraps { - getPropertyDescriptor: Some(getPropertyDescriptor), - getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), - defineProperty: Some(%s), - getOwnPropertyNames: Some(getOwnPropertyNames_), - delete_: Some(%s), - enumerate: Some(enumerate_), + getPropertyDescriptor: Some(getPropertyDescriptor as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, bool, *mut JSPropertyDescriptor) -> bool), + getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, bool, *mut JSPropertyDescriptor) -> bool), + defineProperty: Some(%s as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut JSPropertyDescriptor) -> bool), + getOwnPropertyNames: Some(getOwnPropertyNames_ as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut AutoIdVector) -> bool), + delete_: Some(%s as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut bool) -> bool), + enumerate: Some(enumerate_ as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut AutoIdVector) -> bool), has: None, - hasOwn: Some(hasOwn), - get: Some(get), + hasOwn: Some(hasOwn as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut bool) -> bool), + get: Some(get as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut JSObject, jsid, *mut JSVal) -> bool), set: None, keys: None, iterate: None, @@ -2116,15 +2118,15 @@ let traps = ProxyTraps { hasInstance: None, typeOf: None, objectClassIs: None, - obj_toString: Some(obj_toString), + obj_toString: Some(obj_toString as unsafe extern "C" fn(*mut JSContext, *mut JSObject) -> *mut js::jsapi::JSString), fun_toString: None, //regexp_toShared: ptr::null(), defaultValue: None, iteratorNext: None, - finalize: Some(%s), + finalize: Some(%s as unsafe extern "C" fn(*mut JSFreeOp, *mut JSObject)), getElementIfPresent: None, getPrototypeOf: None, - trace: Some(%s) + trace: Some(%s as unsafe extern "C" fn(*mut JSTracer, *mut JSObject)) }; CreateProxyHandler(&traps, &Class as *const _ as *const _)\ @@ -2763,7 +2765,7 @@ class CGEnum(CGThing): decl = """\ #[repr(uint)] -#[deriving(PartialEq, Copy)] +#[derive(PartialEq, Copy)] #[jstraceable] pub enum %s { %s @@ -4256,7 +4258,7 @@ class CGNonNamespacedEnum(CGThing): # Build the enum body. enumstr = comment + 'pub enum %s {\n%s\n}\n' % (enumName, ',\n'.join(entries)) if deriving: - enumstr = ('#[deriving(%s)]\n' % deriving) + enumstr + enumstr = ('#[derive(%s)]\n' % deriving) + enumstr curr = CGGeneric(enumstr) # Add some whitespace padding. @@ -4458,7 +4460,7 @@ class CGRegisterProxyHandlers(CGThing): descriptors = config.getDescriptors(proxy=True) length = len(descriptors) self.root = CGList([ - CGGeneric("pub static mut proxy_handlers: [*const libc::c_void, ..%d] = [0 as *const libc::c_void, ..%d];" % (length, length)), + CGGeneric("pub static mut proxy_handlers: [*const libc::c_void; %d] = [0 as *const libc::c_void; %d];" % (length, length)), CGRegisterProxyHandlersMethod(descriptors), ], "\n") @@ -4530,11 +4532,12 @@ class CGBindingRoot(CGThing): 'js::jsapi::{JSPropertyOpWrapper, JSPropertySpec, JS_PropertyStub}', 'js::jsapi::{JSStrictPropertyOpWrapper, JSString, JSTracer, JS_ConvertStub}', 'js::jsapi::{JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub}', + 'js::jsapi::{JSMutableHandleValue, JSHandleId, JSType}', 'js::jsval::JSVal', 'js::jsval::{ObjectValue, ObjectOrNullValue, PrivateValue}', 'js::jsval::{NullValue, UndefinedValue}', 'js::glue::{CallJitMethodOp, CallJitPropertyOp, CreateProxyHandler}', - 'js::glue::{GetProxyPrivate, NewProxyObject, ProxyTraps}', + 'js::glue::{GetProxyPrivate, NewProxyObject, ProxyTraps, AutoIdVector}', 'js::glue::{RUST_FUNCTION_VALUE_TO_JITINFO}', 'js::glue::{RUST_JS_NumberValue, RUST_JSID_IS_STRING}', 'js::rust::with_compartment', @@ -4559,6 +4562,7 @@ class CGBindingRoot(CGThing): 'dom::bindings::utils::get_dictionary_property', 'dom::bindings::utils::{NativeProperties, NativePropertyHooks}', 'dom::bindings::utils::ConstantVal::{IntVal, UintVal}', + 'dom::bindings::utils::NonNullJSNative', 'dom::bindings::trace::JSTraceable', 'dom::bindings::callback::{CallbackContainer,CallbackInterface,CallbackFunction}', 'dom::bindings::callback::{CallSetup,ExceptionHandling}', @@ -4696,7 +4700,7 @@ class CGCallback(CGClass): bases=[ClassBase(baseName)], constructors=self.getConstructors(), methods=realMethods+getters+setters, - decorators="#[deriving(PartialEq,Copy,Clone)]#[jstraceable]") + decorators="#[derive(PartialEq,Copy,Clone)]#[jstraceable]") def getConstructors(self): return [ClassConstructor( @@ -5225,11 +5229,11 @@ class GlobalGenRoots(): CGGeneric("use std::mem;\n\n")] for descriptor in descriptors: name = descriptor.name - protos = [CGGeneric('pub trait %s {}\n' % (name + 'Base'))] + protos = [CGGeneric('pub trait %s : Sized {}\n' % (name + 'Base'))] for proto in descriptor.prototypeChain: protos += [CGGeneric('impl %s for %s {}\n' % (proto + 'Base', descriptor.concreteType))] - derived = [CGGeneric('pub trait %s { fn %s(&self) -> bool; }\n' % + derived = [CGGeneric('pub trait %s : Sized { fn %s(&self) -> bool; }\n' % (name + 'Derived', 'is_' + name.lower()))] for protoName in descriptor.prototypeChain[1:-1]: protoDescriptor = config.getDescriptor(protoName) @@ -5237,7 +5241,8 @@ class GlobalGenRoots(): impl ${selfName} for ${baseName} { #[inline] fn ${fname}(&self) -> bool { - ${parentName}Cast::from_actual(self).${fname}() +let base: &${parentName} = ${parentName}Cast::from_actual(self); + base.${fname}() } }\ """).substitute({'fname': 'is_' + name.lower(), @@ -5248,7 +5253,7 @@ impl ${selfName} for ${baseName} { derived += [CGGeneric('\n')] cast = [CGGeneric(string.Template("""\ -pub trait ${castTraitName} { +pub trait ${castTraitName} : Sized { #[inline(always)] fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, Self>> { match base.${checkFn}() { diff --git a/components/script/dom/bindings/conversions.rs b/components/script/dom/bindings/conversions.rs index 8447b9e9554..27e9c1682d1 100644 --- a/components/script/dom/bindings/conversions.rs +++ b/components/script/dom/bindings/conversions.rs @@ -45,7 +45,7 @@ pub trait IDLInterface { } /// A trait to convert Rust types to `JSVal`s. -pub trait ToJSValConvertible for Sized? { +pub trait ToJSValConvertible { /// Convert `self` to a `JSVal`. JSAPI failure causes a task failure. fn to_jsval(&self, cx: *mut JSContext) -> JSVal; } @@ -253,7 +253,7 @@ impl ToJSValConvertible for DOMString { } /// Behavior for stringification of `JSVal`s. -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum StringificationBehavior { /// Convert `null` to the string `"null"`. Default, @@ -498,6 +498,7 @@ impl<T: ToJSValConvertible> ToJSValConvertible for Option<T> { } } +#[old_impl_check] impl<X: default::Default, T: FromJSValConvertible<X>> FromJSValConvertible<()> for Option<T> { fn from_jsval(cx: *mut JSContext, value: JSVal, _: ()) -> Result<Option<T>, ()> { if value.is_null_or_undefined() { diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 2d02dc08ee9..71ac1837afb 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -18,10 +18,11 @@ use js::glue::{ReportError}; use js::rust::with_compartment; use libc; +use std::ffi::CString; use std::ptr; /// DOM exceptions that can be thrown by a native DOM method. -#[deriving(Show, Clone)] +#[derive(Show, Clone)] pub enum Error { /// IndexSizeError IndexSize, @@ -95,14 +96,13 @@ pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) { pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) -> JSBool { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let message = format!("argument could not be converted to any of: {}", names); - message.with_c_str(|string| { - unsafe { ReportError(cx, string) }; - }); + let string = CString::from_slice(message.as_bytes()); + unsafe { ReportError(cx, string.as_ptr()) }; return 0; } /// Format string used to throw `TypeError`s. -static ERROR_FORMAT_STRING_STRING: [libc::c_char, ..4] = [ +const ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [ '{' as libc::c_char, '0' as libc::c_char, '}' as libc::c_char, @@ -110,7 +110,7 @@ static ERROR_FORMAT_STRING_STRING: [libc::c_char, ..4] = [ ]; /// Format string struct used to throw `TypeError`s. -static ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { +const ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char, argCount: 1, exnType: JSEXN_TYPEERR as i16, @@ -127,8 +127,12 @@ unsafe extern fn get_error_message(_user_ref: *mut libc::c_void, /// Throw a `TypeError` with the given message. pub fn throw_type_error(cx: *mut JSContext, error: &str) { - let error = error.to_c_str(); + let error = CString::from_slice(error.as_bytes()); unsafe { - JS_ReportErrorNumber(cx, Some(get_error_message), ptr::null_mut(), 0, error.as_ptr()); + JS_ReportErrorNumber(cx, + Some(get_error_message as + unsafe extern "C" fn(*mut libc::c_void, *const libc::c_char, + libc::c_uint) -> *const JSErrorFormatString), + ptr::null_mut(), 0, error.as_ptr()); } } diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 94a9fdf0cd4..0343771c77e 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -28,7 +28,7 @@ use url::Url; use std::ptr; /// A freely-copyable reference to a rooted global object. -#[deriving(Copy)] +#[derive(Copy)] pub enum GlobalRef<'a> { /// A reference to a `Window` object. Window(JSRef<'a, window::Window>), diff --git a/components/script/dom/bindings/js.rs b/components/script/dom/bindings/js.rs index bc2d52a24bd..637ee079a4d 100644 --- a/components/script/dom/bindings/js.rs +++ b/components/script/dom/bindings/js.rs @@ -57,8 +57,9 @@ use script_task::STACK_ROOTS; use servo_util::smallvec::{SmallVec, SmallVec16}; use std::cell::{Cell, UnsafeCell}; use std::default::Default; -use std::kinds::marker::ContravariantLifetime; +use std::marker::ContravariantLifetime; use std::mem; +use std::ops::Deref; /// A type that represents a JS-owned value that is rooted for the lifetime of this value. /// Importantly, it requires explicit rooting in order to interact with the inner value. @@ -176,6 +177,7 @@ impl<T: Reflectable> JS<T> { } } +#[old_impl_check] impl<T: Assignable<U>, U: Reflectable> JS<U> { /// Create a `JS<T>` from any JS-managed pointer. pub fn from_rooted(root: T) -> JS<U> { @@ -246,6 +248,7 @@ pub struct MutNullableJS<T: Reflectable> { ptr: Cell<Option<JS<T>>> } +#[old_impl_check] impl<T: Assignable<U>, U: Reflectable> MutNullableJS<U> { /// Create a new `MutNullableJS` pub fn new(initial: Option<T>) -> MutNullableJS<U> { @@ -295,7 +298,9 @@ impl<T: Reflectable> MutNullableJS<T> { /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. - pub fn or_init(&self, cb: || -> Temporary<T>) -> Temporary<T> { + pub fn or_init<F>(&self, cb: F) -> Temporary<T> + where F: FnOnce() -> Temporary<T> + { match self.get() { Some(inner) => inner, None => { @@ -323,6 +328,7 @@ impl<T: Reflectable> JS<T> { } } +#[old_impl_check] impl<From, To> JS<From> { /// Return `self` as a `JS` of another type. //XXXjdm It would be lovely if this could be private. @@ -500,7 +506,7 @@ impl RootCollection { unsafe { let roots = self.roots.get(); (*roots).push(untracked.js_ptr); - debug!(" rooting {}", untracked.js_ptr); + debug!(" rooting {:?}", untracked.js_ptr); } } @@ -508,7 +514,7 @@ impl RootCollection { fn unroot<'b, T: Reflectable>(&self, rooted: &Root<T>) { unsafe { let roots = self.roots.get(); - debug!("unrooting {} (expecting {}", + debug!("unrooting {:?} (expecting {:?}", (*roots).as_slice().last().unwrap(), rooted.js_ptr); assert!(*(*roots).as_slice().last().unwrap() == rooted.js_ptr); @@ -565,13 +571,15 @@ impl<T: Reflectable> Drop for Root<T> { } } -impl<'b, T: Reflectable> Deref<JSRef<'b, T>> for Root<T> { +impl<'b, T: Reflectable> Deref for Root<T> { + type Target = JSRef<'b, T>; fn deref<'c>(&'c self) -> &'c JSRef<'b, T> { &self.jsref } } -impl<'a, T: Reflectable> Deref<T> for JSRef<'a, T> { +impl<'a, T: Reflectable> Deref for JSRef<'a, T> { + type Target = T; fn deref<'b>(&'b self) -> &'b T { unsafe { &*self.ptr diff --git a/components/script/dom/bindings/refcounted.rs b/components/script/dom/bindings/refcounted.rs index 05dd4fb43ad..5a23e7f2027 100644 --- a/components/script/dom/bindings/refcounted.rs +++ b/components/script/dom/bindings/refcounted.rs @@ -32,15 +32,17 @@ use js::jsapi::{JS_AddObjectRoot, JS_RemoveObjectRoot, JSContext}; use libc; use std::cell::RefCell; -use std::collections::hash_map::{HashMap, Vacant, Occupied}; +use std::collections::hash_map::HashMap; +use std::collections::hash_map::Entry::{Vacant, Occupied}; use std::rc::Rc; use std::sync::{Arc, Mutex}; -thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None))) +thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> = Rc::new(RefCell::new(None))); /// A pointer to a Rust DOM object that needs to be destroyed. pub struct TrustedReference(*const libc::c_void); +unsafe impl Send for TrustedReference {} /// A safe wrapper around a raw pointer to a DOM object that can be /// shared among tasks for use in asynchronous operations. The underlying @@ -55,6 +57,8 @@ pub struct Trusted<T> { owner_thread: *const libc::c_void, } +unsafe impl<T: Reflectable> Send for Trusted<T> {} + impl<T: Reflectable> Trusted<T> { /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's @@ -91,7 +95,7 @@ impl<T: Reflectable> Trusted<T> { impl<T: Reflectable> Clone for Trusted<T> { fn clone(&self) -> Trusted<T> { { - let mut refcount = self.refcount.lock(); + let mut refcount = self.refcount.lock().unwrap(); *refcount += 1; } @@ -107,7 +111,7 @@ impl<T: Reflectable> Clone for Trusted<T> { #[unsafe_destructor] impl<T: Reflectable> Drop for Trusted<T> { fn drop(&mut self) { - let mut refcount = self.refcount.lock(); + let mut refcount = self.refcount.lock().unwrap(); assert!(*refcount > 0); *refcount -= 1; if *refcount == 0 { @@ -139,7 +143,7 @@ impl LiveDOMReferences { match table.entry(ptr as *const libc::c_void) { Occupied(mut entry) => { let refcount = entry.get_mut(); - *refcount.lock() += 1; + *refcount.lock().unwrap() += 1; refcount.clone() } Vacant(entry) => { @@ -148,7 +152,7 @@ impl LiveDOMReferences { JS_AddObjectRoot(cx, rootable); } let refcount = Arc::new(Mutex::new(1)); - entry.set(refcount.clone()); + entry.insert(refcount.clone()); refcount } } @@ -164,7 +168,7 @@ impl LiveDOMReferences { let mut table = live_references.table.borrow_mut(); match table.entry(raw_reflectable) { Occupied(entry) => { - if *entry.get().lock() != 0 { + if *entry.get().lock().unwrap() != 0 { // there could have been a new reference taken since // this message was dispatched. return; @@ -173,7 +177,7 @@ impl LiveDOMReferences { unsafe { JS_RemoveObjectRoot(cx, (*reflectable).rootable()); } - let _ = entry.take(); + let _ = entry.remove(); } Vacant(_) => { // there could be a cleanup message dispatched, then a new diff --git a/components/script/dom/bindings/str.rs b/components/script/dom/bindings/str.rs index e67c8ac7d6a..77653513717 100644 --- a/components/script/dom/bindings/str.rs +++ b/components/script/dom/bindings/str.rs @@ -7,12 +7,12 @@ //! The `ByteString` struct. use std::borrow::ToOwned; -use std::hash::{Hash, sip}; +use std::hash::{Hash, SipHasher}; use std::str; use std::str::FromStr; /// Encapsulates the IDL `ByteString` type. -#[deriving(Clone,Eq,PartialEq)] +#[derive(Clone,Eq,PartialEq)] #[jstraceable] pub struct ByteString(Vec<u8>); @@ -26,7 +26,7 @@ impl ByteString { /// otherwise. pub fn as_str<'a>(&'a self) -> Option<&'a str> { let ByteString(ref vec) = *self; - str::from_utf8(vec.as_slice()) + str::from_utf8(vec.as_slice()).ok() } /// Returns the underlying vector as a slice. @@ -84,7 +84,7 @@ impl ByteString { /// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-32). pub fn is_field_value(&self) -> bool { // Classifications of characters necessary for the [CRLF] (SP|HT) rule - #[deriving(PartialEq)] + #[derive(PartialEq)] enum PreviousCharacter { Other, CR, @@ -146,8 +146,8 @@ impl ByteString { } } -impl Hash for ByteString { - fn hash(&self, state: &mut sip::SipState) { +impl Hash<SipHasher> for ByteString { + fn hash(&self, state: &mut SipHasher) { let ByteString(ref vec) = *self; vec.hash(state); } diff --git a/components/script/dom/bindings/structuredclone.rs b/components/script/dom/bindings/structuredclone.rs index 85f813cda8b..e7baa868187 100644 --- a/components/script/dom/bindings/structuredclone.rs +++ b/components/script/dom/bindings/structuredclone.rs @@ -60,3 +60,5 @@ impl StructuredCloneData { message } } + +unsafe impl Send for StructuredCloneData {} diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index ff730ea1e12..ff329ce6165 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -33,7 +33,6 @@ use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler}; use dom::node::{Node, TrustedNodeAddress}; use script_task::ScriptChan; -use collections::hash::{Hash, Hasher}; use cssparser::RGBA; use geom::rect::Rect; use html5ever::tree_builder::QuirksMode; @@ -54,9 +53,12 @@ use servo_util::smallvec::{SmallVec1, SmallVec}; use servo_util::str::{LengthOrPercentageOrAuto}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; -use std::comm::{Receiver, Sender}; +use std::collections::hash_state::HashState; +use std::ffi::CString; +use std::hash::{Hash, Hasher}; use std::io::timer::Timer; use std::rc::Rc; +use std::sync::mpsc::{Receiver, Sender}; use string_cache::{Atom, Namespace}; use style::PropertyDeclarationBlock; use url::Url; @@ -74,7 +76,7 @@ impl<T: Reflectable> JSTraceable for JS<T> { } } -no_jsmanaged_fields!(Reflector) +no_jsmanaged_fields!(Reflector); /// Trace a `JSVal`. pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) { @@ -83,7 +85,7 @@ pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) { } unsafe { - let name = description.to_c_str(); + let name = CString::from_slice(description.as_bytes()); (*tracer).debugPrinter = None; (*tracer).debugPrintIndex = -1; (*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void; @@ -101,7 +103,7 @@ pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Ref /// Trace a `JSObject`. pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) { unsafe { - let name = description.to_c_str(); + let name = CString::from_slice(description.as_bytes()); (*tracer).debugPrinter = None; (*tracer).debugPrintIndex = -1; (*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void; @@ -175,14 +177,17 @@ impl<T: JSTraceable> JSTraceable for Option<T> { } } -impl<K,V,S,H> JSTraceable for HashMap<K, V, H> where K: Eq + Hash<S> + JSTraceable, - V: JSTraceable, - H: Hasher<S> { +impl<K,V,S> JSTraceable for HashMap<K, V, S> + where K: Hash<<S as HashState>::Hasher> + Eq + JSTraceable, + V: JSTraceable, + S: HashState, + <S as HashState>::Hasher: Hasher<Output=u64>, +{ #[inline] fn trace(&self, trc: *mut JSTracer) { - for e in self.iter() { - e.val0().trace(trc); - e.val1().trace(trc); + for (k, v) in self.iter() { + k.trace(trc); + v.trace(trc); } } } @@ -197,28 +202,28 @@ impl<A: JSTraceable, B: JSTraceable> JSTraceable for (A, B) { } -no_jsmanaged_fields!(bool, f32, f64, String, Url) -no_jsmanaged_fields!(uint, u8, u16, u32, u64) -no_jsmanaged_fields!(int, i8, i16, i32, i64) -no_jsmanaged_fields!(Sender<T>) -no_jsmanaged_fields!(Receiver<T>) -no_jsmanaged_fields!(Rect<T>) -no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan) -no_jsmanaged_fields!(Atom, Namespace, Timer) -no_jsmanaged_fields!(Trusted<T>) -no_jsmanaged_fields!(PropertyDeclarationBlock) +no_jsmanaged_fields!(bool, f32, f64, String, Url); +no_jsmanaged_fields!(uint, u8, u16, u32, u64); +no_jsmanaged_fields!(int, i8, i16, i32, i64); +no_jsmanaged_fields!(Sender<T>); +no_jsmanaged_fields!(Receiver<T>); +no_jsmanaged_fields!(Rect<T>); +no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan); +no_jsmanaged_fields!(Atom, Namespace, Timer); +no_jsmanaged_fields!(Trusted<T>); +no_jsmanaged_fields!(PropertyDeclarationBlock); // These three are interdependent, if you plan to put jsmanaged data // in one of these make sure it is propagated properly to containing structs -no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId) -no_jsmanaged_fields!(QuirksMode) -no_jsmanaged_fields!(Cx) -no_jsmanaged_fields!(Headers, Method) -no_jsmanaged_fields!(ConstellationChan) -no_jsmanaged_fields!(LayoutChan) -no_jsmanaged_fields!(WindowProxyHandler) -no_jsmanaged_fields!(UntrustedNodeAddress) -no_jsmanaged_fields!(LengthOrPercentageOrAuto) -no_jsmanaged_fields!(RGBA) +no_jsmanaged_fields!(SubpageId, WindowSizeData, PipelineId); +no_jsmanaged_fields!(QuirksMode); +no_jsmanaged_fields!(Cx); +no_jsmanaged_fields!(Headers, Method); +no_jsmanaged_fields!(ConstellationChan); +no_jsmanaged_fields!(LayoutChan); +no_jsmanaged_fields!(WindowProxyHandler); +no_jsmanaged_fields!(UntrustedNodeAddress); +no_jsmanaged_fields!(LengthOrPercentageOrAuto); +no_jsmanaged_fields!(RGBA); impl JSTraceable for Box<ScriptChan+Send> { #[inline] diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index 13d662ae5f7..eef06a16a3b 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -18,6 +18,7 @@ use dom::window; use libc; use libc::c_uint; use std::cell::Cell; +use std::ffi::CString; use std::mem; use std::ptr; use js::glue::UnwrapObject; @@ -84,7 +85,7 @@ pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT; pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1; /// Representation of an IDL constant value. -#[deriving(Clone)] +#[derive(Clone)] pub enum ConstantVal { /// `long` constant. IntVal(i32), @@ -99,7 +100,7 @@ pub enum ConstantVal { } /// Representation of an IDL constant. -#[deriving(Clone)] +#[derive(Clone)] pub struct ConstantSpec { /// name of the constant. pub name: &'static [u8], @@ -130,24 +131,26 @@ pub struct NativePropertyHooks { } /// The struct that holds inheritance information for DOM object reflectors. -#[deriving(Copy)] +#[derive(Copy)] pub struct DOMClass { /// A list of interfaces that this object implements, in order of decreasing /// derivedness. - pub interface_chain: [PrototypeList::ID, ..MAX_PROTO_CHAIN_LENGTH], + pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH], /// The NativePropertyHooks for the interface associated with this class. pub native_hooks: &'static NativePropertyHooks, } +unsafe impl Sync for DOMClass {} /// The JSClass used for DOM object reflectors. -#[deriving(Copy)] +#[derive(Copy)] pub struct DOMJSClass { /// The actual JSClass. pub base: js::Class, /// Associated data for DOM object reflectors. pub dom_class: DOMClass } +unsafe impl Sync for DOMJSClass {} /// Returns the ProtoOrIfaceArray for the given global object. /// Fails if `global` is not a DOM global object. @@ -172,6 +175,7 @@ pub struct NativeProperties { /// Static attributes for the interface. pub staticAttrs: Option<&'static [JSPropertySpec]>, } +unsafe impl Sync for NativeProperties {} /// A JSNative that cannot be null. pub type NonNullJSNative = @@ -196,7 +200,7 @@ pub fn CreateInterfaceObjects2(cx: *mut JSContext, global: *mut JSObject, receiv match constructor { Some((native, name, nargs)) => { - let s = name.to_c_str(); + let s = CString::from_slice(name.as_bytes()); CreateInterfaceObject(cx, global, receiver, native, nargs, proto, members, s.as_ptr()) @@ -322,7 +326,7 @@ pub unsafe extern fn ThrowingConstructor(cx: *mut JSContext, _argc: c_uint, _vp: /// Construct and cache the ProtoOrIfaceArray for the given global. /// Fails if the argument is not a DOM global. pub fn initialize_global(global: *mut JSObject) { - let protoArray = box () ([0 as *mut JSObject, ..PrototypeList::ID::Count as uint]); + let protoArray = box () ([0 as *mut JSObject; PrototypeList::ID::Count as uint]); unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0); let box_ = squirrel_away_unique(protoArray); @@ -351,7 +355,7 @@ pub fn reflect_dom_object<T: Reflectable> /// A struct to store a reference to the reflector of a DOM object. // Allowing unused_attribute because the lint sometimes doesn't run in order #[allow(raw_pointer_deriving, unrooted_must_root, unused_attributes)] -#[deriving(PartialEq)] +#[derive(PartialEq)] #[must_root] #[servo_lang = "reflector"] // If you're renaming or moving this field, update the path in plugins::reflector as well @@ -495,7 +499,7 @@ pub fn IsPlatformObject(obj: *mut JSObject) -> bool { pub fn get_dictionary_property(cx: *mut JSContext, object: *mut JSObject, property: &str) -> Result<Option<JSVal>, ()> { - use std::c_str::CString; + use std::ffi::CString; fn has_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, found: &mut JSBool) -> bool { unsafe { @@ -509,7 +513,7 @@ pub fn get_dictionary_property(cx: *mut JSContext, } } - let property = property.to_c_str(); + let property = CString::from_slice(property.as_bytes()); if object.is_null() { return Ok(None); } @@ -594,7 +598,7 @@ pub unsafe fn delete_property_by_id(cx: *mut JSContext, object: *mut JSObject, } /// Results of `xml_name_type`. -#[deriving(PartialEq)] +#[derive(PartialEq)] #[allow(missing_docs)] pub enum XMLName { QName, diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index 782fff57c9d..69d75231fe8 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -11,9 +11,11 @@ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use servo_util::str::DOMString; + +use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cmp::{min, max}; -use std::ascii::AsciiExt; +use std::num::ToPrimitive; #[jstraceable] pub enum BlobTypeId { @@ -69,7 +71,7 @@ impl Blob { } else { "" }; - let typeStrLower = typeString.as_slice().to_ascii_lower(); + let typeStrLower = typeString.as_slice().to_ascii_lowercase(); Ok(Blob::new(global, bytes, typeStrLower.as_slice())) } } @@ -113,7 +115,7 @@ impl<'a> BlobMethods for JSRef<'a, Blob> { None => "".to_owned(), Some(str) => { if is_ascii_printable(&str) { - str.as_slice().to_ascii_lower().to_owned() + str.as_slice().to_ascii_lowercase().to_owned() } else { "".to_owned() } diff --git a/components/script/dom/browsercontext.rs b/components/script/dom/browsercontext.rs index 959c021b4bc..2e7be2d05f0 100644 --- a/components/script/dom/browsercontext.rs +++ b/components/script/dom/browsercontext.rs @@ -194,17 +194,20 @@ unsafe extern fn set(cx: *mut JSContext, proxy: *mut JSObject, _receiver: *mut J } static PROXY_HANDLER: ProxyTraps = ProxyTraps { - getPropertyDescriptor: Some(getPropertyDescriptor), - getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), - defineProperty: Some(defineProperty), + getPropertyDescriptor: Some(getPropertyDescriptor as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, bool, *mut JSPropertyDescriptor) -> bool), + getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor + as unsafe extern "C" fn(*mut JSContext, *mut JSObject, + jsid, bool, *mut JSPropertyDescriptor) + -> bool), + defineProperty: Some(defineProperty as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut JSPropertyDescriptor) -> bool), getOwnPropertyNames: None, delete_: None, enumerate: None, has: None, - hasOwn: Some(hasOwn), - get: Some(get), - set: Some(set), + hasOwn: Some(hasOwn as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut bool) -> bool), + get: Some(get as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut JSObject, jsid, *mut JSVal) -> bool), + set: Some(set as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut JSObject, jsid, bool, *mut JSVal) -> bool), keys: None, iterate: None, diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 9ed36217fec..a1eb1af9997 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -16,6 +16,8 @@ use geom::size::Size2D; use canvas::canvas_paint_task::{CanvasMsg, CanvasPaintTask}; use canvas::canvas_paint_task::CanvasMsg::{ClearRect, Close, FillRect, Recreate, StrokeRect}; +use std::sync::mpsc::Sender; + #[dom_struct] pub struct CanvasRenderingContext2D { reflector_: Reflector, diff --git a/components/script/dom/create.rs b/components/script/dom/create.rs index 73e39768f6e..8bbbdc9c832 100644 --- a/components/script/dom/create.rs +++ b/components/script/dom/create.rs @@ -89,11 +89,15 @@ pub fn create_element(name: QualName, prefix: Option<DOMString>, } macro_rules! make( - ($ctor:ident $(, $arg:expr)*) => ({ - let obj = $ctor::new(name.local.as_slice().to_owned(), prefix, document $(, $arg)*); + ($ctor:ident) => ({ + let obj = $ctor::new(name.local.as_slice().to_owned(), prefix, document); + ElementCast::from_temporary(obj) + }); + ($ctor:ident, $($arg:expr),+) => ({ + let obj = $ctor::new(name.local.as_slice().to_owned(), prefix, document, $($arg),+); ElementCast::from_temporary(obj) }) - ) + ); // This is a big match, and the IDs for inline-interned atoms are not very structured. // Perhaps we should build a perfect hash from those IDs instead. diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index 32f7f174433..2e438721b6c 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -30,7 +30,7 @@ pub struct CSSStyleDeclaration { readonly: bool, } -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum CSSModificationAccess { ReadWrite, Readonly @@ -47,7 +47,7 @@ macro_rules! css_properties( } )* ); -) +); fn serialize_list(list: &Vec<PropertyDeclaration>) -> DOMString { let mut result = String::new(); @@ -116,11 +116,11 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { if index as uint > declarations.normal.len() { declarations.important .get(index as uint - declarations.normal.len()) - .map(|decl| format!("{} !important", decl)) + .map(|decl| format!("{:?} !important", decl)) } else { declarations.normal .get(index as uint) - .map(|decl| format!("{}", decl)) + .map(|decl| format!("{:?}", decl)) } }); @@ -130,7 +130,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue fn GetPropertyValue(self, property: DOMString) -> DOMString { // Step 1 - let property = Atom::from_slice(property.as_slice().to_ascii_lower().as_slice()); + let property = Atom::from_slice(property.as_slice().to_ascii_lowercase().as_slice()); // Step 2 let longhand_properties = longhands_from_shorthand(property.as_slice()); @@ -165,7 +165,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertypriority fn GetPropertyPriority(self, property: DOMString) -> DOMString { // Step 1 - let property = Atom::from_slice(property.as_slice().to_ascii_lower().as_slice()); + let property = Atom::from_slice(property.as_slice().to_ascii_lowercase().as_slice()); // Step 2 let longhand_properties = longhands_from_shorthand(property.as_slice()); @@ -195,7 +195,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { } // Step 2 - let property = property.as_slice().to_ascii_lower(); + let property = property.as_slice().to_ascii_lowercase(); // Step 3 if !is_supported_property(property.as_slice()) { @@ -208,7 +208,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { } // Step 5 - let priority = priority.as_slice().to_ascii_lower(); + let priority = priority.as_slice().to_ascii_lowercase(); if priority.as_slice() != "!important" && !priority.is_empty() { return Ok(()); } @@ -254,7 +254,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { } // Step 2 - let property = property.as_slice().to_ascii_lower(); + let property = property.as_slice().to_ascii_lowercase(); // Step 3 if !is_supported_property(property.as_slice()) { @@ -262,7 +262,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { } // Step 4 - let priority = priority.as_slice().to_ascii_lower(); + let priority = priority.as_slice().to_ascii_lowercase(); if priority.as_slice() != "important" && !priority.is_empty() { return Ok(()); } @@ -301,7 +301,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { } // Step 2 - let property = property.as_slice().to_ascii_lower(); + let property = property.as_slice().to_ascii_lowercase(); // Step 3 let value = self.GetPropertyValue(property.clone()); @@ -343,5 +343,5 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { rval } - css_properties_accessors!(css_properties) + css_properties_accessors!(css_properties); } diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 1403344dad2..22b7befd87c 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -32,12 +32,13 @@ use js::jsval::JSVal; use js::rust::Cx; use std::rc::Rc; +use std::sync::mpsc::{Sender, Receiver}; use url::Url; /// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with /// every message. While this SendableWorkerScriptChan is alive, the associated Worker object /// will remain alive. -#[deriving(Clone)] +#[derive(Clone)] #[jstraceable] pub struct SendableWorkerScriptChan { sender: Sender<(TrustedWorkerAddress, ScriptMsg)>, @@ -133,7 +134,7 @@ impl DedicatedWorkerGlobalScope { parent_sender: Box<ScriptChan+Send>, own_sender: Sender<(TrustedWorkerAddress, ScriptMsg)>, receiver: Receiver<(TrustedWorkerAddress, ScriptMsg)>) { - spawn_named(format!("WebWorker for {}", worker_url.serialize()), proc() { + spawn_named(format!("WebWorker for {}", worker_url.serialize()), move || { task_state::initialize(SCRIPT | IN_WORKER); let roots = RootCollection::new(); @@ -165,7 +166,7 @@ impl DedicatedWorkerGlobalScope { } loop { - match global.r().receiver.recv_opt() { + match global.r().receiver.recv() { Ok((linked_worker, msg)) => { let _ar = AutoWorkerReset::new(global.r(), linked_worker); global.r().handle_event(msg); @@ -228,7 +229,7 @@ impl<'a> DedicatedWorkerGlobalScopeMethods for JSRef<'a, DedicatedWorkerGlobalSc Ok(()) } - event_handler!(message, GetOnmessage, SetOnmessage) + event_handler!(message, GetOnmessage, SetOnmessage); } impl DedicatedWorkerGlobalScopeDerived for EventTarget { diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index d20dcda10e7..d7e9ce0daa2 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -65,13 +65,13 @@ use url::Url; use std::borrow::ToOwned; use std::collections::HashMap; -use std::collections::hash_map::{Vacant, Occupied}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::ascii::AsciiExt; use std::cell::{Cell, Ref}; use std::default::Default; use time; -#[deriving(PartialEq)] +#[derive(PartialEq)] #[jstraceable] pub enum IsHTMLDocument { HTMLDocument, @@ -284,7 +284,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> { match idmap.entry(id) { Vacant(entry) => { - entry.set(vec!(element.unrooted())); + entry.insert(vec!(element.unrooted())); } Occupied(entry) => { let elements = entry.into_mut(); @@ -321,7 +321,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> { /// https://html.spec.whatwg.org/multipage/#the-indicated-part-of-the-document fn find_fragment_node(self, fragid: DOMString) -> Option<Temporary<Element>> { self.GetElementById(fragid.clone()).or_else(|| { - let check_anchor = |&node: &JSRef<HTMLAnchorElement>| { + let check_anchor = |&:&node: &JSRef<HTMLAnchorElement>| { let elem: JSRef<Element> = ElementCast::from_ref(node); elem.get_attribute(ns!(""), &atom!("name")).root().map_or(false, |attr| { attr.r().value().as_slice() == fragid.as_slice() @@ -385,7 +385,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> { } } -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum DocumentSource { FromParser, NotFromParser, @@ -475,12 +475,12 @@ impl Document { } trait PrivateDocumentHelpers { - fn createNodeList(self, callback: |node: JSRef<Node>| -> bool) -> Temporary<NodeList>; + fn createNodeList<F: Fn(JSRef<Node>) -> bool>(self, callback: F) -> Temporary<NodeList>; fn get_html_element(self) -> Option<Temporary<HTMLHtmlElement>>; } impl<'a> PrivateDocumentHelpers for JSRef<'a, Document> { - fn createNodeList(self, callback: |node: JSRef<Node>| -> bool) -> Temporary<NodeList> { + fn createNodeList<F: Fn(JSRef<Node>) -> bool>(self, callback: F) -> Temporary<NodeList> { let window = self.window.root(); let document_element = self.GetDocumentElement().root(); let nodes = match document_element { @@ -591,7 +591,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { return Err(InvalidCharacter); } let local_name = if self.is_html_document { - local_name.as_slice().to_ascii_lower() + local_name.as_slice().to_ascii_lowercase() } else { local_name }; @@ -727,7 +727,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { fn CreateEvent(self, interface: DOMString) -> Fallible<Temporary<Event>> { let window = self.window.root(); - match interface.as_slice().to_ascii_lower().as_slice() { + match interface.as_slice().to_ascii_lowercase().as_slice() { "uievents" | "uievent" => Ok(EventCast::from_temporary( UIEvent::new_uninitialized(window.r()))), "mouseevents" | "mouseevent" => Ok(EventCast::from_temporary( @@ -771,7 +771,11 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { root.traverse_preorder() .find(|node| node.type_id() == NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement))) .map(|title_elem| { - for text in title_elem.children().filter_map::<JSRef<Text>>(TextCast::to_ref) { + let mut children = title_elem.children().filter_map(|n| { + let t: Option<JSRef<Text>> = TextCast::to_ref(n); + t + }); + for text in children { title.push_str(text.characterdata().data().as_slice()); } }); @@ -1000,7 +1004,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { Temporary::new(self.window) } - global_event_handlers!() - event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange) + global_event_handlers!(); + event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange); } diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index 112dcedf4b2..48f8e4b52f6 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -14,7 +14,7 @@ use servo_util::str::DOMString; use std::borrow::ToOwned; #[repr(uint)] -#[deriving(Copy, Show)] +#[derive(Copy, Show)] #[jstraceable] pub enum DOMErrorName { IndexSizeError = DOMExceptionConstants::INDEX_SIZE_ERR as uint, @@ -98,7 +98,7 @@ impl<'a> DOMExceptionMethods for JSRef<'a, DOMException> { // http://dom.spec.whatwg.org/#error-names-0 fn Name(self) -> DOMString { - self.code.to_string() + format!("{:?}", self.code) } // http://dom.spec.whatwg.org/#error-names-0 diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index 3ae0a4f09de..ed61123d9a2 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -118,7 +118,7 @@ impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> { let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in tokens.iter() { let token = try!(self.check_token_exceptions(token.as_slice())); - atoms.iter().position(|atom| *atom == token).and_then(|index| { + atoms.iter().position(|atom| *atom == token).map(|index| { atoms.remove(index) }); } diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 98dcb3b0be1..d7ebd75f579 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -59,7 +59,7 @@ use html5ever::tree_builder::{NoQuirks, LimitedQuirks, Quirks}; use cssparser::RGBA; use std::ascii::AsciiExt; -use std::borrow::ToOwned; +use std::borrow::{IntoCow, ToOwned}; use std::cell::{Ref, RefMut}; use std::default::Default; use std::mem; @@ -89,14 +89,14 @@ impl ElementDerived for EventTarget { } } -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] #[jstraceable] pub enum ElementTypeId { HTMLElement(HTMLElementTypeId), Element, } -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum ElementCreator { ParserCreated, ScriptCreated, @@ -388,7 +388,7 @@ impl LayoutElementHelpers for JS<Element> { } } -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum StylePriority { Important, Normal, @@ -424,7 +424,7 @@ impl<'a> ElementHelpers<'a> for JSRef<'a, Element> { // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name fn parsed_name(self, name: DOMString) -> DOMString { if self.html_element_in_html_document() { - name.as_slice().to_ascii_lower() + name.as_slice().to_ascii_lowercase() } else { name } @@ -505,7 +505,7 @@ impl<'a> ElementHelpers<'a> for JSRef<'a, Element> { fn update_inline_style(self, property_decl: style::PropertyDeclaration, style_priority: StylePriority) { let mut inline_declarations = self.style_attribute().borrow_mut(); - if let &Some(ref mut declarations) = &mut *inline_declarations { + if let &mut Some(ref mut declarations) = &mut *inline_declarations { let existing_declarations = if style_priority == StylePriority::Important { declarations.important.make_unique() } else { @@ -569,9 +569,10 @@ pub trait AttributeHandlers { prefix: Option<DOMString>); fn set_attribute(self, name: &Atom, value: AttrValue); fn set_custom_attribute(self, name: DOMString, value: DOMString) -> ErrorResult; - fn do_set_attribute(self, local_name: Atom, value: AttrValue, - name: Atom, namespace: Namespace, - prefix: Option<DOMString>, cb: |JSRef<Attr>| -> bool); + fn do_set_attribute<F>(self, local_name: Atom, value: AttrValue, + name: Atom, namespace: Namespace, + prefix: Option<DOMString>, cb: F) + where F: Fn(JSRef<Attr>) -> bool; fn parse_attribute(self, namespace: &Namespace, local_name: &Atom, value: DOMString) -> AttrValue; @@ -633,7 +634,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } fn set_attribute(self, name: &Atom, value: AttrValue) { - assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); + assert!(name.as_slice() == name.as_slice().to_ascii_lowercase().as_slice()); assert!(!name.as_slice().contains(":")); self.do_set_attribute(name.clone(), value, name.clone(), @@ -657,9 +658,15 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { Ok(()) } - fn do_set_attribute(self, local_name: Atom, value: AttrValue, - name: Atom, namespace: Namespace, - prefix: Option<DOMString>, cb: |JSRef<Attr>| -> bool) { + fn do_set_attribute<F>(self, + local_name: Atom, + value: AttrValue, + name: Atom, + namespace: Namespace, + prefix: Option<DOMString>, + cb: F) + where F: Fn(JSRef<Attr>) -> bool + { let idx = self.attrs.borrow().iter() .map(|attr| attr.root()) .position(|attr| cb(attr.r())); @@ -724,7 +731,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { let owner_doc = node.owner_doc().root(); owner_doc.r().quirks_mode() }; - let is_equal = |lhs: &Atom, rhs: &Atom| match quirks_mode { + let is_equal = |&:lhs: &Atom, rhs: &Atom| match quirks_mode { NoQuirks | LimitedQuirks => lhs == rhs, Quirks => lhs.as_slice().eq_ignore_ascii_case(rhs.as_slice()) }; @@ -742,9 +749,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } fn has_attribute(self, name: &Atom) -> bool { - assert!(name.as_slice().chars().all(|ch| { - !ch.is_ascii() || ch.to_ascii().to_lowercase() == ch.to_ascii() - })); + assert!(name.as_slice().bytes().all(|&:b| b.to_ascii_lowercase() == b)); self.attrs.borrow().iter().map(|attr| attr.root()).any(|attr| { *attr.r().local_name() == *name && *attr.r().namespace() == ns!("") }) @@ -760,7 +765,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } fn get_url_attribute(self, name: &Atom) -> DOMString { - assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); + assert!(name.as_slice() == name.as_slice().to_ascii_lowercase().as_slice()); if !self.has_attribute(name) { return "".to_owned(); } @@ -785,7 +790,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } } fn set_string_attribute(self, name: &Atom, value: DOMString) { - assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); + assert!(name.as_slice() == name.as_slice().to_ascii_lowercase().as_slice()); self.set_attribute(name, AttrValue::String(value)); } @@ -800,18 +805,18 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } fn set_tokenlist_attribute(self, name: &Atom, value: DOMString) { - assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); + assert!(name.as_slice() == name.as_slice().to_ascii_lowercase().as_slice()); self.set_attribute(name, AttrValue::from_serialized_tokenlist(value)); } fn set_atomic_tokenlist_attribute(self, name: &Atom, tokens: Vec<Atom>) { - assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); + assert!(name.as_slice() == name.as_slice().to_ascii_lowercase().as_slice()); self.set_attribute(name, AttrValue::from_atomic_tokens(tokens)); } fn get_uint_attribute(self, name: &Atom) -> u32 { assert!(name.as_slice().chars().all(|ch| { - !ch.is_ascii() || ch.to_ascii().to_lowercase() == ch.to_ascii() + !ch.is_ascii() || ch.to_ascii_lowercase() == ch })); let attribute = self.get_attribute(ns!(""), name).root(); match attribute { @@ -826,7 +831,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } } fn set_uint_attribute(self, name: &Atom, value: u32) { - assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); + assert!(name.as_slice() == name.as_slice().to_ascii_lowercase().as_slice()); self.set_attribute(name, AttrValue::UInt(value.to_string(), value)); } } @@ -860,9 +865,9 @@ impl<'a> ElementMethods for JSRef<'a, Element> { None => self.local_name.as_slice().into_cow() }; if self.html_element_in_html_document() { - qualified_name.as_slice().to_ascii_upper() + qualified_name.as_slice().to_ascii_uppercase() } else { - qualified_name.into_string() + qualified_name.into_owned() } } @@ -1374,13 +1379,15 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> { node.get_enabled_state() } fn get_checked_state(self) -> bool { - match HTMLInputElementCast::to_ref(self) { + let input_element: Option<JSRef<HTMLInputElement>> = HTMLInputElementCast::to_ref(self); + match input_element { Some(input) => input.Checked(), None => false, } } fn get_indeterminate_state(self) -> bool { - match HTMLInputElementCast::to_ref(self) { + let input_element: Option<JSRef<HTMLInputElement>> = HTMLInputElementCast::to_ref(self); + match input_element { Some(input) => input.get_indeterminate_state(), None => false, } @@ -1394,7 +1401,9 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> { has_class(self, name) } - fn each_class(self, callback: |&Atom|) { + fn each_class<F>(self, callback: F) + where F: Fn(&Atom) + { match self.get_attribute(ns!(""), &atom!("class")).root() { None => {} Some(ref attr) => { @@ -1410,7 +1419,8 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> { } } fn has_nonzero_border(self) -> bool { - match HTMLTableElementCast::to_ref(self) { + let table_element: Option<JSRef<HTMLTableElement>> = HTMLTableElementCast::to_ref(self); + match table_element { None => false, Some(this) => { match this.get_border() { @@ -1461,7 +1471,10 @@ impl<'a> ActivationElementHelpers<'a> for JSRef<'a, Element> { None => { let node: JSRef<Node> = NodeCast::from_ref(self); node.ancestors() - .filter_map(|node| ElementCast::to_ref(node)) + .filter_map(|node| { + let e: Option<JSRef<Element>> = ElementCast::to_ref(node); + e + }) .filter(|e| e.as_maybe_activatable().is_some()).next() .map(|r| Temporary::from_rooted(r)) } diff --git a/components/script/dom/event.rs b/components/script/dom/event.rs index eda8690e48d..e2fe8c25609 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -19,7 +19,7 @@ use std::default::Default; use time; #[jstraceable] -#[deriving(Copy)] +#[derive(Copy)] pub enum EventPhase { None = EventConstants::NONE as int, Capturing = EventConstants::CAPTURING_PHASE as int, @@ -27,7 +27,7 @@ pub enum EventPhase { Bubbling = EventConstants::BUBBLING_PHASE as int, } -#[deriving(PartialEq)] +#[derive(PartialEq)] #[jstraceable] pub enum EventTypeId { CustomEvent, @@ -40,13 +40,13 @@ pub enum EventTypeId { ErrorEvent } -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum EventBubbles { Bubbles, DoesNotBubble } -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum EventCancelable { Cancelable, NotCancelable diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index fd7de4c64d6..64367ce8b4d 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -21,22 +21,26 @@ use js::jsapi::{JS_CompileUCFunction, JS_GetFunctionObject, JS_CloneFunctionObje use js::jsapi::{JSContext, JSObject}; use servo_util::fnv::FnvHasher; use servo_util::str::DOMString; + use libc::{c_char, size_t}; use std::borrow::ToOwned; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::collections::hash_state::DefaultState; +use std::default::Default; +use std::ffi::CString; use std::ptr; use url::Url; use std::collections::HashMap; -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] #[jstraceable] pub enum ListenerPhase { Capturing, Bubbling, } -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] #[jstraceable] pub enum EventTargetTypeId { Node(NodeTypeId), @@ -47,7 +51,7 @@ pub enum EventTargetTypeId { XMLHttpRequestEventTarget(XMLHttpRequestEventTargetTypeId) } -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] #[jstraceable] pub enum EventListenerType { Additive(EventListener), @@ -63,7 +67,7 @@ impl EventListenerType { } } -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] #[jstraceable] #[privatize] pub struct EventListenerEntry { @@ -75,7 +79,7 @@ pub struct EventListenerEntry { pub struct EventTarget { reflector_: Reflector, type_id: EventTargetTypeId, - handlers: DOMRefCell<HashMap<DOMString, Vec<EventListenerEntry>, FnvHasher>>, + handlers: DOMRefCell<HashMap<DOMString, Vec<EventListenerEntry>, DefaultState<FnvHasher>>>, } impl EventTarget { @@ -83,7 +87,7 @@ impl EventTarget { EventTarget { reflector_: Reflector::new(), type_id: type_id, - handlers: DOMRefCell::new(HashMap::with_hasher(FnvHasher)), + handlers: DOMRefCell::new(Default::default()), } } @@ -146,7 +150,7 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { let mut handlers = self.handlers.borrow_mut(); let entries = match handlers.entry(ty) { Occupied(entry) => entry.into_mut(), - Vacant(entry) => entry.set(vec!()), + Vacant(entry) => entry.insert(vec!()), }; let idx = entries.iter().position(|&entry| { @@ -194,14 +198,14 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { scope: *mut JSObject, ty: &str, source: DOMString) { - let url = url.serialize().to_c_str(); - let name = ty.to_c_str(); + let url = CString::from_slice(url.serialize().as_bytes()); + let name = CString::from_slice(ty.as_bytes()); let lineno = 0; //XXXjdm need to get a real number here let nargs = 1; //XXXjdm not true for onerror - static ARG_NAME: [c_char, ..6] = + const ARG_NAME: [c_char; 6] = ['e' as c_char, 'v' as c_char, 'e' as c_char, 'n' as c_char, 't' as c_char, 0]; - static ARG_NAMES: [*const c_char, ..1] = [&ARG_NAME as *const c_char]; + const ARG_NAMES: [*const c_char; 1] = [&ARG_NAME as *const c_char]; let source: Vec<u16> = source.as_slice().utf16_units().collect(); let handler = unsafe { @@ -209,7 +213,7 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { ptr::null_mut(), name.as_ptr(), nargs, - &ARG_NAMES as *const *const i8 as *mut *const i8, + &ARG_NAMES as *const *const c_char as *mut *const c_char, source.as_ptr(), source.len() as size_t, url.as_ptr(), @@ -255,7 +259,7 @@ impl<'a> EventTargetMethods for JSRef<'a, EventTarget> { let mut handlers = self.handlers.borrow_mut(); let entry = match handlers.entry(ty) { Occupied(entry) => entry.into_mut(), - Vacant(entry) => entry.set(vec!()), + Vacant(entry) => entry.insert(vec!()), }; let phase = if capture { ListenerPhase::Capturing } else { ListenerPhase::Bubbling }; diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 9687bf6d9e5..452832560f9 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -19,9 +19,9 @@ use servo_util::str::DOMString; use std::borrow::ToOwned; use std::collections::HashMap; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; -#[deriving(Clone)] +#[derive(Clone)] #[jstraceable] #[must_root] pub enum FormDatum { @@ -65,7 +65,7 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> { match data.entry(name) { Occupied(entry) => entry.into_mut().push(file), Vacant(entry) => { - entry.set(vec!(file)); + entry.insert(vec!(file)); } } } @@ -74,7 +74,7 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> { let mut data = self.data.borrow_mut(); match data.entry(name) { Occupied(entry) => entry.into_mut().push(FormDatum::StringData(value)), - Vacant (entry) => { entry.set(vec!(FormDatum::StringData(value))); }, + Vacant (entry) => { entry.insert(vec!(FormDatum::StringData(value))); }, } } diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index 3dd5026a5a0..52206f2652b 100644 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -55,15 +55,15 @@ impl<'a> HTMLButtonElementMethods for JSRef<'a, HTMLButtonElement> { } // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_getter!(Disabled) + make_bool_getter!(Disabled); // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_setter!(SetDisabled, "disabled") + make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/forms.html#dom-button-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); - let ty = elem.get_string_attribute(&atom!("type")).into_ascii_lower(); + let ty = elem.get_string_attribute(&atom!("type")).into_ascii_lowercase(); // https://html.spec.whatwg.org/multipage/forms.html#attr-button-type match ty.as_slice() { "reset" | "button" | "menu" => ty, @@ -72,7 +72,7 @@ impl<'a> HTMLButtonElementMethods for JSRef<'a, HTMLButtonElement> { } // https://html.spec.whatwg.org/multipage/forms.html#dom-button-type - make_setter!(SetType, "type") + make_setter!(SetType, "type"); } impl<'a> VirtualMethods for JSRef<'a, HTMLButtonElement> { diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 15f25a495a5..314088a74be 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -26,6 +26,7 @@ use geom::size::Size2D; use std::cell::Cell; use std::default::Default; +use std::sync::mpsc::Sender; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index 9cbff941c03..a1aa197046e 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -96,7 +96,7 @@ impl HTMLCollection { } let filter = TagNameFilter { tag: Atom::from_slice(tag.as_slice()), - ascii_lower_tag: Atom::from_slice(tag.as_slice().to_ascii_lower().as_slice()), + ascii_lower_tag: Atom::from_slice(tag.as_slice().to_ascii_lowercase().as_slice()), }; HTMLCollection::create(window, root, box filter) } @@ -165,12 +165,13 @@ impl HTMLCollection { } fn traverse<'a>(root: JSRef<'a, Node>) - -> FilterMap<'a, JSRef<'a, Node>, + -> FilterMap<JSRef<'a, Node>, JSRef<'a, Element>, - Skip<TreeIterator<'a>>> { + Skip<TreeIterator<'a>>, + fn(JSRef<Node>) -> Option<JSRef<Element>>> { root.traverse_preorder() .skip(1) - .filter_map(ElementCast::to_ref) + .filter_map(ElementCast::to_ref as fn(JSRef<Node>) -> Option<JSRef<Element>>) } } diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index d5fae8353be..633b8f5f297 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -21,6 +21,7 @@ use dom::document::Document; use dom::domstringmap::DOMStringMap; use dom::element::{Element, ElementTypeId, ActivationElementHelpers, AttributeHandlers}; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::htmlinputelement::HTMLInputElement; use dom::htmlmediaelement::HTMLMediaElementTypeId; use dom::htmltablecellelement::HTMLTableCellElementTypeId; use dom::node::{Node, NodeTypeId, window_from_node}; @@ -84,17 +85,17 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> { }) } - make_getter!(Title) - make_setter!(SetTitle, "title") + make_getter!(Title); + make_setter!(SetTitle, "title"); - make_getter!(Lang) - make_setter!(SetLang, "lang") + make_getter!(Lang); + make_setter!(SetLang, "lang"); // http://html.spec.whatwg.org/multipage/#dom-hidden - make_bool_getter!(Hidden) - make_bool_setter!(SetHidden, "hidden") + make_bool_getter!(Hidden); + make_bool_setter!(SetHidden, "hidden"); - global_event_handlers!(NoOnload) + global_event_handlers!(NoOnload); // https://html.spec.whatwg.org/multipage/dom.html#dom-dataset fn Dataset(self) -> Temporary<DOMStringMap> { @@ -123,7 +124,7 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> { // https://html.spec.whatwg.org/multipage/interaction.html#dom-click fn Click(self) { - let maybe_input = HTMLInputElementCast::to_ref(self); + let maybe_input: Option<JSRef<HTMLInputElement>> = HTMLInputElementCast::to_ref(self); match maybe_input { Some(i) if i.Disabled() => return, _ => () @@ -205,7 +206,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLElement> { } } -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] #[jstraceable] pub enum HTMLElementTypeId { HTMLElement, diff --git a/components/script/dom/htmlfieldsetelement.rs b/components/script/dom/htmlfieldsetelement.rs index 6f0241ff8cd..f6d1825bc37 100644 --- a/components/script/dom/htmlfieldsetelement.rs +++ b/components/script/dom/htmlfieldsetelement.rs @@ -71,10 +71,10 @@ impl<'a> HTMLFieldSetElementMethods for JSRef<'a, HTMLFieldSetElement> { } // http://www.whatwg.org/html/#dom-fieldset-disabled - make_bool_getter!(Disabled) + make_bool_getter!(Disabled); // http://www.whatwg.org/html/#dom-fieldset-disabled - make_bool_setter!(SetDisabled, "disabled") + make_bool_setter!(SetDisabled, "disabled"); } impl<'a> VirtualMethods for JSRef<'a, HTMLFieldSetElement> { diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 7890dc1eb99..48edae7059f 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -62,28 +62,28 @@ impl HTMLFormElement { impl<'a> HTMLFormElementMethods for JSRef<'a, HTMLFormElement> { // https://html.spec.whatwg.org/multipage/forms.html#dom-form-acceptcharset - make_getter!(AcceptCharset, "accept-charset") + make_getter!(AcceptCharset, "accept-charset"); // https://html.spec.whatwg.org/multipage/forms.html#dom-form-acceptcharset - make_setter!(SetAcceptCharset, "accept-charset") + make_setter!(SetAcceptCharset, "accept-charset"); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-action - make_url_or_base_getter!(Action) + make_url_or_base_getter!(Action); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-action - make_setter!(SetAction, "action") + make_setter!(SetAction, "action"); // https://html.spec.whatwg.org/multipage/forms.html#dom-form-autocomplete - make_enumerated_getter!(Autocomplete, "on", "off") + make_enumerated_getter!(Autocomplete, "on", ("off")); // https://html.spec.whatwg.org/multipage/forms.html#dom-form-autocomplete - make_setter!(SetAutocomplete, "autocomplete") + make_setter!(SetAutocomplete, "autocomplete"); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-enctype - make_enumerated_getter!(Enctype, "application/x-www-form-urlencoded", "text/plain" | "multipart/form-data") + make_enumerated_getter!(Enctype, "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data")); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-enctype - make_setter!(SetEnctype, "enctype") + make_setter!(SetEnctype, "enctype"); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-encoding fn Encoding(self) -> DOMString { @@ -96,28 +96,28 @@ impl<'a> HTMLFormElementMethods for JSRef<'a, HTMLFormElement> { } // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-method - make_enumerated_getter!(Method, "get", "post" | "dialog") + make_enumerated_getter!(Method, "get", ("post") | ("dialog")); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-method - make_setter!(SetMethod, "method") + make_setter!(SetMethod, "method"); // https://html.spec.whatwg.org/multipage/forms.html#dom-form-name - make_getter!(Name) + make_getter!(Name); // https://html.spec.whatwg.org/multipage/forms.html#dom-form-name - make_setter!(SetName, "name") + make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-novalidate - make_bool_getter!(NoValidate) + make_bool_getter!(NoValidate); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-novalidate - make_bool_setter!(SetNoValidate, "novalidate") + make_bool_setter!(SetNoValidate, "novalidate"); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-target - make_getter!(Target) + make_getter!(Target); // https://html.spec.whatwg.org/multipage/forms.html#dom-fs-target - make_setter!(SetTarget, "target") + make_setter!(SetTarget, "target"); // https://html.spec.whatwg.org/multipage/forms.html#the-form-element:concept-form-submit fn Submit(self) { @@ -130,13 +130,13 @@ impl<'a> HTMLFormElementMethods for JSRef<'a, HTMLFormElement> { } } -#[deriving(Copy)] +#[derive(Copy)] pub enum SubmittedFrom { FromFormSubmitMethod, NotFromFormSubmitMethod } -#[deriving(Copy)] +#[derive(Copy)] pub enum ResetFrom { FromFormResetMethod, NotFromFormResetMethod @@ -399,21 +399,21 @@ pub struct FormDatum { pub value: DOMString } -#[deriving(Copy)] +#[derive(Copy)] pub enum FormEncType { TextPlainEncoded, UrlEncoded, FormDataEncoded } -#[deriving(Copy)] +#[derive(Copy)] pub enum FormMethod { FormGet, FormPost, FormDialog } -#[deriving(Copy)] +#[derive(Copy)] pub enum FormSubmitter<'a> { FormElement(JSRef<'a, HTMLFormElement>), InputElement(JSRef<'a, HTMLInputElement>) @@ -482,7 +482,7 @@ impl<'a> FormSubmitter<'a> { } } -pub trait FormControl<'a> : Copy { +pub trait FormControl<'a> : Copy + Sized { // FIXME: This is wrong (https://github.com/servo/servo/issues/3553) // but we need html5ever to do it correctly fn form_owner(self) -> Option<Temporary<HTMLFormElement>> { @@ -507,16 +507,21 @@ pub trait FormControl<'a> : Copy { .map(Temporary::from_rooted) } - fn get_form_attribute(self, - attr: &Atom, - input: |Self| -> DOMString, - owner: |JSRef<HTMLFormElement>| -> DOMString) -> DOMString { + fn get_form_attribute<InputFn, OwnerFn>(self, + attr: &Atom, + input: InputFn, + owner: OwnerFn) + -> DOMString + where InputFn: Fn(Self) -> DOMString, + OwnerFn: Fn(JSRef<HTMLFormElement>) -> DOMString + { if self.to_element().has_attribute(attr) { input(self) } else { self.form_owner().map_or("".to_owned(), |t| owner(t.root().r())) } } + fn to_element(self) -> JSRef<'a, Element>; // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-mutable fn mutable(self) -> bool; diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 66d0f824fa2..3f5220cea72 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -214,7 +214,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLIFrameElement> { let mut modes = SandboxAllowance::AllowNothing as u8; if let Some(ref tokens) = attr.value().tokens() { for token in tokens.iter() { - modes |= match token.as_slice().to_ascii_lower().as_slice() { + modes |= match token.as_slice().to_ascii_lowercase().as_slice() { "allow-same-origin" => SandboxAllowance::AllowSameOrigin, "allow-forms" => SandboxAllowance::AllowForms, "allow-pointer-lock" => SandboxAllowance::AllowPointerLock, diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index 3d6b8d28c7c..0e0c7da4ea8 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -95,19 +95,19 @@ impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> { } impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> { - make_getter!(Alt) + make_getter!(Alt); - make_setter!(SetAlt, "alt") + make_setter!(SetAlt, "alt"); - make_url_getter!(Src) + make_url_getter!(Src); - make_setter!(SetSrc, "src") + make_setter!(SetSrc, "src"); - make_getter!(UseMap) + make_getter!(UseMap); - make_setter!(SetUseMap, "usemap") + make_setter!(SetUseMap, "usemap"); - make_bool_getter!(IsMap) + make_bool_getter!(IsMap); fn SetIsMap(self, is_map: bool) { let element: JSRef<Element> = ElementCast::from_ref(self); @@ -150,29 +150,29 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> { elem.set_uint_attribute(&atom!("height"), height) } - make_getter!(Name) + make_getter!(Name); - make_setter!(SetName, "name") + make_setter!(SetName, "name"); - make_getter!(Align) + make_getter!(Align); - make_setter!(SetAlign, "align") + make_setter!(SetAlign, "align"); - make_uint_getter!(Hspace) + make_uint_getter!(Hspace); - make_uint_setter!(SetHspace, "hspace") + make_uint_setter!(SetHspace, "hspace"); - make_uint_getter!(Vspace) + make_uint_getter!(Vspace); - make_uint_setter!(SetVspace, "vspace") + make_uint_setter!(SetVspace, "vspace"); - make_getter!(LongDesc) + make_getter!(LongDesc); - make_setter!(SetLongDesc, "longdesc") + make_setter!(SetLongDesc, "longdesc"); - make_getter!(Border) + make_getter!(Border); - make_setter!(SetBorder, "border") + make_setter!(SetBorder, "border"); } impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> { diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index 507f6d05818..0e53879add4 100644 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -46,7 +46,7 @@ const DEFAULT_SUBMIT_VALUE: &'static str = "Submit"; const DEFAULT_RESET_VALUE: &'static str = "Reset"; #[jstraceable] -#[deriving(PartialEq, Copy)] +#[derive(PartialEq, Copy)] #[allow(dead_code)] enum InputType { InputSubmit, @@ -192,16 +192,16 @@ impl RawLayoutHTMLInputElementHelpers for HTMLInputElement { impl<'a> HTMLInputElementMethods for JSRef<'a, HTMLInputElement> { // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_getter!(Disabled) + make_bool_getter!(Disabled); // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_setter!(SetDisabled, "disabled") + make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-defaultchecked - make_bool_getter!(DefaultChecked, "checked") + make_bool_getter!(DefaultChecked, "checked"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-defaultchecked - make_bool_setter!(SetDefaultChecked, "checked") + make_bool_setter!(SetDefaultChecked, "checked"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-checked fn Checked(self) -> bool { @@ -214,28 +214,28 @@ impl<'a> HTMLInputElementMethods for JSRef<'a, HTMLInputElement> { } // https://html.spec.whatwg.org/multipage/forms.html#dom-input-readonly - make_bool_getter!(ReadOnly) + make_bool_getter!(ReadOnly); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-readonly - make_bool_setter!(SetReadOnly, "readonly") + make_bool_setter!(SetReadOnly, "readonly"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-size - make_uint_getter!(Size) + make_uint_getter!(Size); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-size - make_uint_setter!(SetSize, "size") + make_uint_setter!(SetSize, "size"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-type - make_enumerated_getter!(Type, "text", "hidden" | "search" | "tel" | - "url" | "email" | "password" | - "datetime" | "date" | "month" | - "week" | "time" | "datetime-local" | - "number" | "range" | "color" | - "checkbox" | "radio" | "file" | - "submit" | "image" | "reset" | "button") + make_enumerated_getter!(Type, "text", ("hidden") | ("search") | ("tel") | + ("url") | ("email") | ("password") | + ("datetime") | ("date") | ("month") | + ("week") | ("time") | ("datetime-local") | + ("number") | ("range") | ("color") | + ("checkbox") | ("radio") | ("file") | + ("submit") | ("image") | ("reset") | ("button")); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-type - make_setter!(SetType, "type") + make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-value fn Value(self) -> DOMString { @@ -250,40 +250,40 @@ impl<'a> HTMLInputElementMethods for JSRef<'a, HTMLInputElement> { } // https://html.spec.whatwg.org/multipage/forms.html#dom-input-defaultvalue - make_getter!(DefaultValue, "value") + make_getter!(DefaultValue, "value"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-defaultvalue - make_setter!(SetDefaultValue, "value") + make_setter!(SetDefaultValue, "value"); // https://html.spec.whatwg.org/multipage/forms.html#attr-fe-name - make_getter!(Name) + make_getter!(Name); // https://html.spec.whatwg.org/multipage/forms.html#attr-fe-name - make_setter!(SetName, "name") + make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formaction - make_url_or_base_getter!(FormAction) + make_url_or_base_getter!(FormAction); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formaction - make_setter!(SetFormAction, "formaction") + make_setter!(SetFormAction, "formaction"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formenctype - make_enumerated_getter!(FormEnctype, "application/x-www-form-urlencoded", "text/plain" | "multipart/form-data") + make_enumerated_getter!(FormEnctype, "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data")); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formenctype - make_setter!(SetFormEnctype, "formenctype") + make_setter!(SetFormEnctype, "formenctype"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formmethod - make_enumerated_getter!(FormMethod, "get", "post" | "dialog") + make_enumerated_getter!(FormMethod, "get", ("post") | ("dialog")); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formmethod - make_setter!(SetFormMethod, "formmethod") + make_setter!(SetFormMethod, "formmethod"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formtarget - make_getter!(FormTarget) + make_getter!(FormTarget); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formtarget - make_setter!(SetFormTarget, "formtarget") + make_setter!(SetFormTarget, "formtarget"); // https://html.spec.whatwg.org/multipage/forms.html#dom-input-indeterminate fn Indeterminate(self) -> bool { @@ -312,17 +312,23 @@ fn broadcast_radio_checked(broadcaster: JSRef<HTMLInputElement>, group: Option<& let doc = document_from_node(broadcaster).root(); let doc_node: JSRef<Node> = NodeCast::from_ref(doc.r()); - // There is no DOM tree manipulation here, so this is safe - let mut iter = unsafe { - doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap() + // This function is a workaround for lifetime constraint difficulties. + fn do_broadcast<'a>(doc_node: JSRef<'a, Node>, broadcaster: JSRef<'a, HTMLInputElement>, + owner: Option<JSRef<'a, HTMLFormElement>>, group: Option<&str>) { + // There is no DOM tree manipulation here, so this is safe + let mut iter = unsafe { + doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap() .filter_map(|t| HTMLInputElementCast::to_ref(t)) - .filter(|&r| in_same_group(r, owner.r(), group) && broadcaster != r) - }; - for r in iter { - if r.Checked() { - r.SetChecked(false); + .filter(|&r| in_same_group(r, owner, group) && broadcaster != r) + }; + for r in iter { + if r.Checked() { + r.SetChecked(false); + } } } + + do_broadcast(doc_node, broadcaster, owner.r(), group) } fn in_same_group<'a,'b>(other: JSRef<'a, HTMLInputElement>, @@ -766,16 +772,20 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> { let doc = document_from_node(*self).root(); let node: JSRef<Node> = NodeCast::from_ref(doc.r()); let owner = self.form_owner(); - if owner.is_none() || ElementCast::from_ref(*self).click_in_progress() { + let elem: JSRef<Element> = ElementCast::from_ref(*self); + if owner.is_none() || elem.click_in_progress() { return; } // This is safe because we are stopping after finding the first element // and only then performing actions which may modify the DOM tree unsafe { node.query_selector_iter("input[type=submit]".to_owned()).unwrap() - .filter_map(|t| HTMLInputElementCast::to_ref(t)) + .filter_map(|t| { + let h: Option<JSRef<HTMLInputElement>> = HTMLInputElementCast::to_ref(t); + h + }) .find(|r| r.form_owner() == owner) - .map(|s| s.synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey)); + .map(|&:s| s.synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey)); } } } diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index 49018903a5a..8170a4e28d9 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -141,20 +141,20 @@ impl<'a> PrivateHTMLLinkElementHelpers for JSRef<'a, HTMLLinkElement> { } impl<'a> HTMLLinkElementMethods for JSRef<'a, HTMLLinkElement> { - make_url_getter!(Href) - make_setter!(SetHref, "href") + make_url_getter!(Href); + make_setter!(SetHref, "href"); - make_getter!(Rel) - make_setter!(SetRel, "rel") + make_getter!(Rel); + make_setter!(SetRel, "rel"); - make_getter!(Media) - make_setter!(SetMedia, "media") + make_getter!(Media); + make_setter!(SetMedia, "media"); - make_getter!(Hreflang) - make_setter!(SetHreflang, "hreflang") + make_getter!(Hreflang); + make_setter!(SetHreflang, "hreflang"); - make_getter!(Type) - make_setter!(SetType, "type") + make_getter!(Type); + make_setter!(SetType, "type"); fn RelList(self) -> Temporary<DOMTokenList> { self.rel_list.or_init(|| { diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index ea8dcfa4041..ef75b1f43ee 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -38,7 +38,7 @@ impl HTMLMediaElement { } } -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] #[jstraceable] pub enum HTMLMediaElementTypeId { HTMLAudioElement, diff --git a/components/script/dom/htmlobjectelement.rs b/components/script/dom/htmlobjectelement.rs index 43478c532d5..7ebecd3e945 100644 --- a/components/script/dom/htmlobjectelement.rs +++ b/components/script/dom/htmlobjectelement.rs @@ -89,10 +89,10 @@ impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> { } // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type - make_getter!(Type) + make_getter!(Type); // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type - make_setter!(SetType, "type") + make_setter!(SetType, "type"); } impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> { diff --git a/components/script/dom/htmloptgroupelement.rs b/components/script/dom/htmloptgroupelement.rs index 846a53bc41e..ca3cefeead2 100644 --- a/components/script/dom/htmloptgroupelement.rs +++ b/components/script/dom/htmloptgroupelement.rs @@ -47,10 +47,10 @@ impl HTMLOptGroupElement { impl<'a> HTMLOptGroupElementMethods for JSRef<'a, HTMLOptGroupElement> { // http://www.whatwg.org/html#dom-optgroup-disabled - make_bool_getter!(Disabled) + make_bool_getter!(Disabled); // http://www.whatwg.org/html#dom-optgroup-disabled - make_bool_setter!(SetDisabled, "disabled") + make_bool_setter!(SetDisabled, "disabled"); } impl<'a> VirtualMethods for JSRef<'a, HTMLOptGroupElement> { diff --git a/components/script/dom/htmloptionelement.rs b/components/script/dom/htmloptionelement.rs index bfe11883cfc..3df9bae29b1 100644 --- a/components/script/dom/htmloptionelement.rs +++ b/components/script/dom/htmloptionelement.rs @@ -69,7 +69,7 @@ fn collect_text(node: &JSRef<Node>, value: &mut DOMString) { impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> { // http://www.whatwg.org/html/#dom-option-disabled - make_bool_getter!(Disabled) + make_bool_getter!(Disabled); // http://www.whatwg.org/html/#dom-option-disabled fn SetDisabled(self, disabled: bool) { @@ -104,7 +104,7 @@ impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> { } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-value - make_setter!(SetValue, "value") + make_setter!(SetValue, "value"); // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label fn Label(self) -> DOMString { @@ -118,7 +118,7 @@ impl<'a> HTMLOptionElementMethods for JSRef<'a, HTMLOptionElement> { } // https://html.spec.whatwg.org/multipage/forms.html#attr-option-label - make_setter!(SetLabel, "label") + make_setter!(SetLabel, "label"); } diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 317769d23db..56d9beb65e6 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -258,7 +258,7 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> { }, Some(ref s) => { debug!("script type={}", *s); - SCRIPT_JS_MIMES.contains(&s.to_ascii_lower().as_slice().trim_chars(HTML_SPACE_CHARACTERS)) + SCRIPT_JS_MIMES.contains(&s.to_ascii_lowercase().as_slice().trim_matches(HTML_SPACE_CHARACTERS)) }, None => { debug!("no script type"); @@ -271,7 +271,7 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> { }, Some(ref s) => { debug!("script language={}", *s); - SCRIPT_JS_MIMES.contains(&format!("text/{}", s).to_ascii_lower().as_slice()) + SCRIPT_JS_MIMES.contains(&format!("text/{}", s).to_ascii_lowercase().as_slice()) }, None => { debug!("no script type or language, inferring js"); @@ -342,9 +342,9 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLScriptElement> { } impl<'a> HTMLScriptElementMethods for JSRef<'a, HTMLScriptElement> { - make_url_getter!(Src) + make_url_getter!(Src); - make_setter!(SetSrc, "src") + make_setter!(SetSrc, "src"); // http://www.whatwg.org/html/#dom-script-text fn Text(self) -> DOMString { diff --git a/components/script/dom/htmlselectelement.rs b/components/script/dom/htmlselectelement.rs index fce7277d6a9..611bb687e53 100644 --- a/components/script/dom/htmlselectelement.rs +++ b/components/script/dom/htmlselectelement.rs @@ -61,10 +61,10 @@ impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { } // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_getter!(Disabled) + make_bool_getter!(Disabled); // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_setter!(SetDisabled, "disabled") + make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/forms.html#dom-select-type fn Type(self) -> DOMString { diff --git a/components/script/dom/htmltablecellelement.rs b/components/script/dom/htmltablecellelement.rs index 24450399f77..9bb04740c58 100644 --- a/components/script/dom/htmltablecellelement.rs +++ b/components/script/dom/htmltablecellelement.rs @@ -16,7 +16,7 @@ use cssparser::RGBA; use servo_util::str::{mod, DOMString, LengthOrPercentageOrAuto}; use std::cell::Cell; -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] #[jstraceable] pub enum HTMLTableCellElementTypeId { HTMLTableDataCellElement, diff --git a/components/script/dom/htmltableelement.rs b/components/script/dom/htmltableelement.rs index e5494e71afa..46e23a9665a 100644 --- a/components/script/dom/htmltableelement.rs +++ b/components/script/dom/htmltableelement.rs @@ -62,7 +62,10 @@ impl<'a> HTMLTableElementMethods for JSRef<'a, HTMLTableElement> { fn GetCaption(self) -> Option<Temporary<HTMLTableCaptionElement>> { let node: JSRef<Node> = NodeCast::from_ref(self); node.children() - .filter_map::<JSRef<HTMLTableCaptionElement>>(HTMLTableCaptionElementCast::to_ref) + .filter_map(|n| { + let t: Option<JSRef<HTMLTableCaptionElement>> = HTMLTableCaptionElementCast::to_ref(n); + t + }) .next() .map(Temporary::from_rooted) } diff --git a/components/script/dom/htmltextareaelement.rs b/components/script/dom/htmltextareaelement.rs index 8ede6e716ae..79316c02d52 100644 --- a/components/script/dom/htmltextareaelement.rs +++ b/components/script/dom/htmltextareaelement.rs @@ -103,52 +103,52 @@ impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // constraints // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-cols - make_uint_getter!(Cols) + make_uint_getter!(Cols); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-cols - make_uint_setter!(SetCols, "cols") + make_uint_setter!(SetCols, "cols"); // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_getter!(Disabled) + make_bool_getter!(Disabled); // http://www.whatwg.org/html/#dom-fe-disabled - make_bool_setter!(SetDisabled, "disabled") + make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/forms.html#attr-fe-name - make_getter!(Name) + make_getter!(Name); // https://html.spec.whatwg.org/multipage/forms.html#attr-fe-name - make_setter!(SetName, "name") + make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-placeholder - make_getter!(Placeholder) + make_getter!(Placeholder); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-placeholder - make_setter!(SetPlaceholder, "placeholder") + make_setter!(SetPlaceholder, "placeholder"); // https://html.spec.whatwg.org/multipage/forms.html#attr-textarea-readonly - make_bool_getter!(ReadOnly) + make_bool_getter!(ReadOnly); // https://html.spec.whatwg.org/multipage/forms.html#attr-textarea-readonly - make_bool_setter!(SetReadOnly, "readonly") + make_bool_setter!(SetReadOnly, "readonly"); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-required - make_bool_getter!(Required) + make_bool_getter!(Required); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-required - make_bool_setter!(SetRequired, "required") + make_bool_setter!(SetRequired, "required"); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-rows - make_uint_getter!(Rows) + make_uint_getter!(Rows); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-rows - make_uint_setter!(SetRows, "rows") + make_uint_setter!(SetRows, "rows"); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-wrap - make_getter!(Wrap) + make_getter!(Wrap); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-wrap - make_setter!(SetWrap, "wrap") + make_setter!(SetWrap, "wrap"); // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type fn Type(self) -> DOMString { diff --git a/components/script/dom/keyboardevent.rs b/components/script/dom/keyboardevent.rs index cf4cadca3a1..518543c27ed 100644 --- a/components/script/dom/keyboardevent.rs +++ b/components/script/dom/keyboardevent.rs @@ -350,7 +350,7 @@ fn code_value(key: constellation_msg::Key) -> &'static str { constellation_msg::Key::GraveAccent | constellation_msg::Key::World1 | - constellation_msg::Key::World2 => panic!("unknown char code for {}", key), + constellation_msg::Key::World2 => panic!("unknown char code for {:?}", key), constellation_msg::Key::Escape => "Escape", constellation_msg::Key::Enter => "Enter", diff --git a/components/script/dom/macros.rs b/components/script/dom/macros.rs index 646baabf785..30759c3bed0 100644 --- a/components/script/dom/macros.rs +++ b/components/script/dom/macros.rs @@ -11,13 +11,13 @@ macro_rules! make_getter( #[allow(unused_imports)] use std::ascii::AsciiExt; let element: JSRef<Element> = ElementCast::from_ref(self); - element.get_string_attribute(&Atom::from_slice($htmlname.to_ascii_lower().as_slice())) + element.get_string_attribute(&Atom::from_slice($htmlname.to_ascii_lowercase().as_slice())) } ); ($attr:ident) => { - make_getter!($attr, stringify!($attr).to_ascii_lower().as_slice()) + make_getter!($attr, stringify!($attr).to_ascii_lowercase().as_slice()); } -) +); #[macro_export] macro_rules! make_bool_getter( @@ -33,9 +33,9 @@ macro_rules! make_bool_getter( } ); ($attr:ident) => { - make_bool_getter!($attr, stringify!($attr).to_ascii_lower().as_slice()) + make_bool_getter!($attr, stringify!($attr).to_ascii_lowercase().as_slice()); } -) +); #[macro_export] macro_rules! make_uint_getter( @@ -51,9 +51,9 @@ macro_rules! make_uint_getter( } ); ($attr:ident) => { - make_uint_getter!($attr, stringify!($attr).to_ascii_lower().as_slice()) + make_uint_getter!($attr, stringify!($attr).to_ascii_lowercase().as_slice()); } -) +); #[macro_export] macro_rules! make_url_getter( @@ -70,9 +70,9 @@ macro_rules! make_url_getter( ); ($attr:ident) => { // FIXME(pcwalton): Do this at compile time, not runtime. - make_url_getter!($attr, stringify!($attr).to_ascii_lower().as_slice()) + make_url_getter!($attr, stringify!($attr).to_ascii_lowercase().as_slice()); } -) +); #[macro_export] macro_rules! make_url_or_base_getter( @@ -94,13 +94,13 @@ macro_rules! make_url_or_base_getter( } ); ($attr:ident) => { - make_url_or_base_getter!($attr, stringify!($attr).to_ascii_lower().as_slice()) + make_url_or_base_getter!($attr, stringify!($attr).to_ascii_lowercase().as_slice()); } -) +); #[macro_export] macro_rules! make_enumerated_getter( - ( $attr:ident, $htmlname:expr, $default:expr, $($choices: pat)|+) => ( + ( $attr:ident, $htmlname:expr, $default:expr, $(($choices: pat))|+) => ( fn $attr(self) -> DOMString { use dom::element::{Element, AttributeHandlers}; use dom::bindings::codegen::InheritTypes::ElementCast; @@ -109,7 +109,7 @@ macro_rules! make_enumerated_getter( use std::borrow::ToOwned; let element: JSRef<Element> = ElementCast::from_ref(self); let val = element.get_string_attribute(&Atom::from_slice($htmlname)) - .into_ascii_lower(); + .into_ascii_lowercase(); // https://html.spec.whatwg.org/multipage/forms.html#attr-fs-method match val.as_slice() { $($choices)|+ => val, @@ -117,10 +117,10 @@ macro_rules! make_enumerated_getter( } } ); - ($attr:ident, $default:expr, $($choices: pat)|+) => { - make_enumerated_getter!($attr, stringify!($attr).to_ascii_lower().as_slice(), $default, $($choices)|+) + ($attr:ident, $default:expr, $(($choices: pat))|+) => { + make_enumerated_getter!($attr, stringify!($attr).to_ascii_lowercase().as_slice(), $default, $(($choices))|+); } -) +); // concat_idents! doesn't work for function name positions, so // we have to specify both the content name and the HTML name here @@ -135,7 +135,7 @@ macro_rules! make_setter( element.set_string_attribute(&Atom::from_slice($htmlname), value) } ); -) +); #[macro_export] macro_rules! make_bool_setter( @@ -148,7 +148,7 @@ macro_rules! make_bool_setter( element.set_bool_attribute(&Atom::from_slice($htmlname), value) } ); -) +); #[macro_export] macro_rules! make_uint_setter( @@ -161,7 +161,7 @@ macro_rules! make_uint_setter( element.set_uint_attribute(&Atom::from_slice($htmlname), value) } ); -) +); /// For use on non-jsmanaged types /// Use #[jstraceable] on JS managed types @@ -184,7 +184,7 @@ macro_rules! no_jsmanaged_fields( } } ); -) +); /// These are used to generate a event handler which has no special case. macro_rules! define_event_handler( @@ -199,32 +199,32 @@ macro_rules! define_event_handler( eventtarget.set_event_handler_common(stringify!($event_type), listener) } ) -) +); macro_rules! event_handler( ($event_type: ident, $getter: ident, $setter: ident) => ( - define_event_handler!(EventHandlerNonNull, $event_type, $getter, $setter) + define_event_handler!(EventHandlerNonNull, $event_type, $getter, $setter); ) -) +); macro_rules! error_event_handler( ($event_type: ident, $getter: ident, $setter: ident) => ( - define_event_handler!(OnErrorEventHandlerNonNull, $event_type, $getter, $setter) + define_event_handler!(OnErrorEventHandlerNonNull, $event_type, $getter, $setter); ) -) +); // https://html.spec.whatwg.org/multipage/webappapis.html#globaleventhandlers // see webidls/EventHandler.webidl // As more methods get added, just update them here. macro_rules! global_event_handlers( () => ( - event_handler!(load, GetOnload, SetOnload) - global_event_handlers!(NoOnload) + event_handler!(load, GetOnload, SetOnload); + global_event_handlers!(NoOnload); ); (NoOnload) => ( - event_handler!(click, GetOnclick, SetOnclick) - event_handler!(input, GetOninput, SetOninput) - event_handler!(change, GetOnchange, SetOnchange) + event_handler!(click, GetOnclick, SetOnclick); + event_handler!(input, GetOninput, SetOninput); + event_handler!(change, GetOnchange, SetOnchange); ) -) +); diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 5433e666180..2128b0f93f4 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -52,6 +52,7 @@ use style::{matches, SelectorList}; use js::jsapi::{JSContext, JSObject, JSTracer, JSRuntime}; use js::jsfriendapi; +use core::nonzero::NonZero; use libc; use libc::{uintptr_t, c_void}; use std::borrow::ToOwned; @@ -122,7 +123,6 @@ impl NodeDerived for EventTarget { bitflags! { #[doc = "Flags for node items."] #[jstraceable] - #[deriving(Copy)] flags NodeFlags: u16 { #[doc = "Specifies whether this node is in a document."] const IS_IN_DOC = 0x01, @@ -183,7 +183,7 @@ impl Drop for Node { /// suppress observers flag /// http://dom.spec.whatwg.org/#concept-node-insert /// http://dom.spec.whatwg.org/#concept-node-remove -#[deriving(Copy)] +#[derive(Copy)] enum SuppressObserver { Suppressed, Unsuppressed @@ -199,14 +199,14 @@ pub struct SharedLayoutData { pub struct LayoutData { chan: Option<LayoutChan>, _shared_data: SharedLayoutData, - _data: *const (), + _data: NonZero<*const ()>, } pub struct LayoutDataRef { pub data_cell: RefCell<Option<LayoutData>>, } -no_jsmanaged_fields!(LayoutDataRef) +no_jsmanaged_fields!(LayoutDataRef); impl LayoutDataRef { pub fn new() -> LayoutDataRef { @@ -225,8 +225,8 @@ impl LayoutDataRef { pub fn take_chan(&self) -> Option<LayoutChan> { let mut layout_data = self.data_cell.borrow_mut(); match &mut *layout_data { - &None => None, - &Some(ref mut layout_data) => Some(layout_data.chan.take().unwrap()), + &mut None => None, + &mut Some(ref mut layout_data) => Some(layout_data.chan.take().unwrap()), } } @@ -255,8 +255,10 @@ impl LayoutDataRef { } } +unsafe impl Send for LayoutDataRef {} + /// The different types of nodes. -#[deriving(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Show)] #[jstraceable] pub enum NodeTypeId { DocumentType, @@ -387,7 +389,9 @@ impl<'a> QuerySelectorIterator<'a> { } } -impl<'a> Iterator<JSRef<'a, Node>> for QuerySelectorIterator<'a> { +impl<'a> Iterator for QuerySelectorIterator<'a> { + type Item = JSRef<'a, Node>; + fn next(&mut self) -> Option<JSRef<'a, Node>> { let selectors = &self.selectors; // TODO(cgaebel): Is it worth it to build a bloom filter here @@ -501,7 +505,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { } s.push_str(self.debug_str().as_slice()); - debug!("{}", s); + debug!("{:?}", s); // FIXME: this should have a pure version? for kid in self.children() { @@ -511,7 +515,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { /// Returns a string that describes this node. fn debug_str(self) -> String { - format!("{}", self.type_id) + format!("{:?}", self.type_id) } fn is_in_doc(self) -> bool { @@ -825,8 +829,12 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { } fn child_elements(self) -> ChildElementIterator<'a> { + fn cast(n: JSRef<Node>) -> Option<JSRef<Element>> { + ElementCast::to_ref(n) + } + self.children() - .filter_map::<JSRef<Element>>(ElementCast::to_ref) + .filter_map(cast as fn(JSRef<Node>) -> Option<JSRef<Element>>) .peekable() } @@ -861,9 +869,12 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { publicId: "".to_owned(), systemId: "".to_owned(), - attrs: match ElementCast::to_ref(self) { - Some(element) => element.summarize(), - None => vec!(), + attrs: { + let e: Option<JSRef<Element>> = ElementCast::to_ref(self); + match e { + Some(element) => element.summarize(), + None => vec!(), + } }, isDocumentElement: @@ -1007,16 +1018,18 @@ impl RawLayoutNodeHelpers for Node { pub type ChildElementIterator<'a> = Peekable<JSRef<'a, Element>, - FilterMap<'a, - JSRef<'a, Node>, + FilterMap<JSRef<'a, Node>, JSRef<'a, Element>, - NodeChildrenIterator<'a>>>; + NodeChildrenIterator<'a>, + fn(JSRef<Node>) -> Option<JSRef<Element>>>>; pub struct NodeChildrenIterator<'a> { current: Option<JSRef<'a, Node>>, } -impl<'a> Iterator<JSRef<'a, Node>> for NodeChildrenIterator<'a> { +impl<'a> Iterator for NodeChildrenIterator<'a> { + type Item = JSRef<'a, Node>; + fn next(&mut self) -> Option<JSRef<'a, Node>> { let node = self.current; self.current = node.and_then(|node| node.next_sibling().map(|node| *node.root())); @@ -1028,7 +1041,9 @@ pub struct ReverseChildrenIterator { current: Option<Root<Node>>, } -impl Iterator<Temporary<Node>> for ReverseChildrenIterator { +impl Iterator for ReverseChildrenIterator { + type Item = Temporary<Node>; + fn next(&mut self) -> Option<Temporary<Node>> { let node = self.current.r().map(Temporary::from_rooted); self.current = self.current.take().and_then(|node| node.r().prev_sibling()).root(); @@ -1040,7 +1055,9 @@ pub struct AncestorIterator<'a> { current: Option<JSRef<'a, Node>>, } -impl<'a> Iterator<JSRef<'a, Node>> for AncestorIterator<'a> { +impl<'a> Iterator for AncestorIterator<'a> { + type Item = JSRef<'a, Node>; + fn next(&mut self) -> Option<JSRef<'a, Node>> { let node = self.current; self.current = node.and_then(|node| node.parent_node().map(|node| *node.root())); @@ -1063,7 +1080,9 @@ impl<'a> TreeIterator<'a> { } } -impl<'a> Iterator<JSRef<'a, Node>> for TreeIterator<'a> { +impl<'a> Iterator for TreeIterator<'a> { + type Item = JSRef<'a, Node>; + fn next(&mut self) -> Option<JSRef<'a, Node>> { let ret = self.stack.pop(); ret.map(|node| { @@ -1096,7 +1115,7 @@ impl NodeIterator { } fn next_child<'b>(&self, node: JSRef<'b, Node>) -> Option<JSRef<'b, Node>> { - let skip = |element: JSRef<Element>| { + let skip = |&:element: JSRef<Element>| { !self.include_descendants_of_void && element.is_void() }; @@ -1107,7 +1126,9 @@ impl NodeIterator { } } -impl<'a> Iterator<JSRef<'a, Node>> for NodeIterator { +impl<'a> Iterator for NodeIterator { + type Item = JSRef<'a, Node>; + fn next(&mut self) -> Option<JSRef<'a, Node>> { self.current_node = match self.current_node.as_ref().map(|node| node.root()) { None => { @@ -1155,7 +1176,7 @@ impl<'a> Iterator<JSRef<'a, Node>> for NodeIterator { } /// Specifies whether children must be recursively cloned or not. -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] pub enum CloneChildrenFlag { CloneChildren, DoNotCloneChildren @@ -1635,13 +1656,13 @@ impl Node { None => {} Some(chan) => { let LayoutChan(chan) = chan; - chan.send(Msg::ReapLayoutData(layout_data)) + chan.send(Msg::ReapLayoutData(layout_data)).unwrap() }, } } } - pub fn collect_text_contents<'a, T: Iterator<JSRef<'a, Node>>>(mut iterator: T) -> String { + pub fn collect_text_contents<'a, T: Iterator<Item=JSRef<'a, Node>>>(mut iterator: T) -> String { let mut content = String::new(); for node in iterator { let text: Option<JSRef<Text>> = TextCast::to_ref(node); @@ -1989,7 +2010,8 @@ impl<'a> NodeMethods for JSRef<'a, Node> { fn Normalize(self) { let mut prev_text = None; for child in self.children() { - match TextCast::to_ref(child) { + let t: Option<JSRef<Text>> = TextCast::to_ref(child); + match t { Some(text) => { let characterdata: JSRef<CharacterData> = CharacterDataCast::from_ref(text); if characterdata.Length() == 0 { @@ -2185,9 +2207,11 @@ impl<'a> NodeMethods for JSRef<'a, Node> { /// and are also used in the HTML parser interface. #[allow(raw_pointer_deriving)] -#[deriving(Clone, PartialEq, Eq, Copy)] +#[derive(Clone, PartialEq, Eq, Copy)] pub struct TrustedNodeAddress(pub *const c_void); +unsafe impl Send for TrustedNodeAddress {} + pub fn document_from_node<T: NodeBase+Reflectable>(derived: JSRef<T>) -> Temporary<Document> { let node: JSRef<Node> = NodeCast::from_ref(derived); node.owner_doc() @@ -2280,7 +2304,9 @@ impl<'a> style::TNode<'a, JSRef<'a, Element>> for JSRef<'a, Node> { ElementCast::to_ref(self).unwrap() } - fn match_attr(self, attr: &style::AttrSelector, test: |&str| -> bool) -> bool { + fn match_attr<F>(self, attr: &style::AttrSelector, test: F) -> bool + where F: Fn(&str) -> bool + { let name = { if self.is_html_element_in_html_document() { &attr.lower_name @@ -2367,7 +2393,7 @@ impl<'a> DisabledStateHelpers for JSRef<'a, Node> { } /// A summary of the changes that happened to a node. -#[deriving(Copy, Clone, PartialEq)] +#[derive(Copy, Clone, PartialEq)] pub enum NodeDamage { /// The node's `style` attribute changed. NodeStyleDamaged, diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index cbbabb912a7..01fce8d2d82 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -11,7 +11,7 @@ use dom::bindings::error::Fallible; use servo_util::str::DOMString; use servo_net::storage_task::StorageTask; use servo_net::storage_task::StorageTaskMsg; -use std::comm::channel; +use std::sync::mpsc::channel; use url::Url; #[dom_struct] @@ -55,21 +55,21 @@ impl<'a> StorageMethods for JSRef<'a, Storage> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url())); - receiver.recv() + receiver.recv().unwrap() } fn Key(self, index: u32) -> Option<DOMString> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), index)); - receiver.recv() + receiver.recv().unwrap() } fn GetItem(self, name: DOMString) -> Option<DOMString> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::GetItem(sender, self.get_url(), name)); - receiver.recv() + receiver.recv().unwrap() } fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<DOMString> { @@ -82,7 +82,7 @@ impl<'a> StorageMethods for JSRef<'a, Storage> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::SetItem(sender, self.get_url(), name, value)); - if receiver.recv() { + if receiver.recv().unwrap() { //TODO send notification } } @@ -99,7 +99,7 @@ impl<'a> StorageMethods for JSRef<'a, Storage> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::RemoveItem(sender, self.get_url(), name)); - if receiver.recv() { + if receiver.recv().unwrap() { //TODO send notification } } @@ -112,7 +112,7 @@ impl<'a> StorageMethods for JSRef<'a, Storage> { let (sender, receiver) = channel(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url())); - if receiver.recv() { + if receiver.recv().unwrap() { //TODO send notification } } diff --git a/components/script/dom/treewalker.rs b/components/script/dom/treewalker.rs index b578823acd6..d7dab56949d 100644 --- a/components/script/dom/treewalker.rs +++ b/components/script/dom/treewalker.rs @@ -119,30 +119,37 @@ impl<'a> TreeWalkerMethods for JSRef<'a, TreeWalker> { } } -type NodeAdvancer<'a> = |node: JSRef<'a, Node>|: 'a -> Option<Temporary<Node>>; - -trait PrivateTreeWalkerHelpers<'a> { - fn traverse_children(self, - next_child: NodeAdvancer<'a>, - next_sibling: NodeAdvancer<'a>) - -> Fallible<Option<Temporary<Node>>>; - fn traverse_siblings(self, - next_child: NodeAdvancer<'a>, - next_sibling: NodeAdvancer<'a>) - -> Fallible<Option<Temporary<Node>>>; - fn is_root_node(self, node: JSRef<'a, Node>) -> bool; - fn is_current_node(self, node: JSRef<'a, Node>) -> bool; - fn first_following_node_not_following_root(self, node: JSRef<'a, Node>) +type NodeAdvancer<'a> = Fn(JSRef<'a, Node>) -> Option<Temporary<Node>> + 'a; + +trait PrivateTreeWalkerHelpers { + fn traverse_children<F, G>(self, + next_child: F, + next_sibling: G) + -> Fallible<Option<Temporary<Node>>> + where F: Fn(JSRef<Node>) -> Option<Temporary<Node>>, + G: Fn(JSRef<Node>) -> Option<Temporary<Node>>; + fn traverse_siblings<F, G>(self, + next_child: F, + next_sibling: G) + -> Fallible<Option<Temporary<Node>>> + where F: Fn(JSRef<Node>) -> Option<Temporary<Node>>, + G: Fn(JSRef<Node>) -> Option<Temporary<Node>>; + fn is_root_node(self, node: JSRef<Node>) -> bool; + fn is_current_node(self, node: JSRef<Node>) -> bool; + fn first_following_node_not_following_root(self, node: JSRef<Node>) -> Option<Temporary<Node>>; - fn accept_node(self, node: JSRef<'a, Node>) -> Fallible<u16>; + fn accept_node(self, node: JSRef<Node>) -> Fallible<u16>; } -impl<'a> PrivateTreeWalkerHelpers<'a> for JSRef<'a, TreeWalker> { +impl<'a> PrivateTreeWalkerHelpers for JSRef<'a, TreeWalker> { // http://dom.spec.whatwg.org/#concept-traverse-children - fn traverse_children(self, - next_child: NodeAdvancer<'a>, - next_sibling: NodeAdvancer<'a>) - -> Fallible<Option<Temporary<Node>>> { + fn traverse_children<F, G>(self, + next_child: F, + next_sibling: G) + -> Fallible<Option<Temporary<Node>>> + where F: Fn(JSRef<Node>) -> Option<Temporary<Node>>, + G: Fn(JSRef<Node>) -> Option<Temporary<Node>> + { // "To **traverse children** of type *type*, run these steps:" // "1. Let node be the value of the currentNode attribute." // "2. Set node to node's first child if type is first, and node's last child if type is last." @@ -218,10 +225,13 @@ impl<'a> PrivateTreeWalkerHelpers<'a> for JSRef<'a, TreeWalker> { } // http://dom.spec.whatwg.org/#concept-traverse-siblings - fn traverse_siblings(self, - next_child: NodeAdvancer<'a>, - next_sibling: NodeAdvancer<'a>) - -> Fallible<Option<Temporary<Node>>> { + fn traverse_siblings<F, G>(self, + next_child: F, + next_sibling: G) + -> Fallible<Option<Temporary<Node>>> + where F: Fn(JSRef<Node>) -> Option<Temporary<Node>>, + G: Fn(JSRef<Node>) -> Option<Temporary<Node>> + { // "To **traverse siblings** of type *type* run these steps:" // "1. Let node be the value of the currentNode attribute." let mut node = self.current_node.get().root().clone(); @@ -282,7 +292,7 @@ impl<'a> PrivateTreeWalkerHelpers<'a> for JSRef<'a, TreeWalker> { } // http://dom.spec.whatwg.org/#concept-tree-following - fn first_following_node_not_following_root(self, node: JSRef<'a, Node>) + fn first_following_node_not_following_root(self, node: JSRef<Node>) -> Option<Temporary<Node>> { // "An object A is following an object B if A and B are in the same tree // and A comes after B in tree order." @@ -309,7 +319,7 @@ impl<'a> PrivateTreeWalkerHelpers<'a> for JSRef<'a, TreeWalker> { } // http://dom.spec.whatwg.org/#concept-node-filter - fn accept_node(self, node: JSRef<'a, Node>) -> Fallible<u16> { + fn accept_node(self, node: JSRef<Node>) -> Fallible<u16> { // "To filter node run these steps:" // "1. Let n be node's nodeType attribute value minus 1." let n: uint = node.NodeType() as uint - 1; @@ -329,11 +339,11 @@ impl<'a> PrivateTreeWalkerHelpers<'a> for JSRef<'a, TreeWalker> { } } - fn is_root_node(self, node: JSRef<'a, Node>) -> bool { + fn is_root_node(self, node: JSRef<Node>) -> bool { JS::from_rooted(node) == self.root_node } - fn is_current_node(self, node: JSRef<'a, Node>) -> bool { + fn is_current_node(self, node: JSRef<Node>) -> bool { JS::from_rooted(node) == self.current_node.get() } } @@ -526,7 +536,9 @@ impl<'a> TreeWalkerHelpers<'a> for JSRef<'a, TreeWalker> { } } -impl<'a> Iterator<JSRef<'a, Node>> for JSRef<'a, TreeWalker> { +impl<'a> Iterator for JSRef<'a, TreeWalker> { + type Item = JSRef<'a, Node>; + fn next(&mut self) -> Option<JSRef<'a, Node>> { match self.next_node() { Ok(node) => node.map(|n| n.root().clone()), diff --git a/components/script/dom/urlsearchparams.rs b/components/script/dom/urlsearchparams.rs index 035e558d878..b8ab6c9329c 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -18,7 +18,7 @@ use encoding::all::UTF_8; use encoding::types::{EncodingRef, EncoderTrap}; use std::collections::HashMap; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::fmt::radix; use std::ascii::OwnedAsciiExt; @@ -67,7 +67,7 @@ impl<'a> URLSearchParamsMethods for JSRef<'a, URLSearchParams> { match data.entry(name) { Occupied(entry) => entry.into_mut().push(value), Vacant(entry) => { - entry.set(vec!(value)); + entry.insert(vec!(value)); } } @@ -117,7 +117,7 @@ impl URLSearchParamsHelpers for URLSearchParams { a => { // http://url.spec.whatwg.org/#percent-encode let mut encoded = vec!(0x25); // % - let s = format!("{}", radix(a, 16)).into_ascii_upper(); + let s = format!("{}", radix(a, 16)).into_ascii_uppercase(); let bytes = s.as_bytes(); encoded.push_all(bytes); encoded diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 91402fe6c1f..fe7ea336122 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -47,6 +47,7 @@ use libc; use serialize::base64::{FromBase64, ToBase64, STANDARD}; use std::cell::{Ref, RefMut}; use std::default::Default; +use std::ffi::CString; use std::rc::Rc; use time; @@ -283,9 +284,9 @@ impl<'a> WindowMethods for JSRef<'a, Window> { }) } - global_event_handlers!() - event_handler!(unload, GetOnunload, SetOnunload) - error_event_handler!(error, GetOnerror, SetOnerror) + global_event_handlers!(); + event_handler!(unload, GetOnunload, SetOnunload); + error_event_handler!(error, GetOnerror, SetOnerror); fn Screen(self) -> Temporary<Screen> { self.screen.or_init(|| Screen::new(self)) @@ -336,7 +337,7 @@ impl<'a, T: Reflectable> ScriptHelpers for JSRef<'a, T> { let global = global_object_for_js_object(this).root().r().reflector().get_jsobject(); let code: Vec<u16> = code.as_slice().utf16_units().collect(); let mut rval = UndefinedValue(); - let filename = filename.to_c_str(); + let filename = CString::from_slice(filename.as_bytes()); with_compartment(cx, global, || { unsafe { diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 8fa36436c19..df793ede178 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -26,6 +26,7 @@ use js::jsval::JSVal; use url::UrlParser; use std::cell::Cell; +use std::sync::mpsc::{channel, Sender}; pub type TrustedWorkerAddress = Trusted<Worker>; @@ -97,7 +98,7 @@ impl<'a> WorkerMethods for JSRef<'a, Worker> { Ok(()) } - event_handler!(message, GetOnmessage, SetOnmessage) + event_handler!(message, GetOnmessage, SetOnmessage); } pub struct WorkerMessageHandler { diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index da3b50b1f32..e78a4a71ed0 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -30,7 +30,7 @@ use std::default::Default; use std::rc::Rc; use url::{Url, UrlParser}; -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] #[jstraceable] pub enum WorkerGlobalScopeTypeId { DedicatedGlobalScope, diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 191d3cf6dde..f1d061bcdb7 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -34,6 +34,7 @@ use encoding::types::{DecoderTrap, Encoding, EncodingRef, EncoderTrap}; use hyper::header::Headers; use hyper::header::common::{Accept, ContentLength, ContentType}; +use hyper::header::quality_item::QualityItem; use hyper::http::RawStatus; use hyper::mime::{mod, Mime}; use hyper::method::Method; @@ -52,7 +53,7 @@ use servo_util::task::spawn_named; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; -use std::comm::{Sender, Receiver, channel}; +use std::sync::mpsc::{Sender, Receiver, channel}; use std::default::Default; use std::io::Timer; use std::str::FromStr; @@ -64,7 +65,7 @@ use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams; use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams}; pub type SendParam = StringOrURLSearchParams; -#[deriving(PartialEq, Copy)] +#[derive(PartialEq, Copy)] #[jstraceable] enum XMLHttpRequestState { Unsent = 0, @@ -92,11 +93,11 @@ impl Runnable for XHRProgressHandler { } } -#[deriving(PartialEq, Clone, Copy)] +#[derive(PartialEq, Clone, Copy)] #[jstraceable] pub struct GenerationId(uint); -#[deriving(Clone)] +#[derive(Clone)] pub enum XHRProgress { /// Notify that headers have been received HeadersReceived(GenerationId, Option<Headers>, Option<RawStatus>), @@ -230,7 +231,7 @@ impl XMLHttpRequest { notify_partial_progress(fetch_type, XHRProgress::Errored(gen_id, $err)); return Err($err) }); - ) + ); macro_rules! terminate( ($reason:expr) => ( @@ -243,7 +244,7 @@ impl XMLHttpRequest { } } ); - ) + ); match cors_request { @@ -257,13 +258,14 @@ impl XMLHttpRequest { let req2 = req.clone(); // TODO: this exists only to make preflight check non-blocking // perhaps should be handled by the resource_loader? - spawn_named("XHR:Cors".to_owned(), proc() { + spawn_named("XHR:Cors".to_owned(), move || { let response = req2.http_fetch(); chan.send(response); }); select! ( response = cors_port.recv() => { + let response = response.unwrap(); if response.network_error { notify_error_and_return!(Network); } else { @@ -273,8 +275,8 @@ impl XMLHttpRequest { }); } }, - reason = terminate_receiver.recv() => terminate!(reason) - ) + reason = terminate_receiver.recv() => terminate!(reason.unwrap()) + ); } _ => {} } @@ -286,6 +288,7 @@ impl XMLHttpRequest { let progress_port; select! ( response = start_port.recv() => { + let response = response.unwrap(); match cors_request { Ok(Some(ref req)) => { match response.metadata.headers { @@ -302,8 +305,8 @@ impl XMLHttpRequest { progress_port = response.progress_port; }, - reason = terminate_receiver.recv() => terminate!(reason) - ) + reason = terminate_receiver.recv() => terminate!(reason.unwrap()) + ); let mut buf = vec!(); loop { @@ -319,7 +322,7 @@ impl XMLHttpRequest { }; select! ( - progress = progress_port.recv() => match progress { + progress = progress_port.recv() => match progress.unwrap() { Payload(data) => { buf.push_all(data.as_slice()); notify_partial_progress(fetch_type, @@ -333,14 +336,14 @@ impl XMLHttpRequest { notify_error_and_return!(Network); } }, - reason = terminate_receiver.recv() => terminate!(reason) - ) + reason = terminate_receiver.recv() => terminate!(reason.unwrap()) + ); } } } impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { - event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange) + event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange); fn ReadyState(self) -> u16 { self.ready_state.get() as u16 @@ -354,12 +357,12 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { // without changing capitalization, this will actually sidestep rust-http's type system // since methods like "patch" or "PaTcH" will be considered extension methods // despite the there being a rust-http method variant for them - let upper = s.to_ascii_upper(); + let upper = s.to_ascii_uppercase(); match upper.as_slice() { "DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "CONNECT" | "TRACE" | - "TRACK" => from_str(upper.as_slice()), - _ => from_str(s) + "TRACK" => upper.parse(), + _ => s.parse() } }); // Step 2 @@ -438,18 +441,18 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { None => return Err(Syntax) }; - debug!("SetRequestHeader: name={}, value={}", name.as_str(), value.as_str()); + debug!("SetRequestHeader: name={:?}, value={:?}", name.as_str(), value.as_str()); let mut headers = self.request_headers.borrow_mut(); // Steps 6,7 match headers.get_raw(name_str) { Some(raw) => { - debug!("SetRequestHeader: old value = {}", raw[0]); + debug!("SetRequestHeader: old value = {:?}", raw[0]); let mut buf = raw[0].clone(); buf.push_all(b", "); buf.push_all(value.as_slice()); - debug!("SetRequestHeader: new value = {}", buf); + debug!("SetRequestHeader: new value = {:?}", buf); value = ByteString::new(buf); }, None => {} @@ -573,8 +576,9 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { if !request_headers.has::<Accept>() { + let mime = Mime(mime::TopLevel::Star, mime::SubLevel::Star, vec![]); request_headers.set( - Accept(vec![Mime(mime::TopLevel::Star, mime::SubLevel::Star, vec![])])); + Accept(vec![QualityItem::new(mime, 1.0)])); } } // drops the borrow_mut @@ -610,7 +614,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { _ => {} } - debug!("request_headers = {}", *self.request_headers.borrow()); + debug!("request_headers = {:?}", *self.request_headers.borrow()); let gen_id = self.generation_id.get(); if self.sync.get() { @@ -624,7 +628,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { // inflight events queued up in the script task's port. let addr = Trusted::new(self.global.root().r().get_cx(), self, script_chan.clone()); - spawn_named("XHRTask".to_owned(), proc() { + spawn_named("XHRTask".to_owned(), move || { let _ = XMLHttpRequest::fetch(&mut SyncOrAsync::Async(addr, script_chan), resource_task, load_data, @@ -767,7 +771,7 @@ trait PrivateXMLHttpRequestHelpers { impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { fn change_ready_state(self, rs: XMLHttpRequestState) { - assert!(self.ready_state.get() != rs) + assert!(self.ready_state.get() != rs); self.ready_state.set(rs); let global = self.global.root(); let event = Event::new(global.r(), @@ -789,7 +793,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { return } ); - ) + ); // Ignore message if it belongs to a terminated fetch return_if_fetch_was_terminated!(); @@ -893,7 +897,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { fn terminate_ongoing_fetch(self) { let GenerationId(prev_id) = self.generation_id.get(); self.generation_id.set(GenerationId(prev_id + 1)); - self.terminate_sender.borrow().as_ref().map(|s| s.send_opt(TerminateReason::AbortedOrReopened)); + self.terminate_sender.borrow().as_ref().map(|s| s.send(TerminateReason::AbortedOrReopened)); } fn insert_trusted_header(self, name: String, value: String) { @@ -936,10 +940,10 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { let oneshot = self.timer.borrow_mut() .oneshot(Duration::milliseconds(timeout as i64)); let terminate_sender = (*self.terminate_sender.borrow()).clone(); - spawn_named("XHR:Timer".to_owned(), proc () { - match oneshot.recv_opt() { + spawn_named("XHR:Timer".to_owned(), move || { + match oneshot.recv() { Ok(_) => { - terminate_sender.map(|s| s.send_opt(TerminateReason::TimedOut)); + terminate_sender.map(|s| s.send(TerminateReason::TimedOut)); }, Err(_) => { // This occurs if xhr.timeout (the sender) goes out of scope (i.e, xhr went out of scope) @@ -980,7 +984,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { use hyper::header::common::SetCookie; // a dummy header so we can use headers.remove::<SetCookie2>() - #[deriving(Clone)] + #[derive(Clone)] struct SetCookie2; impl Header for SetCookie2 { fn header_name(_: Option<SetCookie2>) -> &'static str { diff --git a/components/script/dom/xmlhttprequesteventtarget.rs b/components/script/dom/xmlhttprequesteventtarget.rs index f596fe8419b..e27496ec2d9 100644 --- a/components/script/dom/xmlhttprequesteventtarget.rs +++ b/components/script/dom/xmlhttprequesteventtarget.rs @@ -9,7 +9,7 @@ use dom::bindings::codegen::InheritTypes::XMLHttpRequestEventTargetDerived; use dom::bindings::js::JSRef; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] #[jstraceable] pub enum XMLHttpRequestEventTargetTypeId { XMLHttpRequest, @@ -44,11 +44,11 @@ impl XMLHttpRequestEventTargetDerived for EventTarget { } impl<'a> XMLHttpRequestEventTargetMethods for JSRef<'a, XMLHttpRequestEventTarget> { - event_handler!(loadstart,GetOnloadstart, SetOnloadstart) - event_handler!(progress, GetOnprogress, SetOnprogress) - event_handler!(abort, GetOnabort, SetOnabort) - event_handler!(error, GetOnerror, SetOnerror) - event_handler!(load, GetOnload, SetOnload) - event_handler!(timeout, GetOntimeout, SetOntimeout) - event_handler!(loadend, GetOnloadend, SetOnloadend) + event_handler!(loadstart,GetOnloadstart, SetOnloadstart); + event_handler!(progress, GetOnprogress, SetOnprogress); + event_handler!(abort, GetOnabort, SetOnabort); + event_handler!(error, GetOnerror, SetOnerror); + event_handler!(load, GetOnload, SetOnload); + event_handler!(timeout, GetOntimeout, SetOntimeout); + event_handler!(loadend, GetOnloadend, SetOnloadend); } diff --git a/components/script/layout_interface.rs b/components/script/layout_interface.rs index 2856930b073..80181c09cda 100644 --- a/components/script/layout_interface.rs +++ b/components/script/layout_interface.rs @@ -13,8 +13,8 @@ use geom::rect::Rect; use script_traits::{ScriptControlChan, OpaqueScriptLayoutChannel, UntrustedNodeAddress}; use servo_msg::constellation_msg::{PipelineExitType, WindowSizeData}; use servo_util::geometry::Au; -use std::any::{Any, AnyRefExt}; -use std::comm::{channel, Receiver, Sender}; +use std::any::Any; +use std::sync::mpsc::{channel, Receiver, Sender}; use std::boxed::BoxAny; use style::Stylesheet; use url::Url; @@ -77,7 +77,7 @@ pub struct HitTestResponse(pub UntrustedNodeAddress); pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>); /// Why we're doing reflow. -#[deriving(PartialEq, Show)] +#[derive(PartialEq, Show)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, @@ -117,7 +117,7 @@ pub struct Reflow { } /// Encapsulates a channel to the layout task. -#[deriving(Clone)] +#[derive(Clone)] pub struct LayoutChan(pub Sender<Msg>); impl LayoutChan { diff --git a/components/script/lib.rs b/components/script/lib.rs index a3c528df29c..f24bd11a82e 100644 --- a/components/script/lib.rs +++ b/components/script/lib.rs @@ -2,19 +2,22 @@ * 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/. */ -#![feature(default_type_params, globs, macro_rules, phase, unsafe_destructor)] +#![feature(unsafe_destructor, plugin, box_syntax, int_uint)] +#![feature(old_impl_check)] #![deny(unsafe_blocks)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(non_snake_case)] #![allow(missing_copy_implementations)] +#![allow(unstable)] #![doc="The script crate contains all matters DOM."] -#[phase(plugin, link)] +#[macro_use] extern crate log; +extern crate core; extern crate devtools_traits; extern crate cssparser; extern crate collections; @@ -26,22 +29,21 @@ extern crate js; extern crate libc; extern crate msg; extern crate net; -extern crate rustrt; extern crate serialize; extern crate time; extern crate canvas; extern crate script_traits; -#[phase(plugin)] +#[no_link] #[plugin] #[macro_use] extern crate "plugins" as servo_plugins; extern crate "net" as servo_net; extern crate "util" as servo_util; -#[phase(plugin, link)] +#[macro_use] extern crate style; extern crate "msg" as servo_msg; extern crate url; extern crate uuid; extern crate string_cache; -#[phase(plugin)] +#[no_link] #[macro_use] #[plugin] extern crate string_cache_macros; pub mod cors; diff --git a/components/script/page.rs b/components/script/page.rs index 979f49f6681..b051e1df891 100644 --- a/components/script/page.rs +++ b/components/script/page.rs @@ -31,7 +31,8 @@ use servo_util::geometry; use servo_util::str::DOMString; use servo_util::smallvec::SmallVec; use std::cell::{Cell, Ref, RefMut}; -use std::comm::{channel, Receiver, Empty, Disconnected}; +use std::sync::mpsc::{channel, Receiver}; +use std::sync::mpsc::TryRecvError::{Empty, Disconnected}; use std::mem::replace; use std::num::Float; use std::rc::Rc; @@ -139,7 +140,7 @@ impl Page { let (rpc_send, rpc_recv) = channel(); let LayoutChan(ref lchan) = layout_chan; lchan.send(Msg::GetRPC(rpc_send)); - rpc_recv.recv() + rpc_recv.recv().unwrap() }; Page { id: id, @@ -196,7 +197,7 @@ impl Page { .position(|page_tree| page_tree.id == id) }; match remove_idx { - Some(idx) => Some(self.children.borrow_mut().remove(idx).unwrap()), + Some(idx) => Some(self.children.borrow_mut().remove(idx)), None => { self.children .borrow_mut() @@ -251,7 +252,9 @@ impl Page { } } -impl Iterator<Rc<Page>> for PageIterator { +impl Iterator for PageIterator { + type Item = Rc<Page>; + fn next(&mut self) -> Option<Rc<Page>> { match self.stack.pop() { Some(next) => { @@ -298,7 +301,7 @@ impl Page { } pub fn get_url(&self) -> Url { - self.url().as_ref().unwrap().ref0().clone() + self.url().as_ref().unwrap().0.clone() } // FIXME(cgaebel): join_layout is racey. What if the compositor triggers a @@ -353,7 +356,7 @@ impl Page { Some(root) => root, }; - debug!("script: performing reflow for goal {}", goal); + debug!("script: performing reflow for goal {:?}", goal); let root: JSRef<Node> = NodeCast::from_ref(root.r()); if !root.get_has_dirty_descendants() { @@ -361,7 +364,7 @@ impl Page { return } - debug!("script: performing reflow for goal {}", goal); + debug!("script: performing reflow for goal {:?}", goal); // Layout will let us know when it's done. let (join_chan, join_port) = channel(); diff --git a/components/script/parse/html.rs b/components/script/parse/html.rs index 156994e5ea1..99bb8edf60f 100644 --- a/components/script/parse/html.rs +++ b/components/script/parse/html.rs @@ -27,7 +27,7 @@ use servo_net::resource_task::{ProgressMsg, LoadResponse}; use servo_util::task_state; use servo_util::task_state::IN_HTML_PARSER; use std::ascii::AsciiExt; -use std::str::CowString; +use std::string::CowString; use url::Url; use html5ever::Attribute; use html5ever::tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText}; diff --git a/components/script/script_task.rs b/components/script/script_task.rs index 6726c0e832e..3c1771a8b2d 100644 --- a/components/script/script_task.rs +++ b/components/script/script_task.rs @@ -68,28 +68,30 @@ use servo_util::task_state; use geom::point::Point2D; use hyper::header::{Header, HeaderFormat}; -use hyper::header::common::util as header_util; +use hyper::header::shared::util as header_util; use js::jsapi::{JS_SetWrapObjectCallbacks, JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ, JS_GC}; -use js::jsapi::{JSContext, JSRuntime}; +use js::jsapi::{JSContext, JSRuntime, JSObject}; use js::jsapi::{JS_SetGCParameter, JSGC_MAX_BYTES}; use js::jsapi::{JS_SetGCCallback, JSGCStatus, JSGC_BEGIN, JSGC_END}; use js::rust::{Cx, RtUtils}; use js; use url::Url; -use std::any::{Any, AnyRefExt}; +use libc; +use std::any::Any; use std::borrow::ToOwned; use std::cell::Cell; -use std::comm::{channel, Sender, Receiver, Select}; use std::fmt::{mod, Show}; use std::mem::replace; +use std::num::ToPrimitive; use std::rc::Rc; +use std::sync::mpsc::{channel, Sender, Receiver, Select}; use std::u32; use time::{Tm, strptime}; -thread_local!(pub static STACK_ROOTS: Cell<Option<RootCollectionPtr>> = Cell::new(None)) +thread_local!(pub static STACK_ROOTS: Cell<Option<RootCollectionPtr>> = Cell::new(None)); -#[deriving(Copy)] +#[derive(Copy)] pub enum TimerSource { FromWindow(PipelineId), FromWorker @@ -147,7 +149,7 @@ impl ScriptChan for NonWorkerScriptChan { fn clone(&self) -> Box<ScriptChan+Send> { let NonWorkerScriptChan(ref chan) = *self; - box NonWorkerScriptChan(chan.clone()) + box NonWorkerScriptChan((*chan).clone()) } } @@ -302,7 +304,7 @@ impl ScriptTaskFactory for ScriptTask { let ConstellationChan(const_chan) = constellation_chan.clone(); let (script_chan, script_port) = channel(); let layout_chan = LayoutChan(layout_chan.sender()); - spawn_named_with_send_on_failure("ScriptTask", task_state::SCRIPT, proc() { + spawn_named_with_send_on_failure("ScriptTask", task_state::SCRIPT, move || { let script_task = ScriptTask::new(id, box compositor as Box<ScriptListener>, layout_chan, @@ -350,6 +352,12 @@ impl ScriptTask { window_size: WindowSizeData) -> ScriptTask { let (js_runtime, js_context) = ScriptTask::new_rt_and_cx(); + let wrap_for_same_compartment = wrap_for_same_compartment as + unsafe extern "C" fn(*mut JSContext, *mut JSObject) -> *mut JSObject; + let pre_wrap = pre_wrap as + unsafe extern fn(*mut JSContext, *mut JSObject, *mut JSObject, + libc::c_uint) -> *mut JSObject; + unsafe { // JS_SetWrapObjectCallbacks clobbers the existing wrap callback, // and JSCompartment::wrap crashes if that happens. The only way @@ -425,7 +433,8 @@ impl ScriptTask { // Needed for debug assertions about whether GC is running. if !cfg!(ndebug) { unsafe { - JS_SetGCCallback(js_runtime.ptr, Some(debug_gc_callback)); + JS_SetGCCallback(js_runtime.ptr, + Some(debug_gc_callback as unsafe extern "C" fn(*mut JSRuntime, JSGCStatus))); } } @@ -497,11 +506,11 @@ impl ScriptTask { } let ret = sel.wait(); if ret == port1.id() { - MixedMessage::FromScript(self.port.recv()) + MixedMessage::FromScript(self.port.recv().unwrap()) } else if ret == port2.id() { - MixedMessage::FromConstellation(self.control_port.recv()) + MixedMessage::FromConstellation(self.control_port.recv().unwrap()) } else if ret == port3.id() { - MixedMessage::FromDevtools(self.devtools_port.recv()) + MixedMessage::FromDevtools(self.devtools_port.recv().unwrap()) } else { panic!("unexpected select result") } @@ -666,7 +675,7 @@ impl ScriptTask { /// Handles a notification that reflow completed. fn handle_reflow_complete_msg(&self, pipeline_id: PipelineId, reflow_id: uint) { - debug!("Script: Reflow {} complete for {}", reflow_id, pipeline_id); + debug!("Script: Reflow {:?} complete for {:?}", reflow_id, pipeline_id); let page = self.page.borrow_mut(); let page = page.find(pipeline_id).expect( "ScriptTask: received a load message for a layout channel that is not associated \ @@ -694,8 +703,8 @@ impl ScriptTask { with a page in the page tree. This is a bug."); page.window_size.set(new_size); match &mut *page.mut_url() { - &Some((_, ref mut needs_reflow)) => *needs_reflow = true, - &None => (), + &mut Some((_, ref mut needs_reflow)) => *needs_reflow = true, + &mut None => (), } } @@ -724,7 +733,7 @@ impl ScriptTask { // If root is being exited, shut down all pages let page = self.page.borrow_mut(); if page.id == id { - debug!("shutting down layout for root page {}", id); + debug!("shutting down layout for root page {:?}", id); *self.js_context.borrow_mut() = None; shut_down_layout(&*page, (*self.js_runtime).ptr, exit_type); return true @@ -748,7 +757,7 @@ impl ScriptTask { /// objects, parses HTML and CSS, and kicks off initial layout. fn load(&self, pipeline_id: PipelineId, load_data: LoadData) { let url = load_data.url.clone(); - debug!("ScriptTask: loading {} on page {}", url, pipeline_id); + debug!("ScriptTask: loading {:?} on page {:?}", url, pipeline_id); let page = self.page.borrow_mut(); let page = page.find(pipeline_id).expect("ScriptTask: received a load @@ -764,7 +773,7 @@ impl ScriptTask { // Pull out the `needs_reflow` flag explicitly because `reflow` can ask for the page's // URL, and we can't be holding a borrow on that URL (#4402). let needed_reflow = match &mut *page.mut_url() { - &Some((_, ref mut needs_reflow)) => replace(needs_reflow, false), + &mut Some((_, ref mut needs_reflow)) => replace(needs_reflow, false), _ => panic!("can't reload a page with no URL!") }; if needed_reflow { @@ -823,7 +832,7 @@ impl ScriptTask { consumer: input_chan, })); - let load_response = input_port.recv(); + let load_response = input_port.recv().unwrap(); load_response.metadata.headers.as_ref().map(|headers| { headers.get().map(|&LastModified(ref tm)| { @@ -855,7 +864,7 @@ impl ScriptTask { self.compositor.borrow_mut().set_ready_state(pipeline_id, PerformingLayout); // Kick off the initial reflow of the page. - debug!("kicking off initial reflow of {}", final_url); + debug!("kicking off initial reflow of {:?}", final_url); document.r().content_changed(NodeCast::from_ref(document.r()), NodeDamage::OtherNodeDamage); window.r().flush_layout(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery); @@ -1025,9 +1034,8 @@ impl ScriptTask { props.location, is_repeating, is_composing, ctrl, alt, shift, meta, props.char_code, 0).root(); - let _ = target.DispatchEvent(EventCast::from_ref(event.r())); - let ev = EventCast::from_ref(event.r()); + let _ = target.DispatchEvent(ev); prevented = ev.DefaultPrevented(); // TODO: if keypress event is canceled, prevent firing input events } @@ -1127,25 +1135,26 @@ impl ScriptTask { } fn handle_click_event(&self, pipeline_id: PipelineId, _button: uint, point: Point2D<f32>) { - debug!("ClickEvent: clicked at {}", point); + debug!("ClickEvent: clicked at {:?}", point); let page = get_page(&*self.page.borrow(), pipeline_id); match page.hit_test(&point) { Some(node_address) => { - debug!("node address is {}", node_address.0); + debug!("node address is {:?}", node_address.0); let temp_node = node::from_untrusted_node_address( self.js_runtime.ptr, node_address).root(); - let maybe_node = match ElementCast::to_ref(temp_node.r()) { + let maybe_elem: Option<JSRef<Element>> = ElementCast::to_ref(temp_node.r()); + let maybe_node = match maybe_elem { Some(element) => Some(element), None => temp_node.r().ancestors().filter_map(ElementCast::to_ref).next(), }; match maybe_node { Some(el) => { - let node = NodeCast::from_ref(el); - debug!("clicked on {}", node.debug_str()); + let node: JSRef<Node> = NodeCast::from_ref(el); + debug!("clicked on {:?}", node.debug_str()); // Prevent click event if form control element is disabled. if node.click_event_filter_by_disabled_state() { return; } match *page.frame() { @@ -1308,7 +1317,7 @@ pub fn get_page(page: &Rc<Page>, pipeline_id: PipelineId) -> Rc<Page> { } //FIXME(seanmonstar): uplift to Hyper -#[deriving(Clone)] +#[derive(Clone)] struct LastModified(pub Tm); impl Header for LastModified { diff --git a/components/script/tests.rs b/components/script/tests.rs index 28710e23647..6b60f0ee534 100644 --- a/components/script/tests.rs +++ b/components/script/tests.rs @@ -35,14 +35,14 @@ macro_rules! sizeof_checker ( stringify!($t), old, new) } }); -) +); // Update the sizes here -sizeof_checker!(size_event_target, EventTarget, 48) -sizeof_checker!(size_node, Node, 288) -sizeof_checker!(size_element, Element, 432) -sizeof_checker!(size_htmlelement, HTMLElement, 464) -sizeof_checker!(size_div, HTMLDivElement, 464) -sizeof_checker!(size_span, HTMLSpanElement, 464) -sizeof_checker!(size_text, Text, 320) -sizeof_checker!(size_characterdata, CharacterData, 320) +sizeof_checker!(size_event_target, EventTarget, 48); +sizeof_checker!(size_node, Node, 288); +sizeof_checker!(size_element, Element, 432); +sizeof_checker!(size_htmlelement, HTMLElement, 464); +sizeof_checker!(size_div, HTMLDivElement, 464); +sizeof_checker!(size_span, HTMLSpanElement, 464); +sizeof_checker!(size_text, Text, 320); +sizeof_checker!(size_characterdata, CharacterData, 320); diff --git a/components/script/textinput.rs b/components/script/textinput.rs index 4c4226738cf..fa9ad4eacff 100644 --- a/components/script/textinput.rs +++ b/components/script/textinput.rs @@ -14,14 +14,14 @@ use std::cmp::{min, max}; use std::default::Default; use std::num::SignedInt; -#[deriving(Copy, PartialEq)] +#[derive(Copy, PartialEq)] enum Selection { Selected, NotSelected } #[jstraceable] -#[deriving(Copy)] +#[derive(Copy)] struct TextPoint { /// 0-based line number line: uint, @@ -59,14 +59,14 @@ impl Default for TextPoint { } /// Control whether this control should allow multiple lines. -#[deriving(PartialEq)] +#[derive(PartialEq)] pub enum Lines { Single, Multiple, } /// The direction in which to delete a character. -#[deriving(PartialEq)] +#[derive(PartialEq)] enum DeleteDir { Forward, Backward diff --git a/components/script/timers.rs b/components/script/timers.rs index ef86c8ccd13..bfcd76b95a4 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -21,15 +21,15 @@ use std::borrow::ToOwned; use std::cell::Cell; use std::cmp; use std::collections::HashMap; -use std::comm::{channel, Sender}; -use std::comm::Select; -use std::hash::{Hash, sip}; +use std::sync::mpsc::{channel, Sender}; +use std::sync::mpsc::Select; +use std::hash::{Hash, Hasher, Writer}; use std::io::timer::Timer; use std::time::duration::Duration; -#[deriving(PartialEq, Eq)] +#[derive(PartialEq, Eq)] #[jstraceable] -#[deriving(Copy)] +#[derive(Copy)] pub struct TimerId(i32); #[jstraceable] @@ -41,14 +41,14 @@ struct TimerHandle { } #[jstraceable] -#[deriving(Clone)] +#[derive(Clone)] pub enum TimerCallback { StringTimerCallback(DOMString), FunctionTimerCallback(Function) } -impl Hash for TimerId { - fn hash(&self, state: &mut sip::SipState) { +impl<H: Writer + Hasher> Hash<H> for TimerId { + fn hash(&self, state: &mut H) { let TimerId(id) = *self; id.hash(state); } @@ -56,7 +56,7 @@ impl Hash for TimerId { impl TimerHandle { fn cancel(&mut self) { - self.cancel_chan.as_ref().map(|chan| chan.send_opt(()).ok()); + self.cancel_chan.as_ref().map(|chan| chan.send(()).ok()); } } @@ -79,7 +79,7 @@ impl Drop for TimerManager { // Enum allowing more descriptive values for the is_interval field #[jstraceable] -#[deriving(PartialEq, Copy, Clone)] +#[derive(PartialEq, Copy, Clone)] pub enum IsInterval { Interval, NonInterval, @@ -91,7 +91,7 @@ pub enum IsInterval { // TODO: Handle rooting during fire_timer when movable GC is turned on #[jstraceable] #[privatize] -#[deriving(Clone)] +#[derive(Clone)] struct TimerData { is_interval: IsInterval, callback: TimerCallback, @@ -129,7 +129,7 @@ impl TimerManager { TimerSource::FromWindow(_) => "Window:SetTimeout", TimerSource::FromWorker => "Worker:SetTimeout", }.to_owned(); - spawn_named(spawn_name, proc() { + spawn_named(spawn_name, move || { let mut tm = tm; let duration = Duration::milliseconds(timeout as i64); let timeout_port = if is_interval == IsInterval::Interval { diff --git a/components/script_traits/Cargo.toml b/components/script_traits/Cargo.toml index b5ca1ca0389..d0075c2d08d 100644 --- a/components/script_traits/Cargo.toml +++ b/components/script_traits/Cargo.toml @@ -22,5 +22,5 @@ path = "../devtools_traits" [dependencies.geom] git = "https://github.com/servo/rust-geom" -[dependencies.url] -git = "https://github.com/servo/rust-url" +[dependencies] +url = "*"
\ No newline at end of file diff --git a/components/script_traits/lib.rs b/components/script_traits/lib.rs index be2de70719a..4a1e3d31294 100644 --- a/components/script_traits/lib.rs +++ b/components/script_traits/lib.rs @@ -2,6 +2,8 @@ * 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/. */ +#![feature(int_uint)] + #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] @@ -31,17 +33,17 @@ use servo_net::resource_task::ResourceTask; use servo_net::storage_task::StorageTask; use servo_util::smallvec::SmallVec1; use std::any::Any; +use std::sync::mpsc::{Sender, Receiver}; use geom::point::Point2D; use geom::rect::Rect; -use serialize::{Encodable, Encoder}; - /// The address of a node. Layout sends these back. They must be validated via /// `from_untrusted_node_address` before they can be used, because we do not trust layout. #[allow(raw_pointer_deriving)] -#[deriving(Copy, Clone)] +#[derive(Copy, Clone)] pub struct UntrustedNodeAddress(pub *const c_void); +unsafe impl Send for UntrustedNodeAddress {} pub struct NewLayoutInfo { pub old_pipeline_id: PipelineId, @@ -72,6 +74,9 @@ pub enum ConstellationControlMsg { GetTitle(PipelineId), } +unsafe impl Send for ConstellationControlMsg { +} + /// Events from the compositor that the script task needs to know about pub enum CompositorEvent { ResizeEvent(WindowSizeData), @@ -88,15 +93,9 @@ pub enum CompositorEvent { pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>)); /// Encapsulates external communication with the script task. -#[deriving(Clone)] +#[derive(Clone)] pub struct ScriptControlChan(pub Sender<ConstellationControlMsg>); -impl<S: Encoder<E>, E> Encodable<S, E> for ScriptControlChan { - fn encode(&self, _s: &mut S) -> Result<(), E> { - Ok(()) - } -} - pub trait ScriptTaskFactory { fn create<C>(_phantom: Option<&mut Self>, id: PipelineId, diff --git a/components/servo/.cargo/config b/components/servo/.cargo/config index 102a11443bb..6c935952e2c 100644 --- a/components/servo/.cargo/config +++ b/components/servo/.cargo/config @@ -1,10 +1,4 @@ -# FIXME: Remove this next rustup. This is a temporary -# hack to allow android cross compilation to work. When -# this is removed, the support/time submodule can also -# be removed! -paths = [ - "../../support/time" -] +paths = ["../../support/android-rs-glue"] [target.arm-linux-androideabi] linker = "../../support/android-rs-glue/apk-builder/target/apk-builder" diff --git a/components/servo/Cargo.lock b/components/servo/Cargo.lock index 166ab14a397..b93de4d340f 100644 --- a/components/servo/Cargo.lock +++ b/components/servo/Cargo.lock @@ -2,23 +2,33 @@ name = "servo" version = "0.0.1" dependencies = [ + "android_glue 0.0.1", "compositing 0.0.1", + "devtools 0.0.1", "gfx 0.0.1", "glfw_app 0.0.1", "glutin_app 0.0.1", "layout 0.0.1", "msg 0.0.1", "net 0.0.1", + "png 0.1.0 (git+https://github.com/servo/rust-png)", "script 0.0.1", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "android_glue" version = "0.0.1" -source = "git+https://github.com/servo/android-rs-glue?ref=servo#122bc28545b5e59a923c466a484c403fa691bd55" +dependencies = [ + "compile_msg 0.1.1 (git+https://github.com/huonw/compile_msg)", +] + +[[package]] +name = "android_glue" +version = "0.0.1" +source = "git+https://github.com/tomaka/android-rs-glue#8fc770e4c1412293e459bc12ca4fcf57780e2186" dependencies = [ "compile_msg 0.1.1 (git+https://github.com/huonw/compile_msg)", ] @@ -26,7 +36,7 @@ dependencies = [ [[package]] name = "azure" version = "0.1.0" -source = "git+https://github.com/servo/rust-azure#d0acabef6221e5fd6840254dc23f91c66b874629" +source = "git+https://github.com/servo/rust-azure#2cc22b161a93f4016457f680b3966d879606d06d" dependencies = [ "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", "core_graphics 0.1.0 (git+https://github.com/servo/rust-core-graphics)", @@ -34,7 +44,7 @@ dependencies = [ "egl 0.1.0 (git+https://github.com/servo/rust-egl)", "freetype 0.1.0 (git+https://github.com/servo/rust-freetype)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", - "skia-sys 0.0.20130412 (git+https://github.com/servo/skia?ref=upstream-2014-06-16)", + "skia-sys 0.0.20130412 (git+https://github.com/servo/skia?branch=upstream-2014-06-16)", "xlib 0.1.0 (git+https://github.com/servo/rust-xlib)", ] @@ -58,7 +68,7 @@ dependencies = [ [[package]] name = "cocoa" version = "0.1.1" -source = "git+https://github.com/servo/rust-cocoa#bf53a53ce306279fc1cae0d56fdd5e7216696420" +source = "git+https://github.com/servo/rust-cocoa#84a405ba9ff2a79d507dc6ee1ea3cf9bf48706d1" [[package]] name = "compile_msg" @@ -83,25 +93,26 @@ dependencies = [ "net 0.0.1", "png 0.1.0 (git+https://github.com/servo/rust-png)", "script_traits 0.0.1", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "cookie" -version = "0.1.0" -source = "git+https://github.com/alexcrichton/cookie-rs#8d1b4bb8d5ed06e58c162eb235a4ccd210b68108" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "openssl 0.2.4 (git+https://github.com/sfackler/rust-openssl)", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "openssl 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "core_foundation" version = "0.1.0" -source = "git+https://github.com/servo/rust-core-foundation#81db9ab15f67e16d7a3e9705a06cad65192014fd" +source = "git+https://github.com/servo/rust-core-foundation#ce3d852765827b64a0d5fb2aadd77da39665b0b0" [[package]] name = "core_graphics" @@ -114,7 +125,7 @@ dependencies = [ [[package]] name = "core_text" version = "0.1.0" -source = "git+https://github.com/servo/rust-core-text#cb369a26a0eb4e83c2128ceb3c685a191113417a" +source = "git+https://github.com/servo/rust-core-text#b5cb33905350e99b2a19f5a22f7b1efea7ad48c2" dependencies = [ "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", "core_graphics 0.1.0 (git+https://github.com/servo/rust-core-graphics)", @@ -122,12 +133,12 @@ dependencies = [ [[package]] name = "cssparser" -version = "0.1.1" -source = "git+https://github.com/servo/rust-cssparser#8d1b3e220e795f7baaa940919059d5f4ef4ec28c" +version = "0.2.0" +source = "git+https://github.com/servo/rust-cssparser#2a8c9f2c5f568495bae16f44b799be39b8efad39" dependencies = [ - "encoding 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "matches 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "text_writer 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)", + "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "text_writer 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -149,63 +160,63 @@ dependencies = [ [[package]] name = "egl" version = "0.1.0" -source = "git+https://github.com/servo/rust-egl#88f2a13812ddbce2bf2317221663a61c31b3e220" +source = "git+https://github.com/servo/rust-egl#cd74c82a8537090edb6c16478e2261db2a8c0b4f" [[package]] name = "encoding" -version = "0.2.6" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "encoding-index-japanese 1.0.20140915 (registry+https://github.com/rust-lang/crates.io-index)", - "encoding-index-korean 1.0.20140915 (registry+https://github.com/rust-lang/crates.io-index)", - "encoding-index-simpchinese 1.0.20140915 (registry+https://github.com/rust-lang/crates.io-index)", - "encoding-index-singlebyte 1.0.20140915 (registry+https://github.com/rust-lang/crates.io-index)", - "encoding-index-tradchinese 1.0.20140915 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding-index-japanese 1.20141219.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding-index-korean 1.20141219.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding-index-simpchinese 1.20141219.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding-index-singlebyte 1.20141219.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding-index-tradchinese 1.20141219.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "encoding-index-japanese" -version = "1.0.20140915" +version = "1.20141219.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "encoding_index_tests 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding_index_tests 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "encoding-index-korean" -version = "1.0.20140915" +version = "1.20141219.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "encoding_index_tests 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding_index_tests 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "encoding-index-simpchinese" -version = "1.0.20140915" +version = "1.20141219.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "encoding_index_tests 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding_index_tests 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "encoding-index-singlebyte" -version = "1.0.20140915" +version = "1.20141219.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "encoding_index_tests 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding_index_tests 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "encoding-index-tradchinese" -version = "1.0.20140915" +version = "1.20141219.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "encoding_index_tests 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding_index_tests 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "encoding_index_tests" -version = "0.1.0" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -233,7 +244,7 @@ dependencies = [ [[package]] name = "freetype" version = "0.1.0" -source = "git+https://github.com/servo/rust-freetype#e55b06110fb2d74a2db68ead740db7e98fb98060" +source = "git+https://github.com/servo/rust-freetype#ec0231343a3ad360d86846c12895a0a0cbb19f79" [[package]] name = "freetype-sys" @@ -242,18 +253,18 @@ source = "git+https://github.com/servo/libfreetype2#f5c49c0da1d5bc6b206c41763440 [[package]] name = "gcc" -version = "0.1.1" -source = "git+https://github.com/alexcrichton/gcc-rs#dfe97a119af4b2db53178eb8c3ca6be6589a152b" +version = "0.1.4" +source = "git+https://github.com/alexcrichton/gcc-rs#f5c52d956e0742a66e40c8301e634e136c3ae287" [[package]] name = "gcc" -version = "0.1.2" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "geom" version = "0.1.0" -source = "git+https://github.com/servo/rust-geom#05f2d5494355adc78ad7d17286912f0d128f503b" +source = "git+https://github.com/servo/rust-geom#a4a4a03aa024412bf3f4e093c0198b433c6ad63f" [[package]] name = "gfx" @@ -275,47 +286,66 @@ dependencies = [ "script_traits 0.0.1", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", "style 0.0.1", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "gl_common" -version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#b5e3f4f76c31bc1b459d5e4c10d879ffa4f67c6e" +version = "0.0.3" +source = "git+https://github.com/bjz/gl-rs.git#230e6c9ed611cddfcb6682dee9686471d54863d0" + +[[package]] +name = "gl_common" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "gl_generator" -version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#b5e3f4f76c31bc1b459d5e4c10d879ffa4f67c6e" +version = "0.0.12" +source = "git+https://github.com/bjz/gl-rs.git#230e6c9ed611cddfcb6682dee9686471d54863d0" +dependencies = [ + "gl_common 0.0.3 (git+https://github.com/bjz/gl-rs.git)", + "khronos_api 0.0.5 (git+https://github.com/bjz/gl-rs.git)", + "log 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "gl_generator" +version = "0.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "gl_common 0.0.1 (git+https://github.com/bjz/gl-rs.git)", - "khronos_api 0.0.2 (git+https://github.com/bjz/gl-rs.git)", - "xml-rs 0.1.3 (git+https://github.com/netvl/xml-rs)", + "gl_common 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "khronos_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "gleam" version = "0.0.1" -source = "git+https://github.com/servo/gleam#c54eb9ad6d4b62b7effbe9c79a1b3720845b45b4" +source = "git+https://github.com/servo/gleam#8a23e963c5b8e1a727a80fb009d71e2f9efb6a89" dependencies = [ - "gl_generator 0.0.1 (git+https://github.com/bjz/gl-rs.git)", + "gl_common 0.0.3 (git+https://github.com/bjz/gl-rs.git)", + "gl_generator 0.0.12 (git+https://github.com/bjz/gl-rs.git)", ] [[package]] name = "glfw" version = "0.0.1" -source = "git+https://github.com/servo/glfw-rs?ref=servo#b186cb444e349a36b992445dc5cb2c99d38f2a42" +source = "git+https://github.com/servo/glfw-rs?branch=servo#757b917511cd14821f3da114ad3110e377d7d858" dependencies = [ - "glfw-sys 3.0.4 (git+https://github.com/servo/glfw?ref=cargo-3.0.4)", - "semver 0.1.4 (git+https://github.com/rust-lang/semver)", + "glfw-sys 3.0.4 (git+https://github.com/servo/glfw?branch=cargo-3.0.4)", + "log 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "semver 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "glfw-sys" version = "3.0.4" -source = "git+https://github.com/servo/glfw?ref=cargo-3.0.4#765dace7e4125b87c764f5ac0e7a80eae5c550b2" +source = "git+https://github.com/servo/glfw?branch=cargo-3.0.4#765dace7e4125b87c764f5ac0e7a80eae5c550b2" [[package]] name = "glfw_app" @@ -325,24 +355,26 @@ dependencies = [ "compositing 0.0.1", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gleam 0.0.1 (git+https://github.com/servo/gleam)", - "glfw 0.0.1 (git+https://github.com/servo/glfw-rs?ref=servo)", + "glfw 0.0.1 (git+https://github.com/servo/glfw-rs?branch=servo)", "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "msg 0.0.1", - "time 0.1.0 (git+https://github.com/rust-lang/time)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "glutin" -version = "0.0.2" -source = "git+https://github.com/servo/glutin?ref=servo#ec6b4d0fff12ef607db422508ae005ba91406f5b" +version = "0.0.4-pre" +source = "git+https://github.com/tomaka/glutin#1d6b863cd454839b8e3cf1e296cbf8f31fb70029" dependencies = [ - "android_glue 0.0.1 (git+https://github.com/servo/android-rs-glue?ref=servo)", + "android_glue 0.0.1 (git+https://github.com/tomaka/android-rs-glue)", "cocoa 0.1.1 (git+https://github.com/servo/rust-cocoa)", + "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", "core_graphics 0.1.0 (git+https://github.com/servo/rust-core-graphics)", - "gl_common 0.0.1 (git+https://github.com/bjz/gl-rs.git)", - "gl_generator 0.0.1 (git+https://github.com/bjz/gl-rs.git)", - "winapi 0.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "gl_common 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gl_generator 0.0.12 (registry+https://github.com/rust-lang/crates.io-index)", + "khronos_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.0.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -351,21 +383,23 @@ version = "0.0.1" dependencies = [ "cgl 0.0.1 (git+https://github.com/servo/rust-cgl)", "compositing 0.0.1", + "egl 0.1.0 (git+https://github.com/servo/rust-egl)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gleam 0.0.1 (git+https://github.com/servo/gleam)", - "glutin 0.0.2 (git+https://github.com/servo/glutin?ref=servo)", + "glutin 0.0.4-pre (git+https://github.com/tomaka/glutin)", "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "msg 0.0.1", - "time 0.1.0 (git+https://github.com/rust-lang/time)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "glx" version = "0.0.1" -source = "git+https://github.com/servo/rust-glx#7126ffa09fcfcc9f85f1406f3b5db729f5fdb7c3" +source = "git+https://github.com/servo/rust-glx#f056a8998987f6f081f9ad7fa396beb1b2988c02" dependencies = [ - "gl_generator 0.0.1 (git+https://github.com/bjz/gl-rs.git)", + "gl_common 0.0.3 (git+https://github.com/bjz/gl-rs.git)", + "gl_generator 0.0.12 (git+https://github.com/bjz/gl-rs.git)", ] [[package]] @@ -376,33 +410,36 @@ source = "git+https://github.com/servo/rust-harfbuzz#59b5b18087418404d661784934c [[package]] name = "html5ever" version = "0.0.0" -source = "git+https://github.com/servo/html5ever#0abe5e30cc03f9e73bfd4fdc018192d149c21fb3" +source = "git+https://github.com/servo/html5ever#d35dfaaf0d85007057a299afc370d07e92538944" dependencies = [ "html5ever_macros 0.0.0 (git+https://github.com/servo/html5ever)", - "phf 0.0.1 (git+https://github.com/sfackler/rust-phf)", - "phf_mac 0.0.1 (git+https://github.com/sfackler/rust-phf)", + "phf 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_mac 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", - "time 0.1.0 (git+https://github.com/rust-lang/time)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "html5ever_macros" version = "0.0.0" -source = "git+https://github.com/servo/html5ever#0abe5e30cc03f9e73bfd4fdc018192d149c21fb3" +source = "git+https://github.com/servo/html5ever#d35dfaaf0d85007057a299afc370d07e92538944" [[package]] name = "hyper" -version = "0.0.1" -source = "git+https://github.com/servo/hyper?ref=servo#43becc919c24939b8b84fe541b0e0898a4827836" +version = "0.1.0" +source = "git+https://github.com/servo/hyper?branch=servo#248a6f29086baa841eb30c88540dca3196accae4" dependencies = [ - "cookie 0.1.0 (git+https://github.com/alexcrichton/cookie-rs)", - "mime 0.0.1 (git+https://github.com/hyperium/mime.rs)", - "mucell 0.1.2 (git+https://github.com/chris-morgan/mucell)", - "openssl 0.2.4 (git+https://github.com/sfackler/rust-openssl)", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "unsafe-any 0.1.1 (git+https://github.com/reem/rust-unsafe-any)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "cookie 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mucell 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "unicase 0.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unsafe-any 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -419,20 +456,25 @@ dependencies = [ [[package]] name = "js" version = "0.1.0" -source = "git+https://github.com/servo/rust-mozjs#5a69e377d6ab7ea8601f711443994f1c8172c7a8" +source = "git+https://github.com/servo/rust-mozjs#6cabb12f858f27d23fc3d2d9f0c334b80eb56573" dependencies = [ "mozjs-sys 0.0.0 (git+https://github.com/servo/mozjs)", ] [[package]] name = "khronos_api" -version = "0.0.2" -source = "git+https://github.com/bjz/gl-rs.git#b5e3f4f76c31bc1b459d5e4c10d879ffa4f67c6e" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "khronos_api" +version = "0.0.5" +source = "git+https://github.com/bjz/gl-rs.git#230e6c9ed611cddfcb6682dee9686471d54863d0" [[package]] name = "layers" version = "0.1.0" -source = "git+https://github.com/servo/rust-layers#f20270839f8658a2b19eae6fade9325efe5f4578" +source = "git+https://github.com/servo/rust-layers#84d6d2cd2d09489eb10af7167fa34c914a8bee71" dependencies = [ "azure 0.1.0 (git+https://github.com/servo/rust-azure)", "cgl 0.0.1 (git+https://github.com/servo/rust-cgl)", @@ -449,8 +491,9 @@ dependencies = [ name = "layout" version = "0.0.1" dependencies = [ - "cssparser 0.1.1 (git+https://github.com/servo/rust-cssparser)", - "encoding 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "canvas 0.0.1", + "cssparser 0.2.0 (git+https://github.com/servo/rust-cssparser)", + "encoding 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gfx 0.0.1", "layout_traits 0.0.1", @@ -461,7 +504,7 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "style 0.0.1", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] @@ -478,8 +521,8 @@ dependencies = [ [[package]] name = "lazy_static" -version = "0.1.0" -source = "git+https://github.com/Kimundi/lazy-static.rs#76f06e4fa7bc8c92f11d1def19bd4ddfd8017cd8" +version = "0.1.6" +source = "git+https://github.com/Kimundi/lazy-static.rs#31a7aa0176ecd70b4aab274a40d1e2cd78c1fbf8" [[package]] name = "libressl-pnacl-sys" @@ -490,14 +533,25 @@ dependencies = [ ] [[package]] +name = "log" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "regex 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] name = "matches" -version = "0.1.0" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "mime" -version = "0.0.1" -source = "git+https://github.com/hyperium/mime.rs#7898f1c29c7f5d35d0c3c7aed37ebcfc95a40873" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "log 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "mozjs-sys" @@ -511,44 +565,44 @@ dependencies = [ "azure 0.1.0 (git+https://github.com/servo/rust-azure)", "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", - "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", + "hyper 0.1.0 (git+https://github.com/servo/hyper?branch=servo)", "io_surface 0.1.0 (git+https://github.com/servo/rust-io-surface)", "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "style 0.0.1", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "mucell" -version = "0.1.2" -source = "git+https://github.com/chris-morgan/mucell#d198c6605b3e688719db168db0939051c803b1ea" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "net" version = "0.0.1" dependencies = [ "geom 0.1.0 (git+https://github.com/servo/rust-geom)", - "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", + "hyper 0.1.0 (git+https://github.com/servo/hyper?branch=servo)", "png 0.1.0 (git+https://github.com/servo/rust-png)", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "openssl" -version = "0.2.4" -source = "git+https://github.com/sfackler/rust-openssl#f299e336d06a85438c3ee90aa06235510f3f5dbe" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "openssl-sys 0.2.4 (git+https://github.com/sfackler/rust-openssl)", + "openssl-sys 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "openssl-sys" -version = "0.2.4" -source = "git+https://github.com/sfackler/rust-openssl#f299e336d06a85438c3ee90aa06235510f3f5dbe" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libressl-pnacl-sys 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "pkg-config 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -556,22 +610,26 @@ dependencies = [ [[package]] name = "phf" -version = "0.0.1" -source = "git+https://github.com/sfackler/rust-phf#6a7cc6eb9ec08b103b6b62fa39bdb3229f3cdbe4" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "xxhash 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "phf_mac" -version = "0.0.1" -source = "git+https://github.com/sfackler/rust-phf#6a7cc6eb9ec08b103b6b62fa39bdb3229f3cdbe4" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "time 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "xxhash 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] +name = "phf_shared" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] name = "pkg-config" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -588,29 +646,39 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "png" version = "0.1.0" -source = "git+https://github.com/servo/rust-png#cc1976df347bb21ac78c5b37e651b85878855991" +source = "git+https://github.com/servo/rust-png#2804379427ced963466d19132b816bb06a8a4006" dependencies = [ - "gcc 0.1.1 (git+https://github.com/alexcrichton/gcc-rs)", + "gcc 0.1.4 (git+https://github.com/alexcrichton/gcc-rs)", "png-sys 1.6.16 (git+https://github.com/servo/rust-png)", ] [[package]] name = "png-sys" version = "1.6.16" -source = "git+https://github.com/servo/rust-png#cc1976df347bb21ac78c5b37e651b85878855991" +source = "git+https://github.com/servo/rust-png#2804379427ced963466d19132b816bb06a8a4006" + +[[package]] +name = "regex" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rustc-serialize" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "script" version = "0.0.1" dependencies = [ "canvas 0.0.1", - "cssparser 0.1.1 (git+https://github.com/servo/rust-cssparser)", + "cssparser 0.2.0 (git+https://github.com/servo/rust-cssparser)", "devtools_traits 0.0.1", - "encoding 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "encoding 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gfx 0.0.1", "html5ever 0.0.0 (git+https://github.com/servo/html5ever)", - "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", + "hyper 0.1.0 (git+https://github.com/servo/hyper?branch=servo)", "js 0.1.0 (git+https://github.com/servo/rust-mozjs)", "msg 0.0.1", "net 0.0.1", @@ -619,10 +687,10 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "style 0.0.1", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", - "uuid 0.1.1 (git+https://github.com/rust-lang/uuid)", + "uuid 0.1.7 (git+https://github.com/rust-lang/uuid)", ] [[package]] @@ -633,19 +701,19 @@ dependencies = [ "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "msg 0.0.1", "net 0.0.1", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] [[package]] name = "semver" -version = "0.1.4" -source = "git+https://github.com/rust-lang/semver#58dc6b1999d345ca925a2f12a6a84676e823e179" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "skia-sys" version = "0.0.20130412" -source = "git+https://github.com/servo/skia?ref=upstream-2014-06-16#35649d0cddfd89c0bfee0ff558da7291e26d30c3" +source = "git+https://github.com/servo/skia?branch=upstream-2014-06-16#35649d0cddfd89c0bfee0ff558da7291e26d30c3" dependencies = [ "expat-sys 2.1.0 (git+https://github.com/servo/libexpat)", "freetype-sys 2.4.11 (git+https://github.com/servo/libfreetype2)", @@ -654,42 +722,42 @@ dependencies = [ [[package]] name = "stb_image" version = "0.1.0" -source = "git+https://github.com/servo/rust-stb-image#97d7e440e80e41a304647363c322eab68e3700aa" +source = "git+https://github.com/servo/rust-stb-image#2ba03a447b9ef101c25e07bb7f8876416e5fcd71" [[package]] name = "string_cache" version = "0.0.0" -source = "git+https://github.com/servo/string-cache#661c537b85f19ac81dfcd84e28557d480b6b7a9f" +source = "git+https://github.com/servo/string-cache#43a1e5d0d0f2a45e2b96160c8fbe6e1d9602cfa9" dependencies = [ - "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", - "phf 0.0.1 (git+https://github.com/sfackler/rust-phf)", - "phf_mac 0.0.1 (git+https://github.com/sfackler/rust-phf)", + "lazy_static 0.1.6 (git+https://github.com/Kimundi/lazy-static.rs)", + "phf 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_mac 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", - "xxhash 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "xxhash 0.0.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "string_cache_macros" version = "0.0.0" -source = "git+https://github.com/servo/string-cache#661c537b85f19ac81dfcd84e28557d480b6b7a9f" +source = "git+https://github.com/servo/string-cache#43a1e5d0d0f2a45e2b96160c8fbe6e1d9602cfa9" dependencies = [ - "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", + "lazy_static 0.1.6 (git+https://github.com/Kimundi/lazy-static.rs)", ] [[package]] name = "style" version = "0.0.1" dependencies = [ - "cssparser 0.1.1 (git+https://github.com/servo/rust-cssparser)", - "encoding 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.2.0 (git+https://github.com/servo/rust-cssparser)", + "encoding 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", - "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", - "matches 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 0.1.6 (git+https://github.com/Kimundi/lazy-static.rs)", + "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "plugins 0.0.1", "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", - "text_writer 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "text_writer 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] @@ -699,59 +767,63 @@ version = "0.0.1" [[package]] name = "text_writer" -version = "0.1.4" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "time" -version = "0.1.0" -source = "git+https://github.com/rust-lang/time#afab521f3b91658a3ba2d3e877b7e01699733bef" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "gcc 0.1.1 (git+https://github.com/alexcrichton/gcc-rs)", + "gcc 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "time" -version = "0.1.3" +name = "unicase" +version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gcc 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] name = "unsafe-any" -version = "0.1.1" -source = "git+https://github.com/reem/rust-unsafe-any#eb3fe87bea85f375b8fcefa0cdecfd131fae9624" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "url" -version = "0.2.4" -source = "git+https://github.com/servo/rust-url#79f8034a8e1815ffa1f49204572ddbf6eb747c75" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "util" version = "0.0.1" dependencies = [ - "cssparser 0.1.1 (git+https://github.com/servo/rust-cssparser)", + "cssparser 0.2.0 (git+https://github.com/servo/rust-cssparser)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "plugins 0.0.1", "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "task_info 0.0.1", - "text_writer 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.0 (git+https://github.com/rust-lang/time)", - "url 0.2.4 (git+https://github.com/servo/rust-url)", + "text_writer 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "uuid" -version = "0.1.1" -source = "git+https://github.com/rust-lang/uuid#fc793c974a25c126c5cf5daa3b18973512a7a6a0" +version = "0.1.7" +source = "git+https://github.com/rust-lang/uuid#3ea51ffa0682c820e8c8b505de078e3bc93e2cb3" +dependencies = [ + "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "winapi" -version = "0.0.2" +version = "0.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -761,11 +833,11 @@ source = "git+https://github.com/servo/rust-xlib#58ec3847b592aeabdcfeb6a2d02033d [[package]] name = "xml-rs" -version = "0.1.3" -source = "git+https://github.com/netvl/xml-rs#1a812d3ba720afd768bd75d29a5b5f10ddcdfbeb" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "xxhash" -version = "0.0.3" +version = "0.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/components/servo/Cargo.toml b/components/servo/Cargo.toml index 2b4b03f5fa5..a99ada57b67 100644 --- a/components/servo/Cargo.toml +++ b/components/servo/Cargo.toml @@ -21,6 +21,9 @@ name = "reftest" path = "../../tests/reftest.rs" harness = false +[dependencies.png] +git = "https://github.com/servo/rust-png" + [[test]] name = "contenttest" path = "../../tests/contenttest.rs" @@ -53,6 +56,9 @@ path = "../layout" [dependencies.gfx] path = "../gfx" +[dependencies.devtools] +path = "../devtools" + [dependencies.glfw_app] path = "../../ports/glfw" optional = true @@ -61,8 +67,10 @@ optional = true path = "../../ports/glutin" optional = true -[dependencies.url] -git = "https://github.com/servo/rust-url" +[dependencies.android_glue] +path = "../../support/android-rs-glue/glue" +optional = true -[dependencies.time] -git = "https://github.com/rust-lang/time" +[dependencies] +url = "*" +time = "*" diff --git a/components/servo/lib.rs b/components/servo/lib.rs index c64e7a10fc5..3cc121da0ff 100644 --- a/components/servo/lib.rs +++ b/components/servo/lib.rs @@ -2,26 +2,25 @@ * 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/. */ -#![feature(globs, macro_rules, phase, thread_local)] +#![feature(thread_local)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] -#[phase(plugin, link)] +#[macro_use] extern crate log; extern crate compositing; extern crate devtools; extern crate "net" as servo_net; extern crate "msg" as servo_msg; -#[phase(plugin, link)] +#[macro_use] extern crate "util" as servo_util; extern crate script; extern crate layout; extern crate gfx; extern crate libc; -extern crate rustrt; extern crate url; use compositing::CompositorEventListener; @@ -41,7 +40,7 @@ use servo_net::image_cache_task::ImageCacheTask; #[cfg(not(test))] use servo_net::resource_task::new_resource_task; #[cfg(not(test))] -use servo_net::storage_task::StorageTaskFactory; +use servo_net::storage_task::{StorageTaskFactory, StorageTask}; #[cfg(not(test))] use gfx::font_cache_task::FontCacheTask; #[cfg(not(test))] @@ -58,7 +57,9 @@ use std::os; #[cfg(not(test))] use std::rc::Rc; #[cfg(not(test))] -use std::task::TaskBuilder; +use std::sync::mpsc::channel; +#[cfg(not(test))] +use std::thread::Builder; pub struct Browser<Window> { compositor: Box<CompositorEventListener + 'static>, @@ -86,8 +87,8 @@ impl<Window> Browser<Window> where Window: WindowMethods + 'static { let (result_chan, result_port) = channel(); let compositor_proxy_for_constellation = compositor_proxy.clone_compositor_proxy(); - TaskBuilder::new() - .spawn(proc() { + Builder::new() + .spawn(move || { let opts = &opts_clone; // Create a Servo instance. let resource_task = new_resource_task(opts.user_agent.clone()); @@ -100,7 +101,7 @@ impl<Window> Browser<Window> where Window: WindowMethods + 'static { ImageCacheTask::new(resource_task.clone(), shared_task_pool) }; let font_cache_task = FontCacheTask::new(resource_task.clone()); - let storage_task = StorageTaskFactory::new(); + let storage_task: StorageTask = StorageTaskFactory::new(); let constellation_chan = Constellation::<layout::layout_task::LayoutTask, script::script_task::ScriptTask>::start( compositor_proxy_for_constellation, @@ -129,7 +130,7 @@ impl<Window> Browser<Window> where Window: WindowMethods + 'static { result_chan.send(constellation_chan); }); - let constellation_chan = result_port.recv(); + let constellation_chan = result_port.recv().unwrap(); debug!("preparing to enter main loop"); let compositor = CompositorTask::create(window, diff --git a/components/servo/main.rs b/components/servo/main.rs index f2fbf67dfb3..98463ee91a6 100644 --- a/components/servo/main.rs +++ b/components/servo/main.rs @@ -2,8 +2,6 @@ * 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/. */ -#![feature(phase)] - #![deny(unused_imports)] #![deny(unused_variables)] @@ -23,7 +21,7 @@ extern crate "glfw_app" as app; extern crate compositing; #[cfg(target_os="android")] -#[phase(plugin, link)] +#[macro_use] extern crate android_glue; #[cfg(target_os="android")] @@ -49,7 +47,7 @@ struct BrowserWrapper { } #[cfg(target_os="android")] -android_start!(main) +android_start!(main); #[cfg(target_os="android")] fn get_args() -> Vec<String> { @@ -65,29 +63,36 @@ fn get_args() -> Vec<String> { } #[cfg(target_os="android")] +struct FilePtr(*mut libc::types::common::c95::FILE); + +#[cfg(target_os="android")] +unsafe impl Send for FilePtr {} + +#[cfg(target_os="android")] fn redirect_output(file_no: c_int) { use libc::funcs::posix88::unistd::{pipe, dup2}; use libc::funcs::posix88::stdio::fdopen; - use libc::c_char; use libc::funcs::c95::stdio::fgets; + use servo_util::task::spawn_named; use std::mem; - use std::c_str::CString; + use std::ffi::CString; + use std::str::from_utf8; unsafe { - let mut pipes: [c_int, ..2] = [ 0, 0 ]; + let mut pipes: [c_int; 2] = [ 0, 0 ]; pipe(pipes.as_mut_ptr()); dup2(pipes[1], file_no); - let input_file = "r".with_c_str(|mode| { - fdopen(pipes[0], mode) - }); - spawn(proc() { + let mode = CString::from_slice("r".as_bytes()); + let input_file = FilePtr(fdopen(pipes[0], mode.as_ptr())); + spawn_named("android-logger".to_owned(), move || { loop { - let mut read_buffer: [c_char, ..1024] = mem::zeroed(); - fgets(read_buffer.as_mut_ptr(), read_buffer.len() as i32, input_file); - let cs = CString::new(read_buffer.as_ptr(), false); - match cs.as_str() { - Some(s) => android_glue::write_log(s), - None => {}, + let mut read_buffer: [u8; 1024] = mem::zeroed(); + let FilePtr(input_file) = input_file; + fgets(read_buffer.as_mut_ptr() as *mut i8, read_buffer.len() as i32, input_file); + let cs = CString::from_slice(&read_buffer); + match from_utf8(cs.as_bytes()) { + Ok(s) => android_glue::write_log(s), + _ => {} } } }); diff --git a/components/style/Cargo.toml b/components/style/Cargo.toml index 8b053ffae62..f5c8bae0939 100644 --- a/components/style/Cargo.toml +++ b/components/style/Cargo.toml @@ -18,9 +18,6 @@ path = "../util" [dependencies.geom] git = "https://github.com/servo/rust-geom" -[dependencies.url] -git = "https://github.com/servo/rust-url" - [dependencies.cssparser] git = "https://github.com/servo/rust-cssparser" @@ -37,3 +34,4 @@ git = "https://github.com/servo/string-cache" text_writer = "0.1.1" encoding = "0.2" matches = "0.1" +url = "*"
\ No newline at end of file diff --git a/components/style/font_face.rs b/components/style/font_face.rs index e18bcb32f01..d4d18f7960b 100644 --- a/components/style/font_face.rs +++ b/components/style/font_face.rs @@ -12,15 +12,15 @@ use url::{Url, UrlParser}; use parser::ParserContext; -pub fn iter_font_face_rules_inner(rules: &[CSSRule], device: &Device, - callback: |family: &str, source: &Source|) { +pub fn iter_font_face_rules_inner<F>(rules: &[CSSRule], device: &Device, + callback: &F) where F: Fn(&str, &Source) { for rule in rules.iter() { match *rule { CSSRule::Style(..) | CSSRule::Charset(..) | CSSRule::Namespace(..) => {}, CSSRule::Media(ref rule) => if rule.media_queries.evaluate(device) { - iter_font_face_rules_inner(rule.rules.as_slice(), device, |f, s| callback(f, s)) + iter_font_face_rules_inner(rule.rules.as_slice(), device, callback) }, CSSRule::FontFace(ref rule) => { for source in rule.sources.iter() { @@ -31,19 +31,19 @@ pub fn iter_font_face_rules_inner(rules: &[CSSRule], device: &Device, } } -#[deriving(Clone, Show, PartialEq, Eq)] +#[derive(Clone, Show, PartialEq, Eq)] pub enum Source { Url(UrlSource), Local(String), } -#[deriving(Clone, Show, PartialEq, Eq)] +#[derive(Clone, Show, PartialEq, Eq)] pub struct UrlSource { pub url: Url, pub format_hints: Vec<String>, } -#[deriving(Show, PartialEq, Eq)] +#[derive(Show, PartialEq, Eq)] pub struct FontFaceRule { pub family: String, pub sources: Vec<Source>, @@ -82,7 +82,7 @@ impl<'a, 'b> AtRuleParser<(), ()> for FontFaceRuleParser<'a, 'b> {} impl<'a, 'b> DeclarationParser<()> for FontFaceRuleParser<'a, 'b> { fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<(), ()> { - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "font-family" => { self.family = Some(try!(parse_one_non_generic_family_name(input))); Ok(()) diff --git a/components/style/legacy.rs b/components/style/legacy.rs index 0316df68185..95a0f7b6db6 100644 --- a/components/style/legacy.rs +++ b/components/style/legacy.rs @@ -18,14 +18,14 @@ use servo_util::smallvec::VecLike; use servo_util::str::LengthOrPercentageOrAuto; /// Legacy presentational attributes that take a length as defined in HTML5 § 2.4.4.4. -#[deriving(Copy, PartialEq, Eq)] +#[derive(Copy, PartialEq, Eq)] pub enum LengthAttribute { /// `<td width>` Width, } /// Legacy presentational attributes that take an integer as defined in HTML5 § 2.4.4.2. -#[deriving(Copy, PartialEq, Eq)] +#[derive(Copy, PartialEq, Eq)] pub enum IntegerAttribute { /// `<input size>` Size, @@ -34,7 +34,7 @@ pub enum IntegerAttribute { } /// Legacy presentational attributes that take a nonnegative integer as defined in HTML5 § 2.4.4.2. -#[deriving(Copy, PartialEq, Eq)] +#[derive(Copy, PartialEq, Eq)] pub enum UnsignedIntegerAttribute { /// `<td border>` Border, @@ -43,7 +43,7 @@ pub enum UnsignedIntegerAttribute { } /// Legacy presentational attributes that take a simple color as defined in HTML5 § 2.4.6. -#[deriving(Copy, PartialEq, Eq)] +#[derive(Copy, PartialEq, Eq)] pub enum SimpleColorAttribute { /// `<body bgcolor>` BgColor, diff --git a/components/style/lib.rs b/components/style/lib.rs index 5359d5617bc..7a0ffa365d1 100644 --- a/components/style/lib.rs +++ b/components/style/lib.rs @@ -2,15 +2,17 @@ * 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/. */ -#![feature(globs, macro_rules)] +#![feature(plugin)] +#![feature(int_uint)] +#![feature(box_syntax)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] +#![allow(unstable)] -#![feature(phase)] -#[phase(plugin, link)] extern crate log; -#[phase(plugin)] extern crate string_cache_macros; +#[macro_use] extern crate log; +#[no_link] #[macro_use] #[plugin] extern crate string_cache_macros; extern crate collections; extern crate geom; @@ -18,22 +20,16 @@ extern crate serialize; extern crate text_writer; extern crate url; -#[phase(plugin, link)] +#[macro_use] extern crate cssparser; -#[phase(plugin)] +#[macro_use] extern crate matches; extern crate encoding; extern crate string_cache; -#[phase(plugin)] -extern crate string_cache_macros; - -#[phase(plugin)] -extern crate plugins; - -#[phase(plugin)] +#[macro_use] extern crate lazy_static; extern crate "util" as servo_util; @@ -70,7 +66,7 @@ pub mod stylesheets; pub mod parser; pub mod selectors; pub mod selector_matching; -pub mod values; +#[macro_use] pub mod values; pub mod properties; pub mod namespaces; pub mod node; diff --git a/components/style/media_queries.rs b/components/style/media_queries.rs index f74c4a31ba5..324ac1a8ee0 100644 --- a/components/style/media_queries.rs +++ b/components/style/media_queries.rs @@ -11,12 +11,12 @@ use servo_util::geometry::{Au, ViewportPx}; use values::{computed, specified}; -#[deriving(Show, PartialEq)] +#[derive(Show, PartialEq)] pub struct MediaQueryList { media_queries: Vec<MediaQuery> } -#[deriving(PartialEq, Eq, Copy, Show)] +#[derive(PartialEq, Eq, Copy, Show)] pub enum Range<T> { Min(T), Max(T), @@ -33,18 +33,18 @@ impl<T: Ord> Range<T> { } } -#[deriving(PartialEq, Eq, Copy, Show)] +#[derive(PartialEq, Eq, Copy, Show)] pub enum Expression { Width(Range<Au>), } -#[deriving(PartialEq, Eq, Copy, Show)] +#[derive(PartialEq, Eq, Copy, Show)] pub enum Qualifier { Only, Not, } -#[deriving(Show, PartialEq)] +#[derive(Show, PartialEq)] pub struct MediaQuery { qualifier: Option<Qualifier>, media_type: MediaQueryType, @@ -62,13 +62,13 @@ impl MediaQuery { } } -#[deriving(PartialEq, Eq, Copy, Show)] +#[derive(PartialEq, Eq, Copy, Show)] pub enum MediaQueryType { All, // Always true MediaType(MediaType), } -#[deriving(PartialEq, Eq, Copy, Show)] +#[derive(PartialEq, Eq, Copy, Show)] pub enum MediaType { Screen, Print, @@ -76,7 +76,7 @@ pub enum MediaType { } #[allow(missing_copy_implementations)] -#[deriving(Show)] +#[derive(Show)] pub struct Device { pub media_type: MediaType, pub viewport_size: TypedSize2D<ViewportPx, f32>, @@ -109,7 +109,7 @@ impl Expression { let name = try!(input.expect_ident()); try!(input.expect_colon()); // TODO: Handle other media features - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "min-width" => { Ok(Expression::Width(Range::Min(try!(parse_non_negative_length(input))))) }, @@ -136,7 +136,7 @@ impl MediaQuery { let media_type; if let Ok(ident) = input.try(|input| input.expect_ident()) { - media_type = match_ignore_ascii_case! { ident: + media_type = match_ignore_ascii_case! { ident, "screen" => MediaQueryType::MediaType(MediaType::Screen), "print" => MediaQueryType::MediaType(MediaType::Print), "all" => MediaQueryType::All @@ -222,7 +222,7 @@ mod tests { use url::Url; use std::borrow::ToOwned; - fn test_media_rule(css: &str, callback: |&MediaQueryList, &str|) { + fn test_media_rule<F>(css: &str, callback: F) where F: Fn(&MediaQueryList, &str) { let url = Url::parse("http://localhost").unwrap(); let stylesheet = Stylesheet::from_str(css, url, Origin::Author); let mut rule_count: int = 0; diff --git a/components/style/namespaces.rs b/components/style/namespaces.rs index 3d3be8403b6..53b6467db9c 100644 --- a/components/style/namespaces.rs +++ b/components/style/namespaces.rs @@ -8,7 +8,7 @@ use string_cache::{Atom, Namespace}; use parser::ParserContext; -#[deriving(Clone)] +#[derive(Clone)] pub struct NamespaceMap { pub default: Option<Namespace>, pub prefix_map: HashMap<String, Namespace>, diff --git a/components/style/node.rs b/components/style/node.rs index 48afb072c43..8bf26b932b3 100644 --- a/components/style/node.rs +++ b/components/style/node.rs @@ -20,7 +20,7 @@ pub trait TNode<'a, E: TElement<'a>> : Clone + Copy { fn is_document(self) -> bool; fn is_element(self) -> bool; fn as_element(self) -> E; - fn match_attr(self, attr: &AttrSelector, test: |&str| -> bool) -> bool; + fn match_attr<F>(self, attr: &AttrSelector, test: F) -> bool where F: Fn(&str) -> bool; fn is_html_element_in_html_document(self) -> bool; fn has_changed(self) -> bool; @@ -55,7 +55,7 @@ pub trait TElement<'a> : Copy { // really messy, since there is a `JSRef` and a `RefCell` involved. Maybe // in the future when we have associated types and/or a more convenient // JS GC story... --pcwalton - fn each_class(self, callback: |&Atom|); + fn each_class<F>(self, callback: F) where F: FnMut(&Atom); } pub trait TElementAttributes : Copy { diff --git a/components/style/properties/mod.rs.mako b/components/style/properties/mod.rs.mako index 77d60cf8516..c4833972501 100644 --- a/components/style/properties/mod.rs.mako +++ b/components/style/properties/mod.rs.mako @@ -361,7 +361,7 @@ pub mod longhands { pub mod computed_value { use std::fmt; - #[deriving(PartialEq, Clone, Eq, Copy)] + #[derive(PartialEq, Clone, Eq, Copy)] pub enum T { Auto, Number(i32), @@ -451,7 +451,7 @@ pub mod longhands { <%self:longhand name="line-height"> use std::fmt; use values::CSSFloat; - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum SpecifiedValue { Normal, Length(specified::Length), @@ -462,7 +462,7 @@ pub mod longhands { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &SpecifiedValue::Normal => write!(f, "normal"), - &SpecifiedValue::Length(length) => write!(f, "{}", length), + &SpecifiedValue::Length(length) => write!(f, "{:?}", length), &SpecifiedValue::Number(number) => write!(f, "{}", number), &SpecifiedValue::Percentage(number) => write!(f, "{}%", number * 100.), } @@ -493,7 +493,7 @@ pub mod longhands { use values::CSSFloat; use servo_util::geometry::Au; use std::fmt; - #[deriving(PartialEq, Copy, Clone)] + #[derive(PartialEq, Copy, Clone)] pub enum T { Normal, Length(Au), @@ -503,7 +503,7 @@ pub mod longhands { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &T::Normal => write!(f, "normal"), - &T::Length(length) => write!(f, "{}%", length), + &T::Length(length) => write!(f, "{:?}%", length), &T::Number(number) => write!(f, "{}", number), } } @@ -535,7 +535,7 @@ pub mod longhands { <% vertical_align_keywords = ( "baseline sub super top text-top middle bottom text-bottom".split()) %> #[allow(non_camel_case_types)] - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum SpecifiedValue { % for keyword in vertical_align_keywords: ${to_rust_ident(keyword)}, @@ -548,7 +548,7 @@ pub mod longhands { % for keyword in vertical_align_keywords: &SpecifiedValue::${to_rust_ident(keyword)} => write!(f, "${keyword}"), % endfor - &SpecifiedValue::LengthOrPercentage(lop) => write!(f, "{}", lop), + &SpecifiedValue::LengthOrPercentage(lop) => write!(f, "{:?}", lop), } } } @@ -558,7 +558,7 @@ pub mod longhands { input.try(specified::LengthOrPercentage::parse_non_negative) .map(SpecifiedValue::LengthOrPercentage) .or_else(|()| { - match_ignore_ascii_case! { try!(input.expect_ident()): + match_ignore_ascii_case! { try!(input.expect_ident()), % for keyword in vertical_align_keywords[:-1]: "${keyword}" => Ok(SpecifiedValue::${to_rust_ident(keyword)}), % endfor @@ -576,7 +576,7 @@ pub mod longhands { use servo_util::geometry::Au; use std::fmt; #[allow(non_camel_case_types)] - #[deriving(PartialEq, Copy, Clone)] + #[derive(PartialEq, Copy, Clone)] pub enum T { % for keyword in vertical_align_keywords: ${to_rust_ident(keyword)}, @@ -590,7 +590,7 @@ pub mod longhands { % for keyword in vertical_align_keywords: &T::${to_rust_ident(keyword)} => write!(f, "${keyword}"), % endfor - &T::Length(length) => write!(f, "{}", length), + &T::Length(length) => write!(f, "{:?}", length), &T::Percentage(number) => write!(f, "{}%", number), } } @@ -642,7 +642,7 @@ pub mod longhands { use cssparser::Token; pub mod computed_value { use std::fmt; - #[deriving(PartialEq, Eq, Clone)] + #[derive(PartialEq, Eq, Clone)] pub enum ContentItem { StringContent(String), } @@ -654,7 +654,7 @@ pub mod longhands { } } #[allow(non_camel_case_types)] - #[deriving(PartialEq, Eq, Clone)] + #[derive(PartialEq, Eq, Clone)] pub enum T { normal, none, @@ -667,7 +667,7 @@ pub mod longhands { &T::none => write!(f, "none"), &T::Content(ref content) => { for c in content.iter() { - let _ = write!(f, "{}", c); + let _ = write!(f, "{:?}", c); } Ok(()) } @@ -781,26 +781,26 @@ pub mod longhands { use values::computed::LengthOrPercentage; use std::fmt; - #[deriving(PartialEq, Copy, Clone)] + #[derive(PartialEq, Copy, Clone)] pub struct T { pub horizontal: LengthOrPercentage, pub vertical: LengthOrPercentage, } impl fmt::Show for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{} {}", self.horizontal, self.vertical) + write!(f, "{:?} {:?}", self.horizontal, self.vertical) } } } - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub struct SpecifiedValue { pub horizontal: specified::LengthOrPercentage, pub vertical: specified::LengthOrPercentage, } impl fmt::Show for SpecifiedValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{} {}", self.horizontal, self.vertical) + write!(f, "{:?} {:?}", self.horizontal, self.vertical) } } @@ -923,7 +923,7 @@ pub mod longhands { use self::computed_value::FontFamily; pub mod computed_value { use std::fmt; - #[deriving(PartialEq, Eq, Clone)] + #[derive(PartialEq, Eq, Clone)] pub enum FontFamily { FamilyName(String), // Generic @@ -974,7 +974,7 @@ pub mod longhands { return Ok(FontFamily::FamilyName(value.into_owned())) } let first_ident = try!(input.expect_ident()); -// match_ignore_ascii_case! { first_ident: +// match_ignore_ascii_case! { first_ident, // "serif" => return Ok(Serif), // "sans-serif" => return Ok(SansSerif), // "cursive" => return Ok(Cursive), @@ -997,7 +997,7 @@ pub mod longhands { <%self:longhand name="font-weight"> use std::fmt; - #[deriving(Clone, PartialEq, Eq, Copy)] + #[derive(Clone, PartialEq, Eq, Copy)] pub enum SpecifiedValue { Bolder, Lighter, @@ -1019,7 +1019,7 @@ pub mod longhands { /// normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { input.try(|input| { - match_ignore_ascii_case! { try!(input.expect_ident()): + match_ignore_ascii_case! { try!(input.expect_ident()), "bold" => Ok(SpecifiedValue::Weight700), "normal" => Ok(SpecifiedValue::Weight400), "bolder" => Ok(SpecifiedValue::Bolder), @@ -1043,7 +1043,7 @@ pub mod longhands { } pub mod computed_value { use std::fmt; - #[deriving(PartialEq, Eq, Copy, Clone)] + #[derive(PartialEq, Eq, Copy, Clone)] pub enum T { % for weight in range(100, 901, 100): Weight${weight}, @@ -1130,7 +1130,7 @@ pub mod longhands { specified::LengthOrPercentage::Percentage(value) => specified::Length::Em(value) }) .or_else(|()| { - match_ignore_ascii_case! { try!(input.expect_ident()): + match_ignore_ascii_case! { try!(input.expect_ident()), "xx-small" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 3 / 5)), "x-small" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 3 / 4)), "small" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 8 / 9)), @@ -1218,7 +1218,7 @@ pub mod longhands { <%self:longhand name="text-decoration"> pub use super::computed_as_specified as to_computed_value; use std::fmt; - #[deriving(PartialEq, Eq, Copy, Clone)] + #[derive(PartialEq, Eq, Copy, Clone)] pub struct SpecifiedValue { pub underline: bool, pub overline: bool, @@ -1270,7 +1270,7 @@ pub mod longhands { let mut blink = false; let mut empty = true; loop { - match_ignore_ascii_case! { try!(input.expect_ident()): + match_ignore_ascii_case! { try!(input.expect_ident()), "underline" => if result.underline { return Err(()) } else { empty = false; result.underline = true }, "overline" => if result.overline { return Err(()) } @@ -1279,7 +1279,7 @@ pub mod longhands { else { empty = false; result.line_through = true }, "blink" => if blink { return Err(()) } else { empty = false; blink = true } - _ => break, + _ => break } } if !empty { Ok(result) } else { Err(()) } @@ -1293,7 +1293,7 @@ pub mod longhands { use cssparser::RGBA; pub use super::computed_as_specified as to_computed_value; - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub struct SpecifiedValue { pub underline: Option<RGBA>, pub overline: Option<RGBA>, @@ -1411,7 +1411,7 @@ pub mod longhands { pub mod computed_value { use servo_util::cursor::Cursor; - #[deriving(Clone, PartialEq, Eq, Copy, Show)] + #[derive(Clone, PartialEq, Eq, Copy, Show)] pub enum T { AutoCursor, SpecifiedCursor(Cursor), @@ -1474,7 +1474,7 @@ pub mod longhands { pub type SpecifiedValue = Vec<SpecifiedBoxShadow>; - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub struct SpecifiedBoxShadow { pub offset_x: specified::Length, pub offset_y: specified::Length, @@ -1489,10 +1489,10 @@ pub mod longhands { if self.inset { let _ = write!(f, "inset "); } - let _ = write!(f, "{} {} {} {}", self.offset_x, self.offset_y, + let _ = write!(f, "{:?} {:?} {:?} {:?}", self.offset_x, self.offset_y, self.blur_radius, self.spread_radius); if let Some(ref color) = self.color { - let _ = write!(f, "{}", color); + let _ = write!(f, "{:?}", color); } Ok(()) } @@ -1505,7 +1505,7 @@ pub mod longhands { pub type T = Vec<BoxShadow>; - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub struct BoxShadow { pub offset_x: Au, pub offset_y: Au, @@ -1520,7 +1520,7 @@ pub mod longhands { if self.inset { let _ = write!(f, "inset "); } - let _ = write!(f, "{} {} {} {} {}", self.offset_x, self.offset_y, + let _ = write!(f, "{:?} {:?} {:?} {:?} {:?}", self.offset_x, self.offset_y, self.blur_radius, self.spread_radius, self.color); Ok(()) } @@ -1561,7 +1561,7 @@ pub mod longhands { pub fn parse_one_box_shadow(input: &mut Parser) -> Result<SpecifiedBoxShadow, ()> { use servo_util::geometry::Au; - let mut lengths = [specified::Length::Au(Au(0)), ..4]; + let mut lengths = [specified::Length::Au(Au(0)); 4]; let mut lengths_parsed = false; let mut color = None; let mut inset = false; @@ -1626,7 +1626,7 @@ pub mod longhands { pub mod computed_value { use servo_util::geometry::Au; - #[deriving(Clone, PartialEq, Eq, Copy, Show)] + #[derive(Clone, PartialEq, Eq, Copy, Show)] pub struct ClipRect { pub top: Au, pub right: Option<Au>, @@ -1637,7 +1637,7 @@ pub mod longhands { pub type T = Option<ClipRect>; } - #[deriving(Clone, Show, PartialEq, Copy)] + #[derive(Clone, Show, PartialEq, Copy)] pub struct SpecifiedClipRect { pub top: specified::Length, pub right: Option<specified::Length>, @@ -1706,7 +1706,7 @@ pub mod longhands { use values::CSSFloat; // TODO(pcwalton): `blur`, `drop-shadow` - #[deriving(Clone, PartialEq, Show)] + #[derive(Clone, PartialEq, Show)] pub enum Filter { Brightness(CSSFloat), Contrast(CSSFloat), @@ -1718,7 +1718,7 @@ pub mod longhands { Sepia(CSSFloat), } - #[deriving(Clone, PartialEq, Show)] + #[derive(Clone, PartialEq, Show)] pub struct T { pub filters: Vec<Filter>, } @@ -1768,7 +1768,7 @@ pub mod longhands { loop { if let Ok(function_name) = input.try(|input| input.expect_function()) { filters.push(try!(input.parse_nested_block(|input| { - match_ignore_ascii_case! { function_name: + match_ignore_ascii_case! { function_name, "brightness" => parse_factor(input).map(Filter::Brightness), "contrast" => parse_factor(input).map(Filter::Contrast), "grayscale" => parse_factor(input).map(Filter::Grayscale), @@ -2031,9 +2031,9 @@ pub mod shorthands { let _ignored = context; fn parse_one_set_of_border_radii(mut input: &mut Parser) - -> Result<[LengthOrPercentage, ..4], ()> { + -> Result<[LengthOrPercentage; 4], ()> { let mut count = 0; - let mut values = [LengthOrPercentage::Length(Length::Au(Au(0))), ..4]; + let mut values = [LengthOrPercentage::Length(Length::Au(Au(0))); 4]; while count < 4 { if let Ok(value) = input.try(LengthOrPercentage::parse) { values[count] = value; @@ -2272,7 +2272,7 @@ mod property_bit_field { use std::mem; pub struct PropertyBitField { - storage: [uint, ..(${len(LONGHANDS)} - 1 + uint::BITS) / uint::BITS] + storage: [uint; (${len(LONGHANDS)} - 1 + uint::BITS) / uint::BITS] } impl PropertyBitField { @@ -2309,7 +2309,7 @@ mod property_bit_field { /// Declarations are stored in reverse order. /// Overridden declarations are skipped. -#[deriving(Show, PartialEq)] +#[derive(Show, PartialEq)] pub struct PropertyDeclarationBlock { pub important: Arc<Vec<PropertyDeclaration>>, pub normal: Arc<Vec<PropertyDeclaration>>, @@ -2399,7 +2399,7 @@ fn deduplicate_property_declarations(declarations: Vec<PropertyDeclaration>) } -#[deriving(Copy, PartialEq, Eq, Show)] +#[derive(Copy, PartialEq, Eq, Show)] pub enum CSSWideKeyword { InitialKeyword, InheritKeyword, @@ -2408,7 +2408,7 @@ pub enum CSSWideKeyword { impl CSSWideKeyword { pub fn parse(input: &mut Parser) -> Result<CSSWideKeyword, ()> { - match_ignore_ascii_case! { try!(input.expect_ident()): + match_ignore_ascii_case! { try!(input.expect_ident()), "initial" => Ok(CSSWideKeyword::InitialKeyword), "inherit" => Ok(CSSWideKeyword::InheritKeyword), "unset" => Ok(CSSWideKeyword::UnsetKeyword) @@ -2418,7 +2418,7 @@ impl CSSWideKeyword { } -#[deriving(Clone, PartialEq, Eq, Copy, Show)] +#[derive(Clone, PartialEq, Eq, Copy, Show)] pub enum DeclaredValue<T> { SpecifiedValue(T), Initial, @@ -2431,14 +2431,14 @@ pub enum DeclaredValue<T> { impl<T: Show> DeclaredValue<T> { pub fn specified_value(&self) -> Option<String> { match self { - &DeclaredValue::SpecifiedValue(ref inner) => Some(format!("{}", inner)), + &DeclaredValue::SpecifiedValue(ref inner) => Some(format!("{:?}", inner)), &DeclaredValue::Initial => None, &DeclaredValue::Inherit => Some("inherit".to_owned()), } } } -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub enum PropertyDeclaration { % for property in LONGHANDS: ${property.camel_case}(DeclaredValue<longhands::${property.ident}::SpecifiedValue>), @@ -2446,7 +2446,7 @@ pub enum PropertyDeclaration { } -#[deriving(Eq, PartialEq, Copy)] +#[derive(Eq, PartialEq, Copy)] pub enum PropertyDeclarationParseResult { UnknownProperty, ExperimentalProperty, @@ -2472,15 +2472,15 @@ impl PropertyDeclaration { % if property.derived_from is None: &PropertyDeclaration::${property.camel_case}(ref value) => value.specified_value() - .unwrap_or_else(|| format!("{}", longhands::${property.ident}::get_initial_value())), + .unwrap_or_else(|| format!("{:?}", longhands::${property.ident}::get_initial_value())), % endif % endfor - decl => panic!("unsupported property declaration: {}", decl.name()), + decl => panic!("unsupported property declaration: {:?}", decl.name()), } } pub fn matches(&self, name: &str) -> bool { - let name_lower = name.as_slice().to_ascii_lower(); + let name_lower = name.as_slice().to_ascii_lowercase(); match (self, name_lower.as_slice()) { % for property in LONGHANDS: % if property.derived_from is None: @@ -2493,7 +2493,7 @@ impl PropertyDeclaration { pub fn parse(name: &str, context: &ParserContext, input: &mut Parser, result_list: &mut Vec<PropertyDeclaration>) -> PropertyDeclarationParseResult { - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, % for property in LONGHANDS: % if property.derived_from is None: "${property.name}" => { @@ -2579,7 +2579,7 @@ pub mod style_structs { % for style_struct in STYLE_STRUCTS: #[allow(missing_copy_implementations)] - #[deriving(PartialEq, Clone)] + #[derive(PartialEq, Clone)] pub struct ${style_struct.name} { % for longhand in style_struct.longhands: pub ${longhand.ident}: longhands::${longhand.ident}::computed_value::T, @@ -2588,7 +2588,7 @@ pub mod style_structs { % endfor } -#[deriving(Clone)] +#[derive(Clone)] pub struct ComputedValues { % for style_struct in STYLE_STRUCTS: ${style_struct.ident}: Arc<style_structs::${style_struct.name}>, @@ -2918,7 +2918,7 @@ pub fn cascade(applicable_declarations: &[DeclarationBlock], DeclaredValue::Inherit => inherited_style.$style_struct_getter().$property.clone(), } }; - ) + ); // Initialize `context` // Declarations blocks are already stored in increasing precedence order. @@ -3136,9 +3136,9 @@ pub fn is_supported_property(property: &str) -> bool { } #[macro_export] -macro_rules! css_properties_accessors( - ($macro: ident) => ( - $macro!( +macro_rules! css_properties_accessors { + ($macro_name: ident) => { + $macro_name! { % for property in SHORTHANDS + LONGHANDS: ## Servo internal CSS properties are not accessible. ## FIXME: Add BinaryName WebIDL annotation (#4435). @@ -3150,9 +3150,9 @@ macro_rules! css_properties_accessors( % endif % endif % endfor - ) - ) -) + } + } +} pub fn longhands_from_shorthand(shorthand: &str) -> Option<Vec<String>> { match shorthand { diff --git a/components/style/selector_matching.rs b/components/style/selector_matching.rs index c617b58e7f2..1f5688ee140 100644 --- a/components/style/selector_matching.rs +++ b/components/style/selector_matching.rs @@ -3,6 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::ascii::AsciiExt; +use std::cmp::Ordering; use std::collections::HashMap; use std::hash::Hash; use std::sync::Arc; @@ -183,14 +184,14 @@ impl SelectorMap { match SelectorMap::get_id_name(&rule) { Some(id_name) => { - self.id_hash.find_push(id_name, rule); + find_push(&mut self.id_hash, id_name, rule); return; } None => {} } match SelectorMap::get_class_name(&rule) { Some(class_name) => { - self.class_hash.find_push(class_name, rule); + find_push(&mut self.class_hash, class_name, rule); return; } None => {} @@ -198,8 +199,8 @@ impl SelectorMap { match SelectorMap::get_local_name(&rule) { Some(LocalName { name, lower_name }) => { - self.local_name_hash.find_push(name, rule.clone()); - self.lower_local_name_hash.find_push(lower_name, rule); + find_push(&mut self.local_name_hash, name, rule.clone()); + find_push(&mut self.lower_local_name_hash, lower_name, rule); return; } None => {} @@ -294,7 +295,7 @@ impl Stylist { for &filename in ["user-agent.css", "servo.css", "presentational-hints.css"].iter() { let ua_stylesheet = Stylesheet::from_bytes( read_resource_file(&[filename]).unwrap().as_slice(), - Url::parse(format!("chrome:///{}", filename).as_slice()).unwrap(), + Url::parse(format!("chrome:///{:?}", filename).as_slice()).unwrap(), None, None, Origin::UserAgent); @@ -512,7 +513,7 @@ impl PerPseudoElementSelectorMap { } } -#[deriving(Clone)] +#[derive(Clone)] struct Rule { // This is an Arc because Rule will essentially be cloned for every node // that it matches. Selector contains an owned vector (through @@ -523,7 +524,7 @@ struct Rule { /// A property declaration together with its precedence among rules of equal specificity so that /// we can sort them. -#[deriving(Clone, Show)] +#[derive(Clone, Show)] pub struct DeclarationBlock { pub declarations: Arc<Vec<PropertyDeclaration>>, source_order: uint, @@ -618,7 +619,7 @@ fn matches_compound_selector<'a,E,N>(selector: &CompoundSelector, /// However since the selector "c1" raises /// NotMatchedAndRestartFromClosestDescendant. So the selector /// "b1 + c1 > b2 ~ " doesn't match and restart matching from "d1". -#[deriving(PartialEq, Eq, Copy)] +#[derive(PartialEq, Eq, Copy)] enum SelectorMatchingResult { Matched, NotMatchedAndRestartFromClosestLaterSibling, @@ -758,7 +759,6 @@ fn matches_compound_selector_internal<'a,E,N>(selector: &CompoundSelector, } bitflags! { - #[deriving(Copy)] flags CommonStyleAffectingAttributes: u8 { const HIDDEN_ATTRIBUTE = 0x01, const NO_WRAP_ATTRIBUTE = 0x02, @@ -773,7 +773,7 @@ pub struct CommonStyleAffectingAttributeInfo { pub mode: CommonStyleAffectingAttributeMode, } -#[deriving(Copy)] +#[derive(Copy)] pub enum CommonStyleAffectingAttributeMode { IsPresent(CommonStyleAffectingAttributes), IsEqual(&'static str, CommonStyleAffectingAttributes), @@ -781,7 +781,7 @@ pub enum CommonStyleAffectingAttributeMode { // NB: This must match the order in `layout::css::matching::CommonStyleAffectingAttributes`. #[inline] -pub fn common_style_affecting_attributes() -> [CommonStyleAffectingAttributeInfo, ..5] { +pub fn common_style_affecting_attributes() -> [CommonStyleAffectingAttributeInfo; 5] { [ CommonStyleAffectingAttributeInfo { atom: atom!("hidden"), @@ -809,7 +809,7 @@ pub fn common_style_affecting_attributes() -> [CommonStyleAffectingAttributeInfo /// Attributes that, if present, disable style sharing. All legacy HTML attributes must be in /// either this list or `common_style_affecting_attributes`. See the comment in /// `synthesize_presentational_hints_for_legacy_attributes`. -pub fn rare_style_affecting_attributes() -> [Atom, ..3] { +pub fn rare_style_affecting_attributes() -> [Atom; 3] { [ atom!("bgcolor"), atom!("border"), atom!("colspan") ] } @@ -1141,22 +1141,15 @@ fn matches_last_child<'a,E,N>(element: &N) -> bool where E: TElement<'a>, N: TNo } } - -trait FindPush<K, V> { - fn find_push(&mut self, key: K, value: V); -} - -impl<K: Eq + Hash, V> FindPush<K, V> for HashMap<K, Vec<V>> { - fn find_push(&mut self, key: K, value: V) { - match self.get_mut(&key) { - Some(vec) => { - vec.push(value); - return - } - None => {} +fn find_push(map: &mut HashMap<Atom, Vec<Rule>>, key: Atom, value: Rule) { + match map.get_mut(&key) { + Some(vec) => { + vec.push(value); + return } - self.insert(key, vec![value]); + None => {} } + map.insert(key, vec![value]); } #[cfg(test)] @@ -1223,7 +1216,7 @@ mod tests { #[test] fn test_get_local_name(){ let rules_list = get_mock_rules(&["img.foo", "#top", "IMG", "ImG"]); - let check = |i, names: Option<(&str, &str)>| { + let check = |&:i: uint, names: Option<(&str, &str)>| { assert!(SelectorMap::get_local_name(&rules_list[i][0]) == names.map(|(name, lower_name)| LocalName { name: Atom::from_slice(name), diff --git a/components/style/selectors.rs b/components/style/selectors.rs index 55b2fc687d0..a4c4b0bea53 100644 --- a/components/style/selectors.rs +++ b/components/style/selectors.rs @@ -5,7 +5,7 @@ use std::cmp; use std::ascii::{AsciiExt, OwnedAsciiExt}; use std::sync::Arc; -use std::str::CowString; +use std::string::CowString; use cssparser::{Token, Parser, parse_nth}; use string_cache::{Atom, Namespace}; @@ -16,14 +16,14 @@ use namespaces::NamespaceMap; use stylesheets::Origin; -#[deriving(PartialEq, Clone, Show)] +#[derive(PartialEq, Clone, Show)] pub struct Selector { pub compound_selectors: Arc<CompoundSelector>, pub pseudo_element: Option<PseudoElement>, pub specificity: u32, } -#[deriving(Eq, PartialEq, Clone, Hash, Copy, Show)] +#[derive(Eq, PartialEq, Clone, Hash, Copy, Show)] pub enum PseudoElement { Before, After, @@ -31,13 +31,13 @@ pub enum PseudoElement { } -#[deriving(PartialEq, Clone, Show)] +#[derive(PartialEq, Clone, Show)] pub struct CompoundSelector { pub simple_selectors: Vec<SimpleSelector>, pub next: Option<(Box<CompoundSelector>, Combinator)>, // c.next is left of c } -#[deriving(PartialEq, Clone, Copy, Show)] +#[derive(PartialEq, Clone, Copy, Show)] pub enum Combinator { Child, // > Descendant, // space @@ -45,7 +45,7 @@ pub enum Combinator { LaterSibling, // ~ } -#[deriving(Eq, PartialEq, Clone, Hash, Show)] +#[derive(Eq, PartialEq, Clone, Hash, Show)] pub enum SimpleSelector { ID(Atom), Class(Atom), @@ -85,27 +85,27 @@ pub enum SimpleSelector { } -#[deriving(Eq, PartialEq, Clone, Hash, Copy, Show)] +#[derive(Eq, PartialEq, Clone, Hash, Copy, Show)] pub enum CaseSensitivity { CaseSensitive, // Selectors spec says language-defined, but HTML says sensitive. CaseInsensitive, } -#[deriving(Eq, PartialEq, Clone, Hash, Show)] +#[derive(Eq, PartialEq, Clone, Hash, Show)] pub struct LocalName { pub name: Atom, pub lower_name: Atom, } -#[deriving(Eq, PartialEq, Clone, Hash, Show)] +#[derive(Eq, PartialEq, Clone, Hash, Show)] pub struct AttrSelector { pub name: Atom, pub lower_name: Atom, pub namespace: NamespaceConstraint, } -#[deriving(Eq, PartialEq, Clone, Hash, Show)] +#[derive(Eq, PartialEq, Clone, Hash, Show)] pub enum NamespaceConstraint { Any, Specific(Namespace), @@ -288,7 +288,7 @@ fn parse_type_selector(context: &ParserContext, input: &mut Parser) Some(name) => { simple_selectors.push(SimpleSelector::LocalName(LocalName { name: Atom::from_slice(name.as_slice()), - lower_name: Atom::from_slice(name.into_owned().into_ascii_lower().as_slice()) + lower_name: Atom::from_slice(name.into_owned().into_ascii_lowercase().as_slice()) })) } None => (), @@ -299,7 +299,7 @@ fn parse_type_selector(context: &ParserContext, input: &mut Parser) } -#[deriving(Show)] +#[derive(Show)] enum SimpleSelectorParseResult { SimpleSelector(SimpleSelector), PseudoElement(PseudoElement), @@ -313,7 +313,7 @@ fn parse_qualified_name<'i, 't> (context: &ParserContext, input: &mut Parser<'i, 't>, in_attr_selector: bool) -> Result<Option<(NamespaceConstraint, Option<CowString<'i>>)>, ()> { - let default_namespace = |local_name| { + let default_namespace = |:local_name| { let namespace = match context.namespaces.default { Some(ref ns) => NamespaceConstraint::Specific(ns.clone()), None => NamespaceConstraint::Any, @@ -321,7 +321,7 @@ fn parse_qualified_name<'i, 't> Ok(Some((namespace, local_name))) }; - let explicit_namespace = |input: &mut Parser<'i, 't>, namespace| { + let explicit_namespace = |&: input: &mut Parser<'i, 't>, namespace| { match input.next_including_whitespace() { Ok(Token::Delim('*')) if !in_attr_selector => { Ok(Some((namespace, None))) @@ -383,7 +383,7 @@ fn parse_attribute_selector(context: &ParserContext, input: &mut Parser) Some((_, None)) => unreachable!(), Some((namespace, Some(local_name))) => AttrSelector { namespace: namespace, - lower_name: Atom::from_slice(local_name.as_slice().to_ascii_lower().as_slice()), + lower_name: Atom::from_slice(local_name.as_slice().to_ascii_lowercase().as_slice()), name: Atom::from_slice(local_name.as_slice()), }, }; @@ -408,7 +408,7 @@ fn parse_attribute_selector(context: &ParserContext, input: &mut Parser) // [foo|=bar] Ok(Token::DashMatch) => { let value = try!(parse_value(input)); - let dashing_value = format!("{}-", value); + let dashing_value = format!("{:?}-", value); Ok(SimpleSelector::AttrDashMatch(attr, value, dashing_value)) } // [foo^=bar] @@ -507,7 +507,7 @@ fn parse_functional_pseudo_class(context: &ParserContext, name: &str, inside_negation: bool) -> Result<SimpleSelector,()> { - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "nth-child" => parse_nth_pseudo_class(input, SimpleSelector::NthChild), "nth-of-type" => parse_nth_pseudo_class(input, SimpleSelector::NthOfType), "nth-last-child" => parse_nth_pseudo_class(input, SimpleSelector::NthLastChild), @@ -524,8 +524,8 @@ fn parse_functional_pseudo_class(context: &ParserContext, } -fn parse_nth_pseudo_class(input: &mut Parser, selector: |i32, i32| -> SimpleSelector) - -> Result<SimpleSelector, ()> { +fn parse_nth_pseudo_class<F>(input: &mut Parser, selector: F) -> Result<SimpleSelector, ()> +where F: FnOnce(i32, i32) -> SimpleSelector { let (a, b) = try!(parse_nth(input)); Ok(selector(a, b)) } @@ -566,7 +566,7 @@ fn parse_one_simple_selector(context: &ParserContext, Ok(Token::Ident(name)) => { match parse_simple_pseudo_class(context, name.as_slice()) { Err(()) => { - let pseudo_element = match_ignore_ascii_case! { name: + let pseudo_element = match_ignore_ascii_case! { name, // Supported CSS 2.1 pseudo-elements only. // ** Do not add to this list! ** "before" => PseudoElement::Before, @@ -607,7 +607,7 @@ fn parse_one_simple_selector(context: &ParserContext, } fn parse_simple_pseudo_class(context: &ParserContext, name: &str) -> Result<SimpleSelector,()> { - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "any-link" => Ok(SimpleSelector::AnyLink), "link" => Ok(SimpleSelector::Link), "visited" => Ok(SimpleSelector::Visited), @@ -635,7 +635,7 @@ fn parse_simple_pseudo_class(context: &ParserContext, name: &str) -> Result<Simp } fn parse_pseudo_element(name: &str) -> Result<PseudoElement, ()> { - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "before" => Ok(PseudoElement::Before), "after" => Ok(PseudoElement::After) _ => Err(()) @@ -673,7 +673,7 @@ mod tests { #[test] fn test_parsing() { - assert_eq!(parse(""), Err(())) + assert_eq!(parse(""), Err(())) ; assert_eq!(parse("EeÉ"), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec!(SimpleSelector::LocalName(LocalName { @@ -683,7 +683,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(0, 0, 1), - }))) + }))); assert_eq!(parse(".foo"), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec!(SimpleSelector::Class(Atom::from_slice("foo"))), @@ -691,7 +691,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(0, 1, 0), - }))) + }))); assert_eq!(parse("#bar"), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec!(SimpleSelector::ID(Atom::from_slice("bar"))), @@ -699,7 +699,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(1, 0, 0), - }))) + }))); assert_eq!(parse("e.foo#bar"), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec!(SimpleSelector::LocalName(LocalName { @@ -711,7 +711,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(1, 1, 1), - }))) + }))); assert_eq!(parse("e.foo #bar"), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec!(SimpleSelector::ID(Atom::from_slice("bar"))), @@ -725,7 +725,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(1, 1, 1), - }))) + }))); // Default namespace does not apply to attribute selectors // https://github.com/mozilla/servo/pull/1652 let mut namespaces = NamespaceMap::new(); @@ -740,7 +740,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(0, 1, 0), - }))) + }))); // Default namespace does not apply to attribute selectors // https://github.com/mozilla/servo/pull/1652 namespaces.default = Some(ns!(MathML)); @@ -755,7 +755,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(0, 1, 0), - }))) + }))); // Default namespace does apply to type selectors assert_eq!(parse_ns("e", namespaces), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { @@ -769,7 +769,7 @@ mod tests { }), pseudo_element: None, specificity: specificity(0, 0, 1), - }))) + }))); // https://github.com/mozilla/servo/issues/1723 assert_eq!(parse("::before"), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { @@ -778,7 +778,7 @@ mod tests { }), pseudo_element: Some(PseudoElement::Before), specificity: specificity(0, 0, 1), - }))) + }))); assert_eq!(parse("div :after"), Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec!(), @@ -791,7 +791,7 @@ mod tests { }), pseudo_element: Some(PseudoElement::After), specificity: specificity(0, 0, 2), - }))) + }))); assert_eq!(parse("#d1 > .ok"), Ok(vec![Selector { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec![ diff --git a/components/style/stylesheets.rs b/components/style/stylesheets.rs index cc3e3f42543..7d9aeaf0297 100644 --- a/components/style/stylesheets.rs +++ b/components/style/stylesheets.rs @@ -15,11 +15,11 @@ use selectors::{Selector, parse_selector_list}; use parser::ParserContext; use properties::{PropertyDeclarationBlock, parse_property_declaration_list}; use namespaces::{NamespaceMap, parse_namespace_rule}; -use media_queries::{mod, Device, MediaQueryList, parse_media_query_list}; +use media_queries::{self, Device, MediaQueryList, parse_media_query_list}; use font_face::{FontFaceRule, Source, parse_font_face_block, iter_font_face_rules_inner}; -#[deriving(Clone, PartialEq, Eq, Copy, Show)] +#[derive(Clone, PartialEq, Eq, Copy, Show)] pub enum Origin { UserAgent, Author, @@ -27,7 +27,7 @@ pub enum Origin { } -#[deriving(Show, PartialEq)] +#[derive(Show, PartialEq)] pub struct Stylesheet { /// List of rules in the order they were found (important for /// cascading order) @@ -36,7 +36,7 @@ pub struct Stylesheet { } -#[deriving(Show, PartialEq)] +#[derive(Show, PartialEq)] pub enum CSSRule { Charset(String), Namespace(Option<String>, Namespace), @@ -45,14 +45,14 @@ pub enum CSSRule { FontFace(FontFaceRule), } -#[deriving(Show, PartialEq)] +#[derive(Show, PartialEq)] pub struct MediaRule { pub media_queries: MediaQueryList, pub rules: Vec<CSSRule>, } -#[deriving(Show, PartialEq)] +#[derive(Show, PartialEq)] pub struct StyleRule { pub selectors: Vec<Selector>, pub declarations: PropertyDeclarationBlock, @@ -60,7 +60,7 @@ pub struct StyleRule { impl Stylesheet { - pub fn from_bytes_iter<I: Iterator<Vec<u8>>>( + pub fn from_bytes_iter<I: Iterator<Item=Vec<u8>>>( mut input: I, base_url: Url, protocol_encoding_label: Option<&str>, environment_encoding: Option<EncodingRef>, origin: Origin) -> Stylesheet { let mut bytes = vec!(); @@ -122,7 +122,7 @@ struct MainRuleParser<'a, 'b: 'a> { } -#[deriving(Eq, PartialEq, Ord, PartialOrd)] +#[derive(Eq, PartialEq, Ord, PartialOrd)] enum State { Start = 1, Imports = 2, @@ -140,7 +140,7 @@ enum AtRulePrelude { impl<'a, 'b> AtRuleParser<AtRulePrelude, CSSRule> for MainRuleParser<'a, 'b> { fn parse_prelude(&mut self, name: &str, input: &mut Parser) -> Result<AtRuleType<AtRulePrelude, CSSRule>, ()> { - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "charset" => { if self.state <= State::Start { // Valid @charset rules are just ignored @@ -174,7 +174,7 @@ impl<'a, 'b> AtRuleParser<AtRulePrelude, CSSRule> for MainRuleParser<'a, 'b> { self.state = State::Body; - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "media" => { let media_queries = parse_media_query_list(input); Ok(AtRuleType::WithBlock(AtRulePrelude::Media(media_queries))) @@ -217,13 +217,13 @@ impl<'a, 'b> QualifiedRuleParser<Vec<Selector>, CSSRule> for MainRuleParser<'a, } -pub fn iter_style_rules<'a>(rules: &[CSSRule], device: &media_queries::Device, - callback: |&StyleRule|) { +pub fn iter_style_rules<'a, F>(rules: &[CSSRule], device: &media_queries::Device, + callback: &mut F) where F: FnMut(&StyleRule) { for rule in rules.iter() { match *rule { CSSRule::Style(ref rule) => callback(rule), CSSRule::Media(ref rule) => if rule.media_queries.evaluate(device) { - iter_style_rules(rule.rules.as_slice(), device, |s| callback(s)) + iter_style_rules(rule.rules.as_slice(), device, callback) }, CSSRule::FontFace(..) | CSSRule::Charset(..) | @@ -232,7 +232,7 @@ pub fn iter_style_rules<'a>(rules: &[CSSRule], device: &media_queries::Device, } } -pub fn iter_stylesheet_media_rules(stylesheet: &Stylesheet, callback: |&MediaRule|) { +pub fn iter_stylesheet_media_rules<F>(stylesheet: &Stylesheet, mut callback: F) where F: FnMut(&MediaRule) { for rule in stylesheet.rules.iter() { match *rule { CSSRule::Media(ref rule) => callback(rule), @@ -245,15 +245,15 @@ pub fn iter_stylesheet_media_rules(stylesheet: &Stylesheet, callback: |&MediaRul } #[inline] -pub fn iter_stylesheet_style_rules(stylesheet: &Stylesheet, device: &media_queries::Device, - callback: |&StyleRule|) { - iter_style_rules(stylesheet.rules.as_slice(), device, callback) +pub fn iter_stylesheet_style_rules<F>(stylesheet: &Stylesheet, device: &media_queries::Device, + mut callback: F) where F: FnMut(&StyleRule) { + iter_style_rules(stylesheet.rules.as_slice(), device, &mut callback) } #[inline] -pub fn iter_font_face_rules(stylesheet: &Stylesheet, device: &Device, - callback: |family: &str, source: &Source|) { +pub fn iter_font_face_rules<F>(stylesheet: &Stylesheet, device: &Device, + callback: &F) where F: Fn(&str, &Source) { iter_font_face_rules_inner(stylesheet.rules.as_slice(), device, callback) } @@ -265,6 +265,7 @@ fn test_parse_stylesheet() { use selectors::*; use string_cache::Atom; use properties::{PropertyDeclaration, DeclaredValue, longhands}; + use std::borrow::ToOwned; let css = r" @namespace url(http://www.w3.org/1999/xhtml); @@ -293,7 +294,7 @@ fn test_parse_stylesheet() { name: atom!(type), lower_name: atom!(type), namespace: NamespaceConstraint::Specific(ns!("")), - }, "hidden".into_string(), CaseSensitivity::CaseInsensitive) + }, "hidden".to_owned(), CaseSensitivity::CaseInsensitive) ], next: None, }), @@ -374,7 +375,7 @@ fn test_parse_stylesheet() { PropertyDeclaration::BackgroundPosition(DeclaredValue::Initial), PropertyDeclaration::BackgroundColor(DeclaredValue::SpecifiedValue( longhands::background_color::SpecifiedValue { - authored: Some("blue".into_string()), + authored: Some("blue".to_owned()), parsed: cssparser::Color::RGBA(cssparser::RGBA { red: 0., green: 0., blue: 1., alpha: 1. }), diff --git a/components/style/values.rs b/components/style/values.rs index fb8806c6c38..dae0c015a59 100644 --- a/components/style/values.rs +++ b/components/style/values.rs @@ -3,23 +3,22 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![allow(non_camel_case_types)] -#![macro_escape] macro_rules! define_css_keyword_enum { ($name: ident: $( $css: expr => $variant: ident ),+,) => { - define_css_keyword_enum!($name: $( $css => $variant ),+) + define_css_keyword_enum!($name: $( $css => $variant ),+); }; ($name: ident: $( $css: expr => $variant: ident ),+) => { #[allow(non_camel_case_types)] - #[deriving(Clone, Eq, PartialEq, FromPrimitive, Copy)] + #[derive(Clone, Eq, PartialEq, FromPrimitive, Copy)] pub enum $name { $( $variant ),+ } impl $name { pub fn parse(input: &mut ::cssparser::Parser) -> Result<$name, ()> { - match_ignore_ascii_case! { try!(input.expect_ident()): + match_ignore_ascii_case! { try!(input.expect_ident()), $( $css => Ok($name::$variant) ),+ _ => Err(()) } @@ -61,7 +60,7 @@ pub mod specified { use super::CSSFloat; use super::computed; - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub struct CSSColor { pub parsed: cssparser::Color, pub authored: Option<String>, @@ -94,7 +93,7 @@ pub mod specified { } } - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub struct CSSRGBA { pub parsed: cssparser::RGBA, pub authored: Option<String>, @@ -112,7 +111,7 @@ pub mod specified { } } - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub struct CSSImage(pub Option<Image>); impl fmt::Show for CSSImage { @@ -128,7 +127,7 @@ pub mod specified { } } - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum Length { Au(Au), // application units Em(CSSFloat), @@ -184,7 +183,7 @@ pub mod specified { Length::parse_internal(input, /* negative_ok = */ false) } pub fn parse_dimension(value: CSSFloat, unit: &str) -> Result<Length, ()> { - match_ignore_ascii_case! { unit: + match_ignore_ascii_case! { unit, "px" => Ok(Length::from_px(value)), "in" => Ok(Length::Au(Au((value * AU_PER_IN) as i32))), "cm" => Ok(Length::Au(Au((value * AU_PER_CM) as i32))), @@ -204,7 +203,7 @@ pub mod specified { } - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum LengthOrPercentage { Length(Length), Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] @@ -251,7 +250,7 @@ pub mod specified { } } - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum LengthOrPercentageOrAuto { Length(Length), Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] @@ -302,7 +301,7 @@ pub mod specified { } } - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum LengthOrPercentageOrNone { Length(Length), Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] @@ -355,7 +354,7 @@ pub mod specified { } // http://dev.w3.org/csswg/css2/colors.html#propdef-background-position - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum PositionComponent { Length(Length), Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] @@ -379,7 +378,7 @@ pub mod specified { Ok(PositionComponent::Length(Length::Au(Au(0)))) } Token::Ident(value) => { - match_ignore_ascii_case! { value: + match_ignore_ascii_case! { value, "center" => Ok(PositionComponent::Center), "left" => Ok(PositionComponent::Left), "right" => Ok(PositionComponent::Right), @@ -405,7 +404,7 @@ pub mod specified { } } - #[deriving(Clone, PartialEq, PartialOrd, Copy)] + #[derive(Clone, PartialEq, PartialOrd, Copy)] pub struct Angle(pub CSSFloat); impl fmt::Show for Angle { @@ -435,7 +434,7 @@ pub mod specified { pub fn parse(input: &mut Parser) -> Result<Angle, ()> { match try!(input.next()) { Token::Dimension(value, unit) => { - match_ignore_ascii_case! { unit: + match_ignore_ascii_case! { unit, "deg" => Ok(Angle(value.value * RAD_PER_DEG)), "grad" => Ok(Angle(value.value * RAD_PER_GRAD)), "turn" => Ok(Angle(value.value * RAD_PER_TURN)), @@ -450,7 +449,7 @@ pub mod specified { } /// Specified values for an image according to CSS-IMAGES. - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub enum Image { Url(Url), LinearGradient(LinearGradient), @@ -481,7 +480,7 @@ pub mod specified { Ok(Image::Url(context.parse_url(url.as_slice()))) } Token::Function(name) => { - match_ignore_ascii_case! { name: + match_ignore_ascii_case! { name, "linear-gradient" => { Ok(Image::LinearGradient(try!( input.parse_nested_block(LinearGradient::parse_function)))) @@ -505,7 +504,7 @@ pub mod specified { } /// Specified values for a CSS linear gradient. - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub struct LinearGradient { /// The angle or corner of the gradient. pub angle_or_corner: AngleOrCorner, @@ -532,7 +531,7 @@ pub mod specified { } /// Specified values for an angle or a corner in a linear gradient. - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub enum AngleOrCorner { Angle(Angle), Corner(HorizontalDirection, VerticalDirection), @@ -558,7 +557,7 @@ pub mod specified { } /// Specified values for one color stop in a linear gradient. - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub struct ColorStop { /// The color of this stop. pub color: CSSColor, @@ -583,8 +582,8 @@ pub mod specified { } } - define_css_keyword_enum!(HorizontalDirection: "left" => Left, "right" => Right) - define_css_keyword_enum!(VerticalDirection: "top" => Top, "bottom" => Bottom) + define_css_keyword_enum!(HorizontalDirection: "left" => Left, "right" => Right); + define_css_keyword_enum!(VerticalDirection: "top" => Top, "bottom" => Bottom); fn parse_one_color_stop(input: &mut Parser) -> Result<ColorStop, ()> { Ok(ColorStop { @@ -644,7 +643,7 @@ pub mod specified { pub fn parse_border_width(input: &mut Parser) -> Result<Length, ()> { input.try(Length::parse_non_negative).or_else(|()| { - match_ignore_ascii_case! { try!(input.expect_ident()): + match_ignore_ascii_case! { try!(input.expect_ident()), "thin" => Ok(Length::from_px(1.)), "medium" => Ok(Length::from_px(3.)), "thick" => Ok(Length::from_px(5.)) @@ -742,7 +741,7 @@ pub mod computed { } } - #[deriving(PartialEq, Clone, Copy)] + #[derive(PartialEq, Clone, Copy)] pub enum LengthOrPercentage { Length(Au), Percentage(CSSFloat), @@ -750,7 +749,7 @@ pub mod computed { impl fmt::Show for LengthOrPercentage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &LengthOrPercentage::Length(length) => write!(f, "{}", length), + &LengthOrPercentage::Length(length) => write!(f, "{:?}", length), &LengthOrPercentage::Percentage(percentage) => write!(f, "{}%", percentage * 100.), } } @@ -767,7 +766,7 @@ pub mod computed { } } - #[deriving(PartialEq, Clone, Copy)] + #[derive(PartialEq, Clone, Copy)] pub enum LengthOrPercentageOrAuto { Length(Au), Percentage(CSSFloat), @@ -776,7 +775,7 @@ pub mod computed { impl fmt::Show for LengthOrPercentageOrAuto { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &LengthOrPercentageOrAuto::Length(length) => write!(f, "{}", length), + &LengthOrPercentageOrAuto::Length(length) => write!(f, "{:?}", length), &LengthOrPercentageOrAuto::Percentage(percentage) => write!(f, "{}%", percentage * 100.), &LengthOrPercentageOrAuto::Auto => write!(f, "auto"), } @@ -795,7 +794,7 @@ pub mod computed { } } - #[deriving(PartialEq, Clone, Copy)] + #[derive(PartialEq, Clone, Copy)] pub enum LengthOrPercentageOrNone { Length(Au), Percentage(CSSFloat), @@ -804,7 +803,7 @@ pub mod computed { impl fmt::Show for LengthOrPercentageOrNone { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &LengthOrPercentageOrNone::Length(length) => write!(f, "{}", length), + &LengthOrPercentageOrNone::Length(length) => write!(f, "{:?}", length), &LengthOrPercentageOrNone::Percentage(percentage) => write!(f, "{}%", percentage * 100.), &LengthOrPercentageOrNone::None => write!(f, "none"), } @@ -824,7 +823,7 @@ pub mod computed { } /// Computed values for an image according to CSS-IMAGES. - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub enum Image { Url(Url), LinearGradient(LinearGradient), @@ -834,13 +833,13 @@ pub mod computed { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Image::Url(ref url) => write!(f, "url(\"{}\")", url), - &Image::LinearGradient(ref grad) => write!(f, "linear-gradient({})", grad), + &Image::LinearGradient(ref grad) => write!(f, "linear-gradient({:?})", grad), } } } /// Computed values for a CSS linear gradient. - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] pub struct LinearGradient { /// The angle or corner of the gradient. pub angle_or_corner: AngleOrCorner, @@ -851,16 +850,16 @@ pub mod computed { impl fmt::Show for LinearGradient { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let _ = write!(f, "{}", self.angle_or_corner); + let _ = write!(f, "{:?}", self.angle_or_corner); for stop in self.stops.iter() { - let _ = write!(f, ", {}", stop); + let _ = write!(f, ", {:?}", stop); } Ok(()) } } /// Computed values for one color stop in a linear gradient. - #[deriving(Clone, PartialEq, Copy)] + #[derive(Clone, PartialEq, Copy)] pub struct ColorStop { /// The color of this stop. pub color: CSSColor, @@ -872,9 +871,9 @@ pub mod computed { impl fmt::Show for ColorStop { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let _ = write!(f, "{}", self.color); + let _ = write!(f, "{:?}", self.color); self.position.map(|pos| { - let _ = write!(f, " {}", pos); + let _ = write!(f, " {:?}", pos); }); Ok(()) } diff --git a/components/util/Cargo.toml b/components/util/Cargo.toml index c418d0b2880..d9209c74e4f 100644 --- a/components/util/Cargo.toml +++ b/components/util/Cargo.toml @@ -36,11 +36,7 @@ git = "https://github.com/servo/string-cache" [dependencies.string_cache_macros] git = "https://github.com/servo/string-cache" -[dependencies.url] -git = "https://github.com/servo/rust-url" - -[dependencies.time] -git = "https://github.com/rust-lang/time" - [dependencies] text_writer = "0.1.1" +url = "*" +time = "*"
\ No newline at end of file diff --git a/components/util/bloom.rs b/components/util/bloom.rs index 2bed80e9e13..6fd5d17e775 100644 --- a/components/util/bloom.rs +++ b/components/util/bloom.rs @@ -58,7 +58,7 @@ const KEY_SHIFT: uint = 16; /// positive rate for N == 100 and to quite bad false positive /// rates for larger N. pub struct BloomFilter { - counters: [u8, ..ARRAY_SIZE], + counters: [u8; ARRAY_SIZE], } impl Clone for BloomFilter { @@ -75,7 +75,7 @@ impl BloomFilter { #[inline] pub fn new() -> BloomFilter { BloomFilter { - counters: [0, ..ARRAY_SIZE], + counters: [0; ARRAY_SIZE], } } @@ -101,7 +101,7 @@ impl BloomFilter { #[inline] pub fn clear(&mut self) { - self.counters = [0, ..ARRAY_SIZE] + self.counters = [0; ARRAY_SIZE] } #[inline] @@ -231,7 +231,7 @@ fn create_and_insert_some_stuff() { let false_positives = range(1001u, 2000).filter(|i| bf.might_contain(i)).count(); - assert!(false_positives < 10) // 1%. + assert!(false_positives < 10); // 1%. for i in range(0u, 100) { bf.remove(&i); @@ -256,7 +256,7 @@ fn create_and_insert_some_stuff() { mod bench { extern crate test; - use std::hash::hash; + use std::hash::{hash, SipHasher}; use std::iter; use super::BloomFilter; @@ -331,7 +331,7 @@ mod bench { fn hash_a_uint(b: &mut test::Bencher) { let mut i = 0u; b.iter(|| { - test::black_box(hash(&i)); + test::black_box(hash::<uint, SipHasher>(&i)); i += 1; }) } diff --git a/components/util/cache.rs b/components/util/cache.rs index 35390d309bf..99e086cdbfe 100644 --- a/components/util/cache.rs +++ b/components/util/cache.rs @@ -2,69 +2,59 @@ * 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/. */ +#![old_impl_check] + use std::collections::HashMap; -use std::collections::hash_map::{Occupied, Vacant}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::collections::hash_state::DefaultState; use rand::Rng; -use std::hash::{Hash, sip}; +use std::hash::{Hash, SipHasher}; use std::iter::repeat; -use std::rand::task_rng; -use std::slice::Items; +use std::rand; +use std::slice::Iter; #[cfg(test)] use std::cell::Cell; -pub trait Cache<K: PartialEq, V: Clone> { - fn insert(&mut self, key: K, value: V); - fn find(&mut self, key: &K) -> Option<V>; - fn find_or_create(&mut self, key: &K, blk: |&K| -> V) -> V; - fn evict_all(&mut self); -} - pub struct HashCache<K, V> { - entries: HashMap<K, V>, + entries: HashMap<K, V, DefaultState<SipHasher>>, } -impl<K: Clone + PartialEq + Eq + Hash, V: Clone> HashCache<K,V> { - pub fn new() -> HashCache<K, V> { +impl<K, V> HashCache<K,V> + where K: Clone + PartialEq + Eq + Hash<SipHasher>, + V: Clone, +{ + pub fn new() -> HashCache<K,V> { HashCache { - entries: HashMap::new(), + entries: HashMap::with_hash_state(DefaultState), } } -} -impl<K: Clone + PartialEq + Eq + Hash, V: Clone> Cache<K,V> for HashCache<K,V> { - fn insert(&mut self, key: K, value: V) { + pub fn insert(&mut self, key: K, value: V) { self.entries.insert(key, value); } - fn find(&mut self, key: &K) -> Option<V> { + pub fn find(&self, key: &K) -> Option<V> { match self.entries.get(key) { Some(v) => Some(v.clone()), - None => None, + None => None, } } - fn find_or_create(&mut self, key: &K, blk: |&K| -> V) -> V { + pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V { match self.entries.entry(key.clone()) { Occupied(occupied) => { (*occupied.get()).clone() } Vacant(vacant) => { - (*vacant.set(blk(key))).clone() + (*vacant.insert(blk(key))).clone() } } } - fn evict_all(&mut self) { + pub fn evict_all(&mut self) { self.entries.clear(); } - -} - -impl<K,V> HashCache<K,V> where K: Clone + PartialEq + Eq + Hash, V: Clone { - pub fn find_equiv<'a,Sized? Q>(&'a self, key: &Q) -> Option<&'a V> where Q: Hash + Equiv<K> { - self.entries.find_equiv(key) - } } #[test] @@ -98,32 +88,30 @@ impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> { let last_index = self.entries.len() - 1; if pos != last_index { let entry = self.entries.remove(pos); - self.entries.push(entry.unwrap()); + self.entries.push(entry); } - self.entries[last_index].ref1().clone() + self.entries[last_index].1.clone() } - pub fn iter<'a>(&'a self) -> Items<'a,(K,V)> { + pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> { self.entries.iter() } -} -impl<K: Clone + PartialEq, V: Clone> Cache<K,V> for LRUCache<K,V> { - fn insert(&mut self, key: K, val: V) { + pub fn insert(&mut self, key: K, val: V) { if self.entries.len() == self.cache_size { self.entries.remove(0); } self.entries.push((key, val)); } - fn find(&mut self, key: &K) -> Option<V> { - match self.entries.iter().position(|&(ref k, _)| *k == *key) { + pub fn find(&mut self, key: &K) -> Option<V> { + match self.entries.iter().position(|&(ref k, _)| key == k) { Some(pos) => Some(self.touch(pos)), None => None, } } - fn find_or_create(&mut self, key: &K, blk: |&K| -> V) -> V { + pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V { match self.entries.iter().position(|&(ref k, _)| *k == *key) { Some(pos) => self.touch(pos), None => { @@ -134,7 +122,7 @@ impl<K: Clone + PartialEq, V: Clone> Cache<K,V> for LRUCache<K,V> { } } - fn evict_all(&mut self) { + pub fn evict_all(&mut self) { self.entries.clear(); } } @@ -145,9 +133,9 @@ pub struct SimpleHashCache<K,V> { k1: u64, } -impl<K:Clone+PartialEq+Hash,V:Clone> SimpleHashCache<K,V> { +impl<K:Clone+Eq+Hash<SipHasher>,V:Clone> SimpleHashCache<K,V> { pub fn new(cache_size: uint) -> SimpleHashCache<K,V> { - let mut r = task_rng(); + let mut r = rand::thread_rng(); SimpleHashCache { entries: repeat(None).take(cache_size).collect(), k0: r.gen(), @@ -161,35 +149,26 @@ impl<K:Clone+PartialEq+Hash,V:Clone> SimpleHashCache<K,V> { } #[inline] - fn bucket_for_key<Q:Hash>(&self, key: &Q) -> uint { - self.to_bucket(sip::hash_with_keys(self.k0, self.k1, key) as uint) + fn bucket_for_key<Q:Hash<SipHasher>>(&self, key: &Q) -> uint { + let mut hasher = SipHasher::new_with_keys(self.k0, self.k1); + key.hash(&mut hasher); + self.to_bucket(hasher.result() as uint) } - #[inline] - pub fn find_equiv<'a,Q:Hash+Equiv<K>>(&'a self, key: &Q) -> Option<&'a V> { - let bucket_index = self.bucket_for_key(key); - match self.entries[bucket_index] { - Some((ref existing_key, ref value)) if key.equiv(existing_key) => Some(value), - _ => None, - } - } -} - -impl<K:Clone+PartialEq+Hash,V:Clone> Cache<K,V> for SimpleHashCache<K,V> { - fn insert(&mut self, key: K, value: V) { + pub fn insert(&mut self, key: K, value: V) { let bucket_index = self.bucket_for_key(&key); self.entries[bucket_index] = Some((key, value)); } - fn find(&mut self, key: &K) -> Option<V> { + pub fn find<Q>(&self, key: &Q) -> Option<V> where Q: PartialEq<K> + Hash<SipHasher> + Eq { let bucket_index = self.bucket_for_key(key); match self.entries[bucket_index] { - Some((ref existing_key, ref value)) if existing_key == key => Some((*value).clone()), + Some((ref existing_key, ref value)) if key == existing_key => Some((*value).clone()), _ => None, } } - fn find_or_create(&mut self, key: &K, blk: |&K| -> V) -> V { + pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V { match self.find(key) { Some(value) => return value, None => {} @@ -199,7 +178,7 @@ impl<K:Clone+PartialEq+Hash,V:Clone> Cache<K,V> for SimpleHashCache<K,V> { value } - fn evict_all(&mut self) { + pub fn evict_all(&mut self) { for slot in self.entries.iter_mut() { *slot = None } diff --git a/components/util/cursor.rs b/components/util/cursor.rs index 23ca2c0af4a..ff203f1a0e7 100644 --- a/components/util/cursor.rs +++ b/components/util/cursor.rs @@ -8,10 +8,9 @@ use cssparser::ToCss; use std::ascii::AsciiExt; use text_writer::TextWriter; - macro_rules! define_cursor { ($( $css: expr => $variant: ident = $value: expr, )+) => { - #[deriving(Clone, Copy, PartialEq, Eq, FromPrimitive, Show)] + #[derive(Clone, Copy, PartialEq, Eq, FromPrimitive, Show)] #[repr(u8)] pub enum Cursor { $( $variant = $value ),+ @@ -19,7 +18,7 @@ macro_rules! define_cursor { impl Cursor { pub fn from_css_keyword(keyword: &str) -> Result<Cursor, ()> { - match_ignore_ascii_case! { keyword: + match_ignore_ascii_case! { keyword, $( concat!($css) => Ok(Cursor::$variant) ),+ _ => Err(()) } diff --git a/components/util/deque/mod.rs b/components/util/deque/mod.rs index b98c872cf0f..505b09ab021 100644 --- a/components/util/deque/mod.rs +++ b/components/util/deque/mod.rs @@ -54,12 +54,13 @@ pub use self::Stolen::{Empty, Abort, Data}; use alloc::arc::Arc; use alloc::heap::{allocate, deallocate}; -use std::kinds::marker; +use std::marker; use std::mem::{forget, min_align_of, size_of, transmute}; use std::ptr; use std::sync::Mutex; -use std::sync::atomic::{AtomicInt, AtomicPtr, SeqCst}; +use std::sync::atomic::{AtomicInt, AtomicPtr}; +use std::sync::atomic::Ordering::SeqCst; // Once the queue is less than 1/K full, then it will be downsized. Note that // the deque requires that this number be less than 2. @@ -97,7 +98,7 @@ pub struct Stealer<T> { } /// When stealing some data, this is an enumeration of the possible outcomes. -#[deriving(PartialEq, Show)] +#[derive(PartialEq, Show)] pub enum Stolen<T> { /// The deque was empty at the time of stealing Empty, @@ -141,6 +142,8 @@ struct Buffer<T> { log_size: uint, } +unsafe impl<T: 'static> Send for Buffer<T> { } + impl<T: Send> BufferPool<T> { /// Allocates a new buffer pool which in turn can be used to allocate new /// deques. @@ -159,16 +162,16 @@ impl<T: Send> BufferPool<T> { fn alloc(&mut self, bits: uint) -> Box<Buffer<T>> { unsafe { - let mut pool = self.pool.lock(); + let mut pool = self.pool.lock().unwrap(); match pool.iter().position(|x| x.size() >= (1 << bits)) { - Some(i) => pool.remove(i).unwrap(), + Some(i) => pool.remove(i), None => box Buffer::new(bits) } } } fn free(&self, buf: Box<Buffer<T>>) { - let mut pool = self.pool.lock(); + let mut pool = self.pool.lock().unwrap(); match pool.iter().position(|v| v.size() > buf.size()) { Some(i) => pool.insert(i, buf), None => pool.push(buf), @@ -403,256 +406,3 @@ impl<T: Send> Drop for Buffer<T> { unsafe { deallocate(self.storage as *mut u8, size, min_align_of::<T>()) } } } - -#[cfg(test)] -mod tests { - use super::{Data, BufferPool, Abort, Empty, Worker, Stealer}; - - use std::mem; - use rustrt::thread::Thread; - use std::rand; - use std::rand::Rng; - use std::sync::atomic::{AtomicBool, INIT_ATOMIC_BOOL, SeqCst, - AtomicUint, INIT_ATOMIC_UINT}; - use std::vec; - - #[test] - fn smoke() { - let pool = BufferPool::new(); - let (w, s) = pool.deque(); - assert_eq!(w.pop(), None); - assert_eq!(s.steal(), Empty); - w.push(1i); - assert_eq!(w.pop(), Some(1)); - w.push(1); - assert_eq!(s.steal(), Data(1)); - w.push(1); - assert_eq!(s.clone().steal(), Data(1)); - } - - #[test] - fn stealpush() { - static AMT: int = 100000; - let pool = BufferPool::<int>::new(); - let (w, s) = pool.deque(); - let t = Thread::start(proc() { - let mut left = AMT; - while left > 0 { - match s.steal() { - Data(i) => { - assert_eq!(i, 1); - left -= 1; - } - Abort | Empty => {} - } - } - }); - - for _ in range(0, AMT) { - w.push(1); - } - - t.join(); - } - - #[test] - fn stealpush_large() { - static AMT: int = 100000; - let pool = BufferPool::<(int, int)>::new(); - let (w, s) = pool.deque(); - let t = Thread::start(proc() { - let mut left = AMT; - while left > 0 { - match s.steal() { - Data((1, 10)) => { left -= 1; } - Data(..) => panic!(), - Abort | Empty => {} - } - } - }); - - for _ in range(0, AMT) { - w.push((1, 10)); - } - - t.join(); - } - - fn stampede(w: Worker<Box<int>>, s: Stealer<Box<int>>, - nthreads: int, amt: uint) { - for _ in range(0, amt) { - w.push(box 20); - } - let mut remaining = AtomicUint::new(amt); - let unsafe_remaining: *mut AtomicUint = &mut remaining; - - let threads = range(0, nthreads).map(|_| { - let s = s.clone(); - Thread::start(proc() { - unsafe { - while (*unsafe_remaining).load(SeqCst) > 0 { - match s.steal() { - Data(box 20) => { - (*unsafe_remaining).fetch_sub(1, SeqCst); - } - Data(..) => panic!(), - Abort | Empty => {} - } - } - } - }) - }).collect::<Vec<Thread<()>>>(); - - while remaining.load(SeqCst) > 0 { - match w.pop() { - Some(box 20) => { remaining.fetch_sub(1, SeqCst); } - Some(..) => panic!(), - None => {} - } - } - - for thread in threads.into_iter() { - thread.join(); - } - } - - #[test] - fn run_stampede() { - let pool = BufferPool::<Box<int>>::new(); - let (w, s) = pool.deque(); - stampede(w, s, 8, 10000); - } - - #[test] - fn many_stampede() { - static AMT: uint = 4; - let pool = BufferPool::<Box<int>>::new(); - let threads = range(0, AMT).map(|_| { - let (w, s) = pool.deque(); - Thread::start(proc() { - stampede(w, s, 4, 10000); - }) - }).collect::<Vec<Thread<()>>>(); - - for thread in threads.into_iter() { - thread.join(); - } - } - - #[test] - fn stress() { - static AMT: int = 100000; - static NTHREADS: int = 8; - static DONE: AtomicBool = INIT_ATOMIC_BOOL; - static HITS: AtomicUint = INIT_ATOMIC_UINT; - let pool = BufferPool::<int>::new(); - let (w, s) = pool.deque(); - - let threads = range(0, NTHREADS).map(|_| { - let s = s.clone(); - Thread::start(proc() { - loop { - match s.steal() { - Data(2) => { HITS.fetch_add(1, SeqCst); } - Data(..) => panic!(), - _ if DONE.load(SeqCst) => break, - _ => {} - } - } - }) - }).collect::<Vec<Thread<()>>>(); - - let mut rng = rand::task_rng(); - let mut expected = 0; - while expected < AMT { - if rng.gen_range(0i, 3) == 2 { - match w.pop() { - None => {} - Some(2) => { HITS.fetch_add(1, SeqCst); }, - Some(_) => panic!(), - } - } else { - expected += 1; - w.push(2); - } - } - - while HITS.load(SeqCst) < AMT as uint { - match w.pop() { - None => {} - Some(2) => { HITS.fetch_add(1, SeqCst); }, - Some(_) => panic!(), - } - } - DONE.store(true, SeqCst); - - for thread in threads.into_iter() { - thread.join(); - } - - assert_eq!(HITS.load(SeqCst), expected as uint); - } - - #[test] - #[cfg_attr(windows, ignore)] // apparently windows scheduling is weird? - fn no_starvation() { - static AMT: int = 10000; - static NTHREADS: int = 4; - static DONE: AtomicBool = INIT_ATOMIC_BOOL; - let pool = BufferPool::<(int, uint)>::new(); - let (w, s) = pool.deque(); - - let (threads, hits) = vec::unzip(range(0, NTHREADS).map(|_| { - let s = s.clone(); - let unique_box = box AtomicUint::new(0); - let thread_box = unsafe { - *mem::transmute::<&Box<AtomicUint>, - *const *mut AtomicUint>(&unique_box) - }; - (Thread::start(proc() { - unsafe { - loop { - match s.steal() { - Data((1, 2)) => { - (*thread_box).fetch_add(1, SeqCst); - } - Data(..) => panic!(), - _ if DONE.load(SeqCst) => break, - _ => {} - } - } - } - }), unique_box) - })); - - let mut rng = rand::task_rng(); - let mut myhit = false; - 'outer: loop { - for _ in range(0, rng.gen_range(0, AMT)) { - if !myhit && rng.gen_range(0i, 3) == 2 { - match w.pop() { - None => {} - Some((1, 2)) => myhit = true, - Some(_) => panic!(), - } - } else { - w.push((1, 2)); - } - } - - for slot in hits.iter() { - let amt = slot.load(SeqCst); - if amt == 0 { continue 'outer; } - } - if myhit { - break - } - } - - DONE.store(true, SeqCst); - - for thread in threads.into_iter() { - thread.join(); - } - } -} diff --git a/components/util/fnv.rs b/components/util/fnv.rs index 13c8e1c28ad..61b4cd73d48 100644 --- a/components/util/fnv.rs +++ b/components/util/fnv.rs @@ -4,7 +4,8 @@ //! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs -pub use std::hash::{Hash, Hasher, Writer}; +use std::default::Default; +use std::hash::{Hasher, Writer}; /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn't quite as speedy as we @@ -13,33 +14,26 @@ pub use std::hash::{Hash, Hasher, Writer}; /// /// This uses FNV hashing, as described here: /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function -#[deriving(Clone)] -pub struct FnvHasher; +#[allow(missing_copy_implementations)] +pub struct FnvHasher(u64); -pub struct FnvState(u64); +impl Default for FnvHasher { + fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) } +} -impl Hasher<FnvState> for FnvHasher { - fn hash<Sized? T: Hash<FnvState>>(&self, t: &T) -> u64 { - let mut state = FnvState(0xcbf29ce484222325); - t.hash(&mut state); - let FnvState(ret) = state; - return ret; - } +impl Hasher for FnvHasher { + type Output = u64; + fn reset(&mut self) { *self = Default::default(); } + fn finish(&self) -> u64 { self.0 } } -impl Writer for FnvState { +impl Writer for FnvHasher { fn write(&mut self, bytes: &[u8]) { - let FnvState(mut hash) = *self; + let FnvHasher(mut hash) = *self; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } - *self = FnvState(hash); + *self = FnvHasher(hash); } } - -#[inline(always)] -pub fn hash<T: Hash<FnvState>>(t: &T) -> u64 { - let s = FnvHasher; - s.hash(t) -} diff --git a/components/util/geometry.rs b/components/util/geometry.rs index 5c3ee808b43..a30849eaf5d 100644 --- a/components/util/geometry.rs +++ b/components/util/geometry.rs @@ -8,11 +8,13 @@ use geom::rect::Rect; use geom::size::Size2D; use geom::num::Zero; -use serialize::{Encodable, Encoder}; use std::default::Default; use std::i32; -use std::num::{Float, NumCast}; +use std::num::{Float, NumCast, ToPrimitive}; use std::fmt; +use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; + +use rustc_serialize::{Encoder, Encodable}; // Units for use with geom::length and geom::scale_factor. @@ -29,7 +31,7 @@ use std::fmt; /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. -#[deriving(Show, Copy)] +#[derive(Show, Copy)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": @@ -41,7 +43,7 @@ pub enum ScreenPx {} /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. -#[deriving(Encodable, Show, Copy)] +#[derive(RustcEncodable, Show, Copy)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. @@ -50,7 +52,7 @@ pub enum ViewportPx {} /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. -#[deriving(Encodable, Show, Copy)] +#[derive(RustcEncodable, Show, Copy)] pub enum PagePx {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: @@ -65,7 +67,7 @@ pub enum PagePx {} // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. -#[deriving(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)] +#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)] pub struct Au(pub i32); impl Default for Au { @@ -112,8 +114,8 @@ pub static MAX_RECT: Rect<Au> = Rect { pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); -impl<E, S: Encoder<E>> Encodable<S, E> for Au { - fn encode(&self, e: &mut S) -> Result<(), E> { +impl Encodable for Au { + fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(to_frac_px(*self)) } } @@ -123,53 +125,65 @@ impl fmt::Show for Au { write!(f, "{}px", to_frac_px(*self)) }} -impl Add<Au,Au> for Au { +impl Add for Au { + type Output = Au; + #[inline] - fn add(&self, other: &Au) -> Au { - let Au(s) = *self; - let Au(o) = *other; + fn add(self, other: Au) -> Au { + let Au(s) = self; + let Au(o) = other; Au(s + o) } } -impl Sub<Au,Au> for Au { +impl Sub for Au { + type Output = Au; + #[inline] - fn sub(&self, other: &Au) -> Au { - let Au(s) = *self; - let Au(o) = *other; + fn sub(self, other: Au) -> Au { + let Au(s) = self; + let Au(o) = other; Au(s - o) } } -impl Mul<i32, Au> for Au { +impl Mul<i32> for Au { + type Output = Au; + #[inline] - fn mul(&self, other: &i32) -> Au { - let Au(s) = *self; - Au(s * *other) + fn mul(self, other: i32) -> Au { + let Au(s) = self; + Au(s * other) } } -impl Div<i32, Au> for Au { +impl Div<i32> for Au { + type Output = Au; + #[inline] - fn div(&self, other: &i32) -> Au { - let Au(s) = *self; - Au(s / *other) + fn div(self, other: i32) -> Au { + let Au(s) = self; + Au(s / other) } } -impl Rem<i32, Au> for Au { +impl Rem<i32> for Au { + type Output = Au; + #[inline] - fn rem(&self, other: &i32) -> Au { - let Au(s) = *self; - Au(s % *other) + fn rem(self, other: i32) -> Au { + let Au(s) = self; + Au(s % other) } } -impl Neg<Au> for Au { +impl Neg for Au { + type Output = Au; + #[inline] - fn neg(&self) -> Au { - let Au(s) = *self; + fn neg(self) -> Au { + let Au(s) = self; Au(-s) } } @@ -323,7 +337,7 @@ pub fn to_pt(au: Au) -> f64 { /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. -pub fn rect_contains_point<T:PartialOrd + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool { +pub fn rect_contains_point<T:PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } diff --git a/components/util/lib.rs b/components/util/lib.rs index 9a97bdbbf78..bceab7a3014 100644 --- a/components/util/lib.rs +++ b/components/util/lib.rs @@ -2,15 +2,18 @@ * 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/. */ -#![feature(default_type_params,macro_rules,unsafe_destructor)] +#![feature(unsafe_destructor)] +#![feature(plugin)] +#![feature(int_uint)] +#![feature(old_impl_check)] +#![feature(box_syntax)] #![deny(unused_imports)] #![deny(unused_variables)] #![allow(missing_copy_implementations)] +#![allow(unstable)] -#![feature(phase)] -#[phase(plugin, link)] -extern crate log; +#[macro_use] extern crate log; extern crate alloc; extern crate collections; @@ -19,9 +22,9 @@ extern crate geom; extern crate getopts; extern crate layers; extern crate libc; +#[no_link] #[macro_use] extern crate cssparser; extern crate rand; -extern crate rustrt; -extern crate serialize; +extern crate "serialize" as rustc_serialize; #[cfg(target_os="macos")] extern crate task_info; extern crate "time" as std_time; @@ -30,9 +33,9 @@ extern crate string_cache; extern crate unicode; extern crate url; -#[phase(plugin)] extern crate plugins; -#[phase(plugin)] extern crate string_cache_macros; -#[phase(plugin)] extern crate lazy_static; +#[no_link] #[macro_use] #[plugin] +extern crate string_cache_macros; +extern crate lazy_static; use std::sync::Arc; diff --git a/components/util/logical_geometry.rs b/components/util/logical_geometry.rs index eebd0735b81..a76bd1ca21e 100644 --- a/components/util/logical_geometry.rs +++ b/components/util/logical_geometry.rs @@ -8,16 +8,17 @@ use geom::{Size2D, Point2D, SideOffsets2D, Rect}; use geom::num::Zero; use std::cmp::{min, max}; use std::fmt::{Show, Formatter, Error}; +use std::ops::{Add, Sub}; bitflags!( - #[deriving(Encodable, Copy)] + #[derive(RustcEncodable)] flags WritingMode: u8 { const FLAG_RTL = 1 << 0, const FLAG_VERTICAL = 1 << 1, const FLAG_VERTICAL_LR = 1 << 2, const FLAG_SIDEWAYS_LEFT = 1 << 3 } -) +); impl WritingMode { #[inline] @@ -79,11 +80,11 @@ impl Show for WritingMode { /// (in addition to taking it as a parameter to methods) and check it. /// In non-debug builds, make this storage zero-size and the checks no-ops. #[cfg(ndebug)] -#[deriving(Encodable, PartialEq, Eq, Clone, Copy)] +#[derive(RustcEncodable, PartialEq, Eq, Clone, Copy)] struct DebugWritingMode; #[cfg(not(ndebug))] -#[deriving(Encodable, PartialEq, Eq, Clone, Copy)] +#[derive(RustcEncodable, PartialEq, Eq, Clone, Copy)] struct DebugWritingMode { mode: WritingMode } @@ -134,7 +135,7 @@ impl Show for DebugWritingMode { /// A 2D size in flow-relative dimensions -#[deriving(Encodable, PartialEq, Eq, Clone, Copy)] +#[derive(RustcEncodable, PartialEq, Eq, Clone, Copy)] pub struct LogicalSize<T> { pub inline: T, // inline-size, a.k.a. logical width, a.k.a. measure pub block: T, // block-size, a.k.a. logical height, a.k.a. extent @@ -143,7 +144,7 @@ pub struct LogicalSize<T> { impl<T: Show> Show for LogicalSize<T> { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { - write!(formatter, "LogicalSize({}, i{}×b{})", + write!(formatter, "LogicalSize({:?}, i{:?}×b{:?})", self.debug_writing_mode, self.inline, self.block) } } @@ -240,9 +241,11 @@ impl<T: Copy> LogicalSize<T> { } } -impl<T: Add<T, T>> Add<LogicalSize<T>, LogicalSize<T>> for LogicalSize<T> { +impl<T: Add<T, Output=T>> Add for LogicalSize<T> { + type Output = LogicalSize<T>; + #[inline] - fn add(&self, other: &LogicalSize<T>) -> LogicalSize<T> { + fn add(self, other: LogicalSize<T>) -> LogicalSize<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalSize { debug_writing_mode: self.debug_writing_mode, @@ -252,9 +255,11 @@ impl<T: Add<T, T>> Add<LogicalSize<T>, LogicalSize<T>> for LogicalSize<T> { } } -impl<T: Sub<T, T>> Sub<LogicalSize<T>, LogicalSize<T>> for LogicalSize<T> { +impl<T: Sub<T, Output=T>> Sub for LogicalSize<T> { + type Output = LogicalSize<T>; + #[inline] - fn sub(&self, other: &LogicalSize<T>) -> LogicalSize<T> { + fn sub(self, other: LogicalSize<T>) -> LogicalSize<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalSize { debug_writing_mode: self.debug_writing_mode, @@ -266,7 +271,7 @@ impl<T: Sub<T, T>> Sub<LogicalSize<T>, LogicalSize<T>> for LogicalSize<T> { /// A 2D point in flow-relative dimensions -#[deriving(PartialEq, Encodable, Eq, Clone, Copy)] +#[derive(PartialEq, RustcEncodable, Eq, Clone, Copy)] pub struct LogicalPoint<T> { pub i: T, /// inline-axis coordinate pub b: T, /// block-axis coordinate @@ -275,7 +280,7 @@ pub struct LogicalPoint<T> { impl<T: Show> Show for LogicalPoint<T> { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { - write!(formatter, "LogicalPoint({} (i{}, b{}))", + write!(formatter, "LogicalPoint({:?} (i{:?}, b{:?}))", self.debug_writing_mode, self.i, self.b) } } @@ -303,7 +308,7 @@ impl<T: Copy> LogicalPoint<T> { } } -impl<T: Copy + Sub<T, T>> LogicalPoint<T> { +impl<T: Copy + Sub<T, Output=T>> LogicalPoint<T> { #[inline] pub fn from_physical(mode: WritingMode, point: Point2D<T>, container_size: Size2D<T>) -> LogicalPoint<T> { @@ -391,7 +396,7 @@ impl<T: Copy + Sub<T, T>> LogicalPoint<T> { } } -impl<T: Add<T,T>> LogicalPoint<T> { +impl<T: Copy + Add<T, Output=T>> LogicalPoint<T> { /// This doesn’t really makes sense, /// but happens when dealing with multiple origins. #[inline] @@ -405,9 +410,11 @@ impl<T: Add<T,T>> LogicalPoint<T> { } } -impl<T: Add<T,T>> Add<LogicalSize<T>, LogicalPoint<T>> for LogicalPoint<T> { +impl<T: Copy + Add<T,Output=T>> Add<LogicalSize<T>> for LogicalPoint<T> { + type Output = LogicalPoint<T>; + #[inline] - fn add(&self, other: &LogicalSize<T>) -> LogicalPoint<T> { + fn add(self, other: LogicalSize<T>) -> LogicalPoint<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalPoint { debug_writing_mode: self.debug_writing_mode, @@ -417,9 +424,11 @@ impl<T: Add<T,T>> Add<LogicalSize<T>, LogicalPoint<T>> for LogicalPoint<T> { } } -impl<T: Sub<T,T>> Sub<LogicalSize<T>, LogicalPoint<T>> for LogicalPoint<T> { +impl<T: Copy + Sub<T,Output=T>> Sub<LogicalSize<T>> for LogicalPoint<T> { + type Output = LogicalPoint<T>; + #[inline] - fn sub(&self, other: &LogicalSize<T>) -> LogicalPoint<T> { + fn sub(self, other: LogicalSize<T>) -> LogicalPoint<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalPoint { debug_writing_mode: self.debug_writing_mode, @@ -434,7 +443,7 @@ impl<T: Sub<T,T>> Sub<LogicalSize<T>, LogicalPoint<T>> for LogicalPoint<T> { /// Represents the four sides of the margins, borders, or padding of a CSS box, /// or a combination of those. /// A positive "margin" can be added to a rectangle to obtain a bigger rectangle. -#[deriving(Encodable, PartialEq, Eq, Clone, Copy)] +#[derive(RustcEncodable, PartialEq, Eq, Clone, Copy)] pub struct LogicalMargin<T> { pub block_start: T, pub inline_end: T, @@ -446,7 +455,7 @@ pub struct LogicalMargin<T> { impl<T: Show> Show for LogicalMargin<T> { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { write!(formatter, - "LogicalMargin({}, inline: {}..{} block: {}..{})", + "LogicalMargin({:?}, inline: {:?}..{:?} block: {:?}..{:?})", self.debug_writing_mode, self.inline_start, self.inline_end, @@ -656,7 +665,7 @@ impl<T: PartialEq + Zero> LogicalMargin<T> { } } -impl<T: Add<T, T>> LogicalMargin<T> { +impl<T: Copy + Add<T, Output=T>> LogicalMargin<T> { #[inline] pub fn inline_start_end(&self) -> T { self.inline_start + self.inline_end @@ -688,9 +697,11 @@ impl<T: Add<T, T>> LogicalMargin<T> { } } -impl<T: Add<T, T>> Add<LogicalMargin<T>, LogicalMargin<T>> for LogicalMargin<T> { +impl<T: Add<T, Output=T>> Add for LogicalMargin<T> { + type Output = LogicalMargin<T>; + #[inline] - fn add(&self, other: &LogicalMargin<T>) -> LogicalMargin<T> { + fn add(self, other: LogicalMargin<T>) -> LogicalMargin<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalMargin { debug_writing_mode: self.debug_writing_mode, @@ -702,9 +713,11 @@ impl<T: Add<T, T>> Add<LogicalMargin<T>, LogicalMargin<T>> for LogicalMargin<T> } } -impl<T: Sub<T, T>> Sub<LogicalMargin<T>, LogicalMargin<T>> for LogicalMargin<T> { +impl<T: Sub<T, Output=T>> Sub for LogicalMargin<T> { + type Output = LogicalMargin<T>; + #[inline] - fn sub(&self, other: &LogicalMargin<T>) -> LogicalMargin<T> { + fn sub(self, other: LogicalMargin<T>) -> LogicalMargin<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalMargin { debug_writing_mode: self.debug_writing_mode, @@ -718,7 +731,7 @@ impl<T: Sub<T, T>> Sub<LogicalMargin<T>, LogicalMargin<T>> for LogicalMargin<T> /// A rectangle in flow-relative dimensions -#[deriving(Encodable, PartialEq, Eq, Clone, Copy)] +#[derive(RustcEncodable, PartialEq, Eq, Clone, Copy)] pub struct LogicalRect<T> { pub start: LogicalPoint<T>, pub size: LogicalSize<T>, @@ -728,7 +741,7 @@ pub struct LogicalRect<T> { impl<T: Show> Show for LogicalRect<T> { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { write!(formatter, - "LogicalRect({}, i{}×b{}, @ (i{},b{}))", + "LogicalRect({:?}, i{:?}×b{:?}, @ (i{:?},b{:?}))", self.debug_writing_mode, self.size.inline, self.size.block, @@ -772,7 +785,7 @@ impl<T: Copy> LogicalRect<T> { } } -impl<T: Copy + Add<T, T> + Sub<T, T>> LogicalRect<T> { +impl<T: Copy + Add<T, Output=T> + Sub<T, Output=T>> LogicalRect<T> { #[inline] pub fn from_physical(mode: WritingMode, rect: Rect<T>, container_size: Size2D<T>) -> LogicalRect<T> { @@ -881,7 +894,7 @@ impl<T: Copy + Add<T, T> + Sub<T, T>> LogicalRect<T> { } } -impl<T: Copy + Ord + Add<T, T> + Sub<T, T>> LogicalRect<T> { +impl<T: Copy + Ord + Add<T, Output=T> + Sub<T, Output=T>> LogicalRect<T> { #[inline] pub fn union(&self, other: &LogicalRect<T>) -> LogicalRect<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); @@ -904,9 +917,11 @@ impl<T: Copy + Ord + Add<T, T> + Sub<T, T>> LogicalRect<T> { } } -impl<T: Add<T, T> + Sub<T, T>> Add<LogicalMargin<T>, LogicalRect<T>> for LogicalRect<T> { +impl<T: Copy + Add<T, Output=T> + Sub<T, Output=T>> Add<LogicalMargin<T>> for LogicalRect<T> { + type Output = LogicalRect<T>; + #[inline] - fn add(&self, other: &LogicalMargin<T>) -> LogicalRect<T> { + fn add(self, other: LogicalMargin<T>) -> LogicalRect<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalRect { start: LogicalPoint { @@ -927,9 +942,11 @@ impl<T: Add<T, T> + Sub<T, T>> Add<LogicalMargin<T>, LogicalRect<T>> for Logical } -impl<T: Add<T, T> + Sub<T, T>> Sub<LogicalMargin<T>, LogicalRect<T>> for LogicalRect<T> { +impl<T: Copy + Add<T, Output=T> + Sub<T, Output=T>> Sub<LogicalMargin<T>> for LogicalRect<T> { + type Output = LogicalRect<T>; + #[inline] - fn sub(&self, other: &LogicalMargin<T>) -> LogicalRect<T> { + fn sub(self, other: LogicalMargin<T>) -> LogicalRect<T> { self.debug_writing_mode.check_debug(other.debug_writing_mode); LogicalRect { start: LogicalPoint { @@ -950,7 +967,7 @@ impl<T: Add<T, T> + Sub<T, T>> Sub<LogicalMargin<T>, LogicalRect<T>> for Logical } #[cfg(test)] -fn modes() -> [WritingMode, ..10] { +fn modes() -> [WritingMode; 10] { [ WritingMode::empty(), FLAG_VERTICAL, diff --git a/components/util/memory.rs b/components/util/memory.rs index 278a5a448fb..5e3033e2aa5 100644 --- a/components/util/memory.rs +++ b/components/util/memory.rs @@ -6,13 +6,16 @@ use libc::{c_char,c_int,c_void,size_t}; use std::borrow::ToOwned; +use std::ffi::CString; use std::io::timer::sleep; #[cfg(target_os="linux")] use std::io::File; +use std::mem; use std::mem::size_of; #[cfg(target_os="linux")] use std::os::page_size; use std::ptr::null_mut; +use std::sync::mpsc::{Sender, channel, Receiver}; use std::time::duration::Duration; use task::spawn_named; #[cfg(target_os="macos")] @@ -45,16 +48,16 @@ impl MemoryProfiler { Some(period) => { let period = Duration::milliseconds((period * 1000f64) as i64); let chan = chan.clone(); - spawn_named("Memory profiler timer".to_owned(), proc() { + spawn_named("Memory profiler timer".to_owned(), move || { loop { sleep(period); - if chan.send_opt(MemoryProfilerMsg::Print).is_err() { + if chan.send(MemoryProfilerMsg::Print).is_err() { break; } } }); // Spawn the memory profiler. - spawn_named("Memory profiler".to_owned(), proc() { + spawn_named("Memory profiler".to_owned(), move || { let memory_profiler = MemoryProfiler::new(port); memory_profiler.start(); }); @@ -62,9 +65,9 @@ impl MemoryProfiler { None => { // No-op to handle messages when the memory profiler is // inactive. - spawn_named("Memory profiler".to_owned(), proc() { + spawn_named("Memory profiler".to_owned(), move || { loop { - match port.recv_opt() { + match port.recv() { Err(_) | Ok(MemoryProfilerMsg::Exit) => break, _ => {} } @@ -84,7 +87,7 @@ impl MemoryProfiler { pub fn start(&self) { loop { - match self.port.recv_opt() { + match self.port.recv() { Ok(msg) => { if !self.handle_msg(msg) { break @@ -151,12 +154,13 @@ extern { fn get_jemalloc_stat(name: &'static str) -> Option<u64> { let mut old: size_t = 0; - let c_name = name.to_c_str(); + let c_name = CString::from_slice(name.as_bytes()); let oldp = &mut old as *mut _ as *mut c_void; let mut oldlen = size_of::<size_t>() as size_t; let rv: c_int; unsafe { - rv = je_mallctl(c_name.into_inner(), oldp, &mut oldlen, null_mut(), 0); + rv = je_mallctl(c_name.as_ptr(), oldp, &mut oldlen, null_mut(), 0); + mem::forget(c_name); // XXX correct? } if rv == 0 { Some(old as u64) } else { None } } @@ -164,7 +168,7 @@ fn get_jemalloc_stat(name: &'static str) -> Option<u64> { // Like std::macros::try!, but for Option<>. macro_rules! option_try( ($e:expr) => (match $e { Some(e) => e, None => return None }) -) +); #[cfg(target_os="linux")] fn get_proc_self_statm_field(field: uint) -> Option<u64> { @@ -172,7 +176,7 @@ fn get_proc_self_statm_field(field: uint) -> Option<u64> { match f.read_to_string() { Ok(contents) => { let s = option_try!(contents.as_slice().words().nth(field)); - let npages: u64 = option_try!(from_str(s)); + let npages: u64 = option_try!(s.parse()); Some(npages * (page_size() as u64)) } Err(_) => None diff --git a/components/util/opts.rs b/components/util/opts.rs index 1ed2eae0608..ae19723b975 100644 --- a/components/util/opts.rs +++ b/components/util/opts.rs @@ -20,7 +20,7 @@ use std::ptr; use std::rt; /// Global flags for Servo, currently set on the command line. -#[deriving(Clone)] +#[derive(Clone)] pub struct Opts { /// The initial URLs to load. pub urls: Vec<String>, @@ -241,31 +241,31 @@ pub fn from_cmdline_args(args: &[String]) -> bool { }; let tile_size: uint = match opt_match.opt_str("s") { - Some(tile_size_str) => from_str(tile_size_str.as_slice()).unwrap(), + Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| - ScaleFactor(from_str(dppx_str.as_slice()).unwrap()) + ScaleFactor(dppx_str.parse().unwrap()) ); let mut n_paint_threads: uint = match opt_match.opt_str("t") { - Some(n_paint_threads_str) => from_str(n_paint_threads_str.as_slice()).unwrap(), + Some(n_paint_threads_str) => n_paint_threads_str.parse().unwrap(), None => 1, // FIXME: Number of cores. }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { - from_str(period.as_slice()).unwrap() + period.parse().unwrap() }); let memory_profiler_period = opt_match.opt_default("m", "5").map(|period| { - from_str(period.as_slice()).unwrap() + period.parse().unwrap() }); let gpu_painting = !FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: uint = match opt_match.opt_str("y") { - Some(layout_threads_str) => from_str(layout_threads_str.as_slice()).unwrap(), + Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; @@ -280,12 +280,12 @@ pub fn from_cmdline_args(args: &[String]) -> bool { } let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { - from_str(port.as_slice()).unwrap() + port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { - let res: Vec<uint> = res_string.as_slice().split('x').map(|r| from_str(r).unwrap()).collect(); + let res: Vec<uint> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); TypedSize2D(res[0], res[1]) } None => { diff --git a/components/util/persistent_list.rs b/components/util/persistent_list.rs index 458c4c96a2a..f20edff3d38 100644 --- a/components/util/persistent_list.rs +++ b/components/util/persistent_list.rs @@ -74,7 +74,9 @@ pub struct PersistentListIterator<'a,T> where T: 'a + Send + Sync { entry: Option<&'a PersistentListEntry<T>>, } -impl<'a,T> Iterator<&'a T> for PersistentListIterator<'a,T> where T: Send + Sync { +impl<'a,T> Iterator for PersistentListIterator<'a,T> where T: Send + Sync { + type Item = &'a T; + #[inline] fn next(&mut self) -> Option<&'a T> { let entry = match self.entry { diff --git a/components/util/range.rs b/components/util/range.rs index ef6e7e0ff47..fbf14f38400 100644 --- a/components/util/range.rs +++ b/components/util/range.rs @@ -26,7 +26,7 @@ impl RangeIndex<int> for int { #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self:ident($T:ty)) => ( - #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show, Copy)] + #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Show, Copy)] $(#[$attr])* pub struct $Self(pub $T); @@ -74,40 +74,42 @@ macro_rules! int_range_index { } } - impl Add<$Self, $Self> for $Self { + impl Add<$Self> for $Self { + type Output = $Self; + #[inline] - fn add(&self, other: &$Self) -> $Self { + fn add(self, other: $Self) -> $Self { $Self(self.get() + other.get()) } } - impl Sub<$Self, $Self> for $Self { + impl Sub<$Self> for $Self { + type Output = $Self; + #[inline] - fn sub(&self, other: &$Self) -> $Self { + fn sub(self, other: $Self) -> $Self { $Self(self.get() - other.get()) } } - impl Mul<$Self, $Self> for $Self { + impl Mul<$Self> for $Self { + type Output = $Self; + #[inline] - fn mul(&self, other: &$Self) -> $Self { + fn mul(self, other: $Self) -> $Self { $Self(self.get() * other.get()) } } - impl Neg<$Self> for $Self { + impl Neg for $Self { + type Output = $Self; + #[inline] - fn neg(&self) -> $Self { + fn neg(self) -> $Self { $Self(-self.get()) } } - impl ::std::num::One for $Self { - fn one() -> $Self { - $Self(1) - } - } - impl ToPrimitive for $Self { fn to_i64(&self) -> Option<i64> { Some(self.get() as i64) @@ -124,66 +126,75 @@ macro_rules! int_range_index { } } - impl Div<$Self, $Self> for $Self { - fn div(&self, other: &$Self) -> $Self { + impl Div<$Self> for $Self { + type Output = $Self; + fn div(self, other: $Self) -> $Self { $Self(self.get() / other.get()) } } - impl Rem<$Self, $Self> for $Self { - fn rem(&self, other: &$Self) -> $Self { + impl Rem<$Self> for $Self { + type Output = $Self; + fn rem(self, other: $Self) -> $Self { $Self(self.get() % other.get()) } } - impl Not<$Self> for $Self { - fn not(&self) -> $Self { + impl Not for $Self { + type Output = $Self; + fn not(self) -> $Self { $Self(!self.get()) } } - impl BitAnd<$Self, $Self> for $Self { - fn bitand(&self, other: &$Self) -> $Self { + impl BitAnd<$Self> for $Self { + type Output = $Self; + fn bitand(self, other: $Self) -> $Self { $Self(self.get() & other.get()) } } - impl BitOr<$Self, $Self> for $Self { - fn bitor(&self, other: &$Self) -> $Self { + impl BitOr<$Self> for $Self { + type Output = $Self; + fn bitor(self, other: $Self) -> $Self { $Self(self.get() | other.get()) } } - impl BitXor<$Self, $Self> for $Self { - fn bitxor(&self, other: &$Self) -> $Self { + impl BitXor<$Self> for $Self { + type Output = $Self; + fn bitxor(self, other: $Self) -> $Self { $Self(self.get() ^ other.get()) } } - impl Shl<uint, $Self> for $Self { - fn shl(&self, n: &uint) -> $Self { - $Self(self.get() << *n) + impl Shl<uint> for $Self { + type Output = $Self; + fn shl(self, n: uint) -> $Self { + $Self(self.get() << n) } } - impl Shr<uint, $Self> for $Self { - fn shr(&self, n: &uint) -> $Self { - $Self(self.get() >> *n) + impl Shr<uint> for $Self { + type Output = $Self; + fn shr(self, n: uint) -> $Self { + $Self(self.get() >> n) } } ) } /// A range of indices -#[deriving(Clone, Encodable, Copy)] +#[derive(Clone, RustcEncodable, Copy)] pub struct Range<I> { begin: I, length: I, } +#[old_impl_check] impl<I: RangeIndex<T>, T> fmt::Show for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "[{} .. {})", self.begin(), self.end()) + write!(f, "[{:?} .. {:?})", self.begin(), self.end()) } } @@ -196,7 +207,9 @@ pub fn each_index<T: Int, I: RangeIndex<T>>(start: I, stop: I) -> EachIndex<T, I EachIndex { it: iter::range(start.get(), stop.get()) } } -impl<T: Int, I: RangeIndex<T>> Iterator<I> for EachIndex<T, I> { +impl<T: Int, I: RangeIndex<T>> Iterator for EachIndex<T, I> { + type Item = I; + #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(|i| RangeIndex::new(i)) @@ -208,6 +221,7 @@ impl<T: Int, I: RangeIndex<T>> Iterator<I> for EachIndex<T, I> { } } +#[old_impl_check] impl<I: RangeIndex<T>, T> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. @@ -345,6 +359,7 @@ impl<I: RangeIndex<T>, T> Range<I> { } /// Methods for `Range`s with indices based on integer values +#[old_impl_check] impl<T: Int, I: RangeIndex<T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] @@ -363,8 +378,9 @@ impl<T: Int, I: RangeIndex<T>> Range<I> { && self.length() <= len }, None => { - debug!("Range<T>::is_valid_for_string: string length (len={}) is longer than the \ - max value for the range index (max={})", s_len, + debug!("Range<T>::is_valid_for_string: string length \ + (len={:?}) is longer than the max value for the range \ + index (max={:?})", s_len, { let max: T = Int::max_value(); let val: I = RangeIndex::new(max); diff --git a/components/util/smallvec.rs b/components/util/smallvec.rs index 2153398d3c3..efd1bfc7f35 100644 --- a/components/util/smallvec.rs +++ b/components/util/smallvec.rs @@ -9,7 +9,8 @@ use std::mem::zeroed as i; use std::cmp; use std::fmt; use std::intrinsics; -use std::kinds::marker::ContravariantLifetime; +use std::iter::FromIterator; +use std::marker::ContravariantLifetime; use std::mem; use std::ptr; use std::raw::Slice; @@ -249,7 +250,9 @@ pub struct SmallVecIterator<'a,T> { lifetime: ContravariantLifetime<'a> } -impl<'a,T> Iterator<&'a T> for SmallVecIterator<'a,T> { +impl<'a,T> Iterator for SmallVecIterator<'a,T> { + type Item = &'a T; + #[inline] fn next(&mut self) -> Option<&'a T> { unsafe { @@ -273,7 +276,9 @@ pub struct SmallVecMutIterator<'a,T> { lifetime: ContravariantLifetime<'a>, } -impl<'a,T> Iterator<&'a mut T> for SmallVecMutIterator<'a,T> { +impl<'a,T> Iterator for SmallVecMutIterator<'a,T> { + type Item = &'a mut T; + #[inline] fn next(&mut self) -> Option<&'a mut T> { unsafe { @@ -298,7 +303,9 @@ pub struct SmallVecMoveIterator<'a,T> { lifetime: ContravariantLifetime<'a>, } -impl<'a, T: 'a> Iterator<T> for SmallVecMoveIterator<'a,T> { +impl<'a, T: 'a> Iterator for SmallVecMoveIterator<'a,T> { + type Item = T; + #[inline] fn next(&mut self) -> Option<T> { unsafe { @@ -341,7 +348,7 @@ macro_rules! def_small_vector( len: uint, cap: uint, ptr: *const T, - data: [T, ..$size], + data: [T; $size], } impl<T> SmallVecPrivate<T> for $name<T> { @@ -403,7 +410,7 @@ macro_rules! def_small_vector( } impl<T> FromIterator<T> for $name<T> { - fn from_iter<I: Iterator<T>>(mut iter: I) -> $name<T> { + fn from_iter<I: Iterator<Item=T>>(mut iter: I) -> $name<T> { let mut v = $name::new(); let (lower_size_bound, _) = iter.size_hint(); @@ -421,7 +428,7 @@ macro_rules! def_small_vector( } impl<T> $name<T> { - pub fn extend<I: Iterator<T>>(&mut self, mut iter: I) { + pub fn extend<I: Iterator<Item=T>>(&mut self, mut iter: I) { let (lower_size_bound, _) = iter.size_hint(); let target_len = self.len() + lower_size_bound; @@ -438,7 +445,7 @@ macro_rules! def_small_vector( impl<T: fmt::Show> fmt::Show for $name<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.as_slice()) + write!(f, "{:?}", self.as_slice()) } } @@ -456,15 +463,15 @@ macro_rules! def_small_vector( } } ) -) +); -def_small_vector!(SmallVec1, 1) -def_small_vector!(SmallVec2, 2) -def_small_vector!(SmallVec4, 4) -def_small_vector!(SmallVec8, 8) -def_small_vector!(SmallVec16, 16) -def_small_vector!(SmallVec24, 24) -def_small_vector!(SmallVec32, 32) +def_small_vector!(SmallVec1, 1); +def_small_vector!(SmallVec2, 2); +def_small_vector!(SmallVec4, 4); +def_small_vector!(SmallVec8, 8); +def_small_vector!(SmallVec16, 16); +def_small_vector!(SmallVec24, 24); +def_small_vector!(SmallVec32, 32); macro_rules! def_small_vector_drop_impl( ($name:ident, $size:expr) => ( @@ -488,15 +495,15 @@ macro_rules! def_small_vector_drop_impl( } } ) -) +); -def_small_vector_drop_impl!(SmallVec1, 1) -def_small_vector_drop_impl!(SmallVec2, 2) -def_small_vector_drop_impl!(SmallVec4, 4) -def_small_vector_drop_impl!(SmallVec8, 8) -def_small_vector_drop_impl!(SmallVec16, 16) -def_small_vector_drop_impl!(SmallVec24, 24) -def_small_vector_drop_impl!(SmallVec32, 32) +def_small_vector_drop_impl!(SmallVec1, 1); +def_small_vector_drop_impl!(SmallVec2, 2); +def_small_vector_drop_impl!(SmallVec4, 4); +def_small_vector_drop_impl!(SmallVec8, 8); +def_small_vector_drop_impl!(SmallVec16, 16); +def_small_vector_drop_impl!(SmallVec24, 24); +def_small_vector_drop_impl!(SmallVec32, 32); macro_rules! def_small_vector_clone_impl( ($name:ident) => ( @@ -510,15 +517,15 @@ macro_rules! def_small_vector_clone_impl( } } ) -) - -def_small_vector_clone_impl!(SmallVec1) -def_small_vector_clone_impl!(SmallVec2) -def_small_vector_clone_impl!(SmallVec4) -def_small_vector_clone_impl!(SmallVec8) -def_small_vector_clone_impl!(SmallVec16) -def_small_vector_clone_impl!(SmallVec24) -def_small_vector_clone_impl!(SmallVec32) +); + +def_small_vector_clone_impl!(SmallVec1); +def_small_vector_clone_impl!(SmallVec2); +def_small_vector_clone_impl!(SmallVec4); +def_small_vector_clone_impl!(SmallVec8); +def_small_vector_clone_impl!(SmallVec16); +def_small_vector_clone_impl!(SmallVec24); +def_small_vector_clone_impl!(SmallVec32); #[cfg(test)] pub mod tests { diff --git a/components/util/sort.rs b/components/util/sort.rs index d31948cb0e8..ce7ab4d86c9 100644 --- a/components/util/sort.rs +++ b/components/util/sort.rs @@ -81,6 +81,7 @@ pub fn quicksort_by<T>(arr: &mut [T], compare: fn(&T, &T) -> Ordering) { #[cfg(test)] pub mod test { + use std::cmp::Ordering; use std::rand; use std::rand::Rng; @@ -88,7 +89,7 @@ pub mod test { #[test] pub fn random() { - let mut rng = rand::task_rng(); + let mut rng = rand::thread_rng(); for _ in range(0u32, 50000u32) { let len: uint = rng.gen(); let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collect(); diff --git a/components/util/str.rs b/components/util/str.rs index db5a6328cdb..352876919d4 100644 --- a/components/util/str.rs +++ b/components/util/str.rs @@ -5,12 +5,14 @@ use geometry::Au; use cssparser::{mod, RGBA, Color}; + +use libc::c_char; use std::ascii::AsciiExt; use std::borrow::ToOwned; +use std::ffi::c_str_to_bytes; use std::iter::Filter; -use std::num::Int; -use std::str::{CharEq, CharSplits, FromStr}; -use unicode::char::UnicodeChar; +use std::num::{Int, ToPrimitive}; +use std::str::{from_utf8, CharEq, FromStr, Split}; pub type DOMString = String; pub type StaticCharVec = &'static [char]; @@ -65,15 +67,16 @@ pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{000d}', ]; -pub fn split_html_space_chars<'a>(s: &'a str) - -> Filter<'a, &'a str, CharSplits<'a, StaticCharVec>> { - s.split(HTML_SPACE_CHARACTERS).filter(|&split| !split.is_empty()) +pub fn split_html_space_chars<'a>(s: &'a str) -> + Filter<&'a str, Split<'a, StaticCharVec>, fn(&&str) -> bool> { + fn not_empty(&split: &&str) -> bool { !split.is_empty() } + s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } /// Shared implementation to parse an integer according to /// <http://www.whatwg.org/html/#rules-for-parsing-integers> or /// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>. -fn do_parse_integer<T: Iterator<char>>(input: T) -> Option<i64> { +fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, @@ -118,7 +121,7 @@ fn do_parse_integer<T: Iterator<char>>(input: T) -> Option<i64> { /// Parse an integer according to /// <http://www.whatwg.org/html/#rules-for-parsing-integers>. -pub fn parse_integer<T: Iterator<char>>(input: T) -> Option<i32> { +pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) @@ -126,13 +129,13 @@ pub fn parse_integer<T: Iterator<char>>(input: T) -> Option<i32> { /// Parse an integer according to /// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>. -pub fn parse_unsigned_integer<T: Iterator<char>>(input: T) -> Option<u32> { +pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> { do_parse_integer(input).and_then(|result| { result.to_u32() }) } -#[deriving(Copy)] +#[derive(Copy)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f64), @@ -141,14 +144,14 @@ pub enum LengthOrPercentageOrAuto { /// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned. pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { - value = value.trim_left_chars(Whitespace); + value = value.trim_left_matches(Whitespace); if value.len() == 0 { return LengthOrPercentageOrAuto::Auto } if value.starts_with("+") { value = value.slice_from(1) } - value = value.trim_left_chars('0'); + value = value.trim_left_matches('0'); if value.len() == 0 { return LengthOrPercentageOrAuto::Auto } @@ -197,7 +200,7 @@ pub fn parse_legacy_color(mut input: &str) -> Result<RGBA,()> { } // Step 3. - input = input.trim_left_chars(Whitespace).trim_right_chars(Whitespace); + input = input.trim_left_matches(Whitespace).trim_right_matches(Whitespace); // Step 4. if input.eq_ignore_ascii_case("transparent") { @@ -321,7 +324,7 @@ pub fn parse_legacy_color(mut input: &str) -> Result<RGBA,()> { } -#[deriving(Clone, Eq, PartialEq, Hash, Show)] +#[derive(Clone, Eq, PartialEq, Hash, Show)] pub struct LowercaseString { inner: String, } @@ -340,3 +343,9 @@ impl Str for LowercaseString { self.inner.as_slice() } } + +/// Creates a String from the given null-terminated buffer. +/// Panics if the buffer does not contain UTF-8. +pub unsafe fn c_str_to_string(s: *const c_char) -> String { + from_utf8(c_str_to_bytes(&s)).unwrap().to_owned() +} diff --git a/components/util/task.rs b/components/util/task.rs index 44c2ff284dc..2045d0c3e83 100644 --- a/components/util/task.rs +++ b/components/util/task.rs @@ -3,33 +3,37 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::ToOwned; -use std::task; -use std::comm::Sender; -use std::task::TaskBuilder; use task_state; +use std::thread; +use std::sync::mpsc::Sender; +use std::thread::Builder; -pub fn spawn_named(name: String, f: proc():Send) { - let builder = task::TaskBuilder::new().named(name); - builder.spawn(proc() { - f(); +pub fn spawn_named<F>(name: String, f: F) + where F: FnOnce() + Send +{ + let builder = thread::Builder::new().name(name); + builder.spawn(move || { + f() }); } /// Arrange to send a particular message to a channel if the task fails. -pub fn spawn_named_with_send_on_failure<T: Send>(name: &'static str, - state: task_state::TaskState, - f: proc(): Send, - msg: T, - dest: Sender<T>) { - let future_result = TaskBuilder::new().named(name).try_future(proc() { +pub fn spawn_named_with_send_on_failure<F, T>(name: &'static str, + state: task_state::TaskState, + f: F, + msg: T, + dest: Sender<T>) + where F: FnOnce() + Send, + T: Send +{ + let future_handle = thread::Builder::new().name(name.to_owned()).scoped(move || { task_state::initialize(state); - f(); + f() }); - let watched_name = name.to_owned(); - let watcher_name = format!("{}Watcher", watched_name); - TaskBuilder::new().named(watcher_name).spawn(proc() { - match future_result.into_inner() { + let watcher_name = format!("{}Watcher", name); + Builder::new().name(watcher_name).spawn(move || { + match future_handle.join() { Ok(()) => (), Err(..) => { debug!("{} failed, notifying constellation", name); @@ -38,3 +42,10 @@ pub fn spawn_named_with_send_on_failure<T: Send>(name: &'static str, } }); } + +#[test] +fn spawn_named_test() { + spawn_named("Test".to_owned(), move || { + debug!("I can run!"); + }); +} diff --git a/components/util/task_state.rs b/components/util/task_state.rs index 3915eeb3059..ef1dbb2ed3e 100644 --- a/components/util/task_state.rs +++ b/components/util/task_state.rs @@ -11,7 +11,7 @@ pub use self::imp::{initialize, get, enter, exit}; bitflags! { - #[deriving(Show, Copy)] + #[derive(Show)] flags TaskState: u32 { const SCRIPT = 0x01, const LAYOUT = 0x02, @@ -35,7 +35,7 @@ macro_rules! task_types ( ( $( $fun:ident = $flag:ident ; )* ) => ( #[cfg(not(ndebug))] static TYPES: &'static [TaskState] = &[ $( $flag ),* ]; -)) +)); task_types! { is_script = SCRIPT; @@ -48,12 +48,12 @@ mod imp { use super::{TaskState, TYPES}; use std::cell::RefCell; - thread_local!(static STATE: RefCell<Option<TaskState>> = RefCell::new(None)) + thread_local!(static STATE: RefCell<Option<TaskState>> = RefCell::new(None)); pub fn initialize(x: TaskState) { STATE.with(|ref k| { match *k.borrow() { - Some(s) => panic!("Task state already initialized as {}", s), + Some(s) => panic!("Task state already initialized as {:?}", s), None => () }; *k.borrow_mut() = Some(x); diff --git a/components/util/taskpool.rs b/components/util/taskpool.rs index 8521ef9dc93..7f2d36be936 100644 --- a/components/util/taskpool.rs +++ b/components/util/taskpool.rs @@ -17,9 +17,11 @@ use task::spawn_named; use std::sync::{Arc, Mutex}; +use std::sync::mpsc::{channel, Sender, Receiver}; +use std::thunk::Thunk; pub struct TaskPool { - tx: Sender<proc():Send>, + tx: Sender<Thunk<()>>, } impl TaskPool { @@ -33,23 +35,25 @@ impl TaskPool { let state = state.clone(); spawn_named( format!("TaskPoolWorker {}/{}", i+1, tasks), - proc() worker(&*state)); + move || worker(&*state)); } return TaskPool { tx: tx }; - fn worker(rx: &Mutex<Receiver<proc():Send>>) { + fn worker(rx: &Mutex<Receiver<Thunk<()>>>) { loop { - let job = rx.lock().recv_opt(); + let job = rx.lock().unwrap().recv(); match job { - Ok(job) => job(), + Ok(job) => job.invoke(()), Err(..) => break, } } } } - pub fn execute(&self, job: proc():Send) { - self.tx.send(job); + pub fn execute<F>(&self, job: F) + where F: FnOnce() + Send + { + self.tx.send(Thunk::new(job)); } } diff --git a/components/util/tid.rs b/components/util/tid.rs index 62723941fcb..e52dbf7fd61 100644 --- a/components/util/tid.rs +++ b/components/util/tid.rs @@ -2,13 +2,13 @@ * 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 std::sync::atomic::{AtomicUint, INIT_ATOMIC_UINT, Ordering}; +use std::sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering}; use std::rc::Rc; use std::cell::RefCell; -static mut next_tid: AtomicUint = INIT_ATOMIC_UINT; +static mut next_tid: AtomicUint = ATOMIC_UINT_INIT; -thread_local!(static TASK_LOCAL_TID: Rc<RefCell<Option<uint>>> = Rc::new(RefCell::new(None))) +thread_local!(static TASK_LOCAL_TID: Rc<RefCell<Option<uint>>> = Rc::new(RefCell::new(None))); /// Every task gets one, that's unique. pub fn tid() -> uint { diff --git a/components/util/time.rs b/components/util/time.rs index a47f3a98c8c..b5805dfa092 100644 --- a/components/util/time.rs +++ b/components/util/time.rs @@ -4,21 +4,21 @@ //! Timing functions. -use collections::TreeMap; +use collections::BTreeMap; use std::borrow::ToOwned; use std::cmp::Ordering; -use std::comm::{Sender, channel, Receiver}; use std::f64; use std::io::timer::sleep; use std::iter::AdditiveIterator; -use std::num::FloatMath; +use std::num::Float; +use std::sync::mpsc::{Sender, channel, Receiver}; use std::time::duration::Duration; use std_time::precise_time_ns; use task::{spawn_named}; use url::Url; // front-end representation of the profiler used to communicate with the profiler -#[deriving(Clone)] +#[derive(Clone)] pub struct TimeProfilerChan(pub Sender<TimeProfilerMsg>); impl TimeProfilerChan { @@ -28,7 +28,7 @@ impl TimeProfilerChan { } } -#[deriving(PartialEq, Clone, PartialOrd, Eq, Ord)] +#[derive(PartialEq, Clone, PartialOrd, Eq, Ord)] pub struct TimerMetadata { url: String, iframe: bool, @@ -60,7 +60,7 @@ impl Formatable for Option<TimerMetadata> { } } -#[deriving(Clone)] +#[derive(Clone)] pub enum TimeProfilerMsg { /// Normal message used for reporting time Time((TimeProfilerCategory, Option<TimerMetadata>), f64), @@ -71,7 +71,7 @@ pub enum TimeProfilerMsg { } #[repr(u32)] -#[deriving(PartialEq, Clone, PartialOrd, Eq, Ord)] +#[derive(PartialEq, Clone, PartialOrd, Eq, Ord)] pub enum TimeProfilerCategory { Compositing, LayoutPerform, @@ -130,7 +130,7 @@ impl Formatable for TimeProfilerCategory { } } -type TimeProfilerBuckets = TreeMap<(TimeProfilerCategory, Option<TimerMetadata>), Vec<f64>>; +type TimeProfilerBuckets = BTreeMap<(TimeProfilerCategory, Option<TimerMetadata>), Vec<f64>>; // back end of the profiler that handles data aggregation and performance metrics pub struct TimeProfiler { @@ -146,25 +146,25 @@ impl TimeProfiler { Some(period) => { let period = Duration::milliseconds((period * 1000f64) as i64); let chan = chan.clone(); - spawn_named("Time profiler timer".to_owned(), proc() { + spawn_named("Time profiler timer".to_owned(), move || { loop { sleep(period); - if chan.send_opt(TimeProfilerMsg::Print).is_err() { + if chan.send(TimeProfilerMsg::Print).is_err() { break; } } }); // Spawn the time profiler. - spawn_named("Time profiler".to_owned(), proc() { + spawn_named("Time profiler".to_owned(), move || { let mut profiler = TimeProfiler::new(port); profiler.start(); }); } None => { // No-op to handle messages when the time profiler is inactive. - spawn_named("Time profiler".to_owned(), proc() { + spawn_named("Time profiler".to_owned(), move || { loop { - match port.recv_opt() { + match port.recv() { Err(_) | Ok(TimeProfilerMsg::Exit) => break, _ => {} } @@ -179,14 +179,14 @@ impl TimeProfiler { pub fn new(port: Receiver<TimeProfilerMsg>) -> TimeProfiler { TimeProfiler { port: port, - buckets: TreeMap::new(), + buckets: BTreeMap::new(), last_msg: None, } } pub fn start(&mut self) { loop { - let msg = self.port.recv_opt(); + let msg = self.port.recv(); match msg { Ok(msg) => { if !self.handle_msg(msg) { @@ -249,13 +249,13 @@ impl TimeProfiler { } } -#[deriving(Eq, PartialEq)] +#[derive(Eq, PartialEq)] pub enum TimerMetadataFrameType { RootWindow, IFrame, } -#[deriving(Eq, PartialEq)] +#[derive(Eq, PartialEq)] pub enum TimerMetadataReflowType { Incremental, FirstReflow, @@ -263,11 +263,13 @@ pub enum TimerMetadataReflowType { pub type ProfilerMetadata<'a> = Option<(&'a Url, TimerMetadataFrameType, TimerMetadataReflowType)>; -pub fn profile<T>(category: TimeProfilerCategory, - meta: ProfilerMetadata, - time_profiler_chan: TimeProfilerChan, - callback: || -> T) - -> T { +pub fn profile<T, F>(category: TimeProfilerCategory, + meta: ProfilerMetadata, + time_profiler_chan: TimeProfilerChan, + callback: F) + -> T + where F: FnOnce() -> T +{ let start_time = precise_time_ns(); let val = callback(); let end_time = precise_time_ns(); @@ -282,7 +284,9 @@ pub fn profile<T>(category: TimeProfilerCategory, return val; } -pub fn time<T>(msg: &str, callback: || -> T) -> T{ +pub fn time<T, F>(msg: &str, callback: F) -> T + where F: Fn() -> T +{ let start_time = precise_time_ns(); let val = callback(); let end_time = precise_time_ns(); diff --git a/components/util/vec.rs b/components/util/vec.rs index c34b76a9794..a902a3133df 100644 --- a/components/util/vec.rs +++ b/components/util/vec.rs @@ -78,7 +78,7 @@ fn test_miss_all_elems<T: PartialEq + PartialOrd + Eq + Ord + Show>(arr: &[T], m let mut i = 0; while i < misses.len() { let res = arr.binary_search_(&misses[i]); - debug!("{} == {} ?", misses[i], res); + debug!("{:?} == {:?} ?", misses[i], res); assert!(!test_match(&misses[i], arr.binary_search_(&misses[i]))); i += 1; } diff --git a/components/util/workqueue.rs b/components/util/workqueue.rs index ee14a4d1a50..c83902526fd 100644 --- a/components/util/workqueue.rs +++ b/components/util/workqueue.rs @@ -15,6 +15,7 @@ use rand::{Rng, XorShiftRng}; use std::mem; use std::rand::weak_rng; use std::sync::atomic::{AtomicUint, Ordering}; +use std::sync::mpsc::{channel, Sender, Receiver}; use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; /// A unit of work. @@ -31,7 +32,7 @@ pub struct WorkUnit<QueueData, WorkData> { } /// Messages from the supervisor to the worker. -enum WorkerMsg<QueueData, WorkData> { +enum WorkerMsg<QueueData: 'static, WorkData: 'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUint, *const QueueData), /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. @@ -40,14 +41,18 @@ enum WorkerMsg<QueueData, WorkData> { Exit, } +unsafe impl<QueueData: 'static, WorkData: 'static> Send for WorkerMsg<QueueData, WorkData> {} + /// Messages to the supervisor. -enum SupervisorMsg<QueueData, WorkData> { +enum SupervisorMsg<QueueData: 'static, WorkData: 'static> { Finished, ReturnDeque(uint, Worker<WorkUnit<QueueData, WorkData>>), } +unsafe impl<QueueData: 'static, WorkData: 'static> Send for SupervisorMsg<QueueData, WorkData> {} + /// Information that the supervisor thread keeps about the worker threads. -struct WorkerInfo<QueueData, WorkData> { +struct WorkerInfo<QueueData: 'static, WorkData: 'static> { /// The communication channel to the workers. chan: Sender<WorkerMsg<QueueData, WorkData>>, /// The worker end of the deque, if we have it. @@ -57,7 +62,7 @@ struct WorkerInfo<QueueData, WorkData> { } /// Information specific to each worker thread that the thread keeps. -struct WorkerThread<QueueData, WorkData> { +struct WorkerThread<QueueData: 'static, WorkData: 'static> { /// The index of this worker. index: uint, /// The communication port from the supervisor. @@ -70,6 +75,8 @@ struct WorkerThread<QueueData, WorkData> { rng: XorShiftRng, } +unsafe impl<QueueData: 'static, WorkData: 'static> Send for WorkerThread<QueueData, WorkData> {} + static SPIN_COUNT: u32 = 128; static SPINS_UNTIL_BACKOFF: u32 = 100; static BACKOFF_INCREMENT_IN_US: u32 = 5; @@ -80,7 +87,7 @@ impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { fn start(&mut self) { loop { // Wait for a start message. - let (mut deque, ref_count, queue_data) = match self.port.recv() { + let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() { WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data), WorkerMsg::Stop => panic!("unexpected stop message"), WorkerMsg::Exit => return, @@ -158,13 +165,13 @@ impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { // the last work unit in the queue, then send a message on the channel. unsafe { if (*ref_count).fetch_sub(1, Ordering::SeqCst) == 1 { - self.chan.send(SupervisorMsg::Finished) + self.chan.send(SupervisorMsg::Finished).unwrap() } } } // Give the deque back to the supervisor. - self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)) + self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap() } } } @@ -196,7 +203,7 @@ impl<'a, QueueData: 'static, WorkData: Send> WorkerProxy<'a, QueueData, WorkData } /// A work queue on which units of work can be submitted. -pub struct WorkQueue<QueueData, WorkData> { +pub struct WorkQueue<QueueData: 'static, WorkData: 'static> { /// Information about each of the workers. workers: Vec<WorkerInfo<QueueData, WorkData>>, /// A port on which deques can be received from the workers. @@ -250,7 +257,7 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { spawn_named( format!("{} worker {}/{}", task_name, i+1, thread_count), - proc() { + move || { task_state::initialize(state | task_state::IN_WORKER); let mut thread = thread; thread.start() @@ -283,7 +290,7 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { // Tell the workers to start. let mut work_count = AtomicUint::new(self.work_count); for worker in self.workers.iter_mut() { - worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, &self.data)) + worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, &self.data)).unwrap() } // Wait for the work to finish. @@ -292,12 +299,12 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { // Tell everyone to stop. for worker in self.workers.iter() { - worker.chan.send(WorkerMsg::Stop) + worker.chan.send(WorkerMsg::Stop).unwrap() } // Get our deques back. for _ in range(0, self.workers.len()) { - match self.port.recv() { + match self.port.recv().unwrap() { SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque), SupervisorMsg::Finished => panic!("unexpected finished message!"), } @@ -306,7 +313,7 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { pub fn shutdown(&mut self) { for worker in self.workers.iter() { - worker.chan.send(WorkerMsg::Exit) + worker.chan.send(WorkerMsg::Exit).unwrap() } } } |