<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.

#![allow(missing_copy_implementations)]

use prelude::v1::*;

use io::{self, Read, Write, ErrorKind, BufRead};

/// Copies the entire contents of a reader into a writer.
///
/// This function will continuously read data from `reader` and then
/// write it into `writer` in a streaming fashion until `reader`
/// returns EOF.
///
/// On success, the total number of bytes that were copied from
/// `reader` to `writer` is returned.
///
/// # Errors
///
/// This function will return an error immediately if any call to `read` or
/// `write` returns an error. All instances of `ErrorKind::Interrupted` are
/// handled by this function and the underlying operation is retried.
///
/// # Examples
///
/// ```
/// use std::io;
///
/// # fn foo() -> io::Result<()> {
/// let mut reader: &[u8] = b"hello";
/// let mut writer: Vec<u8> = vec![];
///
/// try!(io::copy(&mut reader, &mut writer));
///
/// assert_eq!(reader, &writer[..]);
/// # Ok(())
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> io::Result<u64> {
    let mut buf = [0; super::DEFAULT_BUF_SIZE];
    let mut written = 0;
    loop {
        let len = match reader.read(&mut buf) {
            Ok(0) => return Ok(written),
            Ok(len) => len,
            Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        };
        try!(writer.write_all(&buf[..len]));
        written += len as u64;
    }
}

/// A reader which is always at EOF.
///
/// This struct is generally created by calling [`empty()`][empty]. Please see
/// the documentation of `empty()` for more details.
///
/// [empty]: fn.empty.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Empty { _priv: () }

/// Constructs a new handle to an empty reader.
///
/// All reads from the returned reader will return `Ok(0)`.
///
/// # Examples
///
/// A slightly sad example of not reading anything into a buffer:
///
/// ```
/// use std::io;
/// use std::io::Read;
///
/// # fn foo() -> io::Result<String> {
/// let mut buffer = String::new();
/// try!(io::empty().read_to_string(&mut buffer));
/// # Ok(buffer)
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn empty() -> Empty { Empty { _priv: () } }

#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Empty {
    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl BufRead for Empty {
    fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
    fn consume(&mut self, _n: usize) {}
}

/// A reader which yields one byte over and over and over and over and over and...
///
/// This struct is generally created by calling [`repeat()`][repeat]. Please
/// see the documentation of `repeat()` for more details.
///
/// [empty]: fn.repeat.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Repeat { byte: u8 }

/// Creates an instance of a reader that infinitely repeats one byte.
///
/// All reads from this reader will succeed by filling the specified buffer with
/// the given byte.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }

#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Repeat {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        for slot in &mut *buf {
            *slot = self.byte;
        }
        Ok(buf.len())
    }
}

/// A writer which will move data into the void.
///
/// This struct is generally created by calling [`sink()`][sink]. Please
/// see the documentation of `sink()` for more details.
///
/// [empty]: fn.sink.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Sink { _priv: () }

/// Creates an instance of a writer which will successfully consume all data.
///
/// All calls to `write` on the returned instance will return `Ok(buf.len())`
/// and the contents of the buffer will not be inspected.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn sink() -> Sink { Sink { _priv: () } }

#[stable(feature = "rust1", since = "1.0.0")]
impl Write for Sink {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
    fn flush(&mut self) -> io::Result<()> { Ok(()) }
}

#[cfg(test)]
mod tests {
    use prelude::v1::*;

    use io::prelude::*;
    use io::{sink, empty, repeat};

    #[test]
    fn sink_sinks() {
        let mut s = sink();
        assert_eq!(s.write(&[]).unwrap(), 0);
        assert_eq!(s.write(&[0]).unwrap(), 1);
        assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
        assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
    }

    #[test]
    fn empty_reads() {
        let mut e = empty();
        assert_eq!(e.read(&mut []).unwrap(), 0);
        assert_eq!(e.read(&mut [0]).unwrap(), 0);
        assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
        assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
    }

    #[test]
    fn repeat_repeats() {
        let mut r = repeat(4);
        let mut b = [0; 1024];
        assert_eq!(r.read(&mut b).unwrap(), 1024);
        assert!(b.iter().all(|b| *b == 4));
    }

    #[test]
    fn take_some_bytes() {
        assert_eq!(repeat(4).take(100).bytes().count(), 100);
        assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
        assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
    }

    #[test]
    fn tee() {
        let mut buf = [0; 10];
        {
            let mut ptr: &mut [u8] = &mut buf;
            assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]).unwrap(), 5);
        }
        assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn broadcast() {
        let mut buf1 = [0; 10];
        let mut buf2 = [0; 10];
        {
            let mut ptr1: &mut [u8] = &mut buf1;
            let mut ptr2: &mut [u8] = &mut buf2;

            assert_eq!((&mut ptr1).broadcast(&mut ptr2)
                                  .write(&[1, 2, 3]).unwrap(), 3);
        }
        assert_eq!(buf1, buf2);
        assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]);
    }
}
<commit_msg>Rollup merge of #27342 - steveklabnik:fix_links, r=alexcrichton<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.

#![allow(missing_copy_implementations)]

use prelude::v1::*;

use io::{self, Read, Write, ErrorKind, BufRead};

/// Copies the entire contents of a reader into a writer.
///
/// This function will continuously read data from `reader` and then
/// write it into `writer` in a streaming fashion until `reader`
/// returns EOF.
///
/// On success, the total number of bytes that were copied from
/// `reader` to `writer` is returned.
///
/// # Errors
///
/// This function will return an error immediately if any call to `read` or
/// `write` returns an error. All instances of `ErrorKind::Interrupted` are
/// handled by this function and the underlying operation is retried.
///
/// # Examples
///
/// ```
/// use std::io;
///
/// # fn foo() -> io::Result<()> {
/// let mut reader: &[u8] = b"hello";
/// let mut writer: Vec<u8> = vec![];
///
/// try!(io::copy(&mut reader, &mut writer));
///
/// assert_eq!(reader, &writer[..]);
/// # Ok(())
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> io::Result<u64> {
    let mut buf = [0; super::DEFAULT_BUF_SIZE];
    let mut written = 0;
    loop {
        let len = match reader.read(&mut buf) {
            Ok(0) => return Ok(written),
            Ok(len) => len,
            Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        };
        try!(writer.write_all(&buf[..len]));
        written += len as u64;
    }
}

/// A reader which is always at EOF.
///
/// This struct is generally created by calling [`empty()`][empty]. Please see
/// the documentation of `empty()` for more details.
///
/// [empty]: fn.empty.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Empty { _priv: () }

/// Constructs a new handle to an empty reader.
///
/// All reads from the returned reader will return `Ok(0)`.
///
/// # Examples
///
/// A slightly sad example of not reading anything into a buffer:
///
/// ```
/// use std::io;
/// use std::io::Read;
///
/// # fn foo() -> io::Result<String> {
/// let mut buffer = String::new();
/// try!(io::empty().read_to_string(&mut buffer));
/// # Ok(buffer)
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn empty() -> Empty { Empty { _priv: () } }

#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Empty {
    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl BufRead for Empty {
    fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
    fn consume(&mut self, _n: usize) {}
}

/// A reader which yields one byte over and over and over and over and over and...
///
/// This struct is generally created by calling [`repeat()`][repeat]. Please
/// see the documentation of `repeat()` for more details.
///
/// [repeat]: fn.repeat.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Repeat { byte: u8 }

/// Creates an instance of a reader that infinitely repeats one byte.
///
/// All reads from this reader will succeed by filling the specified buffer with
/// the given byte.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }

#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Repeat {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        for slot in &mut *buf {
            *slot = self.byte;
        }
        Ok(buf.len())
    }
}

/// A writer which will move data into the void.
///
/// This struct is generally created by calling [`sink()`][sink]. Please
/// see the documentation of `sink()` for more details.
///
/// [sink]: fn.sink.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Sink { _priv: () }

/// Creates an instance of a writer which will successfully consume all data.
///
/// All calls to `write` on the returned instance will return `Ok(buf.len())`
/// and the contents of the buffer will not be inspected.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn sink() -> Sink { Sink { _priv: () } }

#[stable(feature = "rust1", since = "1.0.0")]
impl Write for Sink {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
    fn flush(&mut self) -> io::Result<()> { Ok(()) }
}

#[cfg(test)]
mod tests {
    use prelude::v1::*;

    use io::prelude::*;
    use io::{sink, empty, repeat};

    #[test]
    fn sink_sinks() {
        let mut s = sink();
        assert_eq!(s.write(&[]).unwrap(), 0);
        assert_eq!(s.write(&[0]).unwrap(), 1);
        assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
        assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
    }

    #[test]
    fn empty_reads() {
        let mut e = empty();
        assert_eq!(e.read(&mut []).unwrap(), 0);
        assert_eq!(e.read(&mut [0]).unwrap(), 0);
        assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
        assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
    }

    #[test]
    fn repeat_repeats() {
        let mut r = repeat(4);
        let mut b = [0; 1024];
        assert_eq!(r.read(&mut b).unwrap(), 1024);
        assert!(b.iter().all(|b| *b == 4));
    }

    #[test]
    fn take_some_bytes() {
        assert_eq!(repeat(4).take(100).bytes().count(), 100);
        assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
        assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
    }

