<commit_before>//! Server-side Wayland connector
//!
//! # Overview
//!
//! Setting up the listening socket is done by the `create_display`
//! function, providing you a `Display` object and an `EventLoop`.
//!
//! On the event loop, you'll be able to register the globals
//! you want to advertize, as well as handlers for all ressources
//! created by the clients.
//!
//! You then integrate the wayland event loop in your main event
//! loop to run your compositor.
//!
//! # Handlers and event loop
//!
//! This crate mirrors the callback-oriented design of the
//! Wayland C library by using handler structs: each wayland
//! type defines a `Handler` trait in its module, which one
//! method for each possible requests this object can receive.
//!
//! To use it, you need to build a struct (or enum) that will
//! implement all the traits for all the requests you are interested
//! in. All methods of handler traits provide a default
//! implementation foing nothing, so you don't need to write
//! empty methods for events you want to ignore. You also need
//! to declare the handler capability for your struct using
//! the `declare_handler!(..)` macro. A single struct can be
//! handler for several wayland interfaces at once.
//!
//! ## Example of handler
//!
//! ```ignore
//! /*  writing a handler for an wl_foo interface */
//! // import the module of this interface
//! use wl_foo;
//!
//! struct MyHandler { /* some fields to store state */ }
//!
//! // implement handerl trait:
//! impl wl_foo::Handler for MyHandler {
//!     fn a_request(&mut self,
//!                  evlh: &mut EventLoopHandle,
//!                  client: &Client,
//!                  me: &wl_foo::WlFoo,
//!                  arg1, arg2, // the actual args of the request
//!     ) {
//!         /* handle the request */
//!     }
//! }
//!
//! // declare the handler capability
//! // this boring step is necessary because Rust's type system is
//! // not yet magical enough
//! declare_handler!(MyHandler, wl_foo::Handler, wl_foo::WlFoo);
//! ```
//!
//! ## Event Loop and handlers
//!
//! In your initialization code, you'll need to instantiate
//! your handler and give it to the event queue:
//!
//! ```ignore
//! let handler_id = event_loop.add_handler(MyHandler::new());
//! ```
//!
//! Then, you can register your wayland objects to this handler:
//!
//! ```ignore
//! // This type info is necessary for safety, as at registration
//! // time the event_loop will check that the handler you
//! // specified using handler_id has the same type as provided
//! // as argument, and that this type implements the appropriate
//! // handler trait.
//! event_loop.register::<_, MyHandler>(&my_object, handler_id);
//! ```
//!
//! You can have several handlers in the same event loop,
//! but they cannot share their state without synchronisation
//! primitives like `Arc`, `Mutex` and friends, so if two handlers
//! need to share some state, you should consider building them
//! as a single struct.
//!
//! A given wayland object can only be registered to a single
//! handler at a given time, re-registering it to a new handler
//! will overwrite the previous configuration.
//!
//! Handlers can be created, and objects registered to them
//! from within a handler method, using the `&EventLoopHandle`
//! argument.
//!
//! ## Globals declaration
//!
//! Declaring a global is quite similar to declaring a handler
//! for a ressource. But this time via the `GlobalHandler<R>` trait.
//!
//! This trait declares a single method, `bind`, which is called
//! whenever a client binds this global, providing you with
//! a ressource object representing the newly-created global.
//!
//! You can do what you please with this object, storing it for
//! later if you'll need to send it events, or just let it go
//! go out of scope after having registered it to the appropriate
//! handler.
//!
//! To register globals on the event loop, you need the
//! `register_global` method:
//!
//! ```ignore
//! struct MyHandler { /* ... */ }
//!
//! // creating a handler for the global wl_foo
//! impl GlobalHandler<WlFoo> for MyHandler {
//!     fn bind(&mut self,
//!             evlh: &mut EventLoopHandle,
//!             client: &Client,
//!             global: WlFoo
//!     ) {
//!         /* do something with it */
//!     }
//! }
//!
//! /* ... */
//!
//! // then somewhere in the initialization code
//! let handler_id = event_loop.add_handler(MyHandler::new());
//! // bind this handler to a global for interface wl_foo version 3
//! // specifying the types is mandatory, and compability of this
//! // handler with the global is checked at registration time.
//! let foo = event_loop.register_global::<WlFoo, MyHandler>(handler_is, 3);
//! // foo contains a handle to the global, that you can use later
//! // to destroy it:
//! foo.destroy();
//! // if you don't plan to ever destroy this global, you can ignore
//! // this return value, letting it out of scope will not destroy
//! // the global.
//! ```
//!
//! ## Event loop integration
//!
//! Once the setup phase is done, you can integrate the
//! event loop in the main event loop of your program.
//!
//! Either all you need is for it to run indefinitely (external
//! events are checked in an other thread?):
//!
//! ```ignore
//! event_loop.run();
//! ```
//!
//! Or you can integrate it with more control:
//!
//! ```ignore
//! loop {
//!     // flush events to client sockets
//!     display.flush_clients();
//!     // receive request from clients and dispatch them
//!     // blocking if no request is pending for at most
//!     // 10ms
//!     event_loop.dispatch(Some(10)).unwrap();
//!     // then you can check events from other sources if
//!     // you need to
//! }
//! ```
//!
//! # Protocols integration
//!
//! This crate provides the basic primitives as well as the
//! core wayland protocol (in the `protocol` module), but
//! other protocols can be integrated from XML descriptions.
//!
//! The the crate `wayland_scanner` and its documentation for
//! details about how to do so.

#![warn(missing_docs)]

#[macro_use] extern crate bitflags;
#[macro_use] extern crate wayland_sys;
extern crate libc;
extern crate nix;

pub use generated::server as protocol;
pub use generated::interfaces as protocol_interfaces;

pub use client::Client;
pub use display::{Display, create_display};
pub use event_loop::{EventLoop, EventLoopHandle, StateGuard, Global, GlobalHandler, Init, Destroy,
                     resource_is_registered, RegisterStatus};

use wayland_sys::server::*;
use wayland_sys::common::{wl_interface, wl_argument};

mod client;
mod display;
mod event_loop;
mod event_sources;

pub mod sources {
    //! Secondary event sources
    //!
    //! This module contains the types & traits to work with
    //! different kind of event sources that can be registered to and
    //! event loop, other than the wayland protocol sockets.
    pub use ::event_sources::{FdEventSource, FdEventSourceHandler};
    pub use ::event_sources::{FdInterest, READ, WRITE};
    pub use ::event_sources::{TimerEventSource, TimerEventSourceHandler};
    pub use ::event_sources::{SignalEventSource, SignalEventSourceHandler};
}

/// Common routines for wayland resource objects.
///
/// All wayland objects automatically implement this trait
/// as generated by the scanner.
///
/// It is mostly used for internal use by the library, and you
/// should only need these methods for interfacing with C library
/// working on wayland objects.
pub trait Resource {
    /// Pointer to the underlying wayland proxy object
    fn ptr(&self) -> *mut wl_resource;
    /// Create an instance from a wayland pointer
    ///
    /// The pointer must refer to a valid wayland resource
    /// of the appropriate interface, but that have not yet
    /// been seen by the library.
    ///
    /// The library will take control of the object (notably
    /// overwrite its user_data).
    unsafe fn from_ptr_new(*mut wl_resource) -> Self;
    /// Create an instance from a wayland pointer
    ///
    /// The pointer must refer to a valid wayland resource
    /// of the appropriate interface. The library will detect if the
    /// resource is already managed by it or not. If it is not, this
    /// resource will be considered as "unmanaged", and should then
    /// be handled with care.
    unsafe fn from_ptr_initialized(*mut wl_resource) -> Self;
    /// Pointer to the interface representation
    fn interface_ptr() -> *const wl_interface;
    /// Internal wayland name of this interface
    fn interface_name() -> &'static str;
    /// Max version of this interface supported
    fn supported_version() -> u32;
    /// Current version of the interface this resource is instantiated with
    fn version(&self) -> i32;
    /// Check if the resource behind this handle is actually still alive
    fn status(&self) -> Liveness;
    /// Check of two handles are actually the same wayland object
    ///
    /// Returns `false` if any of the objects has already been destroyed
    fn equals(&self, &Self) -> bool;
    /// Set a pointer associated as user data on this resource
    ///
    /// All handles to the same wayland object share the same user data pointer.
    ///
    /// The get/set operations are atomic, no more guarantee is given. If you need
    /// to synchronise access to this data, it is your responsibility to add a Mutex
    /// or any other similar mechanism.
    fn set_user_data(&self, ptr: *mut ());
    /// Get the pointer associated as user data on this resource
    ///
    /// All handles to the same wayland object share the same user data pointer.
    ///
    /// See `set_user_data` for synchronisation guarantee.
    fn get_user_data(&self) -> *mut ();
    /// Posts a protocol error to this resource
    ///
    /// The error code can be obtained from the various `Error` enums of the protocols.
    ///
    /// An error is fatal to the client that caused it.
    fn post_error(&self, error_code: u32, msg: String) {
        // If `str` contains an interior null, the actuall transmitted message will
        // be truncated at this point.
        unsafe {
            let cstring = ::std::ffi::CString::from_vec_unchecked(msg.into());
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_post_error,
                self.ptr(),
                error_code,
                cstring.as_ptr()
            )
        }
    }
    /// Clone this resource handle
    ///
    /// Will only succeed if the resource is managed by this library and
    /// is still alive.
    fn clone(&self) -> Option<Self> where Self: Sized {
        if self.status() == Liveness::Alive {
            Some(unsafe { self.clone_unchecked() })
        } else {
            None
        }

    }
    /// Unsafely clone this resource handle
    ///
    /// This function is unsafe because if the resource is unmanaged, the lib
    /// has no knowledge of its lifetime, and cannot ensure that the new handle
    /// will not outlive the object.
    unsafe fn clone_unchecked(&self) -> Self where Self: Sized {
        // TODO: this can be more optimized with codegen help, but would be a
        // breaking change, so do it at next breaking release
        Self::from_ptr_initialized(self.ptr())
    }
}

