<commit_before>//! Details of the `metadata` section of the procedural macro.

use syn::{
    braced,
    parse::{Parse, ParseStream},
    Expr, ExprLit, ExprPath, FieldValue, Ident, Lit, LitBool, LitStr, Member, Token,
};

use crate::util;

mod kw {
    syn::custom_keyword!(metadata);
}

/// The result of processing the `metadata` section of the macro.
pub struct Metadata {
    /// The description field.
    pub description: LitStr,

    /// The method field.
    pub method: Ident,

    /// The name field.
    pub name: LitStr,

    /// The path field.
    pub path: LitStr,

    /// The rate_limited field.
    pub rate_limited: LitBool,

    /// The authentication field.
    pub authentication: Ident,
}

impl Parse for Metadata {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let metadata_kw = input.parse::<kw::metadata>()?;
        input.parse::<Token![:]>()?;
        let field_values;
        braced!(field_values in input);

        let field_values =
            field_values.parse_terminated::<FieldValue, Token![,]>(FieldValue::parse)?;

        let mut description = None;
        let mut method = None;
        let mut name = None;
        let mut path = None;
        let mut rate_limited = None;
        let mut authentication = None;

        for field_value in field_values {
            let identifier = match field_value.member.clone() {
                Member::Named(identifier) => identifier,
                _ => panic!("expected Member::Named"),
            };
            let expr = field_value.expr.clone();

            match &identifier.to_string()[..] {
                "description" => match expr {
                    Expr::Lit(ExprLit { lit: Lit::Str(literal), .. }) => {
                        description = Some(literal);
                    }
                    _ => return Err(syn::Error::new_spanned(expr, "expected a string literal")),
                },
                "method" => match expr {
                    Expr::Path(ExprPath { ref path, .. }) if path.segments.len() == 1 => {
                        method = Some(path.segments[0].ident.clone());
                    }
                    _ => return Err(syn::Error::new_spanned(expr, "expected an identifier")),
                },
                "name" => match expr {
                    Expr::Lit(ExprLit { lit: Lit::Str(literal), .. }) => {
                        name = Some(literal);
                    }
                    _ => return Err(syn::Error::new_spanned(expr, "expected a string literal")),
                },
                "path" => match expr {
                    Expr::Lit(ExprLit { lit: Lit::Str(literal), .. }) => {
                        let path_str = literal.value();
                        if !util::is_valid_endpoint_path(&path_str) {
                            return Err(syn::Error::new_spanned(
                                literal,
                                "path may only contain printable ASCII characters with no spaces",
                            ));
                        }
                        path = Some(literal);
                    }
                    _ => return Err(syn::Error::new_spanned(expr, "expected a string literal")),
                },
                "rate_limited" => match expr {
                    Expr::Lit(ExprLit { lit: Lit::Bool(literal), .. }) => {
                        rate_limited = Some(literal);
                    }
                    _ => return Err(syn::Error::new_spanned(expr, "expected a bool literal")),
                },
                "authentication" => match expr {
                    Expr::Path(ExprPath { ref path, .. }) if path.segments.len() == 1 => {
                        authentication = Some(path.segments[0].ident.clone());
                    }
                    _ => return Err(syn::Error::new_spanned(expr, "expected an identifier")),
                },
                _ => return Err(syn::Error::new_spanned(field_value, "unexpected field")),
            }
        }

        let missing_field =
            |name| syn::Error::new_spanned(metadata_kw, format!("missing field `{}`", name));

        Ok(Self {
            description: description.ok_or_else(|| missing_field("description"))?,
            method: method.ok_or_else(|| missing_field("method"))?,
            name: name.ok_or_else(|| missing_field("name"))?,
            path: path.ok_or_else(|| missing_field("path"))?,
            rate_limited: rate_limited.ok_or_else(|| missing_field("rate_limited"))?,
            authentication: authentication.ok_or_else(|| missing_field("authentication"))?,
        })
    }
}
<commit_msg>api-macros: Refactor metadata parsing<commit_after>//! Details of the `metadata` section of the procedural macro.

use quote::ToTokens;
use syn::{
    braced,
    parse::{Parse, ParseStream},
    Ident, LitBool, LitStr, Token,
};

use crate::util;

mod kw {
    syn::custom_keyword!(metadata);
    syn::custom_keyword!(description);
    syn::custom_keyword!(method);
    syn::custom_keyword!(name);
    syn::custom_keyword!(path);
    syn::custom_keyword!(rate_limited);
    syn::custom_keyword!(authentication);
}

/// The result of processing the `metadata` section of the macro.
pub struct Metadata {
    /// The description field.
    pub description: LitStr,

    /// The method field.
    pub method: Ident,

    /// The name field.
    pub name: LitStr,

    /// The path field.
    pub path: LitStr,

    /// The rate_limited field.
    pub rate_limited: LitBool,

    /// The authentication field.
    pub authentication: Ident,
}

fn set_field<T: ToTokens>(field: &mut Option<T>, value: T) -> syn::Result<()> {
    match field {
        Some(existing_value) => {
            let mut error = syn::Error::new_spanned(value, "duplicate field assignment");
            error.combine(syn::Error::new_spanned(existing_value, "first one here"));
            Err(error)
        }
        None => {
            *field = Some(value);
            Ok(())
        }
    }
}

impl Parse for Metadata {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let metadata_kw: kw::metadata = input.parse()?;
        let _: Token![:] = input.parse()?;

        let field_values;
        braced!(field_values in input);

        let field_values =
            field_values.parse_terminated::<FieldValue, Token![,]>(FieldValue::parse)?;

        let mut description = None;
        let mut method = None;
        let mut name = None;
        let mut path = None;
        let mut rate_limited = None;
        let mut authentication = None;

        for field_value in field_values {
            match field_value {
                FieldValue::Description(d) => set_field(&mut description, d)?,
                FieldValue::Method(m) => set_field(&mut method, m)?,
                FieldValue::Name(n) => set_field(&mut name, n)?,
                FieldValue::Path(p) => set_field(&mut path, p)?,
                FieldValue::RateLimited(rl) => set_field(&mut rate_limited, rl)?,
                FieldValue::Authentication(a) => set_field(&mut authentication, a)?,
            }
        }

        let missing_field =
            |name| syn::Error::new_spanned(metadata_kw, format!("missing field `{}`", name));

        Ok(Self {
            description: description.ok_or_else(|| missing_field("description"))?,
            method: method.ok_or_else(|| missing_field("method"))?,
            name: name.ok_or_else(|| missing_field("name"))?,
            path: path.ok_or_else(|| missing_field("path"))?,
            rate_limited: rate_limited.ok_or_else(|| missing_field("rate_limited"))?,
            authentication: authentication.ok_or_else(|| missing_field("authentication"))?,
        })
    }
}

enum Field {
    Description,
    Method,
    Name,
    Path,
    RateLimited,
    Authentication,
}

impl Parse for Field {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lookahead = input.lookahead1();

        if lookahead.peek(kw::description) {
            let _: kw::description = input.parse()?;
            Ok(Self::Description)
        } else if lookahead.peek(kw::method) {
            let _: kw::method = input.parse()?;
            Ok(Self::Method)
        } else if lookahead.peek(kw::name) {
            let _: kw::name = input.parse()?;
            Ok(Self::Name)
        } else if lookahead.peek(kw::path) {
            let _: kw::path = input.parse()?;
            Ok(Self::Path)
        } else if lookahead.peek(kw::rate_limited) {
            let _: kw::rate_limited = input.parse()?;
            Ok(Self::RateLimited)
        } else if lookahead.peek(kw::authentication) {
            let _: kw::authentication = input.parse()?;
            Ok(Self::Authentication)
        } else {
            Err(lookahead.error())
        }
    }
}

enum FieldValue {
    Description(LitStr),
    Method(Ident),
    Name(LitStr),
    Path(LitStr),
    RateLimited(LitBool),
    Authentication(Ident),
}

impl Parse for FieldValue {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let field: Field = input.parse()?;
        let _: Token![:] = input.parse()?;

        Ok(match field {
            Field::Description => Self::Description(input.parse()?),
            Field::Method => Self::Method(input.parse()?),
            Field::Name => Self::Name(input.parse()?),
            Field::Path => {
                let path: LitStr = input.parse()?;

                if !util::is_valid_endpoint_path(&path.value()) {
                    return Err(syn::Error::new_spanned(
                        &path,
                        "path may only contain printable ASCII characters with no spaces",
                    ));
                }

                Self::Path(path)
            }
            Field::RateLimited => Self::RateLimited(input.parse()?),
            Field::Authentication => Self::Authentication(input.parse()?),
        })
    }
}
<|endoftext|>


<commit_before>use specs::{ReadStorage, System, WriteStorage};

use crate::combat::components::intent::{XAxis, YAxis};
use crate::combat::components::{Action, Command, Facing, Intent, State, Velocity, WalkingState};

pub const X_STEP_SIZES: [[i32; 4]; 3] = [[-25, -3, -23, -4], [0, 0, 0, 0], [25, 3, 23, 4]];
pub const Y_STEP_SIZES: [[i32; 4]; 3] = [[-2, -9, -2, -9], [0, 0, 0, 0], [8, 2, 9, 2]];

pub struct VelocitySystem;

impl<'a> System<'a> for VelocitySystem {
    type SystemData = (
        ReadStorage<'a, Intent>,
        WriteStorage<'a, State>,
        WriteStorage<'a, Velocity>,
        WriteStorage<'a, WalkingState>,
    );

    fn run(&mut self, (intent, mut state, mut velocity, mut walking_state): Self::SystemData) {
        use specs::Join;

        for (intent, state, velocity, walking_state) in
            (&intent, &mut state, &mut velocity, &mut walking_state).join()
        {
            match state.action {
                Action::Idle | Action::Move { .. } => match intent.command {
                    Command::Move { x, y } => {
                        // match x {
                        //     XAxis::Right => state.direction = Facing::Right,
                        //     XAxis::Left => state.direction = Facing::Left,
                        //     _ => (),
                        // }
                        if x == XAxis::Centre && y == YAxis::Centre {
                            state.action = Action::Idle;
                            velocity.x = 0;
                            velocity.y = 0;
                        } else {
                            state.action = Action::Move { x, y };

                            let step = (walking_state.step + 1) % 4;
                            velocity.x = X_STEP_SIZES[(x as i32 + 1) as usize][step as usize];
                            velocity.y = Y_STEP_SIZES[(y as i32 + 1) as usize][step as usize];
                        }
                    }
                    _ => {
                        state.action = Action::Idle;
                        velocity.x = 0;
                        velocity.y = 0;
                    }
                },
                _ => {
                    velocity.x = 0;
                    velocity.y = 0;
                }
            }
        }
    }
}