    #[test]
    fn tee() {
        let mut buf = [0; 10];
        {
            let mut ptr: &mut [u8] = &mut buf;
            assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]).unwrap(), 5);
        }
        assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn broadcast() {
        let mut buf1 = [0; 10];
        let mut buf2 = [0; 10];
        {
            let mut ptr1: &mut [u8] = &mut buf1;
            let mut ptr2: &mut [u8] = &mut buf2;

            assert_eq!((&mut ptr1).broadcast(&mut ptr2)
                                  .write(&[1, 2, 3]).unwrap(), 3);
        }
        assert_eq!(buf1, buf2);
        assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add integration test for binding to port zero<commit_after><|endoftext|>


<commit_before><commit_msg>added integration tests<commit_after>extern crate timely;
extern crate differential_dataflow;

use timely::dataflow::operators::{ToStream, Capture};
use timely::dataflow::operators::capture::Extract;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::{ConsolidateExt, Join};

#[test]
fn join() {

    let data = timely::example(|scope| {

        let col1 = vec![((0,0),1),((1,2),1)]
                        .into_iter()
                        .to_stream(scope)
                        .as_collection();

        let col2 = vec![((0,'a'),1),((1,'B'),1)]
                        .into_iter()
                        .to_stream(scope)
                        .as_collection();

        // should produce triples `(0,0,'a')` and `(1,2,'B')`.
        col1.join(&col2).inner.capture()
    });

    let extracted = data.extract();
    assert_eq!(extracted.len(), 1);
    assert_eq!(extracted[0].1, vec![((0,0,'a'),1), ((1,2,'B'),1)]);

}

#[test]
fn join_map() {

    let data = timely::example(|scope| {
        let col1 = vec![((0,0),1),((1,2),1)].into_iter().to_stream(scope).as_collection();
        let col2 = vec![((0,'a'),1),((1,'B'),1)].into_iter().to_stream(scope).as_collection();

        // should produce records `(0 + 0,'a')` and `(1 + 2,'B')`.
        col1.join_map(&col2, |k,v1,v2| (*k + *v1, *v2)).inner.capture()
    });

    let extracted = data.extract();
    assert_eq!(extracted.len(), 1);
    assert_eq!(extracted[0].1, vec![((0,'a'),1), ((3,'B'),1)]);
}

#[test]
fn semijoin() {
    let data = timely::example(|scope| {
        let col1 = vec![((0,0),1),((1,2),1)].into_iter().to_stream(scope).as_collection();
        let col2 = vec![(0,1)].into_iter().to_stream(scope).as_collection();

        // should retain record `(0,0)` and discard `(1,2)`.
        col1.semijoin(&col2).inner.capture()
    });

    let extracted = data.extract();
    assert_eq!(extracted.len(), 1);
    assert_eq!(extracted[0].1, vec![((0,0),1)]);
}

#[test]
fn antijoin() {
    let data = timely::example(|scope| {
        let col1 = vec![((0,0),1),((1,2),1)].into_iter().to_stream(scope).as_collection();
        let col2 = vec![(0,1)].into_iter().to_stream(scope).as_collection();

        // should retain record `(1,2)` and discard `(0,0)`.
        col1.antijoin(&col2).consolidate().inner.capture()
    });
    let extracted = data.extract();
    assert_eq!(extracted.len(), 1);
    assert_eq!(extracted[0].1, vec![((1,2),1)]);
}<|endoftext|>


<commit_before><commit_msg>Try another version since it looks like Blake2b wraps anyways<commit_after><|endoftext|>


<commit_before>#[doc(
    brief = "Provides all access to AST-related, non-sendable info",
    desc =
    "Rustdoc is intended to be parallel, and the rustc AST is filled \
     with shared boxes. The AST service attempts to provide a single \
     place to query AST-related information, shielding the rest of \
     Rustdoc from its non-sendableness."
)];

import std::map::hashmap;
import rustc::driver::session;
import session::session;
import rustc::driver::driver;
import syntax::diagnostic;
import syntax::diagnostic::handler;
import syntax::ast;
import syntax::codemap;
import syntax::ast_map;
import rustc::back::link;
import rustc::metadata::filesearch;
import rustc::front;
import rustc::middle::resolve;

export ctxt;
export ctxt_handler;
export srv::{};
export from_str;
export from_file;
export exec;

type ctxt = {
    ast: @ast::crate,
    ast_map: ast_map::map,
    exp_map: resolve::exp_map,
    impl_map: resolve::impl_map
};

type srv_owner<T> = fn(srv: srv) -> T;
type ctxt_handler<T> = fn~(ctxt: ctxt) -> T;
type parser = fn~(session::session, str) -> @ast::crate;

enum msg {
    handle_request(fn~(ctxt)),
    exit
}

enum srv = {
    ch: comm::chan<msg>
};

fn from_str<T>(source: str, owner: srv_owner<T>) -> T {
    run(owner, source, parse::from_str_sess)
}

fn from_file<T>(file: str, owner: srv_owner<T>) -> T {
    run(owner, file, parse::from_file_sess)
}

fn run<T>(owner: srv_owner<T>, source: str, +parse: parser) -> T {

    let srv_ = srv({
        ch: task::spawn_listener {|po|
            act(po, source, parse);
        }
    });

    let res = owner(srv_);
    comm::send(srv_.ch, exit);
    ret res;
}

fn act(po: comm::port<msg>, source: str, parse: parser) {
    let (sess, ignore_errors) = build_session();

    let ctxt = build_ctxt(
        sess,
        parse(sess, source),
        ignore_errors
    );

    let mut keep_going = true;
    while keep_going {
        alt comm::recv(po) {
          handle_request(f) {
            f(ctxt);
          }
          exit {
            keep_going = false;
          }
        }
    }
}

fn exec<T:send>(
    srv: srv,
    +f: fn~(ctxt: ctxt) -> T
) -> T {
    let po = comm::port();
    let ch = comm::chan(po);
    let msg = handle_request(fn~(move f, ctxt: ctxt) {
        comm::send(ch, f(ctxt))
    });
    comm::send(srv.ch, msg);
    comm::recv(po)
}

fn build_ctxt(sess: session::session, ast: @ast::crate,
              ignore_errors: @mut bool) -> ctxt {

    import rustc::front::config;

    let ast = config::strip_unconfigured_items(ast);
    let ast = front::test::modify_for_testing(sess, ast);
    let ast_map = ast_map::map_crate(sess.diagnostic(), *ast);
    *ignore_errors = true;
    let {exp_map, impl_map, _} = resolve::resolve_crate(sess, ast_map, ast);
    *ignore_errors = false;

    {
        ast: ast,
        ast_map: ast_map,
        exp_map: exp_map,
        impl_map: impl_map
    }
}

fn build_session() -> (session::session, @mut bool) {
    let sopts: @session::options = session::basic_options();
    let codemap = codemap::new_codemap();
    let error_handlers = build_error_handlers(codemap);
    let {emitter, span_handler, ignore_errors} = error_handlers;

    let session = driver::build_session_(sopts, codemap, emitter,
                                         span_handler);
    (session, ignore_errors)
}

type error_handlers = {
    emitter: diagnostic::emitter,
    span_handler: diagnostic::span_handler,
    ignore_errors: @mut bool
};

// Build a custom error handler that will allow us to ignore non-fatal
// errors
fn build_error_handlers(
    codemap: codemap::codemap
) -> error_handlers {

    type diagnostic_handler = {
        inner: diagnostic::handler,
        ignore_errors: @mut bool
    };

    impl of diagnostic::handler for diagnostic_handler {
        fn fatal(msg: str) -> ! { self.inner.fatal(msg) }
        fn err(msg: str) { self.inner.err(msg) }
        fn bump_err_count() {
            if !(*self.ignore_errors) {
                self.inner.bump_err_count();
            }
        }
        fn has_errors() -> bool { self.inner.has_errors() }
        fn abort_if_errors() { self.inner.abort_if_errors() }
        fn warn(msg: str) { self.inner.warn(msg) }
        fn note(msg: str) { self.inner.note(msg) }
        fn bug(msg: str) -> ! { self.inner.bug(msg) }
        fn unimpl(msg: str) -> ! { self.inner.unimpl(msg) }
        fn emit(cmsp: option<(codemap::codemap, codemap::span)>,
                msg: str, lvl: diagnostic::level) {
            self.inner.emit(cmsp, msg, lvl)
        }
    }

    let ignore_errors = @mut false;
    let emitter = fn@(cmsp: option<(codemap::codemap, codemap::span)>,
                       msg: str, lvl: diagnostic::level) {
        if !(*ignore_errors) {
            diagnostic::emit(cmsp, msg, lvl);
        }
    };
    let inner_handler = diagnostic::mk_handler(some(emitter));
    let handler = {
        inner: inner_handler,
        ignore_errors: ignore_errors
    };
    let span_handler = diagnostic::mk_span_handler(
        handler as diagnostic::handler, codemap);

    {
        emitter: emitter,
        span_handler: span_handler,
        ignore_errors: ignore_errors
    }
}

#[test]
fn should_prune_unconfigured_items() {
    let source = "#[cfg(shut_up_and_leave_me_alone)]fn a() { }";
    from_str(source) {|srv|
        exec(srv) {|ctxt|
            assert vec::is_empty(ctxt.ast.node.module.items);
        }
    }
}

#[test]
fn srv_should_build_ast_map() {
    let source = "fn a() { }";
    from_str(source) {|srv|
        exec(srv) {|ctxt|
            assert ctxt.ast_map.size() != 0u
        };
    }
}

#[test]
fn srv_should_build_reexport_map() {
    let source = "import a::b; export b; mod a { mod b { } }";
    from_str(source) {|srv|
        exec(srv) {|ctxt|
            assert ctxt.exp_map.size() != 0u
        };
    }
}

