<commit_before>s! {
    pub struct shmid_ds {
        pub shm_perm: ::ipc_perm,
        pub shm_segsz: ::size_t,
        pub shm_amp: *mut ::c_void,
        pub shm_lkcnt: ::c_ushort,
        pub shm_lpid: ::pid_t,
        pub shm_cpid: ::pid_t,
        pub shm_nattch: ::shmatt_t,
        pub shm_cnattch: ::c_ulong,
        pub shm_atime: ::time_t,
        pub shm_dtime: ::time_t,
        pub shm_ctime: ::time_t,
        pub shm_pad4: [i64; 4],
    }

    pub struct fil_info {
        pub fi_flags: ::c_int,
        pub fi_pos: ::c_int,
        pub fi_name: [::c_char; ::FILNAME_MAX as usize],
    }
}

pub const AF_LOCAL: ::c_int = 1; // AF_UNIX
pub const AF_FILE: ::c_int = 1; // AF_UNIX

pub const EFD_SEMAPHORE: ::c_int = 0x1;
pub const EFD_NONBLOCK: ::c_int = 0x800;
pub const EFD_CLOEXEC: ::c_int = 0x80000;

pub const TCP_KEEPIDLE: ::c_int = 34;
pub const TCP_KEEPCNT: ::c_int = 35;
pub const TCP_KEEPINTVL: ::c_int = 36;
pub const TCP_CONGESTION: ::c_int = 37;

pub const F_OFD_GETLK: ::c_int = 50;
pub const F_OFD_SETLKL: ::c_int = 51;
pub const F_OFD_SETLKW: ::c_int = 52;
pub const F_FLOCK: ::c_int = 55;
pub const F_FLOCKW: ::c_int = 56;

pub const FIL_ATTACH: ::c_int = 0x1;
pub const FIL_DETACH: ::c_int = 0x2;
pub const FIL_LIST: ::c_int = 0x3;
pub const FILNAME_MAX: ::c_int = 32;
pub const FILF_PROG: ::c_int = 0x1;
pub const FILF_AUTO: ::c_int = 0x2;
pub const FILF_BYPASS: ::c_int = 0x4;
pub const SOL_FILTER: ::c_int = 0xfffc;

pub const MR_HDR_AOUT: ::c_uint = 0x3;

extern "C" {
    pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int;

    pub fn mincore(addr: ::caddr_t, len: ::size_t, vec: *mut ::c_char) -> ::c_int;

    pub fn pset_bind_lwp(
        pset: ::psetid_t,
        id: ::id_t,
        pid: ::pid_t,
        opset: *mut ::psetid_t,
    ) -> ::c_int;
    pub fn pset_getloadavg(pset: ::psetid_t, load: *mut ::c_double, num: ::c_int) -> ::c_int;

    pub fn preadv(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t) -> ::ssize_t;
    pub fn pwritev(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t)
        -> ::ssize_t;
    pub fn getpagesizes2(pagesize: *mut ::size_t, nelem: ::c_int) -> ::c_int;
}
<commit_msg>illumos: wrong values for F_OFD_*<commit_after>s! {
    pub struct shmid_ds {
        pub shm_perm: ::ipc_perm,
        pub shm_segsz: ::size_t,
        pub shm_amp: *mut ::c_void,
        pub shm_lkcnt: ::c_ushort,
        pub shm_lpid: ::pid_t,
        pub shm_cpid: ::pid_t,
        pub shm_nattch: ::shmatt_t,
        pub shm_cnattch: ::c_ulong,
        pub shm_atime: ::time_t,
        pub shm_dtime: ::time_t,
        pub shm_ctime: ::time_t,
        pub shm_pad4: [i64; 4],
    }

    pub struct fil_info {
        pub fi_flags: ::c_int,
        pub fi_pos: ::c_int,
        pub fi_name: [::c_char; ::FILNAME_MAX as usize],
    }
}

pub const AF_LOCAL: ::c_int = 1; // AF_UNIX
pub const AF_FILE: ::c_int = 1; // AF_UNIX

pub const EFD_SEMAPHORE: ::c_int = 0x1;
pub const EFD_NONBLOCK: ::c_int = 0x800;
pub const EFD_CLOEXEC: ::c_int = 0x80000;

pub const TCP_KEEPIDLE: ::c_int = 34;
pub const TCP_KEEPCNT: ::c_int = 35;
pub const TCP_KEEPINTVL: ::c_int = 36;
pub const TCP_CONGESTION: ::c_int = 37;

// These constants are correct for 64-bit programs or 32-bit programs that are
// not using large-file mode.  If Rust ever supports anything other than 64-bit
// compilation on illumos, this may require adjustment:
pub const F_OFD_GETLK: ::c_int = 47;
pub const F_OFD_SETLK: ::c_int = 48;
pub const F_OFD_SETLKW: ::c_int = 49;
pub const F_FLOCK: ::c_int = 53;
pub const F_FLOCKW: ::c_int = 54;

pub const FIL_ATTACH: ::c_int = 0x1;
pub const FIL_DETACH: ::c_int = 0x2;
pub const FIL_LIST: ::c_int = 0x3;
pub const FILNAME_MAX: ::c_int = 32;
pub const FILF_PROG: ::c_int = 0x1;
pub const FILF_AUTO: ::c_int = 0x2;
pub const FILF_BYPASS: ::c_int = 0x4;
pub const SOL_FILTER: ::c_int = 0xfffc;

pub const MR_HDR_AOUT: ::c_uint = 0x3;

extern "C" {
    pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int;

    pub fn mincore(addr: ::caddr_t, len: ::size_t, vec: *mut ::c_char) -> ::c_int;

    pub fn pset_bind_lwp(
        pset: ::psetid_t,
        id: ::id_t,
        pid: ::pid_t,
        opset: *mut ::psetid_t,
    ) -> ::c_int;
    pub fn pset_getloadavg(pset: ::psetid_t, load: *mut ::c_double, num: ::c_int) -> ::c_int;

    pub fn preadv(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t) -> ::ssize_t;
    pub fn pwritev(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t)
        -> ::ssize_t;
    pub fn getpagesizes2(pagesize: *mut ::size_t, nelem: ::c_int) -> ::c_int;
}
<|endoftext|>


<commit_before>use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};

/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
    /// Concatenates two strings using the `||` operator.
    ///
    /// # Example
    ///
    /// ```rust
    /// # include!("../doctest_setup.rs");
    /// #
    /// # table! {
    /// #     users {
    /// #         id -> Integer,
    /// #         name -> VarChar,
    /// #         hair_color -> Nullable<Text>,
    /// #     }
    /// # }
    /// #
    /// # fn main() {
    /// #     use self::users::dsl::*;
    /// #     use diesel::insert_into;
    /// #
    /// #     let connection = connection_no_data();
    /// #     connection.execute("CREATE TABLE users (
    /// #         id INTEGER PRIMARY KEY,
    /// #         name VARCHAR(255) NOT NULL,
    /// #         hair_color VARCHAR(255)
    /// #     )").unwrap();
    /// #
    /// #     insert_into(users)
    /// #         .values(&vec![
    /// #             (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))),
    /// #             (id.eq(2), name.eq("Tess"), hair_color.eq(None)),
    /// #         ])
    /// #         .execute(&connection)
    /// #         .unwrap();
    /// #
    /// let names = users.select(name.concat(" the Greatest")).load(&connection);
    /// let expected_names = vec![
    ///     "Sean the Greatest".to_string(),
    ///     "Tess the Greatest".to_string(),
    /// ];
    /// assert_eq!(Ok(expected_names), names);
    ///
    /// // If the value is nullable, the output will be nullable
    /// let names = users.select(hair_color.concat("ish")).load(&connection);
    /// let expected_names = vec![
    ///     Some("Greenish".to_string()),
    ///     None,
    /// ];
    /// assert_eq!(Ok(expected_names), names);
    /// # }
    /// ```
    fn concat<T>(self, other: T) -> dsl::Concat<Self, T>
    where
        Self::SqlType: SqlType,
        T: AsExpression<Self::SqlType>,
    {
        Grouped(Concat::new(self, other.as_expression()))
    }

    /// Returns a SQL `LIKE` expression
    ///
    /// This method is case insensitive for SQLite and MySQL.
    /// On PostgreSQL, `LIKE` is case sensitive. You may use
    /// [`ilike()`](crate)::expression_methods::PgTextExpressionMethods::ilike())
    /// for case insensitive comparison on PostgreSQL.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # include!("../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     use schema::users::dsl::*;
    /// #     let connection = establish_connection();
    /// #
    /// let starts_with_s = users
    ///     .select(name)
    ///     .filter(name.like("S%"))
    ///     .load::<String>(&connection)?;
    /// assert_eq!(vec!["Sean"], starts_with_s);
    /// #     Ok(())
    /// # }
    /// ```
    fn like<T>(self, other: T) -> dsl::Like<Self, T>
    where
        Self::SqlType: SqlType,
        T: AsExpression<Self::SqlType>,
    {
        Grouped(Like::new(self, other.as_expression()))
    }

    /// Returns a SQL `NOT LIKE` expression
    ///
    /// This method is case insensitive for SQLite and MySQL.
    /// On PostgreSQL `NOT LIKE` is case sensitive. You may use
    /// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike)
    /// for case insensitive comparison on PostgreSQL.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # include!("../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     use schema::users::dsl::*;
    /// #     let connection = establish_connection();
    /// #
    /// let doesnt_start_with_s = users
    ///     .select(name)
    ///     .filter(name.not_like("S%"))
    ///     .load::<String>(&connection)?;
    /// assert_eq!(vec!["Tess"], doesnt_start_with_s);
    /// #     Ok(())
    /// # }
    /// ```
    fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T>
    where
        Self::SqlType: SqlType,
        T: AsExpression<Self::SqlType>,
    {
        Grouped(NotLike::new(self, other.as_expression()))
    }
}

#[doc(hidden)]
/// Marker trait used to implement `TextExpressionMethods` on the appropriate
/// types. Once coherence takes associated types into account, we can remove
/// this trait.
pub trait TextOrNullableText {}

impl TextOrNullableText for Text {}
impl TextOrNullableText for Nullable<Text> {}

impl<T> TextExpressionMethods for T
where
    T: Expression,
    T::SqlType: TextOrNullableText,
{
}
<commit_msg>fix wrong links<commit_after>use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};