pub struct ConfirmVelocity;
// If an entity has a non zero velocity, set movement in State,
// update the walking state step
// This is used after VelocitySystem is piped through RestrictMovementBoundry
// and check entity collision, those two systems might prevent movement
// so we want to update the final velocity here.

impl<'a> System<'a> for ConfirmVelocity {
    type SystemData = (
        ReadStorage<'a, Velocity>,
        WriteStorage<'a, State>,
        WriteStorage<'a, WalkingState>,
    );
    fn run(&mut self, (velocity, mut state, mut walking_state): Self::SystemData) {
        use specs::Join;
        for (velocity, state, walking_state) in (&velocity, &mut state, &mut walking_state).join() {
            match state.action {
                Action::Move { mut x, mut y } => {
                    if velocity.x == 0 {
                        x = XAxis::Centre;
                    }
                    if velocity.y == 0 {
                        y = YAxis::Centre;
                    }
                    if x == XAxis::Centre && y == YAxis::Centre {
                        state.action = Action::Idle;
                    } else {
                        walking_state.step = (walking_state.step + 1) % 4;
                    }
                }
                _ => (),
            }
        }
    }
}
<commit_msg>fix black knight facing step sizes.<commit_after>use specs::{ReadStorage, System, WriteStorage};

use crate::combat::components::intent::{XAxis, YAxis};
use crate::combat::components::{Action, Command, Facing, Intent, State, Velocity, WalkingState};

pub const X_STEP_SIZES: [[i32; 4]; 3] = [[-25, -3, -23, -4], [0, 0, 0, 0], [25, 3, 23, 4]];
pub const Y_STEP_SIZES: [[i32; 4]; 3] = [[-2, -9, -2, -9], [0, 0, 0, 0], [8, 2, 9, 2]];

pub struct VelocitySystem;

impl<'a> System<'a> for VelocitySystem {
    type SystemData = (
        ReadStorage<'a, Intent>,
        WriteStorage<'a, State>,
        WriteStorage<'a, Velocity>,
        WriteStorage<'a, WalkingState>,
    );

    fn run(&mut self, (intent, mut state, mut velocity, mut walking_state): Self::SystemData) {
        use specs::Join;

        for (intent, state, velocity, walking_state) in
            (&intent, &mut state, &mut velocity, &mut walking_state).join()
        {
            match state.action {
                Action::Idle | Action::Move { .. } => match intent.command {
                    Command::Move { x, y } => {
                        if x == XAxis::Centre && y == YAxis::Centre {
                            state.action = Action::Idle;
                            velocity.x = 0;
                            velocity.y = 0;
                        } else {
                            let walking_direction = match x {
                                XAxis::Right => Facing::Right,
                                XAxis::Left => Facing::Left,
                                _ => state.direction,
                            };
                            state.action = Action::Move { x, y };

                            let mut step = (walking_state.step + 1) % 4;
                            if walking_direction != state.direction {
                                // if we have an ai player, then they are always
                                // facing the player, so the step sizes don't
                                // match the animation, shifting this fixes that
                                // this wasn't fixed in the original and the
                                // forward facing animations were off by 1
                                step = (step + 1) % 4;
                            }
                            velocity.x = X_STEP_SIZES[(x as i32 + 1) as usize][step as usize];
                            velocity.y = Y_STEP_SIZES[(y as i32 + 1) as usize][step as usize];
                        }
                    }
                    _ => {
                        state.action = Action::Idle;
                        velocity.x = 0;
                        velocity.y = 0;
                    }
                },
                _ => {
                    velocity.x = 0;
                    velocity.y = 0;
                }
            }
        }
    }
}

pub struct ConfirmVelocity;
// If an entity has a non zero velocity, set movement in State,
// update the walking state step
// This is used after VelocitySystem is piped through RestrictMovementBoundry
// and check entity collision, those two systems might prevent movement
// so we want to update the final velocity here.

impl<'a> System<'a> for ConfirmVelocity {
    type SystemData = (
        ReadStorage<'a, Velocity>,
        WriteStorage<'a, State>,
        WriteStorage<'a, WalkingState>,
    );
    fn run(&mut self, (velocity, mut state, mut walking_state): Self::SystemData) {
        use specs::Join;
        for (velocity, state, walking_state) in (&velocity, &mut state, &mut walking_state).join() {
            match state.action {
                Action::Move { mut x, mut y } => {
                    if velocity.x == 0 {
                        x = XAxis::Centre;
                    }
                    if velocity.y == 0 {
                        y = YAxis::Centre;
                    }
                    if x == XAxis::Centre && y == YAxis::Centre {
                        state.action = Action::Idle;
                    } else {
                        walking_state.step = (walking_state.step + 1) % 4;
                    }
                }
                _ => (),
            }
        }
    }
}
<|endoftext|>


<commit_before>//! Dummy backend implementation to test the code for compile errors
//! outside of the graphics development environment.

extern crate gfx_hal as core;

use std::ops::Range;
use core::{buffer, command, device, format, image, target, mapping, memory, pass, pool, pso};

/// Dummy backend.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Backend { }
impl core::Backend for Backend {
    type Adapter = Adapter;
    type Device = Device;

    type Surface = Surface;
    type Swapchain = Swapchain;

    type CommandQueue = CommandQueue;
    type CommandBuffer = RawCommandBuffer;
    type SubpassCommandBuffer = SubpassCommandBuffer;
    type QueueFamily = QueueFamily;

    type Memory = ();
    type CommandPool = RawCommandPool;
    type SubpassCommandPool = SubpassCommandPool;

    type ShaderModule = ();
    type RenderPass = ();
    type Framebuffer = ();

    type UnboundBuffer = ();
    type Buffer = ();
    type BufferView = ();
    type UnboundImage = ();
    type Image = ();
    type ImageView = ();
    type Sampler = ();

    type ComputePipeline = ();
    type GraphicsPipeline = ();
    type PipelineLayout = ();
    type DescriptorSetLayout = ();
    type DescriptorPool = DescriptorPool;
    type DescriptorSet = ();

    type Fence = ();
    type Semaphore = ();
}

/// Dummy adapter.
pub struct Adapter;
impl core::Adapter<Backend> for Adapter {
    fn open(&self, _: &[(&QueueFamily, core::QueueType, u32)]) -> core::Gpu<Backend> {
        unimplemented!()
    }

    fn info(&self) -> &core::AdapterInfo {
        unimplemented!()
    }

    fn queue_families(&self) -> &[(QueueFamily, core::QueueType)] {
        unimplemented!()
    }
}

/// Dummy command queue doing nothing.
pub struct CommandQueue;
impl core::RawCommandQueue<Backend> for CommandQueue {
    unsafe fn submit_raw(&mut self, _: core::RawSubmission<Backend>, _: Option<&()>) {
        unimplemented!()
    }
}

/// Dummy device doing nothing.
#[derive(Clone)]
pub struct Device;
impl core::Device<Backend> for Device {
    fn get_features(&self) -> &core::Features {
        unimplemented!()
    }

    fn get_limits(&self) -> &core::Limits {
        unimplemented!()
    }

    fn allocate_memory(&mut self, _: &core::MemoryType, _: u64) -> Result<(), device::OutOfMemory> {
        unimplemented!()
    }

    fn create_render_pass(&mut self, _: &[pass::Attachment], _: &[pass::SubpassDesc], _: &[pass::SubpassDependency]) -> () {
        unimplemented!()
    }

    fn create_pipeline_layout(&mut self, _: &[&()]) -> () {
        unimplemented!()
    }