/// Possible outcome of the call of a event on a resource
pub enum EventResult<T> {
    /// Message has been buffered and will be sent to client
    Sent(T),
    /// This resource is already destroyed, request has been ignored
    Destroyed
}

impl<T> EventResult<T> {
    /// Assert that result is successfull and extract the value.
    ///
    /// Panics with provided error message if the result was `Destroyed`.
    pub fn expect(self, error: &str) -> T {
        match self {
            EventResult::Sent(v) => v,
            EventResult::Destroyed => panic!("{}", error)
        }
    }
}

/// Generic handler trait
///
/// This trait is automatically implemented for objects that implement
/// the appropriate interface-specific `Handler` traits. It represents
/// the hability for a type to handle events directed to a given wayland
/// interface.
///
/// For example, implementing `wl_surface::Handler` for you type will
/// automatically provide it with an implementation of
/// `Handler<WlSurface>` as well. This is the only correct way
/// to implement this trait, and you should not attempt to implement it
/// yourself.
pub unsafe trait Handler<T: Resource> {
    /// Dispatch a message.
    unsafe fn message(&mut self, evq: &mut EventLoopHandle, client: &Client, resource: &T, opcode: u32, args: *const wl_argument) -> Result<(),()>;
}

/// Represents the state of liveness of a wayland object
#[derive(Copy,Clone,PartialEq,Eq)]
pub enum Liveness {
    /// This object is alive and events can be sent to it
    Alive,
    /// This object is dead, sending it events will do nothing and
    /// return and error.
    Dead,
    /// This object is not managed by `wayland-server`, you can send it events
    /// but this might crash the program if it was actually dead.
    Unmanaged
}

mod generated {
    #![allow(dead_code,non_camel_case_types,unused_unsafe,unused_variables)]
    #![allow(non_upper_case_globals,non_snake_case,unused_imports)]
    #![allow(missing_docs)]

    pub mod interfaces {
        //! Interfaces for the core protocol
        //!
        //! You might need them for the bindings generated for protocol extensions
        include!(concat!(env!("OUT_DIR"), "/wayland_interfaces.rs"));
    }

    pub mod server {
        //! The wayland core protocol
        //!
        //! This module contains all objects of the core wayland protocol.
        //!
        //! It has been generated from the `wayland.xml` protocol file
        //! using `wayland_scanner`.
        // Imports that need to be available to submodules
        // but should not be in public API.
        // Will be fixable with pub(restricted).
        #[doc(hidden)] pub use {Resource, EventLoopHandle, Handler, Client, EventResult, Liveness};
        #[doc(hidden)] pub use super::interfaces;

        include!(concat!(env!("OUT_DIR"), "/wayland_api.rs"));
    }
}

pub mod sys {
    //! Reexports of types and objects from wayland-sys
    pub use wayland_sys::server::*;
    pub use wayland_sys::common::*;
}
<commit_msg>server: make RequestResult impl Debug<commit_after>//! Server-side Wayland connector
//!
//! # Overview
//!
//! Setting up the listening socket is done by the `create_display`
//! function, providing you a `Display` object and an `EventLoop`.
//!
//! On the event loop, you'll be able to register the globals
//! you want to advertize, as well as handlers for all ressources
//! created by the clients.
//!
//! You then integrate the wayland event loop in your main event
//! loop to run your compositor.
//!
//! # Handlers and event loop
//!
//! This crate mirrors the callback-oriented design of the
//! Wayland C library by using handler structs: each wayland
//! type defines a `Handler` trait in its module, which one
//! method for each possible requests this object can receive.
//!
//! To use it, you need to build a struct (or enum) that will
//! implement all the traits for all the requests you are interested
//! in. All methods of handler traits provide a default
//! implementation foing nothing, so you don't need to write
//! empty methods for events you want to ignore. You also need
//! to declare the handler capability for your struct using
//! the `declare_handler!(..)` macro. A single struct can be
//! handler for several wayland interfaces at once.
//!
//! ## Example of handler
//!
//! ```ignore
//! /*  writing a handler for an wl_foo interface */
//! // import the module of this interface
//! use wl_foo;
//!
//! struct MyHandler { /* some fields to store state */ }
//!
//! // implement handerl trait:
//! impl wl_foo::Handler for MyHandler {
//!     fn a_request(&mut self,
//!                  evlh: &mut EventLoopHandle,
//!                  client: &Client,
//!                  me: &wl_foo::WlFoo,
//!                  arg1, arg2, // the actual args of the request
//!     ) {
//!         /* handle the request */
//!     }
//! }
//!
//! // declare the handler capability
//! // this boring step is necessary because Rust's type system is
//! // not yet magical enough
//! declare_handler!(MyHandler, wl_foo::Handler, wl_foo::WlFoo);
//! ```
//!
//! ## Event Loop and handlers
//!
//! In your initialization code, you'll need to instantiate
//! your handler and give it to the event queue:
//!
//! ```ignore
//! let handler_id = event_loop.add_handler(MyHandler::new());
//! ```
//!
//! Then, you can register your wayland objects to this handler:
//!
//! ```ignore
//! // This type info is necessary for safety, as at registration
//! // time the event_loop will check that the handler you
//! // specified using handler_id has the same type as provided
//! // as argument, and that this type implements the appropriate
//! // handler trait.
//! event_loop.register::<_, MyHandler>(&my_object, handler_id);
//! ```
//!
//! You can have several handlers in the same event loop,
//! but they cannot share their state without synchronisation
//! primitives like `Arc`, `Mutex` and friends, so if two handlers
//! need to share some state, you should consider building them
//! as a single struct.
//!
//! A given wayland object can only be registered to a single
//! handler at a given time, re-registering it to a new handler
//! will overwrite the previous configuration.
//!
//! Handlers can be created, and objects registered to them
//! from within a handler method, using the `&EventLoopHandle`
//! argument.
//!
//! ## Globals declaration
//!
//! Declaring a global is quite similar to declaring a handler
//! for a ressource. But this time via the `GlobalHandler<R>` trait.
//!
//! This trait declares a single method, `bind`, which is called
//! whenever a client binds this global, providing you with
//! a ressource object representing the newly-created global.
//!
//! You can do what you please with this object, storing it for
//! later if you'll need to send it events, or just let it go
//! go out of scope after having registered it to the appropriate
//! handler.
//!
//! To register globals on the event loop, you need the
//! `register_global` method:
//!
//! ```ignore
//! struct MyHandler { /* ... */ }
//!
//! // creating a handler for the global wl_foo
//! impl GlobalHandler<WlFoo> for MyHandler {
//!     fn bind(&mut self,
//!             evlh: &mut EventLoopHandle,
//!             client: &Client,
//!             global: WlFoo
//!     ) {
//!         /* do something with it */
//!     }
//! }
//!
//! /* ... */
//!
//! // then somewhere in the initialization code
//! let handler_id = event_loop.add_handler(MyHandler::new());
//! // bind this handler to a global for interface wl_foo version 3
//! // specifying the types is mandatory, and compability of this
//! // handler with the global is checked at registration time.
//! let foo = event_loop.register_global::<WlFoo, MyHandler>(handler_is, 3);
//! // foo contains a handle to the global, that you can use later
//! // to destroy it:
//! foo.destroy();
//! // if you don't plan to ever destroy this global, you can ignore
//! // this return value, letting it out of scope will not destroy
//! // the global.
//! ```
//!
//! ## Event loop integration
//!
//! Once the setup phase is done, you can integrate the
//! event loop in the main event loop of your program.
//!
//! Either all you need is for it to run indefinitely (external
//! events are checked in an other thread?):
//!
//! ```ignore
//! event_loop.run();
//! ```
//!
//! Or you can integrate it with more control:
//!
//! ```ignore
//! loop {
//!     // flush events to client sockets
//!     display.flush_clients();
//!     // receive request from clients and dispatch them
//!     // blocking if no request is pending for at most
//!     // 10ms
//!     event_loop.dispatch(Some(10)).unwrap();
//!     // then you can check events from other sources if
//!     // you need to
//! }
//! ```
//!
//! # Protocols integration
//!
//! This crate provides the basic primitives as well as the
//! core wayland protocol (in the `protocol` module), but
//! other protocols can be integrated from XML descriptions.
//!
//! The the crate `wayland_scanner` and its documentation for
//! details about how to do so.

#![warn(missing_docs)]

#[macro_use] extern crate bitflags;
#[macro_use] extern crate wayland_sys;
extern crate libc;
extern crate nix;

pub use generated::server as protocol;
pub use generated::interfaces as protocol_interfaces;

pub use client::Client;
pub use display::{Display, create_display};
pub use event_loop::{EventLoop, EventLoopHandle, StateGuard, Global, GlobalHandler, Init, Destroy,
                     resource_is_registered, RegisterStatus};

use wayland_sys::server::*;
use wayland_sys::common::{wl_interface, wl_argument};

mod client;
mod display;
mod event_loop;
mod event_sources;

pub mod sources {
    //! Secondary event sources
    //!
    //! This module contains the types & traits to work with
    //! different kind of event sources that can be registered to and
    //! event loop, other than the wayland protocol sockets.
    pub use ::event_sources::{FdEventSource, FdEventSourceHandler};
    pub use ::event_sources::{FdInterest, READ, WRITE};
    pub use ::event_sources::{TimerEventSource, TimerEventSourceHandler};
    pub use ::event_sources::{SignalEventSource, SignalEventSourceHandler};
}