/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
    /// Concatenates two strings using the `||` operator.
    ///
    /// # Example
    ///
    /// ```rust
    /// # include!("../doctest_setup.rs");
    /// #
    /// # table! {
    /// #     users {
    /// #         id -> Integer,
    /// #         name -> VarChar,
    /// #         hair_color -> Nullable<Text>,
    /// #     }
    /// # }
    /// #
    /// # fn main() {
    /// #     use self::users::dsl::*;
    /// #     use diesel::insert_into;
    /// #
    /// #     let connection = connection_no_data();
    /// #     connection.execute("CREATE TABLE users (
    /// #         id INTEGER PRIMARY KEY,
    /// #         name VARCHAR(255) NOT NULL,
    /// #         hair_color VARCHAR(255)
    /// #     )").unwrap();
    /// #
    /// #     insert_into(users)
    /// #         .values(&vec![
    /// #             (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))),
    /// #             (id.eq(2), name.eq("Tess"), hair_color.eq(None)),
    /// #         ])
    /// #         .execute(&connection)
    /// #         .unwrap();
    /// #
    /// let names = users.select(name.concat(" the Greatest")).load(&connection);
    /// let expected_names = vec![
    ///     "Sean the Greatest".to_string(),
    ///     "Tess the Greatest".to_string(),
    /// ];
    /// assert_eq!(Ok(expected_names), names);
    ///
    /// // If the value is nullable, the output will be nullable
    /// let names = users.select(hair_color.concat("ish")).load(&connection);
    /// let expected_names = vec![
    ///     Some("Greenish".to_string()),
    ///     None,
    /// ];
    /// assert_eq!(Ok(expected_names), names);
    /// # }
    /// ```
    fn concat<T>(self, other: T) -> dsl::Concat<Self, T>
    where
        Self::SqlType: SqlType,
        T: AsExpression<Self::SqlType>,
    {
        Grouped(Concat::new(self, other.as_expression()))
    }

    /// Returns a SQL `LIKE` expression
    ///
    /// This method is case insensitive for SQLite and MySQL.
    /// On PostgreSQL, `LIKE` is case sensitive. You may use
    /// [`ilike()`](crate::expression_methods::PgTextExpressionMethods::ilike())
    /// for case insensitive comparison on PostgreSQL.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # include!("../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     use schema::users::dsl::*;
    /// #     let connection = establish_connection();
    /// #
    /// let starts_with_s = users
    ///     .select(name)
    ///     .filter(name.like("S%"))
    ///     .load::<String>(&connection)?;
    /// assert_eq!(vec!["Sean"], starts_with_s);
    /// #     Ok(())
    /// # }
    /// ```
    fn like<T>(self, other: T) -> dsl::Like<Self, T>
    where
        Self::SqlType: SqlType,
        T: AsExpression<Self::SqlType>,
    {
        Grouped(Like::new(self, other.as_expression()))
    }

    /// Returns a SQL `NOT LIKE` expression
    ///
    /// This method is case insensitive for SQLite and MySQL.
    /// On PostgreSQL `NOT LIKE` is case sensitive. You may use
    /// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike)
    /// for case insensitive comparison on PostgreSQL.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # include!("../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     use schema::users::dsl::*;
    /// #     let connection = establish_connection();
    /// #
    /// let doesnt_start_with_s = users
    ///     .select(name)
    ///     .filter(name.not_like("S%"))
    ///     .load::<String>(&connection)?;
    /// assert_eq!(vec!["Tess"], doesnt_start_with_s);
    /// #     Ok(())
    /// # }
    /// ```
    fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T>
    where
        Self::SqlType: SqlType,
        T: AsExpression<Self::SqlType>,
    {
        Grouped(NotLike::new(self, other.as_expression()))
    }
}

#[doc(hidden)]
/// Marker trait used to implement `TextExpressionMethods` on the appropriate
/// types. Once coherence takes associated types into account, we can remove
/// this trait.
pub trait TextOrNullableText {}

impl TextOrNullableText for Text {}
impl TextOrNullableText for Nullable<Text> {}

impl<T> TextExpressionMethods for T
where
    T: Expression,
    T::SqlType: TextOrNullableText,
{
}
<|endoftext|>


<commit_before>#[test]
fn test_into_async_read() {
    use core::pin::Pin;
    use futures::io::AsyncRead;
    use futures::stream::{self, TryStreamExt};
    use futures::task::Poll;
    use futures_test::{task::noop_context, stream::StreamTestExt};

    macro_rules! assert_read {
        ($reader:expr, $buf:expr, $item:expr) => {
            let mut cx = noop_context();
            loop {
                match Pin::new(&mut $reader).poll_read(&mut cx, $buf) {
                    Poll::Ready(Ok(x)) => {
                        assert_eq!(x, $item);
                        break;
                    }
                    Poll::Ready(Err(err)) => {
                        panic!("assertion failed: expected value but got {}", err);
                    }
                    Poll::Pending => {
                        continue;
                    }
                }
            }
        };
    }

    let stream = stream::iter((1..=3).flat_map(|_| vec![Ok(vec![]), Ok(vec![1, 2, 3, 4, 5])]));
    let mut reader = stream.interleave_pending().into_async_read();
    let mut buf = vec![0; 3];

    assert_read!(reader, &mut buf, 3);
    assert_eq!(&buf, &[1, 2, 3]);

    assert_read!(reader, &mut buf, 2);
    assert_eq!(&buf[..2], &[4, 5]);

    assert_read!(reader, &mut buf, 3);
    assert_eq!(&buf, &[1, 2, 3]);

    assert_read!(reader, &mut buf, 2);
    assert_eq!(&buf[..2], &[4, 5]);

    assert_read!(reader, &mut buf, 3);
    assert_eq!(&buf, &[1, 2, 3]);

    assert_read!(reader, &mut buf, 2);
    assert_eq!(&buf[..2], &[4, 5]);

    assert_read!(reader, &mut buf, 0);
}

#[test]
fn test_into_async_bufread() -> std::io::Result<()> {
    use core::pin::Pin;
    use futures::io::AsyncBufRead;
    use futures::stream::{self, TryStreamExt};
    use futures::task::Poll;
    use futures_test::{task::noop_context, stream::StreamTestExt};

    macro_rules! assert_fill_buf {
        ($reader:expr, $buf:expr) => {
            let mut cx = noop_context();
            loop {
                match Pin::new(&mut $reader).poll_fill_buf(&mut cx) {
                    Poll::Ready(Ok(x)) => {
                        assert_eq!(x, $buf);
                        break;
                    }
                    Poll::Ready(Err(err)) => {
                        panic!("assertion failed: expected value but got {}", err);
                    }
                    Poll::Pending => {
                        continue;
                    }
                }
            }
        };
    }

    let stream = stream::iter((1..=2).flat_map(|_| vec![Ok(vec![]), Ok(vec![1, 2, 3, 4, 5])]));
    let mut reader = stream.interleave_pending().into_async_read();

    let mut reader = Pin::new(&mut reader);

    assert_fill_buf!(reader, &[1, 2, 3, 4, 5][..]);
    reader.as_mut().consume(3);

    assert_fill_buf!(reader, &[4, 5][..]);
    reader.as_mut().consume(2);

    assert_fill_buf!(reader, &[1, 2, 3, 4, 5][..]);
    reader.as_mut().consume(2);

    assert_fill_buf!(reader, &[3, 4, 5][..]);
    reader.as_mut().consume(3);

    assert_fill_buf!(reader, &[][..]);

    Ok(())
}
<commit_msg>Fix clippy::unnecessary_wraps warning<commit_after>#[test]
fn test_into_async_read() {
    use core::pin::Pin;
    use futures::io::AsyncRead;
    use futures::stream::{self, TryStreamExt};
    use futures::task::Poll;
    use futures_test::{task::noop_context, stream::StreamTestExt};

    macro_rules! assert_read {
        ($reader:expr, $buf:expr, $item:expr) => {
            let mut cx = noop_context();
            loop {
                match Pin::new(&mut $reader).poll_read(&mut cx, $buf) {
                    Poll::Ready(Ok(x)) => {
                        assert_eq!(x, $item);
                        break;
                    }
                    Poll::Ready(Err(err)) => {
                        panic!("assertion failed: expected value but got {}", err);
                    }
                    Poll::Pending => {
                        continue;
                    }
                }
            }
        };
    }

    let stream = stream::iter((1..=3).flat_map(|_| vec![Ok(vec![]), Ok(vec![1, 2, 3, 4, 5])]));
    let mut reader = stream.interleave_pending().into_async_read();
    let mut buf = vec![0; 3];

    assert_read!(reader, &mut buf, 3);
    assert_eq!(&buf, &[1, 2, 3]);

    assert_read!(reader, &mut buf, 2);
    assert_eq!(&buf[..2], &[4, 5]);

    assert_read!(reader, &mut buf, 3);
    assert_eq!(&buf, &[1, 2, 3]);

    assert_read!(reader, &mut buf, 2);
    assert_eq!(&buf[..2], &[4, 5]);

    assert_read!(reader, &mut buf, 3);
    assert_eq!(&buf, &[1, 2, 3]);

    assert_read!(reader, &mut buf, 2);
    assert_eq!(&buf[..2], &[4, 5]);

    assert_read!(reader, &mut buf, 0);
}

#[test]
fn test_into_async_bufread() {
    use core::pin::Pin;
    use futures::io::AsyncBufRead;
    use futures::stream::{self, TryStreamExt};
    use futures::task::Poll;
    use futures_test::{task::noop_context, stream::StreamTestExt};

    macro_rules! assert_fill_buf {
        ($reader:expr, $buf:expr) => {
            let mut cx = noop_context();
            loop {
                match Pin::new(&mut $reader).poll_fill_buf(&mut cx) {
                    Poll::Ready(Ok(x)) => {
                        assert_eq!(x, $buf);
                        break;
                    }
                    Poll::Ready(Err(err)) => {
                        panic!("assertion failed: expected value but got {}", err);
                    }
                    Poll::Pending => {
                        continue;
                    }
                }
            }
        };
    }

    let stream = stream::iter((1..=2).flat_map(|_| vec![Ok(vec![]), Ok(vec![1, 2, 3, 4, 5])]));
    let mut reader = stream.interleave_pending().into_async_read();

    let mut reader = Pin::new(&mut reader);

    assert_fill_buf!(reader, &[1, 2, 3, 4, 5][..]);
    reader.as_mut().consume(3);

    assert_fill_buf!(reader, &[4, 5][..]);
    reader.as_mut().consume(2);

    assert_fill_buf!(reader, &[1, 2, 3, 4, 5][..]);
    reader.as_mut().consume(2);

    assert_fill_buf!(reader, &[3, 4, 5][..]);
    reader.as_mut().consume(3);

    assert_fill_buf!(reader, &[][..]);
}
<|endoftext|>


<commit_before>use hir::{Resolution, Either};
use ra_syntax::AstNode;
use test_utils::tested_by;

use crate::completion::{Completions, CompletionContext};

pub(super) fn complete_path(acc: &mut Completions, ctx: &CompletionContext) {
    let path = match &ctx.path_prefix {
        Some(path) => path.clone(),
        _ => return,
    };
    let def = match ctx.analyzer.resolve_hir_path(ctx.db, &path).take_types() {
        Some(Resolution::Def(def)) => def,
        _ => return,
    };
    match def {
        hir::ModuleDef::Module(module) => {
            let module_scope = module.scope(ctx.db);
            for (name, res) in module_scope.entries() {
                if let Some(hir::ModuleDef::BuiltinType(..)) = res.def.as_ref().take_types() {
                    if ctx.use_item_syntax.is_some() {
                        tested_by!(dont_complete_primitive_in_use);
                        continue;
                    }
                }
                if Some(module) == ctx.module {
                    if let Some(import) = res.import {
                        if let Either::A(use_tree) = module.import_source(ctx.db, import) {
                            if use_tree.syntax().range().contains_inclusive(ctx.offset) {
                                // for `use self::foo<|>`, don't suggest `foo` as a completion
                                tested_by!(dont_complete_current_use);
                                continue;
                            }
                        }
                    }
                }
                acc.add_resolution(ctx, name.to_string(), &res.def.map(hir::Resolution::Def));
            }
        }
        hir::ModuleDef::Enum(_) | hir::ModuleDef::Struct(_) | hir::ModuleDef::Union(_) => {
            if let hir::ModuleDef::Enum(e) = def {
                for variant in e.variants(ctx.db) {
                    acc.add_enum_variant(ctx, variant);
                }
            }
            let ty = match def {
                hir::ModuleDef::Enum(e) => e.ty(ctx.db),
                hir::ModuleDef::Struct(s) => s.ty(ctx.db),
                hir::ModuleDef::Union(u) => u.ty(ctx.db),
                _ => unreachable!(),
            };
            let krate = ctx.module.and_then(|m| m.krate(ctx.db));
            if let Some(krate) = krate {
                ty.iterate_impl_items(ctx.db, krate, |item| {
                    match item {
                        hir::ImplItem::Method(func) => {
                            let data = func.data(ctx.db);
                            if !data.has_self_param() {
                                acc.add_function(ctx, func);
                            }
                        }
                        hir::ImplItem::Const(ct) => acc.add_const(ctx, ct),
                        hir::ImplItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
                    }
                    None::<()>
                });
            }
        }
        _ => return,
    };
}

#[cfg(test)]
mod tests {
    use test_utils::covers;

    use crate::completion::{CompletionKind, check_completion, do_completion};

    fn check_reference_completion(code: &str, expected_completions: &str) {
        check_completion(code, expected_completions, CompletionKind::Reference);
    }