    fn create_graphics_pipelines<'a>(
        &mut self,
        _: &[(pso::GraphicsShaderSet<'a, Backend>, &(), pass::Subpass<'a, Backend>, &pso::GraphicsPipelineDesc)],
    ) -> Vec<Result<(), pso::CreationError>> {
        unimplemented!()
    }

    fn create_compute_pipelines<'a>(
        &mut self,
        _: &[(pso::EntryPoint<'a, Backend>, &())],
    ) -> Vec<Result<(), pso::CreationError>> {
        unimplemented!()
    }

    fn create_framebuffer(
        &mut self, _: &(),
        _: &[&()],
        _: device::Extent,
    ) -> Result<(), device::FramebufferError> {
        unimplemented!()
    }

    fn create_shader_module(&mut self, _: &[u8]) -> Result<(), device::ShaderError> {
        unimplemented!()
    }

    fn create_sampler(&mut self, _: image::SamplerInfo) -> () {
        unimplemented!()
    }
    fn create_buffer(&mut self, _: u64, _: u64, _: buffer::Usage) -> Result<(), buffer::CreationError> {
        unimplemented!()
    }

    fn get_buffer_requirements(&mut self, _: &()) -> memory::Requirements {
        unimplemented!()
    }

    fn bind_buffer_memory(&mut self, _: &(), _: u64, _: ()) -> Result<(), device::BindError> {
        unimplemented!()
    }

    fn create_buffer_view(&mut self, _: &(), _: format::Format, _: Range<u64>) -> Result<(), buffer::ViewError> {
        unimplemented!()
    }

    fn create_image(&mut self, _: image::Kind, _: image::Level, _: format::Format, _: image::Usage)
         -> Result<(), image::CreationError>
    {
        unimplemented!()
    }

    fn get_image_requirements(&mut self, _: &()) -> memory::Requirements {
        unimplemented!()
    }

    fn bind_image_memory(&mut self, _: &(), _: u64, _: ()) -> Result<(), device::BindError> {
        unimplemented!()
    }

    fn create_image_view(&
        mut self,
        _: &(),
        _: format::Format,
        _: format::Swizzle,
        _: image::SubresourceRange,
    ) -> Result<(), image::ViewError> {
        unimplemented!()
    }

    fn create_descriptor_pool(&mut self, _: usize, _: &[pso::DescriptorRangeDesc]) -> DescriptorPool {
        unimplemented!()
    }
    fn create_descriptor_set_layout(&mut self, _: &[pso::DescriptorSetLayoutBinding]) -> () {
        unimplemented!()
    }

    fn update_descriptor_sets(&mut self, _: &[pso::DescriptorSetWrite<Backend>]) {
        unimplemented!()
    }

    fn acquire_mapping_raw(&mut self, _: &(), _: Option<Range<u64>>)
        -> Result<*mut u8, mapping::Error>
    {
        unimplemented!()
    }

    fn release_mapping_raw(&mut self, _: &(), _: Option<Range<u64>>) {
        unimplemented!()
    }

    fn create_semaphore(&mut self) -> () {
        unimplemented!()
    }

    fn create_fence(&mut self, _: bool) -> () {
        unimplemented!()
    }

    fn reset_fences(&mut self, _: &[&()]) {
        unimplemented!()
    }
    fn wait_for_fences(&mut self, _: &[&()], _: device::WaitFor, _: u32) -> bool {
        unimplemented!()
    }

    fn free_memory(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_shader_module(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_renderpass(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_pipeline_layout(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_graphics_pipeline(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_compute_pipeline(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_framebuffer(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_buffer(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_buffer_view(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_image(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_image_view(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_sampler(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_descriptor_pool(&mut self, _: DescriptorPool) {
        unimplemented!()
    }

    fn destroy_descriptor_set_layout(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_fence(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_semaphore(&mut self, _: ()) {
        unimplemented!()
    }
}

/// Dummy queue family;
pub struct QueueFamily;
impl core::QueueFamily for QueueFamily {
    fn num_queues(&self) -> u32 {
        unimplemented!()
    }
}

/// Dummy subpass command buffer.
pub struct SubpassCommandBuffer;

/// Dummy raw command pool.
pub struct RawCommandPool;
impl core::RawCommandPool<Backend> for RawCommandPool {
    fn reset(&mut self) {
        unimplemented!()
    }

    unsafe fn from_queue(_: &CommandQueue, _: pool::CommandPoolCreateFlags) -> Self {
        unimplemented!()
    }

    fn allocate(&mut self, _: usize) -> Vec<RawCommandBuffer> {
        unimplemented!()
    }

    unsafe fn free(&mut self, _: Vec<RawCommandBuffer>) {
        unimplemented!()
    }
}

/// Dummy subpass command pool.
pub struct SubpassCommandPool;
impl core::SubpassCommandPool<Backend> for SubpassCommandPool {

}

/// Dummy command buffer, which ignores all the calls.
#[derive(Clone)]
pub struct RawCommandBuffer;
impl core::RawCommandBuffer<Backend> for RawCommandBuffer {
    fn begin(&mut self) {
        unimplemented!()
    }

    fn finish(&mut self) {
        unimplemented!()
    }

    fn reset(&mut self, _: bool) {
        unimplemented!()
    }

    fn pipeline_barrier(
        &mut self,
        _: Range<pso::PipelineStage>,
        _: &[memory::Barrier<Backend>],
    ) {
        unimplemented!()
    }

    fn fill_buffer(&mut self, _: &(), _: Range<u64>, _: u32) {
        unimplemented!()
    }

    fn update_buffer(&mut self, _: &(), _: u64, _: &[u8]) {
        unimplemented!()
    }

    fn clear_color_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: image::SubresourceRange,
        _: command::ClearColor,
    ) {
        unimplemented!()
    }

    fn clear_depth_stencil_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: image::SubresourceRange,
        _: command::ClearDepthStencil,
    ) {
        unimplemented!()
    }

    fn clear_attachments(&mut self, _: &[command::AttachmentClear], _: &[target::Rect]) {
        unimplemented!()
    }

    fn resolve_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: &(),
        _: image::ImageLayout,
        _: &[command::ImageResolve],
    ) {
        unimplemented!()
    }

    fn bind_index_buffer(&mut self, _: buffer::IndexBufferView<Backend>) {
        unimplemented!()
    }

    fn bind_vertex_buffers(&mut self, _: pso::VertexBufferSet<Backend>) {
        unimplemented!()
    }

    fn set_viewports(&mut self, _: &[core::Viewport]) {

    }

    fn set_scissors(&mut self, _: &[target::Rect]) {
        unimplemented!()
    }

    fn set_stencil_reference(&mut self, _: target::Stencil, _: target::Stencil) {
        unimplemented!()
    }

    fn set_blend_constants(&mut self, _: target::ColorValue) {
        unimplemented!()
    }

    fn begin_renderpass(
        &mut self,
        _: &(),
        _: &(),
        _: target::Rect,
        _: &[command::ClearValue],
        _: command::SubpassContents,
    ) {
        unimplemented!()
    }

    fn next_subpass(&mut self, _: command::SubpassContents) {
        unimplemented!()
    }

    fn end_renderpass(&mut self) {
        unimplemented!()
    }

    fn bind_graphics_pipeline(&mut self, _: &()) {
        unimplemented!()
    }

    fn bind_graphics_descriptor_sets(
        &mut self,
        _: &(),
        _: usize,
        _: &[&()],
    ) {
        unimplemented!()
    }

    fn bind_compute_pipeline(&mut self, _: &()) {
        unimplemented!()
    }

    fn bind_compute_descriptor_sets(
        &mut self,
        _: &(),
        _: usize,
        _: &[&()],
    ) {
        unimplemented!()
    }

    fn dispatch(&mut self, _: u32, _: u32, _: u32) {
        unimplemented!()
    }

    fn dispatch_indirect(&mut self, _: &(), _: u64) {
        unimplemented!()
    }

    fn copy_buffer(&mut self, _: &(), _: &(), _: &[command::BufferCopy]) {
        unimplemented!()
    }

    fn copy_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: &(),
        _: image::ImageLayout,
        _: &[command::ImageCopy],
    ) {
        unimplemented!()
    }

    fn copy_buffer_to_image(
        &mut self,
        _: &(),
        _: &(),
        _: image::ImageLayout,
        _: &[command::BufferImageCopy],
    ) {
        unimplemented!()
    }

    fn copy_image_to_buffer(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: &(),
        _: &[command::BufferImageCopy],
    ) {
        unimplemented!()
    }

    fn draw(&mut self,
        _: Range<core::VertexCount>,
        _: Range<core::InstanceCount>,
    ) {
        unimplemented!()
    }

    fn draw_indexed(
        &mut self,
        _: Range<core::IndexCount>,
        _: core::VertexOffset,
        _: Range<core::InstanceCount>,
    ) {
        unimplemented!()
    }

    fn draw_indirect(&mut self, _: &(), _: u64, _: u32, _: u32) {
        unimplemented!()
    }

    fn draw_indexed_indirect(
        &mut self,
        _: &(),
        _: u64,
        _: u32,
        _: u32,
    ) {
        unimplemented!()
    }
}

// Dummy descriptor pool.
#[derive(Debug)]
pub struct DescriptorPool;
impl core::DescriptorPool<Backend> for DescriptorPool {
    fn allocate_sets(&mut self, _: &[&()]) -> Vec<()> {
        unimplemented!()
    }

    fn reset(&mut self) {
        unimplemented!()
    }
}

/// Dummy surface.
pub struct Surface;
impl core::Surface<Backend> for Surface {
    fn get_kind(&self) -> core::image::Kind {
        unimplemented!()
    }

    fn surface_capabilities(&self, _: &Adapter) -> core::SurfaceCapabilities {
        unimplemented!()
    }

    fn supports_queue(&self, _: &QueueFamily) -> bool {
        unimplemented!()
    }

    fn build_swapchain<C>(&mut self,
        _: core::SwapchainConfig,
        _: &core::CommandQueue<Backend, C>
    ) -> (Swapchain, core::Backbuffer<Backend>) {
        unimplemented!()
    }
}

/// Dummy swapchain.
pub struct Swapchain;
impl core::Swapchain<Backend> for Swapchain {
    fn acquire_frame(&mut self, _: core::FrameSync<Backend>) -> core::Frame {
        unimplemented!()
    }

    fn present<C>(
        &mut self,
        _: &mut core::CommandQueue<Backend, C>,
        _: &[&()],
    ) {
        unimplemented!()
    }
}

pub struct Instance;
impl core::Instance for Instance {
    type Backend = Backend;
    fn enumerate_adapters(&self) -> Vec<Adapter> {
        Vec::new()
    }
}
<commit_msg>[empty] update for RawQueueFamily<commit_after>//! Dummy backend implementation to test the code for compile errors
//! outside of the graphics development environment.

extern crate gfx_hal as core;

use std::ops::Range;
use core::{buffer, command, device, format, image, target, mapping, memory, pass, pool, pso, queue};

/// Dummy backend.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Backend { }
impl core::Backend for Backend {
    type Adapter = Adapter;
    type Device = Device;

    type Surface = Surface;
    type Swapchain = Swapchain;

    type CommandQueue = RawCommandQueue;
    type CommandBuffer = RawCommandBuffer;
    type SubpassCommandBuffer = SubpassCommandBuffer;
    type QueueFamily = RawQueueFamily;

    type Memory = ();
    type CommandPool = RawCommandPool;
    type SubpassCommandPool = SubpassCommandPool;

    type ShaderModule = ();
    type RenderPass = ();
    type Framebuffer = ();

    type UnboundBuffer = ();
    type Buffer = ();
    type BufferView = ();
    type UnboundImage = ();
    type Image = ();
    type ImageView = ();
    type Sampler = ();

    type ComputePipeline = ();
    type GraphicsPipeline = ();
    type PipelineLayout = ();
    type DescriptorSetLayout = ();
    type DescriptorPool = DescriptorPool;
    type DescriptorSet = ();

    type Fence = ();
    type Semaphore = ();
}

/// Dummy adapter.
pub struct Adapter;
impl core::Adapter<Backend> for Adapter {
    fn open(&self) -> core::Gpu<Backend> {
        unimplemented!()
    }

    fn info(&self) -> &core::AdapterInfo {
        unimplemented!()
    }

    fn queue_families(&self) -> &[&RawQueueFamily] {
        unimplemented!()
    }
}

/// Dummy command queue doing nothing.
pub struct RawCommandQueue;
impl queue::RawCommandQueue<Backend> for RawCommandQueue {
    unsafe fn submit_raw(&mut self, _: queue::RawSubmission<Backend>, _: Option<&()>) {
        unimplemented!()
    }
}

/// Dummy device doing nothing.
#[derive(Clone)]
pub struct Device;
impl core::Device<Backend> for Device {
    fn get_features(&self) -> &core::Features {
        unimplemented!()
    }

    fn get_limits(&self) -> &core::Limits {
        unimplemented!()
    }

    fn allocate_memory(&mut self, _: &core::MemoryType, _: u64) -> Result<(), device::OutOfMemory> {
        unimplemented!()
    }

    fn create_render_pass(&mut self, _: &[pass::Attachment], _: &[pass::SubpassDesc], _: &[pass::SubpassDependency]) -> () {
        unimplemented!()
    }

    fn create_pipeline_layout(&mut self, _: &[&()]) -> () {
        unimplemented!()
    }

    fn create_graphics_pipelines<'a>(
        &mut self,
        _: &[(pso::GraphicsShaderSet<'a, Backend>, &(), pass::Subpass<'a, Backend>, &pso::GraphicsPipelineDesc)],
    ) -> Vec<Result<(), pso::CreationError>> {
        unimplemented!()
    }

    fn create_compute_pipelines<'a>(
        &mut self,
        _: &[(pso::EntryPoint<'a, Backend>, &())],
    ) -> Vec<Result<(), pso::CreationError>> {
        unimplemented!()
    }

    fn create_framebuffer(
        &mut self, _: &(),
        _: &[&()],
        _: device::Extent,
    ) -> Result<(), device::FramebufferError> {
        unimplemented!()
    }

    fn create_shader_module(&mut self, _: &[u8]) -> Result<(), device::ShaderError> {
        unimplemented!()
    }

    fn create_sampler(&mut self, _: image::SamplerInfo) -> () {
        unimplemented!()
    }
    fn create_buffer(&mut self, _: u64, _: u64, _: buffer::Usage) -> Result<(), buffer::CreationError> {
        unimplemented!()
    }

    fn get_buffer_requirements(&mut self, _: &()) -> memory::Requirements {
        unimplemented!()
    }

    fn bind_buffer_memory(&mut self, _: &(), _: u64, _: ()) -> Result<(), device::BindError> {
        unimplemented!()
    }

    fn create_buffer_view(&mut self, _: &(), _: format::Format, _: Range<u64>) -> Result<(), buffer::ViewError> {
        unimplemented!()
    }

    fn create_image(&mut self, _: image::Kind, _: image::Level, _: format::Format, _: image::Usage)
         -> Result<(), image::CreationError>
    {
        unimplemented!()
    }

    fn get_image_requirements(&mut self, _: &()) -> memory::Requirements {
        unimplemented!()
    }

    fn bind_image_memory(&mut self, _: &(), _: u64, _: ()) -> Result<(), device::BindError> {
        unimplemented!()
    }

    fn create_image_view(&
        mut self,
        _: &(),
        _: format::Format,
        _: format::Swizzle,
        _: image::SubresourceRange,
    ) -> Result<(), image::ViewError> {
        unimplemented!()
    }

    fn create_descriptor_pool(&mut self, _: usize, _: &[pso::DescriptorRangeDesc]) -> DescriptorPool {
        unimplemented!()
    }
    fn create_descriptor_set_layout(&mut self, _: &[pso::DescriptorSetLayoutBinding]) -> () {
        unimplemented!()
    }

    fn update_descriptor_sets(&mut self, _: &[pso::DescriptorSetWrite<Backend>]) {
        unimplemented!()
    }

    fn acquire_mapping_raw(&mut self, _: &(), _: Option<Range<u64>>)
        -> Result<*mut u8, mapping::Error>
    {
        unimplemented!()
    }

    fn release_mapping_raw(&mut self, _: &(), _: Option<Range<u64>>) {
        unimplemented!()
    }

    fn create_semaphore(&mut self) -> () {
        unimplemented!()
    }

    fn create_fence(&mut self, _: bool) -> () {
        unimplemented!()
    }

    fn reset_fences(&mut self, _: &[&()]) {
        unimplemented!()
    }
    fn wait_for_fences(&mut self, _: &[&()], _: device::WaitFor, _: u32) -> bool {
        unimplemented!()
    }

    fn free_memory(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_shader_module(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_renderpass(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_pipeline_layout(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_graphics_pipeline(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_compute_pipeline(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_framebuffer(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_buffer(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_buffer_view(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_image(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_image_view(&mut self, _: ()) {
        unimplemented!()
    }
    fn destroy_sampler(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_descriptor_pool(&mut self, _: DescriptorPool) {
        unimplemented!()
    }

    fn destroy_descriptor_set_layout(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_fence(&mut self, _: ()) {
        unimplemented!()
    }

    fn destroy_semaphore(&mut self, _: ()) {
        unimplemented!()
    }
}

/// Dummy queue family;
pub struct RawQueueFamily;
impl queue::RawQueueFamily<Backend> for RawQueueFamily {
    fn queue_type(&self) -> core::QueueType {
        unimplemented!()
    }
    fn max_queues(&self) -> usize {
        unimplemented!()
    }
    fn create_queue(&mut self) -> RawCommandQueue {
        unimplemented!()
    }
    fn create_pool(&mut self, _: pool::CommandPoolCreateFlags) -> RawCommandPool {
        unimplemented!()
    }
}

/// Dummy subpass command buffer.
pub struct SubpassCommandBuffer;

/// Dummy raw command pool.
pub struct RawCommandPool;
impl pool::RawCommandPool<Backend> for RawCommandPool {
    fn reset(&mut self) {
        unimplemented!()
    }

    fn allocate(&mut self, _: usize) -> Vec<RawCommandBuffer> {
        unimplemented!()
    }

    unsafe fn free(&mut self, _: Vec<RawCommandBuffer>) {
        unimplemented!()
    }
}

/// Dummy subpass command pool.
pub struct SubpassCommandPool;
impl pool::SubpassCommandPool<Backend> for SubpassCommandPool {

}

/// Dummy command buffer, which ignores all the calls.
#[derive(Clone)]
pub struct RawCommandBuffer;
impl command::RawCommandBuffer<Backend> for RawCommandBuffer {
    fn begin(&mut self) {
        unimplemented!()
    }

    fn finish(&mut self) {
        unimplemented!()
    }

    fn reset(&mut self, _: bool) {
        unimplemented!()
    }

    fn pipeline_barrier(
        &mut self,
        _: Range<pso::PipelineStage>,
        _: &[memory::Barrier<Backend>],
    ) {
        unimplemented!()
    }

    fn fill_buffer(&mut self, _: &(), _: Range<u64>, _: u32) {
        unimplemented!()
    }

    fn update_buffer(&mut self, _: &(), _: u64, _: &[u8]) {
        unimplemented!()
    }

    fn clear_color_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: image::SubresourceRange,
        _: command::ClearColor,
    ) {
        unimplemented!()
    }

    fn clear_depth_stencil_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: image::SubresourceRange,
        _: command::ClearDepthStencil,
    ) {
        unimplemented!()
    }

    fn clear_attachments(&mut self, _: &[command::AttachmentClear], _: &[target::Rect]) {
        unimplemented!()
    }

    fn resolve_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: &(),
        _: image::ImageLayout,
        _: &[command::ImageResolve],
    ) {
        unimplemented!()
    }

    fn bind_index_buffer(&mut self, _: buffer::IndexBufferView<Backend>) {
        unimplemented!()
    }

    fn bind_vertex_buffers(&mut self, _: pso::VertexBufferSet<Backend>) {
        unimplemented!()
    }

    fn set_viewports(&mut self, _: &[core::Viewport]) {

    }

    fn set_scissors(&mut self, _: &[target::Rect]) {
        unimplemented!()
    }

    fn set_stencil_reference(&mut self, _: target::Stencil, _: target::Stencil) {
        unimplemented!()
    }

    fn set_blend_constants(&mut self, _: target::ColorValue) {
        unimplemented!()
    }

    fn begin_renderpass(
        &mut self,
        _: &(),
        _: &(),
        _: target::Rect,
        _: &[command::ClearValue],
        _: command::SubpassContents,
    ) {
        unimplemented!()
    }

    fn next_subpass(&mut self, _: command::SubpassContents) {
        unimplemented!()
    }

    fn end_renderpass(&mut self) {
        unimplemented!()
    }

    fn bind_graphics_pipeline(&mut self, _: &()) {
        unimplemented!()
    }

    fn bind_graphics_descriptor_sets(
        &mut self,
        _: &(),
        _: usize,
        _: &[&()],
    ) {
        unimplemented!()
    }

    fn bind_compute_pipeline(&mut self, _: &()) {
        unimplemented!()
    }

    fn bind_compute_descriptor_sets(
        &mut self,
        _: &(),
        _: usize,
        _: &[&()],
    ) {
        unimplemented!()
    }

    fn dispatch(&mut self, _: u32, _: u32, _: u32) {
        unimplemented!()
    }

    fn dispatch_indirect(&mut self, _: &(), _: u64) {
        unimplemented!()
    }

    fn copy_buffer(&mut self, _: &(), _: &(), _: &[command::BufferCopy]) {
        unimplemented!()
    }

    fn copy_image(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: &(),
        _: image::ImageLayout,
        _: &[command::ImageCopy],
    ) {
        unimplemented!()
    }

    fn copy_buffer_to_image(
        &mut self,
        _: &(),
        _: &(),
        _: image::ImageLayout,
        _: &[command::BufferImageCopy],
    ) {
        unimplemented!()
    }

    fn copy_image_to_buffer(
        &mut self,
        _: &(),
        _: image::ImageLayout,
        _: &(),
        _: &[command::BufferImageCopy],
    ) {
        unimplemented!()
    }

    fn draw(&mut self,
        _: Range<core::VertexCount>,
        _: Range<core::InstanceCount>,
    ) {
        unimplemented!()
    }

    fn draw_indexed(
        &mut self,
        _: Range<core::IndexCount>,
        _: core::VertexOffset,
        _: Range<core::InstanceCount>,
    ) {
        unimplemented!()
    }

    fn draw_indirect(&mut self, _: &(), _: u64, _: u32, _: u32) {
        unimplemented!()
    }

    fn draw_indexed_indirect(
        &mut self,
        _: &(),
        _: u64,
        _: u32,
        _: u32,
    ) {
        unimplemented!()
    }
}

// Dummy descriptor pool.
#[derive(Debug)]
pub struct DescriptorPool;
impl core::DescriptorPool<Backend> for DescriptorPool {
    fn allocate_sets(&mut self, _: &[&()]) -> Vec<()> {
        unimplemented!()
    }

    fn reset(&mut self) {
        unimplemented!()
    }
}

/// Dummy surface.
pub struct Surface;
impl core::Surface<Backend> for Surface {
    fn get_kind(&self) -> core::image::Kind {
        unimplemented!()
    }

    fn surface_capabilities(&self, _: &Adapter) -> core::SurfaceCapabilities {
        unimplemented!()
    }

    fn supports_queue(&self, _: &RawQueueFamily) -> bool {
        unimplemented!()
    }

    fn build_swapchain<C>(&mut self,
        _: core::SwapchainConfig,
        _: &core::CommandQueue<Backend, C>
    ) -> (Swapchain, core::Backbuffer<Backend>) {
        unimplemented!()
    }
}

/// Dummy swapchain.
pub struct Swapchain;
impl core::Swapchain<Backend> for Swapchain {
    fn acquire_frame(&mut self, _: core::FrameSync<Backend>) -> core::Frame {
        unimplemented!()
    }

    fn present<C>(
        &mut self,
        _: &mut core::CommandQueue<Backend, C>,
        _: &[&()],
    ) {
        unimplemented!()
    }
}

pub struct Instance;
impl core::Instance for Instance {
    type Backend = Backend;
    fn enumerate_adapters(&self) -> Vec<Adapter> {
        Vec::new()
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use capnp_rpc::{rpc, twoparty, rpc_twoparty_capnp};
use calculator_capnp::calculator;
use gj::Promise;

pub fn main() {
    let args: Vec<String> = ::std::env::args().collect();
    if args.len() != 3 {
        println!("usage: {} client HOST:PORT", args[0]);
        return;
    }

    ::gj::EventLoop::top_level(move |wait_scope| {
        use std::net::ToSocketAddrs;
        let addr = try!(args[2].to_socket_addrs()).next().expect("could not parse address");
        let stream = try!(::gj::io::tcp::Stream::connect(addr).wait(wait_scope));
        let stream2 = try!(stream.try_clone());
        let connection: Box<::capnp_rpc::VatNetwork<twoparty::VatId>> =
            Box::new(twoparty::VatNetwork::new(stream, stream2, Default::default()));
        let mut rpc_system = rpc::System::new(connection, None);
        let calculator = calculator::Client {
            client: rpc_system.bootstrap(rpc_twoparty_capnp::Side::Server)
        };

        {
            println!("Evaluating a literal...");
            let mut request = calculator.evaluate_request();
            request.init().init_expression().set_literal(11.0);
            request.send().promise.then(|response| {
                let value = pry!(pry!(response.get()).get_value());
                let request = value.read_request();
                request.send().promise.then(|response|{
                    assert_eq!(pry!(response.get()).get_value(), 11.0);
                    Promise::ok(())
                })
            }).wait(wait_scope).unwrap();
            println!("PASS");
        }

        {
            println!("Evaluating a literal using pipelining...");
            let mut request = calculator.evaluate_request();
            request.init().init_expression().set_literal(23.0);
            let value = request.send().pipeline.get_value();
            let request = value.read_request();
            request.send().promise.then(|response|{
                assert_eq!(pry!(response.get()).get_value(), 23.0);
                Promise::ok(())
            }).wait(wait_scope).unwrap();
            println!("PASS");
        }

        Ok(())
    }).expect("top level error");
}
<commit_msg>123 + 45 - 67 case. Doesn't quite work yet.<commit_after>// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use capnp_rpc::{rpc, twoparty, rpc_twoparty_capnp};
use calculator_capnp::calculator;
use gj::Promise;

pub fn main() {
    let args: Vec<String> = ::std::env::args().collect();
    if args.len() != 3 {
        println!("usage: {} client HOST:PORT", args[0]);
        return;
    }

    ::gj::EventLoop::top_level(move |wait_scope| {
        use std::net::ToSocketAddrs;
        let addr = try!(args[2].to_socket_addrs()).next().expect("could not parse address");
        let stream = try!(::gj::io::tcp::Stream::connect(addr).wait(wait_scope));
        let stream2 = try!(stream.try_clone());
        let connection: Box<::capnp_rpc::VatNetwork<twoparty::VatId>> =
            Box::new(twoparty::VatNetwork::new(stream, stream2, Default::default()));
        let mut rpc_system = rpc::System::new(connection, None);
        let calculator = calculator::Client {
            client: rpc_system.bootstrap(rpc_twoparty_capnp::Side::Server)
        };

        {
            println!("Evaluating a literal...");
            let mut request = calculator.evaluate_request();
            request.init().init_expression().set_literal(11.0);
            request.send().promise.then(|response| {
                let value = pry!(pry!(response.get()).get_value());
                let request = value.read_request();
                request.send().promise.then(|response|{
                    assert_eq!(pry!(response.get()).get_value(), 11.0);
                    Promise::ok(())
                })
            }).wait(wait_scope).unwrap();
            println!("PASS");
        }

        {
            println!("Evaluating a literal using pipelining...");
            let mut request = calculator.evaluate_request();
            request.init().init_expression().set_literal(23.0);
            let value = request.send().pipeline.get_value();
            let request = value.read_request();
            request.send().promise.then(|response|{
                assert_eq!(pry!(response.get()).get_value(), 23.0);
                Promise::ok(())
            }).wait(wait_scope).unwrap();
            println!("PASS");
        }

        {
            // Make a request to evaluate 123 + 45 - 67.
            //
            // The Calculator interface requires that we first call getOperator() to
            // get the addition and subtraction functions, then call evaluate() to use
            // them.  But, once again, we can get both functions, call evaluate(), and
            // then read() the result -- four RPCs -- in the time of *one* network
            // round trip, because of promise pipelining.

            println!("Using add and subtract... ");

            let add = {
                // Get the "add" function from the server.
                let mut request = calculator.get_operator_request();
                request.init().set_op(calculator::Operator::Add);
                request.send().pipeline.get_func()
            };

            let subtract = {
                // Get the "subtract" function from the server.
                let mut request = calculator.get_operator_request();
                request.init().set_op(calculator::Operator::Subtract);
                request.send().pipeline.get_func()
            };

            // Build the request to evaluate 123 + 45 - 67.
            let mut request = calculator.evaluate_request();

            {
                let mut subtract_call = request.init().init_expression().init_call();
                subtract_call.set_function(subtract);
                let mut subtract_params = subtract_call.init_params(2);
                subtract_params.borrow().get(1).set_literal(67.0);

                let mut add_call = subtract_params.get(0).init_call();
                add_call.set_function(add);
                let mut add_params = add_call.init_params(2);
                add_params.borrow().get(0).set_literal(123.0);
                add_params.get(1).set_literal(45.0);
            }

            // Send the evaluate() request, read() the result, and wait for read() to
            // finish.
            let eval_promise = request.send();
            let read_promise = eval_promise.pipeline.get_value().read_request().send();

            let response = try!(read_promise.promise.wait(wait_scope));
            assert_eq!(try!(response.get()).get_value(), 101.0);

            println!("PASS");
        }
        Ok(())
    }).expect("top level error");
}
<|endoftext|>


<commit_before>// Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

extern crate cgmath;
extern crate chrono;
extern crate env_logger;
extern crate failure;
extern crate flame;
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate richter;
extern crate rodio;

mod game;

use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::net::ToSocketAddrs;
use std::path::Path;
use std::process::exit;
use std::rc::Rc;

use richter::client::input::game::MouseWheel;
use richter::client::input::{Input, InputFocus};
use richter::client::render::{self, GraphicsPackage};
use richter::client::{self, Client};
use richter::common;
use richter::common::console::{CmdRegistry, Console, CvarRegistry};
use richter::common::host::{Host, Program};
use richter::common::vfs::Vfs;

use game::Game;

use cgmath::{Matrix4, SquareMatrix};
use chrono::Duration;
use gfx::Encoder;
use gfx_device_gl::{CommandBuffer, Device, Resources};
use glutin::{CursorState, Event, EventsLoop, GlContext, GlWindow, MouseCursor, WindowEvent};
use rodio::Endpoint;

enum TitleState {
    Menu,
    Console,
}

enum ProgramState {
    Title,
    Game(Game),
}

struct ClientProgram {
    vfs: Rc<Vfs>,
    cvars: Rc<RefCell<CvarRegistry>>,
    cmds: Rc<RefCell<CmdRegistry>>,
    console: Rc<RefCell<Console>>,

    events_loop: RefCell<EventsLoop>,
    window: RefCell<GlWindow>,

    gfx_pkg: Rc<RefCell<GraphicsPackage>>,
    device: RefCell<Device>,
    encoder: RefCell<Encoder<Resources, CommandBuffer>>,
    data: RefCell<render::pipe::Data<Resources>>,

    endpoint: Rc<Endpoint>,

    state: RefCell<ProgramState>,
    input: Rc<RefCell<Input>>,
}

impl ClientProgram {
    pub fn new() -> ClientProgram {
        let mut vfs = Vfs::new();

        // add basedir first
        vfs.add_directory(common::DEFAULT_BASEDIR).unwrap();

        // then add PAK archives
        for vfs_id in 0..common::MAX_PAKFILES {
            // TODO: check `-basedir` command line argument
            let basedir = common::DEFAULT_BASEDIR;
            let path_string = format!("{}/pak{}.pak", basedir, vfs_id);
            let path = Path::new(&path_string);

            // keep adding PAKs until we don't find one or we hit MAX_PAKFILES
            if !path.exists() {
                break;
            }

            vfs.add_pakfile(path).unwrap();
        }

        let cvars = Rc::new(RefCell::new(CvarRegistry::new()));
        client::register_cvars(&cvars.borrow_mut());

        let cmds = Rc::new(RefCell::new(CmdRegistry::new()));
        // TODO: register commands as other subsystems come online

        let console = Rc::new(RefCell::new(Console::new(cmds.clone(), cvars.clone())));

        let input = Rc::new(RefCell::new(Input::new(InputFocus::Game, console.clone())));
        input.borrow_mut().bind_defaults();

        let events_loop = glutin::EventsLoop::new();
        let window_builder = glutin::WindowBuilder::new()
            .with_title("Richter client")
            .with_dimensions(1600, 900);
        let context_builder = glutin::ContextBuilder::new()
            .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (3, 3)))
            .with_vsync(false);

        let (window, device, mut factory, color, depth) =
            gfx_window_glutin::init::<render::ColorFormat, render::DepthFormat>(
                window_builder,
                context_builder,
                &events_loop,
            );

        use gfx::traits::FactoryExt;
        use gfx::Factory;
        let (_, dummy_texture) = factory
            .create_texture_immutable_u8::<render::ColorFormat>(
                gfx::texture::Kind::D2(0, 0, gfx::texture::AaMode::Single),
                gfx::texture::Mipmap::Allocated,
                &[&[]],
            )
            .expect("dummy texture generation failed");

        let sampler = factory.create_sampler(gfx::texture::SamplerInfo::new(
            gfx::texture::FilterMethod::Scale,
            gfx::texture::WrapMode::Tile,
        ));

        let data = render::pipe::Data {
            vertex_buffer: factory.create_vertex_buffer(&[]),
            transform: Matrix4::identity().into(),
            sampler: (dummy_texture.clone(), sampler.clone()),
            out_color: color.clone(),
            out_depth: depth.clone(),
        };

        let encoder = factory.create_command_buffer().into();

        let endpoint = Rc::new(rodio::get_endpoints_list().next().unwrap());

        let gfx_pkg = Rc::new(RefCell::new(GraphicsPackage::new(
            &vfs,
            factory,
            color,
            depth,
            console.clone(),
        )));

        // this will also execute config.cfg and autoexec.cfg (assuming an unmodified quake.rc)
        console.borrow().stuff_text("exec quake.rc\n");

        ClientProgram {
            vfs: Rc::new(vfs),
            cvars,
            cmds,
            console,
            events_loop: RefCell::new(events_loop),
            window: RefCell::new(window),
            gfx_pkg,
            device: RefCell::new(device),
            encoder: RefCell::new(encoder),
            data: RefCell::new(data),
            endpoint,
            state: RefCell::new(ProgramState::Title),
            input,
        }
    }

    fn connect<A>(&mut self, server_addrs: A)
    where
        A: ToSocketAddrs,
    {
        let cl = Client::connect(
            server_addrs,
            self.vfs.clone(),
            self.cvars.clone(),
            self.cmds.clone(),
            self.console.clone(),
            self.endpoint.clone(),
        ).unwrap();

        cl.register_cmds(&mut self.cmds.borrow_mut());

        self.state.replace(ProgramState::Game(
            Game::new(
                self.vfs.clone(),
                self.cvars.clone(),
                self.cmds.clone(),
                self.gfx_pkg.clone(),
                self.input.clone(),
                cl,
            ).unwrap(),
        ));
    }

    fn render(&mut self) {
        self.encoder
            .borrow_mut()
            .clear(&self.gfx_pkg.borrow().color_target(), [0.0, 0.0, 0.0, 1.0]);
        self.encoder
            .borrow_mut()
            .clear_depth(&self.gfx_pkg.borrow().depth_stencil(), 1.0);
        let (win_w, win_h) = self.window.borrow().get_inner_size().unwrap();

        match *self.state.borrow_mut() {
            ProgramState::Title => unimplemented!(),
            ProgramState::Game(ref mut game) => {
                game.render(
                    &mut self.encoder.borrow_mut(),
                    &mut self.data.borrow_mut(),
                    win_w,
                    win_h,
                );
            }
        }

        use std::ops::DerefMut;
        flame::start("Encoder::flush");
        self.encoder
            .borrow_mut()
            .flush(self.device.borrow_mut().deref_mut());
        flame::end("Encoder::flush");

        flame::start("Window::swap_buffers");
        self.window.borrow_mut().swap_buffers().unwrap();
        flame::end("Window::swap_buffers");

        use gfx::Device;
        flame::start("Device::cleanup");
        self.device.borrow_mut().cleanup();
        flame::end("Device::cleanup");
    }
}

impl Program for ClientProgram {
    fn frame(&mut self, frame_duration: Duration) {
        let _guard = flame::start_guard("ClientProgram::frame");
        match *self.state.borrow_mut() {
            ProgramState::Title => unimplemented!(),

            ProgramState::Game(ref mut game) => {
                game.frame(frame_duration);
            }
        }

        flame::start("EventsLoop::poll_events");
        self.events_loop
            .borrow_mut()
            .poll_events(|event| match event {
                Event::WindowEvent {
                    event: WindowEvent::Closed,
                    ..
                } => {
                    // TODO: handle quit properly
                    flame::dump_html(File::create("flame.html").unwrap()).unwrap();
                    std::process::exit(0);
                }

                e => match *self.state.borrow_mut() {
                    ProgramState::Title => unimplemented!(),
                    ProgramState::Game(ref mut game) => game.handle_input(e),
                },
            });
        flame::end("EventsLoop::poll_events");

        match self.input.borrow().current_focus() {
            InputFocus::Game => {
                self.window
                    .borrow_mut()
                    .set_cursor_state(CursorState::Grab)
                    .unwrap();
                self.window.borrow_mut().set_cursor(MouseCursor::NoneCursor);
            }

            _ => {
                self.window
                    .borrow_mut()
                    .set_cursor_state(CursorState::Normal)
                    .unwrap();
                self.window.borrow_mut().set_cursor(MouseCursor::Default);
            }
        }

        // run console commands
        self.console.borrow().execute();

        self.render();
    }
}

fn main() {
    env_logger::init();

    let args: Vec<String> = env::args().collect();

    if args.len() != 2 {
        println!("Usage: {} <server_address>", args[0]);
        exit(1);
    }

    let mut client_program = ClientProgram::new();
    client_program.connect(&args[1]);
    let mut host = Host::new(client_program);

    loop {
        host.frame();
    }
}
<commit_msg>Change 0x0 dummy texture to 1x1<commit_after>// Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

extern crate cgmath;
extern crate chrono;
extern crate env_logger;
extern crate failure;
extern crate flame;
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate richter;
extern crate rodio;

mod game;

use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::net::ToSocketAddrs;
use std::path::Path;
use std::process::exit;
use std::rc::Rc;

use richter::client::input::game::MouseWheel;
use richter::client::input::{Input, InputFocus};
use richter::client::render::{self, GraphicsPackage};
use richter::client::{self, Client};
use richter::common;
use richter::common::console::{CmdRegistry, Console, CvarRegistry};
use richter::common::host::{Host, Program};
use richter::common::vfs::Vfs;

use game::Game;

use cgmath::{Matrix4, SquareMatrix};
use chrono::Duration;
use gfx::Encoder;
use gfx_device_gl::{CommandBuffer, Device, Resources};
use glutin::{CursorState, Event, EventsLoop, GlContext, GlWindow, MouseCursor, WindowEvent};
use rodio::Endpoint;

enum TitleState {
    Menu,
    Console,
}

enum ProgramState {
    Title,
    Game(Game),
}

struct ClientProgram {
    vfs: Rc<Vfs>,
    cvars: Rc<RefCell<CvarRegistry>>,
    cmds: Rc<RefCell<CmdRegistry>>,
    console: Rc<RefCell<Console>>,

    events_loop: RefCell<EventsLoop>,
    window: RefCell<GlWindow>,

    gfx_pkg: Rc<RefCell<GraphicsPackage>>,
    device: RefCell<Device>,
    encoder: RefCell<Encoder<Resources, CommandBuffer>>,
    data: RefCell<render::pipe::Data<Resources>>,

    endpoint: Rc<Endpoint>,

    state: RefCell<ProgramState>,
    input: Rc<RefCell<Input>>,
}

impl ClientProgram {
    pub fn new() -> ClientProgram {
        let mut vfs = Vfs::new();

        // add basedir first
        vfs.add_directory(common::DEFAULT_BASEDIR).unwrap();

        // then add PAK archives
        for vfs_id in 0..common::MAX_PAKFILES {
            // TODO: check `-basedir` command line argument
            let basedir = common::DEFAULT_BASEDIR;
            let path_string = format!("{}/pak{}.pak", basedir, vfs_id);
            let path = Path::new(&path_string);

            // keep adding PAKs until we don't find one or we hit MAX_PAKFILES
            if !path.exists() {
                break;
            }

            vfs.add_pakfile(path).unwrap();
        }

        let cvars = Rc::new(RefCell::new(CvarRegistry::new()));
        client::register_cvars(&cvars.borrow_mut());

        let cmds = Rc::new(RefCell::new(CmdRegistry::new()));
        // TODO: register commands as other subsystems come online

        let console = Rc::new(RefCell::new(Console::new(cmds.clone(), cvars.clone())));

        let input = Rc::new(RefCell::new(Input::new(InputFocus::Game, console.clone())));
        input.borrow_mut().bind_defaults();

        let events_loop = glutin::EventsLoop::new();
        let window_builder = glutin::WindowBuilder::new()
            .with_title("Richter client")
            .with_dimensions(1600, 900);
        let context_builder = glutin::ContextBuilder::new()
            .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (3, 3)))
            .with_vsync(false);

        let (window, device, mut factory, color, depth) =
            gfx_window_glutin::init::<render::ColorFormat, render::DepthFormat>(
                window_builder,
                context_builder,
                &events_loop,
            );

        use gfx::traits::FactoryExt;
        use gfx::Factory;
        let (_, dummy_texture) = factory
            .create_texture_immutable_u8::<render::ColorFormat>(
                gfx::texture::Kind::D2(1, 1, gfx::texture::AaMode::Single),
                gfx::texture::Mipmap::Allocated,
                &[&[]],
            )
            .expect("dummy texture generation failed");

        let sampler = factory.create_sampler(gfx::texture::SamplerInfo::new(
            gfx::texture::FilterMethod::Scale,
            gfx::texture::WrapMode::Tile,
        ));

        let data = render::pipe::Data {
            vertex_buffer: factory.create_vertex_buffer(&[]),
            transform: Matrix4::identity().into(),
            sampler: (dummy_texture.clone(), sampler.clone()),
            out_color: color.clone(),
            out_depth: depth.clone(),
        };

        let encoder = factory.create_command_buffer().into();

        let endpoint = Rc::new(rodio::get_endpoints_list().next().unwrap());

        let gfx_pkg = Rc::new(RefCell::new(GraphicsPackage::new(
            &vfs,
            factory,
            color,
            depth,
            console.clone(),
        )));

        // this will also execute config.cfg and autoexec.cfg (assuming an unmodified quake.rc)
        console.borrow().stuff_text("exec quake.rc\n");

        ClientProgram {
            vfs: Rc::new(vfs),
            cvars,
            cmds,
            console,
            events_loop: RefCell::new(events_loop),
            window: RefCell::new(window),
            gfx_pkg,
            device: RefCell::new(device),
            encoder: RefCell::new(encoder),
            data: RefCell::new(data),
            endpoint,
            state: RefCell::new(ProgramState::Title),
            input,
        }
    }

    fn connect<A>(&mut self, server_addrs: A)
    where
        A: ToSocketAddrs,
    {
        let cl = Client::connect(
            server_addrs,
            self.vfs.clone(),
            self.cvars.clone(),
            self.cmds.clone(),
            self.console.clone(),
            self.endpoint.clone(),
        ).unwrap();

        cl.register_cmds(&mut self.cmds.borrow_mut());

        self.state.replace(ProgramState::Game(
            Game::new(
                self.vfs.clone(),
                self.cvars.clone(),
                self.cmds.clone(),
                self.gfx_pkg.clone(),
                self.input.clone(),
                cl,
            ).unwrap(),
        ));
    }

    fn render(&mut self) {
        self.encoder
            .borrow_mut()
            .clear(&self.gfx_pkg.borrow().color_target(), [0.0, 0.0, 0.0, 1.0]);
        self.encoder
            .borrow_mut()
            .clear_depth(&self.gfx_pkg.borrow().depth_stencil(), 1.0);
        let (win_w, win_h) = self.window.borrow().get_inner_size().unwrap();

        match *self.state.borrow_mut() {
            ProgramState::Title => unimplemented!(),
            ProgramState::Game(ref mut game) => {
                game.render(
                    &mut self.encoder.borrow_mut(),
                    &mut self.data.borrow_mut(),
                    win_w,
                    win_h,
                );
            }
        }

        use std::ops::DerefMut;
        flame::start("Encoder::flush");
        self.encoder
            .borrow_mut()
            .flush(self.device.borrow_mut().deref_mut());
        flame::end("Encoder::flush");

        flame::start("Window::swap_buffers");
        self.window.borrow_mut().swap_buffers().unwrap();
        flame::end("Window::swap_buffers");

        use gfx::Device;
        flame::start("Device::cleanup");
        self.device.borrow_mut().cleanup();
        flame::end("Device::cleanup");
    }
}

impl Program for ClientProgram {
    fn frame(&mut self, frame_duration: Duration) {
        let _guard = flame::start_guard("ClientProgram::frame");
        match *self.state.borrow_mut() {
            ProgramState::Title => unimplemented!(),

            ProgramState::Game(ref mut game) => {
                game.frame(frame_duration);
            }
        }

        flame::start("EventsLoop::poll_events");
        self.events_loop
            .borrow_mut()
            .poll_events(|event| match event {
                Event::WindowEvent {
                    event: WindowEvent::Closed,
                    ..
                } => {
                    // TODO: handle quit properly
                    flame::dump_html(File::create("flame.html").unwrap()).unwrap();
                    std::process::exit(0);
                }

                e => match *self.state.borrow_mut() {
                    ProgramState::Title => unimplemented!(),
                    ProgramState::Game(ref mut game) => game.handle_input(e),
                },
            });
        flame::end("EventsLoop::poll_events");

        match self.input.borrow().current_focus() {
            InputFocus::Game => {
                self.window
                    .borrow_mut()
                    .set_cursor_state(CursorState::Grab)
                    .unwrap();
                self.window.borrow_mut().set_cursor(MouseCursor::NoneCursor);
            }

            _ => {
                self.window
                    .borrow_mut()
                    .set_cursor_state(CursorState::Normal)
                    .unwrap();
                self.window.borrow_mut().set_cursor(MouseCursor::Default);
            }
        }

        // run console commands
        self.console.borrow().execute();

        self.render();
    }
}

fn main() {
    env_logger::init();

    let args: Vec<String> = env::args().collect();

    if args.len() != 2 {
        println!("Usage: {} <server_address>", args[0]);
        exit(1);
    }

    let mut client_program = ClientProgram::new();
    client_program.connect(&args[1]);
    let mut host = Host::new(client_program);

    loop {
        host.frame();
    }
}
<|endoftext|>


<commit_before>extern crate document;

use document::Nodeset;

use super::XPathEvaluationContext;
use super::XPathNodeTest;
use super::XPathValue;
use super::{Boolean,Number,String,Nodes};

use super::axis::XPathAxis;

pub trait XPathExpression {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue;
}

type SubExpression = Box<XPathExpression + 'static>;

pub struct ExpressionAnd {
    pub left:  SubExpression,
    pub right: SubExpression,
}

impl XPathExpression for ExpressionAnd {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        Boolean(self.left.evaluate(context).boolean() &&
                self.right.evaluate(context).boolean())
    }
}

pub struct ExpressionContextNode;

impl XPathExpression for ExpressionContextNode {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut result = Nodeset::new();
        result.add(context.node().clone());
        Nodes(result.clone())
    }
}

pub struct ExpressionEqual {
    pub left:  SubExpression,
    pub right: SubExpression,
}

impl ExpressionEqual {
    fn boolean_evaluate(& self, context: &XPathEvaluationContext) -> bool {
        let left_val = self.left.evaluate(context);
        let right_val = self.right.evaluate(context);

        match (&left_val, &right_val) {
            (&Boolean(_), _) |
            (_, &Boolean(_)) => left_val.boolean() == right_val.boolean(),
            (&Number(_), _) |
            (_, &Number(_)) => left_val.number() == right_val.number(),
            _ => left_val.string() == right_val.string()
        }
    }
}

impl XPathExpression for ExpressionEqual {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        Boolean(self.boolean_evaluate(context))
    }
}

pub struct ExpressionNotEqual {
    equal: ExpressionEqual,
}

impl ExpressionNotEqual {
    pub fn new(left: SubExpression, right: SubExpression) -> ExpressionNotEqual {
        ExpressionNotEqual {
            equal: ExpressionEqual{left: left, right: right}
        }
    }
}

impl XPathExpression for ExpressionNotEqual {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        Boolean(!self.equal.boolean_evaluate(context))
    }
}

pub struct ExpressionFunction {
    pub name: String,
    pub arguments: Vec<SubExpression>,
}

impl XPathExpression for ExpressionFunction {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        match context.function_for_name(self.name.as_slice()) {
            Some(fun) => {
                // TODO: Error when argument count mismatch
                let args = self.arguments.iter().map(|ref arg| arg.evaluate(context)).collect();

                fun.evaluate(context, args)
            },
            None => fail!("throw UnknownXPathFunctionException(_name)"),
        }
    }
}

pub struct ExpressionLiteral {
    pub value: XPathValue,
}

impl XPathExpression for ExpressionLiteral {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        self.value.clone()
    }
}

pub struct ExpressionMath {
    left:  SubExpression,
    right: SubExpression,
    operation: fn(f64, f64) -> f64,
}

fn      add(a: f64, b: f64) -> f64 {a + b}
fn subtract(a: f64, b: f64) -> f64 {a - b}
fn multiply(a: f64, b: f64) -> f64 {a * b}
fn   divide(a: f64, b: f64) -> f64 {a / b}
fn  modulus(a: f64, b: f64) -> f64 {a % b}

impl ExpressionMath {
    pub fn addition(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: add}
    }

    pub fn subtraction(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: subtract}
    }

    pub fn multiplication(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: multiply}
    }

    pub fn division(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: divide}
    }

    pub fn remainder(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: modulus}
    }
}

impl XPathExpression for ExpressionMath {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        let left = self.left.evaluate(context);
        let right = self.right.evaluate(context);
        let op = self.operation;
        return Number(op(left.number(), right.number()));
    }
}

pub struct ExpressionNegation {
    expression: SubExpression,
}

impl XPathExpression for ExpressionNegation {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        let result = self.expression.evaluate(context);
        return Number(-result.number());
    }
}

pub struct ExpressionOr {
    left:  SubExpression,
    right: SubExpression,
}

impl XPathExpression for ExpressionOr {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        return Boolean(self.left.evaluate(context).boolean() ||
                       self.right.evaluate(context).boolean())
    }
}

pub struct ExpressionPath {
    start_point: SubExpression,
    steps: Vec<SubExpression>,
}

impl XPathExpression for ExpressionPath {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        let mut result = self.start_point.evaluate(context).nodeset();

        for step in self.steps.iter() {
            let mut step_result = Nodeset::new();

            let mut sub_context = context.new_context_for(result.size());

            for current_node in result.iter() {
                sub_context.next(current_node.clone());
                let selected = step.evaluate(&sub_context);
                // TODO: What if it is not a nodeset?
                step_result.add_nodeset(&selected.nodeset());
            }

            result = step_result;
        }

        Nodes(result)
    }
}

pub struct ExpressionPredicate {
    pub node_selector: SubExpression,
    pub predicate: SubExpression,
}

impl ExpressionPredicate {
    fn include(value: &XPathValue, context: &XPathEvaluationContext) -> bool {
        match value {
            &Number(v) => context.position() == v as uint,
            _ => value.boolean()
        }
    }
}

impl XPathExpression for ExpressionPredicate {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut selected = Nodeset::new();

        let nodes = self.node_selector.evaluate(context).nodeset();

        let mut sub_context = context.new_context_for(nodes.size());

        for current_node in nodes.iter() {
            sub_context.next(current_node.clone());

            let value = self.predicate.evaluate(&sub_context);

            if ExpressionPredicate::include(&value, &sub_context) {
                selected.add(current_node.clone());
            }
        }

        Nodes(selected)
    }
}

pub struct ExpressionRelational {
    pub  left: SubExpression,
    pub right: SubExpression,
    pub operation: fn(f64, f64) -> bool,
}

fn             less_than(left: f64, right: f64) -> bool { left <  right }
fn    less_than_or_equal(left: f64, right: f64) -> bool { left <= right }
fn          greater_than(left: f64, right: f64) -> bool { left >  right }
fn greater_than_or_equal(left: f64, right: f64) -> bool { left >= right }

impl ExpressionRelational {
    pub fn less_than(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: less_than}
    }

    pub fn less_than_or_equal(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: less_than_or_equal}
    }

    pub fn greater_than(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: greater_than}
    }

    pub fn greater_than_or_equal(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: greater_than_or_equal}
    }
}

