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 |
---|---|---|---|---|
process.rs
|
// Copyright 2012-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.
use prelude::v1::*;
use ascii::*;
use collections::HashMap;
use collections;
use env::split_paths;
use env;
use ffi::{OsString, OsStr};
use fmt;
use fs;
use io::{self, Error};
use libc::{self, c_void};
use mem;
use os::windows::ffi::OsStrExt;
use path::Path;
use ptr;
use sync::StaticMutex;
use sys::c;
use sys::fs::{OpenOptions, File};
use sys::handle::{Handle, RawHandle};
use sys::pipe::AnonPipe;
use sys::stdio;
use sys::{self, cvt};
use sys_common::{AsInner, FromInner};
////////////////////////////////////////////////////////////////////////////////
// Command
////////////////////////////////////////////////////////////////////////////////
fn mk_key(s: &OsStr) -> OsString {
FromInner::from_inner(sys::os_str::Buf {
inner: s.as_inner().inner.to_ascii_uppercase()
})
}
#[derive(Clone)]
pub struct Command {
pub program: OsString,
pub args: Vec<OsString>,
pub env: Option<HashMap<OsString, OsString>>,
pub cwd: Option<OsString>,
pub detach: bool, // not currently exposed in std::process
}
impl Command {
pub fn new(program: &OsStr) -> Command {
Command {
program: program.to_os_string(),
args: Vec::new(),
env: None,
cwd: None,
detach: false,
}
}
pub fn arg(&mut self, arg: &OsStr) {
self.args.push(arg.to_os_string())
}
pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) {
self.args.extend(args.map(OsStr::to_os_string))
}
fn init_env_map(&mut self){
if self.env.is_none() {
self.env = Some(env::vars_os().map(|(key, val)| {
(mk_key(&key), val)
}).collect());
}
}
pub fn env(&mut self, key: &OsStr, val: &OsStr) {
self.init_env_map();
self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string());
}
pub fn env_remove(&mut self, key: &OsStr) {
self.init_env_map();
self.env.as_mut().unwrap().remove(&mk_key(key));
}
pub fn env_clear(&mut self) {
self.env = Some(HashMap::new())
}
pub fn cwd(&mut self, dir: &OsStr) {
self.cwd = Some(dir.to_os_string())
}
}
////////////////////////////////////////////////////////////////////////////////
// Processes
////////////////////////////////////////////////////////////////////////////////
/// A value representing a child process.
///
/// The lifetime of this value is linked to the lifetime of the actual
/// process - the Process destructor calls self.finish() which waits
/// for the process to terminate.
pub struct Process {
handle: Handle,
}
pub enum Stdio {
Inherit,
Piped(AnonPipe),
None,
Handle(RawHandle),
}
impl Process {
pub fn spawn(cfg: &Command,
in_handle: Stdio,
out_handle: Stdio,
err_handle: Stdio) -> io::Result<Process>
{
use libc::{TRUE, STARTF_USESTDHANDLES};
use libc::{DWORD, STARTUPINFO, CreateProcessW};
// To have the spawning semantics of unix/windows stay the same, we need
// to read the *child's* PATH if one is provided. See #15149 for more
// details.
let program = cfg.env.as_ref().and_then(|env| {
for (key, v) in env {
if OsStr::new("PATH")!= &**key { continue }
// Split the value and test each path to see if the
// program exists.
for path in split_paths(&v) {
let path = path.join(cfg.program.to_str().unwrap())
.with_extension(env::consts::EXE_EXTENSION);
if fs::metadata(&path).is_ok() {
return Some(path.into_os_string())
}
}
break
}
None
});
let mut si = zeroed_startupinfo();
si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
si.dwFlags = STARTF_USESTDHANDLES;
let stdin = try!(in_handle.to_handle(c::STD_INPUT_HANDLE));
let stdout = try!(out_handle.to_handle(c::STD_OUTPUT_HANDLE));
let stderr = try!(err_handle.to_handle(c::STD_ERROR_HANDLE));
si.hStdInput = stdin.raw();
si.hStdOutput = stdout.raw();
si.hStdError = stderr.raw();
let program = program.as_ref().unwrap_or(&cfg.program);
let mut cmd_str = make_command_line(program, &cfg.args);
cmd_str.push(0); // add null terminator
// stolen from the libuv code.
let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
if cfg.detach {
flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
}
let (envp, _data) = make_envp(cfg.env.as_ref());
let (dirp, _data) = make_dirp(cfg.cwd.as_ref());
let mut pi = zeroed_process_information();
try!(unsafe {
// `CreateProcess` is racy!
// http://support.microsoft.com/kb/315939
static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new();
let _lock = CREATE_PROCESS_LOCK.lock();
cvt(CreateProcessW(ptr::null(),
cmd_str.as_mut_ptr(),
ptr::null_mut(),
ptr::null_mut(),
TRUE, flags, envp, dirp,
&mut si, &mut pi))
});
// We close the thread handle because we don't care about keeping
// the thread id valid, and we aren't keeping the thread handle
// around to be able to close it later.
drop(Handle::new(pi.hThread));
Ok(Process { handle: Handle::new(pi.hProcess) })
}
pub unsafe fn kill(&self) -> io::Result<()> {
try!(cvt(libc::TerminateProcess(self.handle.raw(), 1)));
Ok(())
}
pub fn id(&self) -> u32 {
unsafe {
c::GetProcessId(self.handle.raw()) as u32
}
}
pub fn wait(&self) -> io::Result<ExitStatus> {
use libc::{STILL_ACTIVE, INFINITE, WAIT_OBJECT_0};
use libc::{GetExitCodeProcess, WaitForSingleObject};
unsafe {
loop {
let mut status = 0;
try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status)));
if status!= STILL_ACTIVE {
return Ok(ExitStatus(status as i32));
}
match WaitForSingleObject(self.handle.raw(), INFINITE) {
WAIT_OBJECT_0 => {}
_ => return Err(Error::last_os_error()),
}
}
}
}
pub fn handle(&self) -> &Handle { &self.handle }
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct ExitStatus(i32);
impl ExitStatus {
pub fn success(&self) -> bool {
self.0 == 0
}
pub fn code(&self) -> Option<i32>
|
}
impl fmt::Display for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "exit code: {}", self.0)
}
}
fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
libc::types::os::arch::extra::STARTUPINFO {
cb: 0,
lpReserved: ptr::null_mut(),
lpDesktop: ptr::null_mut(),
lpTitle: ptr::null_mut(),
dwX: 0,
dwY: 0,
dwXSize: 0,
dwYSize: 0,
dwXCountChars: 0,
dwYCountCharts: 0,
dwFillAttribute: 0,
dwFlags: 0,
wShowWindow: 0,
cbReserved2: 0,
lpReserved2: ptr::null_mut(),
hStdInput: libc::INVALID_HANDLE_VALUE,
hStdOutput: libc::INVALID_HANDLE_VALUE,
hStdError: libc::INVALID_HANDLE_VALUE,
}
}
fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
libc::types::os::arch::extra::PROCESS_INFORMATION {
hProcess: ptr::null_mut(),
hThread: ptr::null_mut(),
dwProcessId: 0,
dwThreadId: 0
}
}
// Produces a wide string *without terminating null*
fn make_command_line(prog: &OsStr, args: &[OsString]) -> Vec<u16> {
// Encode the command and arguments in a command line string such
// that the spawned process may recover them using CommandLineToArgvW.
let mut cmd: Vec<u16> = Vec::new();
append_arg(&mut cmd, prog);
for arg in args {
cmd.push(''as u16);
append_arg(&mut cmd, arg);
}
return cmd;
fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) {
// If an argument has 0 characters then we need to quote it to ensure
// that it actually gets passed through on the command line or otherwise
// it will be dropped entirely when parsed on the other end.
let arg_bytes = &arg.as_inner().inner.as_inner();
let quote = arg_bytes.iter().any(|c| *c == b''|| *c == b'\t')
|| arg_bytes.is_empty();
if quote {
cmd.push('"' as u16);
}
let mut iter = arg.encode_wide();
let mut backslashes: usize = 0;
while let Some(x) = iter.next() {
if x == '\\' as u16 {
backslashes += 1;
} else {
if x == '"' as u16 {
// Add n+1 backslashes to total 2n+1 before internal '"'.
for _ in 0..(backslashes+1) {
cmd.push('\\' as u16);
}
}
backslashes = 0;
}
cmd.push(x);
}
if quote {
// Add n backslashes to total 2n before ending '"'.
for _ in 0..backslashes {
cmd.push('\\' as u16);
}
cmd.push('"' as u16);
}
}
}
fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
-> (*mut c_void, Vec<u16>) {
// On Windows we pass an "environment block" which is not a char**, but
// rather a concatenation of null-terminated k=v\0 sequences, with a final
// \0 to terminate.
match env {
Some(env) => {
let mut blk = Vec::new();
for pair in env {
blk.extend(pair.0.encode_wide());
blk.push('=' as u16);
blk.extend(pair.1.encode_wide());
blk.push(0);
}
blk.push(0);
(blk.as_mut_ptr() as *mut c_void, blk)
}
_ => (ptr::null_mut(), Vec::new())
}
}
fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) {
match d {
Some(dir) => {
let mut dir_str: Vec<u16> = dir.encode_wide().collect();
dir_str.push(0);
(dir_str.as_ptr(), dir_str)
},
None => (ptr::null(), Vec::new())
}
}
impl Stdio {
pub fn clone_if_copy(&self) -> Stdio {
match *self {
Stdio::Inherit => Stdio::Inherit,
Stdio::None => Stdio::None,
Stdio::Handle(handle) => Stdio::Handle(handle),
Stdio::Piped(_) => unreachable!(),
}
}
fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> {
use libc::DUPLICATE_SAME_ACCESS;
match *self {
Stdio::Inherit => {
stdio::get(stdio_id).and_then(|io| {
io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
})
}
Stdio::Handle(ref handle) => {
handle.duplicate(0, true, DUPLICATE_SAME_ACCESS)
}
Stdio::Piped(ref pipe) => {
pipe.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
}
// Similarly to unix, we don't actually leave holes for the
// stdio file descriptors, but rather open up /dev/null
// equivalents. These equivalents are drawn from libuv's
// windows process spawning.
Stdio::None => {
let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
let mut sa = libc::SECURITY_ATTRIBUTES {
nLength: size as libc::DWORD,
lpSecurityDescriptor: ptr::null_mut(),
bInheritHandle: 1,
};
let mut opts = OpenOptions::new();
opts.read(stdio_id == c::STD_INPUT_HANDLE);
opts.write(stdio_id!= c::STD_INPUT_HANDLE);
opts.security_attributes(&mut sa);
File::open(Path::new("NUL"), &opts).map(|file| {
file.into_handle()
})
}
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use str;
use ffi::{OsStr, OsString};
use super::make_command_line;
#[test]
fn test_make_command_line() {
fn test_wrapper(prog: &str, args: &[&str]) -> String {
String::from_utf16(
&make_command_line(OsStr::new(prog),
&args.iter()
.map(|a| OsString::from(a))
.collect::<Vec<OsString>>())).unwrap()
}
assert_eq!(
test_wrapper("prog", &["aaa", "bbb", "ccc"]),
"prog aaa bbb ccc"
);
assert_eq!(
test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
"\"C:\\Program Files\\blah\\blah.exe\" aaa"
);
assert_eq!(
test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
"\"C:\\Program Files\\test\" aa\\\"bb"
);
assert_eq!(
test_wrapper("echo", &["a b c"]),
"echo \"a b c\""
);
assert_eq!(
test_wrapper("echo", &["\" \\\" \\", "\\"]),
"echo \"\\\" \\\\\\\" \\\\\" \\"
);
assert_eq!(
test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
"\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
);
}
}
|
{
Some(self.0)
}
|
identifier_body
|
process.rs
|
// Copyright 2012-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.
use prelude::v1::*;
use ascii::*;
use collections::HashMap;
use collections;
use env::split_paths;
use env;
use ffi::{OsString, OsStr};
use fmt;
use fs;
use io::{self, Error};
use libc::{self, c_void};
use mem;
use os::windows::ffi::OsStrExt;
use path::Path;
use ptr;
use sync::StaticMutex;
use sys::c;
use sys::fs::{OpenOptions, File};
use sys::handle::{Handle, RawHandle};
use sys::pipe::AnonPipe;
use sys::stdio;
use sys::{self, cvt};
use sys_common::{AsInner, FromInner};
////////////////////////////////////////////////////////////////////////////////
// Command
////////////////////////////////////////////////////////////////////////////////
fn mk_key(s: &OsStr) -> OsString {
FromInner::from_inner(sys::os_str::Buf {
inner: s.as_inner().inner.to_ascii_uppercase()
})
}
#[derive(Clone)]
pub struct Command {
pub program: OsString,
pub args: Vec<OsString>,
pub env: Option<HashMap<OsString, OsString>>,
pub cwd: Option<OsString>,
pub detach: bool, // not currently exposed in std::process
}
impl Command {
pub fn new(program: &OsStr) -> Command {
Command {
program: program.to_os_string(),
args: Vec::new(),
env: None,
cwd: None,
detach: false,
}
}
pub fn arg(&mut self, arg: &OsStr) {
self.args.push(arg.to_os_string())
}
pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) {
self.args.extend(args.map(OsStr::to_os_string))
}
fn init_env_map(&mut self){
if self.env.is_none() {
self.env = Some(env::vars_os().map(|(key, val)| {
(mk_key(&key), val)
}).collect());
}
}
pub fn env(&mut self, key: &OsStr, val: &OsStr) {
self.init_env_map();
self.env.as_mut().unwrap().insert(mk_key(key), val.to_os_string());
}
pub fn env_remove(&mut self, key: &OsStr) {
self.init_env_map();
self.env.as_mut().unwrap().remove(&mk_key(key));
}
pub fn env_clear(&mut self) {
self.env = Some(HashMap::new())
}
pub fn cwd(&mut self, dir: &OsStr) {
self.cwd = Some(dir.to_os_string())
}
}
////////////////////////////////////////////////////////////////////////////////
// Processes
////////////////////////////////////////////////////////////////////////////////
/// A value representing a child process.
///
/// The lifetime of this value is linked to the lifetime of the actual
/// process - the Process destructor calls self.finish() which waits
/// for the process to terminate.
pub struct Process {
handle: Handle,
}
pub enum Stdio {
Inherit,
Piped(AnonPipe),
None,
Handle(RawHandle),
}
impl Process {
pub fn spawn(cfg: &Command,
in_handle: Stdio,
out_handle: Stdio,
err_handle: Stdio) -> io::Result<Process>
{
use libc::{TRUE, STARTF_USESTDHANDLES};
use libc::{DWORD, STARTUPINFO, CreateProcessW};
// To have the spawning semantics of unix/windows stay the same, we need
// to read the *child's* PATH if one is provided. See #15149 for more
// details.
let program = cfg.env.as_ref().and_then(|env| {
for (key, v) in env {
if OsStr::new("PATH")!= &**key { continue }
// Split the value and test each path to see if the
// program exists.
for path in split_paths(&v) {
let path = path.join(cfg.program.to_str().unwrap())
.with_extension(env::consts::EXE_EXTENSION);
if fs::metadata(&path).is_ok() {
return Some(path.into_os_string())
}
}
break
}
None
});
let mut si = zeroed_startupinfo();
si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
si.dwFlags = STARTF_USESTDHANDLES;
let stdin = try!(in_handle.to_handle(c::STD_INPUT_HANDLE));
let stdout = try!(out_handle.to_handle(c::STD_OUTPUT_HANDLE));
let stderr = try!(err_handle.to_handle(c::STD_ERROR_HANDLE));
si.hStdInput = stdin.raw();
si.hStdOutput = stdout.raw();
si.hStdError = stderr.raw();
let program = program.as_ref().unwrap_or(&cfg.program);
let mut cmd_str = make_command_line(program, &cfg.args);
cmd_str.push(0); // add null terminator
// stolen from the libuv code.
let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
if cfg.detach {
flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
}
let (envp, _data) = make_envp(cfg.env.as_ref());
let (dirp, _data) = make_dirp(cfg.cwd.as_ref());
let mut pi = zeroed_process_information();
try!(unsafe {
// `CreateProcess` is racy!
// http://support.microsoft.com/kb/315939
static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new();
let _lock = CREATE_PROCESS_LOCK.lock();
cvt(CreateProcessW(ptr::null(),
cmd_str.as_mut_ptr(),
ptr::null_mut(),
ptr::null_mut(),
TRUE, flags, envp, dirp,
&mut si, &mut pi))
});
// We close the thread handle because we don't care about keeping
// the thread id valid, and we aren't keeping the thread handle
// around to be able to close it later.
drop(Handle::new(pi.hThread));
Ok(Process { handle: Handle::new(pi.hProcess) })
}
pub unsafe fn kill(&self) -> io::Result<()> {
try!(cvt(libc::TerminateProcess(self.handle.raw(), 1)));
Ok(())
}
pub fn id(&self) -> u32 {
unsafe {
c::GetProcessId(self.handle.raw()) as u32
}
}
pub fn wait(&self) -> io::Result<ExitStatus> {
use libc::{STILL_ACTIVE, INFINITE, WAIT_OBJECT_0};
use libc::{GetExitCodeProcess, WaitForSingleObject};
unsafe {
loop {
let mut status = 0;
try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status)));
if status!= STILL_ACTIVE {
return Ok(ExitStatus(status as i32));
}
match WaitForSingleObject(self.handle.raw(), INFINITE) {
WAIT_OBJECT_0 => {}
_ => return Err(Error::last_os_error()),
}
}
}
}
pub fn handle(&self) -> &Handle { &self.handle }
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct ExitStatus(i32);
impl ExitStatus {
pub fn success(&self) -> bool {
self.0 == 0
}
pub fn code(&self) -> Option<i32> {
Some(self.0)
}
}
impl fmt::Display for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "exit code: {}", self.0)
}
}
fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
libc::types::os::arch::extra::STARTUPINFO {
cb: 0,
lpReserved: ptr::null_mut(),
lpDesktop: ptr::null_mut(),
lpTitle: ptr::null_mut(),
dwX: 0,
dwY: 0,
dwXSize: 0,
dwYSize: 0,
dwXCountChars: 0,
dwYCountCharts: 0,
dwFillAttribute: 0,
dwFlags: 0,
wShowWindow: 0,
cbReserved2: 0,
lpReserved2: ptr::null_mut(),
hStdInput: libc::INVALID_HANDLE_VALUE,
hStdOutput: libc::INVALID_HANDLE_VALUE,
hStdError: libc::INVALID_HANDLE_VALUE,
}
}
fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
libc::types::os::arch::extra::PROCESS_INFORMATION {
hProcess: ptr::null_mut(),
hThread: ptr::null_mut(),
dwProcessId: 0,
dwThreadId: 0
}
}
// Produces a wide string *without terminating null*
fn make_command_line(prog: &OsStr, args: &[OsString]) -> Vec<u16> {
// Encode the command and arguments in a command line string such
// that the spawned process may recover them using CommandLineToArgvW.
let mut cmd: Vec<u16> = Vec::new();
append_arg(&mut cmd, prog);
for arg in args {
cmd.push(''as u16);
append_arg(&mut cmd, arg);
}
return cmd;
fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr) {
// If an argument has 0 characters then we need to quote it to ensure
// that it actually gets passed through on the command line or otherwise
// it will be dropped entirely when parsed on the other end.
let arg_bytes = &arg.as_inner().inner.as_inner();
let quote = arg_bytes.iter().any(|c| *c == b''|| *c == b'\t')
|| arg_bytes.is_empty();
if quote {
cmd.push('"' as u16);
}
let mut iter = arg.encode_wide();
let mut backslashes: usize = 0;
while let Some(x) = iter.next() {
if x == '\\' as u16 {
backslashes += 1;
} else {
if x == '"' as u16 {
// Add n+1 backslashes to total 2n+1 before internal '"'.
for _ in 0..(backslashes+1) {
cmd.push('\\' as u16);
}
}
backslashes = 0;
}
cmd.push(x);
}
if quote {
// Add n backslashes to total 2n before ending '"'.
for _ in 0..backslashes {
cmd.push('\\' as u16);
}
cmd.push('"' as u16);
}
}
}
fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
-> (*mut c_void, Vec<u16>) {
// On Windows we pass an "environment block" which is not a char**, but
// rather a concatenation of null-terminated k=v\0 sequences, with a final
// \0 to terminate.
match env {
Some(env) => {
let mut blk = Vec::new();
for pair in env {
blk.extend(pair.0.encode_wide());
blk.push('=' as u16);
blk.extend(pair.1.encode_wide());
blk.push(0);
}
blk.push(0);
(blk.as_mut_ptr() as *mut c_void, blk)
}
_ => (ptr::null_mut(), Vec::new())
}
}
fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) {
match d {
Some(dir) => {
let mut dir_str: Vec<u16> = dir.encode_wide().collect();
dir_str.push(0);
(dir_str.as_ptr(), dir_str)
},
None => (ptr::null(), Vec::new())
}
}
impl Stdio {
pub fn clone_if_copy(&self) -> Stdio {
match *self {
Stdio::Inherit => Stdio::Inherit,
Stdio::None => Stdio::None,
Stdio::Handle(handle) => Stdio::Handle(handle),
Stdio::Piped(_) => unreachable!(),
}
}
fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> {
use libc::DUPLICATE_SAME_ACCESS;
match *self {
Stdio::Inherit => {
stdio::get(stdio_id).and_then(|io| {
io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
})
}
|
Stdio::Piped(ref pipe) => {
pipe.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS)
}
// Similarly to unix, we don't actually leave holes for the
// stdio file descriptors, but rather open up /dev/null
// equivalents. These equivalents are drawn from libuv's
// windows process spawning.
Stdio::None => {
let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
let mut sa = libc::SECURITY_ATTRIBUTES {
nLength: size as libc::DWORD,
lpSecurityDescriptor: ptr::null_mut(),
bInheritHandle: 1,
};
let mut opts = OpenOptions::new();
opts.read(stdio_id == c::STD_INPUT_HANDLE);
opts.write(stdio_id!= c::STD_INPUT_HANDLE);
opts.security_attributes(&mut sa);
File::open(Path::new("NUL"), &opts).map(|file| {
file.into_handle()
})
}
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use str;
use ffi::{OsStr, OsString};
use super::make_command_line;
#[test]
fn test_make_command_line() {
fn test_wrapper(prog: &str, args: &[&str]) -> String {
String::from_utf16(
&make_command_line(OsStr::new(prog),
&args.iter()
.map(|a| OsString::from(a))
.collect::<Vec<OsString>>())).unwrap()
}
assert_eq!(
test_wrapper("prog", &["aaa", "bbb", "ccc"]),
"prog aaa bbb ccc"
);
assert_eq!(
test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
"\"C:\\Program Files\\blah\\blah.exe\" aaa"
);
assert_eq!(
test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
"\"C:\\Program Files\\test\" aa\\\"bb"
);
assert_eq!(
test_wrapper("echo", &["a b c"]),
"echo \"a b c\""
);
assert_eq!(
test_wrapper("echo", &["\" \\\" \\", "\\"]),
"echo \"\\\" \\\\\\\" \\\\\" \\"
);
assert_eq!(
test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
"\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}"
);
}
}
|
Stdio::Handle(ref handle) => {
handle.duplicate(0, true, DUPLICATE_SAME_ACCESS)
}
|
random_line_split
|
regions-out-of-scope-slice.rs
|
// Copyright 2012-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.
// compile-flags: -Z parse-only
// ignore-test blk region isn't supported in the front-end
fn foo(cond: bool) {
// Here we will infer a type that uses the
// region of the if stmt then block, but in the scope:
let mut x; //~ ERROR foo
if cond {
x = &'blk [1,2,3];
}
}
fn main() {}
|
random_line_split
|
|
regions-out-of-scope-slice.rs
|
// Copyright 2012-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.
// compile-flags: -Z parse-only
// ignore-test blk region isn't supported in the front-end
fn foo(cond: bool) {
// Here we will infer a type that uses the
// region of the if stmt then block, but in the scope:
let mut x; //~ ERROR foo
if cond
|
}
fn main() {}
|
{
x = &'blk [1,2,3];
}
|
conditional_block
|
regions-out-of-scope-slice.rs
|
// Copyright 2012-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.
// compile-flags: -Z parse-only
// ignore-test blk region isn't supported in the front-end
fn foo(cond: bool) {
// Here we will infer a type that uses the
// region of the if stmt then block, but in the scope:
let mut x; //~ ERROR foo
if cond {
x = &'blk [1,2,3];
}
}
fn main()
|
{}
|
identifier_body
|
|
regions-out-of-scope-slice.rs
|
// Copyright 2012-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.
// compile-flags: -Z parse-only
// ignore-test blk region isn't supported in the front-end
fn
|
(cond: bool) {
// Here we will infer a type that uses the
// region of the if stmt then block, but in the scope:
let mut x; //~ ERROR foo
if cond {
x = &'blk [1,2,3];
}
}
fn main() {}
|
foo
|
identifier_name
|
thread_local.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.
use prelude::v1::*;
use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL};
use mem;
use rt;
use sys_common::mutex::{MUTEX_INIT, Mutex};
pub type Key = DWORD;
pub type Dtor = unsafe extern fn(*mut u8);
// Turns out, like pretty much everything, Windows is pretty close the
// functionality that Unix provides, but slightly different! In the case of
// TLS, Windows does not provide an API to provide a destructor for a TLS
// variable. This ends up being pretty crucial to this implementation, so we
// need a way around this.
//
// The solution here ended up being a little obscure, but fear not, the
// internet has informed me [1][2] that this solution is not unique (no way
// I could have thought of it as well!). The key idea is to insert some hook
// somewhere to run arbitrary code on thread termination. With this in place
// we'll be able to run anything we like, including all TLS destructors!
//
// To accomplish this feat, we perform a number of tasks, all contained
// within this module:
//
// * All TLS destructors are tracked by *us*, not the windows runtime. This
// means that we have a global list of destructors for each TLS key that
// we know about.
// * When a TLS key is destroyed, we're sure to remove it from the dtor list
// if it's in there.
// * When a thread exits, we run over the entire list and run dtors for all
// non-null keys. This attempts to match Unix semantics in this regard.
//
// This ends up having the overhead of using a global list, having some
// locks here and there, and in general just adding some more code bloat. We
// attempt to optimize runtime by forgetting keys that don't have
// destructors, but this only gets us so far.
//
// For more details and nitty-gritty, see the code sections below!
//
// [1]: http://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way
// [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base
// /threading/thread_local_storage_win.cc#L42
// NB these are specifically not types from `std::sync` as they currently rely
// on poisoning and this module needs to operate at a lower level than requiring
// the thread infrastructure to be in place (useful on the borders of
// initialization/destruction).
static DTOR_LOCK: Mutex = MUTEX_INIT;
static mut DTORS: *mut Vec<(Key, Dtor)> = 0 as *mut _;
// -------------------------------------------------------------------------
// Native bindings
//
// This section is just raw bindings to the native functions that Windows
// provides, There's a few extra calls to deal with destructors.
#[inline]
pub unsafe fn create(dtor: Option<Dtor>) -> Key {
const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF;
let key = TlsAlloc();
assert!(key!= TLS_OUT_OF_INDEXES);
match dtor {
Some(f) => register_dtor(key, f),
None => {}
}
return key;
}
#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
let r = TlsSetValue(key, value as LPVOID);
debug_assert!(r!= 0);
}
#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
TlsGetValue(key) as *mut u8
}
#[inline]
pub unsafe fn destroy(key: Key) {
if unregister_dtor(key) {
// FIXME: Currently if a key has a destructor associated with it we
// can't actually ever unregister it. If we were to
// unregister it, then any key destruction would have to be
// serialized with respect to actually running destructors.
//
// We want to avoid a race where right before run_dtors runs
// some destructors TlsFree is called. Allowing the call to
// TlsFree would imply that the caller understands that *all
// known threads* are not exiting, which is quite a difficult
// thing to know!
//
// For now we just leak all keys with dtors to "fix" this.
// Note that source [2] above shows precedent for this sort
// of strategy.
} else {
let r = TlsFree(key);
debug_assert!(r!= 0);
}
}
extern "system" {
fn TlsAlloc() -> DWORD;
fn TlsFree(dwTlsIndex: DWORD) -> BOOL;
fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID;
fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL;
}
// -------------------------------------------------------------------------
// Dtor registration
//
// These functions are associated with registering and unregistering
// destructors. They're pretty simple, they just push onto a vector and scan
// a vector currently.
//
// FIXME: This could probably be at least a little faster with a BTree.
unsafe fn init_dtors() {
if!DTORS.is_null() { return }
let dtors = box Vec::<(Key, Dtor)>::new();
DTORS = mem::transmute(dtors);
rt::at_exit(move|| {
DTOR_LOCK.lock();
let dtors = DTORS;
DTORS = 0 as *mut _;
mem::transmute::<_, Box<Vec<(Key, Dtor)>>>(dtors);
assert!(DTORS.is_null()); // can't re-init after destructing
DTOR_LOCK.unlock();
});
}
unsafe fn register_dtor(key: Key, dtor: Dtor) {
DTOR_LOCK.lock();
init_dtors();
(*DTORS).push((key, dtor));
DTOR_LOCK.unlock();
}
unsafe fn unregister_dtor(key: Key) -> bool {
DTOR_LOCK.lock();
init_dtors();
let ret = {
let dtors = &mut *DTORS;
let before = dtors.len();
dtors.retain(|&(k, _)| k!= key);
dtors.len()!= before
};
DTOR_LOCK.unlock();
ret
}
// -------------------------------------------------------------------------
// Where the Magic (TM) Happens
//
// If you're looking at this code, and wondering "what is this doing?",
// you're not alone! I'll try to break this down step by step:
//
// # What's up with CRT$XLB?
//
// For anything about TLS destructors to work on Windows, we have to be able
// to run *something* when a thread exits. To do so, we place a very special
// static in a very special location. If this is encoded in just the right
// way, the kernel's loader is apparently nice enough to run some function
// of ours whenever a thread exits! How nice of the kernel!
//
// Lots of detailed information can be found in source [1] above, but the
// gist of it is that this is leveraging a feature of Microsoft's PE format
// (executable format) which is not actually used by any compilers today.
// This apparently translates to any callbacks in the ".CRT$XLB" section
// being run on certain events.
//
// So after all that, we use the compiler's #[link_section] feature to place
// a callback pointer into the magic section so it ends up being called.
//
// # What's up with this callback?
//
// The callback specified receives a number of parameters from... someone!
// (the kernel? the runtime? I'm not qute sure!) There are a few events that
// this gets invoked for, but we're currently only interested on when a
// thread or a process "detaches" (exits). The process part happens for the
// last thread and the thread part happens for any normal thread.
//
// # Ok, what's up with running all these destructors?
//
// This will likely need to be improved over time, but this function
// attempts a "poor man's" destructor callback system. To do this we clone a
// local copy of the dtor list to start out with. This is our fudgy attempt
// to not hold the lock while destructors run and not worry about the list
// changing while we're looking at it.
//
// Once we've got a list of what to run, we iterate over all keys, check
// their values, and then run destructors if the values turn out to be non
// null (setting them to null just beforehand). We do this a few times in a
// loop to basically match Unix semantics. If we don't reach a fixed point
// after a short while then we just inevitably leak something most likely.
//
// # The article mentions crazy stuff about "/INCLUDE"?
//
// It sure does! This seems to work for now, so maybe we'll just run into
// that if we start linking with msvc?
#[link_section = ".CRT$XLB"]
#[linkage = "external"]
#[allow(warnings)]
pub static p_thread_callback: unsafe extern "system" fn(LPVOID, DWORD,
LPVOID) =
on_tls_callback;
#[allow(warnings)]
unsafe extern "system" fn on_tls_callback(h: LPVOID,
dwReason: DWORD,
pv: LPVOID) {
const DLL_THREAD_DETACH: DWORD = 3;
const DLL_PROCESS_DETACH: DWORD = 0;
if dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH {
run_dtors();
}
}
unsafe fn run_dtors() {
let mut any_run = true;
for _ in range(0, 5i) {
if!any_run { break }
any_run = false;
let dtors = {
DTOR_LOCK.lock();
let ret = if DTORS.is_null() {
Vec::new()
} else {
(*DTORS).iter().map(|s| *s).collect()
};
DTOR_LOCK.unlock();
ret
};
for &(key, dtor) in dtors.iter() {
let ptr = TlsGetValue(key);
if!ptr.is_null()
|
}
}
}
|
{
TlsSetValue(key, 0 as *mut _);
dtor(ptr as *mut _);
any_run = true;
}
|
conditional_block
|
thread_local.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.
use prelude::v1::*;
use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL};
use mem;
use rt;
use sys_common::mutex::{MUTEX_INIT, Mutex};
pub type Key = DWORD;
pub type Dtor = unsafe extern fn(*mut u8);
// Turns out, like pretty much everything, Windows is pretty close the
// functionality that Unix provides, but slightly different! In the case of
// TLS, Windows does not provide an API to provide a destructor for a TLS
// variable. This ends up being pretty crucial to this implementation, so we
// need a way around this.
//
// The solution here ended up being a little obscure, but fear not, the
// internet has informed me [1][2] that this solution is not unique (no way
// I could have thought of it as well!). The key idea is to insert some hook
// somewhere to run arbitrary code on thread termination. With this in place
// we'll be able to run anything we like, including all TLS destructors!
//
// To accomplish this feat, we perform a number of tasks, all contained
// within this module:
//
// * All TLS destructors are tracked by *us*, not the windows runtime. This
// means that we have a global list of destructors for each TLS key that
// we know about.
// * When a TLS key is destroyed, we're sure to remove it from the dtor list
// if it's in there.
// * When a thread exits, we run over the entire list and run dtors for all
// non-null keys. This attempts to match Unix semantics in this regard.
//
// This ends up having the overhead of using a global list, having some
// locks here and there, and in general just adding some more code bloat. We
// attempt to optimize runtime by forgetting keys that don't have
// destructors, but this only gets us so far.
//
// For more details and nitty-gritty, see the code sections below!
//
// [1]: http://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way
// [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base
// /threading/thread_local_storage_win.cc#L42
// NB these are specifically not types from `std::sync` as they currently rely
// on poisoning and this module needs to operate at a lower level than requiring
// the thread infrastructure to be in place (useful on the borders of
// initialization/destruction).
static DTOR_LOCK: Mutex = MUTEX_INIT;
static mut DTORS: *mut Vec<(Key, Dtor)> = 0 as *mut _;
// -------------------------------------------------------------------------
// Native bindings
//
// This section is just raw bindings to the native functions that Windows
// provides, There's a few extra calls to deal with destructors.
#[inline]
pub unsafe fn create(dtor: Option<Dtor>) -> Key {
const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF;
let key = TlsAlloc();
assert!(key!= TLS_OUT_OF_INDEXES);
match dtor {
Some(f) => register_dtor(key, f),
None => {}
}
return key;
}
#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
let r = TlsSetValue(key, value as LPVOID);
debug_assert!(r!= 0);
}
#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
TlsGetValue(key) as *mut u8
}
#[inline]
pub unsafe fn destroy(key: Key) {
if unregister_dtor(key) {
// FIXME: Currently if a key has a destructor associated with it we
// can't actually ever unregister it. If we were to
// unregister it, then any key destruction would have to be
// serialized with respect to actually running destructors.
//
// We want to avoid a race where right before run_dtors runs
// some destructors TlsFree is called. Allowing the call to
// TlsFree would imply that the caller understands that *all
// known threads* are not exiting, which is quite a difficult
// thing to know!
//
// For now we just leak all keys with dtors to "fix" this.
// Note that source [2] above shows precedent for this sort
// of strategy.
} else {
let r = TlsFree(key);
debug_assert!(r!= 0);
}
}
extern "system" {
fn TlsAlloc() -> DWORD;
fn TlsFree(dwTlsIndex: DWORD) -> BOOL;
fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID;
fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL;
}
// -------------------------------------------------------------------------
// Dtor registration
//
// These functions are associated with registering and unregistering
// destructors. They're pretty simple, they just push onto a vector and scan
// a vector currently.
//
// FIXME: This could probably be at least a little faster with a BTree.
unsafe fn init_dtors() {
if!DTORS.is_null() { return }
let dtors = box Vec::<(Key, Dtor)>::new();
DTORS = mem::transmute(dtors);
rt::at_exit(move|| {
DTOR_LOCK.lock();
let dtors = DTORS;
DTORS = 0 as *mut _;
mem::transmute::<_, Box<Vec<(Key, Dtor)>>>(dtors);
assert!(DTORS.is_null()); // can't re-init after destructing
DTOR_LOCK.unlock();
});
}
unsafe fn register_dtor(key: Key, dtor: Dtor) {
DTOR_LOCK.lock();
init_dtors();
(*DTORS).push((key, dtor));
DTOR_LOCK.unlock();
}
unsafe fn unregister_dtor(key: Key) -> bool {
DTOR_LOCK.lock();
init_dtors();
let ret = {
let dtors = &mut *DTORS;
let before = dtors.len();
dtors.retain(|&(k, _)| k!= key);
dtors.len()!= before
};
DTOR_LOCK.unlock();
ret
}
// -------------------------------------------------------------------------
// Where the Magic (TM) Happens
//
// If you're looking at this code, and wondering "what is this doing?",
// you're not alone! I'll try to break this down step by step:
//
// # What's up with CRT$XLB?
//
// For anything about TLS destructors to work on Windows, we have to be able
// to run *something* when a thread exits. To do so, we place a very special
// static in a very special location. If this is encoded in just the right
// way, the kernel's loader is apparently nice enough to run some function
// of ours whenever a thread exits! How nice of the kernel!
//
// Lots of detailed information can be found in source [1] above, but the
// gist of it is that this is leveraging a feature of Microsoft's PE format
// (executable format) which is not actually used by any compilers today.
// This apparently translates to any callbacks in the ".CRT$XLB" section
// being run on certain events.
//
// So after all that, we use the compiler's #[link_section] feature to place
// a callback pointer into the magic section so it ends up being called.
//
// # What's up with this callback?
//
// The callback specified receives a number of parameters from... someone!
// (the kernel? the runtime? I'm not qute sure!) There are a few events that
// this gets invoked for, but we're currently only interested on when a
// thread or a process "detaches" (exits). The process part happens for the
// last thread and the thread part happens for any normal thread.
//
// # Ok, what's up with running all these destructors?
//
// This will likely need to be improved over time, but this function
// attempts a "poor man's" destructor callback system. To do this we clone a
// local copy of the dtor list to start out with. This is our fudgy attempt
// to not hold the lock while destructors run and not worry about the list
// changing while we're looking at it.
//
// Once we've got a list of what to run, we iterate over all keys, check
// their values, and then run destructors if the values turn out to be non
// null (setting them to null just beforehand). We do this a few times in a
// loop to basically match Unix semantics. If we don't reach a fixed point
// after a short while then we just inevitably leak something most likely.
//
// # The article mentions crazy stuff about "/INCLUDE"?
//
// It sure does! This seems to work for now, so maybe we'll just run into
// that if we start linking with msvc?
#[link_section = ".CRT$XLB"]
#[linkage = "external"]
#[allow(warnings)]
pub static p_thread_callback: unsafe extern "system" fn(LPVOID, DWORD,
LPVOID) =
on_tls_callback;
#[allow(warnings)]
unsafe extern "system" fn on_tls_callback(h: LPVOID,
dwReason: DWORD,
pv: LPVOID) {
const DLL_THREAD_DETACH: DWORD = 3;
const DLL_PROCESS_DETACH: DWORD = 0;
if dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH {
run_dtors();
}
}
unsafe fn run_dtors() {
let mut any_run = true;
for _ in range(0, 5i) {
if!any_run { break }
any_run = false;
let dtors = {
DTOR_LOCK.lock();
let ret = if DTORS.is_null() {
Vec::new()
} else {
(*DTORS).iter().map(|s| *s).collect()
};
DTOR_LOCK.unlock();
ret
};
for &(key, dtor) in dtors.iter() {
let ptr = TlsGetValue(key);
if!ptr.is_null() {
TlsSetValue(key, 0 as *mut _);
dtor(ptr as *mut _);
any_run = true;
|
}
}
}
|
}
|
random_line_split
|
thread_local.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.
use prelude::v1::*;
use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL};
use mem;
use rt;
use sys_common::mutex::{MUTEX_INIT, Mutex};
pub type Key = DWORD;
pub type Dtor = unsafe extern fn(*mut u8);
// Turns out, like pretty much everything, Windows is pretty close the
// functionality that Unix provides, but slightly different! In the case of
// TLS, Windows does not provide an API to provide a destructor for a TLS
// variable. This ends up being pretty crucial to this implementation, so we
// need a way around this.
//
// The solution here ended up being a little obscure, but fear not, the
// internet has informed me [1][2] that this solution is not unique (no way
// I could have thought of it as well!). The key idea is to insert some hook
// somewhere to run arbitrary code on thread termination. With this in place
// we'll be able to run anything we like, including all TLS destructors!
//
// To accomplish this feat, we perform a number of tasks, all contained
// within this module:
//
// * All TLS destructors are tracked by *us*, not the windows runtime. This
// means that we have a global list of destructors for each TLS key that
// we know about.
// * When a TLS key is destroyed, we're sure to remove it from the dtor list
// if it's in there.
// * When a thread exits, we run over the entire list and run dtors for all
// non-null keys. This attempts to match Unix semantics in this regard.
//
// This ends up having the overhead of using a global list, having some
// locks here and there, and in general just adding some more code bloat. We
// attempt to optimize runtime by forgetting keys that don't have
// destructors, but this only gets us so far.
//
// For more details and nitty-gritty, see the code sections below!
//
// [1]: http://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way
// [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base
// /threading/thread_local_storage_win.cc#L42
// NB these are specifically not types from `std::sync` as they currently rely
// on poisoning and this module needs to operate at a lower level than requiring
// the thread infrastructure to be in place (useful on the borders of
// initialization/destruction).
static DTOR_LOCK: Mutex = MUTEX_INIT;
static mut DTORS: *mut Vec<(Key, Dtor)> = 0 as *mut _;
// -------------------------------------------------------------------------
// Native bindings
//
// This section is just raw bindings to the native functions that Windows
// provides, There's a few extra calls to deal with destructors.
#[inline]
pub unsafe fn create(dtor: Option<Dtor>) -> Key {
const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF;
let key = TlsAlloc();
assert!(key!= TLS_OUT_OF_INDEXES);
match dtor {
Some(f) => register_dtor(key, f),
None => {}
}
return key;
}
#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
let r = TlsSetValue(key, value as LPVOID);
debug_assert!(r!= 0);
}
#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
TlsGetValue(key) as *mut u8
}
#[inline]
pub unsafe fn destroy(key: Key) {
if unregister_dtor(key) {
// FIXME: Currently if a key has a destructor associated with it we
// can't actually ever unregister it. If we were to
// unregister it, then any key destruction would have to be
// serialized with respect to actually running destructors.
//
// We want to avoid a race where right before run_dtors runs
// some destructors TlsFree is called. Allowing the call to
// TlsFree would imply that the caller understands that *all
// known threads* are not exiting, which is quite a difficult
// thing to know!
//
// For now we just leak all keys with dtors to "fix" this.
// Note that source [2] above shows precedent for this sort
// of strategy.
} else {
let r = TlsFree(key);
debug_assert!(r!= 0);
}
}
extern "system" {
fn TlsAlloc() -> DWORD;
fn TlsFree(dwTlsIndex: DWORD) -> BOOL;
fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID;
fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL;
}
// -------------------------------------------------------------------------
// Dtor registration
//
// These functions are associated with registering and unregistering
// destructors. They're pretty simple, they just push onto a vector and scan
// a vector currently.
//
// FIXME: This could probably be at least a little faster with a BTree.
unsafe fn init_dtors() {
if!DTORS.is_null() { return }
let dtors = box Vec::<(Key, Dtor)>::new();
DTORS = mem::transmute(dtors);
rt::at_exit(move|| {
DTOR_LOCK.lock();
let dtors = DTORS;
DTORS = 0 as *mut _;
mem::transmute::<_, Box<Vec<(Key, Dtor)>>>(dtors);
assert!(DTORS.is_null()); // can't re-init after destructing
DTOR_LOCK.unlock();
});
}
unsafe fn register_dtor(key: Key, dtor: Dtor) {
DTOR_LOCK.lock();
init_dtors();
(*DTORS).push((key, dtor));
DTOR_LOCK.unlock();
}
unsafe fn unregister_dtor(key: Key) -> bool {
DTOR_LOCK.lock();
init_dtors();
let ret = {
let dtors = &mut *DTORS;
let before = dtors.len();
dtors.retain(|&(k, _)| k!= key);
dtors.len()!= before
};
DTOR_LOCK.unlock();
ret
}
// -------------------------------------------------------------------------
// Where the Magic (TM) Happens
//
// If you're looking at this code, and wondering "what is this doing?",
// you're not alone! I'll try to break this down step by step:
//
// # What's up with CRT$XLB?
//
// For anything about TLS destructors to work on Windows, we have to be able
// to run *something* when a thread exits. To do so, we place a very special
// static in a very special location. If this is encoded in just the right
// way, the kernel's loader is apparently nice enough to run some function
// of ours whenever a thread exits! How nice of the kernel!
//
// Lots of detailed information can be found in source [1] above, but the
// gist of it is that this is leveraging a feature of Microsoft's PE format
// (executable format) which is not actually used by any compilers today.
// This apparently translates to any callbacks in the ".CRT$XLB" section
// being run on certain events.
//
// So after all that, we use the compiler's #[link_section] feature to place
// a callback pointer into the magic section so it ends up being called.
//
// # What's up with this callback?
//
// The callback specified receives a number of parameters from... someone!
// (the kernel? the runtime? I'm not qute sure!) There are a few events that
// this gets invoked for, but we're currently only interested on when a
// thread or a process "detaches" (exits). The process part happens for the
// last thread and the thread part happens for any normal thread.
//
// # Ok, what's up with running all these destructors?
//
// This will likely need to be improved over time, but this function
// attempts a "poor man's" destructor callback system. To do this we clone a
// local copy of the dtor list to start out with. This is our fudgy attempt
// to not hold the lock while destructors run and not worry about the list
// changing while we're looking at it.
//
// Once we've got a list of what to run, we iterate over all keys, check
// their values, and then run destructors if the values turn out to be non
// null (setting them to null just beforehand). We do this a few times in a
// loop to basically match Unix semantics. If we don't reach a fixed point
// after a short while then we just inevitably leak something most likely.
//
// # The article mentions crazy stuff about "/INCLUDE"?
//
// It sure does! This seems to work for now, so maybe we'll just run into
// that if we start linking with msvc?
#[link_section = ".CRT$XLB"]
#[linkage = "external"]
#[allow(warnings)]
pub static p_thread_callback: unsafe extern "system" fn(LPVOID, DWORD,
LPVOID) =
on_tls_callback;
#[allow(warnings)]
unsafe extern "system" fn on_tls_callback(h: LPVOID,
dwReason: DWORD,
pv: LPVOID) {
const DLL_THREAD_DETACH: DWORD = 3;
const DLL_PROCESS_DETACH: DWORD = 0;
if dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH {
run_dtors();
}
}
unsafe fn
|
() {
let mut any_run = true;
for _ in range(0, 5i) {
if!any_run { break }
any_run = false;
let dtors = {
DTOR_LOCK.lock();
let ret = if DTORS.is_null() {
Vec::new()
} else {
(*DTORS).iter().map(|s| *s).collect()
};
DTOR_LOCK.unlock();
ret
};
for &(key, dtor) in dtors.iter() {
let ptr = TlsGetValue(key);
if!ptr.is_null() {
TlsSetValue(key, 0 as *mut _);
dtor(ptr as *mut _);
any_run = true;
}
}
}
}
|
run_dtors
|
identifier_name
|
thread_local.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.
use prelude::v1::*;
use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL};
use mem;
use rt;
use sys_common::mutex::{MUTEX_INIT, Mutex};
pub type Key = DWORD;
pub type Dtor = unsafe extern fn(*mut u8);
// Turns out, like pretty much everything, Windows is pretty close the
// functionality that Unix provides, but slightly different! In the case of
// TLS, Windows does not provide an API to provide a destructor for a TLS
// variable. This ends up being pretty crucial to this implementation, so we
// need a way around this.
//
// The solution here ended up being a little obscure, but fear not, the
// internet has informed me [1][2] that this solution is not unique (no way
// I could have thought of it as well!). The key idea is to insert some hook
// somewhere to run arbitrary code on thread termination. With this in place
// we'll be able to run anything we like, including all TLS destructors!
//
// To accomplish this feat, we perform a number of tasks, all contained
// within this module:
//
// * All TLS destructors are tracked by *us*, not the windows runtime. This
// means that we have a global list of destructors for each TLS key that
// we know about.
// * When a TLS key is destroyed, we're sure to remove it from the dtor list
// if it's in there.
// * When a thread exits, we run over the entire list and run dtors for all
// non-null keys. This attempts to match Unix semantics in this regard.
//
// This ends up having the overhead of using a global list, having some
// locks here and there, and in general just adding some more code bloat. We
// attempt to optimize runtime by forgetting keys that don't have
// destructors, but this only gets us so far.
//
// For more details and nitty-gritty, see the code sections below!
//
// [1]: http://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way
// [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base
// /threading/thread_local_storage_win.cc#L42
// NB these are specifically not types from `std::sync` as they currently rely
// on poisoning and this module needs to operate at a lower level than requiring
// the thread infrastructure to be in place (useful on the borders of
// initialization/destruction).
static DTOR_LOCK: Mutex = MUTEX_INIT;
static mut DTORS: *mut Vec<(Key, Dtor)> = 0 as *mut _;
// -------------------------------------------------------------------------
// Native bindings
//
// This section is just raw bindings to the native functions that Windows
// provides, There's a few extra calls to deal with destructors.
#[inline]
pub unsafe fn create(dtor: Option<Dtor>) -> Key {
const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF;
let key = TlsAlloc();
assert!(key!= TLS_OUT_OF_INDEXES);
match dtor {
Some(f) => register_dtor(key, f),
None => {}
}
return key;
}
#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
let r = TlsSetValue(key, value as LPVOID);
debug_assert!(r!= 0);
}
#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
TlsGetValue(key) as *mut u8
}
#[inline]
pub unsafe fn destroy(key: Key) {
if unregister_dtor(key) {
// FIXME: Currently if a key has a destructor associated with it we
// can't actually ever unregister it. If we were to
// unregister it, then any key destruction would have to be
// serialized with respect to actually running destructors.
//
// We want to avoid a race where right before run_dtors runs
// some destructors TlsFree is called. Allowing the call to
// TlsFree would imply that the caller understands that *all
// known threads* are not exiting, which is quite a difficult
// thing to know!
//
// For now we just leak all keys with dtors to "fix" this.
// Note that source [2] above shows precedent for this sort
// of strategy.
} else {
let r = TlsFree(key);
debug_assert!(r!= 0);
}
}
extern "system" {
fn TlsAlloc() -> DWORD;
fn TlsFree(dwTlsIndex: DWORD) -> BOOL;
fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID;
fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL;
}
// -------------------------------------------------------------------------
// Dtor registration
//
// These functions are associated with registering and unregistering
// destructors. They're pretty simple, they just push onto a vector and scan
// a vector currently.
//
// FIXME: This could probably be at least a little faster with a BTree.
unsafe fn init_dtors() {
if!DTORS.is_null() { return }
let dtors = box Vec::<(Key, Dtor)>::new();
DTORS = mem::transmute(dtors);
rt::at_exit(move|| {
DTOR_LOCK.lock();
let dtors = DTORS;
DTORS = 0 as *mut _;
mem::transmute::<_, Box<Vec<(Key, Dtor)>>>(dtors);
assert!(DTORS.is_null()); // can't re-init after destructing
DTOR_LOCK.unlock();
});
}
unsafe fn register_dtor(key: Key, dtor: Dtor) {
DTOR_LOCK.lock();
init_dtors();
(*DTORS).push((key, dtor));
DTOR_LOCK.unlock();
}
unsafe fn unregister_dtor(key: Key) -> bool {
DTOR_LOCK.lock();
init_dtors();
let ret = {
let dtors = &mut *DTORS;
let before = dtors.len();
dtors.retain(|&(k, _)| k!= key);
dtors.len()!= before
};
DTOR_LOCK.unlock();
ret
}
// -------------------------------------------------------------------------
// Where the Magic (TM) Happens
//
// If you're looking at this code, and wondering "what is this doing?",
// you're not alone! I'll try to break this down step by step:
//
// # What's up with CRT$XLB?
//
// For anything about TLS destructors to work on Windows, we have to be able
// to run *something* when a thread exits. To do so, we place a very special
// static in a very special location. If this is encoded in just the right
// way, the kernel's loader is apparently nice enough to run some function
// of ours whenever a thread exits! How nice of the kernel!
//
// Lots of detailed information can be found in source [1] above, but the
// gist of it is that this is leveraging a feature of Microsoft's PE format
// (executable format) which is not actually used by any compilers today.
// This apparently translates to any callbacks in the ".CRT$XLB" section
// being run on certain events.
//
// So after all that, we use the compiler's #[link_section] feature to place
// a callback pointer into the magic section so it ends up being called.
//
// # What's up with this callback?
//
// The callback specified receives a number of parameters from... someone!
// (the kernel? the runtime? I'm not qute sure!) There are a few events that
// this gets invoked for, but we're currently only interested on when a
// thread or a process "detaches" (exits). The process part happens for the
// last thread and the thread part happens for any normal thread.
//
// # Ok, what's up with running all these destructors?
//
// This will likely need to be improved over time, but this function
// attempts a "poor man's" destructor callback system. To do this we clone a
// local copy of the dtor list to start out with. This is our fudgy attempt
// to not hold the lock while destructors run and not worry about the list
// changing while we're looking at it.
//
// Once we've got a list of what to run, we iterate over all keys, check
// their values, and then run destructors if the values turn out to be non
// null (setting them to null just beforehand). We do this a few times in a
// loop to basically match Unix semantics. If we don't reach a fixed point
// after a short while then we just inevitably leak something most likely.
//
// # The article mentions crazy stuff about "/INCLUDE"?
//
// It sure does! This seems to work for now, so maybe we'll just run into
// that if we start linking with msvc?
#[link_section = ".CRT$XLB"]
#[linkage = "external"]
#[allow(warnings)]
pub static p_thread_callback: unsafe extern "system" fn(LPVOID, DWORD,
LPVOID) =
on_tls_callback;
#[allow(warnings)]
unsafe extern "system" fn on_tls_callback(h: LPVOID,
dwReason: DWORD,
pv: LPVOID)
|
unsafe fn run_dtors() {
let mut any_run = true;
for _ in range(0, 5i) {
if!any_run { break }
any_run = false;
let dtors = {
DTOR_LOCK.lock();
let ret = if DTORS.is_null() {
Vec::new()
} else {
(*DTORS).iter().map(|s| *s).collect()
};
DTOR_LOCK.unlock();
ret
};
for &(key, dtor) in dtors.iter() {
let ptr = TlsGetValue(key);
if!ptr.is_null() {
TlsSetValue(key, 0 as *mut _);
dtor(ptr as *mut _);
any_run = true;
}
}
}
}
|
{
const DLL_THREAD_DETACH: DWORD = 3;
const DLL_PROCESS_DETACH: DWORD = 0;
if dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH {
run_dtors();
}
}
|
identifier_body
|
x86.rs
|
extern crate capstone_sys;
use std::os::raw::c_char;
use capstone_sys::*;
use capstone_sys::x86::*;
const X86_CODE16: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE32: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE64: &'static [u8] = b"\x55\x48\x8b\x05\xb8\x13\x00\x00";
fn to_str(raw: &[c_char]) -> &str {
unsafe {
::std::ffi::CStr::from_ptr(raw.as_ptr()).to_str().expect("invalid UTF-8")
}
}
fn generic(arch: cs_arch, mode: cs_mode, code: &[u8], expected_size: size_t, expected_first: (&str, &str, &[x86_op_type])) {
let mut handle: csh = 0;
let err = unsafe { cs_open(arch, mode, &mut handle) };
assert_eq!(err, CS_ERR_OK);
// let err = unsafe { cs_option(handle, CS_OPT_SYNTAX, CS_OPT_SYNTAX_ATT as size_t) };
// assert_eq!(err, CS_ERR_OK);
let err = unsafe { cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON as size_t) };
assert_eq!(err, CS_ERR_OK);
let mut instrs: *mut cs_insn = ::std::ptr::null_mut();
let size = unsafe { cs_disasm(handle, code.as_ptr(), code.len(), 0, 0 /* read as much as possible */, &mut instrs) };
let err = unsafe { cs_errno(handle) };
assert_eq!(err, CS_ERR_OK);
assert_eq!(size, expected_size);
assert!(!instrs.is_null());
let instr = unsafe { &*instrs };
let (mnemonic, op_str, ops) = expected_first;
assert_eq!(to_str(&instr.mnemonic), mnemonic);
assert_eq!(to_str(&instr.op_str), op_str);
assert!(!instr.detail.is_null());
let detail = unsafe { (&*instr.detail).x86() };
assert_eq!(detail.op_count, ops.len() as u8);
for i in 0..ops.len() {
assert_eq!(detail.operands[i].typ, ops[i]);
}
unsafe {
cs_close(&mut handle);
}
}
#[test]
fn test_x86_16() {
generic(CS_ARCH_X86, CS_MODE_16, X86_CODE16, 15, ("lea", "cx, word ptr [si + 0x32]", &[X86_OP_REG, X86_OP_MEM]));
}
#[test]
fn test_x86_32() {
generic(CS_ARCH_X86, CS_MODE_32, X86_CODE32, 9, ("lea", "ecx, dword ptr [edx + esi + 8]", &[X86_OP_REG, X86_OP_MEM]));
}
#[test]
fn
|
() {
generic(CS_ARCH_X86, CS_MODE_64, X86_CODE64, 2, ("push", "rbp", &[X86_OP_REG]));
}
|
test_x86_64
|
identifier_name
|
x86.rs
|
extern crate capstone_sys;
use std::os::raw::c_char;
use capstone_sys::*;
use capstone_sys::x86::*;
const X86_CODE16: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
|
const X86_CODE32: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE64: &'static [u8] = b"\x55\x48\x8b\x05\xb8\x13\x00\x00";
fn to_str(raw: &[c_char]) -> &str {
unsafe {
::std::ffi::CStr::from_ptr(raw.as_ptr()).to_str().expect("invalid UTF-8")
}
}
fn generic(arch: cs_arch, mode: cs_mode, code: &[u8], expected_size: size_t, expected_first: (&str, &str, &[x86_op_type])) {
let mut handle: csh = 0;
let err = unsafe { cs_open(arch, mode, &mut handle) };
assert_eq!(err, CS_ERR_OK);
// let err = unsafe { cs_option(handle, CS_OPT_SYNTAX, CS_OPT_SYNTAX_ATT as size_t) };
// assert_eq!(err, CS_ERR_OK);
let err = unsafe { cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON as size_t) };
assert_eq!(err, CS_ERR_OK);
let mut instrs: *mut cs_insn = ::std::ptr::null_mut();
let size = unsafe { cs_disasm(handle, code.as_ptr(), code.len(), 0, 0 /* read as much as possible */, &mut instrs) };
let err = unsafe { cs_errno(handle) };
assert_eq!(err, CS_ERR_OK);
assert_eq!(size, expected_size);
assert!(!instrs.is_null());
let instr = unsafe { &*instrs };
let (mnemonic, op_str, ops) = expected_first;
assert_eq!(to_str(&instr.mnemonic), mnemonic);
assert_eq!(to_str(&instr.op_str), op_str);
assert!(!instr.detail.is_null());
let detail = unsafe { (&*instr.detail).x86() };
assert_eq!(detail.op_count, ops.len() as u8);
for i in 0..ops.len() {
assert_eq!(detail.operands[i].typ, ops[i]);
}
unsafe {
cs_close(&mut handle);
}
}
#[test]
fn test_x86_16() {
generic(CS_ARCH_X86, CS_MODE_16, X86_CODE16, 15, ("lea", "cx, word ptr [si + 0x32]", &[X86_OP_REG, X86_OP_MEM]));
}
#[test]
fn test_x86_32() {
generic(CS_ARCH_X86, CS_MODE_32, X86_CODE32, 9, ("lea", "ecx, dword ptr [edx + esi + 8]", &[X86_OP_REG, X86_OP_MEM]));
}
#[test]
fn test_x86_64() {
generic(CS_ARCH_X86, CS_MODE_64, X86_CODE64, 2, ("push", "rbp", &[X86_OP_REG]));
}
|
random_line_split
|
|
x86.rs
|
extern crate capstone_sys;
use std::os::raw::c_char;
use capstone_sys::*;
use capstone_sys::x86::*;
const X86_CODE16: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE32: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE64: &'static [u8] = b"\x55\x48\x8b\x05\xb8\x13\x00\x00";
fn to_str(raw: &[c_char]) -> &str {
unsafe {
::std::ffi::CStr::from_ptr(raw.as_ptr()).to_str().expect("invalid UTF-8")
}
}
fn generic(arch: cs_arch, mode: cs_mode, code: &[u8], expected_size: size_t, expected_first: (&str, &str, &[x86_op_type])) {
let mut handle: csh = 0;
let err = unsafe { cs_open(arch, mode, &mut handle) };
assert_eq!(err, CS_ERR_OK);
// let err = unsafe { cs_option(handle, CS_OPT_SYNTAX, CS_OPT_SYNTAX_ATT as size_t) };
// assert_eq!(err, CS_ERR_OK);
let err = unsafe { cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON as size_t) };
assert_eq!(err, CS_ERR_OK);
let mut instrs: *mut cs_insn = ::std::ptr::null_mut();
let size = unsafe { cs_disasm(handle, code.as_ptr(), code.len(), 0, 0 /* read as much as possible */, &mut instrs) };
let err = unsafe { cs_errno(handle) };
assert_eq!(err, CS_ERR_OK);
assert_eq!(size, expected_size);
assert!(!instrs.is_null());
let instr = unsafe { &*instrs };
let (mnemonic, op_str, ops) = expected_first;
assert_eq!(to_str(&instr.mnemonic), mnemonic);
assert_eq!(to_str(&instr.op_str), op_str);
assert!(!instr.detail.is_null());
let detail = unsafe { (&*instr.detail).x86() };
assert_eq!(detail.op_count, ops.len() as u8);
for i in 0..ops.len() {
assert_eq!(detail.operands[i].typ, ops[i]);
}
unsafe {
cs_close(&mut handle);
}
}
#[test]
fn test_x86_16()
|
#[test]
fn test_x86_32() {
generic(CS_ARCH_X86, CS_MODE_32, X86_CODE32, 9, ("lea", "ecx, dword ptr [edx + esi + 8]", &[X86_OP_REG, X86_OP_MEM]));
}
#[test]
fn test_x86_64() {
generic(CS_ARCH_X86, CS_MODE_64, X86_CODE64, 2, ("push", "rbp", &[X86_OP_REG]));
}
|
{
generic(CS_ARCH_X86, CS_MODE_16, X86_CODE16, 15, ("lea", "cx, word ptr [si + 0x32]", &[X86_OP_REG, X86_OP_MEM]));
}
|
identifier_body
|
platform.rs
|
// Provides the abstraction layer: calls into the appropriate platform-native functions.
use ValidationResult;
#[cfg(target_os = "macos")]
use osx::validate_cert_chain as backend;
#[cfg(windows)]
use windows::validate_cert_chain as backend;
/// Validate a chain of certificates.
///
/// Given a chain of DER-encoded X.509 certificates and the hostname that you're
/// contacting, validates that the system considers that certificate chain valid for
/// the connection.
///
/// The `encoded_certs` should be in order of specificity: the "leaf" certificate first,
/// then each intermediate certificate in order. For the intermediate certificates, order
/// *may not* be important, but it is *extremely important* that the leaf come first.
/// If at all possible, preserve the order.
///
/// # Examples
///
/// Given a pre-allocated collection of certificates:
///
/// ```
/// match validate_cert_chain(certs, "google.com") {
/// ValidationResult::Trusted => Ok("success!"),
/// ValidationResult::NotTrusted => Ok("man in the middle!"),
/// _ => Err("an internal error occurred!"),
/// }
/// ```
pub fn validate_cert_chain(encoded_certs: &[&[u8]], hostname: &str) -> ValidationResult {
backend(encoded_certs, hostname)
|
}
|
random_line_split
|
|
platform.rs
|
// Provides the abstraction layer: calls into the appropriate platform-native functions.
use ValidationResult;
#[cfg(target_os = "macos")]
use osx::validate_cert_chain as backend;
#[cfg(windows)]
use windows::validate_cert_chain as backend;
/// Validate a chain of certificates.
///
/// Given a chain of DER-encoded X.509 certificates and the hostname that you're
/// contacting, validates that the system considers that certificate chain valid for
/// the connection.
///
/// The `encoded_certs` should be in order of specificity: the "leaf" certificate first,
/// then each intermediate certificate in order. For the intermediate certificates, order
/// *may not* be important, but it is *extremely important* that the leaf come first.
/// If at all possible, preserve the order.
///
/// # Examples
///
/// Given a pre-allocated collection of certificates:
///
/// ```
/// match validate_cert_chain(certs, "google.com") {
/// ValidationResult::Trusted => Ok("success!"),
/// ValidationResult::NotTrusted => Ok("man in the middle!"),
/// _ => Err("an internal error occurred!"),
/// }
/// ```
pub fn validate_cert_chain(encoded_certs: &[&[u8]], hostname: &str) -> ValidationResult
|
{
backend(encoded_certs, hostname)
}
|
identifier_body
|
|
platform.rs
|
// Provides the abstraction layer: calls into the appropriate platform-native functions.
use ValidationResult;
#[cfg(target_os = "macos")]
use osx::validate_cert_chain as backend;
#[cfg(windows)]
use windows::validate_cert_chain as backend;
/// Validate a chain of certificates.
///
/// Given a chain of DER-encoded X.509 certificates and the hostname that you're
/// contacting, validates that the system considers that certificate chain valid for
/// the connection.
///
/// The `encoded_certs` should be in order of specificity: the "leaf" certificate first,
/// then each intermediate certificate in order. For the intermediate certificates, order
/// *may not* be important, but it is *extremely important* that the leaf come first.
/// If at all possible, preserve the order.
///
/// # Examples
///
/// Given a pre-allocated collection of certificates:
///
/// ```
/// match validate_cert_chain(certs, "google.com") {
/// ValidationResult::Trusted => Ok("success!"),
/// ValidationResult::NotTrusted => Ok("man in the middle!"),
/// _ => Err("an internal error occurred!"),
/// }
/// ```
pub fn
|
(encoded_certs: &[&[u8]], hostname: &str) -> ValidationResult {
backend(encoded_certs, hostname)
}
|
validate_cert_chain
|
identifier_name
|
desc.rs
|
}
}
impl Id {
pub fn is_valid(self) -> bool {
self.0!= 0
}
pub fn to_type_id(self) -> TypeId {
TypeId(self.0)
}
pub fn to_value_id(self) -> ValueId {
ValueId(self.0)
}
pub fn to_result_id(self) -> ResultId {
ResultId(self.0)
}
}
impl TypeId {
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl ValueId {
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl ResultId {
pub fn to_type_id(self) -> TypeId {
TypeId(self.0)
}
pub fn to_value_id(self) -> ValueId {
ValueId(self.0)
}
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Id({})", self.0)
}
}
impl fmt::Debug for ResultId {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Result({})", self.0)
}
}
impl fmt::Debug for TypeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Type({})", self.0)
}
}
impl fmt::Debug for ValueId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Value({})", self.0)
}
}
macro_rules! def_enum {
(enum $en:ident { $($name:ident = $code:expr),+ }) => (
def_enum!(enum $en : u32 { $($name = $code),+ });
);
(enum $en:ident : $repr:ident { $($name:ident = $code:expr),+ }) => (
#[repr($repr)]
#[derive(Copy, Clone, Debug, PartialEq, Hash)]
pub enum $en {
$($name = $code,)+
}
impl $en {
pub fn from(val: $repr) -> Option<$en> {
match val {
$($code => Some($en::$name),)+
_ => None
}
}
}
)
}
macro_rules! def_bitset {
($setname:ident { $($name:ident = $code:expr),+ }) => (
#[derive(Copy, Clone, PartialEq, Hash)]
pub struct $setname(u32);
impl $setname {
#[inline]
pub fn empty() -> $setname {
$setname(0)
}
#[inline]
pub fn all() -> $setname {
$setname($($code)|+)
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0 == 0
}
#[inline]
pub fn contains(&self, val: $setname) -> bool {
let x = self.0 & val.0;
x!= 0
}
#[inline]
pub fn bits(&self) -> u32 {
self.0
}
#[inline]
pub fn insert(&mut self, val: $setname) {
self.0 |= val.0;
}
#[inline]
pub fn count(&self) -> u32 {
self.0.count_ones()
}
}
impl From<u32> for $setname {
#[inline]
fn from(val: u32) -> $setname {
$setname(val)
}
}
impl fmt::Debug for $setname {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(concat!(stringify!($setname), "{")));
if!self.is_empty() {
let mut _first = true;
$(if self.contains($name) {
if!_first {
try!(f.write_str(" | "));
}
try!(f.write_str(stringify!($name)));
_first = false;
})+
}
f.write_str("}")
}
}
$(pub const $name : $setname = $setname($code);)+
);
}
def_enum!(enum SrcLang {
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCl_CPP = 4
});
def_enum!(enum ExecutionModel {
Vertex = 0,
TesselationControl = 1,
TesselationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6
});
def_enum!(enum AddressingModel {
Logical = 0,
Physical32 = 1,
Physical64 = 2
});
def_enum!(enum MemoryModel {
Simple = 0,
GLSL450 = 1,
OpenCL = 2
});
def_enum!(enum ExecutionMode {
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
IsoLines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31
});
def_enum!(enum StorageClass {
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11
});
def_enum!(enum Dim {
_1D = 0,
_2D = 1,
_3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6
});
def_enum!(enum SamplerAddressingMode {
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4
});
def_enum!(enum SamplerFilterMode {
Nearest = 0,
Linear = 1
});
def_enum!(enum ImageFormat {
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39
});
def_enum!(enum ImageChannelOrder {
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18
});
def_enum!(enum ImageChannelDataType {
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16
});
def_bitset!(ImageOperands {
ImgOpBias = 0x01,
ImgOpLod = 0x02,
ImgOpGrad = 0x04,
ImgOpConstOffset = 0x08,
ImgOpOffset = 0x10,
ImgOpConstOffsets = 0x20,
ImgOpSample = 0x40,
ImgOpMinLod = 0x80
});
def_bitset!(FPFastMathMode {
FastMathNotNaN = 0x01,
FastMathNotInf = 0x02,
FastMathNSZ = 0x04,
FastMathAllowRecip = 0x08,
FastMathFast = 0x10
});
def_enum!(enum FPRoundingMode {
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3
});
def_enum!(enum LinkageType {
Export = 0,
Import = 1
});
def_enum!(enum AccessQualifier {
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2
});
def_enum!(enum FuncParamAttr {
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7
});
def_enum!(enum Decoration {
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44
});
def_enum!(enum BuiltIn {
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43
});
def_bitset!(SelectionControl {
SelCtlFlatten = 0x01,
SelCtlDontFlatten = 0x02
});
def_bitset!(LoopControl {
LoopCtlUnroll = 0x01,
LoopCtlDontUnroll = 0x02
});
def_bitset!(FunctionControl {
FnCtlInline = 0x01,
FnCtlDontInline = 0x02,
FnCtlPure = 0x04,
FnCtlConst = 0x08
});
def_bitset!(MemoryOrdering {
MemOrdAcquire = 0x002,
MemOrdRelease = 0x004,
MemOrdAcquireRelease = 0x008,
MemOrdSequentiallyConsistent = 0x010,
MemOrdUniformMemory = 0x040,
MemOrdSubgroupMemory = 0x080,
MemOrdWorkgroupMemory = 0x100,
MemOrdCrossWorkgroupMemory = 0x200,
MemOrdAtomicCounterMemory = 0x400,
MemOrdImageMemory = 0x800
});
def_bitset!(MemoryAccess {
MemAccVolatile = 0x01,
MemAccAligned = 0x02,
MemAccNontemporal = 0x04
});
def_enum!(enum Scope {
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4
});
def_enum!(enum GroupOperation {
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2
});
def_enum!(enum KernelEnqueueFlags {
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2
});
def_bitset!(KernelProfilingInfo {
ProfInfoCmdExecTime = 0x01
});
def_enum!(enum Capability {
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57
});
def_enum!(enum Op : u16 {
Nop = 0,
Undef = 1,
SourceContinued = 2,
Source = 3,
SourceExtension = 4,
Name = 5,
MemberName = 6,
String = 7,
Line = 8,
Extension = 10,
ExtInstImport = 11,
ExtInst = 12,
MemoryModel = 14,
EntryPoint = 15,
ExecutionMode = 16,
Capability = 17,
TypeVoid = 19,
TypeBool = 20,
TypeInt = 21,
TypeFloat = 22,
TypeVector = 23,
TypeMatrix = 24,
TypeImage = 25,
TypeSampler = 26,
TypeSampledImage = 27,
TypeArray = 28,
TypeRuntimeArray = 29,
TypeStruct = 30,
TypeOpaque = 31,
TypePointer = 32,
TypeFunction = 33,
TypeEvent = 34,
TypeDeviceEvent = 35,
TypeReserveId = 36,
TypeQueue = 37,
TypePipe = 38,
TypeForwardPointer = 39,
ConstantTrue = 41,
ConstantFalse = 42,
Constant = 43,
ConstantComposite = 44,
ConstantSampler = 45,
ConstantNull = 46,
SpecConstantTrue = 48,
SpecConstantFalse = 49,
SpecConstant = 50,
SpecConstantComposite = 51,
SpecConstantOp = 52,
Function = 54,
FunctionParameter = 55,
FunctionEnd = 56,
FunctionCall = 57,
Variable = 59,
ImageTexelPointer = 60,
Load = 61,
Store = 62,
CopyMemory = 63,
CopyMemorySized = 64,
AccessChain = 65,
InBoundsAccessChain = 66,
PtrAccessChain = 67,
ArrayLength = 68,
GenericPtrMemSemantics = 69,
InBoundsPtrAccessChain = 70,
Decorate = 71,
MemberDecorate = 72,
DecorationGroup = 73,
GroupDecorate = 74,
GroupMemberDecorate = 75,
VectorExtractDynamic = 77,
VectorInsertDynamic = 78,
VectorShuffle = 79,
CompositeConstruct = 80,
CompositeExtract = 81,
CompositeInsert = 82,
CopyObject = 83,
Transpose = 84,
SampledImage = 86,
ImageSampleImplicitLod = 87,
ImageSampleExplicitLod = 88,
ImageSampleDrefImplicitLod = 89,
ImageSampleDrefExplicitLod = 90,
ImageSampleProjImplicitLod = 91,
ImageSampleProjExplicitLod = 92,
ImageSampleProjDrefImplicitLod = 93,
ImageSampleProjDrefExplicitLod = 94,
ImageFetch = 95,
ImageGather = 96,
ImageDrefGather = 97,
ImageRead = 98,
ImageWrite = 99,
Image = 100,
ImageQueryFormat = 101,
ImageQueryOrder = 102,
ImageQuerySizeLod = 103,
ImageQuerySize = 104,
ImageQueryLod = 105,
ImageQueryLevels = 106,
ImageQuerySamples = 107,
ConvertFToU = 109,
ConvertFToS = 110,
ConvertSToF = 111,
ConvertUToF = 112,
UConvert = 113,
SConvert = 114,
FConvert = 115,
QuantizeToF16 = 116,
ConvertPtrToU = 117,
SatConvertSToU = 118,
SatConvertUToS = 119,
ConvertUToPtr = 120,
PtrCastToGeneric = 121,
GenericCastToPtr = 122,
GenericCastToPtrExplicit = 123,
Bitcast = 124,
SNegate = 126,
FNegate = 127,
IAdd = 128,
FAdd = 129,
ISub = 130,
FSub = 131,
IMul = 132,
FMul = 133,
UDiv = 134,
SDiv = 135,
FDiv = 136,
UMod = 137,
SRem = 138,
SMod = 139,
FRem = 140,
FMod = 141,
VectorTimesScalar = 142,
MatrixTimesScalar = 143,
VectorTimesMatrix = 144,
MatrixTimesVector = 145,
MatrixTimesMatrix = 146,
OuterProduct = 147,
Dot = 148,
IAddCarry = 149,
ISubBorrow = 150,
UMulExtended = 151,
SMulExtended = 152,
Any = 154,
All = 155,
IsNan = 156,
IsInf = 157,
IsFinite = 158,
IsNormal = 159,
SignBitSet = 160,
LessOrGreater = 161,
Ordered = 162,
Unordered = 163,
LogicalEqual = 164,
LogicalNotEqual = 165,
LogicalOr = 166,
LogicalAnd = 167,
LogicalNot = 168,
Select = 169,
IEqual = 170,
INotEqual = 171,
UGreaterThan = 172,
SGreaterThan = 173,
UGreaterThanEqual = 174,
SGreaterThanEqual = 175,
ULessThan = 176,
SLessThan = 177,
ULessThanEqual = 178,
SLessThanEqual = 179,
FOrdEqual = 180,
FUnordEqual = 181,
FOrdNotEqual = 182,
FUnordNotEqual = 183,
FOrdLessThan = 184,
FUnordLessThan = 185,
FOrdGreaterThan = 186,
FUnordGreaterThan = 187,
FOrdLessThanEqual = 188,
FUnordLessThanEqual = 189,
FOrdGreaterThanEqual = 190,
FUnordGreaterThanEqual = 191,
ShiftRightLogical = 194,
ShiftRightArithmetic = 195,
ShiftLeftLogical = 196,
BitwiseOr = 197,
BitwiseXor = 198,
BitwiseAnd = 199,
Not = 200,
BitFieldInsert = 201,
BitFieldSExtract = 202,
BitFieldUExtract = 203,
BitReverse = 204,
BitCount = 205,
DPdx = 207,
DPdy = 208,
Fwidth = 209,
DPdxFine = 210,
DPdyFine = 211,
FwidthFine = 212,
DPdxCoarse = 213,
DPdyCoarse = 214,
FwidthCoarse = 215,
EmitVertex = 218,
EndPrimitive = 219,
EmitStreamVertex = 220,
EndStreamPrimitive = 221,
ControlBarrier = 224,
MemoryBarrier = 225,
AtomicLoad = 227,
AtomicStore = 228,
AtomicExchange = 229,
AtomicCompareExchange = 230,
AtomicCompareExchangeWeak = 231,
AtomicIIncrement = 232,
AtomicIDecrement = 233,
AtomicIAdd =
|
fmt
|
identifier_name
|
desc.rs
|
}
}
impl Id {
pub fn is_valid(self) -> bool {
self.0!= 0
}
pub fn to_type_id(self) -> TypeId {
TypeId(self.0)
}
pub fn to_value_id(self) -> ValueId {
ValueId(self.0)
}
pub fn to_result_id(self) -> ResultId {
ResultId(self.0)
}
}
impl TypeId {
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl ValueId {
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl ResultId {
pub fn to_type_id(self) -> TypeId {
TypeId(self.0)
}
pub fn to_value_id(self) -> ValueId {
ValueId(self.0)
}
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Id({})", self.0)
}
}
impl fmt::Debug for ResultId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Result({})", self.0)
}
}
impl fmt::Debug for TypeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Type({})", self.0)
}
}
impl fmt::Debug for ValueId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Value({})", self.0)
}
}
macro_rules! def_enum {
(enum $en:ident { $($name:ident = $code:expr),+ }) => (
def_enum!(enum $en : u32 { $($name = $code),+ });
);
(enum $en:ident : $repr:ident { $($name:ident = $code:expr),+ }) => (
#[repr($repr)]
#[derive(Copy, Clone, Debug, PartialEq, Hash)]
pub enum $en {
$($name = $code,)+
}
impl $en {
pub fn from(val: $repr) -> Option<$en> {
match val {
$($code => Some($en::$name),)+
_ => None
}
}
}
)
}
macro_rules! def_bitset {
($setname:ident { $($name:ident = $code:expr),+ }) => (
#[derive(Copy, Clone, PartialEq, Hash)]
pub struct $setname(u32);
impl $setname {
#[inline]
pub fn empty() -> $setname {
$setname(0)
}
#[inline]
pub fn all() -> $setname {
$setname($($code)|+)
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0 == 0
}
#[inline]
pub fn contains(&self, val: $setname) -> bool {
let x = self.0 & val.0;
x!= 0
}
#[inline]
pub fn bits(&self) -> u32 {
self.0
}
#[inline]
pub fn insert(&mut self, val: $setname) {
self.0 |= val.0;
}
#[inline]
pub fn count(&self) -> u32 {
self.0.count_ones()
}
}
impl From<u32> for $setname {
#[inline]
fn from(val: u32) -> $setname {
$setname(val)
}
}
impl fmt::Debug for $setname {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(concat!(stringify!($setname), "{")));
if!self.is_empty() {
let mut _first = true;
$(if self.contains($name) {
if!_first {
try!(f.write_str(" | "));
}
try!(f.write_str(stringify!($name)));
_first = false;
})+
}
f.write_str("}")
}
}
$(pub const $name : $setname = $setname($code);)+
);
}
def_enum!(enum SrcLang {
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCl_CPP = 4
});
def_enum!(enum ExecutionModel {
Vertex = 0,
TesselationControl = 1,
TesselationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6
});
def_enum!(enum AddressingModel {
Logical = 0,
Physical32 = 1,
Physical64 = 2
});
def_enum!(enum MemoryModel {
Simple = 0,
GLSL450 = 1,
OpenCL = 2
});
def_enum!(enum ExecutionMode {
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
IsoLines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31
});
def_enum!(enum StorageClass {
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11
});
def_enum!(enum Dim {
_1D = 0,
_2D = 1,
_3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6
});
def_enum!(enum SamplerAddressingMode {
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4
});
def_enum!(enum SamplerFilterMode {
Nearest = 0,
Linear = 1
});
def_enum!(enum ImageFormat {
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39
});
def_enum!(enum ImageChannelOrder {
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18
});
def_enum!(enum ImageChannelDataType {
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16
});
def_bitset!(ImageOperands {
ImgOpBias = 0x01,
ImgOpLod = 0x02,
ImgOpGrad = 0x04,
ImgOpConstOffset = 0x08,
ImgOpOffset = 0x10,
ImgOpConstOffsets = 0x20,
ImgOpSample = 0x40,
ImgOpMinLod = 0x80
});
def_bitset!(FPFastMathMode {
FastMathNotNaN = 0x01,
FastMathNotInf = 0x02,
FastMathNSZ = 0x04,
FastMathAllowRecip = 0x08,
FastMathFast = 0x10
});
def_enum!(enum FPRoundingMode {
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3
});
def_enum!(enum LinkageType {
Export = 0,
Import = 1
});
def_enum!(enum AccessQualifier {
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2
});
def_enum!(enum FuncParamAttr {
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7
});
def_enum!(enum Decoration {
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44
});
def_enum!(enum BuiltIn {
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43
});
def_bitset!(SelectionControl {
SelCtlFlatten = 0x01,
SelCtlDontFlatten = 0x02
});
def_bitset!(LoopControl {
LoopCtlUnroll = 0x01,
LoopCtlDontUnroll = 0x02
});
def_bitset!(FunctionControl {
FnCtlInline = 0x01,
FnCtlDontInline = 0x02,
FnCtlPure = 0x04,
FnCtlConst = 0x08
});
def_bitset!(MemoryOrdering {
MemOrdAcquire = 0x002,
MemOrdRelease = 0x004,
MemOrdAcquireRelease = 0x008,
MemOrdSequentiallyConsistent = 0x010,
MemOrdUniformMemory = 0x040,
MemOrdSubgroupMemory = 0x080,
MemOrdWorkgroupMemory = 0x100,
MemOrdCrossWorkgroupMemory = 0x200,
MemOrdAtomicCounterMemory = 0x400,
MemOrdImageMemory = 0x800
});
def_bitset!(MemoryAccess {
MemAccVolatile = 0x01,
MemAccAligned = 0x02,
MemAccNontemporal = 0x04
});
def_enum!(enum Scope {
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4
});
def_enum!(enum GroupOperation {
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2
});
def_enum!(enum KernelEnqueueFlags {
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2
});
def_bitset!(KernelProfilingInfo {
ProfInfoCmdExecTime = 0x01
});
def_enum!(enum Capability {
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57
});
def_enum!(enum Op : u16 {
Nop = 0,
Undef = 1,
SourceContinued = 2,
Source = 3,
SourceExtension = 4,
Name = 5,
MemberName = 6,
String = 7,
Line = 8,
Extension = 10,
ExtInstImport = 11,
ExtInst = 12,
MemoryModel = 14,
EntryPoint = 15,
ExecutionMode = 16,
Capability = 17,
TypeVoid = 19,
TypeBool = 20,
TypeInt = 21,
TypeFloat = 22,
TypeVector = 23,
TypeMatrix = 24,
TypeImage = 25,
TypeSampler = 26,
TypeSampledImage = 27,
TypeArray = 28,
TypeRuntimeArray = 29,
TypeStruct = 30,
TypeOpaque = 31,
TypePointer = 32,
TypeFunction = 33,
TypeEvent = 34,
TypeDeviceEvent = 35,
TypeReserveId = 36,
TypeQueue = 37,
TypePipe = 38,
TypeForwardPointer = 39,
ConstantTrue = 41,
ConstantFalse = 42,
Constant = 43,
ConstantComposite = 44,
ConstantSampler = 45,
ConstantNull = 46,
SpecConstantTrue = 48,
SpecConstantFalse = 49,
SpecConstant = 50,
SpecConstantComposite = 51,
SpecConstantOp = 52,
Function = 54,
FunctionParameter = 55,
FunctionEnd = 56,
FunctionCall = 57,
Variable = 59,
ImageTexelPointer = 60,
Load = 61,
Store = 62,
CopyMemory = 63,
CopyMemorySized = 64,
AccessChain = 65,
InBoundsAccessChain = 66,
PtrAccessChain = 67,
ArrayLength = 68,
GenericPtrMemSemantics = 69,
InBoundsPtrAccessChain = 70,
Decorate = 71,
MemberDecorate = 72,
DecorationGroup = 73,
GroupDecorate = 74,
GroupMemberDecorate = 75,
|
CompositeExtract = 81,
CompositeInsert = 82,
CopyObject = 83,
Transpose = 84,
SampledImage = 86,
ImageSampleImplicitLod = 87,
ImageSampleExplicitLod = 88,
ImageSampleDrefImplicitLod = 89,
ImageSampleDrefExplicitLod = 90,
ImageSampleProjImplicitLod = 91,
ImageSampleProjExplicitLod = 92,
ImageSampleProjDrefImplicitLod = 93,
ImageSampleProjDrefExplicitLod = 94,
ImageFetch = 95,
ImageGather = 96,
ImageDrefGather = 97,
ImageRead = 98,
ImageWrite = 99,
Image = 100,
ImageQueryFormat = 101,
ImageQueryOrder = 102,
ImageQuerySizeLod = 103,
ImageQuerySize = 104,
ImageQueryLod = 105,
ImageQueryLevels = 106,
ImageQuerySamples = 107,
ConvertFToU = 109,
ConvertFToS = 110,
ConvertSToF = 111,
ConvertUToF = 112,
UConvert = 113,
SConvert = 114,
FConvert = 115,
QuantizeToF16 = 116,
ConvertPtrToU = 117,
SatConvertSToU = 118,
SatConvertUToS = 119,
ConvertUToPtr = 120,
PtrCastToGeneric = 121,
GenericCastToPtr = 122,
GenericCastToPtrExplicit = 123,
Bitcast = 124,
SNegate = 126,
FNegate = 127,
IAdd = 128,
FAdd = 129,
ISub = 130,
FSub = 131,
IMul = 132,
FMul = 133,
UDiv = 134,
SDiv = 135,
FDiv = 136,
UMod = 137,
SRem = 138,
SMod = 139,
FRem = 140,
FMod = 141,
VectorTimesScalar = 142,
MatrixTimesScalar = 143,
VectorTimesMatrix = 144,
MatrixTimesVector = 145,
MatrixTimesMatrix = 146,
OuterProduct = 147,
Dot = 148,
IAddCarry = 149,
ISubBorrow = 150,
UMulExtended = 151,
SMulExtended = 152,
Any = 154,
All = 155,
IsNan = 156,
IsInf = 157,
IsFinite = 158,
IsNormal = 159,
SignBitSet = 160,
LessOrGreater = 161,
Ordered = 162,
Unordered = 163,
LogicalEqual = 164,
LogicalNotEqual = 165,
LogicalOr = 166,
LogicalAnd = 167,
LogicalNot = 168,
Select = 169,
IEqual = 170,
INotEqual = 171,
UGreaterThan = 172,
SGreaterThan = 173,
UGreaterThanEqual = 174,
SGreaterThanEqual = 175,
ULessThan = 176,
SLessThan = 177,
ULessThanEqual = 178,
SLessThanEqual = 179,
FOrdEqual = 180,
FUnordEqual = 181,
FOrdNotEqual = 182,
FUnordNotEqual = 183,
FOrdLessThan = 184,
FUnordLessThan = 185,
FOrdGreaterThan = 186,
FUnordGreaterThan = 187,
FOrdLessThanEqual = 188,
FUnordLessThanEqual = 189,
FOrdGreaterThanEqual = 190,
FUnordGreaterThanEqual = 191,
ShiftRightLogical = 194,
ShiftRightArithmetic = 195,
ShiftLeftLogical = 196,
BitwiseOr = 197,
BitwiseXor = 198,
BitwiseAnd = 199,
Not = 200,
BitFieldInsert = 201,
BitFieldSExtract = 202,
BitFieldUExtract = 203,
BitReverse = 204,
BitCount = 205,
DPdx = 207,
DPdy = 208,
Fwidth = 209,
DPdxFine = 210,
DPdyFine = 211,
FwidthFine = 212,
DPdxCoarse = 213,
DPdyCoarse = 214,
FwidthCoarse = 215,
EmitVertex = 218,
EndPrimitive = 219,
EmitStreamVertex = 220,
EndStreamPrimitive = 221,
ControlBarrier = 224,
MemoryBarrier = 225,
AtomicLoad = 227,
AtomicStore = 228,
AtomicExchange = 229,
AtomicCompareExchange = 230,
AtomicCompareExchangeWeak = 231,
AtomicIIncrement = 232,
AtomicIDecrement = 233,
AtomicIAdd = 234,
|
VectorExtractDynamic = 77,
VectorInsertDynamic = 78,
VectorShuffle = 79,
CompositeConstruct = 80,
|
random_line_split
|
desc.rs
|
}
}
impl Id {
pub fn is_valid(self) -> bool {
self.0!= 0
}
pub fn to_type_id(self) -> TypeId {
TypeId(self.0)
}
pub fn to_value_id(self) -> ValueId {
ValueId(self.0)
}
pub fn to_result_id(self) -> ResultId {
ResultId(self.0)
}
}
impl TypeId {
pub fn is_valid(self) -> bool
|
}
impl ValueId {
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl ResultId {
pub fn to_type_id(self) -> TypeId {
TypeId(self.0)
}
pub fn to_value_id(self) -> ValueId {
ValueId(self.0)
}
pub fn is_valid(self) -> bool {
self.0!= 0
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Id({})", self.0)
}
}
impl fmt::Debug for ResultId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Result({})", self.0)
}
}
impl fmt::Debug for TypeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Type({})", self.0)
}
}
impl fmt::Debug for ValueId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Value({})", self.0)
}
}
macro_rules! def_enum {
(enum $en:ident { $($name:ident = $code:expr),+ }) => (
def_enum!(enum $en : u32 { $($name = $code),+ });
);
(enum $en:ident : $repr:ident { $($name:ident = $code:expr),+ }) => (
#[repr($repr)]
#[derive(Copy, Clone, Debug, PartialEq, Hash)]
pub enum $en {
$($name = $code,)+
}
impl $en {
pub fn from(val: $repr) -> Option<$en> {
match val {
$($code => Some($en::$name),)+
_ => None
}
}
}
)
}
macro_rules! def_bitset {
($setname:ident { $($name:ident = $code:expr),+ }) => (
#[derive(Copy, Clone, PartialEq, Hash)]
pub struct $setname(u32);
impl $setname {
#[inline]
pub fn empty() -> $setname {
$setname(0)
}
#[inline]
pub fn all() -> $setname {
$setname($($code)|+)
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0 == 0
}
#[inline]
pub fn contains(&self, val: $setname) -> bool {
let x = self.0 & val.0;
x!= 0
}
#[inline]
pub fn bits(&self) -> u32 {
self.0
}
#[inline]
pub fn insert(&mut self, val: $setname) {
self.0 |= val.0;
}
#[inline]
pub fn count(&self) -> u32 {
self.0.count_ones()
}
}
impl From<u32> for $setname {
#[inline]
fn from(val: u32) -> $setname {
$setname(val)
}
}
impl fmt::Debug for $setname {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(concat!(stringify!($setname), "{")));
if!self.is_empty() {
let mut _first = true;
$(if self.contains($name) {
if!_first {
try!(f.write_str(" | "));
}
try!(f.write_str(stringify!($name)));
_first = false;
})+
}
f.write_str("}")
}
}
$(pub const $name : $setname = $setname($code);)+
);
}
def_enum!(enum SrcLang {
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCl_CPP = 4
});
def_enum!(enum ExecutionModel {
Vertex = 0,
TesselationControl = 1,
TesselationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6
});
def_enum!(enum AddressingModel {
Logical = 0,
Physical32 = 1,
Physical64 = 2
});
def_enum!(enum MemoryModel {
Simple = 0,
GLSL450 = 1,
OpenCL = 2
});
def_enum!(enum ExecutionMode {
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
IsoLines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31
});
def_enum!(enum StorageClass {
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11
});
def_enum!(enum Dim {
_1D = 0,
_2D = 1,
_3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6
});
def_enum!(enum SamplerAddressingMode {
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4
});
def_enum!(enum SamplerFilterMode {
Nearest = 0,
Linear = 1
});
def_enum!(enum ImageFormat {
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39
});
def_enum!(enum ImageChannelOrder {
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18
});
def_enum!(enum ImageChannelDataType {
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16
});
def_bitset!(ImageOperands {
ImgOpBias = 0x01,
ImgOpLod = 0x02,
ImgOpGrad = 0x04,
ImgOpConstOffset = 0x08,
ImgOpOffset = 0x10,
ImgOpConstOffsets = 0x20,
ImgOpSample = 0x40,
ImgOpMinLod = 0x80
});
def_bitset!(FPFastMathMode {
FastMathNotNaN = 0x01,
FastMathNotInf = 0x02,
FastMathNSZ = 0x04,
FastMathAllowRecip = 0x08,
FastMathFast = 0x10
});
def_enum!(enum FPRoundingMode {
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3
});
def_enum!(enum LinkageType {
Export = 0,
Import = 1
});
def_enum!(enum AccessQualifier {
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2
});
def_enum!(enum FuncParamAttr {
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7
});
def_enum!(enum Decoration {
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44
});
def_enum!(enum BuiltIn {
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43
});
def_bitset!(SelectionControl {
SelCtlFlatten = 0x01,
SelCtlDontFlatten = 0x02
});
def_bitset!(LoopControl {
LoopCtlUnroll = 0x01,
LoopCtlDontUnroll = 0x02
});
def_bitset!(FunctionControl {
FnCtlInline = 0x01,
FnCtlDontInline = 0x02,
FnCtlPure = 0x04,
FnCtlConst = 0x08
});
def_bitset!(MemoryOrdering {
MemOrdAcquire = 0x002,
MemOrdRelease = 0x004,
MemOrdAcquireRelease = 0x008,
MemOrdSequentiallyConsistent = 0x010,
MemOrdUniformMemory = 0x040,
MemOrdSubgroupMemory = 0x080,
MemOrdWorkgroupMemory = 0x100,
MemOrdCrossWorkgroupMemory = 0x200,
MemOrdAtomicCounterMemory = 0x400,
MemOrdImageMemory = 0x800
});
def_bitset!(MemoryAccess {
MemAccVolatile = 0x01,
MemAccAligned = 0x02,
MemAccNontemporal = 0x04
});
def_enum!(enum Scope {
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4
});
def_enum!(enum GroupOperation {
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2
});
def_enum!(enum KernelEnqueueFlags {
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2
});
def_bitset!(KernelProfilingInfo {
ProfInfoCmdExecTime = 0x01
});
def_enum!(enum Capability {
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57
});
def_enum!(enum Op : u16 {
Nop = 0,
Undef = 1,
SourceContinued = 2,
Source = 3,
SourceExtension = 4,
Name = 5,
MemberName = 6,
String = 7,
Line = 8,
Extension = 10,
ExtInstImport = 11,
ExtInst = 12,
MemoryModel = 14,
EntryPoint = 15,
ExecutionMode = 16,
Capability = 17,
TypeVoid = 19,
TypeBool = 20,
TypeInt = 21,
TypeFloat = 22,
TypeVector = 23,
TypeMatrix = 24,
TypeImage = 25,
TypeSampler = 26,
TypeSampledImage = 27,
TypeArray = 28,
TypeRuntimeArray = 29,
TypeStruct = 30,
TypeOpaque = 31,
TypePointer = 32,
TypeFunction = 33,
TypeEvent = 34,
TypeDeviceEvent = 35,
TypeReserveId = 36,
TypeQueue = 37,
TypePipe = 38,
TypeForwardPointer = 39,
ConstantTrue = 41,
ConstantFalse = 42,
Constant = 43,
ConstantComposite = 44,
ConstantSampler = 45,
ConstantNull = 46,
SpecConstantTrue = 48,
SpecConstantFalse = 49,
SpecConstant = 50,
SpecConstantComposite = 51,
SpecConstantOp = 52,
Function = 54,
FunctionParameter = 55,
FunctionEnd = 56,
FunctionCall = 57,
Variable = 59,
ImageTexelPointer = 60,
Load = 61,
Store = 62,
CopyMemory = 63,
CopyMemorySized = 64,
AccessChain = 65,
InBoundsAccessChain = 66,
PtrAccessChain = 67,
ArrayLength = 68,
GenericPtrMemSemantics = 69,
InBoundsPtrAccessChain = 70,
Decorate = 71,
MemberDecorate = 72,
DecorationGroup = 73,
GroupDecorate = 74,
GroupMemberDecorate = 75,
VectorExtractDynamic = 77,
VectorInsertDynamic = 78,
VectorShuffle = 79,
CompositeConstruct = 80,
CompositeExtract = 81,
CompositeInsert = 82,
CopyObject = 83,
Transpose = 84,
SampledImage = 86,
ImageSampleImplicitLod = 87,
ImageSampleExplicitLod = 88,
ImageSampleDrefImplicitLod = 89,
ImageSampleDrefExplicitLod = 90,
ImageSampleProjImplicitLod = 91,
ImageSampleProjExplicitLod = 92,
ImageSampleProjDrefImplicitLod = 93,
ImageSampleProjDrefExplicitLod = 94,
ImageFetch = 95,
ImageGather = 96,
ImageDrefGather = 97,
ImageRead = 98,
ImageWrite = 99,
Image = 100,
ImageQueryFormat = 101,
ImageQueryOrder = 102,
ImageQuerySizeLod = 103,
ImageQuerySize = 104,
ImageQueryLod = 105,
ImageQueryLevels = 106,
ImageQuerySamples = 107,
ConvertFToU = 109,
ConvertFToS = 110,
ConvertSToF = 111,
ConvertUToF = 112,
UConvert = 113,
SConvert = 114,
FConvert = 115,
QuantizeToF16 = 116,
ConvertPtrToU = 117,
SatConvertSToU = 118,
SatConvertUToS = 119,
ConvertUToPtr = 120,
PtrCastToGeneric = 121,
GenericCastToPtr = 122,
GenericCastToPtrExplicit = 123,
Bitcast = 124,
SNegate = 126,
FNegate = 127,
IAdd = 128,
FAdd = 129,
ISub = 130,
FSub = 131,
IMul = 132,
FMul = 133,
UDiv = 134,
SDiv = 135,
FDiv = 136,
UMod = 137,
SRem = 138,
SMod = 139,
FRem = 140,
FMod = 141,
VectorTimesScalar = 142,
MatrixTimesScalar = 143,
VectorTimesMatrix = 144,
MatrixTimesVector = 145,
MatrixTimesMatrix = 146,
OuterProduct = 147,
Dot = 148,
IAddCarry = 149,
ISubBorrow = 150,
UMulExtended = 151,
SMulExtended = 152,
Any = 154,
All = 155,
IsNan = 156,
IsInf = 157,
IsFinite = 158,
IsNormal = 159,
SignBitSet = 160,
LessOrGreater = 161,
Ordered = 162,
Unordered = 163,
LogicalEqual = 164,
LogicalNotEqual = 165,
LogicalOr = 166,
LogicalAnd = 167,
LogicalNot = 168,
Select = 169,
IEqual = 170,
INotEqual = 171,
UGreaterThan = 172,
SGreaterThan = 173,
UGreaterThanEqual = 174,
SGreaterThanEqual = 175,
ULessThan = 176,
SLessThan = 177,
ULessThanEqual = 178,
SLessThanEqual = 179,
FOrdEqual = 180,
FUnordEqual = 181,
FOrdNotEqual = 182,
FUnordNotEqual = 183,
FOrdLessThan = 184,
FUnordLessThan = 185,
FOrdGreaterThan = 186,
FUnordGreaterThan = 187,
FOrdLessThanEqual = 188,
FUnordLessThanEqual = 189,
FOrdGreaterThanEqual = 190,
FUnordGreaterThanEqual = 191,
ShiftRightLogical = 194,
ShiftRightArithmetic = 195,
ShiftLeftLogical = 196,
BitwiseOr = 197,
BitwiseXor = 198,
BitwiseAnd = 199,
Not = 200,
BitFieldInsert = 201,
BitFieldSExtract = 202,
BitFieldUExtract = 203,
BitReverse = 204,
BitCount = 205,
DPdx = 207,
DPdy = 208,
Fwidth = 209,
DPdxFine = 210,
DPdyFine = 211,
FwidthFine = 212,
DPdxCoarse = 213,
DPdyCoarse = 214,
FwidthCoarse = 215,
EmitVertex = 218,
EndPrimitive = 219,
EmitStreamVertex = 220,
EndStreamPrimitive = 221,
ControlBarrier = 224,
MemoryBarrier = 225,
AtomicLoad = 227,
AtomicStore = 228,
AtomicExchange = 229,
AtomicCompareExchange = 230,
AtomicCompareExchangeWeak = 231,
AtomicIIncrement = 232,
AtomicIDecrement = 233,
AtomicIAdd =
|
{
self.0 != 0
}
|
identifier_body
|
span_encoding.rs
|
// Copyright 2017 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.
// Spans are encoded using 1-bit tag and 2 different encoding formats (one for each tag value).
// One format is used for keeping span data inline,
// another contains index into an out-of-line span interner.
// The encoding format for inline spans were obtained by optimizing over crates in rustc/libstd.
// See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28
use GLOBALS;
use {BytePos, SpanData};
use hygiene::SyntaxContext;
use rustc_data_structures::fx::FxHashMap;
use std::hash::{Hash, Hasher};
/// A compressed span.
/// Contains either fields of `SpanData` inline if they are small, or index into span interner.
/// The primary goal of `Span` is to be as small as possible and fit into other structures
/// (that's why it uses `packed` as well). Decoding speed is the second priority.
/// See `SpanData` for the info on span fields in decoded representation.
#[repr(packed)]
pub struct Span(u32);
impl Copy for Span {}
impl Clone for Span {
#[inline]
fn clone(&self) -> Span {
*self
}
}
impl PartialEq for Span {
#[inline]
fn eq(&self, other: &Span) -> bool {
let a = self.0;
let b = other.0;
a == b
}
}
impl Eq for Span {}
impl Hash for Span {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
let a = self.0;
a.hash(state)
}
}
/// Dummy span, both position and length are zero, syntax context is zero as well.
/// This span is kept inline and encoded with format 0.
pub const DUMMY_SP: Span = Span(0);
impl Span {
#[inline]
pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
encode(&match lo <= hi {
true => SpanData { lo, hi, ctxt },
false => SpanData { lo: hi, hi: lo, ctxt },
})
}
#[inline]
pub fn data(self) -> SpanData {
decode(self)
}
}
// Tags
const TAG_INLINE: u32 = 0;
const TAG_INTERNED: u32 = 1;
const TAG_MASK: u32 = 1;
// Fields indexes
const BASE_INDEX: usize = 0;
const LEN_INDEX: usize = 1;
const CTXT_INDEX: usize = 2;
// Tag = 0, inline format.
// -------------------------------------------------------------
// | base 31:8 | len 7:1 | ctxt (currently 0 bits) | tag 0:0 |
// -------------------------------------------------------------
// Since there are zero bits for ctxt, only SpanData with a 0 SyntaxContext
// can be inline.
const INLINE_SIZES: [u32; 3] = [24, 7, 0];
const INLINE_OFFSETS: [u32; 3] = [8, 1, 1];
// Tag = 1, interned format.
// ------------------------
// | index 31:1 | tag 0:0 |
// ------------------------
const INTERNED_INDEX_SIZE: u32 = 31;
const INTERNED_INDEX_OFFSET: u32 = 1;
#[inline]
fn encode(sd: &SpanData) -> Span {
let (base, len, ctxt) = (sd.lo.0, sd.hi.0 - sd.lo.0, sd.ctxt.as_u32());
let val = if (base >> INLINE_SIZES[BASE_INDEX]) == 0 &&
(len >> INLINE_SIZES[LEN_INDEX]) == 0 &&
(ctxt >> INLINE_SIZES[CTXT_INDEX]) == 0 {
(base << INLINE_OFFSETS[BASE_INDEX]) | (len << INLINE_OFFSETS[LEN_INDEX]) |
(ctxt << INLINE_OFFSETS[CTXT_INDEX]) | TAG_INLINE
} else {
let index = with_span_interner(|interner| interner.intern(sd));
(index << INTERNED_INDEX_OFFSET) | TAG_INTERNED
};
Span(val)
}
#[inline]
fn
|
(span: Span) -> SpanData {
let val = span.0;
// Extract a field at position `pos` having size `size`.
let extract = |pos: u32, size: u32| {
let mask = ((!0u32) as u64 >> (32 - size)) as u32; // Can't shift u32 by 32
(val >> pos) & mask
};
let (base, len, ctxt) = if val & TAG_MASK == TAG_INLINE {(
extract(INLINE_OFFSETS[BASE_INDEX], INLINE_SIZES[BASE_INDEX]),
extract(INLINE_OFFSETS[LEN_INDEX], INLINE_SIZES[LEN_INDEX]),
extract(INLINE_OFFSETS[CTXT_INDEX], INLINE_SIZES[CTXT_INDEX]),
)} else {
let index = extract(INTERNED_INDEX_OFFSET, INTERNED_INDEX_SIZE);
return with_span_interner(|interner| *interner.get(index));
};
SpanData { lo: BytePos(base), hi: BytePos(base + len), ctxt: SyntaxContext::from_u32(ctxt) }
}
#[derive(Default)]
pub struct SpanInterner {
spans: FxHashMap<SpanData, u32>,
span_data: Vec<SpanData>,
}
impl SpanInterner {
fn intern(&mut self, span_data: &SpanData) -> u32 {
if let Some(index) = self.spans.get(span_data) {
return *index;
}
let index = self.spans.len() as u32;
self.span_data.push(*span_data);
self.spans.insert(*span_data, index);
index
}
#[inline]
fn get(&self, index: u32) -> &SpanData {
&self.span_data[index as usize]
}
}
// If an interner exists, return it. Otherwise, prepare a fresh one.
#[inline]
fn with_span_interner<T, F: FnOnce(&mut SpanInterner) -> T>(f: F) -> T {
GLOBALS.with(|globals| f(&mut *globals.span_interner.lock()))
}
|
decode
|
identifier_name
|
span_encoding.rs
|
// Copyright 2017 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.
// Spans are encoded using 1-bit tag and 2 different encoding formats (one for each tag value).
// One format is used for keeping span data inline,
// another contains index into an out-of-line span interner.
// The encoding format for inline spans were obtained by optimizing over crates in rustc/libstd.
// See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28
use GLOBALS;
use {BytePos, SpanData};
use hygiene::SyntaxContext;
use rustc_data_structures::fx::FxHashMap;
use std::hash::{Hash, Hasher};
/// A compressed span.
/// Contains either fields of `SpanData` inline if they are small, or index into span interner.
/// The primary goal of `Span` is to be as small as possible and fit into other structures
/// (that's why it uses `packed` as well). Decoding speed is the second priority.
/// See `SpanData` for the info on span fields in decoded representation.
#[repr(packed)]
pub struct Span(u32);
impl Copy for Span {}
impl Clone for Span {
#[inline]
fn clone(&self) -> Span {
*self
}
}
impl PartialEq for Span {
#[inline]
fn eq(&self, other: &Span) -> bool {
let a = self.0;
let b = other.0;
a == b
}
}
impl Eq for Span {}
impl Hash for Span {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
let a = self.0;
a.hash(state)
}
}
/// Dummy span, both position and length are zero, syntax context is zero as well.
/// This span is kept inline and encoded with format 0.
pub const DUMMY_SP: Span = Span(0);
impl Span {
#[inline]
pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
encode(&match lo <= hi {
true => SpanData { lo, hi, ctxt },
false => SpanData { lo: hi, hi: lo, ctxt },
})
}
#[inline]
pub fn data(self) -> SpanData {
decode(self)
}
}
// Tags
const TAG_INLINE: u32 = 0;
const TAG_INTERNED: u32 = 1;
const TAG_MASK: u32 = 1;
// Fields indexes
const BASE_INDEX: usize = 0;
const LEN_INDEX: usize = 1;
const CTXT_INDEX: usize = 2;
// Tag = 0, inline format.
// -------------------------------------------------------------
// | base 31:8 | len 7:1 | ctxt (currently 0 bits) | tag 0:0 |
// -------------------------------------------------------------
// Since there are zero bits for ctxt, only SpanData with a 0 SyntaxContext
// can be inline.
const INLINE_SIZES: [u32; 3] = [24, 7, 0];
const INLINE_OFFSETS: [u32; 3] = [8, 1, 1];
// Tag = 1, interned format.
// ------------------------
// | index 31:1 | tag 0:0 |
// ------------------------
const INTERNED_INDEX_SIZE: u32 = 31;
const INTERNED_INDEX_OFFSET: u32 = 1;
#[inline]
fn encode(sd: &SpanData) -> Span {
let (base, len, ctxt) = (sd.lo.0, sd.hi.0 - sd.lo.0, sd.ctxt.as_u32());
let val = if (base >> INLINE_SIZES[BASE_INDEX]) == 0 &&
(len >> INLINE_SIZES[LEN_INDEX]) == 0 &&
(ctxt >> INLINE_SIZES[CTXT_INDEX]) == 0 {
(base << INLINE_OFFSETS[BASE_INDEX]) | (len << INLINE_OFFSETS[LEN_INDEX]) |
(ctxt << INLINE_OFFSETS[CTXT_INDEX]) | TAG_INLINE
} else {
let index = with_span_interner(|interner| interner.intern(sd));
(index << INTERNED_INDEX_OFFSET) | TAG_INTERNED
};
Span(val)
}
#[inline]
fn decode(span: Span) -> SpanData {
let val = span.0;
// Extract a field at position `pos` having size `size`.
let extract = |pos: u32, size: u32| {
let mask = ((!0u32) as u64 >> (32 - size)) as u32; // Can't shift u32 by 32
(val >> pos) & mask
};
let (base, len, ctxt) = if val & TAG_MASK == TAG_INLINE {(
extract(INLINE_OFFSETS[BASE_INDEX], INLINE_SIZES[BASE_INDEX]),
extract(INLINE_OFFSETS[LEN_INDEX], INLINE_SIZES[LEN_INDEX]),
extract(INLINE_OFFSETS[CTXT_INDEX], INLINE_SIZES[CTXT_INDEX]),
)} else {
let index = extract(INTERNED_INDEX_OFFSET, INTERNED_INDEX_SIZE);
return with_span_interner(|interner| *interner.get(index));
};
SpanData { lo: BytePos(base), hi: BytePos(base + len), ctxt: SyntaxContext::from_u32(ctxt) }
}
#[derive(Default)]
pub struct SpanInterner {
spans: FxHashMap<SpanData, u32>,
span_data: Vec<SpanData>,
}
impl SpanInterner {
fn intern(&mut self, span_data: &SpanData) -> u32 {
if let Some(index) = self.spans.get(span_data) {
return *index;
}
let index = self.spans.len() as u32;
self.span_data.push(*span_data);
self.spans.insert(*span_data, index);
index
}
#[inline]
fn get(&self, index: u32) -> &SpanData
|
}
// If an interner exists, return it. Otherwise, prepare a fresh one.
#[inline]
fn with_span_interner<T, F: FnOnce(&mut SpanInterner) -> T>(f: F) -> T {
GLOBALS.with(|globals| f(&mut *globals.span_interner.lock()))
}
|
{
&self.span_data[index as usize]
}
|
identifier_body
|
span_encoding.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
// except according to those terms.
// Spans are encoded using 1-bit tag and 2 different encoding formats (one for each tag value).
// One format is used for keeping span data inline,
// another contains index into an out-of-line span interner.
// The encoding format for inline spans were obtained by optimizing over crates in rustc/libstd.
// See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28
use GLOBALS;
use {BytePos, SpanData};
use hygiene::SyntaxContext;
use rustc_data_structures::fx::FxHashMap;
use std::hash::{Hash, Hasher};
/// A compressed span.
/// Contains either fields of `SpanData` inline if they are small, or index into span interner.
/// The primary goal of `Span` is to be as small as possible and fit into other structures
/// (that's why it uses `packed` as well). Decoding speed is the second priority.
/// See `SpanData` for the info on span fields in decoded representation.
#[repr(packed)]
pub struct Span(u32);
impl Copy for Span {}
impl Clone for Span {
#[inline]
fn clone(&self) -> Span {
*self
}
}
impl PartialEq for Span {
#[inline]
fn eq(&self, other: &Span) -> bool {
let a = self.0;
let b = other.0;
a == b
}
}
impl Eq for Span {}
impl Hash for Span {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
let a = self.0;
a.hash(state)
}
}
/// Dummy span, both position and length are zero, syntax context is zero as well.
/// This span is kept inline and encoded with format 0.
pub const DUMMY_SP: Span = Span(0);
impl Span {
#[inline]
pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
encode(&match lo <= hi {
true => SpanData { lo, hi, ctxt },
false => SpanData { lo: hi, hi: lo, ctxt },
})
}
#[inline]
pub fn data(self) -> SpanData {
decode(self)
}
}
// Tags
const TAG_INLINE: u32 = 0;
const TAG_INTERNED: u32 = 1;
const TAG_MASK: u32 = 1;
// Fields indexes
const BASE_INDEX: usize = 0;
const LEN_INDEX: usize = 1;
const CTXT_INDEX: usize = 2;
// Tag = 0, inline format.
// -------------------------------------------------------------
// | base 31:8 | len 7:1 | ctxt (currently 0 bits) | tag 0:0 |
// -------------------------------------------------------------
// Since there are zero bits for ctxt, only SpanData with a 0 SyntaxContext
// can be inline.
const INLINE_SIZES: [u32; 3] = [24, 7, 0];
const INLINE_OFFSETS: [u32; 3] = [8, 1, 1];
// Tag = 1, interned format.
// ------------------------
// | index 31:1 | tag 0:0 |
// ------------------------
const INTERNED_INDEX_SIZE: u32 = 31;
const INTERNED_INDEX_OFFSET: u32 = 1;
#[inline]
fn encode(sd: &SpanData) -> Span {
let (base, len, ctxt) = (sd.lo.0, sd.hi.0 - sd.lo.0, sd.ctxt.as_u32());
let val = if (base >> INLINE_SIZES[BASE_INDEX]) == 0 &&
(len >> INLINE_SIZES[LEN_INDEX]) == 0 &&
(ctxt >> INLINE_SIZES[CTXT_INDEX]) == 0 {
(base << INLINE_OFFSETS[BASE_INDEX]) | (len << INLINE_OFFSETS[LEN_INDEX]) |
(ctxt << INLINE_OFFSETS[CTXT_INDEX]) | TAG_INLINE
} else {
let index = with_span_interner(|interner| interner.intern(sd));
(index << INTERNED_INDEX_OFFSET) | TAG_INTERNED
};
Span(val)
}
#[inline]
fn decode(span: Span) -> SpanData {
let val = span.0;
// Extract a field at position `pos` having size `size`.
let extract = |pos: u32, size: u32| {
let mask = ((!0u32) as u64 >> (32 - size)) as u32; // Can't shift u32 by 32
(val >> pos) & mask
};
let (base, len, ctxt) = if val & TAG_MASK == TAG_INLINE {(
extract(INLINE_OFFSETS[BASE_INDEX], INLINE_SIZES[BASE_INDEX]),
extract(INLINE_OFFSETS[LEN_INDEX], INLINE_SIZES[LEN_INDEX]),
extract(INLINE_OFFSETS[CTXT_INDEX], INLINE_SIZES[CTXT_INDEX]),
)} else {
let index = extract(INTERNED_INDEX_OFFSET, INTERNED_INDEX_SIZE);
return with_span_interner(|interner| *interner.get(index));
};
SpanData { lo: BytePos(base), hi: BytePos(base + len), ctxt: SyntaxContext::from_u32(ctxt) }
}
#[derive(Default)]
pub struct SpanInterner {
spans: FxHashMap<SpanData, u32>,
span_data: Vec<SpanData>,
}
impl SpanInterner {
fn intern(&mut self, span_data: &SpanData) -> u32 {
if let Some(index) = self.spans.get(span_data) {
return *index;
}
let index = self.spans.len() as u32;
self.span_data.push(*span_data);
self.spans.insert(*span_data, index);
index
}
#[inline]
fn get(&self, index: u32) -> &SpanData {
&self.span_data[index as usize]
}
}
// If an interner exists, return it. Otherwise, prepare a fresh one.
#[inline]
fn with_span_interner<T, F: FnOnce(&mut SpanInterner) -> T>(f: F) -> T {
GLOBALS.with(|globals| f(&mut *globals.span_interner.lock()))
}
|
//
// 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
|
random_line_split
|
span_encoding.rs
|
// Copyright 2017 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.
// Spans are encoded using 1-bit tag and 2 different encoding formats (one for each tag value).
// One format is used for keeping span data inline,
// another contains index into an out-of-line span interner.
// The encoding format for inline spans were obtained by optimizing over crates in rustc/libstd.
// See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28
use GLOBALS;
use {BytePos, SpanData};
use hygiene::SyntaxContext;
use rustc_data_structures::fx::FxHashMap;
use std::hash::{Hash, Hasher};
/// A compressed span.
/// Contains either fields of `SpanData` inline if they are small, or index into span interner.
/// The primary goal of `Span` is to be as small as possible and fit into other structures
/// (that's why it uses `packed` as well). Decoding speed is the second priority.
/// See `SpanData` for the info on span fields in decoded representation.
#[repr(packed)]
pub struct Span(u32);
impl Copy for Span {}
impl Clone for Span {
#[inline]
fn clone(&self) -> Span {
*self
}
}
impl PartialEq for Span {
#[inline]
fn eq(&self, other: &Span) -> bool {
let a = self.0;
let b = other.0;
a == b
}
}
impl Eq for Span {}
impl Hash for Span {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
let a = self.0;
a.hash(state)
}
}
/// Dummy span, both position and length are zero, syntax context is zero as well.
/// This span is kept inline and encoded with format 0.
pub const DUMMY_SP: Span = Span(0);
impl Span {
#[inline]
pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
encode(&match lo <= hi {
true => SpanData { lo, hi, ctxt },
false => SpanData { lo: hi, hi: lo, ctxt },
})
}
#[inline]
pub fn data(self) -> SpanData {
decode(self)
}
}
// Tags
const TAG_INLINE: u32 = 0;
const TAG_INTERNED: u32 = 1;
const TAG_MASK: u32 = 1;
// Fields indexes
const BASE_INDEX: usize = 0;
const LEN_INDEX: usize = 1;
const CTXT_INDEX: usize = 2;
// Tag = 0, inline format.
// -------------------------------------------------------------
// | base 31:8 | len 7:1 | ctxt (currently 0 bits) | tag 0:0 |
// -------------------------------------------------------------
// Since there are zero bits for ctxt, only SpanData with a 0 SyntaxContext
// can be inline.
const INLINE_SIZES: [u32; 3] = [24, 7, 0];
const INLINE_OFFSETS: [u32; 3] = [8, 1, 1];
// Tag = 1, interned format.
// ------------------------
// | index 31:1 | tag 0:0 |
// ------------------------
const INTERNED_INDEX_SIZE: u32 = 31;
const INTERNED_INDEX_OFFSET: u32 = 1;
#[inline]
fn encode(sd: &SpanData) -> Span {
let (base, len, ctxt) = (sd.lo.0, sd.hi.0 - sd.lo.0, sd.ctxt.as_u32());
let val = if (base >> INLINE_SIZES[BASE_INDEX]) == 0 &&
(len >> INLINE_SIZES[LEN_INDEX]) == 0 &&
(ctxt >> INLINE_SIZES[CTXT_INDEX]) == 0
|
else {
let index = with_span_interner(|interner| interner.intern(sd));
(index << INTERNED_INDEX_OFFSET) | TAG_INTERNED
};
Span(val)
}
#[inline]
fn decode(span: Span) -> SpanData {
let val = span.0;
// Extract a field at position `pos` having size `size`.
let extract = |pos: u32, size: u32| {
let mask = ((!0u32) as u64 >> (32 - size)) as u32; // Can't shift u32 by 32
(val >> pos) & mask
};
let (base, len, ctxt) = if val & TAG_MASK == TAG_INLINE {(
extract(INLINE_OFFSETS[BASE_INDEX], INLINE_SIZES[BASE_INDEX]),
extract(INLINE_OFFSETS[LEN_INDEX], INLINE_SIZES[LEN_INDEX]),
extract(INLINE_OFFSETS[CTXT_INDEX], INLINE_SIZES[CTXT_INDEX]),
)} else {
let index = extract(INTERNED_INDEX_OFFSET, INTERNED_INDEX_SIZE);
return with_span_interner(|interner| *interner.get(index));
};
SpanData { lo: BytePos(base), hi: BytePos(base + len), ctxt: SyntaxContext::from_u32(ctxt) }
}
#[derive(Default)]
pub struct SpanInterner {
spans: FxHashMap<SpanData, u32>,
span_data: Vec<SpanData>,
}
impl SpanInterner {
fn intern(&mut self, span_data: &SpanData) -> u32 {
if let Some(index) = self.spans.get(span_data) {
return *index;
}
let index = self.spans.len() as u32;
self.span_data.push(*span_data);
self.spans.insert(*span_data, index);
index
}
#[inline]
fn get(&self, index: u32) -> &SpanData {
&self.span_data[index as usize]
}
}
// If an interner exists, return it. Otherwise, prepare a fresh one.
#[inline]
fn with_span_interner<T, F: FnOnce(&mut SpanInterner) -> T>(f: F) -> T {
GLOBALS.with(|globals| f(&mut *globals.span_interner.lock()))
}
|
{
(base << INLINE_OFFSETS[BASE_INDEX]) | (len << INLINE_OFFSETS[LEN_INDEX]) |
(ctxt << INLINE_OFFSETS[CTXT_INDEX]) | TAG_INLINE
}
|
conditional_block
|
func_translator.rs
|
//! Stand-alone WebAssembly to Cretonne IL translator.
//!
//! This module defines the `FuncTranslator` type which can translate a single WebAssembly
//! function to Cretonne IL guided by a `FuncEnvironment` which provides information about the
//! WebAssembly module and the runtime environment.
use code_translator::translate_operator;
use cretonne::entity::EntityRef;
use cretonne::ir::{self, InstBuilder, Ebb};
use cretonne::result::{CtonResult, CtonError};
use cretonne::timing;
use cton_frontend::{FunctionBuilderContext, FunctionBuilder, Variable};
use environ::FuncEnvironment;
use state::TranslationState;
use wasmparser::{self, BinaryReader};
/// WebAssembly to Cretonne IL function translator.
///
/// A `FuncTranslator` is used to translate a binary WebAssembly function into Cretonne IL guided
/// by a `FuncEnvironment` object. A single translator instance can be reused to translate multiple
/// functions which will reduce heap allocation traffic.
pub struct FuncTranslator {
func_ctx: FunctionBuilderContext<Variable>,
state: TranslationState,
}
impl FuncTranslator {
/// Create a new translator.
pub fn new() -> Self {
Self {
func_ctx: FunctionBuilderContext::new(),
state: TranslationState::new(),
}
}
/// Translate a binary WebAssembly function.
///
/// The `code` slice contains the binary WebAssembly *function code* as it appears in the code
/// section of a WebAssembly module, not including the initial size of the function code. The
/// slice is expected to contain two parts:
///
/// - The declaration of *locals*, and
/// - The function *body* as an expression.
///
/// See [the WebAssembly specification][wasm].
///
/// [wasm]: https://webassembly.github.io/spec/binary/modules.html#code-section
///
/// The Cretonne IR function `func` should be completely empty except for the `func.signature`
/// and `func.name` fields. The signature may contain special-purpose arguments which are not
/// regarded as WebAssembly local variables. Any signature arguments marked as
/// `ArgumentPurpose::Normal` are made accessible as WebAssembly local variables.
///
pub fn translate<FE: FuncEnvironment +?Sized>(
&mut self,
code: &[u8],
func: &mut ir::Function,
environ: &mut FE,
) -> CtonResult {
self.translate_from_reader(BinaryReader::new(code), func, environ)
}
/// Translate a binary WebAssembly function from a `BinaryReader`.
pub fn translate_from_reader<FE: FuncEnvironment +?Sized>(
&mut self,
mut reader: BinaryReader,
func: &mut ir::Function,
environ: &mut FE,
) -> CtonResult {
let _tt = timing::wasm_translate_function();
dbg!(
"translate({} bytes, {}{})",
reader.bytes_remaining(),
func.name,
func.signature
);
debug_assert_eq!(func.dfg.num_ebbs(), 0, "Function must be empty");
debug_assert_eq!(func.dfg.num_insts(), 0, "Function must be empty");
// This clears the `FunctionBuilderContext`.
let mut builder = FunctionBuilder::new(func, &mut self.func_ctx);
let entry_block = builder.create_ebb();
builder.append_ebb_params_for_function_params(entry_block);
builder.switch_to_block(entry_block); // This also creates values for the arguments.
builder.seal_block(entry_block);
// Make sure the entry block is inserted in the layout before we make any callbacks to
// `environ`. The callback functions may need to insert things in the entry block.
builder.ensure_inserted_ebb();
let num_params = declare_wasm_parameters(&mut builder, entry_block);
// Set up the translation state with a single pushed control block representing the whole
// function and its return values.
let exit_block = builder.create_ebb();
builder.append_ebb_params_for_function_returns(exit_block);
self.state.initialize(&builder.func.signature, exit_block);
parse_local_decls(&mut reader, &mut builder, num_params)?;
parse_function_body(reader, &mut builder, &mut self.state, environ)?;
builder.finalize();
Ok(())
}
}
/// Declare local variables for the signature parameters that correspond to WebAssembly locals.
///
/// Return the number of local variables declared.
fn declare_wasm_parameters(builder: &mut FunctionBuilder<Variable>, entry_block: Ebb) -> usize {
let sig_len = builder.func.signature.params.len();
let mut next_local = 0;
for i in 0..sig_len {
let param_type = builder.func.signature.params[i];
// There may be additional special-purpose parameters following the normal WebAssembly
// signature parameters. For example, a `vmctx` pointer.
if param_type.purpose == ir::ArgumentPurpose::Normal {
// This is a normal WebAssembly signature parameter, so create a local for it.
let local = Variable::new(next_local);
builder.declare_var(local, param_type.value_type);
next_local += 1;
let param_value = builder.ebb_params(entry_block)[i];
builder.def_var(local, param_value);
}
}
next_local
}
/// Parse the local variable declarations that precede the function body.
///
/// Declare local variables, starting from `num_params`.
fn parse_local_decls(
reader: &mut BinaryReader,
builder: &mut FunctionBuilder<Variable>,
num_params: usize,
) -> CtonResult {
let mut next_local = num_params;
let local_count = reader.read_local_count().map_err(
|_| CtonError::InvalidInput,
)?;
let mut locals_total = 0;
for _ in 0..local_count {
builder.set_srcloc(cur_srcloc(reader));
let (count, ty) = reader.read_local_decl(&mut locals_total).map_err(|_| {
CtonError::InvalidInput
})?;
declare_locals(builder, count, ty, &mut next_local);
}
Ok(())
}
/// Declare `count` local variables of the same type, starting from `next_local`.
///
/// Fail of too many locals are declared in the function, or if the type is not valid for a local.
fn declare_locals(
builder: &mut FunctionBuilder<Variable>,
count: u32,
wasm_type: wasmparser::Type,
next_local: &mut usize,
) {
// All locals are initialized to 0.
use wasmparser::Type::*;
let zeroval = match wasm_type {
I32 => builder.ins().iconst(ir::types::I32, 0),
I64 => builder.ins().iconst(ir::types::I64, 0),
F32 => builder.ins().f32const(ir::immediates::Ieee32::with_bits(0)),
F64 => builder.ins().f64const(ir::immediates::Ieee64::with_bits(0)),
_ => panic!("invalid local type"),
};
let ty = builder.func.dfg.value_type(zeroval);
for _ in 0..count {
let local = Variable::new(*next_local);
builder.declare_var(local, ty);
builder.def_var(local, zeroval);
*next_local += 1;
}
}
/// Parse the function body in `reader`.
///
/// This assumes that the local variable declarations have already been parsed and function
/// arguments and locals are declared in the builder.
fn parse_function_body<FE: FuncEnvironment +?Sized>(
mut reader: BinaryReader,
builder: &mut FunctionBuilder<Variable>,
state: &mut TranslationState,
environ: &mut FE,
) -> CtonResult {
// The control stack is initialized with a single block representing the whole function.
debug_assert_eq!(state.control_stack.len(), 1, "State not initialized");
// Keep going until the final `End` operator which pops the outermost block.
while!state.control_stack.is_empty() {
builder.set_srcloc(cur_srcloc(&reader));
let op = reader.read_operator().map_err(|_| CtonError::InvalidInput)?;
translate_operator(op, builder, state, environ);
}
// The final `End` operator left us in the exit block where we need to manually add a return
// instruction.
//
// If the exit block is unreachable, it may not have the correct arguments, so we would
// generate a return instruction that doesn't match the signature.
if state.reachable {
debug_assert!(builder.is_pristine());
if!builder.is_unreachable() {
builder.ins().return_(&state.stack);
}
}
// Discard any remaining values on the stack. Either we just returned them,
// or the end of the function is unreachable.
state.stack.clear();
debug_assert!(reader.eof());
Ok(())
}
/// Get the current source location from a reader.
fn cur_srcloc(reader: &BinaryReader) -> ir::SourceLoc {
// We record source locations as byte code offsets relative to the beginning of the function.
// This will wrap around of a single function's byte code is larger than 4 GB, but a) the
// WebAssembly format doesn't allow for that, and b) that would hit other Cretonne
// implementation limits anyway.
ir::SourceLoc::new(reader.current_position() as u32)
}
#[cfg(test)]
mod tests {
use cretonne::{ir, Context};
use cretonne::ir::types::I32;
use environ::{DummyEnvironment, FuncEnvironment};
use super::FuncTranslator;
#[test]
fn small1() {
// Implicit return.
//
// (func $small1 (param i32) (result i32)
// (i32.add (get_local 0) (i32.const 1))
// )
const BODY: [u8; 7] = [
0x00, // local decl count
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 1
0x6a, // i32.add
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small1");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn
|
() {
// Same as above, but with an explicit return instruction.
//
// (func $small2 (param i32) (result i32)
// (return (i32.add (get_local 0) (i32.const 1)))
// )
const BODY: [u8; 8] = [
0x00, // local decl count
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 1
0x6a, // i32.add
0x0f, // return
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small2");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn infloop() {
// An infinite loop, no return instructions.
//
// (func $infloop (result i32)
// (local i32)
// (loop (result i32)
// (i32.add (get_local 0) (i32.const 1))
// (set_local 0)
// (br 0)
// )
// )
const BODY: [u8; 16] = [
0x01, // 1 local decl.
0x01, 0x7f, // 1 i32 local.
0x03, 0x7f, // loop i32
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 0
0x6a, // i32.add
0x21, 0x00, // set_local 0
0x0c, 0x00, // br 0
0x0b, // end
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("infloop");
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
}
|
small2
|
identifier_name
|
func_translator.rs
|
//! Stand-alone WebAssembly to Cretonne IL translator.
//!
//! This module defines the `FuncTranslator` type which can translate a single WebAssembly
//! function to Cretonne IL guided by a `FuncEnvironment` which provides information about the
//! WebAssembly module and the runtime environment.
use code_translator::translate_operator;
use cretonne::entity::EntityRef;
use cretonne::ir::{self, InstBuilder, Ebb};
use cretonne::result::{CtonResult, CtonError};
use cretonne::timing;
use cton_frontend::{FunctionBuilderContext, FunctionBuilder, Variable};
use environ::FuncEnvironment;
use state::TranslationState;
use wasmparser::{self, BinaryReader};
/// WebAssembly to Cretonne IL function translator.
///
/// A `FuncTranslator` is used to translate a binary WebAssembly function into Cretonne IL guided
/// by a `FuncEnvironment` object. A single translator instance can be reused to translate multiple
/// functions which will reduce heap allocation traffic.
pub struct FuncTranslator {
func_ctx: FunctionBuilderContext<Variable>,
state: TranslationState,
}
impl FuncTranslator {
/// Create a new translator.
pub fn new() -> Self {
Self {
func_ctx: FunctionBuilderContext::new(),
state: TranslationState::new(),
}
}
/// Translate a binary WebAssembly function.
///
/// The `code` slice contains the binary WebAssembly *function code* as it appears in the code
/// section of a WebAssembly module, not including the initial size of the function code. The
/// slice is expected to contain two parts:
///
/// - The declaration of *locals*, and
/// - The function *body* as an expression.
///
/// See [the WebAssembly specification][wasm].
///
/// [wasm]: https://webassembly.github.io/spec/binary/modules.html#code-section
///
/// The Cretonne IR function `func` should be completely empty except for the `func.signature`
/// and `func.name` fields. The signature may contain special-purpose arguments which are not
/// regarded as WebAssembly local variables. Any signature arguments marked as
/// `ArgumentPurpose::Normal` are made accessible as WebAssembly local variables.
///
pub fn translate<FE: FuncEnvironment +?Sized>(
&mut self,
code: &[u8],
func: &mut ir::Function,
environ: &mut FE,
) -> CtonResult {
self.translate_from_reader(BinaryReader::new(code), func, environ)
}
/// Translate a binary WebAssembly function from a `BinaryReader`.
pub fn translate_from_reader<FE: FuncEnvironment +?Sized>(
&mut self,
mut reader: BinaryReader,
func: &mut ir::Function,
environ: &mut FE,
) -> CtonResult {
let _tt = timing::wasm_translate_function();
dbg!(
"translate({} bytes, {}{})",
reader.bytes_remaining(),
func.name,
func.signature
);
debug_assert_eq!(func.dfg.num_ebbs(), 0, "Function must be empty");
debug_assert_eq!(func.dfg.num_insts(), 0, "Function must be empty");
// This clears the `FunctionBuilderContext`.
let mut builder = FunctionBuilder::new(func, &mut self.func_ctx);
let entry_block = builder.create_ebb();
builder.append_ebb_params_for_function_params(entry_block);
builder.switch_to_block(entry_block); // This also creates values for the arguments.
builder.seal_block(entry_block);
// Make sure the entry block is inserted in the layout before we make any callbacks to
// `environ`. The callback functions may need to insert things in the entry block.
builder.ensure_inserted_ebb();
let num_params = declare_wasm_parameters(&mut builder, entry_block);
// Set up the translation state with a single pushed control block representing the whole
// function and its return values.
let exit_block = builder.create_ebb();
builder.append_ebb_params_for_function_returns(exit_block);
self.state.initialize(&builder.func.signature, exit_block);
parse_local_decls(&mut reader, &mut builder, num_params)?;
parse_function_body(reader, &mut builder, &mut self.state, environ)?;
builder.finalize();
Ok(())
}
}
/// Declare local variables for the signature parameters that correspond to WebAssembly locals.
///
/// Return the number of local variables declared.
fn declare_wasm_parameters(builder: &mut FunctionBuilder<Variable>, entry_block: Ebb) -> usize {
let sig_len = builder.func.signature.params.len();
let mut next_local = 0;
for i in 0..sig_len {
let param_type = builder.func.signature.params[i];
// There may be additional special-purpose parameters following the normal WebAssembly
// signature parameters. For example, a `vmctx` pointer.
if param_type.purpose == ir::ArgumentPurpose::Normal {
// This is a normal WebAssembly signature parameter, so create a local for it.
let local = Variable::new(next_local);
builder.declare_var(local, param_type.value_type);
next_local += 1;
let param_value = builder.ebb_params(entry_block)[i];
builder.def_var(local, param_value);
}
}
next_local
}
/// Parse the local variable declarations that precede the function body.
///
/// Declare local variables, starting from `num_params`.
fn parse_local_decls(
reader: &mut BinaryReader,
builder: &mut FunctionBuilder<Variable>,
num_params: usize,
) -> CtonResult {
let mut next_local = num_params;
let local_count = reader.read_local_count().map_err(
|_| CtonError::InvalidInput,
)?;
let mut locals_total = 0;
for _ in 0..local_count {
builder.set_srcloc(cur_srcloc(reader));
let (count, ty) = reader.read_local_decl(&mut locals_total).map_err(|_| {
CtonError::InvalidInput
})?;
declare_locals(builder, count, ty, &mut next_local);
}
Ok(())
}
/// Declare `count` local variables of the same type, starting from `next_local`.
///
/// Fail of too many locals are declared in the function, or if the type is not valid for a local.
fn declare_locals(
builder: &mut FunctionBuilder<Variable>,
count: u32,
wasm_type: wasmparser::Type,
next_local: &mut usize,
) {
// All locals are initialized to 0.
use wasmparser::Type::*;
let zeroval = match wasm_type {
I32 => builder.ins().iconst(ir::types::I32, 0),
I64 => builder.ins().iconst(ir::types::I64, 0),
F32 => builder.ins().f32const(ir::immediates::Ieee32::with_bits(0)),
F64 => builder.ins().f64const(ir::immediates::Ieee64::with_bits(0)),
_ => panic!("invalid local type"),
};
let ty = builder.func.dfg.value_type(zeroval);
for _ in 0..count {
let local = Variable::new(*next_local);
builder.declare_var(local, ty);
builder.def_var(local, zeroval);
*next_local += 1;
}
}
/// Parse the function body in `reader`.
///
/// This assumes that the local variable declarations have already been parsed and function
/// arguments and locals are declared in the builder.
fn parse_function_body<FE: FuncEnvironment +?Sized>(
mut reader: BinaryReader,
builder: &mut FunctionBuilder<Variable>,
state: &mut TranslationState,
environ: &mut FE,
) -> CtonResult {
// The control stack is initialized with a single block representing the whole function.
debug_assert_eq!(state.control_stack.len(), 1, "State not initialized");
// Keep going until the final `End` operator which pops the outermost block.
while!state.control_stack.is_empty() {
builder.set_srcloc(cur_srcloc(&reader));
|
translate_operator(op, builder, state, environ);
}
// The final `End` operator left us in the exit block where we need to manually add a return
// instruction.
//
// If the exit block is unreachable, it may not have the correct arguments, so we would
// generate a return instruction that doesn't match the signature.
if state.reachable {
debug_assert!(builder.is_pristine());
if!builder.is_unreachable() {
builder.ins().return_(&state.stack);
}
}
// Discard any remaining values on the stack. Either we just returned them,
// or the end of the function is unreachable.
state.stack.clear();
debug_assert!(reader.eof());
Ok(())
}
/// Get the current source location from a reader.
fn cur_srcloc(reader: &BinaryReader) -> ir::SourceLoc {
// We record source locations as byte code offsets relative to the beginning of the function.
// This will wrap around of a single function's byte code is larger than 4 GB, but a) the
// WebAssembly format doesn't allow for that, and b) that would hit other Cretonne
// implementation limits anyway.
ir::SourceLoc::new(reader.current_position() as u32)
}
#[cfg(test)]
mod tests {
use cretonne::{ir, Context};
use cretonne::ir::types::I32;
use environ::{DummyEnvironment, FuncEnvironment};
use super::FuncTranslator;
#[test]
fn small1() {
// Implicit return.
//
// (func $small1 (param i32) (result i32)
// (i32.add (get_local 0) (i32.const 1))
// )
const BODY: [u8; 7] = [
0x00, // local decl count
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 1
0x6a, // i32.add
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small1");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn small2() {
// Same as above, but with an explicit return instruction.
//
// (func $small2 (param i32) (result i32)
// (return (i32.add (get_local 0) (i32.const 1)))
// )
const BODY: [u8; 8] = [
0x00, // local decl count
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 1
0x6a, // i32.add
0x0f, // return
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small2");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn infloop() {
// An infinite loop, no return instructions.
//
// (func $infloop (result i32)
// (local i32)
// (loop (result i32)
// (i32.add (get_local 0) (i32.const 1))
// (set_local 0)
// (br 0)
// )
// )
const BODY: [u8; 16] = [
0x01, // 1 local decl.
0x01, 0x7f, // 1 i32 local.
0x03, 0x7f, // loop i32
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 0
0x6a, // i32.add
0x21, 0x00, // set_local 0
0x0c, 0x00, // br 0
0x0b, // end
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("infloop");
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
}
|
let op = reader.read_operator().map_err(|_| CtonError::InvalidInput)?;
|
random_line_split
|
func_translator.rs
|
//! Stand-alone WebAssembly to Cretonne IL translator.
//!
//! This module defines the `FuncTranslator` type which can translate a single WebAssembly
//! function to Cretonne IL guided by a `FuncEnvironment` which provides information about the
//! WebAssembly module and the runtime environment.
use code_translator::translate_operator;
use cretonne::entity::EntityRef;
use cretonne::ir::{self, InstBuilder, Ebb};
use cretonne::result::{CtonResult, CtonError};
use cretonne::timing;
use cton_frontend::{FunctionBuilderContext, FunctionBuilder, Variable};
use environ::FuncEnvironment;
use state::TranslationState;
use wasmparser::{self, BinaryReader};
/// WebAssembly to Cretonne IL function translator.
///
/// A `FuncTranslator` is used to translate a binary WebAssembly function into Cretonne IL guided
/// by a `FuncEnvironment` object. A single translator instance can be reused to translate multiple
/// functions which will reduce heap allocation traffic.
pub struct FuncTranslator {
func_ctx: FunctionBuilderContext<Variable>,
state: TranslationState,
}
impl FuncTranslator {
/// Create a new translator.
pub fn new() -> Self
|
/// Translate a binary WebAssembly function.
///
/// The `code` slice contains the binary WebAssembly *function code* as it appears in the code
/// section of a WebAssembly module, not including the initial size of the function code. The
/// slice is expected to contain two parts:
///
/// - The declaration of *locals*, and
/// - The function *body* as an expression.
///
/// See [the WebAssembly specification][wasm].
///
/// [wasm]: https://webassembly.github.io/spec/binary/modules.html#code-section
///
/// The Cretonne IR function `func` should be completely empty except for the `func.signature`
/// and `func.name` fields. The signature may contain special-purpose arguments which are not
/// regarded as WebAssembly local variables. Any signature arguments marked as
/// `ArgumentPurpose::Normal` are made accessible as WebAssembly local variables.
///
pub fn translate<FE: FuncEnvironment +?Sized>(
&mut self,
code: &[u8],
func: &mut ir::Function,
environ: &mut FE,
) -> CtonResult {
self.translate_from_reader(BinaryReader::new(code), func, environ)
}
/// Translate a binary WebAssembly function from a `BinaryReader`.
pub fn translate_from_reader<FE: FuncEnvironment +?Sized>(
&mut self,
mut reader: BinaryReader,
func: &mut ir::Function,
environ: &mut FE,
) -> CtonResult {
let _tt = timing::wasm_translate_function();
dbg!(
"translate({} bytes, {}{})",
reader.bytes_remaining(),
func.name,
func.signature
);
debug_assert_eq!(func.dfg.num_ebbs(), 0, "Function must be empty");
debug_assert_eq!(func.dfg.num_insts(), 0, "Function must be empty");
// This clears the `FunctionBuilderContext`.
let mut builder = FunctionBuilder::new(func, &mut self.func_ctx);
let entry_block = builder.create_ebb();
builder.append_ebb_params_for_function_params(entry_block);
builder.switch_to_block(entry_block); // This also creates values for the arguments.
builder.seal_block(entry_block);
// Make sure the entry block is inserted in the layout before we make any callbacks to
// `environ`. The callback functions may need to insert things in the entry block.
builder.ensure_inserted_ebb();
let num_params = declare_wasm_parameters(&mut builder, entry_block);
// Set up the translation state with a single pushed control block representing the whole
// function and its return values.
let exit_block = builder.create_ebb();
builder.append_ebb_params_for_function_returns(exit_block);
self.state.initialize(&builder.func.signature, exit_block);
parse_local_decls(&mut reader, &mut builder, num_params)?;
parse_function_body(reader, &mut builder, &mut self.state, environ)?;
builder.finalize();
Ok(())
}
}
/// Declare local variables for the signature parameters that correspond to WebAssembly locals.
///
/// Return the number of local variables declared.
fn declare_wasm_parameters(builder: &mut FunctionBuilder<Variable>, entry_block: Ebb) -> usize {
let sig_len = builder.func.signature.params.len();
let mut next_local = 0;
for i in 0..sig_len {
let param_type = builder.func.signature.params[i];
// There may be additional special-purpose parameters following the normal WebAssembly
// signature parameters. For example, a `vmctx` pointer.
if param_type.purpose == ir::ArgumentPurpose::Normal {
// This is a normal WebAssembly signature parameter, so create a local for it.
let local = Variable::new(next_local);
builder.declare_var(local, param_type.value_type);
next_local += 1;
let param_value = builder.ebb_params(entry_block)[i];
builder.def_var(local, param_value);
}
}
next_local
}
/// Parse the local variable declarations that precede the function body.
///
/// Declare local variables, starting from `num_params`.
fn parse_local_decls(
reader: &mut BinaryReader,
builder: &mut FunctionBuilder<Variable>,
num_params: usize,
) -> CtonResult {
let mut next_local = num_params;
let local_count = reader.read_local_count().map_err(
|_| CtonError::InvalidInput,
)?;
let mut locals_total = 0;
for _ in 0..local_count {
builder.set_srcloc(cur_srcloc(reader));
let (count, ty) = reader.read_local_decl(&mut locals_total).map_err(|_| {
CtonError::InvalidInput
})?;
declare_locals(builder, count, ty, &mut next_local);
}
Ok(())
}
/// Declare `count` local variables of the same type, starting from `next_local`.
///
/// Fail of too many locals are declared in the function, or if the type is not valid for a local.
fn declare_locals(
builder: &mut FunctionBuilder<Variable>,
count: u32,
wasm_type: wasmparser::Type,
next_local: &mut usize,
) {
// All locals are initialized to 0.
use wasmparser::Type::*;
let zeroval = match wasm_type {
I32 => builder.ins().iconst(ir::types::I32, 0),
I64 => builder.ins().iconst(ir::types::I64, 0),
F32 => builder.ins().f32const(ir::immediates::Ieee32::with_bits(0)),
F64 => builder.ins().f64const(ir::immediates::Ieee64::with_bits(0)),
_ => panic!("invalid local type"),
};
let ty = builder.func.dfg.value_type(zeroval);
for _ in 0..count {
let local = Variable::new(*next_local);
builder.declare_var(local, ty);
builder.def_var(local, zeroval);
*next_local += 1;
}
}
/// Parse the function body in `reader`.
///
/// This assumes that the local variable declarations have already been parsed and function
/// arguments and locals are declared in the builder.
fn parse_function_body<FE: FuncEnvironment +?Sized>(
mut reader: BinaryReader,
builder: &mut FunctionBuilder<Variable>,
state: &mut TranslationState,
environ: &mut FE,
) -> CtonResult {
// The control stack is initialized with a single block representing the whole function.
debug_assert_eq!(state.control_stack.len(), 1, "State not initialized");
// Keep going until the final `End` operator which pops the outermost block.
while!state.control_stack.is_empty() {
builder.set_srcloc(cur_srcloc(&reader));
let op = reader.read_operator().map_err(|_| CtonError::InvalidInput)?;
translate_operator(op, builder, state, environ);
}
// The final `End` operator left us in the exit block where we need to manually add a return
// instruction.
//
// If the exit block is unreachable, it may not have the correct arguments, so we would
// generate a return instruction that doesn't match the signature.
if state.reachable {
debug_assert!(builder.is_pristine());
if!builder.is_unreachable() {
builder.ins().return_(&state.stack);
}
}
// Discard any remaining values on the stack. Either we just returned them,
// or the end of the function is unreachable.
state.stack.clear();
debug_assert!(reader.eof());
Ok(())
}
/// Get the current source location from a reader.
fn cur_srcloc(reader: &BinaryReader) -> ir::SourceLoc {
// We record source locations as byte code offsets relative to the beginning of the function.
// This will wrap around of a single function's byte code is larger than 4 GB, but a) the
// WebAssembly format doesn't allow for that, and b) that would hit other Cretonne
// implementation limits anyway.
ir::SourceLoc::new(reader.current_position() as u32)
}
#[cfg(test)]
mod tests {
use cretonne::{ir, Context};
use cretonne::ir::types::I32;
use environ::{DummyEnvironment, FuncEnvironment};
use super::FuncTranslator;
#[test]
fn small1() {
// Implicit return.
//
// (func $small1 (param i32) (result i32)
// (i32.add (get_local 0) (i32.const 1))
// )
const BODY: [u8; 7] = [
0x00, // local decl count
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 1
0x6a, // i32.add
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small1");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn small2() {
// Same as above, but with an explicit return instruction.
//
// (func $small2 (param i32) (result i32)
// (return (i32.add (get_local 0) (i32.const 1)))
// )
const BODY: [u8; 8] = [
0x00, // local decl count
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 1
0x6a, // i32.add
0x0f, // return
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small2");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn infloop() {
// An infinite loop, no return instructions.
//
// (func $infloop (result i32)
// (local i32)
// (loop (result i32)
// (i32.add (get_local 0) (i32.const 1))
// (set_local 0)
// (br 0)
// )
// )
const BODY: [u8; 16] = [
0x01, // 1 local decl.
0x01, 0x7f, // 1 i32 local.
0x03, 0x7f, // loop i32
0x20, 0x00, // get_local 0
0x41, 0x01, // i32.const 0
0x6a, // i32.add
0x21, 0x00, // set_local 0
0x0c, 0x00, // br 0
0x0b, // end
0x0b, // end
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::default();
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("infloop");
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
}
|
{
Self {
func_ctx: FunctionBuilderContext::new(),
state: TranslationState::new(),
}
}
|
identifier_body
|
lib.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 https://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
#![feature(track_caller)]
#[macro_use]
extern crate log;
pub use crate::compositor::CompositingReason;
pub use crate::compositor::IOCompositor;
pub use crate::compositor::ShutdownState;
pub use crate::compositor_thread::CompositorProxy;
use embedder_traits::Cursor;
use gfx_traits::Epoch;
use ipc_channel::ipc::IpcSender;
use keyboard_types::KeyboardEvent;
use msg::constellation_msg::PipelineId;
use msg::constellation_msg::TopLevelBrowsingContextId;
use msg::constellation_msg::{BrowsingContextId, TraversalDirection};
use script_traits::{
AnimationTickType, LogEntry, WebDriverCommandMsg, WindowSizeData, WindowSizeType,
};
use script_traits::{
CompositorEvent, ConstellationControlMsg, LayoutControlMsg, MediaSessionActionType,
};
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fmt;
use std::time::Duration;
mod compositor;
pub mod compositor_thread;
#[cfg(feature = "gl")]
mod gl;
mod touch;
pub mod windowing;
pub struct SendableFrameTree {
pub pipeline: CompositionPipeline,
pub children: Vec<SendableFrameTree>,
}
/// The subset of the pipeline that is needed for layer composition.
#[derive(Clone)]
pub struct
|
{
pub id: PipelineId,
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub layout_chan: IpcSender<LayoutControlMsg>,
}
/// Messages to the constellation.
pub enum ConstellationMsg {
/// Exit the constellation.
Exit,
/// Request that the constellation send the BrowsingContextId corresponding to the document
/// with the provided pipeline id
GetBrowsingContext(PipelineId, IpcSender<Option<BrowsingContextId>>),
/// Request that the constellation send the current pipeline id for the provided
/// browsing context id, over a provided channel.
GetPipeline(BrowsingContextId, IpcSender<Option<PipelineId>>),
/// Request that the constellation send the current focused top-level browsing context id,
/// over a provided channel.
GetFocusTopLevelBrowsingContext(IpcSender<Option<TopLevelBrowsingContextId>>),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
/// Inform the constellation of a key event.
Keyboard(KeyboardEvent),
/// Whether to allow script to navigate.
AllowNavigationResponse(PipelineId, bool),
/// Request to load a page.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Request to traverse the joint session history of the provided browsing context.
TraverseHistory(TopLevelBrowsingContextId, TraversalDirection),
/// Inform the constellation of a window being resized.
WindowSize(
Option<TopLevelBrowsingContextId>,
WindowSizeData,
WindowSizeType,
),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
/// Reload a top-level browsing context.
Reload(TopLevelBrowsingContextId),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<TopLevelBrowsingContextId>, Option<String>, LogEntry),
/// Create a new top level browsing context.
NewBrowser(ServoUrl, TopLevelBrowsingContextId),
/// Close a top level browsing context.
CloseBrowser(TopLevelBrowsingContextId),
/// Panic a top level browsing context.
SendError(Option<TopLevelBrowsingContextId>, String),
/// Make browser visible.
SelectBrowser(TopLevelBrowsingContextId),
/// Forward an event to the script task of the given pipeline.
ForwardEvent(PipelineId, CompositorEvent),
/// Requesting a change to the onscreen cursor.
SetCursor(Cursor),
/// Enable the sampling profiler, with a given sampling rate and max total sampling duration.
EnableProfiler(Duration, Duration),
/// Disable the sampling profiler.
DisableProfiler,
/// Request to exit from fullscreen mode
ExitFullScreen(TopLevelBrowsingContextId),
/// Media session action.
MediaSessionAction(MediaSessionActionType),
/// Toggle browser visibility.
ChangeBrowserVisibility(TopLevelBrowsingContextId, bool),
}
impl fmt::Debug for ConstellationMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ConstellationMsg::*;
let variant = match *self {
Exit => "Exit",
GetBrowsingContext(..) => "GetBrowsingContext",
GetPipeline(..) => "GetPipeline",
GetFocusTopLevelBrowsingContext(..) => "GetFocusTopLevelBrowsingContext",
IsReadyToSaveImage(..) => "IsReadyToSaveImage",
Keyboard(..) => "Keyboard",
AllowNavigationResponse(..) => "AllowNavigationResponse",
LoadUrl(..) => "LoadUrl",
TraverseHistory(..) => "TraverseHistory",
WindowSize(..) => "WindowSize",
TickAnimation(..) => "TickAnimation",
WebDriverCommand(..) => "WebDriverCommand",
Reload(..) => "Reload",
LogEntry(..) => "LogEntry",
NewBrowser(..) => "NewBrowser",
CloseBrowser(..) => "CloseBrowser",
SendError(..) => "SendError",
SelectBrowser(..) => "SelectBrowser",
ForwardEvent(..) => "ForwardEvent",
SetCursor(..) => "SetCursor",
EnableProfiler(..) => "EnableProfiler",
DisableProfiler => "DisableProfiler",
ExitFullScreen(..) => "ExitFullScreen",
MediaSessionAction(..) => "MediaSessionAction",
ChangeBrowserVisibility(..) => "ChangeBrowserVisibility",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
|
CompositionPipeline
|
identifier_name
|
lib.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 https://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
#![feature(track_caller)]
#[macro_use]
extern crate log;
pub use crate::compositor::CompositingReason;
pub use crate::compositor::IOCompositor;
pub use crate::compositor::ShutdownState;
pub use crate::compositor_thread::CompositorProxy;
use embedder_traits::Cursor;
use gfx_traits::Epoch;
use ipc_channel::ipc::IpcSender;
use keyboard_types::KeyboardEvent;
use msg::constellation_msg::PipelineId;
use msg::constellation_msg::TopLevelBrowsingContextId;
use msg::constellation_msg::{BrowsingContextId, TraversalDirection};
use script_traits::{
AnimationTickType, LogEntry, WebDriverCommandMsg, WindowSizeData, WindowSizeType,
};
use script_traits::{
CompositorEvent, ConstellationControlMsg, LayoutControlMsg, MediaSessionActionType,
};
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fmt;
use std::time::Duration;
mod compositor;
pub mod compositor_thread;
#[cfg(feature = "gl")]
mod gl;
mod touch;
pub mod windowing;
pub struct SendableFrameTree {
pub pipeline: CompositionPipeline,
pub children: Vec<SendableFrameTree>,
}
/// The subset of the pipeline that is needed for layer composition.
#[derive(Clone)]
pub struct CompositionPipeline {
pub id: PipelineId,
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub layout_chan: IpcSender<LayoutControlMsg>,
}
/// Messages to the constellation.
pub enum ConstellationMsg {
/// Exit the constellation.
Exit,
/// Request that the constellation send the BrowsingContextId corresponding to the document
/// with the provided pipeline id
GetBrowsingContext(PipelineId, IpcSender<Option<BrowsingContextId>>),
/// Request that the constellation send the current pipeline id for the provided
/// browsing context id, over a provided channel.
GetPipeline(BrowsingContextId, IpcSender<Option<PipelineId>>),
/// Request that the constellation send the current focused top-level browsing context id,
/// over a provided channel.
GetFocusTopLevelBrowsingContext(IpcSender<Option<TopLevelBrowsingContextId>>),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
/// Inform the constellation of a key event.
Keyboard(KeyboardEvent),
/// Whether to allow script to navigate.
AllowNavigationResponse(PipelineId, bool),
/// Request to load a page.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Request to traverse the joint session history of the provided browsing context.
TraverseHistory(TopLevelBrowsingContextId, TraversalDirection),
/// Inform the constellation of a window being resized.
WindowSize(
Option<TopLevelBrowsingContextId>,
WindowSizeData,
WindowSizeType,
),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
/// Reload a top-level browsing context.
Reload(TopLevelBrowsingContextId),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<TopLevelBrowsingContextId>, Option<String>, LogEntry),
/// Create a new top level browsing context.
NewBrowser(ServoUrl, TopLevelBrowsingContextId),
/// Close a top level browsing context.
CloseBrowser(TopLevelBrowsingContextId),
/// Panic a top level browsing context.
SendError(Option<TopLevelBrowsingContextId>, String),
/// Make browser visible.
SelectBrowser(TopLevelBrowsingContextId),
/// Forward an event to the script task of the given pipeline.
ForwardEvent(PipelineId, CompositorEvent),
/// Requesting a change to the onscreen cursor.
SetCursor(Cursor),
/// Enable the sampling profiler, with a given sampling rate and max total sampling duration.
EnableProfiler(Duration, Duration),
/// Disable the sampling profiler.
DisableProfiler,
/// Request to exit from fullscreen mode
ExitFullScreen(TopLevelBrowsingContextId),
/// Media session action.
MediaSessionAction(MediaSessionActionType),
/// Toggle browser visibility.
ChangeBrowserVisibility(TopLevelBrowsingContextId, bool),
}
impl fmt::Debug for ConstellationMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result
|
SelectBrowser(..) => "SelectBrowser",
ForwardEvent(..) => "ForwardEvent",
SetCursor(..) => "SetCursor",
EnableProfiler(..) => "EnableProfiler",
DisableProfiler => "DisableProfiler",
ExitFullScreen(..) => "ExitFullScreen",
MediaSessionAction(..) => "MediaSessionAction",
ChangeBrowserVisibility(..) => "ChangeBrowserVisibility",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
|
{
use self::ConstellationMsg::*;
let variant = match *self {
Exit => "Exit",
GetBrowsingContext(..) => "GetBrowsingContext",
GetPipeline(..) => "GetPipeline",
GetFocusTopLevelBrowsingContext(..) => "GetFocusTopLevelBrowsingContext",
IsReadyToSaveImage(..) => "IsReadyToSaveImage",
Keyboard(..) => "Keyboard",
AllowNavigationResponse(..) => "AllowNavigationResponse",
LoadUrl(..) => "LoadUrl",
TraverseHistory(..) => "TraverseHistory",
WindowSize(..) => "WindowSize",
TickAnimation(..) => "TickAnimation",
WebDriverCommand(..) => "WebDriverCommand",
Reload(..) => "Reload",
LogEntry(..) => "LogEntry",
NewBrowser(..) => "NewBrowser",
CloseBrowser(..) => "CloseBrowser",
SendError(..) => "SendError",
|
identifier_body
|
lib.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 https://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
#![feature(track_caller)]
#[macro_use]
extern crate log;
pub use crate::compositor::CompositingReason;
pub use crate::compositor::IOCompositor;
pub use crate::compositor::ShutdownState;
pub use crate::compositor_thread::CompositorProxy;
use embedder_traits::Cursor;
use gfx_traits::Epoch;
use ipc_channel::ipc::IpcSender;
use keyboard_types::KeyboardEvent;
use msg::constellation_msg::PipelineId;
use msg::constellation_msg::TopLevelBrowsingContextId;
use msg::constellation_msg::{BrowsingContextId, TraversalDirection};
use script_traits::{
AnimationTickType, LogEntry, WebDriverCommandMsg, WindowSizeData, WindowSizeType,
};
use script_traits::{
CompositorEvent, ConstellationControlMsg, LayoutControlMsg, MediaSessionActionType,
};
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fmt;
use std::time::Duration;
mod compositor;
|
mod touch;
pub mod windowing;
pub struct SendableFrameTree {
pub pipeline: CompositionPipeline,
pub children: Vec<SendableFrameTree>,
}
/// The subset of the pipeline that is needed for layer composition.
#[derive(Clone)]
pub struct CompositionPipeline {
pub id: PipelineId,
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub layout_chan: IpcSender<LayoutControlMsg>,
}
/// Messages to the constellation.
pub enum ConstellationMsg {
/// Exit the constellation.
Exit,
/// Request that the constellation send the BrowsingContextId corresponding to the document
/// with the provided pipeline id
GetBrowsingContext(PipelineId, IpcSender<Option<BrowsingContextId>>),
/// Request that the constellation send the current pipeline id for the provided
/// browsing context id, over a provided channel.
GetPipeline(BrowsingContextId, IpcSender<Option<PipelineId>>),
/// Request that the constellation send the current focused top-level browsing context id,
/// over a provided channel.
GetFocusTopLevelBrowsingContext(IpcSender<Option<TopLevelBrowsingContextId>>),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
/// Inform the constellation of a key event.
Keyboard(KeyboardEvent),
/// Whether to allow script to navigate.
AllowNavigationResponse(PipelineId, bool),
/// Request to load a page.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Request to traverse the joint session history of the provided browsing context.
TraverseHistory(TopLevelBrowsingContextId, TraversalDirection),
/// Inform the constellation of a window being resized.
WindowSize(
Option<TopLevelBrowsingContextId>,
WindowSizeData,
WindowSizeType,
),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
/// Reload a top-level browsing context.
Reload(TopLevelBrowsingContextId),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<TopLevelBrowsingContextId>, Option<String>, LogEntry),
/// Create a new top level browsing context.
NewBrowser(ServoUrl, TopLevelBrowsingContextId),
/// Close a top level browsing context.
CloseBrowser(TopLevelBrowsingContextId),
/// Panic a top level browsing context.
SendError(Option<TopLevelBrowsingContextId>, String),
/// Make browser visible.
SelectBrowser(TopLevelBrowsingContextId),
/// Forward an event to the script task of the given pipeline.
ForwardEvent(PipelineId, CompositorEvent),
/// Requesting a change to the onscreen cursor.
SetCursor(Cursor),
/// Enable the sampling profiler, with a given sampling rate and max total sampling duration.
EnableProfiler(Duration, Duration),
/// Disable the sampling profiler.
DisableProfiler,
/// Request to exit from fullscreen mode
ExitFullScreen(TopLevelBrowsingContextId),
/// Media session action.
MediaSessionAction(MediaSessionActionType),
/// Toggle browser visibility.
ChangeBrowserVisibility(TopLevelBrowsingContextId, bool),
}
impl fmt::Debug for ConstellationMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ConstellationMsg::*;
let variant = match *self {
Exit => "Exit",
GetBrowsingContext(..) => "GetBrowsingContext",
GetPipeline(..) => "GetPipeline",
GetFocusTopLevelBrowsingContext(..) => "GetFocusTopLevelBrowsingContext",
IsReadyToSaveImage(..) => "IsReadyToSaveImage",
Keyboard(..) => "Keyboard",
AllowNavigationResponse(..) => "AllowNavigationResponse",
LoadUrl(..) => "LoadUrl",
TraverseHistory(..) => "TraverseHistory",
WindowSize(..) => "WindowSize",
TickAnimation(..) => "TickAnimation",
WebDriverCommand(..) => "WebDriverCommand",
Reload(..) => "Reload",
LogEntry(..) => "LogEntry",
NewBrowser(..) => "NewBrowser",
CloseBrowser(..) => "CloseBrowser",
SendError(..) => "SendError",
SelectBrowser(..) => "SelectBrowser",
ForwardEvent(..) => "ForwardEvent",
SetCursor(..) => "SetCursor",
EnableProfiler(..) => "EnableProfiler",
DisableProfiler => "DisableProfiler",
ExitFullScreen(..) => "ExitFullScreen",
MediaSessionAction(..) => "MediaSessionAction",
ChangeBrowserVisibility(..) => "ChangeBrowserVisibility",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
|
pub mod compositor_thread;
#[cfg(feature = "gl")]
mod gl;
|
random_line_split
|
main.rs
|
extern crate twox_hash;
extern crate rand;
use std::fs;
use std::hash::Hasher;
use std::io;
use std::io::Read;
use rand::isaac::Isaac64Rng;
use rand::{Rng, SeedableRng};
const ALPHA: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789{}[]-_=+()@#$^&<>?";
fn hash(p: &[u8], l: u64) -> u64 {
let mut h = twox_hash::XxHash::with_seed(l);
h.write(p);
h.finish()
}
fn hash_file<T>(p: T, l: u64) -> Result<u64, io::Error>
where T: AsRef<std::path::Path>
{
let mut h = twox_hash::XxHash::with_seed(l);
let mut buf = [0u8; 512];
let mut f = try!(fs::File::open(p));
loop {
let sz = try!(f.read(&mut buf));
if sz > 0
|
else {
break;
}
}
Ok(h.finish())
}
fn encode(c: &[u8], v: &[u8], l: usize) -> String {
let mut i = 0usize;
let mut j = 0usize;
let mut a = 0u32;
let c_l = c.len() as u32;
let mut s: Vec<u8> = Vec::with_capacity(l);
while i < l {
a += v[j] as u32;
while a >= c_l {
let r = a % c_l;
s.push(c[r as usize]);
a /= c_l;
i += 1;
}
j += 1;
}
unsafe { String::from_utf8_unchecked(s) }
}
fn main() {
let mut args = std::env::args();
if args.len() < 4 {
println!("Usage: pag <length> <name> <files>\n\nEXAMPLE:\nGenerate a password with 16 \
characters for github.com.\npag 16 github.com mypets.jpg holiday.pdf\n");
return;
}
args.next();
let length: u64 = std::str::FromStr::from_str(&args.next().unwrap()).unwrap();
let name = args.next().unwrap();
let mut file_hash = 0u64;
while let Some(filename) = args.next() {
let a = hash_file(filename, length).unwrap();
file_hash ^= a;
}
let hs = file_hash ^ hash(name.as_bytes(), length);
let mut rr = Isaac64Rng::from_seed(&[hs]);
let mut buf = [0u8; 64];
rr.fill_bytes(&mut buf);
let s = encode(ALPHA, &buf, length as usize);
println!("{}", s);
}
|
{
h.write(&buf[..sz]);
}
|
conditional_block
|
main.rs
|
extern crate twox_hash;
extern crate rand;
use std::fs;
use std::hash::Hasher;
use std::io;
use std::io::Read;
use rand::isaac::Isaac64Rng;
use rand::{Rng, SeedableRng};
const ALPHA: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789{}[]-_=+()@#$^&<>?";
fn hash(p: &[u8], l: u64) -> u64 {
let mut h = twox_hash::XxHash::with_seed(l);
h.write(p);
h.finish()
}
fn hash_file<T>(p: T, l: u64) -> Result<u64, io::Error>
where T: AsRef<std::path::Path>
|
fn encode(c: &[u8], v: &[u8], l: usize) -> String {
let mut i = 0usize;
let mut j = 0usize;
let mut a = 0u32;
let c_l = c.len() as u32;
let mut s: Vec<u8> = Vec::with_capacity(l);
while i < l {
a += v[j] as u32;
while a >= c_l {
let r = a % c_l;
s.push(c[r as usize]);
a /= c_l;
i += 1;
}
j += 1;
}
unsafe { String::from_utf8_unchecked(s) }
}
fn main() {
let mut args = std::env::args();
if args.len() < 4 {
println!("Usage: pag <length> <name> <files>\n\nEXAMPLE:\nGenerate a password with 16 \
characters for github.com.\npag 16 github.com mypets.jpg holiday.pdf\n");
return;
}
args.next();
let length: u64 = std::str::FromStr::from_str(&args.next().unwrap()).unwrap();
let name = args.next().unwrap();
let mut file_hash = 0u64;
while let Some(filename) = args.next() {
let a = hash_file(filename, length).unwrap();
file_hash ^= a;
}
let hs = file_hash ^ hash(name.as_bytes(), length);
let mut rr = Isaac64Rng::from_seed(&[hs]);
let mut buf = [0u8; 64];
rr.fill_bytes(&mut buf);
let s = encode(ALPHA, &buf, length as usize);
println!("{}", s);
}
|
{
let mut h = twox_hash::XxHash::with_seed(l);
let mut buf = [0u8; 512];
let mut f = try!(fs::File::open(p));
loop {
let sz = try!(f.read(&mut buf));
if sz > 0 {
h.write(&buf[..sz]);
} else {
break;
}
}
Ok(h.finish())
}
|
identifier_body
|
main.rs
|
extern crate twox_hash;
extern crate rand;
use std::fs;
use std::hash::Hasher;
use std::io;
use std::io::Read;
use rand::isaac::Isaac64Rng;
use rand::{Rng, SeedableRng};
const ALPHA: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789{}[]-_=+()@#$^&<>?";
fn
|
(p: &[u8], l: u64) -> u64 {
let mut h = twox_hash::XxHash::with_seed(l);
h.write(p);
h.finish()
}
fn hash_file<T>(p: T, l: u64) -> Result<u64, io::Error>
where T: AsRef<std::path::Path>
{
let mut h = twox_hash::XxHash::with_seed(l);
let mut buf = [0u8; 512];
let mut f = try!(fs::File::open(p));
loop {
let sz = try!(f.read(&mut buf));
if sz > 0 {
h.write(&buf[..sz]);
} else {
break;
}
}
Ok(h.finish())
}
fn encode(c: &[u8], v: &[u8], l: usize) -> String {
let mut i = 0usize;
let mut j = 0usize;
let mut a = 0u32;
let c_l = c.len() as u32;
let mut s: Vec<u8> = Vec::with_capacity(l);
while i < l {
a += v[j] as u32;
while a >= c_l {
let r = a % c_l;
s.push(c[r as usize]);
a /= c_l;
i += 1;
}
j += 1;
}
unsafe { String::from_utf8_unchecked(s) }
}
fn main() {
let mut args = std::env::args();
if args.len() < 4 {
println!("Usage: pag <length> <name> <files>\n\nEXAMPLE:\nGenerate a password with 16 \
characters for github.com.\npag 16 github.com mypets.jpg holiday.pdf\n");
return;
}
args.next();
let length: u64 = std::str::FromStr::from_str(&args.next().unwrap()).unwrap();
let name = args.next().unwrap();
let mut file_hash = 0u64;
while let Some(filename) = args.next() {
let a = hash_file(filename, length).unwrap();
file_hash ^= a;
}
let hs = file_hash ^ hash(name.as_bytes(), length);
let mut rr = Isaac64Rng::from_seed(&[hs]);
let mut buf = [0u8; 64];
rr.fill_bytes(&mut buf);
let s = encode(ALPHA, &buf, length as usize);
println!("{}", s);
}
|
hash
|
identifier_name
|
main.rs
|
extern crate twox_hash;
extern crate rand;
use std::fs;
use std::hash::Hasher;
use std::io;
use std::io::Read;
use rand::isaac::Isaac64Rng;
use rand::{Rng, SeedableRng};
const ALPHA: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789{}[]-_=+()@#$^&<>?";
fn hash(p: &[u8], l: u64) -> u64 {
let mut h = twox_hash::XxHash::with_seed(l);
h.write(p);
h.finish()
}
fn hash_file<T>(p: T, l: u64) -> Result<u64, io::Error>
where T: AsRef<std::path::Path>
{
let mut h = twox_hash::XxHash::with_seed(l);
let mut buf = [0u8; 512];
let mut f = try!(fs::File::open(p));
loop {
let sz = try!(f.read(&mut buf));
if sz > 0 {
h.write(&buf[..sz]);
} else {
break;
}
}
Ok(h.finish())
}
fn encode(c: &[u8], v: &[u8], l: usize) -> String {
let mut i = 0usize;
let mut j = 0usize;
let mut a = 0u32;
let c_l = c.len() as u32;
let mut s: Vec<u8> = Vec::with_capacity(l);
while i < l {
a += v[j] as u32;
while a >= c_l {
let r = a % c_l;
s.push(c[r as usize]);
a /= c_l;
i += 1;
}
j += 1;
}
unsafe { String::from_utf8_unchecked(s) }
}
fn main() {
let mut args = std::env::args();
if args.len() < 4 {
println!("Usage: pag <length> <name> <files>\n\nEXAMPLE:\nGenerate a password with 16 \
characters for github.com.\npag 16 github.com mypets.jpg holiday.pdf\n");
return;
}
args.next();
let length: u64 = std::str::FromStr::from_str(&args.next().unwrap()).unwrap();
let name = args.next().unwrap();
let mut file_hash = 0u64;
|
while let Some(filename) = args.next() {
let a = hash_file(filename, length).unwrap();
file_hash ^= a;
}
let hs = file_hash ^ hash(name.as_bytes(), length);
let mut rr = Isaac64Rng::from_seed(&[hs]);
let mut buf = [0u8; 64];
rr.fill_bytes(&mut buf);
let s = encode(ALPHA, &buf, length as usize);
println!("{}", s);
}
|
random_line_split
|
|
mod.rs
|
//! http server for semantic engines
use iron::prelude::*;
use ::Config;
mod definition;
mod file;
mod completion;
mod ping;
use ::engine::SemanticEngine;
use iron::typemap::Key;
use iron_hmac::Hmac256Authentication;
use iron_hmac::SecretKey;
/// Errors occurring in the http module
#[derive(Debug)]
pub enum Error {
/// Error occurred in underlying http server lib
HttpServer(::hyper::Error),
// Error occurred in http framework layer
// HttpApp(::iron::IronError),
}
impl From<::hyper::Error> for Error {
fn from(err: ::hyper::Error) -> Error {
Error::HttpServer(err)
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
// -------------------------------------------------------------------------------------------------
/// Iron middleware responsible for attaching a semantic engine to each request
#[derive(Debug, Clone)]
pub struct EngineProvider;
impl Key for EngineProvider {
type Value = Box<SemanticEngine + Send + Sync>;
}
// -------------------------------------------------------------------------------------------------
/// Start the http server using the given configuration
///
/// `serve` is non-blocking.
///
/// # Example
///
/// ```no_run
/// # use libracerd::{Config};
/// let mut cfg = Config::new();
/// cfg.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
///
/// let mut server = ::libracerd::http::serve(&cfg, engine).unwrap();
/// //... later
/// server.close().unwrap();
/// ```
///
pub fn serve<E: SemanticEngine +'static>(config: &Config, engine: E) -> Result<Server> {
use persistent::{Read, Write};
use logger::Logger;
use logger::format::Format;
let mut chain = Chain::new(router!(
post "/parse_file" => file::parse,
post "/find_definition" => definition::find,
post "/list_completions" => completion::list,
get "/ping" => ping::pong));
// Logging middleware
let log_fmt = Format::new("{method} {uri} -> {status} ({response-time})",
Vec::new(), Vec::new());
let (log_before, log_after) = Logger::new(log_fmt);
// log_before must be first middleware in before chain
if config.print_http_logs {
chain.link_before(log_before);
}
// Get HMAC Middleware
let (hmac_before, hmac_after) = if config.secret_file.is_some() {
let secret = SecretKey::new(&config.read_secret_file());
let hmac_header = "x-racerd-hmac";
let (before, after) = Hmac256Authentication::middleware(secret, hmac_header);
(Some(before), Some(after))
} else {
(None, None)
};
// This middleware provides a semantic engine to the request handlers
chain.link_before(Write::<EngineProvider>::one(Box::new(engine)));
// Body parser middlerware
chain.link_before(Read::<::bodyparser::MaxBodyLength>::one(1024 * 1024 * 10));
// Maybe link hmac middleware
if let Some(hmac) = hmac_before
|
if let Some(hmac) = hmac_after {
chain.link_after(hmac);
}
// log_after must be last middleware in after chain
if config.print_http_logs {
chain.link_after(log_after);
}
let app = Iron::new(chain);
Ok(Server {
inner: try!(app.http((&config.addr[..], config.port)))
})
}
/// Wrapper type with information and control of the underlying HTTP server
///
/// This type can only be created via the [`serve`](fn.serve.html) function.
#[derive(Debug)]
pub struct Server {
inner: ::hyper::server::Listening,
}
impl Server {
/// Stop accepting connections
pub fn close(&mut self) -> Result<()> {
Ok(try!(self.inner.close()))
}
/// Get listening address of server (eg. "127.0.0.1:59369")
///
/// # Example
/// ```no_run
/// let mut config = ::libracerd::Config::new();
/// config.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
/// let server = ::libracerd::http::serve(&config, engine).unwrap();
///
/// assert_eq!(server.addr(), "0.0.0.0:3000");
/// ```
pub fn addr(&self) -> String {
format!("{}", self.inner.socket)
}
}
|
{
chain.link_before(hmac);
}
|
conditional_block
|
mod.rs
|
//! http server for semantic engines
use iron::prelude::*;
use ::Config;
mod definition;
mod file;
mod completion;
mod ping;
use ::engine::SemanticEngine;
use iron::typemap::Key;
use iron_hmac::Hmac256Authentication;
use iron_hmac::SecretKey;
/// Errors occurring in the http module
#[derive(Debug)]
pub enum Error {
/// Error occurred in underlying http server lib
HttpServer(::hyper::Error),
// Error occurred in http framework layer
// HttpApp(::iron::IronError),
}
impl From<::hyper::Error> for Error {
fn
|
(err: ::hyper::Error) -> Error {
Error::HttpServer(err)
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
// -------------------------------------------------------------------------------------------------
/// Iron middleware responsible for attaching a semantic engine to each request
#[derive(Debug, Clone)]
pub struct EngineProvider;
impl Key for EngineProvider {
type Value = Box<SemanticEngine + Send + Sync>;
}
// -------------------------------------------------------------------------------------------------
/// Start the http server using the given configuration
///
/// `serve` is non-blocking.
///
/// # Example
///
/// ```no_run
/// # use libracerd::{Config};
/// let mut cfg = Config::new();
/// cfg.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
///
/// let mut server = ::libracerd::http::serve(&cfg, engine).unwrap();
/// //... later
/// server.close().unwrap();
/// ```
///
pub fn serve<E: SemanticEngine +'static>(config: &Config, engine: E) -> Result<Server> {
use persistent::{Read, Write};
use logger::Logger;
use logger::format::Format;
let mut chain = Chain::new(router!(
post "/parse_file" => file::parse,
post "/find_definition" => definition::find,
post "/list_completions" => completion::list,
get "/ping" => ping::pong));
// Logging middleware
let log_fmt = Format::new("{method} {uri} -> {status} ({response-time})",
Vec::new(), Vec::new());
let (log_before, log_after) = Logger::new(log_fmt);
// log_before must be first middleware in before chain
if config.print_http_logs {
chain.link_before(log_before);
}
// Get HMAC Middleware
let (hmac_before, hmac_after) = if config.secret_file.is_some() {
let secret = SecretKey::new(&config.read_secret_file());
let hmac_header = "x-racerd-hmac";
let (before, after) = Hmac256Authentication::middleware(secret, hmac_header);
(Some(before), Some(after))
} else {
(None, None)
};
// This middleware provides a semantic engine to the request handlers
chain.link_before(Write::<EngineProvider>::one(Box::new(engine)));
// Body parser middlerware
chain.link_before(Read::<::bodyparser::MaxBodyLength>::one(1024 * 1024 * 10));
// Maybe link hmac middleware
if let Some(hmac) = hmac_before {
chain.link_before(hmac);
}
if let Some(hmac) = hmac_after {
chain.link_after(hmac);
}
// log_after must be last middleware in after chain
if config.print_http_logs {
chain.link_after(log_after);
}
let app = Iron::new(chain);
Ok(Server {
inner: try!(app.http((&config.addr[..], config.port)))
})
}
/// Wrapper type with information and control of the underlying HTTP server
///
/// This type can only be created via the [`serve`](fn.serve.html) function.
#[derive(Debug)]
pub struct Server {
inner: ::hyper::server::Listening,
}
impl Server {
/// Stop accepting connections
pub fn close(&mut self) -> Result<()> {
Ok(try!(self.inner.close()))
}
/// Get listening address of server (eg. "127.0.0.1:59369")
///
/// # Example
/// ```no_run
/// let mut config = ::libracerd::Config::new();
/// config.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
/// let server = ::libracerd::http::serve(&config, engine).unwrap();
///
/// assert_eq!(server.addr(), "0.0.0.0:3000");
/// ```
pub fn addr(&self) -> String {
format!("{}", self.inner.socket)
}
}
|
from
|
identifier_name
|
mod.rs
|
//! http server for semantic engines
use iron::prelude::*;
use ::Config;
mod definition;
mod file;
mod completion;
mod ping;
use ::engine::SemanticEngine;
use iron::typemap::Key;
use iron_hmac::Hmac256Authentication;
use iron_hmac::SecretKey;
/// Errors occurring in the http module
#[derive(Debug)]
pub enum Error {
/// Error occurred in underlying http server lib
HttpServer(::hyper::Error),
// Error occurred in http framework layer
// HttpApp(::iron::IronError),
}
impl From<::hyper::Error> for Error {
fn from(err: ::hyper::Error) -> Error {
Error::HttpServer(err)
}
|
pub type Result<T> = ::std::result::Result<T, Error>;
// -------------------------------------------------------------------------------------------------
/// Iron middleware responsible for attaching a semantic engine to each request
#[derive(Debug, Clone)]
pub struct EngineProvider;
impl Key for EngineProvider {
type Value = Box<SemanticEngine + Send + Sync>;
}
// -------------------------------------------------------------------------------------------------
/// Start the http server using the given configuration
///
/// `serve` is non-blocking.
///
/// # Example
///
/// ```no_run
/// # use libracerd::{Config};
/// let mut cfg = Config::new();
/// cfg.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
///
/// let mut server = ::libracerd::http::serve(&cfg, engine).unwrap();
/// //... later
/// server.close().unwrap();
/// ```
///
pub fn serve<E: SemanticEngine +'static>(config: &Config, engine: E) -> Result<Server> {
use persistent::{Read, Write};
use logger::Logger;
use logger::format::Format;
let mut chain = Chain::new(router!(
post "/parse_file" => file::parse,
post "/find_definition" => definition::find,
post "/list_completions" => completion::list,
get "/ping" => ping::pong));
// Logging middleware
let log_fmt = Format::new("{method} {uri} -> {status} ({response-time})",
Vec::new(), Vec::new());
let (log_before, log_after) = Logger::new(log_fmt);
// log_before must be first middleware in before chain
if config.print_http_logs {
chain.link_before(log_before);
}
// Get HMAC Middleware
let (hmac_before, hmac_after) = if config.secret_file.is_some() {
let secret = SecretKey::new(&config.read_secret_file());
let hmac_header = "x-racerd-hmac";
let (before, after) = Hmac256Authentication::middleware(secret, hmac_header);
(Some(before), Some(after))
} else {
(None, None)
};
// This middleware provides a semantic engine to the request handlers
chain.link_before(Write::<EngineProvider>::one(Box::new(engine)));
// Body parser middlerware
chain.link_before(Read::<::bodyparser::MaxBodyLength>::one(1024 * 1024 * 10));
// Maybe link hmac middleware
if let Some(hmac) = hmac_before {
chain.link_before(hmac);
}
if let Some(hmac) = hmac_after {
chain.link_after(hmac);
}
// log_after must be last middleware in after chain
if config.print_http_logs {
chain.link_after(log_after);
}
let app = Iron::new(chain);
Ok(Server {
inner: try!(app.http((&config.addr[..], config.port)))
})
}
/// Wrapper type with information and control of the underlying HTTP server
///
/// This type can only be created via the [`serve`](fn.serve.html) function.
#[derive(Debug)]
pub struct Server {
inner: ::hyper::server::Listening,
}
impl Server {
/// Stop accepting connections
pub fn close(&mut self) -> Result<()> {
Ok(try!(self.inner.close()))
}
/// Get listening address of server (eg. "127.0.0.1:59369")
///
/// # Example
/// ```no_run
/// let mut config = ::libracerd::Config::new();
/// config.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
/// let server = ::libracerd::http::serve(&config, engine).unwrap();
///
/// assert_eq!(server.addr(), "0.0.0.0:3000");
/// ```
pub fn addr(&self) -> String {
format!("{}", self.inner.socket)
}
}
|
}
|
random_line_split
|
mod.rs
|
//! http server for semantic engines
use iron::prelude::*;
use ::Config;
mod definition;
mod file;
mod completion;
mod ping;
use ::engine::SemanticEngine;
use iron::typemap::Key;
use iron_hmac::Hmac256Authentication;
use iron_hmac::SecretKey;
/// Errors occurring in the http module
#[derive(Debug)]
pub enum Error {
/// Error occurred in underlying http server lib
HttpServer(::hyper::Error),
// Error occurred in http framework layer
// HttpApp(::iron::IronError),
}
impl From<::hyper::Error> for Error {
fn from(err: ::hyper::Error) -> Error {
Error::HttpServer(err)
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
// -------------------------------------------------------------------------------------------------
/// Iron middleware responsible for attaching a semantic engine to each request
#[derive(Debug, Clone)]
pub struct EngineProvider;
impl Key for EngineProvider {
type Value = Box<SemanticEngine + Send + Sync>;
}
// -------------------------------------------------------------------------------------------------
/// Start the http server using the given configuration
///
/// `serve` is non-blocking.
///
/// # Example
///
/// ```no_run
/// # use libracerd::{Config};
/// let mut cfg = Config::new();
/// cfg.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
///
/// let mut server = ::libracerd::http::serve(&cfg, engine).unwrap();
/// //... later
/// server.close().unwrap();
/// ```
///
pub fn serve<E: SemanticEngine +'static>(config: &Config, engine: E) -> Result<Server>
|
// Get HMAC Middleware
let (hmac_before, hmac_after) = if config.secret_file.is_some() {
let secret = SecretKey::new(&config.read_secret_file());
let hmac_header = "x-racerd-hmac";
let (before, after) = Hmac256Authentication::middleware(secret, hmac_header);
(Some(before), Some(after))
} else {
(None, None)
};
// This middleware provides a semantic engine to the request handlers
chain.link_before(Write::<EngineProvider>::one(Box::new(engine)));
// Body parser middlerware
chain.link_before(Read::<::bodyparser::MaxBodyLength>::one(1024 * 1024 * 10));
// Maybe link hmac middleware
if let Some(hmac) = hmac_before {
chain.link_before(hmac);
}
if let Some(hmac) = hmac_after {
chain.link_after(hmac);
}
// log_after must be last middleware in after chain
if config.print_http_logs {
chain.link_after(log_after);
}
let app = Iron::new(chain);
Ok(Server {
inner: try!(app.http((&config.addr[..], config.port)))
})
}
/// Wrapper type with information and control of the underlying HTTP server
///
/// This type can only be created via the [`serve`](fn.serve.html) function.
#[derive(Debug)]
pub struct Server {
inner: ::hyper::server::Listening,
}
impl Server {
/// Stop accepting connections
pub fn close(&mut self) -> Result<()> {
Ok(try!(self.inner.close()))
}
/// Get listening address of server (eg. "127.0.0.1:59369")
///
/// # Example
/// ```no_run
/// let mut config = ::libracerd::Config::new();
/// config.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
/// let server = ::libracerd::http::serve(&config, engine).unwrap();
///
/// assert_eq!(server.addr(), "0.0.0.0:3000");
/// ```
pub fn addr(&self) -> String {
format!("{}", self.inner.socket)
}
}
|
{
use persistent::{Read, Write};
use logger::Logger;
use logger::format::Format;
let mut chain = Chain::new(router!(
post "/parse_file" => file::parse,
post "/find_definition" => definition::find,
post "/list_completions" => completion::list,
get "/ping" => ping::pong));
// Logging middleware
let log_fmt = Format::new("{method} {uri} -> {status} ({response-time})",
Vec::new(), Vec::new());
let (log_before, log_after) = Logger::new(log_fmt);
// log_before must be first middleware in before chain
if config.print_http_logs {
chain.link_before(log_before);
}
|
identifier_body
|
example_with_default_router.rs
|
extern crate serialize;
extern crate nickel;
extern crate http;
use nickel::{Nickel, Request, Response, HttpRouter};
use std::io::net::ip::Ipv4Addr;
fn main() {
let mut server = Nickel::new();
fn
|
(_request: &Request, response: &mut Response) {
response.send("This is the /bar handler");
}
// go to http://localhost:6767/bar to see this route in action
server.get("/bar", bar_handler);
fn foo_handler (request: &Request, _response: &mut Response) -> String {
format!("Foo is '{}'", request.param("foo"))
}
// go to http://localhost:6767/foo to see this route in action
server.get("/:foo", foo_handler);
server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
}
|
bar_handler
|
identifier_name
|
example_with_default_router.rs
|
extern crate serialize;
extern crate nickel;
extern crate http;
use nickel::{Nickel, Request, Response, HttpRouter};
use std::io::net::ip::Ipv4Addr;
fn main() {
|
fn bar_handler (_request: &Request, response: &mut Response) {
response.send("This is the /bar handler");
}
// go to http://localhost:6767/bar to see this route in action
server.get("/bar", bar_handler);
fn foo_handler (request: &Request, _response: &mut Response) -> String {
format!("Foo is '{}'", request.param("foo"))
}
// go to http://localhost:6767/foo to see this route in action
server.get("/:foo", foo_handler);
server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
}
|
let mut server = Nickel::new();
|
random_line_split
|
example_with_default_router.rs
|
extern crate serialize;
extern crate nickel;
extern crate http;
use nickel::{Nickel, Request, Response, HttpRouter};
use std::io::net::ip::Ipv4Addr;
fn main()
|
{
let mut server = Nickel::new();
fn bar_handler (_request: &Request, response: &mut Response) {
response.send("This is the /bar handler");
}
// go to http://localhost:6767/bar to see this route in action
server.get("/bar", bar_handler);
fn foo_handler (request: &Request, _response: &mut Response) -> String {
format!("Foo is '{}'", request.param("foo"))
}
// go to http://localhost:6767/foo to see this route in action
server.get("/:foo", foo_handler);
server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
}
|
identifier_body
|
|
basic-types-metadata.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.
// min-lldb-version: 310
// compile-flags:-g
// gdb-command:run
// gdb-command:whatis unit
// gdb-check:type = ()
// gdb-command:whatis b
// gdb-check:type = bool
// gdb-command:whatis i
// gdb-check:type = isize
// gdb-command:whatis c
// gdb-check:type = char
// gdb-command:whatis i8
// gdb-check:type = i8
// gdb-command:whatis i16
// gdb-check:type = i16
// gdb-command:whatis i32
// gdb-check:type = i32
// gdb-command:whatis i64
// gdb-check:type = i64
// gdb-command:whatis u
// gdb-check:type = usize
// gdb-command:whatis u8
// gdb-check:type = u8
// gdb-command:whatis u16
// gdb-check:type = u16
// gdb-command:whatis u32
// gdb-check:type = u32
// gdb-command:whatis u64
// gdb-check:type = u64
// gdb-command:whatis f32
// gdb-check:type = f32
// gdb-command:whatis f64
// gdb-check:type = f64
// gdb-command:info functions _yyy
// gdb-check:[...]![...]_yyy([...])([...]);
// gdb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn main() {
let unit: () = ();
let b: bool = false;
let i: isize = -1;
let c: char = 'a';
let i8: i8 = 68;
let i16: i16 = -16;
let i32: i32 = -32;
let i64: i64 = -64;
let u: usize = 1;
let u8: u8 = 100;
let u16: u16 = 16;
let u32: u32 = 32;
let u64: u64 = 64;
let f32: f32 = 2.5;
let f64: f64 = 3.5;
_zzz(); // #break
if 1 == 1 { _yyy(); }
}
fn _zzz() {()}
fn _yyy() ->!
|
{panic!()}
|
identifier_body
|
|
basic-types-metadata.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.
// min-lldb-version: 310
|
// gdb-check:type = ()
// gdb-command:whatis b
// gdb-check:type = bool
// gdb-command:whatis i
// gdb-check:type = isize
// gdb-command:whatis c
// gdb-check:type = char
// gdb-command:whatis i8
// gdb-check:type = i8
// gdb-command:whatis i16
// gdb-check:type = i16
// gdb-command:whatis i32
// gdb-check:type = i32
// gdb-command:whatis i64
// gdb-check:type = i64
// gdb-command:whatis u
// gdb-check:type = usize
// gdb-command:whatis u8
// gdb-check:type = u8
// gdb-command:whatis u16
// gdb-check:type = u16
// gdb-command:whatis u32
// gdb-check:type = u32
// gdb-command:whatis u64
// gdb-check:type = u64
// gdb-command:whatis f32
// gdb-check:type = f32
// gdb-command:whatis f64
// gdb-check:type = f64
// gdb-command:info functions _yyy
// gdb-check:[...]![...]_yyy([...])([...]);
// gdb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn main() {
let unit: () = ();
let b: bool = false;
let i: isize = -1;
let c: char = 'a';
let i8: i8 = 68;
let i16: i16 = -16;
let i32: i32 = -32;
let i64: i64 = -64;
let u: usize = 1;
let u8: u8 = 100;
let u16: u16 = 16;
let u32: u32 = 32;
let u64: u64 = 64;
let f32: f32 = 2.5;
let f64: f64 = 3.5;
_zzz(); // #break
if 1 == 1 { _yyy(); }
}
fn _zzz() {()}
fn _yyy() ->! {panic!()}
|
// compile-flags:-g
// gdb-command:run
// gdb-command:whatis unit
|
random_line_split
|
basic-types-metadata.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.
// min-lldb-version: 310
// compile-flags:-g
// gdb-command:run
// gdb-command:whatis unit
// gdb-check:type = ()
// gdb-command:whatis b
// gdb-check:type = bool
// gdb-command:whatis i
// gdb-check:type = isize
// gdb-command:whatis c
// gdb-check:type = char
// gdb-command:whatis i8
// gdb-check:type = i8
// gdb-command:whatis i16
// gdb-check:type = i16
// gdb-command:whatis i32
// gdb-check:type = i32
// gdb-command:whatis i64
// gdb-check:type = i64
// gdb-command:whatis u
// gdb-check:type = usize
// gdb-command:whatis u8
// gdb-check:type = u8
// gdb-command:whatis u16
// gdb-check:type = u16
// gdb-command:whatis u32
// gdb-check:type = u32
// gdb-command:whatis u64
// gdb-check:type = u64
// gdb-command:whatis f32
// gdb-check:type = f32
// gdb-command:whatis f64
// gdb-check:type = f64
// gdb-command:info functions _yyy
// gdb-check:[...]![...]_yyy([...])([...]);
// gdb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn main() {
let unit: () = ();
let b: bool = false;
let i: isize = -1;
let c: char = 'a';
let i8: i8 = 68;
let i16: i16 = -16;
let i32: i32 = -32;
let i64: i64 = -64;
let u: usize = 1;
let u8: u8 = 100;
let u16: u16 = 16;
let u32: u32 = 32;
let u64: u64 = 64;
let f32: f32 = 2.5;
let f64: f64 = 3.5;
_zzz(); // #break
if 1 == 1
|
}
fn _zzz() {()}
fn _yyy() ->! {panic!()}
|
{ _yyy(); }
|
conditional_block
|
basic-types-metadata.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.
// min-lldb-version: 310
// compile-flags:-g
// gdb-command:run
// gdb-command:whatis unit
// gdb-check:type = ()
// gdb-command:whatis b
// gdb-check:type = bool
// gdb-command:whatis i
// gdb-check:type = isize
// gdb-command:whatis c
// gdb-check:type = char
// gdb-command:whatis i8
// gdb-check:type = i8
// gdb-command:whatis i16
// gdb-check:type = i16
// gdb-command:whatis i32
// gdb-check:type = i32
// gdb-command:whatis i64
// gdb-check:type = i64
// gdb-command:whatis u
// gdb-check:type = usize
// gdb-command:whatis u8
// gdb-check:type = u8
// gdb-command:whatis u16
// gdb-check:type = u16
// gdb-command:whatis u32
// gdb-check:type = u32
// gdb-command:whatis u64
// gdb-check:type = u64
// gdb-command:whatis f32
// gdb-check:type = f32
// gdb-command:whatis f64
// gdb-check:type = f64
// gdb-command:info functions _yyy
// gdb-check:[...]![...]_yyy([...])([...]);
// gdb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn main() {
let unit: () = ();
let b: bool = false;
let i: isize = -1;
let c: char = 'a';
let i8: i8 = 68;
let i16: i16 = -16;
let i32: i32 = -32;
let i64: i64 = -64;
let u: usize = 1;
let u8: u8 = 100;
let u16: u16 = 16;
let u32: u32 = 32;
let u64: u64 = 64;
let f32: f32 = 2.5;
let f64: f64 = 3.5;
_zzz(); // #break
if 1 == 1 { _yyy(); }
}
fn _zzz() {()}
fn
|
() ->! {panic!()}
|
_yyy
|
identifier_name
|
build.rs
|
use std::env;
use std::process::Command;
use std::str::{self, FromStr};
fn
|
() {
// Decide ideal limb width for arithmetic in the float parser. Refer to
// src/lexical/math.rs for where this has an effect.
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
match target_arch.as_str() {
"aarch64" | "mips64" | "powerpc64" | "x86_64" => {
println!("cargo:rustc-cfg=limb_width_64");
}
_ => {
println!("cargo:rustc-cfg=limb_width_32");
}
}
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
// BTreeMap::get_key_value
// https://blog.rust-lang.org/2019/12/19/Rust-1.40.0.html#additions-to-the-standard-library
if minor < 40 {
println!("cargo:rustc-cfg=no_btreemap_get_key_value");
}
// BTreeMap::remove_entry
// https://blog.rust-lang.org/2020/07/16/Rust-1.45.0.html#library-changes
if minor < 45 {
println!("cargo:rustc-cfg=no_btreemap_remove_entry");
}
// BTreeMap::retain
// https://blog.rust-lang.org/2021/06/17/Rust-1.53.0.html#stabilized-apis
if minor < 53 {
println!("cargo:rustc-cfg=no_btreemap_retain");
}
}
fn rustc_minor_version() -> Option<u32> {
let rustc = env::var_os("RUSTC")?;
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next()!= Some("rustc 1") {
return None;
}
let next = pieces.next()?;
u32::from_str(next).ok()
}
|
main
|
identifier_name
|
build.rs
|
use std::env;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
// Decide ideal limb width for arithmetic in the float parser. Refer to
// src/lexical/math.rs for where this has an effect.
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
match target_arch.as_str() {
"aarch64" | "mips64" | "powerpc64" | "x86_64" => {
println!("cargo:rustc-cfg=limb_width_64");
}
_ => {
println!("cargo:rustc-cfg=limb_width_32");
}
}
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
// BTreeMap::get_key_value
// https://blog.rust-lang.org/2019/12/19/Rust-1.40.0.html#additions-to-the-standard-library
if minor < 40 {
println!("cargo:rustc-cfg=no_btreemap_get_key_value");
}
// BTreeMap::remove_entry
// https://blog.rust-lang.org/2020/07/16/Rust-1.45.0.html#library-changes
if minor < 45 {
println!("cargo:rustc-cfg=no_btreemap_remove_entry");
}
|
}
fn rustc_minor_version() -> Option<u32> {
let rustc = env::var_os("RUSTC")?;
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next()!= Some("rustc 1") {
return None;
}
let next = pieces.next()?;
u32::from_str(next).ok()
}
|
// BTreeMap::retain
// https://blog.rust-lang.org/2021/06/17/Rust-1.53.0.html#stabilized-apis
if minor < 53 {
println!("cargo:rustc-cfg=no_btreemap_retain");
}
|
random_line_split
|
build.rs
|
use std::env;
use std::process::Command;
use std::str::{self, FromStr};
fn main()
|
if minor < 40 {
println!("cargo:rustc-cfg=no_btreemap_get_key_value");
}
// BTreeMap::remove_entry
// https://blog.rust-lang.org/2020/07/16/Rust-1.45.0.html#library-changes
if minor < 45 {
println!("cargo:rustc-cfg=no_btreemap_remove_entry");
}
// BTreeMap::retain
// https://blog.rust-lang.org/2021/06/17/Rust-1.53.0.html#stabilized-apis
if minor < 53 {
println!("cargo:rustc-cfg=no_btreemap_retain");
}
}
fn rustc_minor_version() -> Option<u32> {
let rustc = env::var_os("RUSTC")?;
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next()!= Some("rustc 1") {
return None;
}
let next = pieces.next()?;
u32::from_str(next).ok()
}
|
{
// Decide ideal limb width for arithmetic in the float parser. Refer to
// src/lexical/math.rs for where this has an effect.
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
match target_arch.as_str() {
"aarch64" | "mips64" | "powerpc64" | "x86_64" => {
println!("cargo:rustc-cfg=limb_width_64");
}
_ => {
println!("cargo:rustc-cfg=limb_width_32");
}
}
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
// BTreeMap::get_key_value
// https://blog.rust-lang.org/2019/12/19/Rust-1.40.0.html#additions-to-the-standard-library
|
identifier_body
|
build.rs
|
use std::env;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
// Decide ideal limb width for arithmetic in the float parser. Refer to
// src/lexical/math.rs for where this has an effect.
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
match target_arch.as_str() {
"aarch64" | "mips64" | "powerpc64" | "x86_64" => {
println!("cargo:rustc-cfg=limb_width_64");
}
_ => {
println!("cargo:rustc-cfg=limb_width_32");
}
}
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
// BTreeMap::get_key_value
// https://blog.rust-lang.org/2019/12/19/Rust-1.40.0.html#additions-to-the-standard-library
if minor < 40 {
println!("cargo:rustc-cfg=no_btreemap_get_key_value");
}
// BTreeMap::remove_entry
// https://blog.rust-lang.org/2020/07/16/Rust-1.45.0.html#library-changes
if minor < 45 {
println!("cargo:rustc-cfg=no_btreemap_remove_entry");
}
// BTreeMap::retain
// https://blog.rust-lang.org/2021/06/17/Rust-1.53.0.html#stabilized-apis
if minor < 53 {
println!("cargo:rustc-cfg=no_btreemap_retain");
}
}
fn rustc_minor_version() -> Option<u32> {
let rustc = env::var_os("RUSTC")?;
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next()!= Some("rustc 1")
|
let next = pieces.next()?;
u32::from_str(next).ok()
}
|
{
return None;
}
|
conditional_block
|
mod.rs
|
//! API for tracing applications and libraries.
//!
//! The `trace` module includes types for tracking the progression of a single
//! request while it is handled by services that make up an application. A trace
//! is a tree of [`Span`]s which are objects that represent the work being done
//! by individual services or components involved in a request as it flows
//! through a system. This module implements the OpenTelemetry [trace
//! specification].
//!
//! [trace specification]: https://github.com/open-telemetry/opentelemetry-specification/blob/v1.3.0/specification/trace/api.md
//!
//! ## Getting Started
//!
//! ```
//! use opentelemetry_api::{global, trace::{Span, Tracer, TracerProvider}};
//!
//! fn my_library_function() {
//! // Use the global tracer provider to get access to the user-specified
//! // tracer configuration
//! let tracer_provider = global::tracer_provider();
//!
//! // Get a tracer for this library
//! let tracer = tracer_provider.versioned_tracer(
//! "my_name",
//! Some(env!("CARGO_PKG_VERSION")),
//! None
//! );
//!
//! // Create spans
//! let mut span = tracer.start("doing_work");
//!
//! // Do work...
//!
//! // End the span
//! span.end();
//! }
//! ```
//!
//! ## Overview
//!
//! The tracing API consists of a three main traits:
//!
//! * [`TracerProvider`]s are the entry point of the API. They provide access to
//! `Tracer`s.
//! * [`Tracer`]s are types responsible for creating `Span`s.
//! * [`Span`]s provide the API to trace an operation.
//!
//! ## Working with Async Runtimes
//!
//! Exporting spans often involves sending data over a network or performing
//! other I/O tasks. OpenTelemetry allows you to schedule these tasks using
//! whichever runtime you area already using such as [Tokio] or [async-std].
//! When using an async runtime it's best to use the batch span processor
//! where the spans will be sent in batches as opposed to being sent once ended,
//! which often ends up being more efficient.
//!
//! [Tokio]: https://tokio.rs
//! [async-std]: https://async.rs
//!
//! ## Managing Active Spans
//!
//! Spans can be marked as "active" for a given [`Context`], and all newly
//! created spans will automatically be children of the currently active span.
//!
//! The active span for a given thread can be managed via [`get_active_span`]
//! and [`mark_span_as_active`].
//!
//! [`Context`]: crate::Context
//!
//! ```
//! use opentelemetry_api::{global, trace::{self, Span, StatusCode, Tracer, TracerProvider}};
//!
//! fn may_error(rand: f32) {
//! if rand < 0.5 {
//! // Get the currently active span to record additional attributes,
//! // status, etc.
//! trace::get_active_span(|span| {
//! span.set_status(StatusCode::Error, "value too small");
//! });
//! }
//! }
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Create a span
//! let span = tracer.start("parent_span");
//!
//! // Mark the span as active
//! let active = trace::mark_span_as_active(span);
//!
//! // Any span created here will be a child of `parent_span`...
//!
//! // Drop the guard and the span will no longer be active
//! drop(active)
//! ```
//!
//! Additionally [`Tracer::in_span`] can be used as shorthand to simplify
//! managing the parent context.
//!
//! ```
//! use opentelemetry_api::{global, trace::Tracer};
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Use `in_span` to create a new span and mark it as the parent, dropping it
//! // at the end of the block.
//! tracer.in_span("parent_span", |cx| {
//! // spans created here will be children of `parent_span`
//! });
//! ```
//!
//! #### Async active spans
//!
//! Async spans can be propagated with [`TraceContextExt`] and [`FutureExt`].
//!
//! ```
//! use opentelemetry_api::{Context, global, trace::{FutureExt, TraceContextExt, Tracer}};
//!
//! async fn some_work() { }
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Start a span
//! let span = tracer.start("my_span");
//!
//! // Perform some async work with this span as the currently active parent.
//! some_work().with_context(Context::current_with_span(span));
//! ```
use futures_channel::{mpsc::TrySendError, oneshot::Canceled};
use std::borrow::Cow;
use std::time;
use thiserror::Error;
mod context;
pub mod noop;
mod span;
mod span_context;
mod tracer;
mod tracer_provider;
pub use self::{
context::{get_active_span, mark_span_as_active, FutureExt, SpanRef, TraceContextExt},
span::{Span, SpanKind, StatusCode},
span_context::{SpanContext, SpanId, TraceFlags, TraceId, TraceState, TraceStateError},
tracer::{SamplingDecision, SamplingResult, SpanBuilder, Tracer},
tracer_provider::TracerProvider,
};
use crate::{ExportError, KeyValue};
/// Describe the result of operations in tracing API.
pub type TraceResult<T> = Result<T, TraceError>;
/// Errors returned by the trace API.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum TraceError {
/// Export failed with the error returned by the exporter
#[error("Exporter {} encountered the following error(s): {0}",.0.exporter_name())]
ExportFailed(Box<dyn ExportError>),
/// Export failed to finish after certain period and processor stopped the export.
#[error("Exporting timed out after {} seconds",.0.as_secs())]
ExportTimedOut(time::Duration),
/// Other errors propagated from trace SDK that weren't covered above
#[error(transparent)]
Other(#[from] Box<dyn std::error::Error + Send + Sync +'static>),
}
impl<T> From<T> for TraceError
where
T: ExportError,
{
fn from(err: T) -> Self {
TraceError::ExportFailed(Box::new(err))
}
}
impl<T> From<TrySendError<T>> for TraceError {
fn from(err: TrySendError<T>) -> Self {
TraceError::Other(Box::new(err.into_send_error()))
}
}
impl From<Canceled> for TraceError {
fn from(err: Canceled) -> Self {
TraceError::Other(Box::new(err))
}
}
impl From<String> for TraceError {
fn from(err_msg: String) -> Self {
TraceError::Other(Box::new(Custom(err_msg)))
}
}
impl From<&'static str> for TraceError {
fn from(err_msg: &'static str) -> Self {
TraceError::Other(Box::new(Custom(err_msg.into())))
}
}
/// Wrap type for string
#[derive(Error, Debug)]
#[error("{0}")]
struct Custom(String);
/// A `Span` has the ability to add events. Events have a time associated
/// with the moment when they are added to the `Span`.
#[derive(Clone, Debug, PartialEq)]
pub struct Event {
/// Event name
pub name: Cow<'static, str>,
/// Event timestamp
pub timestamp: time::SystemTime,
/// Event attributes
pub attributes: Vec<KeyValue>,
/// Number of dropped attributes
pub dropped_attributes_count: u32,
}
impl Event {
/// Create new `Event`
pub fn new<T: Into<Cow<'static, str>>>(
name: T,
timestamp: time::SystemTime,
attributes: Vec<KeyValue>,
dropped_attributes_count: u32,
) -> Self {
Event {
name: name.into(),
timestamp,
attributes,
dropped_attributes_count,
}
}
/// Create new `Event` with a given name.
pub fn with_name<T: Into<Cow<'static, str>>>(name: T) -> Self {
Event {
name: name.into(),
|
timestamp: crate::time::now(),
attributes: Vec::new(),
dropped_attributes_count: 0,
}
}
}
/// During the `Span` creation user MUST have the ability to record links to other `Span`s. Linked
/// `Span`s can be from the same or a different trace.
#[derive(Clone, Debug, PartialEq)]
pub struct Link {
span_context: SpanContext,
/// Attributes describing this link
pub attributes: Vec<KeyValue>,
/// The number of attributes that were above the limit, and thus dropped.
pub dropped_attributes_count: u32,
}
impl Link {
/// Create a new link
pub fn new(span_context: SpanContext, attributes: Vec<KeyValue>) -> Self {
Link {
span_context,
attributes,
dropped_attributes_count: 0,
}
}
/// The span context of the linked span
pub fn span_context(&self) -> &SpanContext {
&self.span_context
}
/// Attributes of the span link
pub fn attributes(&self) -> &Vec<KeyValue> {
&self.attributes
}
/// Dropped attributes count
pub fn dropped_attributes_count(&self) -> u32 {
self.dropped_attributes_count
}
}
|
random_line_split
|
|
mod.rs
|
//! API for tracing applications and libraries.
//!
//! The `trace` module includes types for tracking the progression of a single
//! request while it is handled by services that make up an application. A trace
//! is a tree of [`Span`]s which are objects that represent the work being done
//! by individual services or components involved in a request as it flows
//! through a system. This module implements the OpenTelemetry [trace
//! specification].
//!
//! [trace specification]: https://github.com/open-telemetry/opentelemetry-specification/blob/v1.3.0/specification/trace/api.md
//!
//! ## Getting Started
//!
//! ```
//! use opentelemetry_api::{global, trace::{Span, Tracer, TracerProvider}};
//!
//! fn my_library_function() {
//! // Use the global tracer provider to get access to the user-specified
//! // tracer configuration
//! let tracer_provider = global::tracer_provider();
//!
//! // Get a tracer for this library
//! let tracer = tracer_provider.versioned_tracer(
//! "my_name",
//! Some(env!("CARGO_PKG_VERSION")),
//! None
//! );
//!
//! // Create spans
//! let mut span = tracer.start("doing_work");
//!
//! // Do work...
//!
//! // End the span
//! span.end();
//! }
//! ```
//!
//! ## Overview
//!
//! The tracing API consists of a three main traits:
//!
//! * [`TracerProvider`]s are the entry point of the API. They provide access to
//! `Tracer`s.
//! * [`Tracer`]s are types responsible for creating `Span`s.
//! * [`Span`]s provide the API to trace an operation.
//!
//! ## Working with Async Runtimes
//!
//! Exporting spans often involves sending data over a network or performing
//! other I/O tasks. OpenTelemetry allows you to schedule these tasks using
//! whichever runtime you area already using such as [Tokio] or [async-std].
//! When using an async runtime it's best to use the batch span processor
//! where the spans will be sent in batches as opposed to being sent once ended,
//! which often ends up being more efficient.
//!
//! [Tokio]: https://tokio.rs
//! [async-std]: https://async.rs
//!
//! ## Managing Active Spans
//!
//! Spans can be marked as "active" for a given [`Context`], and all newly
//! created spans will automatically be children of the currently active span.
//!
//! The active span for a given thread can be managed via [`get_active_span`]
//! and [`mark_span_as_active`].
//!
//! [`Context`]: crate::Context
//!
//! ```
//! use opentelemetry_api::{global, trace::{self, Span, StatusCode, Tracer, TracerProvider}};
//!
//! fn may_error(rand: f32) {
//! if rand < 0.5 {
//! // Get the currently active span to record additional attributes,
//! // status, etc.
//! trace::get_active_span(|span| {
//! span.set_status(StatusCode::Error, "value too small");
//! });
//! }
//! }
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Create a span
//! let span = tracer.start("parent_span");
//!
//! // Mark the span as active
//! let active = trace::mark_span_as_active(span);
//!
//! // Any span created here will be a child of `parent_span`...
//!
//! // Drop the guard and the span will no longer be active
//! drop(active)
//! ```
//!
//! Additionally [`Tracer::in_span`] can be used as shorthand to simplify
//! managing the parent context.
//!
//! ```
//! use opentelemetry_api::{global, trace::Tracer};
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Use `in_span` to create a new span and mark it as the parent, dropping it
//! // at the end of the block.
//! tracer.in_span("parent_span", |cx| {
//! // spans created here will be children of `parent_span`
//! });
//! ```
//!
//! #### Async active spans
//!
//! Async spans can be propagated with [`TraceContextExt`] and [`FutureExt`].
//!
//! ```
//! use opentelemetry_api::{Context, global, trace::{FutureExt, TraceContextExt, Tracer}};
//!
//! async fn some_work() { }
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Start a span
//! let span = tracer.start("my_span");
//!
//! // Perform some async work with this span as the currently active parent.
//! some_work().with_context(Context::current_with_span(span));
//! ```
use futures_channel::{mpsc::TrySendError, oneshot::Canceled};
use std::borrow::Cow;
use std::time;
use thiserror::Error;
mod context;
pub mod noop;
mod span;
mod span_context;
mod tracer;
mod tracer_provider;
pub use self::{
context::{get_active_span, mark_span_as_active, FutureExt, SpanRef, TraceContextExt},
span::{Span, SpanKind, StatusCode},
span_context::{SpanContext, SpanId, TraceFlags, TraceId, TraceState, TraceStateError},
tracer::{SamplingDecision, SamplingResult, SpanBuilder, Tracer},
tracer_provider::TracerProvider,
};
use crate::{ExportError, KeyValue};
/// Describe the result of operations in tracing API.
pub type TraceResult<T> = Result<T, TraceError>;
/// Errors returned by the trace API.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum TraceError {
/// Export failed with the error returned by the exporter
#[error("Exporter {} encountered the following error(s): {0}",.0.exporter_name())]
ExportFailed(Box<dyn ExportError>),
/// Export failed to finish after certain period and processor stopped the export.
#[error("Exporting timed out after {} seconds",.0.as_secs())]
ExportTimedOut(time::Duration),
/// Other errors propagated from trace SDK that weren't covered above
#[error(transparent)]
Other(#[from] Box<dyn std::error::Error + Send + Sync +'static>),
}
impl<T> From<T> for TraceError
where
T: ExportError,
{
fn from(err: T) -> Self {
TraceError::ExportFailed(Box::new(err))
}
}
impl<T> From<TrySendError<T>> for TraceError {
fn from(err: TrySendError<T>) -> Self {
TraceError::Other(Box::new(err.into_send_error()))
}
}
impl From<Canceled> for TraceError {
fn from(err: Canceled) -> Self {
TraceError::Other(Box::new(err))
}
}
impl From<String> for TraceError {
fn from(err_msg: String) -> Self {
TraceError::Other(Box::new(Custom(err_msg)))
}
}
impl From<&'static str> for TraceError {
fn from(err_msg: &'static str) -> Self {
TraceError::Other(Box::new(Custom(err_msg.into())))
}
}
/// Wrap type for string
#[derive(Error, Debug)]
#[error("{0}")]
struct Custom(String);
/// A `Span` has the ability to add events. Events have a time associated
/// with the moment when they are added to the `Span`.
#[derive(Clone, Debug, PartialEq)]
pub struct Event {
/// Event name
pub name: Cow<'static, str>,
/// Event timestamp
pub timestamp: time::SystemTime,
/// Event attributes
pub attributes: Vec<KeyValue>,
/// Number of dropped attributes
pub dropped_attributes_count: u32,
}
impl Event {
/// Create new `Event`
pub fn new<T: Into<Cow<'static, str>>>(
name: T,
timestamp: time::SystemTime,
attributes: Vec<KeyValue>,
dropped_attributes_count: u32,
) -> Self {
Event {
name: name.into(),
timestamp,
attributes,
dropped_attributes_count,
}
}
/// Create new `Event` with a given name.
pub fn with_name<T: Into<Cow<'static, str>>>(name: T) -> Self {
Event {
name: name.into(),
timestamp: crate::time::now(),
attributes: Vec::new(),
dropped_attributes_count: 0,
}
}
}
/// During the `Span` creation user MUST have the ability to record links to other `Span`s. Linked
/// `Span`s can be from the same or a different trace.
#[derive(Clone, Debug, PartialEq)]
pub struct Link {
span_context: SpanContext,
/// Attributes describing this link
pub attributes: Vec<KeyValue>,
/// The number of attributes that were above the limit, and thus dropped.
pub dropped_attributes_count: u32,
}
impl Link {
/// Create a new link
pub fn new(span_context: SpanContext, attributes: Vec<KeyValue>) -> Self
|
/// The span context of the linked span
pub fn span_context(&self) -> &SpanContext {
&self.span_context
}
/// Attributes of the span link
pub fn attributes(&self) -> &Vec<KeyValue> {
&self.attributes
}
/// Dropped attributes count
pub fn dropped_attributes_count(&self) -> u32 {
self.dropped_attributes_count
}
}
|
{
Link {
span_context,
attributes,
dropped_attributes_count: 0,
}
}
|
identifier_body
|
mod.rs
|
//! API for tracing applications and libraries.
//!
//! The `trace` module includes types for tracking the progression of a single
//! request while it is handled by services that make up an application. A trace
//! is a tree of [`Span`]s which are objects that represent the work being done
//! by individual services or components involved in a request as it flows
//! through a system. This module implements the OpenTelemetry [trace
//! specification].
//!
//! [trace specification]: https://github.com/open-telemetry/opentelemetry-specification/blob/v1.3.0/specification/trace/api.md
//!
//! ## Getting Started
//!
//! ```
//! use opentelemetry_api::{global, trace::{Span, Tracer, TracerProvider}};
//!
//! fn my_library_function() {
//! // Use the global tracer provider to get access to the user-specified
//! // tracer configuration
//! let tracer_provider = global::tracer_provider();
//!
//! // Get a tracer for this library
//! let tracer = tracer_provider.versioned_tracer(
//! "my_name",
//! Some(env!("CARGO_PKG_VERSION")),
//! None
//! );
//!
//! // Create spans
//! let mut span = tracer.start("doing_work");
//!
//! // Do work...
//!
//! // End the span
//! span.end();
//! }
//! ```
//!
//! ## Overview
//!
//! The tracing API consists of a three main traits:
//!
//! * [`TracerProvider`]s are the entry point of the API. They provide access to
//! `Tracer`s.
//! * [`Tracer`]s are types responsible for creating `Span`s.
//! * [`Span`]s provide the API to trace an operation.
//!
//! ## Working with Async Runtimes
//!
//! Exporting spans often involves sending data over a network or performing
//! other I/O tasks. OpenTelemetry allows you to schedule these tasks using
//! whichever runtime you area already using such as [Tokio] or [async-std].
//! When using an async runtime it's best to use the batch span processor
//! where the spans will be sent in batches as opposed to being sent once ended,
//! which often ends up being more efficient.
//!
//! [Tokio]: https://tokio.rs
//! [async-std]: https://async.rs
//!
//! ## Managing Active Spans
//!
//! Spans can be marked as "active" for a given [`Context`], and all newly
//! created spans will automatically be children of the currently active span.
//!
//! The active span for a given thread can be managed via [`get_active_span`]
//! and [`mark_span_as_active`].
//!
//! [`Context`]: crate::Context
//!
//! ```
//! use opentelemetry_api::{global, trace::{self, Span, StatusCode, Tracer, TracerProvider}};
//!
//! fn may_error(rand: f32) {
//! if rand < 0.5 {
//! // Get the currently active span to record additional attributes,
//! // status, etc.
//! trace::get_active_span(|span| {
//! span.set_status(StatusCode::Error, "value too small");
//! });
//! }
//! }
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Create a span
//! let span = tracer.start("parent_span");
//!
//! // Mark the span as active
//! let active = trace::mark_span_as_active(span);
//!
//! // Any span created here will be a child of `parent_span`...
//!
//! // Drop the guard and the span will no longer be active
//! drop(active)
//! ```
//!
//! Additionally [`Tracer::in_span`] can be used as shorthand to simplify
//! managing the parent context.
//!
//! ```
//! use opentelemetry_api::{global, trace::Tracer};
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Use `in_span` to create a new span and mark it as the parent, dropping it
//! // at the end of the block.
//! tracer.in_span("parent_span", |cx| {
//! // spans created here will be children of `parent_span`
//! });
//! ```
//!
//! #### Async active spans
//!
//! Async spans can be propagated with [`TraceContextExt`] and [`FutureExt`].
//!
//! ```
//! use opentelemetry_api::{Context, global, trace::{FutureExt, TraceContextExt, Tracer}};
//!
//! async fn some_work() { }
//!
//! // Get a tracer
//! let tracer = global::tracer("my_tracer");
//!
//! // Start a span
//! let span = tracer.start("my_span");
//!
//! // Perform some async work with this span as the currently active parent.
//! some_work().with_context(Context::current_with_span(span));
//! ```
use futures_channel::{mpsc::TrySendError, oneshot::Canceled};
use std::borrow::Cow;
use std::time;
use thiserror::Error;
mod context;
pub mod noop;
mod span;
mod span_context;
mod tracer;
mod tracer_provider;
pub use self::{
context::{get_active_span, mark_span_as_active, FutureExt, SpanRef, TraceContextExt},
span::{Span, SpanKind, StatusCode},
span_context::{SpanContext, SpanId, TraceFlags, TraceId, TraceState, TraceStateError},
tracer::{SamplingDecision, SamplingResult, SpanBuilder, Tracer},
tracer_provider::TracerProvider,
};
use crate::{ExportError, KeyValue};
/// Describe the result of operations in tracing API.
pub type TraceResult<T> = Result<T, TraceError>;
/// Errors returned by the trace API.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum
|
{
/// Export failed with the error returned by the exporter
#[error("Exporter {} encountered the following error(s): {0}",.0.exporter_name())]
ExportFailed(Box<dyn ExportError>),
/// Export failed to finish after certain period and processor stopped the export.
#[error("Exporting timed out after {} seconds",.0.as_secs())]
ExportTimedOut(time::Duration),
/// Other errors propagated from trace SDK that weren't covered above
#[error(transparent)]
Other(#[from] Box<dyn std::error::Error + Send + Sync +'static>),
}
impl<T> From<T> for TraceError
where
T: ExportError,
{
fn from(err: T) -> Self {
TraceError::ExportFailed(Box::new(err))
}
}
impl<T> From<TrySendError<T>> for TraceError {
fn from(err: TrySendError<T>) -> Self {
TraceError::Other(Box::new(err.into_send_error()))
}
}
impl From<Canceled> for TraceError {
fn from(err: Canceled) -> Self {
TraceError::Other(Box::new(err))
}
}
impl From<String> for TraceError {
fn from(err_msg: String) -> Self {
TraceError::Other(Box::new(Custom(err_msg)))
}
}
impl From<&'static str> for TraceError {
fn from(err_msg: &'static str) -> Self {
TraceError::Other(Box::new(Custom(err_msg.into())))
}
}
/// Wrap type for string
#[derive(Error, Debug)]
#[error("{0}")]
struct Custom(String);
/// A `Span` has the ability to add events. Events have a time associated
/// with the moment when they are added to the `Span`.
#[derive(Clone, Debug, PartialEq)]
pub struct Event {
/// Event name
pub name: Cow<'static, str>,
/// Event timestamp
pub timestamp: time::SystemTime,
/// Event attributes
pub attributes: Vec<KeyValue>,
/// Number of dropped attributes
pub dropped_attributes_count: u32,
}
impl Event {
/// Create new `Event`
pub fn new<T: Into<Cow<'static, str>>>(
name: T,
timestamp: time::SystemTime,
attributes: Vec<KeyValue>,
dropped_attributes_count: u32,
) -> Self {
Event {
name: name.into(),
timestamp,
attributes,
dropped_attributes_count,
}
}
/// Create new `Event` with a given name.
pub fn with_name<T: Into<Cow<'static, str>>>(name: T) -> Self {
Event {
name: name.into(),
timestamp: crate::time::now(),
attributes: Vec::new(),
dropped_attributes_count: 0,
}
}
}
/// During the `Span` creation user MUST have the ability to record links to other `Span`s. Linked
/// `Span`s can be from the same or a different trace.
#[derive(Clone, Debug, PartialEq)]
pub struct Link {
span_context: SpanContext,
/// Attributes describing this link
pub attributes: Vec<KeyValue>,
/// The number of attributes that were above the limit, and thus dropped.
pub dropped_attributes_count: u32,
}
impl Link {
/// Create a new link
pub fn new(span_context: SpanContext, attributes: Vec<KeyValue>) -> Self {
Link {
span_context,
attributes,
dropped_attributes_count: 0,
}
}
/// The span context of the linked span
pub fn span_context(&self) -> &SpanContext {
&self.span_context
}
/// Attributes of the span link
pub fn attributes(&self) -> &Vec<KeyValue> {
&self.attributes
}
/// Dropped attributes count
pub fn dropped_attributes_count(&self) -> u32 {
self.dropped_attributes_count
}
}
|
TraceError
|
identifier_name
|
lib.rs
|
/*!
A macro for declaring lazily evaluated statics.
Using this macro, it is possible to have `static`s that require code to be
executed at runtime in order to be initialized.
This includes anything requiring heap allocations, like vectors or hash maps,
as well as anything that requires function calls to be computed.
# Syntax
```ignore
lazy_static! {
[pub] static ref NAME_1: TYPE_1 = EXPR_1;
[pub] static ref NAME_2: TYPE_2 = EXPR_2;
...
[pub] static ref NAME_N: TYPE_N = EXPR_N;
}
```
Metadata (such as doc comments) is allowed on each ref.
# Semantic
For a given `static ref NAME: TYPE = EXPR;`, the macro generates a unique type that
implements `Deref<TYPE>` and stores it in a static with name `NAME`. (Metadata ends up
attaching to this type.)
On first deref, `EXPR` gets evaluated and stored internally, such that all further derefs
can return a reference to the same object.
Like regular `static mut`s, this macro only works for types that fulfill the `Sync`
trait.
# Example
Using the macro:
```rust
#[macro_use]
extern crate lazy_static;
use std::collections::HashMap;
lazy_static! {
static ref HASHMAP: HashMap<u32, &'static str> = {
let mut m = HashMap::new();
m.insert(0, "foo");
m.insert(1, "bar");
m.insert(2, "baz");
m
};
static ref COUNT: usize = HASHMAP.len();
static ref NUMBER: u32 = times_two(21);
}
fn times_two(n: u32) -> u32 { n * 2 }
fn main() {
println!("The map has {} entries.", *COUNT);
println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());
println!("A expensive calculation on a static results in: {}.", *NUMBER);
}
```
# Implementation details
The `Deref` implementation uses a hidden static variable that is guarded by a atomic check on each access. On stable Rust, the macro may need to allocate each static on the heap.
*/
#![cfg_attr(feature="nightly", feature(const_fn, allow_internal_unstable, core_intrinsics))]
#![no_std]
#[cfg(not(feature="nightly"))]
pub mod lazy;
#[cfg(all(feature="nightly", not(feature="spin_no_std")))]
#[path="nightly_lazy.rs"]
pub mod lazy;
#[cfg(all(feature="nightly", feature="spin_no_std"))]
#[path="core_lazy.rs"]
pub mod lazy;
pub use core::ops::Deref as __Deref;
#[macro_export]
#[cfg_attr(feature="nightly", allow_internal_unstable)]
macro_rules! lazy_static {
($(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
lazy_static!(@PRIV, $(#[$attr])* static ref $N : $T = $e; $($t)*);
};
($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
lazy_static!(@PUB, $(#[$attr])* static ref $N : $T = $e; $($t)*);
};
(@$VIS:ident, $(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
lazy_static!(@MAKE TY, $VIS, $(#[$attr])*, $N);
impl $crate::__Deref for $N {
type Target = $T;
#[allow(unsafe_code)]
fn deref<'a>(&'a self) -> &'a $T {
unsafe {
#[inline(always)]
fn __static_ref_initialize() -> $T { $e }
#[inline(always)]
unsafe fn __stability() -> &'static $T {
__lazy_static_create!(LAZY, $T);
LAZY.get(__static_ref_initialize)
|
}
}
}
lazy_static!($($t)*);
};
(@MAKE TY, PUB, $(#[$attr:meta])*, $N:ident) => {
#[allow(missing_copy_implementations)]
#[allow(non_camel_case_types)]
#[allow(dead_code)]
$(#[$attr])*
pub struct $N {__private_field: ()}
#[doc(hidden)]
pub static $N: $N = $N {__private_field: ()};
};
(@MAKE TY, PRIV, $(#[$attr:meta])*, $N:ident) => {
#[allow(missing_copy_implementations)]
#[allow(non_camel_case_types)]
#[allow(dead_code)]
$(#[$attr])*
struct $N {__private_field: ()}
#[doc(hidden)]
static $N: $N = $N {__private_field: ()};
};
() => ()
}
|
}
__stability()
|
random_line_split
|
key_templates.rs
|
// Copyright 2020 The Tink-Rust Authors
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides a registry of generator functions that return [`tink_proto::KeyTemplate`] objects.
use lazy_static::lazy_static;
use std::{collections::HashMap, sync::RwLock};
pub type KeyTemplateGenerator = fn() -> tink_proto::KeyTemplate;
lazy_static! {
/// Global registry of key template generator functions, indexed by template name.
static ref TEMPLATE_GENERATORS: RwLock<HashMap<String, KeyTemplateGenerator>> =
RwLock::new(HashMap::new());
}
/// Register a key template generator function by name.
pub fn register_template_generator(name: &str, generator: KeyTemplateGenerator) {
TEMPLATE_GENERATORS
.write()
.unwrap() // safe: lock
.insert(name.to_string(), generator);
}
/// Find a key template generator function by name.
pub fn get_template_generator(name: &str) -> Option<KeyTemplateGenerator> {
TEMPLATE_GENERATORS.read().unwrap().get(name).copied() // safe: lock
}
/// Return all available key template generator names.
pub fn template_names() -> Vec<String>
|
{
TEMPLATE_GENERATORS
.read()
.unwrap() // safe: lock
.keys()
.cloned()
.collect()
}
|
identifier_body
|
|
key_templates.rs
|
// Copyright 2020 The Tink-Rust Authors
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides a registry of generator functions that return [`tink_proto::KeyTemplate`] objects.
use lazy_static::lazy_static;
use std::{collections::HashMap, sync::RwLock};
pub type KeyTemplateGenerator = fn() -> tink_proto::KeyTemplate;
lazy_static! {
/// Global registry of key template generator functions, indexed by template name.
static ref TEMPLATE_GENERATORS: RwLock<HashMap<String, KeyTemplateGenerator>> =
RwLock::new(HashMap::new());
}
/// Register a key template generator function by name.
pub fn register_template_generator(name: &str, generator: KeyTemplateGenerator) {
TEMPLATE_GENERATORS
.write()
|
/// Find a key template generator function by name.
pub fn get_template_generator(name: &str) -> Option<KeyTemplateGenerator> {
TEMPLATE_GENERATORS.read().unwrap().get(name).copied() // safe: lock
}
/// Return all available key template generator names.
pub fn template_names() -> Vec<String> {
TEMPLATE_GENERATORS
.read()
.unwrap() // safe: lock
.keys()
.cloned()
.collect()
}
|
.unwrap() // safe: lock
.insert(name.to_string(), generator);
}
|
random_line_split
|
key_templates.rs
|
// Copyright 2020 The Tink-Rust Authors
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides a registry of generator functions that return [`tink_proto::KeyTemplate`] objects.
use lazy_static::lazy_static;
use std::{collections::HashMap, sync::RwLock};
pub type KeyTemplateGenerator = fn() -> tink_proto::KeyTemplate;
lazy_static! {
/// Global registry of key template generator functions, indexed by template name.
static ref TEMPLATE_GENERATORS: RwLock<HashMap<String, KeyTemplateGenerator>> =
RwLock::new(HashMap::new());
}
/// Register a key template generator function by name.
pub fn register_template_generator(name: &str, generator: KeyTemplateGenerator) {
TEMPLATE_GENERATORS
.write()
.unwrap() // safe: lock
.insert(name.to_string(), generator);
}
/// Find a key template generator function by name.
pub fn
|
(name: &str) -> Option<KeyTemplateGenerator> {
TEMPLATE_GENERATORS.read().unwrap().get(name).copied() // safe: lock
}
/// Return all available key template generator names.
pub fn template_names() -> Vec<String> {
TEMPLATE_GENERATORS
.read()
.unwrap() // safe: lock
.keys()
.cloned()
.collect()
}
|
get_template_generator
|
identifier_name
|
selection.rs
|
use crate::session::{Session, State, AES_IV_LEN};
use log::{debug, error};
use protocol::messages::connection::ServerSelectionMessage;
impl Session {
pub async fn select_server(&mut self, server_id: i16) -> std::io::Result<u8> {
use protocol::constants::server_connection_error;
use protocol::constants::server_status;
use protocol::messages::connection::SelectedServerDataMessage;
let (aes_key, ticket) = match &self.state {
State::Logged { aes_key, ticket } => (aes_key, ticket),
_ => return Ok(0),
};
let gs = match self.server.game_servers.get(&server_id) {
Some(gs) => gs,
None => return Ok(server_connection_error::NO_REASON),
};
if gs.status()!= server_status::ONLINE {
return Ok(server_connection_error::DUE_TO_STATUS);
}
let encrypted = match openssl::symm::encrypt(
openssl::symm::Cipher::aes_256_cbc(),
aes_key,
Some(&aes_key[..AES_IV_LEN]),
ticket.as_bytes(),
) {
Ok(encrypted) => encrypted,
Err(err) => {
error!("encryption error: {}", err);
return Ok(server_connection_error::NO_REASON);
}
};
debug!("server selected: {}, ticket = {}", gs.id(), ticket);
let ports = &[gs.port() as u32];
self.stream.write(SelectedServerDataMessage {
server_id: gs.id() as _,
address: gs.host(),
ports: std::borrow::Cow::Borrowed(ports),
can_create_new_character: true,
// Just convert from an `&[u8]` to an `&[i8]`.
ticket: unsafe {
std::slice::from_raw_parts(encrypted.as_ptr() as *const i8, encrypted.len())
},
})?;
self.stream.flush().await?;
self.stream.get_ref().shutdown(std::net::Shutdown::Both)?;
Ok(0)
}
pub async fn
|
<'a>(
&'a mut self,
msg: ServerSelectionMessage<'a>,
) -> std::io::Result<()> {
use protocol::messages::connection::SelectedServerRefusedMessage;
let reason = self.select_server(msg.server_id as _).await?;
if reason!= 0 {
self.stream
.send(SelectedServerRefusedMessage {
server_id: msg.server_id,
error: reason,
server_status: self
.server
.game_servers
.get(&(msg.server_id as _))
.map(|gs| gs.status())
.unwrap_or(0),
_phantom: std::marker::PhantomData,
})
.await?;
}
Ok(())
}
}
|
handle_server_selection
|
identifier_name
|
selection.rs
|
use crate::session::{Session, State, AES_IV_LEN};
use log::{debug, error};
use protocol::messages::connection::ServerSelectionMessage;
|
impl Session {
pub async fn select_server(&mut self, server_id: i16) -> std::io::Result<u8> {
use protocol::constants::server_connection_error;
use protocol::constants::server_status;
use protocol::messages::connection::SelectedServerDataMessage;
let (aes_key, ticket) = match &self.state {
State::Logged { aes_key, ticket } => (aes_key, ticket),
_ => return Ok(0),
};
let gs = match self.server.game_servers.get(&server_id) {
Some(gs) => gs,
None => return Ok(server_connection_error::NO_REASON),
};
if gs.status()!= server_status::ONLINE {
return Ok(server_connection_error::DUE_TO_STATUS);
}
let encrypted = match openssl::symm::encrypt(
openssl::symm::Cipher::aes_256_cbc(),
aes_key,
Some(&aes_key[..AES_IV_LEN]),
ticket.as_bytes(),
) {
Ok(encrypted) => encrypted,
Err(err) => {
error!("encryption error: {}", err);
return Ok(server_connection_error::NO_REASON);
}
};
debug!("server selected: {}, ticket = {}", gs.id(), ticket);
let ports = &[gs.port() as u32];
self.stream.write(SelectedServerDataMessage {
server_id: gs.id() as _,
address: gs.host(),
ports: std::borrow::Cow::Borrowed(ports),
can_create_new_character: true,
// Just convert from an `&[u8]` to an `&[i8]`.
ticket: unsafe {
std::slice::from_raw_parts(encrypted.as_ptr() as *const i8, encrypted.len())
},
})?;
self.stream.flush().await?;
self.stream.get_ref().shutdown(std::net::Shutdown::Both)?;
Ok(0)
}
pub async fn handle_server_selection<'a>(
&'a mut self,
msg: ServerSelectionMessage<'a>,
) -> std::io::Result<()> {
use protocol::messages::connection::SelectedServerRefusedMessage;
let reason = self.select_server(msg.server_id as _).await?;
if reason!= 0 {
self.stream
.send(SelectedServerRefusedMessage {
server_id: msg.server_id,
error: reason,
server_status: self
.server
.game_servers
.get(&(msg.server_id as _))
.map(|gs| gs.status())
.unwrap_or(0),
_phantom: std::marker::PhantomData,
})
.await?;
}
Ok(())
}
}
|
random_line_split
|
|
selection.rs
|
use crate::session::{Session, State, AES_IV_LEN};
use log::{debug, error};
use protocol::messages::connection::ServerSelectionMessage;
impl Session {
pub async fn select_server(&mut self, server_id: i16) -> std::io::Result<u8> {
use protocol::constants::server_connection_error;
use protocol::constants::server_status;
use protocol::messages::connection::SelectedServerDataMessage;
let (aes_key, ticket) = match &self.state {
State::Logged { aes_key, ticket } => (aes_key, ticket),
_ => return Ok(0),
};
let gs = match self.server.game_servers.get(&server_id) {
Some(gs) => gs,
None => return Ok(server_connection_error::NO_REASON),
};
if gs.status()!= server_status::ONLINE {
return Ok(server_connection_error::DUE_TO_STATUS);
}
let encrypted = match openssl::symm::encrypt(
openssl::symm::Cipher::aes_256_cbc(),
aes_key,
Some(&aes_key[..AES_IV_LEN]),
ticket.as_bytes(),
) {
Ok(encrypted) => encrypted,
Err(err) => {
error!("encryption error: {}", err);
return Ok(server_connection_error::NO_REASON);
}
};
debug!("server selected: {}, ticket = {}", gs.id(), ticket);
let ports = &[gs.port() as u32];
self.stream.write(SelectedServerDataMessage {
server_id: gs.id() as _,
address: gs.host(),
ports: std::borrow::Cow::Borrowed(ports),
can_create_new_character: true,
// Just convert from an `&[u8]` to an `&[i8]`.
ticket: unsafe {
std::slice::from_raw_parts(encrypted.as_ptr() as *const i8, encrypted.len())
},
})?;
self.stream.flush().await?;
self.stream.get_ref().shutdown(std::net::Shutdown::Both)?;
Ok(0)
}
pub async fn handle_server_selection<'a>(
&'a mut self,
msg: ServerSelectionMessage<'a>,
) -> std::io::Result<()>
|
}
}
|
{
use protocol::messages::connection::SelectedServerRefusedMessage;
let reason = self.select_server(msg.server_id as _).await?;
if reason != 0 {
self.stream
.send(SelectedServerRefusedMessage {
server_id: msg.server_id,
error: reason,
server_status: self
.server
.game_servers
.get(&(msg.server_id as _))
.map(|gs| gs.status())
.unwrap_or(0),
_phantom: std::marker::PhantomData,
})
.await?;
}
Ok(())
|
identifier_body
|
filter.rs
|
use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable};
use crate::ops::Try;
/// An iterator that filters the elements of `iter` with `predicate`.
///
/// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`filter`]: Iterator::filter
/// [`Iterator`]: trait.Iterator.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Clone)]
pub struct Filter<I, P> {
// Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
pub(crate) iter: I,
predicate: P,
}
impl<I, P> Filter<I, P> {
pub(in crate::iter) fn new(iter: I, predicate: P) -> Filter<I, P> {
Filter { iter, predicate }
}
}
#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Filter").field("iter", &self.iter).finish()
}
}
fn filter_fold<T, Acc>(
mut predicate: impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> Acc,
) -> impl FnMut(Acc, T) -> Acc {
move |acc, item| if predicate(&item) { fold(acc, item) } else
|
}
fn filter_try_fold<'a, T, Acc, R: Try<Output = Acc>>(
predicate: &'a mut impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> R + 'a,
) -> impl FnMut(Acc, T) -> R + 'a {
move |acc, item| if predicate(&item) { fold(acc, item) } else { try { acc } }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator, P> Iterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
self.iter.find(&mut self.predicate)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
// this special case allows the compiler to make `.filter(_).count()`
// branchless. Barring perfect branch prediction (which is unattainable in
// the general case), this will be much faster in >90% of cases (containing
// virtually all real workloads) and only a tiny bit slower in the rest.
//
// Having this specialization thus allows us to write `.filter(p).count()`
// where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
// less readable and also less backwards-compatible to Rust before 1.10.
//
// Using the branchless version will also simplify the LLVM byte code, thus
// leaving more budget for LLVM optimizations.
#[inline]
fn count(self) -> usize {
#[inline]
fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
move |x| predicate(&x) as usize
}
self.iter.map(to_usize(self.predicate)).sum()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.fold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
#[inline]
fn next_back(&mut self) -> Option<I::Item> {
self.iter.rfind(&mut self.predicate)
}
#[inline]
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.rfold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<S: Iterator, P, I: Iterator> SourceIter for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
I: SourceIter<Source = S>,
{
type Source = S;
#[inline]
unsafe fn as_inner(&mut self) -> &mut S {
// SAFETY: unsafe function forwarding to unsafe function with the same requirements
unsafe { SourceIter::as_inner(&mut self.iter) }
}
}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
|
{ acc }
|
conditional_block
|
filter.rs
|
use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable};
use crate::ops::Try;
/// An iterator that filters the elements of `iter` with `predicate`.
///
/// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`filter`]: Iterator::filter
/// [`Iterator`]: trait.Iterator.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Clone)]
pub struct Filter<I, P> {
// Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
pub(crate) iter: I,
predicate: P,
}
impl<I, P> Filter<I, P> {
pub(in crate::iter) fn new(iter: I, predicate: P) -> Filter<I, P> {
Filter { iter, predicate }
}
}
#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Filter").field("iter", &self.iter).finish()
}
}
fn filter_fold<T, Acc>(
mut predicate: impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> Acc,
) -> impl FnMut(Acc, T) -> Acc {
move |acc, item| if predicate(&item) { fold(acc, item) } else { acc }
}
fn filter_try_fold<'a, T, Acc, R: Try<Output = Acc>>(
predicate: &'a mut impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> R + 'a,
) -> impl FnMut(Acc, T) -> R + 'a {
move |acc, item| if predicate(&item) { fold(acc, item) } else { try { acc } }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator, P> Iterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
self.iter.find(&mut self.predicate)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
// this special case allows the compiler to make `.filter(_).count()`
// branchless. Barring perfect branch prediction (which is unattainable in
// the general case), this will be much faster in >90% of cases (containing
// virtually all real workloads) and only a tiny bit slower in the rest.
//
// Having this specialization thus allows us to write `.filter(p).count()`
// where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
// less readable and also less backwards-compatible to Rust before 1.10.
//
// Using the branchless version will also simplify the LLVM byte code, thus
// leaving more budget for LLVM optimizations.
#[inline]
fn count(self) -> usize {
#[inline]
fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
move |x| predicate(&x) as usize
}
self.iter.map(to_usize(self.predicate)).sum()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.fold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
#[inline]
fn next_back(&mut self) -> Option<I::Item> {
self.iter.rfind(&mut self.predicate)
}
#[inline]
fn
|
<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.rfold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<S: Iterator, P, I: Iterator> SourceIter for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
I: SourceIter<Source = S>,
{
type Source = S;
#[inline]
unsafe fn as_inner(&mut self) -> &mut S {
// SAFETY: unsafe function forwarding to unsafe function with the same requirements
unsafe { SourceIter::as_inner(&mut self.iter) }
}
}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
|
try_rfold
|
identifier_name
|
filter.rs
|
use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable};
use crate::ops::Try;
/// An iterator that filters the elements of `iter` with `predicate`.
///
/// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`filter`]: Iterator::filter
/// [`Iterator`]: trait.Iterator.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Clone)]
pub struct Filter<I, P> {
// Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
pub(crate) iter: I,
predicate: P,
}
impl<I, P> Filter<I, P> {
pub(in crate::iter) fn new(iter: I, predicate: P) -> Filter<I, P> {
Filter { iter, predicate }
|
}
}
#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Filter").field("iter", &self.iter).finish()
}
}
fn filter_fold<T, Acc>(
mut predicate: impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> Acc,
) -> impl FnMut(Acc, T) -> Acc {
move |acc, item| if predicate(&item) { fold(acc, item) } else { acc }
}
fn filter_try_fold<'a, T, Acc, R: Try<Output = Acc>>(
predicate: &'a mut impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> R + 'a,
) -> impl FnMut(Acc, T) -> R + 'a {
move |acc, item| if predicate(&item) { fold(acc, item) } else { try { acc } }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator, P> Iterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
self.iter.find(&mut self.predicate)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
// this special case allows the compiler to make `.filter(_).count()`
// branchless. Barring perfect branch prediction (which is unattainable in
// the general case), this will be much faster in >90% of cases (containing
// virtually all real workloads) and only a tiny bit slower in the rest.
//
// Having this specialization thus allows us to write `.filter(p).count()`
// where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
// less readable and also less backwards-compatible to Rust before 1.10.
//
// Using the branchless version will also simplify the LLVM byte code, thus
// leaving more budget for LLVM optimizations.
#[inline]
fn count(self) -> usize {
#[inline]
fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
move |x| predicate(&x) as usize
}
self.iter.map(to_usize(self.predicate)).sum()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.fold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
#[inline]
fn next_back(&mut self) -> Option<I::Item> {
self.iter.rfind(&mut self.predicate)
}
#[inline]
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.rfold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<S: Iterator, P, I: Iterator> SourceIter for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
I: SourceIter<Source = S>,
{
type Source = S;
#[inline]
unsafe fn as_inner(&mut self) -> &mut S {
// SAFETY: unsafe function forwarding to unsafe function with the same requirements
unsafe { SourceIter::as_inner(&mut self.iter) }
}
}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
|
random_line_split
|
|
filter.rs
|
use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable};
use crate::ops::Try;
/// An iterator that filters the elements of `iter` with `predicate`.
///
/// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`filter`]: Iterator::filter
/// [`Iterator`]: trait.Iterator.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Clone)]
pub struct Filter<I, P> {
// Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
pub(crate) iter: I,
predicate: P,
}
impl<I, P> Filter<I, P> {
pub(in crate::iter) fn new(iter: I, predicate: P) -> Filter<I, P> {
Filter { iter, predicate }
}
}
#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Filter").field("iter", &self.iter).finish()
}
}
fn filter_fold<T, Acc>(
mut predicate: impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> Acc,
) -> impl FnMut(Acc, T) -> Acc {
move |acc, item| if predicate(&item) { fold(acc, item) } else { acc }
}
fn filter_try_fold<'a, T, Acc, R: Try<Output = Acc>>(
predicate: &'a mut impl FnMut(&T) -> bool,
mut fold: impl FnMut(Acc, T) -> R + 'a,
) -> impl FnMut(Acc, T) -> R + 'a {
move |acc, item| if predicate(&item) { fold(acc, item) } else { try { acc } }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator, P> Iterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
self.iter.find(&mut self.predicate)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>)
|
// this special case allows the compiler to make `.filter(_).count()`
// branchless. Barring perfect branch prediction (which is unattainable in
// the general case), this will be much faster in >90% of cases (containing
// virtually all real workloads) and only a tiny bit slower in the rest.
//
// Having this specialization thus allows us to write `.filter(p).count()`
// where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
// less readable and also less backwards-compatible to Rust before 1.10.
//
// Using the branchless version will also simplify the LLVM byte code, thus
// leaving more budget for LLVM optimizations.
#[inline]
fn count(self) -> usize {
#[inline]
fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
move |x| predicate(&x) as usize
}
self.iter.map(to_usize(self.predicate)).sum()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.fold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
{
#[inline]
fn next_back(&mut self) -> Option<I::Item> {
self.iter.rfind(&mut self.predicate)
}
#[inline]
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Self: Sized,
Fold: FnMut(Acc, Self::Item) -> R,
R: Try<Output = Acc>,
{
self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
}
#[inline]
fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.iter.rfold(init, filter_fold(self.predicate, fold))
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<S: Iterator, P, I: Iterator> SourceIter for Filter<I, P>
where
P: FnMut(&I::Item) -> bool,
I: SourceIter<Source = S>,
{
type Source = S;
#[inline]
unsafe fn as_inner(&mut self) -> &mut S {
// SAFETY: unsafe function forwarding to unsafe function with the same requirements
unsafe { SourceIter::as_inner(&mut self.iter) }
}
}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
|
{
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
|
identifier_body
|
auto-ref-slice-plus-ref.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.
fn main() {
// Testing that method lookup does not automatically borrow
// vectors to slices then automatically create a &mut self
// reference. That would allow creating a mutable pointer to a
// temporary, which would be a source of confusion
let mut a = @[0];
a.test_mut(); //~ ERROR does not implement any method in scope named `test_mut`
}
trait MyIter {
fn test_mut(&mut self);
}
impl<'self> MyIter for &'self [int] {
fn test_mut(&mut self) { }
}
|
random_line_split
|
|
auto-ref-slice-plus-ref.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.
fn main()
|
trait MyIter {
fn test_mut(&mut self);
}
impl<'self> MyIter for &'self [int] {
fn test_mut(&mut self) { }
}
|
{
// Testing that method lookup does not automatically borrow
// vectors to slices then automatically create a &mut self
// reference. That would allow creating a mutable pointer to a
// temporary, which would be a source of confusion
let mut a = @[0];
a.test_mut(); //~ ERROR does not implement any method in scope named `test_mut`
}
|
identifier_body
|
auto-ref-slice-plus-ref.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.
fn main() {
// Testing that method lookup does not automatically borrow
// vectors to slices then automatically create a &mut self
// reference. That would allow creating a mutable pointer to a
// temporary, which would be a source of confusion
let mut a = @[0];
a.test_mut(); //~ ERROR does not implement any method in scope named `test_mut`
}
trait MyIter {
fn test_mut(&mut self);
}
impl<'self> MyIter for &'self [int] {
fn
|
(&mut self) { }
}
|
test_mut
|
identifier_name
|
palette.rs
|
pub mod rgba {
pub const ORIGINAL: [[u8; 4]; 16] = [
// normal
0x000000FF_u32.to_be_bytes(),
|
0xCD00CDFF_u32.to_be_bytes(),
0x00CD00FF_u32.to_be_bytes(),
0x00CDCDFF_u32.to_be_bytes(),
0xCDCD00FF_u32.to_be_bytes(),
0xCDCDCDFF_u32.to_be_bytes(),
// bright
0x000000FF_u32.to_be_bytes(),
0x0000FFFF_u32.to_be_bytes(),
0xFF0000FF_u32.to_be_bytes(),
0xFF00FFFF_u32.to_be_bytes(),
0x00FF00FF_u32.to_be_bytes(),
0x00FFFFFF_u32.to_be_bytes(),
0xFFFF00FF_u32.to_be_bytes(),
0xFFFFFFFF_u32.to_be_bytes(),
];
}
|
0x0000CDFF_u32.to_be_bytes(),
0xCD0000FF_u32.to_be_bytes(),
|
random_line_split
|
x86_64.rs
|
// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use serde::{Deserialize, Serialize};
use base::{error, Result};
use bit_field::*;
use downcast_rs::impl_downcast;
use vm_memory::GuestAddress;
use crate::{Hypervisor, IrqRoute, IrqSource, IrqSourceChip, Vcpu, Vm};
/// A trait for managing cpuids for an x86_64 hypervisor and for checking its capabilities.
pub trait HypervisorX86_64: Hypervisor {
/// Get the system supported CPUID values.
fn get_supported_cpuid(&self) -> Result<CpuId>;
/// Get the system emulated CPUID values.
fn get_emulated_cpuid(&self) -> Result<CpuId>;
/// Gets the list of supported MSRs.
fn get_msr_index_list(&self) -> Result<Vec<u32>>;
}
/// A wrapper for using a VM on x86_64 and getting/setting its state.
pub trait VmX86_64: Vm {
/// Gets the `HypervisorX86_64` that created this VM.
fn get_hypervisor(&self) -> &dyn HypervisorX86_64;
/// Create a Vcpu with the specified Vcpu ID.
fn create_vcpu(&self, id: usize) -> Result<Box<dyn VcpuX86_64>>;
/// Sets the address of the three-page region in the VM's address space.
fn set_tss_addr(&self, addr: GuestAddress) -> Result<()>;
/// Sets the address of a one-page region in the VM's address space.
fn set_identity_map_addr(&self, addr: GuestAddress) -> Result<()>;
}
/// A wrapper around creating and using a VCPU on x86_64.
pub trait VcpuX86_64: Vcpu {
/// Sets or clears the flag that requests the VCPU to exit when it becomes possible to inject
/// interrupts into the guest.
fn set_interrupt_window_requested(&self, requested: bool);
/// Checks if we can inject an interrupt into the VCPU.
fn ready_for_interrupt(&self) -> bool;
/// Injects interrupt vector `irq` into the VCPU.
fn interrupt(&self, irq: u32) -> Result<()>;
/// Injects a non-maskable interrupt into the VCPU.
fn inject_nmi(&self) -> Result<()>;
/// Gets the VCPU general purpose registers.
fn get_regs(&self) -> Result<Regs>;
/// Sets the VCPU general purpose registers.
fn set_regs(&self, regs: &Regs) -> Result<()>;
/// Gets the VCPU special registers.
fn get_sregs(&self) -> Result<Sregs>;
/// Sets the VCPU special registers.
fn set_sregs(&self, sregs: &Sregs) -> Result<()>;
/// Gets the VCPU FPU registers.
fn get_fpu(&self) -> Result<Fpu>;
/// Sets the VCPU FPU registers.
fn set_fpu(&self, fpu: &Fpu) -> Result<()>;
/// Gets the VCPU debug registers.
fn get_debugregs(&self) -> Result<DebugRegs>;
/// Sets the VCPU debug registers.
fn set_debugregs(&self, debugregs: &DebugRegs) -> Result<()>;
/// Gets the VCPU extended control registers.
fn get_xcrs(&self) -> Result<Vec<Register>>;
/// Sets the VCPU extended control registers.
fn set_xcrs(&self, xcrs: &[Register]) -> Result<()>;
/// Gets the model-specific registers. `msrs` specifies the MSR indexes to be queried, and
/// on success contains their indexes and values.
fn get_msrs(&self, msrs: &mut Vec<Register>) -> Result<()>;
/// Sets the model-specific registers.
fn set_msrs(&self, msrs: &[Register]) -> Result<()>;
/// Sets up the data returned by the CPUID instruction.
fn set_cpuid(&self, cpuid: &CpuId) -> Result<()>;
/// Gets the system emulated hyper-v CPUID values.
fn get_hyperv_cpuid(&self) -> Result<CpuId>;
/// Sets up debug registers and configure vcpu for handling guest debug events.
fn set_guest_debug(&self, addrs: &[GuestAddress], enable_singlestep: bool) -> Result<()>;
}
impl_downcast!(VcpuX86_64);
/// A CpuId Entry contains supported feature information for the given processor.
/// This can be modified by the hypervisor to pass additional information to the guest kernel
/// about the hypervisor or vm. Information is returned in the eax, ebx, ecx and edx registers
/// by the cpu for a given function and index/subfunction (passed into the cpu via the eax and ecx
/// register respectively).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CpuIdEntry {
pub function: u32,
pub index: u32,
// flags is needed for KVM. We store it on CpuIdEntry to preserve the flags across
// get_supported_cpuids() -> kvm_cpuid2 -> CpuId -> kvm_cpuid2 -> set_cpuid().
pub flags: u32,
pub eax: u32,
pub ebx: u32,
pub ecx: u32,
pub edx: u32,
}
/// A container for the list of cpu id entries for the hypervisor and underlying cpu.
pub struct CpuId {
pub cpu_id_entries: Vec<CpuIdEntry>,
}
impl CpuId {
/// Constructs a new CpuId, with space allocated for `initial_capacity` CpuIdEntries.
pub fn new(initial_capacity: usize) -> Self {
CpuId {
cpu_id_entries: Vec::with_capacity(initial_capacity),
}
}
}
#[bitfield]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DestinationMode {
Physical = 0,
Logical = 1,
}
#[bitfield]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TriggerMode {
Edge = 0,
Level = 1,
}
#[bitfield]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryMode {
Fixed = 0b000,
Lowest = 0b001,
SMI = 0b010, // System management interrupt
RemoteRead = 0b011, // This is no longer supported by intel.
NMI = 0b100, // Non maskable interrupt
Init = 0b101,
Startup = 0b110,
External = 0b111,
}
// These MSI structures are for Intel's implementation of MSI. The PCI spec defines most of MSI,
// but the Intel spec defines the format of messages for raising interrupts. The PCI spec defines
// three u32s -- the address, address_high, and data -- but Intel only makes use of the address and
// data. The Intel portion of the specification is in Volume 3 section 10.11.
#[bitfield]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct MsiAddressMessage {
pub reserved: BitField2,
#[bits = 1]
pub destination_mode: DestinationMode,
pub redirection_hint: BitField1,
pub reserved_2: BitField8,
pub destination_id: BitField8,
// According to Intel's implementation of MSI, these bits must always be 0xfee.
pub always_0xfee: BitField12,
}
#[bitfield]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct MsiDataMessage {
pub vector: BitField8,
#[bits = 3]
pub delivery_mode: DeliveryMode,
pub reserved: BitField3,
#[bits = 1]
pub level: Level,
#[bits = 1]
pub trigger: TriggerMode,
pub reserved2: BitField16,
}
#[bitfield]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryStatus {
Idle = 0,
Pending = 1,
}
/// The level of a level-triggered interrupt: asserted or deasserted.
#[bitfield]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
Deassert = 0,
Assert = 1,
}
/// Represents a IOAPIC redirection table entry.
#[bitfield]
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct IoapicRedirectionTableEntry {
vector: BitField8,
#[bits = 3]
delivery_mode: DeliveryMode,
#[bits = 1]
dest_mode: DestinationMode,
#[bits = 1]
delivery_status: DeliveryStatus,
polarity: BitField1,
remote_irr: bool,
#[bits = 1]
trigger_mode: TriggerMode,
interrupt_mask: bool, // true iff interrupts are masked.
reserved: BitField39,
dest_id: BitField8,
}
/// Number of pins on the standard KVM/IOAPIC.
pub const NUM_IOAPIC_PINS: usize = 24;
/// Maximum number of pins on the IOAPIC.
pub const MAX_IOAPIC_PINS: usize = 120;
/// Represents the state of the IOAPIC.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IoapicState {
/// base_address is the memory base address for this IOAPIC. It cannot be changed.
pub base_address: u64,
/// ioregsel register. Used for selecting which entry of the redirect table to read/write.
pub ioregsel: u8,
/// ioapicid register. Bits 24 - 27 contain the APIC ID for this device.
pub ioapicid: u32,
/// current_interrupt_level_bitmap represents a bitmap of the state of all of the irq lines
pub current_interrupt_level_bitmap: u32,
/// redirect_table contains the irq settings for each irq line
pub redirect_table: [IoapicRedirectionTableEntry; 120],
}
impl Default for IoapicState {
fn default() -> IoapicState {
unsafe { std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PicSelect {
Primary = 0,
Secondary = 1,
}
#[repr(C)]
#[derive(enumn::N, Debug, Clone, Copy, PartialEq, Eq)]
pub enum PicInitState {
Icw1 = 0,
Icw2 = 1,
Icw3 = 2,
Icw4 = 3,
}
/// Convenience implementation for converting from a u8
impl From<u8> for PicInitState {
fn from(item: u8) -> Self {
PicInitState::n(item).unwrap_or_else(|| {
error!("Invalid PicInitState {}, setting to 0", item);
PicInitState::Icw1
})
}
}
impl Default for PicInitState {
fn default() -> Self {
PicInitState::Icw1
}
}
/// Represents the state of the PIC.
#[repr(C)]
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub struct PicState {
/// Edge detection.
pub last_irr: u8,
/// Interrupt Request Register.
pub irr: u8,
/// Interrupt Mask Register.
pub imr: u8,
/// Interrupt Service Register.
pub isr: u8,
/// Highest priority, for priority rotation.
pub priority_add: u8,
pub irq_base: u8,
pub read_reg_select: bool,
pub poll: bool,
pub special_mask: bool,
pub init_state: PicInitState,
pub auto_eoi: bool,
pub rotate_on_auto_eoi: bool,
pub special_fully_nested_mode: bool,
/// PIC takes either 3 or 4 bytes of initialization command word during
/// initialization. use_4_byte_icw is true if 4 bytes of ICW are needed.
pub use_4_byte_icw: bool,
/// "Edge/Level Control Registers", for edge trigger selection.
/// When a particular bit is set, the corresponding IRQ is in level-triggered mode. Otherwise it
/// is in edge-triggered mode.
pub elcr: u8,
pub elcr_mask: u8,
}
/// The LapicState represents the state of an x86 CPU's Local APIC.
/// The Local APIC consists of 64 128-bit registers, but only the first 32-bits of each register
/// can be used, so this structure only stores the first 32-bits of each register.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct LapicState {
pub regs: [LapicRegister; 64],
}
pub type LapicRegister = u32;
// rust arrays longer than 32 need custom implementations of Debug
impl std::fmt::Debug for LapicState {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
self.regs[..].fmt(formatter)
}
}
// rust arrays longer than 32 need custom implementations of PartialEq
impl PartialEq for LapicState {
fn eq(&self, other: &LapicState) -> bool {
self.regs[..] == other.regs[..]
}
}
// Lapic equality is reflexive, so we impl Eq
impl Eq for LapicState {}
/// The PitState represents the state of the PIT (aka the Programmable Interval Timer).
/// The state is simply the state of it's three channels.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PitState {
pub channels: [PitChannelState; 3],
/// Hypervisor-specific flags for setting the pit state.
pub flags: u32,
}
/// The PitRWMode enum represents the access mode of a PIT channel.
/// Reads and writes to the Pit happen over Port-mapped I/O, which happens one byte at a time,
/// but the count values and latch values are two bytes. So the access mode controls which of the
/// two bytes will be read when.
#[repr(C)]
#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq)]
pub enum PitRWMode {
/// None mode means that no access mode has been set.
None = 0,
/// Least mode means all reads/writes will read/write the least significant byte.
Least = 1,
/// Most mode means all reads/writes will read/write the most significant byte.
Most = 2,
/// Both mode means first the least significant byte will be read/written, then the
/// next read/write will read/write the most significant byte.
Both = 3,
}
/// Convenience implementation for converting from a u8
impl From<u8> for PitRWMode {
fn from(item: u8) -> Self {
PitRWMode::n(item).unwrap_or_else(|| {
error!("Invalid PitRWMode value {}, setting to 0", item);
PitRWMode::None
})
}
}
/// The PitRWState enum represents the state of reading to or writing from a channel.
/// This is related to the PitRWMode, it mainly gives more detail about the state of the channel
/// with respect to PitRWMode::Both.
#[repr(C)]
#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq)]
pub enum PitRWState {
/// None mode means that no access mode has been set.
None = 0,
/// LSB means that the channel is in PitRWMode::Least access mode.
LSB = 1,
/// MSB means that the channel is in PitRWMode::Most access mode.
MSB = 2,
/// Word0 means that the channel is in PitRWMode::Both mode, and the least sginificant byte
/// has not been read/written yet.
Word0 = 3,
/// Word1 means that the channel is in PitRWMode::Both mode and the least significant byte
/// has already been read/written, and the next byte to be read/written will be the most
/// significant byte.
Word1 = 4,
}
/// Convenience implementation for converting from a u8
impl From<u8> for PitRWState {
fn from(item: u8) -> Self {
PitRWState::n(item).unwrap_or_else(|| {
error!("Invalid PitRWState value {}, setting to 0", item);
PitRWState::None
})
}
}
/// The PitChannelState represents the state of one of the PIT's three counters.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PitChannelState {
/// The starting value for the counter.
pub count: u32,
/// Stores the channel count from the last time the count was latched.
pub latched_count: u16,
/// Indicates the PitRWState state of reading the latch value.
pub count_latched: PitRWState,
/// Indicates whether ReadBack status has been latched.
pub status_latched: bool,
/// Stores the channel status from the last time the status was latched. The status contains
/// information about the access mode of this channel, but changing those bits in the status
/// will not change the behavior of the pit.
pub status: u8,
/// Indicates the PitRWState state of reading the counter.
pub read_state: PitRWState,
/// Indicates the PitRWState state of writing the counter.
pub write_state: PitRWState,
/// Stores the value with which the counter was initialized. Counters are 16-
/// bit values with an effective range of 1-65536 (65536 represented by 0).
pub reload_value: u16,
/// The command access mode of this channel.
pub rw_mode: PitRWMode,
/// The operation mode of this channel.
pub mode: u8,
/// Whether or not we are in bcd mode. Not supported by KVM or crosvm's PIT implementation.
pub bcd: bool,
/// Value of the gate input pin. This only applies to channel 2.
pub gate: bool,
/// Nanosecond timestamp of when the count value was loaded.
pub count_load_time: u64,
}
// Convenience constructors for IrqRoutes
impl IrqRoute {
pub fn ioapic_irq_route(irq_num: u32) -> IrqRoute {
IrqRoute {
gsi: irq_num,
source: IrqSource::Irqchip {
chip: IrqSourceChip::Ioapic,
pin: irq_num,
},
}
}
pub fn pic_irq_route(id: IrqSourceChip, irq_num: u32) -> IrqRoute {
IrqRoute {
gsi: irq_num,
source: IrqSource::Irqchip {
chip: id,
pin: irq_num % 8,
},
}
}
}
/// State of a VCPU's general purpose registers.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct
|
{
pub rax: u64,
pub rbx: u64,
pub rcx: u64,
pub rdx: u64,
pub rsi: u64,
pub rdi: u64,
pub rsp: u64,
pub rbp: u64,
pub r8: u64,
pub r9: u64,
pub r10: u64,
pub r11: u64,
pub r12: u64,
pub r13: u64,
pub r14: u64,
pub r15: u64,
pub rip: u64,
pub rflags: u64,
}
/// State of a memory segment.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Segment {
pub base: u64,
pub limit: u32,
pub selector: u16,
pub type_: u8,
pub present: u8,
pub dpl: u8,
pub db: u8,
pub s: u8,
pub l: u8,
pub g: u8,
pub avl: u8,
}
/// State of a global descriptor table or interrupt descriptor table.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct DescriptorTable {
pub base: u64,
pub limit: u16,
}
/// State of a VCPU's special registers.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Sregs {
pub cs: Segment,
pub ds: Segment,
pub es: Segment,
pub fs: Segment,
pub gs: Segment,
pub ss: Segment,
pub tr: Segment,
pub ldt: Segment,
pub gdt: DescriptorTable,
pub idt: DescriptorTable,
pub cr0: u64,
pub cr2: u64,
pub cr3: u64,
pub cr4: u64,
pub cr8: u64,
pub efer: u64,
pub apic_base: u64,
/// A bitmap of pending external interrupts. At most one bit may be set. This interrupt has
/// been acknowledged by the APIC but not yet injected into the cpu core.
pub interrupt_bitmap: [u64; 4usize],
}
/// State of a VCPU's floating point unit.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Fpu {
pub fpr: [[u8; 16usize]; 8usize],
pub fcw: u16,
pub fsw: u16,
pub ftwx: u8,
pub last_opcode: u16,
pub last_ip: u64,
pub last_dp: u64,
pub xmm: [[u8; 16usize]; 16usize],
pub mxcsr: u32,
}
/// State of a VCPU's debug registers.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct DebugRegs {
pub db: [u64; 4usize],
pub dr6: u64,
pub dr7: u64,
}
/// State of one VCPU register. Currently used for MSRs and XCRs.
#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
pub struct Register {
pub id: u32,
pub value: u64,
}
|
Regs
|
identifier_name
|
x86_64.rs
|
// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use serde::{Deserialize, Serialize};
use base::{error, Result};
use bit_field::*;
use downcast_rs::impl_downcast;
use vm_memory::GuestAddress;
use crate::{Hypervisor, IrqRoute, IrqSource, IrqSourceChip, Vcpu, Vm};
/// A trait for managing cpuids for an x86_64 hypervisor and for checking its capabilities.
pub trait HypervisorX86_64: Hypervisor {
/// Get the system supported CPUID values.
fn get_supported_cpuid(&self) -> Result<CpuId>;
/// Get the system emulated CPUID values.
fn get_emulated_cpuid(&self) -> Result<CpuId>;
/// Gets the list of supported MSRs.
fn get_msr_index_list(&self) -> Result<Vec<u32>>;
}
/// A wrapper for using a VM on x86_64 and getting/setting its state.
pub trait VmX86_64: Vm {
/// Gets the `HypervisorX86_64` that created this VM.
fn get_hypervisor(&self) -> &dyn HypervisorX86_64;
/// Create a Vcpu with the specified Vcpu ID.
fn create_vcpu(&self, id: usize) -> Result<Box<dyn VcpuX86_64>>;
/// Sets the address of the three-page region in the VM's address space.
fn set_tss_addr(&self, addr: GuestAddress) -> Result<()>;
/// Sets the address of a one-page region in the VM's address space.
fn set_identity_map_addr(&self, addr: GuestAddress) -> Result<()>;
}
/// A wrapper around creating and using a VCPU on x86_64.
pub trait VcpuX86_64: Vcpu {
/// Sets or clears the flag that requests the VCPU to exit when it becomes possible to inject
/// interrupts into the guest.
fn set_interrupt_window_requested(&self, requested: bool);
/// Checks if we can inject an interrupt into the VCPU.
fn ready_for_interrupt(&self) -> bool;
/// Injects interrupt vector `irq` into the VCPU.
fn interrupt(&self, irq: u32) -> Result<()>;
/// Injects a non-maskable interrupt into the VCPU.
fn inject_nmi(&self) -> Result<()>;
/// Gets the VCPU general purpose registers.
fn get_regs(&self) -> Result<Regs>;
/// Sets the VCPU general purpose registers.
fn set_regs(&self, regs: &Regs) -> Result<()>;
/// Gets the VCPU special registers.
fn get_sregs(&self) -> Result<Sregs>;
/// Sets the VCPU special registers.
fn set_sregs(&self, sregs: &Sregs) -> Result<()>;
/// Gets the VCPU FPU registers.
fn get_fpu(&self) -> Result<Fpu>;
/// Sets the VCPU FPU registers.
fn set_fpu(&self, fpu: &Fpu) -> Result<()>;
/// Gets the VCPU debug registers.
fn get_debugregs(&self) -> Result<DebugRegs>;
/// Sets the VCPU debug registers.
fn set_debugregs(&self, debugregs: &DebugRegs) -> Result<()>;
/// Gets the VCPU extended control registers.
fn get_xcrs(&self) -> Result<Vec<Register>>;
/// Sets the VCPU extended control registers.
fn set_xcrs(&self, xcrs: &[Register]) -> Result<()>;
/// Gets the model-specific registers. `msrs` specifies the MSR indexes to be queried, and
/// on success contains their indexes and values.
fn get_msrs(&self, msrs: &mut Vec<Register>) -> Result<()>;
/// Sets the model-specific registers.
fn set_msrs(&self, msrs: &[Register]) -> Result<()>;
/// Sets up the data returned by the CPUID instruction.
fn set_cpuid(&self, cpuid: &CpuId) -> Result<()>;
/// Gets the system emulated hyper-v CPUID values.
fn get_hyperv_cpuid(&self) -> Result<CpuId>;
/// Sets up debug registers and configure vcpu for handling guest debug events.
fn set_guest_debug(&self, addrs: &[GuestAddress], enable_singlestep: bool) -> Result<()>;
}
impl_downcast!(VcpuX86_64);
/// A CpuId Entry contains supported feature information for the given processor.
/// This can be modified by the hypervisor to pass additional information to the guest kernel
/// about the hypervisor or vm. Information is returned in the eax, ebx, ecx and edx registers
/// by the cpu for a given function and index/subfunction (passed into the cpu via the eax and ecx
/// register respectively).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CpuIdEntry {
pub function: u32,
pub index: u32,
// flags is needed for KVM. We store it on CpuIdEntry to preserve the flags across
// get_supported_cpuids() -> kvm_cpuid2 -> CpuId -> kvm_cpuid2 -> set_cpuid().
pub flags: u32,
pub eax: u32,
pub ebx: u32,
pub ecx: u32,
pub edx: u32,
}
/// A container for the list of cpu id entries for the hypervisor and underlying cpu.
pub struct CpuId {
pub cpu_id_entries: Vec<CpuIdEntry>,
}
impl CpuId {
/// Constructs a new CpuId, with space allocated for `initial_capacity` CpuIdEntries.
pub fn new(initial_capacity: usize) -> Self {
CpuId {
cpu_id_entries: Vec::with_capacity(initial_capacity),
}
}
}
#[bitfield]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DestinationMode {
Physical = 0,
Logical = 1,
}
#[bitfield]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TriggerMode {
Edge = 0,
Level = 1,
}
#[bitfield]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryMode {
Fixed = 0b000,
Lowest = 0b001,
SMI = 0b010, // System management interrupt
RemoteRead = 0b011, // This is no longer supported by intel.
NMI = 0b100, // Non maskable interrupt
Init = 0b101,
Startup = 0b110,
External = 0b111,
}
// These MSI structures are for Intel's implementation of MSI. The PCI spec defines most of MSI,
// but the Intel spec defines the format of messages for raising interrupts. The PCI spec defines
// three u32s -- the address, address_high, and data -- but Intel only makes use of the address and
// data. The Intel portion of the specification is in Volume 3 section 10.11.
#[bitfield]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct MsiAddressMessage {
pub reserved: BitField2,
#[bits = 1]
pub destination_mode: DestinationMode,
pub redirection_hint: BitField1,
pub reserved_2: BitField8,
pub destination_id: BitField8,
// According to Intel's implementation of MSI, these bits must always be 0xfee.
pub always_0xfee: BitField12,
}
#[bitfield]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct MsiDataMessage {
pub vector: BitField8,
#[bits = 3]
pub delivery_mode: DeliveryMode,
pub reserved: BitField3,
#[bits = 1]
pub level: Level,
#[bits = 1]
pub trigger: TriggerMode,
pub reserved2: BitField16,
}
#[bitfield]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryStatus {
Idle = 0,
Pending = 1,
}
/// The level of a level-triggered interrupt: asserted or deasserted.
#[bitfield]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
Deassert = 0,
Assert = 1,
}
/// Represents a IOAPIC redirection table entry.
#[bitfield]
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct IoapicRedirectionTableEntry {
vector: BitField8,
#[bits = 3]
delivery_mode: DeliveryMode,
|
remote_irr: bool,
#[bits = 1]
trigger_mode: TriggerMode,
interrupt_mask: bool, // true iff interrupts are masked.
reserved: BitField39,
dest_id: BitField8,
}
/// Number of pins on the standard KVM/IOAPIC.
pub const NUM_IOAPIC_PINS: usize = 24;
/// Maximum number of pins on the IOAPIC.
pub const MAX_IOAPIC_PINS: usize = 120;
/// Represents the state of the IOAPIC.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IoapicState {
/// base_address is the memory base address for this IOAPIC. It cannot be changed.
pub base_address: u64,
/// ioregsel register. Used for selecting which entry of the redirect table to read/write.
pub ioregsel: u8,
/// ioapicid register. Bits 24 - 27 contain the APIC ID for this device.
pub ioapicid: u32,
/// current_interrupt_level_bitmap represents a bitmap of the state of all of the irq lines
pub current_interrupt_level_bitmap: u32,
/// redirect_table contains the irq settings for each irq line
pub redirect_table: [IoapicRedirectionTableEntry; 120],
}
impl Default for IoapicState {
fn default() -> IoapicState {
unsafe { std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PicSelect {
Primary = 0,
Secondary = 1,
}
#[repr(C)]
#[derive(enumn::N, Debug, Clone, Copy, PartialEq, Eq)]
pub enum PicInitState {
Icw1 = 0,
Icw2 = 1,
Icw3 = 2,
Icw4 = 3,
}
/// Convenience implementation for converting from a u8
impl From<u8> for PicInitState {
fn from(item: u8) -> Self {
PicInitState::n(item).unwrap_or_else(|| {
error!("Invalid PicInitState {}, setting to 0", item);
PicInitState::Icw1
})
}
}
impl Default for PicInitState {
fn default() -> Self {
PicInitState::Icw1
}
}
/// Represents the state of the PIC.
#[repr(C)]
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub struct PicState {
/// Edge detection.
pub last_irr: u8,
/// Interrupt Request Register.
pub irr: u8,
/// Interrupt Mask Register.
pub imr: u8,
/// Interrupt Service Register.
pub isr: u8,
/// Highest priority, for priority rotation.
pub priority_add: u8,
pub irq_base: u8,
pub read_reg_select: bool,
pub poll: bool,
pub special_mask: bool,
pub init_state: PicInitState,
pub auto_eoi: bool,
pub rotate_on_auto_eoi: bool,
pub special_fully_nested_mode: bool,
/// PIC takes either 3 or 4 bytes of initialization command word during
/// initialization. use_4_byte_icw is true if 4 bytes of ICW are needed.
pub use_4_byte_icw: bool,
/// "Edge/Level Control Registers", for edge trigger selection.
/// When a particular bit is set, the corresponding IRQ is in level-triggered mode. Otherwise it
/// is in edge-triggered mode.
pub elcr: u8,
pub elcr_mask: u8,
}
/// The LapicState represents the state of an x86 CPU's Local APIC.
/// The Local APIC consists of 64 128-bit registers, but only the first 32-bits of each register
/// can be used, so this structure only stores the first 32-bits of each register.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct LapicState {
pub regs: [LapicRegister; 64],
}
pub type LapicRegister = u32;
// rust arrays longer than 32 need custom implementations of Debug
impl std::fmt::Debug for LapicState {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
self.regs[..].fmt(formatter)
}
}
// rust arrays longer than 32 need custom implementations of PartialEq
impl PartialEq for LapicState {
fn eq(&self, other: &LapicState) -> bool {
self.regs[..] == other.regs[..]
}
}
// Lapic equality is reflexive, so we impl Eq
impl Eq for LapicState {}
/// The PitState represents the state of the PIT (aka the Programmable Interval Timer).
/// The state is simply the state of it's three channels.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PitState {
pub channels: [PitChannelState; 3],
/// Hypervisor-specific flags for setting the pit state.
pub flags: u32,
}
/// The PitRWMode enum represents the access mode of a PIT channel.
/// Reads and writes to the Pit happen over Port-mapped I/O, which happens one byte at a time,
/// but the count values and latch values are two bytes. So the access mode controls which of the
/// two bytes will be read when.
#[repr(C)]
#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq)]
pub enum PitRWMode {
/// None mode means that no access mode has been set.
None = 0,
/// Least mode means all reads/writes will read/write the least significant byte.
Least = 1,
/// Most mode means all reads/writes will read/write the most significant byte.
Most = 2,
/// Both mode means first the least significant byte will be read/written, then the
/// next read/write will read/write the most significant byte.
Both = 3,
}
/// Convenience implementation for converting from a u8
impl From<u8> for PitRWMode {
fn from(item: u8) -> Self {
PitRWMode::n(item).unwrap_or_else(|| {
error!("Invalid PitRWMode value {}, setting to 0", item);
PitRWMode::None
})
}
}
/// The PitRWState enum represents the state of reading to or writing from a channel.
/// This is related to the PitRWMode, it mainly gives more detail about the state of the channel
/// with respect to PitRWMode::Both.
#[repr(C)]
#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq)]
pub enum PitRWState {
/// None mode means that no access mode has been set.
None = 0,
/// LSB means that the channel is in PitRWMode::Least access mode.
LSB = 1,
/// MSB means that the channel is in PitRWMode::Most access mode.
MSB = 2,
/// Word0 means that the channel is in PitRWMode::Both mode, and the least sginificant byte
/// has not been read/written yet.
Word0 = 3,
/// Word1 means that the channel is in PitRWMode::Both mode and the least significant byte
/// has already been read/written, and the next byte to be read/written will be the most
/// significant byte.
Word1 = 4,
}
/// Convenience implementation for converting from a u8
impl From<u8> for PitRWState {
fn from(item: u8) -> Self {
PitRWState::n(item).unwrap_or_else(|| {
error!("Invalid PitRWState value {}, setting to 0", item);
PitRWState::None
})
}
}
/// The PitChannelState represents the state of one of the PIT's three counters.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PitChannelState {
/// The starting value for the counter.
pub count: u32,
/// Stores the channel count from the last time the count was latched.
pub latched_count: u16,
/// Indicates the PitRWState state of reading the latch value.
pub count_latched: PitRWState,
/// Indicates whether ReadBack status has been latched.
pub status_latched: bool,
/// Stores the channel status from the last time the status was latched. The status contains
/// information about the access mode of this channel, but changing those bits in the status
/// will not change the behavior of the pit.
pub status: u8,
/// Indicates the PitRWState state of reading the counter.
pub read_state: PitRWState,
/// Indicates the PitRWState state of writing the counter.
pub write_state: PitRWState,
/// Stores the value with which the counter was initialized. Counters are 16-
/// bit values with an effective range of 1-65536 (65536 represented by 0).
pub reload_value: u16,
/// The command access mode of this channel.
pub rw_mode: PitRWMode,
/// The operation mode of this channel.
pub mode: u8,
/// Whether or not we are in bcd mode. Not supported by KVM or crosvm's PIT implementation.
pub bcd: bool,
/// Value of the gate input pin. This only applies to channel 2.
pub gate: bool,
/// Nanosecond timestamp of when the count value was loaded.
pub count_load_time: u64,
}
// Convenience constructors for IrqRoutes
impl IrqRoute {
pub fn ioapic_irq_route(irq_num: u32) -> IrqRoute {
IrqRoute {
gsi: irq_num,
source: IrqSource::Irqchip {
chip: IrqSourceChip::Ioapic,
pin: irq_num,
},
}
}
pub fn pic_irq_route(id: IrqSourceChip, irq_num: u32) -> IrqRoute {
IrqRoute {
gsi: irq_num,
source: IrqSource::Irqchip {
chip: id,
pin: irq_num % 8,
},
}
}
}
/// State of a VCPU's general purpose registers.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Regs {
pub rax: u64,
pub rbx: u64,
pub rcx: u64,
pub rdx: u64,
pub rsi: u64,
pub rdi: u64,
pub rsp: u64,
pub rbp: u64,
pub r8: u64,
pub r9: u64,
pub r10: u64,
pub r11: u64,
pub r12: u64,
pub r13: u64,
pub r14: u64,
pub r15: u64,
pub rip: u64,
pub rflags: u64,
}
/// State of a memory segment.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Segment {
pub base: u64,
pub limit: u32,
pub selector: u16,
pub type_: u8,
pub present: u8,
pub dpl: u8,
pub db: u8,
pub s: u8,
pub l: u8,
pub g: u8,
pub avl: u8,
}
/// State of a global descriptor table or interrupt descriptor table.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct DescriptorTable {
pub base: u64,
pub limit: u16,
}
/// State of a VCPU's special registers.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Sregs {
pub cs: Segment,
pub ds: Segment,
pub es: Segment,
pub fs: Segment,
pub gs: Segment,
pub ss: Segment,
pub tr: Segment,
pub ldt: Segment,
pub gdt: DescriptorTable,
pub idt: DescriptorTable,
pub cr0: u64,
pub cr2: u64,
pub cr3: u64,
pub cr4: u64,
pub cr8: u64,
pub efer: u64,
pub apic_base: u64,
/// A bitmap of pending external interrupts. At most one bit may be set. This interrupt has
/// been acknowledged by the APIC but not yet injected into the cpu core.
pub interrupt_bitmap: [u64; 4usize],
}
/// State of a VCPU's floating point unit.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Fpu {
pub fpr: [[u8; 16usize]; 8usize],
pub fcw: u16,
pub fsw: u16,
pub ftwx: u8,
pub last_opcode: u16,
pub last_ip: u64,
pub last_dp: u64,
pub xmm: [[u8; 16usize]; 16usize],
pub mxcsr: u32,
}
/// State of a VCPU's debug registers.
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct DebugRegs {
pub db: [u64; 4usize],
pub dr6: u64,
pub dr7: u64,
}
/// State of one VCPU register. Currently used for MSRs and XCRs.
#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
pub struct Register {
pub id: u32,
pub value: u64,
}
|
#[bits = 1]
dest_mode: DestinationMode,
#[bits = 1]
delivery_status: DeliveryStatus,
polarity: BitField1,
|
random_line_split
|
traced_image.rs
|
use std::path::Path;
use cgmath::Point2;
use glium::backend::Facade;
use glium::framebuffer::SimpleFrameBuffer;
use glium::texture::{
ClientFormat, MipmapsOption, RawImage2d, SrgbTexture2d, Texture2d, UncompressedFloatFormat,
UncompressedUintFormat, UnsignedTexture2d,
};
use glium::{uniform, DrawParameters, IndexBuffer, Rect, Surface, VertexBuffer};
use crate::pt_renderer::RenderConfig;
use crate::vertex::RawVertex;
pub struct TracedImage {
pixels: Vec<f32>,
n_samples: Vec<u32>,
width: u32,
height: u32,
visualizer: Visualizer,
}
impl TracedImage {
pub fn new<F: Facade>(facade: &F, config: &RenderConfig) -> Self {
let width = config.width;
let height = config.height;
let pixels = vec![0.0; (3 * width * height) as usize];
let n_samples = vec![0; (width * height) as usize];
let visualizer = Visualizer::new(facade, config);
Self {
pixels,
n_samples,
width,
height,
visualizer,
}
}
pub fn add_sample(&mut self, rect: Rect, sample: &[f32]) {
for h in 0..rect.height {
for w in 0..rect.width {
let i_image = ((h + rect.bottom) * self.width + w + rect.left) as usize;
let i_block = (h * rect.width + w) as usize;
self.n_samples[i_image] += 1;
for c in 0..3 {
self.pixels[3 * i_image + c] += sample[3 * i_block + c];
}
}
}
}
#[allow(clippy::needless_range_loop)]
pub fn add_splat(&mut self, pixel: Point2<u32>, sample: [f32; 3]) {
let i_image = (pixel.y * self.width + pixel.x) as usize;
for c in 0..3 {
self.pixels[3 * i_image + c] += sample[c];
}
}
pub fn render<F: Facade, S: Surface>(&self, facade: &F, target: &mut S) {
self.visualizer.render(
facade,
target,
&self.pixels,
&self.n_samples,
self.width,
self.height,
);
}
pub fn save<F: Facade>(&self, facade: &F, path: &Path) {
let texture = SrgbTexture2d::empty(facade, self.width, self.height).unwrap();
let mut target = SimpleFrameBuffer::new(facade, &texture).unwrap();
target.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
self.render(facade, &mut target);
let pb = texture.read_to_pixel_buffer();
let raw_image: RawImage2d<u8> = pb.read_as_texture_2d().unwrap();
let image =
image::RgbaImage::from_vec(self.width, self.height, raw_image.data.to_vec()).unwrap();
let image = image::imageops::flip_vertical(&image);
image.save(path).unwrap();
}
}
struct Visualizer {
shader: glium::Program,
vertex_buffer: VertexBuffer<RawVertex>,
index_buffer: IndexBuffer<u32>,
tone_map: bool,
}
impl Visualizer {
fn new<F: Facade>(facade: &F, config: &RenderConfig) -> Self {
let vertices = vec![
RawVertex {
pos: [-1.0, -1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [0.0, 0.0],
},
RawVertex {
pos: [1.0, -1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [1.0, 0.0],
},
RawVertex {
pos: [1.0, 1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [1.0, 1.0],
},
RawVertex {
pos: [-1.0, 1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [0.0, 1.0],
},
];
let vertex_buffer =
VertexBuffer::new(facade, &vertices).expect("Failed to create vertex buffer!");
let indices = vec![0, 1, 2, 0, 2, 3];
let index_buffer =
IndexBuffer::new(facade, glium::index::PrimitiveType::TrianglesList, &indices)
.expect("Failed to create index buffer!");
// Image shader
let vertex_shader_src = include_str!("../shaders/image.vert");
let fragment_shader_src = include_str!("../shaders/image.frag");
let shader =
glium::Program::from_source(facade, vertex_shader_src, fragment_shader_src, None)
.expect("Failed to create program!");
Self {
|
}
fn render<F: Facade, S: Surface>(
&self,
facade: &F,
target: &mut S,
data: &[f32],
n_samples: &[u32],
width: u32,
height: u32,
) {
let data_raw = RawImage2d {
data: std::borrow::Cow::from(data),
width,
height,
format: ClientFormat::F32F32F32,
};
let data_texture = Texture2d::with_format(
facade,
data_raw,
UncompressedFloatFormat::F32F32F32,
MipmapsOption::NoMipmap,
)
.unwrap();
let n_raw = RawImage2d {
data: std::borrow::Cow::from(n_samples),
width,
height,
format: ClientFormat::U32,
};
let n_texture = UnsignedTexture2d::with_format(
facade,
n_raw,
UncompressedUintFormat::U32,
MipmapsOption::NoMipmap,
)
.unwrap();
let uniforms = uniform! {
image: &data_texture,
n: &n_texture,
tone_map: self.tone_map,
};
let draw_parameters = DrawParameters {
..Default::default()
};
target
.draw(
&self.vertex_buffer,
&self.index_buffer,
&self.shader,
&uniforms,
&draw_parameters,
)
.unwrap();
}
}
|
shader,
vertex_buffer,
index_buffer,
tone_map: config.tone_map,
}
|
random_line_split
|
traced_image.rs
|
use std::path::Path;
use cgmath::Point2;
use glium::backend::Facade;
use glium::framebuffer::SimpleFrameBuffer;
use glium::texture::{
ClientFormat, MipmapsOption, RawImage2d, SrgbTexture2d, Texture2d, UncompressedFloatFormat,
UncompressedUintFormat, UnsignedTexture2d,
};
use glium::{uniform, DrawParameters, IndexBuffer, Rect, Surface, VertexBuffer};
use crate::pt_renderer::RenderConfig;
use crate::vertex::RawVertex;
pub struct TracedImage {
pixels: Vec<f32>,
n_samples: Vec<u32>,
width: u32,
height: u32,
visualizer: Visualizer,
}
impl TracedImage {
pub fn new<F: Facade>(facade: &F, config: &RenderConfig) -> Self {
let width = config.width;
let height = config.height;
let pixels = vec![0.0; (3 * width * height) as usize];
let n_samples = vec![0; (width * height) as usize];
let visualizer = Visualizer::new(facade, config);
Self {
pixels,
n_samples,
width,
height,
visualizer,
}
}
pub fn add_sample(&mut self, rect: Rect, sample: &[f32]) {
for h in 0..rect.height {
for w in 0..rect.width {
let i_image = ((h + rect.bottom) * self.width + w + rect.left) as usize;
let i_block = (h * rect.width + w) as usize;
self.n_samples[i_image] += 1;
for c in 0..3 {
self.pixels[3 * i_image + c] += sample[3 * i_block + c];
}
}
}
}
#[allow(clippy::needless_range_loop)]
pub fn add_splat(&mut self, pixel: Point2<u32>, sample: [f32; 3]) {
let i_image = (pixel.y * self.width + pixel.x) as usize;
for c in 0..3 {
self.pixels[3 * i_image + c] += sample[c];
}
}
pub fn render<F: Facade, S: Surface>(&self, facade: &F, target: &mut S) {
self.visualizer.render(
facade,
target,
&self.pixels,
&self.n_samples,
self.width,
self.height,
);
}
pub fn save<F: Facade>(&self, facade: &F, path: &Path) {
let texture = SrgbTexture2d::empty(facade, self.width, self.height).unwrap();
let mut target = SimpleFrameBuffer::new(facade, &texture).unwrap();
target.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
self.render(facade, &mut target);
let pb = texture.read_to_pixel_buffer();
let raw_image: RawImage2d<u8> = pb.read_as_texture_2d().unwrap();
let image =
image::RgbaImage::from_vec(self.width, self.height, raw_image.data.to_vec()).unwrap();
let image = image::imageops::flip_vertical(&image);
image.save(path).unwrap();
}
}
struct Visualizer {
shader: glium::Program,
vertex_buffer: VertexBuffer<RawVertex>,
index_buffer: IndexBuffer<u32>,
tone_map: bool,
}
impl Visualizer {
fn new<F: Facade>(facade: &F, config: &RenderConfig) -> Self
|
tex_coords: [0.0, 1.0],
},
];
let vertex_buffer =
VertexBuffer::new(facade, &vertices).expect("Failed to create vertex buffer!");
let indices = vec![0, 1, 2, 0, 2, 3];
let index_buffer =
IndexBuffer::new(facade, glium::index::PrimitiveType::TrianglesList, &indices)
.expect("Failed to create index buffer!");
// Image shader
let vertex_shader_src = include_str!("../shaders/image.vert");
let fragment_shader_src = include_str!("../shaders/image.frag");
let shader =
glium::Program::from_source(facade, vertex_shader_src, fragment_shader_src, None)
.expect("Failed to create program!");
Self {
shader,
vertex_buffer,
index_buffer,
tone_map: config.tone_map,
}
}
fn render<F: Facade, S: Surface>(
&self,
facade: &F,
target: &mut S,
data: &[f32],
n_samples: &[u32],
width: u32,
height: u32,
) {
let data_raw = RawImage2d {
data: std::borrow::Cow::from(data),
width,
height,
format: ClientFormat::F32F32F32,
};
let data_texture = Texture2d::with_format(
facade,
data_raw,
UncompressedFloatFormat::F32F32F32,
MipmapsOption::NoMipmap,
)
.unwrap();
let n_raw = RawImage2d {
data: std::borrow::Cow::from(n_samples),
width,
height,
format: ClientFormat::U32,
};
let n_texture = UnsignedTexture2d::with_format(
facade,
n_raw,
UncompressedUintFormat::U32,
MipmapsOption::NoMipmap,
)
.unwrap();
let uniforms = uniform! {
image: &data_texture,
n: &n_texture,
tone_map: self.tone_map,
};
let draw_parameters = DrawParameters {
..Default::default()
};
target
.draw(
&self.vertex_buffer,
&self.index_buffer,
&self.shader,
&uniforms,
&draw_parameters,
)
.unwrap();
}
}
|
{
let vertices = vec![
RawVertex {
pos: [-1.0, -1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [0.0, 0.0],
},
RawVertex {
pos: [1.0, -1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [1.0, 0.0],
},
RawVertex {
pos: [1.0, 1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [1.0, 1.0],
},
RawVertex {
pos: [-1.0, 1.0, 0.0],
normal: [0.0, 0.0, 0.0],
|
identifier_body
|
traced_image.rs
|
use std::path::Path;
use cgmath::Point2;
use glium::backend::Facade;
use glium::framebuffer::SimpleFrameBuffer;
use glium::texture::{
ClientFormat, MipmapsOption, RawImage2d, SrgbTexture2d, Texture2d, UncompressedFloatFormat,
UncompressedUintFormat, UnsignedTexture2d,
};
use glium::{uniform, DrawParameters, IndexBuffer, Rect, Surface, VertexBuffer};
use crate::pt_renderer::RenderConfig;
use crate::vertex::RawVertex;
pub struct TracedImage {
pixels: Vec<f32>,
n_samples: Vec<u32>,
width: u32,
height: u32,
visualizer: Visualizer,
}
impl TracedImage {
pub fn new<F: Facade>(facade: &F, config: &RenderConfig) -> Self {
let width = config.width;
let height = config.height;
let pixels = vec![0.0; (3 * width * height) as usize];
let n_samples = vec![0; (width * height) as usize];
let visualizer = Visualizer::new(facade, config);
Self {
pixels,
n_samples,
width,
height,
visualizer,
}
}
pub fn add_sample(&mut self, rect: Rect, sample: &[f32]) {
for h in 0..rect.height {
for w in 0..rect.width {
let i_image = ((h + rect.bottom) * self.width + w + rect.left) as usize;
let i_block = (h * rect.width + w) as usize;
self.n_samples[i_image] += 1;
for c in 0..3 {
self.pixels[3 * i_image + c] += sample[3 * i_block + c];
}
}
}
}
#[allow(clippy::needless_range_loop)]
pub fn add_splat(&mut self, pixel: Point2<u32>, sample: [f32; 3]) {
let i_image = (pixel.y * self.width + pixel.x) as usize;
for c in 0..3 {
self.pixels[3 * i_image + c] += sample[c];
}
}
pub fn
|
<F: Facade, S: Surface>(&self, facade: &F, target: &mut S) {
self.visualizer.render(
facade,
target,
&self.pixels,
&self.n_samples,
self.width,
self.height,
);
}
pub fn save<F: Facade>(&self, facade: &F, path: &Path) {
let texture = SrgbTexture2d::empty(facade, self.width, self.height).unwrap();
let mut target = SimpleFrameBuffer::new(facade, &texture).unwrap();
target.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
self.render(facade, &mut target);
let pb = texture.read_to_pixel_buffer();
let raw_image: RawImage2d<u8> = pb.read_as_texture_2d().unwrap();
let image =
image::RgbaImage::from_vec(self.width, self.height, raw_image.data.to_vec()).unwrap();
let image = image::imageops::flip_vertical(&image);
image.save(path).unwrap();
}
}
struct Visualizer {
shader: glium::Program,
vertex_buffer: VertexBuffer<RawVertex>,
index_buffer: IndexBuffer<u32>,
tone_map: bool,
}
impl Visualizer {
fn new<F: Facade>(facade: &F, config: &RenderConfig) -> Self {
let vertices = vec![
RawVertex {
pos: [-1.0, -1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [0.0, 0.0],
},
RawVertex {
pos: [1.0, -1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [1.0, 0.0],
},
RawVertex {
pos: [1.0, 1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [1.0, 1.0],
},
RawVertex {
pos: [-1.0, 1.0, 0.0],
normal: [0.0, 0.0, 0.0],
tex_coords: [0.0, 1.0],
},
];
let vertex_buffer =
VertexBuffer::new(facade, &vertices).expect("Failed to create vertex buffer!");
let indices = vec![0, 1, 2, 0, 2, 3];
let index_buffer =
IndexBuffer::new(facade, glium::index::PrimitiveType::TrianglesList, &indices)
.expect("Failed to create index buffer!");
// Image shader
let vertex_shader_src = include_str!("../shaders/image.vert");
let fragment_shader_src = include_str!("../shaders/image.frag");
let shader =
glium::Program::from_source(facade, vertex_shader_src, fragment_shader_src, None)
.expect("Failed to create program!");
Self {
shader,
vertex_buffer,
index_buffer,
tone_map: config.tone_map,
}
}
fn render<F: Facade, S: Surface>(
&self,
facade: &F,
target: &mut S,
data: &[f32],
n_samples: &[u32],
width: u32,
height: u32,
) {
let data_raw = RawImage2d {
data: std::borrow::Cow::from(data),
width,
height,
format: ClientFormat::F32F32F32,
};
let data_texture = Texture2d::with_format(
facade,
data_raw,
UncompressedFloatFormat::F32F32F32,
MipmapsOption::NoMipmap,
)
.unwrap();
let n_raw = RawImage2d {
data: std::borrow::Cow::from(n_samples),
width,
height,
format: ClientFormat::U32,
};
let n_texture = UnsignedTexture2d::with_format(
facade,
n_raw,
UncompressedUintFormat::U32,
MipmapsOption::NoMipmap,
)
.unwrap();
let uniforms = uniform! {
image: &data_texture,
n: &n_texture,
tone_map: self.tone_map,
};
let draw_parameters = DrawParameters {
..Default::default()
};
target
.draw(
&self.vertex_buffer,
&self.index_buffer,
&self.shader,
&uniforms,
&draw_parameters,
)
.unwrap();
}
}
|
render
|
identifier_name
|
svg.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("SVG", inherited=False, gecko_name="SVGReset") %>
${helpers.single_keyword(
"dominant-baseline",
"""auto use-script no-change reset-size ideographic alphabetic hanging
mathematical central middle text-after-edge text-before-edge""",
products="gecko",
animation_value_type="discrete",
spec="https://www.w3.org/TR/SVG11/text.html#DominantBaselineProperty",
)}
${helpers.single_keyword(
"vector-effect",
"none non-scaling-stroke",
products="gecko",
animation_value_type="discrete",
spec="https://www.w3.org/TR/SVGTiny12/painting.html#VectorEffectProperty",
)}
// Section 13 - Gradients and Patterns
${helpers.predefined_type(
"stop-color",
"Color",
"RGBA::new(0, 0, 0, 255).into()",
products="gecko",
animation_value_type="AnimatedRGBA",
spec="https://www.w3.org/TR/SVGTiny12/painting.html#StopColorProperty",
)}
${helpers.predefined_type(
"stop-opacity",
"Opacity",
"1.0",
products="gecko",
animation_value_type="ComputedValue",
spec="https://www.w3.org/TR/SVGTiny12/painting.html#propdef-stop-opacity",
)}
// Section 15 - Filter Effects
${helpers.predefined_type(
"flood-color",
"Color",
"RGBA::new(0, 0, 0, 255).into()",
products="gecko",
animation_value_type="AnimatedColor",
spec="https://www.w3.org/TR/SVG/filters.html#FloodColorProperty",
)}
${helpers.predefined_type(
"flood-opacity",
"Opacity",
"1.0",
products="gecko",
animation_value_type="ComputedValue",
spec="https://www.w3.org/TR/SVG/filters.html#FloodOpacityProperty",
)}
${helpers.predefined_type(
"lighting-color",
"Color",
"RGBA::new(255, 255, 255, 255).into()",
products="gecko",
animation_value_type="AnimatedColor",
spec="https://www.w3.org/TR/SVG/filters.html#LightingColorProperty",
)}
// CSS Masking Module Level 1
// https://drafts.fxtf.org/css-masking
${helpers.single_keyword(
"mask-type",
"luminance alpha",
products="gecko",
animation_value_type="discrete",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-type",
)}
${helpers.predefined_type(
"clip-path",
"basic_shape::ClippingShape",
"generics::basic_shape::ShapeSource::None",
products="gecko",
boxed=True,
animation_value_type="ComputedValue",
flags="CREATES_STACKING_CONTEXT",
spec="https://drafts.fxtf.org/css-masking/#propdef-clip-path",
)}
${helpers.single_keyword(
"mask-mode",
"match-source alpha luminance",
vector=True,
products="gecko",
animation_value_type="discrete",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-mode",
)}
${helpers.predefined_type(
"mask-repeat",
"BackgroundRepeat",
"computed::BackgroundRepeat::repeat()",
initial_specified_value="specified::BackgroundRepeat::repeat()",
products="gecko",
extra_prefixes="webkit",
animation_value_type="discrete",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-repeat",
vector=True,
)}
% for (axis, direction) in [("x", "Horizontal"), ("y", "Vertical")]:
${helpers.predefined_type(
"mask-position-" + axis,
"position::" + direction + "Position",
"computed::LengthOrPercentage::zero()",
products="gecko",
extra_prefixes="webkit",
initial_specified_value="specified::PositionComponent::Center",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-position",
animation_value_type="ComputedValue",
vector_animation_type="repeatable_list",
vector=True,
)}
% endfor
${helpers.single_keyword(
"mask-clip",
"border-box content-box padding-box",
extra_gecko_values="fill-box stroke-box view-box no-clip",
vector=True,
products="gecko",
extra_prefixes="webkit",
gecko_enum_prefix="StyleGeometryBox",
gecko_inexhaustive=True,
animation_value_type="discrete",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-clip",
)}
${helpers.single_keyword(
"mask-origin",
"border-box content-box padding-box",
extra_gecko_values="fill-box stroke-box view-box",
vector=True,
products="gecko",
extra_prefixes="webkit",
|
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-origin",
)}
${helpers.predefined_type(
"mask-size",
"background::BackgroundSize",
"computed::BackgroundSize::auto()",
initial_specified_value="specified::BackgroundSize::auto()",
products="gecko",
extra_prefixes="webkit",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-size",
animation_value_type="MaskSizeList",
vector=True,
vector_animation_type="repeatable_list",
)}
${helpers.single_keyword(
"mask-composite",
"add subtract intersect exclude",
vector=True,
products="gecko",
extra_prefixes="webkit",
animation_value_type="discrete",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-composite",
)}
${helpers.predefined_type(
"mask-image",
"ImageLayer",
"Either::First(None_)",
initial_specified_value="Either::First(None_)",
parse_method="parse_with_cors_anonymous",
spec="https://drafts.fxtf.org/css-masking/#propdef-mask-image",
vector=True,
products="gecko",
extra_prefixes="webkit",
animation_value_type="discrete",
flags="CREATES_STACKING_CONTEXT",
)}
|
gecko_enum_prefix="StyleGeometryBox",
gecko_inexhaustive=True,
animation_value_type="discrete",
|
random_line_split
|
blob_url_store.rs
|
use dom::bindings::js::JS;
use dom::blob::Blob;
use origin::Origin;
use std::collections::HashMap;
use uuid::Uuid;
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
struct EntryPair(Origin, JS<Blob>);
// HACK: to work around the HeapSizeOf of Uuid
#[derive(PartialEq, HeapSizeOf, Eq, Hash, JSTraceable)]
struct BlobUrlId(#[ignore_heap_size_of = "defined in uuid"] Uuid);
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
pub struct BlobURLStore {
entries: HashMap<BlobUrlId, EntryPair>,
}
pub enum BlobURLStoreError {
InvalidKey,
InvalidOrigin,
}
impl BlobURLStore {
pub fn new() -> BlobURLStore {
BlobURLStore {
entries: HashMap::new(),
}
}
pub fn request(&self, id: Uuid, origin: &Origin) -> Result<&Blob, BlobURLStoreError> {
match self.entries.get(&BlobUrlId(id)) {
Some(ref pair) => {
if pair.0.same_origin(origin) {
Ok(&pair.1)
} else {
Err(BlobURLStoreError::InvalidOrigin)
}
}
None => Err(BlobURLStoreError::InvalidKey)
}
}
pub fn add_entry(&mut self, id: Uuid, origin: Origin, blob: &Blob) {
self.entries.insert(BlobUrlId(id), EntryPair(origin, JS::from_ref(blob)));
}
pub fn delete_entry(&mut self, id: Uuid) {
self.entries.remove(&BlobUrlId(id));
}
}
|
/* 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/. */
#![allow(dead_code)]
|
random_line_split
|
|
blob_url_store.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/. */
#![allow(dead_code)]
use dom::bindings::js::JS;
use dom::blob::Blob;
use origin::Origin;
use std::collections::HashMap;
use uuid::Uuid;
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
struct EntryPair(Origin, JS<Blob>);
// HACK: to work around the HeapSizeOf of Uuid
#[derive(PartialEq, HeapSizeOf, Eq, Hash, JSTraceable)]
struct BlobUrlId(#[ignore_heap_size_of = "defined in uuid"] Uuid);
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
pub struct BlobURLStore {
entries: HashMap<BlobUrlId, EntryPair>,
}
pub enum
|
{
InvalidKey,
InvalidOrigin,
}
impl BlobURLStore {
pub fn new() -> BlobURLStore {
BlobURLStore {
entries: HashMap::new(),
}
}
pub fn request(&self, id: Uuid, origin: &Origin) -> Result<&Blob, BlobURLStoreError> {
match self.entries.get(&BlobUrlId(id)) {
Some(ref pair) => {
if pair.0.same_origin(origin) {
Ok(&pair.1)
} else {
Err(BlobURLStoreError::InvalidOrigin)
}
}
None => Err(BlobURLStoreError::InvalidKey)
}
}
pub fn add_entry(&mut self, id: Uuid, origin: Origin, blob: &Blob) {
self.entries.insert(BlobUrlId(id), EntryPair(origin, JS::from_ref(blob)));
}
pub fn delete_entry(&mut self, id: Uuid) {
self.entries.remove(&BlobUrlId(id));
}
}
|
BlobURLStoreError
|
identifier_name
|
lib.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.
/*!
The Rust compiler.
# Note
This API is completely unstable and subject to change.
*/
#![crate_id = "rustc#0.10"]
#![comment = "The Rust compiler"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![allow(deprecated)]
#![feature(macro_rules, globs, struct_variant, managed_boxes, quote,
default_type_params, phase)]
extern crate flate;
extern crate arena;
extern crate syntax;
extern crate serialize;
extern crate sync;
extern crate getopts;
extern crate collections;
extern crate time;
#[phase(syntax, link)]
extern crate log;
use back::link;
use driver::session;
use middle::lint;
use d = driver::driver;
use std::any::AnyRefExt;
use std::cmp;
use std::io;
use std::os;
use std::str;
use std::task;
use syntax::ast;
use syntax::diagnostic::Emitter;
use syntax::diagnostic;
use syntax::parse;
pub mod middle {
pub mod trans;
pub mod ty;
pub mod ty_fold;
pub mod subst;
pub mod resolve;
pub mod resolve_lifetime;
pub mod typeck;
pub mod check_loop;
pub mod check_match;
pub mod check_const;
pub mod check_static;
pub mod lint;
pub mod borrowck;
pub mod dataflow;
pub mod mem_categorization;
pub mod liveness;
pub mod kind;
pub mod freevars;
pub mod pat_util;
pub mod region;
pub mod const_eval;
pub mod astencode;
pub mod lang_items;
pub mod privacy;
pub mod moves;
pub mod entry;
pub mod effect;
pub mod reachable;
pub mod graph;
pub mod cfg;
pub mod dead;
}
pub mod front {
pub mod config;
pub mod test;
pub mod std_inject;
pub mod assign_node_ids_and_map;
pub mod feature_gate;
pub mod show_span;
}
pub mod back {
pub mod abi;
|
pub mod rpath;
pub mod svh;
pub mod target_strs;
pub mod x86;
pub mod x86_64;
}
pub mod metadata;
pub mod driver;
pub mod util {
pub mod common;
pub mod ppaux;
pub mod sha2;
pub mod nodemap;
}
pub mod lib {
pub mod llvm;
pub mod llvmdeps;
}
static BUG_REPORT_URL: &'static str =
"http://static.rust-lang.org/doc/master/complement-bugreport.html";
pub fn version(argv0: &str) {
let vers = match option_env!("CFG_VERSION") {
Some(vers) => vers,
None => "unknown version"
};
println!("{} {}", argv0, vers);
println!("host: {}", d::host_triple());
}
pub fn usage(argv0: &str) {
let message = format!("Usage: {} [OPTIONS] INPUT", argv0);
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message, d::optgroups().as_slice()));
}
pub fn describe_warnings() {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
let lint_dict = lint::get_lint_dict();
let mut lint_dict = lint_dict.move_iter()
.map(|(k, v)| (v, k))
.collect::<Vec<(lint::LintSpec, &'static str)> >();
lint_dict.as_mut_slice().sort();
let mut max_key = 0;
for &(_, name) in lint_dict.iter() {
max_key = cmp::max(name.len(), max_key);
}
fn padded(max: uint, s: &str) -> ~str {
" ".repeat(max - s.len()) + s
}
println!("\nAvailable lint checks:\n");
println!(" {} {:7.7s} {}",
padded(max_key, "name"), "default", "meaning");
println!(" {} {:7.7s} {}\n",
padded(max_key, "----"), "-------", "-------");
for (spec, name) in lint_dict.move_iter() {
let name = name.replace("_", "-");
println!(" {} {:7.7s} {}",
padded(max_key, name),
lint::level_to_str(spec.default),
spec.desc);
}
println!("");
}
pub fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = session::debugging_opts_map();
for tuple in r.iter() {
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
}
}
}
}
pub fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = session::basic_codegen_options();
for &(name, parser, desc) in session::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
pub fn run_compiler(args: &[~str]) {
let mut args = args.to_owned();
let binary = args.shift().unwrap();
if args.is_empty() { usage(binary); return; }
let matches =
&match getopts::getopts(args, d::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
d::early_error(f.to_err_msg());
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(binary);
return;
}
let lint_flags = matches.opt_strs("W").move_iter().collect::<Vec<_>>().append(
matches.opt_strs("warn").as_slice());
if lint_flags.iter().any(|x| x == &~"help") {
describe_warnings();
return;
}
let r = matches.opt_strs("Z");
if r.iter().any(|x| x == &~"help") {
describe_debug_flags();
return;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x == &~"help") {
describe_codegen_flags();
return;
}
if cg_flags.contains(&~"passes=list") {
unsafe { lib::llvm::llvm::LLVMRustPrintPasses(); }
return;
}
if matches.opt_present("v") || matches.opt_present("version") {
version(binary);
return;
}
let (input, input_file_path) = match matches.free.len() {
0u => d::early_error("no input filename given"),
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = str::from_utf8_owned(contents).unwrap();
(d::StrInput(src), None)
} else {
(d::FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
_ => d::early_error("multiple input filenames provided")
};
let sopts = d::build_session_options(matches);
let sess = d::build_session(sopts, input_file_path);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let cfg = d::build_configuration(&sess);
let pretty = matches.opt_default("pretty", "normal").map(|a| {
d::parse_pretty(&sess, a)
});
match pretty {
Some::<d::PpMode>(ppm) => {
d::pretty_print_input(sess, cfg, &input, ppm);
return;
}
None::<d::PpMode> => {/* continue */ }
}
let ls = matches.opt_present("ls");
if ls {
match input {
d::FileInput(ref ifile) => {
let mut stdout = io::stdout();
d::list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
d::StrInput(_) => {
d::early_error("can not list metadata for stdin");
}
}
return;
}
let (crate_id, crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_id || crate_name || crate_file_name {
let attrs = parse_crate_attrs(&sess, &input);
let t_outputs = d::build_output_filenames(&input, &odir, &ofile,
attrs.as_slice(), &sess);
let id = link::find_crate_id(attrs.as_slice(), t_outputs.out_filestem);
if crate_id {
println!("{}", id.to_str());
}
if crate_name {
println!("{}", id.name);
}
if crate_file_name {
let crate_types = session::collect_crate_types(&sess,
attrs.as_slice());
for &style in crate_types.iter() {
let fname = link::filename_for_input(&sess, style, &id,
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
return;
}
d::compile_input(sess, cfg, &input, &odir, &ofile);
}
fn parse_crate_attrs(sess: &session::Session, input: &d::Input) ->
Vec<ast::Attribute> {
let result = match *input {
d::FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
d::StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(d::anon_src(),
(*src).clone(),
Vec::new(),
&sess.parse_sess)
}
};
result.move_iter().collect()
}
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor(f: proc:Send()) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
let mut task_builder = task::task().named("rustc");
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task_builder.opts.stack_size = Some(STACK_SIZE);
}
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
match task_builder.try(proc() {
io::stdio::set_stderr(~w);
f()
}) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
if!value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr();
// a.span_bug or.bug call has already printed what
// it wants to print.
if!value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
diagnostic::Bug);
}
let xs = [
~"the compiler hit an unexpected failure path. this is a bug.",
"we would appreciate a bug report: " + BUG_REPORT_URL,
~"run with `RUST_BACKTRACE=1` for a backtrace",
];
for note in xs.iter() {
emitter.emit(None, *note, diagnostic::Note)
}
match r.read_to_str() {
Ok(s) => println!("{}", s),
Err(e) => emitter.emit(None,
format!("failed to read internal stderr: {}", e),
diagnostic::Error),
}
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(~io::util::NullWriter);
fail!();
}
}
}
pub fn main() {
std::os::set_exit_status(main_args(std::os::args()));
}
pub fn main_args(args: &[~str]) -> int {
let owned_args = args.to_owned();
monitor(proc() run_compiler(owned_args));
0
}
|
pub mod archive;
pub mod arm;
pub mod link;
pub mod lto;
pub mod mips;
|
random_line_split
|
lib.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.
/*!
The Rust compiler.
# Note
This API is completely unstable and subject to change.
*/
#![crate_id = "rustc#0.10"]
#![comment = "The Rust compiler"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![allow(deprecated)]
#![feature(macro_rules, globs, struct_variant, managed_boxes, quote,
default_type_params, phase)]
extern crate flate;
extern crate arena;
extern crate syntax;
extern crate serialize;
extern crate sync;
extern crate getopts;
extern crate collections;
extern crate time;
#[phase(syntax, link)]
extern crate log;
use back::link;
use driver::session;
use middle::lint;
use d = driver::driver;
use std::any::AnyRefExt;
use std::cmp;
use std::io;
use std::os;
use std::str;
use std::task;
use syntax::ast;
use syntax::diagnostic::Emitter;
use syntax::diagnostic;
use syntax::parse;
pub mod middle {
pub mod trans;
pub mod ty;
pub mod ty_fold;
pub mod subst;
pub mod resolve;
pub mod resolve_lifetime;
pub mod typeck;
pub mod check_loop;
pub mod check_match;
pub mod check_const;
pub mod check_static;
pub mod lint;
pub mod borrowck;
pub mod dataflow;
pub mod mem_categorization;
pub mod liveness;
pub mod kind;
pub mod freevars;
pub mod pat_util;
pub mod region;
pub mod const_eval;
pub mod astencode;
pub mod lang_items;
pub mod privacy;
pub mod moves;
pub mod entry;
pub mod effect;
pub mod reachable;
pub mod graph;
pub mod cfg;
pub mod dead;
}
pub mod front {
pub mod config;
pub mod test;
pub mod std_inject;
pub mod assign_node_ids_and_map;
pub mod feature_gate;
pub mod show_span;
}
pub mod back {
pub mod abi;
pub mod archive;
pub mod arm;
pub mod link;
pub mod lto;
pub mod mips;
pub mod rpath;
pub mod svh;
pub mod target_strs;
pub mod x86;
pub mod x86_64;
}
pub mod metadata;
pub mod driver;
pub mod util {
pub mod common;
pub mod ppaux;
pub mod sha2;
pub mod nodemap;
}
pub mod lib {
pub mod llvm;
pub mod llvmdeps;
}
static BUG_REPORT_URL: &'static str =
"http://static.rust-lang.org/doc/master/complement-bugreport.html";
pub fn version(argv0: &str) {
let vers = match option_env!("CFG_VERSION") {
Some(vers) => vers,
None => "unknown version"
};
println!("{} {}", argv0, vers);
println!("host: {}", d::host_triple());
}
pub fn usage(argv0: &str) {
let message = format!("Usage: {} [OPTIONS] INPUT", argv0);
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message, d::optgroups().as_slice()));
}
pub fn describe_warnings() {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
let lint_dict = lint::get_lint_dict();
let mut lint_dict = lint_dict.move_iter()
.map(|(k, v)| (v, k))
.collect::<Vec<(lint::LintSpec, &'static str)> >();
lint_dict.as_mut_slice().sort();
let mut max_key = 0;
for &(_, name) in lint_dict.iter() {
max_key = cmp::max(name.len(), max_key);
}
fn padded(max: uint, s: &str) -> ~str {
" ".repeat(max - s.len()) + s
}
println!("\nAvailable lint checks:\n");
println!(" {} {:7.7s} {}",
padded(max_key, "name"), "default", "meaning");
println!(" {} {:7.7s} {}\n",
padded(max_key, "----"), "-------", "-------");
for (spec, name) in lint_dict.move_iter() {
let name = name.replace("_", "-");
println!(" {} {:7.7s} {}",
padded(max_key, name),
lint::level_to_str(spec.default),
spec.desc);
}
println!("");
}
pub fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = session::debugging_opts_map();
for tuple in r.iter() {
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
}
}
}
}
pub fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = session::basic_codegen_options();
for &(name, parser, desc) in session::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
pub fn run_compiler(args: &[~str]) {
let mut args = args.to_owned();
let binary = args.shift().unwrap();
if args.is_empty() { usage(binary); return; }
let matches =
&match getopts::getopts(args, d::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
d::early_error(f.to_err_msg());
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(binary);
return;
}
let lint_flags = matches.opt_strs("W").move_iter().collect::<Vec<_>>().append(
matches.opt_strs("warn").as_slice());
if lint_flags.iter().any(|x| x == &~"help") {
describe_warnings();
return;
}
let r = matches.opt_strs("Z");
if r.iter().any(|x| x == &~"help") {
describe_debug_flags();
return;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x == &~"help") {
describe_codegen_flags();
return;
}
if cg_flags.contains(&~"passes=list") {
unsafe { lib::llvm::llvm::LLVMRustPrintPasses(); }
return;
}
if matches.opt_present("v") || matches.opt_present("version") {
version(binary);
return;
}
let (input, input_file_path) = match matches.free.len() {
0u => d::early_error("no input filename given"),
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = str::from_utf8_owned(contents).unwrap();
(d::StrInput(src), None)
} else {
(d::FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
_ => d::early_error("multiple input filenames provided")
};
let sopts = d::build_session_options(matches);
let sess = d::build_session(sopts, input_file_path);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let cfg = d::build_configuration(&sess);
let pretty = matches.opt_default("pretty", "normal").map(|a| {
d::parse_pretty(&sess, a)
});
match pretty {
Some::<d::PpMode>(ppm) => {
d::pretty_print_input(sess, cfg, &input, ppm);
return;
}
None::<d::PpMode> => {/* continue */ }
}
let ls = matches.opt_present("ls");
if ls {
match input {
d::FileInput(ref ifile) => {
let mut stdout = io::stdout();
d::list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
d::StrInput(_) => {
d::early_error("can not list metadata for stdin");
}
}
return;
}
let (crate_id, crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_id || crate_name || crate_file_name {
let attrs = parse_crate_attrs(&sess, &input);
let t_outputs = d::build_output_filenames(&input, &odir, &ofile,
attrs.as_slice(), &sess);
let id = link::find_crate_id(attrs.as_slice(), t_outputs.out_filestem);
if crate_id {
println!("{}", id.to_str());
}
if crate_name {
println!("{}", id.name);
}
if crate_file_name {
let crate_types = session::collect_crate_types(&sess,
attrs.as_slice());
for &style in crate_types.iter() {
let fname = link::filename_for_input(&sess, style, &id,
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
return;
}
d::compile_input(sess, cfg, &input, &odir, &ofile);
}
fn parse_crate_attrs(sess: &session::Session, input: &d::Input) ->
Vec<ast::Attribute>
|
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor(f: proc:Send()) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
let mut task_builder = task::task().named("rustc");
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task_builder.opts.stack_size = Some(STACK_SIZE);
}
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
match task_builder.try(proc() {
io::stdio::set_stderr(~w);
f()
}) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
if!value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr();
// a.span_bug or.bug call has already printed what
// it wants to print.
if!value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
diagnostic::Bug);
}
let xs = [
~"the compiler hit an unexpected failure path. this is a bug.",
"we would appreciate a bug report: " + BUG_REPORT_URL,
~"run with `RUST_BACKTRACE=1` for a backtrace",
];
for note in xs.iter() {
emitter.emit(None, *note, diagnostic::Note)
}
match r.read_to_str() {
Ok(s) => println!("{}", s),
Err(e) => emitter.emit(None,
format!("failed to read internal stderr: {}", e),
diagnostic::Error),
}
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(~io::util::NullWriter);
fail!();
}
}
}
pub fn main() {
std::os::set_exit_status(main_args(std::os::args()));
}
pub fn main_args(args: &[~str]) -> int {
let owned_args = args.to_owned();
monitor(proc() run_compiler(owned_args));
0
}
|
{
let result = match *input {
d::FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
d::StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(d::anon_src(),
(*src).clone(),
Vec::new(),
&sess.parse_sess)
}
};
result.move_iter().collect()
}
|
identifier_body
|
lib.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.
/*!
The Rust compiler.
# Note
This API is completely unstable and subject to change.
*/
#![crate_id = "rustc#0.10"]
#![comment = "The Rust compiler"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![allow(deprecated)]
#![feature(macro_rules, globs, struct_variant, managed_boxes, quote,
default_type_params, phase)]
extern crate flate;
extern crate arena;
extern crate syntax;
extern crate serialize;
extern crate sync;
extern crate getopts;
extern crate collections;
extern crate time;
#[phase(syntax, link)]
extern crate log;
use back::link;
use driver::session;
use middle::lint;
use d = driver::driver;
use std::any::AnyRefExt;
use std::cmp;
use std::io;
use std::os;
use std::str;
use std::task;
use syntax::ast;
use syntax::diagnostic::Emitter;
use syntax::diagnostic;
use syntax::parse;
pub mod middle {
pub mod trans;
pub mod ty;
pub mod ty_fold;
pub mod subst;
pub mod resolve;
pub mod resolve_lifetime;
pub mod typeck;
pub mod check_loop;
pub mod check_match;
pub mod check_const;
pub mod check_static;
pub mod lint;
pub mod borrowck;
pub mod dataflow;
pub mod mem_categorization;
pub mod liveness;
pub mod kind;
pub mod freevars;
pub mod pat_util;
pub mod region;
pub mod const_eval;
pub mod astencode;
pub mod lang_items;
pub mod privacy;
pub mod moves;
pub mod entry;
pub mod effect;
pub mod reachable;
pub mod graph;
pub mod cfg;
pub mod dead;
}
pub mod front {
pub mod config;
pub mod test;
pub mod std_inject;
pub mod assign_node_ids_and_map;
pub mod feature_gate;
pub mod show_span;
}
pub mod back {
pub mod abi;
pub mod archive;
pub mod arm;
pub mod link;
pub mod lto;
pub mod mips;
pub mod rpath;
pub mod svh;
pub mod target_strs;
pub mod x86;
pub mod x86_64;
}
pub mod metadata;
pub mod driver;
pub mod util {
pub mod common;
pub mod ppaux;
pub mod sha2;
pub mod nodemap;
}
pub mod lib {
pub mod llvm;
pub mod llvmdeps;
}
static BUG_REPORT_URL: &'static str =
"http://static.rust-lang.org/doc/master/complement-bugreport.html";
pub fn version(argv0: &str) {
let vers = match option_env!("CFG_VERSION") {
Some(vers) => vers,
None => "unknown version"
};
println!("{} {}", argv0, vers);
println!("host: {}", d::host_triple());
}
pub fn usage(argv0: &str) {
let message = format!("Usage: {} [OPTIONS] INPUT", argv0);
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message, d::optgroups().as_slice()));
}
pub fn
|
() {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
let lint_dict = lint::get_lint_dict();
let mut lint_dict = lint_dict.move_iter()
.map(|(k, v)| (v, k))
.collect::<Vec<(lint::LintSpec, &'static str)> >();
lint_dict.as_mut_slice().sort();
let mut max_key = 0;
for &(_, name) in lint_dict.iter() {
max_key = cmp::max(name.len(), max_key);
}
fn padded(max: uint, s: &str) -> ~str {
" ".repeat(max - s.len()) + s
}
println!("\nAvailable lint checks:\n");
println!(" {} {:7.7s} {}",
padded(max_key, "name"), "default", "meaning");
println!(" {} {:7.7s} {}\n",
padded(max_key, "----"), "-------", "-------");
for (spec, name) in lint_dict.move_iter() {
let name = name.replace("_", "-");
println!(" {} {:7.7s} {}",
padded(max_key, name),
lint::level_to_str(spec.default),
spec.desc);
}
println!("");
}
pub fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
let r = session::debugging_opts_map();
for tuple in r.iter() {
match *tuple {
(ref name, ref desc, _) => {
println!(" -Z {:>20s} -- {}", *name, *desc);
}
}
}
}
pub fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
let mut cg = session::basic_codegen_options();
for &(name, parser, desc) in session::CG_OPTIONS.iter() {
// we invoke the parser function on `None` to see if this option needs
// an argument or not.
let (width, extra) = if parser(&mut cg, None) {
(25, "")
} else {
(21, "=val")
};
println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
pub fn run_compiler(args: &[~str]) {
let mut args = args.to_owned();
let binary = args.shift().unwrap();
if args.is_empty() { usage(binary); return; }
let matches =
&match getopts::getopts(args, d::optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
d::early_error(f.to_err_msg());
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(binary);
return;
}
let lint_flags = matches.opt_strs("W").move_iter().collect::<Vec<_>>().append(
matches.opt_strs("warn").as_slice());
if lint_flags.iter().any(|x| x == &~"help") {
describe_warnings();
return;
}
let r = matches.opt_strs("Z");
if r.iter().any(|x| x == &~"help") {
describe_debug_flags();
return;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| x == &~"help") {
describe_codegen_flags();
return;
}
if cg_flags.contains(&~"passes=list") {
unsafe { lib::llvm::llvm::LLVMRustPrintPasses(); }
return;
}
if matches.opt_present("v") || matches.opt_present("version") {
version(binary);
return;
}
let (input, input_file_path) = match matches.free.len() {
0u => d::early_error("no input filename given"),
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = str::from_utf8_owned(contents).unwrap();
(d::StrInput(src), None)
} else {
(d::FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
}
_ => d::early_error("multiple input filenames provided")
};
let sopts = d::build_session_options(matches);
let sess = d::build_session(sopts, input_file_path);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
let ofile = matches.opt_str("o").map(|o| Path::new(o));
let cfg = d::build_configuration(&sess);
let pretty = matches.opt_default("pretty", "normal").map(|a| {
d::parse_pretty(&sess, a)
});
match pretty {
Some::<d::PpMode>(ppm) => {
d::pretty_print_input(sess, cfg, &input, ppm);
return;
}
None::<d::PpMode> => {/* continue */ }
}
let ls = matches.opt_present("ls");
if ls {
match input {
d::FileInput(ref ifile) => {
let mut stdout = io::stdout();
d::list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
}
d::StrInput(_) => {
d::early_error("can not list metadata for stdin");
}
}
return;
}
let (crate_id, crate_name, crate_file_name) = sess.opts.print_metas;
// these nasty nested conditions are to avoid doing extra work
if crate_id || crate_name || crate_file_name {
let attrs = parse_crate_attrs(&sess, &input);
let t_outputs = d::build_output_filenames(&input, &odir, &ofile,
attrs.as_slice(), &sess);
let id = link::find_crate_id(attrs.as_slice(), t_outputs.out_filestem);
if crate_id {
println!("{}", id.to_str());
}
if crate_name {
println!("{}", id.name);
}
if crate_file_name {
let crate_types = session::collect_crate_types(&sess,
attrs.as_slice());
for &style in crate_types.iter() {
let fname = link::filename_for_input(&sess, style, &id,
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
}
return;
}
d::compile_input(sess, cfg, &input, &odir, &ofile);
}
fn parse_crate_attrs(sess: &session::Session, input: &d::Input) ->
Vec<ast::Attribute> {
let result = match *input {
d::FileInput(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
d::StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(d::anon_src(),
(*src).clone(),
Vec::new(),
&sess.parse_sess)
}
};
result.move_iter().collect()
}
/// Run a procedure which will detect failures in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor(f: proc:Send()) {
// FIXME: This is a hack for newsched since it doesn't support split stacks.
// rustc needs a lot of stack! When optimizations are disabled, it needs
// even *more* stack than usual as well.
#[cfg(rtopt)]
static STACK_SIZE: uint = 6000000; // 6MB
#[cfg(not(rtopt))]
static STACK_SIZE: uint = 20000000; // 20MB
let mut task_builder = task::task().named("rustc");
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if os::getenv("RUST_MIN_STACK").is_none() {
task_builder.opts.stack_size = Some(STACK_SIZE);
}
let (tx, rx) = channel();
let w = io::ChanWriter::new(tx);
let mut r = io::ChanReader::new(rx);
match task_builder.try(proc() {
io::stdio::set_stderr(~w);
f()
}) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
if!value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr();
// a.span_bug or.bug call has already printed what
// it wants to print.
if!value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
diagnostic::Bug);
}
let xs = [
~"the compiler hit an unexpected failure path. this is a bug.",
"we would appreciate a bug report: " + BUG_REPORT_URL,
~"run with `RUST_BACKTRACE=1` for a backtrace",
];
for note in xs.iter() {
emitter.emit(None, *note, diagnostic::Note)
}
match r.read_to_str() {
Ok(s) => println!("{}", s),
Err(e) => emitter.emit(None,
format!("failed to read internal stderr: {}", e),
diagnostic::Error),
}
}
// Fail so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already
// printed everything that we needed to.
io::stdio::set_stderr(~io::util::NullWriter);
fail!();
}
}
}
pub fn main() {
std::os::set_exit_status(main_args(std::os::args()));
}
pub fn main_args(args: &[~str]) -> int {
let owned_args = args.to_owned();
monitor(proc() run_compiler(owned_args));
0
}
|
describe_warnings
|
identifier_name
|
arithmetic_mean.rs
|
// http://rosettacode.org/wiki/Averages/Arithmetic_mean
// The mean is not defined for an empty list, so we must return an Option
fn mean(list: &[f64]) -> Option<f64> {
match list.len() {
0 => None,
n => {
let sum = list.iter().fold(0f64, |a, &b| a + b);
Some(sum / n as f64)
}
}
}
#[cfg(not(test))]
fn main() {
let input = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0];
// This should be 3.833333
let mean = mean(&input).unwrap();
println!("{}", mean);
}
#[test]
fn simple_test() {
let nums = [1.0, 2.0, 3.0, 4.0, 5.0];
assert_eq!(mean(&nums), Some(3.0));
}
#[test]
fn mean_empty_list()
|
{
let no_nums = [];
assert_eq!(mean(&no_nums), None);
}
|
identifier_body
|
|
arithmetic_mean.rs
|
// http://rosettacode.org/wiki/Averages/Arithmetic_mean
// The mean is not defined for an empty list, so we must return an Option
fn mean(list: &[f64]) -> Option<f64> {
match list.len() {
0 => None,
n => {
let sum = list.iter().fold(0f64, |a, &b| a + b);
Some(sum / n as f64)
}
}
}
#[cfg(not(test))]
fn main() {
let input = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0];
// This should be 3.833333
let mean = mean(&input).unwrap();
println!("{}", mean);
}
#[test]
fn
|
() {
let nums = [1.0, 2.0, 3.0, 4.0, 5.0];
assert_eq!(mean(&nums), Some(3.0));
}
#[test]
fn mean_empty_list() {
let no_nums = [];
assert_eq!(mean(&no_nums), None);
}
|
simple_test
|
identifier_name
|
arithmetic_mean.rs
|
// http://rosettacode.org/wiki/Averages/Arithmetic_mean
// The mean is not defined for an empty list, so we must return an Option
fn mean(list: &[f64]) -> Option<f64> {
match list.len() {
0 => None,
n => {
let sum = list.iter().fold(0f64, |a, &b| a + b);
Some(sum / n as f64)
}
}
}
#[cfg(not(test))]
fn main() {
let input = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0];
|
#[test]
fn simple_test() {
let nums = [1.0, 2.0, 3.0, 4.0, 5.0];
assert_eq!(mean(&nums), Some(3.0));
}
#[test]
fn mean_empty_list() {
let no_nums = [];
assert_eq!(mean(&no_nums), None);
}
|
// This should be 3.833333
let mean = mean(&input).unwrap();
println!("{}", mean);
}
|
random_line_split
|
vec-self-append.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.
extern mod extra;
fn test_heap_to_heap() {
// a spills onto the heap
let mut a = ~[0, 1, 2, 3, 4];
a = a + a; // FIXME(#3387)---can't write a += a
assert_eq!(a.len(), 10u);
assert_eq!(a[0], 0);
assert_eq!(a[1], 1);
assert_eq!(a[2], 2);
assert_eq!(a[3], 3);
assert_eq!(a[4], 4);
assert_eq!(a[5], 0);
assert_eq!(a[6], 1);
assert_eq!(a[7], 2);
assert_eq!(a[8], 3);
assert_eq!(a[9], 4);
}
fn test_stack_to_heap() {
// a is entirely on the stack
let mut a = ~[0, 1, 2];
// a spills to the heap
a = a + a; // FIXME(#3387)---can't write a += a
assert_eq!(a.len(), 6u);
assert_eq!(a[0], 0);
assert_eq!(a[1], 1);
assert_eq!(a[2], 2);
assert_eq!(a[3], 0);
assert_eq!(a[4], 1);
assert_eq!(a[5], 2);
}
fn test_loop() {
// Make sure we properly handle repeated self-appends.
let mut a: ~[int] = ~[0];
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
error2!("{}", a.len());
assert_eq!(a.len(), expected_len);
a = a + a; // FIXME(#3387)---can't write a += a
i -= 1;
expected_len *= 2u;
}
}
pub fn main() { test_heap_to_heap(); test_stack_to_heap(); test_loop(); }
|
random_line_split
|
|
vec-self-append.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.
extern mod extra;
fn test_heap_to_heap() {
// a spills onto the heap
let mut a = ~[0, 1, 2, 3, 4];
a = a + a; // FIXME(#3387)---can't write a += a
assert_eq!(a.len(), 10u);
assert_eq!(a[0], 0);
assert_eq!(a[1], 1);
assert_eq!(a[2], 2);
assert_eq!(a[3], 3);
assert_eq!(a[4], 4);
assert_eq!(a[5], 0);
assert_eq!(a[6], 1);
assert_eq!(a[7], 2);
assert_eq!(a[8], 3);
assert_eq!(a[9], 4);
}
fn test_stack_to_heap()
|
fn test_loop() {
// Make sure we properly handle repeated self-appends.
let mut a: ~[int] = ~[0];
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
error2!("{}", a.len());
assert_eq!(a.len(), expected_len);
a = a + a; // FIXME(#3387)---can't write a += a
i -= 1;
expected_len *= 2u;
}
}
pub fn main() { test_heap_to_heap(); test_stack_to_heap(); test_loop(); }
|
{
// a is entirely on the stack
let mut a = ~[0, 1, 2];
// a spills to the heap
a = a + a; // FIXME(#3387)---can't write a += a
assert_eq!(a.len(), 6u);
assert_eq!(a[0], 0);
assert_eq!(a[1], 1);
assert_eq!(a[2], 2);
assert_eq!(a[3], 0);
assert_eq!(a[4], 1);
assert_eq!(a[5], 2);
}
|
identifier_body
|
vec-self-append.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.
extern mod extra;
fn test_heap_to_heap() {
// a spills onto the heap
let mut a = ~[0, 1, 2, 3, 4];
a = a + a; // FIXME(#3387)---can't write a += a
assert_eq!(a.len(), 10u);
assert_eq!(a[0], 0);
assert_eq!(a[1], 1);
assert_eq!(a[2], 2);
assert_eq!(a[3], 3);
assert_eq!(a[4], 4);
assert_eq!(a[5], 0);
assert_eq!(a[6], 1);
assert_eq!(a[7], 2);
assert_eq!(a[8], 3);
assert_eq!(a[9], 4);
}
fn test_stack_to_heap() {
// a is entirely on the stack
let mut a = ~[0, 1, 2];
// a spills to the heap
a = a + a; // FIXME(#3387)---can't write a += a
assert_eq!(a.len(), 6u);
assert_eq!(a[0], 0);
assert_eq!(a[1], 1);
assert_eq!(a[2], 2);
assert_eq!(a[3], 0);
assert_eq!(a[4], 1);
assert_eq!(a[5], 2);
}
fn test_loop() {
// Make sure we properly handle repeated self-appends.
let mut a: ~[int] = ~[0];
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
error2!("{}", a.len());
assert_eq!(a.len(), expected_len);
a = a + a; // FIXME(#3387)---can't write a += a
i -= 1;
expected_len *= 2u;
}
}
pub fn
|
() { test_heap_to_heap(); test_stack_to_heap(); test_loop(); }
|
main
|
identifier_name
|
macros.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// Interns the passed string literal and memoizes the result in a static
/// variable. This can be used in performance sensitive code.
/// ```
/// use interner::intern;
/// assert_eq!(intern!("example").lookup(), "example");
/// ```
#[macro_export]
macro_rules! intern {
($value:literal) => {{
use $crate::{reexport::Lazy, Intern, StringKey};
static KEY: Lazy<StringKey> = Lazy::new(|| Intern::intern($value));
*KEY
}};
($_:expr) => {
compile_error!("intern! macro can only be used with string literals.")
};
}
/// Macro to implement an interner for an arbitrary type.
/// Given `intern!(<Foo> as <FooKey>);`, this macro will implement the
/// `Intern` trait for `<Foo>`, interning it a generated `<FooKey>` wrapper
|
///
/// # Example
///
/// ```ignore
/// use common::{Intern, intern, StringKey};
/// pub struct User {
/// name: StringKey,
/// }
/// intern!(User as UserKey); // defines the `UserKey` type
///
/// let name: StringKey = "Joe".intern();
/// let user: User = User { name };
/// let user_key: UserKey = user.intern();
/// ```
///
#[macro_export]
macro_rules! make_intern {
($name:ident as $alias:ident) => {
use crate::{Intern, InternKey, InternTable, RawInternKey};
use lazy_static::lazy_static;
lazy_static! {
/// Global interning table for this type
static ref INTERN_TABLE: InternTable<$alias, $name> = InternTable::new();
}
/// Wrapper type for the intern key
#[derive(Copy, Clone, Debug, Eq, Ord, Hash, PartialEq, PartialOrd)]
pub struct $alias(RawInternKey);
impl InternKey for $alias {
type Value = $name;
fn from_raw(raw: RawInternKey) -> Self {
Self(raw)
}
fn into_raw(self) -> RawInternKey {
self.0
}
fn lookup(self) -> &'static Self::Value {
INTERN_TABLE.lookup(self)
}
}
/// The type interns into the generated key type
impl Intern for $name {
type Key = $alias;
fn intern(self) -> Self::Key {
INTERN_TABLE.intern(self)
}
}
};
}
|
/// type. Calling `FooKey::lookup()` will return a reference to the original
/// `<Foo>` value.
|
random_line_split
|
headers.rs
|
use std::ops::Range;
use crate::*;
use super::Wrap;
/// Describes the PE headers.
impl<'a, Pe32: pe32::Pe<'a>, Pe64: pe64::Pe<'a>> Wrap<pe32::headers::Headers<Pe32>, pe64::headers::Headers<Pe64>> {
/// Gets the PE instance.
#[inline]
pub fn pe(&self) -> Wrap<Pe32, Pe64> {
match self {
Wrap::T32(headers) => Wrap::T32(headers.pe()),
Wrap::T64(headers) => Wrap::T64(headers.pe()),
}
}
/// Gets the PE headers as a byte slice.
#[inline]
pub fn image(&self) -> &'a [u8] {
match self {
Wrap::T32(headers) => headers.image(),
Wrap::T64(headers) => headers.image(),
}
}
/// Calculates the optional header's CheckSum.
#[inline]
pub fn
|
(&self) -> u32 {
match self {
Wrap::T32(headers) => headers.check_sum(),
Wrap::T64(headers) => headers.check_sum(),
}
}
/// Gets the code range from the optional header.
#[inline]
pub fn code_range(&self) -> Range<u32> {
match self {
Wrap::T32(headers) => headers.code_range(),
Wrap::T64(headers) => headers.code_range(),
}
}
/// Gets the full image range excluding the PE headers.
#[inline]
pub fn image_range(&self) -> Range<u32> {
match self {
Wrap::T32(headers) => headers.image_range(),
Wrap::T64(headers) => headers.image_range(),
}
}
}
|
check_sum
|
identifier_name
|
headers.rs
|
use std::ops::Range;
use crate::*;
use super::Wrap;
/// Describes the PE headers.
impl<'a, Pe32: pe32::Pe<'a>, Pe64: pe64::Pe<'a>> Wrap<pe32::headers::Headers<Pe32>, pe64::headers::Headers<Pe64>> {
/// Gets the PE instance.
#[inline]
pub fn pe(&self) -> Wrap<Pe32, Pe64> {
match self {
Wrap::T32(headers) => Wrap::T32(headers.pe()),
Wrap::T64(headers) => Wrap::T64(headers.pe()),
}
}
/// Gets the PE headers as a byte slice.
#[inline]
pub fn image(&self) -> &'a [u8] {
match self {
Wrap::T32(headers) => headers.image(),
Wrap::T64(headers) => headers.image(),
}
}
/// Calculates the optional header's CheckSum.
#[inline]
pub fn check_sum(&self) -> u32 {
match self {
Wrap::T32(headers) => headers.check_sum(),
Wrap::T64(headers) => headers.check_sum(),
}
}
/// Gets the code range from the optional header.
#[inline]
pub fn code_range(&self) -> Range<u32> {
match self {
Wrap::T32(headers) => headers.code_range(),
Wrap::T64(headers) => headers.code_range(),
}
}
/// Gets the full image range excluding the PE headers.
#[inline]
pub fn image_range(&self) -> Range<u32> {
match self {
Wrap::T32(headers) => headers.image_range(),
Wrap::T64(headers) => headers.image_range(),
}
|
}
|
}
|
random_line_split
|
headers.rs
|
use std::ops::Range;
use crate::*;
use super::Wrap;
/// Describes the PE headers.
impl<'a, Pe32: pe32::Pe<'a>, Pe64: pe64::Pe<'a>> Wrap<pe32::headers::Headers<Pe32>, pe64::headers::Headers<Pe64>> {
/// Gets the PE instance.
#[inline]
pub fn pe(&self) -> Wrap<Pe32, Pe64>
|
/// Gets the PE headers as a byte slice.
#[inline]
pub fn image(&self) -> &'a [u8] {
match self {
Wrap::T32(headers) => headers.image(),
Wrap::T64(headers) => headers.image(),
}
}
/// Calculates the optional header's CheckSum.
#[inline]
pub fn check_sum(&self) -> u32 {
match self {
Wrap::T32(headers) => headers.check_sum(),
Wrap::T64(headers) => headers.check_sum(),
}
}
/// Gets the code range from the optional header.
#[inline]
pub fn code_range(&self) -> Range<u32> {
match self {
Wrap::T32(headers) => headers.code_range(),
Wrap::T64(headers) => headers.code_range(),
}
}
/// Gets the full image range excluding the PE headers.
#[inline]
pub fn image_range(&self) -> Range<u32> {
match self {
Wrap::T32(headers) => headers.image_range(),
Wrap::T64(headers) => headers.image_range(),
}
}
}
|
{
match self {
Wrap::T32(headers) => Wrap::T32(headers.pe()),
Wrap::T64(headers) => Wrap::T64(headers.pe()),
}
}
|
identifier_body
|
view_conversion.rs
|
// local imports
use view::MatrixView;
use traits::*;
use sralgebra::MagmaBase;
/// Implements matrix conversion API
impl <'a, T:MagmaBase> Conversion<T> for MatrixView<'a, T> {
/// Converts the view to vector from standard library
fn to_std_vec(&self) -> Vec<T> {
let mut vec: Vec<T> = Vec::with_capacity(self.num_cells());
// We iterate over elements in matrix and push in the vector
let ptr = self.matrix().as_ptr();
for c in 0..self.num_cols(){
for r in 0..self.num_rows(){
let offset = self.cell_to_offset(r, c);
vec.push(unsafe{*ptr.offset(offset)});
}
}
vec
}
}
#[cfg(test)]
mod test{
use traits::*;
use constructors::*;
#[test]
fn
|
(){
let m = matrix_rw_i32(3, 3, &[1, 2, 3,
4, 5, 6,
7, 8, 9]);
let v = m.view(2,1, 1, 1);
assert_eq!(v.to_scalar(), 8);
}
}
|
test_view_to_scalar
|
identifier_name
|
view_conversion.rs
|
// local imports
use view::MatrixView;
use traits::*;
use sralgebra::MagmaBase;
/// Implements matrix conversion API
impl <'a, T:MagmaBase> Conversion<T> for MatrixView<'a, T> {
/// Converts the view to vector from standard library
fn to_std_vec(&self) -> Vec<T> {
let mut vec: Vec<T> = Vec::with_capacity(self.num_cells());
// We iterate over elements in matrix and push in the vector
let ptr = self.matrix().as_ptr();
for c in 0..self.num_cols(){
for r in 0..self.num_rows(){
let offset = self.cell_to_offset(r, c);
vec.push(unsafe{*ptr.offset(offset)});
}
}
vec
}
}
#[cfg(test)]
mod test{
use traits::*;
use constructors::*;
#[test]
fn test_view_to_scalar(){
let m = matrix_rw_i32(3, 3, &[1, 2, 3,
|
}
}
|
4, 5, 6,
7, 8, 9]);
let v = m.view(2,1, 1, 1);
assert_eq!(v.to_scalar(), 8);
|
random_line_split
|
view_conversion.rs
|
// local imports
use view::MatrixView;
use traits::*;
use sralgebra::MagmaBase;
/// Implements matrix conversion API
impl <'a, T:MagmaBase> Conversion<T> for MatrixView<'a, T> {
/// Converts the view to vector from standard library
fn to_std_vec(&self) -> Vec<T>
|
}
#[cfg(test)]
mod test{
use traits::*;
use constructors::*;
#[test]
fn test_view_to_scalar(){
let m = matrix_rw_i32(3, 3, &[1, 2, 3,
4, 5, 6,
7, 8, 9]);
let v = m.view(2,1, 1, 1);
assert_eq!(v.to_scalar(), 8);
}
}
|
{
let mut vec: Vec<T> = Vec::with_capacity(self.num_cells());
// We iterate over elements in matrix and push in the vector
let ptr = self.matrix().as_ptr();
for c in 0..self.num_cols(){
for r in 0..self.num_rows(){
let offset = self.cell_to_offset(r, c);
vec.push(unsafe{*ptr.offset(offset)});
}
}
vec
}
|
identifier_body
|
function-prologue-stepping-regular.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.
// This test case checks if function arguments already have the correct value when breaking at the
// beginning of a function.
// min-lldb-version: 310
// ignore-gdb
// ignore-test // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// compile-flags:-g
// lldb-command:breakpoint set --name immediate_args
// lldb-command:breakpoint set --name non_immediate_args
// lldb-command:breakpoint set --name binding
// lldb-command:breakpoint set --name assignment
// lldb-command:breakpoint set --name function_call
// lldb-command:breakpoint set --name identifier
// lldb-command:breakpoint set --name return_expr
// lldb-command:breakpoint set --name arithmetic_expr
// lldb-command:breakpoint set --name if_expr
// lldb-command:breakpoint set --name while_expr
// lldb-command:breakpoint set --name loop_expr
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
// lldb-command:print a
// lldb-check:[...]$8 = 22
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: isize, b: bool, c: f64) {
()
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
()
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0;
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b;
}
fn function_call(x: u64, y: u64, z: f64) {
println!("Hi!")
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x;
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
|
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 {
x
} else {
y
}
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y < 1000 {
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop {
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main() {
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
x + y
|
random_line_split
|
function-prologue-stepping-regular.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.
// This test case checks if function arguments already have the correct value when breaking at the
// beginning of a function.
// min-lldb-version: 310
// ignore-gdb
// ignore-test // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// compile-flags:-g
// lldb-command:breakpoint set --name immediate_args
// lldb-command:breakpoint set --name non_immediate_args
// lldb-command:breakpoint set --name binding
// lldb-command:breakpoint set --name assignment
// lldb-command:breakpoint set --name function_call
// lldb-command:breakpoint set --name identifier
// lldb-command:breakpoint set --name return_expr
// lldb-command:breakpoint set --name arithmetic_expr
// lldb-command:breakpoint set --name if_expr
// lldb-command:breakpoint set --name while_expr
// lldb-command:breakpoint set --name loop_expr
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
// lldb-command:print a
// lldb-check:[...]$8 = 22
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: isize, b: bool, c: f64) {
()
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
()
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0;
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b;
}
fn function_call(x: u64, y: u64, z: f64) {
println!("Hi!")
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x;
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 {
x
} else {
y
}
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y < 1000 {
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop {
x += z;
if x + y > 1000
|
}
}
fn main() {
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
{
return x;
}
|
conditional_block
|
function-prologue-stepping-regular.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.
// This test case checks if function arguments already have the correct value when breaking at the
// beginning of a function.
// min-lldb-version: 310
// ignore-gdb
// ignore-test // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// compile-flags:-g
// lldb-command:breakpoint set --name immediate_args
// lldb-command:breakpoint set --name non_immediate_args
// lldb-command:breakpoint set --name binding
// lldb-command:breakpoint set --name assignment
// lldb-command:breakpoint set --name function_call
// lldb-command:breakpoint set --name identifier
// lldb-command:breakpoint set --name return_expr
// lldb-command:breakpoint set --name arithmetic_expr
// lldb-command:breakpoint set --name if_expr
// lldb-command:breakpoint set --name while_expr
// lldb-command:breakpoint set --name loop_expr
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
// lldb-command:print a
// lldb-check:[...]$8 = 22
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: isize, b: bool, c: f64) {
()
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
()
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0;
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b;
}
fn function_call(x: u64, y: u64, z: f64) {
println!("Hi!")
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x;
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 {
x
} else {
y
}
}
fn
|
(mut x: u64, y: u64, z: u64) -> u64 {
while x + y < 1000 {
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop {
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main() {
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
while_expr
|
identifier_name
|
function-prologue-stepping-regular.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.
// This test case checks if function arguments already have the correct value when breaking at the
// beginning of a function.
// min-lldb-version: 310
// ignore-gdb
// ignore-test // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// compile-flags:-g
// lldb-command:breakpoint set --name immediate_args
// lldb-command:breakpoint set --name non_immediate_args
// lldb-command:breakpoint set --name binding
// lldb-command:breakpoint set --name assignment
// lldb-command:breakpoint set --name function_call
// lldb-command:breakpoint set --name identifier
// lldb-command:breakpoint set --name return_expr
// lldb-command:breakpoint set --name arithmetic_expr
// lldb-command:breakpoint set --name if_expr
// lldb-command:breakpoint set --name while_expr
// lldb-command:breakpoint set --name loop_expr
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
// lldb-command:print a
// lldb-check:[...]$8 = 22
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: isize, b: bool, c: f64) {
()
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
()
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0;
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b;
}
fn function_call(x: u64, y: u64, z: f64) {
println!("Hi!")
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x;
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 {
x
} else {
y
}
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y < 1000 {
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop {
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main()
|
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
{
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
|
identifier_body
|
color.rs
|
pub enum ColorName {
Black,
Blue,
Red,
Purple,
Green,
Cyan,
Yellow,
White,
}
pub fn number_to_color(num: u8) -> ColorName {
match num {
0 => ColorName::Black,
1 => ColorName::Blue,
2 => ColorName::Red,
3 => ColorName::Purple,
4 => ColorName::Green,
5 => ColorName::Cyan,
6 => ColorName::Yellow,
_ => ColorName::White,
}
}
pub struct
|
{
blue: bool,
red: bool,
green: bool,
pub value: u8,
}
fn trf(val: bool) -> u16 {
if val { 4095 } else { 0 }
}
impl Color {
pub fn new(name: ColorName) -> Color {
let value = name as u8;
Color {
blue: (value & 1) > 0,
red: (value & 2) > 0,
green: (value & 4) > 0,
value: value,
}
}
pub fn to_array(&self) -> [u16; 3] {
[trf(self.blue), trf(self.red), trf(self.green)]
}
}
|
Color
|
identifier_name
|
color.rs
|
pub enum ColorName {
Black,
Blue,
Red,
Purple,
Green,
Cyan,
Yellow,
White,
}
pub fn number_to_color(num: u8) -> ColorName {
match num {
0 => ColorName::Black,
1 => ColorName::Blue,
2 => ColorName::Red,
3 => ColorName::Purple,
4 => ColorName::Green,
5 => ColorName::Cyan,
6 => ColorName::Yellow,
_ => ColorName::White,
}
}
pub struct Color {
blue: bool,
red: bool,
green: bool,
pub value: u8,
}
fn trf(val: bool) -> u16 {
if val { 4095 } else { 0 }
}
impl Color {
pub fn new(name: ColorName) -> Color {
|
let value = name as u8;
Color {
blue: (value & 1) > 0,
red: (value & 2) > 0,
green: (value & 4) > 0,
value: value,
}
}
pub fn to_array(&self) -> [u16; 3] {
[trf(self.blue), trf(self.red), trf(self.green)]
}
}
|
random_line_split
|
|
color.rs
|
pub enum ColorName {
Black,
Blue,
Red,
Purple,
Green,
Cyan,
Yellow,
White,
}
pub fn number_to_color(num: u8) -> ColorName {
match num {
0 => ColorName::Black,
1 => ColorName::Blue,
2 => ColorName::Red,
3 => ColorName::Purple,
4 => ColorName::Green,
5 => ColorName::Cyan,
6 => ColorName::Yellow,
_ => ColorName::White,
}
}
pub struct Color {
blue: bool,
red: bool,
green: bool,
pub value: u8,
}
fn trf(val: bool) -> u16 {
if val { 4095 } else { 0 }
}
impl Color {
pub fn new(name: ColorName) -> Color
|
pub fn to_array(&self) -> [u16; 3] {
[trf(self.blue), trf(self.red), trf(self.green)]
}
}
|
{
let value = name as u8;
Color {
blue: (value & 1) > 0,
red: (value & 2) > 0,
green: (value & 4) > 0,
value: value,
}
}
|
identifier_body
|
offsets.rs
|
use byteorder::{BigEndian, ReadBytesExt};
use futures::Stream;
use rdkafka::config::{ClientConfig, TopicConfig};
use rdkafka::consumer::stream_consumer::StreamConsumer;
use rdkafka::consumer::{Consumer, EmptyConsumerContext};
use rdkafka::error::KafkaError;
use rdkafka::{Message, Offset, TopicPartitionList};
use cache::{Cache, OffsetsCache};
use config::{ClusterConfig, Config};
use error::*;
use metadata::{ClusterId, TopicName};
use utils::{insert_at, read_string};
use std::cmp;
use std::collections::HashMap;
use std::io::Cursor;
use std::str;
use std::thread;
use std::time::{Duration, Instant};
#[derive(Debug)]
enum ConsumerUpdate {
Metadata,
OffsetCommit {
group: String,
topic: String,
partition: i32,
offset: i64,
},
OffsetTombstone {
group: String,
topic: String,
partition: i32,
},
}
fn parse_group_offset(
key_rdr: &mut Cursor<&[u8]>,
payload_rdr: &mut Cursor<&[u8]>,
) -> Result<ConsumerUpdate> {
let group = read_string(key_rdr).chain_err(|| "Failed to parse group name from key")?;
let topic = read_string(key_rdr).chain_err(|| "Failed to parse topic name from key")?;
let partition = key_rdr
.read_i32::<BigEndian>()
.chain_err(|| "Failed to parse partition from key")?;
if!payload_rdr.get_ref().is_empty() {
// payload is not empty
let _version = payload_rdr
.read_i16::<BigEndian>()
.chain_err(|| "Failed to parse value version")?;
let offset = payload_rdr
.read_i64::<BigEndian>()
.chain_err(|| "Failed to parse offset from value")?;
Ok(ConsumerUpdate::OffsetCommit {
group,
topic,
partition,
offset,
})
} else {
Ok(ConsumerUpdate::OffsetTombstone {
group,
topic,
partition,
})
}
}
fn parse_message(key: &[u8], payload: &[u8]) -> Result<ConsumerUpdate> {
let mut key_rdr = Cursor::new(key);
let key_version = key_rdr
.read_i16::<BigEndian>()
.chain_err(|| "Failed to parse key version")?;
match key_version {
0 | 1 => parse_group_offset(&mut key_rdr, &mut Cursor::new(payload))
.chain_err(|| "Failed to parse group offset update"),
2 => Ok(ConsumerUpdate::Metadata),
_ => bail!("Key version not recognized"),
}
}
fn
|
(
brokers: &str,
group_id: &str,
start_offsets: Option<Vec<i64>>,
) -> Result<StreamConsumer<EmptyConsumerContext>> {
let consumer = ClientConfig::new()
.set("group.id", group_id)
.set("bootstrap.servers", brokers)
.set("enable.partition.eof", "false")
.set("enable.auto.commit", "false")
.set("session.timeout.ms", "30000")
.set("api.version.request", "true")
//.set("fetch.message.max.bytes", "1024000") // Reduce memory usage
.set("queued.min.messages", "10000") // Reduce memory usage
.set("message.max.bytes", "10485760")
.set_default_topic_config(
TopicConfig::new()
.set("auto.offset.reset", "smallest")
.finalize(),
)
.create::<StreamConsumer<_>>()
.chain_err(|| format!("Consumer creation failed: {}", brokers))?;
match start_offsets {
Some(pos) => {
let mut tp_list = TopicPartitionList::new();
for (partition, &offset) in pos.iter().enumerate() {
tp_list.add_partition_offset(
"__consumer_offsets",
partition as i32,
Offset::Offset(offset),
);
}
debug!(
"Previous offsets found, assigning offsets explicitly: {:?}",
tp_list
);
consumer
.assign(&tp_list)
.chain_err(|| "Failure during consumer assignment")?;
}
None => {
debug!("No previous offsets found, subscribing to topic");
consumer.subscribe(&["__consumer_offsets"]).chain_err(|| {
format!("Can't subscribe to offset __consumer_offsets ({})", brokers)
})?;
}
}
Ok(consumer)
}
// we should really have some tests here
fn update_global_cache(
cluster_id: &ClusterId,
local_cache: &HashMap<(String, String), Vec<i64>>,
cache: &OffsetsCache,
) {
for (&(ref group, ref topic), new_offsets) in local_cache {
// Consider a consuming iterator
// This logic is not needed if i store the consumer offset, right? wrong!
if new_offsets.iter().any(|&offset| offset == -1) {
if let Some(mut existing_offsets) =
cache.get(&(cluster_id.to_owned(), group.to_owned(), topic.to_owned()))
{
// If the new offset is not complete and i have an old one, do the merge
vec_merge_in_place(&mut existing_offsets, &new_offsets, -1, cmp::max);
// for i in 0..(cmp::max(offsets.len(), existing_offsets.len())) {
// let new_offset = cmp::max(
// offsets.get(i).cloned().unwrap_or(-1),
// existing_offsets.get(i).cloned().unwrap_or(-1));
// insert_at(&mut existing_offsets, i, new_offset, -1);
// }
let _ = cache.insert(
(cluster_id.to_owned(), group.to_owned(), topic.to_owned()),
existing_offsets,
);
continue;
}
}
// TODO: log errors
let _ = cache.insert(
(cluster_id.to_owned(), group.to_owned(), topic.to_owned()),
new_offsets.clone(),
);
}
}
fn commit_offset_position_to_array(tp_list: TopicPartitionList) -> Vec<i64> {
let tp_elements = tp_list.elements_for_topic("__consumer_offsets");
let mut offsets = vec![0; tp_elements.len()];
for tp in &tp_elements {
offsets[tp.partition() as usize] = tp.offset().to_raw();
}
offsets
}
fn consume_offset_topic(
cluster_id: ClusterId,
consumer: StreamConsumer<EmptyConsumerContext>,
cache: &Cache,
) -> Result<()> {
let mut local_cache = HashMap::new();
let mut last_dump = Instant::now();
debug!("Starting offset consumer loop for {:?}", cluster_id);
for message in consumer.start_with(Duration::from_millis(200), true).wait() {
match message {
Ok(Ok(m)) => {
let key = m.key().unwrap_or(&[]);
let payload = m.payload().unwrap_or(&[]);
match parse_message(key, payload) {
Ok(ConsumerUpdate::OffsetCommit {
group,
topic,
partition,
offset,
}) => {
let mut offsets = local_cache
.entry((group.to_owned(), topic.to_owned()))
.or_insert_with(Vec::new);
insert_at(&mut offsets, partition as usize, offset, -1);
}
Ok(_) => {}
Err(e) => format_error_chain!(e),
};
}
Ok(Err(KafkaError::NoMessageReceived)) => {}
Ok(Err(e)) => warn!("Kafka error: {} {:?}", cluster_id, e),
Err(e) => warn!("Can't receive data from stream: {:?}", e),
};
// Update the cache if needed
if (Instant::now() - last_dump) > Duration::from_secs(10) {
trace!(
"Dumping local offset cache ({}: {} updates)",
cluster_id,
local_cache.len()
);
update_global_cache(&cluster_id, &local_cache, &cache.offsets);
// Consumer position is not up to date after start, so we have to merge with the
// existing offsets and take the largest.
let res = consumer
.position()
.map(|current_position| {
let previous_position_vec = cache
.internal_offsets
.get(&cluster_id)
.unwrap_or_else(Vec::new);
let mut current_position_vec =
commit_offset_position_to_array(current_position);
vec_merge_in_place(
&mut current_position_vec,
&previous_position_vec,
Offset::Invalid.to_raw(),
cmp::max,
);
cache
.internal_offsets
.insert(cluster_id.clone(), current_position_vec)
})
.chain_err(|| "Failed to store consumer offset position")?;
if let Err(e) = res {
format_error_chain!(e);
}
local_cache = HashMap::with_capacity(local_cache.len());
last_dump = Instant::now();
}
}
Ok(())
}
pub fn vec_merge_in_place<F, T: Copy>(vec1: &mut Vec<T>, vec2: &[T], default: T, merge_fn: F)
where
F: Fn(T, T) -> T,
{
let new_len = cmp::max(vec1.len(), vec2.len());
vec1.resize(new_len, default);
for i in 0..vec1.len() {
vec1[i] = merge_fn(
vec1.get(i).unwrap_or(&default).to_owned(),
vec2.get(i).unwrap_or(&default).to_owned(),
);
}
}
//pub fn vec_merge<F, T: Clone>(vec1: Vec<T>, vec2: Vec<T>, default: T, merge: F) -> Vec<T>
// where F: Fn(T, T) -> T
//{
// (0..cmp::max(vec1.len(), vec2.len()))
// .map(|index|
// merge(
// vec1.get(index).unwrap_or(&default).to_owned(),
// vec2.get(index).unwrap_or(&default).to_owned()))
// .collect::<Vec<T>>()
//}
pub fn run_offset_consumer(
cluster_id: &ClusterId,
cluster_config: &ClusterConfig,
config: &Config,
cache: &Cache,
) -> Result<()> {
let start_position = cache.internal_offsets.get(cluster_id);
let consumer = create_consumer(
&cluster_config.bootstrap_servers(),
&config.consumer_offsets_group_id,
start_position,
)
.chain_err(|| format!("Failed to create offset consumer for {}", cluster_id))?;
let cluster_id_clone = cluster_id.clone();
let cache_alias = cache.alias();
let _ = thread::Builder::new()
.name("offset-consumer".to_owned())
.spawn(move || {
if let Err(e) = consume_offset_topic(cluster_id_clone, consumer, &cache_alias) {
format_error_chain!(e);
}
})
.chain_err(|| "Failed to start offset consumer thread")?;
Ok(())
}
pub trait OffsetStore {
fn offsets_by_cluster(
&self,
cluster_id: &ClusterId,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
fn offsets_by_cluster_topic(
&self,
cluster_id: &ClusterId,
topic_name: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
fn offsets_by_cluster_group(
&self,
cluster_id: &ClusterId,
group_name: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
}
impl OffsetStore for Cache {
fn offsets_by_cluster(
&self,
cluster: &ClusterId,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets.filter_clone(|&(ref c, _, _)| c == cluster)
}
fn offsets_by_cluster_topic(
&self,
cluster: &ClusterId,
topic: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets
.filter_clone(|&(ref c, _, ref t)| c == cluster && t == topic)
}
fn offsets_by_cluster_group(
&self,
cluster: &ClusterId,
group: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets
.filter_clone(|&(ref c, ref g, _)| c == cluster && g == group)
}
}
|
create_consumer
|
identifier_name
|
offsets.rs
|
use byteorder::{BigEndian, ReadBytesExt};
use futures::Stream;
use rdkafka::config::{ClientConfig, TopicConfig};
use rdkafka::consumer::stream_consumer::StreamConsumer;
use rdkafka::consumer::{Consumer, EmptyConsumerContext};
use rdkafka::error::KafkaError;
use rdkafka::{Message, Offset, TopicPartitionList};
use cache::{Cache, OffsetsCache};
use config::{ClusterConfig, Config};
use error::*;
use metadata::{ClusterId, TopicName};
use utils::{insert_at, read_string};
use std::cmp;
use std::collections::HashMap;
use std::io::Cursor;
use std::str;
use std::thread;
use std::time::{Duration, Instant};
#[derive(Debug)]
enum ConsumerUpdate {
Metadata,
OffsetCommit {
group: String,
topic: String,
partition: i32,
offset: i64,
},
OffsetTombstone {
group: String,
topic: String,
partition: i32,
},
}
fn parse_group_offset(
key_rdr: &mut Cursor<&[u8]>,
payload_rdr: &mut Cursor<&[u8]>,
) -> Result<ConsumerUpdate> {
let group = read_string(key_rdr).chain_err(|| "Failed to parse group name from key")?;
let topic = read_string(key_rdr).chain_err(|| "Failed to parse topic name from key")?;
let partition = key_rdr
.read_i32::<BigEndian>()
.chain_err(|| "Failed to parse partition from key")?;
if!payload_rdr.get_ref().is_empty() {
// payload is not empty
let _version = payload_rdr
.read_i16::<BigEndian>()
.chain_err(|| "Failed to parse value version")?;
let offset = payload_rdr
.read_i64::<BigEndian>()
.chain_err(|| "Failed to parse offset from value")?;
Ok(ConsumerUpdate::OffsetCommit {
group,
topic,
partition,
offset,
})
} else {
Ok(ConsumerUpdate::OffsetTombstone {
group,
topic,
partition,
})
}
}
fn parse_message(key: &[u8], payload: &[u8]) -> Result<ConsumerUpdate> {
let mut key_rdr = Cursor::new(key);
let key_version = key_rdr
.read_i16::<BigEndian>()
.chain_err(|| "Failed to parse key version")?;
match key_version {
0 | 1 => parse_group_offset(&mut key_rdr, &mut Cursor::new(payload))
.chain_err(|| "Failed to parse group offset update"),
2 => Ok(ConsumerUpdate::Metadata),
_ => bail!("Key version not recognized"),
}
}
fn create_consumer(
brokers: &str,
group_id: &str,
start_offsets: Option<Vec<i64>>,
) -> Result<StreamConsumer<EmptyConsumerContext>> {
let consumer = ClientConfig::new()
.set("group.id", group_id)
.set("bootstrap.servers", brokers)
.set("enable.partition.eof", "false")
.set("enable.auto.commit", "false")
.set("session.timeout.ms", "30000")
.set("api.version.request", "true")
//.set("fetch.message.max.bytes", "1024000") // Reduce memory usage
.set("queued.min.messages", "10000") // Reduce memory usage
.set("message.max.bytes", "10485760")
.set_default_topic_config(
TopicConfig::new()
.set("auto.offset.reset", "smallest")
.finalize(),
)
.create::<StreamConsumer<_>>()
.chain_err(|| format!("Consumer creation failed: {}", brokers))?;
match start_offsets {
Some(pos) => {
let mut tp_list = TopicPartitionList::new();
for (partition, &offset) in pos.iter().enumerate() {
tp_list.add_partition_offset(
"__consumer_offsets",
partition as i32,
Offset::Offset(offset),
);
}
debug!(
"Previous offsets found, assigning offsets explicitly: {:?}",
tp_list
);
consumer
.assign(&tp_list)
.chain_err(|| "Failure during consumer assignment")?;
}
None => {
debug!("No previous offsets found, subscribing to topic");
consumer.subscribe(&["__consumer_offsets"]).chain_err(|| {
format!("Can't subscribe to offset __consumer_offsets ({})", brokers)
})?;
}
}
Ok(consumer)
}
// we should really have some tests here
fn update_global_cache(
cluster_id: &ClusterId,
local_cache: &HashMap<(String, String), Vec<i64>>,
cache: &OffsetsCache,
) {
for (&(ref group, ref topic), new_offsets) in local_cache {
// Consider a consuming iterator
// This logic is not needed if i store the consumer offset, right? wrong!
if new_offsets.iter().any(|&offset| offset == -1) {
if let Some(mut existing_offsets) =
cache.get(&(cluster_id.to_owned(), group.to_owned(), topic.to_owned()))
{
// If the new offset is not complete and i have an old one, do the merge
vec_merge_in_place(&mut existing_offsets, &new_offsets, -1, cmp::max);
// for i in 0..(cmp::max(offsets.len(), existing_offsets.len())) {
// let new_offset = cmp::max(
// offsets.get(i).cloned().unwrap_or(-1),
// existing_offsets.get(i).cloned().unwrap_or(-1));
// insert_at(&mut existing_offsets, i, new_offset, -1);
// }
let _ = cache.insert(
(cluster_id.to_owned(), group.to_owned(), topic.to_owned()),
existing_offsets,
);
continue;
}
}
// TODO: log errors
let _ = cache.insert(
(cluster_id.to_owned(), group.to_owned(), topic.to_owned()),
new_offsets.clone(),
);
}
}
fn commit_offset_position_to_array(tp_list: TopicPartitionList) -> Vec<i64> {
let tp_elements = tp_list.elements_for_topic("__consumer_offsets");
let mut offsets = vec![0; tp_elements.len()];
for tp in &tp_elements {
offsets[tp.partition() as usize] = tp.offset().to_raw();
}
offsets
}
fn consume_offset_topic(
cluster_id: ClusterId,
consumer: StreamConsumer<EmptyConsumerContext>,
cache: &Cache,
) -> Result<()> {
let mut local_cache = HashMap::new();
let mut last_dump = Instant::now();
debug!("Starting offset consumer loop for {:?}", cluster_id);
for message in consumer.start_with(Duration::from_millis(200), true).wait() {
match message {
Ok(Ok(m)) => {
let key = m.key().unwrap_or(&[]);
let payload = m.payload().unwrap_or(&[]);
match parse_message(key, payload) {
Ok(ConsumerUpdate::OffsetCommit {
group,
topic,
partition,
offset,
}) => {
let mut offsets = local_cache
.entry((group.to_owned(), topic.to_owned()))
.or_insert_with(Vec::new);
insert_at(&mut offsets, partition as usize, offset, -1);
}
Ok(_) => {}
Err(e) => format_error_chain!(e),
};
}
Ok(Err(KafkaError::NoMessageReceived)) => {}
Ok(Err(e)) => warn!("Kafka error: {} {:?}", cluster_id, e),
Err(e) => warn!("Can't receive data from stream: {:?}", e),
};
// Update the cache if needed
if (Instant::now() - last_dump) > Duration::from_secs(10) {
trace!(
"Dumping local offset cache ({}: {} updates)",
cluster_id,
local_cache.len()
|
// Consumer position is not up to date after start, so we have to merge with the
// existing offsets and take the largest.
let res = consumer
.position()
.map(|current_position| {
let previous_position_vec = cache
.internal_offsets
.get(&cluster_id)
.unwrap_or_else(Vec::new);
let mut current_position_vec =
commit_offset_position_to_array(current_position);
vec_merge_in_place(
&mut current_position_vec,
&previous_position_vec,
Offset::Invalid.to_raw(),
cmp::max,
);
cache
.internal_offsets
.insert(cluster_id.clone(), current_position_vec)
})
.chain_err(|| "Failed to store consumer offset position")?;
if let Err(e) = res {
format_error_chain!(e);
}
local_cache = HashMap::with_capacity(local_cache.len());
last_dump = Instant::now();
}
}
Ok(())
}
pub fn vec_merge_in_place<F, T: Copy>(vec1: &mut Vec<T>, vec2: &[T], default: T, merge_fn: F)
where
F: Fn(T, T) -> T,
{
let new_len = cmp::max(vec1.len(), vec2.len());
vec1.resize(new_len, default);
for i in 0..vec1.len() {
vec1[i] = merge_fn(
vec1.get(i).unwrap_or(&default).to_owned(),
vec2.get(i).unwrap_or(&default).to_owned(),
);
}
}
//pub fn vec_merge<F, T: Clone>(vec1: Vec<T>, vec2: Vec<T>, default: T, merge: F) -> Vec<T>
// where F: Fn(T, T) -> T
//{
// (0..cmp::max(vec1.len(), vec2.len()))
// .map(|index|
// merge(
// vec1.get(index).unwrap_or(&default).to_owned(),
// vec2.get(index).unwrap_or(&default).to_owned()))
// .collect::<Vec<T>>()
//}
pub fn run_offset_consumer(
cluster_id: &ClusterId,
cluster_config: &ClusterConfig,
config: &Config,
cache: &Cache,
) -> Result<()> {
let start_position = cache.internal_offsets.get(cluster_id);
let consumer = create_consumer(
&cluster_config.bootstrap_servers(),
&config.consumer_offsets_group_id,
start_position,
)
.chain_err(|| format!("Failed to create offset consumer for {}", cluster_id))?;
let cluster_id_clone = cluster_id.clone();
let cache_alias = cache.alias();
let _ = thread::Builder::new()
.name("offset-consumer".to_owned())
.spawn(move || {
if let Err(e) = consume_offset_topic(cluster_id_clone, consumer, &cache_alias) {
format_error_chain!(e);
}
})
.chain_err(|| "Failed to start offset consumer thread")?;
Ok(())
}
pub trait OffsetStore {
fn offsets_by_cluster(
&self,
cluster_id: &ClusterId,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
fn offsets_by_cluster_topic(
&self,
cluster_id: &ClusterId,
topic_name: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
fn offsets_by_cluster_group(
&self,
cluster_id: &ClusterId,
group_name: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
}
impl OffsetStore for Cache {
fn offsets_by_cluster(
&self,
cluster: &ClusterId,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets.filter_clone(|&(ref c, _, _)| c == cluster)
}
fn offsets_by_cluster_topic(
&self,
cluster: &ClusterId,
topic: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets
.filter_clone(|&(ref c, _, ref t)| c == cluster && t == topic)
}
fn offsets_by_cluster_group(
&self,
cluster: &ClusterId,
group: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets
.filter_clone(|&(ref c, ref g, _)| c == cluster && g == group)
}
}
|
);
update_global_cache(&cluster_id, &local_cache, &cache.offsets);
|
random_line_split
|
offsets.rs
|
use byteorder::{BigEndian, ReadBytesExt};
use futures::Stream;
use rdkafka::config::{ClientConfig, TopicConfig};
use rdkafka::consumer::stream_consumer::StreamConsumer;
use rdkafka::consumer::{Consumer, EmptyConsumerContext};
use rdkafka::error::KafkaError;
use rdkafka::{Message, Offset, TopicPartitionList};
use cache::{Cache, OffsetsCache};
use config::{ClusterConfig, Config};
use error::*;
use metadata::{ClusterId, TopicName};
use utils::{insert_at, read_string};
use std::cmp;
use std::collections::HashMap;
use std::io::Cursor;
use std::str;
use std::thread;
use std::time::{Duration, Instant};
#[derive(Debug)]
enum ConsumerUpdate {
Metadata,
OffsetCommit {
group: String,
topic: String,
partition: i32,
offset: i64,
},
OffsetTombstone {
group: String,
topic: String,
partition: i32,
},
}
fn parse_group_offset(
key_rdr: &mut Cursor<&[u8]>,
payload_rdr: &mut Cursor<&[u8]>,
) -> Result<ConsumerUpdate> {
let group = read_string(key_rdr).chain_err(|| "Failed to parse group name from key")?;
let topic = read_string(key_rdr).chain_err(|| "Failed to parse topic name from key")?;
let partition = key_rdr
.read_i32::<BigEndian>()
.chain_err(|| "Failed to parse partition from key")?;
if!payload_rdr.get_ref().is_empty() {
// payload is not empty
let _version = payload_rdr
.read_i16::<BigEndian>()
.chain_err(|| "Failed to parse value version")?;
let offset = payload_rdr
.read_i64::<BigEndian>()
.chain_err(|| "Failed to parse offset from value")?;
Ok(ConsumerUpdate::OffsetCommit {
group,
topic,
partition,
offset,
})
} else {
Ok(ConsumerUpdate::OffsetTombstone {
group,
topic,
partition,
})
}
}
fn parse_message(key: &[u8], payload: &[u8]) -> Result<ConsumerUpdate> {
let mut key_rdr = Cursor::new(key);
let key_version = key_rdr
.read_i16::<BigEndian>()
.chain_err(|| "Failed to parse key version")?;
match key_version {
0 | 1 => parse_group_offset(&mut key_rdr, &mut Cursor::new(payload))
.chain_err(|| "Failed to parse group offset update"),
2 => Ok(ConsumerUpdate::Metadata),
_ => bail!("Key version not recognized"),
}
}
fn create_consumer(
brokers: &str,
group_id: &str,
start_offsets: Option<Vec<i64>>,
) -> Result<StreamConsumer<EmptyConsumerContext>> {
let consumer = ClientConfig::new()
.set("group.id", group_id)
.set("bootstrap.servers", brokers)
.set("enable.partition.eof", "false")
.set("enable.auto.commit", "false")
.set("session.timeout.ms", "30000")
.set("api.version.request", "true")
//.set("fetch.message.max.bytes", "1024000") // Reduce memory usage
.set("queued.min.messages", "10000") // Reduce memory usage
.set("message.max.bytes", "10485760")
.set_default_topic_config(
TopicConfig::new()
.set("auto.offset.reset", "smallest")
.finalize(),
)
.create::<StreamConsumer<_>>()
.chain_err(|| format!("Consumer creation failed: {}", brokers))?;
match start_offsets {
Some(pos) => {
let mut tp_list = TopicPartitionList::new();
for (partition, &offset) in pos.iter().enumerate() {
tp_list.add_partition_offset(
"__consumer_offsets",
partition as i32,
Offset::Offset(offset),
);
}
debug!(
"Previous offsets found, assigning offsets explicitly: {:?}",
tp_list
);
consumer
.assign(&tp_list)
.chain_err(|| "Failure during consumer assignment")?;
}
None => {
debug!("No previous offsets found, subscribing to topic");
consumer.subscribe(&["__consumer_offsets"]).chain_err(|| {
format!("Can't subscribe to offset __consumer_offsets ({})", brokers)
})?;
}
}
Ok(consumer)
}
// we should really have some tests here
fn update_global_cache(
cluster_id: &ClusterId,
local_cache: &HashMap<(String, String), Vec<i64>>,
cache: &OffsetsCache,
) {
for (&(ref group, ref topic), new_offsets) in local_cache {
// Consider a consuming iterator
// This logic is not needed if i store the consumer offset, right? wrong!
if new_offsets.iter().any(|&offset| offset == -1) {
if let Some(mut existing_offsets) =
cache.get(&(cluster_id.to_owned(), group.to_owned(), topic.to_owned()))
|
}
// TODO: log errors
let _ = cache.insert(
(cluster_id.to_owned(), group.to_owned(), topic.to_owned()),
new_offsets.clone(),
);
}
}
fn commit_offset_position_to_array(tp_list: TopicPartitionList) -> Vec<i64> {
let tp_elements = tp_list.elements_for_topic("__consumer_offsets");
let mut offsets = vec![0; tp_elements.len()];
for tp in &tp_elements {
offsets[tp.partition() as usize] = tp.offset().to_raw();
}
offsets
}
fn consume_offset_topic(
cluster_id: ClusterId,
consumer: StreamConsumer<EmptyConsumerContext>,
cache: &Cache,
) -> Result<()> {
let mut local_cache = HashMap::new();
let mut last_dump = Instant::now();
debug!("Starting offset consumer loop for {:?}", cluster_id);
for message in consumer.start_with(Duration::from_millis(200), true).wait() {
match message {
Ok(Ok(m)) => {
let key = m.key().unwrap_or(&[]);
let payload = m.payload().unwrap_or(&[]);
match parse_message(key, payload) {
Ok(ConsumerUpdate::OffsetCommit {
group,
topic,
partition,
offset,
}) => {
let mut offsets = local_cache
.entry((group.to_owned(), topic.to_owned()))
.or_insert_with(Vec::new);
insert_at(&mut offsets, partition as usize, offset, -1);
}
Ok(_) => {}
Err(e) => format_error_chain!(e),
};
}
Ok(Err(KafkaError::NoMessageReceived)) => {}
Ok(Err(e)) => warn!("Kafka error: {} {:?}", cluster_id, e),
Err(e) => warn!("Can't receive data from stream: {:?}", e),
};
// Update the cache if needed
if (Instant::now() - last_dump) > Duration::from_secs(10) {
trace!(
"Dumping local offset cache ({}: {} updates)",
cluster_id,
local_cache.len()
);
update_global_cache(&cluster_id, &local_cache, &cache.offsets);
// Consumer position is not up to date after start, so we have to merge with the
// existing offsets and take the largest.
let res = consumer
.position()
.map(|current_position| {
let previous_position_vec = cache
.internal_offsets
.get(&cluster_id)
.unwrap_or_else(Vec::new);
let mut current_position_vec =
commit_offset_position_to_array(current_position);
vec_merge_in_place(
&mut current_position_vec,
&previous_position_vec,
Offset::Invalid.to_raw(),
cmp::max,
);
cache
.internal_offsets
.insert(cluster_id.clone(), current_position_vec)
})
.chain_err(|| "Failed to store consumer offset position")?;
if let Err(e) = res {
format_error_chain!(e);
}
local_cache = HashMap::with_capacity(local_cache.len());
last_dump = Instant::now();
}
}
Ok(())
}
pub fn vec_merge_in_place<F, T: Copy>(vec1: &mut Vec<T>, vec2: &[T], default: T, merge_fn: F)
where
F: Fn(T, T) -> T,
{
let new_len = cmp::max(vec1.len(), vec2.len());
vec1.resize(new_len, default);
for i in 0..vec1.len() {
vec1[i] = merge_fn(
vec1.get(i).unwrap_or(&default).to_owned(),
vec2.get(i).unwrap_or(&default).to_owned(),
);
}
}
//pub fn vec_merge<F, T: Clone>(vec1: Vec<T>, vec2: Vec<T>, default: T, merge: F) -> Vec<T>
// where F: Fn(T, T) -> T
//{
// (0..cmp::max(vec1.len(), vec2.len()))
// .map(|index|
// merge(
// vec1.get(index).unwrap_or(&default).to_owned(),
// vec2.get(index).unwrap_or(&default).to_owned()))
// .collect::<Vec<T>>()
//}
pub fn run_offset_consumer(
cluster_id: &ClusterId,
cluster_config: &ClusterConfig,
config: &Config,
cache: &Cache,
) -> Result<()> {
let start_position = cache.internal_offsets.get(cluster_id);
let consumer = create_consumer(
&cluster_config.bootstrap_servers(),
&config.consumer_offsets_group_id,
start_position,
)
.chain_err(|| format!("Failed to create offset consumer for {}", cluster_id))?;
let cluster_id_clone = cluster_id.clone();
let cache_alias = cache.alias();
let _ = thread::Builder::new()
.name("offset-consumer".to_owned())
.spawn(move || {
if let Err(e) = consume_offset_topic(cluster_id_clone, consumer, &cache_alias) {
format_error_chain!(e);
}
})
.chain_err(|| "Failed to start offset consumer thread")?;
Ok(())
}
pub trait OffsetStore {
fn offsets_by_cluster(
&self,
cluster_id: &ClusterId,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
fn offsets_by_cluster_topic(
&self,
cluster_id: &ClusterId,
topic_name: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
fn offsets_by_cluster_group(
&self,
cluster_id: &ClusterId,
group_name: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;
}
impl OffsetStore for Cache {
fn offsets_by_cluster(
&self,
cluster: &ClusterId,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets.filter_clone(|&(ref c, _, _)| c == cluster)
}
fn offsets_by_cluster_topic(
&self,
cluster: &ClusterId,
topic: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets
.filter_clone(|&(ref c, _, ref t)| c == cluster && t == topic)
}
fn offsets_by_cluster_group(
&self,
cluster: &ClusterId,
group: &str,
) -> Vec<((ClusterId, String, TopicName), Vec<i64>)> {
self.offsets
.filter_clone(|&(ref c, ref g, _)| c == cluster && g == group)
}
}
|
{
// If the new offset is not complete and i have an old one, do the merge
vec_merge_in_place(&mut existing_offsets, &new_offsets, -1, cmp::max);
// for i in 0..(cmp::max(offsets.len(), existing_offsets.len())) {
// let new_offset = cmp::max(
// offsets.get(i).cloned().unwrap_or(-1),
// existing_offsets.get(i).cloned().unwrap_or(-1));
// insert_at(&mut existing_offsets, i, new_offset, -1);
// }
let _ = cache.insert(
(cluster_id.to_owned(), group.to_owned(), topic.to_owned()),
existing_offsets,
);
continue;
}
|
conditional_block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.