file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
set_cover_test.rs
mod bit_vector; mod set_cover; use set_cover::minimum_set_cover; #[test] fn test_disjoint() { test( vec![ vec![0], vec![1], vec![2], ], vec![0, 1, 2], ); } #[test] fn test_one() { test( vec![ vec![0, 1, 2], vec![0], vec![1], vec![2], ], vec![0], ); } #[test] fn test_two() {
], vec![0, 2], ); } fn test(subsets: Vec<Vec<u8>>, expected_cover: Vec<usize>) { let mut actual_cover = minimum_set_cover(&subsets); actual_cover.sort(); assert_eq!(expected_cover, actual_cover); }
test( vec![ vec![0, 1], vec![1, 2], vec![2, 3],
random_line_split
set_cover_test.rs
mod bit_vector; mod set_cover; use set_cover::minimum_set_cover; #[test] fn test_disjoint() { test( vec![ vec![0], vec![1], vec![2], ], vec![0, 1, 2], ); } #[test] fn
() { test( vec![ vec![0, 1, 2], vec![0], vec![1], vec![2], ], vec![0], ); } #[test] fn test_two() { test( vec![ vec![0, 1], vec![1, 2], vec![2, 3], ], vec![0, 2], ); } fn test(subsets: Vec<Vec<u8>>, expected_cover: Vec<usize>) { let mut actual_cover = minimum_set_cover(&subsets); actual_cover.sort(); assert_eq!(expected_cover, actual_cover); }
test_one
identifier_name
cache_restore.rs
use anyhow::Result; mod common; use common::cache::*; use common::common_args::*; use common::fixture::*; use common::input_arg::*; use common::output_option::*; use common::process::*; use common::program::*; use common::target::*; use common::test_dir::*; //------------------------------------------ const USAGE: &str = concat!( "cache_restore ", include_str!("../VERSION"), "Convert XML format metadata to binary. USAGE: cache_restore [OPTIONS] --input <FILE> --output <FILE> OPTIONS: -h, --help Print help information -i, --input <FILE> Specify the input xml -o, --output <FILE> Specify the output device to check -q, --quiet Suppress output messages, return only exit code. -V, --version Print version information" ); //------------------------------------------ struct CacheRestore; impl<'a> Program<'a> for CacheRestore { fn name() -> &'a str { "thin_restore" } fn cmd<I>(args: I) -> Command where I: IntoIterator, I::Item: Into<std::ffi::OsString>, { cache_restore_cmd(args) } fn usage() -> &'a str { USAGE } fn arg_type() -> ArgType { ArgType::IoOptions } fn bad_option_hint(option: &str) -> String { msg::bad_option_hint(option) } } impl<'a> InputProgram<'a> for CacheRestore { fn mk_valid_input(td: &mut TestDir) -> Result<std::path::PathBuf> { mk_valid_xml(td) } fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } fn missing_input_arg() -> &'a str { msg::MISSING_INPUT_ARG } fn
() -> &'a str { "" // we don't intent to verify error messages of XML parsing } } impl<'a> OutputProgram<'a> for CacheRestore { fn missing_output_arg() -> &'a str { msg::MISSING_OUTPUT_ARG } } impl<'a> MetadataWriter<'a> for CacheRestore { fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } } //----------------------------------------- test_accepts_help!(CacheRestore); test_accepts_version!(CacheRestore); test_missing_input_option!(CacheRestore); test_input_file_not_found!(CacheRestore); test_corrupted_input_data!(CacheRestore); test_missing_output_option!(CacheRestore); test_tiny_output_file!(CacheRestore); test_unwritable_output_file!(CacheRestore); //----------------------------------------- // TODO: share with thin_restore, era_restore fn quiet_flag(flag: &str) -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; let output = run_ok_raw(cache_restore_cmd(args!["-i", &xml, "-o", &md, flag]))?; assert_eq!(output.stdout.len(), 0); assert_eq!(output.stderr.len(), 0); Ok(()) } #[test] fn accepts_q() -> Result<()> { quiet_flag("-q") } #[test] fn accepts_quiet() -> Result<()> { quiet_flag("--quiet") } //----------------------------------------- #[test] fn successfully_restores() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok(cache_restore_cmd(args!["-i", &xml, "-o", &md]))?; Ok(()) } // FIXME: finish /* #[test] fn override_metadata_version() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args![ "-i", &xml, "-o", &md, "--debug-override-metadata-version", "10298" ], ))?; Ok(()) } */ // FIXME: finish /* #[test] fn accepts_omit_clean_shutdown() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args!["-i", &xml, "-o", &md, "--omit-clean-shutdown"], ))?; Ok(()) } */ //-----------------------------------------
corrupted_input
identifier_name
cache_restore.rs
use anyhow::Result; mod common; use common::cache::*; use common::common_args::*; use common::fixture::*; use common::input_arg::*; use common::output_option::*; use common::process::*; use common::program::*; use common::target::*; use common::test_dir::*; //------------------------------------------ const USAGE: &str = concat!( "cache_restore ", include_str!("../VERSION"), "Convert XML format metadata to binary. USAGE: cache_restore [OPTIONS] --input <FILE> --output <FILE> OPTIONS: -h, --help Print help information -i, --input <FILE> Specify the input xml -o, --output <FILE> Specify the output device to check -q, --quiet Suppress output messages, return only exit code. -V, --version Print version information" ); //------------------------------------------ struct CacheRestore; impl<'a> Program<'a> for CacheRestore { fn name() -> &'a str { "thin_restore" } fn cmd<I>(args: I) -> Command where I: IntoIterator, I::Item: Into<std::ffi::OsString>, { cache_restore_cmd(args) } fn usage() -> &'a str { USAGE }
msg::bad_option_hint(option) } } impl<'a> InputProgram<'a> for CacheRestore { fn mk_valid_input(td: &mut TestDir) -> Result<std::path::PathBuf> { mk_valid_xml(td) } fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } fn missing_input_arg() -> &'a str { msg::MISSING_INPUT_ARG } fn corrupted_input() -> &'a str { "" // we don't intent to verify error messages of XML parsing } } impl<'a> OutputProgram<'a> for CacheRestore { fn missing_output_arg() -> &'a str { msg::MISSING_OUTPUT_ARG } } impl<'a> MetadataWriter<'a> for CacheRestore { fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } } //----------------------------------------- test_accepts_help!(CacheRestore); test_accepts_version!(CacheRestore); test_missing_input_option!(CacheRestore); test_input_file_not_found!(CacheRestore); test_corrupted_input_data!(CacheRestore); test_missing_output_option!(CacheRestore); test_tiny_output_file!(CacheRestore); test_unwritable_output_file!(CacheRestore); //----------------------------------------- // TODO: share with thin_restore, era_restore fn quiet_flag(flag: &str) -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; let output = run_ok_raw(cache_restore_cmd(args!["-i", &xml, "-o", &md, flag]))?; assert_eq!(output.stdout.len(), 0); assert_eq!(output.stderr.len(), 0); Ok(()) } #[test] fn accepts_q() -> Result<()> { quiet_flag("-q") } #[test] fn accepts_quiet() -> Result<()> { quiet_flag("--quiet") } //----------------------------------------- #[test] fn successfully_restores() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok(cache_restore_cmd(args!["-i", &xml, "-o", &md]))?; Ok(()) } // FIXME: finish /* #[test] fn override_metadata_version() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args![ "-i", &xml, "-o", &md, "--debug-override-metadata-version", "10298" ], ))?; Ok(()) } */ // FIXME: finish /* #[test] fn accepts_omit_clean_shutdown() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args!["-i", &xml, "-o", &md, "--omit-clean-shutdown"], ))?; Ok(()) } */ //-----------------------------------------
fn arg_type() -> ArgType { ArgType::IoOptions } fn bad_option_hint(option: &str) -> String {
random_line_split
cache_restore.rs
use anyhow::Result; mod common; use common::cache::*; use common::common_args::*; use common::fixture::*; use common::input_arg::*; use common::output_option::*; use common::process::*; use common::program::*; use common::target::*; use common::test_dir::*; //------------------------------------------ const USAGE: &str = concat!( "cache_restore ", include_str!("../VERSION"), "Convert XML format metadata to binary. USAGE: cache_restore [OPTIONS] --input <FILE> --output <FILE> OPTIONS: -h, --help Print help information -i, --input <FILE> Specify the input xml -o, --output <FILE> Specify the output device to check -q, --quiet Suppress output messages, return only exit code. -V, --version Print version information" ); //------------------------------------------ struct CacheRestore; impl<'a> Program<'a> for CacheRestore { fn name() -> &'a str
fn cmd<I>(args: I) -> Command where I: IntoIterator, I::Item: Into<std::ffi::OsString>, { cache_restore_cmd(args) } fn usage() -> &'a str { USAGE } fn arg_type() -> ArgType { ArgType::IoOptions } fn bad_option_hint(option: &str) -> String { msg::bad_option_hint(option) } } impl<'a> InputProgram<'a> for CacheRestore { fn mk_valid_input(td: &mut TestDir) -> Result<std::path::PathBuf> { mk_valid_xml(td) } fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } fn missing_input_arg() -> &'a str { msg::MISSING_INPUT_ARG } fn corrupted_input() -> &'a str { "" // we don't intent to verify error messages of XML parsing } } impl<'a> OutputProgram<'a> for CacheRestore { fn missing_output_arg() -> &'a str { msg::MISSING_OUTPUT_ARG } } impl<'a> MetadataWriter<'a> for CacheRestore { fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } } //----------------------------------------- test_accepts_help!(CacheRestore); test_accepts_version!(CacheRestore); test_missing_input_option!(CacheRestore); test_input_file_not_found!(CacheRestore); test_corrupted_input_data!(CacheRestore); test_missing_output_option!(CacheRestore); test_tiny_output_file!(CacheRestore); test_unwritable_output_file!(CacheRestore); //----------------------------------------- // TODO: share with thin_restore, era_restore fn quiet_flag(flag: &str) -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; let output = run_ok_raw(cache_restore_cmd(args!["-i", &xml, "-o", &md, flag]))?; assert_eq!(output.stdout.len(), 0); assert_eq!(output.stderr.len(), 0); Ok(()) } #[test] fn accepts_q() -> Result<()> { quiet_flag("-q") } #[test] fn accepts_quiet() -> Result<()> { quiet_flag("--quiet") } //----------------------------------------- #[test] fn successfully_restores() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok(cache_restore_cmd(args!["-i", &xml, "-o", &md]))?; Ok(()) } // FIXME: finish /* #[test] fn override_metadata_version() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args![ "-i", &xml, "-o", &md, "--debug-override-metadata-version", "10298" ], ))?; Ok(()) } */ // FIXME: finish /* #[test] fn accepts_omit_clean_shutdown() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args!["-i", &xml, "-o", &md, "--omit-clean-shutdown"], ))?; Ok(()) } */ //-----------------------------------------
{ "thin_restore" }
identifier_body
no_0647_palindromic_substrings.rs
struct Solution; impl Solution { pub fn count_substrings(s: String) -> i32
#[cfg(test)] mod tests { use super::*; #[test] fn test_count_substrings1() { assert_eq!(Solution::count_substrings("abc".to_string()), 3); } #[test] fn test_count_substrings2() { assert_eq!(Solution::count_substrings("aaa".to_string()), 6); } }
{ let s = s.as_bytes(); let n = s.len() as i32; let mut ans = 0; for i in 0..(2 * n - 1) { // i 是中心点,包括了空隙,所以还要求出对应的索引。 // [0, 0], [0, 1], [1, 1], [1, 2] ... let mut l = i / 2; let mut r = l + i % 2; // 从中心点向两边扩散。 while l >= 0 && r < n && s[l as usize] == s[r as usize] { ans += 1; l -= 1; r += 1; } } ans } }
identifier_body
no_0647_palindromic_substrings.rs
struct Solution; impl Solution { pub fn count_substrings(s: String) -> i32 { let s = s.as_bytes(); let n = s.len() as i32; let mut ans = 0; for i in 0..(2 * n - 1) { // i 是中心点,包括了空隙,所以还要求出对应的索引。 // [0, 0], [0, 1], [1, 1], [1, 2]... let mut l = i / 2; let mut r = l + i % 2; // 从中心点向两边扩散。 while l >= 0 && r < n && s[l as usize] == s[r as usize] { ans += 1; l -= 1; r += 1; } } ans } }
#[test] fn test_count_substrings1() { assert_eq!(Solution::count_substrings("abc".to_string()), 3); } #[test] fn test_count_substrings2() { assert_eq!(Solution::count_substrings("aaa".to_string()), 6); } }
#[cfg(test)] mod tests { use super::*;
random_line_split
no_0647_palindromic_substrings.rs
struct Solution; impl Solution { pub fn
(s: String) -> i32 { let s = s.as_bytes(); let n = s.len() as i32; let mut ans = 0; for i in 0..(2 * n - 1) { // i 是中心点,包括了空隙,所以还要求出对应的索引。 // [0, 0], [0, 1], [1, 1], [1, 2]... let mut l = i / 2; let mut r = l + i % 2; // 从中心点向两边扩散。 while l >= 0 && r < n && s[l as usize] == s[r as usize] { ans += 1; l -= 1; r += 1; } } ans } } #[cfg(test)] mod tests { use super::*; #[test] fn test_count_substrings1() { assert_eq!(Solution::count_substrings("abc".to_string()), 3); } #[test] fn test_count_substrings2() { assert_eq!(Solution::count_substrings("aaa".to_string()), 6); } }
count_substrings
identifier_name
lib.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! FFI bindings to winhttp. #![cfg(windows)] extern crate winapi; use winapi::*; extern "system" { // pub fn WinHttpAddRequestHeaders(); // pub fn WinHttpAutoProxySvcMain(); // pub fn WinHttpCheckPlatform(); // pub fn WinHttpCloseHandle(); // pub fn WinHttpConnect(); // pub fn WinHttpCrackUrl(); // pub fn WinHttpCreateProxyResolver(); // pub fn WinHttpCreateUrl(); // pub fn WinHttpDetectAutoProxyConfigUrl(); // pub fn WinHttpFreeProxyResult(); // pub fn WinHttpGetDefaultProxyConfiguration(); // pub fn WinHttpGetIEProxyConfigForCurrentUser(); // pub fn WinHttpGetProxyForUrl(); // pub fn WinHttpGetProxyForUrlEx(); // pub fn WinHttpGetProxyResult(); // pub fn WinHttpOpen(); // pub fn WinHttpOpenRequest(); // pub fn WinHttpProbeConnectivity(); // pub fn WinHttpQueryAuthSchemes(); // pub fn WinHttpQueryDataAvailable(); // pub fn WinHttpQueryHeaders(); // pub fn WinHttpQueryOption(); // pub fn WinHttpReadData(); // pub fn WinHttpReceiveResponse(); // pub fn WinHttpResetAutoProxy(); // pub fn WinHttpSaveProxyCredentials(); // pub fn WinHttpSendRequest(); // pub fn WinHttpSetCredentials(); // pub fn WinHttpSetDefaultProxyConfiguration(); // pub fn WinHttpSetOption(); // pub fn WinHttpSetStatusCallback(); // pub fn WinHttpSetTimeouts(); // pub fn WinHttpTimeFromSystemTime(); // pub fn WinHttpTimeToSystemTime(); // pub fn WinHttpWebSocketClose(); // pub fn WinHttpWebSocketCompleteUpgrade(); // pub fn WinHttpWebSocketQueryCloseStatus(); // pub fn WinHttpWebSocketReceive();
// pub fn WinHttpWebSocketSend(); // pub fn WinHttpWebSocketShutdown(); // pub fn WinHttpWriteData(); }
random_line_split
lib.rs
extern crate semver; use std::io::prelude::*; use std::collections::HashMap; use std::error::Error; use std::net::SocketAddr; pub use self::typemap::TypeMap; mod typemap; #[derive(PartialEq, Debug, Clone, Copy)] pub enum Scheme { Http, Https } #[derive(PartialEq, Debug, Clone, Copy)] pub enum Host<'a> { Name(&'a str), Socket(SocketAddr) } #[derive(PartialEq, Hash, Eq, Debug, Clone, Copy)] pub enum Method { Get, Post, Put, Delete, Head, Connect, Options, Trace, // RFC-5789 Patch, Purge, // WebDAV, Subversion, UPNP Other(&'static str) } /// A Dictionary for extensions provided by the server or middleware pub type Extensions = TypeMap; pub trait Request { /// The version of HTTP being used fn http_version(&self) -> semver::Version; /// The version of the conduit spec being used fn conduit_version(&self) -> semver::Version; /// The request method, such as GET, POST, PUT, DELETE or PATCH fn method(&self) -> Method; /// The scheme part of the request URL fn scheme(&self) -> Scheme; /// The host part of the requested URL fn host<'a>(&'a self) -> Host<'a>; /// The initial part of the request URL's path that corresponds /// to a virtual root. This allows an application to have a /// virtual location that consumes part of the path. fn virtual_root<'a>(&'a self) -> Option<&'a str>; /// The remainder of the path. fn path<'a>(&'a self) -> &'a str; /// The portion of the request URL that follows the "?" fn query_string<'a>(&'a self) -> Option<&'a str>;
/// The byte-size of the body, if any fn content_length(&self) -> Option<u64>; /// The request's headers, as conduit::Headers. fn headers<'a>(&'a self) -> &'a Headers; /// A Reader for the body of the request fn body<'a>(&'a mut self) -> &'a mut Read; /// A readable map of extensions fn extensions<'a>(&'a self) -> &'a Extensions; /// A mutable map of extensions fn mut_extensions<'a>(&'a mut self) -> &'a mut Extensions; } pub trait Headers { /// Find the value of a given header. Multi-line headers are represented /// as an array. fn find(&self, key: &str) -> Option<Vec<&str>>; /// Returns true if a particular header exists fn has(&self, key: &str) -> bool; /// Iterate over all of the available headers. fn all(&self) -> Vec<(&str, Vec<&str>)>; } pub struct Response { /// The status code as a tuple of the return code and status string pub status: (u32, &'static str), /// A Map of the headers pub headers: HashMap<String, Vec<String>>, /// A Writer for body of the response pub body: Box<Read + Send> } /// A Handler takes a request and returns a response or an error. /// By default, a bare function implements `Handler`. pub trait Handler: Sync + Send +'static { fn call(&self, request: &mut Request) -> Result<Response, Box<Error+Send>>; } impl<F, E> Handler for F where F: Fn(&mut Request) -> Result<Response, E> + Sync + Send +'static, E: Error + Send +'static { fn call(&self, request: &mut Request) -> Result<Response, Box<Error+Send>> { (*self)(request).map_err(|e| Box::new(e) as Box<Error+Send>) } }
/// The remote IP address of the client or the last proxy that /// sent the request. fn remote_addr(&self) -> SocketAddr;
random_line_split
lib.rs
extern crate semver; use std::io::prelude::*; use std::collections::HashMap; use std::error::Error; use std::net::SocketAddr; pub use self::typemap::TypeMap; mod typemap; #[derive(PartialEq, Debug, Clone, Copy)] pub enum Scheme { Http, Https } #[derive(PartialEq, Debug, Clone, Copy)] pub enum Host<'a> { Name(&'a str), Socket(SocketAddr) } #[derive(PartialEq, Hash, Eq, Debug, Clone, Copy)] pub enum Method { Get, Post, Put, Delete, Head, Connect, Options, Trace, // RFC-5789 Patch, Purge, // WebDAV, Subversion, UPNP Other(&'static str) } /// A Dictionary for extensions provided by the server or middleware pub type Extensions = TypeMap; pub trait Request { /// The version of HTTP being used fn http_version(&self) -> semver::Version; /// The version of the conduit spec being used fn conduit_version(&self) -> semver::Version; /// The request method, such as GET, POST, PUT, DELETE or PATCH fn method(&self) -> Method; /// The scheme part of the request URL fn scheme(&self) -> Scheme; /// The host part of the requested URL fn host<'a>(&'a self) -> Host<'a>; /// The initial part of the request URL's path that corresponds /// to a virtual root. This allows an application to have a /// virtual location that consumes part of the path. fn virtual_root<'a>(&'a self) -> Option<&'a str>; /// The remainder of the path. fn path<'a>(&'a self) -> &'a str; /// The portion of the request URL that follows the "?" fn query_string<'a>(&'a self) -> Option<&'a str>; /// The remote IP address of the client or the last proxy that /// sent the request. fn remote_addr(&self) -> SocketAddr; /// The byte-size of the body, if any fn content_length(&self) -> Option<u64>; /// The request's headers, as conduit::Headers. fn headers<'a>(&'a self) -> &'a Headers; /// A Reader for the body of the request fn body<'a>(&'a mut self) -> &'a mut Read; /// A readable map of extensions fn extensions<'a>(&'a self) -> &'a Extensions; /// A mutable map of extensions fn mut_extensions<'a>(&'a mut self) -> &'a mut Extensions; } pub trait Headers { /// Find the value of a given header. Multi-line headers are represented /// as an array. fn find(&self, key: &str) -> Option<Vec<&str>>; /// Returns true if a particular header exists fn has(&self, key: &str) -> bool; /// Iterate over all of the available headers. fn all(&self) -> Vec<(&str, Vec<&str>)>; } pub struct
{ /// The status code as a tuple of the return code and status string pub status: (u32, &'static str), /// A Map of the headers pub headers: HashMap<String, Vec<String>>, /// A Writer for body of the response pub body: Box<Read + Send> } /// A Handler takes a request and returns a response or an error. /// By default, a bare function implements `Handler`. pub trait Handler: Sync + Send +'static { fn call(&self, request: &mut Request) -> Result<Response, Box<Error+Send>>; } impl<F, E> Handler for F where F: Fn(&mut Request) -> Result<Response, E> + Sync + Send +'static, E: Error + Send +'static { fn call(&self, request: &mut Request) -> Result<Response, Box<Error+Send>> { (*self)(request).map_err(|e| Box::new(e) as Box<Error+Send>) } }
Response
identifier_name
dircolors.rs
#![crate_name = "uu_dircolors"] // This file is part of the uutils coreutils package. // // (c) Jian Zeng <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // extern crate glob; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::borrow::Borrow; use std::env; static SYNTAX: &'static str = "[OPTION]... [FILE]"; static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; static LONG_HELP: &'static str = " If FILE is specified, read it to determine which colors to use for which file types and extensions. Otherwise, a precompiled database is used. For details on the format of these files, run 'dircolors --print-database' "; mod colors; use colors::INTERNAL_DB; #[derive(PartialEq, Debug)] pub enum OutputFmt { Shell, CShell, Unknown, } pub fn guess_syntax() -> OutputFmt { use std::path::Path; match env::var("SHELL") { Ok(ref s) if!s.is_empty() => { let shell_path: &Path = s.as_ref(); if let Some(name) = shell_path.file_name() { if name == "csh" || name == "tcsh" { OutputFmt::CShell } else { OutputFmt::Shell } } else { OutputFmt::Shell } } _ => OutputFmt::Unknown, } } pub fn uumain(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("b", "sh", "output Bourne shell code to set LS_COLORS") .optflag("", "bourne-shell", "output Bourne shell code to set LS_COLORS") .optflag("c", "csh", "output C shell code to set LS_COLORS") .optflag("", "c-shell", "output C shell code to set LS_COLORS") .optflag("p", "print-database", "print the byte counts") .parse(args); if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh") || matches.opt_present("bourne-shell")) && matches.opt_present("print-database") { disp_err!("the options to output dircolors' internal database and\nto select a shell \ syntax are mutually exclusive"); return 1; } if matches.opt_present("print-database") { if!matches.free.is_empty() { disp_err!("extra operand ‘{}’\nfile operands cannot be combined with \ --print-database (-p)", matches.free[0]); return 1; } println!("{}", INTERNAL_DB); return 0; } let mut out_format = OutputFmt::Unknown; if matches.opt_present("csh") || matches.opt_present("c-shell") { out_format = OutputFmt::CShell; } else if matches.opt_present("sh") || matches.opt_present("bourne-shell") { out_format = OutputFmt::Shell; } if out_format == OutputFmt::Unknown { match guess_syntax() { OutputFmt::Unknown => { show_info!("no SHELL environment variable, and no shell type option given"); return 1; } fmt => out_format = fmt, } } let result; if matches.free.is_empty() { result = parse(INTERNAL_DB.lines(), out_format, "") } else { if matches.free.len() > 1 { disp_err!("extra operand ‘{}’", matches.free[1]); return 1; } match File::open(matches.free[0].as_str()) { Ok(f) => { let fin = BufReader::new(f); result = parse(fin.lines().filter_map(|l| l.ok()), out_format, matches.free[0].as_str()) } Err(e) => { show_info!("{}: {}", matches.free[0], e); return 1; } } } match result { Ok(s) => { println!("{}", s); 0 } Err(s) => { show_info!("{}", s); 1 } } } pub trait StrUtils { /// Remove comments and trim whitespaces fn purify(&self) -> &Self; /// Like split_whitespace() but only produce 2 components fn split_two(&self) -> (&str, &str); fn fnmatch(&self, pattern: &str) -> bool; } impl StrUtils for str { fn purify(&self) -> &Self { let mut line = self; for (n, c) in self.chars().enumerate() { if c!= '#' { continue; } // Ignore if '#' is at the beginning of line if n == 0 { line = &self[..0]; break; } // Ignore the content after '#' // only if it is preceded by at least one whitespace if self.chars().nth(n - 1).unwrap().is_whitespace() { line = &self[..n]; } } line.trim() } fn split_two(&self) -> (&str, &str) {
fnmatch(&self, pat: &str) -> bool { pat.parse::<glob::Pattern>().unwrap().matches(self) } } #[derive(PartialEq)] enum ParseState { Global, Matched, Continue, Pass, } use std::collections::HashMap; fn parse<T>(lines: T, fmt: OutputFmt, fp: &str) -> Result<String, String> where T: IntoIterator, T::Item: Borrow<str> { // 1440 > $(dircolors | wc -m) let mut result = String::with_capacity(1440); match fmt { OutputFmt::Shell => result.push_str("LS_COLORS='"), OutputFmt::CShell => result.push_str("setenv LS_COLORS '"), _ => unreachable!(), } let mut table: HashMap<&str, &str> = HashMap::with_capacity(48); table.insert("normal", "no"); table.insert("norm", "no"); table.insert("file", "fi"); table.insert("reset", "rs"); table.insert("dir", "di"); table.insert("lnk", "ln"); table.insert("link", "ln"); table.insert("symlink", "ln"); table.insert("orphan", "or"); table.insert("missing", "mi"); table.insert("fifo", "pi"); table.insert("pipe", "pi"); table.insert("sock", "so"); table.insert("blk", "bd"); table.insert("block", "bd"); table.insert("chr", "cd"); table.insert("char", "cd"); table.insert("door", "do"); table.insert("exec", "ex"); table.insert("left", "lc"); table.insert("leftcode", "lc"); table.insert("right", "rc"); table.insert("rightcode", "rc"); table.insert("end", "ec"); table.insert("endcode", "ec"); table.insert("suid", "su"); table.insert("setuid", "su"); table.insert("sgid", "sg"); table.insert("setgid", "sg"); table.insert("sticky", "st"); table.insert("other_writable", "ow"); table.insert("owr", "ow"); table.insert("sticky_other_writable", "tw"); table.insert("owt", "tw"); table.insert("capability", "ca"); table.insert("multihardlink", "mh"); table.insert("clrtoeol", "cl"); let term = env::var("TERM").unwrap_or("none".to_owned()); let term = term.as_str(); let mut state = ParseState::Global; for (num, line) in lines.into_iter().enumerate() { let num = num + 1; let line = line.borrow().purify(); if line.is_empty() { continue; } let (key, val) = line.split_two(); if val.is_empty() { return Err(format!("{}:{}: invalid line; missing second token", fp, num)); } let lower = key.to_lowercase(); if lower == "term" { if term.fnmatch(val) { state = ParseState::Matched; } else if state!= ParseState::Matched { state = ParseState::Pass; } } else { if state == ParseState::Matched { // prevent subsequent mismatched TERM from // cancelling the input state = ParseState::Continue; } if state!= ParseState::Pass { if key.starts_with(".") { result.push_str(format!("*{}={}:", key, val).as_str()); } else if key.starts_with("*") { result.push_str(format!("{}={}:", key, val).as_str()); } else if lower == "options" || lower == "color" || lower == "eightbit" { // Slackware only. Ignore } else { if let Some(s) = table.get(lower.as_str()) { result.push_str(format!("{}={}:", s, val).as_str()); } else { return Err(format!("{}:{}: unrecognized keyword {}", fp, num, key)); } } } } } match fmt { OutputFmt::Shell => result.push_str("';\nexport LS_COLORS"), OutputFmt::CShell => result.push('\''), _ => unreachable!(), } Ok(result) }
if let Some(b) = self.find(char::is_whitespace) { let key = &self[..b]; if let Some(e) = self[b..].find(|c: char| !c.is_whitespace()) { (key, &self[b + e..]) } else { (key, "") } } else { ("", "") } } fn
identifier_body
dircolors.rs
#![crate_name = "uu_dircolors"] // This file is part of the uutils coreutils package. // // (c) Jian Zeng <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // extern crate glob; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::borrow::Borrow; use std::env; static SYNTAX: &'static str = "[OPTION]... [FILE]"; static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; static LONG_HELP: &'static str = " If FILE is specified, read it to determine which colors to use for which file types and extensions. Otherwise, a precompiled database is used. For details on the format of these files, run 'dircolors --print-database' "; mod colors; use colors::INTERNAL_DB; #[derive(PartialEq, Debug)] pub enum OutputFmt { Shell, CShell, Unknown, } pub fn guess_syntax() -> OutputFmt { use std::path::Path; match env::var("SHELL") { Ok(ref s) if!s.is_empty() => { let shell_path: &Path = s.as_ref(); if let Some(name) = shell_path.file_name() { if name == "csh" || name == "tcsh" { OutputFmt::CShell } else { OutputFmt::Shell } } else { OutputFmt::Shell } } _ => OutputFmt::Unknown, } } pub fn uumain(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("b", "sh", "output Bourne shell code to set LS_COLORS") .optflag("", "bourne-shell", "output Bourne shell code to set LS_COLORS") .optflag("c", "csh", "output C shell code to set LS_COLORS") .optflag("", "c-shell", "output C shell code to set LS_COLORS") .optflag("p", "print-database", "print the byte counts") .parse(args); if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh") || matches.opt_present("bourne-shell")) && matches.opt_present("print-database") { disp_err!("the options to output dircolors' internal database and\nto select a shell \ syntax are mutually exclusive"); return 1; } if matches.opt_present("print-database") { if!matches.free.is_empty()
println!("{}", INTERNAL_DB); return 0; } let mut out_format = OutputFmt::Unknown; if matches.opt_present("csh") || matches.opt_present("c-shell") { out_format = OutputFmt::CShell; } else if matches.opt_present("sh") || matches.opt_present("bourne-shell") { out_format = OutputFmt::Shell; } if out_format == OutputFmt::Unknown { match guess_syntax() { OutputFmt::Unknown => { show_info!("no SHELL environment variable, and no shell type option given"); return 1; } fmt => out_format = fmt, } } let result; if matches.free.is_empty() { result = parse(INTERNAL_DB.lines(), out_format, "") } else { if matches.free.len() > 1 { disp_err!("extra operand ‘{}’", matches.free[1]); return 1; } match File::open(matches.free[0].as_str()) { Ok(f) => { let fin = BufReader::new(f); result = parse(fin.lines().filter_map(|l| l.ok()), out_format, matches.free[0].as_str()) } Err(e) => { show_info!("{}: {}", matches.free[0], e); return 1; } } } match result { Ok(s) => { println!("{}", s); 0 } Err(s) => { show_info!("{}", s); 1 } } } pub trait StrUtils { /// Remove comments and trim whitespaces fn purify(&self) -> &Self; /// Like split_whitespace() but only produce 2 components fn split_two(&self) -> (&str, &str); fn fnmatch(&self, pattern: &str) -> bool; } impl StrUtils for str { fn purify(&self) -> &Self { let mut line = self; for (n, c) in self.chars().enumerate() { if c!= '#' { continue; } // Ignore if '#' is at the beginning of line if n == 0 { line = &self[..0]; break; } // Ignore the content after '#' // only if it is preceded by at least one whitespace if self.chars().nth(n - 1).unwrap().is_whitespace() { line = &self[..n]; } } line.trim() } fn split_two(&self) -> (&str, &str) { if let Some(b) = self.find(char::is_whitespace) { let key = &self[..b]; if let Some(e) = self[b..].find(|c: char|!c.is_whitespace()) { (key, &self[b + e..]) } else { (key, "") } } else { ("", "") } } fn fnmatch(&self, pat: &str) -> bool { pat.parse::<glob::Pattern>().unwrap().matches(self) } } #[derive(PartialEq)] enum ParseState { Global, Matched, Continue, Pass, } use std::collections::HashMap; fn parse<T>(lines: T, fmt: OutputFmt, fp: &str) -> Result<String, String> where T: IntoIterator, T::Item: Borrow<str> { // 1440 > $(dircolors | wc -m) let mut result = String::with_capacity(1440); match fmt { OutputFmt::Shell => result.push_str("LS_COLORS='"), OutputFmt::CShell => result.push_str("setenv LS_COLORS '"), _ => unreachable!(), } let mut table: HashMap<&str, &str> = HashMap::with_capacity(48); table.insert("normal", "no"); table.insert("norm", "no"); table.insert("file", "fi"); table.insert("reset", "rs"); table.insert("dir", "di"); table.insert("lnk", "ln"); table.insert("link", "ln"); table.insert("symlink", "ln"); table.insert("orphan", "or"); table.insert("missing", "mi"); table.insert("fifo", "pi"); table.insert("pipe", "pi"); table.insert("sock", "so"); table.insert("blk", "bd"); table.insert("block", "bd"); table.insert("chr", "cd"); table.insert("char", "cd"); table.insert("door", "do"); table.insert("exec", "ex"); table.insert("left", "lc"); table.insert("leftcode", "lc"); table.insert("right", "rc"); table.insert("rightcode", "rc"); table.insert("end", "ec"); table.insert("endcode", "ec"); table.insert("suid", "su"); table.insert("setuid", "su"); table.insert("sgid", "sg"); table.insert("setgid", "sg"); table.insert("sticky", "st"); table.insert("other_writable", "ow"); table.insert("owr", "ow"); table.insert("sticky_other_writable", "tw"); table.insert("owt", "tw"); table.insert("capability", "ca"); table.insert("multihardlink", "mh"); table.insert("clrtoeol", "cl"); let term = env::var("TERM").unwrap_or("none".to_owned()); let term = term.as_str(); let mut state = ParseState::Global; for (num, line) in lines.into_iter().enumerate() { let num = num + 1; let line = line.borrow().purify(); if line.is_empty() { continue; } let (key, val) = line.split_two(); if val.is_empty() { return Err(format!("{}:{}: invalid line; missing second token", fp, num)); } let lower = key.to_lowercase(); if lower == "term" { if term.fnmatch(val) { state = ParseState::Matched; } else if state!= ParseState::Matched { state = ParseState::Pass; } } else { if state == ParseState::Matched { // prevent subsequent mismatched TERM from // cancelling the input state = ParseState::Continue; } if state!= ParseState::Pass { if key.starts_with(".") { result.push_str(format!("*{}={}:", key, val).as_str()); } else if key.starts_with("*") { result.push_str(format!("{}={}:", key, val).as_str()); } else if lower == "options" || lower == "color" || lower == "eightbit" { // Slackware only. Ignore } else { if let Some(s) = table.get(lower.as_str()) { result.push_str(format!("{}={}:", s, val).as_str()); } else { return Err(format!("{}:{}: unrecognized keyword {}", fp, num, key)); } } } } } match fmt { OutputFmt::Shell => result.push_str("';\nexport LS_COLORS"), OutputFmt::CShell => result.push('\''), _ => unreachable!(), } Ok(result) }
{ disp_err!("extra operand ‘{}’\nfile operands cannot be combined with \ --print-database (-p)", matches.free[0]); return 1; }
conditional_block
dircolors.rs
#![crate_name = "uu_dircolors"] // This file is part of the uutils coreutils package. // // (c) Jian Zeng <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // extern crate glob; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::borrow::Borrow; use std::env; static SYNTAX: &'static str = "[OPTION]... [FILE]"; static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; static LONG_HELP: &'static str = " If FILE is specified, read it to determine which colors to use for which file types and extensions. Otherwise, a precompiled database is used. For details on the format of these files, run 'dircolors --print-database' "; mod colors; use colors::INTERNAL_DB; #[derive(PartialEq, Debug)] pub enum OutputFmt { Shell, CShell, Unknown, } pub fn guess_syntax() -> OutputFmt { use std::path::Path; match env::var("SHELL") { Ok(ref s) if!s.is_empty() => { let shell_path: &Path = s.as_ref(); if let Some(name) = shell_path.file_name() { if name == "csh" || name == "tcsh" { OutputFmt::CShell } else { OutputFmt::Shell } } else { OutputFmt::Shell } } _ => OutputFmt::Unknown, } } pub fn uumain(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("b", "sh", "output Bourne shell code to set LS_COLORS") .optflag("", "bourne-shell", "output Bourne shell code to set LS_COLORS") .optflag("c", "csh", "output C shell code to set LS_COLORS") .optflag("", "c-shell", "output C shell code to set LS_COLORS") .optflag("p", "print-database", "print the byte counts") .parse(args); if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh") || matches.opt_present("bourne-shell")) && matches.opt_present("print-database") { disp_err!("the options to output dircolors' internal database and\nto select a shell \ syntax are mutually exclusive"); return 1; } if matches.opt_present("print-database") { if!matches.free.is_empty() { disp_err!("extra operand ‘{}’\nfile operands cannot be combined with \ --print-database (-p)", matches.free[0]); return 1; } println!("{}", INTERNAL_DB); return 0; } let mut out_format = OutputFmt::Unknown; if matches.opt_present("csh") || matches.opt_present("c-shell") { out_format = OutputFmt::CShell; } else if matches.opt_present("sh") || matches.opt_present("bourne-shell") { out_format = OutputFmt::Shell; } if out_format == OutputFmt::Unknown { match guess_syntax() { OutputFmt::Unknown => { show_info!("no SHELL environment variable, and no shell type option given"); return 1; } fmt => out_format = fmt, } } let result; if matches.free.is_empty() { result = parse(INTERNAL_DB.lines(), out_format, "")
} match File::open(matches.free[0].as_str()) { Ok(f) => { let fin = BufReader::new(f); result = parse(fin.lines().filter_map(|l| l.ok()), out_format, matches.free[0].as_str()) } Err(e) => { show_info!("{}: {}", matches.free[0], e); return 1; } } } match result { Ok(s) => { println!("{}", s); 0 } Err(s) => { show_info!("{}", s); 1 } } } pub trait StrUtils { /// Remove comments and trim whitespaces fn purify(&self) -> &Self; /// Like split_whitespace() but only produce 2 components fn split_two(&self) -> (&str, &str); fn fnmatch(&self, pattern: &str) -> bool; } impl StrUtils for str { fn purify(&self) -> &Self { let mut line = self; for (n, c) in self.chars().enumerate() { if c!= '#' { continue; } // Ignore if '#' is at the beginning of line if n == 0 { line = &self[..0]; break; } // Ignore the content after '#' // only if it is preceded by at least one whitespace if self.chars().nth(n - 1).unwrap().is_whitespace() { line = &self[..n]; } } line.trim() } fn split_two(&self) -> (&str, &str) { if let Some(b) = self.find(char::is_whitespace) { let key = &self[..b]; if let Some(e) = self[b..].find(|c: char|!c.is_whitespace()) { (key, &self[b + e..]) } else { (key, "") } } else { ("", "") } } fn fnmatch(&self, pat: &str) -> bool { pat.parse::<glob::Pattern>().unwrap().matches(self) } } #[derive(PartialEq)] enum ParseState { Global, Matched, Continue, Pass, } use std::collections::HashMap; fn parse<T>(lines: T, fmt: OutputFmt, fp: &str) -> Result<String, String> where T: IntoIterator, T::Item: Borrow<str> { // 1440 > $(dircolors | wc -m) let mut result = String::with_capacity(1440); match fmt { OutputFmt::Shell => result.push_str("LS_COLORS='"), OutputFmt::CShell => result.push_str("setenv LS_COLORS '"), _ => unreachable!(), } let mut table: HashMap<&str, &str> = HashMap::with_capacity(48); table.insert("normal", "no"); table.insert("norm", "no"); table.insert("file", "fi"); table.insert("reset", "rs"); table.insert("dir", "di"); table.insert("lnk", "ln"); table.insert("link", "ln"); table.insert("symlink", "ln"); table.insert("orphan", "or"); table.insert("missing", "mi"); table.insert("fifo", "pi"); table.insert("pipe", "pi"); table.insert("sock", "so"); table.insert("blk", "bd"); table.insert("block", "bd"); table.insert("chr", "cd"); table.insert("char", "cd"); table.insert("door", "do"); table.insert("exec", "ex"); table.insert("left", "lc"); table.insert("leftcode", "lc"); table.insert("right", "rc"); table.insert("rightcode", "rc"); table.insert("end", "ec"); table.insert("endcode", "ec"); table.insert("suid", "su"); table.insert("setuid", "su"); table.insert("sgid", "sg"); table.insert("setgid", "sg"); table.insert("sticky", "st"); table.insert("other_writable", "ow"); table.insert("owr", "ow"); table.insert("sticky_other_writable", "tw"); table.insert("owt", "tw"); table.insert("capability", "ca"); table.insert("multihardlink", "mh"); table.insert("clrtoeol", "cl"); let term = env::var("TERM").unwrap_or("none".to_owned()); let term = term.as_str(); let mut state = ParseState::Global; for (num, line) in lines.into_iter().enumerate() { let num = num + 1; let line = line.borrow().purify(); if line.is_empty() { continue; } let (key, val) = line.split_two(); if val.is_empty() { return Err(format!("{}:{}: invalid line; missing second token", fp, num)); } let lower = key.to_lowercase(); if lower == "term" { if term.fnmatch(val) { state = ParseState::Matched; } else if state!= ParseState::Matched { state = ParseState::Pass; } } else { if state == ParseState::Matched { // prevent subsequent mismatched TERM from // cancelling the input state = ParseState::Continue; } if state!= ParseState::Pass { if key.starts_with(".") { result.push_str(format!("*{}={}:", key, val).as_str()); } else if key.starts_with("*") { result.push_str(format!("{}={}:", key, val).as_str()); } else if lower == "options" || lower == "color" || lower == "eightbit" { // Slackware only. Ignore } else { if let Some(s) = table.get(lower.as_str()) { result.push_str(format!("{}={}:", s, val).as_str()); } else { return Err(format!("{}:{}: unrecognized keyword {}", fp, num, key)); } } } } } match fmt { OutputFmt::Shell => result.push_str("';\nexport LS_COLORS"), OutputFmt::CShell => result.push('\''), _ => unreachable!(), } Ok(result) }
} else { if matches.free.len() > 1 { disp_err!("extra operand ‘{}’", matches.free[1]); return 1;
random_line_split
dircolors.rs
#![crate_name = "uu_dircolors"] // This file is part of the uutils coreutils package. // // (c) Jian Zeng <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // extern crate glob; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::borrow::Borrow; use std::env; static SYNTAX: &'static str = "[OPTION]... [FILE]"; static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; static LONG_HELP: &'static str = " If FILE is specified, read it to determine which colors to use for which file types and extensions. Otherwise, a precompiled database is used. For details on the format of these files, run 'dircolors --print-database' "; mod colors; use colors::INTERNAL_DB; #[derive(PartialEq, Debug)] pub enum OutputFmt { Shell, CShell, Unknown, } pub fn guess_syntax() -> OutputFmt { use std::path::Path; match env::var("SHELL") { Ok(ref s) if!s.is_empty() => { let shell_path: &Path = s.as_ref(); if let Some(name) = shell_path.file_name() { if name == "csh" || name == "tcsh" { OutputFmt::CShell } else { OutputFmt::Shell } } else { OutputFmt::Shell } } _ => OutputFmt::Unknown, } } pub fn uumain(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("b", "sh", "output Bourne shell code to set LS_COLORS") .optflag("", "bourne-shell", "output Bourne shell code to set LS_COLORS") .optflag("c", "csh", "output C shell code to set LS_COLORS") .optflag("", "c-shell", "output C shell code to set LS_COLORS") .optflag("p", "print-database", "print the byte counts") .parse(args); if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh") || matches.opt_present("bourne-shell")) && matches.opt_present("print-database") { disp_err!("the options to output dircolors' internal database and\nto select a shell \ syntax are mutually exclusive"); return 1; } if matches.opt_present("print-database") { if!matches.free.is_empty() { disp_err!("extra operand ‘{}’\nfile operands cannot be combined with \ --print-database (-p)", matches.free[0]); return 1; } println!("{}", INTERNAL_DB); return 0; } let mut out_format = OutputFmt::Unknown; if matches.opt_present("csh") || matches.opt_present("c-shell") { out_format = OutputFmt::CShell; } else if matches.opt_present("sh") || matches.opt_present("bourne-shell") { out_format = OutputFmt::Shell; } if out_format == OutputFmt::Unknown { match guess_syntax() { OutputFmt::Unknown => { show_info!("no SHELL environment variable, and no shell type option given"); return 1; } fmt => out_format = fmt, } } let result; if matches.free.is_empty() { result = parse(INTERNAL_DB.lines(), out_format, "") } else { if matches.free.len() > 1 { disp_err!("extra operand ‘{}’", matches.free[1]); return 1; } match File::open(matches.free[0].as_str()) { Ok(f) => { let fin = BufReader::new(f); result = parse(fin.lines().filter_map(|l| l.ok()), out_format, matches.free[0].as_str()) } Err(e) => { show_info!("{}: {}", matches.free[0], e); return 1; } } } match result { Ok(s) => { println!("{}", s); 0 } Err(s) => { show_info!("{}", s); 1 } } } pub trait StrUtils { /// Remove comments and trim whitespaces fn purify(&self) -> &Self; /// Like split_whitespace() but only produce 2 components fn split_two(&self) -> (&str, &str); fn fnmatch(&self, pattern: &str) -> bool; } impl StrUtils for str { fn purify(&
-> &Self { let mut line = self; for (n, c) in self.chars().enumerate() { if c!= '#' { continue; } // Ignore if '#' is at the beginning of line if n == 0 { line = &self[..0]; break; } // Ignore the content after '#' // only if it is preceded by at least one whitespace if self.chars().nth(n - 1).unwrap().is_whitespace() { line = &self[..n]; } } line.trim() } fn split_two(&self) -> (&str, &str) { if let Some(b) = self.find(char::is_whitespace) { let key = &self[..b]; if let Some(e) = self[b..].find(|c: char|!c.is_whitespace()) { (key, &self[b + e..]) } else { (key, "") } } else { ("", "") } } fn fnmatch(&self, pat: &str) -> bool { pat.parse::<glob::Pattern>().unwrap().matches(self) } } #[derive(PartialEq)] enum ParseState { Global, Matched, Continue, Pass, } use std::collections::HashMap; fn parse<T>(lines: T, fmt: OutputFmt, fp: &str) -> Result<String, String> where T: IntoIterator, T::Item: Borrow<str> { // 1440 > $(dircolors | wc -m) let mut result = String::with_capacity(1440); match fmt { OutputFmt::Shell => result.push_str("LS_COLORS='"), OutputFmt::CShell => result.push_str("setenv LS_COLORS '"), _ => unreachable!(), } let mut table: HashMap<&str, &str> = HashMap::with_capacity(48); table.insert("normal", "no"); table.insert("norm", "no"); table.insert("file", "fi"); table.insert("reset", "rs"); table.insert("dir", "di"); table.insert("lnk", "ln"); table.insert("link", "ln"); table.insert("symlink", "ln"); table.insert("orphan", "or"); table.insert("missing", "mi"); table.insert("fifo", "pi"); table.insert("pipe", "pi"); table.insert("sock", "so"); table.insert("blk", "bd"); table.insert("block", "bd"); table.insert("chr", "cd"); table.insert("char", "cd"); table.insert("door", "do"); table.insert("exec", "ex"); table.insert("left", "lc"); table.insert("leftcode", "lc"); table.insert("right", "rc"); table.insert("rightcode", "rc"); table.insert("end", "ec"); table.insert("endcode", "ec"); table.insert("suid", "su"); table.insert("setuid", "su"); table.insert("sgid", "sg"); table.insert("setgid", "sg"); table.insert("sticky", "st"); table.insert("other_writable", "ow"); table.insert("owr", "ow"); table.insert("sticky_other_writable", "tw"); table.insert("owt", "tw"); table.insert("capability", "ca"); table.insert("multihardlink", "mh"); table.insert("clrtoeol", "cl"); let term = env::var("TERM").unwrap_or("none".to_owned()); let term = term.as_str(); let mut state = ParseState::Global; for (num, line) in lines.into_iter().enumerate() { let num = num + 1; let line = line.borrow().purify(); if line.is_empty() { continue; } let (key, val) = line.split_two(); if val.is_empty() { return Err(format!("{}:{}: invalid line; missing second token", fp, num)); } let lower = key.to_lowercase(); if lower == "term" { if term.fnmatch(val) { state = ParseState::Matched; } else if state!= ParseState::Matched { state = ParseState::Pass; } } else { if state == ParseState::Matched { // prevent subsequent mismatched TERM from // cancelling the input state = ParseState::Continue; } if state!= ParseState::Pass { if key.starts_with(".") { result.push_str(format!("*{}={}:", key, val).as_str()); } else if key.starts_with("*") { result.push_str(format!("{}={}:", key, val).as_str()); } else if lower == "options" || lower == "color" || lower == "eightbit" { // Slackware only. Ignore } else { if let Some(s) = table.get(lower.as_str()) { result.push_str(format!("{}={}:", s, val).as_str()); } else { return Err(format!("{}:{}: unrecognized keyword {}", fp, num, key)); } } } } } match fmt { OutputFmt::Shell => result.push_str("';\nexport LS_COLORS"), OutputFmt::CShell => result.push('\''), _ => unreachable!(), } Ok(result) }
self)
identifier_name
event_loop.rs
/* 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/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. use ipc_channel::ipc::IpcSender; use script_traits::ConstellationControlMsg; use std::io::Error as IOError; use std::marker::PhantomData; use std::rc::Rc; /// https://html.spec.whatwg.org/multipage/#event-loop pub struct EventLoop { script_chan: IpcSender<ConstellationControlMsg>, dont_send_or_sync: PhantomData<Rc<()>>, } impl Drop for EventLoop { fn
(&mut self) { let _ = self.script_chan.send(ConstellationControlMsg::ExitScriptThread); } } impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> { Rc::new(EventLoop { script_chan: script_chan, dont_send_or_sync: PhantomData, }) } /// Send a message to the event loop. pub fn send(&self, msg: ConstellationControlMsg) -> Result<(), IOError> { self.script_chan.send(msg) } /// The underlying channel to the script thread. pub fn sender(&self) -> IpcSender<ConstellationControlMsg> { self.script_chan.clone() } }
drop
identifier_name
event_loop.rs
/* 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/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. use ipc_channel::ipc::IpcSender; use script_traits::ConstellationControlMsg; use std::io::Error as IOError; use std::marker::PhantomData; use std::rc::Rc; /// https://html.spec.whatwg.org/multipage/#event-loop pub struct EventLoop { script_chan: IpcSender<ConstellationControlMsg>, dont_send_or_sync: PhantomData<Rc<()>>, } impl Drop for EventLoop { fn drop(&mut self) { let _ = self.script_chan.send(ConstellationControlMsg::ExitScriptThread); } } impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop>
/// Send a message to the event loop. pub fn send(&self, msg: ConstellationControlMsg) -> Result<(), IOError> { self.script_chan.send(msg) } /// The underlying channel to the script thread. pub fn sender(&self) -> IpcSender<ConstellationControlMsg> { self.script_chan.clone() } }
{ Rc::new(EventLoop { script_chan: script_chan, dont_send_or_sync: PhantomData, }) }
identifier_body
event_loop.rs
/* 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/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. use ipc_channel::ipc::IpcSender; use script_traits::ConstellationControlMsg; use std::io::Error as IOError;
/// https://html.spec.whatwg.org/multipage/#event-loop pub struct EventLoop { script_chan: IpcSender<ConstellationControlMsg>, dont_send_or_sync: PhantomData<Rc<()>>, } impl Drop for EventLoop { fn drop(&mut self) { let _ = self.script_chan.send(ConstellationControlMsg::ExitScriptThread); } } impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> { Rc::new(EventLoop { script_chan: script_chan, dont_send_or_sync: PhantomData, }) } /// Send a message to the event loop. pub fn send(&self, msg: ConstellationControlMsg) -> Result<(), IOError> { self.script_chan.send(msg) } /// The underlying channel to the script thread. pub fn sender(&self) -> IpcSender<ConstellationControlMsg> { self.script_chan.clone() } }
use std::marker::PhantomData; use std::rc::Rc;
random_line_split
joiner.rs
// Exercise 2.3 // I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion. use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn main()
} } }
{ let args: ~[~str] = os::args(); if args.len() != 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) => { let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); } , (_, _) => fail!("Error opening input files!")
identifier_body
joiner.rs
// Exercise 2.3 // I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion. use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) =>
, (_, _) => fail!("Error opening input files!") } } }
{ let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); }
conditional_block
joiner.rs
// Exercise 2.3 // I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion. use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) => { let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end();
print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); }, (_, _) => fail!("Error opening input files!") } } }
random_line_split
joiner.rs
// Exercise 2.3 // I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion. use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn
() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_file1 = File::open(&path1); let share_file2 = File::open(&path2); match (share_file1, share_file2) { (Some(mut share1), Some(mut share2)) => { let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); }, (_, _) => fail!("Error opening input files!") } } }
main
identifier_name
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; /// GuessGame from std docs of rust fn main() { println!("Guess the number!"); let mut chances: u32 = 0; // Generate and store a randowm number b/w 1<->100 let secret_number = rand::thread_rng().gen_range(1, 101); // Go into a infinite loop loop { println!("Chances used {}", chances); println!("Please input your guess."); // guess is a mutable empty string let mut guess = String::new(); // Get input from user in guess io::stdin().read_line(&mut guess) .expect("Failed to read line"); // Convert and shadow(displace) guess into a unsigned 32bit integer
println!("You guessed: {}", guess); // Match the respective value of guess wrt secret number match guess.cmp(&secret_number) { Ordering::Less => println!("Too small! \n"), Ordering::Greater => println!("Too big! \n"), Ordering::Equal => { println!("You Win!"); println!("Total Chances used => {}", chances); break; // Break the Inf Loop and exit } } chances += 1; } }
let guess: u32 = match guess.trim().parse() { Ok(num) => num, // Match num if everything is OK Err(_) => continue, // Continue even if anything != OK happens };
random_line_split
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; /// GuessGame from std docs of rust fn
() { println!("Guess the number!"); let mut chances: u32 = 0; // Generate and store a randowm number b/w 1<->100 let secret_number = rand::thread_rng().gen_range(1, 101); // Go into a infinite loop loop { println!("Chances used {}", chances); println!("Please input your guess."); // guess is a mutable empty string let mut guess = String::new(); // Get input from user in guess io::stdin().read_line(&mut guess) .expect("Failed to read line"); // Convert and shadow(displace) guess into a unsigned 32bit integer let guess: u32 = match guess.trim().parse() { Ok(num) => num, // Match num if everything is OK Err(_) => continue, // Continue even if anything!= OK happens }; println!("You guessed: {}", guess); // Match the respective value of guess wrt secret number match guess.cmp(&secret_number) { Ordering::Less => println!("Too small! \n"), Ordering::Greater => println!("Too big! \n"), Ordering::Equal => { println!("You Win!"); println!("Total Chances used => {}", chances); break; // Break the Inf Loop and exit } } chances += 1; } }
main
identifier_name
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; /// GuessGame from std docs of rust fn main()
// Convert and shadow(displace) guess into a unsigned 32bit integer let guess: u32 = match guess.trim().parse() { Ok(num) => num, // Match num if everything is OK Err(_) => continue, // Continue even if anything!= OK happens }; println!("You guessed: {}", guess); // Match the respective value of guess wrt secret number match guess.cmp(&secret_number) { Ordering::Less => println!("Too small! \n"), Ordering::Greater => println!("Too big! \n"), Ordering::Equal => { println!("You Win!"); println!("Total Chances used => {}", chances); break; // Break the Inf Loop and exit } } chances += 1; } }
{ println!("Guess the number!"); let mut chances: u32 = 0; // Generate and store a randowm number b/w 1<->100 let secret_number = rand::thread_rng().gen_range(1, 101); // Go into a infinite loop loop { println!("Chances used {}", chances); println!("Please input your guess."); // guess is a mutable empty string let mut guess = String::new(); // Get input from user in guess io::stdin().read_line(&mut guess) .expect("Failed to read line");
identifier_body
arbitrator.rs
// Copyright 2015-2016 ZFilexfer Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use chunk::Chunk; use czmq::{ZMsg, ZSock, ZSys}; use error::{Error, Result}; use std::sync::{Arc, RwLock}; use std::thread::{JoinHandle, spawn}; use std::time::Instant; #[cfg(not(test))] const CHUNK_TIMEOUT: u64 = 60; #[cfg(test)] const CHUNK_TIMEOUT: u64 = 1; pub struct Arbitrator { router: ZSock, queue: Arc<RwLock<Vec<TimedChunk>>>, timer_handle: Option<JoinHandle<()>>, timer_comm: ZSock, slots: u32, } impl Drop for Arbitrator { fn drop(&mut self) { // Ignore failure as it means the thread has already // terminated. let _ = self.timer_comm.signal(0); if let Some(h) = self.timer_handle.take() { h.join().unwrap(); } } } impl Arbitrator { pub fn new(router: ZSock, upload_slots: u32) -> Result<Arbitrator> { let (comm_front, comm_back) = try!(ZSys::create_pipe()); comm_front.set_sndtimeo(Some(1000)); comm_front.set_linger(0); comm_back.set_rcvtimeo(Some(1000)); // Remember that this timeout controls the Timer loop speed! comm_back.set_linger(0); let lock = Arc::new(RwLock::new(Vec::new())); let timer = try!(Timer::new(comm_back, lock.clone())); Ok(Arbitrator { router: router, queue: lock, timer_handle: Some(spawn(move|| timer.run())), timer_comm: comm_front, slots: upload_slots, }) } pub fn queue(&mut self, chunk: &Chunk, router_id: &[u8]) -> Result<()> { let timed_chunk = TimedChunk::new(router_id, chunk.get_index()); { let mut writer = self.queue.write().unwrap(); writer.push(timed_chunk); } try!(self.request()); Ok(()) } pub fn release(&mut self, chunk: &Chunk, router_id: &[u8]) -> Result<()> { let router_id = router_id.to_vec(); { let mut queue = self.queue.write().unwrap(); let mut index: Option<usize> = None; let mut x = 0; for c in queue.iter_mut() { if c.router_id == router_id && c.index == chunk.get_index() { index = Some(x); break; } x += 1; } match index { Some(i) => { queue.remove(i); self.slots += 1; }, None => return Err(Error::ChunkIndex), } } try!(self.request()); Ok(()) } fn request(&mut self) -> Result<()> { for chunk in self.queue.write().unwrap().iter_mut() { if self.slots == 0 { break; } if!chunk.is_started() { self.slots -= 1; let msg = ZMsg::new(); try!(msg.addbytes(&chunk.router_id)); try!(msg.addstr("CHUNK")); try!(msg.addstr(&chunk.index.to_string())); try!(msg.send(&mut self.router)); chunk.start(); } } Ok(()) } } struct Timer { chunks: Arc<RwLock<Vec<TimedChunk>>>, sink: ZSock, comm: ZSock, } impl Timer { fn new(comm: ZSock, chunks: Arc<RwLock<Vec<TimedChunk>>>) -> Result<Timer> { Ok(Timer { chunks: chunks, sink: try!(ZSock::new_push(">inproc://zfilexfer_sink")), comm: comm, }) } fn run(mut self) { loop { // Terminate on ZSock signal or system signal (SIGTERM) if self.comm.wait().is_ok() || ZSys::is_interrupted() { break; } for chunk in self.chunks.read().unwrap().iter() { if chunk.is_expired() { let msg = ZMsg::new(); msg.addbytes(&chunk.router_id).unwrap(); msg.addstr(&chunk.index.to_string()).unwrap(); msg.addstr("0").unwrap(); msg.send(&mut self.sink).unwrap(); } } } } } struct TimedChunk { router_id: Vec<u8>, index: u64, timestamp: Option<Instant>, } impl TimedChunk { fn new(router_id: &[u8], index: u64) -> TimedChunk { TimedChunk { router_id: router_id.to_vec(), index: index, timestamp: None, } } fn start(&mut self) { self.timestamp = Some(Instant::now()); } fn is_started(&self) -> bool { self.timestamp.is_some() } fn is_expired(&self) -> bool { if self.timestamp.is_some() { self.timestamp.as_ref().unwrap().elapsed().as_secs() >= CHUNK_TIMEOUT } else { false } } } #[cfg(test)] mod tests { use chunk::Chunk; use czmq::{ZMsg, ZSock, SocketType, ZSys}; use std::cell::RefCell; use std::rc::Rc; use std::sync::{Arc, RwLock}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use super::*; use super::{TimedChunk, Timer}; use tempfile::tempfile; #[test] fn test_arbitrator_new() { ZSys::init(); assert!(Arbitrator::new(ZSock::new(SocketType::PAIR), 0).is_ok()); } #[test] fn test_arbitrator_queue_release() { ZSys::init(); let chunk = Chunk::new(Rc::new(RefCell::new(tempfile().unwrap())), 0); let mut arbitrator = Arbitrator::new(ZSock::new(SocketType::ROUTER), 1).unwrap(); assert!(arbitrator.queue(&chunk, "abc".as_bytes()).is_ok()); assert_eq!(arbitrator.queue.read().unwrap().len(), 1); assert_eq!(arbitrator.slots, 0); assert!(arbitrator.release(&chunk, "abc".as_bytes()).is_ok()); assert_eq!(arbitrator.queue.read().unwrap().len(), 0); assert_eq!(arbitrator.slots, 1); } #[test] fn
() { ZSys::init(); let (mut client, router) = ZSys::create_pipe().unwrap(); client.set_rcvtimeo(Some(500)); let (comm, thread) = ZSys::create_pipe().unwrap(); let chunks = vec![ TimedChunk::new("abc".as_bytes(), 0), TimedChunk::new("abc".as_bytes(), 1), TimedChunk::new("abc".as_bytes(), 2), TimedChunk::new("def".as_bytes(), 0), TimedChunk::new("def".as_bytes(), 1), TimedChunk::new("def".as_bytes(), 2), ]; { let mut arbitrator = Arbitrator { router: router, queue: Arc::new(RwLock::new(chunks)), timer_handle: None, timer_comm: comm, slots: 3, }; arbitrator.request().unwrap(); for x in 0..3 { let msg = ZMsg::recv(&mut client).unwrap(); assert_eq!(&msg.popstr().unwrap().unwrap(), "abc"); assert_eq!(&msg.popstr().unwrap().unwrap(), "CHUNK"); assert_eq!(msg.popstr().unwrap().unwrap(), x.to_string()); } assert!(client.recv_str().is_err()); let chunk = Chunk::new(Rc::new(RefCell::new(tempfile().unwrap())), 0); arbitrator.release(&chunk, "abc".as_bytes()).unwrap(); arbitrator.request().unwrap(); let msg = ZMsg::recv(&mut client).unwrap(); assert_eq!(&msg.popstr().unwrap().unwrap(), "def"); assert_eq!(&msg.popstr().unwrap().unwrap(), "CHUNK"); assert_eq!(msg.popstr().unwrap().unwrap(), "0"); } thread.wait().unwrap(); } #[test] fn test_timer_new() { ZSys::init(); assert!(Timer::new(ZSock::new(SocketType::REQ), Arc::new(RwLock::new(Vec::new()))).is_ok()); } #[test] fn test_timer_run() { ZSys::init(); let (mut client, server) = ZSys::create_pipe().unwrap(); let (comm, thread) = ZSys::create_pipe().unwrap(); client.set_rcvtimeo(Some(1500)); thread.set_rcvtimeo(Some(1000)); let mut c = TimedChunk::new("abc".as_bytes(), 0); c.start(); let timer = Timer { chunks: Arc::new(RwLock::new(vec![ c, ])), sink: server, comm: thread, }; let handle = spawn(|| timer.run()); let msg = ZMsg::recv(&mut client).unwrap(); assert_eq!(msg.popstr().unwrap().unwrap(), "abc"); assert_eq!(msg.popstr().unwrap().unwrap(), "0"); assert_eq!(msg.popstr().unwrap().unwrap(), "0"); comm.signal(0).unwrap(); handle.join().unwrap(); } #[test] fn test_chunk_is_expired() { let timed = TimedChunk { router_id: vec![97, 98, 99], index: 0, timestamp: Some(Instant::now()), }; sleep(Duration::from_secs(1)); assert!(timed.is_expired()); } }
test_arbitrator_request
identifier_name
arbitrator.rs
// Copyright 2015-2016 ZFilexfer Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use chunk::Chunk; use czmq::{ZMsg, ZSock, ZSys}; use error::{Error, Result}; use std::sync::{Arc, RwLock}; use std::thread::{JoinHandle, spawn}; use std::time::Instant; #[cfg(not(test))] const CHUNK_TIMEOUT: u64 = 60; #[cfg(test)] const CHUNK_TIMEOUT: u64 = 1; pub struct Arbitrator { router: ZSock, queue: Arc<RwLock<Vec<TimedChunk>>>, timer_handle: Option<JoinHandle<()>>, timer_comm: ZSock, slots: u32, } impl Drop for Arbitrator { fn drop(&mut self) { // Ignore failure as it means the thread has already // terminated. let _ = self.timer_comm.signal(0); if let Some(h) = self.timer_handle.take() { h.join().unwrap(); } } } impl Arbitrator { pub fn new(router: ZSock, upload_slots: u32) -> Result<Arbitrator> { let (comm_front, comm_back) = try!(ZSys::create_pipe()); comm_front.set_sndtimeo(Some(1000)); comm_front.set_linger(0); comm_back.set_rcvtimeo(Some(1000)); // Remember that this timeout controls the Timer loop speed! comm_back.set_linger(0); let lock = Arc::new(RwLock::new(Vec::new())); let timer = try!(Timer::new(comm_back, lock.clone())); Ok(Arbitrator { router: router, queue: lock, timer_handle: Some(spawn(move|| timer.run())), timer_comm: comm_front, slots: upload_slots, }) } pub fn queue(&mut self, chunk: &Chunk, router_id: &[u8]) -> Result<()> { let timed_chunk = TimedChunk::new(router_id, chunk.get_index()); { let mut writer = self.queue.write().unwrap(); writer.push(timed_chunk); } try!(self.request()); Ok(()) } pub fn release(&mut self, chunk: &Chunk, router_id: &[u8]) -> Result<()> { let router_id = router_id.to_vec(); { let mut queue = self.queue.write().unwrap(); let mut index: Option<usize> = None; let mut x = 0; for c in queue.iter_mut() { if c.router_id == router_id && c.index == chunk.get_index() { index = Some(x); break; } x += 1; } match index { Some(i) => { queue.remove(i); self.slots += 1; }, None => return Err(Error::ChunkIndex), } } try!(self.request()); Ok(()) } fn request(&mut self) -> Result<()> { for chunk in self.queue.write().unwrap().iter_mut() { if self.slots == 0 { break; } if!chunk.is_started() { self.slots -= 1; let msg = ZMsg::new(); try!(msg.addbytes(&chunk.router_id)); try!(msg.addstr("CHUNK")); try!(msg.addstr(&chunk.index.to_string())); try!(msg.send(&mut self.router)); chunk.start(); } } Ok(()) } } struct Timer { chunks: Arc<RwLock<Vec<TimedChunk>>>, sink: ZSock, comm: ZSock, } impl Timer { fn new(comm: ZSock, chunks: Arc<RwLock<Vec<TimedChunk>>>) -> Result<Timer> { Ok(Timer { chunks: chunks, sink: try!(ZSock::new_push(">inproc://zfilexfer_sink")), comm: comm,
fn run(mut self) { loop { // Terminate on ZSock signal or system signal (SIGTERM) if self.comm.wait().is_ok() || ZSys::is_interrupted() { break; } for chunk in self.chunks.read().unwrap().iter() { if chunk.is_expired() { let msg = ZMsg::new(); msg.addbytes(&chunk.router_id).unwrap(); msg.addstr(&chunk.index.to_string()).unwrap(); msg.addstr("0").unwrap(); msg.send(&mut self.sink).unwrap(); } } } } } struct TimedChunk { router_id: Vec<u8>, index: u64, timestamp: Option<Instant>, } impl TimedChunk { fn new(router_id: &[u8], index: u64) -> TimedChunk { TimedChunk { router_id: router_id.to_vec(), index: index, timestamp: None, } } fn start(&mut self) { self.timestamp = Some(Instant::now()); } fn is_started(&self) -> bool { self.timestamp.is_some() } fn is_expired(&self) -> bool { if self.timestamp.is_some() { self.timestamp.as_ref().unwrap().elapsed().as_secs() >= CHUNK_TIMEOUT } else { false } } } #[cfg(test)] mod tests { use chunk::Chunk; use czmq::{ZMsg, ZSock, SocketType, ZSys}; use std::cell::RefCell; use std::rc::Rc; use std::sync::{Arc, RwLock}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use super::*; use super::{TimedChunk, Timer}; use tempfile::tempfile; #[test] fn test_arbitrator_new() { ZSys::init(); assert!(Arbitrator::new(ZSock::new(SocketType::PAIR), 0).is_ok()); } #[test] fn test_arbitrator_queue_release() { ZSys::init(); let chunk = Chunk::new(Rc::new(RefCell::new(tempfile().unwrap())), 0); let mut arbitrator = Arbitrator::new(ZSock::new(SocketType::ROUTER), 1).unwrap(); assert!(arbitrator.queue(&chunk, "abc".as_bytes()).is_ok()); assert_eq!(arbitrator.queue.read().unwrap().len(), 1); assert_eq!(arbitrator.slots, 0); assert!(arbitrator.release(&chunk, "abc".as_bytes()).is_ok()); assert_eq!(arbitrator.queue.read().unwrap().len(), 0); assert_eq!(arbitrator.slots, 1); } #[test] fn test_arbitrator_request() { ZSys::init(); let (mut client, router) = ZSys::create_pipe().unwrap(); client.set_rcvtimeo(Some(500)); let (comm, thread) = ZSys::create_pipe().unwrap(); let chunks = vec![ TimedChunk::new("abc".as_bytes(), 0), TimedChunk::new("abc".as_bytes(), 1), TimedChunk::new("abc".as_bytes(), 2), TimedChunk::new("def".as_bytes(), 0), TimedChunk::new("def".as_bytes(), 1), TimedChunk::new("def".as_bytes(), 2), ]; { let mut arbitrator = Arbitrator { router: router, queue: Arc::new(RwLock::new(chunks)), timer_handle: None, timer_comm: comm, slots: 3, }; arbitrator.request().unwrap(); for x in 0..3 { let msg = ZMsg::recv(&mut client).unwrap(); assert_eq!(&msg.popstr().unwrap().unwrap(), "abc"); assert_eq!(&msg.popstr().unwrap().unwrap(), "CHUNK"); assert_eq!(msg.popstr().unwrap().unwrap(), x.to_string()); } assert!(client.recv_str().is_err()); let chunk = Chunk::new(Rc::new(RefCell::new(tempfile().unwrap())), 0); arbitrator.release(&chunk, "abc".as_bytes()).unwrap(); arbitrator.request().unwrap(); let msg = ZMsg::recv(&mut client).unwrap(); assert_eq!(&msg.popstr().unwrap().unwrap(), "def"); assert_eq!(&msg.popstr().unwrap().unwrap(), "CHUNK"); assert_eq!(msg.popstr().unwrap().unwrap(), "0"); } thread.wait().unwrap(); } #[test] fn test_timer_new() { ZSys::init(); assert!(Timer::new(ZSock::new(SocketType::REQ), Arc::new(RwLock::new(Vec::new()))).is_ok()); } #[test] fn test_timer_run() { ZSys::init(); let (mut client, server) = ZSys::create_pipe().unwrap(); let (comm, thread) = ZSys::create_pipe().unwrap(); client.set_rcvtimeo(Some(1500)); thread.set_rcvtimeo(Some(1000)); let mut c = TimedChunk::new("abc".as_bytes(), 0); c.start(); let timer = Timer { chunks: Arc::new(RwLock::new(vec![ c, ])), sink: server, comm: thread, }; let handle = spawn(|| timer.run()); let msg = ZMsg::recv(&mut client).unwrap(); assert_eq!(msg.popstr().unwrap().unwrap(), "abc"); assert_eq!(msg.popstr().unwrap().unwrap(), "0"); assert_eq!(msg.popstr().unwrap().unwrap(), "0"); comm.signal(0).unwrap(); handle.join().unwrap(); } #[test] fn test_chunk_is_expired() { let timed = TimedChunk { router_id: vec![97, 98, 99], index: 0, timestamp: Some(Instant::now()), }; sleep(Duration::from_secs(1)); assert!(timed.is_expired()); } }
}) }
random_line_split
generic-functions-nested.rs
// Copyright 2013-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-android: FIXME(#10381) // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print x // gdb-check:$1 = -1 // gdb-command:print y // gdb-check:$2 = 1 // gdb-command:continue // gdb-command:print x // gdb-check:$3 = -1 // gdb-command:print y // gdb-check:$4 = 2.5 // gdb-command:continue // gdb-command:print x // gdb-check:$5 = -2.5 // gdb-command:print y // gdb-check:$6 = 1 // gdb-command:continue // gdb-command:print x // gdb-check:$7 = -2.5 // gdb-command:print y // gdb-check:$8 = 2.5 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print x // lldb-check:[...]$0 = -1 // lldb-command:print y // lldb-check:[...]$1 = 1
// lldb-command:print x // lldb-check:[...]$2 = -1 // lldb-command:print y // lldb-check:[...]$3 = 2.5 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$4 = -2.5 // lldb-command:print y // lldb-check:[...]$5 = 1 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$6 = -2.5 // lldb-command:print y // lldb-check:[...]$7 = 2.5 // lldb-command:continue #![omit_gdb_pretty_printer_section] fn outer<TA: Clone>(a: TA) { inner(a.clone(), 1); inner(a.clone(), 2.5f64); fn inner<TX, TY>(x: TX, y: TY) { zzz(); // #break } } fn main() { outer(-1); outer(-2.5f64); } fn zzz() { () }
// lldb-command:continue
random_line_split
generic-functions-nested.rs
// Copyright 2013-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-android: FIXME(#10381) // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print x // gdb-check:$1 = -1 // gdb-command:print y // gdb-check:$2 = 1 // gdb-command:continue // gdb-command:print x // gdb-check:$3 = -1 // gdb-command:print y // gdb-check:$4 = 2.5 // gdb-command:continue // gdb-command:print x // gdb-check:$5 = -2.5 // gdb-command:print y // gdb-check:$6 = 1 // gdb-command:continue // gdb-command:print x // gdb-check:$7 = -2.5 // gdb-command:print y // gdb-check:$8 = 2.5 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print x // lldb-check:[...]$0 = -1 // lldb-command:print y // lldb-check:[...]$1 = 1 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$2 = -1 // lldb-command:print y // lldb-check:[...]$3 = 2.5 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$4 = -2.5 // lldb-command:print y // lldb-check:[...]$5 = 1 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$6 = -2.5 // lldb-command:print y // lldb-check:[...]$7 = 2.5 // lldb-command:continue #![omit_gdb_pretty_printer_section] fn outer<TA: Clone>(a: TA) { inner(a.clone(), 1); inner(a.clone(), 2.5f64); fn inner<TX, TY>(x: TX, y: TY) { zzz(); // #break } } fn main()
fn zzz() { () }
{ outer(-1); outer(-2.5f64); }
identifier_body
generic-functions-nested.rs
// Copyright 2013-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-android: FIXME(#10381) // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print x // gdb-check:$1 = -1 // gdb-command:print y // gdb-check:$2 = 1 // gdb-command:continue // gdb-command:print x // gdb-check:$3 = -1 // gdb-command:print y // gdb-check:$4 = 2.5 // gdb-command:continue // gdb-command:print x // gdb-check:$5 = -2.5 // gdb-command:print y // gdb-check:$6 = 1 // gdb-command:continue // gdb-command:print x // gdb-check:$7 = -2.5 // gdb-command:print y // gdb-check:$8 = 2.5 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print x // lldb-check:[...]$0 = -1 // lldb-command:print y // lldb-check:[...]$1 = 1 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$2 = -1 // lldb-command:print y // lldb-check:[...]$3 = 2.5 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$4 = -2.5 // lldb-command:print y // lldb-check:[...]$5 = 1 // lldb-command:continue // lldb-command:print x // lldb-check:[...]$6 = -2.5 // lldb-command:print y // lldb-check:[...]$7 = 2.5 // lldb-command:continue #![omit_gdb_pretty_printer_section] fn outer<TA: Clone>(a: TA) { inner(a.clone(), 1); inner(a.clone(), 2.5f64); fn inner<TX, TY>(x: TX, y: TY) { zzz(); // #break } } fn main() { outer(-1); outer(-2.5f64); } fn
() { () }
zzz
identifier_name
union.rs
use racer_testutils::*; #[test] fn completes_union() { let src = r#" #[repr(C)] union MyUnion { f1: u32, f2: f32, } let u: MyU~ "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "MyUnion"); } #[test] fn completes_maybe_uninit()
#[test] fn completes_union_member() { let src = r#" #[repr(C)] union MyUnion { uint_member: u32, float_member: f32, } impl MyUnion { fn new() -> Self { Self { uint_member: 10 } } } let uni = unsafe { MyUnion::new().uint~ }; "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "uint_member"); } #[test] fn completes_union_method() { let src = r#" #[repr(C)] union MyUnion { uint_member: u32, float_member: f32, } impl MyUnion { fn new() -> Self { Self { uint_member: 10 } } fn double(self) -> Self { Self { uint_member: unsafe { self.uint_member * 2 } } } } let uni = unsafe { MyUnion::new().dou~ }; "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "double"); }
{ let src = r#" let u: std::mem::Mayb~ "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "MaybeUninit"); }
identifier_body
union.rs
use racer_testutils::*; #[test] fn
() { let src = r#" #[repr(C)] union MyUnion { f1: u32, f2: f32, } let u: MyU~ "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "MyUnion"); } #[test] fn completes_maybe_uninit() { let src = r#" let u: std::mem::Mayb~ "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "MaybeUninit"); } #[test] fn completes_union_member() { let src = r#" #[repr(C)] union MyUnion { uint_member: u32, float_member: f32, } impl MyUnion { fn new() -> Self { Self { uint_member: 10 } } } let uni = unsafe { MyUnion::new().uint~ }; "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "uint_member"); } #[test] fn completes_union_method() { let src = r#" #[repr(C)] union MyUnion { uint_member: u32, float_member: f32, } impl MyUnion { fn new() -> Self { Self { uint_member: 10 } } fn double(self) -> Self { Self { uint_member: unsafe { self.uint_member * 2 } } } } let uni = unsafe { MyUnion::new().dou~ }; "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "double"); }
completes_union
identifier_name
union.rs
use racer_testutils::*; #[test] fn completes_union() { let src = r#" #[repr(C)] union MyUnion { f1: u32, f2: f32, } let u: MyU~ "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "MyUnion"); } #[test] fn completes_maybe_uninit() { let src = r#" let u: std::mem::Mayb~ "#; let got = get_only_completion(src, None);
} #[test] fn completes_union_member() { let src = r#" #[repr(C)] union MyUnion { uint_member: u32, float_member: f32, } impl MyUnion { fn new() -> Self { Self { uint_member: 10 } } } let uni = unsafe { MyUnion::new().uint~ }; "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "uint_member"); } #[test] fn completes_union_method() { let src = r#" #[repr(C)] union MyUnion { uint_member: u32, float_member: f32, } impl MyUnion { fn new() -> Self { Self { uint_member: 10 } } fn double(self) -> Self { Self { uint_member: unsafe { self.uint_member * 2 } } } } let uni = unsafe { MyUnion::new().dou~ }; "#; let got = get_only_completion(src, None); assert_eq!(got.matchstr, "double"); }
assert_eq!(got.matchstr, "MaybeUninit");
random_line_split
method_definitions.rs
struct Point<T> { x: T, y: T, } /* Declare `impl<T>` to specify we are implementing * methods on type `Point<T>` */ impl<T> Point<T> {
&self.x } // fn distance_from_origin<f32>(&self) -> f32 { // (self.x.powi(2) + self.y.powi(2)).sqrt() // } } struct PointMixed<T, U> { x: T, y: U, } impl<T, U> PointMixed<T, U> { // `V` and `W` types are only relevant to the method definition fn mixup<V, W>(self, other: PointMixed<V, W>) -> PointMixed<T, W> { PointMixed { x: self.x, y: other.y, } } } pub fn run() { let p = Point { x: 5, y: 10 }; println!("Point with p.x = {}", p.x()); // println!("p.distance_from_origin = {}", p.distance_from_origin()); let p1 = PointMixed { x: 5, y: 10.4 }; let p2 = PointMixed { x: "Hello", y: 'c'}; // String Slice + char let p3 = p1.mixup(p2); println!("PointMixed p3.x = {}, p3.y = {}", p3.x, p3.y); }
/* Getter method `x` returns "reference" to the * data in field type `T` */ fn x(&self) -> &T {
random_line_split
method_definitions.rs
struct Point<T> { x: T, y: T, } /* Declare `impl<T>` to specify we are implementing * methods on type `Point<T>` */ impl<T> Point<T> { /* Getter method `x` returns "reference" to the * data in field type `T` */ fn
(&self) -> &T { &self.x } // fn distance_from_origin<f32>(&self) -> f32 { // (self.x.powi(2) + self.y.powi(2)).sqrt() // } } struct PointMixed<T, U> { x: T, y: U, } impl<T, U> PointMixed<T, U> { // `V` and `W` types are only relevant to the method definition fn mixup<V, W>(self, other: PointMixed<V, W>) -> PointMixed<T, W> { PointMixed { x: self.x, y: other.y, } } } pub fn run() { let p = Point { x: 5, y: 10 }; println!("Point with p.x = {}", p.x()); // println!("p.distance_from_origin = {}", p.distance_from_origin()); let p1 = PointMixed { x: 5, y: 10.4 }; let p2 = PointMixed { x: "Hello", y: 'c'}; // String Slice + char let p3 = p1.mixup(p2); println!("PointMixed p3.x = {}, p3.y = {}", p3.x, p3.y); }
x
identifier_name
events.rs
#[derive(Clone, Debug, Copy)] pub enum Event { /// The size of the window has changed. Resized(u32, u32), /// The position of the window has changed. Moved(i32, i32), /// The window has been closed. Closed, /// The window received a unicode character. ReceivedCharacter(char), /// The window gained or lost focus. /// /// The parameter is true if the window has gained focus, and false if it has lost focus. Focused(bool), /// An event from the keyboard has been received. KeyboardInput(ElementState, ScanCode, Option<VirtualKeyCode>), /// The cursor has moved on the window. /// /// The parameter are the (x,y) coords in pixels relative to the top-left corner of the window. MouseMoved((i32, i32)), /// Returns the horizontal and vertical mouse scrolling. /// /// A positive value indicates that the wheel was rotated forward, away from the user; /// a negative value indicates that the wheel was rotated backward, toward the user. MouseWheel(f64, f64), /// An event from the mouse has been received. MouseInput(ElementState, MouseButton), /// The event loop was woken up by another thread. Awakened, /// The window needs to be redrawn. Refresh, } pub type ScanCode = u8; #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum
{ Pressed, Released, } #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum MouseButton { Left, Right, Middle, Other(u8), } #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum VirtualKeyCode { /// The '1' key over the letters. Key1, /// The '2' key over the letters. Key2, /// The '3' key over the letters. Key3, /// The '4' key over the letters. Key4, /// The '5' key over the letters. Key5, /// The '6' key over the letters. Key6, /// The '7' key over the letters. Key7, /// The '8' key over the letters. Key8, /// The '9' key over the letters. Key9, /// The '0' key over the 'O' and 'P' keys. Key0, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, /// The Escape key, next to F1. Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, /// Print Screen/SysRq. Snapshot, /// Scroll Lock. Scroll, /// Pause/Break key, next to Scroll lock. Pause, /// `Insert`, next to Backspace. Insert, Home, Delete, End, PageDown, PageUp, Left, Up, Right, Down, /// The Backspace key, right over Enter. // TODO: rename Back, /// The Enter key. Return, /// The space bar. Space, Numlock, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, AbntC1, AbntC2, Add, Apostrophe, Apps, At, Ax, Backslash, Calculator, Capital, Colon, Comma, Convert, Decimal, Divide, Equals, Grave, Kana, Kanji, LAlt, LBracket, LControl, LMenu, LShift, LWin, Mail, MediaSelect, MediaStop, Minus, Multiply, Mute, MyComputer, NextTrack, NoConvert, NumpadComma, NumpadEnter, NumpadEquals, OEM102, Period, Playpause, Power, Prevtrack, RAlt, RBracket, RControl, RMenu, RShift, RWin, Semicolon, Slash, Sleep, Stop, Subtract, Sysrq, Tab, Underline, Unlabeled, VolumeDown, VolumeUp, Wake, Webback, WebFavorites, WebForward, WebHome, WebRefresh, WebSearch, WebStop, Yen, }
ElementState
identifier_name
events.rs
#[derive(Clone, Debug, Copy)] pub enum Event { /// The size of the window has changed. Resized(u32, u32), /// The position of the window has changed. Moved(i32, i32), /// The window has been closed. Closed, /// The window received a unicode character. ReceivedCharacter(char), /// The window gained or lost focus. /// /// The parameter is true if the window has gained focus, and false if it has lost focus. Focused(bool), /// An event from the keyboard has been received. KeyboardInput(ElementState, ScanCode, Option<VirtualKeyCode>), /// The cursor has moved on the window. /// /// The parameter are the (x,y) coords in pixels relative to the top-left corner of the window. MouseMoved((i32, i32)), /// Returns the horizontal and vertical mouse scrolling. /// /// A positive value indicates that the wheel was rotated forward, away from the user; /// a negative value indicates that the wheel was rotated backward, toward the user. MouseWheel(f64, f64), /// An event from the mouse has been received. MouseInput(ElementState, MouseButton), /// The event loop was woken up by another thread. Awakened, /// The window needs to be redrawn. Refresh, } pub type ScanCode = u8; #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum ElementState { Pressed, Released, } #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum MouseButton { Left, Right, Middle, Other(u8), } #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] pub enum VirtualKeyCode { /// The '1' key over the letters. Key1, /// The '2' key over the letters. Key2, /// The '3' key over the letters. Key3, /// The '4' key over the letters. Key4, /// The '5' key over the letters. Key5, /// The '6' key over the letters. Key6, /// The '7' key over the letters. Key7, /// The '8' key over the letters. Key8, /// The '9' key over the letters. Key9, /// The '0' key over the 'O' and 'P' keys. Key0, A, B,
G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, /// The Escape key, next to F1. Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, /// Print Screen/SysRq. Snapshot, /// Scroll Lock. Scroll, /// Pause/Break key, next to Scroll lock. Pause, /// `Insert`, next to Backspace. Insert, Home, Delete, End, PageDown, PageUp, Left, Up, Right, Down, /// The Backspace key, right over Enter. // TODO: rename Back, /// The Enter key. Return, /// The space bar. Space, Numlock, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, AbntC1, AbntC2, Add, Apostrophe, Apps, At, Ax, Backslash, Calculator, Capital, Colon, Comma, Convert, Decimal, Divide, Equals, Grave, Kana, Kanji, LAlt, LBracket, LControl, LMenu, LShift, LWin, Mail, MediaSelect, MediaStop, Minus, Multiply, Mute, MyComputer, NextTrack, NoConvert, NumpadComma, NumpadEnter, NumpadEquals, OEM102, Period, Playpause, Power, Prevtrack, RAlt, RBracket, RControl, RMenu, RShift, RWin, Semicolon, Slash, Sleep, Stop, Subtract, Sysrq, Tab, Underline, Unlabeled, VolumeDown, VolumeUp, Wake, Webback, WebFavorites, WebForward, WebHome, WebRefresh, WebSearch, WebStop, Yen, }
C, D, E, F,
random_line_split
mod.rs
use std::default::Default; use std::fs::File;
use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn run() -> i32 { let mut container: String = "".to_string(); let mut settings: Settings = Default::default(); { let mut ap = ArgumentParser::new(); ap.set_description(" A tool which versions containers "); ap.refer(&mut container) .add_argument("container", Store, "A container to version") .required(); ap.refer(&mut settings) .add_option(&["--settings"], Store, "User settings for the container build"); match ap.parse_args() { Ok(()) => {} Err(0) => return 0, Err(_) => return 122, } } // TODO(tailhook) read also config from /work/.vagga/vagga.yaml let cfg = read_config(&Path::new("/work/vagga.yaml")).ok() .expect("Error parsing configuration file"); // TODO let cont = cfg.containers.get(&container) .expect("Container not found"); // TODO let hash = match version::long_version(&cont, &cfg) { Ok(hash) => hash, Err((cmd, e)) => { error!("Error versioning command {}: {}", cmd, e); return 1; } }; debug!("Got hash {:?}", hash); match unsafe { File::from_raw_fd(3) }.write_all(hash.as_bytes()) { Ok(()) => {} Err(e) => { error!("Error writing hash: {}", e); return 1; } } return 0; } pub fn main() { let val = run(); exit(val); }
use std::path::Path;
random_line_split
mod.rs
use std::default::Default; use std::fs::File; use std::path::Path; use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn run() -> i32 { let mut container: String = "".to_string(); let mut settings: Settings = Default::default(); { let mut ap = ArgumentParser::new(); ap.set_description(" A tool which versions containers "); ap.refer(&mut container) .add_argument("container", Store, "A container to version") .required(); ap.refer(&mut settings) .add_option(&["--settings"], Store, "User settings for the container build"); match ap.parse_args() { Ok(()) => {} Err(0) => return 0, Err(_) => return 122, } } // TODO(tailhook) read also config from /work/.vagga/vagga.yaml let cfg = read_config(&Path::new("/work/vagga.yaml")).ok() .expect("Error parsing configuration file"); // TODO let cont = cfg.containers.get(&container) .expect("Container not found"); // TODO let hash = match version::long_version(&cont, &cfg) { Ok(hash) => hash, Err((cmd, e)) => { error!("Error versioning command {}: {}", cmd, e); return 1; } }; debug!("Got hash {:?}", hash); match unsafe { File::from_raw_fd(3) }.write_all(hash.as_bytes()) { Ok(()) =>
Err(e) => { error!("Error writing hash: {}", e); return 1; } } return 0; } pub fn main() { let val = run(); exit(val); }
{}
conditional_block
mod.rs
use std::default::Default; use std::fs::File; use std::path::Path; use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn run() -> i32
} // TODO(tailhook) read also config from /work/.vagga/vagga.yaml let cfg = read_config(&Path::new("/work/vagga.yaml")).ok() .expect("Error parsing configuration file"); // TODO let cont = cfg.containers.get(&container) .expect("Container not found"); // TODO let hash = match version::long_version(&cont, &cfg) { Ok(hash) => hash, Err((cmd, e)) => { error!("Error versioning command {}: {}", cmd, e); return 1; } }; debug!("Got hash {:?}", hash); match unsafe { File::from_raw_fd(3) }.write_all(hash.as_bytes()) { Ok(()) => {} Err(e) => { error!("Error writing hash: {}", e); return 1; } } return 0; } pub fn main() { let val = run(); exit(val); }
{ let mut container: String = "".to_string(); let mut settings: Settings = Default::default(); { let mut ap = ArgumentParser::new(); ap.set_description(" A tool which versions containers "); ap.refer(&mut container) .add_argument("container", Store, "A container to version") .required(); ap.refer(&mut settings) .add_option(&["--settings"], Store, "User settings for the container build"); match ap.parse_args() { Ok(()) => {} Err(0) => return 0, Err(_) => return 122, }
identifier_body
mod.rs
use std::default::Default; use std::fs::File; use std::path::Path; use std::process::exit; use std::io::{Write}; use std::os::unix::io::FromRawFd; use argparse::{ArgumentParser, Store}; use config::read_config; use config::Settings; mod version; pub use self::version::{short_version, Error}; pub fn
() -> i32 { let mut container: String = "".to_string(); let mut settings: Settings = Default::default(); { let mut ap = ArgumentParser::new(); ap.set_description(" A tool which versions containers "); ap.refer(&mut container) .add_argument("container", Store, "A container to version") .required(); ap.refer(&mut settings) .add_option(&["--settings"], Store, "User settings for the container build"); match ap.parse_args() { Ok(()) => {} Err(0) => return 0, Err(_) => return 122, } } // TODO(tailhook) read also config from /work/.vagga/vagga.yaml let cfg = read_config(&Path::new("/work/vagga.yaml")).ok() .expect("Error parsing configuration file"); // TODO let cont = cfg.containers.get(&container) .expect("Container not found"); // TODO let hash = match version::long_version(&cont, &cfg) { Ok(hash) => hash, Err((cmd, e)) => { error!("Error versioning command {}: {}", cmd, e); return 1; } }; debug!("Got hash {:?}", hash); match unsafe { File::from_raw_fd(3) }.write_all(hash.as_bytes()) { Ok(()) => {} Err(e) => { error!("Error writing hash: {}", e); return 1; } } return 0; } pub fn main() { let val = run(); exit(val); }
run
identifier_name
actorref.rs
///A reference to a spawned actorpub trait ActorRef { } pub trait ActorRef{ } ///Spawned actor reference with port and channel pub struct ActorRefWithStream<P2, C1> { port: P2, chan: C1, } impl <T1: Send, T2: Send, C1: GenericChan<T1>, P2: GenericPort<T2>> ActorRef for ActorRefWithStream<P2, C1> {} ///Spawned actor reference with channel pub struct
<C1>{ chan: C1, } impl<T1: Send, C1: GenericChan<T1>> ActorRef for ActorRefWithChan<C1>{} ///Spawned actor reference with port pub struct ActorRefWithPort<P2>{ port: P2, } impl<T2: Send, P2: GenericPort<T2>> ActorRef for ActorRefWithPort<P2>{} ///Spawned actor reference with no port and channel pub struct ActorRefWithoutPortAndChan; impl ActorRef for ActorRefWithoutPortAndChan{}
ActorRefWithChan
identifier_name
actorref.rs
///A reference to a spawned actorpub trait ActorRef { } pub trait ActorRef{ } ///Spawned actor reference with port and channel pub struct ActorRefWithStream<P2, C1> { port: P2, chan: C1,
} impl <T1: Send, T2: Send, C1: GenericChan<T1>, P2: GenericPort<T2>> ActorRef for ActorRefWithStream<P2, C1> {} ///Spawned actor reference with channel pub struct ActorRefWithChan<C1>{ chan: C1, } impl<T1: Send, C1: GenericChan<T1>> ActorRef for ActorRefWithChan<C1>{} ///Spawned actor reference with port pub struct ActorRefWithPort<P2>{ port: P2, } impl<T2: Send, P2: GenericPort<T2>> ActorRef for ActorRefWithPort<P2>{} ///Spawned actor reference with no port and channel pub struct ActorRefWithoutPortAndChan; impl ActorRef for ActorRefWithoutPortAndChan{}
random_line_split
phantom-data-is-structurally-matchable.rs
// run-pass // This file checks that `PhantomData` is considered structurally matchable. use std::marker::PhantomData; fn main() { let mut count = 0; // A type which is not structurally matchable: struct NotSM; // And one that is: #[derive(PartialEq, Eq)] struct SM; // Check that SM is #[structural_match]: const CSM: SM = SM; match SM { CSM => count += 1, }; // Check that PhantomData<T> is #[structural_match] even if T is not. const CPD1: PhantomData<NotSM> = PhantomData; match PhantomData { CPD1 => count += 1, }; // Check that PhantomData<T> is #[structural_match] when T is. const CPD2: PhantomData<SM> = PhantomData; match PhantomData { CPD2 => count += 1, }; // Check that a type which has a PhantomData is `#[structural_match]`. #[derive(PartialEq, Eq, Default)] struct
{ alpha: PhantomData<NotSM>, beta: PhantomData<SM>, } const CFOO: Foo = Foo { alpha: PhantomData, beta: PhantomData, }; match Foo::default() { CFOO => count += 1, }; // Final count must be 4 now if all assert_eq!(count, 4); }
Foo
identifier_name
phantom-data-is-structurally-matchable.rs
// run-pass // This file checks that `PhantomData` is considered structurally matchable. use std::marker::PhantomData; fn main()
}; // Check that PhantomData<T> is #[structural_match] when T is. const CPD2: PhantomData<SM> = PhantomData; match PhantomData { CPD2 => count += 1, }; // Check that a type which has a PhantomData is `#[structural_match]`. #[derive(PartialEq, Eq, Default)] struct Foo { alpha: PhantomData<NotSM>, beta: PhantomData<SM>, } const CFOO: Foo = Foo { alpha: PhantomData, beta: PhantomData, }; match Foo::default() { CFOO => count += 1, }; // Final count must be 4 now if all assert_eq!(count, 4); }
{ let mut count = 0; // A type which is not structurally matchable: struct NotSM; // And one that is: #[derive(PartialEq, Eq)] struct SM; // Check that SM is #[structural_match]: const CSM: SM = SM; match SM { CSM => count += 1, }; // Check that PhantomData<T> is #[structural_match] even if T is not. const CPD1: PhantomData<NotSM> = PhantomData; match PhantomData { CPD1 => count += 1,
identifier_body
phantom-data-is-structurally-matchable.rs
// run-pass // This file checks that `PhantomData` is considered structurally matchable. use std::marker::PhantomData; fn main() { let mut count = 0; // A type which is not structurally matchable: struct NotSM; // And one that is: #[derive(PartialEq, Eq)] struct SM; // Check that SM is #[structural_match]: const CSM: SM = SM; match SM { CSM => count += 1, }; // Check that PhantomData<T> is #[structural_match] even if T is not. const CPD1: PhantomData<NotSM> = PhantomData; match PhantomData { CPD1 => count += 1, }; // Check that PhantomData<T> is #[structural_match] when T is. const CPD2: PhantomData<SM> = PhantomData; match PhantomData { CPD2 => count += 1, }; // Check that a type which has a PhantomData is `#[structural_match]`. #[derive(PartialEq, Eq, Default)] struct Foo {
alpha: PhantomData, beta: PhantomData, }; match Foo::default() { CFOO => count += 1, }; // Final count must be 4 now if all assert_eq!(count, 4); }
alpha: PhantomData<NotSM>, beta: PhantomData<SM>, } const CFOO: Foo = Foo {
random_line_split
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, expected: doc::Record) { let vm = new_vm(); let (expr, typ) = vm.typecheck_str("basic", module, None).unwrap(); let (meta, _) = metadata(&vm.get_env(), &expr.expr()); let out = doc::record( "basic", &typ, &Default::default(), &<() as gluon::base::source::Source>::new(""), &meta, ); assert_eq!(out, expected,); } #[test] fn
() { let module = r#" /// This is the test function let test x = x { test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![doc::Field { name: "test".to_string(), args: vec![doc::Argument { implicit: false, name: "x".to_string(), }], typ: handlebars::html_escape("forall a. a -> a"), attributes: "".to_string(), comment: "This is the test function".to_string(), definition_line: None, }], }, ); } #[test] fn doc_hidden() { let module = r#" #[doc(hidden)] type Test = Int #[doc(hidden)] let test x = x { Test, test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![], }, ); } #[test] fn check_links() { let _ = env_logger::try_init(); let out = Path::new("../target/doc_test"); if out.exists() { fs::remove_dir_all(out).unwrap_or_else(|err| panic!("{}", err)); } doc::generate_for_path(&new_vm(), "../std", out).unwrap_or_else(|err| panic!("{}", err)); let out = fs::canonicalize(out).unwrap(); let errors = cargo_deadlinks::unavailable_urls( &out, &cargo_deadlinks::CheckContext { check_http: true }, ) .collect::<Vec<_>>(); assert!(errors.is_empty(), "{}", errors.iter().format("\n")); }
basic
identifier_name
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, expected: doc::Record) { let vm = new_vm(); let (expr, typ) = vm.typecheck_str("basic", module, None).unwrap(); let (meta, _) = metadata(&vm.get_env(), &expr.expr()); let out = doc::record( "basic", &typ, &Default::default(), &<() as gluon::base::source::Source>::new(""), &meta, ); assert_eq!(out, expected,); } #[test] fn basic() { let module = r#" /// This is the test function let test x = x { test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![doc::Field { name: "test".to_string(), args: vec![doc::Argument { implicit: false, name: "x".to_string(), }], typ: handlebars::html_escape("forall a. a -> a"), attributes: "".to_string(), comment: "This is the test function".to_string(), definition_line: None, }], }, ); } #[test] fn doc_hidden() { let module = r#" #[doc(hidden)] type Test = Int #[doc(hidden)] let test x = x { Test, test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![], }, ); } #[test] fn check_links() { let _ = env_logger::try_init(); let out = Path::new("../target/doc_test"); if out.exists()
doc::generate_for_path(&new_vm(), "../std", out).unwrap_or_else(|err| panic!("{}", err)); let out = fs::canonicalize(out).unwrap(); let errors = cargo_deadlinks::unavailable_urls( &out, &cargo_deadlinks::CheckContext { check_http: true }, ) .collect::<Vec<_>>(); assert!(errors.is_empty(), "{}", errors.iter().format("\n")); }
{ fs::remove_dir_all(out).unwrap_or_else(|err| panic!("{}", err)); }
conditional_block
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, expected: doc::Record) { let vm = new_vm(); let (expr, typ) = vm.typecheck_str("basic", module, None).unwrap(); let (meta, _) = metadata(&vm.get_env(), &expr.expr()); let out = doc::record( "basic", &typ, &Default::default(), &<() as gluon::base::source::Source>::new(""), &meta, ); assert_eq!(out, expected,); } #[test] fn basic()
}], }, ); } #[test] fn doc_hidden() { let module = r#" #[doc(hidden)] type Test = Int #[doc(hidden)] let test x = x { Test, test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![], }, ); } #[test] fn check_links() { let _ = env_logger::try_init(); let out = Path::new("../target/doc_test"); if out.exists() { fs::remove_dir_all(out).unwrap_or_else(|err| panic!("{}", err)); } doc::generate_for_path(&new_vm(), "../std", out).unwrap_or_else(|err| panic!("{}", err)); let out = fs::canonicalize(out).unwrap(); let errors = cargo_deadlinks::unavailable_urls( &out, &cargo_deadlinks::CheckContext { check_http: true }, ) .collect::<Vec<_>>(); assert!(errors.is_empty(), "{}", errors.iter().format("\n")); }
{ let module = r#" /// This is the test function let test x = x { test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![doc::Field { name: "test".to_string(), args: vec![doc::Argument { implicit: false, name: "x".to_string(), }], typ: handlebars::html_escape("forall a . a -> a"), attributes: "".to_string(), comment: "This is the test function".to_string(), definition_line: None,
identifier_body
doc.rs
use std::{fs, path::Path}; use {itertools::Itertools, rayon::prelude::*}; use gluon_doc as doc; use gluon::{check::metadata::metadata, RootedThread, ThreadExt}; fn new_vm() -> RootedThread { ::gluon::VmBuilder::new() .import_paths(Some(vec!["..".into()])) .build() } fn doc_check(module: &str, expected: doc::Record) { let vm = new_vm(); let (expr, typ) = vm.typecheck_str("basic", module, None).unwrap(); let (meta, _) = metadata(&vm.get_env(), &expr.expr()); let out = doc::record( "basic", &typ, &Default::default(), &<() as gluon::base::source::Source>::new(""), &meta, ); assert_eq!(out, expected,); } #[test] fn basic() { let module = r#" /// This is the test function let test x = x { test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![doc::Field { name: "test".to_string(), args: vec![doc::Argument { implicit: false, name: "x".to_string(), }], typ: handlebars::html_escape("forall a. a -> a"), attributes: "".to_string(), comment: "This is the test function".to_string(), definition_line: None, }], }, ); } #[test] fn doc_hidden() { let module = r#" #[doc(hidden)] type Test = Int #[doc(hidden)] let test x = x { Test, test } "#; doc_check( module, doc::Record { types: Vec::new(), values: vec![], }, ); }
#[test] fn check_links() { let _ = env_logger::try_init(); let out = Path::new("../target/doc_test"); if out.exists() { fs::remove_dir_all(out).unwrap_or_else(|err| panic!("{}", err)); } doc::generate_for_path(&new_vm(), "../std", out).unwrap_or_else(|err| panic!("{}", err)); let out = fs::canonicalize(out).unwrap(); let errors = cargo_deadlinks::unavailable_urls( &out, &cargo_deadlinks::CheckContext { check_http: true }, ) .collect::<Vec<_>>(); assert!(errors.is_empty(), "{}", errors.iter().format("\n")); }
random_line_split
requests.rs
use std::slice::Iter; use super::{ Request }; pub struct Requests<'a> { request: Option<&'a Request>, requests: Iter<'a, Request>, } impl<'a> Requests<'a> { pub fn new(request: &'a Request, requests: &'a Vec<Request>) -> Requests<'a> { Requests { request: Some(request), requests: requests.iter(), } } } impl<'a> Iterator for Requests<'a> { type Item = &'a Request; fn next(&mut self) -> Option<&'a Request> { match (self.requests.next(), self.request) { (None, None) => None, (None, request) =>
, (request, _) => request, } } fn size_hint(&self) -> (usize, Option<usize>) { match (self.request, self.requests.size_hint()) { (None, size_hint) => size_hint, (Some(_), (min, max)) => (min + 1, max.map(|max| max + 1)), } } }
{ self.request = None; request }
conditional_block
requests.rs
use std::slice::Iter; use super::{ Request };
} impl<'a> Requests<'a> { pub fn new(request: &'a Request, requests: &'a Vec<Request>) -> Requests<'a> { Requests { request: Some(request), requests: requests.iter(), } } } impl<'a> Iterator for Requests<'a> { type Item = &'a Request; fn next(&mut self) -> Option<&'a Request> { match (self.requests.next(), self.request) { (None, None) => None, (None, request) => { self.request = None; request }, (request, _) => request, } } fn size_hint(&self) -> (usize, Option<usize>) { match (self.request, self.requests.size_hint()) { (None, size_hint) => size_hint, (Some(_), (min, max)) => (min + 1, max.map(|max| max + 1)), } } }
pub struct Requests<'a> { request: Option<&'a Request>, requests: Iter<'a, Request>,
random_line_split
requests.rs
use std::slice::Iter; use super::{ Request }; pub struct Requests<'a> { request: Option<&'a Request>, requests: Iter<'a, Request>, } impl<'a> Requests<'a> { pub fn
(request: &'a Request, requests: &'a Vec<Request>) -> Requests<'a> { Requests { request: Some(request), requests: requests.iter(), } } } impl<'a> Iterator for Requests<'a> { type Item = &'a Request; fn next(&mut self) -> Option<&'a Request> { match (self.requests.next(), self.request) { (None, None) => None, (None, request) => { self.request = None; request }, (request, _) => request, } } fn size_hint(&self) -> (usize, Option<usize>) { match (self.request, self.requests.size_hint()) { (None, size_hint) => size_hint, (Some(_), (min, max)) => (min + 1, max.map(|max| max + 1)), } } }
new
identifier_name
newlambdas.rs
// Copyright 2012 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. // Tests for the new |args| expr lambda syntax fn f<F>(i: int, f: F) -> int where F: FnOnce(int) -> int { f(i) } fn g<G>(_g: G) where G: FnOnce() { } pub fn main() { assert_eq!(f(10, |a| a), 10);
assert_eq!(f(10, |a| a), 10); g(||{}); }
g(||());
random_line_split
newlambdas.rs
// Copyright 2012 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. // Tests for the new |args| expr lambda syntax fn f<F>(i: int, f: F) -> int where F: FnOnce(int) -> int { f(i) } fn g<G>(_g: G) where G: FnOnce() { } pub fn
() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(f(10, |a| a), 10); g(||{}); }
main
identifier_name
newlambdas.rs
// Copyright 2012 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. // Tests for the new |args| expr lambda syntax fn f<F>(i: int, f: F) -> int where F: FnOnce(int) -> int
fn g<G>(_g: G) where G: FnOnce() { } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(f(10, |a| a), 10); g(||{}); }
{ f(i) }
identifier_body
mod.rs
pass_name, tcx, mir_body, source_file, fn_sig_span, body_span, basic_coverage_blocks, coverage_counters: CoverageCounters::new(function_source_hash), } } fn inject_counters(&'a mut self) { let tcx = self.tcx; let mir_source = self.mir_body.source; let def_id = mir_source.def_id(); let fn_sig_span = self.fn_sig_span; let body_span = self.body_span; let mut graphviz_data = debug::GraphvizData::new(); let mut debug_used_expressions = debug::UsedExpressions::new(); let dump_mir = pretty::dump_enabled(tcx, self.pass_name, def_id); let dump_graphviz = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_graphviz; let dump_spanview = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_spanview.is_some(); if dump_graphviz { graphviz_data.enable(); self.coverage_counters.enable_debug(); } if dump_graphviz || level_enabled!(tracing::Level::DEBUG) { debug_used_expressions.enable(); } //////////////////////////////////////////////////// // Compute `CoverageSpan`s from the `CoverageGraph`. let coverage_spans = CoverageSpans::generate_coverage_spans( &self.mir_body, fn_sig_span, body_span, &self.basic_coverage_blocks, ); if dump_spanview { debug::dump_coverage_spanview( tcx, self.mir_body, &self.basic_coverage_blocks, self.pass_name, body_span, &coverage_spans, ); } //////////////////////////////////////////////////// // Create an optimized mix of `Counter`s and `Expression`s for the `CoverageGraph`. Ensure // every `CoverageSpan` has a `Counter` or `Expression` assigned to its `BasicCoverageBlock` // and all `Expression` dependencies (operands) are also generated, for any other // `BasicCoverageBlock`s not already associated with a `CoverageSpan`. // // Intermediate expressions (used to compute other `Expression` values), which have no // direct associate to any `BasicCoverageBlock`, are returned in the method `Result`. let intermediate_expressions_or_error = self .coverage_counters .make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans); let (result, intermediate_expressions) = match intermediate_expressions_or_error { Ok(intermediate_expressions) => { // If debugging, add any intermediate expressions (which are not associated with any // BCB) to the `debug_used_expressions` map. if debug_used_expressions.is_enabled() { for intermediate_expression in &intermediate_expressions { debug_used_expressions.add_expression_operands(intermediate_expression); } } //////////////////////////////////////////////////// // Remove the counter or edge counter from of each `CoverageSpan`s associated // `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR. // // `Coverage` statements injected from `CoverageSpan`s will include the code regions // (source code start and end positions) to be counted by the associated counter. // // These `CoverageSpan`-associated counters are removed from their associated // `BasicCoverageBlock`s so that the only remaining counters in the `CoverageGraph` // are indirect counters (to be injected next, without associated code regions). self.inject_coverage_span_counters( coverage_spans, &mut graphviz_data, &mut debug_used_expressions, ); //////////////////////////////////////////////////// // For any remaining `BasicCoverageBlock` counters (that were not associated with // any `CoverageSpan`), inject `Coverage` statements (_without_ code region `Span`s) // to ensure `BasicCoverageBlock` counters that other `Expression`s may depend on // are in fact counted, even though they don't directly contribute to counting // their own independent code region's coverage. self.inject_indirect_counters(&mut graphviz_data, &mut debug_used_expressions); // Intermediate expressions will be injected as the final step, after generating // debug output, if any. //////////////////////////////////////////////////// (Ok(()), intermediate_expressions) } Err(e) => (Err(e), Vec::new()), }; if graphviz_data.is_enabled() { // Even if there was an error, a partial CoverageGraph can still generate a useful // graphviz output. debug::dump_coverage_graphviz( tcx, self.mir_body, self.pass_name, &self.basic_coverage_blocks, &self.coverage_counters.debug_counters, &graphviz_data, &intermediate_expressions, &debug_used_expressions, ); } if let Err(e) = result { bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e) }; // Depending on current `debug_options()`, `alert_on_unused_expressions()` could panic, so // this check is performed as late as possible, to allow other debug output (logs and dump // files), which might be helpful in analyzing unused expressions, to still be generated. debug_used_expressions.alert_on_unused_expressions(&self.coverage_counters.debug_counters); //////////////////////////////////////////////////// // Finally, inject the intermediate expressions collected along the way. for intermediate_expression in intermediate_expressions { inject_intermediate_expression(self.mir_body, intermediate_expression); } } /// Inject a counter for each `CoverageSpan`. There can be multiple `CoverageSpan`s for a given /// BCB, but only one actual counter needs to be incremented per BCB. `bb_counters` maps each /// `bcb` to its `Counter`, when injected. Subsequent `CoverageSpan`s for a BCB that already has /// a `Counter` will inject an `Expression` instead, and compute its value by adding `ZERO` to /// the BCB `Counter` value. /// /// If debugging, add every BCB `Expression` associated with a `CoverageSpan`s to the /// `used_expression_operands` map. fn inject_coverage_span_counters( &mut self, coverage_spans: Vec<CoverageSpan>, graphviz_data: &mut debug::GraphvizData, debug_used_expressions: &mut debug::UsedExpressions, ) { let tcx = self.tcx; let source_map = tcx.sess.source_map(); let body_span = self.body_span; let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy()); let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes()); for covspan in coverage_spans { let bcb = covspan.bcb; let span = covspan.span; let counter_kind = if let Some(&counter_operand) = bcb_counters[bcb].as_ref() { self.coverage_counters.make_identity_counter(counter_operand) } else if let Some(counter_kind) = self.bcb_data_mut(bcb).take_counter() { bcb_counters[bcb] = Some(counter_kind.as_operand_id()); debug_used_expressions.add_expression_operands(&counter_kind); counter_kind } else { bug!("Every BasicCoverageBlock should have a Counter or Expression"); }; graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind); debug!( "Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})", file_name, self.source_file, source_map.span_to_diagnostic_string(span), source_map.span_to_diagnostic_string(body_span) ); inject_statement( self.mir_body, counter_kind, self.bcb_leader_bb(bcb), Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)), ); } } /// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the /// counter from the `CoverageSpan`s `BasicCoverageBlock`, removing it from the BCB in the /// process (via `take_counter()`). /// /// Any other counter associated with a `BasicCoverageBlock`, or its incoming edge, but not /// associated with a `CoverageSpan`, should only exist if the counter is an `Expression` /// dependency (one of the expression operands). Collect them, and inject the additional /// counters into the MIR, without a reportable coverage span. fn inject_indirect_counters( &mut self, graphviz_data: &mut debug::GraphvizData, debug_used_expressions: &mut debug::UsedExpressions, ) { let mut bcb_counters_without_direct_coverage_spans = Vec::new(); for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() { if let Some(counter_kind) = target_bcb_data.take_counter() { bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind)); } if let Some(edge_counters) = target_bcb_data.take_edge_counters() { for (from_bcb, counter_kind) in edge_counters { bcb_counters_without_direct_coverage_spans.push(( Some(from_bcb), target_bcb, counter_kind, )); } } } // If debug is enabled, validate that every BCB or edge counter not directly associated // with a coverage span is at least indirectly associated (it is a dependency of a BCB // counter that _is_ associated with a coverage span). debug_used_expressions.validate(&bcb_counters_without_direct_coverage_spans); for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans { debug_used_expressions.add_unused_expression_if_not_found( &counter_kind, edge_from_bcb, target_bcb, ); match counter_kind { CoverageKind::Counter {.. } => { let inject_to_bb = if let Some(from_bcb) = edge_from_bcb { // The MIR edge starts `from_bb` (the outgoing / last BasicBlock in // `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the // `target_bcb`; also called the `leader_bb`). let from_bb = self.bcb_last_bb(from_bcb); let to_bb = self.bcb_leader_bb(target_bcb); let new_bb = inject_edge_counter_basic_block(self.mir_body, from_bb, to_bb); graphviz_data.set_edge_counter(from_bcb, new_bb, &counter_kind); debug!( "Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \ BasicBlock {:?}, for unclaimed edge counter {}", edge_from_bcb, from_bb, target_bcb, to_bb, new_bb, self.format_counter(&counter_kind), ); new_bb } else { let target_bb = self.bcb_last_bb(target_bcb); graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind); debug!( "{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}", target_bcb, target_bb, self.format_counter(&counter_kind), ); target_bb }; inject_statement(self.mir_body, counter_kind, inject_to_bb, None); } CoverageKind::Expression {.. } => { inject_intermediate_expression(self.mir_body, counter_kind) } _ => bug!("CoverageKind should be a counter"), } } } #[inline] fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock { self.bcb_data(bcb).leader_bb() } #[inline] fn bcb_last_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock { self.bcb_data(bcb).last_bb() } #[inline] fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData { &self.basic_coverage_blocks[bcb] } #[inline] fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData { &mut self.basic_coverage_blocks[bcb] } #[inline] fn format_counter(&self, counter_kind: &CoverageKind) -> String { self.coverage_counters.debug_counters.format_counter(counter_kind) } } fn inject_edge_counter_basic_block( mir_body: &mut mir::Body<'tcx>, from_bb: BasicBlock, to_bb: BasicBlock, ) -> BasicBlock { let span = mir_body[from_bb].terminator().source_info.span.shrink_to_hi(); let new_bb = mir_body.basic_blocks_mut().push(BasicBlockData { statements: vec![], // counter will be injected here terminator: Some(Terminator { source_info: SourceInfo::outermost(span), kind: TerminatorKind::Goto { target: to_bb }, }), is_cleanup: false, }); let edge_ref = mir_body[from_bb] .terminator_mut() .successors_mut() .find(|successor| **successor == to_bb) .expect("from_bb should have a successor for to_bb"); *edge_ref = new_bb; new_bb } fn inject_statement( mir_body: &mut mir::Body<'tcx>, counter_kind: CoverageKind, bb: BasicBlock, some_code_region: Option<CodeRegion>, ) { debug!( " injecting statement {:?} for {:?} at code region: {:?}", counter_kind, bb, some_code_region ); let data = &mut mir_body[bb]; let source_info = data.terminator().source_info; let statement = Statement { source_info, kind: StatementKind::Coverage(Box::new(Coverage { kind: counter_kind, code_region: some_code_region, })), }; data.statements.insert(0, statement); } // Non-code expressions are injected into the coverage map, without generating executable code. fn inject_intermediate_expression(mir_body: &mut mir::Body<'tcx>, expression: CoverageKind) { debug_assert!(if let CoverageKind::Expression {.. } = expression { true } else { false }); debug!(" injecting non-code expression {:?}", expression); let inject_in_bb = mir::START_BLOCK; let data = &mut mir_body[inject_in_bb]; let source_info = data.terminator().source_info; let statement = Statement { source_info, kind: StatementKind::Coverage(Box::new(Coverage { kind: expression, code_region: None })), }; data.statements.push(statement); } /// Convert the Span into its file name, start line and column, and end line and column fn make_code_region( source_map: &SourceMap, file_name: Symbol, source_file: &Lrc<SourceFile>, span: Span, body_span: Span, ) -> CodeRegion { let (start_line, mut start_col) = source_file.lookup_file_pos(span.lo()); let (end_line, end_col) = if span.hi() == span.lo() { let (end_line, mut end_col) = (start_line, start_col); // Extend an empty span by one character so the region will be counted. let CharPos(char_pos) = start_col; if span.hi() == body_span.hi() { start_col = CharPos(char_pos - 1); } else { end_col = CharPos(char_pos + 1); } (end_line, end_col) } else { source_file.lookup_file_pos(span.hi()) }; let start_line = source_map.doctest_offset_line(&source_file.name, start_line); let end_line = source_map.doctest_offset_line(&source_file.name, end_line); CodeRegion { file_name, start_line: start_line as u32, start_col: start_col.to_u32() + 1, end_line: end_line as u32, end_col: end_col.to_u32() + 1, } } fn fn_sig_and_body<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, ) -> (Option<&'tcx rustc_hir::FnSig<'tcx>>, &'tcx rustc_hir::Body<'tcx>) { // FIXME(#79625): Consider improving MIR to provide the information needed, to avoid going back // to HIR for it. let hir_node = tcx.hir().get_if_local(def_id).expect("expected DefId is local"); let fn_body_id = hir::map::associated_body(hir_node).expect("HIR node is a function with body"); (hir::map::fn_sig(hir_node), tcx.hir().body(fn_body_id)) } fn get_body_span<'tcx>( tcx: TyCtxt<'tcx>, hir_body: &rustc_hir::Body<'tcx>, mir_body: &mut mir::Body<'tcx>, ) -> Span { let mut body_span = hir_body.value.span; let def_id = mir_body.source.def_id(); if tcx.is_closure(def_id) { // If the MIR function is a closure, and if the closure body span // starts from a macro, but it's content is not in that macro, try // to find a non-macro callsite, and instrument the spans there // instead. loop { let expn_data = body_span.ctxt().outer_expn_data(); if expn_data.is_root() { break; } if let ExpnKind::Macro {.. } = expn_data.kind { body_span = expn_data.call_site; } else { break; } } } body_span } fn
hash_mir_source
identifier_name
mod.rs
mir_source.def_id() ); return; } let hir_id = tcx.hir().local_def_id_to_hir_id(mir_source.def_id().expect_local()); let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some(); // Only instrument functions, methods, and closures (not constants since they are evaluated // at compile time by Miri). // FIXME(#73156): Handle source code coverage in const eval, but note, if and when const // expressions get coverage spans, we will probably have to "carve out" space for const // expressions from coverage spans in enclosing MIR's, like we do for closures. (That might // be tricky if const expressions have no corresponding statements in the enclosing MIR. // Closures are carved out by their initial `Assign` statement.) if!is_fn_like { trace!("InstrumentCoverage skipped for {:?} (not an FnLikeNode)", mir_source.def_id()); return; } match mir_body.basic_blocks()[mir::START_BLOCK].terminator().kind { TerminatorKind::Unreachable => { trace!("InstrumentCoverage skipped for unreachable `START_BLOCK`"); return; } _ => {} } let codegen_fn_attrs = tcx.codegen_fn_attrs(mir_source.def_id()); if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) { return; } trace!("InstrumentCoverage starting for {:?}", mir_source.def_id()); Instrumentor::new(&self.name(), tcx, mir_body).inject_counters(); trace!("InstrumentCoverage done for {:?}", mir_source.def_id()); } } struct Instrumentor<'a, 'tcx> { pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>, source_file: Lrc<SourceFile>, fn_sig_span: Span, body_span: Span, basic_coverage_blocks: CoverageGraph, coverage_counters: CoverageCounters, } impl<'a, 'tcx> Instrumentor<'a, 'tcx> { fn new(pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>) -> Self { let source_map = tcx.sess.source_map(); let def_id = mir_body.source.def_id(); let (some_fn_sig, hir_body) = fn_sig_and_body(tcx, def_id); let body_span = get_body_span(tcx, hir_body, mir_body); let source_file = source_map.lookup_source_file(body_span.lo()); let fn_sig_span = match some_fn_sig.filter(|fn_sig| { fn_sig.span.ctxt() == body_span.ctxt() && Lrc::ptr_eq(&source_file, &source_map.lookup_source_file(fn_sig.span.lo())) }) { Some(fn_sig) => fn_sig.span.with_hi(body_span.lo()), None => body_span.shrink_to_lo(), }; debug!( "instrumenting {}: {:?}, fn sig span: {:?}, body span: {:?}", if tcx.is_closure(def_id) { "closure" } else { "function" }, def_id, fn_sig_span, body_span ); let function_source_hash = hash_mir_source(tcx, hir_body); let basic_coverage_blocks = CoverageGraph::from_mir(mir_body); Self { pass_name, tcx, mir_body, source_file, fn_sig_span, body_span, basic_coverage_blocks, coverage_counters: CoverageCounters::new(function_source_hash), } } fn inject_counters(&'a mut self) { let tcx = self.tcx; let mir_source = self.mir_body.source; let def_id = mir_source.def_id(); let fn_sig_span = self.fn_sig_span; let body_span = self.body_span; let mut graphviz_data = debug::GraphvizData::new(); let mut debug_used_expressions = debug::UsedExpressions::new(); let dump_mir = pretty::dump_enabled(tcx, self.pass_name, def_id); let dump_graphviz = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_graphviz; let dump_spanview = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_spanview.is_some(); if dump_graphviz { graphviz_data.enable(); self.coverage_counters.enable_debug(); } if dump_graphviz || level_enabled!(tracing::Level::DEBUG) { debug_used_expressions.enable(); } //////////////////////////////////////////////////// // Compute `CoverageSpan`s from the `CoverageGraph`. let coverage_spans = CoverageSpans::generate_coverage_spans( &self.mir_body, fn_sig_span, body_span, &self.basic_coverage_blocks, ); if dump_spanview { debug::dump_coverage_spanview( tcx, self.mir_body, &self.basic_coverage_blocks, self.pass_name, body_span, &coverage_spans, ); } //////////////////////////////////////////////////// // Create an optimized mix of `Counter`s and `Expression`s for the `CoverageGraph`. Ensure // every `CoverageSpan` has a `Counter` or `Expression` assigned to its `BasicCoverageBlock` // and all `Expression` dependencies (operands) are also generated, for any other // `BasicCoverageBlock`s not already associated with a `CoverageSpan`. // // Intermediate expressions (used to compute other `Expression` values), which have no // direct associate to any `BasicCoverageBlock`, are returned in the method `Result`. let intermediate_expressions_or_error = self .coverage_counters .make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans); let (result, intermediate_expressions) = match intermediate_expressions_or_error { Ok(intermediate_expressions) => { // If debugging, add any intermediate expressions (which are not associated with any // BCB) to the `debug_used_expressions` map. if debug_used_expressions.is_enabled() { for intermediate_expression in &intermediate_expressions { debug_used_expressions.add_expression_operands(intermediate_expression); } } //////////////////////////////////////////////////// // Remove the counter or edge counter from of each `CoverageSpan`s associated // `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR. // // `Coverage` statements injected from `CoverageSpan`s will include the code regions // (source code start and end positions) to be counted by the associated counter. // // These `CoverageSpan`-associated counters are removed from their associated // `BasicCoverageBlock`s so that the only remaining counters in the `CoverageGraph` // are indirect counters (to be injected next, without associated code regions). self.inject_coverage_span_counters( coverage_spans, &mut graphviz_data, &mut debug_used_expressions, ); //////////////////////////////////////////////////// // For any remaining `BasicCoverageBlock` counters (that were not associated with // any `CoverageSpan`), inject `Coverage` statements (_without_ code region `Span`s) // to ensure `BasicCoverageBlock` counters that other `Expression`s may depend on // are in fact counted, even though they don't directly contribute to counting // their own independent code region's coverage. self.inject_indirect_counters(&mut graphviz_data, &mut debug_used_expressions); // Intermediate expressions will be injected as the final step, after generating // debug output, if any. //////////////////////////////////////////////////// (Ok(()), intermediate_expressions) } Err(e) => (Err(e), Vec::new()), }; if graphviz_data.is_enabled() { // Even if there was an error, a partial CoverageGraph can still generate a useful // graphviz output. debug::dump_coverage_graphviz( tcx, self.mir_body, self.pass_name, &self.basic_coverage_blocks, &self.coverage_counters.debug_counters, &graphviz_data, &intermediate_expressions, &debug_used_expressions, ); } if let Err(e) = result { bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e) }; // Depending on current `debug_options()`, `alert_on_unused_expressions()` could panic, so // this check is performed as late as possible, to allow other debug output (logs and dump // files), which might be helpful in analyzing unused expressions, to still be generated. debug_used_expressions.alert_on_unused_expressions(&self.coverage_counters.debug_counters); //////////////////////////////////////////////////// // Finally, inject the intermediate expressions collected along the way. for intermediate_expression in intermediate_expressions { inject_intermediate_expression(self.mir_body, intermediate_expression); } } /// Inject a counter for each `CoverageSpan`. There can be multiple `CoverageSpan`s for a given /// BCB, but only one actual counter needs to be incremented per BCB. `bb_counters` maps each /// `bcb` to its `Counter`, when injected. Subsequent `CoverageSpan`s for a BCB that already has /// a `Counter` will inject an `Expression` instead, and compute its value by adding `ZERO` to /// the BCB `Counter` value. /// /// If debugging, add every BCB `Expression` associated with a `CoverageSpan`s to the /// `used_expression_operands` map. fn inject_coverage_span_counters( &mut self, coverage_spans: Vec<CoverageSpan>, graphviz_data: &mut debug::GraphvizData, debug_used_expressions: &mut debug::UsedExpressions, ) { let tcx = self.tcx; let source_map = tcx.sess.source_map(); let body_span = self.body_span; let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy()); let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes()); for covspan in coverage_spans { let bcb = covspan.bcb; let span = covspan.span; let counter_kind = if let Some(&counter_operand) = bcb_counters[bcb].as_ref() { self.coverage_counters.make_identity_counter(counter_operand) } else if let Some(counter_kind) = self.bcb_data_mut(bcb).take_counter() { bcb_counters[bcb] = Some(counter_kind.as_operand_id()); debug_used_expressions.add_expression_operands(&counter_kind); counter_kind } else { bug!("Every BasicCoverageBlock should have a Counter or Expression"); }; graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind); debug!( "Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})", file_name, self.source_file, source_map.span_to_diagnostic_string(span), source_map.span_to_diagnostic_string(body_span)
self.bcb_leader_bb(bcb), Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)), ); } } /// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the /// counter from the `CoverageSpan`s `BasicCoverageBlock`, removing it from the BCB in the /// process (via `take_counter()`). /// /// Any other counter associated with a `BasicCoverageBlock`, or its incoming edge, but not /// associated with a `CoverageSpan`, should only exist if the counter is an `Expression` /// dependency (one of the expression operands). Collect them, and inject the additional /// counters into the MIR, without a reportable coverage span. fn inject_indirect_counters( &mut self, graphviz_data: &mut debug::GraphvizData, debug_used_expressions: &mut debug::UsedExpressions, ) { let mut bcb_counters_without_direct_coverage_spans = Vec::new(); for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() { if let Some(counter_kind) = target_bcb_data.take_counter() { bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind)); } if let Some(edge_counters) = target_bcb_data.take_edge_counters() { for (from_bcb, counter_kind) in edge_counters { bcb_counters_without_direct_coverage_spans.push(( Some(from_bcb), target_bcb, counter_kind, )); } } } // If debug is enabled, validate that every BCB or edge counter not directly associated // with a coverage span is at least indirectly associated (it is a dependency of a BCB // counter that _is_ associated with a coverage span). debug_used_expressions.validate(&bcb_counters_without_direct_coverage_spans); for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans { debug_used_expressions.add_unused_expression_if_not_found( &counter_kind, edge_from_bcb, target_bcb, ); match counter_kind { CoverageKind::Counter {.. } => { let inject_to_bb = if let Some(from_bcb) = edge_from_bcb { // The MIR edge starts `from_bb` (the outgoing / last BasicBlock in // `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the // `target_bcb`; also called the `leader_bb`). let from_bb = self.bcb_last_bb(from_bcb); let to_bb = self.bcb_leader_bb(target_bcb); let new_bb = inject_edge_counter_basic_block(self.mir_body, from_bb, to_bb); graphviz_data.set_edge_counter(from_bcb, new_bb, &counter_kind); debug!( "Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \ BasicBlock {:?}, for unclaimed edge counter {}", edge_from_bcb, from_bb, target_bcb, to_bb, new_bb, self.format_counter(&counter_kind), ); new_bb } else { let target_bb = self.bcb_last_bb(target_bcb); graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind); debug!( "{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}", target_bcb, target_bb, self.format_counter(&counter_kind), ); target_bb }; inject_statement(self.mir_body, counter_kind, inject_to_bb, None); } CoverageKind::Expression {.. } => { inject_intermediate_expression(self.mir_body, counter_kind) } _ => bug!("CoverageKind should be a counter"), } } } #[inline] fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock { self.bcb_data(bcb).leader_bb() } #[inline] fn bcb_last_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock { self.bcb_data(bcb).last_bb() } #[inline] fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData { &self.basic_coverage_blocks[bcb] } #[inline] fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData { &mut self.basic_coverage_blocks[bcb] } #[inline] fn format_counter(&self, counter_kind: &CoverageKind) -> String { self.coverage_counters.debug_counters.format_counter(counter_kind) } } fn inject_edge_counter_basic_block( mir_body: &mut mir::Body<'tcx>, from_bb: BasicBlock, to_bb: BasicBlock, ) -> BasicBlock { let span = mir_body[from_bb].terminator().source_info.span.shrink_to_hi(); let new_bb = mir_body.basic_blocks_mut().push(BasicBlockData { statements: vec![], // counter will be injected here terminator: Some(Terminator { source_info: SourceInfo::outermost(span), kind: TerminatorKind::Goto { target: to_bb }, }), is_cleanup: false, }); let edge_ref = mir_body[from_bb] .terminator_mut() .successors_mut() .find(|successor| **successor == to_bb) .expect("from_bb should have a successor for to_bb"); *edge_ref = new_bb; new_bb } fn inject_statement( mir_body: &mut mir::Body<'tcx>, counter_kind: CoverageKind, bb: BasicBlock, some_code_region: Option<CodeRegion>, ) { debug!( " injecting statement {:?} for {:?} at code region: {:?}", counter_kind, bb, some_code_region ); let data = &mut mir_body[bb]; let source_info = data.terminator().source_info; let statement = Statement { source_info, kind: StatementKind::Coverage(Box::new(Coverage { kind: counter_kind, code_region: some_code_region, })), }; data.statements.insert(0, statement);
); inject_statement( self.mir_body, counter_kind,
random_line_split
mod.rs
mir_source.def_id() ); return; } let hir_id = tcx.hir().local_def_id_to_hir_id(mir_source.def_id().expect_local()); let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some(); // Only instrument functions, methods, and closures (not constants since they are evaluated // at compile time by Miri). // FIXME(#73156): Handle source code coverage in const eval, but note, if and when const // expressions get coverage spans, we will probably have to "carve out" space for const // expressions from coverage spans in enclosing MIR's, like we do for closures. (That might // be tricky if const expressions have no corresponding statements in the enclosing MIR. // Closures are carved out by their initial `Assign` statement.) if!is_fn_like { trace!("InstrumentCoverage skipped for {:?} (not an FnLikeNode)", mir_source.def_id()); return; } match mir_body.basic_blocks()[mir::START_BLOCK].terminator().kind { TerminatorKind::Unreachable => { trace!("InstrumentCoverage skipped for unreachable `START_BLOCK`"); return; } _ => {} } let codegen_fn_attrs = tcx.codegen_fn_attrs(mir_source.def_id()); if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) { return; } trace!("InstrumentCoverage starting for {:?}", mir_source.def_id()); Instrumentor::new(&self.name(), tcx, mir_body).inject_counters(); trace!("InstrumentCoverage done for {:?}", mir_source.def_id()); } } struct Instrumentor<'a, 'tcx> { pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>, source_file: Lrc<SourceFile>, fn_sig_span: Span, body_span: Span, basic_coverage_blocks: CoverageGraph, coverage_counters: CoverageCounters, } impl<'a, 'tcx> Instrumentor<'a, 'tcx> { fn new(pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>) -> Self { let source_map = tcx.sess.source_map(); let def_id = mir_body.source.def_id(); let (some_fn_sig, hir_body) = fn_sig_and_body(tcx, def_id); let body_span = get_body_span(tcx, hir_body, mir_body); let source_file = source_map.lookup_source_file(body_span.lo()); let fn_sig_span = match some_fn_sig.filter(|fn_sig| { fn_sig.span.ctxt() == body_span.ctxt() && Lrc::ptr_eq(&source_file, &source_map.lookup_source_file(fn_sig.span.lo())) }) { Some(fn_sig) => fn_sig.span.with_hi(body_span.lo()), None => body_span.shrink_to_lo(), }; debug!( "instrumenting {}: {:?}, fn sig span: {:?}, body span: {:?}", if tcx.is_closure(def_id) { "closure" } else { "function" }, def_id, fn_sig_span, body_span ); let function_source_hash = hash_mir_source(tcx, hir_body); let basic_coverage_blocks = CoverageGraph::from_mir(mir_body); Self { pass_name, tcx, mir_body, source_file, fn_sig_span, body_span, basic_coverage_blocks, coverage_counters: CoverageCounters::new(function_source_hash), } } fn inject_counters(&'a mut self) { let tcx = self.tcx; let mir_source = self.mir_body.source; let def_id = mir_source.def_id(); let fn_sig_span = self.fn_sig_span; let body_span = self.body_span; let mut graphviz_data = debug::GraphvizData::new(); let mut debug_used_expressions = debug::UsedExpressions::new(); let dump_mir = pretty::dump_enabled(tcx, self.pass_name, def_id); let dump_graphviz = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_graphviz; let dump_spanview = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_spanview.is_some(); if dump_graphviz { graphviz_data.enable(); self.coverage_counters.enable_debug(); } if dump_graphviz || level_enabled!(tracing::Level::DEBUG) { debug_used_expressions.enable(); } //////////////////////////////////////////////////// // Compute `CoverageSpan`s from the `CoverageGraph`. let coverage_spans = CoverageSpans::generate_coverage_spans( &self.mir_body, fn_sig_span, body_span, &self.basic_coverage_blocks, ); if dump_spanview { debug::dump_coverage_spanview( tcx, self.mir_body, &self.basic_coverage_blocks, self.pass_name, body_span, &coverage_spans, ); } //////////////////////////////////////////////////// // Create an optimized mix of `Counter`s and `Expression`s for the `CoverageGraph`. Ensure // every `CoverageSpan` has a `Counter` or `Expression` assigned to its `BasicCoverageBlock` // and all `Expression` dependencies (operands) are also generated, for any other // `BasicCoverageBlock`s not already associated with a `CoverageSpan`. // // Intermediate expressions (used to compute other `Expression` values), which have no // direct associate to any `BasicCoverageBlock`, are returned in the method `Result`. let intermediate_expressions_or_error = self .coverage_counters .make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans); let (result, intermediate_expressions) = match intermediate_expressions_or_error { Ok(intermediate_expressions) => { // If debugging, add any intermediate expressions (which are not associated with any // BCB) to the `debug_used_expressions` map. if debug_used_expressions.is_enabled() { for intermediate_expression in &intermediate_expressions { debug_used_expressions.add_expression_operands(intermediate_expression); } } //////////////////////////////////////////////////// // Remove the counter or edge counter from of each `CoverageSpan`s associated // `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR. // // `Coverage` statements injected from `CoverageSpan`s will include the code regions // (source code start and end positions) to be counted by the associated counter. // // These `CoverageSpan`-associated counters are removed from their associated // `BasicCoverageBlock`s so that the only remaining counters in the `CoverageGraph` // are indirect counters (to be injected next, without associated code regions). self.inject_coverage_span_counters( coverage_spans, &mut graphviz_data, &mut debug_used_expressions, ); //////////////////////////////////////////////////// // For any remaining `BasicCoverageBlock` counters (that were not associated with // any `CoverageSpan`), inject `Coverage` statements (_without_ code region `Span`s) // to ensure `BasicCoverageBlock` counters that other `Expression`s may depend on // are in fact counted, even though they don't directly contribute to counting // their own independent code region's coverage. self.inject_indirect_counters(&mut graphviz_data, &mut debug_used_expressions); // Intermediate expressions will be injected as the final step, after generating // debug output, if any. //////////////////////////////////////////////////// (Ok(()), intermediate_expressions) } Err(e) => (Err(e), Vec::new()), }; if graphviz_data.is_enabled() { // Even if there was an error, a partial CoverageGraph can still generate a useful // graphviz output. debug::dump_coverage_graphviz( tcx, self.mir_body, self.pass_name, &self.basic_coverage_blocks, &self.coverage_counters.debug_counters, &graphviz_data, &intermediate_expressions, &debug_used_expressions, ); } if let Err(e) = result { bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e) }; // Depending on current `debug_options()`, `alert_on_unused_expressions()` could panic, so // this check is performed as late as possible, to allow other debug output (logs and dump // files), which might be helpful in analyzing unused expressions, to still be generated. debug_used_expressions.alert_on_unused_expressions(&self.coverage_counters.debug_counters); //////////////////////////////////////////////////// // Finally, inject the intermediate expressions collected along the way. for intermediate_expression in intermediate_expressions { inject_intermediate_expression(self.mir_body, intermediate_expression); } } /// Inject a counter for each `CoverageSpan`. There can be multiple `CoverageSpan`s for a given /// BCB, but only one actual counter needs to be incremented per BCB. `bb_counters` maps each /// `bcb` to its `Counter`, when injected. Subsequent `CoverageSpan`s for a BCB that already has /// a `Counter` will inject an `Expression` instead, and compute its value by adding `ZERO` to /// the BCB `Counter` value. /// /// If debugging, add every BCB `Expression` associated with a `CoverageSpan`s to the /// `used_expression_operands` map. fn inject_coverage_span_counters( &mut self, coverage_spans: Vec<CoverageSpan>, graphviz_data: &mut debug::GraphvizData, debug_used_expressions: &mut debug::UsedExpressions, ) { let tcx = self.tcx; let source_map = tcx.sess.source_map(); let body_span = self.body_span; let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy()); let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes()); for covspan in coverage_spans { let bcb = covspan.bcb; let span = covspan.span; let counter_kind = if let Some(&counter_operand) = bcb_counters[bcb].as_ref() { self.coverage_counters.make_identity_counter(counter_operand) } else if let Some(counter_kind) = self.bcb_data_mut(bcb).take_counter() { bcb_counters[bcb] = Some(counter_kind.as_operand_id()); debug_used_expressions.add_expression_operands(&counter_kind); counter_kind } else { bug!("Every BasicCoverageBlock should have a Counter or Expression"); }; graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind); debug!( "Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})", file_name, self.source_file, source_map.span_to_diagnostic_string(span), source_map.span_to_diagnostic_string(body_span) ); inject_statement( self.mir_body, counter_kind, self.bcb_leader_bb(bcb), Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)), ); } } /// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the /// counter from the `CoverageSpan`s `BasicCoverageBlock`, removing it from the BCB in the /// process (via `take_counter()`). /// /// Any other counter associated with a `BasicCoverageBlock`, or its incoming edge, but not /// associated with a `CoverageSpan`, should only exist if the counter is an `Expression` /// dependency (one of the expression operands). Collect them, and inject the additional /// counters into the MIR, without a reportable coverage span. fn inject_indirect_counters( &mut self, graphviz_data: &mut debug::GraphvizData, debug_used_expressions: &mut debug::UsedExpressions, ) { let mut bcb_counters_without_direct_coverage_spans = Vec::new(); for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() { if let Some(counter_kind) = target_bcb_data.take_counter() { bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind)); } if let Some(edge_counters) = target_bcb_data.take_edge_counters() { for (from_bcb, counter_kind) in edge_counters { bcb_counters_without_direct_coverage_spans.push(( Some(from_bcb), target_bcb, counter_kind, )); } } } // If debug is enabled, validate that every BCB or edge counter not directly associated // with a coverage span is at least indirectly associated (it is a dependency of a BCB // counter that _is_ associated with a coverage span). debug_used_expressions.validate(&bcb_counters_without_direct_coverage_spans); for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans { debug_used_expressions.add_unused_expression_if_not_found( &counter_kind, edge_from_bcb, target_bcb, ); match counter_kind { CoverageKind::Counter {.. } =>
new_bb } else { let target_bb = self.bcb_last_bb(target_bcb); graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind); debug!( "{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}", target_bcb, target_bb, self.format_counter(&counter_kind), ); target_bb }; inject_statement(self.mir_body, counter_kind, inject_to_bb, None); } CoverageKind::Expression {.. } => { inject_intermediate_expression(self.mir_body, counter_kind) } _ => bug!("CoverageKind should be a counter"), } } } #[inline] fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock { self.bcb_data(bcb).leader_bb() } #[inline] fn bcb_last_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock { self.bcb_data(bcb).last_bb() } #[inline] fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData { &self.basic_coverage_blocks[bcb] } #[inline] fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData { &mut self.basic_coverage_blocks[bcb] } #[inline] fn format_counter(&self, counter_kind: &CoverageKind) -> String { self.coverage_counters.debug_counters.format_counter(counter_kind) } } fn inject_edge_counter_basic_block( mir_body: &mut mir::Body<'tcx>, from_bb: BasicBlock, to_bb: BasicBlock, ) -> BasicBlock { let span = mir_body[from_bb].terminator().source_info.span.shrink_to_hi(); let new_bb = mir_body.basic_blocks_mut().push(BasicBlockData { statements: vec![], // counter will be injected here terminator: Some(Terminator { source_info: SourceInfo::outermost(span), kind: TerminatorKind::Goto { target: to_bb }, }), is_cleanup: false, }); let edge_ref = mir_body[from_bb] .terminator_mut() .successors_mut() .find(|successor| **successor == to_bb) .expect("from_bb should have a successor for to_bb"); *edge_ref = new_bb; new_bb } fn inject_statement( mir_body: &mut mir::Body<'tcx>, counter_kind: CoverageKind, bb: BasicBlock, some_code_region: Option<CodeRegion>, ) { debug!( " injecting statement {:?} for {:?} at code region: {:?}", counter_kind, bb, some_code_region ); let data = &mut mir_body[bb]; let source_info = data.terminator().source_info; let statement = Statement { source_info, kind: StatementKind::Coverage(Box::new(Coverage { kind: counter_kind, code_region: some_code_region, })), }; data.statements.insert(0, statement
{ let inject_to_bb = if let Some(from_bcb) = edge_from_bcb { // The MIR edge starts `from_bb` (the outgoing / last BasicBlock in // `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the // `target_bcb`; also called the `leader_bb`). let from_bb = self.bcb_last_bb(from_bcb); let to_bb = self.bcb_leader_bb(target_bcb); let new_bb = inject_edge_counter_basic_block(self.mir_body, from_bb, to_bb); graphviz_data.set_edge_counter(from_bcb, new_bb, &counter_kind); debug!( "Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \ BasicBlock {:?}, for unclaimed edge counter {}", edge_from_bcb, from_bb, target_bcb, to_bb, new_bb, self.format_counter(&counter_kind), );
conditional_block
codemap.rs
// Copyright 2012 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. /*! The CodeMap tracks all the source code used within a single crate, mapping from integer byte positions to the original source code location. Each bit of source parsed during crate parsing (typically files, in-memory strings, or various bits of macro expansion) cover a continuous range of bytes in the CodeMap and are represented by FileMaps. Byte positions are stored in `spans` and used pervasively in the compiler. They are absolute positions within the CodeMap, which upon request can be converted to line and column information, source code snippets, etc. */ use std::cell::RefCell; use std::cmp; use extra::serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { fn from_uint(n: uint) -> Self; fn to_uint(&self) -> uint; } /// A byte offset. Keep this small (currently 32-bits), as AST contains /// a lot of them. #[deriving(Clone, Eq, IterBytes, Ord)] pub struct BytePos(u32); /// A character offset. Because of multibyte utf8 characters, a byte offset /// is not equivalent to a character offset. The CodeMap will convert BytePos /// values to CharPos values as necessary. #[deriving(Eq,IterBytes, Ord)] pub struct CharPos(uint); // XXX: Lots of boilerplate in these impls, but so far my attempts to fix // have been unsuccessful impl Pos for BytePos { fn from_uint(n: uint) -> BytePos { BytePos(n as u32) } fn to_uint(&self) -> uint { let BytePos(n) = *self; n as uint } } impl Add<BytePos, BytePos> for BytePos { fn add(&self, rhs: &BytePos) -> BytePos { BytePos((self.to_uint() + rhs.to_uint()) as u32) } } impl Sub<BytePos, BytePos> for BytePos { fn sub(&self, rhs: &BytePos) -> BytePos { BytePos((self.to_uint() - rhs.to_uint()) as u32) } } impl Pos for CharPos { fn from_uint(n: uint) -> CharPos { CharPos(n) } fn to_uint(&self) -> uint { let CharPos(n) = *self; n } } impl Add<CharPos,CharPos> for CharPos { fn add(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() + rhs.to_uint()) } } impl Sub<CharPos,CharPos> for CharPos { fn sub(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() - rhs.to_uint()) } } /** Spans represent a region of code, used for error reporting. Positions in spans are *absolute* positions from the beginning of the codemap, not positions relative to FileMaps. Methods on the CodeMap can be used to relate spans back to the original source. */ #[deriving(Clone, IterBytes)] pub struct Span { lo: BytePos, hi: BytePos, expn_info: Option<@ExpnInfo> } pub static DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_info: None }; #[deriving(Clone, Eq, Encodable, Decodable, IterBytes)] pub struct Spanned<T> { node: T, span: Span, } impl cmp::Eq for Span { fn eq(&self, other: &Span) -> bool { return (*self).lo == (*other).lo && (*self).hi == (*other).hi; } fn ne(&self, other: &Span) -> bool {!(*self).eq(other) } } impl<S:Encoder> Encodable<S> for Span { /* Note #1972 -- spans are encoded but not decoded */ fn encode(&self, s: &mut S) { s.emit_nil() } } impl<D:Decoder> Decodable<D> for Span { fn decode(_d: &mut D) -> Span { DUMMY_SP } } pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> { respan(mk_sp(lo, hi), t) } pub fn respan<T>(sp: Span, t: T) -> Spanned<T> { Spanned {node: t, span: sp} } pub fn dummy_spanned<T>(t: T) -> Spanned<T> { respan(DUMMY_SP, t) } /* assuming that we're not in macro expansion */ pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span { Span {lo: lo, hi: hi, expn_info: None} } /// A source code location used for error reporting pub struct Loc { /// Information about the original source file: @FileMap, /// The (1-based) line number line: uint, /// The (0-based) column offset col: CharPos } /// A source code location used as the result of lookup_char_pos_adj // Actually, *none* of the clients use the filename *or* file field; // perhaps they should just be removed. pub struct
{ filename: FileName, line: uint, col: CharPos, file: Option<@FileMap>, } // used to be structural records. Better names, anyone? pub struct FileMapAndLine {fm: @FileMap, line: uint} pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos} #[deriving(IterBytes)] pub enum MacroFormat { // e.g. #[deriving(...)] <item> MacroAttribute, // e.g. `format!()` MacroBang } #[deriving(IterBytes)] pub struct NameAndSpan { name: @str, // the format with which the macro was invoked. format: MacroFormat, span: Option<Span> } /// Extra information for tracking macro expansion of spans #[deriving(IterBytes)] pub struct ExpnInfo { call_site: Span, callee: NameAndSpan } pub type FileName = @str; pub struct FileLines { file: @FileMap, lines: ~[uint] } // represents the origin of a file: pub enum FileSubstr { // indicates that this is a normal standalone file: FssNone, // indicates that this "file" is actually a substring // of another file that appears earlier in the codemap FssInternal(Span), } /// Identifies an offset of a multi-byte character in a FileMap pub struct MultiByteChar { /// The absolute offset of the character in the CodeMap pos: BytePos, /// The number of bytes, >=2 bytes: uint, } /// A single source in the CodeMap pub struct FileMap { /// The name of the file that the source came from, source that doesn't /// originate from files has names between angle brackets by convention, /// e.g. `<anon>` name: FileName, /// Extra information used by qquote substr: FileSubstr, /// The complete source code src: @str, /// The start position of this source in the CodeMap start_pos: BytePos, /// Locations of lines beginnings in the source code lines: RefCell<~[BytePos]>, /// Locations of multi-byte characters in the source code multibyte_chars: RefCell<~[MultiByteChar]>, } impl FileMap { // EFFECT: register a start-of-line offset in the // table of line-beginnings. // UNCHECKED INVARIANT: these offsets must be added in the right // order and must be in the right places; there is shared knowledge // about what ends a line between this file and parse.rs pub fn next_line(&self, pos: BytePos) { // the new charpos must be > the last one (or it's the first one). let mut lines = self.lines.borrow_mut();; let line_len = lines.get().len(); assert!(line_len == 0 || (lines.get()[line_len - 1] < pos)) lines.get().push(pos); } // get a line from the list of pre-computed line-beginnings pub fn get_line(&self, line: int) -> ~str { let mut lines = self.lines.borrow_mut(); let begin: BytePos = lines.get()[line] - self.start_pos; let begin = begin.to_uint(); let slice = self.src.slice_from(begin); match slice.find('\n') { Some(e) => slice.slice_to(e).to_owned(), None => slice.to_owned() } } pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) { assert!(bytes >=2 && bytes <= 4); let mbc = MultiByteChar { pos: pos, bytes: bytes, }; let mut multibyte_chars = self.multibyte_chars.borrow_mut(); multibyte_chars.get().push(mbc); } pub fn is_real_file(&self) -> bool { !(self.name.starts_with("<") && self.name.ends_with(">")) } } pub struct CodeMap { files: RefCell<~[@FileMap]> } impl CodeMap { pub fn new() -> CodeMap { CodeMap { files: RefCell::new(~[]), } } /// Add a new FileMap to the CodeMap and return it pub fn new_filemap(&self, filename: FileName, src: @str) -> @FileMap { return self.new_filemap_w_substr(filename, FssNone, src); } pub fn new_filemap_w_substr(&self, filename: FileName, substr: FileSubstr, src: @str) -> @FileMap { let mut files = self.files.borrow_mut(); let start_pos = if files.get().len() == 0 { 0 } else { let last_start = files.get().last().start_pos.to_uint(); let last_len = files.get().last().src.len(); last_start + last_len }; let filemap = @FileMap { name: filename, substr: substr, src: src, start_pos: Pos::from_uint(start_pos), lines: RefCell::new(~[]), multibyte_chars: RefCell::new(~[]), }; files.get().push(filemap); return filemap; } pub fn mk_substr_filename(&self, sp: Span) -> ~str { let pos = self.lookup_char_pos(sp.lo); return format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_uint() + 1) } /// Lookup source information about a BytePos pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { return self.lookup_pos(pos); } pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt { let loc = self.lookup_char_pos(pos); match (loc.file.substr) { FssNone => LocWithOpt { filename: loc.file.name, line: loc.line, col: loc.col, file: Some(loc.file)}, FssInternal(sp) => self.lookup_char_pos_adj( sp.lo + (pos - loc.file.start_pos)), } } pub fn adjust_span(&self, sp: Span) -> Span { let line = self.lookup_line(sp.lo); match (line.fm.substr) { FssNone => sp, FssInternal(s) => { self.adjust_span(Span { lo: s.lo + (sp.lo - line.fm.start_pos), hi: s.lo + (sp.hi - line.fm.start_pos), expn_info: sp.expn_info }) } } } pub fn span_to_str(&self, sp: Span) -> ~str { { let files = self.files.borrow(); if files.get().len() == 0 && sp == DUMMY_SP { return ~"no-location"; } } let lo = self.lookup_char_pos_adj(sp.lo); let hi = self.lookup_char_pos_adj(sp.hi); return format!("{}:{}:{}: {}:{}", lo.filename, lo.line, lo.col.to_uint() + 1, hi.line, hi.col.to_uint() + 1) } pub fn span_to_filename(&self, sp: Span) -> FileName { let lo = self.lookup_char_pos(sp.lo); lo.file.name } pub fn span_to_lines(&self, sp: Span) -> @FileLines { let lo = self.lookup_char_pos(sp.lo); let hi = self.lookup_char_pos(sp.hi); let mut lines = ~[]; for i in range(lo.line - 1u, hi.line as uint) { lines.push(i); }; return @FileLines {file: lo.file, lines: lines}; } pub fn span_to_snippet(&self, sp: Span) -> Option<~str> { let begin = self.lookup_byte_offset(sp.lo); let end = self.lookup_byte_offset(sp.hi); // FIXME #8256: this used to be an assert but whatever precondition // it's testing isn't true for all spans in the AST, so to allow the // caller to not have to fail (and it can't catch it since the CodeMap // isn't sendable), return None if begin.fm.start_pos!= end.fm.start_pos { None } else { Some(begin.fm.src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned()) } } pub fn get_filemap(&self, filename: &str) -> @FileMap { let files = self.files.borrow(); for fm in files.get().iter() { if filename == fm.name { return *fm } } //XXjdm the following triggers a mismatched type bug // (or expected function, found _|_) fail!(); // ("asking for " + filename + " which we don't know about"); } } impl CodeMap { fn lookup_filemap_idx(&self, pos: BytePos) -> uint { let files = self.files.borrow(); let files = files.get(); let len = files.len(); let mut a = 0u; let mut b = len; while b - a > 1u { let m = (a + b) / 2u; if files[m].start_pos > pos { b = m; } else { a = m; } } if (a >= len) { fail!("position {} does not resolve to a source location", pos.to_uint()) } return a; } fn lookup_line(&self, pos: BytePos) -> FileMapAndLine { let idx = self.lookup_filemap_idx(pos); let files = self.files.borrow(); let f = files.get()[idx]; let mut a = 0u; let mut lines = f.lines.borrow_mut(); let mut b = lines.get().len(); while b - a > 1u { let m = (a + b) / 2u; if lines.get()[m] > pos { b = m; } else { a = m; } } return FileMapAndLine {fm: f, line: a}; } fn lookup_pos(&self, pos: BytePos) -> Loc { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); let line = a + 1u; // Line numbers start at 1 let chpos = self.bytepos_to_local_charpos(pos); let mut lines = f.lines.borrow_mut(); let linebpos = lines.get()[a]; let linechpos = self.bytepos_to_local_charpos(linebpos); debug!("codemap: byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); debug!("codemap: char pos {:?} is on the line at char pos {:?}", chpos, linechpos); debug!("codemap: byte is on line: {:?}", line); assert!(chpos >= linechpos); return Loc { file: f, line: line, col: chpos - linechpos }; } fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos { let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); let fm = files.get()[idx]; let offset = bpos - fm.start_pos; return FileMapAndBytePos {fm: fm, pos: offset}; } // Converts an absolute BytePos to a CharPos relative to the file it is // located in fn bytepos_to_local_charpos(&self, bpos: BytePos) -> CharPos { debug!("codemap: converting {:?} to char pos", bpos); let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); let map = files.get()[idx]; // The number of extra bytes due to multibyte chars in the FileMap let mut total_extra_bytes = 0; let multibyte_chars = map.multibyte_chars.borrow(); for mbc in multibyte_chars.get().iter() { debug!("codemap: {:?}-byte char at {:?}", mbc.bytes, mbc.pos); if mbc.pos < bpos { total_extra_bytes += mbc.bytes; // We should never see a byte position in the middle of a // character assert!(bpos == mbc.pos || bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes); } else { break; } } CharPos(bpos.to_uint() - total_extra_bytes) } } #[cfg(test)] mod test { use super::*; #[test] fn t1 () { let cm = CodeMap::new(); let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line"); fm.next_line(BytePos(0)); assert_eq!(&fm.get_line(0),&~"first line."); // TESTING BROKEN BEHAVIOR: fm.next_line(BytePos(10)); assert_eq!(&fm.get_line(1),&~"."); } #[test] #[should_fail] fn t2 () { let cm = CodeMap::new(); let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line"); // TESTING *REALLY* BROKEN BEHAVIOR: fm.next_line(BytePos(0)); fm.next_line(BytePos(10)); fm.next_line(BytePos(2)); } }
LocWithOpt
identifier_name
codemap.rs
// Copyright 2012 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. /*! The CodeMap tracks all the source code used within a single crate, mapping from integer byte positions to the original source code location. Each bit of source parsed during crate parsing (typically files, in-memory strings, or various bits of macro expansion) cover a continuous range of bytes in the CodeMap and are represented by FileMaps. Byte positions are stored in `spans` and used pervasively in the compiler. They are absolute positions within the CodeMap, which upon request can be converted to line and column information, source code snippets, etc. */ use std::cell::RefCell; use std::cmp; use extra::serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { fn from_uint(n: uint) -> Self; fn to_uint(&self) -> uint; } /// A byte offset. Keep this small (currently 32-bits), as AST contains /// a lot of them. #[deriving(Clone, Eq, IterBytes, Ord)] pub struct BytePos(u32); /// A character offset. Because of multibyte utf8 characters, a byte offset /// is not equivalent to a character offset. The CodeMap will convert BytePos /// values to CharPos values as necessary. #[deriving(Eq,IterBytes, Ord)] pub struct CharPos(uint); // XXX: Lots of boilerplate in these impls, but so far my attempts to fix // have been unsuccessful impl Pos for BytePos { fn from_uint(n: uint) -> BytePos { BytePos(n as u32) } fn to_uint(&self) -> uint { let BytePos(n) = *self; n as uint } } impl Add<BytePos, BytePos> for BytePos { fn add(&self, rhs: &BytePos) -> BytePos { BytePos((self.to_uint() + rhs.to_uint()) as u32) } } impl Sub<BytePos, BytePos> for BytePos { fn sub(&self, rhs: &BytePos) -> BytePos { BytePos((self.to_uint() - rhs.to_uint()) as u32) } } impl Pos for CharPos { fn from_uint(n: uint) -> CharPos { CharPos(n) } fn to_uint(&self) -> uint { let CharPos(n) = *self; n } } impl Add<CharPos,CharPos> for CharPos { fn add(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() + rhs.to_uint()) } } impl Sub<CharPos,CharPos> for CharPos { fn sub(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() - rhs.to_uint()) } } /** Spans represent a region of code, used for error reporting. Positions in spans are *absolute* positions from the beginning of the codemap, not positions relative to FileMaps. Methods on the CodeMap can be used to relate spans back to the original source. */ #[deriving(Clone, IterBytes)] pub struct Span { lo: BytePos, hi: BytePos, expn_info: Option<@ExpnInfo> } pub static DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_info: None }; #[deriving(Clone, Eq, Encodable, Decodable, IterBytes)] pub struct Spanned<T> { node: T, span: Span, } impl cmp::Eq for Span { fn eq(&self, other: &Span) -> bool { return (*self).lo == (*other).lo && (*self).hi == (*other).hi; } fn ne(&self, other: &Span) -> bool {!(*self).eq(other) } } impl<S:Encoder> Encodable<S> for Span { /* Note #1972 -- spans are encoded but not decoded */ fn encode(&self, s: &mut S) { s.emit_nil() } } impl<D:Decoder> Decodable<D> for Span { fn decode(_d: &mut D) -> Span { DUMMY_SP } } pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> { respan(mk_sp(lo, hi), t) } pub fn respan<T>(sp: Span, t: T) -> Spanned<T> { Spanned {node: t, span: sp} } pub fn dummy_spanned<T>(t: T) -> Spanned<T> { respan(DUMMY_SP, t) } /* assuming that we're not in macro expansion */ pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span { Span {lo: lo, hi: hi, expn_info: None} } /// A source code location used for error reporting pub struct Loc { /// Information about the original source file: @FileMap, /// The (1-based) line number line: uint, /// The (0-based) column offset col: CharPos } /// A source code location used as the result of lookup_char_pos_adj // Actually, *none* of the clients use the filename *or* file field; // perhaps they should just be removed. pub struct LocWithOpt {
// used to be structural records. Better names, anyone? pub struct FileMapAndLine {fm: @FileMap, line: uint} pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos} #[deriving(IterBytes)] pub enum MacroFormat { // e.g. #[deriving(...)] <item> MacroAttribute, // e.g. `format!()` MacroBang } #[deriving(IterBytes)] pub struct NameAndSpan { name: @str, // the format with which the macro was invoked. format: MacroFormat, span: Option<Span> } /// Extra information for tracking macro expansion of spans #[deriving(IterBytes)] pub struct ExpnInfo { call_site: Span, callee: NameAndSpan } pub type FileName = @str; pub struct FileLines { file: @FileMap, lines: ~[uint] } // represents the origin of a file: pub enum FileSubstr { // indicates that this is a normal standalone file: FssNone, // indicates that this "file" is actually a substring // of another file that appears earlier in the codemap FssInternal(Span), } /// Identifies an offset of a multi-byte character in a FileMap pub struct MultiByteChar { /// The absolute offset of the character in the CodeMap pos: BytePos, /// The number of bytes, >=2 bytes: uint, } /// A single source in the CodeMap pub struct FileMap { /// The name of the file that the source came from, source that doesn't /// originate from files has names between angle brackets by convention, /// e.g. `<anon>` name: FileName, /// Extra information used by qquote substr: FileSubstr, /// The complete source code src: @str, /// The start position of this source in the CodeMap start_pos: BytePos, /// Locations of lines beginnings in the source code lines: RefCell<~[BytePos]>, /// Locations of multi-byte characters in the source code multibyte_chars: RefCell<~[MultiByteChar]>, } impl FileMap { // EFFECT: register a start-of-line offset in the // table of line-beginnings. // UNCHECKED INVARIANT: these offsets must be added in the right // order and must be in the right places; there is shared knowledge // about what ends a line between this file and parse.rs pub fn next_line(&self, pos: BytePos) { // the new charpos must be > the last one (or it's the first one). let mut lines = self.lines.borrow_mut();; let line_len = lines.get().len(); assert!(line_len == 0 || (lines.get()[line_len - 1] < pos)) lines.get().push(pos); } // get a line from the list of pre-computed line-beginnings pub fn get_line(&self, line: int) -> ~str { let mut lines = self.lines.borrow_mut(); let begin: BytePos = lines.get()[line] - self.start_pos; let begin = begin.to_uint(); let slice = self.src.slice_from(begin); match slice.find('\n') { Some(e) => slice.slice_to(e).to_owned(), None => slice.to_owned() } } pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) { assert!(bytes >=2 && bytes <= 4); let mbc = MultiByteChar { pos: pos, bytes: bytes, }; let mut multibyte_chars = self.multibyte_chars.borrow_mut(); multibyte_chars.get().push(mbc); } pub fn is_real_file(&self) -> bool { !(self.name.starts_with("<") && self.name.ends_with(">")) } } pub struct CodeMap { files: RefCell<~[@FileMap]> } impl CodeMap { pub fn new() -> CodeMap { CodeMap { files: RefCell::new(~[]), } } /// Add a new FileMap to the CodeMap and return it pub fn new_filemap(&self, filename: FileName, src: @str) -> @FileMap { return self.new_filemap_w_substr(filename, FssNone, src); } pub fn new_filemap_w_substr(&self, filename: FileName, substr: FileSubstr, src: @str) -> @FileMap { let mut files = self.files.borrow_mut(); let start_pos = if files.get().len() == 0 { 0 } else { let last_start = files.get().last().start_pos.to_uint(); let last_len = files.get().last().src.len(); last_start + last_len }; let filemap = @FileMap { name: filename, substr: substr, src: src, start_pos: Pos::from_uint(start_pos), lines: RefCell::new(~[]), multibyte_chars: RefCell::new(~[]), }; files.get().push(filemap); return filemap; } pub fn mk_substr_filename(&self, sp: Span) -> ~str { let pos = self.lookup_char_pos(sp.lo); return format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_uint() + 1) } /// Lookup source information about a BytePos pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { return self.lookup_pos(pos); } pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt { let loc = self.lookup_char_pos(pos); match (loc.file.substr) { FssNone => LocWithOpt { filename: loc.file.name, line: loc.line, col: loc.col, file: Some(loc.file)}, FssInternal(sp) => self.lookup_char_pos_adj( sp.lo + (pos - loc.file.start_pos)), } } pub fn adjust_span(&self, sp: Span) -> Span { let line = self.lookup_line(sp.lo); match (line.fm.substr) { FssNone => sp, FssInternal(s) => { self.adjust_span(Span { lo: s.lo + (sp.lo - line.fm.start_pos), hi: s.lo + (sp.hi - line.fm.start_pos), expn_info: sp.expn_info }) } } } pub fn span_to_str(&self, sp: Span) -> ~str { { let files = self.files.borrow(); if files.get().len() == 0 && sp == DUMMY_SP { return ~"no-location"; } } let lo = self.lookup_char_pos_adj(sp.lo); let hi = self.lookup_char_pos_adj(sp.hi); return format!("{}:{}:{}: {}:{}", lo.filename, lo.line, lo.col.to_uint() + 1, hi.line, hi.col.to_uint() + 1) } pub fn span_to_filename(&self, sp: Span) -> FileName { let lo = self.lookup_char_pos(sp.lo); lo.file.name } pub fn span_to_lines(&self, sp: Span) -> @FileLines { let lo = self.lookup_char_pos(sp.lo); let hi = self.lookup_char_pos(sp.hi); let mut lines = ~[]; for i in range(lo.line - 1u, hi.line as uint) { lines.push(i); }; return @FileLines {file: lo.file, lines: lines}; } pub fn span_to_snippet(&self, sp: Span) -> Option<~str> { let begin = self.lookup_byte_offset(sp.lo); let end = self.lookup_byte_offset(sp.hi); // FIXME #8256: this used to be an assert but whatever precondition // it's testing isn't true for all spans in the AST, so to allow the // caller to not have to fail (and it can't catch it since the CodeMap // isn't sendable), return None if begin.fm.start_pos!= end.fm.start_pos { None } else { Some(begin.fm.src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned()) } } pub fn get_filemap(&self, filename: &str) -> @FileMap { let files = self.files.borrow(); for fm in files.get().iter() { if filename == fm.name { return *fm } } //XXjdm the following triggers a mismatched type bug // (or expected function, found _|_) fail!(); // ("asking for " + filename + " which we don't know about"); } } impl CodeMap { fn lookup_filemap_idx(&self, pos: BytePos) -> uint { let files = self.files.borrow(); let files = files.get(); let len = files.len(); let mut a = 0u; let mut b = len; while b - a > 1u { let m = (a + b) / 2u; if files[m].start_pos > pos { b = m; } else { a = m; } } if (a >= len) { fail!("position {} does not resolve to a source location", pos.to_uint()) } return a; } fn lookup_line(&self, pos: BytePos) -> FileMapAndLine { let idx = self.lookup_filemap_idx(pos); let files = self.files.borrow(); let f = files.get()[idx]; let mut a = 0u; let mut lines = f.lines.borrow_mut(); let mut b = lines.get().len(); while b - a > 1u { let m = (a + b) / 2u; if lines.get()[m] > pos { b = m; } else { a = m; } } return FileMapAndLine {fm: f, line: a}; } fn lookup_pos(&self, pos: BytePos) -> Loc { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); let line = a + 1u; // Line numbers start at 1 let chpos = self.bytepos_to_local_charpos(pos); let mut lines = f.lines.borrow_mut(); let linebpos = lines.get()[a]; let linechpos = self.bytepos_to_local_charpos(linebpos); debug!("codemap: byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); debug!("codemap: char pos {:?} is on the line at char pos {:?}", chpos, linechpos); debug!("codemap: byte is on line: {:?}", line); assert!(chpos >= linechpos); return Loc { file: f, line: line, col: chpos - linechpos }; } fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos { let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); let fm = files.get()[idx]; let offset = bpos - fm.start_pos; return FileMapAndBytePos {fm: fm, pos: offset}; } // Converts an absolute BytePos to a CharPos relative to the file it is // located in fn bytepos_to_local_charpos(&self, bpos: BytePos) -> CharPos { debug!("codemap: converting {:?} to char pos", bpos); let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); let map = files.get()[idx]; // The number of extra bytes due to multibyte chars in the FileMap let mut total_extra_bytes = 0; let multibyte_chars = map.multibyte_chars.borrow(); for mbc in multibyte_chars.get().iter() { debug!("codemap: {:?}-byte char at {:?}", mbc.bytes, mbc.pos); if mbc.pos < bpos { total_extra_bytes += mbc.bytes; // We should never see a byte position in the middle of a // character assert!(bpos == mbc.pos || bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes); } else { break; } } CharPos(bpos.to_uint() - total_extra_bytes) } } #[cfg(test)] mod test { use super::*; #[test] fn t1 () { let cm = CodeMap::new(); let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line"); fm.next_line(BytePos(0)); assert_eq!(&fm.get_line(0),&~"first line."); // TESTING BROKEN BEHAVIOR: fm.next_line(BytePos(10)); assert_eq!(&fm.get_line(1),&~"."); } #[test] #[should_fail] fn t2 () { let cm = CodeMap::new(); let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line"); // TESTING *REALLY* BROKEN BEHAVIOR: fm.next_line(BytePos(0)); fm.next_line(BytePos(10)); fm.next_line(BytePos(2)); } }
filename: FileName, line: uint, col: CharPos, file: Option<@FileMap>, }
random_line_split
codemap.rs
// Copyright 2012 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. /*! The CodeMap tracks all the source code used within a single crate, mapping from integer byte positions to the original source code location. Each bit of source parsed during crate parsing (typically files, in-memory strings, or various bits of macro expansion) cover a continuous range of bytes in the CodeMap and are represented by FileMaps. Byte positions are stored in `spans` and used pervasively in the compiler. They are absolute positions within the CodeMap, which upon request can be converted to line and column information, source code snippets, etc. */ use std::cell::RefCell; use std::cmp; use extra::serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { fn from_uint(n: uint) -> Self; fn to_uint(&self) -> uint; } /// A byte offset. Keep this small (currently 32-bits), as AST contains /// a lot of them. #[deriving(Clone, Eq, IterBytes, Ord)] pub struct BytePos(u32); /// A character offset. Because of multibyte utf8 characters, a byte offset /// is not equivalent to a character offset. The CodeMap will convert BytePos /// values to CharPos values as necessary. #[deriving(Eq,IterBytes, Ord)] pub struct CharPos(uint); // XXX: Lots of boilerplate in these impls, but so far my attempts to fix // have been unsuccessful impl Pos for BytePos { fn from_uint(n: uint) -> BytePos { BytePos(n as u32) } fn to_uint(&self) -> uint { let BytePos(n) = *self; n as uint } } impl Add<BytePos, BytePos> for BytePos { fn add(&self, rhs: &BytePos) -> BytePos { BytePos((self.to_uint() + rhs.to_uint()) as u32) } } impl Sub<BytePos, BytePos> for BytePos { fn sub(&self, rhs: &BytePos) -> BytePos { BytePos((self.to_uint() - rhs.to_uint()) as u32) } } impl Pos for CharPos { fn from_uint(n: uint) -> CharPos { CharPos(n) } fn to_uint(&self) -> uint
} impl Add<CharPos,CharPos> for CharPos { fn add(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() + rhs.to_uint()) } } impl Sub<CharPos,CharPos> for CharPos { fn sub(&self, rhs: &CharPos) -> CharPos { CharPos(self.to_uint() - rhs.to_uint()) } } /** Spans represent a region of code, used for error reporting. Positions in spans are *absolute* positions from the beginning of the codemap, not positions relative to FileMaps. Methods on the CodeMap can be used to relate spans back to the original source. */ #[deriving(Clone, IterBytes)] pub struct Span { lo: BytePos, hi: BytePos, expn_info: Option<@ExpnInfo> } pub static DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_info: None }; #[deriving(Clone, Eq, Encodable, Decodable, IterBytes)] pub struct Spanned<T> { node: T, span: Span, } impl cmp::Eq for Span { fn eq(&self, other: &Span) -> bool { return (*self).lo == (*other).lo && (*self).hi == (*other).hi; } fn ne(&self, other: &Span) -> bool {!(*self).eq(other) } } impl<S:Encoder> Encodable<S> for Span { /* Note #1972 -- spans are encoded but not decoded */ fn encode(&self, s: &mut S) { s.emit_nil() } } impl<D:Decoder> Decodable<D> for Span { fn decode(_d: &mut D) -> Span { DUMMY_SP } } pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> { respan(mk_sp(lo, hi), t) } pub fn respan<T>(sp: Span, t: T) -> Spanned<T> { Spanned {node: t, span: sp} } pub fn dummy_spanned<T>(t: T) -> Spanned<T> { respan(DUMMY_SP, t) } /* assuming that we're not in macro expansion */ pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span { Span {lo: lo, hi: hi, expn_info: None} } /// A source code location used for error reporting pub struct Loc { /// Information about the original source file: @FileMap, /// The (1-based) line number line: uint, /// The (0-based) column offset col: CharPos } /// A source code location used as the result of lookup_char_pos_adj // Actually, *none* of the clients use the filename *or* file field; // perhaps they should just be removed. pub struct LocWithOpt { filename: FileName, line: uint, col: CharPos, file: Option<@FileMap>, } // used to be structural records. Better names, anyone? pub struct FileMapAndLine {fm: @FileMap, line: uint} pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos} #[deriving(IterBytes)] pub enum MacroFormat { // e.g. #[deriving(...)] <item> MacroAttribute, // e.g. `format!()` MacroBang } #[deriving(IterBytes)] pub struct NameAndSpan { name: @str, // the format with which the macro was invoked. format: MacroFormat, span: Option<Span> } /// Extra information for tracking macro expansion of spans #[deriving(IterBytes)] pub struct ExpnInfo { call_site: Span, callee: NameAndSpan } pub type FileName = @str; pub struct FileLines { file: @FileMap, lines: ~[uint] } // represents the origin of a file: pub enum FileSubstr { // indicates that this is a normal standalone file: FssNone, // indicates that this "file" is actually a substring // of another file that appears earlier in the codemap FssInternal(Span), } /// Identifies an offset of a multi-byte character in a FileMap pub struct MultiByteChar { /// The absolute offset of the character in the CodeMap pos: BytePos, /// The number of bytes, >=2 bytes: uint, } /// A single source in the CodeMap pub struct FileMap { /// The name of the file that the source came from, source that doesn't /// originate from files has names between angle brackets by convention, /// e.g. `<anon>` name: FileName, /// Extra information used by qquote substr: FileSubstr, /// The complete source code src: @str, /// The start position of this source in the CodeMap start_pos: BytePos, /// Locations of lines beginnings in the source code lines: RefCell<~[BytePos]>, /// Locations of multi-byte characters in the source code multibyte_chars: RefCell<~[MultiByteChar]>, } impl FileMap { // EFFECT: register a start-of-line offset in the // table of line-beginnings. // UNCHECKED INVARIANT: these offsets must be added in the right // order and must be in the right places; there is shared knowledge // about what ends a line between this file and parse.rs pub fn next_line(&self, pos: BytePos) { // the new charpos must be > the last one (or it's the first one). let mut lines = self.lines.borrow_mut();; let line_len = lines.get().len(); assert!(line_len == 0 || (lines.get()[line_len - 1] < pos)) lines.get().push(pos); } // get a line from the list of pre-computed line-beginnings pub fn get_line(&self, line: int) -> ~str { let mut lines = self.lines.borrow_mut(); let begin: BytePos = lines.get()[line] - self.start_pos; let begin = begin.to_uint(); let slice = self.src.slice_from(begin); match slice.find('\n') { Some(e) => slice.slice_to(e).to_owned(), None => slice.to_owned() } } pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) { assert!(bytes >=2 && bytes <= 4); let mbc = MultiByteChar { pos: pos, bytes: bytes, }; let mut multibyte_chars = self.multibyte_chars.borrow_mut(); multibyte_chars.get().push(mbc); } pub fn is_real_file(&self) -> bool { !(self.name.starts_with("<") && self.name.ends_with(">")) } } pub struct CodeMap { files: RefCell<~[@FileMap]> } impl CodeMap { pub fn new() -> CodeMap { CodeMap { files: RefCell::new(~[]), } } /// Add a new FileMap to the CodeMap and return it pub fn new_filemap(&self, filename: FileName, src: @str) -> @FileMap { return self.new_filemap_w_substr(filename, FssNone, src); } pub fn new_filemap_w_substr(&self, filename: FileName, substr: FileSubstr, src: @str) -> @FileMap { let mut files = self.files.borrow_mut(); let start_pos = if files.get().len() == 0 { 0 } else { let last_start = files.get().last().start_pos.to_uint(); let last_len = files.get().last().src.len(); last_start + last_len }; let filemap = @FileMap { name: filename, substr: substr, src: src, start_pos: Pos::from_uint(start_pos), lines: RefCell::new(~[]), multibyte_chars: RefCell::new(~[]), }; files.get().push(filemap); return filemap; } pub fn mk_substr_filename(&self, sp: Span) -> ~str { let pos = self.lookup_char_pos(sp.lo); return format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_uint() + 1) } /// Lookup source information about a BytePos pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { return self.lookup_pos(pos); } pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt { let loc = self.lookup_char_pos(pos); match (loc.file.substr) { FssNone => LocWithOpt { filename: loc.file.name, line: loc.line, col: loc.col, file: Some(loc.file)}, FssInternal(sp) => self.lookup_char_pos_adj( sp.lo + (pos - loc.file.start_pos)), } } pub fn adjust_span(&self, sp: Span) -> Span { let line = self.lookup_line(sp.lo); match (line.fm.substr) { FssNone => sp, FssInternal(s) => { self.adjust_span(Span { lo: s.lo + (sp.lo - line.fm.start_pos), hi: s.lo + (sp.hi - line.fm.start_pos), expn_info: sp.expn_info }) } } } pub fn span_to_str(&self, sp: Span) -> ~str { { let files = self.files.borrow(); if files.get().len() == 0 && sp == DUMMY_SP { return ~"no-location"; } } let lo = self.lookup_char_pos_adj(sp.lo); let hi = self.lookup_char_pos_adj(sp.hi); return format!("{}:{}:{}: {}:{}", lo.filename, lo.line, lo.col.to_uint() + 1, hi.line, hi.col.to_uint() + 1) } pub fn span_to_filename(&self, sp: Span) -> FileName { let lo = self.lookup_char_pos(sp.lo); lo.file.name } pub fn span_to_lines(&self, sp: Span) -> @FileLines { let lo = self.lookup_char_pos(sp.lo); let hi = self.lookup_char_pos(sp.hi); let mut lines = ~[]; for i in range(lo.line - 1u, hi.line as uint) { lines.push(i); }; return @FileLines {file: lo.file, lines: lines}; } pub fn span_to_snippet(&self, sp: Span) -> Option<~str> { let begin = self.lookup_byte_offset(sp.lo); let end = self.lookup_byte_offset(sp.hi); // FIXME #8256: this used to be an assert but whatever precondition // it's testing isn't true for all spans in the AST, so to allow the // caller to not have to fail (and it can't catch it since the CodeMap // isn't sendable), return None if begin.fm.start_pos!= end.fm.start_pos { None } else { Some(begin.fm.src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned()) } } pub fn get_filemap(&self, filename: &str) -> @FileMap { let files = self.files.borrow(); for fm in files.get().iter() { if filename == fm.name { return *fm } } //XXjdm the following triggers a mismatched type bug // (or expected function, found _|_) fail!(); // ("asking for " + filename + " which we don't know about"); } } impl CodeMap { fn lookup_filemap_idx(&self, pos: BytePos) -> uint { let files = self.files.borrow(); let files = files.get(); let len = files.len(); let mut a = 0u; let mut b = len; while b - a > 1u { let m = (a + b) / 2u; if files[m].start_pos > pos { b = m; } else { a = m; } } if (a >= len) { fail!("position {} does not resolve to a source location", pos.to_uint()) } return a; } fn lookup_line(&self, pos: BytePos) -> FileMapAndLine { let idx = self.lookup_filemap_idx(pos); let files = self.files.borrow(); let f = files.get()[idx]; let mut a = 0u; let mut lines = f.lines.borrow_mut(); let mut b = lines.get().len(); while b - a > 1u { let m = (a + b) / 2u; if lines.get()[m] > pos { b = m; } else { a = m; } } return FileMapAndLine {fm: f, line: a}; } fn lookup_pos(&self, pos: BytePos) -> Loc { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); let line = a + 1u; // Line numbers start at 1 let chpos = self.bytepos_to_local_charpos(pos); let mut lines = f.lines.borrow_mut(); let linebpos = lines.get()[a]; let linechpos = self.bytepos_to_local_charpos(linebpos); debug!("codemap: byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); debug!("codemap: char pos {:?} is on the line at char pos {:?}", chpos, linechpos); debug!("codemap: byte is on line: {:?}", line); assert!(chpos >= linechpos); return Loc { file: f, line: line, col: chpos - linechpos }; } fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos { let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); let fm = files.get()[idx]; let offset = bpos - fm.start_pos; return FileMapAndBytePos {fm: fm, pos: offset}; } // Converts an absolute BytePos to a CharPos relative to the file it is // located in fn bytepos_to_local_charpos(&self, bpos: BytePos) -> CharPos { debug!("codemap: converting {:?} to char pos", bpos); let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); let map = files.get()[idx]; // The number of extra bytes due to multibyte chars in the FileMap let mut total_extra_bytes = 0; let multibyte_chars = map.multibyte_chars.borrow(); for mbc in multibyte_chars.get().iter() { debug!("codemap: {:?}-byte char at {:?}", mbc.bytes, mbc.pos); if mbc.pos < bpos { total_extra_bytes += mbc.bytes; // We should never see a byte position in the middle of a // character assert!(bpos == mbc.pos || bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes); } else { break; } } CharPos(bpos.to_uint() - total_extra_bytes) } } #[cfg(test)] mod test { use super::*; #[test] fn t1 () { let cm = CodeMap::new(); let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line"); fm.next_line(BytePos(0)); assert_eq!(&fm.get_line(0),&~"first line."); // TESTING BROKEN BEHAVIOR: fm.next_line(BytePos(10)); assert_eq!(&fm.get_line(1),&~"."); } #[test] #[should_fail] fn t2 () { let cm = CodeMap::new(); let fm = cm.new_filemap(@"blork.rs",@"first line.\nsecond line"); // TESTING *REALLY* BROKEN BEHAVIOR: fm.next_line(BytePos(0)); fm.next_line(BytePos(10)); fm.next_line(BytePos(2)); } }
{ let CharPos(n) = *self; n }
identifier_body
check_const.rs
// Copyright 2012-2013 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 driver::session::Session; use middle::def::*; use middle::resolve; use middle::ty; use middle::typeck; use util::ppaux; use syntax::ast::*; use syntax::{ast_util, ast_map}; use syntax::visit::Visitor; use syntax::visit; pub struct CheckCrateVisitor<'a> { tcx: &'a ty::ctxt, } impl<'a> Visitor<bool> for CheckCrateVisitor<'a> { fn visit_item(&mut self, i: &Item, env: bool) { check_item(self, i, env); } fn visit_pat(&mut self, p: &Pat, env: bool) { check_pat(self, p, env); } fn visit_expr(&mut self, ex: &Expr, env: bool) { check_expr(self, ex, env); } } pub fn check_crate(krate: &Crate, tcx: &ty::ctxt) { visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx }, krate, false); tcx.sess.abort_if_errors(); } fn check_item(v: &mut CheckCrateVisitor, it: &Item, _is_const: bool) { match it.node { ItemStatic(_, _, ex) => { v.visit_expr(&*ex, true); check_item_recursion(&v.tcx.sess, &v.tcx.map, &v.tcx.def_map, it); } ItemEnum(ref enum_definition, _) => { for var in (*enum_definition).variants.iter() { for ex in var.node.disr_expr.iter() { v.visit_expr(&**ex, true); } } } _ => visit::walk_item(v, it, false) } } fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) { fn is_str(e: &Expr) -> bool { match e.node { ExprVstore(expr, ExprVstoreUniq) => { match expr.node { ExprLit(lit) => ast_util::lit_is_str(lit), _ => false, } } _ => false, } } match p.node { // Let through plain ~-string literals here PatLit(ref a) => if!is_str(&**a) { v.visit_expr(&**a, true); }, PatRange(ref a, ref b) => { if!is_str(&**a) { v.visit_expr(&**a, true); } if!is_str(&**b) { v.visit_expr(&**b, true); } } _ => visit::walk_pat(v, p, false) } } fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) { if is_const { match e.node { ExprUnary(UnDeref, _) => { } ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => { v.tcx.sess.span_err(e.span, "cannot do allocations in constant expressions"); return; } ExprLit(lit) if ast_util::lit_is_str(lit) => {} ExprBinary(..) | ExprUnary(..) => { let method_call = typeck::MethodCall::expr(e.id); if v.tcx.method_map.borrow().contains_key(&method_call) { v.tcx.sess.span_err(e.span, "user-defined operators are not \ allowed in constant expressions"); } } ExprLit(_) => (), ExprCast(_, _) => { let ety = ty::expr_ty(v.tcx, e); if!ty::type_is_numeric(ety) &&!ty::type_is_unsafe_ptr(ety) { v.tcx .sess .span_err(e.span, format!("can not cast to `{}` in a constant \ expression", ppaux::ty_to_str(v.tcx, ety)).as_slice()) } } ExprPath(ref pth) => { // NB: In the future you might wish to relax this slightly // to handle on-demand instantiation of functions via // foo::<bar> in a const. Currently that is only done on // a path in trans::callee that only works in block contexts. if!pth.segments.iter().all(|segment| segment.types.is_empty()) { v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ items without type parameters"); } match v.tcx.def_map.borrow().find(&e.id) { Some(&DefStatic(..)) | Some(&DefFn(_, _)) | Some(&DefVariant(_, _, _)) |
v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ constants or functions"); } None => { v.tcx.sess.span_bug(e.span, "unbound path in const?!"); } } } ExprCall(callee, _) => { match v.tcx.def_map.borrow().find(&callee.id) { Some(&DefStruct(..)) => {} // OK. Some(&DefVariant(..)) => {} // OK. _ => { v.tcx.sess.span_err(e.span, "function calls in constants are limited to \ struct and enum constructors"); } } } ExprBlock(ref block) => { // Check all statements in the block for stmt in block.stmts.iter() { let block_span_err = |span| v.tcx.sess.span_err(span, "blocks in constants are limited to \ items and tail expressions"); match stmt.node { StmtDecl(ref span, _) => { match span.node { DeclLocal(_) => block_span_err(span.span), // Item statements are allowed DeclItem(_) => {} } } StmtExpr(ref expr, _) => block_span_err(expr.span), StmtSemi(ref semi, _) => block_span_err(semi.span), StmtMac(..) => v.tcx.sess.span_bug(e.span, "unexpanded statement macro in const?!") } } match block.expr { Some(ref expr) => check_expr(v, &**expr, true), None => {} } } ExprVstore(_, ExprVstoreMutSlice) | ExprVstore(_, ExprVstoreSlice) | ExprVec(_) | ExprAddrOf(MutImmutable, _) | ExprParen(..) | ExprField(..) | ExprIndex(..) | ExprTup(..) | ExprRepeat(..) | ExprStruct(..) => { } ExprAddrOf(..) => { v.tcx.sess.span_err(e.span, "references in constants may only refer to \ immutable values"); }, ExprVstore(_, ExprVstoreUniq) => { v.tcx.sess.span_err(e.span, "cannot allocate vectors in constant expressions") }, _ => { v.tcx.sess.span_err(e.span, "constant contains unimplemented expression type"); return; } } } visit::walk_expr(v, e, is_const); } struct CheckItemRecursionVisitor<'a> { root_it: &'a Item, sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, idstack: Vec<NodeId> } // Make sure a const item doesn't recursively refer to itself // FIXME: Should use the dependency graph when it's available (#1356) pub fn check_item_recursion<'a>(sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, it: &'a Item) { let mut visitor = CheckItemRecursionVisitor { root_it: it, sess: sess, ast_map: ast_map, def_map: def_map, idstack: Vec::new() }; visitor.visit_item(it, ()); } impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> { fn visit_item(&mut self, it: &Item, _: ()) { if self.idstack.iter().any(|x| x == &(it.id)) { self.sess.span_fatal(self.root_it.span, "recursive constant"); } self.idstack.push(it.id); visit::walk_item(self, it, ()); self.idstack.pop(); } fn visit_expr(&mut self, e: &Expr, _: ()) { match e.node { ExprPath(..) => { match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(&*self.ast_map.expect_item(def_id.node), ()); } _ => () } }, _ => () } visit::walk_expr(self, e, ()); } }
Some(&DefStruct(_)) => { } Some(&def) => { debug!("(checking const) found bad def: {:?}", def);
random_line_split
check_const.rs
// Copyright 2012-2013 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 driver::session::Session; use middle::def::*; use middle::resolve; use middle::ty; use middle::typeck; use util::ppaux; use syntax::ast::*; use syntax::{ast_util, ast_map}; use syntax::visit::Visitor; use syntax::visit; pub struct CheckCrateVisitor<'a> { tcx: &'a ty::ctxt, } impl<'a> Visitor<bool> for CheckCrateVisitor<'a> { fn
(&mut self, i: &Item, env: bool) { check_item(self, i, env); } fn visit_pat(&mut self, p: &Pat, env: bool) { check_pat(self, p, env); } fn visit_expr(&mut self, ex: &Expr, env: bool) { check_expr(self, ex, env); } } pub fn check_crate(krate: &Crate, tcx: &ty::ctxt) { visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx }, krate, false); tcx.sess.abort_if_errors(); } fn check_item(v: &mut CheckCrateVisitor, it: &Item, _is_const: bool) { match it.node { ItemStatic(_, _, ex) => { v.visit_expr(&*ex, true); check_item_recursion(&v.tcx.sess, &v.tcx.map, &v.tcx.def_map, it); } ItemEnum(ref enum_definition, _) => { for var in (*enum_definition).variants.iter() { for ex in var.node.disr_expr.iter() { v.visit_expr(&**ex, true); } } } _ => visit::walk_item(v, it, false) } } fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) { fn is_str(e: &Expr) -> bool { match e.node { ExprVstore(expr, ExprVstoreUniq) => { match expr.node { ExprLit(lit) => ast_util::lit_is_str(lit), _ => false, } } _ => false, } } match p.node { // Let through plain ~-string literals here PatLit(ref a) => if!is_str(&**a) { v.visit_expr(&**a, true); }, PatRange(ref a, ref b) => { if!is_str(&**a) { v.visit_expr(&**a, true); } if!is_str(&**b) { v.visit_expr(&**b, true); } } _ => visit::walk_pat(v, p, false) } } fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) { if is_const { match e.node { ExprUnary(UnDeref, _) => { } ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => { v.tcx.sess.span_err(e.span, "cannot do allocations in constant expressions"); return; } ExprLit(lit) if ast_util::lit_is_str(lit) => {} ExprBinary(..) | ExprUnary(..) => { let method_call = typeck::MethodCall::expr(e.id); if v.tcx.method_map.borrow().contains_key(&method_call) { v.tcx.sess.span_err(e.span, "user-defined operators are not \ allowed in constant expressions"); } } ExprLit(_) => (), ExprCast(_, _) => { let ety = ty::expr_ty(v.tcx, e); if!ty::type_is_numeric(ety) &&!ty::type_is_unsafe_ptr(ety) { v.tcx .sess .span_err(e.span, format!("can not cast to `{}` in a constant \ expression", ppaux::ty_to_str(v.tcx, ety)).as_slice()) } } ExprPath(ref pth) => { // NB: In the future you might wish to relax this slightly // to handle on-demand instantiation of functions via // foo::<bar> in a const. Currently that is only done on // a path in trans::callee that only works in block contexts. if!pth.segments.iter().all(|segment| segment.types.is_empty()) { v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ items without type parameters"); } match v.tcx.def_map.borrow().find(&e.id) { Some(&DefStatic(..)) | Some(&DefFn(_, _)) | Some(&DefVariant(_, _, _)) | Some(&DefStruct(_)) => { } Some(&def) => { debug!("(checking const) found bad def: {:?}", def); v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ constants or functions"); } None => { v.tcx.sess.span_bug(e.span, "unbound path in const?!"); } } } ExprCall(callee, _) => { match v.tcx.def_map.borrow().find(&callee.id) { Some(&DefStruct(..)) => {} // OK. Some(&DefVariant(..)) => {} // OK. _ => { v.tcx.sess.span_err(e.span, "function calls in constants are limited to \ struct and enum constructors"); } } } ExprBlock(ref block) => { // Check all statements in the block for stmt in block.stmts.iter() { let block_span_err = |span| v.tcx.sess.span_err(span, "blocks in constants are limited to \ items and tail expressions"); match stmt.node { StmtDecl(ref span, _) => { match span.node { DeclLocal(_) => block_span_err(span.span), // Item statements are allowed DeclItem(_) => {} } } StmtExpr(ref expr, _) => block_span_err(expr.span), StmtSemi(ref semi, _) => block_span_err(semi.span), StmtMac(..) => v.tcx.sess.span_bug(e.span, "unexpanded statement macro in const?!") } } match block.expr { Some(ref expr) => check_expr(v, &**expr, true), None => {} } } ExprVstore(_, ExprVstoreMutSlice) | ExprVstore(_, ExprVstoreSlice) | ExprVec(_) | ExprAddrOf(MutImmutable, _) | ExprParen(..) | ExprField(..) | ExprIndex(..) | ExprTup(..) | ExprRepeat(..) | ExprStruct(..) => { } ExprAddrOf(..) => { v.tcx.sess.span_err(e.span, "references in constants may only refer to \ immutable values"); }, ExprVstore(_, ExprVstoreUniq) => { v.tcx.sess.span_err(e.span, "cannot allocate vectors in constant expressions") }, _ => { v.tcx.sess.span_err(e.span, "constant contains unimplemented expression type"); return; } } } visit::walk_expr(v, e, is_const); } struct CheckItemRecursionVisitor<'a> { root_it: &'a Item, sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, idstack: Vec<NodeId> } // Make sure a const item doesn't recursively refer to itself // FIXME: Should use the dependency graph when it's available (#1356) pub fn check_item_recursion<'a>(sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, it: &'a Item) { let mut visitor = CheckItemRecursionVisitor { root_it: it, sess: sess, ast_map: ast_map, def_map: def_map, idstack: Vec::new() }; visitor.visit_item(it, ()); } impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> { fn visit_item(&mut self, it: &Item, _: ()) { if self.idstack.iter().any(|x| x == &(it.id)) { self.sess.span_fatal(self.root_it.span, "recursive constant"); } self.idstack.push(it.id); visit::walk_item(self, it, ()); self.idstack.pop(); } fn visit_expr(&mut self, e: &Expr, _: ()) { match e.node { ExprPath(..) => { match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(&*self.ast_map.expect_item(def_id.node), ()); } _ => () } }, _ => () } visit::walk_expr(self, e, ()); } }
visit_item
identifier_name
check_const.rs
// Copyright 2012-2013 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 driver::session::Session; use middle::def::*; use middle::resolve; use middle::ty; use middle::typeck; use util::ppaux; use syntax::ast::*; use syntax::{ast_util, ast_map}; use syntax::visit::Visitor; use syntax::visit; pub struct CheckCrateVisitor<'a> { tcx: &'a ty::ctxt, } impl<'a> Visitor<bool> for CheckCrateVisitor<'a> { fn visit_item(&mut self, i: &Item, env: bool) { check_item(self, i, env); } fn visit_pat(&mut self, p: &Pat, env: bool) { check_pat(self, p, env); } fn visit_expr(&mut self, ex: &Expr, env: bool) { check_expr(self, ex, env); } } pub fn check_crate(krate: &Crate, tcx: &ty::ctxt) { visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx }, krate, false); tcx.sess.abort_if_errors(); } fn check_item(v: &mut CheckCrateVisitor, it: &Item, _is_const: bool) { match it.node { ItemStatic(_, _, ex) => { v.visit_expr(&*ex, true); check_item_recursion(&v.tcx.sess, &v.tcx.map, &v.tcx.def_map, it); } ItemEnum(ref enum_definition, _) => { for var in (*enum_definition).variants.iter() { for ex in var.node.disr_expr.iter() { v.visit_expr(&**ex, true); } } } _ => visit::walk_item(v, it, false) } } fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) { fn is_str(e: &Expr) -> bool { match e.node { ExprVstore(expr, ExprVstoreUniq) => { match expr.node { ExprLit(lit) => ast_util::lit_is_str(lit), _ => false, } } _ => false, } } match p.node { // Let through plain ~-string literals here PatLit(ref a) => if!is_str(&**a) { v.visit_expr(&**a, true); }, PatRange(ref a, ref b) => { if!is_str(&**a) { v.visit_expr(&**a, true); } if!is_str(&**b) { v.visit_expr(&**b, true); } } _ => visit::walk_pat(v, p, false) } } fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) { if is_const { match e.node { ExprUnary(UnDeref, _) => { } ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => { v.tcx.sess.span_err(e.span, "cannot do allocations in constant expressions"); return; } ExprLit(lit) if ast_util::lit_is_str(lit) => {} ExprBinary(..) | ExprUnary(..) => { let method_call = typeck::MethodCall::expr(e.id); if v.tcx.method_map.borrow().contains_key(&method_call) { v.tcx.sess.span_err(e.span, "user-defined operators are not \ allowed in constant expressions"); } } ExprLit(_) => (), ExprCast(_, _) => { let ety = ty::expr_ty(v.tcx, e); if!ty::type_is_numeric(ety) &&!ty::type_is_unsafe_ptr(ety) { v.tcx .sess .span_err(e.span, format!("can not cast to `{}` in a constant \ expression", ppaux::ty_to_str(v.tcx, ety)).as_slice()) } } ExprPath(ref pth) => { // NB: In the future you might wish to relax this slightly // to handle on-demand instantiation of functions via // foo::<bar> in a const. Currently that is only done on // a path in trans::callee that only works in block contexts. if!pth.segments.iter().all(|segment| segment.types.is_empty()) { v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ items without type parameters"); } match v.tcx.def_map.borrow().find(&e.id) { Some(&DefStatic(..)) | Some(&DefFn(_, _)) | Some(&DefVariant(_, _, _)) | Some(&DefStruct(_)) =>
Some(&def) => { debug!("(checking const) found bad def: {:?}", def); v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ constants or functions"); } None => { v.tcx.sess.span_bug(e.span, "unbound path in const?!"); } } } ExprCall(callee, _) => { match v.tcx.def_map.borrow().find(&callee.id) { Some(&DefStruct(..)) => {} // OK. Some(&DefVariant(..)) => {} // OK. _ => { v.tcx.sess.span_err(e.span, "function calls in constants are limited to \ struct and enum constructors"); } } } ExprBlock(ref block) => { // Check all statements in the block for stmt in block.stmts.iter() { let block_span_err = |span| v.tcx.sess.span_err(span, "blocks in constants are limited to \ items and tail expressions"); match stmt.node { StmtDecl(ref span, _) => { match span.node { DeclLocal(_) => block_span_err(span.span), // Item statements are allowed DeclItem(_) => {} } } StmtExpr(ref expr, _) => block_span_err(expr.span), StmtSemi(ref semi, _) => block_span_err(semi.span), StmtMac(..) => v.tcx.sess.span_bug(e.span, "unexpanded statement macro in const?!") } } match block.expr { Some(ref expr) => check_expr(v, &**expr, true), None => {} } } ExprVstore(_, ExprVstoreMutSlice) | ExprVstore(_, ExprVstoreSlice) | ExprVec(_) | ExprAddrOf(MutImmutable, _) | ExprParen(..) | ExprField(..) | ExprIndex(..) | ExprTup(..) | ExprRepeat(..) | ExprStruct(..) => { } ExprAddrOf(..) => { v.tcx.sess.span_err(e.span, "references in constants may only refer to \ immutable values"); }, ExprVstore(_, ExprVstoreUniq) => { v.tcx.sess.span_err(e.span, "cannot allocate vectors in constant expressions") }, _ => { v.tcx.sess.span_err(e.span, "constant contains unimplemented expression type"); return; } } } visit::walk_expr(v, e, is_const); } struct CheckItemRecursionVisitor<'a> { root_it: &'a Item, sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, idstack: Vec<NodeId> } // Make sure a const item doesn't recursively refer to itself // FIXME: Should use the dependency graph when it's available (#1356) pub fn check_item_recursion<'a>(sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, it: &'a Item) { let mut visitor = CheckItemRecursionVisitor { root_it: it, sess: sess, ast_map: ast_map, def_map: def_map, idstack: Vec::new() }; visitor.visit_item(it, ()); } impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> { fn visit_item(&mut self, it: &Item, _: ()) { if self.idstack.iter().any(|x| x == &(it.id)) { self.sess.span_fatal(self.root_it.span, "recursive constant"); } self.idstack.push(it.id); visit::walk_item(self, it, ()); self.idstack.pop(); } fn visit_expr(&mut self, e: &Expr, _: ()) { match e.node { ExprPath(..) => { match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(&*self.ast_map.expect_item(def_id.node), ()); } _ => () } }, _ => () } visit::walk_expr(self, e, ()); } }
{ }
conditional_block
check_const.rs
// Copyright 2012-2013 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 driver::session::Session; use middle::def::*; use middle::resolve; use middle::ty; use middle::typeck; use util::ppaux; use syntax::ast::*; use syntax::{ast_util, ast_map}; use syntax::visit::Visitor; use syntax::visit; pub struct CheckCrateVisitor<'a> { tcx: &'a ty::ctxt, } impl<'a> Visitor<bool> for CheckCrateVisitor<'a> { fn visit_item(&mut self, i: &Item, env: bool) { check_item(self, i, env); } fn visit_pat(&mut self, p: &Pat, env: bool) { check_pat(self, p, env); } fn visit_expr(&mut self, ex: &Expr, env: bool) { check_expr(self, ex, env); } } pub fn check_crate(krate: &Crate, tcx: &ty::ctxt) { visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx }, krate, false); tcx.sess.abort_if_errors(); } fn check_item(v: &mut CheckCrateVisitor, it: &Item, _is_const: bool) { match it.node { ItemStatic(_, _, ex) => { v.visit_expr(&*ex, true); check_item_recursion(&v.tcx.sess, &v.tcx.map, &v.tcx.def_map, it); } ItemEnum(ref enum_definition, _) => { for var in (*enum_definition).variants.iter() { for ex in var.node.disr_expr.iter() { v.visit_expr(&**ex, true); } } } _ => visit::walk_item(v, it, false) } } fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) { fn is_str(e: &Expr) -> bool { match e.node { ExprVstore(expr, ExprVstoreUniq) => { match expr.node { ExprLit(lit) => ast_util::lit_is_str(lit), _ => false, } } _ => false, } } match p.node { // Let through plain ~-string literals here PatLit(ref a) => if!is_str(&**a) { v.visit_expr(&**a, true); }, PatRange(ref a, ref b) => { if!is_str(&**a) { v.visit_expr(&**a, true); } if!is_str(&**b) { v.visit_expr(&**b, true); } } _ => visit::walk_pat(v, p, false) } } fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) { if is_const { match e.node { ExprUnary(UnDeref, _) => { } ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => { v.tcx.sess.span_err(e.span, "cannot do allocations in constant expressions"); return; } ExprLit(lit) if ast_util::lit_is_str(lit) => {} ExprBinary(..) | ExprUnary(..) => { let method_call = typeck::MethodCall::expr(e.id); if v.tcx.method_map.borrow().contains_key(&method_call) { v.tcx.sess.span_err(e.span, "user-defined operators are not \ allowed in constant expressions"); } } ExprLit(_) => (), ExprCast(_, _) => { let ety = ty::expr_ty(v.tcx, e); if!ty::type_is_numeric(ety) &&!ty::type_is_unsafe_ptr(ety) { v.tcx .sess .span_err(e.span, format!("can not cast to `{}` in a constant \ expression", ppaux::ty_to_str(v.tcx, ety)).as_slice()) } } ExprPath(ref pth) => { // NB: In the future you might wish to relax this slightly // to handle on-demand instantiation of functions via // foo::<bar> in a const. Currently that is only done on // a path in trans::callee that only works in block contexts. if!pth.segments.iter().all(|segment| segment.types.is_empty()) { v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ items without type parameters"); } match v.tcx.def_map.borrow().find(&e.id) { Some(&DefStatic(..)) | Some(&DefFn(_, _)) | Some(&DefVariant(_, _, _)) | Some(&DefStruct(_)) => { } Some(&def) => { debug!("(checking const) found bad def: {:?}", def); v.tcx.sess.span_err(e.span, "paths in constants may only refer to \ constants or functions"); } None => { v.tcx.sess.span_bug(e.span, "unbound path in const?!"); } } } ExprCall(callee, _) => { match v.tcx.def_map.borrow().find(&callee.id) { Some(&DefStruct(..)) => {} // OK. Some(&DefVariant(..)) => {} // OK. _ => { v.tcx.sess.span_err(e.span, "function calls in constants are limited to \ struct and enum constructors"); } } } ExprBlock(ref block) => { // Check all statements in the block for stmt in block.stmts.iter() { let block_span_err = |span| v.tcx.sess.span_err(span, "blocks in constants are limited to \ items and tail expressions"); match stmt.node { StmtDecl(ref span, _) => { match span.node { DeclLocal(_) => block_span_err(span.span), // Item statements are allowed DeclItem(_) => {} } } StmtExpr(ref expr, _) => block_span_err(expr.span), StmtSemi(ref semi, _) => block_span_err(semi.span), StmtMac(..) => v.tcx.sess.span_bug(e.span, "unexpanded statement macro in const?!") } } match block.expr { Some(ref expr) => check_expr(v, &**expr, true), None => {} } } ExprVstore(_, ExprVstoreMutSlice) | ExprVstore(_, ExprVstoreSlice) | ExprVec(_) | ExprAddrOf(MutImmutable, _) | ExprParen(..) | ExprField(..) | ExprIndex(..) | ExprTup(..) | ExprRepeat(..) | ExprStruct(..) => { } ExprAddrOf(..) => { v.tcx.sess.span_err(e.span, "references in constants may only refer to \ immutable values"); }, ExprVstore(_, ExprVstoreUniq) => { v.tcx.sess.span_err(e.span, "cannot allocate vectors in constant expressions") }, _ => { v.tcx.sess.span_err(e.span, "constant contains unimplemented expression type"); return; } } } visit::walk_expr(v, e, is_const); } struct CheckItemRecursionVisitor<'a> { root_it: &'a Item, sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, idstack: Vec<NodeId> } // Make sure a const item doesn't recursively refer to itself // FIXME: Should use the dependency graph when it's available (#1356) pub fn check_item_recursion<'a>(sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, it: &'a Item) { let mut visitor = CheckItemRecursionVisitor { root_it: it, sess: sess, ast_map: ast_map, def_map: def_map, idstack: Vec::new() }; visitor.visit_item(it, ()); } impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> { fn visit_item(&mut self, it: &Item, _: ())
fn visit_expr(&mut self, e: &Expr, _: ()) { match e.node { ExprPath(..) => { match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(&*self.ast_map.expect_item(def_id.node), ()); } _ => () } }, _ => () } visit::walk_expr(self, e, ()); } }
{ if self.idstack.iter().any(|x| x == &(it.id)) { self.sess.span_fatal(self.root_it.span, "recursive constant"); } self.idstack.push(it.id); visit::walk_item(self, it, ()); self.idstack.pop(); }
identifier_body
cell_manhattan_inv.rs
// Copyright 2015 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! An example of using cell range noise extern crate noise; use noise::{cell2_manhattan_inv, cell3_manhattan_inv, cell4_manhattan_inv, Seed, Point2}; mod debug; fn main() { debug::render_png("cell2_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell2_manhattan_inv); debug::render_png("cell3_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell3_manhattan_inv); debug::render_png("cell4_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell4_manhattan_inv); println!("\nGenerated cell2_manhattan_inv.png, cell3_manhattan_inv.png and cell4_manhattan_inv.png"); } fn scaled_cell2_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell2_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0 } fn scaled_cell3_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell3_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 16.0]) * 2.0 - 1.0 } fn scaled_cell4_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64
{ cell4_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0 }
identifier_body
cell_manhattan_inv.rs
// Copyright 2015 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // limitations under the License. //! An example of using cell range noise extern crate noise; use noise::{cell2_manhattan_inv, cell3_manhattan_inv, cell4_manhattan_inv, Seed, Point2}; mod debug; fn main() { debug::render_png("cell2_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell2_manhattan_inv); debug::render_png("cell3_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell3_manhattan_inv); debug::render_png("cell4_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell4_manhattan_inv); println!("\nGenerated cell2_manhattan_inv.png, cell3_manhattan_inv.png and cell4_manhattan_inv.png"); } fn scaled_cell2_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell2_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0 } fn scaled_cell3_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell3_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 16.0]) * 2.0 - 1.0 } fn scaled_cell4_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell4_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0 }
random_line_split
cell_manhattan_inv.rs
// Copyright 2015 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! An example of using cell range noise extern crate noise; use noise::{cell2_manhattan_inv, cell3_manhattan_inv, cell4_manhattan_inv, Seed, Point2}; mod debug; fn
() { debug::render_png("cell2_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell2_manhattan_inv); debug::render_png("cell3_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell3_manhattan_inv); debug::render_png("cell4_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell4_manhattan_inv); println!("\nGenerated cell2_manhattan_inv.png, cell3_manhattan_inv.png and cell4_manhattan_inv.png"); } fn scaled_cell2_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell2_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0 } fn scaled_cell3_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell3_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 16.0]) * 2.0 - 1.0 } fn scaled_cell4_manhattan_inv(seed: &Seed, point: &Point2<f64>) -> f64 { cell4_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0 }
main
identifier_name
enum.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use winreg::enums::*; use winreg::RegKey; fn main() -> io::Result<()> { println!("File extensions, registered in system:"); for i in RegKey::predef(HKEY_CLASSES_ROOT) .enum_keys() .map(|x| x.unwrap()) .filter(|x| x.starts_with('.')) { println!("{}", i); } let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("HARDWARE\\DESCRIPTION\\System")?; for (name, value) in system.enum_values().map(|x| x.unwrap()) {
Ok(()) }
println!("{} = {:?}", name, value); }
random_line_split
enum.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use winreg::enums::*; use winreg::RegKey; fn main() -> io::Result<()>
{ println!("File extensions, registered in system:"); for i in RegKey::predef(HKEY_CLASSES_ROOT) .enum_keys() .map(|x| x.unwrap()) .filter(|x| x.starts_with('.')) { println!("{}", i); } let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("HARDWARE\\DESCRIPTION\\System")?; for (name, value) in system.enum_values().map(|x| x.unwrap()) { println!("{} = {:?}", name, value); } Ok(()) }
identifier_body
enum.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use winreg::enums::*; use winreg::RegKey; fn
() -> io::Result<()> { println!("File extensions, registered in system:"); for i in RegKey::predef(HKEY_CLASSES_ROOT) .enum_keys() .map(|x| x.unwrap()) .filter(|x| x.starts_with('.')) { println!("{}", i); } let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("HARDWARE\\DESCRIPTION\\System")?; for (name, value) in system.enum_values().map(|x| x.unwrap()) { println!("{} = {:?}", name, value); } Ok(()) }
main
identifier_name
article.rs
use chrono::naive::NaiveDateTime; use serde::{Deserialize, Serialize}; use validator::Validate; use crate::schema::articles; #[derive(Debug, Clone, Queryable, Insertable, Serialize, Deserialize)] pub struct Article { pub id: i32, pub author_id: i32, pub in_reply_to: Option<String>,
pub article_format: String, pub excerpt: Option<String>, pub body: String, pub published: bool, pub inserted_at: NaiveDateTime, pub updated_at: NaiveDateTime, pub posse: bool, pub lang: String, } #[derive(Deserialize, Serialize, Debug, Insertable, Clone, Validate, Default)] #[table_name = "articles"] pub struct NewArticle { pub author_id: Option<i32>, pub in_reply_to: Option<String>, #[validate(length(min = 3, max = 255))] pub title: String, #[validate(length(min = 3, max = 255))] pub slug: String, pub guid: Option<String>, pub article_format: Option<String>, pub excerpt: Option<String>, #[validate(length(min = 3, max = 255))] pub body: String, #[serde(default)] pub published: bool, #[serde(default)] pub posse: bool, #[validate(length(min = 2, max = 2))] pub lang: String, pub inserted_at: Option<NaiveDateTime>, pub updated_at: Option<NaiveDateTime>, }
pub title: String, pub slug: String, pub guid: String,
random_line_split
article.rs
use chrono::naive::NaiveDateTime; use serde::{Deserialize, Serialize}; use validator::Validate; use crate::schema::articles; #[derive(Debug, Clone, Queryable, Insertable, Serialize, Deserialize)] pub struct Article { pub id: i32, pub author_id: i32, pub in_reply_to: Option<String>, pub title: String, pub slug: String, pub guid: String, pub article_format: String, pub excerpt: Option<String>, pub body: String, pub published: bool, pub inserted_at: NaiveDateTime, pub updated_at: NaiveDateTime, pub posse: bool, pub lang: String, } #[derive(Deserialize, Serialize, Debug, Insertable, Clone, Validate, Default)] #[table_name = "articles"] pub struct
{ pub author_id: Option<i32>, pub in_reply_to: Option<String>, #[validate(length(min = 3, max = 255))] pub title: String, #[validate(length(min = 3, max = 255))] pub slug: String, pub guid: Option<String>, pub article_format: Option<String>, pub excerpt: Option<String>, #[validate(length(min = 3, max = 255))] pub body: String, #[serde(default)] pub published: bool, #[serde(default)] pub posse: bool, #[validate(length(min = 2, max = 2))] pub lang: String, pub inserted_at: Option<NaiveDateTime>, pub updated_at: Option<NaiveDateTime>, }
NewArticle
identifier_name
chrono.rs
//! This module makes it possible to map `chrono::DateTime` values to postgres `Date` //! and `Timestamp` fields. It is enabled with the `chrono` feature. extern crate chrono; use std::error::Error; use std::io::Write; use self::chrono::{Duration, NaiveDateTime, NaiveDate, NaiveTime}; use expression::AsExpression; use expression::bound::Bound; use query_source::Queryable; use super::{PgTime, PgTimestamp}; use types::{self, FromSql, IsNull, Time, Timestamp, ToSql}; expression_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } queryable_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } // Postgres timestamps start from January 1st 2000. fn pg_epoch() -> NaiveDateTime { NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0) } impl FromSql<Timestamp> for NaiveDateTime { fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error>> { let PgTimestamp(offset) = try!(FromSql::<Timestamp>::from_sql(bytes)); Ok(pg_epoch() + Duration::microseconds(offset)) } } impl ToSql<Timestamp> for NaiveDateTime { fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error>> { let time = match (*self - pg_epoch()).num_microseconds() { Some(time) => time, None => { let error_message = format!("{:?} as microseconds is too large to fit in an i64", self); return Err(Box::<Error + Send + Sync>::from(error_message)); } }; ToSql::<Timestamp>::to_sql(&PgTimestamp(time), out) } } fn midnight() -> NaiveTime { NaiveTime::from_hms(0, 0, 0) } impl ToSql<Time> for NaiveTime { fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error>> { let duration = *self - midnight(); match duration.num_microseconds() { Some(offset) => ToSql::<Time>::to_sql(&PgTime(offset), out), None => unreachable!() } } } impl FromSql<Time> for NaiveTime { fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error>> { let PgTime(offset) = try!(FromSql::<Time>::from_sql(bytes)); let duration = Duration::microseconds(offset); Ok(midnight() + duration) } } #[cfg(test)] mod tests { extern crate dotenv; extern crate chrono; use self::chrono::*; use self::dotenv::dotenv; use ::select; use connection::Connection; use expression::dsl::{sql, now}; use prelude::*; use types::{Time, Timestamp}; fn connection() -> Connection { dotenv().ok(); let connection_url = ::std::env::var("DATABASE_URL").ok() .expect("DATABASE_URL must be set in order to run tests"); Connection::establish(&connection_url).unwrap() } #[test] fn unix_epoch_encodes_correctly() { let connection = connection(); let time = NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0); let query = select(sql::<Timestamp>("'1970-01-01'").eq(time)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn unix_epoch_decodes_correctly() { let connection = connection(); let time = NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0); let epoch_from_sql = select(sql::<Timestamp>("'1970-01-01'::timestamp")) .get_result(&connection); assert_eq!(Ok(time), epoch_from_sql); } #[test] fn times_relative_to_now_encode_correctly() { let connection = connection(); let time = UTC::now().naive_utc() + Duration::seconds(60); let query = select(now.at_time_zone("utc").lt(time)); assert!(query.get_result::<bool>(&connection).unwrap()); let time = UTC::now().naive_utc() - Duration::seconds(60); let query = select(now.at_time_zone("utc").gt(time)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn times_of_day_encode_correctly() { let connection = connection(); let midnight = NaiveTime::from_hms(0, 0, 0); let query = select(sql::<Time>("'00:00:00'::time").eq(midnight)); assert!(query.get_result::<bool>(&connection).unwrap()); let noon = NaiveTime::from_hms(12, 0, 0); let query = select(sql::<Time>("'12:00:00'::time").eq(noon)); assert!(query.get_result::<bool>(&connection).unwrap()); let roughly_half_past_eleven = NaiveTime::from_hms_micro(23, 37, 04, 2200); let query = select(sql::<Time>("'23:37:04.002200'::time").eq(roughly_half_past_eleven)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn times_of_day_decode_correctly()
}
{ let connection = connection(); let midnight = NaiveTime::from_hms(0, 0, 0); let query = select(sql::<Time>("'00:00:00'::time")); assert_eq!(Ok(midnight), query.get_result::<NaiveTime>(&connection)); let noon = NaiveTime::from_hms(12, 0, 0); let query = select(sql::<Time>("'12:00:00'::time")); assert_eq!(Ok(noon), query.get_result::<NaiveTime>(&connection)); let roughly_half_past_eleven = NaiveTime::from_hms_micro(23, 37, 04, 2200); let query = select(sql::<Time>("'23:37:04.002200'::time")); assert_eq!(Ok(roughly_half_past_eleven), query.get_result::<NaiveTime>(&connection)); }
identifier_body
chrono.rs
//! This module makes it possible to map `chrono::DateTime` values to postgres `Date` //! and `Timestamp` fields. It is enabled with the `chrono` feature. extern crate chrono; use std::error::Error;
use query_source::Queryable; use super::{PgTime, PgTimestamp}; use types::{self, FromSql, IsNull, Time, Timestamp, ToSql}; expression_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } queryable_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } // Postgres timestamps start from January 1st 2000. fn pg_epoch() -> NaiveDateTime { NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0) } impl FromSql<Timestamp> for NaiveDateTime { fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error>> { let PgTimestamp(offset) = try!(FromSql::<Timestamp>::from_sql(bytes)); Ok(pg_epoch() + Duration::microseconds(offset)) } } impl ToSql<Timestamp> for NaiveDateTime { fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error>> { let time = match (*self - pg_epoch()).num_microseconds() { Some(time) => time, None => { let error_message = format!("{:?} as microseconds is too large to fit in an i64", self); return Err(Box::<Error + Send + Sync>::from(error_message)); } }; ToSql::<Timestamp>::to_sql(&PgTimestamp(time), out) } } fn midnight() -> NaiveTime { NaiveTime::from_hms(0, 0, 0) } impl ToSql<Time> for NaiveTime { fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error>> { let duration = *self - midnight(); match duration.num_microseconds() { Some(offset) => ToSql::<Time>::to_sql(&PgTime(offset), out), None => unreachable!() } } } impl FromSql<Time> for NaiveTime { fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error>> { let PgTime(offset) = try!(FromSql::<Time>::from_sql(bytes)); let duration = Duration::microseconds(offset); Ok(midnight() + duration) } } #[cfg(test)] mod tests { extern crate dotenv; extern crate chrono; use self::chrono::*; use self::dotenv::dotenv; use ::select; use connection::Connection; use expression::dsl::{sql, now}; use prelude::*; use types::{Time, Timestamp}; fn connection() -> Connection { dotenv().ok(); let connection_url = ::std::env::var("DATABASE_URL").ok() .expect("DATABASE_URL must be set in order to run tests"); Connection::establish(&connection_url).unwrap() } #[test] fn unix_epoch_encodes_correctly() { let connection = connection(); let time = NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0); let query = select(sql::<Timestamp>("'1970-01-01'").eq(time)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn unix_epoch_decodes_correctly() { let connection = connection(); let time = NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0); let epoch_from_sql = select(sql::<Timestamp>("'1970-01-01'::timestamp")) .get_result(&connection); assert_eq!(Ok(time), epoch_from_sql); } #[test] fn times_relative_to_now_encode_correctly() { let connection = connection(); let time = UTC::now().naive_utc() + Duration::seconds(60); let query = select(now.at_time_zone("utc").lt(time)); assert!(query.get_result::<bool>(&connection).unwrap()); let time = UTC::now().naive_utc() - Duration::seconds(60); let query = select(now.at_time_zone("utc").gt(time)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn times_of_day_encode_correctly() { let connection = connection(); let midnight = NaiveTime::from_hms(0, 0, 0); let query = select(sql::<Time>("'00:00:00'::time").eq(midnight)); assert!(query.get_result::<bool>(&connection).unwrap()); let noon = NaiveTime::from_hms(12, 0, 0); let query = select(sql::<Time>("'12:00:00'::time").eq(noon)); assert!(query.get_result::<bool>(&connection).unwrap()); let roughly_half_past_eleven = NaiveTime::from_hms_micro(23, 37, 04, 2200); let query = select(sql::<Time>("'23:37:04.002200'::time").eq(roughly_half_past_eleven)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn times_of_day_decode_correctly() { let connection = connection(); let midnight = NaiveTime::from_hms(0, 0, 0); let query = select(sql::<Time>("'00:00:00'::time")); assert_eq!(Ok(midnight), query.get_result::<NaiveTime>(&connection)); let noon = NaiveTime::from_hms(12, 0, 0); let query = select(sql::<Time>("'12:00:00'::time")); assert_eq!(Ok(noon), query.get_result::<NaiveTime>(&connection)); let roughly_half_past_eleven = NaiveTime::from_hms_micro(23, 37, 04, 2200); let query = select(sql::<Time>("'23:37:04.002200'::time")); assert_eq!(Ok(roughly_half_past_eleven), query.get_result::<NaiveTime>(&connection)); } }
use std::io::Write; use self::chrono::{Duration, NaiveDateTime, NaiveDate, NaiveTime}; use expression::AsExpression; use expression::bound::Bound;
random_line_split
chrono.rs
//! This module makes it possible to map `chrono::DateTime` values to postgres `Date` //! and `Timestamp` fields. It is enabled with the `chrono` feature. extern crate chrono; use std::error::Error; use std::io::Write; use self::chrono::{Duration, NaiveDateTime, NaiveDate, NaiveTime}; use expression::AsExpression; use expression::bound::Bound; use query_source::Queryable; use super::{PgTime, PgTimestamp}; use types::{self, FromSql, IsNull, Time, Timestamp, ToSql}; expression_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } queryable_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } // Postgres timestamps start from January 1st 2000. fn pg_epoch() -> NaiveDateTime { NaiveDate::from_ymd(2000, 1, 1).and_hms(0, 0, 0) } impl FromSql<Timestamp> for NaiveDateTime { fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error>> { let PgTimestamp(offset) = try!(FromSql::<Timestamp>::from_sql(bytes)); Ok(pg_epoch() + Duration::microseconds(offset)) } } impl ToSql<Timestamp> for NaiveDateTime { fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error>> { let time = match (*self - pg_epoch()).num_microseconds() { Some(time) => time, None => { let error_message = format!("{:?} as microseconds is too large to fit in an i64", self); return Err(Box::<Error + Send + Sync>::from(error_message)); } }; ToSql::<Timestamp>::to_sql(&PgTimestamp(time), out) } } fn midnight() -> NaiveTime { NaiveTime::from_hms(0, 0, 0) } impl ToSql<Time> for NaiveTime { fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error>> { let duration = *self - midnight(); match duration.num_microseconds() { Some(offset) => ToSql::<Time>::to_sql(&PgTime(offset), out), None => unreachable!() } } } impl FromSql<Time> for NaiveTime { fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error>> { let PgTime(offset) = try!(FromSql::<Time>::from_sql(bytes)); let duration = Duration::microseconds(offset); Ok(midnight() + duration) } } #[cfg(test)] mod tests { extern crate dotenv; extern crate chrono; use self::chrono::*; use self::dotenv::dotenv; use ::select; use connection::Connection; use expression::dsl::{sql, now}; use prelude::*; use types::{Time, Timestamp}; fn
() -> Connection { dotenv().ok(); let connection_url = ::std::env::var("DATABASE_URL").ok() .expect("DATABASE_URL must be set in order to run tests"); Connection::establish(&connection_url).unwrap() } #[test] fn unix_epoch_encodes_correctly() { let connection = connection(); let time = NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0); let query = select(sql::<Timestamp>("'1970-01-01'").eq(time)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn unix_epoch_decodes_correctly() { let connection = connection(); let time = NaiveDate::from_ymd(1970, 1, 1).and_hms(0, 0, 0); let epoch_from_sql = select(sql::<Timestamp>("'1970-01-01'::timestamp")) .get_result(&connection); assert_eq!(Ok(time), epoch_from_sql); } #[test] fn times_relative_to_now_encode_correctly() { let connection = connection(); let time = UTC::now().naive_utc() + Duration::seconds(60); let query = select(now.at_time_zone("utc").lt(time)); assert!(query.get_result::<bool>(&connection).unwrap()); let time = UTC::now().naive_utc() - Duration::seconds(60); let query = select(now.at_time_zone("utc").gt(time)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn times_of_day_encode_correctly() { let connection = connection(); let midnight = NaiveTime::from_hms(0, 0, 0); let query = select(sql::<Time>("'00:00:00'::time").eq(midnight)); assert!(query.get_result::<bool>(&connection).unwrap()); let noon = NaiveTime::from_hms(12, 0, 0); let query = select(sql::<Time>("'12:00:00'::time").eq(noon)); assert!(query.get_result::<bool>(&connection).unwrap()); let roughly_half_past_eleven = NaiveTime::from_hms_micro(23, 37, 04, 2200); let query = select(sql::<Time>("'23:37:04.002200'::time").eq(roughly_half_past_eleven)); assert!(query.get_result::<bool>(&connection).unwrap()); } #[test] fn times_of_day_decode_correctly() { let connection = connection(); let midnight = NaiveTime::from_hms(0, 0, 0); let query = select(sql::<Time>("'00:00:00'::time")); assert_eq!(Ok(midnight), query.get_result::<NaiveTime>(&connection)); let noon = NaiveTime::from_hms(12, 0, 0); let query = select(sql::<Time>("'12:00:00'::time")); assert_eq!(Ok(noon), query.get_result::<NaiveTime>(&connection)); let roughly_half_past_eleven = NaiveTime::from_hms_micro(23, 37, 04, 2200); let query = select(sql::<Time>("'23:37:04.002200'::time")); assert_eq!(Ok(roughly_half_past_eleven), query.get_result::<NaiveTime>(&connection)); } }
connection
identifier_name
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_xml_rs; extern crate quick_xml; //extern crate serde_derive; use std::env; use std::fs::File; use std::io::prelude::*; use std::str; use serde_xml_rs::deserialize; mod server; mod iso8583_parser; struct Configuration { address: String, port: String, } //read connection configuration from config.xml and set it in 'Configuration' struct fn read_configuration() -> Configuration { use quick_xml::reader::Reader; use quick_xml::events::Event; let mut cfg: Configuration = Configuration { address: String::new (), port: String::new () }; let mut file = File::open("config.xml").expect("config file not found"); let mut contents = String::new(); file.read_to_string(&mut contents) .expect("something went wrong reading the file"); let mut reader = Reader::from_str(&mut contents); reader.trim_text(true); let mut bind_address = Vec::new(); let mut port = Vec::new(); let mut buf = Vec::new(); loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) if e.name() == b"bind_address" => { bind_address.push( reader .read_text(b"bind_address", &mut Vec::new()) .expect("Cannot decode text value"), ); cfg.address =bind_address.pop().unwrap(); println!("{:?}", cfg.address); } Ok(Event::Start(ref e)) if e.name() == b"port" => { port.push( reader .read_text(b"port", &mut Vec::new()) .expect("Cannot decode text value"), ); cfg.port =port.pop().unwrap(); println!("{:?}", cfg.port); } Ok(Event::Eof) => break, // exits the loop when reaching end of file Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), // There are several other `Event`s we do not consider here } buf.clear(); } cfg } fn main()
{ let config :Configuration; config = read_configuration(); let listening_address = format!("{}:{}", config.address, config.port); server::start_listening(listening_address); }
identifier_body
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_xml_rs; extern crate quick_xml; //extern crate serde_derive; use std::env; use std::fs::File; use std::io::prelude::*; use std::str; use serde_xml_rs::deserialize; mod server; mod iso8583_parser; struct Configuration { address: String, port: String, } //read connection configuration from config.xml and set it in 'Configuration' struct fn read_configuration() -> Configuration { use quick_xml::reader::Reader; use quick_xml::events::Event; let mut cfg: Configuration = Configuration { address: String::new (), port: String::new () }; let mut file = File::open("config.xml").expect("config file not found"); let mut contents = String::new(); file.read_to_string(&mut contents) .expect("something went wrong reading the file"); let mut reader = Reader::from_str(&mut contents); reader.trim_text(true); let mut bind_address = Vec::new(); let mut port = Vec::new(); let mut buf = Vec::new(); loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) if e.name() == b"bind_address" => { bind_address.push( reader .read_text(b"bind_address", &mut Vec::new()) .expect("Cannot decode text value"), ); cfg.address =bind_address.pop().unwrap(); println!("{:?}", cfg.address); } Ok(Event::Start(ref e)) if e.name() == b"port" => { port.push( reader .read_text(b"port", &mut Vec::new()) .expect("Cannot decode text value"), ); cfg.port =port.pop().unwrap(); println!("{:?}", cfg.port); } Ok(Event::Eof) => break, // exits the loop when reaching end of file Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), // There are several other `Event`s we do not consider here } buf.clear(); } cfg } fn
() { let config :Configuration; config = read_configuration(); let listening_address = format!("{}:{}", config.address, config.port); server::start_listening(listening_address); }
main
identifier_name
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_xml_rs; extern crate quick_xml; //extern crate serde_derive; use std::env; use std::fs::File; use std::io::prelude::*;
mod server; mod iso8583_parser; struct Configuration { address: String, port: String, } //read connection configuration from config.xml and set it in 'Configuration' struct fn read_configuration() -> Configuration { use quick_xml::reader::Reader; use quick_xml::events::Event; let mut cfg: Configuration = Configuration { address: String::new (), port: String::new () }; let mut file = File::open("config.xml").expect("config file not found"); let mut contents = String::new(); file.read_to_string(&mut contents) .expect("something went wrong reading the file"); let mut reader = Reader::from_str(&mut contents); reader.trim_text(true); let mut bind_address = Vec::new(); let mut port = Vec::new(); let mut buf = Vec::new(); loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) if e.name() == b"bind_address" => { bind_address.push( reader .read_text(b"bind_address", &mut Vec::new()) .expect("Cannot decode text value"), ); cfg.address =bind_address.pop().unwrap(); println!("{:?}", cfg.address); } Ok(Event::Start(ref e)) if e.name() == b"port" => { port.push( reader .read_text(b"port", &mut Vec::new()) .expect("Cannot decode text value"), ); cfg.port =port.pop().unwrap(); println!("{:?}", cfg.port); } Ok(Event::Eof) => break, // exits the loop when reaching end of file Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), // There are several other `Event`s we do not consider here } buf.clear(); } cfg } fn main() { let config :Configuration; config = read_configuration(); let listening_address = format!("{}:{}", config.address, config.port); server::start_listening(listening_address); }
use std::str; use serde_xml_rs::deserialize;
random_line_split
issue-13560.rs
// 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. // aux-build:issue-13560-1.rs // aux-build:issue-13560-2.rs // aux-build:issue-13560-3.rs // ignore-stage1 // Regression test for issue #13560, the test itself is all in the dependent // libraries. The fail which previously failed to compile is the one numbered 3. extern crate issue_13560_2 as t2; extern crate issue_13560_3 as t3;
fn main() {}
random_line_split
issue-13560.rs
// 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. // aux-build:issue-13560-1.rs // aux-build:issue-13560-2.rs // aux-build:issue-13560-3.rs // ignore-stage1 // Regression test for issue #13560, the test itself is all in the dependent // libraries. The fail which previously failed to compile is the one numbered 3. extern crate issue_13560_2 as t2; extern crate issue_13560_3 as t3; fn
() {}
main
identifier_name
issue-13560.rs
// 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. // aux-build:issue-13560-1.rs // aux-build:issue-13560-2.rs // aux-build:issue-13560-3.rs // ignore-stage1 // Regression test for issue #13560, the test itself is all in the dependent // libraries. The fail which previously failed to compile is the one numbered 3. extern crate issue_13560_2 as t2; extern crate issue_13560_3 as t3; fn main()
{}
identifier_body
liveness-dead.rs
// Copyright 2012 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(dead_code)]; #[deny(dead_assignment)]; fn f1(x: &mut int) { *x = 1; // no error } fn f2() { let mut x: int = 3; //~ ERROR: value assigned to `x` is never read x = 4; x.clone(); } fn f3() { let mut x: int = 3; x.clone(); x = 4; //~ ERROR: value assigned to `x` is never read }
fn main() {}
random_line_split
liveness-dead.rs
// Copyright 2012 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(dead_code)]; #[deny(dead_assignment)]; fn f1(x: &mut int)
fn f2() { let mut x: int = 3; //~ ERROR: value assigned to `x` is never read x = 4; x.clone(); } fn f3() { let mut x: int = 3; x.clone(); x = 4; //~ ERROR: value assigned to `x` is never read } fn main() {}
{ *x = 1; // no error }
identifier_body
liveness-dead.rs
// Copyright 2012 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(dead_code)]; #[deny(dead_assignment)]; fn f1(x: &mut int) { *x = 1; // no error } fn
() { let mut x: int = 3; //~ ERROR: value assigned to `x` is never read x = 4; x.clone(); } fn f3() { let mut x: int = 3; x.clone(); x = 4; //~ ERROR: value assigned to `x` is never read } fn main() {}
f2
identifier_name
renderer.rs
use std::fmt; use std::error::Error; use super::format::{Format, DefaultFormat}; use super::builders::Builder; use super::output::Output; use super::super::error::ParseError; use super::super::ast::Block; #[derive(Debug)] pub enum RenderError { ParseError(ParseError), } /// /// # Example /// /// ``` /// use squid::html::Renderer; /// use squid::ast::{Block, HeadingLevel}; /// /// let blocks = vec![ /// Ok(Block::Heading(HeadingLevel::Level1, "Hello World".into())), /// ]; /// /// let mut renderer = Renderer::new(blocks.into_iter()); /// /// for node in renderer { /// println!("{}", node.unwrap()); /// } /// ``` /// /// ## Output /// ```text /// <h1>hello world</h1> /// ``` /// #[derive(Debug)] pub struct Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { // Not using Cow because Cow would require F to be `Clone`able format: F,
I: Iterator<Item = Result<Block, ParseError>>, { /// /// Creates a new renderer with the default implementation of `Format`. /// pub fn new(input: I) -> Self { Renderer { input, format: DefaultFormat, } } } impl fmt::Display for RenderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for RenderError { fn description(&self) -> &str { match *self { RenderError::ParseError(ref err) => err.description(), } } fn cause(&self) -> Option<&Error> { match *self { RenderError::ParseError(ref err) => Some(err), } } } impl From<ParseError> for RenderError { fn from(err: ParseError) -> Self { RenderError::ParseError(err) } } impl<F, I> Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { pub fn with_format(format: F, input: I) -> Self { Renderer { format, input } } } impl<F, I> Iterator for Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { type Item = Result<Output, RenderError>; fn next(&mut self) -> Option<Self::Item> { let node = self.input.next()?.and_then(|block| { let mut builder = Builder::new(); match block { Block::Heading(level, content) => self.format.heading(&mut builder, level, content), Block::Paragraph(text) => self.format.paragraph(&mut builder, text), Block::Quote(text) => self.format.quote(&mut builder, text), Block::List(list_type, items) => self.format.list(&mut builder, list_type, items), _ => unimplemented!(), } Ok(builder.consume()) }); Some(node.map_err(Into::into)) } }
input: I, } impl<I> Renderer<DefaultFormat, I> where
random_line_split
renderer.rs
use std::fmt; use std::error::Error; use super::format::{Format, DefaultFormat}; use super::builders::Builder; use super::output::Output; use super::super::error::ParseError; use super::super::ast::Block; #[derive(Debug)] pub enum RenderError { ParseError(ParseError), } /// /// # Example /// /// ``` /// use squid::html::Renderer; /// use squid::ast::{Block, HeadingLevel}; /// /// let blocks = vec![ /// Ok(Block::Heading(HeadingLevel::Level1, "Hello World".into())), /// ]; /// /// let mut renderer = Renderer::new(blocks.into_iter()); /// /// for node in renderer { /// println!("{}", node.unwrap()); /// } /// ``` /// /// ## Output /// ```text /// <h1>hello world</h1> /// ``` /// #[derive(Debug)] pub struct Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { // Not using Cow because Cow would require F to be `Clone`able format: F, input: I, } impl<I> Renderer<DefaultFormat, I> where I: Iterator<Item = Result<Block, ParseError>>, { /// /// Creates a new renderer with the default implementation of `Format`. /// pub fn new(input: I) -> Self { Renderer { input, format: DefaultFormat, } } } impl fmt::Display for RenderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for RenderError { fn
(&self) -> &str { match *self { RenderError::ParseError(ref err) => err.description(), } } fn cause(&self) -> Option<&Error> { match *self { RenderError::ParseError(ref err) => Some(err), } } } impl From<ParseError> for RenderError { fn from(err: ParseError) -> Self { RenderError::ParseError(err) } } impl<F, I> Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { pub fn with_format(format: F, input: I) -> Self { Renderer { format, input } } } impl<F, I> Iterator for Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { type Item = Result<Output, RenderError>; fn next(&mut self) -> Option<Self::Item> { let node = self.input.next()?.and_then(|block| { let mut builder = Builder::new(); match block { Block::Heading(level, content) => self.format.heading(&mut builder, level, content), Block::Paragraph(text) => self.format.paragraph(&mut builder, text), Block::Quote(text) => self.format.quote(&mut builder, text), Block::List(list_type, items) => self.format.list(&mut builder, list_type, items), _ => unimplemented!(), } Ok(builder.consume()) }); Some(node.map_err(Into::into)) } }
description
identifier_name
renderer.rs
use std::fmt; use std::error::Error; use super::format::{Format, DefaultFormat}; use super::builders::Builder; use super::output::Output; use super::super::error::ParseError; use super::super::ast::Block; #[derive(Debug)] pub enum RenderError { ParseError(ParseError), } /// /// # Example /// /// ``` /// use squid::html::Renderer; /// use squid::ast::{Block, HeadingLevel}; /// /// let blocks = vec![ /// Ok(Block::Heading(HeadingLevel::Level1, "Hello World".into())), /// ]; /// /// let mut renderer = Renderer::new(blocks.into_iter()); /// /// for node in renderer { /// println!("{}", node.unwrap()); /// } /// ``` /// /// ## Output /// ```text /// <h1>hello world</h1> /// ``` /// #[derive(Debug)] pub struct Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { // Not using Cow because Cow would require F to be `Clone`able format: F, input: I, } impl<I> Renderer<DefaultFormat, I> where I: Iterator<Item = Result<Block, ParseError>>, { /// /// Creates a new renderer with the default implementation of `Format`. /// pub fn new(input: I) -> Self { Renderer { input, format: DefaultFormat, } } } impl fmt::Display for RenderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for RenderError { fn description(&self) -> &str { match *self { RenderError::ParseError(ref err) => err.description(), } } fn cause(&self) -> Option<&Error> { match *self { RenderError::ParseError(ref err) => Some(err), } } } impl From<ParseError> for RenderError { fn from(err: ParseError) -> Self { RenderError::ParseError(err) } } impl<F, I> Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { pub fn with_format(format: F, input: I) -> Self { Renderer { format, input } } } impl<F, I> Iterator for Renderer<F, I> where F: Format +'static, I: Iterator<Item = Result<Block, ParseError>>, { type Item = Result<Output, RenderError>; fn next(&mut self) -> Option<Self::Item>
}
{ let node = self.input.next()?.and_then(|block| { let mut builder = Builder::new(); match block { Block::Heading(level, content) => self.format.heading(&mut builder, level, content), Block::Paragraph(text) => self.format.paragraph(&mut builder, text), Block::Quote(text) => self.format.quote(&mut builder, text), Block::List(list_type, items) => self.format.list(&mut builder, list_type, items), _ => unimplemented!(), } Ok(builder.consume()) }); Some(node.map_err(Into::into)) }
identifier_body
issue-11085.rs
// Copyright 2012-2013-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. // run-pass #![allow(dead_code)] // compile-flags: --cfg foo // pretty-expanded FIXME #23616 struct Foo { #[cfg(fail)] bar: baz, foo: isize, } struct Foo2 { #[cfg(foo)] foo: isize, } enum Bar1 { Bar1_1, #[cfg(fail)] Bar1_2(NotAType), } enum Bar2 { #[cfg(fail)] Bar2_1(NotAType), } enum Bar3 { Bar3_1 { #[cfg(fail)] foo: isize, bar: isize, } } pub fn main() { let _f = Foo { foo: 3 }; let _f = Foo2 { foo: 3 }; match Bar1::Bar1_1 { Bar1::Bar1_1 =>
} let _f = Bar3::Bar3_1 { bar: 3 }; }
{}
conditional_block
issue-11085.rs
// Copyright 2012-2013-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. // run-pass #![allow(dead_code)] // compile-flags: --cfg foo // pretty-expanded FIXME #23616 struct Foo { #[cfg(fail)] bar: baz, foo: isize,
#[cfg(foo)] foo: isize, } enum Bar1 { Bar1_1, #[cfg(fail)] Bar1_2(NotAType), } enum Bar2 { #[cfg(fail)] Bar2_1(NotAType), } enum Bar3 { Bar3_1 { #[cfg(fail)] foo: isize, bar: isize, } } pub fn main() { let _f = Foo { foo: 3 }; let _f = Foo2 { foo: 3 }; match Bar1::Bar1_1 { Bar1::Bar1_1 => {} } let _f = Bar3::Bar3_1 { bar: 3 }; }
} struct Foo2 {
random_line_split
issue-11085.rs
// Copyright 2012-2013-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. // run-pass #![allow(dead_code)] // compile-flags: --cfg foo // pretty-expanded FIXME #23616 struct Foo { #[cfg(fail)] bar: baz, foo: isize, } struct Foo2 { #[cfg(foo)] foo: isize, } enum
{ Bar1_1, #[cfg(fail)] Bar1_2(NotAType), } enum Bar2 { #[cfg(fail)] Bar2_1(NotAType), } enum Bar3 { Bar3_1 { #[cfg(fail)] foo: isize, bar: isize, } } pub fn main() { let _f = Foo { foo: 3 }; let _f = Foo2 { foo: 3 }; match Bar1::Bar1_1 { Bar1::Bar1_1 => {} } let _f = Bar3::Bar3_1 { bar: 3 }; }
Bar1
identifier_name
lambda-infer-unresolved.rs
// Copyright 2012 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. // This should typecheck even though the type of e is not fully // resolved when we finish typechecking the ||. struct Refs { refs: Vec<isize>, n: isize } pub fn main()
{ let mut e = Refs{refs: vec!(), n: 0}; let _f = || println!("{}", e.n); let x: &[isize] = &e.refs; assert_eq!(x.len(), 0); }
identifier_body
lambda-infer-unresolved.rs
// Copyright 2012 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. // This should typecheck even though the type of e is not fully // resolved when we finish typechecking the ||. struct
{ refs: Vec<isize>, n: isize } pub fn main() { let mut e = Refs{refs: vec!(), n: 0}; let _f = || println!("{}", e.n); let x: &[isize] = &e.refs; assert_eq!(x.len(), 0); }
Refs
identifier_name
lambda-infer-unresolved.rs
// Copyright 2012 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.
// This should typecheck even though the type of e is not fully // resolved when we finish typechecking the ||. struct Refs { refs: Vec<isize>, n: isize } pub fn main() { let mut e = Refs{refs: vec!(), n: 0}; let _f = || println!("{}", e.n); let x: &[isize] = &e.refs; assert_eq!(x.len(), 0); }
random_line_split
result.rs
use std::io::Error as IoError; use std::sync::mpsc::{SendError, RecvError}; use std::result; use mio::NotifyError; use queue::Message; use {Handler}; #[derive(Debug)] pub enum Error<H: Handler> { QueueOutOfService, Io(IoError), NotifyError(NotifyError<Message<H::Processor, H::Message, H::Response>>), SendError(SendError<H::Response>), RecvError(RecvError), } pub type Result<T, H: Handler> = result::Result<T, Error<H>>; impl<H: Handler> From<IoError> for Error<H> { fn from(err: IoError) -> Error<H>
} impl<H: Handler> From<NotifyError<Message<H::Processor, H::Message, H::Response>>> for Error<H> { fn from(err: NotifyError<Message<H::Processor, H::Message, H::Response>>) -> Error<H> { Error::NotifyError(err) } } impl<H: Handler> From<SendError<H::Response>> for Error<H> { fn from(err: SendError<H::Response>) -> Error<H> { Error::SendError(err) } } impl<H: Handler> From<RecvError> for Error<H> { fn from(err: RecvError) -> Error<H> { Error::RecvError(err) } } #[derive(Debug)] pub struct ResponseError(pub &'static str); pub type ResponseResult<T> = result::Result<T, ResponseError>;
{ Error::Io(err) }
identifier_body
result.rs
use std::io::Error as IoError; use std::sync::mpsc::{SendError, RecvError}; use std::result; use mio::NotifyError; use queue::Message; use {Handler}; #[derive(Debug)] pub enum Error<H: Handler> { QueueOutOfService, Io(IoError), NotifyError(NotifyError<Message<H::Processor, H::Message, H::Response>>), SendError(SendError<H::Response>), RecvError(RecvError), } pub type Result<T, H: Handler> = result::Result<T, Error<H>>; impl<H: Handler> From<IoError> for Error<H> { fn from(err: IoError) -> Error<H> { Error::Io(err) } } impl<H: Handler> From<NotifyError<Message<H::Processor, H::Message, H::Response>>> for Error<H> { fn from(err: NotifyError<Message<H::Processor, H::Message, H::Response>>) -> Error<H> { Error::NotifyError(err) } } impl<H: Handler> From<SendError<H::Response>> for Error<H> { fn from(err: SendError<H::Response>) -> Error<H> { Error::SendError(err) } } impl<H: Handler> From<RecvError> for Error<H> { fn
(err: RecvError) -> Error<H> { Error::RecvError(err) } } #[derive(Debug)] pub struct ResponseError(pub &'static str); pub type ResponseResult<T> = result::Result<T, ResponseError>;
from
identifier_name
result.rs
use std::io::Error as IoError; use std::sync::mpsc::{SendError, RecvError}; use std::result; use mio::NotifyError; use queue::Message; use {Handler}; #[derive(Debug)] pub enum Error<H: Handler> { QueueOutOfService, Io(IoError), NotifyError(NotifyError<Message<H::Processor, H::Message, H::Response>>), SendError(SendError<H::Response>), RecvError(RecvError), } pub type Result<T, H: Handler> = result::Result<T, Error<H>>; impl<H: Handler> From<IoError> for Error<H> { fn from(err: IoError) -> Error<H> { Error::Io(err) } } impl<H: Handler> From<NotifyError<Message<H::Processor, H::Message, H::Response>>> for Error<H> { fn from(err: NotifyError<Message<H::Processor, H::Message, H::Response>>) -> Error<H> { Error::NotifyError(err) } }
impl<H: Handler> From<SendError<H::Response>> for Error<H> { fn from(err: SendError<H::Response>) -> Error<H> { Error::SendError(err) } } impl<H: Handler> From<RecvError> for Error<H> { fn from(err: RecvError) -> Error<H> { Error::RecvError(err) } } #[derive(Debug)] pub struct ResponseError(pub &'static str); pub type ResponseResult<T> = result::Result<T, ResponseError>;
random_line_split
var-captured-in-nested-closure.rs
// Copyright 2013-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-android: FIXME(#10381) // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print variable // gdb-check:$1 = 1 // gdb-command:print constant // gdb-check:$2 = 2 // gdb-command:print a_struct // gdb-check:$3 = {a = -3, b = 4.5, c = 5} // gdb-command:print *struct_ref // gdb-check:$4 = {a = -3, b = 4.5, c = 5} // gdb-command:print *owned // gdb-check:$5 = 6 // gdb-command:print managed->val // gdb-check:$6 = 7 // gdb-command:print closure_local // gdb-check:$7 = 8 // gdb-command:continue // gdb-command:finish // gdb-command:print variable // gdb-check:$8 = 1 // gdb-command:print constant // gdb-check:$9 = 2 // gdb-command:print a_struct // gdb-check:$10 = {a = -3, b = 4.5, c = 5} // gdb-command:print *struct_ref // gdb-check:$11 = {a = -3, b = 4.5, c = 5} // gdb-command:print *owned // gdb-check:$12 = 6 // gdb-command:print managed->val // gdb-check:$13 = 7 // gdb-command:print closure_local // gdb-check:$14 = 8 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print variable // lldb-check:[...]$0 = 1 // lldb-command:print constant // lldb-check:[...]$1 = 2 // lldb-command:print a_struct // lldb-check:[...]$2 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *struct_ref // lldb-check:[...]$3 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *owned // lldb-check:[...]$4 = 6 // lldb-command:print managed->val // lldb-check:[...]$5 = 7 // lldb-command:print closure_local // lldb-check:[...]$6 = 8 // lldb-command:continue // lldb-command:print variable // lldb-check:[...]$7 = 1 // lldb-command:print constant // lldb-check:[...]$8 = 2 // lldb-command:print a_struct // lldb-check:[...]$9 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *struct_ref // lldb-check:[...]$10 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *owned // lldb-check:[...]$11 = 6 // lldb-command:print managed->val // lldb-check:[...]$12 = 7 // lldb-command:print closure_local // lldb-check:[...]$13 = 8 // lldb-command:continue #![allow(unused_variable)] use std::gc::GC; struct Struct { a: int, b: f64, c: uint } fn main() { let mut variable = 1; let constant = 2; let a_struct = Struct { a: -3, b: 4.5, c: 5 }; let struct_ref = &a_struct; let owned = box 6; let managed = box(GC) 7; let closure = || { let closure_local = 8; let nested_closure = || { zzz(); // #break variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local; }; zzz(); // #break nested_closure(); }; closure(); } fn zzz()
{()}
identifier_body
var-captured-in-nested-closure.rs
// Copyright 2013-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-android: FIXME(#10381) // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print variable // gdb-check:$1 = 1 // gdb-command:print constant // gdb-check:$2 = 2 // gdb-command:print a_struct // gdb-check:$3 = {a = -3, b = 4.5, c = 5} // gdb-command:print *struct_ref // gdb-check:$4 = {a = -3, b = 4.5, c = 5} // gdb-command:print *owned // gdb-check:$5 = 6 // gdb-command:print managed->val // gdb-check:$6 = 7 // gdb-command:print closure_local // gdb-check:$7 = 8 // gdb-command:continue // gdb-command:finish // gdb-command:print variable // gdb-check:$8 = 1 // gdb-command:print constant // gdb-check:$9 = 2 // gdb-command:print a_struct // gdb-check:$10 = {a = -3, b = 4.5, c = 5} // gdb-command:print *struct_ref // gdb-check:$11 = {a = -3, b = 4.5, c = 5} // gdb-command:print *owned // gdb-check:$12 = 6 // gdb-command:print managed->val // gdb-check:$13 = 7 // gdb-command:print closure_local // gdb-check:$14 = 8 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print variable // lldb-check:[...]$0 = 1 // lldb-command:print constant // lldb-check:[...]$1 = 2 // lldb-command:print a_struct // lldb-check:[...]$2 = Struct { a: -3, b: 4.5, c: 5 }
// lldb-check:[...]$5 = 7 // lldb-command:print closure_local // lldb-check:[...]$6 = 8 // lldb-command:continue // lldb-command:print variable // lldb-check:[...]$7 = 1 // lldb-command:print constant // lldb-check:[...]$8 = 2 // lldb-command:print a_struct // lldb-check:[...]$9 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *struct_ref // lldb-check:[...]$10 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *owned // lldb-check:[...]$11 = 6 // lldb-command:print managed->val // lldb-check:[...]$12 = 7 // lldb-command:print closure_local // lldb-check:[...]$13 = 8 // lldb-command:continue #![allow(unused_variable)] use std::gc::GC; struct Struct { a: int, b: f64, c: uint } fn main() { let mut variable = 1; let constant = 2; let a_struct = Struct { a: -3, b: 4.5, c: 5 }; let struct_ref = &a_struct; let owned = box 6; let managed = box(GC) 7; let closure = || { let closure_local = 8; let nested_closure = || { zzz(); // #break variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local; }; zzz(); // #break nested_closure(); }; closure(); } fn zzz() {()}
// lldb-command:print *struct_ref // lldb-check:[...]$3 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *owned // lldb-check:[...]$4 = 6 // lldb-command:print managed->val
random_line_split