impl XPathExpression for ExpressionRelational {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let left_val = self.left.evaluate(context);
        let right_val = self.right.evaluate(context);
        let op = self.operation;
        Boolean(op(left_val.number(), right_val.number()))
    }
}

pub struct ExpressionRootNode;

impl XPathExpression for ExpressionRootNode {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let n = &context.node;

        let mut result = Nodeset::new();
        result.add(n.document().root());
        Nodes(result)
    }
}

type StepAxis = Box<XPathAxis + 'static>;
type StepTest = Box<XPathNodeTest + 'static>;

pub struct ExpressionStep {
    axis: StepAxis,
    node_test: StepTest,
}

impl ExpressionStep {
    pub fn new(axis: StepAxis, node_test: StepTest) -> ExpressionStep {
        ExpressionStep {axis: axis, node_test: node_test}
    }
}

impl XPathExpression for ExpressionStep {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut result = Nodeset::new();
        self.axis.select_nodes(context, self.node_test, & mut result);
        Nodes(result)
    }
}

pub struct ExpressionUnion {
    pub left:  SubExpression,
    pub right: SubExpression,
}

impl XPathExpression for ExpressionUnion {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut left_val = self.left.evaluate(context).nodeset();
        let right_val = self.right.evaluate(context).nodeset();
        left_val.add_nodeset(&right_val);
        Nodes(left_val)
    }
}