    #[test]
    fn dont_complete_current_use() {
        covers!(dont_complete_current_use);
        let completions = do_completion(r"use self::foo<|>;", CompletionKind::Reference);
        assert!(completions.is_empty());
    }

    #[test]
    fn dont_complete_current_use_in_braces_with_glob() {
        let completions = do_completion(
            r"
            mod foo { pub struct S; }
            use self::{foo::*, bar<|>};
            ",
            CompletionKind::Reference,
        );
        assert_eq!(completions.len(), 2);
    }

    #[test]
    fn dont_complete_primitive_in_use() {
        covers!(dont_complete_primitive_in_use);
        let completions = do_completion(r"use self::<|>;", CompletionKind::BuiltinType);
        assert!(completions.is_empty());
    }

    #[test]
    fn completes_primitives() {
        let completions =
            do_completion(r"fn main() { let _: <|> = 92; }", CompletionKind::BuiltinType);
        assert_eq!(completions.len(), 17);
    }

    #[test]
    fn completes_mod_with_docs() {
        check_reference_completion(
            "mod_with_docs",
            r"
            use self::my<|>;

            /// Some simple
            /// docs describing `mod my`.
            mod my {
                struct Bar;
            }
            ",
        );
    }

    #[test]
    fn completes_use_item_starting_with_self() {
        check_reference_completion(
            "use_item_starting_with_self",
            r"
            use self::m::<|>;

            mod m {
                struct Bar;
            }
            ",
        );
    }

    #[test]
    fn completes_use_item_starting_with_crate() {
        check_reference_completion(
            "use_item_starting_with_crate",
            "
            //- /lib.rs
            mod foo;
            struct Spam;
            //- /foo.rs
            use crate::Sp<|>
            ",
        );
    }

    #[test]
    fn completes_nested_use_tree() {
        check_reference_completion(
            "nested_use_tree",
            "
            //- /lib.rs
            mod foo;
            struct Spam;
            //- /foo.rs
            use crate::{Sp<|>};
            ",
        );
    }

    #[test]
    fn completes_deeply_nested_use_tree() {
        check_reference_completion(
            "deeply_nested_use_tree",
            "
            //- /lib.rs
            mod foo;
            pub mod bar {
                pub mod baz {
                    pub struct Spam;
                }
            }
            //- /foo.rs
            use crate::{bar::{baz::Sp<|>}};
            ",
        );
    }

    #[test]
    fn completes_enum_variant() {
        check_reference_completion(
            "enum_variant",
            "
            //- /lib.rs
            /// An enum
            enum E {
                /// Foo Variant
                Foo,
                /// Bar Variant with i32
                Bar(i32)
            }
            fn foo() { let _ = E::<|> }
            ",
        );
    }

    #[test]
    fn completes_enum_variant_with_details() {
        check_reference_completion(
            "enum_variant_with_details",
            "
            //- /lib.rs
            struct S { field: u32 }
            /// An enum
            enum E {
                /// Foo Variant (empty)
                Foo,
                /// Bar Variant with i32 and u32
                Bar(i32, u32),
                ///
                S(S),
            }
            fn foo() { let _ = E::<|> }
            ",
        );
    }

    #[test]
    fn completes_struct_associated_method() {
        check_reference_completion(
            "struct_associated_method",
            "
            //- /lib.rs
            /// A Struct
            struct S;

            impl S {
                /// An associated method
                fn m() { }
            }

            fn foo() { let _ = S::<|> }
            ",
        );
    }

    #[test]
    fn completes_struct_associated_const() {
        check_reference_completion(
            "struct_associated_const",
            "
            //- /lib.rs
            /// A Struct
            struct S;

            impl S {
                /// An associated const
                const C: i32 = 42;
            }

            fn foo() { let _ = S::<|> }
            ",
        );
    }

    #[test]
    fn completes_struct_associated_type() {
        check_reference_completion(
            "struct_associated_type",
            "
            //- /lib.rs
            /// A Struct
            struct S;

            impl S {
                /// An associated type
                type T = i32;
            }

            fn foo() { let _ = S::<|> }
            ",
        );
    }

    #[test]
    fn completes_enum_associated_method() {
        check_reference_completion(
            "enum_associated_method",
            "
            //- /lib.rs
            /// An enum
            enum S {};

            impl S {
                /// An associated method
                fn m() { }
            }

            fn foo() { let _ = S::<|> }
            ",
        );
    }

    #[test]
    fn completes_union_associated_method() {
        check_reference_completion(
            "union_associated_method",
            "
            //- /lib.rs
            /// A union
            union U {};

            impl U {
                /// An associated method
                fn m() { }
            }

            fn foo() { let _ = U::<|> }
            ",
        );
    }

    #[test]
    fn completes_use_paths_across_crates() {
        check_reference_completion(
            "completes_use_paths_across_crates",
            "
            //- /main.rs
            use foo::<|>;

            //- /foo/lib.rs
            pub mod bar {
                pub struct S;
            }
            ",
        );
    }
}
<commit_msg>inline snapshots<commit_after>use hir::{Resolution, Either};
use ra_syntax::AstNode;
use test_utils::tested_by;

use crate::completion::{Completions, CompletionContext};

pub(super) fn complete_path(acc: &mut Completions, ctx: &CompletionContext) {
    let path = match &ctx.path_prefix {
        Some(path) => path.clone(),
        _ => return,
    };
    let def = match ctx.analyzer.resolve_hir_path(ctx.db, &path).take_types() {
        Some(Resolution::Def(def)) => def,
        _ => return,
    };
    match def {
        hir::ModuleDef::Module(module) => {
            let module_scope = module.scope(ctx.db);
            for (name, res) in module_scope.entries() {
                if let Some(hir::ModuleDef::BuiltinType(..)) = res.def.as_ref().take_types() {
                    if ctx.use_item_syntax.is_some() {
                        tested_by!(dont_complete_primitive_in_use);
                        continue;
                    }
                }
                if Some(module) == ctx.module {
                    if let Some(import) = res.import {
                        if let Either::A(use_tree) = module.import_source(ctx.db, import) {
                            if use_tree.syntax().range().contains_inclusive(ctx.offset) {
                                // for `use self::foo<|>`, don't suggest `foo` as a completion
                                tested_by!(dont_complete_current_use);
                                continue;
                            }
                        }
                    }
                }
                acc.add_resolution(ctx, name.to_string(), &res.def.map(hir::Resolution::Def));
            }
        }
        hir::ModuleDef::Enum(_) | hir::ModuleDef::Struct(_) | hir::ModuleDef::Union(_) => {
            if let hir::ModuleDef::Enum(e) = def {
                for variant in e.variants(ctx.db) {
                    acc.add_enum_variant(ctx, variant);
                }
            }
            let ty = match def {
                hir::ModuleDef::Enum(e) => e.ty(ctx.db),
                hir::ModuleDef::Struct(s) => s.ty(ctx.db),
                hir::ModuleDef::Union(u) => u.ty(ctx.db),
                _ => unreachable!(),
            };
            let krate = ctx.module.and_then(|m| m.krate(ctx.db));
            if let Some(krate) = krate {
                ty.iterate_impl_items(ctx.db, krate, |item| {
                    match item {
                        hir::ImplItem::Method(func) => {
                            let data = func.data(ctx.db);
                            if !data.has_self_param() {
                                acc.add_function(ctx, func);
                            }
                        }
                        hir::ImplItem::Const(ct) => acc.add_const(ctx, ct),
                        hir::ImplItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
                    }
                    None::<()>
                });
            }
        }
        _ => return,
    };
}

#[cfg(test)]
mod tests {
    use test_utils::covers;

    use crate::completion::{CompletionKind, do_completion, CompletionItem};
    use insta::assert_debug_snapshot_matches;

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

    #[test]
    fn dont_complete_current_use() {
        covers!(dont_complete_current_use);
        let completions = do_completion(r"use self::foo<|>;", CompletionKind::Reference);
        assert!(completions.is_empty());
    }

    #[test]
    fn dont_complete_current_use_in_braces_with_glob() {
        let completions = do_completion(
            r"
            mod foo { pub struct S; }
            use self::{foo::*, bar<|>};
            ",
            CompletionKind::Reference,
        );
        assert_eq!(completions.len(), 2);
    }

    #[test]
    fn dont_complete_primitive_in_use() {
        covers!(dont_complete_primitive_in_use);
        let completions = do_completion(r"use self::<|>;", CompletionKind::BuiltinType);
        assert!(completions.is_empty());
    }

    #[test]
    fn completes_primitives() {
        let completions =
            do_completion(r"fn main() { let _: <|> = 92; }", CompletionKind::BuiltinType);
        assert_eq!(completions.len(), 17);
    }

    #[test]
    fn completes_mod_with_docs() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                r"
                use self::my<|>;