/// Common routines for wayland resource objects.
///
/// All wayland objects automatically implement this trait
/// as generated by the scanner.
///
/// It is mostly used for internal use by the library, and you
/// should only need these methods for interfacing with C library
/// working on wayland objects.
pub trait Resource {
    /// Pointer to the underlying wayland proxy object
    fn ptr(&self) -> *mut wl_resource;
    /// Create an instance from a wayland pointer
    ///
    /// The pointer must refer to a valid wayland resource
    /// of the appropriate interface, but that have not yet
    /// been seen by the library.
    ///
    /// The library will take control of the object (notably
    /// overwrite its user_data).
    unsafe fn from_ptr_new(*mut wl_resource) -> Self;
    /// Create an instance from a wayland pointer
    ///
    /// The pointer must refer to a valid wayland resource
    /// of the appropriate interface. The library will detect if the
    /// resource is already managed by it or not. If it is not, this
    /// resource will be considered as "unmanaged", and should then
    /// be handled with care.
    unsafe fn from_ptr_initialized(*mut wl_resource) -> Self;
    /// Pointer to the interface representation
    fn interface_ptr() -> *const wl_interface;
    /// Internal wayland name of this interface
    fn interface_name() -> &'static str;
    /// Max version of this interface supported
    fn supported_version() -> u32;
    /// Current version of the interface this resource is instantiated with
    fn version(&self) -> i32;
    /// Check if the resource behind this handle is actually still alive
    fn status(&self) -> Liveness;
    /// Check of two handles are actually the same wayland object
    ///
    /// Returns `false` if any of the objects has already been destroyed
    fn equals(&self, &Self) -> bool;
    /// Set a pointer associated as user data on this resource
    ///
    /// All handles to the same wayland object share the same user data pointer.
    ///
    /// The get/set operations are atomic, no more guarantee is given. If you need
    /// to synchronise access to this data, it is your responsibility to add a Mutex
    /// or any other similar mechanism.
    fn set_user_data(&self, ptr: *mut ());
    /// Get the pointer associated as user data on this resource
    ///
    /// All handles to the same wayland object share the same user data pointer.
    ///
    /// See `set_user_data` for synchronisation guarantee.
    fn get_user_data(&self) -> *mut ();
    /// Posts a protocol error to this resource
    ///
    /// The error code can be obtained from the various `Error` enums of the protocols.
    ///
    /// An error is fatal to the client that caused it.
    fn post_error(&self, error_code: u32, msg: String) {
        // If `str` contains an interior null, the actuall transmitted message will
        // be truncated at this point.
        unsafe {
            let cstring = ::std::ffi::CString::from_vec_unchecked(msg.into());
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_post_error,
                self.ptr(),
                error_code,
                cstring.as_ptr()
            )
        }
    }
    /// Clone this resource handle
    ///
    /// Will only succeed if the resource is managed by this library and
    /// is still alive.
    fn clone(&self) -> Option<Self> where Self: Sized {
        if self.status() == Liveness::Alive {
            Some(unsafe { self.clone_unchecked() })
        } else {
            None
        }

    }
    /// Unsafely clone this resource handle
    ///
    /// This function is unsafe because if the resource is unmanaged, the lib
    /// has no knowledge of its lifetime, and cannot ensure that the new handle
    /// will not outlive the object.
    unsafe fn clone_unchecked(&self) -> Self where Self: Sized {
        // TODO: this can be more optimized with codegen help, but would be a
        // breaking change, so do it at next breaking release
        Self::from_ptr_initialized(self.ptr())
    }
}

/// Possible outcome of the call of a event on a resource
#[derive(Debug)]
pub enum EventResult<T> {
    /// Message has been buffered and will be sent to client
    Sent(T),
    /// This resource is already destroyed, request has been ignored
    Destroyed
}

impl<T> EventResult<T> {
    /// Assert that result is successfull and extract the value.
    ///
    /// Panics with provided error message if the result was `Destroyed`.
    pub fn expect(self, error: &str) -> T {
        match self {
            EventResult::Sent(v) => v,
            EventResult::Destroyed => panic!("{}", error)
        }
    }
}

/// Generic handler trait
///
/// This trait is automatically implemented for objects that implement
/// the appropriate interface-specific `Handler` traits. It represents
/// the hability for a type to handle events directed to a given wayland
/// interface.
///
/// For example, implementing `wl_surface::Handler` for you type will
/// automatically provide it with an implementation of
/// `Handler<WlSurface>` as well. This is the only correct way
/// to implement this trait, and you should not attempt to implement it
/// yourself.
pub unsafe trait Handler<T: Resource> {
    /// Dispatch a message.
    unsafe fn message(&mut self, evq: &mut EventLoopHandle, client: &Client, resource: &T, opcode: u32, args: *const wl_argument) -> Result<(),()>;
}

/// Represents the state of liveness of a wayland object
#[derive(Copy,Clone,PartialEq,Eq)]
pub enum Liveness {
    /// This object is alive and events can be sent to it
    Alive,
    /// This object is dead, sending it events will do nothing and
    /// return and error.
    Dead,
    /// This object is not managed by `wayland-server`, you can send it events
    /// but this might crash the program if it was actually dead.
    Unmanaged
}

mod generated {
    #![allow(dead_code,non_camel_case_types,unused_unsafe,unused_variables)]
    #![allow(non_upper_case_globals,non_snake_case,unused_imports)]
    #![allow(missing_docs)]

    pub mod interfaces {
        //! Interfaces for the core protocol
        //!
        //! You might need them for the bindings generated for protocol extensions
        include!(concat!(env!("OUT_DIR"), "/wayland_interfaces.rs"));
    }

    pub mod server {
        //! The wayland core protocol
        //!
        //! This module contains all objects of the core wayland protocol.
        //!
        //! It has been generated from the `wayland.xml` protocol file
        //! using `wayland_scanner`.
        // Imports that need to be available to submodules
        // but should not be in public API.
        // Will be fixable with pub(restricted).
        #[doc(hidden)] pub use {Resource, EventLoopHandle, Handler, Client, EventResult, Liveness};
        #[doc(hidden)] pub use super::interfaces;

        include!(concat!(env!("OUT_DIR"), "/wayland_api.rs"));
    }
}

pub mod sys {
    //! Reexports of types and objects from wayland-sys
    pub use wayland_sys::server::*;
    pub use wayland_sys::common::*;
}
<|endoftext|>


<commit_before>use hir::{AdtDef, Ty, TypeCtor};

use crate::completion::completion_item::{Builder, CompletionKind};
use crate::{
    completion::{completion_context::CompletionContext, completion_item::Completions},
    CompletionItem,
};
use ra_syntax::ast::AstNode;
use ra_syntax::TextRange;
use ra_text_edit::TextEditBuilder;
use rustc_hash::FxHashSet;

/// Complete dot accesses, i.e. fields or methods (and .await syntax).
pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
    if let Some(dot_receiver) = &ctx.dot_receiver {
        let receiver_ty = ctx.analyzer.type_of(ctx.db, &dot_receiver);

        if let Some(receiver_ty) = receiver_ty {
            if !ctx.is_call {
                complete_fields(acc, ctx, receiver_ty.clone());
            }
            complete_methods(acc, ctx, receiver_ty.clone());

            // Suggest .await syntax for types that implement Future trait
            if ctx.analyzer.impls_future(ctx.db, receiver_ty) {
                CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), "await")
                    .detail("expr.await")
                    .insert_text("await")
                    .add_to(acc);
            }
        }
    }
}

fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) {
    for receiver in ctx.analyzer.autoderef(ctx.db, receiver) {
        if let Ty::Apply(a_ty) = receiver {
            match a_ty.ctor {
                TypeCtor::Adt(AdtDef::Struct(s)) => {
                    for field in s.fields(ctx.db) {
                        acc.add_field(ctx, field, &a_ty.parameters);
                    }
                }
                // FIXME unions
                TypeCtor::Tuple { .. } => {
                    for (i, ty) in a_ty.parameters.iter().enumerate() {
                        acc.add_pos_field(ctx, i, ty);
                    }
                }
                _ => {}
            }
        };
    }
}

fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) {
    let mut seen_methods = FxHashSet::default();
    ctx.analyzer.iterate_method_candidates(ctx.db, receiver, None, |_ty, func| {
        let data = func.data(ctx.db);
        if data.has_self_param() && seen_methods.insert(data.name().clone()) {
            acc.add_function(ctx, func);
        }
        None::<()>
    });
}

#[cfg(test)]
mod tests {
    use crate::completion::{do_completion, CompletionItem, CompletionKind};
    use insta::assert_debug_snapshot_matches;

    fn do_ref_completion(code: &str) -> Vec<CompletionItem> {
        do_completion(code, CompletionKind::Reference)
    }