pub struct ExpressionVariable {
    pub name: String,
}

impl XPathExpression for ExpressionVariable {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        match context.value_of(self.name.as_slice()) {
            Some(v) => v.clone(),
            None => fail!("throw UnknownVariableException(_name)"),
        }
    }
}
<commit_msg>Fix warnings in expressions<commit_after>extern crate document;

use document::Nodeset;

use super::XPathEvaluationContext;
use super::XPathNodeTest;
use super::XPathValue;
use super::{Boolean,Number,Nodes};

use super::axis::XPathAxis;

pub trait XPathExpression {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue;
}

pub type SubExpression = Box<XPathExpression + 'static>;

pub struct ExpressionAnd {
    pub left:  SubExpression,
    pub right: SubExpression,
}

impl XPathExpression for ExpressionAnd {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        Boolean(self.left.evaluate(context).boolean() &&
                self.right.evaluate(context).boolean())
    }
}

pub struct ExpressionContextNode;

impl XPathExpression for ExpressionContextNode {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut result = Nodeset::new();
        result.add(context.node().clone());
        Nodes(result.clone())
    }
}

pub struct ExpressionEqual {
    pub left:  SubExpression,
    pub right: SubExpression,
}

impl ExpressionEqual {
    fn boolean_evaluate(& self, context: &XPathEvaluationContext) -> bool {
        let left_val = self.left.evaluate(context);
        let right_val = self.right.evaluate(context);

        match (&left_val, &right_val) {
            (&Boolean(_), _) |
            (_, &Boolean(_)) => left_val.boolean() == right_val.boolean(),
            (&Number(_), _) |
            (_, &Number(_)) => left_val.number() == right_val.number(),
            _ => left_val.string() == right_val.string()
        }
    }
}