#[test]
fn srv_should_resolve_external_crates() {
    let source = "use std;\
                  fn f() -> std::sha1::sha1 {\
                  std::sha1::mk_sha1() }";
    // Just testing that resolve doesn't crash
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_resolve_core_crate() {
    let source = "fn a() -> option { fail }";
    // Just testing that resolve doesn't crash
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_resolve_non_existant_imports() {
    // We want to ignore things we can't resolve. Shouldn't
    // need to be able to find external crates to create docs.
    let source = "import wooboo; fn a() { }";
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_resolve_non_existant_uses() {
    let source = "use forble; fn a() { }";
    from_str(source) {|_srv| }
}

#[test]
fn should_ignore_external_import_paths_that_dont_exist() {
    let source = "use forble; import forble::bippy;";
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_return_request_result() {
    let source = "fn a() { }";
    from_str(source) {|srv|
        let result = exec(srv) {|_ctxt| 1000};
        assert result == 1000;
    }
}
<commit_msg>rustdoc: Work around some more metadata infelicities<commit_after>#[doc(
    brief = "Provides all access to AST-related, non-sendable info",
    desc =
    "Rustdoc is intended to be parallel, and the rustc AST is filled \
     with shared boxes. The AST service attempts to provide a single \
     place to query AST-related information, shielding the rest of \
     Rustdoc from its non-sendableness."
)];

import std::map::hashmap;
import rustc::driver::session;
import session::{basic_options, options};
import session::session;
import rustc::driver::driver;
import syntax::diagnostic;
import syntax::diagnostic::handler;
import syntax::ast;
import syntax::codemap;
import syntax::ast_map;
import rustc::back::link;
import rustc::metadata::filesearch;
import rustc::front;
import rustc::middle::resolve;

export ctxt;
export ctxt_handler;
export srv::{};
export from_str;
export from_file;
export exec;

type ctxt = {
    ast: @ast::crate,
    ast_map: ast_map::map,
    exp_map: resolve::exp_map,
    impl_map: resolve::impl_map
};

type srv_owner<T> = fn(srv: srv) -> T;
type ctxt_handler<T> = fn~(ctxt: ctxt) -> T;
type parser = fn~(session, str) -> @ast::crate;

enum msg {
    handle_request(fn~(ctxt)),
    exit
}

enum srv = {
    ch: comm::chan<msg>
};

fn from_str<T>(source: str, owner: srv_owner<T>) -> T {
    run(owner, source, parse::from_str_sess)
}

fn from_file<T>(file: str, owner: srv_owner<T>) -> T {
    run(owner, file, parse::from_file_sess)
}

fn run<T>(owner: srv_owner<T>, source: str, +parse: parser) -> T {

    let srv_ = srv({
        ch: task::spawn_listener {|po|
            act(po, source, parse);
        }
    });

    let res = owner(srv_);
    comm::send(srv_.ch, exit);
    ret res;
}

fn act(po: comm::port<msg>, source: str, parse: parser) {
    let (sess, ignore_errors) = build_session();

    let ctxt = build_ctxt(
        sess,
        parse(sess, source),
        ignore_errors
    );

    let mut keep_going = true;
    while keep_going {
        alt comm::recv(po) {
          handle_request(f) {
            f(ctxt);
          }
          exit {
            keep_going = false;
          }
        }
    }
}

fn exec<T:send>(
    srv: srv,
    +f: fn~(ctxt: ctxt) -> T
) -> T {
    let po = comm::port();
    let ch = comm::chan(po);
    let msg = handle_request(fn~(move f, ctxt: ctxt) {
        comm::send(ch, f(ctxt))
    });
    comm::send(srv.ch, msg);
    comm::recv(po)
}

fn build_ctxt(sess: session,
              ast: @ast::crate,
              ignore_errors: @mut bool) -> ctxt {

    import rustc::front::config;

    let ast = config::strip_unconfigured_items(ast);
    let ast = front::test::modify_for_testing(sess, ast);
    let ast_map = ast_map::map_crate(sess.diagnostic(), *ast);
    *ignore_errors = true;
    let {exp_map, impl_map, _} = resolve::resolve_crate(sess, ast_map, ast);
    *ignore_errors = false;

    {
        ast: ast,
        ast_map: ast_map,
        exp_map: exp_map,
        impl_map: impl_map
    }
}

fn build_session() -> (session, @mut bool) {
    let sopts: @options = basic_options();
    let codemap = codemap::new_codemap();
    let error_handlers = build_error_handlers(codemap);
    let {emitter, span_handler, ignore_errors} = error_handlers;

    let session = driver::build_session_(sopts, codemap, emitter,
                                         span_handler);
    (session, ignore_errors)
}

type error_handlers = {
    emitter: diagnostic::emitter,
    span_handler: diagnostic::span_handler,
    ignore_errors: @mut bool
};

// Build a custom error handler that will allow us to ignore non-fatal
// errors
fn build_error_handlers(
    codemap: codemap::codemap
) -> error_handlers {

    type diagnostic_handler = {
        inner: diagnostic::handler,
        ignore_errors: @mut bool
    };

    impl of diagnostic::handler for diagnostic_handler {
        fn fatal(msg: str) -> ! { self.inner.fatal(msg) }
        fn err(msg: str) { self.inner.err(msg) }
        fn bump_err_count() {
            if !(*self.ignore_errors) {
                self.inner.bump_err_count();
            }
        }
        fn has_errors() -> bool { self.inner.has_errors() }
        fn abort_if_errors() { self.inner.abort_if_errors() }
        fn warn(msg: str) { self.inner.warn(msg) }
        fn note(msg: str) { self.inner.note(msg) }
        fn bug(msg: str) -> ! { self.inner.bug(msg) }
        fn unimpl(msg: str) -> ! { self.inner.unimpl(msg) }
        fn emit(cmsp: option<(codemap::codemap, codemap::span)>,
                msg: str, lvl: diagnostic::level) {
            self.inner.emit(cmsp, msg, lvl)
        }
    }

    let ignore_errors = @mut false;
    let emitter = fn@(cmsp: option<(codemap::codemap, codemap::span)>,
                       msg: str, lvl: diagnostic::level) {
        if !(*ignore_errors) {
            diagnostic::emit(cmsp, msg, lvl);
        }
    };
    let inner_handler = diagnostic::mk_handler(some(emitter));
    let handler = {
        inner: inner_handler,
        ignore_errors: ignore_errors
    };
    let span_handler = diagnostic::mk_span_handler(
        handler as diagnostic::handler, codemap);

    {
        emitter: emitter,
        span_handler: span_handler,
        ignore_errors: ignore_errors
    }
}

#[test]
fn should_prune_unconfigured_items() {
    let source = "#[cfg(shut_up_and_leave_me_alone)]fn a() { }";
    from_str(source) {|srv|
        exec(srv) {|ctxt|
            assert vec::is_empty(ctxt.ast.node.module.items);
        }
    }
}

#[test]
fn srv_should_build_ast_map() {
    let source = "fn a() { }";
    from_str(source) {|srv|
        exec(srv) {|ctxt|
            assert ctxt.ast_map.size() != 0u
        };
    }
}

#[test]
fn srv_should_build_reexport_map() {
    let source = "import a::b; export b; mod a { mod b { } }";
    from_str(source) {|srv|
        exec(srv) {|ctxt|
            assert ctxt.exp_map.size() != 0u
        };
    }
}

#[test]
fn srv_should_resolve_external_crates() {
    let source = "use std;\
                  fn f() -> std::sha1::sha1 {\
                  std::sha1::mk_sha1() }";
    // Just testing that resolve doesn't crash
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_resolve_core_crate() {
    let source = "fn a() -> option { fail }";
    // Just testing that resolve doesn't crash
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_resolve_non_existant_imports() {
    // We want to ignore things we can't resolve. Shouldn't
    // need to be able to find external crates to create docs.
    let source = "import wooboo; fn a() { }";
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_resolve_non_existant_uses() {
    let source = "use forble; fn a() { }";
    from_str(source) {|_srv| }
}

#[test]
fn should_ignore_external_import_paths_that_dont_exist() {
    let source = "use forble; import forble::bippy;";
    from_str(source) {|_srv| }
}

#[test]
fn srv_should_return_request_result() {
    let source = "fn a() { }";
    from_str(source) {|srv|
        let result = exec(srv) {|_ctxt| 1000};
        assert result == 1000;
    }
}
<|endoftext|>


<commit_before>// Copyright 2012-2015 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.

use hir::def_id::DefId;
use infer::type_variable;
use ty::{self, BoundRegion, DefIdTree, Region, Ty, TyCtxt};

use std::fmt;
use syntax::abi;
use syntax::ast::{self, Name};
use errors::DiagnosticBuilder;
use syntax_pos::Span;

use hir;

#[derive(Clone, Copy, Debug)]
pub struct ExpectedFound<T> {
    pub expected: T,
    pub found: T,
}

// Data structures used in type unification
#[derive(Clone, Debug)]
pub enum TypeError<'tcx> {
    Mismatch,
    UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
    AbiMismatch(ExpectedFound<abi::Abi>),
    Mutability,
    TupleSize(ExpectedFound<usize>),
    FixedArraySize(ExpectedFound<usize>),
    ArgCount,
    RegionsDoesNotOutlive(&'tcx Region, &'tcx Region),
    RegionsNotSame(&'tcx Region, &'tcx Region),
    RegionsNoOverlap(&'tcx Region, &'tcx Region),
    RegionsInsufficientlyPolymorphic(BoundRegion, &'tcx Region, Option<Box<ty::Issue32330>>),
    RegionsOverlyPolymorphic(BoundRegion, &'tcx Region, Option<Box<ty::Issue32330>>),
    Sorts(ExpectedFound<Ty<'tcx>>),
    IntMismatch(ExpectedFound<ty::IntVarValue>),
    FloatMismatch(ExpectedFound<ast::FloatTy>),
    Traits(ExpectedFound<DefId>),
    VariadicMismatch(ExpectedFound<bool>),
    CyclicTy,
    ProjectionNameMismatched(ExpectedFound<Name>),
    ProjectionBoundsLength(ExpectedFound<usize>),
    TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>),
    ExistentialMismatch(ExpectedFound<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>),
}

#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum UnconstrainedNumeric {
    UnconstrainedFloat,
    UnconstrainedInt,
    Neither,
}

/// Explains the source of a type err in a short, human readable way. This is meant to be placed
/// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
/// afterwards to present additional details, particularly when it comes to lifetime-related
/// errors.
impl<'tcx> fmt::Display for TypeError<'tcx> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::TypeError::*;
        fn report_maybe_different(f: &mut fmt::Formatter,
                                  expected: String, found: String) -> fmt::Result {
            // A naive approach to making sure that we're not reporting silly errors such as:
            // (expected closure, found closure).
            if expected == found {
                write!(f, "expected {}, found a different {}", expected, found)
            } else {
                write!(f, "expected {}, found {}", expected, found)
            }
        }

        match *self {
            CyclicTy => write!(f, "cyclic type of infinite size"),
            Mismatch => write!(f, "types differ"),
            UnsafetyMismatch(values) => {
                write!(f, "expected {} fn, found {} fn",
                       values.expected,
                       values.found)
            }
            AbiMismatch(values) => {
                write!(f, "expected {} fn, found {} fn",
                       values.expected,
                       values.found)
            }
            Mutability => write!(f, "types differ in mutability"),
            FixedArraySize(values) => {
                write!(f, "expected an array with a fixed size of {} elements, \
                           found one with {} elements",
                       values.expected,
                       values.found)
            }
            TupleSize(values) => {
                write!(f, "expected a tuple with {} elements, \
                           found one with {} elements",
                       values.expected,
                       values.found)
            }
            ArgCount => {
                write!(f, "incorrect number of function parameters")
            }
            RegionsDoesNotOutlive(..) => {
                write!(f, "lifetime mismatch")
            }
            RegionsNotSame(..) => {
                write!(f, "lifetimes are not the same")
            }
            RegionsNoOverlap(..) => {
                write!(f, "lifetimes do not intersect")
            }
            RegionsInsufficientlyPolymorphic(br, _, _) => {
                write!(f, "expected bound lifetime parameter {}, \
                           found concrete lifetime", br)
            }
            RegionsOverlyPolymorphic(br, _, _) => {
                write!(f, "expected concrete lifetime, \
                           found bound lifetime parameter {}", br)
            }
            Sorts(values) => ty::tls::with(|tcx| {
                report_maybe_different(f, values.expected.sort_string(tcx),
                                       values.found.sort_string(tcx))
            }),
            Traits(values) => ty::tls::with(|tcx| {
                report_maybe_different(f,
                                       format!("trait `{}`",
                                               tcx.item_path_str(values.expected)),
                                       format!("trait `{}`",
                                               tcx.item_path_str(values.found)))
            }),
            IntMismatch(ref values) => {
                write!(f, "expected `{:?}`, found `{:?}`",
                       values.expected,
                       values.found)
            }
            FloatMismatch(ref values) => {
                write!(f, "expected `{:?}`, found `{:?}`",
                       values.expected,
                       values.found)
            }
            VariadicMismatch(ref values) => {
                write!(f, "expected {} fn, found {} function",
                       if values.expected { "variadic" } else { "non-variadic" },
                       if values.found { "variadic" } else { "non-variadic" })
            }
            ProjectionNameMismatched(ref values) => {
                write!(f, "expected {}, found {}",
                       values.expected,
                       values.found)
            }
            ProjectionBoundsLength(ref values) => {
                write!(f, "expected {} associated type bindings, found {}",
                       values.expected,
                       values.found)
            },
            TyParamDefaultMismatch(ref values) => {
                write!(f, "conflicting type parameter defaults `{}` and `{}`",
                       values.expected.ty,
                       values.found.ty)
            }
            ExistentialMismatch(ref values) => {
                report_maybe_different(f, format!("trait `{}`", values.expected),
                                       format!("trait `{}`", values.found))
            }
        }
    }
}

impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
    pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
        match self.sty {
            ty::TyBool | ty::TyChar | ty::TyInt(_) |
            ty::TyUint(_) | ty::TyFloat(_) | ty::TyStr | ty::TyNever => self.to_string(),
            ty::TyTuple(ref tys, _) if tys.is_empty() => self.to_string(),

            ty::TyAdt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)),
            ty::TyArray(_, n) => format!("array of {} elements", n),
            ty::TySlice(_) => "slice".to_string(),
            ty::TyRawPtr(_) => "*-ptr".to_string(),
            ty::TyRef(region, tymut) => {
                let tymut_string = tymut.to_string();
                if tymut_string == "_" ||         //unknown type name,
                   tymut_string.len() > 10 ||     //name longer than saying "reference",
                   region.to_string() != ""       //... or a complex type
                {
                    match tymut {
                        ty::TypeAndMut{mutbl, ..} => {
                            format!("{}reference", match mutbl {
                                hir::Mutability::MutMutable => "mutable ",
                                _ => ""
                            })
                        }
                    }
                } else {
                    format!("&{}", tymut_string)
                }
            }
            ty::TyFnDef(..) => format!("fn item"),
            ty::TyFnPtr(_) => "fn pointer".to_string(),
            ty::TyDynamic(ref inner, ..) => {
                inner.principal().map_or_else(|| "trait".to_string(),
                    |p| format!("trait {}", tcx.item_path_str(p.def_id())))
            }
            ty::TyClosure(..) => "closure".to_string(),
            ty::TyTuple(..) => "tuple".to_string(),
            ty::TyInfer(ty::TyVar(_)) => "inferred type".to_string(),
            ty::TyInfer(ty::IntVar(_)) => "integral variable".to_string(),
            ty::TyInfer(ty::FloatVar(_)) => "floating-point variable".to_string(),
            ty::TyInfer(ty::FreshTy(_)) => "skolemized type".to_string(),
            ty::TyInfer(ty::FreshIntTy(_)) => "skolemized integral type".to_string(),
            ty::TyInfer(ty::FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
            ty::TyProjection(_) => "associated type".to_string(),
            ty::TyParam(ref p) => {
                if p.is_self() {
                    "Self".to_string()
                } else {
                    "type parameter".to_string()
                }
            }
            ty::TyAnon(..) => "anonymized type".to_string(),
            ty::TyError => "type error".to_string(),
        }
    }
}

impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
    pub fn note_and_explain_type_err(self,
                                     db: &mut DiagnosticBuilder,
                                     err: &TypeError<'tcx>,
                                     sp: Span) {
        use self::TypeError::*;

        match err.clone() {
            RegionsDoesNotOutlive(subregion, superregion) => {
                self.note_and_explain_region(db, "", subregion, "...");
                self.note_and_explain_region(db, "...does not necessarily outlive ",
                                           superregion, "");
            }
            RegionsNotSame(region1, region2) => {
                self.note_and_explain_region(db, "", region1, "...");
                self.note_and_explain_region(db, "...is not the same lifetime as ",
                                           region2, "");
            }
            RegionsNoOverlap(region1, region2) => {
                self.note_and_explain_region(db, "", region1, "...");
                self.note_and_explain_region(db, "...does not overlap ",
                                           region2, "");
            }
            RegionsInsufficientlyPolymorphic(_, conc_region, _) => {
                self.note_and_explain_region(db, "concrete lifetime that was found is ",
                                           conc_region, "");
            }
            RegionsOverlyPolymorphic(_, &ty::ReVar(_), _) => {
                // don't bother to print out the message below for
                // inference variables, it's not very illuminating.
            }
            RegionsOverlyPolymorphic(_, conc_region, _) => {
                self.note_and_explain_region(db, "expected concrete lifetime is ",
                                           conc_region, "");
            }
            Sorts(values) => {
                let expected_str = values.expected.sort_string(self);
                let found_str = values.found.sort_string(self);
                if expected_str == found_str && expected_str == "closure" {
                    db.span_note(sp,
                        "no two closures, even if identical, have the same type");
                    db.span_help(sp,
                        "consider boxing your closure and/or using it as a trait object");
                }
            },
            TyParamDefaultMismatch(values) => {
                let expected = values.expected;
                let found = values.found;
                db.span_note(sp, &format!("conflicting type parameter defaults `{}` and `{}`",
                                          expected.ty,
                                          found.ty));

                match self.hir.span_if_local(expected.def_id) {
                    Some(span) => {
                        db.span_note(span, "a default was defined here...");
                    }
                    None => {
                        let item_def_id = self.parent(expected.def_id).unwrap();
                        db.note(&format!("a default is defined on `{}`",
                                         self.item_path_str(item_def_id)));
                    }
                }

                db.span_note(
                    expected.origin_span,
                    "...that was applied to an unconstrained type variable here");

                match self.hir.span_if_local(found.def_id) {
                    Some(span) => {
                        db.span_note(span, "a second default was defined here...");
                    }
                    None => {
                        let item_def_id = self.parent(found.def_id).unwrap();
                        db.note(&format!("a second default is defined on `{}`",
                                         self.item_path_str(item_def_id)));
                    }
                }

                db.span_note(found.origin_span,
                             "...that also applies to the same type variable here");
            }
            _ => {}
        }
    }
}
<commit_msg>Avoid spurious ` ` in lifetime diagnostics<commit_after>// Copyright 2012-2015 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.

use hir::def_id::DefId;
use infer::type_variable;
use ty::{self, BoundRegion, DefIdTree, Region, Ty, TyCtxt};

use std::fmt;
use syntax::abi;
use syntax::ast::{self, Name};
use errors::DiagnosticBuilder;
use syntax_pos::Span;

use hir;

#[derive(Clone, Copy, Debug)]
pub struct ExpectedFound<T> {
    pub expected: T,
    pub found: T,
}

// Data structures used in type unification
#[derive(Clone, Debug)]
pub enum TypeError<'tcx> {
    Mismatch,
    UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
    AbiMismatch(ExpectedFound<abi::Abi>),
    Mutability,
    TupleSize(ExpectedFound<usize>),
    FixedArraySize(ExpectedFound<usize>),
    ArgCount,
    RegionsDoesNotOutlive(&'tcx Region, &'tcx Region),
    RegionsNotSame(&'tcx Region, &'tcx Region),
    RegionsNoOverlap(&'tcx Region, &'tcx Region),
    RegionsInsufficientlyPolymorphic(BoundRegion, &'tcx Region, Option<Box<ty::Issue32330>>),
    RegionsOverlyPolymorphic(BoundRegion, &'tcx Region, Option<Box<ty::Issue32330>>),
    Sorts(ExpectedFound<Ty<'tcx>>),
    IntMismatch(ExpectedFound<ty::IntVarValue>),
    FloatMismatch(ExpectedFound<ast::FloatTy>),
    Traits(ExpectedFound<DefId>),
    VariadicMismatch(ExpectedFound<bool>),
    CyclicTy,
    ProjectionNameMismatched(ExpectedFound<Name>),
    ProjectionBoundsLength(ExpectedFound<usize>),
    TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>),
    ExistentialMismatch(ExpectedFound<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>),
}

#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum UnconstrainedNumeric {
    UnconstrainedFloat,
    UnconstrainedInt,
    Neither,
}