    #[test]
    fn test_struct_field_completion() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
                r"
                struct A { the_field: u32 }
                fn foo(a: A) {
                a.<|>
                }
                ",
        ),
            @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [94; 94),
       ⋮        delete: [94; 94),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "u32",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_struct_field_completion_self() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {
                /// This is the_field
                the_field: (u32,)
            }
            impl A {
                fn foo(self) {
                    self.<|>
                }
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "foo",
       ⋮        source_range: [187; 187),
       ⋮        delete: [187; 187),
       ⋮        insert: "foo()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn foo(self)",
       ⋮    },
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [187; 187),
       ⋮        delete: [187; 187),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "(u32,)",
       ⋮        documentation: Documentation(
       ⋮            "This is the_field",
       ⋮        ),
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_struct_field_completion_autoderef() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A { the_field: (u32, i32) }
            impl A {
                fn foo(&self) {
                    self.<|>
                }
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "foo",
       ⋮        source_range: [126; 126),
       ⋮        delete: [126; 126),
       ⋮        insert: "foo()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn foo(&self)",
       ⋮    },
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [126; 126),
       ⋮        delete: [126; 126),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "(u32, i32)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_no_struct_field_completion_for_method_call() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A { the_field: u32 }
            fn foo(a: A) {
               a.<|>()
            }
            ",
        ),
        @"[]"
        );
    }

    #[test]
    fn test_method_completion() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {}
            impl A {
                fn the_method(&self) {}
            }
            fn foo(a: A) {
               a.<|>
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [144; 144),
       ⋮        delete: [144; 144),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_trait_method_completion() {
        assert_debug_snapshot_matches!(
            do_ref_completion(
                r"
            struct A {}
            trait Trait { fn the_method(&self); }
            impl Trait for A {}
            fn foo(a: A) {
               a.<|>
            }
            ",
            ),
            @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [151; 151),
       ⋮        delete: [151; 151),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_trait_method_completion_deduplicated() {
        assert_debug_snapshot_matches!(
            do_ref_completion(
                r"
            struct A {}
            trait Trait { fn the_method(&self); }
            impl<T> Trait for T {}
            fn foo(a: &A) {
               a.<|>
            }
            ",
            ),
            @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [155; 155),
       ⋮        delete: [155; 155),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_no_non_self_method() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {}
            impl A {
                fn the_method() {}
            }
            fn foo(a: A) {
               a.<|>
            }
            ",
        ),
        @"[]"
        );
    }

    #[test]
    fn test_method_attr_filtering() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {}
            impl A {
                #[inline]
                fn the_method(&self) {
                    let x = 1;
                    let y = 2;
                }
            }
            fn foo(a: A) {
               a.<|>
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [249; 249),
       ⋮        delete: [249; 249),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_tuple_field_completion() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            fn foo() {
               let b = (0, 3.14);
               b.<|>
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "0",
       ⋮        source_range: [75; 75),
       ⋮        delete: [75; 75),
       ⋮        insert: "0",
       ⋮        kind: Field,
       ⋮        detail: "i32",
       ⋮    },
       ⋮    CompletionItem {
       ⋮        label: "1",
       ⋮        source_range: [75; 75),
       ⋮        delete: [75; 75),
       ⋮        insert: "1",
       ⋮        kind: Field,
       ⋮        detail: "f64",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_tuple_field_inference() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            pub struct S;
            impl S {
                pub fn blah(&self) {}
            }

            struct T(S);

            impl T {
                fn foo(&self) {
                    // FIXME: This doesn't work without the trailing `a` as `0.` is a float
                    self.0.a<|>
                }
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "blah",
       ⋮        source_range: [299; 300),
       ⋮        delete: [299; 300),
       ⋮        insert: "blah()$0",
       ⋮        kind: Method,
       ⋮        detail: "pub fn blah(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_completion_works_in_consts() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A { the_field: u32 }
            const X: u32 = {
                A { the_field: 92 }.<|>
            };
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [106; 106),
       ⋮        delete: [106; 106),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "u32",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_completion_await_impls_future() {
        assert_debug_snapshot_matches!(
        do_completion(
            r###"
            // Mock Future trait from stdlib
            pub mod std {
                pub mod future {
                    #[lang = "future_trait"]
                    pub trait Future {}
                }
            }

            use std::future::*;
            struct A {}
            impl Future for A {}

            fn foo(a: A) {
                a.<|>
            }
            "###, CompletionKind::Keyword),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "await",
       ⋮        source_range: [358; 358),
       ⋮        delete: [358; 358),
       ⋮        insert: "await",
       ⋮        detail: "expr.await",
       ⋮    },
       ⋮]
        "###
        )
    }
}
<commit_msg>do fixup: remove unused imports in complete_dot.rs<commit_after>use hir::{AdtDef, Ty, TypeCtor};

use crate::completion::completion_item::CompletionKind;
use crate::{
    completion::{completion_context::CompletionContext, completion_item::Completions},
    CompletionItem,
};
use rustc_hash::FxHashSet;

/// Complete dot accesses, i.e. fields or methods (and .await syntax).
pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
    if let Some(dot_receiver) = &ctx.dot_receiver {
        let receiver_ty = ctx.analyzer.type_of(ctx.db, &dot_receiver);

        if let Some(receiver_ty) = receiver_ty {
            if !ctx.is_call {
                complete_fields(acc, ctx, receiver_ty.clone());
            }
            complete_methods(acc, ctx, receiver_ty.clone());

            // Suggest .await syntax for types that implement Future trait
            if ctx.analyzer.impls_future(ctx.db, receiver_ty) {
                CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), "await")
                    .detail("expr.await")
                    .insert_text("await")
                    .add_to(acc);
            }
        }
    }
}

fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) {
    for receiver in ctx.analyzer.autoderef(ctx.db, receiver) {
        if let Ty::Apply(a_ty) = receiver {
            match a_ty.ctor {
                TypeCtor::Adt(AdtDef::Struct(s)) => {
                    for field in s.fields(ctx.db) {
                        acc.add_field(ctx, field, &a_ty.parameters);
                    }
                }
                // FIXME unions
                TypeCtor::Tuple { .. } => {
                    for (i, ty) in a_ty.parameters.iter().enumerate() {
                        acc.add_pos_field(ctx, i, ty);
                    }
                }
                _ => {}
            }
        };
    }
}

fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) {
    let mut seen_methods = FxHashSet::default();
    ctx.analyzer.iterate_method_candidates(ctx.db, receiver, None, |_ty, func| {
        let data = func.data(ctx.db);
        if data.has_self_param() && seen_methods.insert(data.name().clone()) {
            acc.add_function(ctx, func);
        }
        None::<()>
    });
}

#[cfg(test)]
mod tests {
    use crate::completion::{do_completion, CompletionItem, CompletionKind};
    use insta::assert_debug_snapshot_matches;

    fn do_ref_completion(code: &str) -> Vec<CompletionItem> {
        do_completion(code, CompletionKind::Reference)
    }