impl XPathExpression for ExpressionEqual {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        Boolean(self.boolean_evaluate(context))
    }
}

pub struct ExpressionNotEqual {
    equal: ExpressionEqual,
}

impl ExpressionNotEqual {
    pub fn new(left: SubExpression, right: SubExpression) -> ExpressionNotEqual {
        ExpressionNotEqual {
            equal: ExpressionEqual{left: left, right: right}
        }
    }
}

impl XPathExpression for ExpressionNotEqual {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        Boolean(!self.equal.boolean_evaluate(context))
    }
}

pub struct ExpressionFunction {
    pub name: String,
    pub arguments: Vec<SubExpression>,
}

impl XPathExpression for ExpressionFunction {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        match context.function_for_name(self.name.as_slice()) {
            Some(fun) => {
                // TODO: Error when argument count mismatch
                let args = self.arguments.iter().map(|ref arg| arg.evaluate(context)).collect();

                fun.evaluate(context, args)
            },
            None => fail!("throw UnknownXPathFunctionException(_name)"),
        }
    }
}

pub struct ExpressionLiteral {
    pub value: XPathValue,
}

impl XPathExpression for ExpressionLiteral {
    fn evaluate(& self, _: &XPathEvaluationContext) -> XPathValue {
        self.value.clone()
    }
}

