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
main.rs
extern crate chrono; extern crate iron; extern crate persistent; extern crate r2d2; extern crate r2d2_sqlite; extern crate router; extern crate rusqlite; extern crate rustc_serialize; extern crate sha2; use chrono::*; use iron::prelude::*; use iron::Url; use iron::modifiers::Redirect; use iron::status::Status; use iron::typemap::Key; use persistent::Read; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use router::Router; use rusqlite::Connection; use rustc_serialize::hex::ToHex; use sha2::{Digest, Sha256}; use std::env; const HOST: &'static str = "https://yaus.pw/"; pub type SqlitePool = Pool<SqliteConnectionManager>; pub struct YausDb; impl Key for YausDb { type Value = SqlitePool; } // A simple macro to return early if the URL can't parse. macro_rules! try_url { ($url:expr) => { match Url::parse($url) { Ok(_) => { }, Err(_) => { return Ok(Response::with((Status::BadRequest, "Malformed URL"))); } } } } fn create_shortened_url(db: &Connection, long_url: &str) -> IronResult<Response> { let mut d = Sha256::default(); d.input(long_url.as_bytes()); let locator = d.result().as_slice().to_hex(); let timestamp = Local::now().to_rfc3339(); db.execute("INSERT INTO urls VALUES (NULL,?1,?2,?3)", &[&timestamp, &long_url, &&locator[0..7]]).unwrap(); Ok(Response::with((Status::Created, [HOST, &locator[0..7]].join("")))) } /// Given a long URL, see if it already exists in the table, else create an entry and return /// it. /// /// A 200 means that a shortened URL already exists and has been returned. A 201 /// response means that a new shortened URL has been created. fn check_or_shorten_url(db: &Connection, long_url: &str) -> IronResult<Response> { let mut stmt = db.prepare("SELECT locator FROM urls WHERE url = (?)").unwrap(); let mut row = stmt.query_map::<String, _>(&[&long_url], |r| r.get(0)).unwrap(); if let Some(l) = row.next() { return Ok(Response::with((Status::Ok, [HOST, &l.unwrap()].join("")))); } create_shortened_url(db, long_url) } /// The handler to shorten a URL. fn shorten_handler(req: &mut Request) -> IronResult<Response> { match req.url.clone().query() { None => { Ok(Response::with((Status::BadRequest, "URL missing in query"))) }, Some(s) => { let (k, v) = s.split_at(4); if k == "url=" { try_url!(v); let pool = req.get::<Read<YausDb>>().unwrap().clone(); let db = pool.get().unwrap(); check_or_shorten_url(&db, v) } else { Ok(Response::with((Status::BadRequest, "Malformed query string"))) } } } } /// The handler that redirects to the long URL. fn
(req: &mut Request) -> IronResult<Response> { let pool = req.get::<Read<YausDb>>().unwrap().clone(); let db = pool.get().unwrap(); let locator = req.url.path()[0]; let mut stmt = db.prepare("SELECT url FROM urls WHERE locator = (?)").unwrap(); let mut row = stmt.query_map::<String, _>(&[&locator], |r| r.get(0)).unwrap(); if let Some(u) = row.next() { let long_url = Url::parse(&u.unwrap()).unwrap(); Ok(Response::with((Status::MovedPermanently, Redirect(long_url)))) } else { Ok(Response::with((Status::NotFound, "Not found"))) } } fn index_handler(_: &mut Request) -> IronResult<Response> { Ok(Response::with((Status::Ok, "See https://github.com/gsquire/yaus for the API"))) } fn main() { let mut router = Router::new(); router.get("/shorten", shorten_handler, "shorten"); router.get("/:locator", redirect_handler, "locator"); router.get("/", index_handler, "index"); let config = r2d2::Config::default(); let db = env::var("SHORT_DB").unwrap(); let manager = SqliteConnectionManager::new(&db); let pool = r2d2::Pool::new(config, manager).unwrap(); let mut chain = Chain::new(router); chain.link_before(Read::<YausDb>::one(pool)); Iron::new(chain).http("localhost:3000").unwrap(); }
redirect_handler
identifier_name
sampler_linux.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/. */ #![allow(unsafe_code)] use crate::sampler::{NativeStack, Sampler}; use libc; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal}; use std::cell::UnsafeCell; use std::io; use std::mem; use std::process; use std::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; use std::thread; use unwind_sys::{ unw_cursor_t, unw_get_reg, unw_init_local, unw_step, UNW_ESUCCESS, UNW_REG_IP, UNW_REG_SP, }; // Hack to workaround broken libunwind pkg-config contents for <1.1-3ubuntu.1. // https://bugs.launchpad.net/ubuntu/+source/libunwind/+bug/1336912 #[link(name = "lzma")] extern "C" {} struct UncheckedSyncUnsafeCell<T>(std::cell::UnsafeCell<T>); /// Safety: dereferencing the pointer from `UnsafeCell::get` must involve external synchronization unsafe impl<T> Sync for UncheckedSyncUnsafeCell<T> {} static SHARED_STATE: UncheckedSyncUnsafeCell<SharedState> = UncheckedSyncUnsafeCell(std::cell::UnsafeCell::new(SharedState { msg2: None, msg3: None, msg4: None, })); static CONTEXT: AtomicPtr<libc::ucontext_t> = AtomicPtr::new(ptr::null_mut()); type MonitoredThreadId = libc::pid_t; struct SharedState { // "msg1" is the signal. msg2: Option<PosixSemaphore>, msg3: Option<PosixSemaphore>, msg4: Option<PosixSemaphore>, } fn clear_shared_state() { // Safety: this is only called from the sampling thread (there’s only one) // Sampled threads only access SHARED_STATE in their signal handler. // This signal and the semaphores in SHARED_STATE provide the necessary synchronization. unsafe { let shared_state = &mut *SHARED_STATE.0.get(); shared_state.msg2 = None; shared_state.msg3 = None; shared_state.msg4 = None; } CONTEXT.store(ptr::null_mut(), Ordering::SeqCst); } fn reset_shared_state() { // Safety: same as clear_shared_state unsafe { let shared_state = &mut *SHARED_STATE.0.get(); shared_state.msg2 = Some(PosixSemaphore::new(0).expect("valid semaphore")); shared_state.msg3 = Some(PosixSemaphore::new(0).expect("valid semaphore")); shared_state.msg4 = Some(PosixSemaphore::new(0).expect("valid semaphore")); } CONTEXT.store(ptr::null_mut(), Ordering::SeqCst); } struct PosixSemaphore { sem: UnsafeCell<libc::sem_t>, } impl PosixSemaphore { pub fn new(value: u32) -> io::Result<Self> { let mut sem = mem::MaybeUninit::uninit(); let r = unsafe { libc::sem_init(sem.as_mut_ptr(), 0 /* not shared */, value) }; if r == -1 { return Err(io::Error::last_os_error()); } Ok(PosixSemaphore { sem: UnsafeCell::new(unsafe { sem.assume_init() }), }) } pub fn post(&self) -> io::Result<()> { if unsafe { libc::sem_post(self.sem.get()) } == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } pub fn wait(&self) -> io::Result<()> { if unsafe { libc::sem_wait(self.sem.get()) } == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } /// Retries the wait if it returned due to EINTR. /// Returns Ok on success and the error on any other return value. pub fn wait_through_intr(&self) -> io::Result<()> { loop { match self.wait() { Err(os_error) => { let err = os_error.raw_os_error().expect("no os error"); if err == libc::EINTR { thread::yield_now(); continue; } return Err(os_error); }, _ => return Ok(()), } } } } unsafe impl Sync for PosixSemaphore {} impl Drop for PosixSemaphore { /// Destroys the semaphore. fn drop(&mut self) { unsafe { libc::sem_destroy(self.sem.get()) }; } } #[allow(dead_code)] pub struct LinuxSampler { thread_id: MonitoredThreadId, old_handler: SigAction, } impl LinuxSampler { #[allow(unsafe_code, dead_code)] pub fn ne
-> Box<dyn Sampler> { let thread_id = unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t }; let handler = SigHandler::SigAction(sigprof_handler); let action = SigAction::new( handler, SaFlags::SA_RESTART | SaFlags::SA_SIGINFO, SigSet::empty(), ); let old_handler = unsafe { sigaction(Signal::SIGPROF, &action).expect("signal handler set") }; Box::new(LinuxSampler { thread_id, old_handler, }) } } enum RegNum { Ip = UNW_REG_IP as isize, Sp = UNW_REG_SP as isize, } fn get_register(cursor: *mut unw_cursor_t, num: RegNum) -> Result<u64, i32> { unsafe { let mut val = 0; let ret = unw_get_reg(cursor, num as i32, &mut val); if ret == UNW_ESUCCESS { Ok(val) } else { Err(ret) } } } fn step(cursor: *mut unw_cursor_t) -> Result<bool, i32> { unsafe { // libunwind 1.1 seems to get confused and walks off the end of the stack. The last IP // it reports is 0, so we'll stop if we're there. if get_register(cursor, RegNum::Ip).unwrap_or(1) == 0 { return Ok(false); } let ret = unw_step(cursor); if ret > 0 { Ok(true) } else if ret == 0 { Ok(false) } else { Err(ret) } } } impl Sampler for LinuxSampler { #[allow(unsafe_code)] fn suspend_and_sample_thread(&self) -> Result<NativeStack, ()> { // Warning: The "critical section" begins here. // In the critical section: // we must not do any dynamic memory allocation, // nor try to acquire any lock // or any other unshareable resource. // first we reinitialize the semaphores reset_shared_state(); // signal the thread, wait for it to tell us state was copied. send_sigprof(self.thread_id); // Safety: non-exclusive reference only // since sampled threads are accessing this concurrently let shared_state = unsafe { &*SHARED_STATE.0.get() }; shared_state .msg2 .as_ref() .unwrap() .wait_through_intr() .expect("msg2 failed"); let context = CONTEXT.load(Ordering::SeqCst); let mut cursor = mem::MaybeUninit::uninit(); let ret = unsafe { unw_init_local(cursor.as_mut_ptr(), context) }; let result = if ret == UNW_ESUCCESS { let mut native_stack = NativeStack::new(); loop { let ip = match get_register(cursor.as_mut_ptr(), RegNum::Ip) { Ok(ip) => ip, Err(_) => break, }; let sp = match get_register(cursor.as_mut_ptr(), RegNum::Sp) { Ok(sp) => sp, Err(_) => break, }; if native_stack .process_register(ip as *mut _, sp as *mut _) .is_err() || !step(cursor.as_mut_ptr()).unwrap_or(false) { break; } } Ok(native_stack) } else { Err(()) }; // signal the thread to continue. shared_state .msg3 .as_ref() .unwrap() .post() .expect("msg3 failed"); // wait for thread to continue. shared_state .msg4 .as_ref() .unwrap() .wait_through_intr() .expect("msg4 failed"); // No-op, but marks the end of the shared borrow drop(shared_state); clear_shared_state(); // NOTE: End of "critical section". result } } impl Drop for LinuxSampler { fn drop(&mut self) { unsafe { sigaction(Signal::SIGPROF, &self.old_handler).expect("previous signal handler restored") }; } } extern "C" fn sigprof_handler( sig: libc::c_int, _info: *mut libc::siginfo_t, ctx: *mut libc::c_void, ) { assert_eq!(sig, libc::SIGPROF); // copy the context. CONTEXT.store(ctx as *mut libc::ucontext_t, Ordering::SeqCst); // Safety: non-exclusive reference only // since the sampling thread is accessing this concurrently let shared_state = unsafe { &*SHARED_STATE.0.get() }; // Tell the sampler we copied the context. shared_state.msg2.as_ref().unwrap().post().expect("posted"); // Wait for sampling to finish. shared_state .msg3 .as_ref() .unwrap() .wait_through_intr() .expect("msg3 wait succeeded"); // OK we are done! shared_state.msg4.as_ref().unwrap().post().expect("posted"); // DO NOT TOUCH shared state here onwards. } fn send_sigprof(to: libc::pid_t) { unsafe { libc::syscall(libc::SYS_tgkill, process::id(), to, libc::SIGPROF); } }
w()
identifier_name
sampler_linux.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/. */ #![allow(unsafe_code)] use crate::sampler::{NativeStack, Sampler}; use libc; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal}; use std::cell::UnsafeCell; use std::io; use std::mem; use std::process; use std::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; use std::thread; use unwind_sys::{ unw_cursor_t, unw_get_reg, unw_init_local, unw_step, UNW_ESUCCESS, UNW_REG_IP, UNW_REG_SP, }; // Hack to workaround broken libunwind pkg-config contents for <1.1-3ubuntu.1. // https://bugs.launchpad.net/ubuntu/+source/libunwind/+bug/1336912 #[link(name = "lzma")] extern "C" {} struct UncheckedSyncUnsafeCell<T>(std::cell::UnsafeCell<T>); /// Safety: dereferencing the pointer from `UnsafeCell::get` must involve external synchronization unsafe impl<T> Sync for UncheckedSyncUnsafeCell<T> {} static SHARED_STATE: UncheckedSyncUnsafeCell<SharedState> = UncheckedSyncUnsafeCell(std::cell::UnsafeCell::new(SharedState { msg2: None, msg3: None, msg4: None, })); static CONTEXT: AtomicPtr<libc::ucontext_t> = AtomicPtr::new(ptr::null_mut()); type MonitoredThreadId = libc::pid_t; struct SharedState { // "msg1" is the signal. msg2: Option<PosixSemaphore>, msg3: Option<PosixSemaphore>, msg4: Option<PosixSemaphore>, } fn clear_shared_state() { // Safety: this is only called from the sampling thread (there’s only one) // Sampled threads only access SHARED_STATE in their signal handler. // This signal and the semaphores in SHARED_STATE provide the necessary synchronization. unsafe { let shared_state = &mut *SHARED_STATE.0.get(); shared_state.msg2 = None; shared_state.msg3 = None; shared_state.msg4 = None; } CONTEXT.store(ptr::null_mut(), Ordering::SeqCst); } fn reset_shared_state() { // Safety: same as clear_shared_state unsafe { let shared_state = &mut *SHARED_STATE.0.get(); shared_state.msg2 = Some(PosixSemaphore::new(0).expect("valid semaphore")); shared_state.msg3 = Some(PosixSemaphore::new(0).expect("valid semaphore")); shared_state.msg4 = Some(PosixSemaphore::new(0).expect("valid semaphore")); } CONTEXT.store(ptr::null_mut(), Ordering::SeqCst); } struct PosixSemaphore { sem: UnsafeCell<libc::sem_t>, } impl PosixSemaphore { pub fn new(value: u32) -> io::Result<Self> { let mut sem = mem::MaybeUninit::uninit(); let r = unsafe { libc::sem_init(sem.as_mut_ptr(), 0 /* not shared */, value) }; if r == -1 { return Err(io::Error::last_os_error()); } Ok(PosixSemaphore { sem: UnsafeCell::new(unsafe { sem.assume_init() }), }) } pub fn post(&self) -> io::Result<()> { if unsafe { libc::sem_post(self.sem.get()) } == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } pub fn wait(&self) -> io::Result<()> { if unsafe { libc::sem_wait(self.sem.get()) } == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } /// Retries the wait if it returned due to EINTR. /// Returns Ok on success and the error on any other return value. pub fn wait_through_intr(&self) -> io::Result<()> { loop { match self.wait() { Err(os_error) => { let err = os_error.raw_os_error().expect("no os error"); if err == libc::EINTR { thread::yield_now(); continue; } return Err(os_error); }, _ => return Ok(()), } } } } unsafe impl Sync for PosixSemaphore {} impl Drop for PosixSemaphore {
unsafe { libc::sem_destroy(self.sem.get()) }; } } #[allow(dead_code)] pub struct LinuxSampler { thread_id: MonitoredThreadId, old_handler: SigAction, } impl LinuxSampler { #[allow(unsafe_code, dead_code)] pub fn new() -> Box<dyn Sampler> { let thread_id = unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t }; let handler = SigHandler::SigAction(sigprof_handler); let action = SigAction::new( handler, SaFlags::SA_RESTART | SaFlags::SA_SIGINFO, SigSet::empty(), ); let old_handler = unsafe { sigaction(Signal::SIGPROF, &action).expect("signal handler set") }; Box::new(LinuxSampler { thread_id, old_handler, }) } } enum RegNum { Ip = UNW_REG_IP as isize, Sp = UNW_REG_SP as isize, } fn get_register(cursor: *mut unw_cursor_t, num: RegNum) -> Result<u64, i32> { unsafe { let mut val = 0; let ret = unw_get_reg(cursor, num as i32, &mut val); if ret == UNW_ESUCCESS { Ok(val) } else { Err(ret) } } } fn step(cursor: *mut unw_cursor_t) -> Result<bool, i32> { unsafe { // libunwind 1.1 seems to get confused and walks off the end of the stack. The last IP // it reports is 0, so we'll stop if we're there. if get_register(cursor, RegNum::Ip).unwrap_or(1) == 0 { return Ok(false); } let ret = unw_step(cursor); if ret > 0 { Ok(true) } else if ret == 0 { Ok(false) } else { Err(ret) } } } impl Sampler for LinuxSampler { #[allow(unsafe_code)] fn suspend_and_sample_thread(&self) -> Result<NativeStack, ()> { // Warning: The "critical section" begins here. // In the critical section: // we must not do any dynamic memory allocation, // nor try to acquire any lock // or any other unshareable resource. // first we reinitialize the semaphores reset_shared_state(); // signal the thread, wait for it to tell us state was copied. send_sigprof(self.thread_id); // Safety: non-exclusive reference only // since sampled threads are accessing this concurrently let shared_state = unsafe { &*SHARED_STATE.0.get() }; shared_state .msg2 .as_ref() .unwrap() .wait_through_intr() .expect("msg2 failed"); let context = CONTEXT.load(Ordering::SeqCst); let mut cursor = mem::MaybeUninit::uninit(); let ret = unsafe { unw_init_local(cursor.as_mut_ptr(), context) }; let result = if ret == UNW_ESUCCESS { let mut native_stack = NativeStack::new(); loop { let ip = match get_register(cursor.as_mut_ptr(), RegNum::Ip) { Ok(ip) => ip, Err(_) => break, }; let sp = match get_register(cursor.as_mut_ptr(), RegNum::Sp) { Ok(sp) => sp, Err(_) => break, }; if native_stack .process_register(ip as *mut _, sp as *mut _) .is_err() || !step(cursor.as_mut_ptr()).unwrap_or(false) { break; } } Ok(native_stack) } else { Err(()) }; // signal the thread to continue. shared_state .msg3 .as_ref() .unwrap() .post() .expect("msg3 failed"); // wait for thread to continue. shared_state .msg4 .as_ref() .unwrap() .wait_through_intr() .expect("msg4 failed"); // No-op, but marks the end of the shared borrow drop(shared_state); clear_shared_state(); // NOTE: End of "critical section". result } } impl Drop for LinuxSampler { fn drop(&mut self) { unsafe { sigaction(Signal::SIGPROF, &self.old_handler).expect("previous signal handler restored") }; } } extern "C" fn sigprof_handler( sig: libc::c_int, _info: *mut libc::siginfo_t, ctx: *mut libc::c_void, ) { assert_eq!(sig, libc::SIGPROF); // copy the context. CONTEXT.store(ctx as *mut libc::ucontext_t, Ordering::SeqCst); // Safety: non-exclusive reference only // since the sampling thread is accessing this concurrently let shared_state = unsafe { &*SHARED_STATE.0.get() }; // Tell the sampler we copied the context. shared_state.msg2.as_ref().unwrap().post().expect("posted"); // Wait for sampling to finish. shared_state .msg3 .as_ref() .unwrap() .wait_through_intr() .expect("msg3 wait succeeded"); // OK we are done! shared_state.msg4.as_ref().unwrap().post().expect("posted"); // DO NOT TOUCH shared state here onwards. } fn send_sigprof(to: libc::pid_t) { unsafe { libc::syscall(libc::SYS_tgkill, process::id(), to, libc::SIGPROF); } }
/// Destroys the semaphore. fn drop(&mut self) {
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_types::{ request::Request, Position, TextDocumentIdentifier, TextDocumentPositionParams, Url, }; use schema::Schema; use serde::{Deserialize, Serialize}; pub(crate) enum ResolvedTypesAtLocation {} #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationParams { file_name: String, line: u64, character: u64, } impl ResolvedTypesAtLocationParams { fn to_text_document_position_params(&self) -> LSPRuntimeResult<TextDocumentPositionParams> { Ok(TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::parse(&self.file_name).map_err(|_| LSPRuntimeError::ExpectedError)?, }, position: Position { character: self.character, line: self.line, }, }) } } #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationResponse { pub path_and_schema_name: Option<PathAndSchemaName>, } #[derive(Deserialize, Serialize)] pub(crate) struct PathAndSchemaName { pub path: Vec<String>, pub schema_name: String, } impl Request for ResolvedTypesAtLocation { type Params = ResolvedTypesAtLocationParams; type Result = ResolvedTypesAtLocationResponse; const METHOD: &'static str = "relay/getResolvedTypesAtLocation"; } pub(crate) fn on_get_resolved_types_at_location<TPerfLogger: PerfLogger +'static>( state: &mut LSPState<TPerfLogger>, params: <ResolvedTypesAtLocation as Request>::Params, ) -> LSPRuntimeResult<<ResolvedTypesAtLocation as Request>::Result> { if let Ok(node_resolution_info) = state.resolve_node(params.to_text_document_position_params()?) { if let Some(schema) = state.get_schemas().get(&node_resolution_info.project_name)
} Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: None, }) }
{ // If type_path is empty, type_path.resolve_current_field() will panic. if !node_resolution_info.type_path.0.is_empty() { let type_and_field = node_resolution_info .type_path .resolve_current_field(&schema); if let Some((_parent_type, field)) = type_and_field { let type_name = schema.get_type_name(field.type_.inner()).to_string(); // TODO resolve enclosing types, not just types immediately under the cursor return Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: Some(PathAndSchemaName { path: vec![type_name], schema_name: node_resolution_info.project_name.to_string(), }), }); } } }
conditional_block
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_types::{ request::Request, Position, TextDocumentIdentifier, TextDocumentPositionParams, Url, }; use schema::Schema; use serde::{Deserialize, Serialize}; pub(crate) enum ResolvedTypesAtLocation {} #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationParams { file_name: String, line: u64, character: u64, } impl ResolvedTypesAtLocationParams { fn to_text_document_position_params(&self) -> LSPRuntimeResult<TextDocumentPositionParams> { Ok(TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::parse(&self.file_name).map_err(|_| LSPRuntimeError::ExpectedError)?, }, position: Position { character: self.character, line: self.line, }, }) } } #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationResponse { pub path_and_schema_name: Option<PathAndSchemaName>, } #[derive(Deserialize, Serialize)] pub(crate) struct PathAndSchemaName { pub path: Vec<String>, pub schema_name: String, } impl Request for ResolvedTypesAtLocation { type Params = ResolvedTypesAtLocationParams; type Result = ResolvedTypesAtLocationResponse; const METHOD: &'static str = "relay/getResolvedTypesAtLocation"; } pub(crate) fn on_get_resolved_types_at_location<TPerfLogger: PerfLogger +'static>( state: &mut LSPState<TPerfLogger>, params: <ResolvedTypesAtLocation as Request>::Params, ) -> LSPRuntimeResult<<ResolvedTypesAtLocation as Request>::Result>
} } Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: None, }) }
{ if let Ok(node_resolution_info) = state.resolve_node(params.to_text_document_position_params()?) { if let Some(schema) = state.get_schemas().get(&node_resolution_info.project_name) { // If type_path is empty, type_path.resolve_current_field() will panic. if !node_resolution_info.type_path.0.is_empty() { let type_and_field = node_resolution_info .type_path .resolve_current_field(&schema); if let Some((_parent_type, field)) = type_and_field { let type_name = schema.get_type_name(field.type_.inner()).to_string(); // TODO resolve enclosing types, not just types immediately under the cursor return Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: Some(PathAndSchemaName { path: vec![type_name], schema_name: node_resolution_info.project_name.to_string(), }), }); } }
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_types::{ request::Request, Position, TextDocumentIdentifier, TextDocumentPositionParams, Url, }; use schema::Schema; use serde::{Deserialize, Serialize}; pub(crate) enum ResolvedTypesAtLocation {} #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationParams { file_name: String, line: u64, character: u64, } impl ResolvedTypesAtLocationParams { fn to_text_document_position_params(&self) -> LSPRuntimeResult<TextDocumentPositionParams> { Ok(TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::parse(&self.file_name).map_err(|_| LSPRuntimeError::ExpectedError)?, }, position: Position { character: self.character, line: self.line, }, }) } } #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationResponse { pub path_and_schema_name: Option<PathAndSchemaName>, } #[derive(Deserialize, Serialize)] pub(crate) struct PathAndSchemaName { pub path: Vec<String>, pub schema_name: String, } impl Request for ResolvedTypesAtLocation { type Params = ResolvedTypesAtLocationParams; type Result = ResolvedTypesAtLocationResponse; const METHOD: &'static str = "relay/getResolvedTypesAtLocation"; } pub(crate) fn on_get_resolved_types_at_location<TPerfLogger: PerfLogger +'static>( state: &mut LSPState<TPerfLogger>, params: <ResolvedTypesAtLocation as Request>::Params, ) -> LSPRuntimeResult<<ResolvedTypesAtLocation as Request>::Result> { if let Ok(node_resolution_info) = state.resolve_node(params.to_text_document_position_params()?) { if let Some(schema) = state.get_schemas().get(&node_resolution_info.project_name) { // If type_path is empty, type_path.resolve_current_field() will panic. if!node_resolution_info.type_path.0.is_empty() { let type_and_field = node_resolution_info .type_path .resolve_current_field(&schema); if let Some((_parent_type, field)) = type_and_field { let type_name = schema.get_type_name(field.type_.inner()).to_string(); // TODO resolve enclosing types, not just types immediately under the cursor return Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: Some(PathAndSchemaName { path: vec![type_name], schema_name: node_resolution_info.project_name.to_string(), }), }); } }
path_and_schema_name: None, }) }
} } Ok(ResolvedTypesAtLocationResponse {
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_types::{ request::Request, Position, TextDocumentIdentifier, TextDocumentPositionParams, Url, }; use schema::Schema; use serde::{Deserialize, Serialize}; pub(crate) enum ResolvedTypesAtLocation {} #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationParams { file_name: String, line: u64, character: u64, } impl ResolvedTypesAtLocationParams { fn
(&self) -> LSPRuntimeResult<TextDocumentPositionParams> { Ok(TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::parse(&self.file_name).map_err(|_| LSPRuntimeError::ExpectedError)?, }, position: Position { character: self.character, line: self.line, }, }) } } #[derive(Deserialize, Serialize)] pub(crate) struct ResolvedTypesAtLocationResponse { pub path_and_schema_name: Option<PathAndSchemaName>, } #[derive(Deserialize, Serialize)] pub(crate) struct PathAndSchemaName { pub path: Vec<String>, pub schema_name: String, } impl Request for ResolvedTypesAtLocation { type Params = ResolvedTypesAtLocationParams; type Result = ResolvedTypesAtLocationResponse; const METHOD: &'static str = "relay/getResolvedTypesAtLocation"; } pub(crate) fn on_get_resolved_types_at_location<TPerfLogger: PerfLogger +'static>( state: &mut LSPState<TPerfLogger>, params: <ResolvedTypesAtLocation as Request>::Params, ) -> LSPRuntimeResult<<ResolvedTypesAtLocation as Request>::Result> { if let Ok(node_resolution_info) = state.resolve_node(params.to_text_document_position_params()?) { if let Some(schema) = state.get_schemas().get(&node_resolution_info.project_name) { // If type_path is empty, type_path.resolve_current_field() will panic. if!node_resolution_info.type_path.0.is_empty() { let type_and_field = node_resolution_info .type_path .resolve_current_field(&schema); if let Some((_parent_type, field)) = type_and_field { let type_name = schema.get_type_name(field.type_.inner()).to_string(); // TODO resolve enclosing types, not just types immediately under the cursor return Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: Some(PathAndSchemaName { path: vec![type_name], schema_name: node_resolution_info.project_name.to_string(), }), }); } } } } Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: None, }) }
to_text_document_position_params
identifier_name
lib.rs
//! A blazingly fast chess library. //! //! This package is separated into two parts. Firstly, the board representation & associated functions //! (the current crate, `pleco`), and secondly, the AI implementations using these chess foundations, //! [pleco_engine](https://crates.io/crates/pleco_engine). //! //! The general formatting and structure of the library take heavy influence from the basic building //! blocks of the [Stockfish](https://stockfishchess.org/) chess engine. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/pleco) and can be //! used by adding `pleco` to the dependencies in your project's `Cargo.toml`. //! //! # Platforms //! //! `pleco` is currently tested and created for use with the `x86_64` instruction set in mind. //! Currently, there are no guarantees of correct behavior if compiled for a different //! instruction set. //! //! # Nightly Features //! //! If on nightly rust, the feature `nightly` is available. This enables some nightly //! optimizations and speed improvements. //! //! # Safety //! //! While generally a safe library, pleco was built with a focus of speed in mind. Usage of methods //! must be followed carefully, as there are many possible ways to `panic` unexpectedly. Methods //! with the ability to panic will be documented as such. //! //! # Examples //! //! You can create a [`Board`] with the starting position like so: //! //! ```ignore //! use pleco::Board; //! let board = Board::start_pos(); //! ``` //! //! Generating a list of moves (Contained inside a [`MoveList`]) can be done with: //! //! ```ignore //! let list = board.generate_moves(); //! ``` //! //! Applying and undoing moves is simple: //! //! ```ignore //! let mut board = Board::start_pos(); //! let list = board.generate_moves();
//! board.apply_move(*mov); //! println!("{}",board.get_fen()); //! board.undo_move(); //! } //! ``` //! //! Using fen strings is also supported: //! //! ```ignore //! let start_position = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; //! let board = Board::from_fen(start_position).unwrap(); //! ``` //! //! [`MoveList`]: core/move_list/struct.MoveList.html //! [`Board`]: board/struct.Board.html #![cfg_attr(feature = "dev", allow(unstable_features))] #![cfg_attr(test, allow(dead_code))] //#![crate_type = "rlib"] #![cfg_attr(feature = "nightly", feature(core_intrinsics))] #![cfg_attr(feature = "nightly", feature(const_slice_ptr_len))] #![cfg_attr(feature = "nightly", feature(trusted_len))] #![allow(clippy::cast_lossless)] #![allow(clippy::unreadable_literal)] #![allow(dead_code)] #[macro_use] extern crate bitflags; #[macro_use] extern crate lazy_static; extern crate num_cpus; extern crate rand; extern crate rayon; extern crate mucow; pub mod core; pub mod board; pub mod bots; pub mod helper; pub mod tools; pub use board::Board; pub use core::piece_move::{BitMove,ScoringMove}; pub use core::move_list::{MoveList,ScoringMoveList}; pub use core::sq::SQ; pub use core::bitboard::BitBoard; pub use helper::Helper; pub use core::{Player, Piece, PieceType, Rank, File}; pub mod bot_prelude { //! Easy importing of all available bots. pub use bots::RandomBot; pub use bots::MiniMaxSearcher; pub use bots::ParallelMiniMaxSearcher; pub use bots::AlphaBetaSearcher; pub use bots::JamboreeSearcher; pub use bots::IterativeSearcher; pub use tools::Searcher; }
//! //! for mov in list.iter() {
random_line_split
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] use crate::virtio::IrqType; use crate::virtio::{Block, CacheType, Queue}; use rate_limiter::RateLimiter; use utils::kernel_version::{min_kernel_version_for_io_uring, KernelVersion}; use utils::tempfile::TempFile; /// Create a default Block instance to be used in tests. pub fn default_block(file_engine_type: FileEngineType) -> Block { // Create backing file. let f = TempFile::new().unwrap(); f.as_file().set_len(0x1000).unwrap(); default_block_with_path(f.as_path().to_str().unwrap().to_string(), file_engine_type) } /// Return the Async FileEngineType if supported by the host, otherwise default to Sync. pub fn default_engine_type_for_kv() -> FileEngineType { if KernelVersion::get().unwrap() >= min_kernel_version_for_io_uring() { FileEngineType::Async } else
} /// Create a default Block instance using file at the specified path to be used in tests. pub fn default_block_with_path(path: String, file_engine_type: FileEngineType) -> Block { // Rate limiting is enabled but with a high operation rate (10 million ops/s). let rate_limiter = RateLimiter::new(0, 0, 0, 100_000, 0, 10).unwrap(); let id = "test".to_string(); // The default block device is read-write and non-root. Block::new( id, None, CacheType::Unsafe, path, false, false, rate_limiter, file_engine_type, ) .unwrap() } pub fn set_queue(blk: &mut Block, idx: usize, q: Queue) { blk.queues[idx] = q; } pub fn set_rate_limiter(blk: &mut Block, rl: RateLimiter) { blk.rate_limiter = rl; } pub fn rate_limiter(blk: &mut Block) -> &RateLimiter { &blk.rate_limiter } #[cfg(test)] pub fn simulate_queue_event(b: &mut Block, maybe_expected_irq: Option<bool>) { // Trigger the queue event. b.queue_evts[0].write(1).unwrap(); // Handle event. b.process_queue_event(); // Validate the queue operation finished successfully. if let Some(expected_irq) = maybe_expected_irq { assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } } #[cfg(test)] pub fn simulate_async_completion_event(b: &mut Block, expected_irq: bool) { if let FileEngine::Async(engine) = b.disk.file_engine_mut() { // Wait for all the async operations to complete. engine.drain(false).unwrap(); // Wait for the async completion event to be sent. thread::sleep(Duration::from_millis(150)); // Handle event. b.process_async_completion_event(); } // Validate if there are pending IRQs. assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } #[cfg(test)] pub fn simulate_queue_and_async_completion_events(b: &mut Block, expected_irq: bool) { match b.disk.file_engine_mut() { FileEngine::Async(_) => { simulate_queue_event(b, None); simulate_async_completion_event(b, expected_irq); } FileEngine::Sync(_) => { simulate_queue_event(b, Some(expected_irq)); } } }
{ FileEngineType::Sync }
conditional_block
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] use crate::virtio::IrqType; use crate::virtio::{Block, CacheType, Queue}; use rate_limiter::RateLimiter; use utils::kernel_version::{min_kernel_version_for_io_uring, KernelVersion}; use utils::tempfile::TempFile; /// Create a default Block instance to be used in tests. pub fn default_block(file_engine_type: FileEngineType) -> Block { // Create backing file. let f = TempFile::new().unwrap(); f.as_file().set_len(0x1000).unwrap(); default_block_with_path(f.as_path().to_str().unwrap().to_string(), file_engine_type) } /// Return the Async FileEngineType if supported by the host, otherwise default to Sync. pub fn default_engine_type_for_kv() -> FileEngineType { if KernelVersion::get().unwrap() >= min_kernel_version_for_io_uring() { FileEngineType::Async } else { FileEngineType::Sync } } /// Create a default Block instance using file at the specified path to be used in tests. pub fn default_block_with_path(path: String, file_engine_type: FileEngineType) -> Block { // Rate limiting is enabled but with a high operation rate (10 million ops/s).
id, None, CacheType::Unsafe, path, false, false, rate_limiter, file_engine_type, ) .unwrap() } pub fn set_queue(blk: &mut Block, idx: usize, q: Queue) { blk.queues[idx] = q; } pub fn set_rate_limiter(blk: &mut Block, rl: RateLimiter) { blk.rate_limiter = rl; } pub fn rate_limiter(blk: &mut Block) -> &RateLimiter { &blk.rate_limiter } #[cfg(test)] pub fn simulate_queue_event(b: &mut Block, maybe_expected_irq: Option<bool>) { // Trigger the queue event. b.queue_evts[0].write(1).unwrap(); // Handle event. b.process_queue_event(); // Validate the queue operation finished successfully. if let Some(expected_irq) = maybe_expected_irq { assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } } #[cfg(test)] pub fn simulate_async_completion_event(b: &mut Block, expected_irq: bool) { if let FileEngine::Async(engine) = b.disk.file_engine_mut() { // Wait for all the async operations to complete. engine.drain(false).unwrap(); // Wait for the async completion event to be sent. thread::sleep(Duration::from_millis(150)); // Handle event. b.process_async_completion_event(); } // Validate if there are pending IRQs. assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } #[cfg(test)] pub fn simulate_queue_and_async_completion_events(b: &mut Block, expected_irq: bool) { match b.disk.file_engine_mut() { FileEngine::Async(_) => { simulate_queue_event(b, None); simulate_async_completion_event(b, expected_irq); } FileEngine::Sync(_) => { simulate_queue_event(b, Some(expected_irq)); } } }
let rate_limiter = RateLimiter::new(0, 0, 0, 100_000, 0, 10).unwrap(); let id = "test".to_string(); // The default block device is read-write and non-root. Block::new(
random_line_split
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] use crate::virtio::IrqType; use crate::virtio::{Block, CacheType, Queue}; use rate_limiter::RateLimiter; use utils::kernel_version::{min_kernel_version_for_io_uring, KernelVersion}; use utils::tempfile::TempFile; /// Create a default Block instance to be used in tests. pub fn default_block(file_engine_type: FileEngineType) -> Block { // Create backing file. let f = TempFile::new().unwrap(); f.as_file().set_len(0x1000).unwrap(); default_block_with_path(f.as_path().to_str().unwrap().to_string(), file_engine_type) } /// Return the Async FileEngineType if supported by the host, otherwise default to Sync. pub fn default_engine_type_for_kv() -> FileEngineType { if KernelVersion::get().unwrap() >= min_kernel_version_for_io_uring() { FileEngineType::Async } else { FileEngineType::Sync } } /// Create a default Block instance using file at the specified path to be used in tests. pub fn default_block_with_path(path: String, file_engine_type: FileEngineType) -> Block { // Rate limiting is enabled but with a high operation rate (10 million ops/s). let rate_limiter = RateLimiter::new(0, 0, 0, 100_000, 0, 10).unwrap(); let id = "test".to_string(); // The default block device is read-write and non-root. Block::new( id, None, CacheType::Unsafe, path, false, false, rate_limiter, file_engine_type, ) .unwrap() } pub fn set_queue(blk: &mut Block, idx: usize, q: Queue) { blk.queues[idx] = q; } pub fn set_rate_limiter(blk: &mut Block, rl: RateLimiter) { blk.rate_limiter = rl; } pub fn rate_limiter(blk: &mut Block) -> &RateLimiter { &blk.rate_limiter } #[cfg(test)] pub fn
(b: &mut Block, maybe_expected_irq: Option<bool>) { // Trigger the queue event. b.queue_evts[0].write(1).unwrap(); // Handle event. b.process_queue_event(); // Validate the queue operation finished successfully. if let Some(expected_irq) = maybe_expected_irq { assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } } #[cfg(test)] pub fn simulate_async_completion_event(b: &mut Block, expected_irq: bool) { if let FileEngine::Async(engine) = b.disk.file_engine_mut() { // Wait for all the async operations to complete. engine.drain(false).unwrap(); // Wait for the async completion event to be sent. thread::sleep(Duration::from_millis(150)); // Handle event. b.process_async_completion_event(); } // Validate if there are pending IRQs. assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } #[cfg(test)] pub fn simulate_queue_and_async_completion_events(b: &mut Block, expected_irq: bool) { match b.disk.file_engine_mut() { FileEngine::Async(_) => { simulate_queue_event(b, None); simulate_async_completion_event(b, expected_irq); } FileEngine::Sync(_) => { simulate_queue_event(b, Some(expected_irq)); } } }
simulate_queue_event
identifier_name
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] use crate::virtio::IrqType; use crate::virtio::{Block, CacheType, Queue}; use rate_limiter::RateLimiter; use utils::kernel_version::{min_kernel_version_for_io_uring, KernelVersion}; use utils::tempfile::TempFile; /// Create a default Block instance to be used in tests. pub fn default_block(file_engine_type: FileEngineType) -> Block { // Create backing file. let f = TempFile::new().unwrap(); f.as_file().set_len(0x1000).unwrap(); default_block_with_path(f.as_path().to_str().unwrap().to_string(), file_engine_type) } /// Return the Async FileEngineType if supported by the host, otherwise default to Sync. pub fn default_engine_type_for_kv() -> FileEngineType { if KernelVersion::get().unwrap() >= min_kernel_version_for_io_uring() { FileEngineType::Async } else { FileEngineType::Sync } } /// Create a default Block instance using file at the specified path to be used in tests. pub fn default_block_with_path(path: String, file_engine_type: FileEngineType) -> Block { // Rate limiting is enabled but with a high operation rate (10 million ops/s). let rate_limiter = RateLimiter::new(0, 0, 0, 100_000, 0, 10).unwrap(); let id = "test".to_string(); // The default block device is read-write and non-root. Block::new( id, None, CacheType::Unsafe, path, false, false, rate_limiter, file_engine_type, ) .unwrap() } pub fn set_queue(blk: &mut Block, idx: usize, q: Queue)
pub fn set_rate_limiter(blk: &mut Block, rl: RateLimiter) { blk.rate_limiter = rl; } pub fn rate_limiter(blk: &mut Block) -> &RateLimiter { &blk.rate_limiter } #[cfg(test)] pub fn simulate_queue_event(b: &mut Block, maybe_expected_irq: Option<bool>) { // Trigger the queue event. b.queue_evts[0].write(1).unwrap(); // Handle event. b.process_queue_event(); // Validate the queue operation finished successfully. if let Some(expected_irq) = maybe_expected_irq { assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } } #[cfg(test)] pub fn simulate_async_completion_event(b: &mut Block, expected_irq: bool) { if let FileEngine::Async(engine) = b.disk.file_engine_mut() { // Wait for all the async operations to complete. engine.drain(false).unwrap(); // Wait for the async completion event to be sent. thread::sleep(Duration::from_millis(150)); // Handle event. b.process_async_completion_event(); } // Validate if there are pending IRQs. assert_eq!(b.irq_trigger.has_pending_irq(IrqType::Vring), expected_irq); } #[cfg(test)] pub fn simulate_queue_and_async_completion_events(b: &mut Block, expected_irq: bool) { match b.disk.file_engine_mut() { FileEngine::Async(_) => { simulate_queue_event(b, None); simulate_async_completion_event(b, expected_irq); } FileEngine::Sync(_) => { simulate_queue_event(b, Some(expected_irq)); } } }
{ blk.queues[idx] = q; }
identifier_body
mod.rs
//! Items related to the **Frame** type, describing a single frame of graphics for a single window. use crate::color::IntoLinSrgba; use crate::wgpu; use std::ops; use std::path::PathBuf; use std::sync::Mutex; use std::time::Duration; pub mod raw; pub use self::raw::RawFrame; /// A **Frame** to which the user can draw graphics before it is presented to the display. /// /// **Frame**s are delivered to the user for drawing via the user's **view** function. /// /// See the **RawFrame** docs for more details on how the implementation works under the hood. The /// **Frame** type differs in that rather than drawing directly to the swapchain image the user may /// draw to an intermediary linear sRGBA image. There are several advantages of drawing to an /// intermediary image. pub struct Frame<'swap_chain> { raw_frame: RawFrame<'swap_chain>, render_data: &'swap_chain RenderData, capture_data: &'swap_chain CaptureData, } /// Data specific to the intermediary textures. #[derive(Debug)] pub struct RenderData { intermediary_lin_srgba: IntermediaryLinSrgba, msaa_samples: u32, size: [u32; 2], // For writing the intermediary linear sRGBA texture to the swap chain texture. texture_reshaper: wgpu::TextureReshaper, } /// Data related to the capturing of a frame. #[derive(Debug)] pub(crate) struct CaptureData { // If `Some`, indicates a path to which the current frame should be written. pub(crate) next_frame_path: Mutex<Option<PathBuf>>, // The `TextureCapturer` used to capture the frame. pub(crate) texture_capturer: wgpu::TextureCapturer, } /// Intermediary textures used as a target before resolving multisampling and writing to the /// swapchain texture. #[derive(Debug)] pub(crate) struct IntermediaryLinSrgba { msaa_texture: Option<(wgpu::Texture, wgpu::TextureView)>, texture: wgpu::Texture, texture_view: wgpu::TextureView, } impl<'swap_chain> ops::Deref for Frame<'swap_chain> { type Target = RawFrame<'swap_chain>; fn deref(&self) -> &Self::Target { &self.raw_frame } } impl<'swap_chain> Frame<'swap_chain> { /// The default number of multisample anti-aliasing samples used if the window with which the /// `Frame` is associated supports it. pub const DEFAULT_MSAA_SAMPLES: u32 = 4; /// The texture format used by the intermediary linear sRGBA image. /// /// We use a high bit depth format in order to retain as much information as possible when /// converting from the linear representation to the swapchain format (normally a non-linear /// representation). // TODO: Kvark recommends trying `Rgb10A2Unorm`. pub const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; // Initialise a new empty frame ready for "drawing". pub(crate) fn new_empty( raw_frame: RawFrame<'swap_chain>, render_data: &'swap_chain RenderData, capture_data: &'swap_chain CaptureData, ) -> Self { Frame { raw_frame, render_data, capture_data, } } // The private implementation of `submit`, allowing it to be called during `drop` if submission // has not yet occurred. fn submit_inner(&mut self) { let Frame { ref capture_data, ref render_data, ref mut raw_frame, } = *self; // Resolve the MSAA if necessary. if let Some((_, ref msaa_texture_view)) = render_data.intermediary_lin_srgba.msaa_texture { let mut encoder = raw_frame.command_encoder(); wgpu::resolve_texture( msaa_texture_view, &render_data.intermediary_lin_srgba.texture_view, &mut *encoder, ); } // Check to see if the user specified capturing the frame. let mut snapshot_capture = None; if let Ok(mut guard) = capture_data.next_frame_path.lock() { if let Some(path) = guard.take() { let device = raw_frame.device_queue_pair().device(); let mut encoder = raw_frame.command_encoder(); let snapshot = capture_data.texture_capturer.capture( device, &mut *encoder, &render_data.intermediary_lin_srgba.texture, ); snapshot_capture = Some((path, snapshot)); } } // Convert the linear sRGBA image to the swapchain image. // // To do so, we sample the linear sRGBA image and draw it to the swapchain image using // two triangles and a fragment shader. { let mut encoder = raw_frame.command_encoder(); render_data .texture_reshaper .encode_render_pass(raw_frame.swap_chain_texture(), &mut *encoder); } // Submit all commands on the device queue. raw_frame.submit_inner(); // If the user did specify capturing the frame, submit the asynchronous read. if let Some((path, snapshot)) = snapshot_capture { let result = snapshot.read(move |result| match result { // TODO: Log errors, don't print to stderr. Err(e) => eprintln!("failed to async read captured frame: {:?}", e), Ok(image) => { let image = image.to_owned(); if let Err(e) = image.save(&path) { // TODO: Log errors, don't print to stderr. eprintln!( "failed to save captured frame to \"{}\": {}", path.display(), e ); } } }); if let Err(wgpu::TextureCapturerAwaitWorkerTimeout(_)) = result { // TODO: Log errors, don't print to stderr. eprintln!("timed out while waiting for a worker thread to capture the frame"); } } } /// The texture to which all graphics should be drawn this frame. /// /// This is **not** the swapchain texture, but rather an intermediary linear sRGBA image. This /// intermediary image is used in order to: /// /// - Ensure consistent MSAA resolve behaviour across platforms. /// - Avoid the need for multiple implicit conversions to and from linear sRGBA for each /// graphics pipeline render pass that is used. /// - Allow for the user's rendered image to persist between frames. /// /// The exact format of the texture is equal to `Frame::TEXTURE_FORMAT`. /// /// If the number of MSAA samples specified is greater than `1` (which it is by default if /// supported by the platform), this will be a multisampled texture. After the **view** /// function returns, this texture will be resolved to a non-multisampled linear sRGBA texture. /// After the texture has been resolved if necessary, it will then be used as a shader input /// within a graphics pipeline used to draw the swapchain texture. pub fn texture(&self) -> &wgpu::Texture { self.render_data .intermediary_lin_srgba .msaa_texture .as_ref() .map(|(tex, _)| tex) .unwrap_or(&self.render_data.intermediary_lin_srgba.texture) } /// A full view into the frame's texture. /// /// See `texture` for details. pub fn texture_view(&self) -> &wgpu::TextureView { self.render_data .intermediary_lin_srgba .msaa_texture .as_ref() .map(|(_, view)| view) .unwrap_or(&self.render_data.intermediary_lin_srgba.texture_view) } /// Returns the resolve target texture in the case that MSAA is enabled. pub fn resolve_target(&self) -> Option<&wgpu::TextureView> { if self.render_data.msaa_samples <= 1 { None } else { Some(&self.render_data.intermediary_lin_srgba.texture_view) } } /// The color format of the `Frame`'s intermediary linear sRGBA texture (equal to /// `Frame::TEXTURE_FORMAT`). pub fn texture_format(&self) -> wgpu::TextureFormat { Self::TEXTURE_FORMAT } /// The number of MSAA samples of the `Frame`'s intermediary linear sRGBA texture. pub fn texture_msaa_samples(&self) -> u32 { self.render_data.msaa_samples } /// The size of the frame's texture in pixels. pub fn texture_size(&self) -> [u32; 2] { self.render_data.size } /// Short-hand for constructing a `wgpu::RenderPassColorAttachmentDescriptor` for use within a /// render pass that targets this frame's texture. The returned descriptor's `attachment` will /// the same `wgpu::TextureView` returned by the `Frame::texture` method. /// /// Note that this method will not perform any resolving. In the case that `msaa_samples` is /// greater than `1`, a render pass will be automatically added after the `view` completes and /// before the texture is drawn to the swapchain. pub fn
(&self) -> wgpu::RenderPassColorAttachmentDescriptor { let load = wgpu::LoadOp::Load; let store = true; let attachment = match self.render_data.intermediary_lin_srgba.msaa_texture { None => &self.render_data.intermediary_lin_srgba.texture_view, Some((_, ref msaa_texture_view)) => msaa_texture_view, }; let resolve_target = None; wgpu::RenderPassColorAttachmentDescriptor { attachment, resolve_target, ops: wgpu::Operations { load, store }, } } /// Clear the texture with the given color. pub fn clear<C>(&self, color: C) where C: IntoLinSrgba<f32>, { let lin_srgba = color.into_lin_srgba(); let (r, g, b, a) = lin_srgba.into_components(); let (r, g, b, a) = (r as f64, g as f64, b as f64, a as f64); let color = wgpu::Color { r, g, b, a }; wgpu::clear_texture(self.texture_view(), color, &mut *self.command_encoder()) } /// Submit the frame to the GPU! /// /// Note that you do not need to call this manually as submission will occur automatically when /// the **Frame** is dropped. /// /// Before submission, the frame does the following: /// /// - If the frame's intermediary linear sRGBA texture is multisampled, resolve it. /// - Write the intermediary linear sRGBA image to the swap chain texture. /// /// It can sometimes be useful to submit the **Frame** before `view` completes in order to read /// the frame's texture back to the CPU (e.g. for screen shots, recordings, etc). pub fn submit(mut self) { self.submit_inner(); } } impl CaptureData { pub(crate) fn new(max_jobs: u32, timeout: Option<Duration>) -> Self { CaptureData { next_frame_path: Default::default(), texture_capturer: wgpu::TextureCapturer::new(Some(max_jobs), timeout), } } } impl RenderData { /// Initialise the render data. /// /// Creates an `wgpu::TextureView` with the given parameters. /// /// If `msaa_samples` is greater than 1 a `multisampled` texture will also be created. Otherwise the /// a regular non-multisampled image will be created. pub(crate) fn new( device: &wgpu::Device, swap_chain_dims: [u32; 2], swap_chain_format: wgpu::TextureFormat, msaa_samples: u32, ) -> Self { let intermediary_lin_srgba = create_intermediary_lin_srgba(device, swap_chain_dims, msaa_samples); let src_sample_count = 1; let swap_chain_sample_count = 1; let texture_reshaper = wgpu::TextureReshaper::new( device, &intermediary_lin_srgba.texture_view, src_sample_count, intermediary_lin_srgba.texture_view.sample_type(), swap_chain_sample_count, swap_chain_format, ); RenderData { intermediary_lin_srgba, texture_reshaper, size: swap_chain_dims, msaa_samples, } } } impl<'swap_chain> Drop for Frame<'swap_chain> { fn drop(&mut self) { if!self.raw_frame.is_submitted() { self.submit_inner(); } } } fn create_lin_srgba_msaa_texture( device: &wgpu::Device, swap_chain_dims: [u32; 2], msaa_samples: u32, ) -> wgpu::Texture { wgpu::TextureBuilder::new() .size(swap_chain_dims) .sample_count(msaa_samples) .usage(wgpu::TextureUsage::RENDER_ATTACHMENT) .format(Frame::TEXTURE_FORMAT) .build(device) } fn create_lin_srgba_texture(device: &wgpu::Device, swap_chain_dims: [u32; 2]) -> wgpu::Texture { wgpu::TextureBuilder::new() .size(swap_chain_dims) .format(Frame::TEXTURE_FORMAT) .usage(wgpu::TextureUsage::RENDER_ATTACHMENT | wgpu::TextureUsage::SAMPLED) .build(device) } fn create_intermediary_lin_srgba( device: &wgpu::Device, swap_chain_dims: [u32; 2], msaa_samples: u32, ) -> IntermediaryLinSrgba { let msaa_texture = match msaa_samples { 0 | 1 => None, _ => { let texture = create_lin_srgba_msaa_texture(device, swap_chain_dims, msaa_samples); let texture_view = texture.view().build(); Some((texture, texture_view)) } }; let texture = create_lin_srgba_texture(device, swap_chain_dims); let texture_view = texture.view().build(); IntermediaryLinSrgba { msaa_texture, texture, texture_view, } }
color_attachment_descriptor
identifier_name
mod.rs
//! Items related to the **Frame** type, describing a single frame of graphics for a single window. use crate::color::IntoLinSrgba; use crate::wgpu; use std::ops; use std::path::PathBuf; use std::sync::Mutex; use std::time::Duration; pub mod raw; pub use self::raw::RawFrame; /// A **Frame** to which the user can draw graphics before it is presented to the display. /// /// **Frame**s are delivered to the user for drawing via the user's **view** function. /// /// See the **RawFrame** docs for more details on how the implementation works under the hood. The /// **Frame** type differs in that rather than drawing directly to the swapchain image the user may /// draw to an intermediary linear sRGBA image. There are several advantages of drawing to an /// intermediary image. pub struct Frame<'swap_chain> { raw_frame: RawFrame<'swap_chain>, render_data: &'swap_chain RenderData, capture_data: &'swap_chain CaptureData, } /// Data specific to the intermediary textures. #[derive(Debug)] pub struct RenderData { intermediary_lin_srgba: IntermediaryLinSrgba, msaa_samples: u32, size: [u32; 2], // For writing the intermediary linear sRGBA texture to the swap chain texture. texture_reshaper: wgpu::TextureReshaper, } /// Data related to the capturing of a frame. #[derive(Debug)] pub(crate) struct CaptureData { // If `Some`, indicates a path to which the current frame should be written. pub(crate) next_frame_path: Mutex<Option<PathBuf>>, // The `TextureCapturer` used to capture the frame. pub(crate) texture_capturer: wgpu::TextureCapturer, } /// Intermediary textures used as a target before resolving multisampling and writing to the /// swapchain texture. #[derive(Debug)] pub(crate) struct IntermediaryLinSrgba { msaa_texture: Option<(wgpu::Texture, wgpu::TextureView)>, texture: wgpu::Texture, texture_view: wgpu::TextureView, } impl<'swap_chain> ops::Deref for Frame<'swap_chain> { type Target = RawFrame<'swap_chain>; fn deref(&self) -> &Self::Target { &self.raw_frame } } impl<'swap_chain> Frame<'swap_chain> { /// The default number of multisample anti-aliasing samples used if the window with which the /// `Frame` is associated supports it. pub const DEFAULT_MSAA_SAMPLES: u32 = 4; /// The texture format used by the intermediary linear sRGBA image. /// /// We use a high bit depth format in order to retain as much information as possible when /// converting from the linear representation to the swapchain format (normally a non-linear /// representation). // TODO: Kvark recommends trying `Rgb10A2Unorm`. pub const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; // Initialise a new empty frame ready for "drawing". pub(crate) fn new_empty( raw_frame: RawFrame<'swap_chain>, render_data: &'swap_chain RenderData, capture_data: &'swap_chain CaptureData, ) -> Self { Frame { raw_frame, render_data, capture_data, } } // The private implementation of `submit`, allowing it to be called during `drop` if submission // has not yet occurred.
} = *self; // Resolve the MSAA if necessary. if let Some((_, ref msaa_texture_view)) = render_data.intermediary_lin_srgba.msaa_texture { let mut encoder = raw_frame.command_encoder(); wgpu::resolve_texture( msaa_texture_view, &render_data.intermediary_lin_srgba.texture_view, &mut *encoder, ); } // Check to see if the user specified capturing the frame. let mut snapshot_capture = None; if let Ok(mut guard) = capture_data.next_frame_path.lock() { if let Some(path) = guard.take() { let device = raw_frame.device_queue_pair().device(); let mut encoder = raw_frame.command_encoder(); let snapshot = capture_data.texture_capturer.capture( device, &mut *encoder, &render_data.intermediary_lin_srgba.texture, ); snapshot_capture = Some((path, snapshot)); } } // Convert the linear sRGBA image to the swapchain image. // // To do so, we sample the linear sRGBA image and draw it to the swapchain image using // two triangles and a fragment shader. { let mut encoder = raw_frame.command_encoder(); render_data .texture_reshaper .encode_render_pass(raw_frame.swap_chain_texture(), &mut *encoder); } // Submit all commands on the device queue. raw_frame.submit_inner(); // If the user did specify capturing the frame, submit the asynchronous read. if let Some((path, snapshot)) = snapshot_capture { let result = snapshot.read(move |result| match result { // TODO: Log errors, don't print to stderr. Err(e) => eprintln!("failed to async read captured frame: {:?}", e), Ok(image) => { let image = image.to_owned(); if let Err(e) = image.save(&path) { // TODO: Log errors, don't print to stderr. eprintln!( "failed to save captured frame to \"{}\": {}", path.display(), e ); } } }); if let Err(wgpu::TextureCapturerAwaitWorkerTimeout(_)) = result { // TODO: Log errors, don't print to stderr. eprintln!("timed out while waiting for a worker thread to capture the frame"); } } } /// The texture to which all graphics should be drawn this frame. /// /// This is **not** the swapchain texture, but rather an intermediary linear sRGBA image. This /// intermediary image is used in order to: /// /// - Ensure consistent MSAA resolve behaviour across platforms. /// - Avoid the need for multiple implicit conversions to and from linear sRGBA for each /// graphics pipeline render pass that is used. /// - Allow for the user's rendered image to persist between frames. /// /// The exact format of the texture is equal to `Frame::TEXTURE_FORMAT`. /// /// If the number of MSAA samples specified is greater than `1` (which it is by default if /// supported by the platform), this will be a multisampled texture. After the **view** /// function returns, this texture will be resolved to a non-multisampled linear sRGBA texture. /// After the texture has been resolved if necessary, it will then be used as a shader input /// within a graphics pipeline used to draw the swapchain texture. pub fn texture(&self) -> &wgpu::Texture { self.render_data .intermediary_lin_srgba .msaa_texture .as_ref() .map(|(tex, _)| tex) .unwrap_or(&self.render_data.intermediary_lin_srgba.texture) } /// A full view into the frame's texture. /// /// See `texture` for details. pub fn texture_view(&self) -> &wgpu::TextureView { self.render_data .intermediary_lin_srgba .msaa_texture .as_ref() .map(|(_, view)| view) .unwrap_or(&self.render_data.intermediary_lin_srgba.texture_view) } /// Returns the resolve target texture in the case that MSAA is enabled. pub fn resolve_target(&self) -> Option<&wgpu::TextureView> { if self.render_data.msaa_samples <= 1 { None } else { Some(&self.render_data.intermediary_lin_srgba.texture_view) } } /// The color format of the `Frame`'s intermediary linear sRGBA texture (equal to /// `Frame::TEXTURE_FORMAT`). pub fn texture_format(&self) -> wgpu::TextureFormat { Self::TEXTURE_FORMAT } /// The number of MSAA samples of the `Frame`'s intermediary linear sRGBA texture. pub fn texture_msaa_samples(&self) -> u32 { self.render_data.msaa_samples } /// The size of the frame's texture in pixels. pub fn texture_size(&self) -> [u32; 2] { self.render_data.size } /// Short-hand for constructing a `wgpu::RenderPassColorAttachmentDescriptor` for use within a /// render pass that targets this frame's texture. The returned descriptor's `attachment` will /// the same `wgpu::TextureView` returned by the `Frame::texture` method. /// /// Note that this method will not perform any resolving. In the case that `msaa_samples` is /// greater than `1`, a render pass will be automatically added after the `view` completes and /// before the texture is drawn to the swapchain. pub fn color_attachment_descriptor(&self) -> wgpu::RenderPassColorAttachmentDescriptor { let load = wgpu::LoadOp::Load; let store = true; let attachment = match self.render_data.intermediary_lin_srgba.msaa_texture { None => &self.render_data.intermediary_lin_srgba.texture_view, Some((_, ref msaa_texture_view)) => msaa_texture_view, }; let resolve_target = None; wgpu::RenderPassColorAttachmentDescriptor { attachment, resolve_target, ops: wgpu::Operations { load, store }, } } /// Clear the texture with the given color. pub fn clear<C>(&self, color: C) where C: IntoLinSrgba<f32>, { let lin_srgba = color.into_lin_srgba(); let (r, g, b, a) = lin_srgba.into_components(); let (r, g, b, a) = (r as f64, g as f64, b as f64, a as f64); let color = wgpu::Color { r, g, b, a }; wgpu::clear_texture(self.texture_view(), color, &mut *self.command_encoder()) } /// Submit the frame to the GPU! /// /// Note that you do not need to call this manually as submission will occur automatically when /// the **Frame** is dropped. /// /// Before submission, the frame does the following: /// /// - If the frame's intermediary linear sRGBA texture is multisampled, resolve it. /// - Write the intermediary linear sRGBA image to the swap chain texture. /// /// It can sometimes be useful to submit the **Frame** before `view` completes in order to read /// the frame's texture back to the CPU (e.g. for screen shots, recordings, etc). pub fn submit(mut self) { self.submit_inner(); } } impl CaptureData { pub(crate) fn new(max_jobs: u32, timeout: Option<Duration>) -> Self { CaptureData { next_frame_path: Default::default(), texture_capturer: wgpu::TextureCapturer::new(Some(max_jobs), timeout), } } } impl RenderData { /// Initialise the render data. /// /// Creates an `wgpu::TextureView` with the given parameters. /// /// If `msaa_samples` is greater than 1 a `multisampled` texture will also be created. Otherwise the /// a regular non-multisampled image will be created. pub(crate) fn new( device: &wgpu::Device, swap_chain_dims: [u32; 2], swap_chain_format: wgpu::TextureFormat, msaa_samples: u32, ) -> Self { let intermediary_lin_srgba = create_intermediary_lin_srgba(device, swap_chain_dims, msaa_samples); let src_sample_count = 1; let swap_chain_sample_count = 1; let texture_reshaper = wgpu::TextureReshaper::new( device, &intermediary_lin_srgba.texture_view, src_sample_count, intermediary_lin_srgba.texture_view.sample_type(), swap_chain_sample_count, swap_chain_format, ); RenderData { intermediary_lin_srgba, texture_reshaper, size: swap_chain_dims, msaa_samples, } } } impl<'swap_chain> Drop for Frame<'swap_chain> { fn drop(&mut self) { if!self.raw_frame.is_submitted() { self.submit_inner(); } } } fn create_lin_srgba_msaa_texture( device: &wgpu::Device, swap_chain_dims: [u32; 2], msaa_samples: u32, ) -> wgpu::Texture { wgpu::TextureBuilder::new() .size(swap_chain_dims) .sample_count(msaa_samples) .usage(wgpu::TextureUsage::RENDER_ATTACHMENT) .format(Frame::TEXTURE_FORMAT) .build(device) } fn create_lin_srgba_texture(device: &wgpu::Device, swap_chain_dims: [u32; 2]) -> wgpu::Texture { wgpu::TextureBuilder::new() .size(swap_chain_dims) .format(Frame::TEXTURE_FORMAT) .usage(wgpu::TextureUsage::RENDER_ATTACHMENT | wgpu::TextureUsage::SAMPLED) .build(device) } fn create_intermediary_lin_srgba( device: &wgpu::Device, swap_chain_dims: [u32; 2], msaa_samples: u32, ) -> IntermediaryLinSrgba { let msaa_texture = match msaa_samples { 0 | 1 => None, _ => { let texture = create_lin_srgba_msaa_texture(device, swap_chain_dims, msaa_samples); let texture_view = texture.view().build(); Some((texture, texture_view)) } }; let texture = create_lin_srgba_texture(device, swap_chain_dims); let texture_view = texture.view().build(); IntermediaryLinSrgba { msaa_texture, texture, texture_view, } }
fn submit_inner(&mut self) { let Frame { ref capture_data, ref render_data, ref mut raw_frame,
random_line_split
mod.rs
//! Items related to the **Frame** type, describing a single frame of graphics for a single window. use crate::color::IntoLinSrgba; use crate::wgpu; use std::ops; use std::path::PathBuf; use std::sync::Mutex; use std::time::Duration; pub mod raw; pub use self::raw::RawFrame; /// A **Frame** to which the user can draw graphics before it is presented to the display. /// /// **Frame**s are delivered to the user for drawing via the user's **view** function. /// /// See the **RawFrame** docs for more details on how the implementation works under the hood. The /// **Frame** type differs in that rather than drawing directly to the swapchain image the user may /// draw to an intermediary linear sRGBA image. There are several advantages of drawing to an /// intermediary image. pub struct Frame<'swap_chain> { raw_frame: RawFrame<'swap_chain>, render_data: &'swap_chain RenderData, capture_data: &'swap_chain CaptureData, } /// Data specific to the intermediary textures. #[derive(Debug)] pub struct RenderData { intermediary_lin_srgba: IntermediaryLinSrgba, msaa_samples: u32, size: [u32; 2], // For writing the intermediary linear sRGBA texture to the swap chain texture. texture_reshaper: wgpu::TextureReshaper, } /// Data related to the capturing of a frame. #[derive(Debug)] pub(crate) struct CaptureData { // If `Some`, indicates a path to which the current frame should be written. pub(crate) next_frame_path: Mutex<Option<PathBuf>>, // The `TextureCapturer` used to capture the frame. pub(crate) texture_capturer: wgpu::TextureCapturer, } /// Intermediary textures used as a target before resolving multisampling and writing to the /// swapchain texture. #[derive(Debug)] pub(crate) struct IntermediaryLinSrgba { msaa_texture: Option<(wgpu::Texture, wgpu::TextureView)>, texture: wgpu::Texture, texture_view: wgpu::TextureView, } impl<'swap_chain> ops::Deref for Frame<'swap_chain> { type Target = RawFrame<'swap_chain>; fn deref(&self) -> &Self::Target { &self.raw_frame } } impl<'swap_chain> Frame<'swap_chain> { /// The default number of multisample anti-aliasing samples used if the window with which the /// `Frame` is associated supports it. pub const DEFAULT_MSAA_SAMPLES: u32 = 4; /// The texture format used by the intermediary linear sRGBA image. /// /// We use a high bit depth format in order to retain as much information as possible when /// converting from the linear representation to the swapchain format (normally a non-linear /// representation). // TODO: Kvark recommends trying `Rgb10A2Unorm`. pub const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; // Initialise a new empty frame ready for "drawing". pub(crate) fn new_empty( raw_frame: RawFrame<'swap_chain>, render_data: &'swap_chain RenderData, capture_data: &'swap_chain CaptureData, ) -> Self { Frame { raw_frame, render_data, capture_data, } } // The private implementation of `submit`, allowing it to be called during `drop` if submission // has not yet occurred. fn submit_inner(&mut self) { let Frame { ref capture_data, ref render_data, ref mut raw_frame, } = *self; // Resolve the MSAA if necessary. if let Some((_, ref msaa_texture_view)) = render_data.intermediary_lin_srgba.msaa_texture { let mut encoder = raw_frame.command_encoder(); wgpu::resolve_texture( msaa_texture_view, &render_data.intermediary_lin_srgba.texture_view, &mut *encoder, ); } // Check to see if the user specified capturing the frame. let mut snapshot_capture = None; if let Ok(mut guard) = capture_data.next_frame_path.lock() { if let Some(path) = guard.take() { let device = raw_frame.device_queue_pair().device(); let mut encoder = raw_frame.command_encoder(); let snapshot = capture_data.texture_capturer.capture( device, &mut *encoder, &render_data.intermediary_lin_srgba.texture, ); snapshot_capture = Some((path, snapshot)); } } // Convert the linear sRGBA image to the swapchain image. // // To do so, we sample the linear sRGBA image and draw it to the swapchain image using // two triangles and a fragment shader. { let mut encoder = raw_frame.command_encoder(); render_data .texture_reshaper .encode_render_pass(raw_frame.swap_chain_texture(), &mut *encoder); } // Submit all commands on the device queue. raw_frame.submit_inner(); // If the user did specify capturing the frame, submit the asynchronous read. if let Some((path, snapshot)) = snapshot_capture { let result = snapshot.read(move |result| match result { // TODO: Log errors, don't print to stderr. Err(e) => eprintln!("failed to async read captured frame: {:?}", e), Ok(image) => { let image = image.to_owned(); if let Err(e) = image.save(&path) { // TODO: Log errors, don't print to stderr. eprintln!( "failed to save captured frame to \"{}\": {}", path.display(), e ); } } }); if let Err(wgpu::TextureCapturerAwaitWorkerTimeout(_)) = result { // TODO: Log errors, don't print to stderr. eprintln!("timed out while waiting for a worker thread to capture the frame"); } } } /// The texture to which all graphics should be drawn this frame. /// /// This is **not** the swapchain texture, but rather an intermediary linear sRGBA image. This /// intermediary image is used in order to: /// /// - Ensure consistent MSAA resolve behaviour across platforms. /// - Avoid the need for multiple implicit conversions to and from linear sRGBA for each /// graphics pipeline render pass that is used. /// - Allow for the user's rendered image to persist between frames. /// /// The exact format of the texture is equal to `Frame::TEXTURE_FORMAT`. /// /// If the number of MSAA samples specified is greater than `1` (which it is by default if /// supported by the platform), this will be a multisampled texture. After the **view** /// function returns, this texture will be resolved to a non-multisampled linear sRGBA texture. /// After the texture has been resolved if necessary, it will then be used as a shader input /// within a graphics pipeline used to draw the swapchain texture. pub fn texture(&self) -> &wgpu::Texture { self.render_data .intermediary_lin_srgba .msaa_texture .as_ref() .map(|(tex, _)| tex) .unwrap_or(&self.render_data.intermediary_lin_srgba.texture) } /// A full view into the frame's texture. /// /// See `texture` for details. pub fn texture_view(&self) -> &wgpu::TextureView { self.render_data .intermediary_lin_srgba .msaa_texture .as_ref() .map(|(_, view)| view) .unwrap_or(&self.render_data.intermediary_lin_srgba.texture_view) } /// Returns the resolve target texture in the case that MSAA is enabled. pub fn resolve_target(&self) -> Option<&wgpu::TextureView> { if self.render_data.msaa_samples <= 1 { None } else { Some(&self.render_data.intermediary_lin_srgba.texture_view) } } /// The color format of the `Frame`'s intermediary linear sRGBA texture (equal to /// `Frame::TEXTURE_FORMAT`). pub fn texture_format(&self) -> wgpu::TextureFormat { Self::TEXTURE_FORMAT } /// The number of MSAA samples of the `Frame`'s intermediary linear sRGBA texture. pub fn texture_msaa_samples(&self) -> u32 { self.render_data.msaa_samples } /// The size of the frame's texture in pixels. pub fn texture_size(&self) -> [u32; 2] { self.render_data.size } /// Short-hand for constructing a `wgpu::RenderPassColorAttachmentDescriptor` for use within a /// render pass that targets this frame's texture. The returned descriptor's `attachment` will /// the same `wgpu::TextureView` returned by the `Frame::texture` method. /// /// Note that this method will not perform any resolving. In the case that `msaa_samples` is /// greater than `1`, a render pass will be automatically added after the `view` completes and /// before the texture is drawn to the swapchain. pub fn color_attachment_descriptor(&self) -> wgpu::RenderPassColorAttachmentDescriptor { let load = wgpu::LoadOp::Load; let store = true; let attachment = match self.render_data.intermediary_lin_srgba.msaa_texture { None => &self.render_data.intermediary_lin_srgba.texture_view, Some((_, ref msaa_texture_view)) => msaa_texture_view, }; let resolve_target = None; wgpu::RenderPassColorAttachmentDescriptor { attachment, resolve_target, ops: wgpu::Operations { load, store }, } } /// Clear the texture with the given color. pub fn clear<C>(&self, color: C) where C: IntoLinSrgba<f32>,
/// Submit the frame to the GPU! /// /// Note that you do not need to call this manually as submission will occur automatically when /// the **Frame** is dropped. /// /// Before submission, the frame does the following: /// /// - If the frame's intermediary linear sRGBA texture is multisampled, resolve it. /// - Write the intermediary linear sRGBA image to the swap chain texture. /// /// It can sometimes be useful to submit the **Frame** before `view` completes in order to read /// the frame's texture back to the CPU (e.g. for screen shots, recordings, etc). pub fn submit(mut self) { self.submit_inner(); } } impl CaptureData { pub(crate) fn new(max_jobs: u32, timeout: Option<Duration>) -> Self { CaptureData { next_frame_path: Default::default(), texture_capturer: wgpu::TextureCapturer::new(Some(max_jobs), timeout), } } } impl RenderData { /// Initialise the render data. /// /// Creates an `wgpu::TextureView` with the given parameters. /// /// If `msaa_samples` is greater than 1 a `multisampled` texture will also be created. Otherwise the /// a regular non-multisampled image will be created. pub(crate) fn new( device: &wgpu::Device, swap_chain_dims: [u32; 2], swap_chain_format: wgpu::TextureFormat, msaa_samples: u32, ) -> Self { let intermediary_lin_srgba = create_intermediary_lin_srgba(device, swap_chain_dims, msaa_samples); let src_sample_count = 1; let swap_chain_sample_count = 1; let texture_reshaper = wgpu::TextureReshaper::new( device, &intermediary_lin_srgba.texture_view, src_sample_count, intermediary_lin_srgba.texture_view.sample_type(), swap_chain_sample_count, swap_chain_format, ); RenderData { intermediary_lin_srgba, texture_reshaper, size: swap_chain_dims, msaa_samples, } } } impl<'swap_chain> Drop for Frame<'swap_chain> { fn drop(&mut self) { if!self.raw_frame.is_submitted() { self.submit_inner(); } } } fn create_lin_srgba_msaa_texture( device: &wgpu::Device, swap_chain_dims: [u32; 2], msaa_samples: u32, ) -> wgpu::Texture { wgpu::TextureBuilder::new() .size(swap_chain_dims) .sample_count(msaa_samples) .usage(wgpu::TextureUsage::RENDER_ATTACHMENT) .format(Frame::TEXTURE_FORMAT) .build(device) } fn create_lin_srgba_texture(device: &wgpu::Device, swap_chain_dims: [u32; 2]) -> wgpu::Texture { wgpu::TextureBuilder::new() .size(swap_chain_dims) .format(Frame::TEXTURE_FORMAT) .usage(wgpu::TextureUsage::RENDER_ATTACHMENT | wgpu::TextureUsage::SAMPLED) .build(device) } fn create_intermediary_lin_srgba( device: &wgpu::Device, swap_chain_dims: [u32; 2], msaa_samples: u32, ) -> IntermediaryLinSrgba { let msaa_texture = match msaa_samples { 0 | 1 => None, _ => { let texture = create_lin_srgba_msaa_texture(device, swap_chain_dims, msaa_samples); let texture_view = texture.view().build(); Some((texture, texture_view)) } }; let texture = create_lin_srgba_texture(device, swap_chain_dims); let texture_view = texture.view().build(); IntermediaryLinSrgba { msaa_texture, texture, texture_view, } }
{ let lin_srgba = color.into_lin_srgba(); let (r, g, b, a) = lin_srgba.into_components(); let (r, g, b, a) = (r as f64, g as f64, b as f64, a as f64); let color = wgpu::Color { r, g, b, a }; wgpu::clear_texture(self.texture_view(), color, &mut *self.command_encoder()) }
identifier_body
xmlname.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/. */ //! Functions for validating and extracting qualified XML names. use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::str::DOMString; use html5ever::{LocalName, Namespace, Prefix}; /// Validate a qualified name. See https://dom.spec.whatwg.org/#validate for details. pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult { match xml_name_type(qualified_name) { XMLName::InvalidXMLName => { // Step 1. Err(Error::InvalidCharacter) }, XMLName::Name => { // Step 2. Err(Error::Namespace) }, XMLName::QName => Ok(()), } } /// Validate a namespace and qualified name and extract their parts. /// See https://dom.spec.whatwg.org/#validate-and-extract for details. pub fn validate_and_extract( namespace: Option<DOMString>, qualified_name: &str, ) -> Fallible<(Namespace, Option<Prefix>, LocalName)> { // Step 1. let namespace = namespace_from_domstring(namespace); // Step 2. validate_qualified_name(qualified_name)?; let colon = ':'; // Step 5. let mut parts = qualified_name.splitn(2, colon); let (maybe_prefix, local_name) = { let maybe_prefix = parts.next(); let maybe_local_name = parts.next(); debug_assert!(parts.next().is_none()); if let Some(local_name) = maybe_local_name { debug_assert!(!maybe_prefix.unwrap().is_empty()); (maybe_prefix, local_name) } else { (None, maybe_prefix.unwrap()) } }; debug_assert!(!local_name.contains(colon)); match (namespace, maybe_prefix) { (ns!(), Some(_)) => { // Step 6. Err(Error::Namespace) }, (ref ns, Some("xml")) if ns!= &ns!(xml) => { // Step 7. Err(Error::Namespace) }, (ref ns, p) if ns!= &ns!(xmlns) && (qualified_name == "xmlns" || p == Some("xmlns")) => { // Step 8. Err(Error::Namespace) }, (ns!(xmlns), p) if qualified_name!= "xmlns" && p!= Some("xmlns") => { // Step 9. Err(Error::Namespace) }, (ns, p) => { // Step 10. Ok((ns, p.map(Prefix::from), LocalName::from(local_name))) }, } } /// Results of `xml_name_type`. #[derive(PartialEq)] #[allow(missing_docs)] pub enum XMLName { QName, Name, InvalidXMLName, } /// Check if an element name is valid. See http://www.w3.org/TR/xml/#NT-Name /// for details. pub fn xml_name_type(name: &str) -> XMLName { fn
(c: char) -> bool { match c { ':' | 'A'...'Z' | '_' | 'a'...'z' | '\u{C0}'...'\u{D6}' | '\u{D8}'...'\u{F6}' | '\u{F8}'...'\u{2FF}' | '\u{370}'...'\u{37D}' | '\u{37F}'...'\u{1FFF}' | '\u{200C}'...'\u{200D}' | '\u{2070}'...'\u{218F}' | '\u{2C00}'...'\u{2FEF}' | '\u{3001}'...'\u{D7FF}' | '\u{F900}'...'\u{FDCF}' | '\u{FDF0}'...'\u{FFFD}' | '\u{10000}'...'\u{EFFFF}' => true, _ => false, } } fn is_valid_continuation(c: char) -> bool { is_valid_start(c) || match c { '-' | '.' | '0'...'9' | '\u{B7}' | '\u{300}'...'\u{36F}' | '\u{203F}'...'\u{2040}' => true, _ => false, } } let mut iter = name.chars(); let mut non_qname_colons = false; let mut seen_colon = false; let mut last = match iter.next() { None => return XMLName::InvalidXMLName, Some(c) => { if!is_valid_start(c) { return XMLName::InvalidXMLName; } if c == ':' { non_qname_colons = true; } c }, }; for c in iter { if!is_valid_continuation(c) { return XMLName::InvalidXMLName; } if c == ':' { if seen_colon { non_qname_colons = true; } else { seen_colon = true; } } last = c } if last == ':' { non_qname_colons = true } if non_qname_colons { XMLName::Name } else { XMLName::QName } } /// Convert a possibly-null URL to a namespace. /// /// If the URL is None, returns the empty namespace. pub fn namespace_from_domstring(url: Option<DOMString>) -> Namespace { match url { None => ns!(), Some(s) => Namespace::from(s), } }
is_valid_start
identifier_name
xmlname.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/. */ //! Functions for validating and extracting qualified XML names. use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::str::DOMString; use html5ever::{LocalName, Namespace, Prefix}; /// Validate a qualified name. See https://dom.spec.whatwg.org/#validate for details. pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult { match xml_name_type(qualified_name) { XMLName::InvalidXMLName => { // Step 1. Err(Error::InvalidCharacter) }, XMLName::Name => { // Step 2. Err(Error::Namespace) }, XMLName::QName => Ok(()), } } /// Validate a namespace and qualified name and extract their parts. /// See https://dom.spec.whatwg.org/#validate-and-extract for details. pub fn validate_and_extract( namespace: Option<DOMString>, qualified_name: &str, ) -> Fallible<(Namespace, Option<Prefix>, LocalName)> { // Step 1. let namespace = namespace_from_domstring(namespace); // Step 2. validate_qualified_name(qualified_name)?; let colon = ':'; // Step 5. let mut parts = qualified_name.splitn(2, colon); let (maybe_prefix, local_name) = { let maybe_prefix = parts.next(); let maybe_local_name = parts.next(); debug_assert!(parts.next().is_none()); if let Some(local_name) = maybe_local_name { debug_assert!(!maybe_prefix.unwrap().is_empty()); (maybe_prefix, local_name) } else { (None, maybe_prefix.unwrap()) } }; debug_assert!(!local_name.contains(colon)); match (namespace, maybe_prefix) { (ns!(), Some(_)) => { // Step 6. Err(Error::Namespace) }, (ref ns, Some("xml")) if ns!= &ns!(xml) => { // Step 7. Err(Error::Namespace) }, (ref ns, p) if ns!= &ns!(xmlns) && (qualified_name == "xmlns" || p == Some("xmlns")) => { // Step 8. Err(Error::Namespace) }, (ns!(xmlns), p) if qualified_name!= "xmlns" && p!= Some("xmlns") => { // Step 9. Err(Error::Namespace) }, (ns, p) => { // Step 10. Ok((ns, p.map(Prefix::from), LocalName::from(local_name))) }, } } /// Results of `xml_name_type`. #[derive(PartialEq)] #[allow(missing_docs)] pub enum XMLName { QName, Name, InvalidXMLName, } /// Check if an element name is valid. See http://www.w3.org/TR/xml/#NT-Name /// for details. pub fn xml_name_type(name: &str) -> XMLName { fn is_valid_start(c: char) -> bool { match c { ':' | 'A'...'Z' | '_' | 'a'...'z' | '\u{C0}'...'\u{D6}' | '\u{D8}'...'\u{F6}' | '\u{F8}'...'\u{2FF}' | '\u{370}'...'\u{37D}' | '\u{37F}'...'\u{1FFF}' | '\u{200C}'...'\u{200D}' | '\u{2070}'...'\u{218F}' | '\u{2C00}'...'\u{2FEF}' | '\u{3001}'...'\u{D7FF}' | '\u{F900}'...'\u{FDCF}' | '\u{FDF0}'...'\u{FFFD}' | '\u{10000}'...'\u{EFFFF}' => true, _ => false, } } fn is_valid_continuation(c: char) -> bool { is_valid_start(c) || match c { '-' | '.' | '0'...'9' | '\u{B7}' | '\u{300}'...'\u{36F}' | '\u{203F}'...'\u{2040}' => true, _ => false, } } let mut iter = name.chars(); let mut non_qname_colons = false; let mut seen_colon = false; let mut last = match iter.next() { None => return XMLName::InvalidXMLName, Some(c) => { if!is_valid_start(c) { return XMLName::InvalidXMLName; } if c == ':' { non_qname_colons = true; } c }, }; for c in iter { if!is_valid_continuation(c) { return XMLName::InvalidXMLName; } if c == ':'
last = c } if last == ':' { non_qname_colons = true } if non_qname_colons { XMLName::Name } else { XMLName::QName } } /// Convert a possibly-null URL to a namespace. /// /// If the URL is None, returns the empty namespace. pub fn namespace_from_domstring(url: Option<DOMString>) -> Namespace { match url { None => ns!(), Some(s) => Namespace::from(s), } }
{ if seen_colon { non_qname_colons = true; } else { seen_colon = true; } }
conditional_block
xmlname.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/. */ //! Functions for validating and extracting qualified XML names. use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::str::DOMString; use html5ever::{LocalName, Namespace, Prefix}; /// Validate a qualified name. See https://dom.spec.whatwg.org/#validate for details. pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult { match xml_name_type(qualified_name) { XMLName::InvalidXMLName => { // Step 1. Err(Error::InvalidCharacter) }, XMLName::Name => { // Step 2. Err(Error::Namespace) }, XMLName::QName => Ok(()), } } /// Validate a namespace and qualified name and extract their parts. /// See https://dom.spec.whatwg.org/#validate-and-extract for details. pub fn validate_and_extract( namespace: Option<DOMString>, qualified_name: &str, ) -> Fallible<(Namespace, Option<Prefix>, LocalName)> { // Step 1. let namespace = namespace_from_domstring(namespace); // Step 2. validate_qualified_name(qualified_name)?; let colon = ':'; // Step 5. let mut parts = qualified_name.splitn(2, colon); let (maybe_prefix, local_name) = { let maybe_prefix = parts.next(); let maybe_local_name = parts.next(); debug_assert!(parts.next().is_none()); if let Some(local_name) = maybe_local_name { debug_assert!(!maybe_prefix.unwrap().is_empty()); (maybe_prefix, local_name) } else { (None, maybe_prefix.unwrap()) } }; debug_assert!(!local_name.contains(colon)); match (namespace, maybe_prefix) { (ns!(), Some(_)) => { // Step 6. Err(Error::Namespace) }, (ref ns, Some("xml")) if ns!= &ns!(xml) => { // Step 7. Err(Error::Namespace) }, (ref ns, p) if ns!= &ns!(xmlns) && (qualified_name == "xmlns" || p == Some("xmlns")) => { // Step 8. Err(Error::Namespace) }, (ns!(xmlns), p) if qualified_name!= "xmlns" && p!= Some("xmlns") => { // Step 9. Err(Error::Namespace) }, (ns, p) => { // Step 10.
} /// Results of `xml_name_type`. #[derive(PartialEq)] #[allow(missing_docs)] pub enum XMLName { QName, Name, InvalidXMLName, } /// Check if an element name is valid. See http://www.w3.org/TR/xml/#NT-Name /// for details. pub fn xml_name_type(name: &str) -> XMLName { fn is_valid_start(c: char) -> bool { match c { ':' | 'A'...'Z' | '_' | 'a'...'z' | '\u{C0}'...'\u{D6}' | '\u{D8}'...'\u{F6}' | '\u{F8}'...'\u{2FF}' | '\u{370}'...'\u{37D}' | '\u{37F}'...'\u{1FFF}' | '\u{200C}'...'\u{200D}' | '\u{2070}'...'\u{218F}' | '\u{2C00}'...'\u{2FEF}' | '\u{3001}'...'\u{D7FF}' | '\u{F900}'...'\u{FDCF}' | '\u{FDF0}'...'\u{FFFD}' | '\u{10000}'...'\u{EFFFF}' => true, _ => false, } } fn is_valid_continuation(c: char) -> bool { is_valid_start(c) || match c { '-' | '.' | '0'...'9' | '\u{B7}' | '\u{300}'...'\u{36F}' | '\u{203F}'...'\u{2040}' => true, _ => false, } } let mut iter = name.chars(); let mut non_qname_colons = false; let mut seen_colon = false; let mut last = match iter.next() { None => return XMLName::InvalidXMLName, Some(c) => { if!is_valid_start(c) { return XMLName::InvalidXMLName; } if c == ':' { non_qname_colons = true; } c }, }; for c in iter { if!is_valid_continuation(c) { return XMLName::InvalidXMLName; } if c == ':' { if seen_colon { non_qname_colons = true; } else { seen_colon = true; } } last = c } if last == ':' { non_qname_colons = true } if non_qname_colons { XMLName::Name } else { XMLName::QName } } /// Convert a possibly-null URL to a namespace. /// /// If the URL is None, returns the empty namespace. pub fn namespace_from_domstring(url: Option<DOMString>) -> Namespace { match url { None => ns!(), Some(s) => Namespace::from(s), } }
Ok((ns, p.map(Prefix::from), LocalName::from(local_name))) }, }
random_line_split
protocol.rs
use std::marker::PhantomData; use std::mem; use session_types::*; use peano::{Peano,Pop}; use super::{IO, Transfers}; /// A `Protocol` describes the underlying protocol, including the "initial" session /// type. `Handler`s are defined over concrete `Protocol`s to implement the behavior /// of a protocol in a given `SessionType`. pub trait Protocol { type Initial: SessionType; } /// Handlers must return `Defer` to indicate to the `Session` how to proceed in /// the future. `Defer` can be obtained by calling `.defer()` on the channel, or /// by calling `.close()` when the session is `End`. pub struct Defer<P: Protocol, I> { io: Option<I>, proto: Option<P>, func: DeferFunc<P, I, (), ()>, open: bool, _marker: PhantomData<P> } impl<P: Protocol, I> Defer<P, I> { #[doc(hidden)] pub fn new<X: SessionType, Y: SessionType>(chan: Channel<P, I, X, Y>, next: DeferFunc<P, I, (), ()>, open: bool) -> Defer<P, I> { Defer { io: Some(chan.io), proto: Some(chan.proto), func: next, open: open, _marker: PhantomData } } } impl<P: Protocol, I> Defer<P, I> { pub fn with(&mut self) -> bool { let p: Channel<P, I, (), ()> = Channel::new(self.io.take().unwrap(), self.proto.take().unwrap()); let mut new = (self.func)(p); self.func = new.func; self.open = new.open; self.io = Some(new.io.take().unwrap()); self.proto = Some(new.proto.take().unwrap()); self.open } } #[doc(hidden)] pub type DeferFunc<P, I, E, S> = fn(Channel<P, I, E, S>) -> Defer<P, I>; /// Channels are provided to handlers to act as a "courier" for the session type /// and a guard for the IO backend. pub struct Channel<P: Protocol, I, E: SessionType, S: SessionType> { io: I, pub proto: P, _marker: PhantomData<(P, E, S)> } impl<P: Protocol, I, E: SessionType, S: SessionType> Channel<P, I, E, S> { #[doc(hidden)] /// This is unsafe because it could violate memory safety guarantees of the /// API if used improperly. pub unsafe fn into_session<N: SessionType>(self) -> Channel<P, I, E, N> { Channel { io: self.io, proto: self.proto, _marker: PhantomData } } } impl<P: Protocol, I, E: SessionType, S: SessionType> Channel<P, I, E, S> { fn new(io: I, proto: P) -> Channel<P, I, E, S> { Channel { io: io, proto: proto, _marker: PhantomData } } } /// `Handler` is implemented on `Protocol` for every session type you expect to defer, /// including the initial state. pub trait Handler<I, E: SessionType, S: SessionType>: Protocol + Sized { /// Given a channel in a particular state, with a particular environment, /// do whatever you'd like with the channel and return `Defer`, which you /// can obtain by doing `.defer()` on the channel or `.close()` on the /// channel. fn with(Channel<Self, I, E, S>) -> Defer<Self, I>; } pub fn channel<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), P::Initial> { Channel::new(io, proto) } pub fn
<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), <P::Initial as SessionType>::Dual> { Channel::new(io, proto) } impl<I, E: SessionType, S: SessionType, P: Handler<I, E, S>> Channel<P, I, E, S> { /// Defer the rest of the protocol execution. Useful for returning early. /// /// There must be a [`Handler`](trait.Handler.html) implemented for the protocol state you're deferring. pub fn defer(self) -> Defer<P, I> { let next_func: DeferFunc<P, I, E, S> = Handler::<I, E, S>::with; Defer::new(self, unsafe { mem::transmute(next_func) }, true) } } impl<I: IO, E: SessionType, P: Protocol> Channel<P, I, E, End> { /// Close the channel. Only possible if it's in the `End` state. pub fn close(mut self) -> Defer<P, I> { unsafe { self.io.close() }; let next_func: DeferFunc<P, I, E, End> = Dummy::<P, I, E, End>::with; Defer::new(self, unsafe { mem::transmute(next_func) }, false) } } impl<I: Transfers<T>, T, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Send<T, S>> { /// Send a `T` to IO. pub fn send(mut self, a: T) -> Channel<P, I, E, S> { unsafe { self.io.send(a) }; Channel::new(self.io, self.proto) } } impl<I: Transfers<T>, T, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Recv<T, S>> { /// Receive a `T` from IO. pub fn recv(mut self) -> Result<(T, Channel<P, I, E, S>), Self> { match unsafe { self.io.recv() } { Some(res) => Ok((res, Channel::new(self.io, self.proto))), None => { Err(self) } } } } impl<I, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Nest<S>> { /// Enter into a nested protocol. pub fn enter(self) -> Channel<P, I, (S, E), S> { Channel::new(self.io, self.proto) } } impl<I, N: Peano, E: SessionType + Pop<N>, P: Protocol> Channel<P, I, E, Escape<N>> { /// Escape from a nested protocol. pub fn pop(self) -> Channel<P, I, E::Tail, E::Head> { Channel::new(self.io, self.proto) } } impl<I: IO, E: SessionType, R: SessionType, P: Protocol> Channel<P, I, E, R> { /// Select a protocol to advance to. pub fn choose<S: SessionType>(mut self) -> Channel<P, I, E, S> where R: Chooser<S> { unsafe { self.io.send_discriminant(R::num()); } Channel::new(self.io, self.proto) } } impl<I: IO, // Our IO E: SessionType, // Our current environment S: SessionType, // The first branch of our accepting session Q: SessionType, // The second branch of our accepting session P: Acceptor<I, E, Accept<S, Q>> // We must be able to "accept" with our current state > Channel<P, I, E, Accept<S, Q>> { /// Accept one of many protocols and advance to its handler. pub fn accept(mut self) -> Result<Defer<P, I>, Channel<P, I, E, Accept<S, Q>>> { match unsafe { self.io.recv_discriminant() } { Some(num) => { Ok(<P as Acceptor<I, E, Accept<S, Q>>>::with(self, num)) }, None => { Err(self) } } } } struct Dummy<P, I, E, S>(PhantomData<(P, I, E, S)>); impl<I, P: Protocol, E: SessionType, S: SessionType> Dummy<P, I, E, S> { fn with(_: Channel<P, I, E, S>) -> Defer<P, I> { panic!("Channel was closed!"); } }
channel_dual
identifier_name
protocol.rs
use std::marker::PhantomData; use std::mem; use session_types::*; use peano::{Peano,Pop}; use super::{IO, Transfers}; /// A `Protocol` describes the underlying protocol, including the "initial" session /// type. `Handler`s are defined over concrete `Protocol`s to implement the behavior /// of a protocol in a given `SessionType`. pub trait Protocol { type Initial: SessionType; } /// Handlers must return `Defer` to indicate to the `Session` how to proceed in /// the future. `Defer` can be obtained by calling `.defer()` on the channel, or /// by calling `.close()` when the session is `End`. pub struct Defer<P: Protocol, I> { io: Option<I>, proto: Option<P>, func: DeferFunc<P, I, (), ()>, open: bool, _marker: PhantomData<P> } impl<P: Protocol, I> Defer<P, I> { #[doc(hidden)] pub fn new<X: SessionType, Y: SessionType>(chan: Channel<P, I, X, Y>, next: DeferFunc<P, I, (), ()>, open: bool) -> Defer<P, I> { Defer { io: Some(chan.io), proto: Some(chan.proto), func: next, open: open, _marker: PhantomData } } } impl<P: Protocol, I> Defer<P, I> { pub fn with(&mut self) -> bool { let p: Channel<P, I, (), ()> = Channel::new(self.io.take().unwrap(), self.proto.take().unwrap()); let mut new = (self.func)(p); self.func = new.func; self.open = new.open; self.io = Some(new.io.take().unwrap()); self.proto = Some(new.proto.take().unwrap()); self.open } } #[doc(hidden)] pub type DeferFunc<P, I, E, S> = fn(Channel<P, I, E, S>) -> Defer<P, I>; /// Channels are provided to handlers to act as a "courier" for the session type /// and a guard for the IO backend. pub struct Channel<P: Protocol, I, E: SessionType, S: SessionType> { io: I, pub proto: P, _marker: PhantomData<(P, E, S)> } impl<P: Protocol, I, E: SessionType, S: SessionType> Channel<P, I, E, S> { #[doc(hidden)] /// This is unsafe because it could violate memory safety guarantees of the /// API if used improperly. pub unsafe fn into_session<N: SessionType>(self) -> Channel<P, I, E, N> { Channel { io: self.io, proto: self.proto, _marker: PhantomData } } } impl<P: Protocol, I, E: SessionType, S: SessionType> Channel<P, I, E, S> { fn new(io: I, proto: P) -> Channel<P, I, E, S> { Channel { io: io, proto: proto, _marker: PhantomData } } } /// `Handler` is implemented on `Protocol` for every session type you expect to defer, /// including the initial state. pub trait Handler<I, E: SessionType, S: SessionType>: Protocol + Sized { /// Given a channel in a particular state, with a particular environment, /// do whatever you'd like with the channel and return `Defer`, which you /// can obtain by doing `.defer()` on the channel or `.close()` on the /// channel. fn with(Channel<Self, I, E, S>) -> Defer<Self, I>; } pub fn channel<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), P::Initial>
pub fn channel_dual<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), <P::Initial as SessionType>::Dual> { Channel::new(io, proto) } impl<I, E: SessionType, S: SessionType, P: Handler<I, E, S>> Channel<P, I, E, S> { /// Defer the rest of the protocol execution. Useful for returning early. /// /// There must be a [`Handler`](trait.Handler.html) implemented for the protocol state you're deferring. pub fn defer(self) -> Defer<P, I> { let next_func: DeferFunc<P, I, E, S> = Handler::<I, E, S>::with; Defer::new(self, unsafe { mem::transmute(next_func) }, true) } } impl<I: IO, E: SessionType, P: Protocol> Channel<P, I, E, End> { /// Close the channel. Only possible if it's in the `End` state. pub fn close(mut self) -> Defer<P, I> { unsafe { self.io.close() }; let next_func: DeferFunc<P, I, E, End> = Dummy::<P, I, E, End>::with; Defer::new(self, unsafe { mem::transmute(next_func) }, false) } } impl<I: Transfers<T>, T, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Send<T, S>> { /// Send a `T` to IO. pub fn send(mut self, a: T) -> Channel<P, I, E, S> { unsafe { self.io.send(a) }; Channel::new(self.io, self.proto) } } impl<I: Transfers<T>, T, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Recv<T, S>> { /// Receive a `T` from IO. pub fn recv(mut self) -> Result<(T, Channel<P, I, E, S>), Self> { match unsafe { self.io.recv() } { Some(res) => Ok((res, Channel::new(self.io, self.proto))), None => { Err(self) } } } } impl<I, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Nest<S>> { /// Enter into a nested protocol. pub fn enter(self) -> Channel<P, I, (S, E), S> { Channel::new(self.io, self.proto) } } impl<I, N: Peano, E: SessionType + Pop<N>, P: Protocol> Channel<P, I, E, Escape<N>> { /// Escape from a nested protocol. pub fn pop(self) -> Channel<P, I, E::Tail, E::Head> { Channel::new(self.io, self.proto) } } impl<I: IO, E: SessionType, R: SessionType, P: Protocol> Channel<P, I, E, R> { /// Select a protocol to advance to. pub fn choose<S: SessionType>(mut self) -> Channel<P, I, E, S> where R: Chooser<S> { unsafe { self.io.send_discriminant(R::num()); } Channel::new(self.io, self.proto) } } impl<I: IO, // Our IO E: SessionType, // Our current environment S: SessionType, // The first branch of our accepting session Q: SessionType, // The second branch of our accepting session P: Acceptor<I, E, Accept<S, Q>> // We must be able to "accept" with our current state > Channel<P, I, E, Accept<S, Q>> { /// Accept one of many protocols and advance to its handler. pub fn accept(mut self) -> Result<Defer<P, I>, Channel<P, I, E, Accept<S, Q>>> { match unsafe { self.io.recv_discriminant() } { Some(num) => { Ok(<P as Acceptor<I, E, Accept<S, Q>>>::with(self, num)) }, None => { Err(self) } } } } struct Dummy<P, I, E, S>(PhantomData<(P, I, E, S)>); impl<I, P: Protocol, E: SessionType, S: SessionType> Dummy<P, I, E, S> { fn with(_: Channel<P, I, E, S>) -> Defer<P, I> { panic!("Channel was closed!"); } }
{ Channel::new(io, proto) }
identifier_body
protocol.rs
use std::marker::PhantomData; use std::mem; use session_types::*; use peano::{Peano,Pop}; use super::{IO, Transfers}; /// A `Protocol` describes the underlying protocol, including the "initial" session /// type. `Handler`s are defined over concrete `Protocol`s to implement the behavior /// of a protocol in a given `SessionType`. pub trait Protocol { type Initial: SessionType; } /// Handlers must return `Defer` to indicate to the `Session` how to proceed in /// the future. `Defer` can be obtained by calling `.defer()` on the channel, or /// by calling `.close()` when the session is `End`. pub struct Defer<P: Protocol, I> { io: Option<I>, proto: Option<P>, func: DeferFunc<P, I, (), ()>, open: bool, _marker: PhantomData<P> } impl<P: Protocol, I> Defer<P, I> { #[doc(hidden)] pub fn new<X: SessionType, Y: SessionType>(chan: Channel<P, I, X, Y>, next: DeferFunc<P, I, (), ()>, open: bool) -> Defer<P, I> { Defer { io: Some(chan.io), proto: Some(chan.proto), func: next, open: open, _marker: PhantomData } } } impl<P: Protocol, I> Defer<P, I> { pub fn with(&mut self) -> bool { let p: Channel<P, I, (), ()> = Channel::new(self.io.take().unwrap(), self.proto.take().unwrap()); let mut new = (self.func)(p); self.func = new.func; self.open = new.open; self.io = Some(new.io.take().unwrap()); self.proto = Some(new.proto.take().unwrap()); self.open } } #[doc(hidden)] pub type DeferFunc<P, I, E, S> = fn(Channel<P, I, E, S>) -> Defer<P, I>; /// Channels are provided to handlers to act as a "courier" for the session type /// and a guard for the IO backend. pub struct Channel<P: Protocol, I, E: SessionType, S: SessionType> { io: I, pub proto: P, _marker: PhantomData<(P, E, S)> } impl<P: Protocol, I, E: SessionType, S: SessionType> Channel<P, I, E, S> { #[doc(hidden)] /// This is unsafe because it could violate memory safety guarantees of the /// API if used improperly. pub unsafe fn into_session<N: SessionType>(self) -> Channel<P, I, E, N> { Channel { io: self.io, proto: self.proto, _marker: PhantomData } } } impl<P: Protocol, I, E: SessionType, S: SessionType> Channel<P, I, E, S> { fn new(io: I, proto: P) -> Channel<P, I, E, S> { Channel { io: io, proto: proto, _marker: PhantomData } } } /// `Handler` is implemented on `Protocol` for every session type you expect to defer, /// including the initial state. pub trait Handler<I, E: SessionType, S: SessionType>: Protocol + Sized { /// Given a channel in a particular state, with a particular environment, /// do whatever you'd like with the channel and return `Defer`, which you /// can obtain by doing `.defer()` on the channel or `.close()` on the /// channel. fn with(Channel<Self, I, E, S>) -> Defer<Self, I>;
pub fn channel<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), P::Initial> { Channel::new(io, proto) } pub fn channel_dual<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), <P::Initial as SessionType>::Dual> { Channel::new(io, proto) } impl<I, E: SessionType, S: SessionType, P: Handler<I, E, S>> Channel<P, I, E, S> { /// Defer the rest of the protocol execution. Useful for returning early. /// /// There must be a [`Handler`](trait.Handler.html) implemented for the protocol state you're deferring. pub fn defer(self) -> Defer<P, I> { let next_func: DeferFunc<P, I, E, S> = Handler::<I, E, S>::with; Defer::new(self, unsafe { mem::transmute(next_func) }, true) } } impl<I: IO, E: SessionType, P: Protocol> Channel<P, I, E, End> { /// Close the channel. Only possible if it's in the `End` state. pub fn close(mut self) -> Defer<P, I> { unsafe { self.io.close() }; let next_func: DeferFunc<P, I, E, End> = Dummy::<P, I, E, End>::with; Defer::new(self, unsafe { mem::transmute(next_func) }, false) } } impl<I: Transfers<T>, T, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Send<T, S>> { /// Send a `T` to IO. pub fn send(mut self, a: T) -> Channel<P, I, E, S> { unsafe { self.io.send(a) }; Channel::new(self.io, self.proto) } } impl<I: Transfers<T>, T, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Recv<T, S>> { /// Receive a `T` from IO. pub fn recv(mut self) -> Result<(T, Channel<P, I, E, S>), Self> { match unsafe { self.io.recv() } { Some(res) => Ok((res, Channel::new(self.io, self.proto))), None => { Err(self) } } } } impl<I, E: SessionType, S: SessionType, P: Protocol> Channel<P, I, E, Nest<S>> { /// Enter into a nested protocol. pub fn enter(self) -> Channel<P, I, (S, E), S> { Channel::new(self.io, self.proto) } } impl<I, N: Peano, E: SessionType + Pop<N>, P: Protocol> Channel<P, I, E, Escape<N>> { /// Escape from a nested protocol. pub fn pop(self) -> Channel<P, I, E::Tail, E::Head> { Channel::new(self.io, self.proto) } } impl<I: IO, E: SessionType, R: SessionType, P: Protocol> Channel<P, I, E, R> { /// Select a protocol to advance to. pub fn choose<S: SessionType>(mut self) -> Channel<P, I, E, S> where R: Chooser<S> { unsafe { self.io.send_discriminant(R::num()); } Channel::new(self.io, self.proto) } } impl<I: IO, // Our IO E: SessionType, // Our current environment S: SessionType, // The first branch of our accepting session Q: SessionType, // The second branch of our accepting session P: Acceptor<I, E, Accept<S, Q>> // We must be able to "accept" with our current state > Channel<P, I, E, Accept<S, Q>> { /// Accept one of many protocols and advance to its handler. pub fn accept(mut self) -> Result<Defer<P, I>, Channel<P, I, E, Accept<S, Q>>> { match unsafe { self.io.recv_discriminant() } { Some(num) => { Ok(<P as Acceptor<I, E, Accept<S, Q>>>::with(self, num)) }, None => { Err(self) } } } } struct Dummy<P, I, E, S>(PhantomData<(P, I, E, S)>); impl<I, P: Protocol, E: SessionType, S: SessionType> Dummy<P, I, E, S> { fn with(_: Channel<P, I, E, S>) -> Defer<P, I> { panic!("Channel was closed!"); } }
}
random_line_split
hosts.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/. */ use parse_hosts::HostsFile; use servo_url::ServoUrl; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::{BufReader, Read}; use std::net::IpAddr; use std::sync::Mutex; lazy_static! { static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table());
fn create_host_table() -> Option<HashMap<String, IpAddr>> { // TODO: handle bad file path let path = match env::var("HOST_FILE") { Ok(host_file_path) => host_file_path, Err(_) => return None, }; let mut file = match File::open(&path) { Ok(f) => BufReader::new(f), Err(_) => return None, }; let mut lines = String::new(); match file.read_to_string(&mut lines) { Ok(_) => (), Err(_) => return None, }; Some(parse_hostsfile(&lines)) } pub fn replace_host_table(table: HashMap<String, IpAddr>) { *HOST_TABLE.lock().unwrap() = Some(table); } pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> { let mut host_table = HashMap::new(); for line in HostsFile::read_buffered(hostsfile_content.as_bytes()).lines() { if let Ok(ref line) = line { for host in line.hosts() { if let Some(ip) = line.ip() { host_table.insert(host.to_owned(), ip); } } } } host_table } pub fn replace_hosts(url: &ServoUrl) -> ServoUrl { HOST_TABLE.lock().unwrap().as_ref().map_or_else(|| url.clone(), |host_table| host_replacement(host_table, url)) } pub fn host_replacement(host_table: &HashMap<String, IpAddr>, url: &ServoUrl) -> ServoUrl { url.domain() .and_then(|domain| { host_table.get(domain).map(|ip| { let mut new_url = url.clone(); new_url.set_ip_host(*ip).unwrap(); new_url }) }) .unwrap_or_else(|| url.clone()) }
}
random_line_split
hosts.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/. */ use parse_hosts::HostsFile; use servo_url::ServoUrl; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::{BufReader, Read}; use std::net::IpAddr; use std::sync::Mutex; lazy_static! { static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table()); } fn create_host_table() -> Option<HashMap<String, IpAddr>> { // TODO: handle bad file path let path = match env::var("HOST_FILE") { Ok(host_file_path) => host_file_path, Err(_) => return None, }; let mut file = match File::open(&path) { Ok(f) => BufReader::new(f), Err(_) => return None, }; let mut lines = String::new(); match file.read_to_string(&mut lines) { Ok(_) => (), Err(_) => return None, }; Some(parse_hostsfile(&lines)) } pub fn replace_host_table(table: HashMap<String, IpAddr>) { *HOST_TABLE.lock().unwrap() = Some(table); } pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> { let mut host_table = HashMap::new(); for line in HostsFile::read_buffered(hostsfile_content.as_bytes()).lines() { if let Ok(ref line) = line { for host in line.hosts() { if let Some(ip) = line.ip() { host_table.insert(host.to_owned(), ip); } } } } host_table } pub fn replace_hosts(url: &ServoUrl) -> ServoUrl { HOST_TABLE.lock().unwrap().as_ref().map_or_else(|| url.clone(), |host_table| host_replacement(host_table, url)) } pub fn host_replacement(host_table: &HashMap<String, IpAddr>, url: &ServoUrl) -> ServoUrl
{ url.domain() .and_then(|domain| { host_table.get(domain).map(|ip| { let mut new_url = url.clone(); new_url.set_ip_host(*ip).unwrap(); new_url }) }) .unwrap_or_else(|| url.clone()) }
identifier_body
hosts.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/. */ use parse_hosts::HostsFile; use servo_url::ServoUrl; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::{BufReader, Read}; use std::net::IpAddr; use std::sync::Mutex; lazy_static! { static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table()); } fn create_host_table() -> Option<HashMap<String, IpAddr>> { // TODO: handle bad file path let path = match env::var("HOST_FILE") { Ok(host_file_path) => host_file_path, Err(_) => return None, }; let mut file = match File::open(&path) { Ok(f) => BufReader::new(f), Err(_) => return None, }; let mut lines = String::new(); match file.read_to_string(&mut lines) { Ok(_) => (), Err(_) => return None, }; Some(parse_hostsfile(&lines)) } pub fn replace_host_table(table: HashMap<String, IpAddr>) { *HOST_TABLE.lock().unwrap() = Some(table); } pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> { let mut host_table = HashMap::new(); for line in HostsFile::read_buffered(hostsfile_content.as_bytes()).lines() { if let Ok(ref line) = line { for host in line.hosts() { if let Some(ip) = line.ip() { host_table.insert(host.to_owned(), ip); } } } } host_table } pub fn replace_hosts(url: &ServoUrl) -> ServoUrl { HOST_TABLE.lock().unwrap().as_ref().map_or_else(|| url.clone(), |host_table| host_replacement(host_table, url)) } pub fn
(host_table: &HashMap<String, IpAddr>, url: &ServoUrl) -> ServoUrl { url.domain() .and_then(|domain| { host_table.get(domain).map(|ip| { let mut new_url = url.clone(); new_url.set_ip_host(*ip).unwrap(); new_url }) }) .unwrap_or_else(|| url.clone()) }
host_replacement
identifier_name
messages.rs
// Copyright 2015 © Samuel Dolt <[email protected]> // // This file is part of orion_backend. // // Orion_backend is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Orion_backend is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with orion_backend. If not, see <http://www.gnu.org/licenses/>. pub static COPYRIGHT: &'static str = " Copyright © 2015 Samuel Dolt <[email protected]> License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change or redistribute it. The is NO WARRANTY, to the extent permitted by law. "; pub static INVALID_TIMESTAMP: &'static str = " Invalid timestamp - Timestamp must be a valid IETF RFC3339 string. Example: - 1985-04-12T23:20:50.52Z Represents 20 minutes and 50.52 seconds after the 23rd hour of April 12th, 1985 in UTC
"; pub static INVALID_VALUE: &'static str = " Invalid value - Value should represent one or more measurements Example: - 9[V] - 9[V] 3[A] 5[K] Valid unit: - [V] for Volt - [A] for Ampere - [Ω] for Ohm - [W] for Watt - [K] for Kelvin - [s] for second - [kg] for Kilogram "; pub static INVALID_DEVICE: &'static str = " Invalid device - Device should be [email protected] Example: - [email protected] - [email protected]_usb ";
More info at `https://www.ietf.org/rfc/rfc3339.txt`
random_line_split
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId};
use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package, config: &Config) -> CargoResult<Resolve> { let prev = try!(ops::load_pkg_lockfile(package, config)); let resolve = try!(resolve_with_previous(registry, package, Method::Everything, prev.as_ref(), None)); if package.package_id().source_id().is_path() { try!(ops::write_pkg_lockfile(package, &resolve, config)); } Ok(resolve) } /// Resolve all dependencies for a package using an optional previous instance /// of resolve to guide the resolution process. /// /// This also takes an optional hash set, `to_avoid`, which is a list of package /// ids that should be avoided when consulting the previous instance of resolve /// (often used in pairings with updates). /// /// The previous resolve normally comes from a lockfile. This function does not /// read or write lockfiles from the filesystem. pub fn resolve_with_previous<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoResult<Resolve> { try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one package, they must all be updated in // step when any of them are updated. // // TODO: This seems like a hokey reason to single out the registry as being // different let mut to_avoid_sources = HashSet::new(); if let Some(to_avoid) = to_avoid { to_avoid_sources.extend(to_avoid.iter() .map(|p| p.source_id()) .filter(|s|!s.is_registry())); } let summary = package.summary().clone(); let (summary, replace) = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version // without disturbing the graph structure. To this end we perform // two actions here: // // 1. We inform the package registry of all locked packages. This // involves informing it of both the locked package's id as well // as the versions of all locked dependencies. The registry will // then takes this information into account when it is queried. // // 2. The specified package's summary will have its dependencies // modified to their precise variants. This will instruct the // first step of the resolution process to not query for ranges // but rather for precise dependency versions. // // This process must handle altered dependencies, however, as // it's possible for a manifest to change over time to have // dependencies added, removed, or modified to different version // ranges. To deal with this, we only actually lock a dependency // to the previously resolved version if the dependency listed // still matches the locked version. for node in r.iter().filter(|p| keep(p, to_avoid, &to_avoid_sources)) { let deps = r.deps_not_replaced(node) .filter(|p| keep(p, to_avoid, &to_avoid_sources)) .cloned().collect(); registry.register_lock(node.clone(), deps); } let summary = { let map = r.deps_not_replaced(r.root()).filter(|p| { keep(p, to_avoid, &to_avoid_sources) }).map(|d| { (d.name(), d) }).collect::<HashMap<_, _>>(); summary.map_dependencies(|dep| { match map.get(dep.name()) { Some(&lock) if dep.matches_id(lock) => dep.lock_to(lock), _ => dep, } }) }; let replace = package.manifest().replace(); let replace = replace.iter().map(|&(ref spec, ref dep)| { for (key, val) in r.replacements().iter() { if spec.matches(key) && dep.matches_id(val) { return (spec.clone(), dep.clone().lock_to(val)) } } (spec.clone(), dep.clone()) }).collect::<Vec<_>>(); (summary, replace) } None => (summary, package.manifest().replace().to_owned()), }; let mut resolved = try!(resolver::resolve(&summary, &method, &replace, registry)); if let Some(previous) = previous { resolved.copy_metadata(previous); } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avoid_sources: &HashSet<&'a SourceId>) -> bool { !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) =>!set.contains(p), None => true, } } }
use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops;
random_line_split
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package, config: &Config) -> CargoResult<Resolve> { let prev = try!(ops::load_pkg_lockfile(package, config)); let resolve = try!(resolve_with_previous(registry, package, Method::Everything, prev.as_ref(), None)); if package.package_id().source_id().is_path() { try!(ops::write_pkg_lockfile(package, &resolve, config)); } Ok(resolve) } /// Resolve all dependencies for a package using an optional previous instance /// of resolve to guide the resolution process. /// /// This also takes an optional hash set, `to_avoid`, which is a list of package /// ids that should be avoided when consulting the previous instance of resolve /// (often used in pairings with updates). /// /// The previous resolve normally comes from a lockfile. This function does not /// read or write lockfiles from the filesystem. pub fn
<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoResult<Resolve> { try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one package, they must all be updated in // step when any of them are updated. // // TODO: This seems like a hokey reason to single out the registry as being // different let mut to_avoid_sources = HashSet::new(); if let Some(to_avoid) = to_avoid { to_avoid_sources.extend(to_avoid.iter() .map(|p| p.source_id()) .filter(|s|!s.is_registry())); } let summary = package.summary().clone(); let (summary, replace) = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version // without disturbing the graph structure. To this end we perform // two actions here: // // 1. We inform the package registry of all locked packages. This // involves informing it of both the locked package's id as well // as the versions of all locked dependencies. The registry will // then takes this information into account when it is queried. // // 2. The specified package's summary will have its dependencies // modified to their precise variants. This will instruct the // first step of the resolution process to not query for ranges // but rather for precise dependency versions. // // This process must handle altered dependencies, however, as // it's possible for a manifest to change over time to have // dependencies added, removed, or modified to different version // ranges. To deal with this, we only actually lock a dependency // to the previously resolved version if the dependency listed // still matches the locked version. for node in r.iter().filter(|p| keep(p, to_avoid, &to_avoid_sources)) { let deps = r.deps_not_replaced(node) .filter(|p| keep(p, to_avoid, &to_avoid_sources)) .cloned().collect(); registry.register_lock(node.clone(), deps); } let summary = { let map = r.deps_not_replaced(r.root()).filter(|p| { keep(p, to_avoid, &to_avoid_sources) }).map(|d| { (d.name(), d) }).collect::<HashMap<_, _>>(); summary.map_dependencies(|dep| { match map.get(dep.name()) { Some(&lock) if dep.matches_id(lock) => dep.lock_to(lock), _ => dep, } }) }; let replace = package.manifest().replace(); let replace = replace.iter().map(|&(ref spec, ref dep)| { for (key, val) in r.replacements().iter() { if spec.matches(key) && dep.matches_id(val) { return (spec.clone(), dep.clone().lock_to(val)) } } (spec.clone(), dep.clone()) }).collect::<Vec<_>>(); (summary, replace) } None => (summary, package.manifest().replace().to_owned()), }; let mut resolved = try!(resolver::resolve(&summary, &method, &replace, registry)); if let Some(previous) = previous { resolved.copy_metadata(previous); } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avoid_sources: &HashSet<&'a SourceId>) -> bool { !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) =>!set.contains(p), None => true, } } }
resolve_with_previous
identifier_name
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package, config: &Config) -> CargoResult<Resolve> { let prev = try!(ops::load_pkg_lockfile(package, config)); let resolve = try!(resolve_with_previous(registry, package, Method::Everything, prev.as_ref(), None)); if package.package_id().source_id().is_path() { try!(ops::write_pkg_lockfile(package, &resolve, config)); } Ok(resolve) } /// Resolve all dependencies for a package using an optional previous instance /// of resolve to guide the resolution process. /// /// This also takes an optional hash set, `to_avoid`, which is a list of package /// ids that should be avoided when consulting the previous instance of resolve /// (often used in pairings with updates). /// /// The previous resolve normally comes from a lockfile. This function does not /// read or write lockfiles from the filesystem. pub fn resolve_with_previous<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoResult<Resolve> { try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one package, they must all be updated in // step when any of them are updated. // // TODO: This seems like a hokey reason to single out the registry as being // different let mut to_avoid_sources = HashSet::new(); if let Some(to_avoid) = to_avoid { to_avoid_sources.extend(to_avoid.iter() .map(|p| p.source_id()) .filter(|s|!s.is_registry())); } let summary = package.summary().clone(); let (summary, replace) = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version // without disturbing the graph structure. To this end we perform // two actions here: // // 1. We inform the package registry of all locked packages. This // involves informing it of both the locked package's id as well // as the versions of all locked dependencies. The registry will // then takes this information into account when it is queried. // // 2. The specified package's summary will have its dependencies // modified to their precise variants. This will instruct the // first step of the resolution process to not query for ranges // but rather for precise dependency versions. // // This process must handle altered dependencies, however, as // it's possible for a manifest to change over time to have // dependencies added, removed, or modified to different version // ranges. To deal with this, we only actually lock a dependency // to the previously resolved version if the dependency listed // still matches the locked version. for node in r.iter().filter(|p| keep(p, to_avoid, &to_avoid_sources)) { let deps = r.deps_not_replaced(node) .filter(|p| keep(p, to_avoid, &to_avoid_sources)) .cloned().collect(); registry.register_lock(node.clone(), deps); } let summary = { let map = r.deps_not_replaced(r.root()).filter(|p| { keep(p, to_avoid, &to_avoid_sources) }).map(|d| { (d.name(), d) }).collect::<HashMap<_, _>>(); summary.map_dependencies(|dep| { match map.get(dep.name()) { Some(&lock) if dep.matches_id(lock) => dep.lock_to(lock), _ => dep, } }) }; let replace = package.manifest().replace(); let replace = replace.iter().map(|&(ref spec, ref dep)| { for (key, val) in r.replacements().iter() { if spec.matches(key) && dep.matches_id(val) { return (spec.clone(), dep.clone().lock_to(val)) } } (spec.clone(), dep.clone()) }).collect::<Vec<_>>(); (summary, replace) } None => (summary, package.manifest().replace().to_owned()), }; let mut resolved = try!(resolver::resolve(&summary, &method, &replace, registry)); if let Some(previous) = previous { resolved.copy_metadata(previous); } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avoid_sources: &HashSet<&'a SourceId>) -> bool
}
{ !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) => !set.contains(p), None => true, } }
identifier_body
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package, config: &Config) -> CargoResult<Resolve> { let prev = try!(ops::load_pkg_lockfile(package, config)); let resolve = try!(resolve_with_previous(registry, package, Method::Everything, prev.as_ref(), None)); if package.package_id().source_id().is_path() { try!(ops::write_pkg_lockfile(package, &resolve, config)); } Ok(resolve) } /// Resolve all dependencies for a package using an optional previous instance /// of resolve to guide the resolution process. /// /// This also takes an optional hash set, `to_avoid`, which is a list of package /// ids that should be avoided when consulting the previous instance of resolve /// (often used in pairings with updates). /// /// The previous resolve normally comes from a lockfile. This function does not /// read or write lockfiles from the filesystem. pub fn resolve_with_previous<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoResult<Resolve> { try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one package, they must all be updated in // step when any of them are updated. // // TODO: This seems like a hokey reason to single out the registry as being // different let mut to_avoid_sources = HashSet::new(); if let Some(to_avoid) = to_avoid { to_avoid_sources.extend(to_avoid.iter() .map(|p| p.source_id()) .filter(|s|!s.is_registry())); } let summary = package.summary().clone(); let (summary, replace) = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version // without disturbing the graph structure. To this end we perform // two actions here: // // 1. We inform the package registry of all locked packages. This // involves informing it of both the locked package's id as well // as the versions of all locked dependencies. The registry will // then takes this information into account when it is queried. // // 2. The specified package's summary will have its dependencies // modified to their precise variants. This will instruct the // first step of the resolution process to not query for ranges // but rather for precise dependency versions. // // This process must handle altered dependencies, however, as // it's possible for a manifest to change over time to have // dependencies added, removed, or modified to different version // ranges. To deal with this, we only actually lock a dependency // to the previously resolved version if the dependency listed // still matches the locked version. for node in r.iter().filter(|p| keep(p, to_avoid, &to_avoid_sources)) { let deps = r.deps_not_replaced(node) .filter(|p| keep(p, to_avoid, &to_avoid_sources)) .cloned().collect(); registry.register_lock(node.clone(), deps); } let summary = { let map = r.deps_not_replaced(r.root()).filter(|p| { keep(p, to_avoid, &to_avoid_sources) }).map(|d| { (d.name(), d) }).collect::<HashMap<_, _>>(); summary.map_dependencies(|dep| { match map.get(dep.name()) { Some(&lock) if dep.matches_id(lock) => dep.lock_to(lock), _ => dep, } }) }; let replace = package.manifest().replace(); let replace = replace.iter().map(|&(ref spec, ref dep)| { for (key, val) in r.replacements().iter() { if spec.matches(key) && dep.matches_id(val)
} (spec.clone(), dep.clone()) }).collect::<Vec<_>>(); (summary, replace) } None => (summary, package.manifest().replace().to_owned()), }; let mut resolved = try!(resolver::resolve(&summary, &method, &replace, registry)); if let Some(previous) = previous { resolved.copy_metadata(previous); } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avoid_sources: &HashSet<&'a SourceId>) -> bool { !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) =>!set.contains(p), None => true, } } }
{ return (spec.clone(), dep.clone().lock_to(val)) }
conditional_block
main.rs
extern crate rand; use rand::Rng; use std::io; use std::cmp::Ordering; fn main()
println!("Expected an integer number, found non integer, ignoring the input."); continue; }, } } }; println!("You guessed {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too Small"), Ordering::Greater => println!("Too Big"), Ordering::Equal => { println!("You Won"); break; }, } println!(""); } }
{ let stopper = String::from("Quit"); let secret_number = rand::thread_rng().gen_range(1, 101); loop{ println!("Please enter your guess!"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess:i32 = match guess.trim().parse() { Ok(num) => num, Err(_) => { match guess.trim().cmp(&stopper) { Ordering::Equal => break, Ordering::Less => { println!("Expected an integer number, found non integer, ignoring the input."); continue; }, Ordering::Greater => {
identifier_body
main.rs
extern crate rand; use rand::Rng; use std::io; use std::cmp::Ordering; fn main() { let stopper = String::from("Quit"); let secret_number = rand::thread_rng().gen_range(1, 101); loop{ println!("Please enter your guess!"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess:i32 = match guess.trim().parse() { Ok(num) => num, Err(_) => { match guess.trim().cmp(&stopper) { Ordering::Equal => break, Ordering::Less => { println!("Expected an integer number, found non integer, ignoring the input."); continue; }, Ordering::Greater => { println!("Expected an integer number, found non integer, ignoring the input."); continue; }, } } }; println!("You guessed {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too Small"), Ordering::Greater => println!("Too Big"), Ordering::Equal => { println!("You Won"); break;
} println!(""); } }
},
random_line_split
main.rs
extern crate rand; use rand::Rng; use std::io; use std::cmp::Ordering; fn
() { let stopper = String::from("Quit"); let secret_number = rand::thread_rng().gen_range(1, 101); loop{ println!("Please enter your guess!"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess:i32 = match guess.trim().parse() { Ok(num) => num, Err(_) => { match guess.trim().cmp(&stopper) { Ordering::Equal => break, Ordering::Less => { println!("Expected an integer number, found non integer, ignoring the input."); continue; }, Ordering::Greater => { println!("Expected an integer number, found non integer, ignoring the input."); continue; }, } } }; println!("You guessed {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too Small"), Ordering::Greater => println!("Too Big"), Ordering::Equal => { println!("You Won"); break; }, } println!(""); } }
main
identifier_name
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U, F>(&self, f: F) -> Option<U> where F: FnMut(&str) -> U; /// Returns text arguments. fn text_args(&self) -> Option<String> { self.text(|text| text.to_owned()) } } impl<T: GenericEvent> TextEvent for T { fn from_text(text: &str, old_event: &Self) -> Option<Self> { GenericEvent::from_args(TEXT, &text.to_owned() as &Any, old_event) } fn text<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(&str) -> U { if self.event_id()!= TEXT
self.with_args(|any| { if let Some(text) = any.downcast_ref::<String>() { Some(f(&text)) } else { panic!("Expected &str") } }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_text() { use super::super::Input; let e = Input::Text("".to_string()); let x: Option<Input> = TextEvent::from_text("hello", &e); let y: Option<Input> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[test] fn test_event_text() { use Event; use super::super::Input; let e = Event::Input(Input::Text("".to_string())); let x: Option<Event> = TextEvent::from_text("hello", &e); let y: Option<Event> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } }
{ return None; }
conditional_block
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U, F>(&self, f: F) -> Option<U> where F: FnMut(&str) -> U; /// Returns text arguments. fn text_args(&self) -> Option<String> { self.text(|text| text.to_owned()) } } impl<T: GenericEvent> TextEvent for T { fn from_text(text: &str, old_event: &Self) -> Option<Self> { GenericEvent::from_args(TEXT, &text.to_owned() as &Any, old_event) } fn text<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(&str) -> U { if self.event_id()!= TEXT { return None; } self.with_args(|any| { if let Some(text) = any.downcast_ref::<String>() { Some(f(&text)) } else { panic!("Expected &str") } }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_text() { use super::super::Input; let e = Input::Text("".to_string()); let x: Option<Input> = TextEvent::from_text("hello", &e); let y: Option<Input> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[test] fn
() { use Event; use super::super::Input; let e = Event::Input(Input::Text("".to_string())); let x: Option<Event> = TextEvent::from_text("hello", &e); let y: Option<Event> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } }
test_event_text
identifier_name
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U, F>(&self, f: F) -> Option<U> where F: FnMut(&str) -> U; /// Returns text arguments. fn text_args(&self) -> Option<String> { self.text(|text| text.to_owned()) } } impl<T: GenericEvent> TextEvent for T { fn from_text(text: &str, old_event: &Self) -> Option<Self> { GenericEvent::from_args(TEXT, &text.to_owned() as &Any, old_event) } fn text<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(&str) -> U
} #[cfg(test)] mod tests { use super::*; #[test] fn test_input_text() { use super::super::Input; let e = Input::Text("".to_string()); let x: Option<Input> = TextEvent::from_text("hello", &e); let y: Option<Input> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[test] fn test_event_text() { use Event; use super::super::Input; let e = Event::Input(Input::Text("".to_string())); let x: Option<Event> = TextEvent::from_text("hello", &e); let y: Option<Event> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } }
{ if self.event_id() != TEXT { return None; } self.with_args(|any| { if let Some(text) = any.downcast_ref::<String>() { Some(f(&text)) } else { panic!("Expected &str") } }) }
identifier_body
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U, F>(&self, f: F) -> Option<U> where F: FnMut(&str) -> U; /// Returns text arguments. fn text_args(&self) -> Option<String> { self.text(|text| text.to_owned()) } } impl<T: GenericEvent> TextEvent for T { fn from_text(text: &str, old_event: &Self) -> Option<Self> { GenericEvent::from_args(TEXT, &text.to_owned() as &Any, old_event) } fn text<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(&str) -> U { if self.event_id()!= TEXT { return None; } self.with_args(|any| { if let Some(text) = any.downcast_ref::<String>() { Some(f(&text)) } else { panic!("Expected &str")
}) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_text() { use super::super::Input; let e = Input::Text("".to_string()); let x: Option<Input> = TextEvent::from_text("hello", &e); let y: Option<Input> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[test] fn test_event_text() { use Event; use super::super::Input; let e = Event::Input(Input::Text("".to_string())); let x: Option<Event> = TextEvent::from_text("hello", &e); let y: Option<Event> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } }
}
random_line_split
deriving-cmp-generic-enum.rs
// Copyright 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. // no-pretty-expanded FIXME #15189 #[derive(PartialEq, Eq, PartialOrd, Ord)] enum E<T> { E0, E1(T), E2(T,T) } pub fn main() { let e0 = E::E0; let e11 = E::E1(1); let e12 = E::E1(2); let e21 = E::E2(1, 1); let e22 = E::E2(1, 2); // in order for both PartialOrd and Ord let es = [e0, e11, e12, e21, e22]; for (i, e1) in es.iter().enumerate() { for (j, e2) in es.iter().enumerate() { let ord = i.cmp(&j); let eq = i == j; let lt = i < j;
assert_eq!(*e1 == *e2, eq); assert_eq!(*e1!= *e2,!eq); // PartialOrd assert_eq!(*e1 < *e2, lt); assert_eq!(*e1 > *e2, gt); assert_eq!(*e1 <= *e2, le); assert_eq!(*e1 >= *e2, ge); // Ord assert_eq!(e1.cmp(e2), ord); } } }
let le = i <= j; let gt = i > j; let ge = i >= j; // PartialEq
random_line_split
deriving-cmp-generic-enum.rs
// Copyright 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. // no-pretty-expanded FIXME #15189 #[derive(PartialEq, Eq, PartialOrd, Ord)] enum
<T> { E0, E1(T), E2(T,T) } pub fn main() { let e0 = E::E0; let e11 = E::E1(1); let e12 = E::E1(2); let e21 = E::E2(1, 1); let e22 = E::E2(1, 2); // in order for both PartialOrd and Ord let es = [e0, e11, e12, e21, e22]; for (i, e1) in es.iter().enumerate() { for (j, e2) in es.iter().enumerate() { let ord = i.cmp(&j); let eq = i == j; let lt = i < j; let le = i <= j; let gt = i > j; let ge = i >= j; // PartialEq assert_eq!(*e1 == *e2, eq); assert_eq!(*e1!= *e2,!eq); // PartialOrd assert_eq!(*e1 < *e2, lt); assert_eq!(*e1 > *e2, gt); assert_eq!(*e1 <= *e2, le); assert_eq!(*e1 >= *e2, ge); // Ord assert_eq!(e1.cmp(e2), ord); } } }
E
identifier_name
adt-brace-structs.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. // Unit test for the "user substitutions" that are annotated on each // node. #![feature(nll)] struct SomeStruct<T> { t: T } fn no_annot() { let c = 66; SomeStruct { t: &c }; } fn annot_underscore() { let c = 66; SomeStruct::<_> { t: &c }; } fn annot_reference_any_lifetime() { let c = 66; SomeStruct::<&u32> { t: &c }; } fn annot_reference_static_lifetime() { let c = 66; SomeStruct::<&'static u32> { t: &c }; //~ ERROR } fn annot_reference_named_lifetime<'a>(_d: &'a u32) { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR } fn annot_reference_named_lifetime_ok<'a>(c: &'a u32) { SomeStruct::<&'a u32> { t: c }; } fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) { let _closure = || { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR }; } fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) { let _closure = || { SomeStruct::<&'a u32> { t: c }; }; } fn
() { }
main
identifier_name
adt-brace-structs.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. // Unit test for the "user substitutions" that are annotated on each // node. #![feature(nll)] struct SomeStruct<T> { t: T } fn no_annot() { let c = 66; SomeStruct { t: &c }; } fn annot_underscore()
fn annot_reference_any_lifetime() { let c = 66; SomeStruct::<&u32> { t: &c }; } fn annot_reference_static_lifetime() { let c = 66; SomeStruct::<&'static u32> { t: &c }; //~ ERROR } fn annot_reference_named_lifetime<'a>(_d: &'a u32) { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR } fn annot_reference_named_lifetime_ok<'a>(c: &'a u32) { SomeStruct::<&'a u32> { t: c }; } fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) { let _closure = || { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR }; } fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) { let _closure = || { SomeStruct::<&'a u32> { t: c }; }; } fn main() { }
{ let c = 66; SomeStruct::<_> { t: &c }; }
identifier_body
adt-brace-structs.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. // Unit test for the "user substitutions" that are annotated on each // node. #![feature(nll)] struct SomeStruct<T> { t: T } fn no_annot() { let c = 66; SomeStruct { t: &c }; } fn annot_underscore() { let c = 66; SomeStruct::<_> { t: &c }; } fn annot_reference_any_lifetime() { let c = 66; SomeStruct::<&u32> { t: &c }; } fn annot_reference_static_lifetime() { let c = 66; SomeStruct::<&'static u32> { t: &c }; //~ ERROR } fn annot_reference_named_lifetime<'a>(_d: &'a u32) { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR } fn annot_reference_named_lifetime_ok<'a>(c: &'a u32) { SomeStruct::<&'a u32> { t: c }; }
} fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) { let _closure = || { SomeStruct::<&'a u32> { t: c }; }; } fn main() { }
fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) { let _closure = || { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR };
random_line_split
onig.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 onig; pub struct Regex(onig::Regex); unsafe impl Send for Regex {} impl Regex { pub fn new(pattern: &str) -> Result<Self, onig::Error> { onig::Regex::new(pattern).map(Regex) } pub fn is_match(&self, text: &str) -> bool { // Gah. onig's is_match function is anchored, but find is not. self.0.search_with_options( text, 0, text.len(), onig::SEARCH_OPTION_NONE, None).is_some() } pub fn find_iter<'r, 't>(
) -> onig::FindMatches<'r, 't> { self.0.find_iter(text) } }
&'r self, text: &'t str,
random_line_split
onig.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 onig; pub struct Regex(onig::Regex); unsafe impl Send for Regex {} impl Regex { pub fn new(pattern: &str) -> Result<Self, onig::Error>
pub fn is_match(&self, text: &str) -> bool { // Gah. onig's is_match function is anchored, but find is not. self.0.search_with_options( text, 0, text.len(), onig::SEARCH_OPTION_NONE, None).is_some() } pub fn find_iter<'r, 't>( &'r self, text: &'t str, ) -> onig::FindMatches<'r, 't> { self.0.find_iter(text) } }
{ onig::Regex::new(pattern).map(Regex) }
identifier_body
onig.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 onig; pub struct
(onig::Regex); unsafe impl Send for Regex {} impl Regex { pub fn new(pattern: &str) -> Result<Self, onig::Error> { onig::Regex::new(pattern).map(Regex) } pub fn is_match(&self, text: &str) -> bool { // Gah. onig's is_match function is anchored, but find is not. self.0.search_with_options( text, 0, text.len(), onig::SEARCH_OPTION_NONE, None).is_some() } pub fn find_iter<'r, 't>( &'r self, text: &'t str, ) -> onig::FindMatches<'r, 't> { self.0.find_iter(text) } }
Regex
identifier_name
types.rs
#![allow(unused_variables)] #![allow(non_upper_case_globals)] #![allow(dead_code)] #![allow(improper_ctypes)] use std::slice; use std::os::raw::c_char; #[repr(C)] pub struct mpc_state_t { pub pos: i64, pub row: i64, pub col: i64, } #[repr(C)] pub struct mpc_ast_t { pub tag: *mut c_char, pub contents: *mut c_char, pub state: mpc_state_t, pub children_num: i32, pub children: *const *const mpc_ast_t, } #[repr(C)] pub struct
; //TODO map structs to C #[repr(C)] pub struct module { pub name: *mut c_char, pub imports: *mut vector, pub functions: *mut vector, pub types: *mut vector, } #[repr(C)] pub struct import { pub name: *mut c_char, pub alias: *mut c_char, pub local: bool, pub w_alias: bool, } #[repr(C)] pub struct function { pub name: *mut c_char, pub public : bool, pub param_count : i32, pub params: *mut vector, pub ret_type: symbol_type, } #[repr(C)] pub struct param { pub p_type: symbol_type, pub name: *mut c_char, } #[repr(C)] pub struct symbol_type { pub name: *mut c_char, pub indirection: i32, pub constant: bool, pub volatile: bool, } #[repr(C)] pub struct user_type { pub name: *mut c_char, pub t_type: type_kind, pub public: bool, } #[repr(C)] pub enum type_kind { ALIAS, STRUCT, UNION, ENUM, FUNC, TEMP } impl mpc_ast_t { pub unsafe fn get_children(&self) -> &'static[*const mpc_ast_t] { slice::from_raw_parts(self.children, self.children_num as usize) } }
vector
identifier_name
types.rs
#![allow(unused_variables)] #![allow(non_upper_case_globals)] #![allow(dead_code)] #![allow(improper_ctypes)] use std::slice; use std::os::raw::c_char; #[repr(C)] pub struct mpc_state_t {
#[repr(C)] pub struct mpc_ast_t { pub tag: *mut c_char, pub contents: *mut c_char, pub state: mpc_state_t, pub children_num: i32, pub children: *const *const mpc_ast_t, } #[repr(C)] pub struct vector; //TODO map structs to C #[repr(C)] pub struct module { pub name: *mut c_char, pub imports: *mut vector, pub functions: *mut vector, pub types: *mut vector, } #[repr(C)] pub struct import { pub name: *mut c_char, pub alias: *mut c_char, pub local: bool, pub w_alias: bool, } #[repr(C)] pub struct function { pub name: *mut c_char, pub public : bool, pub param_count : i32, pub params: *mut vector, pub ret_type: symbol_type, } #[repr(C)] pub struct param { pub p_type: symbol_type, pub name: *mut c_char, } #[repr(C)] pub struct symbol_type { pub name: *mut c_char, pub indirection: i32, pub constant: bool, pub volatile: bool, } #[repr(C)] pub struct user_type { pub name: *mut c_char, pub t_type: type_kind, pub public: bool, } #[repr(C)] pub enum type_kind { ALIAS, STRUCT, UNION, ENUM, FUNC, TEMP } impl mpc_ast_t { pub unsafe fn get_children(&self) -> &'static[*const mpc_ast_t] { slice::from_raw_parts(self.children, self.children_num as usize) } }
pub pos: i64, pub row: i64, pub col: i64, }
random_line_split
main.rs
extern crate byteorder; extern crate num; #[macro_use] extern crate enum_primitive; mod n64; mod cpu; mod pif; mod rsp; mod audio_interface; mod video_interface; mod peripheral_interface; mod serial_interface; mod interconnect; mod mem_map; use std::env; use std::fs; use std::io::Read; use std::path::Path; fn
() { let pif_file_name = env::args().nth(1).unwrap(); let rom_file_name = env::args().nth(2).unwrap(); let pif = read_bin(pif_file_name); let rom = read_bin(rom_file_name); let mut n64 = n64::N64::new(pif, rom); loop { //println!("N64: {:#?}", &n64); n64.run_instruction(); } } fn read_bin<P: AsRef<Path>>(path: P) -> Box<[u8]> { let mut file = fs::File::open(path).unwrap(); let mut file_buf = Vec::new(); file.read_to_end(&mut file_buf).unwrap(); file_buf.into_boxed_slice() }
main
identifier_name
main.rs
#[macro_use] extern crate enum_primitive; mod n64; mod cpu; mod pif; mod rsp; mod audio_interface; mod video_interface; mod peripheral_interface; mod serial_interface; mod interconnect; mod mem_map; use std::env; use std::fs; use std::io::Read; use std::path::Path; fn main() { let pif_file_name = env::args().nth(1).unwrap(); let rom_file_name = env::args().nth(2).unwrap(); let pif = read_bin(pif_file_name); let rom = read_bin(rom_file_name); let mut n64 = n64::N64::new(pif, rom); loop { //println!("N64: {:#?}", &n64); n64.run_instruction(); } } fn read_bin<P: AsRef<Path>>(path: P) -> Box<[u8]> { let mut file = fs::File::open(path).unwrap(); let mut file_buf = Vec::new(); file.read_to_end(&mut file_buf).unwrap(); file_buf.into_boxed_slice() }
extern crate byteorder; extern crate num;
random_line_split
main.rs
extern crate byteorder; extern crate num; #[macro_use] extern crate enum_primitive; mod n64; mod cpu; mod pif; mod rsp; mod audio_interface; mod video_interface; mod peripheral_interface; mod serial_interface; mod interconnect; mod mem_map; use std::env; use std::fs; use std::io::Read; use std::path::Path; fn main()
fn read_bin<P: AsRef<Path>>(path: P) -> Box<[u8]> { let mut file = fs::File::open(path).unwrap(); let mut file_buf = Vec::new(); file.read_to_end(&mut file_buf).unwrap(); file_buf.into_boxed_slice() }
{ let pif_file_name = env::args().nth(1).unwrap(); let rom_file_name = env::args().nth(2).unwrap(); let pif = read_bin(pif_file_name); let rom = read_bin(rom_file_name); let mut n64 = n64::N64::new(pif, rom); loop { //println!("N64: {:#?}", &n64); n64.run_instruction(); } }
identifier_body
day_2.rs
pub use tdd_kata::sorting_kata::day_2::{Sort, BubbleSort, InsertSort, InPlaceMergeSort}; pub use rand::distributions::range::Range; pub use rand::distributions::Sample; pub use rand; pub use expectest::prelude::be_equal_to;
before_each { let mut between = Range::new(0, 1000); let mut rng = rand::thread_rng(); let mut data = Vec::with_capacity(10); let mut ret = Vec::with_capacity(10); for _ in 0..10 { let datum = between.sample(&mut rng); data.push(datum); ret.push(datum); } ret.sort(); } it "should be sorted out by bubble sort" { BubbleSort::sort(&mut data); expect!(data).to(be_equal_to(ret)); } it "should be sorted out by insert sort" { InsertSort::sort(&mut data); expect!(data).to(be_equal_to(ret)); } it "should be sorted out by inplace merge sort" { InPlaceMergeSort::sort(&mut data); expect!(data).to(be_equal_to(ret)); } }
describe! array {
random_line_split
main.rs
extern crate failure; extern crate rand; use failure::{err_msg, Error}; use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!("Please input you guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; let guess = Guess::new(guess); let guess = match guess { Ok(value) => value.value, Err(_) => { print!("Guess value must be between 1 and 100"); continue; } }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } pub struct
{ value: u32, } impl Guess { pub fn new(value: u32) -> Result<Guess, Error> { if value > 100 || value < 1 { // 由作者抛出的应用异常 return Err(err_msg("Guess value must be between 1 and 100")); }; let guess = Guess { value }; Ok(guess) } pub fn value(&self) -> u32 { self.value } }
Guess
identifier_name
main.rs
extern crate failure; extern crate rand; use failure::{err_msg, Error}; use rand::Rng; use std::cmp::Ordering; use std::io; fn main()
Ok(value) => value.value, Err(_) => { print!("Guess value must be between 1 and 100"); continue; } }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } pub struct Guess { value: u32, } impl Guess { pub fn new(value: u32) -> Result<Guess, Error> { if value > 100 || value < 1 { // 由作者抛出的应用异常 return Err(err_msg("Guess value must be between 1 and 100")); }; let guess = Guess { value }; Ok(guess) } pub fn value(&self) -> u32 { self.value } }
{ println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!("Please input you guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; let guess = Guess::new(guess); let guess = match guess {
identifier_body
main.rs
extern crate failure; extern crate rand; use failure::{err_msg, Error}; use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!("Please input you guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; let guess = Guess::new(guess); let guess = match guess {
continue; } }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } pub struct Guess { value: u32, } impl Guess { pub fn new(value: u32) -> Result<Guess, Error> { if value > 100 || value < 1 { // 由作者抛出的应用异常 return Err(err_msg("Guess value must be between 1 and 100")); }; let guess = Guess { value }; Ok(guess) } pub fn value(&self) -> u32 { self.value } }
Ok(value) => value.value, Err(_) => { print!("Guess value must be between 1 and 100");
random_line_split
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use rule_graph; use smallvec::{smallvec, SmallVec}; pub type FNV = hash::BuildHasherDefault<FnvHasher>; /// /// Params represent a TypeId->Key map. /// /// For efficiency and hashability, they're stored as sorted Keys (with distinct TypeIds), and /// wrapped in an `Arc` that allows us to copy-on-write for param contents. /// #[repr(C)] #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Params(SmallVec<[Key; 4]>); impl Params { pub fn new<I: IntoIterator<Item = Key>>(param_inputs: I) -> Result<Params, String> { let mut params = param_inputs.into_iter().collect::<SmallVec<[Key; 4]>>(); params.sort_by_key(|k| *k.type_id()); if params.len() > 1 { let mut prev = &params[0]; for param in &params[1..] { if param.type_id() == prev.type_id() { return Err(format!( "Values used as `Params` must have distinct types, but the following values had the same type (`{}`):\n {}\n {}", externs::type_to_str(*prev.type_id()), externs::key_to_str(prev), externs::key_to_str(param) )); } prev = param; } } Ok(Params(params)) } pub fn new_single(param: Key) -> Params { Params(smallvec![param]) } /// /// Adds the given param Key to these Params, replacing an existing param with the same type if /// it exists. /// pub fn put(&mut self, param: Key) { match self.binary_search(param.type_id) { Ok(idx) => self.0[idx] = param, Err(idx) => self.0.insert(idx, param), } } /// /// Filters this Params object in-place to contain only params matching the given predicate. /// pub fn retain<F: FnMut(&mut Key) -> bool>(&mut self, f: F) { self.0.retain(f) } /// /// Returns the Key for the given TypeId if it is represented in this set of Params. /// pub fn find(&self, type_id: TypeId) -> Option<&Key> { self.binary_search(type_id).ok().map(|idx| &self.0[idx]) } fn binary_search(&self, type_id: TypeId) -> Result<usize, usize> { self .0 .binary_search_by(|probe| probe.type_id().cmp(&type_id)) } pub fn type_ids<'a>(&'a self) -> impl Iterator<Item = TypeId> + 'a { self.0.iter().map(|k| *k.type_id()) } /// /// Given a set of either param type or param value strings: sort, join, and render as one string. /// pub fn display<T>(params: T) -> String where T: Iterator, T::Item: fmt::Display, { let mut params: Vec<_> = params.map(|p| format!("{}", p)).collect(); match params.len() { 0 => "()".to_string(), 1 => params.pop().unwrap(), _ => { params.sort(); format!("({})", params.join(", ")) } } } } impl fmt::Display for Params { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", Self::display(self.0.iter())) } } pub type Id = u64; // The type of a python object (which itself has a type, but which is not represented // by a Key, because that would result in a infinitely recursive structure.) #[repr(C)] #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct TypeId(pub Id); impl TypeId { fn pretty_print(self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self == ANY_TYPE { write!(f, "Any") } else { write!(f, "{}", externs::type_to_str(self)) } } } impl rule_graph::TypeId for TypeId { /// /// Render a string for a collection of TypeIds. /// fn display<I>(type_ids: I) -> String where I: Iterator<Item = TypeId>, { Params::display(type_ids) } } impl fmt::Debug for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.pretty_print(f) } } impl fmt::Display for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.pretty_print(f) } } // On the python side, the 0th type id is used as an anonymous id pub const ANY_TYPE: TypeId = TypeId(0); // An identifier for a python function. #[repr(C)] #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Function(pub Key); impl Function { pub fn name(&self) -> String { let Function(key) = self; let module = externs::project_str(&externs::val_for(&key), "__module__"); let name = externs::project_str(&externs::val_for(&key), "__name__"); // NB: this is a custom dunder method that Python code should populate before sending the // function (e.g. an `@rule`) through FFI. let line_number = externs::project_str(&externs::val_for(&key), "__line_number__"); format!("{}:{}:{}", module, line_number, name) } } impl fmt::Display for Function { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}()", self.name()) } } impl fmt::Debug for Function { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}()", self.name()) } } /// /// Wraps a type id for use as a key in HashMaps and sets. /// #[repr(C)] #[derive(Clone, Copy)] pub struct Key { id: Id, type_id: TypeId, } impl fmt::Debug for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::key_to_str(self)) } } impl Eq for Key {} impl PartialEq for Key { fn eq(&self, other: &Key) -> bool { self.id == other.id } } impl hash::Hash for Key { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.id.hash(state); } } impl fmt::Display for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::key_to_str(self)) } } impl Key { pub fn
(id: Id, type_id: TypeId) -> Key { Key { id, type_id } } pub fn id(&self) -> Id { self.id } pub fn type_id(&self) -> &TypeId { &self.type_id } } /// /// A wrapper around a Arc<Handle> /// #[derive(Clone, Eq, PartialEq)] pub struct Value(Arc<Handle>); impl Value { pub fn new(handle: Handle) -> Value { Value(Arc::new(handle)) } } impl Deref for Value { type Target = Handle; fn deref(&self) -> &Handle { &self.0 } } impl fmt::Debug for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::val_to_str(&self)) } } /// /// Creates a Handle (which represents exclusive access) from a Value (which might be shared), /// cloning if necessary. /// impl From<Value> for Handle { fn from(value: Value) -> Self { match Arc::try_unwrap(value.0) { Ok(handle) => handle, Err(arc_handle) => externs::clone_val(&arc_handle), } } } impl From<Handle> for Value { fn from(handle: Handle) -> Self { Value::new(handle) } } #[derive(Clone, Debug, Eq, PartialEq)] pub enum Failure { /// A Node failed because a filesystem change invalidated it or its inputs. /// A root requestor should usually immediately retry their request. Invalidated, /// A rule raised an exception. Throw(Value, String), } impl fmt::Display for Failure { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Failure::Invalidated => write!(f, "Exhausted retries due to changed files."), Failure::Throw(exc, _) => write!(f, "{}", externs::val_to_str(exc)), } } } pub fn throw(msg: &str) -> Failure { Failure::Throw( externs::create_exception(msg), format!( "Traceback (no traceback):\n <pants native internals>\nException: {}", msg ), ) }
new
identifier_name
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use rule_graph; use smallvec::{smallvec, SmallVec}; pub type FNV = hash::BuildHasherDefault<FnvHasher>; /// /// Params represent a TypeId->Key map. /// /// For efficiency and hashability, they're stored as sorted Keys (with distinct TypeIds), and /// wrapped in an `Arc` that allows us to copy-on-write for param contents. /// #[repr(C)] #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Params(SmallVec<[Key; 4]>); impl Params { pub fn new<I: IntoIterator<Item = Key>>(param_inputs: I) -> Result<Params, String> { let mut params = param_inputs.into_iter().collect::<SmallVec<[Key; 4]>>(); params.sort_by_key(|k| *k.type_id()); if params.len() > 1 { let mut prev = &params[0]; for param in &params[1..] { if param.type_id() == prev.type_id() { return Err(format!( "Values used as `Params` must have distinct types, but the following values had the same type (`{}`):\n {}\n {}", externs::type_to_str(*prev.type_id()), externs::key_to_str(prev), externs::key_to_str(param) )); } prev = param; } } Ok(Params(params)) } pub fn new_single(param: Key) -> Params { Params(smallvec![param]) } /// /// Adds the given param Key to these Params, replacing an existing param with the same type if /// it exists. /// pub fn put(&mut self, param: Key) { match self.binary_search(param.type_id) { Ok(idx) => self.0[idx] = param, Err(idx) => self.0.insert(idx, param), } } /// /// Filters this Params object in-place to contain only params matching the given predicate. /// pub fn retain<F: FnMut(&mut Key) -> bool>(&mut self, f: F) { self.0.retain(f) } /// /// Returns the Key for the given TypeId if it is represented in this set of Params. /// pub fn find(&self, type_id: TypeId) -> Option<&Key> { self.binary_search(type_id).ok().map(|idx| &self.0[idx]) } fn binary_search(&self, type_id: TypeId) -> Result<usize, usize> { self .0 .binary_search_by(|probe| probe.type_id().cmp(&type_id)) } pub fn type_ids<'a>(&'a self) -> impl Iterator<Item = TypeId> + 'a { self.0.iter().map(|k| *k.type_id()) } /// /// Given a set of either param type or param value strings: sort, join, and render as one string. /// pub fn display<T>(params: T) -> String where T: Iterator, T::Item: fmt::Display, { let mut params: Vec<_> = params.map(|p| format!("{}", p)).collect(); match params.len() { 0 => "()".to_string(), 1 => params.pop().unwrap(), _ => { params.sort(); format!("({})", params.join(", ")) } } } } impl fmt::Display for Params { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
} pub type Id = u64; // The type of a python object (which itself has a type, but which is not represented // by a Key, because that would result in a infinitely recursive structure.) #[repr(C)] #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct TypeId(pub Id); impl TypeId { fn pretty_print(self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self == ANY_TYPE { write!(f, "Any") } else { write!(f, "{}", externs::type_to_str(self)) } } } impl rule_graph::TypeId for TypeId { /// /// Render a string for a collection of TypeIds. /// fn display<I>(type_ids: I) -> String where I: Iterator<Item = TypeId>, { Params::display(type_ids) } } impl fmt::Debug for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.pretty_print(f) } } impl fmt::Display for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.pretty_print(f) } } // On the python side, the 0th type id is used as an anonymous id pub const ANY_TYPE: TypeId = TypeId(0); // An identifier for a python function. #[repr(C)] #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Function(pub Key); impl Function { pub fn name(&self) -> String { let Function(key) = self; let module = externs::project_str(&externs::val_for(&key), "__module__"); let name = externs::project_str(&externs::val_for(&key), "__name__"); // NB: this is a custom dunder method that Python code should populate before sending the // function (e.g. an `@rule`) through FFI. let line_number = externs::project_str(&externs::val_for(&key), "__line_number__"); format!("{}:{}:{}", module, line_number, name) } } impl fmt::Display for Function { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}()", self.name()) } } impl fmt::Debug for Function { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}()", self.name()) } } /// /// Wraps a type id for use as a key in HashMaps and sets. /// #[repr(C)] #[derive(Clone, Copy)] pub struct Key { id: Id, type_id: TypeId, } impl fmt::Debug for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::key_to_str(self)) } } impl Eq for Key {} impl PartialEq for Key { fn eq(&self, other: &Key) -> bool { self.id == other.id } } impl hash::Hash for Key { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.id.hash(state); } } impl fmt::Display for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::key_to_str(self)) } } impl Key { pub fn new(id: Id, type_id: TypeId) -> Key { Key { id, type_id } } pub fn id(&self) -> Id { self.id } pub fn type_id(&self) -> &TypeId { &self.type_id } } /// /// A wrapper around a Arc<Handle> /// #[derive(Clone, Eq, PartialEq)] pub struct Value(Arc<Handle>); impl Value { pub fn new(handle: Handle) -> Value { Value(Arc::new(handle)) } } impl Deref for Value { type Target = Handle; fn deref(&self) -> &Handle { &self.0 } } impl fmt::Debug for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::val_to_str(&self)) } } /// /// Creates a Handle (which represents exclusive access) from a Value (which might be shared), /// cloning if necessary. /// impl From<Value> for Handle { fn from(value: Value) -> Self { match Arc::try_unwrap(value.0) { Ok(handle) => handle, Err(arc_handle) => externs::clone_val(&arc_handle), } } } impl From<Handle> for Value { fn from(handle: Handle) -> Self { Value::new(handle) } } #[derive(Clone, Debug, Eq, PartialEq)] pub enum Failure { /// A Node failed because a filesystem change invalidated it or its inputs. /// A root requestor should usually immediately retry their request. Invalidated, /// A rule raised an exception. Throw(Value, String), } impl fmt::Display for Failure { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Failure::Invalidated => write!(f, "Exhausted retries due to changed files."), Failure::Throw(exc, _) => write!(f, "{}", externs::val_to_str(exc)), } } } pub fn throw(msg: &str) -> Failure { Failure::Throw( externs::create_exception(msg), format!( "Traceback (no traceback):\n <pants native internals>\nException: {}", msg ), ) }
{ write!(f, "{}", Self::display(self.0.iter())) }
identifier_body
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use rule_graph; use smallvec::{smallvec, SmallVec}; pub type FNV = hash::BuildHasherDefault<FnvHasher>; /// /// Params represent a TypeId->Key map. /// /// For efficiency and hashability, they're stored as sorted Keys (with distinct TypeIds), and /// wrapped in an `Arc` that allows us to copy-on-write for param contents. /// #[repr(C)] #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Params(SmallVec<[Key; 4]>); impl Params { pub fn new<I: IntoIterator<Item = Key>>(param_inputs: I) -> Result<Params, String> { let mut params = param_inputs.into_iter().collect::<SmallVec<[Key; 4]>>(); params.sort_by_key(|k| *k.type_id()); if params.len() > 1 { let mut prev = &params[0]; for param in &params[1..] { if param.type_id() == prev.type_id() { return Err(format!( "Values used as `Params` must have distinct types, but the following values had the same type (`{}`):\n {}\n {}", externs::type_to_str(*prev.type_id()), externs::key_to_str(prev), externs::key_to_str(param) )); } prev = param; } } Ok(Params(params)) } pub fn new_single(param: Key) -> Params { Params(smallvec![param]) } /// /// Adds the given param Key to these Params, replacing an existing param with the same type if /// it exists. /// pub fn put(&mut self, param: Key) { match self.binary_search(param.type_id) { Ok(idx) => self.0[idx] = param, Err(idx) => self.0.insert(idx, param), } } /// /// Filters this Params object in-place to contain only params matching the given predicate. /// pub fn retain<F: FnMut(&mut Key) -> bool>(&mut self, f: F) { self.0.retain(f) } /// /// Returns the Key for the given TypeId if it is represented in this set of Params. /// pub fn find(&self, type_id: TypeId) -> Option<&Key> { self.binary_search(type_id).ok().map(|idx| &self.0[idx]) } fn binary_search(&self, type_id: TypeId) -> Result<usize, usize> { self .0 .binary_search_by(|probe| probe.type_id().cmp(&type_id)) } pub fn type_ids<'a>(&'a self) -> impl Iterator<Item = TypeId> + 'a { self.0.iter().map(|k| *k.type_id()) } /// /// Given a set of either param type or param value strings: sort, join, and render as one string. /// pub fn display<T>(params: T) -> String where T: Iterator, T::Item: fmt::Display, { let mut params: Vec<_> = params.map(|p| format!("{}", p)).collect(); match params.len() { 0 => "()".to_string(), 1 => params.pop().unwrap(), _ => { params.sort(); format!("({})", params.join(", ")) } } } } impl fmt::Display for Params { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", Self::display(self.0.iter())) } } pub type Id = u64; // The type of a python object (which itself has a type, but which is not represented // by a Key, because that would result in a infinitely recursive structure.) #[repr(C)] #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct TypeId(pub Id); impl TypeId { fn pretty_print(self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self == ANY_TYPE { write!(f, "Any") } else { write!(f, "{}", externs::type_to_str(self)) } } } impl rule_graph::TypeId for TypeId { /// /// Render a string for a collection of TypeIds. /// fn display<I>(type_ids: I) -> String where I: Iterator<Item = TypeId>, { Params::display(type_ids) } } impl fmt::Debug for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.pretty_print(f) } } impl fmt::Display for TypeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.pretty_print(f) } } // On the python side, the 0th type id is used as an anonymous id pub const ANY_TYPE: TypeId = TypeId(0); // An identifier for a python function. #[repr(C)] #[derive(Clone, Copy, Eq, Hash, PartialEq)] pub struct Function(pub Key); impl Function { pub fn name(&self) -> String { let Function(key) = self; let module = externs::project_str(&externs::val_for(&key), "__module__"); let name = externs::project_str(&externs::val_for(&key), "__name__"); // NB: this is a custom dunder method that Python code should populate before sending the // function (e.g. an `@rule`) through FFI. let line_number = externs::project_str(&externs::val_for(&key), "__line_number__"); format!("{}:{}:{}", module, line_number, name) } } impl fmt::Display for Function { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}()", self.name()) } } impl fmt::Debug for Function { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}()", self.name()) } } /// /// Wraps a type id for use as a key in HashMaps and sets. /// #[repr(C)] #[derive(Clone, Copy)] pub struct Key { id: Id, type_id: TypeId, } impl fmt::Debug for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::key_to_str(self)) } } impl Eq for Key {} impl PartialEq for Key { fn eq(&self, other: &Key) -> bool { self.id == other.id } }
fn hash<H: hash::Hasher>(&self, state: &mut H) { self.id.hash(state); } } impl fmt::Display for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::key_to_str(self)) } } impl Key { pub fn new(id: Id, type_id: TypeId) -> Key { Key { id, type_id } } pub fn id(&self) -> Id { self.id } pub fn type_id(&self) -> &TypeId { &self.type_id } } /// /// A wrapper around a Arc<Handle> /// #[derive(Clone, Eq, PartialEq)] pub struct Value(Arc<Handle>); impl Value { pub fn new(handle: Handle) -> Value { Value(Arc::new(handle)) } } impl Deref for Value { type Target = Handle; fn deref(&self) -> &Handle { &self.0 } } impl fmt::Debug for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::val_to_str(&self)) } } /// /// Creates a Handle (which represents exclusive access) from a Value (which might be shared), /// cloning if necessary. /// impl From<Value> for Handle { fn from(value: Value) -> Self { match Arc::try_unwrap(value.0) { Ok(handle) => handle, Err(arc_handle) => externs::clone_val(&arc_handle), } } } impl From<Handle> for Value { fn from(handle: Handle) -> Self { Value::new(handle) } } #[derive(Clone, Debug, Eq, PartialEq)] pub enum Failure { /// A Node failed because a filesystem change invalidated it or its inputs. /// A root requestor should usually immediately retry their request. Invalidated, /// A rule raised an exception. Throw(Value, String), } impl fmt::Display for Failure { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Failure::Invalidated => write!(f, "Exhausted retries due to changed files."), Failure::Throw(exc, _) => write!(f, "{}", externs::val_to_str(exc)), } } } pub fn throw(msg: &str) -> Failure { Failure::Throw( externs::create_exception(msg), format!( "Traceback (no traceback):\n <pants native internals>\nException: {}", msg ), ) }
impl hash::Hash for Key {
random_line_split
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAssigner, ValueConversion}; use crate::ir::{self, AbiParam, ArgumentExtension, ArgumentLoc, ArgumentPurpose, Type}; use crate::isa::RegClass; use crate::regalloc::RegisterSet; use core::i32; use target_lexicon::Triple; struct Args { pointer_bits: u8, pointer_bytes: u8, pointer_type: Type, regs: u32, reg_limit: u32, offset: u32, } impl Args { fn new(bits: u8, enable_e: bool) -> Self { Self { pointer_bits: bits, pointer_bytes: bits / 8, pointer_type: Type::int(u16::from(bits)).unwrap(), regs: 0, reg_limit: if enable_e { 6 } else { 8 }, offset: 0, } } } impl ArgAssigner for Args { fn assign(&mut self, arg: &AbiParam) -> ArgAction { fn align(value: u32, to: u32) -> u32 { (value + to - 1) &!(to - 1) } let ty = arg.value_type; // Check for a legal type. // RISC-V doesn't have SIMD at all, so break all vectors down. if ty.is_vector() { return ValueConversion::VectorSplit.into(); } // Large integers and booleans are broken down to fit in a register. if!ty.is_float() && ty.bits() > u16::from(self.pointer_bits) { // Align registers and stack to a multiple of two pointers. self.regs = align(self.regs, 2); self.offset = align(self.offset, 2 * u32::from(self.pointer_bytes)); return ValueConversion::IntSplit.into(); } // Small integers are extended to the size of a pointer register. if ty.is_int() && ty.bits() < u16::from(self.pointer_bits) { match arg.extension { ArgumentExtension::None => {} ArgumentExtension::Uext => return ValueConversion::Uext(self.pointer_type).into(), ArgumentExtension::Sext => return ValueConversion::Sext(self.pointer_type).into(), } } if self.regs < self.reg_limit { // Assign to a register. let reg = if ty.is_float() { FPR.unit(10 + self.regs as usize) } else { GPR.unit(10 + self.regs as usize) }; self.regs += 1; ArgumentLoc::Reg(reg).into() } else { // Assign a stack location. let loc = ArgumentLoc::Stack(self.offset as i32); self.offset += u32::from(self.pointer_bytes); debug_assert!(self.offset <= i32::MAX as u32); loc.into() } } } /// Legalize `sig` for RISC-V. pub fn legalize_signature( sig: &mut ir::Signature, triple: &Triple, isa_flags: &settings::Flags, current: bool, ) { let bits = triple.pointer_width().unwrap().bits(); let mut args = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.params, &mut args); let mut rets = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.returns, &mut rets); if current { let ptr = Type::int(u16::from(bits)).unwrap(); // Add the link register as an argument and return value. // // The `jalr` instruction implementing a return can technically accept the return address // in any register, but a micro-architecture with a return address predictor will only // recognize it as a return if the address is in `x1`. let link = AbiParam::special_reg(ptr, ArgumentPurpose::Link, GPR.unit(1)); sig.params.push(link); sig.returns.push(link); } } /// Get register class for a type appearing in a legalized signature. pub fn regclass_for_abi_type(ty: Type) -> RegClass { if ty.is_float() { FPR } else { GPR } } pub fn
(_func: &ir::Function, isa_flags: &settings::Flags) -> RegisterSet { let mut regs = RegisterSet::new(); regs.take(GPR, GPR.unit(0)); // Hard-wired 0. // %x1 is the link register which is available for allocation. regs.take(GPR, GPR.unit(2)); // Stack pointer. regs.take(GPR, GPR.unit(3)); // Global pointer. regs.take(GPR, GPR.unit(4)); // Thread pointer. // TODO: %x8 is the frame pointer. Reserve it? // Remove %x16 and up for RV32E. if isa_flags.enable_e() { for u in 16..32 { regs.take(GPR, GPR.unit(u)); } } regs }
allocatable_registers
identifier_name
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAssigner, ValueConversion}; use crate::ir::{self, AbiParam, ArgumentExtension, ArgumentLoc, ArgumentPurpose, Type}; use crate::isa::RegClass; use crate::regalloc::RegisterSet; use core::i32; use target_lexicon::Triple; struct Args { pointer_bits: u8, pointer_bytes: u8, pointer_type: Type, regs: u32, reg_limit: u32, offset: u32, } impl Args { fn new(bits: u8, enable_e: bool) -> Self { Self { pointer_bits: bits, pointer_bytes: bits / 8, pointer_type: Type::int(u16::from(bits)).unwrap(), regs: 0, reg_limit: if enable_e { 6 } else { 8 }, offset: 0, } } } impl ArgAssigner for Args { fn assign(&mut self, arg: &AbiParam) -> ArgAction { fn align(value: u32, to: u32) -> u32 { (value + to - 1) &!(to - 1) } let ty = arg.value_type; // Check for a legal type. // RISC-V doesn't have SIMD at all, so break all vectors down. if ty.is_vector() { return ValueConversion::VectorSplit.into(); } // Large integers and booleans are broken down to fit in a register. if!ty.is_float() && ty.bits() > u16::from(self.pointer_bits) { // Align registers and stack to a multiple of two pointers. self.regs = align(self.regs, 2); self.offset = align(self.offset, 2 * u32::from(self.pointer_bytes)); return ValueConversion::IntSplit.into(); } // Small integers are extended to the size of a pointer register. if ty.is_int() && ty.bits() < u16::from(self.pointer_bits) { match arg.extension { ArgumentExtension::None => {} ArgumentExtension::Uext => return ValueConversion::Uext(self.pointer_type).into(), ArgumentExtension::Sext => return ValueConversion::Sext(self.pointer_type).into(), } } if self.regs < self.reg_limit
else { // Assign a stack location. let loc = ArgumentLoc::Stack(self.offset as i32); self.offset += u32::from(self.pointer_bytes); debug_assert!(self.offset <= i32::MAX as u32); loc.into() } } } /// Legalize `sig` for RISC-V. pub fn legalize_signature( sig: &mut ir::Signature, triple: &Triple, isa_flags: &settings::Flags, current: bool, ) { let bits = triple.pointer_width().unwrap().bits(); let mut args = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.params, &mut args); let mut rets = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.returns, &mut rets); if current { let ptr = Type::int(u16::from(bits)).unwrap(); // Add the link register as an argument and return value. // // The `jalr` instruction implementing a return can technically accept the return address // in any register, but a micro-architecture with a return address predictor will only // recognize it as a return if the address is in `x1`. let link = AbiParam::special_reg(ptr, ArgumentPurpose::Link, GPR.unit(1)); sig.params.push(link); sig.returns.push(link); } } /// Get register class for a type appearing in a legalized signature. pub fn regclass_for_abi_type(ty: Type) -> RegClass { if ty.is_float() { FPR } else { GPR } } pub fn allocatable_registers(_func: &ir::Function, isa_flags: &settings::Flags) -> RegisterSet { let mut regs = RegisterSet::new(); regs.take(GPR, GPR.unit(0)); // Hard-wired 0. // %x1 is the link register which is available for allocation. regs.take(GPR, GPR.unit(2)); // Stack pointer. regs.take(GPR, GPR.unit(3)); // Global pointer. regs.take(GPR, GPR.unit(4)); // Thread pointer. // TODO: %x8 is the frame pointer. Reserve it? // Remove %x16 and up for RV32E. if isa_flags.enable_e() { for u in 16..32 { regs.take(GPR, GPR.unit(u)); } } regs }
{ // Assign to a register. let reg = if ty.is_float() { FPR.unit(10 + self.regs as usize) } else { GPR.unit(10 + self.regs as usize) }; self.regs += 1; ArgumentLoc::Reg(reg).into() }
conditional_block
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAssigner, ValueConversion}; use crate::ir::{self, AbiParam, ArgumentExtension, ArgumentLoc, ArgumentPurpose, Type}; use crate::isa::RegClass; use crate::regalloc::RegisterSet; use core::i32; use target_lexicon::Triple; struct Args { pointer_bits: u8, pointer_bytes: u8, pointer_type: Type, regs: u32, reg_limit: u32, offset: u32, } impl Args { fn new(bits: u8, enable_e: bool) -> Self { Self { pointer_bits: bits, pointer_bytes: bits / 8, pointer_type: Type::int(u16::from(bits)).unwrap(), regs: 0, reg_limit: if enable_e { 6 } else { 8 }, offset: 0, } } } impl ArgAssigner for Args { fn assign(&mut self, arg: &AbiParam) -> ArgAction { fn align(value: u32, to: u32) -> u32 { (value + to - 1) &!(to - 1) } let ty = arg.value_type; // Check for a legal type. // RISC-V doesn't have SIMD at all, so break all vectors down. if ty.is_vector() { return ValueConversion::VectorSplit.into(); } // Large integers and booleans are broken down to fit in a register. if!ty.is_float() && ty.bits() > u16::from(self.pointer_bits) { // Align registers and stack to a multiple of two pointers. self.regs = align(self.regs, 2); self.offset = align(self.offset, 2 * u32::from(self.pointer_bytes)); return ValueConversion::IntSplit.into(); } // Small integers are extended to the size of a pointer register. if ty.is_int() && ty.bits() < u16::from(self.pointer_bits) { match arg.extension { ArgumentExtension::None => {} ArgumentExtension::Uext => return ValueConversion::Uext(self.pointer_type).into(), ArgumentExtension::Sext => return ValueConversion::Sext(self.pointer_type).into(), } } if self.regs < self.reg_limit { // Assign to a register. let reg = if ty.is_float() { FPR.unit(10 + self.regs as usize) } else { GPR.unit(10 + self.regs as usize) }; self.regs += 1; ArgumentLoc::Reg(reg).into() } else { // Assign a stack location. let loc = ArgumentLoc::Stack(self.offset as i32); self.offset += u32::from(self.pointer_bytes); debug_assert!(self.offset <= i32::MAX as u32); loc.into() } } } /// Legalize `sig` for RISC-V. pub fn legalize_signature( sig: &mut ir::Signature, triple: &Triple, isa_flags: &settings::Flags, current: bool, )
} } /// Get register class for a type appearing in a legalized signature. pub fn regclass_for_abi_type(ty: Type) -> RegClass { if ty.is_float() { FPR } else { GPR } } pub fn allocatable_registers(_func: &ir::Function, isa_flags: &settings::Flags) -> RegisterSet { let mut regs = RegisterSet::new(); regs.take(GPR, GPR.unit(0)); // Hard-wired 0. // %x1 is the link register which is available for allocation. regs.take(GPR, GPR.unit(2)); // Stack pointer. regs.take(GPR, GPR.unit(3)); // Global pointer. regs.take(GPR, GPR.unit(4)); // Thread pointer. // TODO: %x8 is the frame pointer. Reserve it? // Remove %x16 and up for RV32E. if isa_flags.enable_e() { for u in 16..32 { regs.take(GPR, GPR.unit(u)); } } regs }
{ let bits = triple.pointer_width().unwrap().bits(); let mut args = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.params, &mut args); let mut rets = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.returns, &mut rets); if current { let ptr = Type::int(u16::from(bits)).unwrap(); // Add the link register as an argument and return value. // // The `jalr` instruction implementing a return can technically accept the return address // in any register, but a micro-architecture with a return address predictor will only // recognize it as a return if the address is in `x1`. let link = AbiParam::special_reg(ptr, ArgumentPurpose::Link, GPR.unit(1)); sig.params.push(link); sig.returns.push(link);
identifier_body
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAssigner, ValueConversion}; use crate::ir::{self, AbiParam, ArgumentExtension, ArgumentLoc, ArgumentPurpose, Type}; use crate::isa::RegClass; use crate::regalloc::RegisterSet; use core::i32; use target_lexicon::Triple; struct Args { pointer_bits: u8, pointer_bytes: u8, pointer_type: Type, regs: u32, reg_limit: u32, offset: u32, } impl Args { fn new(bits: u8, enable_e: bool) -> Self { Self { pointer_bits: bits, pointer_bytes: bits / 8, pointer_type: Type::int(u16::from(bits)).unwrap(), regs: 0, reg_limit: if enable_e { 6 } else { 8 }, offset: 0, } } } impl ArgAssigner for Args { fn assign(&mut self, arg: &AbiParam) -> ArgAction { fn align(value: u32, to: u32) -> u32 { (value + to - 1) &!(to - 1) } let ty = arg.value_type; // Check for a legal type. // RISC-V doesn't have SIMD at all, so break all vectors down. if ty.is_vector() { return ValueConversion::VectorSplit.into(); } // Large integers and booleans are broken down to fit in a register. if!ty.is_float() && ty.bits() > u16::from(self.pointer_bits) { // Align registers and stack to a multiple of two pointers. self.regs = align(self.regs, 2); self.offset = align(self.offset, 2 * u32::from(self.pointer_bytes)); return ValueConversion::IntSplit.into(); } // Small integers are extended to the size of a pointer register. if ty.is_int() && ty.bits() < u16::from(self.pointer_bits) { match arg.extension { ArgumentExtension::None => {} ArgumentExtension::Uext => return ValueConversion::Uext(self.pointer_type).into(), ArgumentExtension::Sext => return ValueConversion::Sext(self.pointer_type).into(), } } if self.regs < self.reg_limit { // Assign to a register. let reg = if ty.is_float() { FPR.unit(10 + self.regs as usize) } else { GPR.unit(10 + self.regs as usize) }; self.regs += 1; ArgumentLoc::Reg(reg).into() } else { // Assign a stack location. let loc = ArgumentLoc::Stack(self.offset as i32); self.offset += u32::from(self.pointer_bytes); debug_assert!(self.offset <= i32::MAX as u32); loc.into() } } } /// Legalize `sig` for RISC-V. pub fn legalize_signature( sig: &mut ir::Signature, triple: &Triple, isa_flags: &settings::Flags, current: bool, ) { let bits = triple.pointer_width().unwrap().bits(); let mut args = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.params, &mut args); let mut rets = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.returns, &mut rets); if current { let ptr = Type::int(u16::from(bits)).unwrap(); // Add the link register as an argument and return value. // // The `jalr` instruction implementing a return can technically accept the return address // in any register, but a micro-architecture with a return address predictor will only // recognize it as a return if the address is in `x1`. let link = AbiParam::special_reg(ptr, ArgumentPurpose::Link, GPR.unit(1)); sig.params.push(link); sig.returns.push(link); } } /// Get register class for a type appearing in a legalized signature. pub fn regclass_for_abi_type(ty: Type) -> RegClass { if ty.is_float() { FPR } else { GPR } } pub fn allocatable_registers(_func: &ir::Function, isa_flags: &settings::Flags) -> RegisterSet { let mut regs = RegisterSet::new(); regs.take(GPR, GPR.unit(0)); // Hard-wired 0. // %x1 is the link register which is available for allocation. regs.take(GPR, GPR.unit(2)); // Stack pointer. regs.take(GPR, GPR.unit(3)); // Global pointer.
// TODO: %x8 is the frame pointer. Reserve it? // Remove %x16 and up for RV32E. if isa_flags.enable_e() { for u in 16..32 { regs.take(GPR, GPR.unit(u)); } } regs }
regs.take(GPR, GPR.unit(4)); // Thread pointer.
random_line_split
main.rs
#![crate_id = "spliced#0.1-pre"] #![license = "MIT"] #![crate_type = "bin"] extern crate green; extern crate rustuv; extern crate serialize; extern crate splice; use std::comm::{Disconnected, Empty}; use proto::{KeepAlive, OpenBuffer, OpenFile, RunCommand}; use proto::{Ack, Allow, Deny, Handle}; use proto::{RequestId, Request}; mod conn; mod proto; #[start] fn
(argc: int, argv: **u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } fn main() { let cfg = splice::conf::load_default().unwrap(); let mut server = conn::Server::new( cfg.default_server_addr.as_slice(), cfg.default_server_port, None).unwrap(); loop { let raw_client = server.accept(); spawn(proc() { match raw_client.ok() { Some(c) => { match c.negotiate().ok() { Some((down, mut up)) => { println!("Negotiated"); let (tx, rx) = channel::<(RequestId, Request)>(); spawn(proc() { let mut down = down; 'resp: loop { match rx.try_recv() { Ok((id, req)) => { match down.send_response(id, &match req { KeepAlive => Ack, _ => Deny, // Deny unimplemented requests }) { _ => (), // Ignore errors for now } }, Err(Disconnected) => break'resp, Err(Empty) => (), }; } }); 'req: loop { match up.get_request() { Ok(v) => match tx.send_opt(v) { Err(..) => break'req, _ => (), }, Err(e) => match e.kind { std::io::Closed => break'req, _ => (), }, }; } } None => println!("Negotiate failed"), } }, None => println!("No connection"), } }); } }
start
identifier_name
main.rs
#![crate_id = "spliced#0.1-pre"] #![license = "MIT"] #![crate_type = "bin"] extern crate green; extern crate rustuv; extern crate serialize; extern crate splice; use std::comm::{Disconnected, Empty}; use proto::{KeepAlive, OpenBuffer, OpenFile, RunCommand}; use proto::{Ack, Allow, Deny, Handle}; use proto::{RequestId, Request}; mod conn; mod proto; #[start] fn start(argc: int, argv: **u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } fn main() { let cfg = splice::conf::load_default().unwrap(); let mut server = conn::Server::new(
cfg.default_server_addr.as_slice(), cfg.default_server_port, None).unwrap(); loop { let raw_client = server.accept(); spawn(proc() { match raw_client.ok() { Some(c) => { match c.negotiate().ok() { Some((down, mut up)) => { println!("Negotiated"); let (tx, rx) = channel::<(RequestId, Request)>(); spawn(proc() { let mut down = down; 'resp: loop { match rx.try_recv() { Ok((id, req)) => { match down.send_response(id, &match req { KeepAlive => Ack, _ => Deny, // Deny unimplemented requests }) { _ => (), // Ignore errors for now } }, Err(Disconnected) => break'resp, Err(Empty) => (), }; } }); 'req: loop { match up.get_request() { Ok(v) => match tx.send_opt(v) { Err(..) => break'req, _ => (), }, Err(e) => match e.kind { std::io::Closed => break'req, _ => (), }, }; } } None => println!("Negotiate failed"), } }, None => println!("No connection"), } }); } }
random_line_split
main.rs
#![crate_id = "spliced#0.1-pre"] #![license = "MIT"] #![crate_type = "bin"] extern crate green; extern crate rustuv; extern crate serialize; extern crate splice; use std::comm::{Disconnected, Empty}; use proto::{KeepAlive, OpenBuffer, OpenFile, RunCommand}; use proto::{Ack, Allow, Deny, Handle}; use proto::{RequestId, Request}; mod conn; mod proto; #[start] fn start(argc: int, argv: **u8) -> int
fn main() { let cfg = splice::conf::load_default().unwrap(); let mut server = conn::Server::new( cfg.default_server_addr.as_slice(), cfg.default_server_port, None).unwrap(); loop { let raw_client = server.accept(); spawn(proc() { match raw_client.ok() { Some(c) => { match c.negotiate().ok() { Some((down, mut up)) => { println!("Negotiated"); let (tx, rx) = channel::<(RequestId, Request)>(); spawn(proc() { let mut down = down; 'resp: loop { match rx.try_recv() { Ok((id, req)) => { match down.send_response(id, &match req { KeepAlive => Ack, _ => Deny, // Deny unimplemented requests }) { _ => (), // Ignore errors for now } }, Err(Disconnected) => break'resp, Err(Empty) => (), }; } }); 'req: loop { match up.get_request() { Ok(v) => match tx.send_opt(v) { Err(..) => break'req, _ => (), }, Err(e) => match e.kind { std::io::Closed => break'req, _ => (), }, }; } } None => println!("Negotiate failed"), } }, None => println!("No connection"), } }); } }
{ green::start(argc, argv, rustuv::event_loop, main) }
identifier_body
power_set.rs
// Given a set, generate its power set, which is the set of all subsets of that // set: http://rosettacode.org/wiki/Power_set use std::vec::Vec; use std::slice::Items; // If set == {} // return {{}} // else if set == {a} U rest // return power_set(rest) U ({a} U each set in power_set(rest)) fn power_set<'a, T: Clone + 'a>(items: &mut Items<'a,T>) -> Vec<Vec<T>> { let mut power = Vec::new(); match items.next() { None => power.push(Vec::new()), Some(item) => { for set in power_set(items).iter() { power.push(set.clone()); power.push(set.clone().append_one(item.clone())); } } } power } #[test] fn test() { let set = Vec::<int>::new(); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!())); let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!(), vec!(1), vec!(2), vec!(2, 1), vec!(3), vec!(3, 1), vec!(3, 2), vec!(3, 2, 1))); } #[cfg(not(test))] fn
() { let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); set.push(4); let power = power_set(&mut set.iter()); println!("Set : {}", set); println!("Power Set: {}", power); }
main
identifier_name
power_set.rs
// Given a set, generate its power set, which is the set of all subsets of that // set: http://rosettacode.org/wiki/Power_set use std::vec::Vec; use std::slice::Items; // If set == {} // return {{}} // else if set == {a} U rest // return power_set(rest) U ({a} U each set in power_set(rest)) fn power_set<'a, T: Clone + 'a>(items: &mut Items<'a,T>) -> Vec<Vec<T>> { let mut power = Vec::new(); match items.next() { None => power.push(Vec::new()), Some(item) => { for set in power_set(items).iter() { power.push(set.clone()); power.push(set.clone().append_one(item.clone())); } } } power } #[test] fn test() { let set = Vec::<int>::new(); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!())); let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!(), vec!(1), vec!(2), vec!(2, 1), vec!(3), vec!(3, 1), vec!(3, 2), vec!(3, 2, 1))); } #[cfg(not(test))] fn main() { let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); set.push(4); let power = power_set(&mut set.iter()); println!("Set : {}", set); println!("Power Set: {}", power);
}
random_line_split
power_set.rs
// Given a set, generate its power set, which is the set of all subsets of that // set: http://rosettacode.org/wiki/Power_set use std::vec::Vec; use std::slice::Items; // If set == {} // return {{}} // else if set == {a} U rest // return power_set(rest) U ({a} U each set in power_set(rest)) fn power_set<'a, T: Clone + 'a>(items: &mut Items<'a,T>) -> Vec<Vec<T>> { let mut power = Vec::new(); match items.next() { None => power.push(Vec::new()), Some(item) => { for set in power_set(items).iter() { power.push(set.clone()); power.push(set.clone().append_one(item.clone())); } } } power } #[test] fn test()
#[cfg(not(test))] fn main() { let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); set.push(4); let power = power_set(&mut set.iter()); println!("Set : {}", set); println!("Power Set: {}", power); }
{ let set = Vec::<int>::new(); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!())); let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!(), vec!(1), vec!(2), vec!(2, 1), vec!(3), vec!(3, 1), vec!(3, 2), vec!(3, 2, 1))); }
identifier_body
create.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainId, transaction::{ChangeSet, WriteSetPayload}, write_set::{WriteOp, WriteSetMut}, }; use diem_validator_interface::{DiemValidatorInterface, JsonRpcDebuggerInterface}; use std::collections::{BTreeMap, BTreeSet}; use vm::CompiledModule; pub fn create_release( // ChainID to distinguish the diem network. e.g: PREMAINNET chain_id: ChainId, // Public JSON-rpc endpoint URL. // TODO: Get rid of this URL argument once we have a stable mapping from ChainId to its url. url: String, // Blockchain height version: u64, // Set the flag to true in the first release. This will manually create the first release artifact on disk. first_release: bool, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let release_artifact = ReleaseArtifact { chain_id, version, stdlib_hash: hash_for_modules( release_modules .iter() .map(|(bytes, module)| (module.self_id(), bytes)), )?, }; if first_release { if load_artifact(&chain_id).is_ok() { bail!("Previous release existed"); } save_release_artifact(release_artifact.clone())?; } let artifact = load_artifact(&chain_id)?; if artifact.chain_id!= chain_id { bail!("Artifact mismatch with on disk file"); } if artifact.version > version { bail!( "Artifact version is ahead of the argument: old: {:?}, new: {:?}", artifact.version, version ); } let remote = Box::new(JsonRpcDebuggerInterface::new(url.as_str())?); let payload = create_release_from_artifact(&release_artifact, url.as_str(), release_modules)?; verify_payload_change( remote, Some(version), &payload, release_modules.iter().map(|(_bytes, m)| m), )?; save_release_artifact(release_artifact)?; Ok(payload) } pub(crate) fn create_release_from_artifact( artifact: &ReleaseArtifact, remote_url: &str, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload>
pub(crate) fn create_release_writeset( remote_frameworks: &[CompiledModule], local_frameworks: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote_framework_map = remote_frameworks .iter() .map(|m| (m.self_id(), m)) .collect::<BTreeMap<_, _>>(); let remote_ids = remote_framework_map.keys().collect::<BTreeSet<_>>(); let local_framework_map = local_frameworks .iter() .map(|(bytes, module)| (module.self_id(), (bytes, module))) .collect::<BTreeMap<_, _>>(); let local_ids = local_framework_map.keys().collect::<BTreeSet<_>>(); let mut framework_changes = BTreeMap::new(); // 1. Insert new modules to be published. for module_id in local_ids.difference(&remote_ids) { let module = *local_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); framework_changes.insert(*module_id, Some(module)); } // 2. Remove modules that are already deleted locally. for module_id in remote_ids.difference(&local_ids) { framework_changes.insert(*module_id, None); } // 3. Check the diff between on chain modules and local modules, update when local bytes is different. for module_id in local_ids.intersection(&remote_ids) { let (local_bytes, local_module) = *local_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); let remote_module = remote_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); if &local_module!= remote_module { framework_changes.insert(*module_id, Some((local_bytes, local_module))); } } let mut write_patch = WriteSetMut::new(vec![]); for (id, module_opt) in framework_changes.into_iter() { let path = AccessPath::code_access_path(id.clone()); match module_opt { Some((bytes, _)) => { write_patch.push((path, WriteOp::Value((*bytes).clone()))); } None => write_patch.push((path, WriteOp::Deletion)), } } Ok(WriteSetPayload::Direct(ChangeSet::new( write_patch.freeze()?, vec![], ))) }
{ let remote = JsonRpcDebuggerInterface::new(remote_url)?; let remote_modules = remote.get_diem_framework_modules_by_version(artifact.version)?; create_release_writeset(&remote_modules, release_modules) }
identifier_body
create.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainId, transaction::{ChangeSet, WriteSetPayload}, write_set::{WriteOp, WriteSetMut}, }; use diem_validator_interface::{DiemValidatorInterface, JsonRpcDebuggerInterface}; use std::collections::{BTreeMap, BTreeSet}; use vm::CompiledModule; pub fn create_release( // ChainID to distinguish the diem network. e.g: PREMAINNET chain_id: ChainId, // Public JSON-rpc endpoint URL. // TODO: Get rid of this URL argument once we have a stable mapping from ChainId to its url. url: String, // Blockchain height version: u64, // Set the flag to true in the first release. This will manually create the first release artifact on disk. first_release: bool, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let release_artifact = ReleaseArtifact { chain_id, version, stdlib_hash: hash_for_modules( release_modules .iter() .map(|(bytes, module)| (module.self_id(), bytes)), )?, }; if first_release { if load_artifact(&chain_id).is_ok() { bail!("Previous release existed"); } save_release_artifact(release_artifact.clone())?; } let artifact = load_artifact(&chain_id)?; if artifact.chain_id!= chain_id { bail!("Artifact mismatch with on disk file"); } if artifact.version > version { bail!( "Artifact version is ahead of the argument: old: {:?}, new: {:?}", artifact.version, version ); } let remote = Box::new(JsonRpcDebuggerInterface::new(url.as_str())?); let payload = create_release_from_artifact(&release_artifact, url.as_str(), release_modules)?; verify_payload_change( remote, Some(version), &payload, release_modules.iter().map(|(_bytes, m)| m), )?; save_release_artifact(release_artifact)?; Ok(payload) } pub(crate) fn
( artifact: &ReleaseArtifact, remote_url: &str, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote = JsonRpcDebuggerInterface::new(remote_url)?; let remote_modules = remote.get_diem_framework_modules_by_version(artifact.version)?; create_release_writeset(&remote_modules, release_modules) } pub(crate) fn create_release_writeset( remote_frameworks: &[CompiledModule], local_frameworks: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote_framework_map = remote_frameworks .iter() .map(|m| (m.self_id(), m)) .collect::<BTreeMap<_, _>>(); let remote_ids = remote_framework_map.keys().collect::<BTreeSet<_>>(); let local_framework_map = local_frameworks .iter() .map(|(bytes, module)| (module.self_id(), (bytes, module))) .collect::<BTreeMap<_, _>>(); let local_ids = local_framework_map.keys().collect::<BTreeSet<_>>(); let mut framework_changes = BTreeMap::new(); // 1. Insert new modules to be published. for module_id in local_ids.difference(&remote_ids) { let module = *local_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); framework_changes.insert(*module_id, Some(module)); } // 2. Remove modules that are already deleted locally. for module_id in remote_ids.difference(&local_ids) { framework_changes.insert(*module_id, None); } // 3. Check the diff between on chain modules and local modules, update when local bytes is different. for module_id in local_ids.intersection(&remote_ids) { let (local_bytes, local_module) = *local_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); let remote_module = remote_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); if &local_module!= remote_module { framework_changes.insert(*module_id, Some((local_bytes, local_module))); } } let mut write_patch = WriteSetMut::new(vec![]); for (id, module_opt) in framework_changes.into_iter() { let path = AccessPath::code_access_path(id.clone()); match module_opt { Some((bytes, _)) => { write_patch.push((path, WriteOp::Value((*bytes).clone()))); } None => write_patch.push((path, WriteOp::Deletion)), } } Ok(WriteSetPayload::Direct(ChangeSet::new( write_patch.freeze()?, vec![], ))) }
create_release_from_artifact
identifier_name
create.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainId, transaction::{ChangeSet, WriteSetPayload}, write_set::{WriteOp, WriteSetMut}, }; use diem_validator_interface::{DiemValidatorInterface, JsonRpcDebuggerInterface}; use std::collections::{BTreeMap, BTreeSet}; use vm::CompiledModule; pub fn create_release( // ChainID to distinguish the diem network. e.g: PREMAINNET chain_id: ChainId, // Public JSON-rpc endpoint URL. // TODO: Get rid of this URL argument once we have a stable mapping from ChainId to its url. url: String, // Blockchain height version: u64, // Set the flag to true in the first release. This will manually create the first release artifact on disk. first_release: bool, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let release_artifact = ReleaseArtifact { chain_id, version, stdlib_hash: hash_for_modules( release_modules .iter() .map(|(bytes, module)| (module.self_id(), bytes)), )?, }; if first_release { if load_artifact(&chain_id).is_ok() { bail!("Previous release existed"); } save_release_artifact(release_artifact.clone())?; } let artifact = load_artifact(&chain_id)?; if artifact.chain_id!= chain_id { bail!("Artifact mismatch with on disk file"); } if artifact.version > version { bail!( "Artifact version is ahead of the argument: old: {:?}, new: {:?}", artifact.version, version ); } let remote = Box::new(JsonRpcDebuggerInterface::new(url.as_str())?); let payload = create_release_from_artifact(&release_artifact, url.as_str(), release_modules)?; verify_payload_change( remote, Some(version), &payload, release_modules.iter().map(|(_bytes, m)| m), )?; save_release_artifact(release_artifact)?; Ok(payload) } pub(crate) fn create_release_from_artifact( artifact: &ReleaseArtifact, remote_url: &str, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote = JsonRpcDebuggerInterface::new(remote_url)?; let remote_modules = remote.get_diem_framework_modules_by_version(artifact.version)?; create_release_writeset(&remote_modules, release_modules) } pub(crate) fn create_release_writeset( remote_frameworks: &[CompiledModule], local_frameworks: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote_framework_map = remote_frameworks .iter() .map(|m| (m.self_id(), m)) .collect::<BTreeMap<_, _>>(); let remote_ids = remote_framework_map.keys().collect::<BTreeSet<_>>(); let local_framework_map = local_frameworks .iter() .map(|(bytes, module)| (module.self_id(), (bytes, module))) .collect::<BTreeMap<_, _>>(); let local_ids = local_framework_map.keys().collect::<BTreeSet<_>>(); let mut framework_changes = BTreeMap::new(); // 1. Insert new modules to be published. for module_id in local_ids.difference(&remote_ids) { let module = *local_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); framework_changes.insert(*module_id, Some(module)); } // 2. Remove modules that are already deleted locally. for module_id in remote_ids.difference(&local_ids) { framework_changes.insert(*module_id, None); } // 3. Check the diff between on chain modules and local modules, update when local bytes is different. for module_id in local_ids.intersection(&remote_ids) { let (local_bytes, local_module) = *local_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); let remote_module = remote_framework_map .get(*module_id) .expect("ModuleID not found in local stdlib"); if &local_module!= remote_module { framework_changes.insert(*module_id, Some((local_bytes, local_module))); } } let mut write_patch = WriteSetMut::new(vec![]); for (id, module_opt) in framework_changes.into_iter() { let path = AccessPath::code_access_path(id.clone()); match module_opt { Some((bytes, _)) => { write_patch.push((path, WriteOp::Value((*bytes).clone())));
Ok(WriteSetPayload::Direct(ChangeSet::new( write_patch.freeze()?, vec![], ))) }
} None => write_patch.push((path, WriteOp::Deletion)), } }
random_line_split
parse_test.rs
extern crate mair; use std::fs::*; use std::path::{Path, PathBuf}; use std::io::{self, Read, Write}; use std::ffi::OsStr; use mair::parse::str_ptr_diff; use mair::parse::error::*; use mair::parse::lexer::*; use mair::parse::parser::*; use mair::parse::ast::*; fn test_dir_helper<P: AsRef<Path>, F: Fn(&mut Write, &str) -> io::Result<()>>( path: P, f: F, ) -> io::Result<bool> { let mut passed = true; for dirent in read_dir(path)? { let pathi = dirent?.path(); if pathi.extension() == Some(&OsStr::new("in")) { println!("testing {}", pathi.display()); let patho = pathi.with_extension("out"); let mut si = String::new(); let mut vo = vec![]; File::open(&pathi)? .read_to_string(&mut si)?; File::open(&patho)? .read_to_end(&mut vo)?; let mut buf = vec![]; f(&mut buf, &si)?; if vo == buf { println!("ok"); } else { File::create(&patho)? .write_all(&buf)?; passed = false; println!("fail"); } } } Ok(passed) } fn test_dir<F: Fn(&mut Write, &str) -> io::Result<()>>(dir: &str, f: F) { let mut path = PathBuf::new(); path.push("."); path.push("tests"); path.push(dir); match test_dir_helper(path, f) { Err(e) => panic!("os error: {:?}", e), Ok(false) => panic!("test fail"), Ok(true) => (), } } fn test_dir_lines<F: Fn(&mut Write, &str) -> io::Result<()>>(dir: &str, f: F) { test_dir(dir, |mut fo, s| { for (i, line) in s.lines().enumerate() { print!("#{} ", i + 1); f(&mut fo, line)? } println!(""); Ok(()) }); } fn lex(input: &str) -> Result<Vec<Token>, LexicalError>
fn tts(input: &str) -> Result<Vec<TT>, UnmatchedDelimError> { let ltoks = lex(input).unwrap(); parse_tts(input, &ltoks) } fn parse(input: &str) -> (Mod, Vec<HardSyntaxError>) { let tts_ = tts(input).unwrap(); parse_crate(input, tts_) } #[test] fn parse_test() { test_dir_lines("lexer_unit", |f, s| { writeln!(f, "{:?}", lex(s)) }); test_dir("lexer_large", |f, s| { writeln!(f, "{:?}", lex(s)) }); test_dir_lines("tts_simple", |f, s| { writeln!(f, "{:?}", tts(s)) }); test_dir("tts_large", |f, s| { writeln!(f, "{:?}", tts(s)) }); test_dir("parser_large", |f, s| { let (m, v) = parse(s); writeln!(f, "{:?}", m)?; for HardSyntaxError{ loc, reason } in v { writeln!(f, "{}..{} {:?} {}", str_ptr_diff(loc, s), str_ptr_diff(&loc[loc.len()..], s), loc, reason, )?; } Ok(()) }); }
{ let mut v = vec![]; for c in Lexer::new(input) { v.push(c?); } Ok(v) }
identifier_body
parse_test.rs
extern crate mair; use std::fs::*; use std::path::{Path, PathBuf}; use std::io::{self, Read, Write}; use std::ffi::OsStr; use mair::parse::str_ptr_diff; use mair::parse::error::*; use mair::parse::lexer::*; use mair::parse::parser::*; use mair::parse::ast::*; fn test_dir_helper<P: AsRef<Path>, F: Fn(&mut Write, &str) -> io::Result<()>>( path: P, f: F, ) -> io::Result<bool> { let mut passed = true; for dirent in read_dir(path)? { let pathi = dirent?.path(); if pathi.extension() == Some(&OsStr::new("in")) { println!("testing {}", pathi.display()); let patho = pathi.with_extension("out"); let mut si = String::new(); let mut vo = vec![]; File::open(&pathi)? .read_to_string(&mut si)?; File::open(&patho)? .read_to_end(&mut vo)?; let mut buf = vec![]; f(&mut buf, &si)?; if vo == buf { println!("ok"); } else { File::create(&patho)? .write_all(&buf)?; passed = false; println!("fail"); } } } Ok(passed) }
fn test_dir<F: Fn(&mut Write, &str) -> io::Result<()>>(dir: &str, f: F) { let mut path = PathBuf::new(); path.push("."); path.push("tests"); path.push(dir); match test_dir_helper(path, f) { Err(e) => panic!("os error: {:?}", e), Ok(false) => panic!("test fail"), Ok(true) => (), } } fn test_dir_lines<F: Fn(&mut Write, &str) -> io::Result<()>>(dir: &str, f: F) { test_dir(dir, |mut fo, s| { for (i, line) in s.lines().enumerate() { print!("#{} ", i + 1); f(&mut fo, line)? } println!(""); Ok(()) }); } fn lex(input: &str) -> Result<Vec<Token>, LexicalError> { let mut v = vec![]; for c in Lexer::new(input) { v.push(c?); } Ok(v) } fn tts(input: &str) -> Result<Vec<TT>, UnmatchedDelimError> { let ltoks = lex(input).unwrap(); parse_tts(input, &ltoks) } fn parse(input: &str) -> (Mod, Vec<HardSyntaxError>) { let tts_ = tts(input).unwrap(); parse_crate(input, tts_) } #[test] fn parse_test() { test_dir_lines("lexer_unit", |f, s| { writeln!(f, "{:?}", lex(s)) }); test_dir("lexer_large", |f, s| { writeln!(f, "{:?}", lex(s)) }); test_dir_lines("tts_simple", |f, s| { writeln!(f, "{:?}", tts(s)) }); test_dir("tts_large", |f, s| { writeln!(f, "{:?}", tts(s)) }); test_dir("parser_large", |f, s| { let (m, v) = parse(s); writeln!(f, "{:?}", m)?; for HardSyntaxError{ loc, reason } in v { writeln!(f, "{}..{} {:?} {}", str_ptr_diff(loc, s), str_ptr_diff(&loc[loc.len()..], s), loc, reason, )?; } Ok(()) }); }
random_line_split
parse_test.rs
extern crate mair; use std::fs::*; use std::path::{Path, PathBuf}; use std::io::{self, Read, Write}; use std::ffi::OsStr; use mair::parse::str_ptr_diff; use mair::parse::error::*; use mair::parse::lexer::*; use mair::parse::parser::*; use mair::parse::ast::*; fn test_dir_helper<P: AsRef<Path>, F: Fn(&mut Write, &str) -> io::Result<()>>( path: P, f: F, ) -> io::Result<bool> { let mut passed = true; for dirent in read_dir(path)? { let pathi = dirent?.path(); if pathi.extension() == Some(&OsStr::new("in")) { println!("testing {}", pathi.display()); let patho = pathi.with_extension("out"); let mut si = String::new(); let mut vo = vec![]; File::open(&pathi)? .read_to_string(&mut si)?; File::open(&patho)? .read_to_end(&mut vo)?; let mut buf = vec![]; f(&mut buf, &si)?; if vo == buf { println!("ok"); } else { File::create(&patho)? .write_all(&buf)?; passed = false; println!("fail"); } } } Ok(passed) } fn test_dir<F: Fn(&mut Write, &str) -> io::Result<()>>(dir: &str, f: F) { let mut path = PathBuf::new(); path.push("."); path.push("tests"); path.push(dir); match test_dir_helper(path, f) { Err(e) => panic!("os error: {:?}", e), Ok(false) => panic!("test fail"), Ok(true) => (), } } fn test_dir_lines<F: Fn(&mut Write, &str) -> io::Result<()>>(dir: &str, f: F) { test_dir(dir, |mut fo, s| { for (i, line) in s.lines().enumerate() { print!("#{} ", i + 1); f(&mut fo, line)? } println!(""); Ok(()) }); } fn lex(input: &str) -> Result<Vec<Token>, LexicalError> { let mut v = vec![]; for c in Lexer::new(input) { v.push(c?); } Ok(v) } fn
(input: &str) -> Result<Vec<TT>, UnmatchedDelimError> { let ltoks = lex(input).unwrap(); parse_tts(input, &ltoks) } fn parse(input: &str) -> (Mod, Vec<HardSyntaxError>) { let tts_ = tts(input).unwrap(); parse_crate(input, tts_) } #[test] fn parse_test() { test_dir_lines("lexer_unit", |f, s| { writeln!(f, "{:?}", lex(s)) }); test_dir("lexer_large", |f, s| { writeln!(f, "{:?}", lex(s)) }); test_dir_lines("tts_simple", |f, s| { writeln!(f, "{:?}", tts(s)) }); test_dir("tts_large", |f, s| { writeln!(f, "{:?}", tts(s)) }); test_dir("parser_large", |f, s| { let (m, v) = parse(s); writeln!(f, "{:?}", m)?; for HardSyntaxError{ loc, reason } in v { writeln!(f, "{}..{} {:?} {}", str_ptr_diff(loc, s), str_ptr_diff(&loc[loc.len()..], s), loc, reason, )?; } Ok(()) }); }
tts
identifier_name
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn
<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current = start; while current < stop { if f(current).abs() < epsilon { ret.push(current); } current = current + step; } ret } #[test] fn test_find_roots() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); let expected = [0.0f64, 1.0, 2.0]; for (&a, &b) in roots.iter().zip(expected.iter()) { assert!((a - b).abs() < 0.0001); } } fn main() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); println!("roots of f(x) = x^3 - 3x^2 + 2x are: {:?}", roots); }
find_roots
identifier_name
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn find_roots<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current = start; while current < stop { if f(current).abs() < epsilon { ret.push(current); } current = current + step; } ret } #[test] fn test_find_roots()
fn main() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); println!("roots of f(x) = x^3 - 3x^2 + 2x are: {:?}", roots); }
{ let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); let expected = [0.0f64, 1.0, 2.0]; for (&a, &b) in roots.iter().zip(expected.iter()) { assert!((a - b).abs() < 0.0001); } }
identifier_body
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn find_roots<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current = start; while current < stop { if f(current).abs() < epsilon { ret.push(current); } current = current + step; } ret } #[test] fn test_find_roots() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); let expected = [0.0f64, 1.0, 2.0]; for (&a, &b) in roots.iter().zip(expected.iter()) { assert!((a - b).abs() < 0.0001); } } fn main() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0,
0.00000001, ); println!("roots of f(x) = x^3 - 3x^2 + 2x are: {:?}", roots); }
3.0, 0.0001,
random_line_split
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn find_roots<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current = start; while current < stop { if f(current).abs() < epsilon
current = current + step; } ret } #[test] fn test_find_roots() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); let expected = [0.0f64, 1.0, 2.0]; for (&a, &b) in roots.iter().zip(expected.iter()) { assert!((a - b).abs() < 0.0001); } } fn main() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); println!("roots of f(x) = x^3 - 3x^2 + 2x are: {:?}", roots); }
{ ret.push(current); }
conditional_block
mod.rs
use std::io::{self, Write}; use std::collections::HashMap; mod parser; use nes::Nes; use self::parser::Command; pub struct Debugger<'a> { nes: Nes<'a>, pub breakpoints: HashMap<usize, usize>, } impl<'a> Debugger<'a> { pub fn init(nes: Nes<'a>) -> Self { let mut debugger = Debugger { nes: nes, breakpoints: HashMap::new(), }; debugger.reset(); debugger } pub fn run(&mut self){ let mut next_key = 1; loop { print!("Gidget>"); io::stdout().flush().unwrap(); let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let command = input.trim().parse::<Command>(); match command { Ok(Command::Step(num_steps)) => self.step(num_steps), Ok(Command::Run) => self.step_forever(), Ok(Command::Breakpoint(addr)) => self.set_breakpoint(&mut next_key, addr as usize), Ok(Command::ListBreakPoints) => self.list_breakpoints(), Ok(Command::ClearBreakpoint(num)) => self.clear_bp(&num), Ok(Command::Print(addr)) => self.print(addr as usize), Ok(Command::PrintRange(low_addr, high_addr)) => self.print_range(low_addr as usize, high_addr as usize), Ok(Command::Help) => self.help(), Ok(Command::Quit) => break, Err(ref e) => println!("{}", e), } } } pub fn reset(&mut self)
fn step(&mut self, num_steps: usize) { for _ in 0..num_steps { let opcode = self.nes.step(); print!("{:02X} {}", opcode, opcode_to_name(opcode)); println!("{:?}", self.nes.cpu); } } fn step_forever(&mut self) { self.nes.run(Some(&self.breakpoints)); } fn set_breakpoint(&mut self, key: &mut usize, addr: usize) { self.breakpoints.insert(*key, addr); *key += 1; } fn list_breakpoints(&mut self) { for (key, addr) in self.breakpoints.iter() { println!("{:}\t${:04X}", key, addr); } } fn clear_bp(&mut self, key: &usize) { self.breakpoints.remove(key); } fn print(&mut self, addr: usize) { if addr <= 0xFFFF { println!("M[${:04X}] = {:X}", addr, self.nes.cpu.fetch_byte(&mut self.nes.interconnect, addr as u16)); } else { println!("Invalid address: ${:X}", addr); } } fn print_range(&mut self, low_addr: usize, high_addr: usize) { if low_addr > 0xFFFF || high_addr > 0xFFFF { println!("Invalid address: LOW: ${:X} HIGH: {:X}", low_addr, high_addr); } else if low_addr > high_addr { println!("Low address higher than high address: LOW: ${:X} HIGH: ${:X}", low_addr, high_addr); } else { for (i, addr) in (low_addr..high_addr).enumerate() { if i % 16 == 0 { print!("\n${:04X}| ", addr); io::stdout().flush().unwrap(); } print!("{:02X} ", self.nes.cpu.fetch_byte(&mut self.nes.interconnect, addr as u16)); } print!("\n"); io::stdout().flush().unwrap(); } } fn help(&self) { println!("GIDGET DEBUGGER"); println!("Usage: COMMAND (SHORTCUT) <Args>"); println!("\tbreak\t\t(b)\t<Address>\t\t\t- Sets breakpoint at specified address"); println!("\tlist\t\t(l)\t\t\t\t\t- Lists all active breakpoints"); println!("\tclear\t\t(cb)\t<Breakpoint Number>\t\t- Clears specified breakpoint"); println!("\tprint\t\t(p)\t<Address>\t\t\t- Prints value in memory at specified address"); println!("\tpr\t\t\t<Low Address>:<High Address>\t- Prints the values over the specified range of memory"); println!("\tstep\t\t(s)\t<Steps>\t\t\t\t- Steps the NES the specified number of times (empty steps 1)"); println!("\trun/continue\t(r/c)\t\t\t\t\t- Runs the NES as normal"); println!("\tquit\t\t(q)\t\t\t\t\t- Quits the debugger"); println!("\thelp\t\t(h)\t\t\t\t\t- Prints this help message"); } } fn opcode_to_name(opcode: u8) -> String { format!("{:20}", match opcode { // Branches 0x10 => "BPL (label)", 0x30 => "BMI (label)", 0x50 => "BVC (label)", 0x70 => "BVS (label)", 0x90 => "BCC (label)", 0xB0 => "BCS (label)", 0xD0 => "BNE (label)", 0xF0 => "BEQ (label)", // ALU operations 0x61 => "ADC (d,x)", 0x65 => "ADC d", 0x69 => "ADC #v", 0x6D => "ADC a", 0x71 => "ADC (d),y", 0x75 => "ADC d,x", 0x79 => "ADC a,y", 0x7D => "ADC a,x", 0x21 => "AND (d,x)", 0x25 => "AND d", 0x29 => "AND #v", 0x2D => "AND a", 0x31 => "AND (d),y", 0x35 => "AND d,x", 0x39 => "AND a,y", 0x3D => "AND a,x", 0x06 => "ASL d", 0x0A => "ASL A", 0x0E => "ASL a", 0x16 => "ASL d,x", 0x1E => "ASL a,x", 0x24 => "BIT d", 0x2C => "BIT a", 0xC1 => "CMP (d,x)", 0xC5 => "CMP d", 0xC9 => "CMP #v", 0xCD => "CMP a", 0xD1 => "CMP (d),y", 0xD5 => "CMP d,x", 0xD9 => "CMP a,y", 0xDD => "CMP a,x", 0xE0 => "CPX #v", 0xE4 => "CPX d", 0xEC => "CPX a", 0xC0 => "CPY #v", 0xC4 => "CPY d", 0xCC => "CPY a", 0x41 => "EOR (d,x)", 0x45 => "EOR d", 0x49 => "EOR #v", 0x4D => "EOR a", 0x51 => "EOR (d),y", 0x55 => "EOR d,x", 0x59 => "EOR a,y", 0x5D => "EOR a,x", 0x4A => "LSR A", 0x46 => "LSR d", 0x4E => "LSR a", 0x56 => "LSR d,x", 0x5E => "LSR a,x", 0x01 => "ORA (d,x)", 0x05 => "ORA d", 0x09 => "ORA #v", 0x0D => "ORA a", 0x11 => "ORA (d),y", 0x15 => "ORA d,x", 0x19 => "ORA a,y", 0x1D => "ORA a,x", 0x2A => "ROL A", 0x26 => "ROL d", 0x2E => "ROL a", 0x36 => "ROL d,x", 0x3E => "ROL a,x", 0x6A => "ROR A", 0x66 => "ROR d", 0x6E => "ROR a", 0x76 => "ROR d,x", 0x7E => "ROR a,x", 0xE1 => "SBC (d,x)", 0xE5 => "SBC d", 0xE9 => "SBC #v", 0xED => "SBC a", 0xF1 => "SBC (d),y", 0xF5 => "SBC d,x", 0xF9 => "SBC a,y", 0xFD => "SBC a,x", // Increments and Decrements 0xE6 => "INC d", 0xEE => "INC a", 0xF6 => "INC d,x", 0xFE => "INC a,x", 0xE8 => "INX", 0xC8 => "INY", 0xC6 => "DEC d", 0xCE => "DEC a", 0xD6 => "DEC d,x", 0xDE => "DEC a,x", 0xCA => "DEX", 0x88 => "DEY", // Loads 0xA1 => "LDA (d,x)", 0xA5 => "LDA d", 0xA9 => "LDA #v", 0xAD => "LDA a", 0xB1 => "LDA (d),y", 0xB5 => "LDA d,x", 0xB9 => "LDA a,y", 0xBD => "LDA a,x", 0xA2 => "LDX #v", 0xA6 => "LDX d", 0xAE => "LDX a", 0xB6 => "LDX d,y", 0xBE => "LDX a,y", 0xA0 => "LDY #v", 0xA4 => "LDY d", 0xAC => "LDY a", 0xB4 => "LDY d,x", 0xBC => "LDY a,x", // Stores 0x81 => "STA (d,x)", 0x85 => "STA d", 0x8D => "STA a", 0x91 => "STA (d),y", 0x95 => "STA d,x", 0x99 => "STA a,y", 0x9D => "kTA a,x", 0x86 => "STX d", 0x8E => "STX a", 0x96 => "STX d,y", 0x84 => "STY d", 0x8C => "STY a", 0x94 => "STY d,x", // Flag sets 0x38 => "SEC", 0x78 => "SEI", 0xF8 => "SED", // Flag clears 0x18 => "CLC", 0xB8 => "CLV", 0xD8 => "CLD", // Stack 0x08 => "PHP", 0x28 => "PLP", 0x48 => "PHA", 0x68 => "PLA", // Transfers 0xAA => "TAX", 0xA8 => "TAY", 0xBA => "TSX", 0x8A => "TXA", 0x9A => "TXS", 0x98 => "TYA", // Jumps 0x4C => "JMP a", 0x6C => "JMP (a)", 0x20 => "JSR", 0x40 => "RTI", 0x60 => "RTS", 0xEA => "NOP", _ => unreachable!(), } ) }
{ self.nes.reset(); }
identifier_body
mod.rs
use std::io::{self, Write}; use std::collections::HashMap; mod parser; use nes::Nes; use self::parser::Command; pub struct Debugger<'a> { nes: Nes<'a>, pub breakpoints: HashMap<usize, usize>, } impl<'a> Debugger<'a> { pub fn init(nes: Nes<'a>) -> Self { let mut debugger = Debugger { nes: nes, breakpoints: HashMap::new(), }; debugger.reset(); debugger } pub fn run(&mut self){ let mut next_key = 1; loop { print!("Gidget>"); io::stdout().flush().unwrap(); let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let command = input.trim().parse::<Command>(); match command { Ok(Command::Step(num_steps)) => self.step(num_steps), Ok(Command::Run) => self.step_forever(), Ok(Command::Breakpoint(addr)) => self.set_breakpoint(&mut next_key, addr as usize), Ok(Command::ListBreakPoints) => self.list_breakpoints(), Ok(Command::ClearBreakpoint(num)) => self.clear_bp(&num), Ok(Command::Print(addr)) => self.print(addr as usize), Ok(Command::PrintRange(low_addr, high_addr)) => self.print_range(low_addr as usize, high_addr as usize), Ok(Command::Help) => self.help(), Ok(Command::Quit) => break, Err(ref e) => println!("{}", e), } } } pub fn reset(&mut self) { self.nes.reset(); } fn step(&mut self, num_steps: usize) { for _ in 0..num_steps { let opcode = self.nes.step(); print!("{:02X} {}", opcode, opcode_to_name(opcode)); println!("{:?}", self.nes.cpu); } } fn step_forever(&mut self) { self.nes.run(Some(&self.breakpoints)); } fn set_breakpoint(&mut self, key: &mut usize, addr: usize) { self.breakpoints.insert(*key, addr); *key += 1; } fn list_breakpoints(&mut self) { for (key, addr) in self.breakpoints.iter() { println!("{:}\t${:04X}", key, addr); } } fn clear_bp(&mut self, key: &usize) { self.breakpoints.remove(key); } fn
(&mut self, addr: usize) { if addr <= 0xFFFF { println!("M[${:04X}] = {:X}", addr, self.nes.cpu.fetch_byte(&mut self.nes.interconnect, addr as u16)); } else { println!("Invalid address: ${:X}", addr); } } fn print_range(&mut self, low_addr: usize, high_addr: usize) { if low_addr > 0xFFFF || high_addr > 0xFFFF { println!("Invalid address: LOW: ${:X} HIGH: {:X}", low_addr, high_addr); } else if low_addr > high_addr { println!("Low address higher than high address: LOW: ${:X} HIGH: ${:X}", low_addr, high_addr); } else { for (i, addr) in (low_addr..high_addr).enumerate() { if i % 16 == 0 { print!("\n${:04X}| ", addr); io::stdout().flush().unwrap(); } print!("{:02X} ", self.nes.cpu.fetch_byte(&mut self.nes.interconnect, addr as u16)); } print!("\n"); io::stdout().flush().unwrap(); } } fn help(&self) { println!("GIDGET DEBUGGER"); println!("Usage: COMMAND (SHORTCUT) <Args>"); println!("\tbreak\t\t(b)\t<Address>\t\t\t- Sets breakpoint at specified address"); println!("\tlist\t\t(l)\t\t\t\t\t- Lists all active breakpoints"); println!("\tclear\t\t(cb)\t<Breakpoint Number>\t\t- Clears specified breakpoint"); println!("\tprint\t\t(p)\t<Address>\t\t\t- Prints value in memory at specified address"); println!("\tpr\t\t\t<Low Address>:<High Address>\t- Prints the values over the specified range of memory"); println!("\tstep\t\t(s)\t<Steps>\t\t\t\t- Steps the NES the specified number of times (empty steps 1)"); println!("\trun/continue\t(r/c)\t\t\t\t\t- Runs the NES as normal"); println!("\tquit\t\t(q)\t\t\t\t\t- Quits the debugger"); println!("\thelp\t\t(h)\t\t\t\t\t- Prints this help message"); } } fn opcode_to_name(opcode: u8) -> String { format!("{:20}", match opcode { // Branches 0x10 => "BPL (label)", 0x30 => "BMI (label)", 0x50 => "BVC (label)", 0x70 => "BVS (label)", 0x90 => "BCC (label)", 0xB0 => "BCS (label)", 0xD0 => "BNE (label)", 0xF0 => "BEQ (label)", // ALU operations 0x61 => "ADC (d,x)", 0x65 => "ADC d", 0x69 => "ADC #v", 0x6D => "ADC a", 0x71 => "ADC (d),y", 0x75 => "ADC d,x", 0x79 => "ADC a,y", 0x7D => "ADC a,x", 0x21 => "AND (d,x)", 0x25 => "AND d", 0x29 => "AND #v", 0x2D => "AND a", 0x31 => "AND (d),y", 0x35 => "AND d,x", 0x39 => "AND a,y", 0x3D => "AND a,x", 0x06 => "ASL d", 0x0A => "ASL A", 0x0E => "ASL a", 0x16 => "ASL d,x", 0x1E => "ASL a,x", 0x24 => "BIT d", 0x2C => "BIT a", 0xC1 => "CMP (d,x)", 0xC5 => "CMP d", 0xC9 => "CMP #v", 0xCD => "CMP a", 0xD1 => "CMP (d),y", 0xD5 => "CMP d,x", 0xD9 => "CMP a,y", 0xDD => "CMP a,x", 0xE0 => "CPX #v", 0xE4 => "CPX d", 0xEC => "CPX a", 0xC0 => "CPY #v", 0xC4 => "CPY d", 0xCC => "CPY a", 0x41 => "EOR (d,x)", 0x45 => "EOR d", 0x49 => "EOR #v", 0x4D => "EOR a", 0x51 => "EOR (d),y", 0x55 => "EOR d,x", 0x59 => "EOR a,y", 0x5D => "EOR a,x", 0x4A => "LSR A", 0x46 => "LSR d", 0x4E => "LSR a", 0x56 => "LSR d,x", 0x5E => "LSR a,x", 0x01 => "ORA (d,x)", 0x05 => "ORA d", 0x09 => "ORA #v", 0x0D => "ORA a", 0x11 => "ORA (d),y", 0x15 => "ORA d,x", 0x19 => "ORA a,y", 0x1D => "ORA a,x", 0x2A => "ROL A", 0x26 => "ROL d", 0x2E => "ROL a", 0x36 => "ROL d,x", 0x3E => "ROL a,x", 0x6A => "ROR A", 0x66 => "ROR d", 0x6E => "ROR a", 0x76 => "ROR d,x", 0x7E => "ROR a,x", 0xE1 => "SBC (d,x)", 0xE5 => "SBC d", 0xE9 => "SBC #v", 0xED => "SBC a", 0xF1 => "SBC (d),y", 0xF5 => "SBC d,x", 0xF9 => "SBC a,y", 0xFD => "SBC a,x", // Increments and Decrements 0xE6 => "INC d", 0xEE => "INC a", 0xF6 => "INC d,x", 0xFE => "INC a,x", 0xE8 => "INX", 0xC8 => "INY", 0xC6 => "DEC d", 0xCE => "DEC a", 0xD6 => "DEC d,x", 0xDE => "DEC a,x", 0xCA => "DEX", 0x88 => "DEY", // Loads 0xA1 => "LDA (d,x)", 0xA5 => "LDA d", 0xA9 => "LDA #v", 0xAD => "LDA a", 0xB1 => "LDA (d),y", 0xB5 => "LDA d,x", 0xB9 => "LDA a,y", 0xBD => "LDA a,x", 0xA2 => "LDX #v", 0xA6 => "LDX d", 0xAE => "LDX a", 0xB6 => "LDX d,y", 0xBE => "LDX a,y", 0xA0 => "LDY #v", 0xA4 => "LDY d", 0xAC => "LDY a", 0xB4 => "LDY d,x", 0xBC => "LDY a,x", // Stores 0x81 => "STA (d,x)", 0x85 => "STA d", 0x8D => "STA a", 0x91 => "STA (d),y", 0x95 => "STA d,x", 0x99 => "STA a,y", 0x9D => "kTA a,x", 0x86 => "STX d", 0x8E => "STX a", 0x96 => "STX d,y", 0x84 => "STY d", 0x8C => "STY a", 0x94 => "STY d,x", // Flag sets 0x38 => "SEC", 0x78 => "SEI", 0xF8 => "SED", // Flag clears 0x18 => "CLC", 0xB8 => "CLV", 0xD8 => "CLD", // Stack 0x08 => "PHP", 0x28 => "PLP", 0x48 => "PHA", 0x68 => "PLA", // Transfers 0xAA => "TAX", 0xA8 => "TAY", 0xBA => "TSX", 0x8A => "TXA", 0x9A => "TXS", 0x98 => "TYA", // Jumps 0x4C => "JMP a", 0x6C => "JMP (a)", 0x20 => "JSR", 0x40 => "RTI", 0x60 => "RTS", 0xEA => "NOP", _ => unreachable!(), } ) }
print
identifier_name
mod.rs
use std::io::{self, Write}; use std::collections::HashMap; mod parser; use nes::Nes; use self::parser::Command; pub struct Debugger<'a> { nes: Nes<'a>, pub breakpoints: HashMap<usize, usize>, } impl<'a> Debugger<'a> { pub fn init(nes: Nes<'a>) -> Self {
breakpoints: HashMap::new(), }; debugger.reset(); debugger } pub fn run(&mut self){ let mut next_key = 1; loop { print!("Gidget>"); io::stdout().flush().unwrap(); let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let command = input.trim().parse::<Command>(); match command { Ok(Command::Step(num_steps)) => self.step(num_steps), Ok(Command::Run) => self.step_forever(), Ok(Command::Breakpoint(addr)) => self.set_breakpoint(&mut next_key, addr as usize), Ok(Command::ListBreakPoints) => self.list_breakpoints(), Ok(Command::ClearBreakpoint(num)) => self.clear_bp(&num), Ok(Command::Print(addr)) => self.print(addr as usize), Ok(Command::PrintRange(low_addr, high_addr)) => self.print_range(low_addr as usize, high_addr as usize), Ok(Command::Help) => self.help(), Ok(Command::Quit) => break, Err(ref e) => println!("{}", e), } } } pub fn reset(&mut self) { self.nes.reset(); } fn step(&mut self, num_steps: usize) { for _ in 0..num_steps { let opcode = self.nes.step(); print!("{:02X} {}", opcode, opcode_to_name(opcode)); println!("{:?}", self.nes.cpu); } } fn step_forever(&mut self) { self.nes.run(Some(&self.breakpoints)); } fn set_breakpoint(&mut self, key: &mut usize, addr: usize) { self.breakpoints.insert(*key, addr); *key += 1; } fn list_breakpoints(&mut self) { for (key, addr) in self.breakpoints.iter() { println!("{:}\t${:04X}", key, addr); } } fn clear_bp(&mut self, key: &usize) { self.breakpoints.remove(key); } fn print(&mut self, addr: usize) { if addr <= 0xFFFF { println!("M[${:04X}] = {:X}", addr, self.nes.cpu.fetch_byte(&mut self.nes.interconnect, addr as u16)); } else { println!("Invalid address: ${:X}", addr); } } fn print_range(&mut self, low_addr: usize, high_addr: usize) { if low_addr > 0xFFFF || high_addr > 0xFFFF { println!("Invalid address: LOW: ${:X} HIGH: {:X}", low_addr, high_addr); } else if low_addr > high_addr { println!("Low address higher than high address: LOW: ${:X} HIGH: ${:X}", low_addr, high_addr); } else { for (i, addr) in (low_addr..high_addr).enumerate() { if i % 16 == 0 { print!("\n${:04X}| ", addr); io::stdout().flush().unwrap(); } print!("{:02X} ", self.nes.cpu.fetch_byte(&mut self.nes.interconnect, addr as u16)); } print!("\n"); io::stdout().flush().unwrap(); } } fn help(&self) { println!("GIDGET DEBUGGER"); println!("Usage: COMMAND (SHORTCUT) <Args>"); println!("\tbreak\t\t(b)\t<Address>\t\t\t- Sets breakpoint at specified address"); println!("\tlist\t\t(l)\t\t\t\t\t- Lists all active breakpoints"); println!("\tclear\t\t(cb)\t<Breakpoint Number>\t\t- Clears specified breakpoint"); println!("\tprint\t\t(p)\t<Address>\t\t\t- Prints value in memory at specified address"); println!("\tpr\t\t\t<Low Address>:<High Address>\t- Prints the values over the specified range of memory"); println!("\tstep\t\t(s)\t<Steps>\t\t\t\t- Steps the NES the specified number of times (empty steps 1)"); println!("\trun/continue\t(r/c)\t\t\t\t\t- Runs the NES as normal"); println!("\tquit\t\t(q)\t\t\t\t\t- Quits the debugger"); println!("\thelp\t\t(h)\t\t\t\t\t- Prints this help message"); } } fn opcode_to_name(opcode: u8) -> String { format!("{:20}", match opcode { // Branches 0x10 => "BPL (label)", 0x30 => "BMI (label)", 0x50 => "BVC (label)", 0x70 => "BVS (label)", 0x90 => "BCC (label)", 0xB0 => "BCS (label)", 0xD0 => "BNE (label)", 0xF0 => "BEQ (label)", // ALU operations 0x61 => "ADC (d,x)", 0x65 => "ADC d", 0x69 => "ADC #v", 0x6D => "ADC a", 0x71 => "ADC (d),y", 0x75 => "ADC d,x", 0x79 => "ADC a,y", 0x7D => "ADC a,x", 0x21 => "AND (d,x)", 0x25 => "AND d", 0x29 => "AND #v", 0x2D => "AND a", 0x31 => "AND (d),y", 0x35 => "AND d,x", 0x39 => "AND a,y", 0x3D => "AND a,x", 0x06 => "ASL d", 0x0A => "ASL A", 0x0E => "ASL a", 0x16 => "ASL d,x", 0x1E => "ASL a,x", 0x24 => "BIT d", 0x2C => "BIT a", 0xC1 => "CMP (d,x)", 0xC5 => "CMP d", 0xC9 => "CMP #v", 0xCD => "CMP a", 0xD1 => "CMP (d),y", 0xD5 => "CMP d,x", 0xD9 => "CMP a,y", 0xDD => "CMP a,x", 0xE0 => "CPX #v", 0xE4 => "CPX d", 0xEC => "CPX a", 0xC0 => "CPY #v", 0xC4 => "CPY d", 0xCC => "CPY a", 0x41 => "EOR (d,x)", 0x45 => "EOR d", 0x49 => "EOR #v", 0x4D => "EOR a", 0x51 => "EOR (d),y", 0x55 => "EOR d,x", 0x59 => "EOR a,y", 0x5D => "EOR a,x", 0x4A => "LSR A", 0x46 => "LSR d", 0x4E => "LSR a", 0x56 => "LSR d,x", 0x5E => "LSR a,x", 0x01 => "ORA (d,x)", 0x05 => "ORA d", 0x09 => "ORA #v", 0x0D => "ORA a", 0x11 => "ORA (d),y", 0x15 => "ORA d,x", 0x19 => "ORA a,y", 0x1D => "ORA a,x", 0x2A => "ROL A", 0x26 => "ROL d", 0x2E => "ROL a", 0x36 => "ROL d,x", 0x3E => "ROL a,x", 0x6A => "ROR A", 0x66 => "ROR d", 0x6E => "ROR a", 0x76 => "ROR d,x", 0x7E => "ROR a,x", 0xE1 => "SBC (d,x)", 0xE5 => "SBC d", 0xE9 => "SBC #v", 0xED => "SBC a", 0xF1 => "SBC (d),y", 0xF5 => "SBC d,x", 0xF9 => "SBC a,y", 0xFD => "SBC a,x", // Increments and Decrements 0xE6 => "INC d", 0xEE => "INC a", 0xF6 => "INC d,x", 0xFE => "INC a,x", 0xE8 => "INX", 0xC8 => "INY", 0xC6 => "DEC d", 0xCE => "DEC a", 0xD6 => "DEC d,x", 0xDE => "DEC a,x", 0xCA => "DEX", 0x88 => "DEY", // Loads 0xA1 => "LDA (d,x)", 0xA5 => "LDA d", 0xA9 => "LDA #v", 0xAD => "LDA a", 0xB1 => "LDA (d),y", 0xB5 => "LDA d,x", 0xB9 => "LDA a,y", 0xBD => "LDA a,x", 0xA2 => "LDX #v", 0xA6 => "LDX d", 0xAE => "LDX a", 0xB6 => "LDX d,y", 0xBE => "LDX a,y", 0xA0 => "LDY #v", 0xA4 => "LDY d", 0xAC => "LDY a", 0xB4 => "LDY d,x", 0xBC => "LDY a,x", // Stores 0x81 => "STA (d,x)", 0x85 => "STA d", 0x8D => "STA a", 0x91 => "STA (d),y", 0x95 => "STA d,x", 0x99 => "STA a,y", 0x9D => "kTA a,x", 0x86 => "STX d", 0x8E => "STX a", 0x96 => "STX d,y", 0x84 => "STY d", 0x8C => "STY a", 0x94 => "STY d,x", // Flag sets 0x38 => "SEC", 0x78 => "SEI", 0xF8 => "SED", // Flag clears 0x18 => "CLC", 0xB8 => "CLV", 0xD8 => "CLD", // Stack 0x08 => "PHP", 0x28 => "PLP", 0x48 => "PHA", 0x68 => "PLA", // Transfers 0xAA => "TAX", 0xA8 => "TAY", 0xBA => "TSX", 0x8A => "TXA", 0x9A => "TXS", 0x98 => "TYA", // Jumps 0x4C => "JMP a", 0x6C => "JMP (a)", 0x20 => "JSR", 0x40 => "RTI", 0x60 => "RTS", 0xEA => "NOP", _ => unreachable!(), } ) }
let mut debugger = Debugger { nes: nes,
random_line_split
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy is free software: you can redistribute it and/or modify it | // | under the terms of the GNU General Public License as published by the | // | Free Software Foundation, either version 3 of the License, or (at your | // | option) any later version. | // | | // | System Syzygy is distributed in the hope that it will be useful, but | // | WITHOUT ANY WARRANTY; without even the implied warranty of | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ mod scenes; mod view; use self::view::View; use crate::gui::Window; use crate::modes::{run_puzzle, Mode}; use crate::save::SaveData; // ========================================================================= // pub fn
( window: &mut Window, save_data: &mut SaveData, ) -> Mode { let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().shifting_ground, ) }; run_puzzle(window, save_data, view) } // ========================================================================= //
run_shifting_ground
identifier_name
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy is free software: you can redistribute it and/or modify it | // | under the terms of the GNU General Public License as published by the | // | Free Software Foundation, either version 3 of the License, or (at your | // | option) any later version. | // | | // | System Syzygy is distributed in the hope that it will be useful, but | // | WITHOUT ANY WARRANTY; without even the implied warranty of | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ mod scenes; mod view; use self::view::View; use crate::gui::Window; use crate::modes::{run_puzzle, Mode}; use crate::save::SaveData; // ========================================================================= // pub fn run_shifting_ground( window: &mut Window, save_data: &mut SaveData, ) -> Mode
// ========================================================================= //
{ let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().shifting_ground, ) }; run_puzzle(window, save_data, view) }
identifier_body
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy is free software: you can redistribute it and/or modify it | // | under the terms of the GNU General Public License as published by the | // | Free Software Foundation, either version 3 of the License, or (at your | // | option) any later version. | // | | // | System Syzygy is distributed in the hope that it will be useful, but |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ mod scenes; mod view; use self::view::View; use crate::gui::Window; use crate::modes::{run_puzzle, Mode}; use crate::save::SaveData; // ========================================================================= // pub fn run_shifting_ground( window: &mut Window, save_data: &mut SaveData, ) -> Mode { let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().shifting_ground, ) }; run_puzzle(window, save_data, view) } // ========================================================================= //
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
random_line_split
mod.rs
mod test; use sourcefile::SourceFile as SourceFile; use dispatch::InvokeReceivier as InvokeReceivier; use dispatch::Dispatch as Dispatch; use dispatch::Invoke as Invoke; use type_name::TypeName as TypeName; use common::ParseError as ParseError; use arguments::Argument as Argument; pub fn compile_dispatch(dispatch: &Box<Dispatch>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError>
fn compile_type_invoke(invoke: &Box<Invoke>, type_name: &Box<TypeName>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError> { if! sourcefile.has_external(type_name.name.clone()) { return Err(ParseError::new_msg(&format!("Unkown type {}", type_name.canonical()))); } let external = sourcefile.get_external(&type_name.name).unwrap(); if! external.is_roo() { let mut output = "".to_string(); output.push_str(&format!("{}.{}{}(", external.reference_name(), static_call_chain(&invoke), invoke.message_name())); output.push_str(&arguments(&invoke)); output.push_str(");"); return Ok(output); } return Ok("".to_string()); } fn static_call_chain(invoke: &Box<Invoke>) -> String { let mut output = "".to_string(); for (_, static_receiver) in invoke.enumerate_static_receivers() { output.push_str(static_receiver); output.push_str("."); } return output; } #[allow(unused_variables)] fn arguments(invoke: &Box<Invoke>) -> String { let mut output = "".to_string(); return match invoke.args { None => output, Some(ref args) => { for (index, arg) in args.enumerate() { match *arg { Argument::IntegerArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::BooleanArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::DecimalArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::CharSeqArg {ref name, ref value} => { output.push_str(&format!("\"{}\"", (&value.clone()))); if index < args.count() - 1 { output.push_str(",") }; }, Argument::ObjectArg {ref name, ref value} => {panic!("not implemented");}, Argument::DispatchArg {ref name, ref value} => {panic!("not implemented");} } } output } } }
{ match dispatch.stack[0].receiver { Some(InvokeReceivier::Constant{ref value}) => panic!("not implemented"), Some(InvokeReceivier::InstanceObject{ref value}) => panic!("not implemented"), Some(InvokeReceivier::TypeObject{ref value}) => return compile_type_invoke(&dispatch.stack[0], &value, &sourcefile), _ => panic!("not implemented") } }
identifier_body
mod.rs
mod test; use sourcefile::SourceFile as SourceFile; use dispatch::InvokeReceivier as InvokeReceivier; use dispatch::Dispatch as Dispatch; use dispatch::Invoke as Invoke; use type_name::TypeName as TypeName; use common::ParseError as ParseError; use arguments::Argument as Argument; pub fn compile_dispatch(dispatch: &Box<Dispatch>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError> { match dispatch.stack[0].receiver { Some(InvokeReceivier::Constant{ref value}) => panic!("not implemented"), Some(InvokeReceivier::InstanceObject{ref value}) => panic!("not implemented"), Some(InvokeReceivier::TypeObject{ref value}) => return compile_type_invoke(&dispatch.stack[0], &value, &sourcefile), _ => panic!("not implemented") } } fn compile_type_invoke(invoke: &Box<Invoke>, type_name: &Box<TypeName>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError> { if! sourcefile.has_external(type_name.name.clone()) { return Err(ParseError::new_msg(&format!("Unkown type {}", type_name.canonical()))); } let external = sourcefile.get_external(&type_name.name).unwrap();
output.push_str(&format!("{}.{}{}(", external.reference_name(), static_call_chain(&invoke), invoke.message_name())); output.push_str(&arguments(&invoke)); output.push_str(");"); return Ok(output); } return Ok("".to_string()); } fn static_call_chain(invoke: &Box<Invoke>) -> String { let mut output = "".to_string(); for (_, static_receiver) in invoke.enumerate_static_receivers() { output.push_str(static_receiver); output.push_str("."); } return output; } #[allow(unused_variables)] fn arguments(invoke: &Box<Invoke>) -> String { let mut output = "".to_string(); return match invoke.args { None => output, Some(ref args) => { for (index, arg) in args.enumerate() { match *arg { Argument::IntegerArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::BooleanArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::DecimalArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::CharSeqArg {ref name, ref value} => { output.push_str(&format!("\"{}\"", (&value.clone()))); if index < args.count() - 1 { output.push_str(",") }; }, Argument::ObjectArg {ref name, ref value} => {panic!("not implemented");}, Argument::DispatchArg {ref name, ref value} => {panic!("not implemented");} } } output } } }
if ! external.is_roo() { let mut output = "".to_string();
random_line_split
mod.rs
mod test; use sourcefile::SourceFile as SourceFile; use dispatch::InvokeReceivier as InvokeReceivier; use dispatch::Dispatch as Dispatch; use dispatch::Invoke as Invoke; use type_name::TypeName as TypeName; use common::ParseError as ParseError; use arguments::Argument as Argument; pub fn compile_dispatch(dispatch: &Box<Dispatch>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError> { match dispatch.stack[0].receiver { Some(InvokeReceivier::Constant{ref value}) => panic!("not implemented"), Some(InvokeReceivier::InstanceObject{ref value}) => panic!("not implemented"), Some(InvokeReceivier::TypeObject{ref value}) => return compile_type_invoke(&dispatch.stack[0], &value, &sourcefile), _ => panic!("not implemented") } } fn
(invoke: &Box<Invoke>, type_name: &Box<TypeName>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError> { if! sourcefile.has_external(type_name.name.clone()) { return Err(ParseError::new_msg(&format!("Unkown type {}", type_name.canonical()))); } let external = sourcefile.get_external(&type_name.name).unwrap(); if! external.is_roo() { let mut output = "".to_string(); output.push_str(&format!("{}.{}{}(", external.reference_name(), static_call_chain(&invoke), invoke.message_name())); output.push_str(&arguments(&invoke)); output.push_str(");"); return Ok(output); } return Ok("".to_string()); } fn static_call_chain(invoke: &Box<Invoke>) -> String { let mut output = "".to_string(); for (_, static_receiver) in invoke.enumerate_static_receivers() { output.push_str(static_receiver); output.push_str("."); } return output; } #[allow(unused_variables)] fn arguments(invoke: &Box<Invoke>) -> String { let mut output = "".to_string(); return match invoke.args { None => output, Some(ref args) => { for (index, arg) in args.enumerate() { match *arg { Argument::IntegerArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::BooleanArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::DecimalArg {ref name, ref value} => { output.push_str(&value.to_string()); if index < args.count() - 1 { output.push_str(",") }; }, Argument::CharSeqArg {ref name, ref value} => { output.push_str(&format!("\"{}\"", (&value.clone()))); if index < args.count() - 1 { output.push_str(",") }; }, Argument::ObjectArg {ref name, ref value} => {panic!("not implemented");}, Argument::DispatchArg {ref name, ref value} => {panic!("not implemented");} } } output } } }
compile_type_invoke
identifier_name
day6.rs
#[macro_use] extern crate derive_builder; #[derive(Clone, Debug)] struct
{ width: u32, height: u32, } impl Default for Resolution { fn default() -> Resolution { Resolution { width: 1920, height: 1080, } } } #[derive(Debug, Default, Builder)] #[builder(field(private), setter(into))] struct GameConfig { #[builder(default)] resolution: Resolution, save_dir: Option<String>, #[builder(default)] autosave: bool, fov: f32, render_distance: u32, } fn main() { println!("24 Days of Rust vol. 2 - derive_builder"); let conf = GameConfigBuilder::default() .save_dir("saves".to_string()) .fov(70.0) .render_distance(1000u32) .build() .unwrap(); println!("{:?}", conf); }
Resolution
identifier_name
day6.rs
#[macro_use] extern crate derive_builder; #[derive(Clone, Debug)] struct Resolution { width: u32, height: u32, } impl Default for Resolution { fn default() -> Resolution { Resolution { width: 1920, height: 1080, } } } #[derive(Debug, Default, Builder)] #[builder(field(private), setter(into))]
resolution: Resolution, save_dir: Option<String>, #[builder(default)] autosave: bool, fov: f32, render_distance: u32, } fn main() { println!("24 Days of Rust vol. 2 - derive_builder"); let conf = GameConfigBuilder::default() .save_dir("saves".to_string()) .fov(70.0) .render_distance(1000u32) .build() .unwrap(); println!("{:?}", conf); }
struct GameConfig { #[builder(default)]
random_line_split
progress.rs
use std::io::{Read, Result}; use std::time::{Duration, Instant}; pub struct Progress<R> { bytes: usize, tick: Instant, stream: R, } impl<R> Progress<R> { pub fn new(stream: R) -> Self { Progress { bytes: 0, tick: Instant::now() + Duration::from_millis(2000), stream, } } } impl<R: Read> Read for Progress<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let num = self.stream.read(buf)?; self.bytes += num; let now = Instant::now(); if now > self.tick
Ok(num) } } impl<R> Drop for Progress<R> { fn drop(&mut self) { errorf!("done ({} bytes)\n", self.bytes); } }
{ self.tick = now + Duration::from_millis(500); errorf!("downloading... {} bytes\n", self.bytes); }
conditional_block
progress.rs
use std::io::{Read, Result}; use std::time::{Duration, Instant}; pub struct Progress<R> { bytes: usize, tick: Instant, stream: R, } impl<R> Progress<R> {
pub fn new(stream: R) -> Self { Progress { bytes: 0, tick: Instant::now() + Duration::from_millis(2000), stream, } } } impl<R: Read> Read for Progress<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let num = self.stream.read(buf)?; self.bytes += num; let now = Instant::now(); if now > self.tick { self.tick = now + Duration::from_millis(500); errorf!("downloading... {} bytes\n", self.bytes); } Ok(num) } } impl<R> Drop for Progress<R> { fn drop(&mut self) { errorf!("done ({} bytes)\n", self.bytes); } }
random_line_split
progress.rs
use std::io::{Read, Result}; use std::time::{Duration, Instant}; pub struct
<R> { bytes: usize, tick: Instant, stream: R, } impl<R> Progress<R> { pub fn new(stream: R) -> Self { Progress { bytes: 0, tick: Instant::now() + Duration::from_millis(2000), stream, } } } impl<R: Read> Read for Progress<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let num = self.stream.read(buf)?; self.bytes += num; let now = Instant::now(); if now > self.tick { self.tick = now + Duration::from_millis(500); errorf!("downloading... {} bytes\n", self.bytes); } Ok(num) } } impl<R> Drop for Progress<R> { fn drop(&mut self) { errorf!("done ({} bytes)\n", self.bytes); } }
Progress
identifier_name
tile.rs
use colors; use pixset; use pixset::PixLike; use std::default::Default; #[derive(Clone, Copy, Debug, Default)] pub struct
<P: PixLike> { pub fg: colors::Rgb, pub bg: colors::Rgb, pub pix: P, } // TODO default? impl<P> Tile<P> where P: pixset::PixLike, { pub fn new() -> Self { Tile { fg: *colors::BLACK, bg: *colors::BLACK, pix: Default::default(), } } pub fn make(fg: colors::Rgb, bg: colors::Rgb, pix: P) -> Self { Tile { fg: fg, bg: bg, pix: pix, } } pub fn clear(&mut self) { // TODO gross let t = Tile::new(); self.fg = t.fg; self.bg = t.bg; self.pix = t.pix; } }
Tile
identifier_name
tile.rs
use colors; use pixset; use pixset::PixLike; use std::default::Default; #[derive(Clone, Copy, Debug, Default)] pub struct Tile<P: PixLike> { pub fg: colors::Rgb, pub bg: colors::Rgb, pub pix: P, } // TODO default?
impl<P> Tile<P> where P: pixset::PixLike, { pub fn new() -> Self { Tile { fg: *colors::BLACK, bg: *colors::BLACK, pix: Default::default(), } } pub fn make(fg: colors::Rgb, bg: colors::Rgb, pix: P) -> Self { Tile { fg: fg, bg: bg, pix: pix, } } pub fn clear(&mut self) { // TODO gross let t = Tile::new(); self.fg = t.fg; self.bg = t.bg; self.pix = t.pix; } }
random_line_split
tile.rs
use colors; use pixset; use pixset::PixLike; use std::default::Default; #[derive(Clone, Copy, Debug, Default)] pub struct Tile<P: PixLike> { pub fg: colors::Rgb, pub bg: colors::Rgb, pub pix: P, } // TODO default? impl<P> Tile<P> where P: pixset::PixLike, { pub fn new() -> Self { Tile { fg: *colors::BLACK, bg: *colors::BLACK, pix: Default::default(), } } pub fn make(fg: colors::Rgb, bg: colors::Rgb, pix: P) -> Self
pub fn clear(&mut self) { // TODO gross let t = Tile::new(); self.fg = t.fg; self.bg = t.bg; self.pix = t.pix; } }
{ Tile { fg: fg, bg: bg, pix: pix, } }
identifier_body
load.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. //! Used by `rustc` when loading a plugin. use rustc::session::Session; use rustc_metadata::creader::CrateLoader; use rustc_metadata::cstore::CStore; use registry::Registry; use std::borrow::ToOwned; use std::env; use std::mem; use std::path::PathBuf; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; /// Pointer to a registrar function. pub type PluginRegistrarFun = fn(&mut Registry); pub struct PluginRegistrar { pub fun: PluginRegistrarFun, pub args: Vec<ast::NestedMetaItem>, } struct PluginLoader<'a> { sess: &'a Session, reader: CrateLoader<'a>, plugins: Vec<PluginRegistrar>, } fn call_malformed_plugin_attribute(a: &Session, b: Span) { span_err!(a, b, E0498, "malformed plugin attribute"); } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, cstore: &CStore, krate: &ast::Crate, crate_name: &str, addl_plugins: Option<Vec<String>>) -> Vec<PluginRegistrar>
for plugin in plugins { // plugins must have a name and can't be key = value match plugin.name() { Some(name) if!plugin.is_value_str() => { let args = plugin.meta_item_list().map(ToOwned::to_owned); loader.load_plugin(plugin.span, &name.as_str(), args.unwrap_or_default()); }, _ => call_malformed_plugin_attribute(sess, attr.span), } } } } if let Some(plugins) = addl_plugins { for plugin in plugins { loader.load_plugin(DUMMY_SP, &plugin, vec![]); } } loader.plugins } impl<'a> PluginLoader<'a> { fn new(sess: &'a Session, cstore: &'a CStore, crate_name: &str) -> Self { PluginLoader { sess, reader: CrateLoader::new(sess, cstore, crate_name), plugins: vec![], } } fn load_plugin(&mut self, span: Span, name: &str, args: Vec<ast::NestedMetaItem>) { let registrar = self.reader.find_plugin_registrar(span, name); if let Some((lib, disambiguator)) = registrar { let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator); let fun = self.dylink_registrar(span, lib, symbol); self.plugins.push(PluginRegistrar { fun, args, }); } } // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, span: Span, path: PathBuf, symbol: String) -> PluginRegistrarFun { use rustc_metadata::dynamic_lib::DynamicLibrary; // Make sure the path contains a / or the linker will search for it. let path = env::current_dir().unwrap().join(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors Err(err) => { self.sess.span_fatal(span, &err) } }; unsafe { let registrar = match lib.symbol(&symbol) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => { self.sess.span_fatal(span, &err) } }; // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long // (e.g., an @-box cycle or a thread). mem::forget(lib); registrar } } }
{ let mut loader = PluginLoader::new(sess, cstore, crate_name); // do not report any error now. since crate attributes are // not touched by expansion, every use of plugin without // the feature enabled will result in an error later... if sess.features_untracked().plugin { for attr in &krate.attrs { if !attr.check_name("plugin") { continue; } let plugins = match attr.meta_item_list() { Some(xs) => xs, None => { call_malformed_plugin_attribute(sess, attr.span); continue; } };
identifier_body
load.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. //! Used by `rustc` when loading a plugin. use rustc::session::Session; use rustc_metadata::creader::CrateLoader; use rustc_metadata::cstore::CStore; use registry::Registry; use std::borrow::ToOwned; use std::env; use std::mem; use std::path::PathBuf; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; /// Pointer to a registrar function. pub type PluginRegistrarFun = fn(&mut Registry); pub struct PluginRegistrar { pub fun: PluginRegistrarFun, pub args: Vec<ast::NestedMetaItem>, } struct
<'a> { sess: &'a Session, reader: CrateLoader<'a>, plugins: Vec<PluginRegistrar>, } fn call_malformed_plugin_attribute(a: &Session, b: Span) { span_err!(a, b, E0498, "malformed plugin attribute"); } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, cstore: &CStore, krate: &ast::Crate, crate_name: &str, addl_plugins: Option<Vec<String>>) -> Vec<PluginRegistrar> { let mut loader = PluginLoader::new(sess, cstore, crate_name); // do not report any error now. since crate attributes are // not touched by expansion, every use of plugin without // the feature enabled will result in an error later... if sess.features_untracked().plugin { for attr in &krate.attrs { if!attr.check_name("plugin") { continue; } let plugins = match attr.meta_item_list() { Some(xs) => xs, None => { call_malformed_plugin_attribute(sess, attr.span); continue; } }; for plugin in plugins { // plugins must have a name and can't be key = value match plugin.name() { Some(name) if!plugin.is_value_str() => { let args = plugin.meta_item_list().map(ToOwned::to_owned); loader.load_plugin(plugin.span, &name.as_str(), args.unwrap_or_default()); }, _ => call_malformed_plugin_attribute(sess, attr.span), } } } } if let Some(plugins) = addl_plugins { for plugin in plugins { loader.load_plugin(DUMMY_SP, &plugin, vec![]); } } loader.plugins } impl<'a> PluginLoader<'a> { fn new(sess: &'a Session, cstore: &'a CStore, crate_name: &str) -> Self { PluginLoader { sess, reader: CrateLoader::new(sess, cstore, crate_name), plugins: vec![], } } fn load_plugin(&mut self, span: Span, name: &str, args: Vec<ast::NestedMetaItem>) { let registrar = self.reader.find_plugin_registrar(span, name); if let Some((lib, disambiguator)) = registrar { let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator); let fun = self.dylink_registrar(span, lib, symbol); self.plugins.push(PluginRegistrar { fun, args, }); } } // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, span: Span, path: PathBuf, symbol: String) -> PluginRegistrarFun { use rustc_metadata::dynamic_lib::DynamicLibrary; // Make sure the path contains a / or the linker will search for it. let path = env::current_dir().unwrap().join(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors Err(err) => { self.sess.span_fatal(span, &err) } }; unsafe { let registrar = match lib.symbol(&symbol) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => { self.sess.span_fatal(span, &err) } }; // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long // (e.g., an @-box cycle or a thread). mem::forget(lib); registrar } } }
PluginLoader
identifier_name
load.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. //! Used by `rustc` when loading a plugin. use rustc::session::Session; use rustc_metadata::creader::CrateLoader; use rustc_metadata::cstore::CStore; use registry::Registry; use std::borrow::ToOwned; use std::env; use std::mem; use std::path::PathBuf; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; /// Pointer to a registrar function. pub type PluginRegistrarFun = fn(&mut Registry); pub struct PluginRegistrar { pub fun: PluginRegistrarFun, pub args: Vec<ast::NestedMetaItem>, } struct PluginLoader<'a> { sess: &'a Session, reader: CrateLoader<'a>, plugins: Vec<PluginRegistrar>, } fn call_malformed_plugin_attribute(a: &Session, b: Span) { span_err!(a, b, E0498, "malformed plugin attribute"); } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, cstore: &CStore, krate: &ast::Crate, crate_name: &str, addl_plugins: Option<Vec<String>>) -> Vec<PluginRegistrar> { let mut loader = PluginLoader::new(sess, cstore, crate_name); // do not report any error now. since crate attributes are // not touched by expansion, every use of plugin without // the feature enabled will result in an error later... if sess.features_untracked().plugin { for attr in &krate.attrs { if!attr.check_name("plugin") { continue; } let plugins = match attr.meta_item_list() { Some(xs) => xs, None => { call_malformed_plugin_attribute(sess, attr.span); continue; } }; for plugin in plugins { // plugins must have a name and can't be key = value match plugin.name() { Some(name) if!plugin.is_value_str() => { let args = plugin.meta_item_list().map(ToOwned::to_owned); loader.load_plugin(plugin.span, &name.as_str(), args.unwrap_or_default()); }, _ => call_malformed_plugin_attribute(sess, attr.span), } } } } if let Some(plugins) = addl_plugins { for plugin in plugins { loader.load_plugin(DUMMY_SP, &plugin, vec![]); } } loader.plugins } impl<'a> PluginLoader<'a> { fn new(sess: &'a Session, cstore: &'a CStore, crate_name: &str) -> Self { PluginLoader { sess, reader: CrateLoader::new(sess, cstore, crate_name),
} fn load_plugin(&mut self, span: Span, name: &str, args: Vec<ast::NestedMetaItem>) { let registrar = self.reader.find_plugin_registrar(span, name); if let Some((lib, disambiguator)) = registrar { let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator); let fun = self.dylink_registrar(span, lib, symbol); self.plugins.push(PluginRegistrar { fun, args, }); } } // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, span: Span, path: PathBuf, symbol: String) -> PluginRegistrarFun { use rustc_metadata::dynamic_lib::DynamicLibrary; // Make sure the path contains a / or the linker will search for it. let path = env::current_dir().unwrap().join(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors Err(err) => { self.sess.span_fatal(span, &err) } }; unsafe { let registrar = match lib.symbol(&symbol) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => { self.sess.span_fatal(span, &err) } }; // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long // (e.g., an @-box cycle or a thread). mem::forget(lib); registrar } } }
plugins: vec![], }
random_line_split
load.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. //! Used by `rustc` when loading a plugin. use rustc::session::Session; use rustc_metadata::creader::CrateLoader; use rustc_metadata::cstore::CStore; use registry::Registry; use std::borrow::ToOwned; use std::env; use std::mem; use std::path::PathBuf; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; /// Pointer to a registrar function. pub type PluginRegistrarFun = fn(&mut Registry); pub struct PluginRegistrar { pub fun: PluginRegistrarFun, pub args: Vec<ast::NestedMetaItem>, } struct PluginLoader<'a> { sess: &'a Session, reader: CrateLoader<'a>, plugins: Vec<PluginRegistrar>, } fn call_malformed_plugin_attribute(a: &Session, b: Span) { span_err!(a, b, E0498, "malformed plugin attribute"); } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, cstore: &CStore, krate: &ast::Crate, crate_name: &str, addl_plugins: Option<Vec<String>>) -> Vec<PluginRegistrar> { let mut loader = PluginLoader::new(sess, cstore, crate_name); // do not report any error now. since crate attributes are // not touched by expansion, every use of plugin without // the feature enabled will result in an error later... if sess.features_untracked().plugin { for attr in &krate.attrs { if!attr.check_name("plugin") { continue; } let plugins = match attr.meta_item_list() { Some(xs) => xs, None => { call_malformed_plugin_attribute(sess, attr.span); continue; } }; for plugin in plugins { // plugins must have a name and can't be key = value match plugin.name() { Some(name) if!plugin.is_value_str() => { let args = plugin.meta_item_list().map(ToOwned::to_owned); loader.load_plugin(plugin.span, &name.as_str(), args.unwrap_or_default()); }, _ => call_malformed_plugin_attribute(sess, attr.span), } } } } if let Some(plugins) = addl_plugins { for plugin in plugins { loader.load_plugin(DUMMY_SP, &plugin, vec![]); } } loader.plugins } impl<'a> PluginLoader<'a> { fn new(sess: &'a Session, cstore: &'a CStore, crate_name: &str) -> Self { PluginLoader { sess, reader: CrateLoader::new(sess, cstore, crate_name), plugins: vec![], } } fn load_plugin(&mut self, span: Span, name: &str, args: Vec<ast::NestedMetaItem>) { let registrar = self.reader.find_plugin_registrar(span, name); if let Some((lib, disambiguator)) = registrar
} // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, span: Span, path: PathBuf, symbol: String) -> PluginRegistrarFun { use rustc_metadata::dynamic_lib::DynamicLibrary; // Make sure the path contains a / or the linker will search for it. let path = env::current_dir().unwrap().join(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors Err(err) => { self.sess.span_fatal(span, &err) } }; unsafe { let registrar = match lib.symbol(&symbol) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => { self.sess.span_fatal(span, &err) } }; // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long // (e.g., an @-box cycle or a thread). mem::forget(lib); registrar } } }
{ let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator); let fun = self.dylink_registrar(span, lib, symbol); self.plugins.push(PluginRegistrar { fun, args, }); }
conditional_block
bracket-push.rs
extern crate bracket_push; use bracket_push::*; #[test] fn paired_square_brackets() { assert!(Brackets::from("[]").are_balanced()); } #[test] fn empty_string() { assert!(Brackets::from("").are_balanced()); } #[test] fn unpaired_brackets() { assert!(!Brackets::from("[[").are_balanced()); } #[test] fn wrong_ordered_brackets()
#[test] fn wrong_closing_bracket() { assert!(!Brackets::from("{]").are_balanced()); } #[test] fn paired_with_whitespace() { assert!(Brackets::from("{ }").are_balanced()); } #[test] fn simple_nested_brackets() { assert!(Brackets::from("{[]}").are_balanced()); } #[test] fn several_paired_brackets() { assert!(Brackets::from("{}[]").are_balanced()); } #[test] fn paired_and_nested_brackets() { assert!(Brackets::from("([{}({}[])])").are_balanced()); } #[test] fn unopened_closing_brackets() { assert!(!Brackets::from("{[)][]}").are_balanced()); } #[test] fn unpaired_and_nested_brackets() { assert!(!Brackets::from("([{])").are_balanced()); } #[test] fn paired_and_wrong_nested_brackets() { assert!(!Brackets::from("[({]})").are_balanced()); } #[test] fn math_expression() { assert!(Brackets::from("(((185 + 223.85) * 15) - 543)/2").are_balanced()); } #[test] fn complex_latex_expression() { let input = "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \ \\end{array}\\right)"; assert!(Brackets::from(input).are_balanced()); }
{ assert!(!Brackets::from("}{").are_balanced()); }
identifier_body
bracket-push.rs
extern crate bracket_push; use bracket_push::*; #[test] fn paired_square_brackets() { assert!(Brackets::from("[]").are_balanced()); } #[test] fn empty_string() { assert!(Brackets::from("").are_balanced()); } #[test] fn unpaired_brackets() { assert!(!Brackets::from("[[").are_balanced()); } #[test] fn wrong_ordered_brackets() { assert!(!Brackets::from("}{").are_balanced()); } #[test] fn wrong_closing_bracket() { assert!(!Brackets::from("{]").are_balanced()); } #[test] fn paired_with_whitespace() { assert!(Brackets::from("{ }").are_balanced()); } #[test] fn simple_nested_brackets() { assert!(Brackets::from("{[]}").are_balanced()); } #[test] fn several_paired_brackets() { assert!(Brackets::from("{}[]").are_balanced()); } #[test] fn paired_and_nested_brackets() { assert!(Brackets::from("([{}({}[])])").are_balanced()); } #[test] fn unopened_closing_brackets() { assert!(!Brackets::from("{[)][]}").are_balanced()); } #[test] fn unpaired_and_nested_brackets() { assert!(!Brackets::from("([{])").are_balanced()); } #[test] fn
() { assert!(!Brackets::from("[({]})").are_balanced()); } #[test] fn math_expression() { assert!(Brackets::from("(((185 + 223.85) * 15) - 543)/2").are_balanced()); } #[test] fn complex_latex_expression() { let input = "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \ \\end{array}\\right)"; assert!(Brackets::from(input).are_balanced()); }
paired_and_wrong_nested_brackets
identifier_name
bracket-push.rs
extern crate bracket_push; use bracket_push::*;
assert!(Brackets::from("[]").are_balanced()); } #[test] fn empty_string() { assert!(Brackets::from("").are_balanced()); } #[test] fn unpaired_brackets() { assert!(!Brackets::from("[[").are_balanced()); } #[test] fn wrong_ordered_brackets() { assert!(!Brackets::from("}{").are_balanced()); } #[test] fn wrong_closing_bracket() { assert!(!Brackets::from("{]").are_balanced()); } #[test] fn paired_with_whitespace() { assert!(Brackets::from("{ }").are_balanced()); } #[test] fn simple_nested_brackets() { assert!(Brackets::from("{[]}").are_balanced()); } #[test] fn several_paired_brackets() { assert!(Brackets::from("{}[]").are_balanced()); } #[test] fn paired_and_nested_brackets() { assert!(Brackets::from("([{}({}[])])").are_balanced()); } #[test] fn unopened_closing_brackets() { assert!(!Brackets::from("{[)][]}").are_balanced()); } #[test] fn unpaired_and_nested_brackets() { assert!(!Brackets::from("([{])").are_balanced()); } #[test] fn paired_and_wrong_nested_brackets() { assert!(!Brackets::from("[({]})").are_balanced()); } #[test] fn math_expression() { assert!(Brackets::from("(((185 + 223.85) * 15) - 543)/2").are_balanced()); } #[test] fn complex_latex_expression() { let input = "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \ \\end{array}\\right)"; assert!(Brackets::from(input).are_balanced()); }
#[test] fn paired_square_brackets() {
random_line_split