    #[test]
    fn test_struct_field_completion() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
                r"
                struct A { the_field: u32 }
                fn foo(a: A) {
                a.<|>
                }
                ",
        ),
            @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [94; 94),
       ⋮        delete: [94; 94),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "u32",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_struct_field_completion_self() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {
                /// This is the_field
                the_field: (u32,)
            }
            impl A {
                fn foo(self) {
                    self.<|>
                }
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "foo",
       ⋮        source_range: [187; 187),
       ⋮        delete: [187; 187),
       ⋮        insert: "foo()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn foo(self)",
       ⋮    },
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [187; 187),
       ⋮        delete: [187; 187),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "(u32,)",
       ⋮        documentation: Documentation(
       ⋮            "This is the_field",
       ⋮        ),
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_struct_field_completion_autoderef() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A { the_field: (u32, i32) }
            impl A {
                fn foo(&self) {
                    self.<|>
                }
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "foo",
       ⋮        source_range: [126; 126),
       ⋮        delete: [126; 126),
       ⋮        insert: "foo()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn foo(&self)",
       ⋮    },
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [126; 126),
       ⋮        delete: [126; 126),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "(u32, i32)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_no_struct_field_completion_for_method_call() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A { the_field: u32 }
            fn foo(a: A) {
               a.<|>()
            }
            ",
        ),
        @"[]"
        );
    }

    #[test]
    fn test_method_completion() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {}
            impl A {
                fn the_method(&self) {}
            }
            fn foo(a: A) {
               a.<|>
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [144; 144),
       ⋮        delete: [144; 144),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_trait_method_completion() {
        assert_debug_snapshot_matches!(
            do_ref_completion(
                r"
            struct A {}
            trait Trait { fn the_method(&self); }
            impl Trait for A {}
            fn foo(a: A) {
               a.<|>
            }
            ",
            ),
            @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [151; 151),
       ⋮        delete: [151; 151),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_trait_method_completion_deduplicated() {
        assert_debug_snapshot_matches!(
            do_ref_completion(
                r"
            struct A {}
            trait Trait { fn the_method(&self); }
            impl<T> Trait for T {}
            fn foo(a: &A) {
               a.<|>
            }
            ",
            ),
            @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [155; 155),
       ⋮        delete: [155; 155),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_no_non_self_method() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {}
            impl A {
                fn the_method() {}
            }
            fn foo(a: A) {
               a.<|>
            }
            ",
        ),
        @"[]"
        );
    }

    #[test]
    fn test_method_attr_filtering() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A {}
            impl A {
                #[inline]
                fn the_method(&self) {
                    let x = 1;
                    let y = 2;
                }
            }
            fn foo(a: A) {
               a.<|>
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_method",
       ⋮        source_range: [249; 249),
       ⋮        delete: [249; 249),
       ⋮        insert: "the_method()$0",
       ⋮        kind: Method,
       ⋮        detail: "fn the_method(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_tuple_field_completion() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            fn foo() {
               let b = (0, 3.14);
               b.<|>
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "0",
       ⋮        source_range: [75; 75),
       ⋮        delete: [75; 75),
       ⋮        insert: "0",
       ⋮        kind: Field,
       ⋮        detail: "i32",
       ⋮    },
       ⋮    CompletionItem {
       ⋮        label: "1",
       ⋮        source_range: [75; 75),
       ⋮        delete: [75; 75),
       ⋮        insert: "1",
       ⋮        kind: Field,
       ⋮        detail: "f64",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_tuple_field_inference() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            pub struct S;
            impl S {
                pub fn blah(&self) {}
            }

            struct T(S);

            impl T {
                fn foo(&self) {
                    // FIXME: This doesn't work without the trailing `a` as `0.` is a float
                    self.0.a<|>
                }
            }
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "blah",
       ⋮        source_range: [299; 300),
       ⋮        delete: [299; 300),
       ⋮        insert: "blah()$0",
       ⋮        kind: Method,
       ⋮        detail: "pub fn blah(&self)",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_completion_works_in_consts() {
        assert_debug_snapshot_matches!(
        do_ref_completion(
            r"
            struct A { the_field: u32 }
            const X: u32 = {
                A { the_field: 92 }.<|>
            };
            ",
        ),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "the_field",
       ⋮        source_range: [106; 106),
       ⋮        delete: [106; 106),
       ⋮        insert: "the_field",
       ⋮        kind: Field,
       ⋮        detail: "u32",
       ⋮    },
       ⋮]
        "###
        );
    }

    #[test]
    fn test_completion_await_impls_future() {
        assert_debug_snapshot_matches!(
        do_completion(
            r###"
            // Mock Future trait from stdlib
            pub mod std {
                pub mod future {
                    #[lang = "future_trait"]
                    pub trait Future {}
                }
            }

            use std::future::*;
            struct A {}
            impl Future for A {}

            fn foo(a: A) {
                a.<|>
            }
            "###, CompletionKind::Keyword),
        @r###"
       ⋮[
       ⋮    CompletionItem {
       ⋮        label: "await",
       ⋮        source_range: [358; 358),
       ⋮        delete: [358; 358),
       ⋮        insert: "await",
       ⋮        detail: "expr.await",
       ⋮    },
       ⋮]
        "###
        )
    }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;

pub struct Translator
{
  rules: HashMap<(char, char), char>,
}

impl Translator
{
  pub fn new() -> Translator
  {
    Translator
    {
      rules: HashMap::new(),
    }
  }

  pub fn default() -> Translator
  {
    Translator
    {
      rules: HashMap::new(),
    }
  }

  fn translate_char(&self, current : char, previous : char) -> char
  {
    match self.rules.get(&(current, previous))
    {
      Some(result) => *result,
      None => match self.rules.get(&(current, ' '))
      {
        Some(result) => *result,
        None => current,
      }
    }
  }

  pub fn translate(&self, text : &str) -> String
  {
    let mut result = String::with_capacity(text.len() * std::mem::size_of::<char>());

    let mut previous = ' ';
    for c in text.chars()
    {
      previous = self.translate_char(c, previous);
      result.push(previous);
    }

    result
  }
}
<commit_msg>'with_capacity' fix<commit_after>use std::collections::HashMap;

pub struct Translator
{
  rules: HashMap<(char, char), char>,
}

impl Translator
{
  pub fn new() -> Translator
  {
    Translator
    {
      rules: HashMap::new(),
    }
  }

  pub fn default() -> Translator
  {
    Translator
    {
      rules: HashMap::new(),
    }
  }

  fn translate_char(&self, current : char, previous : char) -> char
  {
    match self.rules.get(&(current, previous))
    {
      Some(result) => *result,
      None => match self.rules.get(&(current, ' '))
      {
        Some(result) => *result,
        None => current,
      }
    }
  }

  pub fn translate(&self, text : &str) -> String
  {
    let mut result = String::with_capacity(text.len());

    let mut previous = ' ';
    for c in text.chars()
    {
      previous = self.translate_char(c, previous);
      result.push(previous);
    }

    result
  }
}
<|endoftext|>


<commit_before>extern crate gimli;
use gimli::{AttributeValue, DebugAbbrev, DebugInfo, Endianity, EntriesCursor, LittleEndian};

#[cfg(test)]
fn assert_current_name<'input, 'abbrev, 'unit, Endian>(cursor: &mut EntriesCursor<'input,
                                                                           'abbrev,
                                                                           'unit,
                                                                           Endian>,
                                                       name: &'static str)
    where Endian: Endianity
{
    let entry = cursor.current()
        .expect("Should have an entry result")
        .expect("and it should be ok");

    let value = entry.attr_value(gimli::DW_AT_name)
        .expect("Should have found the name attribute");

    let mut with_null: Vec<u8> = name.as_bytes().into();
    with_null.push(0);

    assert_eq!(value, AttributeValue::String(&with_null));
}

#[cfg(test)]
fn assert_next_dfs<'input, 'abbrev, 'unit, Endian>(cursor: &mut EntriesCursor<'input,
                                                                           'abbrev,
                                                                           'unit,
                                                                           Endian>,
                                                   name: &'static str,
                                                   depth: isize)
    where Endian: Endianity
{
    assert_eq!(cursor.next_dfs().expect("Should not be done with traversal"), depth);
    assert_current_name(cursor, name);
}

#[cfg(test)]
fn assert_next_sibling<'input, 'abbrev, 'unit, Endian>(cursor: &mut EntriesCursor<'input,
                                                                           'abbrev,
                                                                           'unit,
                                                                           Endian>,
                                                       name: &'static str)
    where Endian: Endianity
{
    cursor.next_sibling().expect("Should not be done with traversal");
    assert_current_name(cursor, name);
}

#[cfg(test)]
#[cfg_attr(rustfmt, rustfmt_skip)]
const ENTRIES_CURSOR_TESTS_ABBREV_BUF: [u8; 8] = [
    // Code
    0x01,

    // DW_TAG_subprogram
    0x2e,

    // DW_CHILDREN_yes
    0x01,

    // Begin attributes

        // Attribute name = DW_AT_name
        0x03,
        // Attribute form = DW_FORM_string
        0x08,

    // End attributes
    0x00,
    0x00,

    // Null terminator
    0x00
];

#[cfg(test)]
#[cfg_attr(rustfmt, rustfmt_skip)]
const ENTRIES_CURSOR_TESTS_DEBUG_INFO_BUF: [u8; 71] = [
    // Compilation unit header

    // 32-bit unit length = 67
    0x43, 0x00, 0x00, 0x00,
    // Version 4
    0x04, 0x00,
    // debug_abbrev_offset
    0x00, 0x00, 0x00, 0x00,
    // Address size
    0x04,

    // DIEs

    // Abbreviation code
    0x01,
    // Attribute of form DW_FORM_string = "001\0"
    0x30, 0x30, 0x31, 0x00,

    // Children

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "002\0"
        0x30, 0x30, 0x32, 0x00,

        // Children

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "003\0"
            0x30, 0x30, 0x33, 0x00,

            // Children

            // End of children
            0x00,

        // End of children
        0x00,

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "004\0"
        0x30, 0x30, 0x34, 0x00,

        // Children

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "005\0"
            0x30, 0x30, 0x35, 0x00,

            // Children

            // End of children
            0x00,

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "006\0"
            0x30, 0x30, 0x36, 0x00,

            // Children

            // End of children
            0x00,

        // End of children
        0x00,

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "007\0"
        0x30, 0x30, 0x37, 0x00,

        // Children

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "008\0"
            0x30, 0x30, 0x38, 0x00,

            // Children

                // Abbreviation code
                0x01,
                // Attribute of form DW_FORM_string = "009\0"
                0x30, 0x30, 0x39, 0x00,

                // Children

                // End of children
                0x00,

            // End of children
            0x00,

        // End of children
        0x00,

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "010\0"
        0x30, 0x31, 0x30, 0x00,

        // Children

        // End of children
        0x00,

    // End of children
    0x00
];

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_cursor_next_dfs() {
    let info_buf = &ENTRIES_CURSOR_TESTS_DEBUG_INFO_BUF;
    let debug_info = DebugInfo::<LittleEndian>::new(info_buf);

    let unit = debug_info.units().next()
        .expect("should have a unit result")
        .expect("and it should be ok");

    let abbrevs_buf = &ENTRIES_CURSOR_TESTS_ABBREV_BUF;
    let debug_abbrev = DebugAbbrev::<LittleEndian>::new(abbrevs_buf);

    let abbrevs = unit.abbreviations(debug_abbrev)
        .expect("Should parse abbreviations");

    let mut cursor = unit.entries(&abbrevs);

    assert_current_name(&mut cursor, "001");
    assert_next_dfs(&mut cursor, "002", 1);
    assert_next_dfs(&mut cursor, "003", 1);
    assert_next_dfs(&mut cursor, "004", -1);
    assert_next_dfs(&mut cursor, "005", 1);
    assert_next_dfs(&mut cursor, "006", 0);
    assert_next_dfs(&mut cursor, "007", -1);
    assert_next_dfs(&mut cursor, "008", 1);
    assert_next_dfs(&mut cursor, "009", 1);
    assert_next_dfs(&mut cursor, "010", -2);

    assert!(cursor.next_dfs().is_none());
    assert!(cursor.current().is_none());
}

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_cursor_next_sibling_no_sibling_ptr() {
    let info_buf = &ENTRIES_CURSOR_TESTS_DEBUG_INFO_BUF;
    let debug_info = DebugInfo::<LittleEndian>::new(info_buf);

    let unit = debug_info.units().next()
        .expect("should have a unit result")
        .expect("and it should be ok");

    let abbrevs_buf = &ENTRIES_CURSOR_TESTS_ABBREV_BUF;
    let debug_abbrev = DebugAbbrev::<LittleEndian>::new(abbrevs_buf);

    let abbrevs = unit.abbreviations(debug_abbrev)
        .expect("Should parse abbreviations");

    let mut cursor = unit.entries(&abbrevs);

    assert_current_name(&mut cursor, "001");

    // Down to the first child of the root entry.

    assert_next_dfs(&mut cursor, "002", 1);

    // Now iterate all children of the root via `next_sibling`.

    assert_next_sibling(&mut cursor, "004");
    assert_next_sibling(&mut cursor, "007");
    assert_next_sibling(&mut cursor, "010");

    // And now the cursor should be exhausted.

    assert!(cursor.next_sibling().is_none());
    assert!(cursor.current().is_none());
}

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_cursor_next_sibling_with_sibling_ptr() {
    let info_buf = [
        // Compilation unit header

        // 32-bit unit length = 56
        0x38, 0x00, 0x00, 0x00,
        // Version 4
        0x04, 0x00,
        // debug_abbrev_offset
        0x00, 0x00, 0x00, 0x00,
        // Address size
        0x04,

        // DIEs

        // Abbreviation code
        0x01,

        // DW_AT_name of form DW_FORM_string = "001\0"
        0x30, 0x30, 0x31, 0x00,
        // DW_AT_sibling of form DW_FORM_ref1
        0x00,

        // Children

            // Abbreviation code
            0x01,

            // DW_AT_name of form DW_FORM_string = "002\0"
            0x30, 0x30, 0x32, 0x00,
            // Valid DW_AT_sibling pointer of form DW_FORM_ref1 = 31
            0x1f,

            // Children

                // Abbreviation code
                0x01,

                // DW_AT_name of form DW_FORM_string = "003\0"
                0x30, 0x30, 0x33, 0x00,
                // DW_AT_sibling of form DW_FORM_ref1
                0x00,

                // No children
                0x00,

            // End children
            0x00,

            // Abbreviation code
            0x01,

            // DW_AT_name of form DW_FORM_string = "004\0"
            0x30, 0x30, 0x34, 0x00,
            // Invalid DW_AT_sibling of form DW_FORM_ref1 = 255
            0xff,

            // Children

                // Abbreviation code
                0x01,

                // DW_AT_name of form DW_FORM_string = "005\0"
                0x30, 0x30, 0x35, 0x00,
                // DW_AT_sibling of form DW_FORM_ref1
                0x00,

                // No children
                0x00,

            // End children
            0x00,

            // Abbreviation code
            0x01,

            // DW_AT_name of form DW_FORM_string = "006\0"
            0x30, 0x30, 0x36, 0x00,
            // DW_AT_sibling of form DW_FORM_ref1
            0x00,

            // Children

                // Abbreviation code
                0x01,

                // DW_AT_name of form DW_FORM_string = "007\0"
                0x30, 0x30, 0x37, 0x00,
                // DW_AT_sibling of form DW_FORM_ref1
                0x00,

                // No children
                0x00,

            // End children
            0x00,

        // End children
        0x00,
    ];

    let debug_info = DebugInfo::<LittleEndian>::new(&info_buf);

    let unit = debug_info.units().next()
        .expect("should have a unit result")
        .expect("and it should be ok");

    let abbrev_buf = [
        // Code
        0x01,

        // DW_TAG_subprogram
        0x2e,

        // DW_CHILDREN_yes
        0x01,

        // Begin attributes

        // Attribute name = DW_AT_name
        0x03,
        // Attribute form = DW_FORM_string
        0x08,

        // Attribute name = DW_AT_sibling
        0x01,
        // Attribute form = DW_FORM_ref1
        0x11,

        // End attributes
        0x00,
        0x00,

        // Null terminator
        0x00
    ];

    let debug_abbrev = DebugAbbrev::<LittleEndian>::new(&abbrev_buf);

    let abbrevs = unit.abbreviations(debug_abbrev)
        .expect("Should parse abbreviations");

    let mut cursor = unit.entries(&abbrevs);

    assert_current_name(&mut cursor, "001");

    // Down to the first child of the root.

    assert_next_dfs(&mut cursor, "002", 1);

    // Now iterate all children of the root via `next_sibling`.

    assert_next_sibling(&mut cursor, "004");
    assert_next_sibling(&mut cursor, "006");

    // And now the cursor should be exhausted.

    assert!(cursor.next_sibling().is_none());
    assert!(cursor.current().is_none());
}
<commit_msg>Run rustfmt<commit_after>extern crate gimli;
use gimli::{AttributeValue, DebugAbbrev, DebugInfo, Endianity, EntriesCursor, LittleEndian};

#[cfg(test)]
fn assert_current_name<'input, 'abbrev, 'unit, Endian>(cursor: &mut EntriesCursor<'input,
                                                                                'abbrev,
                                                                                'unit,
                                                                                Endian>,
                                                       name: &'static str)
    where Endian: Endianity
{
    let entry = cursor.current()
        .expect("Should have an entry result")
        .expect("and it should be ok");

    let value = entry.attr_value(gimli::DW_AT_name)
        .expect("Should have found the name attribute");

    let mut with_null: Vec<u8> = name.as_bytes().into();
    with_null.push(0);

    assert_eq!(value, AttributeValue::String(&with_null));
}

#[cfg(test)]
fn assert_next_dfs<'input, 'abbrev, 'unit, Endian>(cursor: &mut EntriesCursor<'input,
                                                                              'abbrev,
                                                                              'unit,
                                                                              Endian>,
                                                   name: &'static str,
                                                   depth: isize)
    where Endian: Endianity
{
    assert_eq!(cursor.next_dfs().expect("Should not be done with traversal"),
               depth);
    assert_current_name(cursor, name);
}