pub struct ExpressionMath {
    left:  SubExpression,
    right: SubExpression,
    operation: fn(f64, f64) -> f64,
}

fn      add(a: f64, b: f64) -> f64 {a + b}
fn subtract(a: f64, b: f64) -> f64 {a - b}
fn multiply(a: f64, b: f64) -> f64 {a * b}
fn   divide(a: f64, b: f64) -> f64 {a / b}
fn  modulus(a: f64, b: f64) -> f64 {a % b}

impl ExpressionMath {
    pub fn addition(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: add}
    }

    pub fn subtraction(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: subtract}
    }

    pub fn multiplication(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: multiply}
    }

    pub fn division(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: divide}
    }

    pub fn remainder(left: SubExpression, right: SubExpression) -> ExpressionMath {
        ExpressionMath{left: left, right: right, operation: modulus}
    }
}

impl XPathExpression for ExpressionMath {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        let left = self.left.evaluate(context);
        let right = self.right.evaluate(context);
        let op = self.operation;
        return Number(op(left.number(), right.number()));
    }
}

pub struct ExpressionNegation {
    expression: SubExpression,
}

impl XPathExpression for ExpressionNegation {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        let result = self.expression.evaluate(context);
        return Number(-result.number());
    }
}

pub struct ExpressionOr {
    left:  SubExpression,
    right: SubExpression,
}