                /// Some simple
                /// docs describing `mod my`.
                mod my {
                    struct Bar;
                }
                "
            ),
            @r###"[
    CompletionItem {
        label: "my",
        source_range: [27; 29),
        delete: [27; 29),
        insert: "my",
        kind: Module,
        documentation: Documentation(
            "Some simple\ndocs describing `mod my`.",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_use_item_starting_with_self() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                r"
                use self::m::<|>;

                mod m {
                    struct Bar;
                }
                "
            ),
            @r###"[
    CompletionItem {
        label: "Bar",
        source_range: [30; 30),
        delete: [30; 30),
        insert: "Bar",
        kind: Struct,
    },
]"###
        );
    }

    #[test]
    fn completes_use_item_starting_with_crate() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                mod foo;
                struct Spam;
                //- /foo.rs
                use crate::Sp<|>
                "
            ),
            @r###"[
    CompletionItem {
        label: "Spam",
        source_range: [11; 13),
        delete: [11; 13),
        insert: "Spam",
        kind: Struct,
    },
    CompletionItem {
        label: "foo",
        source_range: [11; 13),
        delete: [11; 13),
        insert: "foo",
        kind: Module,
    },
]"###
        );
    }

    #[test]
    fn completes_nested_use_tree() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                mod foo;
                struct Spam;
                //- /foo.rs
                use crate::{Sp<|>};
                "
            ),
            @r###"[
    CompletionItem {
        label: "Spam",
        source_range: [12; 14),
        delete: [12; 14),
        insert: "Spam",
        kind: Struct,
    },
    CompletionItem {
        label: "foo",
        source_range: [12; 14),
        delete: [12; 14),
        insert: "foo",
        kind: Module,
    },
]"###
        );
    }

    #[test]
    fn completes_deeply_nested_use_tree() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                mod foo;
                pub mod bar {
                    pub mod baz {
                        pub struct Spam;
                    }
                }
                //- /foo.rs
                use crate::{bar::{baz::Sp<|>}};
                "
            ),
            @r###"[
    CompletionItem {
        label: "Spam",
        source_range: [23; 25),
        delete: [23; 25),
        insert: "Spam",
        kind: Struct,
    },
]"###
        );
    }

    #[test]
    fn completes_enum_variant() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                /// An enum
                enum E {
                    /// Foo Variant
                    Foo,
                    /// Bar Variant with i32
                    Bar(i32)
                }
                fn foo() { let _ = E::<|> }
                "
            ),
            @r###"[
    CompletionItem {
        label: "Bar",
        source_range: [116; 116),
        delete: [116; 116),
        insert: "Bar",
        kind: EnumVariant,
        detail: "(i32)",
        documentation: Documentation(
            "Bar Variant with i32",
        ),
    },
    CompletionItem {
        label: "Foo",
        source_range: [116; 116),
        delete: [116; 116),
        insert: "Foo",
        kind: EnumVariant,
        detail: "()",
        documentation: Documentation(
            "Foo Variant",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_enum_variant_with_details() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                struct S { field: u32 }
                /// An enum
                enum E {
                    /// Foo Variant (empty)
                    Foo,
                    /// Bar Variant with i32 and u32
                    Bar(i32, u32),
                    ///
                    S(S),
                }
                fn foo() { let _ = E::<|> }
                "
            ),
            @r###"[
    CompletionItem {
        label: "Bar",
        source_range: [180; 180),
        delete: [180; 180),
        insert: "Bar",
        kind: EnumVariant,
        detail: "(i32, u32)",
        documentation: Documentation(
            "Bar Variant with i32 and u32",
        ),
    },
    CompletionItem {
        label: "Foo",
        source_range: [180; 180),
        delete: [180; 180),
        insert: "Foo",
        kind: EnumVariant,
        detail: "()",
        documentation: Documentation(
            "Foo Variant (empty)",
        ),
    },
    CompletionItem {
        label: "S",
        source_range: [180; 180),
        delete: [180; 180),
        insert: "S",
        kind: EnumVariant,
        detail: "(S)",
        documentation: Documentation(
            "",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_struct_associated_method() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                /// A Struct
                struct S;

                impl S {
                    /// An associated method
                    fn m() { }
                }

                fn foo() { let _ = S::<|> }
                "
            ),
            @r###"[
    CompletionItem {
        label: "m",
        source_range: [100; 100),
        delete: [100; 100),
        insert: "m()$0",
        kind: Function,
        detail: "fn m()",
        documentation: Documentation(
            "An associated method",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_struct_associated_const() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                /// A Struct
                struct S;

                impl S {
                    /// An associated const
                    const C: i32 = 42;
                }

                fn foo() { let _ = S::<|> }
                "
            ),
            @r###"[
    CompletionItem {
        label: "C",
        source_range: [107; 107),
        delete: [107; 107),
        insert: "C",
        kind: Const,
        detail: "const C: i32 = 42;",
        documentation: Documentation(
            "An associated const",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_struct_associated_type() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                /// A Struct
                struct S;

                impl S {
                    /// An associated type
                    type T = i32;
                }

                fn foo() { let _ = S::<|> }
                "
            ),
            @r###"[
    CompletionItem {
        label: "T",
        source_range: [101; 101),
        delete: [101; 101),
        insert: "T",
        kind: TypeAlias,
        detail: "type T = i32;",
        documentation: Documentation(
            "An associated type",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_enum_associated_method() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                /// An enum
                enum S {};

                impl S {
                    /// An associated method
                    fn m() { }
                }

                fn foo() { let _ = S::<|> }
                "
            ),
            @r###"[
    CompletionItem {
        label: "m",
        source_range: [100; 100),
        delete: [100; 100),
        insert: "m()$0",
        kind: Function,
        detail: "fn m()",
        documentation: Documentation(
            "An associated method",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_union_associated_method() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /lib.rs
                /// A union
                union U {};

                impl U {
                    /// An associated method
                    fn m() { }
                }

                fn foo() { let _ = U::<|> }
                "
            ),
            @r###"[
    CompletionItem {
        label: "m",
        source_range: [101; 101),
        delete: [101; 101),
        insert: "m()$0",
        kind: Function,
        detail: "fn m()",
        documentation: Documentation(
            "An associated method",
        ),
    },
]"###
        );
    }

    #[test]
    fn completes_use_paths_across_crates() {
        assert_debug_snapshot_matches!(
            do_reference_completion(
                "
                //- /main.rs
                use foo::<|>;

                //- /foo/lib.rs
                pub mod bar {
                    pub struct S;
                }
                "
            ),
            @r###"[
    CompletionItem {
        label: "bar",
        source_range: [9; 9),
        delete: [9; 9),
        insert: "bar",
        kind: Module,
    },
]"###
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>No more need for lazy in chat example<commit_after><|endoftext|>


<commit_before><commit_msg>fix intent<commit_after><|endoftext|>


<commit_before>//! [POST /_matrix/client/r0/rooms/{roomId}/leave](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-rooms-roomid-leave)

use ruma_api::ruma_api;
use ruma_identifiers::RoomId;

ruma_api! {
    metadata: {
        description: "Leave a room.",
        method: POST,
        name: "leave_room",
        path: "/_matrix/client/r0/rooms/:room_id/leave",
        rate_limited: true,
        requires_authentication: true,
    }

    request: {
        /// The room to leave.
        #[ruma_api(path)]
        pub room_id: RoomId,
    }

    response: {}

    error: crate::Error
}
<commit_msg>client-api: Update leave_room to new API conventions<commit_after>//! [POST /_matrix/client/r0/rooms/{roomId}/leave](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-rooms-roomid-leave)

use ruma_api::ruma_api;
use ruma_identifiers::RoomId;

ruma_api! {
    metadata: {
        description: "Leave a room.",
        method: POST,
        name: "leave_room",
        path: "/_matrix/client/r0/rooms/:room_id/leave",
        rate_limited: true,
        requires_authentication: true,
    }

    request: {
        /// The room to leave.
        #[ruma_api(path)]
        pub room_id: &'a RoomId,
    }

    response: {}

    error: crate::Error
}

impl<'a> Request<'a> {
    /// Creates a new `Request` with the given room id.
    pub fn new(room_id: &'a RoomId) -> Self {
        Self { room_id }
    }
}

impl Response {
    /// Creates an empty `Response`.
    pub fn new() -> Self {
        Self
    }
}
<|endoftext|>


<commit_before><commit_msg>removed reference to `queue` which does no longer exist for `Text` (yay!)<commit_after><|endoftext|>


<commit_before>use std::{io, path};
use std::rand;
use std::rand::Rng;

fn end(level: uint, state: ~[~str], word:~str){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);

        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");
	println(fmt!("   The word was: %s",word.to_str()));
	println("   PLAY AGAIN? ");
}

fn draw(level: uint, state: ~[~str], past_guess: ~[~str]){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);

        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");

	print("   Past Guesses: ");
	for j in range(0, past_guess.len()){
		print(past_guess[j]);
                print(" ");
	}
	println("");
	println("");
	print("   Enter Next Guess: ");
}

fn load(filename: ~str) -> ~[~str] {
	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(filename));

	if read.is_ok() {
	let file = read.unwrap();
	return file.read_lines();
	}

	println(fmt!("Error in reading the file: %?", read.unwrap_err()));
	return ~[];
}

fn isDuplicate(guess: char, guesses: ~[~str]) -> bool{

	for i in range(0,guesses.len()) {
		if (guess.to_str() == guesses[i]){
			return true;
		}
	}
	return false;

}

//fn searchChar(guess: char) -> bool{

//}

fn main() {
        let mut rng = rand::task_rng();
	let dictionary: ~[~str] = load(~"words.txt");
	let max_size: uint = dictionary.len();
        let n: uint = rng.gen_integer_range(0u, max_size);
	let word: ~str = dictionary[n];
	let word_len: uint = word.char_len();

	//Stores the guessed word
	let mut i = 0;
	let mut stateWord: ~[~str] = ~[];
	while (i < word_len) {
        	stateWord = stateWord + ~[~"_"];
		i += 1;
        }

        //println(fmt!("%s Guessed Word: ", stateWord.to_str()));
	//println(word);

	let mut guesses: ~[~str] = ~[];

	let mut j = 0;

        let max_guess : uint = 6;
	let mut has_won: bool = false;
	while (j < max_guess  && !has_won){
		has_won = true;
		for i in range(0,stateWord.len()) {
			if(stateWord[i]== ~"_"){
				has_won = false;
			}
		}
		if(has_won){
			end(11, stateWord.clone(), word.clone());
			break;
		}
		draw(j+1, stateWord.clone(), guesses.clone());
		let line = io::stdin().read_line();
		let guess_char: char = line.char_at(0);
		//println(fmt!("%? guessed: ", guess_char));
		let has_char: bool = word.contains_char(guess_char);

		if(isDuplicate(guess_char, guesses.clone())){
			//println(fmt!("%? Pick another letter! You have already guess ", guess_char.to_str()));
		}else if (has_char){
			guesses.push(guess_char.to_str());
       			let mut i = 0;
			while (i < word_len) {
				if(word.char_at(i) != guess_char){
        	 			//print("_ ");
                		}else{
		 			stateWord[i] = guess_char.to_str();
				}
				i += 1;
       			 }
			//println("");
		}
		else{
			guesses.push(guess_char.to_str());
			//println("nope.");
			j += 1;
		}

	}
	if(j >= max_guess) {end(17, stateWord.clone(), word.clone());}
}
<commit_msg>only accepts letters<commit_after>use std::{io, path};
use std::rand;
use std::rand::Rng;

fn end(level: uint, state: ~[~str], word:~str){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);

        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");
	println(fmt!("   The word was: %s",word.to_str()));
	println("   PLAY AGAIN? ");
}

fn draw(level: uint, state: ~[~str], past_guess: ~[~str]){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);

        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");

	print("   Past Guesses: ");
	for j in range(0, past_guess.len()){
		print(past_guess[j]);
                print(" ");
	}
	println("");
	println("");
	print("   Enter Next Guess: ");
}

fn load(filename: ~str) -> ~[~str] {
	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(filename));

	if read.is_ok() {
	let file = read.unwrap();
	return file.read_lines();
	}

	println(fmt!("Error in reading the file: %?", read.unwrap_err()));
	return ~[];
}

fn isDuplicate(guess: char, guesses: ~[~str]) -> bool{

	for i in range(0,guesses.len()) {
		if (guess.to_str() == guesses[i]){
			return true;
		}
	}
	return false;

}

//fn searchChar(guess: char) -> bool{

//}

fn main() {
        let mut rng = rand::task_rng();
	let dictionary: ~[~str] = load(~"words.txt");
	let max_size: uint = dictionary.len();
        let n: uint = rng.gen_integer_range(0u, max_size);
	let word: ~str = dictionary[n];
	let word_len: uint = word.char_len();

	//Stores the guessed word
	let mut i = 0;
	let mut stateWord: ~[~str] = ~[];
	while (i < word_len) {
        	stateWord = stateWord + ~[~"_"];
		i += 1;
        }

        //println(fmt!("%s Guessed Word: ", stateWord.to_str()));
	//println(word);

	let mut guesses: ~[~str] = ~[];

	let mut j = 0;

        let max_guess : uint = 6;
	let mut has_won: bool = false;
	while (j < max_guess  && !has_won){
		let mut is_valid: bool = false;
		has_won = true;
		for i in range(0,stateWord.len()) {
			if(stateWord[i]== ~"_"){
				has_won = false;
			}
		}
		if(has_won){
			end(11, stateWord.clone(), word.clone());
			break;
		}
		draw(j+1, stateWord.clone(), guesses.clone());
		let mut line : ~str = ~"";
		while(!is_valid){
		  line = io::stdin().read_line();
		  if(line.len() > 0){
			if(line.char_at(0).is_alphabetic()){
				is_valid = true;
			}
             }

		}
		let guess_char: char = line.char_at(0);
		//println(fmt!("%? guessed: ", guess_char));
		let has_char: bool = word.contains_char(guess_char);

		if(isDuplicate(guess_char, guesses.clone())){
			//println(fmt!("%? Pick another letter! You have already guess ", guess_char.to_str()));
		}else if (has_char){
			guesses.push(guess_char.to_str());
       			let mut i = 0;
			while (i < word_len) {
				if(word.char_at(i) != guess_char){
        	 			//print("_ ");
                		}else{
		 			stateWord[i] = guess_char.to_str();
				}
				i += 1;
       			 }
			//println("");
		}
		else{
			guesses.push(guess_char.to_str());
			//println("nope.");
			j += 1;
		}

	}
	if(j >= max_guess) {end(17, stateWord.clone(), word.clone());}
}
<|endoftext|>