#[cfg(test)]
fn assert_next_sibling<'input, 'abbrev, 'unit, Endian>(cursor: &mut EntriesCursor<'input,
                                                                                'abbrev,
                                                                                'unit,
                                                                                Endian>,
                                                       name: &'static str)
    where Endian: Endianity
{
    cursor.next_sibling().expect("Should not be done with traversal");
    assert_current_name(cursor, name);
}

#[cfg(test)]
#[cfg_attr(rustfmt, rustfmt_skip)]
const ENTRIES_CURSOR_TESTS_ABBREV_BUF: [u8; 8] = [
    // Code
    0x01,

    // DW_TAG_subprogram
    0x2e,

    // DW_CHILDREN_yes
    0x01,

    // Begin attributes

        // Attribute name = DW_AT_name
        0x03,
        // Attribute form = DW_FORM_string
        0x08,

    // End attributes
    0x00,
    0x00,

    // Null terminator
    0x00
];

#[cfg(test)]
#[cfg_attr(rustfmt, rustfmt_skip)]
const ENTRIES_CURSOR_TESTS_DEBUG_INFO_BUF: [u8; 71] = [
    // Compilation unit header

    // 32-bit unit length = 67
    0x43, 0x00, 0x00, 0x00,
    // Version 4
    0x04, 0x00,
    // debug_abbrev_offset
    0x00, 0x00, 0x00, 0x00,
    // Address size
    0x04,

    // DIEs

    // Abbreviation code
    0x01,
    // Attribute of form DW_FORM_string = "001\0"
    0x30, 0x30, 0x31, 0x00,

    // Children

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "002\0"
        0x30, 0x30, 0x32, 0x00,

        // Children

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "003\0"
            0x30, 0x30, 0x33, 0x00,

            // Children

            // End of children
            0x00,

        // End of children
        0x00,

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "004\0"
        0x30, 0x30, 0x34, 0x00,

        // Children

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "005\0"
            0x30, 0x30, 0x35, 0x00,

            // Children

            // End of children
            0x00,

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "006\0"
            0x30, 0x30, 0x36, 0x00,

            // Children

            // End of children
            0x00,

        // End of children
        0x00,

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "007\0"
        0x30, 0x30, 0x37, 0x00,

        // Children

            // Abbreviation code
            0x01,
            // Attribute of form DW_FORM_string = "008\0"
            0x30, 0x30, 0x38, 0x00,

            // Children

                // Abbreviation code
                0x01,
                // Attribute of form DW_FORM_string = "009\0"
                0x30, 0x30, 0x39, 0x00,

                // Children

                // End of children
                0x00,

            // End of children
            0x00,

        // End of children
        0x00,

        // Abbreviation code
        0x01,
        // Attribute of form DW_FORM_string = "010\0"
        0x30, 0x31, 0x30, 0x00,

        // Children

        // End of children
        0x00,

    // End of children
    0x00
];

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_cursor_next_dfs() {
    let info_buf = &ENTRIES_CURSOR_TESTS_DEBUG_INFO_BUF;
    let debug_info = DebugInfo::<LittleEndian>::new(info_buf);

    let unit = debug_info.units().next()
        .expect("should have a unit result")
        .expect("and it should be ok");

    let abbrevs_buf = &ENTRIES_CURSOR_TESTS_ABBREV_BUF;
    let debug_abbrev = DebugAbbrev::<LittleEndian>::new(abbrevs_buf);

    let abbrevs = unit.abbreviations(debug_abbrev)
        .expect("Should parse abbreviations");

    let mut cursor = unit.entries(&abbrevs);

    assert_current_name(&mut cursor, "001");
    assert_next_dfs(&mut cursor, "002", 1);
    assert_next_dfs(&mut cursor, "003", 1);
    assert_next_dfs(&mut cursor, "004", -1);
    assert_next_dfs(&mut cursor, "005", 1);
    assert_next_dfs(&mut cursor, "006", 0);
    assert_next_dfs(&mut cursor, "007", -1);
    assert_next_dfs(&mut cursor, "008", 1);
    assert_next_dfs(&mut cursor, "009", 1);
    assert_next_dfs(&mut cursor, "010", -2);

    assert!(cursor.next_dfs().is_none());
    assert!(cursor.current().is_none());
}

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_cursor_next_sibling_no_sibling_ptr() {
    let info_buf = &ENTRIES_CURSOR_TESTS_DEBUG_INFO_BUF;
    let debug_info = DebugInfo::<LittleEndian>::new(info_buf);

    let unit = debug_info.units().next()
        .expect("should have a unit result")
        .expect("and it should be ok");

    let abbrevs_buf = &ENTRIES_CURSOR_TESTS_ABBREV_BUF;
    let debug_abbrev = DebugAbbrev::<LittleEndian>::new(abbrevs_buf);

    let abbrevs = unit.abbreviations(debug_abbrev)
        .expect("Should parse abbreviations");

    let mut cursor = unit.entries(&abbrevs);

    assert_current_name(&mut cursor, "001");

    // Down to the first child of the root entry.

    assert_next_dfs(&mut cursor, "002", 1);

    // Now iterate all children of the root via `next_sibling`.

    assert_next_sibling(&mut cursor, "004");
    assert_next_sibling(&mut cursor, "007");
    assert_next_sibling(&mut cursor, "010");

    // And now the cursor should be exhausted.

    assert!(cursor.next_sibling().is_none());
    assert!(cursor.current().is_none());
}

#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_cursor_next_sibling_with_sibling_ptr() {
    let info_buf = [
        // Compilation unit header

        // 32-bit unit length = 56
        0x38, 0x00, 0x00, 0x00,
        // Version 4
        0x04, 0x00,
        // debug_abbrev_offset
        0x00, 0x00, 0x00, 0x00,
        // Address size
        0x04,

        // DIEs

        // Abbreviation code
        0x01,

        // DW_AT_name of form DW_FORM_string = "001\0"
        0x30, 0x30, 0x31, 0x00,
        // DW_AT_sibling of form DW_FORM_ref1
        0x00,

        // Children

            // Abbreviation code
            0x01,

            // DW_AT_name of form DW_FORM_string = "002\0"
            0x30, 0x30, 0x32, 0x00,
            // Valid DW_AT_sibling pointer of form DW_FORM_ref1 = 31
            0x1f,

            // Children

                // Abbreviation code
                0x01,

                // DW_AT_name of form DW_FORM_string = "003\0"
                0x30, 0x30, 0x33, 0x00,
                // DW_AT_sibling of form DW_FORM_ref1
                0x00,

                // No children
                0x00,

            // End children
            0x00,

            // Abbreviation code
            0x01,

            // DW_AT_name of form DW_FORM_string = "004\0"
            0x30, 0x30, 0x34, 0x00,
            // Invalid DW_AT_sibling of form DW_FORM_ref1 = 255
            0xff,

            // Children

                // Abbreviation code
                0x01,

                // DW_AT_name of form DW_FORM_string = "005\0"
                0x30, 0x30, 0x35, 0x00,
                // DW_AT_sibling of form DW_FORM_ref1
                0x00,

                // No children
                0x00,

            // End children
            0x00,

            // Abbreviation code
            0x01,

            // DW_AT_name of form DW_FORM_string = "006\0"
            0x30, 0x30, 0x36, 0x00,
            // DW_AT_sibling of form DW_FORM_ref1
            0x00,

            // Children

                // Abbreviation code
                0x01,

                // DW_AT_name of form DW_FORM_string = "007\0"
                0x30, 0x30, 0x37, 0x00,
                // DW_AT_sibling of form DW_FORM_ref1
                0x00,

                // No children
                0x00,

            // End children
            0x00,

        // End children
        0x00,
    ];

    let debug_info = DebugInfo::<LittleEndian>::new(&info_buf);

    let unit = debug_info.units().next()
        .expect("should have a unit result")
        .expect("and it should be ok");

    let abbrev_buf = [
        // Code
        0x01,

        // DW_TAG_subprogram
        0x2e,

        // DW_CHILDREN_yes
        0x01,

        // Begin attributes

        // Attribute name = DW_AT_name
        0x03,
        // Attribute form = DW_FORM_string
        0x08,

        // Attribute name = DW_AT_sibling
        0x01,
        // Attribute form = DW_FORM_ref1
        0x11,

        // End attributes
        0x00,
        0x00,

        // Null terminator
        0x00
    ];

    let debug_abbrev = DebugAbbrev::<LittleEndian>::new(&abbrev_buf);

    let abbrevs = unit.abbreviations(debug_abbrev)
        .expect("Should parse abbreviations");

    let mut cursor = unit.entries(&abbrevs);

    assert_current_name(&mut cursor, "001");

    // Down to the first child of the root.

    assert_next_dfs(&mut cursor, "002", 1);

    // Now iterate all children of the root via `next_sibling`.

    assert_next_sibling(&mut cursor, "004");
    assert_next_sibling(&mut cursor, "006");

    // And now the cursor should be exhausted.

    assert!(cursor.next_sibling().is_none());
    assert!(cursor.current().is_none());
}
<|endoftext|>