impl XPathExpression for ExpressionOr {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        return Boolean(self.left.evaluate(context).boolean() ||
                       self.right.evaluate(context).boolean())
    }
}

pub struct ExpressionPath {
    start_point: SubExpression,
    steps: Vec<SubExpression>,
}

impl XPathExpression for ExpressionPath {
    fn evaluate(& self, context: &XPathEvaluationContext) -> XPathValue {
        let mut result = self.start_point.evaluate(context).nodeset();

        for step in self.steps.iter() {
            let mut step_result = Nodeset::new();

            let mut sub_context = context.new_context_for(result.size());

            for current_node in result.iter() {
                sub_context.next(current_node.clone());
                let selected = step.evaluate(&sub_context);
                // TODO: What if it is not a nodeset?
                step_result.add_nodeset(&selected.nodeset());
            }

            result = step_result;
        }

        Nodes(result)
    }
}

pub struct ExpressionPredicate {
    pub node_selector: SubExpression,
    pub predicate: SubExpression,
}

impl ExpressionPredicate {
    fn include(value: &XPathValue, context: &XPathEvaluationContext) -> bool {
        match value {
            &Number(v) => context.position() == v as uint,
            _ => value.boolean()
        }
    }
}

impl XPathExpression for ExpressionPredicate {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut selected = Nodeset::new();

        let nodes = self.node_selector.evaluate(context).nodeset();

        let mut sub_context = context.new_context_for(nodes.size());

        for current_node in nodes.iter() {
            sub_context.next(current_node.clone());

            let value = self.predicate.evaluate(&sub_context);

            if ExpressionPredicate::include(&value, &sub_context) {
                selected.add(current_node.clone());
            }
        }

        Nodes(selected)
    }
}

pub struct ExpressionRelational {
    pub  left: SubExpression,
    pub right: SubExpression,
    pub operation: fn(f64, f64) -> bool,
}

fn             less_than(left: f64, right: f64) -> bool { left <  right }
fn    less_than_or_equal(left: f64, right: f64) -> bool { left <= right }
fn          greater_than(left: f64, right: f64) -> bool { left >  right }
fn greater_than_or_equal(left: f64, right: f64) -> bool { left >= right }

impl ExpressionRelational {
    pub fn less_than(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: less_than}
    }

    pub fn less_than_or_equal(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: less_than_or_equal}
    }

    pub fn greater_than(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: greater_than}
    }

    pub fn greater_than_or_equal(left: SubExpression, right: SubExpression) -> ExpressionRelational
    {
        ExpressionRelational{left: left, right: right, operation: greater_than_or_equal}
    }
}

impl XPathExpression for ExpressionRelational {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let left_val = self.left.evaluate(context);
        let right_val = self.right.evaluate(context);
        let op = self.operation;
        Boolean(op(left_val.number(), right_val.number()))
    }
}

pub struct ExpressionRootNode;

impl XPathExpression for ExpressionRootNode {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let n = &context.node;

        let mut result = Nodeset::new();
        result.add(n.document().root());
        Nodes(result)
    }
}

pub type StepAxis = Box<XPathAxis + 'static>;
pub type StepTest = Box<XPathNodeTest + 'static>;

pub struct ExpressionStep {
    axis: StepAxis,
    node_test: StepTest,
}

impl ExpressionStep {
    pub fn new(axis: StepAxis, node_test: StepTest) -> ExpressionStep {
        ExpressionStep {axis: axis, node_test: node_test}
    }
}

impl XPathExpression for ExpressionStep {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut result = Nodeset::new();
        self.axis.select_nodes(context, self.node_test, & mut result);
        Nodes(result)
    }
}

pub struct ExpressionUnion {
    pub left:  SubExpression,
    pub right: SubExpression,
}

impl XPathExpression for ExpressionUnion {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        let mut left_val = self.left.evaluate(context).nodeset();
        let right_val = self.right.evaluate(context).nodeset();
        left_val.add_nodeset(&right_val);
        Nodes(left_val)
    }
}

pub struct ExpressionVariable {
    pub name: String,
}

impl XPathExpression for ExpressionVariable {
    fn evaluate(&self, context: &XPathEvaluationContext) -> XPathValue {
        match context.value_of(self.name.as_slice()) {
            Some(v) => v.clone(),
            None => fail!("throw UnknownVariableException(_name)"),
        }
    }
}
<|endoftext|>


<commit_before>//! This is NOT a real example. This is a test designed to see if we can actually run the turtle
//! process

use std::process;

use turtle::Drawing;

fn main() {
    let mut drawing = Drawing::new();
    let mut turtle = drawing.add_turtle();

    turtle.set_speed(2);
    turtle.right(90.0);
    turtle.forward(50.0);

    process::exit(0);
}
<commit_msg>Noting that runtest doesn't currently work since it can't close the window<commit_after>//! This is NOT a real example. This is a test designed to see if we can actually run the turtle
//! process

use std::process;

use turtle::Turtle;

fn main() {
    let mut turtle = Turtle::new();

    turtle.set_speed(2);
    turtle.right(90.0);
    turtle.forward(50.0);

    //TODO: Exiting the process currently doesn't cause the window to get closed. We should add a
    // `close(self)` or `quit(self)` method to `Drawing` that closes the window explicitly.
    process::exit(0);
}
<|endoftext|>