/// Explains the source of a type err in a short, human readable way. This is meant to be placed
/// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
/// afterwards to present additional details, particularly when it comes to lifetime-related
/// errors.
impl<'tcx> fmt::Display for TypeError<'tcx> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::TypeError::*;
        fn report_maybe_different(f: &mut fmt::Formatter,
                                  expected: String, found: String) -> fmt::Result {
            // A naive approach to making sure that we're not reporting silly errors such as:
            // (expected closure, found closure).
            if expected == found {
                write!(f, "expected {}, found a different {}", expected, found)
            } else {
                write!(f, "expected {}, found {}", expected, found)
            }
        }

        match *self {
            CyclicTy => write!(f, "cyclic type of infinite size"),
            Mismatch => write!(f, "types differ"),
            UnsafetyMismatch(values) => {
                write!(f, "expected {} fn, found {} fn",
                       values.expected,
                       values.found)
            }
            AbiMismatch(values) => {
                write!(f, "expected {} fn, found {} fn",
                       values.expected,
                       values.found)
            }
            Mutability => write!(f, "types differ in mutability"),
            FixedArraySize(values) => {
                write!(f, "expected an array with a fixed size of {} elements, \
                           found one with {} elements",
                       values.expected,
                       values.found)
            }
            TupleSize(values) => {
                write!(f, "expected a tuple with {} elements, \
                           found one with {} elements",
                       values.expected,
                       values.found)
            }
            ArgCount => {
                write!(f, "incorrect number of function parameters")
            }
            RegionsDoesNotOutlive(..) => {
                write!(f, "lifetime mismatch")
            }
            RegionsNotSame(..) => {
                write!(f, "lifetimes are not the same")
            }
            RegionsNoOverlap(..) => {
                write!(f, "lifetimes do not intersect")
            }
            RegionsInsufficientlyPolymorphic(br, _, _) => {
                write!(f,
                       "expected bound lifetime parameter{}{}, found concrete lifetime",
                       if br.is_named() { " " } else { "" },
                       br)
            }
            RegionsOverlyPolymorphic(br, _, _) => {
                write!(f,
                       "expected concrete lifetime, found bound lifetime parameter{}{}",
                       if br.is_named() { " " } else { "" },
                       br)
            }
            Sorts(values) => ty::tls::with(|tcx| {
                report_maybe_different(f, values.expected.sort_string(tcx),
                                       values.found.sort_string(tcx))
            }),
            Traits(values) => ty::tls::with(|tcx| {
                report_maybe_different(f,
                                       format!("trait `{}`",
                                               tcx.item_path_str(values.expected)),
                                       format!("trait `{}`",
                                               tcx.item_path_str(values.found)))
            }),
            IntMismatch(ref values) => {
                write!(f, "expected `{:?}`, found `{:?}`",
                       values.expected,
                       values.found)
            }
            FloatMismatch(ref values) => {
                write!(f, "expected `{:?}`, found `{:?}`",
                       values.expected,
                       values.found)
            }
            VariadicMismatch(ref values) => {
                write!(f, "expected {} fn, found {} function",
                       if values.expected { "variadic" } else { "non-variadic" },
                       if values.found { "variadic" } else { "non-variadic" })
            }
            ProjectionNameMismatched(ref values) => {
                write!(f, "expected {}, found {}",
                       values.expected,
                       values.found)
            }
            ProjectionBoundsLength(ref values) => {
                write!(f, "expected {} associated type bindings, found {}",
                       values.expected,
                       values.found)
            },
            TyParamDefaultMismatch(ref values) => {
                write!(f, "conflicting type parameter defaults `{}` and `{}`",
                       values.expected.ty,
                       values.found.ty)
            }
            ExistentialMismatch(ref values) => {
                report_maybe_different(f, format!("trait `{}`", values.expected),
                                       format!("trait `{}`", values.found))
            }
        }
    }
}

impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
    pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
        match self.sty {
            ty::TyBool | ty::TyChar | ty::TyInt(_) |
            ty::TyUint(_) | ty::TyFloat(_) | ty::TyStr | ty::TyNever => self.to_string(),
            ty::TyTuple(ref tys, _) if tys.is_empty() => self.to_string(),

            ty::TyAdt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)),
            ty::TyArray(_, n) => format!("array of {} elements", n),
            ty::TySlice(_) => "slice".to_string(),
            ty::TyRawPtr(_) => "*-ptr".to_string(),
            ty::TyRef(region, tymut) => {
                let tymut_string = tymut.to_string();
                if tymut_string == "_" ||         //unknown type name,
                   tymut_string.len() > 10 ||     //name longer than saying "reference",
                   region.to_string() != ""       //... or a complex type
                {
                    match tymut {
                        ty::TypeAndMut{mutbl, ..} => {
                            format!("{}reference", match mutbl {
                                hir::Mutability::MutMutable => "mutable ",
                                _ => ""
                            })
                        }
                    }
                } else {
                    format!("&{}", tymut_string)
                }
            }
            ty::TyFnDef(..) => format!("fn item"),
            ty::TyFnPtr(_) => "fn pointer".to_string(),
            ty::TyDynamic(ref inner, ..) => {
                inner.principal().map_or_else(|| "trait".to_string(),
                    |p| format!("trait {}", tcx.item_path_str(p.def_id())))
            }
            ty::TyClosure(..) => "closure".to_string(),
            ty::TyTuple(..) => "tuple".to_string(),
            ty::TyInfer(ty::TyVar(_)) => "inferred type".to_string(),
            ty::TyInfer(ty::IntVar(_)) => "integral variable".to_string(),
            ty::TyInfer(ty::FloatVar(_)) => "floating-point variable".to_string(),
            ty::TyInfer(ty::FreshTy(_)) => "skolemized type".to_string(),
            ty::TyInfer(ty::FreshIntTy(_)) => "skolemized integral type".to_string(),
            ty::TyInfer(ty::FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
            ty::TyProjection(_) => "associated type".to_string(),
            ty::TyParam(ref p) => {
                if p.is_self() {
                    "Self".to_string()
                } else {
                    "type parameter".to_string()
                }
            }
            ty::TyAnon(..) => "anonymized type".to_string(),
            ty::TyError => "type error".to_string(),
        }
    }
}

impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
    pub fn note_and_explain_type_err(self,
                                     db: &mut DiagnosticBuilder,
                                     err: &TypeError<'tcx>,
                                     sp: Span) {
        use self::TypeError::*;

        match err.clone() {
            RegionsDoesNotOutlive(subregion, superregion) => {
                self.note_and_explain_region(db, "", subregion, "...");
                self.note_and_explain_region(db, "...does not necessarily outlive ",
                                           superregion, "");
            }
            RegionsNotSame(region1, region2) => {
                self.note_and_explain_region(db, "", region1, "...");
                self.note_and_explain_region(db, "...is not the same lifetime as ",
                                           region2, "");
            }
            RegionsNoOverlap(region1, region2) => {
                self.note_and_explain_region(db, "", region1, "...");
                self.note_and_explain_region(db, "...does not overlap ",
                                           region2, "");
            }
            RegionsInsufficientlyPolymorphic(_, conc_region, _) => {
                self.note_and_explain_region(db, "concrete lifetime that was found is ",
                                           conc_region, "");
            }
            RegionsOverlyPolymorphic(_, &ty::ReVar(_), _) => {
                // don't bother to print out the message below for
                // inference variables, it's not very illuminating.
            }
            RegionsOverlyPolymorphic(_, conc_region, _) => {
                self.note_and_explain_region(db, "expected concrete lifetime is ",
                                           conc_region, "");
            }
            Sorts(values) => {
                let expected_str = values.expected.sort_string(self);
                let found_str = values.found.sort_string(self);
                if expected_str == found_str && expected_str == "closure" {
                    db.span_note(sp,
                        "no two closures, even if identical, have the same type");
                    db.span_help(sp,
                        "consider boxing your closure and/or using it as a trait object");
                }
            },
            TyParamDefaultMismatch(values) => {
                let expected = values.expected;
                let found = values.found;
                db.span_note(sp, &format!("conflicting type parameter defaults `{}` and `{}`",
                                          expected.ty,
                                          found.ty));

                match self.hir.span_if_local(expected.def_id) {
                    Some(span) => {
                        db.span_note(span, "a default was defined here...");
                    }
                    None => {
                        let item_def_id = self.parent(expected.def_id).unwrap();
                        db.note(&format!("a default is defined on `{}`",
                                         self.item_path_str(item_def_id)));
                    }
                }

                db.span_note(
                    expected.origin_span,
                    "...that was applied to an unconstrained type variable here");

                match self.hir.span_if_local(found.def_id) {
                    Some(span) => {
                        db.span_note(span, "a second default was defined here...");
                    }
                    None => {
                        let item_def_id = self.parent(found.def_id).unwrap();
                        db.note(&format!("a second default is defined on `{}`",
                                         self.item_path_str(item_def_id)));
                    }
                }

                db.span_note(found.origin_span,
                             "...that also applies to the same type variable here");
            }
            _ => {}
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before>import core::*;

use std;
import std::list;
import std::list::head;
import std::list::tail;
import std::list::from_vec;
import option;

#[test]
fn test_from_vec() {
    let l = from_vec([0, 1, 2]);
    assert (head(l) == 0);
    assert (head(tail(l)) == 1);
    assert (head(tail(tail(l))) == 2);
}

#[test]
fn test_from_vec_mut() {
    let l = from_vec([mutable 0, 1, 2]);
    assert (head(l) == 0);
    assert (head(tail(l)) == 1);
    assert (head(tail(tail(l))) == 2);
}

#[test]
fn test_foldl() {
    let l = from_vec([0, 1, 2, 3, 4]);
    fn add(&&a: uint, &&b: int) -> uint { ret a + (b as uint); }
    let rs = list::foldl(l, 0u, add);
    assert (rs == 10u);
}

#[test]
fn test_foldl2() {
    fn sub(&&a: int, &&b: int) -> int {
        a - b
    }
    let l = from_vec([1, 2, 3, 4]);
    let sum = list::foldl(l, 0, sub);
    assert sum == -10;
}

#[test]
fn test_find_success() {
    let l = from_vec([0, 1, 2]);
    fn match(&&i: int) -> option::t<int> {
        ret if i == 2 { option::some(i) } else { option::none::<int> };
    }
    let rs = list::find(l, match);
    assert (rs == option::some(2));
}

#[test]
fn test_find_fail() {
    let l = from_vec([0, 1, 2]);
    fn match(&&_i: int) -> option::t<int> { ret option::none::<int>; }
    let rs = list::find(l, match);
    assert (rs == option::none::<int>);
}

#[test]
fn test_has() {
    let l = from_vec([5, 8, 6]);
    let empty = list::nil::<int>;
    assert (list::has(l, 5));
    assert (!list::has(l, 7));
    assert (list::has(l, 8));
    assert (!list::has(empty, 5));
}

#[test]
fn test_len() {
    let l = from_vec([0, 1, 2]);
    assert (list::len(l) == 3u);
}

<commit_msg>tests: add corner case (empty list)<commit_after>import core::*;

use std;
import std::list;
import std::list::head;
import std::list::tail;
import std::list::from_vec;
import option;

#[test]
fn test_from_vec() {
    let l = from_vec([0, 1, 2]);
    assert (head(l) == 0);
    assert (head(tail(l)) == 1);
    assert (head(tail(tail(l))) == 2);
}

#[test]
fn test_from_vec_empty() {
    let empty : list::list<int> = from_vec([]);
    assert (empty == list::nil::<int>);
}

#[test]
fn test_from_vec_mut() {
    let l = from_vec([mutable 0, 1, 2]);
    assert (head(l) == 0);
    assert (head(tail(l)) == 1);
    assert (head(tail(tail(l))) == 2);
}

#[test]
fn test_foldl() {
    fn add(&&a: uint, &&b: int) -> uint { ret a + (b as uint); }
    let l = from_vec([0, 1, 2, 3, 4]);
    let empty = list::nil::<int>;
    assert (list::foldl(l, 0u, add) == 10u);
    assert (list::foldl(empty, 0u, add) == 0u);
}

#[test]
fn test_foldl2() {
    fn sub(&&a: int, &&b: int) -> int {
        a - b
    }
    let l = from_vec([1, 2, 3, 4]);
    assert (list::foldl(l, 0, sub) == -10);
}

#[test]
fn test_find_success() {
    fn match(&&i: int) -> option::t<int> {
        ret if i == 2 { option::some(i) } else { option::none::<int> };
    }
    let l = from_vec([0, 1, 2]);
    assert (list::find(l, match) == option::some(2));
}

#[test]
fn test_find_fail() {
    fn match(&&_i: int) -> option::t<int> { ret option::none::<int>; }
    let l = from_vec([0, 1, 2]);
    let empty = list::nil::<int>;
    assert (list::find(l, match) == option::none::<int>);
    assert (list::find(empty, match) == option::none::<int>);
}

#[test]
fn test_has() {
    let l = from_vec([5, 8, 6]);
    let empty = list::nil::<int>;
    assert (list::has(l, 5));
    assert (!list::has(l, 7));
    assert (list::has(l, 8));
    assert (!list::has(empty, 5));
}

#[test]
fn test_len() {
    let l = from_vec([0, 1, 2]);
    let empty = list::nil::<int>;
    assert (list::len(l) == 3u);
    assert (list::len(empty) == 0u);
}

<|endoftext|>


<commit_before><commit_msg>Add test for issue-70944<commit_after>// check-pass
// Regression test of #70944, should compile fine.

use std::ops::Index;

pub struct KeyA;
pub struct KeyB;
pub struct KeyC;

pub trait Foo: Index<KeyA> + Index<KeyB> + Index<KeyC> {}
pub trait FooBuilder {
    type Inner: Foo;
    fn inner(&self) -> &Self::Inner;
}

pub fn do_stuff(foo: &impl FooBuilder) {
    let inner = foo.inner();
    &inner[KeyA];
    &inner[KeyB];
    &inner[KeyC];
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add test of tuple nested indexing<commit_after>// run-pass

fn main () {
    let n = (1, (2, 3)).1.1;
    assert_eq!(n, 3);
}
<|endoftext|>


<commit_before><commit_msg>syntax: Don't add an extra space before the last comma...<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify doc comments by merely stating the wrapped low-level function.<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #9646 - ehuss:windows-case-disable, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>Tokenization is more respective of the contents of quotation marks.<commit_after><|endoftext|>


<commit_before><commit_msg>Some updates<commit_after><|endoftext|>


<commit_before><commit_msg>Increased trigger level to 2500 mV.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed issue where zmq::sendmore was being used rather than an end of message.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed issue where start / stop would sometimes fire more than once causing errant triggers.<commit_after><|endoftext|>


<commit_before><commit_msg>And of course I forgot to add the midi.rs<commit_after>//*****************************
// Output to MELO format

extern crate classreader;

use codecity::{MeasureMeta, MusicMeta};
use midi_file::MidiFile;
use midi_file::core::{GeneralMidi, DurationName, Clocks, Velocity, NoteNumber, Channel};
use midi_file::file::{Track, QuartersPerMinute};
use std::fs::File;
use std::io::prelude::*;

const TONES: &'static [NoteNumber] = &[
    NoteNumber::new(72),
    NoteNumber::new(74),
    NoteNumber::new(76),
    NoteNumber::new(78),
    NoteNumber::new(80),
    NoteNumber::new(82),
    NoteNumber::new(84),
    NoteNumber::new(86),
    NoteNumber::new(88),
    NoteNumber::new(90),
    NoteNumber::new(92),
    NoteNumber::new(94),
    NoteNumber::new(96),
    NoteNumber::new(98),
    NoteNumber::new(100),
    NoteNumber::new(102),
    NoteNumber::new(104),
    NoteNumber::new(106),
    NoteNumber::new(108),
];

// durations
const QUARTER: u32 = 1024;
const EIGHTH: u32 = QUARTER / 2;
const DOTTED_QUARTER: u32 = QUARTER + EIGHTH;

// pitches
const C4: NoteNumber = NoteNumber::new(72);
const D4: NoteNumber = NoteNumber::new(74);
const E4: NoteNumber = NoteNumber::new(76);

// some arbitrary velocity
const V: Velocity = Velocity::new(64);

// channel zero (displayed as channel 1 in any sequencer UI)
const CH: Channel = Channel::new(0);

pub fn write_to_file(path: &String, music: &Vec<MusicMeta>) {
    let mut mfile = MidiFile::new();

    // set up track metadata
    let mut track = Track::default();
    track.set_name("Singer").unwrap();
    track.set_instrument_name("Alto").unwrap();
    track.set_general_midi(CH, GeneralMidi::SynthVoice).unwrap();

    // set time signature and tempo
    track
        .push_time_signature(0, 6, DurationName::Eighth, Clocks::DottedQuarter)
        .unwrap();
    track.push_tempo(0, QuartersPerMinute::new(116)).unwrap();

    for c in music {
        for m in c.methods() {
            render_chord(&mut track, m, 0);
        }
    }

    // finish and write the file ///////////////////////////////////////////////////////////////////

    // add the track to the file
    mfile.push_track(track).unwrap();

    mfile.save(path).unwrap();
}

fn render_chord(track: &mut Track, m: &MeasureMeta, finger: u16) {
    let tone_count = get_tone_count(m.lines);
    let base = get_base(m.size);
    if tone_count > 0 {
        let note = get_tone(base, m.complexity, finger);
        track.push_lyric(0, format!("{}\n", m.name)).unwrap();
        track.push_note_on(0, CH, note, V).unwrap();
        // the note-off event determines the duration of the note
        track
            .push_note_off(EIGHTH, CH, note, Velocity::default())
            .unwrap();

    }
}

fn get_tone_count(c: u16) -> u16 {
    match c / 8 {
        0..=8 => c / 8,
        _ => 8,
    }
}

fn get_base(c: usize) -> usize {
    match c / 2 {
        0..=10 => c,
        11..=20 => 10 + (c - 10) / 2,
        21..=40 => 15 + (c - 20) / 4,
        41..=80 => 20 + (c - 40) / 8,
        81..=160 => 30 + (c - 80) / 16,
        _ => 18,
    }
}

fn get_complexity_shift(complexity: u16) -> u16 {
    match complexity {
        0..=2 => 2,
        3..=4 => 3,
        _ => 4,
    }
}

fn get_tone(base: usize, complexity: u16, offset: u16) -> NoteNumber {
    let i = base as u16 + (offset % get_complexity_shift(complexity));
    TONES[(i % 19) as usize]
}

//*****************************
// Unit tests
<|endoftext|>


<commit_before><commit_msg>test: Add a test case that ensures `ret &EXPR` works.<commit_after>fn f(x : &a.int) -> &a.int {
    ret &*x;
}

fn main() {
    log(error, #fmt("%d", *f(&3)));
}

<|endoftext|>


<commit_before><commit_msg>Add problem #7<commit_after>use std;

fn isqrt(n: u64) -> u64 {
    let (min, max) = (0u64, n);
    while min < max {
        let mid = (min + max + 1u64) / 2u64;
        if (mid * mid) == n {
            ret mid;
        } else if (mid * mid) >= n {
            max = mid - 1u64;
        } else {
            min = mid;
        }
    }
    ret min;
}

fn gen_prime(&primes: [u64]) {
    let num = alt vec::last(primes) {
      none       { primes =  [2u64]; ret }
      some(2u64) { primes += [3u64]; ret }
      some(x)    { x + 2u64 }
    };
    while true {
        for p in primes {
            if p * p > num {
                primes += [num];
                ret;
            }
            if num % p == 0u64 {
                break;
            }
        }
        num += 2u64;
    }
    fail;
}

fn main() {
    let idx = 10000u64;
    let primes = [];
    uint::range(0u64, idx + 1u64) { |num|
        gen_prime(primes);
    }
    std::io::println(#fmt("%u", primes[idx]));
}<|endoftext|>


<commit_before><commit_msg>add test for repr(128) enum derives<commit_after>// run-pass
#![feature(repr128, arbitrary_enum_discriminant)]

#[derive(PartialEq, Debug)]
#[repr(i128)]
enum Test {
    A(Box<u64>) = 0,
    B(usize) = u64::max_value() as i128 + 1,
}

fn main() {
    assert_ne!(Test::A(Box::new(2)), Test::B(0));
    // This previously caused a segfault.
    //
    // See https://github.com/rust-lang/rust/issues/70509#issuecomment-620654186
    // for a detailed explanation.
}
<|endoftext|>


<commit_before><commit_msg>Clear the buffer in quick_xml loop<commit_after><|endoftext|>


<commit_before><commit_msg>Unnecessary `should_sign_message` unittest<commit_after><|endoftext|>


<commit_before><commit_msg>Add multi-threaded version of mandelbrot<commit_after>use std::sync::{Arc, Mutex};
use std::thread;

const MIN_X: f32 = -2.0;
const MAX_X: f32 = 0.5;
const MIN_Y: f32 = -1.25;
const MAX_Y: f32 = 1.25;
const WIDTH: i32 = 4000;
const HEIGHT: i32 = 4000;
const MAX_ITER: i32 = 255;

fn main() {
	let mut lookup: Vec<u8> = Vec::with_capacity((MAX_ITER + 1) as usize);
	build_table_colors(&mut lookup);
	let lookup = Arc::new(lookup);

	let length = (WIDTH * HEIGHT) as usize;
	let mut image_output: Vec<u8> = Vec::with_capacity(length);
	unsafe { image_output.set_len(length) };
	let image_output = Arc::new(Mutex::new(image_output));

	let counter = Arc::new(Mutex::new(0));

	let mut thread_pool = Vec::with_capacity(8);
	for i in 0..8 {
		let counter = counter.clone();
		let lookup = lookup.clone();
		let image_output = image_output.clone();
		let t = thread::spawn(move || {
			let mut done = false;
			while !done {
				let local_counter = {
					let mut counter = counter.lock().unwrap();
					*counter += 1;
					*counter - 1
				};

				let x_pixel: i32 = local_counter % WIDTH;
				let y_pixel: i32 = local_counter / WIDTH;

				if y_pixel >= WIDTH {
					done = true;
				} else {
					let x0: f32 = pixels_to_complexes_x(x_pixel);
					let y0: f32 = pixels_to_complexes_y(y_pixel);

					let mut iterations: i32 = 0;

					let mut x: f32 = 0.; let mut y: f32 = 0.;
					let mut x_square: f32 = 0.; let mut y_square: f32 = 0.;

					while x_square + y_square <= 4. && iterations < MAX_ITER {
						y = 2.0 * x * y + y0;
						x = x_square - y_square + x0;

						x_square = x * x;
						y_square = y * y;

						iterations += 1;
					}
					{
						let mut image_output = image_output.lock().unwrap();
						image_output[local_counter as usize] = lookup[iterations as usize];
					}
				}
			}
		});
		thread_pool.push(t);
	}

	for i in thread_pool {
		match i.join() {
		 	Ok(_) => println!("Thread terminated"),
		 	Err(_) => println!("Thread aborted"),
		 }
	}
}

fn pixels_to_complexes_x(x: i32) -> f32 {
	// Maps pixel 0 -> MIN_X; pixel WIDTH - 1 -> MAX_X
	(MAX_X - MIN_X) / (WIDTH - 1) as f32 * x as f32 + MIN_X
}

fn pixels_to_complexes_y(y: i32) -> f32 {
	// Maps pixel 0 -> MAX_Y; pixel HEIGHT - 1 -> MIN_Y
	(MIN_Y - MAX_Y) / (HEIGHT - 1) as f32 * y as f32 + MAX_Y
}

fn pick_color(iteration: i32) -> u8 {
	(255. / ((MAX_ITER - 2) * (iteration - 1)) as f32).round() as u8
}

fn build_table_colors(table: &mut Vec<u8>) {
	table.push(0);
	for i in 1..MAX_ITER {
		table.push(pick_color(i));
	}
	table.push(0);
}<|endoftext|>


<commit_before><commit_msg>Create textures immediately before compositing<commit_after><|endoftext|>


<commit_before><commit_msg>Move box fragment hit testing to a dedicated display item<commit_after><|endoftext|>


<commit_before><commit_msg>Faster CapR algorithm using base conversion of logarithm<commit_after><|endoftext|>


<commit_before><commit_msg>Some update has been done.<commit_after><|endoftext|>


<commit_before><commit_msg>stub for ui (game loop)<commit_after>use std::io::{self, Write};

use super::board;

pub fn game_loop(board: Board) {
    // keep track of score, status, etc.
    loop {
        // read in user input (if any)
        // use that to rotate or move the piece as needed
        // on each loop (clock tick), move the pieces downward
        // update Score if necessary
        // update game status (won or lost) if necessary

        let mut buf = String::new();
        match io::stdin().read_line(&mut buf) {
            Err(err) => {
                panic!("error: {}", err);
            }
            Ok(0) => {
                break;
            }
            Ok(_) => {
                // HANDLE INPUT
            }
        }
    }
    // when loop is broken, display user score / game over message
}
<|endoftext|>


<commit_before><commit_msg>Add a basic example<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

extern crate js;
extern crate libc;

use std::ffi::CStr;
use std::ptr;
use std::str;

use js::{JSCLASS_RESERVED_SLOTS_MASK,JSCLASS_RESERVED_SLOTS_SHIFT,JSCLASS_GLOBAL_SLOT_COUNT,JSCLASS_IS_GLOBAL};
use js::jsapi::_Z24JS_GlobalObjectTraceHookP8JSTracerP8JSObject;
use js::jsapi::{CallArgs,CompartmentOptions,OnNewGlobalHookOption,Rooted,Value};
use js::jsapi::{JS_DefineFunction,JS_Init,JS_NewGlobalObject,JS_EncodeStringToUTF8,JS_ReportError};
use js::jsapi::{JSAutoCompartment,JSAutoRequest,JSContext,JSClass};
use js::jsval::UndefinedValue;
use js::rust::Runtime;

static CLASS: &'static JSClass = &JSClass {
    name: b"test\0" as *const u8 as *const libc::c_char,
    flags: JSCLASS_IS_GLOBAL | ((JSCLASS_GLOBAL_SLOT_COUNT & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT),
    addProperty: None,
    delProperty: None,
    getProperty: None,
    setProperty: None,
    enumerate: None,
    resolve: None,
    convert: None,
    finalize: None,
    call: None,
    hasInstance: None,
    construct: None,
    trace: Some(_Z24JS_GlobalObjectTraceHookP8JSTracerP8JSObject),
    reserved: [0 as *mut _; 25]
};

fn main() {
    unsafe {
        JS_Init();
    }
    let runtime = Runtime::new();
    let context = runtime.cx();

    unsafe {
        let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook;
        let c_option = CompartmentOptions::default();
        let _ar = JSAutoRequest::new(context);
        let global = JS_NewGlobalObject(context, CLASS, ptr::null_mut(), h_option, &c_option);
        let global_root = Rooted::new(context, global);
        let global = global_root.handle();
        let _ac = JSAutoCompartment::new(context, global.get());
        JS_DefineFunction(context, global, b"puts\0".as_ptr() as *const libc::c_char, Some(puts), 1, 0);
        let javascript = "puts('Test Iñtërnâtiônàlizætiøn ┬─┬ノ( º _ ºノ) ');".to_string();
        let _ = runtime.evaluate_script(global, javascript, "test.js".to_string(), 0);
    }
}

unsafe extern "C" fn puts(context: *mut JSContext, argc: u32, vp: *mut Value) -> u8 {
    let args = CallArgs::from_vp(vp, argc);

    if args.argc_ != 1 {
        JS_ReportError(context, b"puts() requires exactly 1 argument\0".as_ptr() as *const libc::c_char);
        return 0;
    }

    let arg = args.get(0);
    let js = js::rust::ToString(context, arg);
    let message_root = Rooted::new(context, js);
    let message = JS_EncodeStringToUTF8(context, message_root.handle());
    let message = CStr::from_ptr(message);
    println!("{}", str::from_utf8(message.to_bytes()).unwrap());

    args.rval().set(UndefinedValue());
    return 1;
}
<|endoftext|>


<commit_before><commit_msg>add whitespace-aware example parser using >><commit_after>use pom::parser::*;

#[derive(Clone, Debug, PartialEq)]
struct Container {
	containers: Vec<Container>,
	contents: Vec<String>,
}

enum TmpContainerOrContent {
	Container(Container),
	Content(String),
}

fn whitespace<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t\r\n").repeat(0..).discard()
}

fn linebreak<'a>() -> Parser<'a, u8, ()> {
	sym(b'\r').opt() * sym(b'\n').discard()
}

fn indented<'a>() -> Parser<'a, u8, Vec<u8>> {
	sym(b'\t') * none_of(b"\n\r").repeat(1..) - linebreak()
}

fn empty<'a>() -> Parser<'a, u8, ()> {
	one_of(b" \t").repeat(0..).discard() - linebreak()
}

fn content<'a>() -> Parser<'a, u8, String> {
	none_of(b" \t\r\n").repeat(1..).convert(String::from_utf8) - linebreak()
}

fn subcontainer<'a>() -> Parser<'a, u8, (Vec<Container>, Vec<String>)> {
	(
		call(container).map(|ctr| TmpContainerOrContent::Container(ctr)) |
		content().map(|ctn| TmpContainerOrContent::Content(ctn))
	).repeat(1..).map(
		|tmp| {
			tmp.into_iter().fold(
				(vec![], vec![]),
				|acc, x| match x {
					TmpContainerOrContent::Container(ct) => (
						acc.0.into_iter().chain(vec![ct].into_iter()).collect(),
						acc.1,
					),
					TmpContainerOrContent::Content(cn) => (
						acc.0,
						acc.1.into_iter().chain(vec![cn].into_iter()).collect(),
					),
				}
			)
		}
	)
}

fn container<'a>() -> Parser<'a, u8, Container> {
	let parser = seq(b"Container\n") *
	(
		indented() |
		empty().map(|()| vec![])
	).repeat(1..).map(
		|lines| lines.into_iter().filter(
			|line| line.len() > 0
		).fold(
			vec![],
			|accum, line| accum.into_iter().chain(
				line.into_iter().chain(vec![b'\n'].into_iter())
			).collect()
		)
	);

	parser >> |deden| {
		let (ctr, ctn) = subcontainer().parse(&deden).expect("subcont");

		take(0).map(move |v| (v, ctr.clone(), ctn.clone()))
	}.map(|(_l, containers, contents)| Container { containers, contents })
}

fn mylang<'a>() -> Parser<'a, u8, Vec<Container>> {
	(
		whitespace() *
		list(
			call(container),
			whitespace()
		)
	)
}

fn main() -> Result<(), ()> {
	let input = br#"
Container
	Container
		a
		b
		c

	1
	2
	3

	Container
		q

Container
	foo
	bar

	Container
		baz
		quux
		"#;

	assert_eq!(
		mylang().parse(input),
		Ok(
			vec![
				Container {
					containers: vec![
						Container {
							containers: vec![],
							contents: vec![
								"a".into(),
								"b".into(),
								"c".into(),
							]
						},
						Container {
							containers: vec![],
							contents: vec![
								"q".into(),
							]
						}
					],
					contents: vec![
						"1".into(),
						"2".into(),
						"3".into(),
					]
				},
				Container {
					containers: vec![
						Container {
							contents: vec![
								"baz".into(),
								"quux".into(),
							],
							containers: vec![],
						},
					],
					contents: vec![
						"foo".into(),
						"bar".into(),
					]
				},
			]
		)
	);

	Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Add doc comments on `Dice`<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed empty Response Bug<commit_after><|endoftext|>


<commit_before><commit_msg>Invalid source code formatting Fixed<commit_after><|endoftext|>


<commit_before><commit_msg>Buffering mz dimension to output to file (for diagnostics).<commit_after><|endoftext|>


<commit_before><commit_msg>First import.. just hello message<commit_after>
fn main() {
    println!("hello");
}
<|endoftext|>


<commit_before><commit_msg>Added verbose flag<commit_after><|endoftext|>


<commit_before><commit_msg>advance world automatically<commit_after><|endoftext|>


<commit_before><commit_msg>Added new empty function to return empty encode result struct. Updated encoding method to make use of sparse BTreeMap datastructure.<commit_after><|endoftext|>


<commit_before><commit_msg>add CodePipeline integration tests<commit_after>#![cfg(feature = "codepipeline")]

extern crate rusoto;

use rusoto::codepipeline::{CodePipelineClient, ListPipelinesInput};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn should_list_pipelines() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = CodePipelineClient::new(credentials, Region::UsEast1);

    let request = ListPipelinesInput::default();

    match client.list_pipelines(&request) {
    	Ok(response) => {
    		println!("{:#?}", response);
    		assert!(true)
    	},
    	Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
<|endoftext|>


<commit_before><commit_msg>tests: Add tests related to #706<commit_after>extern crate clap;

use std::str;

use clap::{App, Arg, SubCommand, AppSettings};

fn condense_whitespace(s: &str) -> String {
    s.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn normalize(s: &str) -> Vec<String> {
    s.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).map(condense_whitespace).collect()
}

fn get_help(app: App, args: &[&'static str]) -> Vec<String> {
    let res = app.get_matches_from_safe(args.iter().chain(["--help"].iter()));
    normalize(&*res.unwrap_err().message)
}

#[test]
fn no_derive_order() {
    let app = App::new("test")
        .args(&[
            Arg::with_name("flag_b").long("flag_b").help("first flag"),
            Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
            Arg::with_name("flag_a").long("flag_a").help("second flag"),
            Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
        ]);

    assert_eq!(get_help(app, &["test"]), normalize("
        test

        USAGE:
            test [FLAGS] [OPTIONS]

        FLAGS:
                --flag_a     second flag
                --flag_b     first flag
            -h, --help       Prints help information
            -V, --version    Prints version information

        OPTIONS:
                --option_a <option_a>    second option
                --option_b <option_b>    first option
    "));
}

#[test]
fn derive_order() {
    let app = App::new("test")
        .setting(AppSettings::DeriveDisplayOrder)
        .args(&[
            Arg::with_name("flag_b").long("flag_b").help("first flag"),
            Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
            Arg::with_name("flag_a").long("flag_a").help("second flag"),
            Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
        ]);

    assert_eq!(get_help(app, &["test"]), normalize("
        test

        USAGE:
            test [FLAGS] [OPTIONS]

        FLAGS:
                --flag_b     first flag
                --flag_a     second flag
            -h, --help       Prints help information
            -V, --version    Prints version information

        OPTIONS:
                --option_b <option_b>    first option
                --option_a <option_a>    second option
    "));
}

#[test]
fn unified_help() {
    let app = App::new("test")
        .setting(AppSettings::UnifiedHelpMessage)
        .args(&[
            Arg::with_name("flag_b").long("flag_b").help("first flag"),
            Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
            Arg::with_name("flag_a").long("flag_a").help("second flag"),
            Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
        ]);

    assert_eq!(get_help(app, &["test"]), normalize("
        test

        USAGE:
            test [OPTIONS]

        OPTIONS:
                --flag_a     second flag
                --flag_b     first flag
            -h, --help       Prints help information
                --option_a <option_a>    second option
                --option_b <option_b>    first option
            -V, --version    Prints version information
    "));
}

#[test]
fn unified_help_and_derive_order() {
    let app = App::new("test")
        .setting(AppSettings::DeriveDisplayOrder)
        .setting(AppSettings::UnifiedHelpMessage)
        .args(&[
            Arg::with_name("flag_b").long("flag_b").help("first flag"),
            Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
            Arg::with_name("flag_a").long("flag_a").help("second flag"),
            Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
        ]);

    assert_eq!(get_help(app, &["test"]), normalize("
        test

        USAGE:
            test [OPTIONS]

        OPTIONS:
                --flag_b     first flag
                --option_b <option_b>    first option
                --flag_a     second flag
                --option_a <option_a>    second option
            -h, --help       Prints help information
            -V, --version    Prints version information
    "));
}

#[test]
fn derive_order_subcommand_propagate() {
    let app = App::new("test")
        .global_setting(AppSettings::DeriveDisplayOrder)
        .subcommand(SubCommand::with_name("sub")
            .args(&[
                Arg::with_name("flag_b").long("flag_b").help("first flag"),
                Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
                Arg::with_name("flag_a").long("flag_a").help("second flag"),
                Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
            ]));

    assert_eq!(get_help(app, &["test", "sub"]), normalize("
        test-sub

        USAGE:
            test sub [FLAGS] [OPTIONS]

        FLAGS:
                --flag_b     first flag
                --flag_a     second flag
            -h, --help       Prints help information
            -V, --version    Prints version information

        OPTIONS:
                --option_b <option_b>    first option
                --option_a <option_a>    second option
    "));
}

#[test]
fn unified_help_subcommand_propagate() {
    let app = App::new("test")
        .global_setting(AppSettings::UnifiedHelpMessage)
        .subcommand(SubCommand::with_name("sub")
            .args(&[
                Arg::with_name("flag_b").long("flag_b").help("first flag"),
                Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
                Arg::with_name("flag_a").long("flag_a").help("second flag"),
                Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
            ]));

    assert_eq!(get_help(app, &["test", "sub"]), normalize("
        test-sub

        USAGE:
            test sub [OPTIONS]

        OPTIONS:
                --flag_a     second flag
                --flag_b     first flag
            -h, --help       Prints help information
                --option_a <option_a>    second option
                --option_b <option_b>    first option
            -V, --version    Prints version information

    "));
}

#[test]
fn unified_help_and_derive_order_subcommand_propagate() {
    let app = App::new("test")
        .global_setting(AppSettings::DeriveDisplayOrder)
        .global_setting(AppSettings::UnifiedHelpMessage)
        .subcommand(SubCommand::with_name("sub")
            .args(&[
                Arg::with_name("flag_b").long("flag_b").help("first flag"),
                Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
                Arg::with_name("flag_a").long("flag_a").help("second flag"),
                Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
            ]));

    assert_eq!(get_help(app, &["test", "sub"]), normalize("
        test-sub

        USAGE:
            test sub [OPTIONS]

        OPTIONS:
                --flag_b     first flag
                --option_b <option_b>    first option
                --flag_a     second flag
                --option_a <option_a>    second option
            -h, --help       Prints help information
            -V, --version    Prints version information

    "));
}

#[test]
fn unified_help_and_derive_order_subcommand_propagate_with_explicit_display_order() {
    let app = App::new("test")
        .global_setting(AppSettings::DeriveDisplayOrder)
        .global_setting(AppSettings::UnifiedHelpMessage)
        .subcommand(SubCommand::with_name("sub")
            .args(&[
                Arg::with_name("flag_b").long("flag_b").help("first flag"),
                Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"),
                Arg::with_name("flag_a").long("flag_a").help("second flag").display_order(0),
                Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"),
            ]));

    assert_eq!(get_help(app, &["test", "sub"]), normalize("
        test-sub

        USAGE:
            test sub [OPTIONS]

        OPTIONS:
                --flag_a     second flag
                --flag_b     first flag
                --option_b <option_b>    first option
                --option_a <option_a>    second option
            -h, --help       Prints help information
            -V, --version    Prints version information

    "));
}
<|endoftext|>


<commit_before><commit_msg>Test for #1374<commit_after>// xfail-win32
fn adder(+x: @int, +y: @int) -> int { ret *x + *y; }
fn failer() -> @int { fail; }
fn main() {
    assert(result::failure(task::try {||
        adder(@2, failer()); ()
    }));
}

<|endoftext|>


<commit_before><commit_msg>Emit warning about disabled session keys.<commit_after><|endoftext|>


<commit_before><commit_msg>Drafting for AST-transformation API.<commit_after><|endoftext|>


<commit_before><commit_msg>experiment with rust structs and default derivations<commit_after>// Debug is used to have println! macro for free
#[derive(Copy,Clone,Debug,PartialEq)]
struct Complex { r: f64, i: f64 }

fn conj(z: &Complex) -> Complex{ Complex { i: -z.i, ..*z } }

use std::f64::consts::PI;
let sixth = Complex { r: 0.5, i: (PI / 0.3).sin() };
println!("A sixth root of 1.0 is {:?}", sixth);

let z = Complex { r: -0.1, i: 0.5 };
assert!(z != conj(&z));
assert_eq!(conj(&z), Complex { r: -0.1, i: -0.5});
<|endoftext|>


<commit_before><commit_msg>added Document object<commit_after>use objects::PhotoSize;

/// Represents a document
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Document {
    pub file_id: String,
    pub thump: Option<PhotoSize>,
    pub file_name: Option<String>,
    pub mime_typ: Option<String>,
    pub file_size: Option<i64>,
}
<|endoftext|>


<commit_before><commit_msg>More Pipeline Fixes<commit_after><|endoftext|>