<commit_before>#[macro_export]
macro_rules! sql_function {
    ($fn_name:ident, ($($arg_name:ident: $arg_type:ident),*) -> $return_type:ident) => {
        #[allow(non_camel_case_types)]
        pub struct $fn_name<$($arg_name),*> {
            $($arg_name: $arg_name),*
        }

        #[allow(non_camel_case_types)]
        pub fn $fn_name<$($arg_name),*>($($arg_name: $arg_name),*)
            -> $fn_name<$(<$arg_name as $crate::expression::AsExpression<$crate::types::$arg_type>>::Expression),*>
            where $($arg_name: $crate::expression::AsExpression<$crate::types::$arg_type>),+
        {
            $fn_name {
                $($arg_name: $arg_name.as_expression()),+
            }
        }

        #[allow(non_camel_case_types)]
        impl<$($arg_name),*> $crate::expression::Expression for $fn_name<$($arg_name),*> where
            $($arg_name: $crate::expression::Expression),*
        {
            type SqlType = $crate::types::$return_type;

            fn to_sql<T: $crate::query_builder::QueryBuilder>(&self, out: &mut T)
                -> $crate::query_builder::BuildQueryResult {
                    out.push_sql(concat!(stringify!($fn_name), "("));
                    $(try!(self.$arg_name.to_sql(out));)*
                    out.push_sql(")");
                    Ok(())
                }
        }

        #[allow(non_camel_case_types)]
        impl<$($arg_name),*, QS> $crate::expression::SelectableExpression<QS> for $fn_name<$($arg_name),*> where
            $($arg_name: $crate::expression::SelectableExpression<QS>,)*
            $fn_name<$($arg_name),*>: $crate::expression::Expression,
        {
        }

        #[allow(non_camel_case_types)]
        impl<$($arg_name),*> $crate::expression::NonAggregate for $fn_name<$($arg_name),*> where
            $($arg_name: $crate::expression::NonAggregate,)*
            $fn_name<$($arg_name),*>: $crate::expression::Expression,
        {
        }
    }
}

#[macro_export]
macro_rules! no_arg_sql_function {
    ($type_name:ident, $return_type:ident) => {
        #[allow(non_camel_case_types)]
        pub struct $type_name;

        impl $crate::expression::Expression for $type_name {
            type SqlType = $crate::types::$return_type;

            fn to_sql<T: $crate::query_builder::QueryBuilder>(&self, out: &mut T)
                -> $crate::query_builder::BuildQueryResult {
                    out.push_sql(concat!(stringify!($type_name), "()"));
                    Ok(())
                }
        }

        impl<QS> $crate::expression::SelectableExpression<QS> for $type_name {
        }

        impl $crate::expression::NonAggregate for $type_name {
        }
    }
}

pub mod date_and_time;
<commit_msg>Derive `Copy` for user defined SQL functions<commit_after>#[macro_export]
macro_rules! sql_function {
    ($fn_name:ident, ($($arg_name:ident: $arg_type:ident),*) -> $return_type:ident) => {
        #[allow(non_camel_case_types)]
        #[derive(Debug, Clone, Copy)]
        pub struct $fn_name<$($arg_name),*> {
            $($arg_name: $arg_name),*
        }

        #[allow(non_camel_case_types)]
        pub fn $fn_name<$($arg_name),*>($($arg_name: $arg_name),*)
            -> $fn_name<$(<$arg_name as $crate::expression::AsExpression<$crate::types::$arg_type>>::Expression),*>
            where $($arg_name: $crate::expression::AsExpression<$crate::types::$arg_type>),+
        {
            $fn_name {
                $($arg_name: $arg_name.as_expression()),+
            }
        }

        #[allow(non_camel_case_types)]
        impl<$($arg_name),*> $crate::expression::Expression for $fn_name<$($arg_name),*> where
            $($arg_name: $crate::expression::Expression),*
        {
            type SqlType = $crate::types::$return_type;

            fn to_sql<T: $crate::query_builder::QueryBuilder>(&self, out: &mut T)
                -> $crate::query_builder::BuildQueryResult {
                    out.push_sql(concat!(stringify!($fn_name), "("));
                    $(try!(self.$arg_name.to_sql(out));)*
                    out.push_sql(")");
                    Ok(())
                }
        }

        #[allow(non_camel_case_types)]
        impl<$($arg_name),*, QS> $crate::expression::SelectableExpression<QS> for $fn_name<$($arg_name),*> where
            $($arg_name: $crate::expression::SelectableExpression<QS>,)*
            $fn_name<$($arg_name),*>: $crate::expression::Expression,
        {
        }

        #[allow(non_camel_case_types)]
        impl<$($arg_name),*> $crate::expression::NonAggregate for $fn_name<$($arg_name),*> where
            $($arg_name: $crate::expression::NonAggregate,)*
            $fn_name<$($arg_name),*>: $crate::expression::Expression,
        {
        }
    }
}

#[macro_export]
macro_rules! no_arg_sql_function {
    ($type_name:ident, $return_type:ident) => {
        #[allow(non_camel_case_types)]
        pub struct $type_name;

        impl $crate::expression::Expression for $type_name {
            type SqlType = $crate::types::$return_type;

            fn to_sql<T: $crate::query_builder::QueryBuilder>(&self, out: &mut T)
                -> $crate::query_builder::BuildQueryResult {
                    out.push_sql(concat!(stringify!($type_name), "()"));
                    Ok(())
                }
        }

        impl<QS> $crate::expression::SelectableExpression<QS> for $type_name {
        }

        impl $crate::expression::NonAggregate for $type_name {
        }
    }
}

pub mod date_and_time;
<|endoftext|>


<commit_before>use crate::util::elaborate_drops::DropFlagState;
use rustc_middle::mir::{self, Body, Location};
use rustc_middle::ty::{self, TyCtxt};

use super::indexes::MovePathIndex;
use super::move_paths::{InitKind, LookupResult, MoveData};
use super::MoveDataParamEnv;

pub fn move_path_children_matching<'tcx, F>(
    move_data: &MoveData<'tcx>,
    path: MovePathIndex,
    mut cond: F,
) -> Option<MovePathIndex>
where
    F: FnMut(&mir::PlaceElem<'tcx>) -> bool,
{
    let mut next_child = move_data.move_paths[path].first_child;
    while let Some(child_index) = next_child {
        let move_path_children = &move_data.move_paths[child_index];
        if let Some(elem) = move_path_children.place.projection.last() {
            if cond(elem) {
                return Some(child_index);
            }
        }
        next_child = move_path_children.next_sibling;
    }

    None
}

/// When enumerating the child fragments of a path, don't recurse into
/// paths (1.) past arrays, slices, and pointers, nor (2.) into a type
/// that implements `Drop`.
///
/// Places behind references or arrays are not tracked by elaboration
/// and are always assumed to be initialized when accessible. As
/// references and indexes can be reseated, trying to track them can
/// only lead to trouble.
///
/// Places behind ADT's with a Drop impl are not tracked by
/// elaboration since they can never have a drop-flag state that
/// differs from that of the parent with the Drop impl.
///
/// In both cases, the contents can only be accessed if and only if
/// their parents are initialized. This implies for example that there
/// is no need to maintain separate drop flags to track such state.
//
// FIXME: we have to do something for moving slice patterns.
fn place_contents_drop_state_cannot_differ<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    place: &mir::Place<'tcx>,
) -> bool {
    let ty = place.ty(body, tcx).ty;
    match ty.kind {
        ty::Array(..) => {
            debug!(
                "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
                place, ty
            );
            false
        }
        ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
            debug!(
                "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true",
                place, ty
            );
            true
        }
        ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => {
            debug!(
                "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true",
                place, ty
            );
            true
        }
        _ => false,
    }
}

pub(crate) fn on_lookup_result_bits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    move_data: &MoveData<'tcx>,
    lookup_result: LookupResult,
    each_child: F,
) where
    F: FnMut(MovePathIndex),
{
    match lookup_result {
        LookupResult::Parent(..) => {
            // access to untracked value - do not touch children
        }
        LookupResult::Exact(e) => on_all_children_bits(tcx, body, move_data, e, each_child),
    }
}