<commit_before><commit_msg>Spawn connect_and_req calls (#296)<commit_after><|endoftext|>


<commit_before>use ::MatchResult;

use pact_matching::Mismatch;
use pact_matching::models::{Pact, Interaction, Request, OptionalBody, PactSpecification};
use pact_matching::models::matchingrules::*;
use pact_matching::models::generators::*;
use pact_matching::models::parse_query_string;

use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use log::{log, error, warn, info, debug};
use hyper::{Body, Response, Server, Error};
use hyper::http::response::{Builder as ResponseBuilder};
use hyper::http::header::{HeaderMap, HeaderName, HeaderValue, InvalidHeaderName, InvalidHeaderValue};
use hyper::service::service_fn;
use futures::future;
use futures::future::Future;
use futures::stream::Stream;
use itertools::Itertools;

enum InteractionError {
    InvalidHeaderEncoding,
    RequestBodyError,
    ResponseHeaderEncodingError,
    ResponseBodyError
}

fn extract_path(uri: &hyper::Uri) -> String {
    uri.path_and_query()
        .map(|path_and_query| path_and_query.path())
        .unwrap_or("/")
        .into()
}

fn extract_query_string(uri: &hyper::Uri) -> Option<HashMap<String, Vec<String>>> {
    uri.path_and_query()
        .and_then(|path_and_query| path_and_query.query())
        .and_then(|query| parse_query_string(&query.into()))
}

fn extract_headers(headers: &hyper::HeaderMap) -> Result<Option<HashMap<String, String>>, InteractionError> {
    if headers.len() > 0 {
        let result: Result<HashMap<String, String>, InteractionError> = headers.keys()
            .map(|name| -> Result<(String, String), InteractionError> {
                let values = headers.get_all(name);
                let mut iter = values.iter();

                let first_value = iter.next().unwrap();

                if iter.next().is_some() {
                    warn!("Multiple headers associated with '{}', but only the first is used", name);
                }

                Ok((
                    name.as_str().into(),
                    first_value.to_str()
                        .map_err(|err| InteractionError::InvalidHeaderEncoding)?
                        .into()
                    )
                )
            })
            .collect();

        result.map(|map| Some(map))
    } else {
        Ok(None)
    }
}

pub fn extract_body(chunk: hyper::Chunk) -> OptionalBody {
    let bytes = chunk.into_bytes();
    if bytes.len() > 0 {
        OptionalBody::Present(bytes.to_vec())
    } else {
        OptionalBody::Empty
    }
}

fn hyper_request_to_pact_request(req: hyper::Request<Body>) -> impl Future<Item = Request, Error = InteractionError> {
    let method = req.method().to_string();
    let path = extract_path(req.uri());
    let query = extract_query_string(req.uri());
    let headers = extract_headers(req.headers());

    future::done(headers)
        .and_then(move |headers| {
            req.into_body()
                .concat2()
                .map_err(|_| InteractionError::RequestBodyError)
                .map(|body_chunk| (headers, body_chunk))
        })
        .and_then(|(headers, body_chunk)|
            Ok(Request {
                method: method,
                path: path,
                query: query,
                headers: headers,
                body: extract_body(body_chunk),
                matching_rules: MatchingRules::default(),
                generators: Generators::default()
            })
        )
}

fn method_or_path_mismatch(mismatches: &Vec<Mismatch>) -> bool {
    mismatches.iter()
        .map(|mismatch| mismatch.mismatch_type())
        .any(|mismatch_type| mismatch_type == "MethodMismatch" || mismatch_type == "PathMismatch")
}

fn match_request(req: &Request, interactions: &Vec<Interaction>) -> MatchResult {
    let match_results = interactions
        .into_iter()
        .map(|i| (i.clone(), pact_matching::match_request(i.request.clone(), req.clone())))
        .sorted_by(|i1, i2| {
            let list1 = i1.1.clone().into_iter().map(|m| m.mismatch_type()).unique().count();
            let list2 = i2.1.clone().into_iter().map(|m| m.mismatch_type()).unique().count();
            Ord::cmp(&list1, &list2)
        });
    match match_results.first() {
        Some(res) => {
            if res.1.is_empty() {
                MatchResult::RequestMatch(res.0.clone())
            } else if method_or_path_mismatch(&res.1) {
                MatchResult::RequestNotFound(req.clone())
            } else {
                MatchResult::RequestMismatch(res.0.clone(), res.1.clone())
            }
        },
        None => MatchResult::RequestNotFound(req.clone())
    }
}

fn set_hyper_headers(builder: &mut ResponseBuilder, headers: &Option<HashMap<String, String>>) -> Result<(), InteractionError> {
    let hyper_headers = builder.headers_mut().unwrap();
    match headers {
        Some(header_map) => {
            for (k, v) in header_map {
                // FIXME?: Headers are not sent in "raw" mode.
                // Names are converted to lower case and values are parsed.
                hyper_headers.insert(
                    HeaderName::from_bytes(k.as_bytes())
                        .map_err(|err| {
                            error!("Invalid header name '{}' ({})", k, err);
                            InteractionError::ResponseHeaderEncodingError
                        })?,
                    v.parse::<HeaderValue>()
                        .map_err(|err| {
                            error!("Invalid header value '{}': '{}' ({})", k, v, err);
                            InteractionError::ResponseHeaderEncodingError
                        })?
                );
            }
        },
        _ => {}
    }
    Ok(())
}

fn match_result_to_hyper_response(match_result: MatchResult) -> Result<Response<Body>, InteractionError> {
    match match_result {
        MatchResult::RequestMatch(ref interaction) => {
            let response = pact_matching::generate_response(&interaction.response);
            info!("Request matched, sending response {:?}", response);
            info!("     body: '{}'\n\n", interaction.response.body.str_value());
            info!("     body: '{}'\n\n", interaction.response.body.str_value());

            let mut builder = Response::builder();
            builder.status(response.status);

            builder.header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            set_hyper_headers(&mut builder, &response.headers)?;

            builder.body(match response.body {
                OptionalBody::Present(ref s) => Body::from(s.clone()),
                _ => Body::empty()
            })
                .map_err(|_| InteractionError::ResponseBodyError)
        },
        _ => {
            Ok(Response::new(Body::from("Hello")))
        }
    }
}

fn handle_request(
    req: hyper::Request<Body>,
    pact: Arc<Pact>,
) -> impl Future<Item = Response<Body>, Error = InteractionError> {
    debug!("Creating pact request from hyper request");

    hyper_request_to_pact_request(req)
        .and_then(move |req| {
            info!("Received request {:?}", req);
            let match_result = match_request(&req, &pact.interactions);

            // TODO:
            // record_result(&mock_server_id, &match_result);

            match_result_to_hyper_response(match_result)
        })
}

// TODO: Should instead use some form of X-Pact headers
fn handle_mock_request_error(result: Result<Response<Body>, InteractionError>) -> Result<Response<Body>, Error> {
    match result {
        Ok(response) => Ok(response),
        Err(error) => {
            let response = match error {
                InteractionError::InvalidHeaderEncoding => Response::builder()
                    .status(400)
                    .body(Body::from("Found an invalid header encoding")),
                InteractionError::RequestBodyError => Response::builder()
                    .status(500)
                    .body(Body::from("Could not process request body")),
                InteractionError::ResponseBodyError => Response::builder()
                    .status(500)
                    .body(Body::from("Could not process response body")),
                InteractionError::ResponseHeaderEncodingError => Response::builder()
                    .status(500)
                    .body(Body::from("Could not set response header"))
            };
            Ok(response.unwrap())
        }
    }
}

pub fn start(
    id: String,
    pact: Pact,
    port: u16,
    shutdown: impl Future<Item = (), Error = ()>,
) -> (impl Future<Item = (), Error = Error>, u16) {
    let pact = Arc::new(pact);
    let addr = ([0, 0, 0, 0], port).into();

    let server = Server::bind(&addr)
        .serve(move || {
            let pact = pact.clone();
            service_fn(move |req| {
                handle_request(req, pact.clone())
                    .then(handle_mock_request_error)
            })
        });

    let port = server.local_addr().port();

    (server.with_graceful_shutdown(shutdown), port)
}
<commit_msg>Also handle match failures<commit_after>use ::MatchResult;

use pact_matching::Mismatch;
use pact_matching::models::{Pact, Interaction, Request, OptionalBody, PactSpecification};
use pact_matching::models::matchingrules::*;
use pact_matching::models::generators::*;
use pact_matching::models::parse_query_string;

use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use log::{log, error, warn, info, debug};
use hyper::{Body, Response, Server, Error};
use hyper::http::response::{Builder as ResponseBuilder};
use hyper::http::header::{HeaderMap, HeaderName, HeaderValue, InvalidHeaderName, InvalidHeaderValue};
use hyper::service::service_fn;
use futures::future;
use futures::future::Future;
use futures::stream::Stream;
use itertools::Itertools;
use serde_json::json;

enum InteractionError {
    InvalidHeaderEncoding,
    RequestBodyError,
    ResponseHeaderEncodingError,
    ResponseBodyError
}

fn extract_path(uri: &hyper::Uri) -> String {
    uri.path_and_query()
        .map(|path_and_query| path_and_query.path())
        .unwrap_or("/")
        .into()
}

fn extract_query_string(uri: &hyper::Uri) -> Option<HashMap<String, Vec<String>>> {
    uri.path_and_query()
        .and_then(|path_and_query| path_and_query.query())
        .and_then(|query| parse_query_string(&query.into()))
}

fn extract_headers(headers: &hyper::HeaderMap) -> Result<Option<HashMap<String, String>>, InteractionError> {
    if headers.len() > 0 {
        let result: Result<HashMap<String, String>, InteractionError> = headers.keys()
            .map(|name| -> Result<(String, String), InteractionError> {
                let values = headers.get_all(name);
                let mut iter = values.iter();

                let first_value = iter.next().unwrap();

                if iter.next().is_some() {
                    warn!("Multiple headers associated with '{}', but only the first is used", name);
                }

                Ok((
                    name.as_str().into(),
                    first_value.to_str()
                        .map_err(|err| InteractionError::InvalidHeaderEncoding)?
                        .into()
                    )
                )
            })
            .collect();

        result.map(|map| Some(map))
    } else {
        Ok(None)
    }
}

pub fn extract_body(chunk: hyper::Chunk) -> OptionalBody {
    let bytes = chunk.into_bytes();
    if bytes.len() > 0 {
        OptionalBody::Present(bytes.to_vec())
    } else {
        OptionalBody::Empty
    }
}

fn hyper_request_to_pact_request(req: hyper::Request<Body>) -> impl Future<Item = Request, Error = InteractionError> {
    let method = req.method().to_string();
    let path = extract_path(req.uri());
    let query = extract_query_string(req.uri());
    let headers = extract_headers(req.headers());

    future::done(headers)
        .and_then(move |headers| {
            req.into_body()
                .concat2()
                .map_err(|_| InteractionError::RequestBodyError)
                .map(|body_chunk| (headers, body_chunk))
        })
        .and_then(|(headers, body_chunk)|
            Ok(Request {
                method: method,
                path: path,
                query: query,
                headers: headers,
                body: extract_body(body_chunk),
                matching_rules: MatchingRules::default(),
                generators: Generators::default()
            })
        )
}

fn method_or_path_mismatch(mismatches: &Vec<Mismatch>) -> bool {
    mismatches.iter()
        .map(|mismatch| mismatch.mismatch_type())
        .any(|mismatch_type| mismatch_type == "MethodMismatch" || mismatch_type == "PathMismatch")
}

fn match_request(req: &Request, interactions: &Vec<Interaction>) -> MatchResult {
    let match_results = interactions
        .into_iter()
        .map(|i| (i.clone(), pact_matching::match_request(i.request.clone(), req.clone())))
        .sorted_by(|i1, i2| {
            let list1 = i1.1.clone().into_iter().map(|m| m.mismatch_type()).unique().count();
            let list2 = i2.1.clone().into_iter().map(|m| m.mismatch_type()).unique().count();
            Ord::cmp(&list1, &list2)
        });
    match match_results.first() {
        Some(res) => {
            if res.1.is_empty() {
                MatchResult::RequestMatch(res.0.clone())
            } else if method_or_path_mismatch(&res.1) {
                MatchResult::RequestNotFound(req.clone())
            } else {
                MatchResult::RequestMismatch(res.0.clone(), res.1.clone())
            }
        },
        None => MatchResult::RequestNotFound(req.clone())
    }
}

fn set_hyper_headers(builder: &mut ResponseBuilder, headers: &Option<HashMap<String, String>>) -> Result<(), InteractionError> {
    let hyper_headers = builder.headers_mut().unwrap();
    match headers {
        Some(header_map) => {
            for (k, v) in header_map {
                // FIXME?: Headers are not sent in "raw" mode.
                // Names are converted to lower case and values are parsed.
                hyper_headers.insert(
                    HeaderName::from_bytes(k.as_bytes())
                        .map_err(|err| {
                            error!("Invalid header name '{}' ({})", k, err);
                            InteractionError::ResponseHeaderEncodingError
                        })?,
                    v.parse::<HeaderValue>()
                        .map_err(|err| {
                            error!("Invalid header value '{}': '{}' ({})", k, v, err);
                            InteractionError::ResponseHeaderEncodingError
                        })?
                );
            }
        },
        _ => {}
    }
    Ok(())
}

fn error_body(request: &Request, error: &String) -> String {
    let body = json!({ "error" : format!("{} : {:?}", error, request) });
    body.to_string()
}

fn match_result_to_hyper_response(request: &Request, match_result: MatchResult) -> Result<Response<Body>, InteractionError> {
    match match_result {
        MatchResult::RequestMatch(ref interaction) => {
            let response = pact_matching::generate_response(&interaction.response);
            info!("Request matched, sending response {:?}", response);
            info!("     body: '{}'\n\n", interaction.response.body.str_value());
            info!("     body: '{}'\n\n", interaction.response.body.str_value());

            let mut builder = Response::builder();
            builder.status(response.status);

            builder.header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            set_hyper_headers(&mut builder, &response.headers)?;

            builder.body(match response.body {
                OptionalBody::Present(ref s) => Body::from(s.clone()),
                _ => Body::empty()
            })
                .map_err(|_| InteractionError::ResponseBodyError)
        },
        _ => {
            Response::builder()
                .status(500)
                .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
                .header(hyper::header::CONTENT_TYPE, "application/json; charset=utf-8")
                .header("X-Pact", match_result.match_key())
                .body(Body::from(error_body(&request, &match_result.match_key())))
                .map_err(|_| InteractionError::ResponseBodyError)
        }
    }
}

fn handle_request(
    req: hyper::Request<Body>,
    pact: Arc<Pact>,
) -> impl Future<Item = Response<Body>, Error = InteractionError> {
    debug!("Creating pact request from hyper request");

    hyper_request_to_pact_request(req)
        .and_then(move |request| {
            info!("Received request {:?}", request);
            let match_result = match_request(&request, &pact.interactions);

            // TODO:
            // record_result(&mock_server_id, &match_result);

            match_result_to_hyper_response(&request, match_result)
        })
}

// TODO: Should instead use some form of X-Pact headers
fn handle_mock_request_error(result: Result<Response<Body>, InteractionError>) -> Result<Response<Body>, Error> {
    match result {
        Ok(response) => Ok(response),
        Err(error) => {
            let response = match error {
                InteractionError::InvalidHeaderEncoding => Response::builder()
                    .status(400)
                    .body(Body::from("Found an invalid header encoding")),
                InteractionError::RequestBodyError => Response::builder()
                    .status(500)
                    .body(Body::from("Could not process request body")),
                InteractionError::ResponseBodyError => Response::builder()
                    .status(500)
                    .body(Body::from("Could not process response body")),
                InteractionError::ResponseHeaderEncodingError => Response::builder()
                    .status(500)
                    .body(Body::from("Could not set response header"))
            };
            Ok(response.unwrap())
        }
    }
}

pub fn start(
    id: String,
    pact: Pact,
    port: u16,
    shutdown: impl Future<Item = (), Error = ()>,
) -> (impl Future<Item = (), Error = Error>, u16) {
    let pact = Arc::new(pact);
    let addr = ([0, 0, 0, 0], port).into();

    let server = Server::bind(&addr)
        .serve(move || {
            let pact = pact.clone();
            service_fn(move |req| {
                handle_request(req, pact.clone())
                    .then(handle_mock_request_error)
            })
        });

    let port = server.local_addr().port();

    (server.with_graceful_shutdown(shutdown), port)
}
<|endoftext|>


<commit_before><commit_msg>Fix constants in match pattern.<commit_after><|endoftext|>


<commit_before>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern crate libc;

use std::io::process::Command;
use std::iter::IteratorExt;

use libc::funcs::posix88::unistd;

// "ps -A -o pid,sid,command" with GNU ps should output something like this:
//   PID   SID COMMAND
//     1     1 /sbin/init
//     2     0 [kthreadd]
//     3     0 [ksoftirqd/0]
// ...
// 12562  9237 ./spawn-failure
// 12563  9237 [spawn-failure] <defunct>
// 12564  9237 [spawn-failure] <defunct>
// ...
// 12592  9237 [spawn-failure] <defunct>
// 12593  9237 ps -A -o pid,sid,command
// 12884 12884 /bin/zsh
// 12922 12922 /bin/zsh
// ...

#[cfg(unix)]
fn find_zombies() {
    // http://man.freebsd.org/ps(1)
    // http://man7.org/linux/man-pages/man1/ps.1.html
    #[cfg(not(target_os = "macos"))]
    const FIELDS: &'static str = "pid,sid,command";

    // https://developer.apple.com/library/mac/documentation/Darwin/
    // Reference/ManPages/man1/ps.1.html
    #[cfg(target_os = "macos")]
    const FIELDS: &'static str = "pid,sess,command";

    let my_sid = unsafe { unistd::getsid(0) };

    let ps_cmd_output = Command::new("ps").args(&["-A", "-o", FIELDS]).output().unwrap();
    let ps_output = String::from_utf8_lossy(ps_cmd_output.output.as_slice());

    let found = ps_output.split('\n').enumerate().any(|(line_no, line)|
        0 < line_no && 0 < line.len() &&
        my_sid == from_str(line.split(' ').filter(|w| 0 < w.len()).nth(1)
            .expect("1st column should be Session ID")
            ).expect("Session ID string into integer") &&
        line.contains("defunct") && {
            println!("Zombie child {}", line);
            true
        }
    );

    assert!( ! found, "Found at least one zombie child");
}

#[cfg(windows)]
fn find_zombies() { }

fn main() {
    let too_long = format!("/NoSuchCommand{:0300}", 0u8);

    for _ in range(0u32, 100) {
        let invalid = Command::new(too_long.as_slice()).spawn();
        assert!(invalid.is_err());
    }

    find_zombies();
}
<commit_msg>Ignore wait-forked-but-failed-child<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-test

extern crate libc;

use std::io::process::Command;
use std::iter::IteratorExt;

use libc::funcs::posix88::unistd;

// "ps -A -o pid,sid,command" with GNU ps should output something like this:
//   PID   SID COMMAND
//     1     1 /sbin/init
//     2     0 [kthreadd]
//     3     0 [ksoftirqd/0]
// ...
// 12562  9237 ./spawn-failure
// 12563  9237 [spawn-failure] <defunct>
// 12564  9237 [spawn-failure] <defunct>
// ...
// 12592  9237 [spawn-failure] <defunct>
// 12593  9237 ps -A -o pid,sid,command
// 12884 12884 /bin/zsh
// 12922 12922 /bin/zsh
// ...

#[cfg(unix)]
fn find_zombies() {
    // http://man.freebsd.org/ps(1)
    // http://man7.org/linux/man-pages/man1/ps.1.html
    #[cfg(not(target_os = "macos"))]
    const FIELDS: &'static str = "pid,sid,command";

    // https://developer.apple.com/library/mac/documentation/Darwin/
    // Reference/ManPages/man1/ps.1.html
    #[cfg(target_os = "macos")]
    const FIELDS: &'static str = "pid,sess,command";

    let my_sid = unsafe { unistd::getsid(0) };

    let ps_cmd_output = Command::new("ps").args(&["-A", "-o", FIELDS]).output().unwrap();
    let ps_output = String::from_utf8_lossy(ps_cmd_output.output.as_slice());

    let found = ps_output.split('\n').enumerate().any(|(line_no, line)|
        0 < line_no && 0 < line.len() &&
        my_sid == from_str(line.split(' ').filter(|w| 0 < w.len()).nth(1)
            .expect("1st column should be Session ID")
            ).expect("Session ID string into integer") &&
        line.contains("defunct") && {
            println!("Zombie child {}", line);
            true
        }
    );

    assert!( ! found, "Found at least one zombie child");
}

#[cfg(windows)]
fn find_zombies() { }

fn main() {
    let too_long = format!("/NoSuchCommand{:0300}", 0u8);

    for _ in range(0u32, 100) {
        let invalid = Command::new(too_long.as_slice()).spawn();
        assert!(invalid.is_err());
    }

    find_zombies();
}
<|endoftext|>


<commit_before>use cocoa::base::id;

pub struct RenderCommandEncoder(id);

impl_from_into_raw!(RenderCommandEncoder, of protocol "MTLRenderCommandEncoder");
<commit_msg>Add some work on RenderCommandEncoder<commit_after>use cocoa::base::id;
use {DepthStencilState, RenderPipelineState};

pub struct RenderCommandEncoder(id);

impl RenderCommandEncoder {
    pub fn set_blend_color(&mut self, red: f32, green: f32, blue: f32, alpha: f32) {
        unimplemented!();
    }

    pub fn set_cull_mode(&mut self, cull_mode: CullMode) {
        unimplemented!();
    }

    pub fn set_depth_bias_with_slope_and_clamp(&mut self, depth_bias: f32, slope: f32, clamp: f32) {
        unimplemented!();
    }

    pub fn set_depth_clip_mode(&mut self, depth_clip_mode: DepthClipMode) {
        unimplemented!();
    }

    pub fn set_depth_stencil_state(&mut self, depth_stencil_state: &DepthStencilState) {
        unimplemented!();
    }

    pub fn set_front_facing_winding(&mut self, winding: Winding) {
        unimplemented!();
    }
}

impl_from_into_raw!(RenderCommandEncoder, of protocol "MTLRenderCommandEncoder");

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CullMode {
    None,
    Front,
    Back
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DepthClipMode {
    Clip,
    Clamp
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Winding {
    Clockwise,
    CounterClockwise
}
<|endoftext|>


<commit_before>/// This list represents the default file types that ripgrep ships with. In
/// general, any file format is fair game, although it should generally be
/// limited to reasonably popular open formats. For other cases, you can add
/// types to each invocation of ripgrep with the '--type-add' flag.
///
/// If you would like to add or improve this list, please file a PR:
/// https://github.com/BurntSushi/ripgrep
///
/// Please try to keep this list sorted lexicographically and wrapped to 79
/// columns (inclusive).
#[rustfmt::skip]
pub const DEFAULT_TYPES: &[(&str, &[&str])] = &[
    ("agda", &["*.agda", "*.lagda"]),
    ("aidl", &["*.aidl"]),
    ("amake", &["*.mk", "*.bp"]),
    ("asciidoc", &["*.adoc", "*.asc", "*.asciidoc"]),
    ("asm", &["*.asm", "*.s", "*.S"]),
    ("asp", &[
        "*.aspx", "*.aspx.cs", "*.aspx.cs", "*.ascx", "*.ascx.cs", "*.ascx.vb",
    ]),
    ("ats", &["*.ats", "*.dats", "*.sats", "*.hats"]),
    ("avro", &["*.avdl", "*.avpr", "*.avsc"]),
    ("awk", &["*.awk"]),
    ("bazel", &["*.bzl", "WORKSPACE", "BUILD", "BUILD.bazel"]),
    ("bitbake", &["*.bb", "*.bbappend", "*.bbclass", "*.conf", "*.inc"]),
    ("brotli", &["*.br"]),
    ("buildstream", &["*.bst"]),
    ("bzip2", &["*.bz2", "*.tbz2"]),
    ("c", &["*.[chH]", "*.[chH].in", "*.cats"]),
    ("cabal", &["*.cabal"]),
    ("cbor", &["*.cbor"]),
    ("ceylon", &["*.ceylon"]),
    ("clojure", &["*.clj", "*.cljc", "*.cljs", "*.cljx"]),
    ("cmake", &["*.cmake", "CMakeLists.txt"]),
    ("coffeescript", &["*.coffee"]),
    ("config", &["*.cfg", "*.conf", "*.config", "*.ini"]),
    ("coq", &["*.v"]),
    ("cpp", &[
        "*.[ChH]", "*.cc", "*.[ch]pp", "*.[ch]xx", "*.hh",  "*.inl",
        "*.[ChH].in", "*.cc.in", "*.[ch]pp.in", "*.[ch]xx.in", "*.hh.in",
    ]),
    ("creole", &["*.creole"]),
    ("crystal", &["Projectfile", "*.cr"]),
    ("cs", &["*.cs"]),
    ("csharp", &["*.cs"]),
    ("cshtml", &["*.cshtml"]),
    ("css", &["*.css", "*.scss"]),
    ("csv", &["*.csv"]),
    ("cython", &["*.pyx", "*.pxi", "*.pxd"]),
    ("d", &["*.d"]),
    ("dart", &["*.dart"]),
    ("dhall", &["*.dhall"]),
    ("diff", &["*.patch", "*.diff"]),
    ("docker", &["*Dockerfile*"]),
    ("dvc", &["Dvcfile", "*.dvc"]),
    ("ebuild", &["*.ebuild"]),
    ("edn", &["*.edn"]),
    ("elisp", &["*.el"]),
    ("elixir", &["*.ex", "*.eex", "*.exs"]),
    ("elm", &["*.elm"]),
    ("erb", &["*.erb"]),
    ("erlang", &["*.erl", "*.hrl"]),
    ("fidl", &["*.fidl"]),
    ("fish", &["*.fish"]),
    ("fortran", &[
        "*.f", "*.F", "*.f77", "*.F77", "*.pfo",
        "*.f90", "*.F90", "*.f95", "*.F95",
    ]),
    ("fsharp", &["*.fs", "*.fsx", "*.fsi"]),
    ("gap", &["*.g", "*.gap", "*.gi", "*.gd", "*.tst"]),
    ("gn", &["*.gn", "*.gni"]),
    ("go", &["*.go"]),
    ("gradle", &["*.gradle"]),
    ("groovy", &["*.groovy", "*.gradle"]),
    ("gzip", &["*.gz", "*.tgz"]),
    ("h", &["*.h", "*.hpp"]),
    ("haml", &["*.haml"]),
    ("haskell", &["*.hs", "*.lhs", "*.cpphs", "*.c2hs", "*.hsc"]),
    ("hbs", &["*.hbs"]),
    ("hs", &["*.hs", "*.lhs"]),
    ("html", &["*.htm", "*.html", "*.ejs"]),
    ("idris", &["*.idr", "*.lidr"]),
    ("java", &["*.java", "*.jsp", "*.jspx", "*.properties"]),
    ("jinja", &["*.j2", "*.jinja", "*.jinja2"]),
    ("jl", &["*.jl"]),
    ("js", &["*.js", "*.jsx", "*.vue"]),
    ("json", &["*.json", "composer.lock"]),
    ("jsonl", &["*.jsonl"]),
    ("julia", &["*.jl"]),
    ("jupyter", &["*.ipynb", "*.jpynb"]),
    ("k", &["*.k"]),
    ("kotlin", &["*.kt", "*.kts"]),
    ("less", &["*.less"]),
    ("license", &[
        // General
        "COPYING", "COPYING[.-]*",
        "COPYRIGHT", "COPYRIGHT[.-]*",
        "EULA", "EULA[.-]*",
        "licen[cs]e", "licen[cs]e.*",
        "LICEN[CS]E", "LICEN[CS]E[.-]*", "*[.-]LICEN[CS]E*",
        "NOTICE", "NOTICE[.-]*",
        "PATENTS", "PATENTS[.-]*",
        "UNLICEN[CS]E", "UNLICEN[CS]E[.-]*",
        // GPL (gpl.txt, etc.)
        "agpl[.-]*",
        "gpl[.-]*",
        "lgpl[.-]*",
        // Other license-specific (APACHE-2.0.txt, etc.)
        "AGPL-*[0-9]*",
        "APACHE-*[0-9]*",
        "BSD-*[0-9]*",
        "CC-BY-*",
        "GFDL-*[0-9]*",
        "GNU-*[0-9]*",
        "GPL-*[0-9]*",
        "LGPL-*[0-9]*",
        "MIT-*[0-9]*",
        "MPL-*[0-9]*",
        "OFL-*[0-9]*",
    ]),
    ("lisp", &["*.el", "*.jl", "*.lisp", "*.lsp", "*.sc", "*.scm"]),
    ("lock", &["*.lock", "package-lock.json"]),
    ("log", &["*.log"]),
    ("lua", &["*.lua"]),
    ("lz4", &["*.lz4"]),
    ("lzma", &["*.lzma"]),
    ("m4", &["*.ac", "*.m4"]),
    ("make", &[
        "[Gg][Nn][Uu]makefile", "[Mm]akefile",
        "[Gg][Nn][Uu]makefile.am", "[Mm]akefile.am",
        "[Gg][Nn][Uu]makefile.in", "[Mm]akefile.in",
        "*.mk", "*.mak"
    ]),
    ("mako", &["*.mako", "*.mao"]),
    ("man", &["*.[0-9lnpx]", "*.[0-9][cEFMmpSx]"]),
    ("markdown", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]),
    ("matlab", &["*.m"]),
    ("md", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]),
    ("meson", &["meson.build", "meson_options.txt"]),
    ("mk", &["mkfile"]),
    ("ml", &["*.ml"]),
    ("msbuild", &[
        "*.csproj", "*.fsproj", "*.vcxproj", "*.proj", "*.props", "*.targets",
    ]),
    ("nim", &["*.nim", "*.nimf", "*.nimble", "*.nims"]),
    ("nix", &["*.nix"]),
    ("objc", &["*.h", "*.m"]),
    ("objcpp", &["*.h", "*.mm"]),
    ("ocaml", &["*.ml", "*.mli", "*.mll", "*.mly"]),
    ("org", &["*.org", "*.org_archive"]),
    ("pascal", &["*.pas", "*.dpr", "*.lpr", "*.pp", "*.inc"]),
    ("pdf", &["*.pdf"]),
    ("perl", &["*.perl", "*.pl", "*.PL", "*.plh", "*.plx", "*.pm", "*.t"]),
    ("php", &["*.php", "*.php3", "*.php4", "*.php5", "*.phtml"]),
    ("pod", &["*.pod"]),
    ("postscript", &["*.eps", "*.ps"]),
    ("protobuf", &["*.proto"]),
    ("ps", &["*.cdxml", "*.ps1", "*.ps1xml", "*.psd1", "*.psm1"]),
    ("puppet", &["*.erb", "*.pp", "*.rb"]),
    ("purs", &["*.purs"]),
    ("py", &["*.py"]),
    ("qmake", &["*.pro", "*.pri", "*.prf"]),
    ("qml", &["*.qml"]),
    ("r", &["*.R", "*.r", "*.Rmd", "*.Rnw"]),
    ("racket", &["*.rkt"]),
    ("rdoc", &["*.rdoc"]),
    ("readme", &["README*", "*README"]),
    ("robot", &["*.robot"]),
    ("rst", &["*.rst"]),
    ("ruby", &["Gemfile", "*.gemspec", ".irbrc", "Rakefile", "*.rb"]),
    ("rust", &["*.rs"]),
    ("sass", &["*.sass", "*.scss"]),
    ("scala", &["*.scala", "*.sbt"]),
    ("sh", &[
        // Portable/misc. init files
        ".login", ".logout", ".profile", "profile",
        // bash-specific init files
        ".bash_login", "bash_login",
        ".bash_logout", "bash_logout",
        ".bash_profile", "bash_profile",
        ".bashrc", "bashrc", "*.bashrc",
        // csh-specific init files
        ".cshrc", "*.cshrc",
        // ksh-specific init files
        ".kshrc", "*.kshrc",
        // tcsh-specific init files
        ".tcshrc",
        // zsh-specific init files
        ".zshenv", "zshenv",
        ".zlogin", "zlogin",
        ".zlogout", "zlogout",
        ".zprofile", "zprofile",
        ".zshrc", "zshrc",
        // Extensions
        "*.bash", "*.csh", "*.ksh", "*.sh", "*.tcsh", "*.zsh",
    ]),
    ("slim", &["*.skim", "*.slim", "*.slime"]),
    ("smarty", &["*.tpl"]),
    ("sml", &["*.sml", "*.sig"]),
    ("soy", &["*.soy"]),
    ("spark", &["*.spark"]),
    ("spec", &["*.spec"]),
    ("sql", &["*.sql", "*.psql"]),
    ("stylus", &["*.styl"]),
    ("sv", &["*.v", "*.vg", "*.sv", "*.svh", "*.h"]),
    ("svg", &["*.svg"]),
    ("swift", &["*.swift"]),
    ("swig", &["*.def", "*.i"]),
    ("systemd", &[
        "*.automount", "*.conf", "*.device", "*.link", "*.mount", "*.path",
        "*.scope", "*.service", "*.slice", "*.socket", "*.swap", "*.target",
        "*.timer",
    ]),
    ("taskpaper", &["*.taskpaper"]),
    ("tcl", &["*.tcl"]),
    ("tex", &["*.tex", "*.ltx", "*.cls", "*.sty", "*.bib", "*.dtx", "*.ins"]),
    ("textile", &["*.textile"]),
    ("tf", &["*.tf"]),
    ("thrift", &["*.thrift"]),
    ("toml", &["*.toml", "Cargo.lock"]),
    ("ts", &["*.ts", "*.tsx"]),
    ("twig", &["*.twig"]),
    ("txt", &["*.txt"]),
    ("typoscript", &["*.typoscript", "*.ts"]),
    ("vala", &["*.vala"]),
    ("vb", &["*.vb"]),
    ("verilog", &["*.v", "*.vh", "*.sv", "*.svh"]),
    ("vhdl", &["*.vhd", "*.vhdl"]),
    ("vim", &["*.vim"]),
    ("vimscript", &["*.vim"]),
    ("webidl", &["*.idl", "*.webidl", "*.widl"]),
    ("wiki", &["*.mediawiki", "*.wiki"]),
    ("xml", &[
        "*.xml", "*.xml.dist", "*.dtd", "*.xsl", "*.xslt", "*.xsd", "*.xjb",
        "*.rng", "*.sch", "*.xhtml",
    ]),
    ("xz", &["*.xz", "*.txz"]),
    ("yacc", &["*.y"]),
    ("yaml", &["*.yaml", "*.yml"]),
    ("z", &["*.Z"]),
    ("zig", &["*.zig"]),
    ("zsh", &[
        ".zshenv", "zshenv",
        ".zlogin", "zlogin",
        ".zlogout", "zlogout",
        ".zprofile", "zprofile",
        ".zshrc", "zshrc",
        "*.zsh",
    ]),
    ("zstd", &["*.zst", "*.zstd"]),
];
<commit_msg>ignore/types: add vcl (#1659)<commit_after>/// This list represents the default file types that ripgrep ships with. In
/// general, any file format is fair game, although it should generally be
/// limited to reasonably popular open formats. For other cases, you can add
/// types to each invocation of ripgrep with the '--type-add' flag.
///
/// If you would like to add or improve this list, please file a PR:
/// https://github.com/BurntSushi/ripgrep
///
/// Please try to keep this list sorted lexicographically and wrapped to 79
/// columns (inclusive).
#[rustfmt::skip]
pub const DEFAULT_TYPES: &[(&str, &[&str])] = &[
    ("agda", &["*.agda", "*.lagda"]),
    ("aidl", &["*.aidl"]),
    ("amake", &["*.mk", "*.bp"]),
    ("asciidoc", &["*.adoc", "*.asc", "*.asciidoc"]),
    ("asm", &["*.asm", "*.s", "*.S"]),
    ("asp", &[
        "*.aspx", "*.aspx.cs", "*.aspx.cs", "*.ascx", "*.ascx.cs", "*.ascx.vb",
    ]),
    ("ats", &["*.ats", "*.dats", "*.sats", "*.hats"]),
    ("avro", &["*.avdl", "*.avpr", "*.avsc"]),
    ("awk", &["*.awk"]),
    ("bazel", &["*.bzl", "WORKSPACE", "BUILD", "BUILD.bazel"]),
    ("bitbake", &["*.bb", "*.bbappend", "*.bbclass", "*.conf", "*.inc"]),
    ("brotli", &["*.br"]),
    ("buildstream", &["*.bst"]),
    ("bzip2", &["*.bz2", "*.tbz2"]),
    ("c", &["*.[chH]", "*.[chH].in", "*.cats"]),
    ("cabal", &["*.cabal"]),
    ("cbor", &["*.cbor"]),
    ("ceylon", &["*.ceylon"]),
    ("clojure", &["*.clj", "*.cljc", "*.cljs", "*.cljx"]),
    ("cmake", &["*.cmake", "CMakeLists.txt"]),
    ("coffeescript", &["*.coffee"]),
    ("config", &["*.cfg", "*.conf", "*.config", "*.ini"]),
    ("coq", &["*.v"]),
    ("cpp", &[
        "*.[ChH]", "*.cc", "*.[ch]pp", "*.[ch]xx", "*.hh",  "*.inl",
        "*.[ChH].in", "*.cc.in", "*.[ch]pp.in", "*.[ch]xx.in", "*.hh.in",
    ]),
    ("creole", &["*.creole"]),
    ("crystal", &["Projectfile", "*.cr"]),
    ("cs", &["*.cs"]),
    ("csharp", &["*.cs"]),
    ("cshtml", &["*.cshtml"]),
    ("css", &["*.css", "*.scss"]),
    ("csv", &["*.csv"]),
    ("cython", &["*.pyx", "*.pxi", "*.pxd"]),
    ("d", &["*.d"]),
    ("dart", &["*.dart"]),
    ("dhall", &["*.dhall"]),
    ("diff", &["*.patch", "*.diff"]),
    ("docker", &["*Dockerfile*"]),
    ("dvc", &["Dvcfile", "*.dvc"]),
    ("ebuild", &["*.ebuild"]),
    ("edn", &["*.edn"]),
    ("elisp", &["*.el"]),
    ("elixir", &["*.ex", "*.eex", "*.exs"]),
    ("elm", &["*.elm"]),
    ("erb", &["*.erb"]),
    ("erlang", &["*.erl", "*.hrl"]),
    ("fidl", &["*.fidl"]),
    ("fish", &["*.fish"]),
    ("fortran", &[
        "*.f", "*.F", "*.f77", "*.F77", "*.pfo",
        "*.f90", "*.F90", "*.f95", "*.F95",
    ]),
    ("fsharp", &["*.fs", "*.fsx", "*.fsi"]),
    ("gap", &["*.g", "*.gap", "*.gi", "*.gd", "*.tst"]),
    ("gn", &["*.gn", "*.gni"]),
    ("go", &["*.go"]),
    ("gradle", &["*.gradle"]),
    ("groovy", &["*.groovy", "*.gradle"]),
    ("gzip", &["*.gz", "*.tgz"]),
    ("h", &["*.h", "*.hpp"]),
    ("haml", &["*.haml"]),
    ("haskell", &["*.hs", "*.lhs", "*.cpphs", "*.c2hs", "*.hsc"]),
    ("hbs", &["*.hbs"]),
    ("hs", &["*.hs", "*.lhs"]),
    ("html", &["*.htm", "*.html", "*.ejs"]),
    ("idris", &["*.idr", "*.lidr"]),
    ("java", &["*.java", "*.jsp", "*.jspx", "*.properties"]),
    ("jinja", &["*.j2", "*.jinja", "*.jinja2"]),
    ("jl", &["*.jl"]),
    ("js", &["*.js", "*.jsx", "*.vue"]),
    ("json", &["*.json", "composer.lock"]),
    ("jsonl", &["*.jsonl"]),
    ("julia", &["*.jl"]),
    ("jupyter", &["*.ipynb", "*.jpynb"]),
    ("k", &["*.k"]),
    ("kotlin", &["*.kt", "*.kts"]),
    ("less", &["*.less"]),
    ("license", &[
        // General
        "COPYING", "COPYING[.-]*",
        "COPYRIGHT", "COPYRIGHT[.-]*",
        "EULA", "EULA[.-]*",
        "licen[cs]e", "licen[cs]e.*",
        "LICEN[CS]E", "LICEN[CS]E[.-]*", "*[.-]LICEN[CS]E*",
        "NOTICE", "NOTICE[.-]*",
        "PATENTS", "PATENTS[.-]*",
        "UNLICEN[CS]E", "UNLICEN[CS]E[.-]*",
        // GPL (gpl.txt, etc.)
        "agpl[.-]*",
        "gpl[.-]*",
        "lgpl[.-]*",
        // Other license-specific (APACHE-2.0.txt, etc.)
        "AGPL-*[0-9]*",
        "APACHE-*[0-9]*",
        "BSD-*[0-9]*",
        "CC-BY-*",
        "GFDL-*[0-9]*",
        "GNU-*[0-9]*",
        "GPL-*[0-9]*",
        "LGPL-*[0-9]*",
        "MIT-*[0-9]*",
        "MPL-*[0-9]*",
        "OFL-*[0-9]*",
    ]),
    ("lisp", &["*.el", "*.jl", "*.lisp", "*.lsp", "*.sc", "*.scm"]),
    ("lock", &["*.lock", "package-lock.json"]),
    ("log", &["*.log"]),
    ("lua", &["*.lua"]),
    ("lz4", &["*.lz4"]),
    ("lzma", &["*.lzma"]),
    ("m4", &["*.ac", "*.m4"]),
    ("make", &[
        "[Gg][Nn][Uu]makefile", "[Mm]akefile",
        "[Gg][Nn][Uu]makefile.am", "[Mm]akefile.am",
        "[Gg][Nn][Uu]makefile.in", "[Mm]akefile.in",
        "*.mk", "*.mak"
    ]),
    ("mako", &["*.mako", "*.mao"]),
    ("man", &["*.[0-9lnpx]", "*.[0-9][cEFMmpSx]"]),
    ("markdown", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]),
    ("matlab", &["*.m"]),
    ("md", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]),
    ("meson", &["meson.build", "meson_options.txt"]),
    ("mk", &["mkfile"]),
    ("ml", &["*.ml"]),
    ("msbuild", &[
        "*.csproj", "*.fsproj", "*.vcxproj", "*.proj", "*.props", "*.targets",
    ]),
    ("nim", &["*.nim", "*.nimf", "*.nimble", "*.nims"]),
    ("nix", &["*.nix"]),
    ("objc", &["*.h", "*.m"]),
    ("objcpp", &["*.h", "*.mm"]),
    ("ocaml", &["*.ml", "*.mli", "*.mll", "*.mly"]),
    ("org", &["*.org", "*.org_archive"]),
    ("pascal", &["*.pas", "*.dpr", "*.lpr", "*.pp", "*.inc"]),
    ("pdf", &["*.pdf"]),
    ("perl", &["*.perl", "*.pl", "*.PL", "*.plh", "*.plx", "*.pm", "*.t"]),
    ("php", &["*.php", "*.php3", "*.php4", "*.php5", "*.phtml"]),
    ("pod", &["*.pod"]),
    ("postscript", &["*.eps", "*.ps"]),
    ("protobuf", &["*.proto"]),
    ("ps", &["*.cdxml", "*.ps1", "*.ps1xml", "*.psd1", "*.psm1"]),
    ("puppet", &["*.erb", "*.pp", "*.rb"]),
    ("purs", &["*.purs"]),
    ("py", &["*.py"]),
    ("qmake", &["*.pro", "*.pri", "*.prf"]),
    ("qml", &["*.qml"]),
    ("r", &["*.R", "*.r", "*.Rmd", "*.Rnw"]),
    ("racket", &["*.rkt"]),
    ("rdoc", &["*.rdoc"]),
    ("readme", &["README*", "*README"]),
    ("robot", &["*.robot"]),
    ("rst", &["*.rst"]),
    ("ruby", &["Gemfile", "*.gemspec", ".irbrc", "Rakefile", "*.rb"]),
    ("rust", &["*.rs"]),
    ("sass", &["*.sass", "*.scss"]),
    ("scala", &["*.scala", "*.sbt"]),
    ("sh", &[
        // Portable/misc. init files
        ".login", ".logout", ".profile", "profile",
        // bash-specific init files
        ".bash_login", "bash_login",
        ".bash_logout", "bash_logout",
        ".bash_profile", "bash_profile",
        ".bashrc", "bashrc", "*.bashrc",
        // csh-specific init files
        ".cshrc", "*.cshrc",
        // ksh-specific init files
        ".kshrc", "*.kshrc",
        // tcsh-specific init files
        ".tcshrc",
        // zsh-specific init files
        ".zshenv", "zshenv",
        ".zlogin", "zlogin",
        ".zlogout", "zlogout",
        ".zprofile", "zprofile",
        ".zshrc", "zshrc",
        // Extensions
        "*.bash", "*.csh", "*.ksh", "*.sh", "*.tcsh", "*.zsh",
    ]),
    ("slim", &["*.skim", "*.slim", "*.slime"]),
    ("smarty", &["*.tpl"]),
    ("sml", &["*.sml", "*.sig"]),
    ("soy", &["*.soy"]),
    ("spark", &["*.spark"]),
    ("spec", &["*.spec"]),
    ("sql", &["*.sql", "*.psql"]),
    ("stylus", &["*.styl"]),
    ("sv", &["*.v", "*.vg", "*.sv", "*.svh", "*.h"]),
    ("svg", &["*.svg"]),
    ("swift", &["*.swift"]),
    ("swig", &["*.def", "*.i"]),
    ("systemd", &[
        "*.automount", "*.conf", "*.device", "*.link", "*.mount", "*.path",
        "*.scope", "*.service", "*.slice", "*.socket", "*.swap", "*.target",
        "*.timer",
    ]),
    ("taskpaper", &["*.taskpaper"]),
    ("tcl", &["*.tcl"]),
    ("tex", &["*.tex", "*.ltx", "*.cls", "*.sty", "*.bib", "*.dtx", "*.ins"]),
    ("textile", &["*.textile"]),
    ("tf", &["*.tf"]),
    ("thrift", &["*.thrift"]),
    ("toml", &["*.toml", "Cargo.lock"]),
    ("ts", &["*.ts", "*.tsx"]),
    ("twig", &["*.twig"]),
    ("txt", &["*.txt"]),
    ("typoscript", &["*.typoscript", "*.ts"]),
    ("vala", &["*.vala"]),
    ("vb", &["*.vb"]),
    ("vcl", &["*.vcl"]),
    ("verilog", &["*.v", "*.vh", "*.sv", "*.svh"]),
    ("vhdl", &["*.vhd", "*.vhdl"]),
    ("vim", &["*.vim"]),
    ("vimscript", &["*.vim"]),
    ("webidl", &["*.idl", "*.webidl", "*.widl"]),
    ("wiki", &["*.mediawiki", "*.wiki"]),
    ("xml", &[
        "*.xml", "*.xml.dist", "*.dtd", "*.xsl", "*.xslt", "*.xsd", "*.xjb",
        "*.rng", "*.sch", "*.xhtml",
    ]),
    ("xz", &["*.xz", "*.txz"]),
    ("yacc", &["*.y"]),
    ("yaml", &["*.yaml", "*.yml"]),
    ("z", &["*.Z"]),
    ("zig", &["*.zig"]),
    ("zsh", &[
        ".zshenv", "zshenv",
        ".zlogin", "zlogin",
        ".zlogout", "zlogout",
        ".zprofile", "zprofile",
        ".zshrc", "zshrc",
        "*.zsh",
    ]),
    ("zstd", &["*.zst", "*.zstd"]),
];
<|endoftext|>