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
rust-picotcp-dhcpd.rs
#![feature(globs)] extern crate libc; extern crate picotcp; use picotcp::pico_ip4; use picotcp::pico_ip6; use picotcp::pico_dhcp_server::*; fn main() { /* Initialize stack */ let pico = picotcp::stack::new(); let my_ip_addr = pico_ip4::new("192.168.2.150"); let my_netmask = pico_ip4::new("255.255.255.0"); let my_ip6_addr = pico_ip6 { addr:[0xaa, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }; // Constructor is still WIP... let my_6_netmask = pico_ip6 { addr:[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0] }; let dhcp_start = pico_ip4::new("192.168.2.1"); let dhcp_end = pico_ip4::new("192.168.2.10"); let pico_dev_eth = picotcp::tap_create("tap0"); picotcp::ipv4_link_add(pico_dev_eth, my_ip_addr.clone(), my_netmask.clone()); picotcp::ipv6_link_add(pico_dev_eth, my_ip6_addr.clone(), my_6_netmask.clone()); println!("tap0: ip addr is {}", my_ip_addr.clone()); println!("tap0: ip6 addr is {}", my_ip6_addr); let mut settings : pico_dhcp_server_setting = pico_dhcp_server_setting { pool_start: dhcp_start.clone(), pool_next: dhcp_start, pool_end: dhcp_end, lease_time: 0, dev: pico_dev_eth, s: 0,
dhcp_server_initiate(&mut settings); pico.stack_loop(); }
server_ip: my_ip_addr, netmask: my_netmask, flags: 0 };
random_line_split
rust-picotcp-dhcpd.rs
#![feature(globs)] extern crate libc; extern crate picotcp; use picotcp::pico_ip4; use picotcp::pico_ip6; use picotcp::pico_dhcp_server::*; fn
() { /* Initialize stack */ let pico = picotcp::stack::new(); let my_ip_addr = pico_ip4::new("192.168.2.150"); let my_netmask = pico_ip4::new("255.255.255.0"); let my_ip6_addr = pico_ip6 { addr:[0xaa, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }; // Constructor is still WIP... let my_6_netmask = pico_ip6 { addr:[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0] }; let dhcp_start = pico_ip4::new("192.168.2.1"); let dhcp_end = pico_ip4::new("192.168.2.10"); let pico_dev_eth = picotcp::tap_create("tap0"); picotcp::ipv4_link_add(pico_dev_eth, my_ip_addr.clone(), my_netmask.clone()); picotcp::ipv6_link_add(pico_dev_eth, my_ip6_addr.clone(), my_6_netmask.clone()); println!("tap0: ip addr is {}", my_ip_addr.clone()); println!("tap0: ip6 addr is {}", my_ip6_addr); let mut settings : pico_dhcp_server_setting = pico_dhcp_server_setting { pool_start: dhcp_start.clone(), pool_next: dhcp_start, pool_end: dhcp_end, lease_time: 0, dev: pico_dev_eth, s: 0, server_ip: my_ip_addr, netmask: my_netmask, flags: 0 }; dhcp_server_initiate(&mut settings); pico.stack_loop(); }
main
identifier_name
rust-picotcp-dhcpd.rs
#![feature(globs)] extern crate libc; extern crate picotcp; use picotcp::pico_ip4; use picotcp::pico_ip6; use picotcp::pico_dhcp_server::*; fn main()
pool_start: dhcp_start.clone(), pool_next: dhcp_start, pool_end: dhcp_end, lease_time: 0, dev: pico_dev_eth, s: 0, server_ip: my_ip_addr, netmask: my_netmask, flags: 0 }; dhcp_server_initiate(&mut settings); pico.stack_loop(); }
{ /* Initialize stack */ let pico = picotcp::stack::new(); let my_ip_addr = pico_ip4::new("192.168.2.150"); let my_netmask = pico_ip4::new("255.255.255.0"); let my_ip6_addr = pico_ip6 { addr:[0xaa, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }; // Constructor is still WIP... let my_6_netmask = pico_ip6 { addr:[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0] }; let dhcp_start = pico_ip4::new("192.168.2.1"); let dhcp_end = pico_ip4::new("192.168.2.10"); let pico_dev_eth = picotcp::tap_create("tap0"); picotcp::ipv4_link_add(pico_dev_eth, my_ip_addr.clone(), my_netmask.clone()); picotcp::ipv6_link_add(pico_dev_eth, my_ip6_addr.clone(), my_6_netmask.clone()); println!("tap0: ip addr is {}", my_ip_addr.clone()); println!("tap0: ip6 addr is {}", my_ip6_addr); let mut settings : pico_dhcp_server_setting = pico_dhcp_server_setting {
identifier_body
huge-largest-array.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. // run-pass use std::mem::size_of; #[cfg(target_pointer_width = "32")] pub fn main() { assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1); } #[cfg(target_pointer_width = "64")] pub fn main()
{ assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1); }
identifier_body
huge-largest-array.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. // run-pass use std::mem::size_of; #[cfg(target_pointer_width = "32")] pub fn main() { assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1); } #[cfg(target_pointer_width = "64")] pub fn
() { assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1); }
main
identifier_name
huge-largest-array.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. // run-pass use std::mem::size_of; #[cfg(target_pointer_width = "32")] pub fn main() { assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1); } #[cfg(target_pointer_width = "64")] pub fn main() { assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1); }
random_line_split
namespaced-enum-glob-import-no-impls.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. mod m2 { pub enum Foo { A, B(isize), C { a: isize }, } impl Foo { pub fn foo() {} pub fn bar(&self) {} } } mod m { pub use m2::Foo::*; } pub fn main() { use m2::Foo::*; foo(); //~ ERROR unresolved name `foo` m::foo(); //~ ERROR unresolved name `m::foo` bar(); //~ ERROR unresolved name `bar`
}
m::bar(); //~ ERROR unresolved name `m::bar`
random_line_split
namespaced-enum-glob-import-no-impls.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. mod m2 { pub enum Foo { A, B(isize), C { a: isize }, } impl Foo { pub fn
() {} pub fn bar(&self) {} } } mod m { pub use m2::Foo::*; } pub fn main() { use m2::Foo::*; foo(); //~ ERROR unresolved name `foo` m::foo(); //~ ERROR unresolved name `m::foo` bar(); //~ ERROR unresolved name `bar` m::bar(); //~ ERROR unresolved name `m::bar` }
foo
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(step_trait)] #![deny(unsafe_code)] extern crate heapsize; #[macro_use] extern crate heapsize_derive; extern crate num_traits; extern crate rustc_serialize; extern crate serde; #[macro_use] extern crate serde_derive; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize { 0 } #[inline] fn one() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn
(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline] fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) } } impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?}.. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end() } /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool { self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I) { self.begin = begin; self.length = length; } #[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin { Range::empty() } else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
get
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(step_trait)] #![deny(unsafe_code)] extern crate heapsize; #[macro_use] extern crate heapsize_derive; extern crate num_traits; extern crate rustc_serialize; extern crate serde; #[macro_use] extern crate serde_derive; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize { 0 } #[inline] fn one() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn get(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline] fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) } } impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?}.. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end() } /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool { self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I) { self.begin = begin; self.length = length; } #[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin
else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
{ Range::empty() }
conditional_block
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(step_trait)] #![deny(unsafe_code)] extern crate heapsize; #[macro_use] extern crate heapsize_derive; extern crate num_traits; extern crate rustc_serialize; extern crate serde; #[macro_use] extern crate serde_derive; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize { 0 } #[inline] fn one() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn get(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline] fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) } } impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?}.. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end()
self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I) { self.begin = begin; self.length = length; } #[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin { Range::empty() } else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
} /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool {
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(step_trait)] #![deny(unsafe_code)] extern crate heapsize; #[macro_use] extern crate heapsize_derive; extern crate num_traits; extern crate rustc_serialize; extern crate serde; #[macro_use] extern crate serde_derive; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize
#[inline] fn one() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn get(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline] fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) } } impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?}.. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end() } /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool { self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I) { self.begin = begin; self.length = length; } #[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin { Range::empty() } else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
{ 0 }
identifier_body
highlight.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. //! Basic html highlighting functionality //! //! This module uses libsyntax's lexer to provide token-based highlighting for //! the HTML documentation generated by rustdoc. use std::io; use syntax::parse; use syntax::parse::lexer; use html::escape::Escape; use t = syntax::parse::token; /// Highlights some source code, returning the HTML output. pub fn
(src: &str, class: Option<&str>, id: Option<&str>) -> String { debug!("highlighting: ================\n{}\n==============", src); let sess = parse::new_parse_sess(); let fm = parse::string_to_filemap(&sess, src.to_string(), "<stdin>".to_string()); let mut out = io::MemWriter::new(); doit(&sess, lexer::StringReader::new(&sess.span_diagnostic, fm), class, id, &mut out).unwrap(); String::from_utf8_lossy(out.unwrap().as_slice()).into_string() } /// Exhausts the `lexer` writing the output into `out`. /// /// The general structure for this method is to iterate over each token, /// possibly giving it an HTML span with a class specifying what flavor of token /// it's used. All source code emission is done as slices from the source map, /// not from the tokens themselves, in order to stay true to the original /// source. fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>, id: Option<&str>, out: &mut Writer) -> io::IoResult<()> { use syntax::parse::lexer::Reader; try!(write!(out, "<pre ")); match id { Some(id) => try!(write!(out, "id='{}' ", id)), None => {} } try!(write!(out, "class='rust {}'>\n", class.unwrap_or(""))); let mut is_attribute = false; let mut is_macro = false; let mut is_macro_nonterminal = false; loop { let next = lexer.next_token(); let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap(); if next.tok == t::EOF { break } let klass = match next.tok { t::WS => { try!(write!(out, "{}", Escape(snip(next.sp).as_slice()))); continue }, t::COMMENT => { try!(write!(out, "<span class='comment'>{}</span>", Escape(snip(next.sp).as_slice()))); continue }, t::SHEBANG(s) => { try!(write!(out, "{}", Escape(s.as_str()))); continue }, // If this '&' token is directly adjacent to another token, assume // that it's the address-of operator instead of the and-operator. // This allows us to give all pointers their own class (`Box` and // `@` are below). t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2", t::AT | t::TILDE => "kw-2", // consider this as part of a macro invocation if there was a // leading identifier t::NOT if is_macro => { is_macro = false; "macro" } // operators t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT | t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW | t::BINOPEQ(..) | t::FAT_ARROW => "op", // miscellaneous, no highlighting t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI | t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN | t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "", t::DOLLAR => { if t::is_ident(&lexer.peek().tok) { is_macro_nonterminal = true; "macro-nonterminal" } else { "" } } // This is the start of an attribute. We're going to want to // continue highlighting it as an attribute until the ending ']' is // seen, so skip out early. Down below we terminate the attribute // span when we see the ']'. t::POUND => { is_attribute = true; try!(write!(out, r"<span class='attribute'>#")); continue } t::RBRACKET => { if is_attribute { is_attribute = false; try!(write!(out, "]</span>")); continue } else { "" } } // text literals t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) | t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string", // number literals t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number", // keywords are also included in the identifier set t::IDENT(ident, _is_mod_sep) => { match t::get_ident(ident).get() { "ref" | "mut" => "kw-2", "self" => "self", "false" | "true" => "boolval", "Option" | "Result" => "prelude-ty", "Some" | "None" | "Ok" | "Err" => "prelude-val", _ if t::is_any_keyword(&next.tok) => "kw", _ => { if is_macro_nonterminal { is_macro_nonterminal = false; "macro-nonterminal" } else if lexer.peek().tok == t::NOT { is_macro = true; "macro" } else { "ident" } } } } t::LIFETIME(..) => "lifetime", t::DOC_COMMENT(..) => "doccomment", t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "", }; // as mentioned above, use the original source code instead of // stringifying this token let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap(); if klass == "" { try!(write!(out, "{}", Escape(snip.as_slice()))); } else { try!(write!(out, "<span class='{}'>{}</span>", klass, Escape(snip.as_slice()))); } } write!(out, "</pre>\n") }
highlight
identifier_name
highlight.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. //! Basic html highlighting functionality //! //! This module uses libsyntax's lexer to provide token-based highlighting for //! the HTML documentation generated by rustdoc. use std::io; use syntax::parse; use syntax::parse::lexer; use html::escape::Escape; use t = syntax::parse::token; /// Highlights some source code, returning the HTML output. pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String { debug!("highlighting: ================\n{}\n==============", src); let sess = parse::new_parse_sess(); let fm = parse::string_to_filemap(&sess, src.to_string(), "<stdin>".to_string()); let mut out = io::MemWriter::new(); doit(&sess, lexer::StringReader::new(&sess.span_diagnostic, fm), class, id, &mut out).unwrap(); String::from_utf8_lossy(out.unwrap().as_slice()).into_string() } /// Exhausts the `lexer` writing the output into `out`. /// /// The general structure for this method is to iterate over each token, /// possibly giving it an HTML span with a class specifying what flavor of token /// it's used. All source code emission is done as slices from the source map, /// not from the tokens themselves, in order to stay true to the original /// source. fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>, id: Option<&str>, out: &mut Writer) -> io::IoResult<()> { use syntax::parse::lexer::Reader; try!(write!(out, "<pre ")); match id { Some(id) => try!(write!(out, "id='{}' ", id)), None => {} } try!(write!(out, "class='rust {}'>\n", class.unwrap_or(""))); let mut is_attribute = false; let mut is_macro = false; let mut is_macro_nonterminal = false; loop { let next = lexer.next_token(); let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap(); if next.tok == t::EOF { break } let klass = match next.tok { t::WS => { try!(write!(out, "{}", Escape(snip(next.sp).as_slice()))); continue }, t::COMMENT => { try!(write!(out, "<span class='comment'>{}</span>", Escape(snip(next.sp).as_slice()))); continue }, t::SHEBANG(s) => { try!(write!(out, "{}", Escape(s.as_str()))); continue }, // If this '&' token is directly adjacent to another token, assume // that it's the address-of operator instead of the and-operator. // This allows us to give all pointers their own class (`Box` and // `@` are below). t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2", t::AT | t::TILDE => "kw-2", // consider this as part of a macro invocation if there was a // leading identifier t::NOT if is_macro => { is_macro = false; "macro" } // operators t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT | t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW | t::BINOPEQ(..) | t::FAT_ARROW => "op", // miscellaneous, no highlighting t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI | t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN | t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "", t::DOLLAR => { if t::is_ident(&lexer.peek().tok) { is_macro_nonterminal = true; "macro-nonterminal" } else { "" } } // This is the start of an attribute. We're going to want to // continue highlighting it as an attribute until the ending ']' is // seen, so skip out early. Down below we terminate the attribute // span when we see the ']'. t::POUND => { is_attribute = true; try!(write!(out, r"<span class='attribute'>#")); continue } t::RBRACKET => { if is_attribute { is_attribute = false; try!(write!(out, "]</span>")); continue } else { ""
t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) | t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string", // number literals t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number", // keywords are also included in the identifier set t::IDENT(ident, _is_mod_sep) => { match t::get_ident(ident).get() { "ref" | "mut" => "kw-2", "self" => "self", "false" | "true" => "boolval", "Option" | "Result" => "prelude-ty", "Some" | "None" | "Ok" | "Err" => "prelude-val", _ if t::is_any_keyword(&next.tok) => "kw", _ => { if is_macro_nonterminal { is_macro_nonterminal = false; "macro-nonterminal" } else if lexer.peek().tok == t::NOT { is_macro = true; "macro" } else { "ident" } } } } t::LIFETIME(..) => "lifetime", t::DOC_COMMENT(..) => "doccomment", t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "", }; // as mentioned above, use the original source code instead of // stringifying this token let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap(); if klass == "" { try!(write!(out, "{}", Escape(snip.as_slice()))); } else { try!(write!(out, "<span class='{}'>{}</span>", klass, Escape(snip.as_slice()))); } } write!(out, "</pre>\n") }
} } // text literals
random_line_split
highlight.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. //! Basic html highlighting functionality //! //! This module uses libsyntax's lexer to provide token-based highlighting for //! the HTML documentation generated by rustdoc. use std::io; use syntax::parse; use syntax::parse::lexer; use html::escape::Escape; use t = syntax::parse::token; /// Highlights some source code, returning the HTML output. pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String
/// Exhausts the `lexer` writing the output into `out`. /// /// The general structure for this method is to iterate over each token, /// possibly giving it an HTML span with a class specifying what flavor of token /// it's used. All source code emission is done as slices from the source map, /// not from the tokens themselves, in order to stay true to the original /// source. fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>, id: Option<&str>, out: &mut Writer) -> io::IoResult<()> { use syntax::parse::lexer::Reader; try!(write!(out, "<pre ")); match id { Some(id) => try!(write!(out, "id='{}' ", id)), None => {} } try!(write!(out, "class='rust {}'>\n", class.unwrap_or(""))); let mut is_attribute = false; let mut is_macro = false; let mut is_macro_nonterminal = false; loop { let next = lexer.next_token(); let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap(); if next.tok == t::EOF { break } let klass = match next.tok { t::WS => { try!(write!(out, "{}", Escape(snip(next.sp).as_slice()))); continue }, t::COMMENT => { try!(write!(out, "<span class='comment'>{}</span>", Escape(snip(next.sp).as_slice()))); continue }, t::SHEBANG(s) => { try!(write!(out, "{}", Escape(s.as_str()))); continue }, // If this '&' token is directly adjacent to another token, assume // that it's the address-of operator instead of the and-operator. // This allows us to give all pointers their own class (`Box` and // `@` are below). t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2", t::AT | t::TILDE => "kw-2", // consider this as part of a macro invocation if there was a // leading identifier t::NOT if is_macro => { is_macro = false; "macro" } // operators t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT | t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW | t::BINOPEQ(..) | t::FAT_ARROW => "op", // miscellaneous, no highlighting t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI | t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN | t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "", t::DOLLAR => { if t::is_ident(&lexer.peek().tok) { is_macro_nonterminal = true; "macro-nonterminal" } else { "" } } // This is the start of an attribute. We're going to want to // continue highlighting it as an attribute until the ending ']' is // seen, so skip out early. Down below we terminate the attribute // span when we see the ']'. t::POUND => { is_attribute = true; try!(write!(out, r"<span class='attribute'>#")); continue } t::RBRACKET => { if is_attribute { is_attribute = false; try!(write!(out, "]</span>")); continue } else { "" } } // text literals t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) | t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string", // number literals t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number", // keywords are also included in the identifier set t::IDENT(ident, _is_mod_sep) => { match t::get_ident(ident).get() { "ref" | "mut" => "kw-2", "self" => "self", "false" | "true" => "boolval", "Option" | "Result" => "prelude-ty", "Some" | "None" | "Ok" | "Err" => "prelude-val", _ if t::is_any_keyword(&next.tok) => "kw", _ => { if is_macro_nonterminal { is_macro_nonterminal = false; "macro-nonterminal" } else if lexer.peek().tok == t::NOT { is_macro = true; "macro" } else { "ident" } } } } t::LIFETIME(..) => "lifetime", t::DOC_COMMENT(..) => "doccomment", t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "", }; // as mentioned above, use the original source code instead of // stringifying this token let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap(); if klass == "" { try!(write!(out, "{}", Escape(snip.as_slice()))); } else { try!(write!(out, "<span class='{}'>{}</span>", klass, Escape(snip.as_slice()))); } } write!(out, "</pre>\n") }
{ debug!("highlighting: ================\n{}\n==============", src); let sess = parse::new_parse_sess(); let fm = parse::string_to_filemap(&sess, src.to_string(), "<stdin>".to_string()); let mut out = io::MemWriter::new(); doit(&sess, lexer::StringReader::new(&sess.span_diagnostic, fm), class, id, &mut out).unwrap(); String::from_utf8_lossy(out.unwrap().as_slice()).into_string() }
identifier_body
task-comm-7.rs
// run-pass #![allow(unused_must_use)] #![allow(unused_assignments)] // ignore-emscripten no threads support use std::sync::mpsc::{channel, Sender}; use std::thread; pub fn main()
fn test00_start(c: &Sender<isize>, start: isize, number_of_messages: isize) { let mut i: isize = 0; while i < number_of_messages { c.send(start + i).unwrap(); i += 1; } } fn test00() { let mut r: isize = 0; let mut sum: isize = 0; let (tx, rx) = channel(); let number_of_messages: isize = 10; let tx2 = tx.clone(); let t1 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 0, number_of_messages); }); let tx2 = tx.clone(); let t2 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 1, number_of_messages); }); let tx2 = tx.clone(); let t3 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 2, number_of_messages); }); let tx2 = tx.clone(); let t4 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 3, number_of_messages); }); let mut i: isize = 0; while i < number_of_messages { r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; i += 1; } assert_eq!(sum, number_of_messages * 4 * (number_of_messages * 4 - 1) / 2); t1.join(); t2.join(); t3.join(); t4.join(); }
{ test00(); }
identifier_body
task-comm-7.rs
// run-pass #![allow(unused_must_use)] #![allow(unused_assignments)] // ignore-emscripten no threads support use std::sync::mpsc::{channel, Sender};
use std::thread; pub fn main() { test00(); } fn test00_start(c: &Sender<isize>, start: isize, number_of_messages: isize) { let mut i: isize = 0; while i < number_of_messages { c.send(start + i).unwrap(); i += 1; } } fn test00() { let mut r: isize = 0; let mut sum: isize = 0; let (tx, rx) = channel(); let number_of_messages: isize = 10; let tx2 = tx.clone(); let t1 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 0, number_of_messages); }); let tx2 = tx.clone(); let t2 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 1, number_of_messages); }); let tx2 = tx.clone(); let t3 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 2, number_of_messages); }); let tx2 = tx.clone(); let t4 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 3, number_of_messages); }); let mut i: isize = 0; while i < number_of_messages { r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; i += 1; } assert_eq!(sum, number_of_messages * 4 * (number_of_messages * 4 - 1) / 2); t1.join(); t2.join(); t3.join(); t4.join(); }
random_line_split
task-comm-7.rs
// run-pass #![allow(unused_must_use)] #![allow(unused_assignments)] // ignore-emscripten no threads support use std::sync::mpsc::{channel, Sender}; use std::thread; pub fn main() { test00(); } fn test00_start(c: &Sender<isize>, start: isize, number_of_messages: isize) { let mut i: isize = 0; while i < number_of_messages { c.send(start + i).unwrap(); i += 1; } } fn
() { let mut r: isize = 0; let mut sum: isize = 0; let (tx, rx) = channel(); let number_of_messages: isize = 10; let tx2 = tx.clone(); let t1 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 0, number_of_messages); }); let tx2 = tx.clone(); let t2 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 1, number_of_messages); }); let tx2 = tx.clone(); let t3 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 2, number_of_messages); }); let tx2 = tx.clone(); let t4 = thread::spawn(move|| { test00_start(&tx2, number_of_messages * 3, number_of_messages); }); let mut i: isize = 0; while i < number_of_messages { r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; r = rx.recv().unwrap(); sum += r; i += 1; } assert_eq!(sum, number_of_messages * 4 * (number_of_messages * 4 - 1) / 2); t1.join(); t2.join(); t3.join(); t4.join(); }
test00
identifier_name
vibrance.rs
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ip.rsh" float vibrance = 0.f; static const float Rf = 0.2999f; static const float Gf = 0.587f; static const float Bf = 0.114f; static float S = 0.f; static float MS = 0.f; static float Rt = 0.f; static float Gt = 0.f; static float Bt = 0.f; static float Vib = 0.f; void vibranceKernel(const uchar4 *in, uchar4 *out) { float R, G, B; int r = in->r; int g = in->g; int b = in->b; float red = (r-max(g, b))/256.f; float sx = (float)(Vib/(1+exp(-red*3))); S = sx+1; MS = 1.0f - S; Rt = Rf * MS; Gt = Gf * MS; Bt = Bf * MS; int t = (r + g) / 2;
B = b; float Rc = R * (Rt + S) + G * Gt + B * Bt; float Gc = R * Rt + G * (Gt + S) + B * Bt; float Bc = R * Rt + G * Gt + B * (Bt + S); out->r = rsClamp(Rc, 0, 255); out->g = rsClamp(Gc, 0, 255); out->b = rsClamp(Bc, 0, 255); } void prepareVibrance() { Vib = vibrance/100.f; S = Vib + 1; MS = 1.0f - S; Rt = Rf * MS; Gt = Gf * MS; Bt = Bf * MS; }
R = r; G = g;
random_line_split
message.rs
use std::str; use std::str::FromStr; use std::ascii::AsciiExt; use IterListHeader; use Error::{ForbiddenHeader, MissingHeader}; pub trait Message { fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>; fn contains_header(&self, &str) -> bool; fn get_value_header(&self, name: &str) -> Option<&[u8]> { let value_header = self.get_header(name); if value_header.is_none() || value_header.unwrap().len()!= 1 { return None; } Some(&value_header.unwrap()[0]) } fn get_list_header(&self, name: &str) -> Option<IterListHeader> { if let Some(values) = self.get_header(name) { Some(IterListHeader::new(values)) } else { None } } fn content_length(&self) -> ::Result<usize> { if self.contains_header("Transfer-Encoding") { return Err(ForbiddenHeader); } let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader)); FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from) } fn is_chunked(&self) -> bool
}
{ if let Some(values) = self.get_list_header("Transfer-Encoding") { for value in values { if value.eq_ignore_ascii_case(b"chunked") { return true } } } false }
identifier_body
message.rs
use std::str; use std::str::FromStr; use std::ascii::AsciiExt; use IterListHeader; use Error::{ForbiddenHeader, MissingHeader}; pub trait Message { fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>; fn contains_header(&self, &str) -> bool; fn
(&self, name: &str) -> Option<&[u8]> { let value_header = self.get_header(name); if value_header.is_none() || value_header.unwrap().len()!= 1 { return None; } Some(&value_header.unwrap()[0]) } fn get_list_header(&self, name: &str) -> Option<IterListHeader> { if let Some(values) = self.get_header(name) { Some(IterListHeader::new(values)) } else { None } } fn content_length(&self) -> ::Result<usize> { if self.contains_header("Transfer-Encoding") { return Err(ForbiddenHeader); } let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader)); FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from) } fn is_chunked(&self) -> bool { if let Some(values) = self.get_list_header("Transfer-Encoding") { for value in values { if value.eq_ignore_ascii_case(b"chunked") { return true } } } false } }
get_value_header
identifier_name
message.rs
use std::str; use std::str::FromStr; use std::ascii::AsciiExt; use IterListHeader; use Error::{ForbiddenHeader, MissingHeader}; pub trait Message { fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>; fn contains_header(&self, &str) -> bool; fn get_value_header(&self, name: &str) -> Option<&[u8]> { let value_header = self.get_header(name); if value_header.is_none() || value_header.unwrap().len()!= 1 { return None; } Some(&value_header.unwrap()[0]) } fn get_list_header(&self, name: &str) -> Option<IterListHeader> { if let Some(values) = self.get_header(name)
else { None } } fn content_length(&self) -> ::Result<usize> { if self.contains_header("Transfer-Encoding") { return Err(ForbiddenHeader); } let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader)); FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from) } fn is_chunked(&self) -> bool { if let Some(values) = self.get_list_header("Transfer-Encoding") { for value in values { if value.eq_ignore_ascii_case(b"chunked") { return true } } } false } }
{ Some(IterListHeader::new(values)) }
conditional_block
message.rs
use std::str; use std::str::FromStr; use std::ascii::AsciiExt; use IterListHeader; use Error::{ForbiddenHeader, MissingHeader}; pub trait Message { fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>; fn contains_header(&self, &str) -> bool; fn get_value_header(&self, name: &str) -> Option<&[u8]> { let value_header = self.get_header(name); if value_header.is_none() || value_header.unwrap().len()!= 1 { return None; } Some(&value_header.unwrap()[0]) } fn get_list_header(&self, name: &str) -> Option<IterListHeader> { if let Some(values) = self.get_header(name) { Some(IterListHeader::new(values)) } else { None } } fn content_length(&self) -> ::Result<usize> { if self.contains_header("Transfer-Encoding") {
let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader)); FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from) } fn is_chunked(&self) -> bool { if let Some(values) = self.get_list_header("Transfer-Encoding") { for value in values { if value.eq_ignore_ascii_case(b"chunked") { return true } } } false } }
return Err(ForbiddenHeader); }
random_line_split
executor.rs
use serde::{Serialize, Deserialize}; use std::mem; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::collections::HashMap; use amy; use slog; use time::Duration; use ferris::{Wheel, CopyWheel, Resolution}; use envelope::Envelope; use pid::Pid; use process::Process; use node_id::NodeId; use msg::Msg; use cluster::ClusterMsg; use correlation_id::CorrelationId; use metrics::Metrics; use super::{ExecutorStatus, ExecutorMetrics, ExecutorMsg}; pub struct
<T> { pid: Pid, node: NodeId, envelopes: Vec<Envelope<T>>, processes: HashMap<Pid, Box<Process<T>>>, service_senders: HashMap<Pid, amy::Sender<Envelope<T>>>, tx: Sender<ExecutorMsg<T>>, rx: Receiver<ExecutorMsg<T>>, cluster_tx: Sender<ClusterMsg<T>>, timer_wheel: CopyWheel<(Pid, Option<CorrelationId>)>, logger: slog::Logger, metrics: ExecutorMetrics } impl<'de, T: Serialize + Deserialize<'de> + Send + Debug + Clone> Executor<T> { pub fn new(node: NodeId, tx: Sender<ExecutorMsg<T>>, rx: Receiver<ExecutorMsg<T>>, cluster_tx: Sender<ClusterMsg<T>>, logger: slog::Logger) -> Executor<T> { let pid = Pid { group: Some("rabble".to_string()), name: "executor".to_string(), node: node.clone() }; Executor { pid: pid, node: node, envelopes: Vec::new(), processes: HashMap::new(), service_senders: HashMap::new(), tx: tx, rx: rx, cluster_tx: cluster_tx, timer_wheel: CopyWheel::new(vec![Resolution::TenMs, Resolution::Sec, Resolution::Min]), logger: logger.new(o!("component" => "executor")), metrics: ExecutorMetrics::new() } } /// Run the executor /// ///This call blocks the current thread indefinitely. pub fn run(mut self) { while let Ok(msg) = self.rx.recv() { match msg { ExecutorMsg::Envelope(envelope) => { self.metrics.received_envelopes += 1; self.route(envelope); }, ExecutorMsg::Start(pid, process) => self.start(pid, process), ExecutorMsg::Stop(pid) => self.stop(pid), ExecutorMsg::RegisterService(pid, tx) => { self.service_senders.insert(pid, tx); }, ExecutorMsg::GetStatus(correlation_id) => self.get_status(correlation_id), ExecutorMsg::Tick => self.tick(), // Just return so the thread exits ExecutorMsg::Shutdown => return } } } fn get_status(&self, correlation_id: CorrelationId) { let status = ExecutorStatus { total_processes: self.processes.len(), services: self.service_senders.keys().cloned().collect() }; let envelope = Envelope { to: correlation_id.pid.clone(), from: self.pid.clone(), msg: Msg::ExecutorStatus(status), correlation_id: Some(correlation_id) }; self.route_to_service(envelope); } fn start(&mut self, pid: Pid, mut process: Box<Process<T>>) { let envelopes = process.init(self.pid.clone()); self.processes.insert(pid, process); for envelope in envelopes { if envelope.to == self.pid { self.handle_executor_envelope(envelope); } else { self.route(envelope); } } } fn stop(&mut self, pid: Pid) { self.processes.remove(&pid); } fn tick(&mut self) { for (pid, c_id) in self.timer_wheel.expire() { let envelope = Envelope::new(pid, self.pid.clone(), Msg::Timeout, c_id); let _ = self.route_to_process(envelope); } } /// Route envelopes to local or remote processes /// /// Retrieve any envelopes from processes handling local messages and put them on either the /// executor or the cluster channel depending upon whether they are local or remote. /// /// Note that all envelopes sent to an executor are sent from the local cluster server and must /// be addressed to local processes. fn route(&mut self, envelope: Envelope<T>) { if self.node!= envelope.to.node { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); return; } if let Err(envelope) = self.route_to_process(envelope) { self.route_to_service(envelope); } } /// Route an envelope to a process if it exists on this node. /// /// Return Ok(()) if the process exists, Err(envelope) otherwise. fn route_to_process(&mut self, envelope: Envelope<T>) -> Result<(), Envelope<T>> { if envelope.to == self.pid { self.handle_executor_envelope(envelope); return Ok(()); } if &envelope.to.name == "cluster_server" && envelope.to.group.as_ref().unwrap() == "rabble" { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); return Ok(()); } if let Some(process) = self.processes.get_mut(&envelope.to) { let Envelope {from, msg, correlation_id,..} = envelope; process.handle(msg, from, correlation_id, &mut self.envelopes); } else { return Err(envelope); }; // Take envelopes out of self temporarily so we don't get a borrowck error let mut envelopes = mem::replace(&mut self.envelopes, Vec::new()); for envelope in envelopes.drain(..) { if envelope.to == self.pid { self.handle_executor_envelope(envelope); continue; } if envelope.to.node == self.node { // This won't ever fail because we hold a ref to both ends of the channel self.tx.send(ExecutorMsg::Envelope(envelope)).unwrap(); } else { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); } } // Return the allocated vec back to self let _ = mem::replace(&mut self.envelopes, envelopes); Ok(()) } /// Route an envelope to a service on this node fn route_to_service(&self, envelope: Envelope<T>) { if let Some(tx) = self.service_senders.get(&envelope.to) { tx.send(envelope).unwrap(); } else { warn!(self.logger, "Failed to find service"; "pid" => envelope.to.to_string()); } } fn handle_executor_envelope(&mut self, envelope: Envelope<T>) { let Envelope {from, msg, correlation_id,..} = envelope; match msg { Msg::StartTimer(time_in_ms) => { self.timer_wheel.start((from, correlation_id), Duration::milliseconds(time_in_ms as i64)); self.metrics.timers_started += 1; }, Msg::CancelTimer(correlation_id) => { self.timer_wheel.stop((from, correlation_id)); self.metrics.timers_cancelled += 1; } Msg::GetMetrics => self.send_metrics(from, correlation_id), _ => error!(self.logger, "Invalid message sent to executor"; "from" => from.to_string(), "msg" => format!("{:?}", msg)) } } fn send_metrics(&mut self, from: Pid, correlation_id: Option<CorrelationId>) { self.metrics.processes = self.processes.len() as i64; self.metrics.services = self.service_senders.len() as i64; let envelope = Envelope { to: from, from: self.pid.clone(), msg: Msg::Metrics(self.metrics.data()), correlation_id: correlation_id }; self.route(envelope); } }
Executor
identifier_name
executor.rs
use serde::{Serialize, Deserialize}; use std::mem; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::collections::HashMap; use amy; use slog; use time::Duration; use ferris::{Wheel, CopyWheel, Resolution}; use envelope::Envelope; use pid::Pid; use process::Process; use node_id::NodeId; use msg::Msg; use cluster::ClusterMsg; use correlation_id::CorrelationId; use metrics::Metrics; use super::{ExecutorStatus, ExecutorMetrics, ExecutorMsg}; pub struct Executor<T> { pid: Pid, node: NodeId, envelopes: Vec<Envelope<T>>, processes: HashMap<Pid, Box<Process<T>>>, service_senders: HashMap<Pid, amy::Sender<Envelope<T>>>, tx: Sender<ExecutorMsg<T>>, rx: Receiver<ExecutorMsg<T>>, cluster_tx: Sender<ClusterMsg<T>>, timer_wheel: CopyWheel<(Pid, Option<CorrelationId>)>, logger: slog::Logger, metrics: ExecutorMetrics } impl<'de, T: Serialize + Deserialize<'de> + Send + Debug + Clone> Executor<T> { pub fn new(node: NodeId, tx: Sender<ExecutorMsg<T>>, rx: Receiver<ExecutorMsg<T>>, cluster_tx: Sender<ClusterMsg<T>>, logger: slog::Logger) -> Executor<T> { let pid = Pid { group: Some("rabble".to_string()), name: "executor".to_string(), node: node.clone() }; Executor { pid: pid, node: node, envelopes: Vec::new(), processes: HashMap::new(), service_senders: HashMap::new(), tx: tx, rx: rx, cluster_tx: cluster_tx, timer_wheel: CopyWheel::new(vec![Resolution::TenMs, Resolution::Sec, Resolution::Min]), logger: logger.new(o!("component" => "executor")), metrics: ExecutorMetrics::new() } } /// Run the executor
match msg { ExecutorMsg::Envelope(envelope) => { self.metrics.received_envelopes += 1; self.route(envelope); }, ExecutorMsg::Start(pid, process) => self.start(pid, process), ExecutorMsg::Stop(pid) => self.stop(pid), ExecutorMsg::RegisterService(pid, tx) => { self.service_senders.insert(pid, tx); }, ExecutorMsg::GetStatus(correlation_id) => self.get_status(correlation_id), ExecutorMsg::Tick => self.tick(), // Just return so the thread exits ExecutorMsg::Shutdown => return } } } fn get_status(&self, correlation_id: CorrelationId) { let status = ExecutorStatus { total_processes: self.processes.len(), services: self.service_senders.keys().cloned().collect() }; let envelope = Envelope { to: correlation_id.pid.clone(), from: self.pid.clone(), msg: Msg::ExecutorStatus(status), correlation_id: Some(correlation_id) }; self.route_to_service(envelope); } fn start(&mut self, pid: Pid, mut process: Box<Process<T>>) { let envelopes = process.init(self.pid.clone()); self.processes.insert(pid, process); for envelope in envelopes { if envelope.to == self.pid { self.handle_executor_envelope(envelope); } else { self.route(envelope); } } } fn stop(&mut self, pid: Pid) { self.processes.remove(&pid); } fn tick(&mut self) { for (pid, c_id) in self.timer_wheel.expire() { let envelope = Envelope::new(pid, self.pid.clone(), Msg::Timeout, c_id); let _ = self.route_to_process(envelope); } } /// Route envelopes to local or remote processes /// /// Retrieve any envelopes from processes handling local messages and put them on either the /// executor or the cluster channel depending upon whether they are local or remote. /// /// Note that all envelopes sent to an executor are sent from the local cluster server and must /// be addressed to local processes. fn route(&mut self, envelope: Envelope<T>) { if self.node!= envelope.to.node { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); return; } if let Err(envelope) = self.route_to_process(envelope) { self.route_to_service(envelope); } } /// Route an envelope to a process if it exists on this node. /// /// Return Ok(()) if the process exists, Err(envelope) otherwise. fn route_to_process(&mut self, envelope: Envelope<T>) -> Result<(), Envelope<T>> { if envelope.to == self.pid { self.handle_executor_envelope(envelope); return Ok(()); } if &envelope.to.name == "cluster_server" && envelope.to.group.as_ref().unwrap() == "rabble" { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); return Ok(()); } if let Some(process) = self.processes.get_mut(&envelope.to) { let Envelope {from, msg, correlation_id,..} = envelope; process.handle(msg, from, correlation_id, &mut self.envelopes); } else { return Err(envelope); }; // Take envelopes out of self temporarily so we don't get a borrowck error let mut envelopes = mem::replace(&mut self.envelopes, Vec::new()); for envelope in envelopes.drain(..) { if envelope.to == self.pid { self.handle_executor_envelope(envelope); continue; } if envelope.to.node == self.node { // This won't ever fail because we hold a ref to both ends of the channel self.tx.send(ExecutorMsg::Envelope(envelope)).unwrap(); } else { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); } } // Return the allocated vec back to self let _ = mem::replace(&mut self.envelopes, envelopes); Ok(()) } /// Route an envelope to a service on this node fn route_to_service(&self, envelope: Envelope<T>) { if let Some(tx) = self.service_senders.get(&envelope.to) { tx.send(envelope).unwrap(); } else { warn!(self.logger, "Failed to find service"; "pid" => envelope.to.to_string()); } } fn handle_executor_envelope(&mut self, envelope: Envelope<T>) { let Envelope {from, msg, correlation_id,..} = envelope; match msg { Msg::StartTimer(time_in_ms) => { self.timer_wheel.start((from, correlation_id), Duration::milliseconds(time_in_ms as i64)); self.metrics.timers_started += 1; }, Msg::CancelTimer(correlation_id) => { self.timer_wheel.stop((from, correlation_id)); self.metrics.timers_cancelled += 1; } Msg::GetMetrics => self.send_metrics(from, correlation_id), _ => error!(self.logger, "Invalid message sent to executor"; "from" => from.to_string(), "msg" => format!("{:?}", msg)) } } fn send_metrics(&mut self, from: Pid, correlation_id: Option<CorrelationId>) { self.metrics.processes = self.processes.len() as i64; self.metrics.services = self.service_senders.len() as i64; let envelope = Envelope { to: from, from: self.pid.clone(), msg: Msg::Metrics(self.metrics.data()), correlation_id: correlation_id }; self.route(envelope); } }
/// ///This call blocks the current thread indefinitely. pub fn run(mut self) { while let Ok(msg) = self.rx.recv() {
random_line_split
executor.rs
use serde::{Serialize, Deserialize}; use std::mem; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::collections::HashMap; use amy; use slog; use time::Duration; use ferris::{Wheel, CopyWheel, Resolution}; use envelope::Envelope; use pid::Pid; use process::Process; use node_id::NodeId; use msg::Msg; use cluster::ClusterMsg; use correlation_id::CorrelationId; use metrics::Metrics; use super::{ExecutorStatus, ExecutorMetrics, ExecutorMsg}; pub struct Executor<T> { pid: Pid, node: NodeId, envelopes: Vec<Envelope<T>>, processes: HashMap<Pid, Box<Process<T>>>, service_senders: HashMap<Pid, amy::Sender<Envelope<T>>>, tx: Sender<ExecutorMsg<T>>, rx: Receiver<ExecutorMsg<T>>, cluster_tx: Sender<ClusterMsg<T>>, timer_wheel: CopyWheel<(Pid, Option<CorrelationId>)>, logger: slog::Logger, metrics: ExecutorMetrics } impl<'de, T: Serialize + Deserialize<'de> + Send + Debug + Clone> Executor<T> { pub fn new(node: NodeId, tx: Sender<ExecutorMsg<T>>, rx: Receiver<ExecutorMsg<T>>, cluster_tx: Sender<ClusterMsg<T>>, logger: slog::Logger) -> Executor<T> { let pid = Pid { group: Some("rabble".to_string()), name: "executor".to_string(), node: node.clone() }; Executor { pid: pid, node: node, envelopes: Vec::new(), processes: HashMap::new(), service_senders: HashMap::new(), tx: tx, rx: rx, cluster_tx: cluster_tx, timer_wheel: CopyWheel::new(vec![Resolution::TenMs, Resolution::Sec, Resolution::Min]), logger: logger.new(o!("component" => "executor")), metrics: ExecutorMetrics::new() } } /// Run the executor /// ///This call blocks the current thread indefinitely. pub fn run(mut self) { while let Ok(msg) = self.rx.recv() { match msg { ExecutorMsg::Envelope(envelope) => { self.metrics.received_envelopes += 1; self.route(envelope); }, ExecutorMsg::Start(pid, process) => self.start(pid, process), ExecutorMsg::Stop(pid) => self.stop(pid), ExecutorMsg::RegisterService(pid, tx) => { self.service_senders.insert(pid, tx); }, ExecutorMsg::GetStatus(correlation_id) => self.get_status(correlation_id), ExecutorMsg::Tick => self.tick(), // Just return so the thread exits ExecutorMsg::Shutdown => return } } } fn get_status(&self, correlation_id: CorrelationId) { let status = ExecutorStatus { total_processes: self.processes.len(), services: self.service_senders.keys().cloned().collect() }; let envelope = Envelope { to: correlation_id.pid.clone(), from: self.pid.clone(), msg: Msg::ExecutorStatus(status), correlation_id: Some(correlation_id) }; self.route_to_service(envelope); } fn start(&mut self, pid: Pid, mut process: Box<Process<T>>) { let envelopes = process.init(self.pid.clone()); self.processes.insert(pid, process); for envelope in envelopes { if envelope.to == self.pid { self.handle_executor_envelope(envelope); } else { self.route(envelope); } } } fn stop(&mut self, pid: Pid) { self.processes.remove(&pid); } fn tick(&mut self)
/// Route envelopes to local or remote processes /// /// Retrieve any envelopes from processes handling local messages and put them on either the /// executor or the cluster channel depending upon whether they are local or remote. /// /// Note that all envelopes sent to an executor are sent from the local cluster server and must /// be addressed to local processes. fn route(&mut self, envelope: Envelope<T>) { if self.node!= envelope.to.node { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); return; } if let Err(envelope) = self.route_to_process(envelope) { self.route_to_service(envelope); } } /// Route an envelope to a process if it exists on this node. /// /// Return Ok(()) if the process exists, Err(envelope) otherwise. fn route_to_process(&mut self, envelope: Envelope<T>) -> Result<(), Envelope<T>> { if envelope.to == self.pid { self.handle_executor_envelope(envelope); return Ok(()); } if &envelope.to.name == "cluster_server" && envelope.to.group.as_ref().unwrap() == "rabble" { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); return Ok(()); } if let Some(process) = self.processes.get_mut(&envelope.to) { let Envelope {from, msg, correlation_id,..} = envelope; process.handle(msg, from, correlation_id, &mut self.envelopes); } else { return Err(envelope); }; // Take envelopes out of self temporarily so we don't get a borrowck error let mut envelopes = mem::replace(&mut self.envelopes, Vec::new()); for envelope in envelopes.drain(..) { if envelope.to == self.pid { self.handle_executor_envelope(envelope); continue; } if envelope.to.node == self.node { // This won't ever fail because we hold a ref to both ends of the channel self.tx.send(ExecutorMsg::Envelope(envelope)).unwrap(); } else { self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap(); } } // Return the allocated vec back to self let _ = mem::replace(&mut self.envelopes, envelopes); Ok(()) } /// Route an envelope to a service on this node fn route_to_service(&self, envelope: Envelope<T>) { if let Some(tx) = self.service_senders.get(&envelope.to) { tx.send(envelope).unwrap(); } else { warn!(self.logger, "Failed to find service"; "pid" => envelope.to.to_string()); } } fn handle_executor_envelope(&mut self, envelope: Envelope<T>) { let Envelope {from, msg, correlation_id,..} = envelope; match msg { Msg::StartTimer(time_in_ms) => { self.timer_wheel.start((from, correlation_id), Duration::milliseconds(time_in_ms as i64)); self.metrics.timers_started += 1; }, Msg::CancelTimer(correlation_id) => { self.timer_wheel.stop((from, correlation_id)); self.metrics.timers_cancelled += 1; } Msg::GetMetrics => self.send_metrics(from, correlation_id), _ => error!(self.logger, "Invalid message sent to executor"; "from" => from.to_string(), "msg" => format!("{:?}", msg)) } } fn send_metrics(&mut self, from: Pid, correlation_id: Option<CorrelationId>) { self.metrics.processes = self.processes.len() as i64; self.metrics.services = self.service_senders.len() as i64; let envelope = Envelope { to: from, from: self.pid.clone(), msg: Msg::Metrics(self.metrics.data()), correlation_id: correlation_id }; self.route(envelope); } }
{ for (pid, c_id) in self.timer_wheel.expire() { let envelope = Envelope::new(pid, self.pid.clone(), Msg::Timeout, c_id); let _ = self.route_to_process(envelope); } }
identifier_body
gcthread.rs
//! Garbage collection thread use std::any::Any; use std::cmp::min; use std::mem::size_of; use std::sync::mpsc; use std::thread; use std::time::Duration; use num_cpus; use scoped_pool::Pool; use appthread::AppThread; use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR}; use heap::{CollectOps, Object}; use journal; use parheap::ParHeap; use statistics::{StatsLogger, DefaultLogger}; use youngheap::YoungHeap; pub type EntryReceiver = journal::Receiver<Object>; pub type EntrySender = journal::Sender<Object>; pub type JournalReceiver = mpsc::Receiver<EntryReceiver>; pub type JournalSender = mpsc::Sender<EntryReceiver>; pub type JournalList = Vec<EntryReceiver>; /// The Garbage Collection thread handle. pub struct GcThread<S: StatsLogger> { /// This is cloned and given to app threads. tx_chan: JournalSender, /// The GC thread's handle to join on. handle: thread::JoinHandle<S>, } impl GcThread<DefaultLogger> { /// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized /// across all available CPUs. pub fn spawn_gc() -> GcThread<DefaultLogger> { let cores = num_cpus::get(); Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new()) } } impl<S: StatsLogger +'static> GcThread<S> { /// Run the GC on the current thread, spawning another thread to run the application function /// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom /// StatsLogger implementation and a CollectOps heap implementation. pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S> where T: CollectOps + Send +'static { let (tx, rx) = mpsc::channel(); let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger)); GcThread { tx_chan: tx, handle: handle, } } /// Spawn an app thread that journals to the GC thread. pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static { AppThread::spawn_from_gc(self.tx_chan.clone(), f) } /// Wait for the GC thread to finish. On success, returns the object that implements /// `StatsLogger` for the calling thread to examine. pub fn join(self) -> Result<S, Box<Any + Send +'static>> { self.handle.join() } } /// Main GC thread loop. fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S where S: StatsLogger, T: CollectOps + Send { let mut pool = Pool::new(num_threads); let mut gc = YoungHeap::new(num_threads, mature, logger); // block, wait for first journal gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!")); gc.logger().mark_start_time(); // next duration to sleep if all journals are empty let mut sleep_dur: usize = 0; // loop until all journals are disconnected while gc.num_journals() > 0 { // new appthread connected if let Ok(journal) = rx_chan.try_recv() { gc.add_journal(journal); } let entries_read = gc.read_journals(); // sleep if nothing read from journal if entries_read == 0 { thread::sleep(Duration::from_millis(sleep_dur as u64)); gc.logger().add_sleep(sleep_dur); // back off exponentially up to the max sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR); } else { // reset next sleep duration on receiving no entries sleep_dur = MIN_SLEEP_DUR; } // TODO: base this call on a duration since last call? let young_count = gc.minor_collection(&mut pool); // do a major collection if the young count reaches a threshold and we're not just trying // to keep up with the app threads // TODO: force a major collection every n minutes if sleep_dur!= MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD { gc.major_collection(&mut pool); } } // do a final collection where all roots should be unrooted gc.minor_collection(&mut pool); gc.major_collection(&mut pool); // return logger to calling thread gc.logger().mark_end_time(); gc.shutdown() } /// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending /// on the word size. #[inline]
3 } }
pub fn ptr_shift() -> i32 { if size_of::<usize>() == 32 { 2 } else {
random_line_split
gcthread.rs
//! Garbage collection thread use std::any::Any; use std::cmp::min; use std::mem::size_of; use std::sync::mpsc; use std::thread; use std::time::Duration; use num_cpus; use scoped_pool::Pool; use appthread::AppThread; use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR}; use heap::{CollectOps, Object}; use journal; use parheap::ParHeap; use statistics::{StatsLogger, DefaultLogger}; use youngheap::YoungHeap; pub type EntryReceiver = journal::Receiver<Object>; pub type EntrySender = journal::Sender<Object>; pub type JournalReceiver = mpsc::Receiver<EntryReceiver>; pub type JournalSender = mpsc::Sender<EntryReceiver>; pub type JournalList = Vec<EntryReceiver>; /// The Garbage Collection thread handle. pub struct GcThread<S: StatsLogger> { /// This is cloned and given to app threads. tx_chan: JournalSender, /// The GC thread's handle to join on. handle: thread::JoinHandle<S>, } impl GcThread<DefaultLogger> { /// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized /// across all available CPUs. pub fn spawn_gc() -> GcThread<DefaultLogger> { let cores = num_cpus::get(); Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new()) } } impl<S: StatsLogger +'static> GcThread<S> { /// Run the GC on the current thread, spawning another thread to run the application function /// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom /// StatsLogger implementation and a CollectOps heap implementation. pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S> where T: CollectOps + Send +'static { let (tx, rx) = mpsc::channel(); let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger)); GcThread { tx_chan: tx, handle: handle, } } /// Spawn an app thread that journals to the GC thread. pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static { AppThread::spawn_from_gc(self.tx_chan.clone(), f) } /// Wait for the GC thread to finish. On success, returns the object that implements /// `StatsLogger` for the calling thread to examine. pub fn join(self) -> Result<S, Box<Any + Send +'static>> { self.handle.join() } } /// Main GC thread loop. fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S where S: StatsLogger, T: CollectOps + Send { let mut pool = Pool::new(num_threads); let mut gc = YoungHeap::new(num_threads, mature, logger); // block, wait for first journal gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!")); gc.logger().mark_start_time(); // next duration to sleep if all journals are empty let mut sleep_dur: usize = 0; // loop until all journals are disconnected while gc.num_journals() > 0 { // new appthread connected if let Ok(journal) = rx_chan.try_recv() { gc.add_journal(journal); } let entries_read = gc.read_journals(); // sleep if nothing read from journal if entries_read == 0 { thread::sleep(Duration::from_millis(sleep_dur as u64)); gc.logger().add_sleep(sleep_dur); // back off exponentially up to the max sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR); } else
// TODO: base this call on a duration since last call? let young_count = gc.minor_collection(&mut pool); // do a major collection if the young count reaches a threshold and we're not just trying // to keep up with the app threads // TODO: force a major collection every n minutes if sleep_dur!= MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD { gc.major_collection(&mut pool); } } // do a final collection where all roots should be unrooted gc.minor_collection(&mut pool); gc.major_collection(&mut pool); // return logger to calling thread gc.logger().mark_end_time(); gc.shutdown() } /// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending /// on the word size. #[inline] pub fn ptr_shift() -> i32 { if size_of::<usize>() == 32 { 2 } else { 3 } }
{ // reset next sleep duration on receiving no entries sleep_dur = MIN_SLEEP_DUR; }
conditional_block
gcthread.rs
//! Garbage collection thread use std::any::Any; use std::cmp::min; use std::mem::size_of; use std::sync::mpsc; use std::thread; use std::time::Duration; use num_cpus; use scoped_pool::Pool; use appthread::AppThread; use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR}; use heap::{CollectOps, Object}; use journal; use parheap::ParHeap; use statistics::{StatsLogger, DefaultLogger}; use youngheap::YoungHeap; pub type EntryReceiver = journal::Receiver<Object>; pub type EntrySender = journal::Sender<Object>; pub type JournalReceiver = mpsc::Receiver<EntryReceiver>; pub type JournalSender = mpsc::Sender<EntryReceiver>; pub type JournalList = Vec<EntryReceiver>; /// The Garbage Collection thread handle. pub struct GcThread<S: StatsLogger> { /// This is cloned and given to app threads. tx_chan: JournalSender, /// The GC thread's handle to join on. handle: thread::JoinHandle<S>, } impl GcThread<DefaultLogger> { /// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized /// across all available CPUs. pub fn spawn_gc() -> GcThread<DefaultLogger> { let cores = num_cpus::get(); Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new()) } } impl<S: StatsLogger +'static> GcThread<S> { /// Run the GC on the current thread, spawning another thread to run the application function /// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom /// StatsLogger implementation and a CollectOps heap implementation. pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S> where T: CollectOps + Send +'static { let (tx, rx) = mpsc::channel(); let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger)); GcThread { tx_chan: tx, handle: handle, } } /// Spawn an app thread that journals to the GC thread. pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static
/// Wait for the GC thread to finish. On success, returns the object that implements /// `StatsLogger` for the calling thread to examine. pub fn join(self) -> Result<S, Box<Any + Send +'static>> { self.handle.join() } } /// Main GC thread loop. fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S where S: StatsLogger, T: CollectOps + Send { let mut pool = Pool::new(num_threads); let mut gc = YoungHeap::new(num_threads, mature, logger); // block, wait for first journal gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!")); gc.logger().mark_start_time(); // next duration to sleep if all journals are empty let mut sleep_dur: usize = 0; // loop until all journals are disconnected while gc.num_journals() > 0 { // new appthread connected if let Ok(journal) = rx_chan.try_recv() { gc.add_journal(journal); } let entries_read = gc.read_journals(); // sleep if nothing read from journal if entries_read == 0 { thread::sleep(Duration::from_millis(sleep_dur as u64)); gc.logger().add_sleep(sleep_dur); // back off exponentially up to the max sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR); } else { // reset next sleep duration on receiving no entries sleep_dur = MIN_SLEEP_DUR; } // TODO: base this call on a duration since last call? let young_count = gc.minor_collection(&mut pool); // do a major collection if the young count reaches a threshold and we're not just trying // to keep up with the app threads // TODO: force a major collection every n minutes if sleep_dur!= MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD { gc.major_collection(&mut pool); } } // do a final collection where all roots should be unrooted gc.minor_collection(&mut pool); gc.major_collection(&mut pool); // return logger to calling thread gc.logger().mark_end_time(); gc.shutdown() } /// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending /// on the word size. #[inline] pub fn ptr_shift() -> i32 { if size_of::<usize>() == 32 { 2 } else { 3 } }
{ AppThread::spawn_from_gc(self.tx_chan.clone(), f) }
identifier_body
gcthread.rs
//! Garbage collection thread use std::any::Any; use std::cmp::min; use std::mem::size_of; use std::sync::mpsc; use std::thread; use std::time::Duration; use num_cpus; use scoped_pool::Pool; use appthread::AppThread; use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR}; use heap::{CollectOps, Object}; use journal; use parheap::ParHeap; use statistics::{StatsLogger, DefaultLogger}; use youngheap::YoungHeap; pub type EntryReceiver = journal::Receiver<Object>; pub type EntrySender = journal::Sender<Object>; pub type JournalReceiver = mpsc::Receiver<EntryReceiver>; pub type JournalSender = mpsc::Sender<EntryReceiver>; pub type JournalList = Vec<EntryReceiver>; /// The Garbage Collection thread handle. pub struct
<S: StatsLogger> { /// This is cloned and given to app threads. tx_chan: JournalSender, /// The GC thread's handle to join on. handle: thread::JoinHandle<S>, } impl GcThread<DefaultLogger> { /// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized /// across all available CPUs. pub fn spawn_gc() -> GcThread<DefaultLogger> { let cores = num_cpus::get(); Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new()) } } impl<S: StatsLogger +'static> GcThread<S> { /// Run the GC on the current thread, spawning another thread to run the application function /// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom /// StatsLogger implementation and a CollectOps heap implementation. pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S> where T: CollectOps + Send +'static { let (tx, rx) = mpsc::channel(); let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger)); GcThread { tx_chan: tx, handle: handle, } } /// Spawn an app thread that journals to the GC thread. pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T> where F: FnOnce() -> T, F: Send +'static, T: Send +'static { AppThread::spawn_from_gc(self.tx_chan.clone(), f) } /// Wait for the GC thread to finish. On success, returns the object that implements /// `StatsLogger` for the calling thread to examine. pub fn join(self) -> Result<S, Box<Any + Send +'static>> { self.handle.join() } } /// Main GC thread loop. fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S where S: StatsLogger, T: CollectOps + Send { let mut pool = Pool::new(num_threads); let mut gc = YoungHeap::new(num_threads, mature, logger); // block, wait for first journal gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!")); gc.logger().mark_start_time(); // next duration to sleep if all journals are empty let mut sleep_dur: usize = 0; // loop until all journals are disconnected while gc.num_journals() > 0 { // new appthread connected if let Ok(journal) = rx_chan.try_recv() { gc.add_journal(journal); } let entries_read = gc.read_journals(); // sleep if nothing read from journal if entries_read == 0 { thread::sleep(Duration::from_millis(sleep_dur as u64)); gc.logger().add_sleep(sleep_dur); // back off exponentially up to the max sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR); } else { // reset next sleep duration on receiving no entries sleep_dur = MIN_SLEEP_DUR; } // TODO: base this call on a duration since last call? let young_count = gc.minor_collection(&mut pool); // do a major collection if the young count reaches a threshold and we're not just trying // to keep up with the app threads // TODO: force a major collection every n minutes if sleep_dur!= MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD { gc.major_collection(&mut pool); } } // do a final collection where all roots should be unrooted gc.minor_collection(&mut pool); gc.major_collection(&mut pool); // return logger to calling thread gc.logger().mark_end_time(); gc.shutdown() } /// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending /// on the word size. #[inline] pub fn ptr_shift() -> i32 { if size_of::<usize>() == 32 { 2 } else { 3 } }
GcThread
identifier_name
main.rs
use std::error::Error; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::Path; use std::collections::HashMap; extern crate regex; use regex::Regex; enum Ineq { Equals(i32), GreaterThan(i32), LessThan(i32), } // -------------------------------------------------------- fn find_sue (constraints: &HashMap<&str, Ineq>, filename: &str) -> i32 { let path = Path::new(filename); let display = path.display(); // Open the path in read-only mode, returns `io::Result<File>` let file = match File::open(&path) { // The `description` method of `io::Error` returns a string that describes the error Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)), Ok(file) => file, };
let reader = BufReader::new(file); let lines = reader.lines(); let re = Regex::new(r"(?P<key>[:alpha:]+): (?P<value>\d+)").unwrap(); let mut sue_num = 0; let mut sue_no_conflict = -1i32; for line in lines { let text = line.unwrap(); sue_num += 1; let mut has_conflict = false; for cap in re.captures_iter(&text) { let key = cap.name("key").unwrap_or(""); let value = cap.name("value").unwrap_or("").parse::<i32>().unwrap(); match constraints.get(&key) { Some(&Ineq::Equals(present_value)) => { if value!= present_value { has_conflict = true; } }, Some(&Ineq::GreaterThan(present_value)) => { if value <= present_value { has_conflict = true; } }, Some(&Ineq::LessThan(present_value)) => { if value >= present_value { has_conflict = true; } }, _ => {}, } } if!has_conflict { println!("Sue {} has no conflicts", sue_num); sue_no_conflict = sue_num; } } sue_no_conflict } // -------------------------------------------------------- fn main() { println!("Running part 1..."); let mut sue_stats_exact = HashMap::new(); sue_stats_exact.insert("children", Ineq::Equals(3) ); sue_stats_exact.insert("cats", Ineq::Equals(7) ); sue_stats_exact.insert("samoyeds", Ineq::Equals(2) ); sue_stats_exact.insert("pomeranians", Ineq::Equals(3) ); sue_stats_exact.insert("akitas", Ineq::Equals(0) ); sue_stats_exact.insert("vizslas", Ineq::Equals(0) ); sue_stats_exact.insert("goldfish", Ineq::Equals(5) ); sue_stats_exact.insert("trees", Ineq::Equals(3) ); sue_stats_exact.insert("cars", Ineq::Equals(2) ); sue_stats_exact.insert("perfumes", Ineq::Equals(1) ); find_sue(&sue_stats_exact, "day16.txt"); println!("Running part 2..."); let mut sue_stats_ineq = HashMap::new(); sue_stats_ineq.insert("children", Ineq::Equals(3) ); sue_stats_ineq.insert("cats", Ineq::GreaterThan(7) ); sue_stats_ineq.insert("samoyeds", Ineq::Equals(2) ); sue_stats_ineq.insert("pomeranians", Ineq::LessThan(3) ); sue_stats_ineq.insert("akitas", Ineq::Equals(0) ); sue_stats_ineq.insert("vizslas", Ineq::Equals(0) ); sue_stats_ineq.insert("goldfish", Ineq::LessThan(5) ); sue_stats_ineq.insert("trees", Ineq::GreaterThan(3) ); sue_stats_ineq.insert("cars", Ineq::Equals(2) ); sue_stats_ineq.insert("perfumes", Ineq::Equals(1) ); find_sue(&sue_stats_ineq, "day16.txt"); }
random_line_split
main.rs
use std::error::Error; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::Path; use std::collections::HashMap; extern crate regex; use regex::Regex; enum Ineq { Equals(i32), GreaterThan(i32), LessThan(i32), } // -------------------------------------------------------- fn find_sue (constraints: &HashMap<&str, Ineq>, filename: &str) -> i32 { let path = Path::new(filename); let display = path.display(); // Open the path in read-only mode, returns `io::Result<File>` let file = match File::open(&path) { // The `description` method of `io::Error` returns a string that describes the error Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)), Ok(file) => file, }; let reader = BufReader::new(file); let lines = reader.lines(); let re = Regex::new(r"(?P<key>[:alpha:]+): (?P<value>\d+)").unwrap(); let mut sue_num = 0; let mut sue_no_conflict = -1i32; for line in lines { let text = line.unwrap(); sue_num += 1; let mut has_conflict = false; for cap in re.captures_iter(&text) { let key = cap.name("key").unwrap_or(""); let value = cap.name("value").unwrap_or("").parse::<i32>().unwrap(); match constraints.get(&key) { Some(&Ineq::Equals(present_value)) => { if value!= present_value { has_conflict = true; } }, Some(&Ineq::GreaterThan(present_value)) => { if value <= present_value { has_conflict = true; } }, Some(&Ineq::LessThan(present_value)) => { if value >= present_value
}, _ => {}, } } if!has_conflict { println!("Sue {} has no conflicts", sue_num); sue_no_conflict = sue_num; } } sue_no_conflict } // -------------------------------------------------------- fn main() { println!("Running part 1..."); let mut sue_stats_exact = HashMap::new(); sue_stats_exact.insert("children", Ineq::Equals(3) ); sue_stats_exact.insert("cats", Ineq::Equals(7) ); sue_stats_exact.insert("samoyeds", Ineq::Equals(2) ); sue_stats_exact.insert("pomeranians", Ineq::Equals(3) ); sue_stats_exact.insert("akitas", Ineq::Equals(0) ); sue_stats_exact.insert("vizslas", Ineq::Equals(0) ); sue_stats_exact.insert("goldfish", Ineq::Equals(5) ); sue_stats_exact.insert("trees", Ineq::Equals(3) ); sue_stats_exact.insert("cars", Ineq::Equals(2) ); sue_stats_exact.insert("perfumes", Ineq::Equals(1) ); find_sue(&sue_stats_exact, "day16.txt"); println!("Running part 2..."); let mut sue_stats_ineq = HashMap::new(); sue_stats_ineq.insert("children", Ineq::Equals(3) ); sue_stats_ineq.insert("cats", Ineq::GreaterThan(7) ); sue_stats_ineq.insert("samoyeds", Ineq::Equals(2) ); sue_stats_ineq.insert("pomeranians", Ineq::LessThan(3) ); sue_stats_ineq.insert("akitas", Ineq::Equals(0) ); sue_stats_ineq.insert("vizslas", Ineq::Equals(0) ); sue_stats_ineq.insert("goldfish", Ineq::LessThan(5) ); sue_stats_ineq.insert("trees", Ineq::GreaterThan(3) ); sue_stats_ineq.insert("cars", Ineq::Equals(2) ); sue_stats_ineq.insert("perfumes", Ineq::Equals(1) ); find_sue(&sue_stats_ineq, "day16.txt"); }
{ has_conflict = true; }
conditional_block
main.rs
use std::error::Error; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::Path; use std::collections::HashMap; extern crate regex; use regex::Regex; enum
{ Equals(i32), GreaterThan(i32), LessThan(i32), } // -------------------------------------------------------- fn find_sue (constraints: &HashMap<&str, Ineq>, filename: &str) -> i32 { let path = Path::new(filename); let display = path.display(); // Open the path in read-only mode, returns `io::Result<File>` let file = match File::open(&path) { // The `description` method of `io::Error` returns a string that describes the error Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)), Ok(file) => file, }; let reader = BufReader::new(file); let lines = reader.lines(); let re = Regex::new(r"(?P<key>[:alpha:]+): (?P<value>\d+)").unwrap(); let mut sue_num = 0; let mut sue_no_conflict = -1i32; for line in lines { let text = line.unwrap(); sue_num += 1; let mut has_conflict = false; for cap in re.captures_iter(&text) { let key = cap.name("key").unwrap_or(""); let value = cap.name("value").unwrap_or("").parse::<i32>().unwrap(); match constraints.get(&key) { Some(&Ineq::Equals(present_value)) => { if value!= present_value { has_conflict = true; } }, Some(&Ineq::GreaterThan(present_value)) => { if value <= present_value { has_conflict = true; } }, Some(&Ineq::LessThan(present_value)) => { if value >= present_value { has_conflict = true; } }, _ => {}, } } if!has_conflict { println!("Sue {} has no conflicts", sue_num); sue_no_conflict = sue_num; } } sue_no_conflict } // -------------------------------------------------------- fn main() { println!("Running part 1..."); let mut sue_stats_exact = HashMap::new(); sue_stats_exact.insert("children", Ineq::Equals(3) ); sue_stats_exact.insert("cats", Ineq::Equals(7) ); sue_stats_exact.insert("samoyeds", Ineq::Equals(2) ); sue_stats_exact.insert("pomeranians", Ineq::Equals(3) ); sue_stats_exact.insert("akitas", Ineq::Equals(0) ); sue_stats_exact.insert("vizslas", Ineq::Equals(0) ); sue_stats_exact.insert("goldfish", Ineq::Equals(5) ); sue_stats_exact.insert("trees", Ineq::Equals(3) ); sue_stats_exact.insert("cars", Ineq::Equals(2) ); sue_stats_exact.insert("perfumes", Ineq::Equals(1) ); find_sue(&sue_stats_exact, "day16.txt"); println!("Running part 2..."); let mut sue_stats_ineq = HashMap::new(); sue_stats_ineq.insert("children", Ineq::Equals(3) ); sue_stats_ineq.insert("cats", Ineq::GreaterThan(7) ); sue_stats_ineq.insert("samoyeds", Ineq::Equals(2) ); sue_stats_ineq.insert("pomeranians", Ineq::LessThan(3) ); sue_stats_ineq.insert("akitas", Ineq::Equals(0) ); sue_stats_ineq.insert("vizslas", Ineq::Equals(0) ); sue_stats_ineq.insert("goldfish", Ineq::LessThan(5) ); sue_stats_ineq.insert("trees", Ineq::GreaterThan(3) ); sue_stats_ineq.insert("cars", Ineq::Equals(2) ); sue_stats_ineq.insert("perfumes", Ineq::Equals(1) ); find_sue(&sue_stats_ineq, "day16.txt"); }
Ineq
identifier_name
ascii_chars_increasing.rs
use malachite_base::chars::exhaustive::ascii_chars_increasing; #[test] fn
() { assert_eq!( ascii_chars_increasing().collect::<String>(), "\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\ \u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f}!\"#$%&\'()*\ +,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u{7f}" ); assert_eq!(ascii_chars_increasing().count(), 1 << 7); }
test_ascii_chars_increasing
identifier_name
ascii_chars_increasing.rs
use malachite_base::chars::exhaustive::ascii_chars_increasing; #[test] fn test_ascii_chars_increasing()
{ assert_eq!( ascii_chars_increasing().collect::<String>(), "\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\ \u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f} !\"#$%&\'()*\ +,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u{7f}" ); assert_eq!(ascii_chars_increasing().count(), 1 << 7); }
identifier_body
ascii_chars_increasing.rs
use malachite_base::chars::exhaustive::ascii_chars_increasing; #[test] fn test_ascii_chars_increasing() { assert_eq!( ascii_chars_increasing().collect::<String>(), "\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\ \u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f}!\"#$%&\'()*\ +,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u{7f}"
); assert_eq!(ascii_chars_increasing().count(), 1 << 7); }
random_line_split
issue-3038.rs
impl HTMLTableElement { fn func()
last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } } }
{ if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0 { if let Some(last_tbody) = node.find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) {
identifier_body
issue-3038.rs
impl HTMLTableElement { fn func() { if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0 { if let Some(last_tbody) = node.find(|n| {
.expect("InsertRow failed to append first row."); } } } }
n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>())
random_line_split
issue-3038.rs
impl HTMLTableElement { fn
() { if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0 { if let Some(last_tbody) = node.find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } } }
func
identifier_name
issue-3038.rs
impl HTMLTableElement { fn func() { if number_of_row_elements == 0 { if let Some(last_tbody) = node .rev_children() .filter_map(DomRoot::downcast::<Element>) .find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } } if number_of_row_elements == 0
} }
{ if let Some(last_tbody) = node.find(|n| { n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") }) { last_tbody .upcast::<Node>() .AppendChild(new_row.upcast::<Node>()) .expect("InsertRow failed to append first row."); } }
conditional_block
file.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Modules/fs_fat/dir.rs use kernel::prelude::*; use kernel::lib::mem::aref::ArefBorrow; use kernel::vfs::node; const ERROR_SHORTCHAIN: node::IoError = node::IoError::Unknown("Cluster chain terminated early"); pub type FilesystemInner = super::FilesystemInner; pub struct FileNode { fs: ArefBorrow<FilesystemInner>, //parent_dir: u32, first_cluster: u32, size: u32, } impl FileNode { pub fn new_boxed(fs: ArefBorrow<FilesystemInner>, _parent: u32, first_cluster: u32, size: u32) -> Box<FileNode> { Box::new(FileNode { fs: fs, //parent_dir: parent, first_cluster: first_cluster, size: size, }) } }
impl node::NodeBase for FileNode { fn get_id(&self) -> node::InodeId { todo!("FileNode::get_id") } } impl node::File for FileNode { fn size(&self) -> u64 { self.size as u64 } fn truncate(&self, newsize: u64) -> node::Result<u64> { todo!("FileNode::truncate({:#x})", newsize); } fn clear(&self, ofs: u64, size: u64) -> node::Result<()> { todo!("FileNode::clear({:#x}+{:#x}", ofs, size); } fn read(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { // Sanity check and bound parameters if ofs >= self.size as u64 { // out of range return Err( node::IoError::OutOfRange ); } let maxread = (self.size as u64 - ofs) as usize; let buf = if buf.len() > maxread { &mut buf[..maxread] } else { buf }; let read_length = buf.len(); // Seek to correct position in the cluster chain let mut clusters = super::ClusterList::chained(self.fs.reborrow(), self.first_cluster) .skip( (ofs/self.fs.cluster_size as u64) as usize); let ofs = (ofs % self.fs.cluster_size as u64) as usize; // First incomplete cluster let chunks = if ofs!= 0 { let cluster = match clusters.next() { Some(v) => v, None => return Err( ERROR_SHORTCHAIN ), }; let short_count = ::core::cmp::min(self.fs.cluster_size-ofs, buf.len()); let c = try!(self.fs.load_cluster(cluster)); let n = buf[..short_count].clone_from_slice( &c[ofs..] ); assert_eq!(n, short_count); buf[short_count..].chunks_mut(self.fs.cluster_size) } else { buf.chunks_mut(self.fs.cluster_size) }; // The rest of the clusters for dst in chunks { let cluster = match clusters.next() { Some(v) => v, None => return Err(ERROR_SHORTCHAIN), }; if dst.len() == self.fs.cluster_size { // Read directly try!(self.fs.read_cluster(cluster, dst)); } else { // Bounce (could leave the bouncing up to read_cluster I guess...) let c = try!(self.fs.load_cluster(cluster)); let n = dst.clone_from_slice( &c ); assert_eq!(n, dst.len()); } } Ok( read_length ) } /// Write data to the file, can only grow the file if ofs==size fn write(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { todo!("FileNode::write({:#x}, {:p})", ofs, ::kernel::lib::SlicePtr(buf)); } }
random_line_split
file.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Modules/fs_fat/dir.rs use kernel::prelude::*; use kernel::lib::mem::aref::ArefBorrow; use kernel::vfs::node; const ERROR_SHORTCHAIN: node::IoError = node::IoError::Unknown("Cluster chain terminated early"); pub type FilesystemInner = super::FilesystemInner; pub struct
{ fs: ArefBorrow<FilesystemInner>, //parent_dir: u32, first_cluster: u32, size: u32, } impl FileNode { pub fn new_boxed(fs: ArefBorrow<FilesystemInner>, _parent: u32, first_cluster: u32, size: u32) -> Box<FileNode> { Box::new(FileNode { fs: fs, //parent_dir: parent, first_cluster: first_cluster, size: size, }) } } impl node::NodeBase for FileNode { fn get_id(&self) -> node::InodeId { todo!("FileNode::get_id") } } impl node::File for FileNode { fn size(&self) -> u64 { self.size as u64 } fn truncate(&self, newsize: u64) -> node::Result<u64> { todo!("FileNode::truncate({:#x})", newsize); } fn clear(&self, ofs: u64, size: u64) -> node::Result<()> { todo!("FileNode::clear({:#x}+{:#x}", ofs, size); } fn read(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { // Sanity check and bound parameters if ofs >= self.size as u64 { // out of range return Err( node::IoError::OutOfRange ); } let maxread = (self.size as u64 - ofs) as usize; let buf = if buf.len() > maxread { &mut buf[..maxread] } else { buf }; let read_length = buf.len(); // Seek to correct position in the cluster chain let mut clusters = super::ClusterList::chained(self.fs.reborrow(), self.first_cluster) .skip( (ofs/self.fs.cluster_size as u64) as usize); let ofs = (ofs % self.fs.cluster_size as u64) as usize; // First incomplete cluster let chunks = if ofs!= 0 { let cluster = match clusters.next() { Some(v) => v, None => return Err( ERROR_SHORTCHAIN ), }; let short_count = ::core::cmp::min(self.fs.cluster_size-ofs, buf.len()); let c = try!(self.fs.load_cluster(cluster)); let n = buf[..short_count].clone_from_slice( &c[ofs..] ); assert_eq!(n, short_count); buf[short_count..].chunks_mut(self.fs.cluster_size) } else { buf.chunks_mut(self.fs.cluster_size) }; // The rest of the clusters for dst in chunks { let cluster = match clusters.next() { Some(v) => v, None => return Err(ERROR_SHORTCHAIN), }; if dst.len() == self.fs.cluster_size { // Read directly try!(self.fs.read_cluster(cluster, dst)); } else { // Bounce (could leave the bouncing up to read_cluster I guess...) let c = try!(self.fs.load_cluster(cluster)); let n = dst.clone_from_slice( &c ); assert_eq!(n, dst.len()); } } Ok( read_length ) } /// Write data to the file, can only grow the file if ofs==size fn write(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { todo!("FileNode::write({:#x}, {:p})", ofs, ::kernel::lib::SlicePtr(buf)); } }
FileNode
identifier_name
file.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Modules/fs_fat/dir.rs use kernel::prelude::*; use kernel::lib::mem::aref::ArefBorrow; use kernel::vfs::node; const ERROR_SHORTCHAIN: node::IoError = node::IoError::Unknown("Cluster chain terminated early"); pub type FilesystemInner = super::FilesystemInner; pub struct FileNode { fs: ArefBorrow<FilesystemInner>, //parent_dir: u32, first_cluster: u32, size: u32, } impl FileNode { pub fn new_boxed(fs: ArefBorrow<FilesystemInner>, _parent: u32, first_cluster: u32, size: u32) -> Box<FileNode> { Box::new(FileNode { fs: fs, //parent_dir: parent, first_cluster: first_cluster, size: size, }) } } impl node::NodeBase for FileNode { fn get_id(&self) -> node::InodeId
} impl node::File for FileNode { fn size(&self) -> u64 { self.size as u64 } fn truncate(&self, newsize: u64) -> node::Result<u64> { todo!("FileNode::truncate({:#x})", newsize); } fn clear(&self, ofs: u64, size: u64) -> node::Result<()> { todo!("FileNode::clear({:#x}+{:#x}", ofs, size); } fn read(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { // Sanity check and bound parameters if ofs >= self.size as u64 { // out of range return Err( node::IoError::OutOfRange ); } let maxread = (self.size as u64 - ofs) as usize; let buf = if buf.len() > maxread { &mut buf[..maxread] } else { buf }; let read_length = buf.len(); // Seek to correct position in the cluster chain let mut clusters = super::ClusterList::chained(self.fs.reborrow(), self.first_cluster) .skip( (ofs/self.fs.cluster_size as u64) as usize); let ofs = (ofs % self.fs.cluster_size as u64) as usize; // First incomplete cluster let chunks = if ofs!= 0 { let cluster = match clusters.next() { Some(v) => v, None => return Err( ERROR_SHORTCHAIN ), }; let short_count = ::core::cmp::min(self.fs.cluster_size-ofs, buf.len()); let c = try!(self.fs.load_cluster(cluster)); let n = buf[..short_count].clone_from_slice( &c[ofs..] ); assert_eq!(n, short_count); buf[short_count..].chunks_mut(self.fs.cluster_size) } else { buf.chunks_mut(self.fs.cluster_size) }; // The rest of the clusters for dst in chunks { let cluster = match clusters.next() { Some(v) => v, None => return Err(ERROR_SHORTCHAIN), }; if dst.len() == self.fs.cluster_size { // Read directly try!(self.fs.read_cluster(cluster, dst)); } else { // Bounce (could leave the bouncing up to read_cluster I guess...) let c = try!(self.fs.load_cluster(cluster)); let n = dst.clone_from_slice( &c ); assert_eq!(n, dst.len()); } } Ok( read_length ) } /// Write data to the file, can only grow the file if ofs==size fn write(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> { todo!("FileNode::write({:#x}, {:p})", ofs, ::kernel::lib::SlicePtr(buf)); } }
{ todo!("FileNode::get_id") }
identifier_body
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T) { for ch in &self.child_protos { t.mark_traceable(*ch); } } } /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first
else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn set_upvalue(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
{ first = false; Rc::new(Cell::new(Upval::Closed(env))) }
conditional_block
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T) { for ch in &self.child_protos { t.mark_traceable(*ch); } } } /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first { first = false; Rc::new(Cell::new(Upval::Closed(env))) } else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn
(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
set_upvalue
identifier_name
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T) { for ch in &self.child_protos { t.mark_traceable(*ch); } } } /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot
Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first { first = false; Rc::new(Cell::new(Upval::Closed(env))) } else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn set_upvalue(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
random_line_split
function.rs
//! Defines the `FunctionProto` type, which is a garbage-collected version of core's `FnData`, as //! well as the `Function` type, which is an instantiated, runnable function inside the VM. use lea_core::fndata::{UpvalDesc, FnData}; use lea_core::opcode::*; use mem::*; use Value; use std::rc::Rc; use std::cell::Cell; /// A compiled function. When instantiated by the VM, becomes a `Function`. #[derive(Clone, Debug)] pub struct FunctionProto { /// The name of the source from which this function was compiled pub source_name: String, /// The number of stack slots required by this function (might be dynamically increased) pub stacksize: u8, /// Number of parameters accepted (ignoring varargs) pub params: u8, /// True if declared as a varargs function pub varargs: bool, /// The opcodes emitted for the code in the function bodyt.mark_traceable(r), pub opcodes: Opcodes, /// Constants used by this function. pub consts: Vec<Value>, /// List of Upvalue reference descriptions pub upvalues: Vec<UpvalDesc>, /// Names of Upvalues (names may not be defined) pub upval_names: Vec<String>, /// Contains the last opcode number emitted for a given line pub lines: Vec<usize>, /// References to the prototypes of all function declared within the body of this function. /// When dynamically compiling code, this allows the GC to collect prototypes that are unused. pub child_protos: Vec<TracedRef<FunctionProto>>, } impl FunctionProto { pub fn from_fndata<G: GcStrategy>(fndata: FnData, gc: &mut G) -> TracedRef<FunctionProto> { let proto = FunctionProto { source_name: fndata.source_name, stacksize: fndata.stacksize, params: fndata.params, varargs: fndata.varargs, opcodes: fndata.opcodes, upvalues: fndata.upvals, upval_names: vec![], // TODO lines: fndata.lines, consts: fndata.consts.into_iter().map(|lit| Value::from_literal(lit, gc)).collect(), child_protos: fndata.child_protos.into_iter() .map(|data| FunctionProto::from_fndata(*data, gc)).collect(), }; gc.register_obj(proto) } } impl Traceable for FunctionProto { fn trace<T: Tracer>(&self, t: &mut T)
} /// An active Upvalue #[derive(Debug, Clone, Copy)] pub enum Upval { /// Upvalue is stored in a stack slot Open(usize), /// Closed upvalue, storing its value inline Closed(Value), } /// Instantiated function #[derive(Debug)] pub struct Function { /// The prototype from which this function was instantiated pub proto: TracedRef<FunctionProto>, /// Upvalue references, indexed by upvalue ID pub upvalues: Vec<Rc<Cell<Upval>>>, } impl Function { /// Create a new `Function` from its prototype. /// /// Upvalues are filled in by calling `search_upval` with the upvalue description from the /// prototype. `search_upval` will be called in the right order: Upvalue 0 will be resolved /// first. pub fn new<F, G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, mut search_upval: F) -> Function where F: FnMut(&UpvalDesc) -> Rc<Cell<Upval>> { // TODO Code style of fn decl (is there something official?) let protoref = unsafe { gc.get_ref(proto) }; Function { proto: proto, upvalues: protoref.upvalues.iter().map(|desc| search_upval(desc)).collect(), } } pub fn with_env<G: GcStrategy>(gc: &G, proto: TracedRef<FunctionProto>, env: Value) -> Function { let mut first = true; Function::new(gc, proto, |_| if first { first = false; Rc::new(Cell::new(Upval::Closed(env))) } else { Rc::new(Cell::new(Upval::Closed(Value::Nil))) }) } /// Sets an upvalue to the given value. pub fn set_upvalue(&mut self, id: usize, val: Upval) { self.upvalues[id].set(val); } } impl Traceable for Function { fn trace<T: Tracer>(&self, t: &mut T) { t.mark_traceable(self.proto); for uv in &self.upvalues { if let Upval::Closed(val) = uv.get() { val.trace(t); } } } }
{ for ch in &self.child_protos { t.mark_traceable(*ch); } }
identifier_body
dependent_pairs.rs
use iterators::adaptors::Concat; use iterators::general::CachedIterator; use iterators::tuples::{LogPairIndices, ZOrderTupleIndices}; use malachite_base::num::conversion::traits::ExactFrom; use std::collections::HashMap; use std::hash::Hash; pub fn dependent_pairs<'a, I: Iterator + 'a, J: Iterator, F: 'a>( xs: I, f: F, ) -> Box<dyn Iterator<Item = (I::Item, J::Item)> + 'a> where F: Fn(&I::Item) -> J, I::Item: Clone, { Box::new(Concat::new( xs.map(move |x| f(&x).map(move |y| (x.clone(), y))), )) } pub struct RandomDependentPairs<I: Iterator, J: Iterator, F, T> where F: Fn(&T, &I::Item) -> J, { xs: I, f: F, data: T, x_to_ys: HashMap<I::Item, J>, } impl<I: Iterator, J: Iterator, F, T> Iterator for RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let x = self.xs.next().unwrap(); let ys = self .x_to_ys .entry(x.clone()) .or_insert((self.f)(&self.data, &x)); Some((x, ys.next().unwrap())) } } pub fn random_dependent_pairs<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { RandomDependentPairs { xs, f, data, x_to_ys: HashMap::new(), } } macro_rules! exhaustive_dependent_pairs { ( $struct_name:ident, $fn_name:ident, $index_type:ident, $index_ctor:expr, $x_index_fn:expr ) => { pub struct $struct_name<I: Iterator, J: Iterator, F, T> where I::Item: Clone, { f: F, xs: CachedIterator<I>, x_to_ys: HashMap<I::Item, J>, i: $index_type, data: T, } impl<I: Iterator, J: Iterator, F, T> Iterator for $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let xi = $x_index_fn(&self.i);
return Some((x, ys.next().unwrap())); } let mut ys = (self.f)(&self.data, &x); let y = ys.next().unwrap(); self.x_to_ys.insert(x.clone(), ys); Some((x, y)) } } pub fn $fn_name<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { $struct_name { f, xs: CachedIterator::new(xs), x_to_ys: HashMap::new(), i: $index_ctor, data, } } }; } exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfiniteLog, exhaustive_dependent_pairs_infinite_log, LogPairIndices, LogPairIndices::new(), |i: &LogPairIndices| i.indices().1 ); exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfinite, exhaustive_dependent_pairs_infinite, ZOrderTupleIndices, ZOrderTupleIndices::new(2), |i: &ZOrderTupleIndices| usize::exact_from(i.0[1]) );
let x = self.xs.get(xi).unwrap(); self.i.increment(); if let Some(ys) = self.x_to_ys.get_mut(&x) {
random_line_split
dependent_pairs.rs
use iterators::adaptors::Concat; use iterators::general::CachedIterator; use iterators::tuples::{LogPairIndices, ZOrderTupleIndices}; use malachite_base::num::conversion::traits::ExactFrom; use std::collections::HashMap; use std::hash::Hash; pub fn dependent_pairs<'a, I: Iterator + 'a, J: Iterator, F: 'a>( xs: I, f: F, ) -> Box<dyn Iterator<Item = (I::Item, J::Item)> + 'a> where F: Fn(&I::Item) -> J, I::Item: Clone, { Box::new(Concat::new( xs.map(move |x| f(&x).map(move |y| (x.clone(), y))), )) } pub struct
<I: Iterator, J: Iterator, F, T> where F: Fn(&T, &I::Item) -> J, { xs: I, f: F, data: T, x_to_ys: HashMap<I::Item, J>, } impl<I: Iterator, J: Iterator, F, T> Iterator for RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let x = self.xs.next().unwrap(); let ys = self .x_to_ys .entry(x.clone()) .or_insert((self.f)(&self.data, &x)); Some((x, ys.next().unwrap())) } } pub fn random_dependent_pairs<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> RandomDependentPairs<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { RandomDependentPairs { xs, f, data, x_to_ys: HashMap::new(), } } macro_rules! exhaustive_dependent_pairs { ( $struct_name:ident, $fn_name:ident, $index_type:ident, $index_ctor:expr, $x_index_fn:expr ) => { pub struct $struct_name<I: Iterator, J: Iterator, F, T> where I::Item: Clone, { f: F, xs: CachedIterator<I>, x_to_ys: HashMap<I::Item, J>, i: $index_type, data: T, } impl<I: Iterator, J: Iterator, F, T> Iterator for $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { type Item = (I::Item, J::Item); fn next(&mut self) -> Option<(I::Item, J::Item)> { let xi = $x_index_fn(&self.i); let x = self.xs.get(xi).unwrap(); self.i.increment(); if let Some(ys) = self.x_to_ys.get_mut(&x) { return Some((x, ys.next().unwrap())); } let mut ys = (self.f)(&self.data, &x); let y = ys.next().unwrap(); self.x_to_ys.insert(x.clone(), ys); Some((x, y)) } } pub fn $fn_name<I: Iterator, J: Iterator, F, T>( data: T, xs: I, f: F, ) -> $struct_name<I, J, F, T> where F: Fn(&T, &I::Item) -> J, I::Item: Clone + Eq + Hash, { $struct_name { f, xs: CachedIterator::new(xs), x_to_ys: HashMap::new(), i: $index_ctor, data, } } }; } exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfiniteLog, exhaustive_dependent_pairs_infinite_log, LogPairIndices, LogPairIndices::new(), |i: &LogPairIndices| i.indices().1 ); exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfinite, exhaustive_dependent_pairs_infinite, ZOrderTupleIndices, ZOrderTupleIndices::new(2), |i: &ZOrderTupleIndices| usize::exact_from(i.0[1]) );
RandomDependentPairs
identifier_name
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn print_version() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main() { print_version(); let opts = parse_args(); if opts.flag_version { // We're done here :) return; } println!("Running tcp server on {} with {}mb capacity...",
opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
random_line_split
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn print_version() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main() { print_version(); let opts = parse_args(); if opts.flag_version
println!("Running tcp server on {} with {}mb capacity...", opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
{ // We're done here :) return; }
conditional_block
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn
() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main() { print_version(); let opts = parse_args(); if opts.flag_version { // We're done here :) return; } println!("Running tcp server on {} with {}mb capacity...", opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
print_version
identifier_name
main.rs
// Benchmark testing primitives #![feature(test)] extern crate test; #[macro_use] extern crate maplit; extern crate bufstream; extern crate docopt; extern crate linked_hash_map; extern crate libc; extern crate net2; extern crate rand; extern crate rustc_serialize; extern crate time; mod common; mod metrics; mod options; mod orchestrator; mod platform; mod protocol; mod storage; mod tcp_transport; mod testlib; use common::consts; use options::parse_args; use orchestrator::ListenerTask; fn print_version() { println!("{} {}", consts::APP_NAME, consts::APP_VERSION); } fn main()
{ print_version(); let opts = parse_args(); if opts.flag_version { // We're done here :) return; } println!("Running tcp server on {} with {}mb capacity...", opts.get_bind_string(), opts.get_mem_limit()); let mut listener_task = ListenerTask::new(opts.clone()); listener_task.run(); }
identifier_body
hsts.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 net_traits::IncludeSubdomains; use rustc_serialize::json::{decode}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::{from_utf8}; use time; use url::Url; use util::resource_files::read_resource_file; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSEntry { pub host: String, pub include_subdomains: bool, pub max_age: Option<u64>, pub timestamp: Option<u64> } impl HSTSEntry { pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option<u64>) -> Option<HSTSEntry> { if host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok() { None } else { Some(HSTSEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, timestamp: Some(time::get_time().sec as u64) }) } } pub fn is_expired(&self) -> bool { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age }, _ => false } } fn matches_domain(&self, host: &str) -> bool { !self.is_expired() && self.host == host } fn matches_subdomain(&self, host: &str) -> bool { !self.is_expired() && host.ends_with(&format!(".{}", self.host)) } } #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSList { pub entries: Vec<HSTSEntry> } impl HSTSList { pub fn new() -> HSTSList { HSTSList { entries: vec![] } } pub fn new_from_preload(preload_content: &str) -> Option<HSTSList> { decode(preload_content).ok() } pub fn is_host_secure(&self, host: &str) -> bool { // TODO - Should this be faster than O(n)? The HSTS list is only a few // hundred or maybe thousand entries... // // Could optimise by searching for exact matches first (via a map or // something), then checking for subdomains.
} }) } fn has_domain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_domain(&host) }) } fn has_subdomain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_subdomain(host) }) } pub fn push(&mut self, entry: HSTSEntry) { let have_domain = self.has_domain(&entry.host); let have_subdomain = self.has_subdomain(&entry.host); if!have_domain &&!have_subdomain { self.entries.push(entry); } else if!have_subdomain { for e in &mut self.entries { if e.matches_domain(&entry.host) { e.include_subdomains = entry.include_subdomains; e.max_age = entry.max_age; } } } } } pub fn preload_hsts_domains() -> Option<HSTSList> { read_resource_file(&["hsts_preload.json"]).ok().and_then(|bytes| { from_utf8(&bytes).ok().and_then(|hsts_preload_content| { HSTSList::new_from_preload(hsts_preload_content) }) }) } pub fn secure_url(url: &Url) -> Url { if &*url.scheme == "http" { let mut secure_url = url.clone(); secure_url.scheme = "https".to_owned(); secure_url.relative_scheme_data_mut() .map(|scheme_data| { scheme_data.default_port = Some(443); }); secure_url } else { url.clone() } }
self.entries.iter().any(|e| { if e.include_subdomains { e.matches_subdomain(host) || e.matches_domain(host) } else { e.matches_domain(host)
random_line_split
hsts.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 net_traits::IncludeSubdomains; use rustc_serialize::json::{decode}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::{from_utf8}; use time; use url::Url; use util::resource_files::read_resource_file; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSEntry { pub host: String, pub include_subdomains: bool, pub max_age: Option<u64>, pub timestamp: Option<u64> } impl HSTSEntry { pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option<u64>) -> Option<HSTSEntry> { if host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok() { None } else { Some(HSTSEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, timestamp: Some(time::get_time().sec as u64) }) } } pub fn is_expired(&self) -> bool { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age }, _ => false } } fn matches_domain(&self, host: &str) -> bool { !self.is_expired() && self.host == host } fn matches_subdomain(&self, host: &str) -> bool { !self.is_expired() && host.ends_with(&format!(".{}", self.host)) } } #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSList { pub entries: Vec<HSTSEntry> } impl HSTSList { pub fn new() -> HSTSList { HSTSList { entries: vec![] } } pub fn new_from_preload(preload_content: &str) -> Option<HSTSList> { decode(preload_content).ok() } pub fn is_host_secure(&self, host: &str) -> bool { // TODO - Should this be faster than O(n)? The HSTS list is only a few // hundred or maybe thousand entries... // // Could optimise by searching for exact matches first (via a map or // something), then checking for subdomains. self.entries.iter().any(|e| { if e.include_subdomains { e.matches_subdomain(host) || e.matches_domain(host) } else { e.matches_domain(host) } }) } fn has_domain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_domain(&host) }) } fn has_subdomain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_subdomain(host) }) } pub fn push(&mut self, entry: HSTSEntry) { let have_domain = self.has_domain(&entry.host); let have_subdomain = self.has_subdomain(&entry.host); if!have_domain &&!have_subdomain
else if!have_subdomain { for e in &mut self.entries { if e.matches_domain(&entry.host) { e.include_subdomains = entry.include_subdomains; e.max_age = entry.max_age; } } } } } pub fn preload_hsts_domains() -> Option<HSTSList> { read_resource_file(&["hsts_preload.json"]).ok().and_then(|bytes| { from_utf8(&bytes).ok().and_then(|hsts_preload_content| { HSTSList::new_from_preload(hsts_preload_content) }) }) } pub fn secure_url(url: &Url) -> Url { if &*url.scheme == "http" { let mut secure_url = url.clone(); secure_url.scheme = "https".to_owned(); secure_url.relative_scheme_data_mut() .map(|scheme_data| { scheme_data.default_port = Some(443); }); secure_url } else { url.clone() } }
{ self.entries.push(entry); }
conditional_block
hsts.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 net_traits::IncludeSubdomains; use rustc_serialize::json::{decode}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::{from_utf8}; use time; use url::Url; use util::resource_files::read_resource_file; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct
{ pub host: String, pub include_subdomains: bool, pub max_age: Option<u64>, pub timestamp: Option<u64> } impl HSTSEntry { pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option<u64>) -> Option<HSTSEntry> { if host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok() { None } else { Some(HSTSEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, timestamp: Some(time::get_time().sec as u64) }) } } pub fn is_expired(&self) -> bool { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age }, _ => false } } fn matches_domain(&self, host: &str) -> bool { !self.is_expired() && self.host == host } fn matches_subdomain(&self, host: &str) -> bool { !self.is_expired() && host.ends_with(&format!(".{}", self.host)) } } #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct HSTSList { pub entries: Vec<HSTSEntry> } impl HSTSList { pub fn new() -> HSTSList { HSTSList { entries: vec![] } } pub fn new_from_preload(preload_content: &str) -> Option<HSTSList> { decode(preload_content).ok() } pub fn is_host_secure(&self, host: &str) -> bool { // TODO - Should this be faster than O(n)? The HSTS list is only a few // hundred or maybe thousand entries... // // Could optimise by searching for exact matches first (via a map or // something), then checking for subdomains. self.entries.iter().any(|e| { if e.include_subdomains { e.matches_subdomain(host) || e.matches_domain(host) } else { e.matches_domain(host) } }) } fn has_domain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_domain(&host) }) } fn has_subdomain(&self, host: &str) -> bool { self.entries.iter().any(|e| { e.matches_subdomain(host) }) } pub fn push(&mut self, entry: HSTSEntry) { let have_domain = self.has_domain(&entry.host); let have_subdomain = self.has_subdomain(&entry.host); if!have_domain &&!have_subdomain { self.entries.push(entry); } else if!have_subdomain { for e in &mut self.entries { if e.matches_domain(&entry.host) { e.include_subdomains = entry.include_subdomains; e.max_age = entry.max_age; } } } } } pub fn preload_hsts_domains() -> Option<HSTSList> { read_resource_file(&["hsts_preload.json"]).ok().and_then(|bytes| { from_utf8(&bytes).ok().and_then(|hsts_preload_content| { HSTSList::new_from_preload(hsts_preload_content) }) }) } pub fn secure_url(url: &Url) -> Url { if &*url.scheme == "http" { let mut secure_url = url.clone(); secure_url.scheme = "https".to_owned(); secure_url.relative_scheme_data_mut() .map(|scheme_data| { scheme_data.default_port = Some(443); }); secure_url } else { url.clone() } }
HSTSEntry
identifier_name
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program 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 2 // of the License, or (at your option) any later version. // // This program 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 this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn read_line_unix(prompt: &str) -> Option<String> { let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } } pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else
}
{ let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } }
conditional_block
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program 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 2 // of the License, or (at your option) any later version. // // This program 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 this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn read_line_unix(prompt: &str) -> Option<String>
pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else { let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } } }
{ let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } }
identifier_body
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program 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 2 // of the License, or (at your option) any later version. // // This program 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 this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn read_line_unix(prompt: &str) -> Option<String> { let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } } pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else { let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } } }
random_line_split
readline.rs
// SairaDB - A distributed database // Copyright (C) 2015 by Siyu Wang // // This program 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 2 // of the License, or (at your option) any later version. // // This program 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 this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. use std::ffi::{CStr, CString}; use std::str::from_utf8; use std::io::stdin; #[cfg(unix)] #[link(name = "readline")] extern "C" { #[link_name = "add_history"] fn rl_add_history(line: *const i8); #[link_name = "readline"] fn rl_readline(prompt: *const i8) -> *const i8; } #[cfg(unix)] pub fn push_history(line: &str) { let line = CString::new(line.as_bytes()).unwrap(); unsafe { rl_add_history(line.as_ptr()) }; } #[cfg(unix)] fn
(prompt: &str) -> Option<String> { let pr = CString::new(prompt.as_bytes()).unwrap(); let sp = unsafe { rl_readline(pr.as_ptr()) }; if sp.is_null() { None } else { let cs = unsafe { CStr::from_ptr(sp) }; let line = from_utf8(cs.to_bytes()).unwrap(); push_history(&line); Some(line.to_string()) } } pub fn read_line(prompt: &str) -> Option<String> { if cfg!(unix) { read_line_unix(prompt) } else { let mut s = "".to_string(); print!("{}", prompt); match stdin().read_line(&mut s) { Ok(_) => { s.pop(); // pop '\n' Some(s) } Err(_) => None } } }
read_line_unix
identifier_name
usbiodef.rs
// Copyright © 2016 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! Common header file for all USB IOCTLs defined for //! the core stack. We define them in this single header file //! so that we can maintain backward compatibilty with older //! versions of the stack. use shared::guiddef::GUID; use shared::minwindef::ULONG; use um::winioctl::{FILE_ANY_ACCESS, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, METHOD_NEITHER}; use um::winnt::PVOID; pub const USB_SUBMIT_URB: ULONG = 0; pub const USB_RESET_PORT: ULONG = 1; pub const USB_GET_ROOTHUB_PDO: ULONG = 3; pub const USB_GET_PORT_STATUS: ULONG = 4; pub const USB_ENABLE_PORT: ULONG = 5; pub const USB_GET_HUB_COUNT: ULONG = 6; pub const USB_CYCLE_PORT: ULONG = 7; pub const USB_GET_HUB_NAME: ULONG = 8; pub const USB_IDLE_NOTIFICATION: ULONG = 9; pub const USB_RECORD_FAILURE: ULONG = 10; pub const USB_GET_BUS_INFO: ULONG = 264; pub const USB_GET_CONTROLLER_NAME: ULONG = 265; pub const USB_GET_BUSGUID_INFO: ULONG = 266; pub const USB_GET_PARENT_HUB_INFO: ULONG = 267; pub const USB_GET_DEVICE_HANDLE: ULONG = 268;
pub const USB_GET_DEVICE_HANDLE_EX: ULONG = 269; pub const USB_GET_TT_DEVICE_HANDLE: ULONG = 270; pub const USB_GET_TOPOLOGY_ADDRESS: ULONG = 271; pub const USB_IDLE_NOTIFICATION_EX: ULONG = 272; pub const USB_REQ_GLOBAL_SUSPEND: ULONG = 273; pub const USB_REQ_GLOBAL_RESUME: ULONG = 274; pub const USB_GET_HUB_CONFIG_INFO: ULONG = 275; pub const USB_FAIL_GET_STATUS: ULONG = 280; pub const USB_REGISTER_COMPOSITE_DEVICE: ULONG = 0; pub const USB_UNREGISTER_COMPOSITE_DEVICE: ULONG = 1; pub const USB_REQUEST_REMOTE_WAKE_NOTIFICATION: ULONG = 2; pub const HCD_GET_STATS_1: ULONG = 255; pub const HCD_DIAGNOSTIC_MODE_ON: ULONG = 256; pub const HCD_DIAGNOSTIC_MODE_OFF: ULONG = 257; pub const HCD_GET_ROOT_HUB_NAME: ULONG = 258; pub const HCD_GET_DRIVERKEY_NAME: ULONG = 265; pub const HCD_GET_STATS_2: ULONG = 266; pub const HCD_DISABLE_PORT: ULONG = 268; pub const HCD_ENABLE_PORT: ULONG = 269; pub const HCD_USER_REQUEST: ULONG = 270; pub const HCD_TRACE_READ_REQUEST: ULONG = 275; pub const USB_GET_NODE_INFORMATION: ULONG = 258; pub const USB_GET_NODE_CONNECTION_INFORMATION: ULONG = 259; pub const USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION: ULONG = 260; pub const USB_GET_NODE_CONNECTION_NAME: ULONG = 261; pub const USB_DIAG_IGNORE_HUBS_ON: ULONG = 262; pub const USB_DIAG_IGNORE_HUBS_OFF: ULONG = 263; pub const USB_GET_NODE_CONNECTION_DRIVERKEY_NAME: ULONG = 264; pub const USB_GET_HUB_CAPABILITIES: ULONG = 271; pub const USB_GET_NODE_CONNECTION_ATTRIBUTES: ULONG = 272; pub const USB_HUB_CYCLE_PORT: ULONG = 273; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX: ULONG = 274; pub const USB_RESET_HUB: ULONG = 275; pub const USB_GET_HUB_CAPABILITIES_EX: ULONG = 276; pub const USB_GET_HUB_INFORMATION_EX: ULONG = 277; pub const USB_GET_PORT_CONNECTOR_PROPERTIES: ULONG = 278; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX_V2: ULONG = 279; DEFINE_GUID!{GUID_DEVINTERFACE_USB_HUB, 0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8} DEFINE_GUID!{GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} DEFINE_GUID!{GUID_DEVINTERFACE_USB_HOST_CONTROLLER, 0x3abf6f2d, 0x71c4, 0x462a, 0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27} DEFINE_GUID!{GUID_USB_WMI_STD_DATA, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_STD_NOTIFICATION, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_DEVICE_PERF_INFO, 0x66c1aa3c, 0x499f, 0x49a0, 0xa9, 0xa5, 0x61, 0xe2, 0x35, 0x9f, 0x64, 0x7} DEFINE_GUID!{GUID_USB_WMI_NODE_INFO, 0x9c179357, 0xdc7a, 0x4f41, 0xb6, 0x6b, 0x32, 0x3b, 0x9d, 0xdc, 0xb5, 0xb1} DEFINE_GUID!{GUID_USB_WMI_TRACING, 0x3a61881b, 0xb4e6, 0x4bf9, 0xae, 0xf, 0x3c, 0xd8, 0xf3, 0x94, 0xe5, 0x2f} DEFINE_GUID!{GUID_USB_TRANSFER_TRACING, 0x681eb8aa, 0x403d, 0x452c, 0x9f, 0x8a, 0xf0, 0x61, 0x6f, 0xac, 0x95, 0x40} DEFINE_GUID!{GUID_USB_PERFORMANCE_TRACING, 0xd5de77a6, 0x6ae9, 0x425c, 0xb1, 0xe2, 0xf5, 0x61, 0x5f, 0xd3, 0x48, 0xa9} DEFINE_GUID!{GUID_USB_WMI_SURPRISE_REMOVAL_NOTIFICATION, 0x9bbbf831, 0xa2f2, 0x43b4, 0x96, 0xd1, 0x86, 0x94, 0x4b, 0x59, 0x14, 0xb3} pub const GUID_CLASS_USBHUB: GUID = GUID_DEVINTERFACE_USB_HUB; pub const GUID_CLASS_USB_DEVICE: GUID = GUID_DEVINTERFACE_USB_DEVICE; pub const GUID_CLASS_USB_HOST_CONTROLLER: GUID = GUID_DEVINTERFACE_USB_HOST_CONTROLLER; pub const FILE_DEVICE_USB: ULONG = FILE_DEVICE_UNKNOWN; #[inline] pub fn USB_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context: PVOID, ) -> ()} STRUCT!{struct USB_IDLE_CALLBACK_INFO { IdleCallback: USB_IDLE_CALLBACK, IdleContext: PVOID, }} pub type PUSB_IDLE_CALLBACK_INFO = *mut USB_IDLE_CALLBACK_INFO;
random_line_split
usbiodef.rs
// Copyright © 2016 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! Common header file for all USB IOCTLs defined for //! the core stack. We define them in this single header file //! so that we can maintain backward compatibilty with older //! versions of the stack. use shared::guiddef::GUID; use shared::minwindef::ULONG; use um::winioctl::{FILE_ANY_ACCESS, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, METHOD_NEITHER}; use um::winnt::PVOID; pub const USB_SUBMIT_URB: ULONG = 0; pub const USB_RESET_PORT: ULONG = 1; pub const USB_GET_ROOTHUB_PDO: ULONG = 3; pub const USB_GET_PORT_STATUS: ULONG = 4; pub const USB_ENABLE_PORT: ULONG = 5; pub const USB_GET_HUB_COUNT: ULONG = 6; pub const USB_CYCLE_PORT: ULONG = 7; pub const USB_GET_HUB_NAME: ULONG = 8; pub const USB_IDLE_NOTIFICATION: ULONG = 9; pub const USB_RECORD_FAILURE: ULONG = 10; pub const USB_GET_BUS_INFO: ULONG = 264; pub const USB_GET_CONTROLLER_NAME: ULONG = 265; pub const USB_GET_BUSGUID_INFO: ULONG = 266; pub const USB_GET_PARENT_HUB_INFO: ULONG = 267; pub const USB_GET_DEVICE_HANDLE: ULONG = 268; pub const USB_GET_DEVICE_HANDLE_EX: ULONG = 269; pub const USB_GET_TT_DEVICE_HANDLE: ULONG = 270; pub const USB_GET_TOPOLOGY_ADDRESS: ULONG = 271; pub const USB_IDLE_NOTIFICATION_EX: ULONG = 272; pub const USB_REQ_GLOBAL_SUSPEND: ULONG = 273; pub const USB_REQ_GLOBAL_RESUME: ULONG = 274; pub const USB_GET_HUB_CONFIG_INFO: ULONG = 275; pub const USB_FAIL_GET_STATUS: ULONG = 280; pub const USB_REGISTER_COMPOSITE_DEVICE: ULONG = 0; pub const USB_UNREGISTER_COMPOSITE_DEVICE: ULONG = 1; pub const USB_REQUEST_REMOTE_WAKE_NOTIFICATION: ULONG = 2; pub const HCD_GET_STATS_1: ULONG = 255; pub const HCD_DIAGNOSTIC_MODE_ON: ULONG = 256; pub const HCD_DIAGNOSTIC_MODE_OFF: ULONG = 257; pub const HCD_GET_ROOT_HUB_NAME: ULONG = 258; pub const HCD_GET_DRIVERKEY_NAME: ULONG = 265; pub const HCD_GET_STATS_2: ULONG = 266; pub const HCD_DISABLE_PORT: ULONG = 268; pub const HCD_ENABLE_PORT: ULONG = 269; pub const HCD_USER_REQUEST: ULONG = 270; pub const HCD_TRACE_READ_REQUEST: ULONG = 275; pub const USB_GET_NODE_INFORMATION: ULONG = 258; pub const USB_GET_NODE_CONNECTION_INFORMATION: ULONG = 259; pub const USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION: ULONG = 260; pub const USB_GET_NODE_CONNECTION_NAME: ULONG = 261; pub const USB_DIAG_IGNORE_HUBS_ON: ULONG = 262; pub const USB_DIAG_IGNORE_HUBS_OFF: ULONG = 263; pub const USB_GET_NODE_CONNECTION_DRIVERKEY_NAME: ULONG = 264; pub const USB_GET_HUB_CAPABILITIES: ULONG = 271; pub const USB_GET_NODE_CONNECTION_ATTRIBUTES: ULONG = 272; pub const USB_HUB_CYCLE_PORT: ULONG = 273; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX: ULONG = 274; pub const USB_RESET_HUB: ULONG = 275; pub const USB_GET_HUB_CAPABILITIES_EX: ULONG = 276; pub const USB_GET_HUB_INFORMATION_EX: ULONG = 277; pub const USB_GET_PORT_CONNECTOR_PROPERTIES: ULONG = 278; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX_V2: ULONG = 279; DEFINE_GUID!{GUID_DEVINTERFACE_USB_HUB, 0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8} DEFINE_GUID!{GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} DEFINE_GUID!{GUID_DEVINTERFACE_USB_HOST_CONTROLLER, 0x3abf6f2d, 0x71c4, 0x462a, 0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27} DEFINE_GUID!{GUID_USB_WMI_STD_DATA, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_STD_NOTIFICATION, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_DEVICE_PERF_INFO, 0x66c1aa3c, 0x499f, 0x49a0, 0xa9, 0xa5, 0x61, 0xe2, 0x35, 0x9f, 0x64, 0x7} DEFINE_GUID!{GUID_USB_WMI_NODE_INFO, 0x9c179357, 0xdc7a, 0x4f41, 0xb6, 0x6b, 0x32, 0x3b, 0x9d, 0xdc, 0xb5, 0xb1} DEFINE_GUID!{GUID_USB_WMI_TRACING, 0x3a61881b, 0xb4e6, 0x4bf9, 0xae, 0xf, 0x3c, 0xd8, 0xf3, 0x94, 0xe5, 0x2f} DEFINE_GUID!{GUID_USB_TRANSFER_TRACING, 0x681eb8aa, 0x403d, 0x452c, 0x9f, 0x8a, 0xf0, 0x61, 0x6f, 0xac, 0x95, 0x40} DEFINE_GUID!{GUID_USB_PERFORMANCE_TRACING, 0xd5de77a6, 0x6ae9, 0x425c, 0xb1, 0xe2, 0xf5, 0x61, 0x5f, 0xd3, 0x48, 0xa9} DEFINE_GUID!{GUID_USB_WMI_SURPRISE_REMOVAL_NOTIFICATION, 0x9bbbf831, 0xa2f2, 0x43b4, 0x96, 0xd1, 0x86, 0x94, 0x4b, 0x59, 0x14, 0xb3} pub const GUID_CLASS_USBHUB: GUID = GUID_DEVINTERFACE_USB_HUB; pub const GUID_CLASS_USB_DEVICE: GUID = GUID_DEVINTERFACE_USB_DEVICE; pub const GUID_CLASS_USB_HOST_CONTROLLER: GUID = GUID_DEVINTERFACE_USB_HOST_CONTROLLER; pub const FILE_DEVICE_USB: ULONG = FILE_DEVICE_UNKNOWN; #[inline] pub fn USB_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } #[inline] pub fn U
id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context: PVOID, ) -> ()} STRUCT!{struct USB_IDLE_CALLBACK_INFO { IdleCallback: USB_IDLE_CALLBACK, IdleContext: PVOID, }} pub type PUSB_IDLE_CALLBACK_INFO = *mut USB_IDLE_CALLBACK_INFO;
SB_KERNEL_CTL(
identifier_name
usbiodef.rs
// Copyright © 2016 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! Common header file for all USB IOCTLs defined for //! the core stack. We define them in this single header file //! so that we can maintain backward compatibilty with older //! versions of the stack. use shared::guiddef::GUID; use shared::minwindef::ULONG; use um::winioctl::{FILE_ANY_ACCESS, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, METHOD_NEITHER}; use um::winnt::PVOID; pub const USB_SUBMIT_URB: ULONG = 0; pub const USB_RESET_PORT: ULONG = 1; pub const USB_GET_ROOTHUB_PDO: ULONG = 3; pub const USB_GET_PORT_STATUS: ULONG = 4; pub const USB_ENABLE_PORT: ULONG = 5; pub const USB_GET_HUB_COUNT: ULONG = 6; pub const USB_CYCLE_PORT: ULONG = 7; pub const USB_GET_HUB_NAME: ULONG = 8; pub const USB_IDLE_NOTIFICATION: ULONG = 9; pub const USB_RECORD_FAILURE: ULONG = 10; pub const USB_GET_BUS_INFO: ULONG = 264; pub const USB_GET_CONTROLLER_NAME: ULONG = 265; pub const USB_GET_BUSGUID_INFO: ULONG = 266; pub const USB_GET_PARENT_HUB_INFO: ULONG = 267; pub const USB_GET_DEVICE_HANDLE: ULONG = 268; pub const USB_GET_DEVICE_HANDLE_EX: ULONG = 269; pub const USB_GET_TT_DEVICE_HANDLE: ULONG = 270; pub const USB_GET_TOPOLOGY_ADDRESS: ULONG = 271; pub const USB_IDLE_NOTIFICATION_EX: ULONG = 272; pub const USB_REQ_GLOBAL_SUSPEND: ULONG = 273; pub const USB_REQ_GLOBAL_RESUME: ULONG = 274; pub const USB_GET_HUB_CONFIG_INFO: ULONG = 275; pub const USB_FAIL_GET_STATUS: ULONG = 280; pub const USB_REGISTER_COMPOSITE_DEVICE: ULONG = 0; pub const USB_UNREGISTER_COMPOSITE_DEVICE: ULONG = 1; pub const USB_REQUEST_REMOTE_WAKE_NOTIFICATION: ULONG = 2; pub const HCD_GET_STATS_1: ULONG = 255; pub const HCD_DIAGNOSTIC_MODE_ON: ULONG = 256; pub const HCD_DIAGNOSTIC_MODE_OFF: ULONG = 257; pub const HCD_GET_ROOT_HUB_NAME: ULONG = 258; pub const HCD_GET_DRIVERKEY_NAME: ULONG = 265; pub const HCD_GET_STATS_2: ULONG = 266; pub const HCD_DISABLE_PORT: ULONG = 268; pub const HCD_ENABLE_PORT: ULONG = 269; pub const HCD_USER_REQUEST: ULONG = 270; pub const HCD_TRACE_READ_REQUEST: ULONG = 275; pub const USB_GET_NODE_INFORMATION: ULONG = 258; pub const USB_GET_NODE_CONNECTION_INFORMATION: ULONG = 259; pub const USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION: ULONG = 260; pub const USB_GET_NODE_CONNECTION_NAME: ULONG = 261; pub const USB_DIAG_IGNORE_HUBS_ON: ULONG = 262; pub const USB_DIAG_IGNORE_HUBS_OFF: ULONG = 263; pub const USB_GET_NODE_CONNECTION_DRIVERKEY_NAME: ULONG = 264; pub const USB_GET_HUB_CAPABILITIES: ULONG = 271; pub const USB_GET_NODE_CONNECTION_ATTRIBUTES: ULONG = 272; pub const USB_HUB_CYCLE_PORT: ULONG = 273; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX: ULONG = 274; pub const USB_RESET_HUB: ULONG = 275; pub const USB_GET_HUB_CAPABILITIES_EX: ULONG = 276; pub const USB_GET_HUB_INFORMATION_EX: ULONG = 277; pub const USB_GET_PORT_CONNECTOR_PROPERTIES: ULONG = 278; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX_V2: ULONG = 279; DEFINE_GUID!{GUID_DEVINTERFACE_USB_HUB, 0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8} DEFINE_GUID!{GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} DEFINE_GUID!{GUID_DEVINTERFACE_USB_HOST_CONTROLLER, 0x3abf6f2d, 0x71c4, 0x462a, 0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27} DEFINE_GUID!{GUID_USB_WMI_STD_DATA, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_STD_NOTIFICATION, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_DEVICE_PERF_INFO, 0x66c1aa3c, 0x499f, 0x49a0, 0xa9, 0xa5, 0x61, 0xe2, 0x35, 0x9f, 0x64, 0x7} DEFINE_GUID!{GUID_USB_WMI_NODE_INFO, 0x9c179357, 0xdc7a, 0x4f41, 0xb6, 0x6b, 0x32, 0x3b, 0x9d, 0xdc, 0xb5, 0xb1} DEFINE_GUID!{GUID_USB_WMI_TRACING, 0x3a61881b, 0xb4e6, 0x4bf9, 0xae, 0xf, 0x3c, 0xd8, 0xf3, 0x94, 0xe5, 0x2f} DEFINE_GUID!{GUID_USB_TRANSFER_TRACING, 0x681eb8aa, 0x403d, 0x452c, 0x9f, 0x8a, 0xf0, 0x61, 0x6f, 0xac, 0x95, 0x40} DEFINE_GUID!{GUID_USB_PERFORMANCE_TRACING, 0xd5de77a6, 0x6ae9, 0x425c, 0xb1, 0xe2, 0xf5, 0x61, 0x5f, 0xd3, 0x48, 0xa9} DEFINE_GUID!{GUID_USB_WMI_SURPRISE_REMOVAL_NOTIFICATION, 0x9bbbf831, 0xa2f2, 0x43b4, 0x96, 0xd1, 0x86, 0x94, 0x4b, 0x59, 0x14, 0xb3} pub const GUID_CLASS_USBHUB: GUID = GUID_DEVINTERFACE_USB_HUB; pub const GUID_CLASS_USB_DEVICE: GUID = GUID_DEVINTERFACE_USB_DEVICE; pub const GUID_CLASS_USB_HOST_CONTROLLER: GUID = GUID_DEVINTERFACE_USB_HOST_CONTROLLER; pub const FILE_DEVICE_USB: ULONG = FILE_DEVICE_UNKNOWN; #[inline] pub fn USB_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL(id: ULONG) -> ULONG {
#[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context: PVOID, ) -> ()} STRUCT!{struct USB_IDLE_CALLBACK_INFO { IdleCallback: USB_IDLE_CALLBACK, IdleContext: PVOID, }} pub type PUSB_IDLE_CALLBACK_INFO = *mut USB_IDLE_CALLBACK_INFO;
CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) }
identifier_body
macros.rs
// Bloom // // HTTP REST API caching middleware // Copyright: 2017, Valerian Saliou <[email protected]> // License: Mozilla Public License v2.0 (MPL v2.0) macro_rules! get_cache_store_client_try { ($pool:expr, $error:expr, $client:ident $code:block) => { // In the event of a Redis failure, 'try_get' allows a full pass-through to be performed, \ // thus ensuring service continuity with degraded performance. If 'get' was used there, \ // performing as many pool 'get' as the pool size would incur a synchronous locking, \ // which would wait forever until the Redis connection is restored (this is dangerous). match $pool.try_get() { Some(mut $client) => $code, None => { error!("failed getting a cache store client from pool (try mode)"); Err($error) } } }; } macro_rules! get_cache_store_client_wait { ($pool:expr, $error:expr, $client:ident $code:block) => { // 'get' is used as an alternative to 'try_get', when there is no choice but to ensure \
// an operation succeeds (eg. for cache purges). match $pool.get() { Ok(mut $client) => $code, Err(err) => { error!( "failed getting a cache store client from pool (wait mode), because: {}", err ); Err($error) } } }; }
random_line_split
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else
} } else { error!("Plugin not found: {:?}", library); std::process::exit(123); } }); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::Library::new(library) }
{ error!("Init function not found: {:?}", initializer); std::process::exit(123); }
conditional_block
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else { error!("Init function not found: {:?}", initializer); std::process::exit(123); }
}); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::Library::new(library) }
} } else { error!("Plugin not found: {:?}", library); std::process::exit(123); }
random_line_split
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn
(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else { error!("Init function not found: {:?}", initializer); std::process::exit(123); } } } else { error!("Plugin not found: {:?}", library); std::process::exit(123); } }); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::Library::new(library) }
init_plugin
identifier_name
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else { error!("Init function not found: {:?}", initializer); std::process::exit(123); } } } else { error!("Plugin not found: {:?}", library); std::process::exit(123); } }); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library>
{ libloading::Library::new(library) }
identifier_body
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>, Vec<u8>>, Coordinate) { let (min, max) = min_max(&list); let diff = max - min; let add = Coordinate::new(-min.x, -min.y); let image = gen_canvas(diff.x as u32, diff.y as u32); (image, add) } /** Finds the min and max of a list and returns (min, max). the min and max use the size of the Draw trait to enlarge the are the min, max occupy. */ fn min_max<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) { let mut size: i16 = consts::DEFAULT_SIZE as i16; let mut min = coordinate!(); let mut max = coordinate!(); for item in list { size = cmp::max(size, item.size() as i16); let (imin, imax) = item.min_max(); max.x = cmp::max(max.x, imax.x); min.x = cmp::min(min.x, imin.x); max.y = cmp::max(max.y, imax.y); min.y = cmp::min(min.y, imin.y); } let size = coordinate!(size / 4); (min - size, max + size) } /** Generates a canvas from the image crate. */ fn gen_canvas(w: u32, h: u32) -> image::ImageBuffer<Rgba<u8>, Vec<u8>>
#[cfg(test)] mod tests { use super::*; #[test] fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(), 0); assert_eq!(image.height(), 0); } #[test] fn test_min_max() { let nodes = Node::from_list(&[(-50, 50), (50, -50), (0, 25), (25, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-55, -55)); assert_eq!(max, Coordinate::new(55, 55)); } #[test] fn test_min_max_2() { let nodes = Node::from_list(&[(-9999, 50), (50, -50), (0, 25), (9999, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-10004, -55)); assert_eq!(max, Coordinate::new(10004, 55)); } }
{ image::DynamicImage::new_rgba8(w, h).to_rgba() }
identifier_body
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>, Vec<u8>>, Coordinate) { let (min, max) = min_max(&list); let diff = max - min; let add = Coordinate::new(-min.x, -min.y); let image = gen_canvas(diff.x as u32, diff.y as u32); (image, add) } /** Finds the min and max of a list and returns (min, max). the min and max use the size of the Draw trait to enlarge the are the min, max occupy. */ fn
<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) { let mut size: i16 = consts::DEFAULT_SIZE as i16; let mut min = coordinate!(); let mut max = coordinate!(); for item in list { size = cmp::max(size, item.size() as i16); let (imin, imax) = item.min_max(); max.x = cmp::max(max.x, imax.x); min.x = cmp::min(min.x, imin.x); max.y = cmp::max(max.y, imax.y); min.y = cmp::min(min.y, imin.y); } let size = coordinate!(size / 4); (min - size, max + size) } /** Generates a canvas from the image crate. */ fn gen_canvas(w: u32, h: u32) -> image::ImageBuffer<Rgba<u8>, Vec<u8>> { image::DynamicImage::new_rgba8(w, h).to_rgba() } #[cfg(test)] mod tests { use super::*; #[test] fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(), 0); assert_eq!(image.height(), 0); } #[test] fn test_min_max() { let nodes = Node::from_list(&[(-50, 50), (50, -50), (0, 25), (25, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-55, -55)); assert_eq!(max, Coordinate::new(55, 55)); } #[test] fn test_min_max_2() { let nodes = Node::from_list(&[(-9999, 50), (50, -50), (0, 25), (9999, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-10004, -55)); assert_eq!(max, Coordinate::new(10004, 55)); } }
min_max
identifier_name
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>, Vec<u8>>, Coordinate) { let (min, max) = min_max(&list); let diff = max - min; let add = Coordinate::new(-min.x, -min.y); let image = gen_canvas(diff.x as u32, diff.y as u32); (image, add) } /** Finds the min and max of a list and returns (min, max). the min and max use the size of the Draw trait to enlarge the are the min, max occupy. */ fn min_max<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) { let mut size: i16 = consts::DEFAULT_SIZE as i16; let mut min = coordinate!(); let mut max = coordinate!(); for item in list { size = cmp::max(size, item.size() as i16); let (imin, imax) = item.min_max(); max.x = cmp::max(max.x, imax.x); min.x = cmp::min(min.x, imin.x); max.y = cmp::max(max.y, imax.y); min.y = cmp::min(min.y, imin.y); } let size = coordinate!(size / 4); (min - size, max + size) } /** Generates a canvas from the image crate. */ fn gen_canvas(w: u32, h: u32) -> image::ImageBuffer<Rgba<u8>, Vec<u8>> { image::DynamicImage::new_rgba8(w, h).to_rgba() } #[cfg(test)] mod tests { use super::*; #[test]
fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(), 0); assert_eq!(image.height(), 0); } #[test] fn test_min_max() { let nodes = Node::from_list(&[(-50, 50), (50, -50), (0, 25), (25, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-55, -55)); assert_eq!(max, Coordinate::new(55, 55)); } #[test] fn test_min_max_2() { let nodes = Node::from_list(&[(-9999, 50), (50, -50), (0, 25), (9999, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-10004, -55)); assert_eq!(max, Coordinate::new(10004, 55)); } }
random_line_split
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate yak_client; extern crate capnp; extern crate log4rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::Error; use std::path::Path; use yak_client::{WireProtocol,Request,Response,Operation,Datum,SeqNo,YakError}; #[macro_use] mod store; mod sqlite_store; macro_rules! try_box { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { return Err(From::from(Box::new(err) as Box<Error +'static>)) } }) } #[derive(Debug)] enum ServerError { CapnpError(capnp::Error), CapnpNotInSchema(capnp::NotInSchema), IoError(std::io::Error), DownstreamError(YakError), StoreError(Box<Error>), } impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ServerError::CapnpError(ref e) => e.fmt(f), &ServerError::CapnpNotInSchema(ref e) => e.fmt(f),
&ServerError::IoError(ref e) => e.fmt(f), &ServerError::DownstreamError(ref e) => e.fmt(f), &ServerError::StoreError(ref e) => write!(f, "{}", e), } } } impl Error for ServerError { fn description(&self) -> &str { match self { &ServerError::CapnpError(ref e) => e.description(), &ServerError::CapnpNotInSchema(ref e) => e.description(), &ServerError::IoError(ref e) => e.description(), &ServerError::DownstreamError(ref e) => e.description(), &ServerError::StoreError(ref e) => e.description(), } } } struct DownStream<S: Read+Write> { protocol: Arc<Mutex<WireProtocol<S>>>, } impl <S: ::std::fmt::Debug + Read + Write> ::std::fmt::Debug for DownStream<S> where S: ::std::fmt::Debug +'static { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self.protocol.try_lock() { Ok(ref proto) => write!(fmt, "DownStream{{ protocol: {:?} }}", &**proto), Err(_) => write!(fmt, "DownStream{{ protocol: <locked> }}"), } } } impl<S> Clone for DownStream<S> where S: Read+Write { fn clone(&self) -> DownStream<S> { DownStream { protocol: self.protocol.clone() } } } static LOG_FILE: &'static str = "log.toml"; pub fn main() { if let Err(e) = log4rs::init_file(LOG_FILE, Default::default()) { panic!("Could not init logger from file {}: {}", LOG_FILE, e); } match do_run() { Ok(()) => info!("Terminated normally"), Err(e) => panic!("Failed: {}", e), } } fn do_run() -> Result<(), ServerError> { let mut a = std::env::args().skip(1); let storedir = a.next().unwrap(); let local : String = a.next().unwrap(); let next = match a.next() { Some(ref addr) => Some(try!(DownStream::new(addr))), None => None }; let listener = TcpListener::bind(&local as &str).unwrap(); info!("listening started on {}, ready to accept", local); let store = sqlite_store::SqliteStore::new(Path::new(&storedir)).unwrap(); for stream in listener.incoming() { let next = next.clone(); let store = store.clone(); let sock = stream.unwrap(); let peer = sock.peer_addr().unwrap(); let _ = try!(thread::Builder::new().name(format!("C{}", peer)).spawn(move || { debug!("Accept stream from {:?}", peer); match Session::new(peer, sock, store, next).process_requests() { Err(e) => report_session_errors(&e), _ => () } })); } Ok(()) } fn report_session_errors(error: &Error) { error!("Session failed with: {}", error); while let Some(error) = error.cause() { error!("\tCaused by: {}", error); } } impl DownStream<TcpStream> { fn new(addr: &str) -> Result<DownStream<TcpStream>, ServerError> { debug!("Connect downstream: {:?}", addr); let proto = try_box!(WireProtocol::connect(addr)); debug!("Connected downstream: {:?}", proto); Ok(DownStream { protocol: Arc::new(Mutex::new(proto)) }) } } fn ptr_addr<T>(obj:&T) -> usize { return obj as *const T as usize; } impl<S: Read+Write> DownStream<S> { fn handle(&self, msg: &Request) -> Result<Response, ServerError> { let mut wire = self.protocol.lock().unwrap(); debug!("Downstream: -> {:x}", ptr_addr(&msg)); try!(wire.send(msg)); debug!("Downstream wait: {:x}", ptr_addr(&msg)); let resp = try!(wire.read::<Response>()); debug!("Downstream: <- {:x}", ptr_addr(&resp)); resp.map(Ok).unwrap_or(Err(ServerError::DownstreamError(YakError::ProtocolError))) } } struct Session<Id, S:Read+Write+'static, ST> { id: Id, protocol: WireProtocol<S>, store: ST, next: Option<DownStream<S>> } impl<Id: fmt::Display, S: Read+Write, ST:store::Store> Session<Id, S, ST> { fn new(id: Id, conn: S, store: ST, next: Option<DownStream<S>>) -> Session<Id, S, ST> { Session { id: id, protocol: WireProtocol::new(conn), store: store, next: next } } fn process_requests(&mut self) -> Result<(), ServerError> { trace!("{}: Waiting for message", self.id); while let Some(msg) = try!(self.protocol.read::<Request>()) { try!(self.process_one(msg)); } Ok(()) } fn process_one(&mut self, msg: Request) -> Result<(), ServerError> { trace!("{}: Handle message: {:x}", self.id, ptr_addr(&msg)); let resp = match msg.operation { Operation::Write { ref key, ref value } => { let resp = try!(self.write(msg.sequence, &msg.space, &key, &value)); try!(self.send_downstream_or(&msg, resp)) }, Operation::Read { key } => try!(self.read(msg.sequence, &msg.space, &key)), Operation::Subscribe => { try!(self.subscribe(msg.sequence, &msg.space)); Response::Okay(msg.sequence) }, }; trace!("Response: {:?}", resp); try!(self.protocol.send(&resp)); Ok(()) } fn send_downstream_or(&self, msg: &Request, default: Response) -> Result<Response, ServerError> { match self.next { Some(ref d) => d.handle(msg), None => Ok(default), } } fn read(&self, seq: SeqNo, space: &str, key: &[u8]) -> Result<Response, ServerError> { let val = try_box!(self.store.read(space, key)); trace!("{}/{:?}: read:{:?}: -> {:?}", self.id, space, key, val); let data = val.iter().map(|c| Datum { key: Vec::new(), content: c.clone() }).collect(); Ok(Response::OkayData(seq, data)) } fn write(&self, seq: SeqNo, space: &str, key: &[u8], val: &[u8]) -> Result<Response, ServerError> { trace!("{}/{:?}: write:{:?} -> {:?}", self.id, space, key, val); try_box!(self.store.write(space, key, val)); Ok(Response::Okay(seq)) } fn subscribe(&mut self, seq: SeqNo, space: &str) -> Result<(), ServerError> { try!(self.protocol.send(&Response::Okay(seq))); for d in try_box!(self.store.subscribe(space)) { try!(self.protocol.send(&Response::Delivery(d))); } Ok(()) } } impl From<capnp::Error> for ServerError { fn from(err: capnp::Error) -> ServerError { ServerError::CapnpError(err) } } impl From<capnp::NotInSchema> for ServerError { fn from(err: capnp::NotInSchema) -> ServerError { ServerError::CapnpNotInSchema(err) } } impl From<io::Error> for ServerError { fn from(err: io::Error) -> ServerError { ServerError::IoError(err) } } impl From<YakError> for ServerError { fn from(err: YakError) -> ServerError { ServerError::DownstreamError(err) } } impl From<Box<Error>> for ServerError { fn from(err: Box<Error>) -> ServerError { ServerError::StoreError(err) } }
random_line_split
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate yak_client; extern crate capnp; extern crate log4rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::Error; use std::path::Path; use yak_client::{WireProtocol,Request,Response,Operation,Datum,SeqNo,YakError}; #[macro_use] mod store; mod sqlite_store; macro_rules! try_box { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { return Err(From::from(Box::new(err) as Box<Error +'static>)) } }) } #[derive(Debug)] enum ServerError { CapnpError(capnp::Error), CapnpNotInSchema(capnp::NotInSchema), IoError(std::io::Error), DownstreamError(YakError), StoreError(Box<Error>), } impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ServerError::CapnpError(ref e) => e.fmt(f), &ServerError::CapnpNotInSchema(ref e) => e.fmt(f), &ServerError::IoError(ref e) => e.fmt(f), &ServerError::DownstreamError(ref e) => e.fmt(f), &ServerError::StoreError(ref e) => write!(f, "{}", e), } } } impl Error for ServerError { fn description(&self) -> &str { match self { &ServerError::CapnpError(ref e) => e.description(), &ServerError::CapnpNotInSchema(ref e) => e.description(), &ServerError::IoError(ref e) => e.description(), &ServerError::DownstreamError(ref e) => e.description(), &ServerError::StoreError(ref e) => e.description(), } } } struct DownStream<S: Read+Write> { protocol: Arc<Mutex<WireProtocol<S>>>, } impl <S: ::std::fmt::Debug + Read + Write> ::std::fmt::Debug for DownStream<S> where S: ::std::fmt::Debug +'static { fn
(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self.protocol.try_lock() { Ok(ref proto) => write!(fmt, "DownStream{{ protocol: {:?} }}", &**proto), Err(_) => write!(fmt, "DownStream{{ protocol: <locked> }}"), } } } impl<S> Clone for DownStream<S> where S: Read+Write { fn clone(&self) -> DownStream<S> { DownStream { protocol: self.protocol.clone() } } } static LOG_FILE: &'static str = "log.toml"; pub fn main() { if let Err(e) = log4rs::init_file(LOG_FILE, Default::default()) { panic!("Could not init logger from file {}: {}", LOG_FILE, e); } match do_run() { Ok(()) => info!("Terminated normally"), Err(e) => panic!("Failed: {}", e), } } fn do_run() -> Result<(), ServerError> { let mut a = std::env::args().skip(1); let storedir = a.next().unwrap(); let local : String = a.next().unwrap(); let next = match a.next() { Some(ref addr) => Some(try!(DownStream::new(addr))), None => None }; let listener = TcpListener::bind(&local as &str).unwrap(); info!("listening started on {}, ready to accept", local); let store = sqlite_store::SqliteStore::new(Path::new(&storedir)).unwrap(); for stream in listener.incoming() { let next = next.clone(); let store = store.clone(); let sock = stream.unwrap(); let peer = sock.peer_addr().unwrap(); let _ = try!(thread::Builder::new().name(format!("C{}", peer)).spawn(move || { debug!("Accept stream from {:?}", peer); match Session::new(peer, sock, store, next).process_requests() { Err(e) => report_session_errors(&e), _ => () } })); } Ok(()) } fn report_session_errors(error: &Error) { error!("Session failed with: {}", error); while let Some(error) = error.cause() { error!("\tCaused by: {}", error); } } impl DownStream<TcpStream> { fn new(addr: &str) -> Result<DownStream<TcpStream>, ServerError> { debug!("Connect downstream: {:?}", addr); let proto = try_box!(WireProtocol::connect(addr)); debug!("Connected downstream: {:?}", proto); Ok(DownStream { protocol: Arc::new(Mutex::new(proto)) }) } } fn ptr_addr<T>(obj:&T) -> usize { return obj as *const T as usize; } impl<S: Read+Write> DownStream<S> { fn handle(&self, msg: &Request) -> Result<Response, ServerError> { let mut wire = self.protocol.lock().unwrap(); debug!("Downstream: -> {:x}", ptr_addr(&msg)); try!(wire.send(msg)); debug!("Downstream wait: {:x}", ptr_addr(&msg)); let resp = try!(wire.read::<Response>()); debug!("Downstream: <- {:x}", ptr_addr(&resp)); resp.map(Ok).unwrap_or(Err(ServerError::DownstreamError(YakError::ProtocolError))) } } struct Session<Id, S:Read+Write+'static, ST> { id: Id, protocol: WireProtocol<S>, store: ST, next: Option<DownStream<S>> } impl<Id: fmt::Display, S: Read+Write, ST:store::Store> Session<Id, S, ST> { fn new(id: Id, conn: S, store: ST, next: Option<DownStream<S>>) -> Session<Id, S, ST> { Session { id: id, protocol: WireProtocol::new(conn), store: store, next: next } } fn process_requests(&mut self) -> Result<(), ServerError> { trace!("{}: Waiting for message", self.id); while let Some(msg) = try!(self.protocol.read::<Request>()) { try!(self.process_one(msg)); } Ok(()) } fn process_one(&mut self, msg: Request) -> Result<(), ServerError> { trace!("{}: Handle message: {:x}", self.id, ptr_addr(&msg)); let resp = match msg.operation { Operation::Write { ref key, ref value } => { let resp = try!(self.write(msg.sequence, &msg.space, &key, &value)); try!(self.send_downstream_or(&msg, resp)) }, Operation::Read { key } => try!(self.read(msg.sequence, &msg.space, &key)), Operation::Subscribe => { try!(self.subscribe(msg.sequence, &msg.space)); Response::Okay(msg.sequence) }, }; trace!("Response: {:?}", resp); try!(self.protocol.send(&resp)); Ok(()) } fn send_downstream_or(&self, msg: &Request, default: Response) -> Result<Response, ServerError> { match self.next { Some(ref d) => d.handle(msg), None => Ok(default), } } fn read(&self, seq: SeqNo, space: &str, key: &[u8]) -> Result<Response, ServerError> { let val = try_box!(self.store.read(space, key)); trace!("{}/{:?}: read:{:?}: -> {:?}", self.id, space, key, val); let data = val.iter().map(|c| Datum { key: Vec::new(), content: c.clone() }).collect(); Ok(Response::OkayData(seq, data)) } fn write(&self, seq: SeqNo, space: &str, key: &[u8], val: &[u8]) -> Result<Response, ServerError> { trace!("{}/{:?}: write:{:?} -> {:?}", self.id, space, key, val); try_box!(self.store.write(space, key, val)); Ok(Response::Okay(seq)) } fn subscribe(&mut self, seq: SeqNo, space: &str) -> Result<(), ServerError> { try!(self.protocol.send(&Response::Okay(seq))); for d in try_box!(self.store.subscribe(space)) { try!(self.protocol.send(&Response::Delivery(d))); } Ok(()) } } impl From<capnp::Error> for ServerError { fn from(err: capnp::Error) -> ServerError { ServerError::CapnpError(err) } } impl From<capnp::NotInSchema> for ServerError { fn from(err: capnp::NotInSchema) -> ServerError { ServerError::CapnpNotInSchema(err) } } impl From<io::Error> for ServerError { fn from(err: io::Error) -> ServerError { ServerError::IoError(err) } } impl From<YakError> for ServerError { fn from(err: YakError) -> ServerError { ServerError::DownstreamError(err) } } impl From<Box<Error>> for ServerError { fn from(err: Box<Error>) -> ServerError { ServerError::StoreError(err) } }
fmt
identifier_name
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate yak_client; extern crate capnp; extern crate log4rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::Error; use std::path::Path; use yak_client::{WireProtocol,Request,Response,Operation,Datum,SeqNo,YakError}; #[macro_use] mod store; mod sqlite_store; macro_rules! try_box { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { return Err(From::from(Box::new(err) as Box<Error +'static>)) } }) } #[derive(Debug)] enum ServerError { CapnpError(capnp::Error), CapnpNotInSchema(capnp::NotInSchema), IoError(std::io::Error), DownstreamError(YakError), StoreError(Box<Error>), } impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ServerError::CapnpError(ref e) => e.fmt(f), &ServerError::CapnpNotInSchema(ref e) => e.fmt(f), &ServerError::IoError(ref e) => e.fmt(f), &ServerError::DownstreamError(ref e) => e.fmt(f), &ServerError::StoreError(ref e) => write!(f, "{}", e), } } } impl Error for ServerError { fn description(&self) -> &str { match self { &ServerError::CapnpError(ref e) => e.description(), &ServerError::CapnpNotInSchema(ref e) => e.description(), &ServerError::IoError(ref e) => e.description(), &ServerError::DownstreamError(ref e) => e.description(), &ServerError::StoreError(ref e) => e.description(), } } } struct DownStream<S: Read+Write> { protocol: Arc<Mutex<WireProtocol<S>>>, } impl <S: ::std::fmt::Debug + Read + Write> ::std::fmt::Debug for DownStream<S> where S: ::std::fmt::Debug +'static { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self.protocol.try_lock() { Ok(ref proto) => write!(fmt, "DownStream{{ protocol: {:?} }}", &**proto), Err(_) => write!(fmt, "DownStream{{ protocol: <locked> }}"), } } } impl<S> Clone for DownStream<S> where S: Read+Write { fn clone(&self) -> DownStream<S> { DownStream { protocol: self.protocol.clone() } } } static LOG_FILE: &'static str = "log.toml"; pub fn main() { if let Err(e) = log4rs::init_file(LOG_FILE, Default::default()) { panic!("Could not init logger from file {}: {}", LOG_FILE, e); } match do_run() { Ok(()) => info!("Terminated normally"), Err(e) => panic!("Failed: {}", e), } } fn do_run() -> Result<(), ServerError> { let mut a = std::env::args().skip(1); let storedir = a.next().unwrap(); let local : String = a.next().unwrap(); let next = match a.next() { Some(ref addr) => Some(try!(DownStream::new(addr))), None => None }; let listener = TcpListener::bind(&local as &str).unwrap(); info!("listening started on {}, ready to accept", local); let store = sqlite_store::SqliteStore::new(Path::new(&storedir)).unwrap(); for stream in listener.incoming() { let next = next.clone(); let store = store.clone(); let sock = stream.unwrap(); let peer = sock.peer_addr().unwrap(); let _ = try!(thread::Builder::new().name(format!("C{}", peer)).spawn(move || { debug!("Accept stream from {:?}", peer); match Session::new(peer, sock, store, next).process_requests() { Err(e) => report_session_errors(&e), _ => () } })); } Ok(()) } fn report_session_errors(error: &Error) { error!("Session failed with: {}", error); while let Some(error) = error.cause() { error!("\tCaused by: {}", error); } } impl DownStream<TcpStream> { fn new(addr: &str) -> Result<DownStream<TcpStream>, ServerError> { debug!("Connect downstream: {:?}", addr); let proto = try_box!(WireProtocol::connect(addr)); debug!("Connected downstream: {:?}", proto); Ok(DownStream { protocol: Arc::new(Mutex::new(proto)) }) } } fn ptr_addr<T>(obj:&T) -> usize { return obj as *const T as usize; } impl<S: Read+Write> DownStream<S> { fn handle(&self, msg: &Request) -> Result<Response, ServerError> { let mut wire = self.protocol.lock().unwrap(); debug!("Downstream: -> {:x}", ptr_addr(&msg)); try!(wire.send(msg)); debug!("Downstream wait: {:x}", ptr_addr(&msg)); let resp = try!(wire.read::<Response>()); debug!("Downstream: <- {:x}", ptr_addr(&resp)); resp.map(Ok).unwrap_or(Err(ServerError::DownstreamError(YakError::ProtocolError))) } } struct Session<Id, S:Read+Write+'static, ST> { id: Id, protocol: WireProtocol<S>, store: ST, next: Option<DownStream<S>> } impl<Id: fmt::Display, S: Read+Write, ST:store::Store> Session<Id, S, ST> { fn new(id: Id, conn: S, store: ST, next: Option<DownStream<S>>) -> Session<Id, S, ST> { Session { id: id, protocol: WireProtocol::new(conn), store: store, next: next } } fn process_requests(&mut self) -> Result<(), ServerError> { trace!("{}: Waiting for message", self.id); while let Some(msg) = try!(self.protocol.read::<Request>()) { try!(self.process_one(msg)); } Ok(()) } fn process_one(&mut self, msg: Request) -> Result<(), ServerError> { trace!("{}: Handle message: {:x}", self.id, ptr_addr(&msg)); let resp = match msg.operation { Operation::Write { ref key, ref value } => { let resp = try!(self.write(msg.sequence, &msg.space, &key, &value)); try!(self.send_downstream_or(&msg, resp)) }, Operation::Read { key } => try!(self.read(msg.sequence, &msg.space, &key)), Operation::Subscribe => { try!(self.subscribe(msg.sequence, &msg.space)); Response::Okay(msg.sequence) }, }; trace!("Response: {:?}", resp); try!(self.protocol.send(&resp)); Ok(()) } fn send_downstream_or(&self, msg: &Request, default: Response) -> Result<Response, ServerError> { match self.next { Some(ref d) => d.handle(msg), None => Ok(default), } } fn read(&self, seq: SeqNo, space: &str, key: &[u8]) -> Result<Response, ServerError>
fn write(&self, seq: SeqNo, space: &str, key: &[u8], val: &[u8]) -> Result<Response, ServerError> { trace!("{}/{:?}: write:{:?} -> {:?}", self.id, space, key, val); try_box!(self.store.write(space, key, val)); Ok(Response::Okay(seq)) } fn subscribe(&mut self, seq: SeqNo, space: &str) -> Result<(), ServerError> { try!(self.protocol.send(&Response::Okay(seq))); for d in try_box!(self.store.subscribe(space)) { try!(self.protocol.send(&Response::Delivery(d))); } Ok(()) } } impl From<capnp::Error> for ServerError { fn from(err: capnp::Error) -> ServerError { ServerError::CapnpError(err) } } impl From<capnp::NotInSchema> for ServerError { fn from(err: capnp::NotInSchema) -> ServerError { ServerError::CapnpNotInSchema(err) } } impl From<io::Error> for ServerError { fn from(err: io::Error) -> ServerError { ServerError::IoError(err) } } impl From<YakError> for ServerError { fn from(err: YakError) -> ServerError { ServerError::DownstreamError(err) } } impl From<Box<Error>> for ServerError { fn from(err: Box<Error>) -> ServerError { ServerError::StoreError(err) } }
{ let val = try_box!(self.store.read(space, key)); trace!("{}/{:?}: read:{:?}: -> {:?}", self.id, space, key, val); let data = val.iter().map(|c| Datum { key: Vec::new(), content: c.clone() }).collect(); Ok(Response::OkayData(seq, data)) }
identifier_body
lib.rs
#![crate_name = "r6"] //! r6.rs is an attempt to implement R6RS Scheme in Rust language #![feature(slice_patterns)] #![feature(io)] // This line should be at the top of the extern link list, // because some weird compiler bug lets log imported from rustc, not crates.io log #[macro_use] extern crate log; #[macro_use] extern crate enum_primitive; extern crate phf; extern crate regex; extern crate num; extern crate unicode_categories; extern crate immutable_map; #[cfg(test)] macro_rules! list{ ($($x:expr),*) => ( vec![$($x),*].into_iter().collect() ) } #[cfg(test)] macro_rules! sym{ ($e:expr) => ( Datum::Sym(Cow::Borrowed($e)) ) } #[cfg(test)] macro_rules! num{ ($e:expr) => ( Datum::Num(Number::new_int($e, 0)) ) } /// Error values returned from parser, compiler or runtime pub mod error; /// Basic datum types pub mod datum; /// Implement eqv? primitive pub mod eqv; pub mod parser; pub mod lexer; /// Virtual machine running the bytecode pub mod runtime; /// Primitive functions pub mod primitive; /// Compiles datum into a bytecode pub mod compiler; /// R6RS `base` library pub mod base; /// Real part of the numerical tower pub mod real; /// Numerical tower pub mod number; /// Cast Datum into rust types
pub mod cast; /// Macro implementations pub mod syntax;
random_line_split
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub use self::statement_cache::{MaybeCached, StatementCache, StatementCacheKey}; pub use self::transaction_manager::{AnsiTransactionManager, TransactionManager}; /// Perform simple operations on a backend. /// /// You should likely use [`Connection`] instead. pub trait SimpleConnection { /// Execute multiple SQL statements within the same string. /// /// This function is used to execute migrations, /// which may contain more than one SQL statement. fn batch_execute(&self, query: &str) -> QueryResult<()>; } /// A connection to a database pub trait Connection: SimpleConnection + Send { /// The backend this type connects to type Backend: Backend; /// Establishes a new connection to the database /// /// The argument to this method and the method's behavior varies by backend. /// See the documentation for that backend's connection class /// for details about what it accepts and how it behaves. fn establish(database_url: &str) -> ConnectionResult<Self> where Self: Sized; /// Executes the given function inside of a database transaction /// /// If there is already an open transaction, /// savepoints will be used instead. /// /// If the transaction fails to commit due to a `SerializationFailure` or a /// `ReadOnlyTransaction` a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. In the second case the connection should be considered broken /// as it contains a uncommitted unabortable open transaction. /// /// If a nested transaction fails to release the corresponding savepoint /// a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// })?; /// /// conn.transaction::<(), _, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Pascal")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby", "Pascal"], all_names); /// /// // If we want to roll back the transaction, but don't have an /// // actual error to return, we can return `RollbackTransaction`. /// Err(Error::RollbackTransaction) /// }); /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// # Ok(()) /// # } /// ``` fn transaction<T, E, F>(&self, f: F) -> Result<T, E> where Self: Sized, F: FnOnce() -> Result<T, E>, E: From<Error>, { let transaction_manager = self.transaction_manager(); transaction_manager.begin_transaction(self)?; match f() { Ok(value) => { transaction_manager.commit_transaction(self)?; Ok(value) } Err(e) => { transaction_manager.rollback_transaction(self)?; Err(e) } } } /// Creates a transaction that will never be committed. This is useful for /// tests. Panics if called while inside of a transaction. fn begin_test_transaction(&self) -> QueryResult<()> where Self: Sized, { let transaction_manager = self.transaction_manager(); assert_eq!(transaction_manager.get_transaction_depth(), 0); transaction_manager.begin_transaction(self) } /// Executes the given function inside a transaction, but does not commit /// it. Panics if the given function returns an error. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.test_transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?;
/// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// }); /// /// // Even though we returned `Ok`, the transaction wasn't committed. /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess"], all_names); /// # Ok(()) /// # } /// ``` fn test_transaction<T, E, F>(&self, f: F) -> T where F: FnOnce() -> Result<T, E>, E: Debug, Self: Sized, { let mut user_result = None; let _ = self.transaction::<(), _, _>(|| { user_result = f().ok(); Err(Error::RollbackTransaction) }); user_result.expect("Transaction did not succeed") } #[doc(hidden)] fn execute(&self, query: &str) -> QueryResult<usize>; #[doc(hidden)] fn load<T, U>(&self, source: T) -> QueryResult<Vec<U>> where Self: Sized, T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, U: FromSqlRow<T::SqlType, Self::Backend>, Self::Backend: QueryMetadata<T::SqlType>; #[doc(hidden)] fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize> where Self: Sized, T: QueryFragment<Self::Backend> + QueryId; #[doc(hidden)] fn transaction_manager(&self) -> &dyn TransactionManager<Self> where Self: Sized; } /// A variant of the [`Connection`](trait.Connection.html) trait that is /// usable with dynamic dispatch /// /// If you are looking for a way to use pass database connections /// for different database backends around in your application /// this trait won't help you much. Normally you should only /// need to use this trait if you are interacting with a connection /// passed to a [`Migration`](../migration/trait.Migration.html) pub trait BoxableConnection<DB: Backend>: Connection<Backend = DB> + std::any::Any { #[doc(hidden)] fn as_any(&self) -> &dyn std::any::Any; } impl<C> BoxableConnection<C::Backend> for C where C: Connection + std::any::Any, { fn as_any(&self) -> &dyn std::any::Any { self } } impl<DB: Backend> dyn BoxableConnection<DB> { /// Downcast the current connection to a specific connection /// type. /// /// This will return `None` if the underlying /// connection does not match the corresponding /// type, otherwise a reference to the underlying connection is returned pub fn downcast_ref<T>(&self) -> Option<&T> where T: Connection<Backend = DB> +'static, { self.as_any().downcast_ref::<T>() } /// Check if the current connection is /// a specific connection type pub fn is<T>(&self) -> bool where T: Connection<Backend = DB> +'static, { self.as_any().is::<T>() } }
/// /// let all_names = users.select(name).load::<String>(&conn)?;
random_line_split
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub use self::statement_cache::{MaybeCached, StatementCache, StatementCacheKey}; pub use self::transaction_manager::{AnsiTransactionManager, TransactionManager}; /// Perform simple operations on a backend. /// /// You should likely use [`Connection`] instead. pub trait SimpleConnection { /// Execute multiple SQL statements within the same string. /// /// This function is used to execute migrations, /// which may contain more than one SQL statement. fn batch_execute(&self, query: &str) -> QueryResult<()>; } /// A connection to a database pub trait Connection: SimpleConnection + Send { /// The backend this type connects to type Backend: Backend; /// Establishes a new connection to the database /// /// The argument to this method and the method's behavior varies by backend. /// See the documentation for that backend's connection class /// for details about what it accepts and how it behaves. fn establish(database_url: &str) -> ConnectionResult<Self> where Self: Sized; /// Executes the given function inside of a database transaction /// /// If there is already an open transaction, /// savepoints will be used instead. /// /// If the transaction fails to commit due to a `SerializationFailure` or a /// `ReadOnlyTransaction` a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. In the second case the connection should be considered broken /// as it contains a uncommitted unabortable open transaction. /// /// If a nested transaction fails to release the corresponding savepoint /// a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// })?; /// /// conn.transaction::<(), _, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Pascal")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby", "Pascal"], all_names); /// /// // If we want to roll back the transaction, but don't have an /// // actual error to return, we can return `RollbackTransaction`. /// Err(Error::RollbackTransaction) /// }); /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// # Ok(()) /// # } /// ``` fn transaction<T, E, F>(&self, f: F) -> Result<T, E> where Self: Sized, F: FnOnce() -> Result<T, E>, E: From<Error>, { let transaction_manager = self.transaction_manager(); transaction_manager.begin_transaction(self)?; match f() { Ok(value) => { transaction_manager.commit_transaction(self)?; Ok(value) } Err(e) =>
} } /// Creates a transaction that will never be committed. This is useful for /// tests. Panics if called while inside of a transaction. fn begin_test_transaction(&self) -> QueryResult<()> where Self: Sized, { let transaction_manager = self.transaction_manager(); assert_eq!(transaction_manager.get_transaction_depth(), 0); transaction_manager.begin_transaction(self) } /// Executes the given function inside a transaction, but does not commit /// it. Panics if the given function returns an error. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.test_transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// }); /// /// // Even though we returned `Ok`, the transaction wasn't committed. /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess"], all_names); /// # Ok(()) /// # } /// ``` fn test_transaction<T, E, F>(&self, f: F) -> T where F: FnOnce() -> Result<T, E>, E: Debug, Self: Sized, { let mut user_result = None; let _ = self.transaction::<(), _, _>(|| { user_result = f().ok(); Err(Error::RollbackTransaction) }); user_result.expect("Transaction did not succeed") } #[doc(hidden)] fn execute(&self, query: &str) -> QueryResult<usize>; #[doc(hidden)] fn load<T, U>(&self, source: T) -> QueryResult<Vec<U>> where Self: Sized, T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, U: FromSqlRow<T::SqlType, Self::Backend>, Self::Backend: QueryMetadata<T::SqlType>; #[doc(hidden)] fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize> where Self: Sized, T: QueryFragment<Self::Backend> + QueryId; #[doc(hidden)] fn transaction_manager(&self) -> &dyn TransactionManager<Self> where Self: Sized; } /// A variant of the [`Connection`](trait.Connection.html) trait that is /// usable with dynamic dispatch /// /// If you are looking for a way to use pass database connections /// for different database backends around in your application /// this trait won't help you much. Normally you should only /// need to use this trait if you are interacting with a connection /// passed to a [`Migration`](../migration/trait.Migration.html) pub trait BoxableConnection<DB: Backend>: Connection<Backend = DB> + std::any::Any { #[doc(hidden)] fn as_any(&self) -> &dyn std::any::Any; } impl<C> BoxableConnection<C::Backend> for C where C: Connection + std::any::Any, { fn as_any(&self) -> &dyn std::any::Any { self } } impl<DB: Backend> dyn BoxableConnection<DB> { /// Downcast the current connection to a specific connection /// type. /// /// This will return `None` if the underlying /// connection does not match the corresponding /// type, otherwise a reference to the underlying connection is returned pub fn downcast_ref<T>(&self) -> Option<&T> where T: Connection<Backend = DB> +'static, { self.as_any().downcast_ref::<T>() } /// Check if the current connection is /// a specific connection type pub fn is<T>(&self) -> bool where T: Connection<Backend = DB> +'static, { self.as_any().is::<T>() } }
{ transaction_manager.rollback_transaction(self)?; Err(e) }
conditional_block
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub use self::statement_cache::{MaybeCached, StatementCache, StatementCacheKey}; pub use self::transaction_manager::{AnsiTransactionManager, TransactionManager}; /// Perform simple operations on a backend. /// /// You should likely use [`Connection`] instead. pub trait SimpleConnection { /// Execute multiple SQL statements within the same string. /// /// This function is used to execute migrations, /// which may contain more than one SQL statement. fn batch_execute(&self, query: &str) -> QueryResult<()>; } /// A connection to a database pub trait Connection: SimpleConnection + Send { /// The backend this type connects to type Backend: Backend; /// Establishes a new connection to the database /// /// The argument to this method and the method's behavior varies by backend. /// See the documentation for that backend's connection class /// for details about what it accepts and how it behaves. fn establish(database_url: &str) -> ConnectionResult<Self> where Self: Sized; /// Executes the given function inside of a database transaction /// /// If there is already an open transaction, /// savepoints will be used instead. /// /// If the transaction fails to commit due to a `SerializationFailure` or a /// `ReadOnlyTransaction` a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. In the second case the connection should be considered broken /// as it contains a uncommitted unabortable open transaction. /// /// If a nested transaction fails to release the corresponding savepoint /// a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// })?; /// /// conn.transaction::<(), _, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Pascal")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby", "Pascal"], all_names); /// /// // If we want to roll back the transaction, but don't have an /// // actual error to return, we can return `RollbackTransaction`. /// Err(Error::RollbackTransaction) /// }); /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// # Ok(()) /// # } /// ``` fn transaction<T, E, F>(&self, f: F) -> Result<T, E> where Self: Sized, F: FnOnce() -> Result<T, E>, E: From<Error>, { let transaction_manager = self.transaction_manager(); transaction_manager.begin_transaction(self)?; match f() { Ok(value) => { transaction_manager.commit_transaction(self)?; Ok(value) } Err(e) => { transaction_manager.rollback_transaction(self)?; Err(e) } } } /// Creates a transaction that will never be committed. This is useful for /// tests. Panics if called while inside of a transaction. fn begin_test_transaction(&self) -> QueryResult<()> where Self: Sized, { let transaction_manager = self.transaction_manager(); assert_eq!(transaction_manager.get_transaction_depth(), 0); transaction_manager.begin_transaction(self) } /// Executes the given function inside a transaction, but does not commit /// it. Panics if the given function returns an error. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.test_transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// }); /// /// // Even though we returned `Ok`, the transaction wasn't committed. /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess"], all_names); /// # Ok(()) /// # } /// ``` fn test_transaction<T, E, F>(&self, f: F) -> T where F: FnOnce() -> Result<T, E>, E: Debug, Self: Sized, { let mut user_result = None; let _ = self.transaction::<(), _, _>(|| { user_result = f().ok(); Err(Error::RollbackTransaction) }); user_result.expect("Transaction did not succeed") } #[doc(hidden)] fn execute(&self, query: &str) -> QueryResult<usize>; #[doc(hidden)] fn load<T, U>(&self, source: T) -> QueryResult<Vec<U>> where Self: Sized, T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, U: FromSqlRow<T::SqlType, Self::Backend>, Self::Backend: QueryMetadata<T::SqlType>; #[doc(hidden)] fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize> where Self: Sized, T: QueryFragment<Self::Backend> + QueryId; #[doc(hidden)] fn transaction_manager(&self) -> &dyn TransactionManager<Self> where Self: Sized; } /// A variant of the [`Connection`](trait.Connection.html) trait that is /// usable with dynamic dispatch /// /// If you are looking for a way to use pass database connections /// for different database backends around in your application /// this trait won't help you much. Normally you should only /// need to use this trait if you are interacting with a connection /// passed to a [`Migration`](../migration/trait.Migration.html) pub trait BoxableConnection<DB: Backend>: Connection<Backend = DB> + std::any::Any { #[doc(hidden)] fn as_any(&self) -> &dyn std::any::Any; } impl<C> BoxableConnection<C::Backend> for C where C: Connection + std::any::Any, { fn
(&self) -> &dyn std::any::Any { self } } impl<DB: Backend> dyn BoxableConnection<DB> { /// Downcast the current connection to a specific connection /// type. /// /// This will return `None` if the underlying /// connection does not match the corresponding /// type, otherwise a reference to the underlying connection is returned pub fn downcast_ref<T>(&self) -> Option<&T> where T: Connection<Backend = DB> +'static, { self.as_any().downcast_ref::<T>() } /// Check if the current connection is /// a specific connection type pub fn is<T>(&self) -> bool where T: Connection<Backend = DB> +'static, { self.as_any().is::<T>() } }
as_any
identifier_name
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub use self::statement_cache::{MaybeCached, StatementCache, StatementCacheKey}; pub use self::transaction_manager::{AnsiTransactionManager, TransactionManager}; /// Perform simple operations on a backend. /// /// You should likely use [`Connection`] instead. pub trait SimpleConnection { /// Execute multiple SQL statements within the same string. /// /// This function is used to execute migrations, /// which may contain more than one SQL statement. fn batch_execute(&self, query: &str) -> QueryResult<()>; } /// A connection to a database pub trait Connection: SimpleConnection + Send { /// The backend this type connects to type Backend: Backend; /// Establishes a new connection to the database /// /// The argument to this method and the method's behavior varies by backend. /// See the documentation for that backend's connection class /// for details about what it accepts and how it behaves. fn establish(database_url: &str) -> ConnectionResult<Self> where Self: Sized; /// Executes the given function inside of a database transaction /// /// If there is already an open transaction, /// savepoints will be used instead. /// /// If the transaction fails to commit due to a `SerializationFailure` or a /// `ReadOnlyTransaction` a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. In the second case the connection should be considered broken /// as it contains a uncommitted unabortable open transaction. /// /// If a nested transaction fails to release the corresponding savepoint /// a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// })?; /// /// conn.transaction::<(), _, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Pascal")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby", "Pascal"], all_names); /// /// // If we want to roll back the transaction, but don't have an /// // actual error to return, we can return `RollbackTransaction`. /// Err(Error::RollbackTransaction) /// }); /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// # Ok(()) /// # } /// ``` fn transaction<T, E, F>(&self, f: F) -> Result<T, E> where Self: Sized, F: FnOnce() -> Result<T, E>, E: From<Error>, { let transaction_manager = self.transaction_manager(); transaction_manager.begin_transaction(self)?; match f() { Ok(value) => { transaction_manager.commit_transaction(self)?; Ok(value) } Err(e) => { transaction_manager.rollback_transaction(self)?; Err(e) } } } /// Creates a transaction that will never be committed. This is useful for /// tests. Panics if called while inside of a transaction. fn begin_test_transaction(&self) -> QueryResult<()> where Self: Sized, { let transaction_manager = self.transaction_manager(); assert_eq!(transaction_manager.get_transaction_depth(), 0); transaction_manager.begin_transaction(self) } /// Executes the given function inside a transaction, but does not commit /// it. Panics if the given function returns an error. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.test_transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// }); /// /// // Even though we returned `Ok`, the transaction wasn't committed. /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess"], all_names); /// # Ok(()) /// # } /// ``` fn test_transaction<T, E, F>(&self, f: F) -> T where F: FnOnce() -> Result<T, E>, E: Debug, Self: Sized, { let mut user_result = None; let _ = self.transaction::<(), _, _>(|| { user_result = f().ok(); Err(Error::RollbackTransaction) }); user_result.expect("Transaction did not succeed") } #[doc(hidden)] fn execute(&self, query: &str) -> QueryResult<usize>; #[doc(hidden)] fn load<T, U>(&self, source: T) -> QueryResult<Vec<U>> where Self: Sized, T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, U: FromSqlRow<T::SqlType, Self::Backend>, Self::Backend: QueryMetadata<T::SqlType>; #[doc(hidden)] fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize> where Self: Sized, T: QueryFragment<Self::Backend> + QueryId; #[doc(hidden)] fn transaction_manager(&self) -> &dyn TransactionManager<Self> where Self: Sized; } /// A variant of the [`Connection`](trait.Connection.html) trait that is /// usable with dynamic dispatch /// /// If you are looking for a way to use pass database connections /// for different database backends around in your application /// this trait won't help you much. Normally you should only /// need to use this trait if you are interacting with a connection /// passed to a [`Migration`](../migration/trait.Migration.html) pub trait BoxableConnection<DB: Backend>: Connection<Backend = DB> + std::any::Any { #[doc(hidden)] fn as_any(&self) -> &dyn std::any::Any; } impl<C> BoxableConnection<C::Backend> for C where C: Connection + std::any::Any, { fn as_any(&self) -> &dyn std::any::Any { self } } impl<DB: Backend> dyn BoxableConnection<DB> { /// Downcast the current connection to a specific connection /// type. /// /// This will return `None` if the underlying /// connection does not match the corresponding /// type, otherwise a reference to the underlying connection is returned pub fn downcast_ref<T>(&self) -> Option<&T> where T: Connection<Backend = DB> +'static, { self.as_any().downcast_ref::<T>() } /// Check if the current connection is /// a specific connection type pub fn is<T>(&self) -> bool where T: Connection<Backend = DB> +'static,
}
{ self.as_any().is::<T>() }
identifier_body
json_body_parser.rs
use serialize::{Decodable, json}; use request::Request; use typemap::Key; use plugin::{Plugin, Pluggable}; use std::io; use std::io::{Read, ErrorKind};
impl<'mw, 'conn, D> Plugin<Request<'mw, 'conn, D>> for JsonBodyParser { type Error = io::Error; fn eval(req: &mut Request<D>) -> Result<String, io::Error> { let mut s = String::new(); try!(req.origin.read_to_string(&mut s)); Ok(s) } } pub trait JsonBody { fn json_as<T: Decodable>(&mut self) -> Result<T, io::Error>; } impl<'mw, 'conn, D> JsonBody for Request<'mw, 'conn, D> { fn json_as<T: Decodable>(&mut self) -> Result<T, io::Error> { self.get_ref::<JsonBodyParser>().and_then(|parsed| json::decode::<T>(&*parsed).map_err(|err| io::Error::new(ErrorKind::Other, format!("Parse error: {}", err)) ) ) } }
// Plugin boilerplate struct JsonBodyParser; impl Key for JsonBodyParser { type Value = String; }
random_line_split
json_body_parser.rs
use serialize::{Decodable, json}; use request::Request; use typemap::Key; use plugin::{Plugin, Pluggable}; use std::io; use std::io::{Read, ErrorKind}; // Plugin boilerplate struct
; impl Key for JsonBodyParser { type Value = String; } impl<'mw, 'conn, D> Plugin<Request<'mw, 'conn, D>> for JsonBodyParser { type Error = io::Error; fn eval(req: &mut Request<D>) -> Result<String, io::Error> { let mut s = String::new(); try!(req.origin.read_to_string(&mut s)); Ok(s) } } pub trait JsonBody { fn json_as<T: Decodable>(&mut self) -> Result<T, io::Error>; } impl<'mw, 'conn, D> JsonBody for Request<'mw, 'conn, D> { fn json_as<T: Decodable>(&mut self) -> Result<T, io::Error> { self.get_ref::<JsonBodyParser>().and_then(|parsed| json::decode::<T>(&*parsed).map_err(|err| io::Error::new(ErrorKind::Other, format!("Parse error: {}", err)) ) ) } }
JsonBodyParser
identifier_name
reporter.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 cssparser::SourceLocation;
use msg::constellation_msg::PipelineId; use script_traits::ConstellationControlMsg; use servo_url::ServoUrl; use std::sync::{Mutex, Arc}; use style::error_reporting::{ParseErrorReporter, ContextualParseError}; #[derive(HeapSizeOf, Clone)] pub struct CSSErrorReporter { pub pipelineid: PipelineId, // Arc+Mutex combo is necessary to make this struct Sync, // which is necessary to fulfill the bounds required by the // uses of the ParseErrorReporter trait. #[ignore_heap_size_of = "Arc is defined in libstd"] pub script_chan: Arc<Mutex<IpcSender<ConstellationControlMsg>>>, } impl ParseErrorReporter for CSSErrorReporter { fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { if log_enabled!(log::LogLevel::Info) { info!("Url:\t{}\n{}:{} {}", url.as_str(), location.line, location.column, error.to_string()) } //TODO: report a real filename let _ = self.script_chan.lock().unwrap().send( ConstellationControlMsg::ReportCSSError(self.pipelineid, "".to_owned(), location.line, location.column, error.to_string())); } }
use ipc_channel::ipc::IpcSender; use log;
random_line_split
reporter.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 cssparser::SourceLocation; use ipc_channel::ipc::IpcSender; use log; use msg::constellation_msg::PipelineId; use script_traits::ConstellationControlMsg; use servo_url::ServoUrl; use std::sync::{Mutex, Arc}; use style::error_reporting::{ParseErrorReporter, ContextualParseError}; #[derive(HeapSizeOf, Clone)] pub struct CSSErrorReporter { pub pipelineid: PipelineId, // Arc+Mutex combo is necessary to make this struct Sync, // which is necessary to fulfill the bounds required by the // uses of the ParseErrorReporter trait. #[ignore_heap_size_of = "Arc is defined in libstd"] pub script_chan: Arc<Mutex<IpcSender<ConstellationControlMsg>>>, } impl ParseErrorReporter for CSSErrorReporter { fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { if log_enabled!(log::LogLevel::Info)
//TODO: report a real filename let _ = self.script_chan.lock().unwrap().send( ConstellationControlMsg::ReportCSSError(self.pipelineid, "".to_owned(), location.line, location.column, error.to_string())); } }
{ info!("Url:\t{}\n{}:{} {}", url.as_str(), location.line, location.column, error.to_string()) }
conditional_block
reporter.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 cssparser::SourceLocation; use ipc_channel::ipc::IpcSender; use log; use msg::constellation_msg::PipelineId; use script_traits::ConstellationControlMsg; use servo_url::ServoUrl; use std::sync::{Mutex, Arc}; use style::error_reporting::{ParseErrorReporter, ContextualParseError}; #[derive(HeapSizeOf, Clone)] pub struct CSSErrorReporter { pub pipelineid: PipelineId, // Arc+Mutex combo is necessary to make this struct Sync, // which is necessary to fulfill the bounds required by the // uses of the ParseErrorReporter trait. #[ignore_heap_size_of = "Arc is defined in libstd"] pub script_chan: Arc<Mutex<IpcSender<ConstellationControlMsg>>>, } impl ParseErrorReporter for CSSErrorReporter { fn
(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { if log_enabled!(log::LogLevel::Info) { info!("Url:\t{}\n{}:{} {}", url.as_str(), location.line, location.column, error.to_string()) } //TODO: report a real filename let _ = self.script_chan.lock().unwrap().send( ConstellationControlMsg::ReportCSSError(self.pipelineid, "".to_owned(), location.line, location.column, error.to_string())); } }
report_error
identifier_name
mod.rs
//! Translators for various architectures to Falcon IL. //! //! Translators in Falcon do not lift individual instructions, but instead lift //! basic blocks. This is both more performant than lifting individual //! instructions, and allows Falcon to deal with weird cases such as the delay //! slot in the MIPS architecture. //! //! Translators lift individual instructions to `ControlFlowGraph`, and combine //! these graphs to form a single block. A single instruction may lift to not //! only multiple Falcon IL instructions, but also multiple IL blocks. //! //! Instructions for direct branches in Falcon IL are omitted in the IL, and //! instead edges with conditional guards are emitted. The Brc operation is only //! emitted for indirect branches, and instructions which are typically used to //! call other functions. //! //! If you are lifting directly from loader (Elf/PE/other), you do not need to //! pay attention to the translators. The correct translator will be chosen //! automatically. use crate::memory::MemoryPermissions; pub mod aarch64; mod block_translation_result; pub mod mips; mod options; pub mod ppc; pub mod x86; use crate::error::*; use crate::il; use crate::il::*; pub use block_translation_result::BlockTranslationResult; use falcon_capstone::capstone; pub use options::{ManualEdge, Options, OptionsBuilder}; use std::collections::{BTreeMap, VecDeque}; pub(crate) const DEFAULT_TRANSLATION_BLOCK_BYTES: usize = 64; /// This trait is used by the translator to continually find and lift bytes from an underlying /// memory model. /// /// Anything that implements this trait can be used as a memory backing for lifting. pub trait TranslationMemory { fn permissions(&self, address: u64) -> Option<MemoryPermissions>; fn get_u8(&self, address: u64) -> Option<u8>; fn get_bytes(&self, address: u64, length: usize) -> Vec<u8> { let mut bytes = Vec::new(); for i in 0..length { match self.permissions(address) { Some(permissions) => { if!permissions.contains(MemoryPermissions::EXECUTE) { break; } } None => break, } match self.get_u8(address + i as u64) { Some(u) => bytes.push(u), None => break, }; } bytes } } // A convenience function for turning unhandled instructions into intrinsics pub(crate) fn unhandled_intrinsic( control_flow_graph: &mut il::ControlFlowGraph, instruction: &capstone::Instr, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block()?; block.intrinsic(il::Intrinsic::new( instruction.mnemonic.clone(), format!("{} {}", instruction.mnemonic, instruction.op_str), Vec::new(), None, None, instruction.bytes.get(0..4).unwrap().to_vec(), )); block.index() }; control_flow_graph.set_entry(block_index)?; control_flow_graph.set_exit(block_index)?; Ok(()) } /// A generic translation trait, implemented by various architectures. pub trait Translator { /// Translates a basic block fn translate_block( &self, bytes: &[u8], address: u64, options: &Options, ) -> Result<BlockTranslationResult>; /// Translates a function fn translate_function( &self, memory: &dyn TranslationMemory, function_address: u64, ) -> Result<Function> { self.translate_function_extended(memory, function_address, &Options::default()) } /// Translates a function /// /// Provides additional options over translate_function fn translate_function_extended( &self, memory: &dyn TranslationMemory, function_address: u64, options: &Options, ) -> Result<Function> { // Addresses of blocks pending translation let mut translation_queue: VecDeque<u64> = VecDeque::new(); // The results of block translations let mut translation_results: BTreeMap<u64, BlockTranslationResult> = BTreeMap::new(); translation_queue.push_front(function_address); options.manual_edges().iter().for_each(|manual_edge| { translation_queue.push_back(manual_edge.head_address()); translation_queue.push_back(manual_edge.tail_address()); }); // translate all blocks in the function while!translation_queue.is_empty() { let block_address = translation_queue.pop_front().unwrap(); if translation_results.contains_key(&block_address) { continue; } let block_bytes = memory.get_bytes(block_address, DEFAULT_TRANSLATION_BLOCK_BYTES); if block_bytes.is_empty() {
control_flow_graph.set_entry(block_index)?; control_flow_graph.set_exit(block_index)?; translation_results.insert( block_address, BlockTranslationResult::new( vec![(block_address, control_flow_graph)], block_address, 0, Vec::new(), ), ); continue; } // translate this block let block_translation_result = self.translate_block(&block_bytes, block_address, options)?; // enqueue all successors for successor in block_translation_result.successors().iter() { if!translation_queue.contains(&successor.0) { translation_queue.push_back(successor.0); } } translation_results.insert(block_address, block_translation_result); } // We now insert all of these blocks into a new control flow graph, // keeping track of their new entry and exit indices. // A mapping of instruction address to entry/exit vertex indices let mut instruction_indices: BTreeMap<u64, (usize, usize)> = BTreeMap::new(); // A mapping of block address to entry/exit vertex indices; let mut block_indices: BTreeMap<u64, (usize, usize)> = BTreeMap::new(); let mut control_flow_graph = ControlFlowGraph::new(); for result in &translation_results { let block_translation_result = result.1; let mut block_entry = 0; let mut block_exit = 0; let mut previous_exit = None; for &(address, ref instruction_graph) in block_translation_result.instructions().iter() { // Have we already inserted this instruction? let (entry, exit) = if instruction_indices.get(&address).is_some() { instruction_indices[&address] } else { let (entry, exit) = control_flow_graph.insert(instruction_graph)?; instruction_indices.insert(address, (entry, exit)); (entry, exit) }; // If this is not our first instruction through this block. if let Some(previous_exit) = previous_exit { // If an edge from the previous block to this block doesn't // exist if control_flow_graph.edge(previous_exit, entry).is_err() { // Create an edge from the previous block to this block. control_flow_graph.unconditional_edge(previous_exit, entry)?; } } // Our first instruction through this block else { block_entry = entry; } block_exit = exit; previous_exit = Some(exit); } block_indices.insert(*result.0, (block_entry, block_exit)); } // Insert the edges // Start with edges for our manual edges for manual_edge in options.manual_edges() { let (_, edge_head) = block_indices[&manual_edge.head_address()]; let (edge_tail, _) = block_indices[&manual_edge.tail_address()]; if control_flow_graph.edge(edge_head, edge_tail).is_ok() { continue; } if let Some(condition) = manual_edge.condition() { control_flow_graph.conditional_edge(edge_head, edge_tail, condition.clone())?; } else { control_flow_graph.unconditional_edge(edge_head, edge_tail)?; } } // For every block translation result for (address, block_translation_result) in translation_results { // Get the exit index for the last/tail vertex in this block let (_, block_exit) = block_indices[&address]; // For every successor in the block translation result (this is an // (address, condition) tuple) for (successor_address, successor_condition) in block_translation_result.successors().iter() { // get the entry index for the first/head block in the successor let (block_entry, _) = block_indices[successor_address]; // check for duplicate edges if control_flow_graph.edge(block_exit, block_entry).is_ok() { continue; } match successor_condition { Some(ref condition) => control_flow_graph.conditional_edge( block_exit, block_entry, condition.clone(), )?, None => control_flow_graph.unconditional_edge(block_exit, block_entry)?, } } } // One block is the start of our control_flow_graph control_flow_graph.set_entry(block_indices[&function_address].0)?; // merge for the user control_flow_graph.merge()?; Ok(Function::new(function_address, control_flow_graph)) } }
let mut control_flow_graph = ControlFlowGraph::new(); let block_index = control_flow_graph.new_block()?.index();
random_line_split
mod.rs
//! Translators for various architectures to Falcon IL. //! //! Translators in Falcon do not lift individual instructions, but instead lift //! basic blocks. This is both more performant than lifting individual //! instructions, and allows Falcon to deal with weird cases such as the delay //! slot in the MIPS architecture. //! //! Translators lift individual instructions to `ControlFlowGraph`, and combine //! these graphs to form a single block. A single instruction may lift to not //! only multiple Falcon IL instructions, but also multiple IL blocks. //! //! Instructions for direct branches in Falcon IL are omitted in the IL, and //! instead edges with conditional guards are emitted. The Brc operation is only //! emitted for indirect branches, and instructions which are typically used to //! call other functions. //! //! If you are lifting directly from loader (Elf/PE/other), you do not need to //! pay attention to the translators. The correct translator will be chosen //! automatically. use crate::memory::MemoryPermissions; pub mod aarch64; mod block_translation_result; pub mod mips; mod options; pub mod ppc; pub mod x86; use crate::error::*; use crate::il; use crate::il::*; pub use block_translation_result::BlockTranslationResult; use falcon_capstone::capstone; pub use options::{ManualEdge, Options, OptionsBuilder}; use std::collections::{BTreeMap, VecDeque}; pub(crate) const DEFAULT_TRANSLATION_BLOCK_BYTES: usize = 64; /// This trait is used by the translator to continually find and lift bytes from an underlying /// memory model. /// /// Anything that implements this trait can be used as a memory backing for lifting. pub trait TranslationMemory { fn permissions(&self, address: u64) -> Option<MemoryPermissions>; fn get_u8(&self, address: u64) -> Option<u8>; fn get_bytes(&self, address: u64, length: usize) -> Vec<u8> { let mut bytes = Vec::new(); for i in 0..length { match self.permissions(address) { Some(permissions) => { if!permissions.contains(MemoryPermissions::EXECUTE) { break; } } None => break, } match self.get_u8(address + i as u64) { Some(u) => bytes.push(u), None => break, }; } bytes } } // A convenience function for turning unhandled instructions into intrinsics pub(crate) fn unhandled_intrinsic( control_flow_graph: &mut il::ControlFlowGraph, instruction: &capstone::Instr, ) -> Result<()>
} /// A generic translation trait, implemented by various architectures. pub trait Translator { /// Translates a basic block fn translate_block( &self, bytes: &[u8], address: u64, options: &Options, ) -> Result<BlockTranslationResult>; /// Translates a function fn translate_function( &self, memory: &dyn TranslationMemory, function_address: u64, ) -> Result<Function> { self.translate_function_extended(memory, function_address, &Options::default()) } /// Translates a function /// /// Provides additional options over translate_function fn translate_function_extended( &self, memory: &dyn TranslationMemory, function_address: u64, options: &Options, ) -> Result<Function> { // Addresses of blocks pending translation let mut translation_queue: VecDeque<u64> = VecDeque::new(); // The results of block translations let mut translation_results: BTreeMap<u64, BlockTranslationResult> = BTreeMap::new(); translation_queue.push_front(function_address); options.manual_edges().iter().for_each(|manual_edge| { translation_queue.push_back(manual_edge.head_address()); translation_queue.push_back(manual_edge.tail_address()); }); // translate all blocks in the function while!translation_queue.is_empty() { let block_address = translation_queue.pop_front().unwrap(); if translation_results.contains_key(&block_address) { continue; } let block_bytes = memory.get_bytes(block_address, DEFAULT_TRANSLATION_BLOCK_BYTES); if block_bytes.is_empty() { let mut control_flow_graph = ControlFlowGraph::new(); let block_index = control_flow_graph.new_block()?.index(); control_flow_graph.set_entry(block_index)?; control_flow_graph.set_exit(block_index)?; translation_results.insert( block_address, BlockTranslationResult::new( vec![(block_address, control_flow_graph)], block_address, 0, Vec::new(), ), ); continue; } // translate this block let block_translation_result = self.translate_block(&block_bytes, block_address, options)?; // enqueue all successors for successor in block_translation_result.successors().iter() { if!translation_queue.contains(&successor.0) { translation_queue.push_back(successor.0); } } translation_results.insert(block_address, block_translation_result); } // We now insert all of these blocks into a new control flow graph, // keeping track of their new entry and exit indices. // A mapping of instruction address to entry/exit vertex indices let mut instruction_indices: BTreeMap<u64, (usize, usize)> = BTreeMap::new(); // A mapping of block address to entry/exit vertex indices; let mut block_indices: BTreeMap<u64, (usize, usize)> = BTreeMap::new(); let mut control_flow_graph = ControlFlowGraph::new(); for result in &translation_results { let block_translation_result = result.1; let mut block_entry = 0; let mut block_exit = 0; let mut previous_exit = None; for &(address, ref instruction_graph) in block_translation_result.instructions().iter() { // Have we already inserted this instruction? let (entry, exit) = if instruction_indices.get(&address).is_some() { instruction_indices[&address] } else { let (entry, exit) = control_flow_graph.insert(instruction_graph)?; instruction_indices.insert(address, (entry, exit)); (entry, exit) }; // If this is not our first instruction through this block. if let Some(previous_exit) = previous_exit { // If an edge from the previous block to this block doesn't // exist if control_flow_graph.edge(previous_exit, entry).is_err() { // Create an edge from the previous block to this block. control_flow_graph.unconditional_edge(previous_exit, entry)?; } } // Our first instruction through this block else { block_entry = entry; } block_exit = exit; previous_exit = Some(exit); } block_indices.insert(*result.0, (block_entry, block_exit)); } // Insert the edges // Start with edges for our manual edges for manual_edge in options.manual_edges() { let (_, edge_head) = block_indices[&manual_edge.head_address()]; let (edge_tail, _) = block_indices[&manual_edge.tail_address()]; if control_flow_graph.edge(edge_head, edge_tail).is_ok() { continue; } if let Some(condition) = manual_edge.condition() { control_flow_graph.conditional_edge(edge_head, edge_tail, condition.clone())?; } else { control_flow_graph.unconditional_edge(edge_head, edge_tail)?; } } // For every block translation result for (address, block_translation_result) in translation_results { // Get the exit index for the last/tail vertex in this block let (_, block_exit) = block_indices[&address]; // For every successor in the block translation result (this is an // (address, condition) tuple) for (successor_address, successor_condition) in block_translation_result.successors().iter() { // get the entry index for the first/head block in the successor let (block_entry, _) = block_indices[successor_address]; // check for duplicate edges if control_flow_graph.edge(block_exit, block_entry).is_ok() { continue; } match successor_condition { Some(ref condition) => control_flow_graph.conditional_edge( block_exit, block_entry, condition.clone(), )?, None => control_flow_graph.unconditional_edge(block_exit, block_entry)?, } } } // One block is the start of our control_flow_graph control_flow_graph.set_entry(block_indices[&function_address].0)?; // merge for the user control_flow_graph.merge()?; Ok(Function::new(function_address, control_flow_graph)) } }
{ let block_index = { let block = control_flow_graph.new_block()?; block.intrinsic(il::Intrinsic::new( instruction.mnemonic.clone(), format!("{} {}", instruction.mnemonic, instruction.op_str), Vec::new(), None, None, instruction.bytes.get(0..4).unwrap().to_vec(), )); block.index() }; control_flow_graph.set_entry(block_index)?; control_flow_graph.set_exit(block_index)?; Ok(())
identifier_body
mod.rs
//! Translators for various architectures to Falcon IL. //! //! Translators in Falcon do not lift individual instructions, but instead lift //! basic blocks. This is both more performant than lifting individual //! instructions, and allows Falcon to deal with weird cases such as the delay //! slot in the MIPS architecture. //! //! Translators lift individual instructions to `ControlFlowGraph`, and combine //! these graphs to form a single block. A single instruction may lift to not //! only multiple Falcon IL instructions, but also multiple IL blocks. //! //! Instructions for direct branches in Falcon IL are omitted in the IL, and //! instead edges with conditional guards are emitted. The Brc operation is only //! emitted for indirect branches, and instructions which are typically used to //! call other functions. //! //! If you are lifting directly from loader (Elf/PE/other), you do not need to //! pay attention to the translators. The correct translator will be chosen //! automatically. use crate::memory::MemoryPermissions; pub mod aarch64; mod block_translation_result; pub mod mips; mod options; pub mod ppc; pub mod x86; use crate::error::*; use crate::il; use crate::il::*; pub use block_translation_result::BlockTranslationResult; use falcon_capstone::capstone; pub use options::{ManualEdge, Options, OptionsBuilder}; use std::collections::{BTreeMap, VecDeque}; pub(crate) const DEFAULT_TRANSLATION_BLOCK_BYTES: usize = 64; /// This trait is used by the translator to continually find and lift bytes from an underlying /// memory model. /// /// Anything that implements this trait can be used as a memory backing for lifting. pub trait TranslationMemory { fn permissions(&self, address: u64) -> Option<MemoryPermissions>; fn get_u8(&self, address: u64) -> Option<u8>; fn get_bytes(&self, address: u64, length: usize) -> Vec<u8> { let mut bytes = Vec::new(); for i in 0..length { match self.permissions(address) { Some(permissions) => { if!permissions.contains(MemoryPermissions::EXECUTE) { break; } } None => break, } match self.get_u8(address + i as u64) { Some(u) => bytes.push(u), None => break, }; } bytes } } // A convenience function for turning unhandled instructions into intrinsics pub(crate) fn
( control_flow_graph: &mut il::ControlFlowGraph, instruction: &capstone::Instr, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block()?; block.intrinsic(il::Intrinsic::new( instruction.mnemonic.clone(), format!("{} {}", instruction.mnemonic, instruction.op_str), Vec::new(), None, None, instruction.bytes.get(0..4).unwrap().to_vec(), )); block.index() }; control_flow_graph.set_entry(block_index)?; control_flow_graph.set_exit(block_index)?; Ok(()) } /// A generic translation trait, implemented by various architectures. pub trait Translator { /// Translates a basic block fn translate_block( &self, bytes: &[u8], address: u64, options: &Options, ) -> Result<BlockTranslationResult>; /// Translates a function fn translate_function( &self, memory: &dyn TranslationMemory, function_address: u64, ) -> Result<Function> { self.translate_function_extended(memory, function_address, &Options::default()) } /// Translates a function /// /// Provides additional options over translate_function fn translate_function_extended( &self, memory: &dyn TranslationMemory, function_address: u64, options: &Options, ) -> Result<Function> { // Addresses of blocks pending translation let mut translation_queue: VecDeque<u64> = VecDeque::new(); // The results of block translations let mut translation_results: BTreeMap<u64, BlockTranslationResult> = BTreeMap::new(); translation_queue.push_front(function_address); options.manual_edges().iter().for_each(|manual_edge| { translation_queue.push_back(manual_edge.head_address()); translation_queue.push_back(manual_edge.tail_address()); }); // translate all blocks in the function while!translation_queue.is_empty() { let block_address = translation_queue.pop_front().unwrap(); if translation_results.contains_key(&block_address) { continue; } let block_bytes = memory.get_bytes(block_address, DEFAULT_TRANSLATION_BLOCK_BYTES); if block_bytes.is_empty() { let mut control_flow_graph = ControlFlowGraph::new(); let block_index = control_flow_graph.new_block()?.index(); control_flow_graph.set_entry(block_index)?; control_flow_graph.set_exit(block_index)?; translation_results.insert( block_address, BlockTranslationResult::new( vec![(block_address, control_flow_graph)], block_address, 0, Vec::new(), ), ); continue; } // translate this block let block_translation_result = self.translate_block(&block_bytes, block_address, options)?; // enqueue all successors for successor in block_translation_result.successors().iter() { if!translation_queue.contains(&successor.0) { translation_queue.push_back(successor.0); } } translation_results.insert(block_address, block_translation_result); } // We now insert all of these blocks into a new control flow graph, // keeping track of their new entry and exit indices. // A mapping of instruction address to entry/exit vertex indices let mut instruction_indices: BTreeMap<u64, (usize, usize)> = BTreeMap::new(); // A mapping of block address to entry/exit vertex indices; let mut block_indices: BTreeMap<u64, (usize, usize)> = BTreeMap::new(); let mut control_flow_graph = ControlFlowGraph::new(); for result in &translation_results { let block_translation_result = result.1; let mut block_entry = 0; let mut block_exit = 0; let mut previous_exit = None; for &(address, ref instruction_graph) in block_translation_result.instructions().iter() { // Have we already inserted this instruction? let (entry, exit) = if instruction_indices.get(&address).is_some() { instruction_indices[&address] } else { let (entry, exit) = control_flow_graph.insert(instruction_graph)?; instruction_indices.insert(address, (entry, exit)); (entry, exit) }; // If this is not our first instruction through this block. if let Some(previous_exit) = previous_exit { // If an edge from the previous block to this block doesn't // exist if control_flow_graph.edge(previous_exit, entry).is_err() { // Create an edge from the previous block to this block. control_flow_graph.unconditional_edge(previous_exit, entry)?; } } // Our first instruction through this block else { block_entry = entry; } block_exit = exit; previous_exit = Some(exit); } block_indices.insert(*result.0, (block_entry, block_exit)); } // Insert the edges // Start with edges for our manual edges for manual_edge in options.manual_edges() { let (_, edge_head) = block_indices[&manual_edge.head_address()]; let (edge_tail, _) = block_indices[&manual_edge.tail_address()]; if control_flow_graph.edge(edge_head, edge_tail).is_ok() { continue; } if let Some(condition) = manual_edge.condition() { control_flow_graph.conditional_edge(edge_head, edge_tail, condition.clone())?; } else { control_flow_graph.unconditional_edge(edge_head, edge_tail)?; } } // For every block translation result for (address, block_translation_result) in translation_results { // Get the exit index for the last/tail vertex in this block let (_, block_exit) = block_indices[&address]; // For every successor in the block translation result (this is an // (address, condition) tuple) for (successor_address, successor_condition) in block_translation_result.successors().iter() { // get the entry index for the first/head block in the successor let (block_entry, _) = block_indices[successor_address]; // check for duplicate edges if control_flow_graph.edge(block_exit, block_entry).is_ok() { continue; } match successor_condition { Some(ref condition) => control_flow_graph.conditional_edge( block_exit, block_entry, condition.clone(), )?, None => control_flow_graph.unconditional_edge(block_exit, block_entry)?, } } } // One block is the start of our control_flow_graph control_flow_graph.set_entry(block_indices[&function_address].0)?; // merge for the user control_flow_graph.merge()?; Ok(Function::new(function_address, control_flow_graph)) } }
unhandled_intrinsic
identifier_name
build.rs
extern crate gcc; use std::path::PathBuf; use std::env; const LIB_NAME: &'static str = "libctxswtch.a"; fn main() { let arch = if cfg!(target_arch = "x86_64") { "x86_64" } else if cfg!(target_arch = "i686") { "i686" } else if cfg!(target_arch = "arm") { "arm" } else if cfg!(target_arch = "mips") { "mips" } else if cfg!(target_arch = "mipsel")
else { panic!("Unsupported architecture: {}", env::var("TARGET").unwrap()); }; let src_path = &["src", "asm", arch, "_context.S"].iter().collect::<PathBuf>(); gcc::compile_library(LIB_NAME, &[src_path.to_str().unwrap()]); // seems like this line is no need actually // println!("cargo:rustc-flags=-l ctxswtch:static"); }
{ "mipsel" }
conditional_block
build.rs
extern crate gcc; use std::path::PathBuf; use std::env; const LIB_NAME: &'static str = "libctxswtch.a"; fn
() { let arch = if cfg!(target_arch = "x86_64") { "x86_64" } else if cfg!(target_arch = "i686") { "i686" } else if cfg!(target_arch = "arm") { "arm" } else if cfg!(target_arch = "mips") { "mips" } else if cfg!(target_arch = "mipsel") { "mipsel" } else { panic!("Unsupported architecture: {}", env::var("TARGET").unwrap()); }; let src_path = &["src", "asm", arch, "_context.S"].iter().collect::<PathBuf>(); gcc::compile_library(LIB_NAME, &[src_path.to_str().unwrap()]); // seems like this line is no need actually // println!("cargo:rustc-flags=-l ctxswtch:static"); }
main
identifier_name
build.rs
extern crate gcc; use std::path::PathBuf; use std::env; const LIB_NAME: &'static str = "libctxswtch.a"; fn main()
}
{ let arch = if cfg!(target_arch = "x86_64") { "x86_64" } else if cfg!(target_arch = "i686") { "i686" } else if cfg!(target_arch = "arm") { "arm" } else if cfg!(target_arch = "mips") { "mips" } else if cfg!(target_arch = "mipsel") { "mipsel" } else { panic!("Unsupported architecture: {}", env::var("TARGET").unwrap()); }; let src_path = &["src", "asm", arch, "_context.S"].iter().collect::<PathBuf>(); gcc::compile_library(LIB_NAME, &[src_path.to_str().unwrap()]); // seems like this line is no need actually // println!("cargo:rustc-flags=-l ctxswtch:static");
identifier_body
build.rs
extern crate gcc; use std::path::PathBuf; use std::env; const LIB_NAME: &'static str = "libctxswtch.a";
if cfg!(target_arch = "x86_64") { "x86_64" } else if cfg!(target_arch = "i686") { "i686" } else if cfg!(target_arch = "arm") { "arm" } else if cfg!(target_arch = "mips") { "mips" } else if cfg!(target_arch = "mipsel") { "mipsel" } else { panic!("Unsupported architecture: {}", env::var("TARGET").unwrap()); }; let src_path = &["src", "asm", arch, "_context.S"].iter().collect::<PathBuf>(); gcc::compile_library(LIB_NAME, &[src_path.to_str().unwrap()]); // seems like this line is no need actually // println!("cargo:rustc-flags=-l ctxswtch:static"); }
fn main() { let arch =
random_line_split
nbb.rs
//! A Non-blocking buffer implementation use alloc::raw_vec::RawVec; use core::ptr; use interrupts::no_interrupts; use super::stream::*; /// A non-blocking circular buffer for use /// by interrupt handlers pub struct NonBlockingBuffer { // A buffer buffer: RawVec<char>, // index of the front of the buffer front: usize, // number of elements in the buffer size: usize, } impl NonBlockingBuffer { pub fn new(cap: usize) -> NonBlockingBuffer {
buffer: RawVec::with_capacity(cap), front: 0, size: 0, } } } impl InputStream for NonBlockingBuffer { type Output = Option<char>; /// Get the next character in the stream if there is one fn get(&mut self) -> Option<char> { no_interrupts(|| { if self.size > 0 { let i = self.front; self.front = (self.front + 1) % self.buffer.cap(); self.size -= 1; unsafe { Some(ptr::read(self.buffer.ptr().offset(i as isize))) } } else { None } }) } } impl Iterator for NonBlockingBuffer { type Item = char; fn next(&mut self) -> Option<char> { self.get() } } impl OutputStream<char> for NonBlockingBuffer { /// Put the given character at the end of the buffer. /// /// If there is no room in the buffer, the character is /// dropped. fn put(&mut self, c: char) { no_interrupts(|| { if self.size < self.buffer.cap() { let next = (self.front + self.size) % self.buffer.cap(); unsafe { ptr::write(self.buffer.ptr().offset(next as isize), c); } self.size += 1; } }) } }
NonBlockingBuffer {
random_line_split
nbb.rs
//! A Non-blocking buffer implementation use alloc::raw_vec::RawVec; use core::ptr; use interrupts::no_interrupts; use super::stream::*; /// A non-blocking circular buffer for use /// by interrupt handlers pub struct NonBlockingBuffer { // A buffer buffer: RawVec<char>, // index of the front of the buffer front: usize, // number of elements in the buffer size: usize, } impl NonBlockingBuffer { pub fn new(cap: usize) -> NonBlockingBuffer
} impl InputStream for NonBlockingBuffer { type Output = Option<char>; /// Get the next character in the stream if there is one fn get(&mut self) -> Option<char> { no_interrupts(|| { if self.size > 0 { let i = self.front; self.front = (self.front + 1) % self.buffer.cap(); self.size -= 1; unsafe { Some(ptr::read(self.buffer.ptr().offset(i as isize))) } } else { None } }) } } impl Iterator for NonBlockingBuffer { type Item = char; fn next(&mut self) -> Option<char> { self.get() } } impl OutputStream<char> for NonBlockingBuffer { /// Put the given character at the end of the buffer. /// /// If there is no room in the buffer, the character is /// dropped. fn put(&mut self, c: char) { no_interrupts(|| { if self.size < self.buffer.cap() { let next = (self.front + self.size) % self.buffer.cap(); unsafe { ptr::write(self.buffer.ptr().offset(next as isize), c); } self.size += 1; } }) } }
{ NonBlockingBuffer { buffer: RawVec::with_capacity(cap), front: 0, size: 0, } }
identifier_body
nbb.rs
//! A Non-blocking buffer implementation use alloc::raw_vec::RawVec; use core::ptr; use interrupts::no_interrupts; use super::stream::*; /// A non-blocking circular buffer for use /// by interrupt handlers pub struct NonBlockingBuffer { // A buffer buffer: RawVec<char>, // index of the front of the buffer front: usize, // number of elements in the buffer size: usize, } impl NonBlockingBuffer { pub fn new(cap: usize) -> NonBlockingBuffer { NonBlockingBuffer { buffer: RawVec::with_capacity(cap), front: 0, size: 0, } } } impl InputStream for NonBlockingBuffer { type Output = Option<char>; /// Get the next character in the stream if there is one fn get(&mut self) -> Option<char> { no_interrupts(|| { if self.size > 0 { let i = self.front; self.front = (self.front + 1) % self.buffer.cap(); self.size -= 1; unsafe { Some(ptr::read(self.buffer.ptr().offset(i as isize))) } } else { None } }) } } impl Iterator for NonBlockingBuffer { type Item = char; fn next(&mut self) -> Option<char> { self.get() } } impl OutputStream<char> for NonBlockingBuffer { /// Put the given character at the end of the buffer. /// /// If there is no room in the buffer, the character is /// dropped. fn
(&mut self, c: char) { no_interrupts(|| { if self.size < self.buffer.cap() { let next = (self.front + self.size) % self.buffer.cap(); unsafe { ptr::write(self.buffer.ptr().offset(next as isize), c); } self.size += 1; } }) } }
put
identifier_name
nbb.rs
//! A Non-blocking buffer implementation use alloc::raw_vec::RawVec; use core::ptr; use interrupts::no_interrupts; use super::stream::*; /// A non-blocking circular buffer for use /// by interrupt handlers pub struct NonBlockingBuffer { // A buffer buffer: RawVec<char>, // index of the front of the buffer front: usize, // number of elements in the buffer size: usize, } impl NonBlockingBuffer { pub fn new(cap: usize) -> NonBlockingBuffer { NonBlockingBuffer { buffer: RawVec::with_capacity(cap), front: 0, size: 0, } } } impl InputStream for NonBlockingBuffer { type Output = Option<char>; /// Get the next character in the stream if there is one fn get(&mut self) -> Option<char> { no_interrupts(|| { if self.size > 0
else { None } }) } } impl Iterator for NonBlockingBuffer { type Item = char; fn next(&mut self) -> Option<char> { self.get() } } impl OutputStream<char> for NonBlockingBuffer { /// Put the given character at the end of the buffer. /// /// If there is no room in the buffer, the character is /// dropped. fn put(&mut self, c: char) { no_interrupts(|| { if self.size < self.buffer.cap() { let next = (self.front + self.size) % self.buffer.cap(); unsafe { ptr::write(self.buffer.ptr().offset(next as isize), c); } self.size += 1; } }) } }
{ let i = self.front; self.front = (self.front + 1) % self.buffer.cap(); self.size -= 1; unsafe { Some(ptr::read(self.buffer.ptr().offset(i as isize))) } }
conditional_block
sin.rs
//! Implements vertical (lane-wise) floating-point `sin`.
#[inline] pub fn sin(self) -> Self { use crate::codegen::math::float::sin::Sin; Sin::sin(self) } /// Sine of `self * PI`. #[inline] pub fn sin_pi(self) -> Self { use crate::codegen::math::float::sin_pi::SinPi; SinPi::sin_pi(self) } /// Sine and cosine of `self * PI`. #[inline] pub fn sin_cos_pi(self) -> (Self, Self) { use crate::codegen::math::float::sin_cos_pi::SinCosPi; SinCosPi::sin_cos_pi(self) } } test_if!{ $test_tt: paste::item! { pub mod [<$id _math_sin>] { use super::*; #[cfg_attr(not(target_arch = "wasm32"), test)] #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] fn sin() { use crate::$elem_ty::consts::PI; let z = $id::splat(0 as $elem_ty); let p = $id::splat(PI as $elem_ty); let ph = $id::splat(PI as $elem_ty / 2.); let o_r = $id::splat((PI as $elem_ty / 2.).sin()); let z_r = $id::splat((PI as $elem_ty).sin()); assert_eq!(z, z.sin()); assert_eq!(o_r, ph.sin()); assert_eq!(z_r, p.sin()); } } } } }; }
macro_rules! impl_math_float_sin { ([$elem_ty:ident; $elem_count:expr]: $id:ident | $test_tt:tt) => { impl $id { /// Sine.
random_line_split
macro_rules.rs
of `{}` is likely invalid in this context", name); parser.span_note(self.site_span, &msg[..]); } } } impl<'a> MacResult for ParserAnyMacro<'a> { fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> { let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); Some(ret) } fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> { let ret = self.parser.borrow_mut().parse_pat(); self.ensure_complete_parse(false); Some(ret) } fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); while let Some(item) = self.parser.borrow_mut().parse_item() { ret.push(item); } self.ensure_complete_parse(false); Some(ret) } fn make_impl_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::ImplItem>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => ret.push(panictry!(parser.parse_impl_item())) } } self.ensure_complete_parse(false); Some(ret) } fn make_stmts(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Stmt>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => match parser.parse_stmt_nopanic() { Ok(maybe_stmt) => match maybe_stmt { Some(stmt) => ret.push(stmt), None => (), }, Err(_) => break, } } } self.ensure_complete_parse(false); Some(ret) } } struct MacroRulesMacroExpander { name: ast::Ident, imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: Span, arg: &[ast::TokenTree]) -> Box<MacResult+'cx> { generic_extension(cx, sp, self.name, self.imported_from, arg, &self.lhses, &self.rhses) } } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx ExtCtxt, sp: Span, name: ast::Ident, imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) -> Box<MacResult+'cx> { if cx.trace_macros() { println!("{}! {{ {} }}", token::get_ident(name), print::pprust::tts_to_string(arg)); } // Which arm's failure should we report? (the one furthest along) let mut best_fail_spot = DUMMY_SP; let mut best_fail_msg = "internal error: ran no matchers".to_string(); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { TtDelimited(_, ref delim) => &delim.tts[..], _ => panic!(cx.span_fatal(sp, "malformed macro lhs")) }; match TokenTree::parse(cx, lhs_tt, arg) { Success(named_matches) => { let rhs = match *rhses[i] { // okay, what's your transcriber? MatchedNonterminal(NtTT(ref tt)) => { match **tt { // ignore delimiters TtDelimited(_, ref delimed) => delimed.tts.clone(), _ => panic!(cx.span_fatal(sp, "macro rhs must be delimited")), } }, _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic, Some(named_matches), imported_from, rhs); let mut p = Parser::new(cx.parse_sess(), cx.cfg(), Box::new(trncbr)); panictry!(p.check_unknown_macro_variable()); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return Box::new(ParserAnyMacro { parser: RefCell::new(p), // Pass along the original expansion site and the name of the macro // so we can print a useful error message if the parse of the expanded // macro leaves unparsed tokens. site_span: sp, macro_ident: name }) } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, Error(sp, ref msg) => panic!(cx.span_fatal(sp, &msg[..])) } } _ => cx.bug("non-matcher found in parsed lhses") } } panic!(cx.span_fatal(best_fail_spot, &best_fail_msg[..])); } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. pub fn compile<'cx>(cx: &'cx mut ExtCtxt, def: &ast::MacroDef) -> SyntaxExtension { let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ //...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_nm, special_idents::tt, token::Plain, token::Plain); let match_rhs_tok = MatchNt(rhs_nm, special_idents::tt, token::Plain, token::Plain); let argument_gram = vec!( TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![ TtToken(DUMMY_SP, match_lhs_tok), TtToken(DUMMY_SP, token::FatArrow), TtToken(DUMMY_SP, match_rhs_tok)], separator: Some(token::Semi), op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUMMY_SP, token::Semi)], separator: None, op: ast::ZeroOrMore, num_captures: 0 }))); // Parse the macro_rules! invocation (`none` is for no interpolations): let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic, None, None, def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(), arg_reader, argument_gram); // Extract the arguments: let lhses = match **argument_map.get(&lhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for lhs in &lhses { check_lhs_nt_follows(cx, &**lhs, def.span); } let rhses = match **argument_map.get(&rhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; let exp: Box<_> = Box::new(MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, }); NormalTT(exp, Some(def.span), def.allow_internal_unstable) } fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span) { // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where the entire lhs is // those tts. Or, it can be a "bare sequence", not wrapped in parens. match lhs { &MatchedNonterminal(NtTT(ref inner)) => match &**inner { &TtDelimited(_, ref tts) => { check_matcher(cx, tts.tts.iter(), &Eof); }, tt @ &TtSequence(..) => { check_matcher(cx, Some(tt).into_iter(), &Eof); }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find \ a TtDelimited or TtSequence)") }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find a \ MatchedNonterminal)") }; // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. } // returns the last token that was checked, for TtSequence. this gets used later on. fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) -> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { use print::pprust::token_to_string; let mut last = None; // 2. For each token T in M: let mut tokens = matcher.peekable(); while let Some(token) = tokens.next() { last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by a \ sequence repetition, which is not \ allowed for `{1}` fragments", name.as_str(), frag_spec.as_str()) ); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { (_, Err(msg)) => { cx.span_err(sp, &msg); continue } (&Eof, _) => return Some((sp, tok.clone())), (_, Ok(true)) => continue, (next, Ok(false)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next))); continue }, } }, TtSequence(sp, ref seq) => { // iii. Else, T is a complex NT. match seq.separator { // If T has the form $(...)U+ or $(...)U* for some token U, // run the algorithm on the contents with F set to U. If it // accepts, continue, else, reject. Some(ref u) => { let last = check_matcher(cx, seq.tts.iter(), u); match last { // Since the delimiter isn't required after the last // repetition, make sure that the *next* token is // sane. This doesn't actually compute the FIRST of // the rest of the matcher yet, it only considers // single tokens and simple NTs. This is imprecise, // but conservatively correct. Some((span, tok)) => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => { cx.span_err(sp, "sequence repetition followed by \ another sequence repetition, which is not allowed"); Eof }, None => Eof }; check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), &fol) }, None => last, } }, // If T has the form $(...)+ or $(...)*, run the algorithm // on the contents with F set to the token following the // sequence. If it accepts, continue, else, reject. None => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(),
Some(_) => { cx.span_err(sp, "sequence repetition followed by another \ sequence repetition, which is not allowed");
random_line_split
macro_rules.rs
let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); let span = parser.span; parser.span_err(span, &msg[..]); let name = token::get_ident(self.macro_ident); let msg = format!("caused by the macro expansion here; the usage \ of `{}` is likely invalid in this context", name); parser.span_note(self.site_span, &msg[..]); } } } impl<'a> MacResult for ParserAnyMacro<'a> { fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> { let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); Some(ret) } fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> { let ret = self.parser.borrow_mut().parse_pat(); self.ensure_complete_parse(false); Some(ret) } fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); while let Some(item) = self.parser.borrow_mut().parse_item() { ret.push(item); } self.ensure_complete_parse(false); Some(ret) } fn make_impl_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::ImplItem>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => ret.push(panictry!(parser.parse_impl_item())) } } self.ensure_complete_parse(false); Some(ret) } fn make_stmts(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Stmt>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => match parser.parse_stmt_nopanic() { Ok(maybe_stmt) => match maybe_stmt { Some(stmt) => ret.push(stmt), None => (), }, Err(_) => break, } } } self.ensure_complete_parse(false); Some(ret) } } struct MacroRulesMacroExpander { name: ast::Ident, imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: Span, arg: &[ast::TokenTree]) -> Box<MacResult+'cx> { generic_extension(cx, sp, self.name, self.imported_from, arg, &self.lhses, &self.rhses) } } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx ExtCtxt, sp: Span, name: ast::Ident, imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) -> Box<MacResult+'cx> { if cx.trace_macros() { println!("{}! {{ {} }}", token::get_ident(name), print::pprust::tts_to_string(arg)); } // Which arm's failure should we report? (the one furthest along) let mut best_fail_spot = DUMMY_SP; let mut best_fail_msg = "internal error: ran no matchers".to_string(); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { TtDelimited(_, ref delim) => &delim.tts[..], _ => panic!(cx.span_fatal(sp, "malformed macro lhs")) }; match TokenTree::parse(cx, lhs_tt, arg) { Success(named_matches) => { let rhs = match *rhses[i] { // okay, what's your transcriber? MatchedNonterminal(NtTT(ref tt)) => { match **tt { // ignore delimiters TtDelimited(_, ref delimed) => delimed.tts.clone(), _ => panic!(cx.span_fatal(sp, "macro rhs must be delimited")), } }, _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic, Some(named_matches), imported_from, rhs); let mut p = Parser::new(cx.parse_sess(), cx.cfg(), Box::new(trncbr)); panictry!(p.check_unknown_macro_variable()); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return Box::new(ParserAnyMacro { parser: RefCell::new(p), // Pass along the original expansion site and the name of the macro // so we can print a useful error message if the parse of the expanded // macro leaves unparsed tokens. site_span: sp, macro_ident: name }) } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, Error(sp, ref msg) => panic!(cx.span_fatal(sp, &msg[..])) } } _ => cx.bug("non-matcher found in parsed lhses") } } panic!(cx.span_fatal(best_fail_spot, &best_fail_msg[..])); } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. pub fn compile<'cx>(cx: &'cx mut ExtCtxt, def: &ast::MacroDef) -> SyntaxExtension { let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ //...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_nm, special_idents::tt, token::Plain, token::Plain); let match_rhs_tok = MatchNt(rhs_nm, special_idents::tt, token::Plain, token::Plain); let argument_gram = vec!( TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![ TtToken(DUMMY_SP, match_lhs_tok), TtToken(DUMMY_SP, token::FatArrow), TtToken(DUMMY_SP, match_rhs_tok)], separator: Some(token::Semi), op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUMMY_SP, token::Semi)], separator: None, op: ast::ZeroOrMore, num_captures: 0 }))); // Parse the macro_rules! invocation (`none` is for no interpolations): let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic, None, None, def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(), arg_reader, argument_gram); // Extract the arguments: let lhses = match **argument_map.get(&lhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for lhs in &lhses { check_lhs_nt_follows(cx, &**lhs, def.span); } let rhses = match **argument_map.get(&rhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; let exp: Box<_> = Box::new(MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, }); NormalTT(exp, Some(def.span), def.allow_internal_unstable) } fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span)
// returns the last token that was checked, for TtSequence. this gets used later on. fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) -> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { use print::pprust::token_to_string; let mut last = None; // 2. For each token T in M: let mut tokens = matcher.peekable(); while let Some(token) = tokens.next() { last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by a \ sequence repetition, which is not \ allowed for `{1}` fragments", name.as_str(), frag_spec.as_str()) ); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { (_, Err(msg)) => { cx.span_err(sp, &msg); continue } (&Eof, _) => return Some((sp, tok.clone())), (_, Ok(true)) => continue, (next, Ok(false)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next))); continue }, } }, TtSequence(sp, ref seq) => { // iii. Else, T is a complex NT. match seq.separator { // If T has the form $(...)U+ or $(...)U* for some token U, // run the algorithm on the contents with F set to U. If it // accepts, continue, else, reject. Some(ref u) => { let last = check_matcher(cx, seq.tts.iter(), u); match last { // Since the delimiter isn't required after the last // repetition, make sure that the *next* token is // sane. This doesn't actually compute the FIRST of // the rest of the matcher yet, it only considers // single tokens and simple NTs. This is imprecise, // but conservatively correct. Some((span, tok)) => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => { cx.span_err(sp, "sequence repetition followed by \ another sequence repetition, which is not allowed"); Eof }, None => Eof }; check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), &fol) }, None => last, } }, // If T has the form $(...)+ or $(...)*, run the algorithm // on the contents with F set to the token following the // sequence. If it accepts, continue, else, reject. None => { let fol = match tokens.peek() {
{ // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where the entire lhs is // those tts. Or, it can be a "bare sequence", not wrapped in parens. match lhs { &MatchedNonterminal(NtTT(ref inner)) => match &**inner { &TtDelimited(_, ref tts) => { check_matcher(cx, tts.tts.iter(), &Eof); }, tt @ &TtSequence(..) => { check_matcher(cx, Some(tt).into_iter(), &Eof); }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find \ a TtDelimited or TtSequence)") }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find a \ MatchedNonterminal)") }; // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. }
identifier_body
macro_rules.rs
let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); let span = parser.span; parser.span_err(span, &msg[..]); let name = token::get_ident(self.macro_ident); let msg = format!("caused by the macro expansion here; the usage \ of `{}` is likely invalid in this context", name); parser.span_note(self.site_span, &msg[..]); } } } impl<'a> MacResult for ParserAnyMacro<'a> { fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> { let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); Some(ret) } fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> { let ret = self.parser.borrow_mut().parse_pat(); self.ensure_complete_parse(false); Some(ret) } fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); while let Some(item) = self.parser.borrow_mut().parse_item() { ret.push(item); } self.ensure_complete_parse(false); Some(ret) } fn make_impl_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::ImplItem>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => ret.push(panictry!(parser.parse_impl_item())) } } self.ensure_complete_parse(false); Some(ret) } fn make_stmts(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Stmt>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => match parser.parse_stmt_nopanic() { Ok(maybe_stmt) => match maybe_stmt { Some(stmt) => ret.push(stmt), None => (), }, Err(_) => break, } } } self.ensure_complete_parse(false); Some(ret) } } struct MacroRulesMacroExpander { name: ast::Ident, imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: Span, arg: &[ast::TokenTree]) -> Box<MacResult+'cx> { generic_extension(cx, sp, self.name, self.imported_from, arg, &self.lhses, &self.rhses) } } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx ExtCtxt, sp: Span, name: ast::Ident, imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) -> Box<MacResult+'cx> { if cx.trace_macros() { println!("{}! {{ {} }}", token::get_ident(name), print::pprust::tts_to_string(arg)); } // Which arm's failure should we report? (the one furthest along) let mut best_fail_spot = DUMMY_SP; let mut best_fail_msg = "internal error: ran no matchers".to_string(); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { TtDelimited(_, ref delim) => &delim.tts[..], _ => panic!(cx.span_fatal(sp, "malformed macro lhs")) }; match TokenTree::parse(cx, lhs_tt, arg) { Success(named_matches) => { let rhs = match *rhses[i] { // okay, what's your transcriber? MatchedNonterminal(NtTT(ref tt)) => { match **tt { // ignore delimiters TtDelimited(_, ref delimed) => delimed.tts.clone(), _ => panic!(cx.span_fatal(sp, "macro rhs must be delimited")), } }, _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic, Some(named_matches), imported_from, rhs); let mut p = Parser::new(cx.parse_sess(), cx.cfg(), Box::new(trncbr)); panictry!(p.check_unknown_macro_variable()); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return Box::new(ParserAnyMacro { parser: RefCell::new(p), // Pass along the original expansion site and the name of the macro // so we can print a useful error message if the parse of the expanded // macro leaves unparsed tokens. site_span: sp, macro_ident: name }) } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, Error(sp, ref msg) => panic!(cx.span_fatal(sp, &msg[..])) } } _ => cx.bug("non-matcher found in parsed lhses") } } panic!(cx.span_fatal(best_fail_spot, &best_fail_msg[..])); } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. pub fn compile<'cx>(cx: &'cx mut ExtCtxt, def: &ast::MacroDef) -> SyntaxExtension { let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ //...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_nm, special_idents::tt, token::Plain, token::Plain); let match_rhs_tok = MatchNt(rhs_nm, special_idents::tt, token::Plain, token::Plain); let argument_gram = vec!( TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![ TtToken(DUMMY_SP, match_lhs_tok), TtToken(DUMMY_SP, token::FatArrow), TtToken(DUMMY_SP, match_rhs_tok)], separator: Some(token::Semi), op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUMMY_SP, token::Semi)], separator: None, op: ast::ZeroOrMore, num_captures: 0 }))); // Parse the macro_rules! invocation (`none` is for no interpolations): let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic, None, None, def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(), arg_reader, argument_gram); // Extract the arguments: let lhses = match **argument_map.get(&lhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for lhs in &lhses { check_lhs_nt_follows(cx, &**lhs, def.span); } let rhses = match **argument_map.get(&rhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; let exp: Box<_> = Box::new(MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, }); NormalTT(exp, Some(def.span), def.allow_internal_unstable) } fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span) { // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where the entire lhs is // those tts. Or, it can be a "bare sequence", not wrapped in parens. match lhs { &MatchedNonterminal(NtTT(ref inner)) => match &**inner { &TtDelimited(_, ref tts) => { check_matcher(cx, tts.tts.iter(), &Eof); }, tt @ &TtSequence(..) => { check_matcher(cx, Some(tt).into_iter(), &Eof); }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find \ a TtDelimited or TtSequence)") }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find a \ MatchedNonterminal)") }; // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. } // returns the last token that was checked, for TtSequence. this gets used later on. fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) -> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { use print::pprust::token_to_string; let mut last = None; // 2. For each token T in M: let mut tokens = matcher.peekable(); while let Some(token) = tokens.next() { last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by a \ sequence repetition, which is not \ allowed for `{1}` fragments", name.as_str(), frag_spec.as_str()) ); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { (_, Err(msg)) => { cx.span_err(sp, &msg); continue } (&Eof, _) => return Some((sp, tok.clone())), (_, Ok(true)) => continue, (next, Ok(false)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next))); continue }, } }, TtSequence(sp, ref seq) =>
cx.span_err(sp, "sequence repetition followed by \ another sequence repetition, which is not allowed"); Eof }, None => Eof }; check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), &fol) }, None => last, } }, // If T has the form $(...)+ or $(...)*, run the algorithm // on the contents with F set to the token following the // sequence. If it accepts, continue, else, reject. None => { let fol = match tokens.peek() {
{ // iii. Else, T is a complex NT. match seq.separator { // If T has the form $(...)U+ or $(...)U* for some token U, // run the algorithm on the contents with F set to U. If it // accepts, continue, else, reject. Some(ref u) => { let last = check_matcher(cx, seq.tts.iter(), u); match last { // Since the delimiter isn't required after the last // repetition, make sure that the *next* token is // sane. This doesn't actually compute the FIRST of // the rest of the matcher yet, it only considers // single tokens and simple NTs. This is imprecise, // but conservatively correct. Some((span, tok)) => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => {
conditional_block
macro_rules.rs
let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); let span = parser.span; parser.span_err(span, &msg[..]); let name = token::get_ident(self.macro_ident); let msg = format!("caused by the macro expansion here; the usage \ of `{}` is likely invalid in this context", name); parser.span_note(self.site_span, &msg[..]); } } } impl<'a> MacResult for ParserAnyMacro<'a> { fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> { let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); Some(ret) } fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> { let ret = self.parser.borrow_mut().parse_pat(); self.ensure_complete_parse(false); Some(ret) } fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); while let Some(item) = self.parser.borrow_mut().parse_item() { ret.push(item); } self.ensure_complete_parse(false); Some(ret) } fn make_impl_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::ImplItem>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => ret.push(panictry!(parser.parse_impl_item())) } } self.ensure_complete_parse(false); Some(ret) } fn make_stmts(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Stmt>>> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); match parser.token { token::Eof => break, _ => match parser.parse_stmt_nopanic() { Ok(maybe_stmt) => match maybe_stmt { Some(stmt) => ret.push(stmt), None => (), }, Err(_) => break, } } } self.ensure_complete_parse(false); Some(ret) } } struct MacroRulesMacroExpander { name: ast::Ident, imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: Span, arg: &[ast::TokenTree]) -> Box<MacResult+'cx> { generic_extension(cx, sp, self.name, self.imported_from, arg, &self.lhses, &self.rhses) } } /// Given `lhses` and `rhses`, this is the new macro we create fn
<'cx>(cx: &'cx ExtCtxt, sp: Span, name: ast::Ident, imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) -> Box<MacResult+'cx> { if cx.trace_macros() { println!("{}! {{ {} }}", token::get_ident(name), print::pprust::tts_to_string(arg)); } // Which arm's failure should we report? (the one furthest along) let mut best_fail_spot = DUMMY_SP; let mut best_fail_msg = "internal error: ran no matchers".to_string(); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { TtDelimited(_, ref delim) => &delim.tts[..], _ => panic!(cx.span_fatal(sp, "malformed macro lhs")) }; match TokenTree::parse(cx, lhs_tt, arg) { Success(named_matches) => { let rhs = match *rhses[i] { // okay, what's your transcriber? MatchedNonterminal(NtTT(ref tt)) => { match **tt { // ignore delimiters TtDelimited(_, ref delimed) => delimed.tts.clone(), _ => panic!(cx.span_fatal(sp, "macro rhs must be delimited")), } }, _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic, Some(named_matches), imported_from, rhs); let mut p = Parser::new(cx.parse_sess(), cx.cfg(), Box::new(trncbr)); panictry!(p.check_unknown_macro_variable()); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return Box::new(ParserAnyMacro { parser: RefCell::new(p), // Pass along the original expansion site and the name of the macro // so we can print a useful error message if the parse of the expanded // macro leaves unparsed tokens. site_span: sp, macro_ident: name }) } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, Error(sp, ref msg) => panic!(cx.span_fatal(sp, &msg[..])) } } _ => cx.bug("non-matcher found in parsed lhses") } } panic!(cx.span_fatal(best_fail_spot, &best_fail_msg[..])); } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. pub fn compile<'cx>(cx: &'cx mut ExtCtxt, def: &ast::MacroDef) -> SyntaxExtension { let lhs_nm = gensym_ident("lhs"); let rhs_nm = gensym_ident("rhs"); // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ //...quasiquoting this would be nice. // These spans won't matter, anyways let match_lhs_tok = MatchNt(lhs_nm, special_idents::tt, token::Plain, token::Plain); let match_rhs_tok = MatchNt(rhs_nm, special_idents::tt, token::Plain, token::Plain); let argument_gram = vec!( TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![ TtToken(DUMMY_SP, match_lhs_tok), TtToken(DUMMY_SP, token::FatArrow), TtToken(DUMMY_SP, match_rhs_tok)], separator: Some(token::Semi), op: ast::OneOrMore, num_captures: 2 })), //to phase into semicolon-termination instead of //semicolon-separation TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition { tts: vec![TtToken(DUMMY_SP, token::Semi)], separator: None, op: ast::ZeroOrMore, num_captures: 0 }))); // Parse the macro_rules! invocation (`none` is for no interpolations): let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic, None, None, def.body.clone()); let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(), arg_reader, argument_gram); // Extract the arguments: let lhses = match **argument_map.get(&lhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; for lhs in &lhses { check_lhs_nt_follows(cx, &**lhs, def.span); } let rhses = match **argument_map.get(&rhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; let exp: Box<_> = Box::new(MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, }); NormalTT(exp, Some(def.span), def.allow_internal_unstable) } fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span) { // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where the entire lhs is // those tts. Or, it can be a "bare sequence", not wrapped in parens. match lhs { &MatchedNonterminal(NtTT(ref inner)) => match &**inner { &TtDelimited(_, ref tts) => { check_matcher(cx, tts.tts.iter(), &Eof); }, tt @ &TtSequence(..) => { check_matcher(cx, Some(tt).into_iter(), &Eof); }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find \ a TtDelimited or TtSequence)") }, _ => cx.span_bug(sp, "wrong-structured lhs for follow check (didn't find a \ MatchedNonterminal)") }; // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. } // returns the last token that was checked, for TtSequence. this gets used later on. fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) -> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { use print::pprust::token_to_string; let mut last = None; // 2. For each token T in M: let mut tokens = matcher.peekable(); while let Some(token) = tokens.next() { last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by a \ sequence repetition, which is not \ allowed for `{1}` fragments", name.as_str(), frag_spec.as_str()) ); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { (_, Err(msg)) => { cx.span_err(sp, &msg); continue } (&Eof, _) => return Some((sp, tok.clone())), (_, Ok(true)) => continue, (next, Ok(false)) => { cx.span_err(sp, &format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next))); continue }, } }, TtSequence(sp, ref seq) => { // iii. Else, T is a complex NT. match seq.separator { // If T has the form $(...)U+ or $(...)U* for some token U, // run the algorithm on the contents with F set to U. If it // accepts, continue, else, reject. Some(ref u) => { let last = check_matcher(cx, seq.tts.iter(), u); match last { // Since the delimiter isn't required after the last // repetition, make sure that the *next* token is // sane. This doesn't actually compute the FIRST of // the rest of the matcher yet, it only considers // single tokens and simple NTs. This is imprecise, // but conservatively correct. Some((span, tok)) => { let fol = match tokens.peek() { Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtDelimited(_, ref delim)) => delim.close_token(), Some(_) => { cx.span_err(sp, "sequence repetition followed by \ another sequence repetition, which is not allowed"); Eof }, None => Eof }; check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), &fol) }, None => last, } }, // If T has the form $(...)+ or $(...)*, run the algorithm // on the contents with F set to the token following the // sequence. If it accepts, continue, else, reject. None => { let fol = match tokens.peek() {
generic_extension
identifier_name