pub(crate) fn on_all_children_bits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    move_data: &MoveData<'tcx>,
    move_path_index: MovePathIndex,
    mut each_child: F,
) where
    F: FnMut(MovePathIndex),
{
    fn is_terminal_path<'tcx>(
        tcx: TyCtxt<'tcx>,
        body: &Body<'tcx>,
        move_data: &MoveData<'tcx>,
        path: MovePathIndex,
    ) -> bool {
        place_contents_drop_state_cannot_differ(tcx, body, &move_data.move_paths[path].place)
    }

    fn on_all_children_bits<'tcx, F>(
        tcx: TyCtxt<'tcx>,
        body: &Body<'tcx>,
        move_data: &MoveData<'tcx>,
        move_path_index: MovePathIndex,
        each_child: &mut F,
    ) where
        F: FnMut(MovePathIndex),
    {
        each_child(move_path_index);

        if is_terminal_path(tcx, body, move_data, move_path_index) {
            return;
        }

        let mut next_child_index = move_data.move_paths[move_path_index].first_child;
        while let Some(child_index) = next_child_index {
            on_all_children_bits(tcx, body, move_data, child_index, each_child);
            next_child_index = move_data.move_paths[child_index].next_sibling;
        }
    }
    on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child);
}

pub(crate) fn on_all_drop_children_bits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    ctxt: &MoveDataParamEnv<'tcx>,
    path: MovePathIndex,
    mut each_child: F,
) where
    F: FnMut(MovePathIndex),
{
    on_all_children_bits(tcx, body, &ctxt.move_data, path, |child| {
        let place = &ctxt.move_data.move_paths[path].place;
        let ty = place.ty(body, tcx).ty;
        debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty);

        let erased_ty = tcx.erase_regions(&ty);
        if erased_ty.needs_drop(tcx, ctxt.param_env) {
            each_child(child);
        } else {
            debug!("on_all_drop_children_bits - skipping")
        }
    })
}

pub(crate) fn drop_flag_effects_for_function_entry<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    ctxt: &MoveDataParamEnv<'tcx>,
    mut callback: F,
) where
    F: FnMut(MovePathIndex, DropFlagState),
{
    let move_data = &ctxt.move_data;
    for arg in body.args_iter() {
        let place = mir::Place::from(arg);
        let lookup_result = move_data.rev_lookup.find(place.as_ref());
        on_lookup_result_bits(tcx, body, move_data, lookup_result, |mpi| {
            callback(mpi, DropFlagState::Present)
        });
    }
}

pub(crate) fn drop_flag_effects_for_location<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    ctxt: &MoveDataParamEnv<'tcx>,
    loc: Location,
    mut callback: F,
) where
    F: FnMut(MovePathIndex, DropFlagState),
{
    let move_data = &ctxt.move_data;
    debug!("drop_flag_effects_for_location({:?})", loc);

    // first, move out of the RHS
    for mi in &move_data.loc_map[loc] {
        let path = mi.move_path_index(move_data);
        debug!("moving out of path {:?}", move_data.move_paths[path]);

        on_all_children_bits(tcx, body, move_data, path, |mpi| callback(mpi, DropFlagState::Absent))
    }

    debug!("drop_flag_effects: assignment for location({:?})", loc);

    for_location_inits(tcx, body, move_data, loc, |mpi| callback(mpi, DropFlagState::Present));
}

pub(crate) fn for_location_inits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    move_data: &MoveData<'tcx>,
    loc: Location,
    mut callback: F,
) where
    F: FnMut(MovePathIndex),
{
    for ii in &move_data.init_loc_map[loc] {
        let init = move_data.inits[*ii];
        match init.kind {
            InitKind::Deep => {
                let path = init.path;

                on_all_children_bits(tcx, body, move_data, path, &mut callback)
            }
            InitKind::Shallow => {
                let mpi = init.path;
                callback(mpi);
            }
            InitKind::NonPanicPathOnly => (),
        }
    }
}
<commit_msg>Use Place directly on place_contents_drop_state_cannot_differ, it's Copy<commit_after>use crate::util::elaborate_drops::DropFlagState;
use rustc_middle::mir::{self, Body, Location};
use rustc_middle::ty::{self, TyCtxt};

use super::indexes::MovePathIndex;
use super::move_paths::{InitKind, LookupResult, MoveData};
use super::MoveDataParamEnv;

pub fn move_path_children_matching<'tcx, F>(
    move_data: &MoveData<'tcx>,
    path: MovePathIndex,
    mut cond: F,
) -> Option<MovePathIndex>
where
    F: FnMut(&mir::PlaceElem<'tcx>) -> bool,
{
    let mut next_child = move_data.move_paths[path].first_child;
    while let Some(child_index) = next_child {
        let move_path_children = &move_data.move_paths[child_index];
        if let Some(elem) = move_path_children.place.projection.last() {
            if cond(elem) {
                return Some(child_index);
            }
        }
        next_child = move_path_children.next_sibling;
    }

    None
}

/// When enumerating the child fragments of a path, don't recurse into
/// paths (1.) past arrays, slices, and pointers, nor (2.) into a type
/// that implements `Drop`.
///
/// Places behind references or arrays are not tracked by elaboration
/// and are always assumed to be initialized when accessible. As
/// references and indexes can be reseated, trying to track them can
/// only lead to trouble.
///
/// Places behind ADT's with a Drop impl are not tracked by
/// elaboration since they can never have a drop-flag state that
/// differs from that of the parent with the Drop impl.
///
/// In both cases, the contents can only be accessed if and only if
/// their parents are initialized. This implies for example that there
/// is no need to maintain separate drop flags to track such state.
//
// FIXME: we have to do something for moving slice patterns.
fn place_contents_drop_state_cannot_differ<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    place: mir::Place<'tcx>,
) -> bool {
    let ty = place.ty(body, tcx).ty;
    match ty.kind {
        ty::Array(..) => {
            debug!(
                "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
                place, ty
            );
            false
        }
        ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
            debug!(
                "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true",
                place, ty
            );
            true
        }
        ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => {
            debug!(
                "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true",
                place, ty
            );
            true
        }
        _ => false,
    }
}

pub(crate) fn on_lookup_result_bits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    move_data: &MoveData<'tcx>,
    lookup_result: LookupResult,
    each_child: F,
) where
    F: FnMut(MovePathIndex),
{
    match lookup_result {
        LookupResult::Parent(..) => {
            // access to untracked value - do not touch children
        }
        LookupResult::Exact(e) => on_all_children_bits(tcx, body, move_data, e, each_child),
    }
}

pub(crate) fn on_all_children_bits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    move_data: &MoveData<'tcx>,
    move_path_index: MovePathIndex,
    mut each_child: F,
) where
    F: FnMut(MovePathIndex),
{
    fn is_terminal_path<'tcx>(
        tcx: TyCtxt<'tcx>,
        body: &Body<'tcx>,
        move_data: &MoveData<'tcx>,
        path: MovePathIndex,
    ) -> bool {
        place_contents_drop_state_cannot_differ(tcx, body, move_data.move_paths[path].place)
    }

    fn on_all_children_bits<'tcx, F>(
        tcx: TyCtxt<'tcx>,
        body: &Body<'tcx>,
        move_data: &MoveData<'tcx>,
        move_path_index: MovePathIndex,
        each_child: &mut F,
    ) where
        F: FnMut(MovePathIndex),
    {
        each_child(move_path_index);

        if is_terminal_path(tcx, body, move_data, move_path_index) {
            return;
        }

        let mut next_child_index = move_data.move_paths[move_path_index].first_child;
        while let Some(child_index) = next_child_index {
            on_all_children_bits(tcx, body, move_data, child_index, each_child);
            next_child_index = move_data.move_paths[child_index].next_sibling;
        }
    }
    on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child);
}

pub(crate) fn on_all_drop_children_bits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    ctxt: &MoveDataParamEnv<'tcx>,
    path: MovePathIndex,
    mut each_child: F,
) where
    F: FnMut(MovePathIndex),
{
    on_all_children_bits(tcx, body, &ctxt.move_data, path, |child| {
        let place = &ctxt.move_data.move_paths[path].place;
        let ty = place.ty(body, tcx).ty;
        debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty);

        let erased_ty = tcx.erase_regions(&ty);
        if erased_ty.needs_drop(tcx, ctxt.param_env) {
            each_child(child);
        } else {
            debug!("on_all_drop_children_bits - skipping")
        }
    })
}

pub(crate) fn drop_flag_effects_for_function_entry<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    ctxt: &MoveDataParamEnv<'tcx>,
    mut callback: F,
) where
    F: FnMut(MovePathIndex, DropFlagState),
{
    let move_data = &ctxt.move_data;
    for arg in body.args_iter() {
        let place = mir::Place::from(arg);
        let lookup_result = move_data.rev_lookup.find(place.as_ref());
        on_lookup_result_bits(tcx, body, move_data, lookup_result, |mpi| {
            callback(mpi, DropFlagState::Present)
        });
    }
}

pub(crate) fn drop_flag_effects_for_location<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    ctxt: &MoveDataParamEnv<'tcx>,
    loc: Location,
    mut callback: F,
) where
    F: FnMut(MovePathIndex, DropFlagState),
{
    let move_data = &ctxt.move_data;
    debug!("drop_flag_effects_for_location({:?})", loc);

    // first, move out of the RHS
    for mi in &move_data.loc_map[loc] {
        let path = mi.move_path_index(move_data);
        debug!("moving out of path {:?}", move_data.move_paths[path]);

        on_all_children_bits(tcx, body, move_data, path, |mpi| callback(mpi, DropFlagState::Absent))
    }

    debug!("drop_flag_effects: assignment for location({:?})", loc);

    for_location_inits(tcx, body, move_data, loc, |mpi| callback(mpi, DropFlagState::Present));
}

pub(crate) fn for_location_inits<'tcx, F>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    move_data: &MoveData<'tcx>,
    loc: Location,
    mut callback: F,
) where
    F: FnMut(MovePathIndex),
{
    for ii in &move_data.init_loc_map[loc] {
        let init = move_data.inits[*ii];
        match init.kind {
            InitKind::Deep => {
                let path = init.path;

                on_all_children_bits(tcx, body, move_data, path, &mut callback)
            }
            InitKind::Shallow => {
                let mpi = init.path;
                callback(mpi);
            }
            InitKind::NonPanicPathOnly => (),
        }
    }
}
<|endoftext|>